Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python ReportLab Multipage PDF and Custom Fonts

Generate multipage PDFs with custom fonts in Python ReportLab by registering TTF fonts, using Platypus flowables, controlling page breaks, and handling Unicode.

~6 min readPython
#ReportLab#PDF generation#Custom fonts#Platypus
Illustration of a multipage PDF document with custom font glyphs and page break markers, representing ReportLab font registration and Platypus layout.

When you need to generate a multipage PDF in Python with a font that is not one of the built-in Helvetica, Times, or Courier families, ReportLab requires explicit font registration. The process is straightforward, but the details matter: you must register the font file, create a font object, and then attach it to paragraph styles. This article walks through the exact steps for using custom fonts in a multipage ReportLab PDF, including page-break control and common pitfalls with Unicode and font embedding.

Why ReportLab Needs Explicit Font Registration

ReportLab's default fonts are the standard PDF Type 1 fonts: Helvetica, Times-Roman, and Courier. These are always available and require no registration. For any other font, you must provide a TrueType or OpenType font file and register it with pdfmetrics.registerFont(). This is because PDF viewers expect fonts to be embedded or referenced correctly, and ReportLab does not assume you have access to system fonts. The registration step tells ReportLab where to find the font file and what name to use internally.

Without registration, trying to use a custom font name in a paragraph style raises a KeyError when the flowable is laid out or during doc.build(). The important point is to register the font before using it in any flowable.

Building a Minimal Multipage PDF with Platypus

Platypus (Page Layout and Typography Using Scripts) is ReportLab's high-level document builder. It manages page breaks, margins, and flowables automatically. The simplest way to create a multipage PDF is to use SimpleDocTemplate and pass a list of flowables like Paragraph and Spacer. Here is a minimal example that creates two pages:

python
from reportlab.lib.pagesizes import letter from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.units import inch from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, PageBreak doc = SimpleDocTemplate("example.pdf", pagesize=letter) styles = getSampleStyleSheet() story = [] for i in range(50): story.append(Paragraph(f"Paragraph {i+1}", styles["Normal"])) story.append(Spacer(1, 0.1 * inch)) # Force a page break after the first 25 paragraphs story.insert(25, PageBreak()) doc.build(story)

This creates a two-page PDF because the PageBreak flowable forces a new page after the first 25 paragraphs. Without it, ReportLab would automatically break pages when the content exceeds the page height. The automatic behavior is often sufficient, but explicit page breaks give you control over where content starts.

Registering Custom Fonts with TTFont

To use a custom font, you need a .ttf or .otf file. ReportLab's TTFont class is the usual way to register these fonts, though OpenType support depends on the font's internal format. The registration code looks like this:

python
from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont("MyFont", "path/to/font.ttf"))

The first argument is the name you will use in styles. It can be any string, but it must match exactly when you set the fontName property. The second argument is the file path. Relative paths are resolved from the current working directory, so it is safer to use an absolute path or a path relative to the script's location.

For fonts that contain multiple weights (e.g., regular and bold), you register each weight separately with different names:

python
pdfmetrics.registerFont(TTFont("MyFont-Regular", "fonts/MyFont-Regular.ttf")) pdfmetrics.registerFont(TTFont("MyFont-Bold", "fonts/MyFont-Bold.ttf"))

Then you can use MyFont-Regular and MyFont-Bold in different styles.

Applying Custom Fonts to Paragraph Styles

Once registered, you can create a custom ParagraphStyle that uses the font. The getSampleStyleSheet() provides default styles, but you can clone and modify them:

python
from reportlab.lib.styles import ParagraphStyle from reportlab.lib.enums import TA_LEFT custom_style = ParagraphStyle( name="CustomBody", fontName="MyFont-Regular", fontSize=12, leading=16, alignment=TA_LEFT, )

Then use this style in your Paragraph flowables:

python
paragraph = Paragraph("This text uses a custom font.", custom_style)

