使用 wkhtmltopdf python html转pdf
前言
使用 wkhtmltopdf python html 转 pdf。
一、环境
- pdfkit0.61
- python3.7
- miniconda4.8.3 (https://blog.csdn.net/mtl1994/article/details/114968140)
二、安装与配置
1.首先安装pdfkit0.61
pip install pdfkit
2.下载wkhtmltopdf
https://wkhtmltopdf.org/downloads.html
根据自己的电脑下载相应的版本,然后安装
2.python html转pdf
# -*- coding: utf-8 -*-
import pdfkit
#启动参数
wkhtmltopdf_options = {
'enable-local-file-access': None
}
#下载的wkhtmltopdf绝对路径
path_wkthmltopdf = r'D:\\install\\wkhtmltox\\wkhtmltopdf\\bin\\wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)
#h.html 输入 out.pdf 输出
pdfkit.from_file("h.html", "out.pdf", configuration=config, options=wkhtmltopdf_options)
3.url转pdf
pdfkit.from_url("https://www.baidu.com", "out.pdf", configuration=config, options=wkhtmltopdf_options)
遇到的问题
1.pdf 中文乱码
#html head标签加上下面
<meta http-equiv="content-type" content="text/html;charset=utf-8">
OSError: wkhtmltopdf reported an error:
Loading pages (1/6)
Warning: Blocked access to file D:/Paddle/htmlToPdf/bg2.png
Error: Failed to load about:blank, with network status code 301 and http status code 0 - Protocol “about” is unknown
Counting pages (2/6)
Resolving links (4/6)
Loading headers and footers (5/6)
Printing pages (6/6)
Done
Exit with code 1 due to network error: ProtocolUnknownError
#加上启动参数
wkhtmltopdf_options = {
'enable-local-file-access': None
}
pdfkit.from_file(html, to_file, configuration=config, options=wkhtmltopdf_options)
总结
~~~