LLION/ PDF, print & document engineering

Fonts in PDF

LLION Editorial · Updated

A PDF never contains text in the sense a word processor does. It contains strings of character codes and, for each string, a reference to a font object that says which glyph each code selects and how wide it is. Whether the glyph program itself is inside the file, and whether the codes can be turned back into Unicode, are separate questions with separate answers, and both are decided by the writer of the file. That is why a document can look perfect and copy as garbage, or look wrong on one machine and right on another. This page explains the font objects, the two families they come in, what embedding and subsetting actually store, and how to check a file.

Where fonts live#

A page's /Resources dictionary maps resource names to font dictionaries; the content stream selects one with Tf and shows strings with Tj or TJ, as the syntax page describes. A font dictionary has /Type /Font, a /Subtype naming its kind, and /BaseFont, the PostScript name of the typeface. What else it contains depends on the subtype.

Font object chain: the page resources point to a Type 0 font, which points to a CIDFontType2 descendant and a ToUnicode CMap; the descendant points to a font descriptor that holds the embedded TrueType program in FontFile2 Page/Resources /Font /F1 Type0 font/Encoding /Identity-H ToUnicodeCMap stream CIDFontType2/W widths, /CIDToGIDMap FontDescriptor/Flags /FontBBox FontFile2TrueType program /DescendantFonts A simple font (Type1, TrueType) has no descendant:the font dictionary points straight at its descriptor,and may carry /Encoding and /ToUnicode itself.
The chain for a composite font with an embedded TrueType program. Each arrow is an indirect reference; every box is a separate object.

Simple fonts#

A simple font maps single-byte codes, 0 to 255, to glyphs (ISO 32000-1 §9.6). The subtypes are /Type1 (a PostScript Type 1 program, or one of the standard 14), /TrueType, /Type3 (glyphs defined as PDF content streams, used by some TeX and scanning workflows) and /MMType1 (a multiple-master instance). The dictionary gives /FirstChar, /LastChar and a /Widths array so a reader can lay out text without opening the font program, and an /Encoding that says which glyph each code selects.

Encoding is where simple fonts show their age. /Encoding may be a predefined name such as /WinAnsiEncoding or /MacRomanEncoding, or a dictionary with a base encoding and a /Differences array that remaps individual codes to glyph names (§9.6.6). For TrueType fonts the rules for turning a code into a glyph index run through the font's own cmap tables and are notoriously fiddly, which is one reason generators moved away from simple TrueType fonts. The hard limit is 256 codes per font: a document in a language that needs more glyphs, or a design that uses many OpenType alternates, cannot be expressed as a simple font without splitting it into several.

Composite fonts#

A composite font, subtype /Type0, decodes strings as multi-byte codes and sends them through a CMap to CIDs, character identifiers, which select glyphs in a descendant CIDFont (§9.7). The /DescendantFonts array holds exactly one CIDFont, either /CIDFontType0 (glyphs from a CFF or OpenType-CFF program) or /CIDFontType2 (glyphs from a TrueType program). The /Encoding of the Type 0 font is usually the predefined /Identity-H: two bytes per code, and the code is the CID. For /CIDFontType2, /CIDToGIDMap then maps CIDs to glyph indices, often also identity. Widths come from a compact /W array rather than a flat list.

This is the structure nearly every modern generator writes for TrueType and OpenType fonts, whatever the language of the text. It removes the 256-glyph limit, it sidesteps the simple-font encoding rules, and with identity mappings the pipeline is just "code equals glyph index". The cost is that the codes carry no meaning of their own, which brings us to extraction.

Text extraction and ToUnicode#

Showing text and extracting it are different operations, and the format only guarantees the first. To turn codes back into characters a reader follows the rules of §9.10: if the font has a /ToUnicode CMap, use it; otherwise, for a simple font, derive characters from the encoding's glyph names (a glyph called eacute is U+00E9) or, for a composite font with a known CID ordering, from the ordering's Unicode tables. A /Type0 font with /Identity-H and no /ToUnicode fails every rule: the codes are glyph indices in a private font program, and nothing in the file says what they mean. Copying such text yields boxes, wrong letters, or sequences like /uni0048 depending on the viewer.

A ToUnicode CMap is a small stream in the font dictionary that maps code ranges to Unicode strings:

a ToUnicode CMap fragment: codes 0x0001 to 0x0003 map to A, B, C; code 0x0024 maps to the ligature "fi"PDF syntax
/CIDInit /ProcSet findresource begin
12 dict begin
begincmap
/CMapName /Adobe-Identity-UCS def
1 begincodespacerange
<0000> <FFFF>
endcodespacerange
1 beginbfrange
<0001> <0003> <0041>
endbfrange
1 beginbfchar
<0024> <00660069>
endbfchar
endcmap
CMapName currentdict /CMap defineresource pop
end
end

