使用 wkhtmltopdf python html转pdf


前言

使用 wkhtmltopdf python html 转 pdf。


一、环境

  1. pdfkit0.61
  2. python3.7
  3. miniconda4.8.3 (https://blog.csdn.net/mtl1994/article/details/114968140)

二、安装与配置

1.首先安装pdfkit0.61

pip install pdfkit

2.下载wkhtmltopdf

https://wkhtmltopdf.org/downloads.html

image-20210319101638579

根据自己的电脑下载相应的版本,然后安装

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

image-20210319102311641

#加上启动参数
wkhtmltopdf_options = {
	'enable-local-file-access': None
}
pdfkit.from_file(html, to_file, configuration=config, options=wkhtmltopdf_options)

总结

~~~

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