一. 环境配置
- 下载并安装 wkhtmltopdf (https://wkhtmltopdf.org/downloads.html)
pip install pdfkit
pip install whtmltopdf
二. 转换方法
import pdfkit
def html_to_pdf(html_path, save_path, path_type='file_path'):
'''
params:
html_path HTML 文件路径/URL/字符串
save_path PDF 文件要保存的位置
path_type 输入的 html_path 的类型
'''
path_wk = r'D:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe' #wkhtmltopdf 安装位置
config = pdfkit.configuration(wkhtmltopdf = path_wk)
if path_type == 'url_path':
pdfkit.from_url(html_path, save_path, configuration=config)
elif path_type == 'file_path':
pdfkit.from_file(html_path, save_path, configuration=config)
elif path_type == 'string':
pdfkit.from_string(html_path, save_path, configuration=config)