In the previous lesson we saw that the 14 standard fonts have two serious problems for a real invoicing system: they only support the characters in WinAnsiEncoding (a customer called "Łukasz" or an arrow "→" in the notes breaks generation), and their look depends on the fonts installed on the viewer's machine. The professional solution is to embed a TrueType font with Unicode support in the PDF. In this lesson you'll learn how to load such fonts with PDType0Font, how to embed only the glyphs you need (subsetting), how to choose fonts with a suitable licence, how to detect characters a font can't draw, and how to provide a fallback font. All of this will be wrapped up in the InvoiceLabFonts class, which will be the entry point to typography for the rest of the course.

Contents

  1. Why embed fonts
  2. Recommended free fonts and licences
  3. Organizing fonts in the project
  4. Loading a font with PDType0Font.load
  5. Subsetting: embedding only what you need
  6. Unicode and missing glyphs
  7. Fallback fonts
  8. OpenType, CFF and TTC collections
  9. PDType1Font vs PDType0Font
  10. System fonts and FontMapper: why you shouldn't rely on them
  11. One font per document: the InvoiceLabFonts class
  12. Applying it to the invoice

Why embed fonts

An embedded font travels inside the PDF: the file contains the drawings (glyphs) of the letters the document uses. A non-embedded font only appears by name, and it's up to the viewer to find a font with that name or a similar one.

Aspect Non-embedded font (standard 14) Embedded font (TrueType)
Look across viewers Variable (each viewer substitutes in its own way) Identical everywhere
Available characters ~220 (WinAnsi) Everything the font contains (thousands)
PDF size Minimal Somewhat larger (a few KB with subsetting)
PDF/A (long-term legal archiving) Not allowed Required
Corporate identity Impossible The brand's typeface
Text extraction (copy, search) Correct for WinAnsi Correct if the font has a ToUnicode table (PDFBox generates it)

For an invoice, a document with legal value that may be kept for years and may end up in a PDF/A archive (module 8), embedding is the right choice.

Recommended free fonts and licences

A font is software and it comes with a licence. Before adding a .ttf to your project, check two things:

  1. Whether you can redistribute it: when you put it in src/main/resources, the file will travel inside your JAR. Windows and macOS fonts (Arial, Calibri, Helvetica Neue…) have licences that do not allow you to redistribute them in your application, even if you have them installed.
  2. Whether it allows embedding: every TrueType font declares in its OS/2 table (fsType field) whether it can be embedded in documents. PDFBox respects this: if the font is marked as Restricted License, PDType0Font.load throws IOException: This font does not permit embedding. If it forbids subsetting, the error comes when saving (IOException: This font does not permit subsetting) and you'll have to load it with embedSubset = false, embedding it in full.

Free fonts you can safely use in a commercial product:

Family Licence Coverage Comment
DejaVu Sans / Serif / Mono Bitstream Vera (free) Latin, Greek, Cyrillic, many symbols and arrows The one we'll use in InvoiceLab: very complete
Liberation Sans / Serif / Mono SIL Open Font License 1.1 Latin, Greek, Cyrillic Same metrics as Arial, Times New Roman and Courier New: text takes up the same space
Noto Sans / Serif (Google) SIL Open Font License 1.1 One family per writing system (Noto Sans SC for Simplified Chinese, Noto Sans Arabic…) Ideal as fallback fonts; download the .ttf versions

The SIL Open Font License lets you use, embed and redistribute the font with your software; what it doesn't allow is selling it on its own. Keep the licence file next to the font (fonts/LICENSE-DejaVu.txt): it's good practice that any audit will appreciate.

Organizing fonts in the project

Following the structure set out in lesson 01-02, fonts go in src/main/resources/fonts/. For InvoiceLab we'll use the DejaVu Sans family:

invoicelab/
└── src/main/resources/
    └── fonts/
        ├── DejaVuSans.ttf
        ├── DejaVuSans-Bold.ttf
        ├── DejaVuSans-Oblique.ttf
        └── LICENSE-DejaVu.txt