Good generators write one for every font. When text extraction, search, accessibility checks or PDF/A validation fail on a file that displays correctly, a missing or wrong ToUnicode map is the first thing to check, and pdffonts reports it in its uni column.

The standard 14 and PDF 2.0#

ISO 32000-1 §9.6.2.2 names fourteen Type 1 fonts that every conforming reader must be able to render without a font program in the file: Times (Roman, Bold, Italic, BoldItalic), Helvetica (regular, Bold, Oblique, BoldOblique), Courier (the same four), Symbol and ZapfDingbats. A file that uses /BaseFont /Helvetica with no embedded program is relying on that rule, and readers substitute a metric-compatible face (Liberation Sans, Arimo, Nimbus Sans) when the original is not installed. The text reflows correctly because the widths match; the shapes differ slightly.

PDF 2.0 (ISO 32000-2) removed the exemption: a 2.0 file is expected to embed every font it uses, standard 14 included. The practical rule for new documents is therefore simple. Embed everything. The one-page example on the anatomy page deliberately does not, to stay at 592 bytes, and it is a 1.7 file.

What embedding stores#

Embedding means the font program is inside the PDF, referenced from the font descriptor (§9.8), a dictionary holding metrics and flags for the font: /Flags, /FontBBox, /ItalicAngle, /Ascent, /Descent, /CapHeight, /StemV. Exactly one of three keys carries the program (§9.9, Table 126):

Embedded font program keys in the font descriptor (ISO 32000-1 Table 126)
KeyProgram formatUsed for
/FontFileType 1 (PFB-style, with /Length1, /Length2, /Length3 segments)/Type1 fonts
/FontFile2TrueType (glyf outlines)/TrueType and /CIDFontType2
/FontFile3 with /Subtype /Type1CCompact Font Format (CFF) equivalent of a Type 1 font/Type1 fonts
/FontFile3 with /Subtype /CIDFontType0CCFF CID-keyed font/CIDFontType0
/FontFile3 with /Subtype /OpenTypeComplete OpenType wrapper (PDF 1.6)any subtype, depending on the outlines inside

The stream itself is binary and almost always Flate-compressed. Fonts are the second-largest thing in a typical text document after images, which is why subsetting exists.

Subsetting#

A subset font contains only the glyphs the document uses. The specification marks one by prefixing the font name with a tag of six uppercase letters and a plus sign (§9.6.4): /BaseFont /DDPEFM+Helvetica. Different subsets of the same face in one file must carry different tags, and the tag is what lets a reader tell them apart and, when documents are merged, decide whether two fonts can be combined.

Subsetting cuts a 500 KB CJK font to a few kilobytes and is the default in every serious generator. The trade-offs are small but real. Text added to the document later needs glyphs the subset may not have, so editors either fall back to a system font or produce a notdef box. Form fields filled after creation have the same problem, which is why form designers embed full fonts for field appearance. And font licences sometimes forbid subsetting outright (next section). PDF/A permits subsets; it only requires that every glyph used be present.

Licensing flags#

TrueType and OpenType fonts declare their embedding permissions in the fsType field of the OS/2 table. Per the OpenType specification, the low four bits hold one of four exclusive values: 0, installable embedding; 2, restricted licence embedding (the font must not be embedded without permission); 4, preview and print embedding (the embedded copy may be used only to view and print); 8, editable embedding. Bit 8 (value 0x0100) means the font must not be subsetted, and bit 9 (0x0200) permits embedding bitmaps only. Type 1 fonts carry no equivalent field; their terms live in the licence text.

Generators handle this inconsistently. Some refuse to embed a font whose fsType is 2 and substitute silently; others ignore the field entirely and embed whatever they are given. The field is a declaration, not a technical lock, and it does not change the legal position either way: the licence you accepted when you obtained the font does. Open-licence fonts (SIL OFL, Apache, UFL) permit embedding and subsetting; commercial licences vary, and "desktop" licences frequently exclude embedding in documents that will be distributed.

Checking a file#

In Acrobat and most viewers, Document Properties lists every font with "(Embedded)", "(Embedded Subset)" or nothing. From the command line, poppler's pdffonts prints one row per font with columns for the name, type, encoding, and yes/no flags for embedded, subset and ToUnicode, followed by the object number; its type column distinguishes Type 1, Type 1C, Type 3, TrueType, CID Type 0, CID Type 0C and CID TrueType, which is enough to tell what was embedded and how.

The same information is a short script away with pdf-lib, which exposes the raw dictionaries. This lists each page's fonts and whether the descriptor holds a program:

