xhtml2pdf Tutorial: Convert HTML to PDF in Python

This guide walks through building a Python HTML to PDF report using xhtml2pdf, Jinja2 templates, and matplotlib charts. By the end, you will have a working script that reads sales data from a JSON file, renders it into styled HTML, and converts it to a PDF ready for distribution or printing.
The Libraries: xhtml2pdf and Jinja2
xhtml2pdf (formerly known as pisa) is a Python library built on the ReportLab Toolkit. It converts HTML and CSS into PDF documents without a headless browser. It supports HTML5 and CSS 2.1 (with some CSS3), which works well for reports, invoices, and similar layouts. Complex CSS like flexbox or grid is not supported.
Jinja2 is a templating engine for Python. In this tutorial it generates the HTML that xhtml2pdf then converts to PDF. Variables like {{ total_sales }} and loops like {% for month in months %} keep the template reusable across different data sets.
xhtml2pdf also appears in the top Python HTML to PDF libraries comparison. For more on templating engines, see the HTML template engines guide.
From HTML to PDF: Step-by-Step with xhtml2pdf
Prerequisites
-
Python
- Ensure you have Python installed on your system.
- You can download the latest version from Python.org.
-
Code Editor
- Choose your preferred code editor.
- Popular options include Visual Studio Code or PyCharm.
Setting Up the Environment
Start by setting up the project environment and installing the required libraries.
Project Folder Structure
The project uses the following file structure:
html-to-pdf-project/ # Root directory
├── data/ # Data files
│ └── annual_data.json # Example data file for report
├── image/ # Image assets
│ └── logo.png
├── templates/ # Jinja2 HTML templates
│ ├── annual_report.html # Report template
│ └── styles.css # CSS styles for reports
├── utils/
│ └── chart_generator.py # Module for creating charts
└── generate_annual_report.py # Main script
Installing Required Libraries
Install the libraries used for Python PDF generation in this project:
pip install xhtml2pdf jinja2 matplotlib
xhtml2pdf: Converts HTML/CSS to PDF.jinja2: Creates dynamic HTML templates.matplotlib: Produces charts and visualizations.