Maven copies src/main/resources into the JAR, so at runtime the fonts are read from the classpath, not from disk: it will work the same on your computer, on a server or inside a Docker container.

Watch out for one Maven detail: if you enable resource filtering in the pom.xml (<filtering>true</filtering>) to substitute variables in configuration files, Maven will also "filter" the .ttf files as if they were text and corrupt them. If you need filtering, exclude them:

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
            <excludes>
                <exclude>fonts/**</exclude>
                <exclude>img/**</exclude>
            </excludes>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>false</filtering>
            <includes>
                <include>fonts/**</include>
                <include>img/**</include>
            </includes>
        </resource>
    </resources>
</build>

Loading a font with PDType0Font.load

PDType0Font is PDFBox's class for composite (Type 0) fonts: each character is encoded with two bytes (Identity-H encoding), which makes it possible to use all of the font's glyphs, not just 256. The most useful loading methods are:

Method Use
PDType0Font.load(PDDocument doc, File file) Load from disk (tests, tools)
PDType0Font.load(PDDocument doc, InputStream in) Load from the classpath or another byte source. Closes the stream when done
PDType0Font.load(PDDocument doc, InputStream in, boolean embedSubset) The same, choosing whether to embed a subset (true) or the full font (false)

The first two embed a subset by default. A first example, loading from the classpath:

try (PDDocument document = new PDDocument()) {
    PDFont dejaVu;
    try (InputStream in = getClass().getResourceAsStream("/fonts/DejaVuSans.ttf")) {
        if (in == null) {
            throw new IOException("Cannot find /fonts/DejaVuSans.ttf on the classpath");
        }
        dejaVu = PDType0Font.load(document, in);
    }

    PDPage page = new PDPage(PDRectangle.A4);
    document.addPage(page);
    try (PDPageContentStream content = new PDPageContentStream(document, page)) {
        content.beginText();
        content.setFont(dejaVu, 12);
        content.newLineAtOffset(50, 780);
        content.showText("Customer: Łukasz Nowak (Łódź) → 1.234,56 €");   // now it works!
        content.endText();
    }
    document.save("output/first-embedded-font.pdf");
}

Important points:

  • The first parameter is the document. An embedded font belongs to a specific PDDocument, because its data will end up inside that file. We'll come back to this at the end of the lesson.
  • getResourceAsStream returns null (it doesn't throw an exception) if the resource doesn't exist. Always check it: a NullPointerException deep inside PDFBox is much harder to diagnose.
  • The path starts with /: it's absolute from the root of the classpath. Without the slash, it would be looked up relative to the class's package.
  • The showText method and the rest of the text API don't change: only the font object changes. That's why in the previous lesson we declared the variables as PDFont.

Subsetting: embedding only what you need

DejaVu Sans weighs about 740 KB because it contains more than 6,000 glyphs. An invoice uses, at most, around a hundred. With embedSubset = true, PDFBox keeps track of which characters are used and, when saving, embeds a reduced version of the font with only those glyphs. Let's compare the same one-line PDF generated in three ways:

private static void generate(String output, File ttf, boolean subset) throws IOException {
    try (PDDocument document = new PDDocument()) {
        PDFont font = (ttf == null)
                ? new PDType1Font(Standard14Fonts.FontName.HELVETICA)
                : PDType0Font.load(document, new FileInputStream(ttf), subset);
        // ... A4 page with "Invoice F-2026-0001 · Nebula Distribution Ltd." ...
        document.save(output);
    }
}
standard          882 bytes
subset          6,797 bytes
full          394,582 bytes
TTF file      759,720 bytes
  • The standard font takes up no space (just the name), with the drawbacks we already know.
  • The subset adds about 6 KB: a minimal price for an identical look in every viewer and Unicode support.
  • The full font multiplies the size by 60 (PDFBox compresses it, which is why it doesn't reach the 740 KB of the .ttf). In a batch of 10,000 invoices, the difference is almost 4 GB.

When should you embed the full font? Practically only in AcroForm forms (module 5): the user can type new text into the fields and the viewer needs all the glyphs. For generated documents, always use a subset.

If you inspect the PDF's fonts (with PDFDebugger or with Poppler's pdffonts tool), you'll see that the name has a random six-letter prefix. That's the standard's convention for marking subsets:

name                                 type              encoding         emb sub uni
------------------------------------ ----------------- ---------------- --- --- ---
AAPUQD+DejaVuSans                    CID TrueType      Identity-H       yes yes yes
AAATXC+DejaVuSans-Bold               CID TrueType      Identity-H       yes yes yes

emb (embedded), sub (subset) and uni (has a ToUnicode table, needed to copy and search the text) should all be yes.

Unicode and missing glyphs

A Unicode font doesn't have every Unicode character (there are more than 150,000). DejaVu Sans covers Latin, Greek, Cyrillic and many symbols, but not Chinese, Japanese or most emojis. If you try to write a character with no glyph, showText throws the same IllegalArgumentException we saw with WinAnsi, with a different message:

No glyph for U+5317 (北) in font DejaVuSans
No glyph for U+1F69A () in font DejaVuSans
No glyph for U+000A (
) in font DejaVuSans

Line breaks and tabs are still not allowed: they aren't glyphs, they're control characters.

How to detect a character with no glyph

You may come across the hasGlyph(int) method in the API and think it's what you need here. Careful: in PDType0Font, the parameter isn't the character's Unicode code point but the font's internal code (the glyph identifier):

PDType0Font f = PDType0Font.load(document, new File("src/main/resources/fonts/DejaVuSans.ttf"));
System.out.println(f.hasGlyph(65));       // true... but DejaVu's glyph 65 is NOT the "A"
System.out.println(f.hasGlyph(0x5317));   // false, though for a different reason than you think

The reliable approach, valid for any font type, is the one we already used in the previous lesson: try to encode the text with encode and catch the exception.

public static boolean canRender(PDFont font, String text) throws IOException {
    try {
        font.encode(text);      // the same thing showText does internally
        return true;
    } catch (IllegalArgumentException e) {
        return false;
    }
}

Sanitizing text before writing it

Invoice data comes from databases and web forms: it may contain tabs, line breaks, invisible characters or an emoji the customer typed into the notes field. None of these cases should stop the invoice from being generated. A sensible policy:

Input character What we do
Tab, line feed, carriage return Replace with a space
Other (invisible) control characters Remove
Printable character with no glyph in the font Replace with ? (and, if possible, use a fallback font)
public static String sanitize(PDFont font, String text) throws IOException {
    StringBuilder result = new StringBuilder(text.length());
    text.codePoints().forEach(cp -> {
        if (cp == '\t' || cp == '\n' || cp == '\r') {
            result.append(' ');
        } else if (!Character.isISOControl(cp)) {
            result.appendCodePoint(cp);
        }
    });
    StringBuilder clean = new StringBuilder(result.length());
    for (int i = 0; i < result.length(); ) {
        int cp = result.codePointAt(i);
        String character = new String(Character.toChars(cp));
        clean.append(canRender(font, character) ? character : "?");
        i += Character.charCount(cp);
    }
    return clean.toString();
}

Why we iterate over code points (codePoints(), codePointAt) rather than char: characters outside Unicode's basic plane, such as emojis or some ideographs, take up two chars in Java (a surrogate pair). Iterating char by char would split them in half. Character.charCount(cp) tells you how many chars each character occupies so you can advance correctly.

Fallback fonts

Replacing with ? avoids the error, but a customer name such as "北京贸易有限公司" (a Beijing company) turned into "????????" isn't acceptable on an invoice. The professional technique is a list of fonts in order of preference: each character is written with the first font that has it. Word processors and browsers do the same.

flowchart LR
    T["Text: 'Customer: 北京'"] --> D{"Does DejaVu Sans<br/>have the character?"}
    D -- Yes --> T1["Run 'Customer: '<br/>with DejaVu Sans"]
    D -- No --> R{"Does the CJK font<br/>have it?"}
    R -- Yes --> T2["Run '北京'<br/>with CJK font"]
    R -- No --> Q["'?' with DejaVu Sans"]

The FallbackText class splits the text into consecutive runs that can each be written with a single font, and then writes them one after another, switching fonts between them (remember from lesson 02-02 that text continues where the previous text ended):

package com.invoicelab.pdf;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;

/**
 * Writes text using a list of fonts in order of preference:
 * each character is drawn with the first font that has it.
 */
