IC Improve Code Recipes

Recipe 11.5 · Python

PDF Generation with QuestPDF

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

Invoices, statements, certificates and letters need to be PDFs. Legacy options are a reporting tool with a designer, an HTML-to-PDF converter that drives a headless browser, or an old version of a PDF library under a license that no longer fits. Each has its own deployment headaches.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

Code like this was written against an old open-source release of a library that later moved to the AGPL or a commercial license. Positioning is manual, page breaks in tables need hand-tuning, and the stream is never disposed.

Requirements: Python 3.12+. Install: pip install reportlab

Python Invoice PDF built imperatively with a low-level PDF writer (p246_r11_5_manual_pdf_invoice_before.py)
"""Invoice PDF built imperatively with a low-level PDF writer

Source: ImproveCode, Chapter 11, Recipe 11.5 "PDF Generation with QuestPDF"
Section: The way it's often written
Book page: 246  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
iTextSharp Document/PdfPTable -> reportlab SimpleDocTemplate/Table; the file
stream is not disposed on error, there is no layout, totals or paging.
"""

from typing import Any

from reportlab.platypus import Paragraph, SimpleDocTemplate, Table
from reportlab.lib.styles import getSampleStyleSheet


def write_invoice(path: str, invoice: Any) -> None:
    doc = SimpleDocTemplate(open(path, "wb"))
    story: list[Any] = []
    story.append(Paragraph("Invoice " + invoice.number,
                           getSampleStyleSheet()["Normal"]))
    cells: list[list[str]] = []
    for line in invoice.lines:
        cells.append([line.description, str(line.qty)])
        # ...
    story.append(Table(cells))
    doc.build(story)

The improved recipe

QuestPDF describes documents with a fluent C# layout API. Headers and footers repeat on every page, tables break across pages and repeat their header row, and page numbers are built in.

License note. QuestPDF is not free for everyone. Its Community license is free for individuals, small businesses under a revenue threshold (annual gross revenue under USD 1 million at the time of writing), qualifying charities, academic institutions and open-source projects. Larger organizations need a paid Professional or Enterprise license. The terms have changed before, so read the current license on the QuestPDF web site before you ship. The code declares the license you hold with one line at startup.

NuGet package: QuestPDF.

Requirements: Python 3.12+. Install: pip install reportlab

Python Declarative invoice PDF: header, line-item table, total and page X of Y footer (p247_r11_5_invoice_pdf_document.py)
"""Declarative invoice PDF: header, line-item table, total and page X of Y footer

Source: ImproveCode, Chapter 11, Recipe 11.5 "PDF Generation with QuestPDF"
Section: The improved recipe
Book page: 247-249  -- original C# listing
Converted from C# to Python.
QuestPDF -> reportlab platypus (SimpleDocTemplate, Table, repeatRows header);
"Page N of M" uses a two-pass canvas. Currency "C" en-US -> f"${x:,.2f}".
QuestPDF licensing has no equivalent (reportlab is BSD-licensed).
"""

from __future__ import annotations

import datetime as dt
import io
from dataclasses import dataclass
from decimal import Decimal
from typing import Any

from reportlab.lib import colors
from reportlab.lib.pagesizes import LETTER
from reportlab.lib.styles import ParagraphStyle
from reportlab.pdfgen import canvas
from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle


@dataclass(frozen=True)
class InvoiceLine:
    description: str
    quantity: int
    unit_price: Decimal

    @property
    def total(self) -> Decimal:
        return self.quantity * self.unit_price


@dataclass(frozen=True)
class InvoiceModel:
    number: str
    issued_on: dt.date
    seller_name: str
    customer_name: str
    lines: list[InvoiceLine]


def _format(amount: Decimal) -> str:
    sign = "-" if amount < 0 else ""
    return f"{sign}${abs(amount):,.2f}"


class _NumberedCanvas(canvas.Canvas):
    """Canvas that defers pages so the footer can show the total page count."""

    def __init__(self, *args: Any, **kwargs: Any) -> None:
        super().__init__(*args, **kwargs)
        self._saved: list[dict[str, Any]] = []

    def showPage(self) -> None:  # noqa: N802 (reportlab API)
        self._saved.append(dict(self.__dict__))
        self._startPage()

    def save(self) -> None:
        total = len(self._saved)
        for state in self._saved:
            self.__dict__.update(state)
            self.setFont("Helvetica", 10)
            self.drawCentredString(LETTER[0] / 2, 25,
                                   f"Page {self._pageNumber} of {total}")
            super().showPage()
        super().save()


