How to convert a local HTML file to PDF using Pyth

2019-09-21 14:20发布

问题:

If you have a local HTML file, how do you convert it to a PDF using Python on in a Windows environment?

A post suggested to use pdfkit but an error I kept receiving was:

Traceback (most recent call last):
  File "C:\python36\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 "\\EXODUS\FolderRedirections\jarad.collier\My Documents\root\scripts\Jupyter Notebooks\convert_html_to_pdf.py", line 5, in <module>
    pdfkit.from_file('Two_Proportion_Hypothesis_Testing.html', 'out.pdf')
  File "C:\python36\lib\site-packages\pdfkit\api.py", line 47, in from_file
    configuration=configuration, cover_first=cover_first)
  File "C:\python36\lib\site-packages\pdfkit\pdfkit.py", line 42, in __init__
    self.configuration = (Configuration() if configuration is None
  File "C:\python36\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

回答1:

Per this answer: How to convert webpage into PDF by using Python, the advice was to use pdfkit. You also have to install wkhtmltopdf.

Since you have a local .html file, you then need to use this command:

pdfkit.from_file('test.html', 'out.pdf')

But this will throw an error if you haven't added the wkhtmltopdf executables to your system path. This was the part that tripped me up and I wanted to share.

On Windows, open your environment variables and add them to your System variables > Path like below. In my case, these .exe files were located here after I installed the wkhtmltopdf from an exe:

C:\Program Files\wkhtmltopdf\bin