public final class FallbackText {

    /** A fragment of text that can be written entirely with a single font. */
    public record Run(String text, PDFont font) {
    }

    private FallbackText() {
    }

    /** Splits the text into runs; characters that no font has are replaced with '?'. */
    public static List<Run> split(String text, List<PDFont> fonts) throws IOException {
        List<Run> runs = new ArrayList<>();
        StringBuilder current = new StringBuilder();
        PDFont currentFont = null;

        for (int i = 0; i < text.length(); ) {
            int cp = text.codePointAt(i);
            i += Character.charCount(cp);
            String character = new String(Character.toChars(cp));

            PDFont chosen = null;
            for (PDFont f : fonts) {
                if (InvoiceLabFonts.canRender(f, character)) {
                    chosen = f;
                    break;
                }
            }
            if (chosen == null) {            // no font has it
                chosen = fonts.get(0);
                character = "?";
            }
            if (chosen != currentFont && current.length() > 0) {
                runs.add(new Run(current.toString(), currentFont));
                current.setLength(0);
            }
            currentFont = chosen;
            current.append(character);
        }
        if (current.length() > 0) {
            runs.add(new Run(current.toString(), currentFont));
        }
        return runs;
    }

    /** Writes the text (must be called inside beginText/endText). */
    public static void write(PDPageContentStream content, String text, float size,
                             List<PDFont> fonts) throws IOException {
        for (Run run : split(text, fonts)) {
            content.setFont(run.font(), size);
            content.showText(run.text());
        }
    }
}