class InvoiceDocument:
    def __init__(self, model: InvoiceModel) -> None:
        if model is None:
            raise ValueError("model is required")
        self._model = model

    def generate_pdf(self) -> bytes:
        m = self._model
        buffer = io.BytesIO()
        doc = SimpleDocTemplate(
            buffer, pagesize=LETTER,
            leftMargin=40, rightMargin=40, topMargin=40, bottomMargin=40,
            title=f"Invoice {m.number}", author=m.seller_name,
        )
        base = ParagraphStyle("base", fontName="Helvetica", fontSize=10, leading=13)
        title = ParagraphStyle("title", parent=base, fontName="Helvetica-Bold",
                               fontSize=20, leading=24)
        bold = ParagraphStyle("bold", parent=base, fontName="Helvetica-Bold")
        total_style = ParagraphStyle("total", parent=bold, fontSize=12,
                                     leading=15, alignment=2)

        left = [
            Paragraph(f"Invoice {m.number}", title),
            Paragraph(f"Issued {m.issued_on.day} {m.issued_on:%b %Y}", base),
            Paragraph(f"Bill to: {m.customer_name}", base),
        ]
        seller = Paragraph(m.seller_name, ParagraphStyle(
            "seller", parent=bold, alignment=2))
        width = LETTER[0] - 80
        header = Table([[left, seller]], colWidths=[width - 180, 180])
        header.setStyle(TableStyle([("VALIGN", (0, 0), (-1, -1), "TOP")]))

        story: list[Any] = [header, Spacer(1, 15), self._compose_table(width)]
        total = sum((line.total for line in m.lines), Decimal(0))
        story += [Spacer(1, 10), Paragraph(f"Total: {_format(total)}", total_style)]

        doc.build(story, canvasmaker=_NumberedCanvas)
        return buffer.getvalue()

    def _compose_table(self, width: float) -> Table:
        data: list[list[str]] = [["Description", "Qty", "Unit price", "Amount"]]
        for line in self._model.lines:
            data.append([line.description, f"{line.quantity:,}",
                         _format(line.unit_price), _format(line.total)])

        unit = width / 10  # relative columns 5:1:2:2
        table = Table(data, colWidths=[unit * 5, unit, unit * 2, unit * 2],
                      repeatRows=1)
        table.setStyle(TableStyle([
            ("FONT", (0, 0), (-1, -1), "Helvetica", 10),
            ("FONT", (0, 0), (-1, 0), "Helvetica-Bold", 10),
            ("ALIGN", (1, 0), (-1, -1), "RIGHT"),
            ("LINEBELOW", (0, 0), (-1, 0), 1, colors.HexColor("#757575")),
            ("LINEBELOW", (0, 1), (-1, -1), 0.5, colors.HexColor("#EEEEEE")),
            ("TOPPADDING", (0, 0), (-1, 0), 4),
            ("BOTTOMPADDING", (0, 0), (-1, 0), 4),
            ("TOPPADDING", (0, 1), (-1, -1), 3),
            ("BOTTOMPADDING", (0, 1), (-1, -1), 3),
        ]))
        return table


def create_invoice_pdf(model: InvoiceModel) -> bytes:
    """InvoicePdf.Create."""
    return InvoiceDocument(model).generate_pdf()

How it works

A QuestPDF document is a class implementing IDocument. Compose describes the page: size, margins and default text style, then three slots. The header and footer repeat on every page. The content flows across as many pages as it needs, and the table moves to the next page between rows, repeating its header there.

Layout is containers inside containers. Row places items side by side, with RelativeItem sharing the remaining width and ConstantItem taking a fixed width in points. Column stacks items vertically. Element(HeaderCell) applies a small styling function, which is how you keep table styles consistent without repeating border and padding calls on every cell.

CurrentPageNumber and TotalPages are resolved at render time, so "Page 2 of 5" is always right. GetMetadata sets the title and author that PDF viewers show.

Money is formatted with an explicit culture, not the server's current culture. An invoice should not change currency symbol because it was generated on a server in a different region. Pick the culture from the customer's account, not from the thread.

GeneratePdf() returns a byte array. There are overloads for a Stream and a file path, and in a web endpoint you can return the bytes with Results.File(bytes, "application/pdf", "invoice.pdf"). In development, the QuestPDF Companion app shows a live preview as you edit the layout code.

Variations and pitfalls

  • Set the license once. Put the QuestPDF.Settings.License line in Program.cs. It is in the helper here only so the listing is self-contained. QuestPDF throws at generation time if no license is set.
  • Fonts. QuestPDF embeds the fonts it uses. On Linux containers, install the fonts your design names, or register a font file with FontManager.RegisterFont. Otherwise text falls back to a default font.
  • Separate data from layout. Build the InvoiceModel in your application service and keep the document class free of database calls. That makes PDF tests simple: build a model, generate, check the byte count or compare against a stored reference.
  • HTML to PDF. If your designers already maintain HTML templates, a headless browser such as Playwright's page.PdfAsync() renders them faithfully. It is a heavier dependency to deploy.