Search code examples
pythonhtmlpyinstallerwkhtmltopdfpython-pdfkit

Converting HTML to PDF in Python


What is a good method for converting an HTML string file to PDF? I am trying to create a simple tool that creates a PDF report using some user inputs and an HTML template. I want to distribute this tool so that other coworkers can use it.

Right now I am trying to use pdfkit and wkhtmltopdf. The issue is that I can only get this code to work when I specify the path to the wkhtmltopdf.exe file. When I package the code using PyInstaller, other users will not be able to use the program because they do not have the HTML template file or a path to wkhtmltopdf. Any ideas on how to resolve this or are there any alternative python packages/methods that I should use?


Solution

  • If you want to package the HTML template in your module and you are using setuptools you can include any other files with a couple of changes:

    1. Create a file called MANIFEST.in in your base directory of the module
    2. Add all of the files you want to include like this: include <path/to/file/in/module>
    3. In setup.py add include_package_data=True to setup()

    Making those changes should allow your module to include your template and allow the other modules to convert it to a PDF.

    If you are having pathing problems within the module, make sure that you are using absolute paths to reference other files. I would suggest using the builtin os module to build a path which works for any user. For example: os.path.abspath("path/to/my/file")