Key points of the algorithm:

  • The text is traversed by code point and, for each one, the first font in the list that can render it is chosen.
  • As long as the chosen font doesn't change, characters accumulate in the same run; when it changes, the previous run is closed. This produces few showText calls and few font switches.
  • The split method is independent of drawing and returns data (List<Run>), which means it can be unit-tested and, in the next lesson, used to measure the width of fallback text by adding up the widths of its runs.
  • It's a per-character fallback. It doesn't handle complex scripts that need shaping (Arabic, right-to-left Hebrew, Devanagari…): PDFBox doesn't reorder or join letters. Those cases require specialized libraries.

An example with several alphabets. For Chinese we use a CJK font in TrueType format (.ttf), for example Noto Sans SC or Droid Sans Fallback; here we've copied it to fonts/DroidSansFallbackFull.ttf:

try (PDDocument document = new PDDocument()) {
    InvoiceLabFonts fonts = new InvoiceLabFonts(document);   // we'll see it shortly
    PDFont regular = fonts.regular();
    PDFont cjk = fonts.load("DroidSansFallbackFull.ttf");
    // ... page and content box ...
    String[] texts = { "Customer: Łukasz Nowak (Łódź)", "Ελληνικά: Αθήνα · Кириллица: Москва",
            "Arrows and symbols: → ✓ ≤ ≥ ± · 1.234,56 €", "Customer: 北京贸易有限公司" };

    try (PDPageContentStream content = new PDPageContentStream(document, page)) {
        content.beginText();
        content.newLineAtOffset(box.left(), box.yFromTop(Measures.mm(10)));
        content.setLeading(20);
        for (String t : texts) {
            FallbackText.write(content, t, 11, List.of(regular, cjk));
            content.newLine();
        }
        content.setFont(fonts.italic(), 11);
        content.showText(InvoiceLabFonts.sanitize(regular, "Notes:\tdeliver\nto unit 3 🚚"));
        content.endText();
    }
    document.save("output/unicode-test.pdf");
}

