Generate PDF files from HTML in Python

Kevin Tewouda
4 min readMar 10, 2024

WeasyPrint at our rescue

Photo by Patrick Hendry on Unsplash

We sometimes need to generate PDFs from invoices, reports, or tickets we emit to clients. If you are in a case where your clients can see these documents from a web application, you may not want to recreate it from scratch using tools specifically designed for this task like ReportLab. In this article, I will show you a library capable of transforming HTML pages into beautiful PDFs. This library is called WeasyPrint.

Installation

You will need Python 3.8 or higher to use this library. But before trying to install it with your favorite package manager, there is an external dependency called Pango that helps with text rendering. The method to install it will vary between platforms. The official documentation has a dedicated section for it that I encourage you to read, but here are the instructions for common distributions.

# ubuntu
$ sudo apt install pango1.0-tools

# macOS
$ brew install pango

On Windows, you will need to install GTK3 installer to have Pango automatically installed.

When that is done, you can now install WeasyPrint with your favorite package manager.

# with pip
$ pip install weasyprint

# with uv
$ uv pip install weasyprint

# with poetry
$ poetry add weasyprint

--

--

Kevin Tewouda

Déserteur camerounais résidant désormais en France. Passionné de programmation, sport, de cinéma et mangas. J’écris en français et en anglais dû à mes origines.