Generating PDFs with Python: ReportLab, fpdf2, WeasyPrint and pypdf
Python's PDF libraries divide cleanly by job. ReportLab draws and lays out; fpdf2 does the same with a smaller API; WeasyPrint renders HTML and CSS; pypdf reads, merges and edits files that already exist. One library rarely covers a whole project: a typical invoice service renders with WeasyPrint and then stamps or merges with pypdf. The examples on this page were written against the current documentation of each project (versions in the table) and checked for API names there; Python is not installed on the machine that built this site, so they were not executed here. The JavaScript page carries executed examples of the equivalent operations.
The libraries#
| Library | Version | Licence | Python | Approach | Best for | Not for |
|---|---|---|---|---|---|---|
| ReportLab | 5.1.0 | BSD-style open-source licence; ReportLab PLUS is a commercial product with extra tools | 3.9 to 3.13 | Drawing API (canvas) plus a layout engine (Platypus) | Reports, data-heavy documents, charts; anything that needs both precision and flow | Rendering HTML; the API is large and the learning curve real |
| fpdf2 | 2.8.9 | LGPL-3.0 | 3.10 and later | Drawing API with cells, multi-line text, tables and a limited HTML subset | Simple documents, forms, labels; quick scripts | Complex layouts; CSS |
| WeasyPrint | 70.0 | BSD-3-Clause | 3.10 and later, plus Pango 1.44 or later | HTML and CSS renderer with its own paged-media engine | Documents that exist as HTML templates; running headers and page numbers in CSS | Hosts where installing Pango and cairo is hard; JavaScript-rendered content |
| pypdf | 6.21.4 | BSD-3-Clause | 3.9 and later | Reader and writer for existing files | Merging, splitting, rotating, cropping, metadata, form filling, text extraction | Creating documents from scratch (it can, but others are easier) |
| borb | 3.0.9 | AGPL-3.0-or-later, or a commercial licence | 3.6 and later | Layout engine and reader | Teams that accept AGPL or buy the licence | Closed-source services without a commercial licence |
| Playwright | 1.64.1 | Apache-2.0 | 3.10 and later | Drives headless Chromium | Rendering real HTML with full CSS and JavaScript | Small files; untrusted HTML without isolation |
PyPDF2 no longer exists as a separate project: it was merged back into pypdf in 2022, and import PyPDF2 in new code points at an unmaintained package. Use pypdf.
Drawing with ReportLab#
The canvas is a page-at-a-time drawing surface measured in points from the bottom-left corner. Fonts beyond the standard fourteen are registered once from a TrueType file.
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import mm
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
pdfmetrics.registerFont(TTFont("Noto", "fonts/NotoSans-Regular.ttf")) # embedded as a subset when used
width, height = A4 # 595.28 x 841.89 points
c = canvas.Canvas("hello.pdf", pagesize=A4)
c.setTitle("ReportLab example")
c.setFont("Noto", 24)
c.drawString(20 * mm, height - 30 * mm, "Hello, PDF. Grüße, señor, 10 €")
c.setFont("Helvetica", 11) # standard font, Latin only
c.drawString(20 * mm, height - 40 * mm, "Second line in Helvetica.")
c.line(20 * mm, height - 44 * mm, 100 * mm, height - 44 * mm)
c.showPage() # finish page 1; drawing after this goes on page 2
c.save()For flowing documents, Platypus takes a list of flowables (paragraphs, tables, spacers, images) and paginates them. Page furniture is drawn by callbacks that receive the canvas.
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import mm
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
styles = getSampleStyleSheet()
def footer(canvas, doc):
canvas.saveState()
canvas.setFont("Helvetica", 9)
canvas.drawRightString(A4[0] - 20 * mm, 12 * mm, f"Page {doc.page}")
canvas.restoreState()
rows = [["Item", "Qty", "Unit", "Total"]] + [[f"Line item {i}", "1", "12.50", "12.50"] for i in range(1, 80)]
table = Table(rows, colWidths=[90 * mm, 20 * mm, 25 * mm, 25 * mm], repeatRows=1) # header repeats on each page
table.setStyle(TableStyle([
("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#eeeeff")),
("ALIGN", (1, 1), (-1, -1), "RIGHT"),
("LINEBELOW", (0, 0), (-1, -1), 0.5, colors.grey),
]))
story = [Paragraph("Invoice 1001", styles["Title"]),
Paragraph("Payment is due within 30 days.", styles["Normal"]),
Spacer(1, 6 * mm),
table]
doc = SimpleDocTemplate("invoice.pdf", pagesize=A4, leftMargin=20 * mm, rightMargin=20 * mm,
topMargin=20 * mm, bottomMargin=20 * mm, title="Invoice 1001")
doc.build(story, onFirstPage=footer, onLaterPages=footer)repeatRows=1 is the detail people miss: without it the header row appears once and the continuation pages start with bare data. TableStyle commands address cell ranges with (column, row) pairs, negative indexes counting from the end.
Drawing with fpdf2#
fpdf2 is the maintained successor of the old PyFPDF, with a small API and good Unicode support once a TrueType font is added. Its coordinate origin is the top-left corner and its default unit is millimetres.
from fpdf import FPDF
pdf = FPDF(format="A4") # unit="mm" by default
pdf.add_font("Noto", style="", fname="fonts/NotoSans-Regular.ttf") # subset embedded on output
pdf.set_font("Noto", size=14)
pdf.add_page()
pdf.cell(text="Hello, PDF. Grüße, señor, 10 €", new_x="LMARGIN", new_y="NEXT")
pdf.set_font("Noto", size=10)
pdf.multi_cell(w=0, text="A long paragraph is wrapped by multi_cell to the available width, "
"which is the page width minus both margins when w is 0.")
pdf.ln(4)
pdf.write_html("""
<h2>Items</h2>
<table width="100%"><thead><tr><th width="60%">Item</th><th width="40%">Total</th></tr></thead>
<tbody><tr><td>Design work</td><td>960.00</td></tr><tr><td>Hosting</td><td>120.00</td></tr></tbody></table>
""")
pdf.set_title("fpdf2 example")
pdf.output("fpdf2.pdf")write_html understands a documented subset of HTML (headings, paragraphs, lists, basic tables, font tags, images, links) and no CSS. It is convenient for simple markup produced by your own code, not for arbitrary pages. The built-in fonts (Helvetica, Times, Courier) cover Latin-1 only; text outside that range raises an error until a TrueType font is added, which is the right behaviour.
Rendering HTML with WeasyPrint#
WeasyPrint implements CSS Paged Media properly: @page margin boxes, counter(page), named pages, footnotes and string sets all work, which is why it is the usual choice for HTML templates that need running headers without a browser.
from weasyprint import HTML, CSS
html = """
<!doctype html><html><head><meta charset="utf-8"><title>Invoice 1001</title></head>
<body><h1>Invoice 1001</h1>
<table><thead><tr><th>Item</th><th>Total</th></tr></thead>
<tbody><tr><td>Design work</td><td>960.00</td></tr></tbody></table>
</body></html>
"""
css = CSS(string="""
@page { size: A4; margin: 20mm 15mm 25mm 15mm;
@bottom-center { content: "Page " counter(page) " of " counter(pages); font: 9pt sans-serif; } }
@font-face { font-family: "Noto"; src: url("fonts/NotoSans-Regular.ttf"); }
body { font: 11pt/1.4 "Noto", sans-serif; }
thead { display: table-header-group; }
tr { break-inside: avoid; }
""")
HTML(string=html, base_url=".").write_pdf("invoice.pdf", stylesheets=[css])base_url decides how relative URLs for fonts and images resolve; set it explicitly, because the default (the current working directory of the process) is rarely what a web application expects. For PDF/A output, recent versions accept pdf_variant="pdf/a-3b" on write_pdf; check the version's documentation for the exact spelling. The print-CSS rules that matter are the same as for Chromium and are collected on the HTML-to-PDF page.
For HTML that depends on JavaScript, or for CSS that WeasyPrint does not implement, Playwright drives Chromium from Python with the same options as the Node API, in snake case:
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch() # after: python -m playwright install chromium
page = browser.new_page()
page.set_content(html, wait_until="networkidle")
page.pdf(path="invoice.pdf", prefer_css_page_size=True, print_background=True,
margin={"top": "20mm", "right": "15mm", "bottom": "25mm", "left": "15mm"})
browser.close()Editing existing files with pypdf#
pypdf is the tool for everything that starts from a PDF you already have.
from pypdf import PdfReader, PdfWriter
# Merge three files, keeping the second one's pages 0 to 2 only
writer = PdfWriter()
writer.append("cover.pdf")
writer.append("body.pdf", pages=(0, 3))
writer.append("terms.pdf")
# Rotate the last page and read sizes
writer.pages[-1].rotate(90)
for i, page in enumerate(writer.pages):
box = page.mediabox # RectangleObject in points
print(i + 1, float(box.width), float(box.height), page.rotation)
# Metadata: copy what exists, then set fields (keys are PDF names)
reader = PdfReader("cover.pdf")
if reader.metadata is not None:
writer.add_metadata(reader.metadata)
writer.add_metadata({"/Title": "Merged pack", "/Author": "Example Ltd", "/Producer": "pypdf"})
writer.write("merged.pdf")page.mediabox is the full page as stored; the visible or trimmed area may be a different box, which the page-boxes page explains. rotate(90) sets the page's /Rotate entry rather than transforming the content, so a reader shows it rotated while the stored coordinates stay as they were. Metadata written with add_metadata goes into the information dictionary; the metadata page covers how that relates to XMP and which tools read which.
Checking the output#
Whatever produced the file, check it with tools that do not share its assumptions. qpdf --check invoice.pdf reports structural errors and tells you whether the file uses object streams or a classic cross-reference table. pdftotext from poppler, or pypdf's extract_text(), shows whether the text is real text with a usable encoding or has lost its mapping to Unicode, which happens when a font is embedded without a ToUnicode map. The PDF inspector lists every font with its embedding and subset status, the page boxes and the metadata, in the browser.
A short test that catches most regressions in a document pipeline: generate the document, assert the page count, assert that a known string is extractable from page 1, and assert that every font the inspector lists is embedded. Those three checks fail on exactly the problems that reach production, which are a layout that spilled onto an extra page, a font that was substituted, and text that became unsearchable.
Traps#
System libraries. WeasyPrint needs Pango 1.44 or later and cairo. On Debian and Ubuntu they come from apt; on Windows the documented route is MSYS2 (pacman -S mingw-w64-ucrt-x86_64-pango) and the documentation warns that antivirus tools sometimes flag the package. Container images should install them in the base layer. ReportLab, fpdf2 and pypdf are pure Python apart from optional accelerators and have no such dependency.
Fonts. ReportLab's and fpdf2's built-in fonts are the standard fourteen with Latin-1 or WinAnsi coverage; anything else needs a TrueType font registered or added as shown, and the font file must be on the server, in a path the process can read. With WeasyPrint, fonts come from @font-face or from the system through fontconfig; the first is reproducible, the second is not. The fonts page explains what ends up in the file.
Units. ReportLab uses points with helpers (mm, inch, cm) from reportlab.lib.units; fpdf2 defaults to millimetres; pypdf reports points. Mixing them is the usual cause of a layout that is 2.83 times too big or too small. The units reference has the factors.
Memory and temporary files. ReportLab and fpdf2 can write to a BytesIO buffer instead of a path, which is what a web framework wants. WeasyPrint builds the whole document in memory before writing; very long documents take time and RAM, and a worker queue with a timeout is the usual mitigation. Do not leave rendered files in /tmp on long-running servers.
Untrusted HTML. WeasyPrint fetches URLs referenced by the HTML and CSS. If the HTML comes from users, pass a custom url_fetcher that allows only your own asset host and rejects file://, or the renderer becomes an internal-network scanner. The HTML-to-PDF page covers the full set of mitigations.
Licences. fpdf2's LGPL-3.0 is fine for closed-source applications that import it normally; borb's AGPL is not, unless the application's source is published or a commercial licence is bought. ReportLab's open-source library is BSD-licensed; the PLUS product is separate. Check the licence file in each repository rather than relying on a package index summary.
Sources
- ReportLab User Guide (canvas, Platypus, tables)
- ReportLab on PyPI (version 5.1.0, BSD licence)
- fpdf2 documentation (Unicode fonts, HTML)
- fpdf2 licence (LGPL-3.0)
- WeasyPrint 70.0 documentation, First Steps
- WeasyPrint licence (BSD-3-Clause)
- pypdf documentation (merging, metadata, transformations)
- pypdf licence (BSD-3-Clause)
- borb repository (AGPL-3.0-or-later, commercial licence available)
- Playwright for Python, page.pdf()