如何使用python3将HTML转换为PDF

时间:2015-06-02 16:16:01

标签: python-3.x

如何使用python3将HTML转换为PDF?我用pyqt5写了一些关于webView的代码,我想把webView中的html转换成pdf,我该怎么办?

我曾尝试使用html2pdf,但它似乎只支持python2.x 我试图安装wkhtmltox-0.12.2.2_msvc2013-win64.exe和pdfkit,然后使用示例代码。

import pdfkit

pdfkit.from_url('http://google.com', 'out.pdf')
pdfkit.from_file('test.html', 'out.pdf')
pdfkit.from_string('Hello!', 'out.pdf')

但我也失败了。错误随之而来。

Traceback (most recent call last):
File "E:\Python34\lib\site-packages\pdfkit\configuration.py", line 21,  in __init__
with open(self.wkhtmltopdf) as f:
FileNotFoundError: [Errno 2] No such file or directory: b''

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
  pdfkit.from_url('http://google.com', 'out.pdf')
File "E:\Python34\lib\site-packages\pdfkit\api.py", line 22, in from_url
configuration=configuration)
File "E:\Python34\lib\site-packages\pdfkit\pdfkit.py", line 38, in __init__
self.configuration = (Configuration() if configuration is None
File "E:\Python34\lib\site-packages\pdfkit\configuration.py", line 27, in __init__
'https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf' % self.wkhtmltopdf)
OSError: No wkhtmltopdf executable found: "b''"
If this file exists please check that this process can read it.   Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf

但我也失败了。我该怎么办?我的系统是window7 x64,python的版本是3.4

2 个答案:

答案 0 :(得分:1)

'set path'可能意味着将**.exe添加到系统环境变量$Path$。例如,将D:\Program Files\wkhtmltopdf\bin添加到$Path$

答案 1 :(得分:1)

由于尚未得到接受的答案,因此有一个很棒的库在Python 3中工作,我在经过多次搜索后尝试使用PyPDF2,wkhtmltopdf beta分支用于Python 3,qpdf等。这是weasyprint。我有相关的答案和示例代码here

为了完整起见,请从documentation

from weasyprint import HTML HTML('http://weasyprint.org/').write_pdf('/tmp/weasyprint-website.pdf')

它真的很容易。