The first four lines appear in full: the first three using only DejaVu Sans, and the fourth combining DejaVu ("Customer: ") with the CJK font ("北京贸易有限公司"). The last one shows Notes: deliver to unit 3 ?: the tab and line break have been turned into spaces and the truck emoji, which no font has, into ?. Thanks to subsetting, the CJK font (4 MB on disk) only adds a few KB to the PDF.

OpenType, CFF and TTC collections

Modern fonts are distributed in several formats, and not all of them load the same way in PDFBox:

Format Extension PDType0Font.load? Comment
TrueType .ttf Yes The recommended format
OpenType with TrueType outlines .ttf (sometimes .otf) Yes Internally it's TrueType
OpenType with CFF (PostScript) outlines .otf No: IOException: True Type fonts using CFF outlines are not supported Look for the .ttf version of the same family (Noto, Source Sans… publish one)
TrueType collection .ttc Not directly Contains several fonts; you have to extract one with TrueTypeCollection and use PDType0Font.load(doc, ttf, true)
Legacy Type 1 .pfb + .afm No (it's a different class, PDType1Font) Obsolete format; avoid it

Rule of thumb for InvoiceLab: always use .ttf. If a corporate typeface is only delivered as .otf, ask the designer for the TrueType version.

PDType1Font vs PDType0Font

Feature PDType1Font (standard 14) PDType0Font (embedded TrueType)
How it's created new PDType1Font(Standard14Fonts.FontName.X) PDType0Font.load(document, ...)
Needs a font file No Yes (.ttf)
Tied to a document No: it can be reused across documents Yes: only in the document it was loaded with
Encoding WinAnsiEncoding (1 byte per character) Identity-H (2 bytes per glyph)
Characters ~220 All the font's glyphs
Embedding Never Always (subset or full)
setWordSpacing (Tw) Works Ignored (only affects single-byte codes)
PDF size Minimal +5-20 KB per font with subsetting
PDF/A Not valid Valid
Recommended use Prototypes, quick tests, debugging grid All production documents

There's a third class, PDTrueTypeFont, which embeds a TrueType font as a single-byte "simple" font (with WinAnsi). It has the same character limitations as the standard fonts; you won't need it in this course.

System fonts and FontMapper: why you shouldn't rely on them

When PDFBox needs a font that isn't embedded (to render or measure one of the 14 standard fonts, or when opening someone else's PDF), it looks for it among the fonts installed on the system via the FontMappers class:

FontMapping<TrueTypeFont> mapping = FontMappers.instance().getTrueTypeFont("Arial", null);
System.out.println(mapping.getFont().getName() + " fallback=" + mapping.isFallback());
// On a Linux machine with Liberation fonts: "LiberationSans fallback=false"

That's the cause of the "Using fallback font LiberationSans for base font Symbol" warning you saw in the previous lesson. The first time it's used, PDFBox scans all the system fonts (it can take several seconds) and stores a cache in the .pdfbox.cache file in the user's home directory.

You might be tempted to load a system font in order to embed it (PDType0Font.load(doc, new File("C:/Windows/Fonts/arial.ttf"))). Don't do that in production code:

  • On a server or Docker container there are usually no fonts installed, or different ones: the same invoice would look different in development and in production.
  • The paths depend on the operating system.
  • The licence probably doesn't allow you to embed that font in documents you distribute.
  • The initial scan adds latency and can fail if the user's home directory isn't writable.

InvoiceLab rule: all fonts come from src/main/resources/fonts/. Never from the system.

One font per document: the InvoiceLabFonts class

The problem: a PDType0Font can't be shared between documents

A PDType0Font keeps references to the document it was loaded into and tracks the glyphs used in that document so it can generate the subset when saving. If you try to reuse it in another document (for example, by storing it in a static field to "save time"), the result ranges from an error to a corrupt PDF. A real case: loading the font with invoice 1, closing that document and using it in invoice 2 produces:

java.io.IOException: The TrueType font null does not contain a 'cmap' table