If you need bold or italic, register the corresponding font files and create separate styles. ReportLab does not synthesize bold or italic from a regular font; it uses the exact font file you provide. If you use inline <b> markup in a Paragraph, call pdfmetrics.registerFontFamily() so ReportLab can map normal, bold, italic, and bold-italic variants. Alternatively, use a separate ParagraphStyle whose fontName points directly to the bold font.

Controlling Page Breaks in Long Documents

For a truly multipage PDF, you often need to control where pages break. ReportLab provides several flowables for this:

  • PageBreak() forces a new page immediately.
  • CondPageBreak(height) inserts a page break only if less than height space remains on the current page.
  • Spacer adds vertical space and can influence natural breaks.

A common pattern is to use CondPageBreak to keep a section together. For example, if you have a heading and a paragraph that should stay on the same page, you can insert a CondPageBreak before the heading with a height equal to the heading plus the paragraph. This avoids orphaned headings.

python
from reportlab.platypus import CondPageBreak # Reserve 2 inches for the heading and first paragraph story.append(CondPageBreak(2 * inch)) story.append(Paragraph("Section Heading", heading_style)) story.append(Paragraph("Introductory text...", body_style))

For long documents with many sections, you can also use NextPageTemplate and PageTemplate to change page layouts, but that is more advanced. The basic PageBreak and CondPageBreak cover most needs.

Handling Unicode and Missing Glyphs

Custom fonts often include characters outside the Latin-1 range. ReportLab's TTFont supports Unicode, but the font file must contain the glyphs for the characters you use. If a glyph is missing, ReportLab will not raise an error; it will render a blank or a placeholder depending on the PDF viewer. To avoid this, test your content with the actual font and check for missing glyphs.

One common issue is with fonts that do not include a particular script (e.g., Cyrillic, Arabic, or CJK). You need a font that covers those code points. Also, some fonts have different internal encodings; ReportLab expects Unicode text, so you should ensure your strings are Python str objects (not bytes).

Font Licensing and Embedding Constraints

PDF files can embed fonts in two ways: subsetting and full embedding. ReportLab by default embeds the entire font file. This increases the PDF size but guarantees that the text renders correctly on any device. For large fonts, this can bloat the file. If output size matters, you can create a subsetted font with an external font tool and register that subset instead.

Some commercial fonts have embedding restrictions. The font file's fsType field indicates the embedding permission. ReportLab does not read this field; it will embed regardless. To avoid legal issues, verify the font's license. For open-source fonts like those from Google Fonts, embedding is generally allowed.

Performance and Memory Considerations for Large PDFs

Generating a PDF with hundreds of pages and multiple custom fonts can consume significant memory because Platypus holds the flowable list in memory while building the document. For very large documents, consider using canvas directly instead of Platypus, though that requires manual page management. For a typical document with a few fonts and a moderate number of flowables, the Platypus approach is simple and fast enough.

Font registration is a one-time cost. Once registered, each font is loaded into memory. If you use many fonts, memory usage increases. For a typical document with two or three fonts, this is negligible. If you are generating many PDFs in a loop, reuse the same registered font objects instead of re-registering them for each document.

Another performance factor is the number of flowables. Each Paragraph is laid out and wrapped, which is CPU-intensive. For long documents, consider using XPreformatted for pre-wrapped text or Table for structured data. But for most use cases, the straightforward Platypus approach is fast enough.

A practical tip: if you need to generate a PDF with a custom font that is not available on the target system, embedding is essential. ReportLab handles this automatically when you register the font. The resulting PDF will display correctly even on machines that do not have the font installed.

For a production system, you should also handle the case where the font file is missing. Wrap the registration in a try-except block and provide a fallback to a default font. This prevents the entire PDF generation from failing due to a missing asset.

python
try: pdfmetrics.registerFont(TTFont("MyFont", "fonts/MyFont.ttf")) font_name = "MyFont" except (IOError, OSError): font_name = "Helvetica"

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.