Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert HTML to PDF with python3

Tags:

python-3.x

How to convert HTML to PDF with python3? i write some code about webView with pyqt5,and i want to convert the html in the webView to pdf,what should i do?

i have tried to use the html2pdf,but it seem to only support python2.x and i have tried to install the wkhtmltox-0.12.2.2_msvc2013-win64.exe and pdfkit,and then use the example code.

import pdfkit

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

but i also failed.and the error is following.

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

but i also failed.so what should i do? My system is window7 x64 ,python's version is 3.4

like image 259
zonzely Avatar asked Jun 02 '15 16:06

zonzely


1 Answers

Since this hasn't had an accepted answer yet, there is a great library that works in Python 3 that I found after much searching and failed attempts at using PyPDF2, wkhtmltopdf beta branch for Python 3, qpdf, etc. It is weasyprint. I have the related answer and sample code here.

For completeness sake, from the documentation:

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

and it really works that easy.

like image 121
jamescampbell Avatar answered Sep 30 '22 08:09

jamescampbell