Closing the first document released the font's data. On top of that, PDType0Font isn't safe to use from multiple threads.

The solution: a static byte cache + per-document fonts

The expensive part is reading the .ttf file from the classpath; creating the PDType0Font from bytes in memory is fast. So we separate the two:

  • A static cache of each file's bytes (shared by the whole application; a byte[] that nobody modifies is thread-safe).
  • One InvoiceLabFonts object per document, which creates each PDType0Font the first time it's requested (lazy loading) and reuses it within that document.
package com.invoicelab.pdf;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;

/**
 * InvoiceLab corporate fonts for ONE document.
 *
 * - The bytes of each .ttf file are read from the classpath only once per application (static cache).
 * - The PDType0Font objects are created once per document and used only in that document.
 */
public final class InvoiceLabFonts {

    private static final String FOLDER = "/fonts/";
    private static final String REGULAR = "DejaVuSans.ttf";
    private static final String BOLD = "DejaVuSans-Bold.ttf";
    private static final String ITALIC = "DejaVuSans-Oblique.ttf";

    /** Font file cache shared by the whole application (bytes only: thread-safe). */
    private static final Map<String, byte[]> FONT_BYTES = new ConcurrentHashMap<>();

    private final PDDocument document;
    private PDFont regular;
    private PDFont bold;
    private PDFont italic;

    public InvoiceLabFonts(PDDocument document) {
        this.document = document;
    }

    public PDFont regular() throws IOException {
        if (regular == null) {
            regular = load(REGULAR);
        }
        return regular;
    }

    public PDFont bold() throws IOException {
        if (bold == null) {
            bold = load(BOLD);
        }
        return bold;
    }

    public PDFont italic() throws IOException {
        if (italic == null) {
            italic = load(ITALIC);
        }
        return italic;
    }

    /** Loads any other font from the /fonts/ folder for this document. */
    public PDFont load(String file) throws IOException {
        byte[] bytes = readBytes(file);
        // embedSubset = true: only the glyphs used will be embedded (done when saving)
        return PDType0Font.load(document, new ByteArrayInputStream(bytes), true);
    }

    private static byte[] readBytes(String file) throws IOException {
        try {
            return FONT_BYTES.computeIfAbsent(file, f -> {
                try (InputStream in = InvoiceLabFonts.class.getResourceAsStream(FOLDER + f)) {
                    if (in == null) {
                        throw new UncheckedIOException(
                                new IOException("Font not found on the classpath: " + FOLDER + f));
                    }
                    return in.readAllBytes();
                } catch (IOException e) {
                    throw new UncheckedIOException(e);
                }
            });
        } catch (UncheckedIOException e) {
            throw e.getCause();
        }
    }

    // ---------------------------------------------------------------------
    // Unicode utilities
    // ---------------------------------------------------------------------

    /** true if the font has a glyph for every character in the text. */
    public static boolean canRender(PDFont font, String text) throws IOException {
        try {
            font.encode(text);
            return true;
        } catch (IllegalArgumentException e) {
            return false;
        }
    }

    /**
     * Prepares a text for showText: converts tabs and line breaks into spaces,
     * removes other control characters and replaces anything the font can't draw with '?'.
     */
    public static String sanitize(PDFont font, String text) throws IOException {
        // ... body shown in the "Sanitizing text before writing it" section ...
    }
}

An explanation of the less obvious parts:

  • ConcurrentHashMap.computeIfAbsent: reads the file only the first time each name is requested, even if several threads are generating invoices at once.
  • UncheckedIOException: the computeIfAbsent lambda can't throw checked exceptions, so we wrap the IOException and unwrap it outside (e.getCause()) so the caller receives a normal IOException.
  • readAllBytes() (Java 9+) reads the whole resource; the try-with-resources closes the stream.
  • Lazy loading: if a document doesn't use italics, the italic font is neither loaded nor embedded.
  • load(String) is public for additional fonts (such as the CJK fallback font) without modifying the class.
  • The methods return PDFont, not PDType0Font: callers don't depend on the concrete type.