list-fonts.js (pdf-lib 1.17.1, Node 20 or newer)JavaScript
const fs = require("fs");
const { PDFDocument, PDFName, PDFDict, PDFArray } = require("pdf-lib");

async function main(file) {
  const doc = await PDFDocument.load(fs.readFileSync(file), { updateMetadata: false, ignoreEncryption: true });
  doc.getPages().forEach((page, i) => {
    const fonts = page.node.Resources() && page.node.Resources().lookupMaybe(PDFName.of("Font"), PDFDict);
    if (!fonts) return;
    for (const [key, value] of fonts.entries()) {
      const font = doc.context.lookup(value, PDFDict);
      const subtype = String(font.get(PDFName.of("Subtype")) || "");
      const base = String(font.get(PDFName.of("BaseFont")) || "");
      let target = font;
      if (subtype === "/Type0") {                       // composite: look at the descendant
        const desc = font.lookupMaybe(PDFName.of("DescendantFonts"), PDFArray);
        if (desc && desc.size()) target = doc.context.lookup(desc.get(0), PDFDict);
      }
      const fd = target.lookupMaybe(PDFName.of("FontDescriptor"), PDFDict);
      let program = "not embedded";
      if (fd) for (const k of ["FontFile", "FontFile2", "FontFile3"]) if (fd.has(PDFName.of(k))) program = k;
      const subset = /^\/[A-Z]{6}\+/.test(base) ? ", subset" : "";
      console.log(`page ${i + 1}  ${key}  ${base}  ${subtype}  ${program}${subset}`);
    }
  });
}
main(process.argv[2]);

Run against the 592-byte example it prints one line, page 1 /F1 /Helvetica /Type1 not embedded. Run against the ISO 32000-1 specification PDF itself, the output begins:

node list-fonts.js PDF32000_2008.pdf (first lines)Text
page 1  /T1_0  /DDPEFM+Helvetica       /Type1     FontFile3, subset
page 1  /T1_1  /DDPEIM+Helvetica-Bold  /Type1     FontFile3, subset
page 2  /TT0   /Arial-BoldMT           /TrueType  not embedded
page 2  /TT1   /ArialMT                /TrueType  not embedded
page 4  /C2_0  /DDPGBI+SymbolMT        /Type0     FontFile2, subset

Even the standard's own PDF mixes embedded CFF subsets, an unembedded TrueType Arial, and a composite font with a TrueType subset. The PDF inspector on this site reports the same fields in the browser.

What goes wrong, and the fix#

  • Font not embedded, not installed. The viewer substitutes. With a standard-14 name the widths match and the text reflows cleanly; with anything else the substitute's widths differ, lines overrun or gap, and bold or italic may be synthesised. Fix: embed. For existing files, Ghostscript and some commercial tools can embed from a locally installed copy, but the honest fix is re-exporting.
  • Text displays, copies as nonsense. Missing or incorrect ToUnicode, usually with an /Identity-H composite font. Fix: regenerate with a tool that writes ToUnicode; for existing files, OCR is often the only route.
  • Boxes or blanks for some characters. The subset lacks a glyph that later editing needed, or a simple font's /Differences names a glyph the program does not have. Fix: embed the full font where editing is expected, and check .notdef warnings in preflight.
  • Fuzzy text that cannot be selected. A Type 3 bitmap font, typically from old TeX output or a scanner. Fix: re-render from source with outline fonts, or OCR.
  • PDF/A or PDF/X validation fails on fonts. Both families require every font to be embedded, and PDF/A additionally requires that embedded programs contain every glyph used; its level A conformance also requires that text be mappable to Unicode. The standards page lists the rules per part.

Embedding with a library#

Every generator covered in the developer guides embeds TrueType and OpenType fonts and subsets by default when given the font file. In pdf-lib the sequence is register fontkit, embed the bytes, draw; the subset option controls subsetting:

embed.mjs (pdf-lib 1.17.1 with @pdf-lib/fontkit 1.1.1)JavaScript
import fontkit from "@pdf-lib/fontkit";
import { PDFDocument } from "pdf-lib";

const doc = await PDFDocument.create();
doc.registerFontkit(fontkit);
const font = await doc.embedFont(fontBytes, { subset: true });   // Uint8Array of a .ttf or .otf
const page = doc.addPage([595.28, 841.89]);
page.drawText("Embedded and subset", { x: 72, y: 770, size: 24, font });

Hand a generator a .woff2 and it will fail: the web font wrappers are not font programs a PDF can hold, so keep the original .ttf or .otf for document generation. The per-language guides show the equivalent calls for ReportLab, fpdf2, TCPDF, QuestPDF, PDFBox and the others, and the JavaScript guide covers the browser case, where fonts must be fetched as bytes before they can be embedded.

Sources