Free Python xhtml2pdf Templates (Pure-Python HTML to PDF)
Pure-Python HTML-to-PDF converter built on top of ReportLab — pip-only with no Cairo/Pango binaries. Renders single-page HTML in 61 ms and 23 stress-test pages in 2.06s (139.0 KB PDF), subject to CSS 2.1 layout limits.
Install: pip install xhtml2pdf==0.2.16 | Runtime: Python (Python 3) | Version: 0.2.16 | Popularity: 780k/mo installs
Works with: Django, FastAPI, Flask
How xhtml2pdf (Python) Templates Work in CodePDF
Emits xhtml2pdf-compatible HTML/CSS rendered via pisa.CreatePDF() on top of ReportLab — pip-installable anywhere Python runs.
- Avoids unsupported CSS Flexbox/Grid crashes in pisa by emitting xhtml2pdf-safe positioning and table structures
- Installs via pip alone with zero OS-level apt/brew packages
- Compact ~15 KB output ready for FastAPI StreamingResponse and Django views
Quick Start: Generate PDFs with xhtml2pdf
Install xhtml2pdf (Python) (Python 3), then run the code CodePDF exports for any template:
pip install xhtml2pdf==0.2.16
- Save the generated file as my_document.py.
- Run python my_document.py to produce the PDF.
- No native binaries are required; it renders through ReportLab.
- CSS support is limited to a subset - prefer tables over flexbox layouts.
Example xhtml2pdf Output (Professional Invoice)
Compiled directly from the Professional Invoice template (Python 3):
import html as _html
from reportlab.pdfbase import pdfmetrics
from xhtml2pdf import pisa
# This code is generated using codepdf.dev
_BLOCKED_1X1_PNG = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="
def _validate_safe_xhtml_uri(raw_uri: str) -> str:
import base64 as _b64
import ipaddress as _ip
import os as _os
import re as _re
import socket as _socket
import urllib.parse as _up
import urllib.request as _ur
def _assert_public_ip(addr: str, target_url: str) -> None:
ip = _ip.ip_address(addr.split("%", 1)[0])
if getattr(ip, "ipv4_mapped", None) is not None:
ip = ip.ipv4_mapped
if not ip.is_global or ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved or ip.is_multicast or ip.is_unspecified:
raise ValueError(f"Blocked non-public IP in URI: {target_url}")
def _validate_http_url(target_url: str) -> None:
p = _up.urlparse(target_url)
sc = (p.scheme or "").lower()
if sc not in ("https", "http") or p.username or p.password:
raise ValueError(f"Blocked unsupported URI scheme: {sc or 'empty'}")
h = (p.hostname or "").strip().lower()
// … (696 more lines in full generated file)
Custom Fonts in xhtml2pdf
Generated code falls back to Standard 14 fonts unless CSS @font-face rules point to local TrueType (.ttf) files on disk (inline base64 font URIs and WOFF2 are not supported by pisa).
- Convert web fonts to .ttf and place them under ./fonts/.
- Declare @font-face rules in your <style> tag pointing to the local path.
- Provide link_callback in pisa.CreatePDF() if serving assets from non-default directories.
Official documentation: xhtml2pdf docs
xhtml2pdf Benchmark Results
Measured on CodePDF’s 26-component, 23-page All-Components Dynamic Multi-Page Flow Stress Test (same document across all 22 libraries).
| Metric | xhtml2pdf | Rank (of 22) |
|---|---|---|
| Wall-clock time | 2.06 s | 21st fastest |
| CPU time | 2.62 s | 19th lowest |
| Peak RAM | 159.6 MB | 15th lowest |
| PDF file size | 139 KB | 5th smallest |
- Engine type
- CSS-to-PDF
- Under the hood
- Pure-Python HTML/CSS 2.1 parser (pisa) translating markup onto ReportLab underneath
- Runs in
- Python 3 (Django, FastAPI, Flask — pip-only)
- Verdict
- Pip-only pure-Python HTML/CSS 2.1 on ReportLab (61 ms single-page; 2.06s & 139.0 KB across 23p) — zero Pango/Cairo OS dependencies.
Under the Hood & Benchmark Highlights
- Converts HTML + CSS into ReportLab primitives under the hood, giving Python HTML-to-PDF via pip alone without Cairo, Pango, or Chromium.
- On our 11-page stress test it finished in 1.74s with a 109.5 KB PDF (~131 MB RAM) — dramatically faster and lighter than WeasyPrint (80.8s / 1,022 KB).
- Tradeoff: its pisa parser only understands a subset of CSS 2.1 (no CSS Grid, modern Flexbox, or WOFF2 fonts).
Good to Know (xhtml2pdf Caveats)
- Strict CSS 2.1 subset: xhtml2pdf's pisa parser does not support modern CSS Grid or full Flexbox; stick to tables and simple block layouts (or switch to WeasyPrint / ReportLab for complex layouts).
- Font format limit: Only local .ttf fonts are supported in @font-face — .woff and .woff2 web fonts fail in pisa.
- HTML parsing overhead over ReportLab: Pure PDF generation took 61 ms single-page and 2.06s across 23 stress-test pages (139.0 KB PDF) — faster and smaller than WeasyPrint (4.34s / 1,059.8 KB), though slower than direct ReportLab canvas code (170 ms).
Popular xhtml2pdf PDF Templates
- Professional Invoice xhtml2pdf template — Line-item invoice with billing details, totals and payment terms.
- Student Tuition & Bursar Fee Receipt xhtml2pdf template — Official university bursar payment receipt categorizing IRS Form 1098-T qualified tuition, mandatory fees, and applied grant aid.
- Formal Employment Offer Letter xhtml2pdf template — Executive employment offer letter with compensation KPIs, benefits list, at-will terms, and dual acceptance signatures.
- Purchase Order xhtml2pdf template — Procurement PO with vendor, ship-to, line items and approval block.
- Student Report Card xhtml2pdf template — Academic progress report with subject grades, attendance summary, GPA calculation and remarks.
- Official Landlord Rent Payment Receipt xhtml2pdf template — Statutory rent payment receipt with QR ledger verification, itemized rent/parking allocation, and $0.00 current balance confirmation.
All 100 CodePDF templates export to xhtml2pdf (Python). Browse them by category: Career (5) · Business (6) · Education (7) · Marketing (6) · Human Resources (8) · Finance (7) · Legal (8) · Healthcare (10) · Logistics (6) · Real Estate (6) · Hospitality (4) · Operations (5) · Technology (5) · Banking (9) · Non-Profit (4) · Personal (3) · Compliance & Enterprise (1), or see the full template gallery.
xhtml2pdf Template FAQs
Why do normal HTML templates break in xhtml2pdf?
xhtml2pdf's pisa parser only supports a subset of CSS2.1 and breaks on modern CSS Grid/Flexbox. CodePDF generates xhtml2pdf-compatible styles so layouts render cleanly.
Does xhtml2pdf require wkhtmltopdf or GTK/Cairo?
No. xhtml2pdf is pure Python built on ReportLab and installs strictly via pip.
Can I switch from xhtml2pdf to native ReportLab later?
Yes — export the exact same CodePDF template to native ReportLab canvas code anytime for 6x faster execution.
xhtml2pdf vs Other Python PDF Libraries
- ReportLab (Python) — 170 ms, 46.4 MB RAM, 179.5 KB PDF. Fastest & lowest-RAM Python engine (170 ms for 22p, 1.5 ms single-page, 46.4 MB RAM, 0.29s CPU) with BSD-3-Clause license.
- WeasyPrint (Python) — 4.34 s, 188.2 MB RAM, 1059.8 KB PDF. Modern CSS Paged Media without Chromium via Pango/Cairo: 144 ms single-page, 4.34s & 1,059.8 KB across 18 dense overflowing pages.
- fpdf2 (Python) — 389 ms, 81.8 MB RAM, 135 KB PDF. Smallest-PDF Python engine (135.0 KB across 22p; 2.0 KB / 3.5 ms single-page) in 389 ms with 100% pure Python (zero C libs; LGPL-3.0).
See the full 22-library benchmark rankings · Compare all supported PDF libraries