The usage pattern looks like this, and we'll repeat it throughout the course:

try (PDDocument document = new PDDocument()) {
    InvoiceLabFonts fonts = new InvoiceLabFonts(document);   // one per document
    // ... use fonts.regular(), fonts.bold() on every page of THIS document ...
    document.save("output/invoice.pdf");                     // the subsets are generated here
}   // once the document is closed, its fonts can no longer be used

Applying it to the invoice

Let's go back to IssuerCustomerDetails from the previous lesson. Since writeBlock takes PDFont, the change is limited to creating the fonts, and now we can have customers with any name DejaVu Sans covers:

try (PDDocument document = new PDDocument()) {
    InvoiceLabFonts fonts = new InvoiceLabFonts(document);
    PDFont regular = fonts.regular();
    PDFont bold = fonts.bold();

    List<String> customer = List.of(
            "Łukasz Nowak Import Sp. z o.o.",
            "VAT ID: PL0000000000",
            "ul. Przykładowa 7",
            "90-001 Łódź (Poland)");
    // ... the rest of the code is identical to lesson 02-02 ...
}

A single line of change when creating each font, and the invoice becomes viewer-independent and ready for international customers. When the data comes from a database (module 3), we'll pass each text through InvoiceLabFonts.sanitize(...) or FallbackText before writing it.

Common Mistakes and Tips

  • Storing a PDType0Font in a static field to reuse it across documents. It causes errors such as "does not contain a 'cmap' table" or corrupt PDFs. Cache the bytes, not the font.
  • Not checking for null from getResourceAsStream. If the path is wrong (missing leading /, different capitalization on Linux), you'll get a confusing error. Throw your own IOException that includes the path.
  • Maven resource filtering enabled on fonts. It corrupts the .ttf files; exclude them from filtering.
  • Using hasGlyph(int) with Unicode code points. In PDType0Font it takes internal codes. Use encode with try/catch.
  • Loading an .otf with CFF outlines. It throws "True Type fonts using CFF outlines are not supported". Use the .ttf version.
  • Embedding the full font (embedSubset = false) in generated documents: it multiplies the PDF size with no benefit at all. Keep it for forms.
  • Using system fonts on a server. What works on your laptop fails in the container. Fonts belong in resources.
  • Ignoring the licence. Having a font on your computer doesn't mean you can distribute it. Use families with a free licence (OFL, Bitstream Vera) and keep the licence next to the file.
  • Tip: iterate over text by code point, not by char, when working with Unicode.

Exercises

  1. The Liberation family. Add the fonts LiberationSerif-Regular.ttf and LiberationSerif-Bold.ttf to src/main/resources/fonts/ and write a program that, using InvoiceLabFonts.load(...), generates a PDF with the title "Supply agreement" in Liberation Serif bold (18 pt) and, below it, "Nebula Distribution Ltd. and Łukasz Nowak Import" in Liberation Serif regular (11 pt).
  2. Report of characters that can't be rendered. Write a method static Set<String> missingGlyphs(PDFont font, String text) that returns the set of characters (as strings) the font can't draw, ignoring control characters. Test it with DejaVu Sans and the text "Urgent order 🚚 for 北京 → deliver ✓".
  3. Diagnosis. A colleague has written this code to "optimize" invoice generation. Explain what's wrong with it and how to fix it.
public class FastGenerator {
    private static PDFont font;

    public static byte[] generate(String customer) throws IOException {
        try (PDDocument document = new PDDocument()) {
            if (font == null) {
                font = PDType0Font.load(document, new File("C:/Windows/Fonts/arial.ttf"), false);
            }
            // ... writes the invoice with 'font' and saves it to a byte[] ...
        }
    }
}

Solutions

Solution 1.

try (PDDocument document = new PDDocument()) {
    InvoiceLabFonts fonts = new InvoiceLabFonts(document);
    PDFont serif = fonts.load("LiberationSerif-Regular.ttf");
    PDFont serifBold = fonts.load("LiberationSerif-Bold.ttf");

    PDPage page = new PDPage(PDRectangle.A4);
    document.addPage(page);
    ContentBox box = ContentBox.invoice(page.getMediaBox());

    try (PDPageContentStream content = new PDPageContentStream(document, page)) {
        content.beginText();
        content.newLineAtOffset(box.left(), box.yFromTop(Measures.mm(10)));
        content.setFont(serifBold, 18);
        content.showText("Supply agreement");
        content.newLineAtOffset(0, -24);
        content.setFont(serif, 11);
        content.showText("Nebula Distribution Ltd. and Łukasz Nowak Import");
        content.endText();
    }
    document.save("output/contract-liberation.pdf");
}

If you call load again with the same name in another document, the file isn't read from the classpath again: the cached bytes are reused. If you wanted to use Liberation Serif often, you could add serif() and serifBold() methods to InvoiceLabFonts following the regular() pattern.

Solution 2.

static Set<String> missingGlyphs(PDFont font, String text) throws IOException {
    Set<String> missing = new LinkedHashSet<>();          // keeps the order of appearance
    for (int i = 0; i < text.length(); ) {
        int cp = text.codePointAt(i);
        i += Character.charCount(cp);
        if (Character.isISOControl(cp)) {
            continue;
        }
        String character = new String(Character.toChars(cp));
        if (!InvoiceLabFonts.canRender(font, character)) {
            missing.add(character);
        }
    }
    return missing;
}

With DejaVu Sans it returns [🚚, 北, 京]: the arrow → and the ✓ are in the font. This method is useful for logging which characters were replaced, which lets you spot early on that a new fallback font is needed.

Solution 3. There are four problems:

  1. A static font shared between documents: the first invoice works, but the second uses a font tied to a document that has already been closed (a "does not contain a 'cmap' table" error or a corrupt PDF). In addition, several simultaneous requests would share an object that isn't thread-safe.
  2. A system font with a Windows path: it fails on any Linux server or container, and Arial can't be redistributed.
  3. embedSubset = false: it embeds the full font in every invoice (hundreds of unnecessary KB).
  4. Even if the above were fixed, the "optimization" saves very little: the expensive part is reading the file, not creating the PDType0Font.

Corrected version, using InvoiceLabFonts (static byte cache, per-document fonts, subsetting and a free font from the classpath):

public static byte[] generate(String customer) throws IOException {
    try (PDDocument document = new PDDocument()) {
        InvoiceLabFonts fonts = new InvoiceLabFonts(document);
        PDFont font = fonts.regular();
        // ... writes the invoice with 'font' ...
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        document.save(output);
        return output.toByteArray();
    }
}

Conclusion

InvoiceLab's invoices no longer depend on the viewer or on WinAnsiEncoding: we embed TrueType fonts with PDType0Font.load, always as a subset so they only take up a few KB, we choose freely licensed families (DejaVu, Liberation, Noto) stored in src/main/resources/fonts/, we detect characters with no glyph using encode, we sanitize text and, when needed, we combine fonts with FallbackText. You also know why you shouldn't use .otf fonts with CFF outlines or system fonts, and why a PDType0Font belongs to a single document, a rule the InvoiceLabFonts class encapsulates.

Writing text is no longer a problem; positioning it properly still is. So far we've placed each line at fixed coordinates and centred things "by eye". In the next lesson we'll learn to measure text (its real width and height from the font metrics) so we can align it left, centre or right (the invoice amounts), justify it, break long paragraphs into lines and truncate text that doesn't fit, all brought together in a reusable text box: TextBlock.

PDF Generation and Editing with Apache PDFBox

Module 1: PDF and PDFBox Fundamentals

Module 2: Generating Content

Module 3: Business Documents

Module 4: Editing Existing PDFs

Module 5: AcroForm Forms

Module 6: Extraction and Analysis

Module 7: Security and Digital Signatures

Module 8: PDFBox in Production

© Copyright 2026. All rights reserved