Technical Article

Rendering Embedded PDF Fonts in Delphi with HotPDF

The word "Invoice" in a subset-embedded PDF is often not stored as letters at all. Under a composite font with an Identity encoding, the content stream holds two-byte glyph indices, so the word can look like <002C00510059...>: numbers that mean a capital I and a lowercase n only inside the font program packed into that one file. On the workstation that produced it, a renderer that looks fonts up by name may still draw the page correctly, because the face happens to be installed there. On a clean build server the same page shows empty boxes, or a lookalike face that moves every line break

ISO 32000-1 §9.9 defines three places in the font descriptor where the font program can live: FontFile holds an original Type 1 program, FontFile2 a TrueType program, and FontFile3 a bare CFF (Type1C or CIDFontType0C) or an OpenType wrapper. Type 3 fonts, defined in §9.6.5, embed no binary program at all; each glyph is a small PDF content stream. The outline maths differs for each one (quadratic B-splines, cubic charstrings, arbitrary page operators), and before any outline is touched, an encoding layer has to turn character codes into glyph indices

HotPDF: Embedded PDF font carriers: the font descriptor holds FontFile, FontFile2, or FontFile3 programs and Type 3 content streams, and each carrier follows its own rendering path
TrueType glyf outlines, CFF charstrings and Type 3 content streams each get their own interpreter, while a FontFile Type 1 program takes the installed-font path

Which embedded fonts HotPDF draws from the file

The HotPDF page renderer draws text from the font programs stored inside the PDF whenever the file carries one it can read: TrueType glyf outlines from FontFile2, CFF Type 2 charstrings from FontFile3 (an OpenType OTTO wrapper is unwrapped to its CFF table first), and Type 3 glyph procedures. Every glyph becomes a filled vector path, and nothing has to be installed on the machine. This is the font-side companion to rendering PDF pages to a TBitmap with HotPDF, which covers the renderer as a whole

There is no font API to call. RenderLoadedPageToBitmap picks the embedded path per font and per glyph on its own, and the only setting worth touching for font work is the fallback policy, which decides whether the renderer quietly works around a problem or records it for you:

uses
  Graphics, HPDFDoc, HPDFPageRenderer;

procedure RenderPageWithEmbeddedFonts(const FileName: string);
var
  Pdf: THotPDF;
  Bmp: TBitmap;
  Diag: THPDFRenderFallbackDiagnostics;
  I: Integer;
begin
  Pdf := THotPDF.Create(nil);
  try
    if Pdf.LoadFromFile(FileName) <= 0 then
      Exit;
    // Record fallbacks (a Type 3 nesting limit, an undecodable stream)
    // instead of ignoring them; rfpStrict raises an exception instead
    Pdf.RenderFallbackPolicy := rfpReport;
    Bmp := Pdf.RenderLoadedPageToBitmap(0, 144);
    if Bmp = nil then
      Exit;
    try
      Bmp.SaveToFile('page1.bmp');
    finally
      Bmp.Free;
    end;
    Diag := Pdf.GetLastRenderFallbackDiagnostics;
    for I := 0 to High(Diag) do
      Writeln(string(Diag[I].ObjectName), ': ', string(Diag[I].Reason));
  finally
    Pdf.Free;
  end;
end;

Two kinds of font take the installed-font path instead. A FontFile Type 1 program, which is eexec-encrypted, is not interpreted, and neither is a simple TrueType font whose program has no usable cmap; both draw through the face Windows supplies for the font name. The rest of this article is about what happens on the embedded path

TrueType glyf outlines: implied points and exact cubics

For a FontFile2 program HotPDF reads head for units per em and the loca offset format, finds each glyph record through loca, decodes the delta-encoded contour points, and replays them as a GDI path. Two TrueType conventions decide whether the result looks right. Two consecutive off-curve points imply an on-curve point at their midpoint, and a contour whose points are all off-curve starts at the midpoint of its last and first points. Skip the first rule and rounded letters grow flat facets; skip the second and an O or a 0 drawn entirely from control points vanishes

The other mismatch is curve degree. TrueType curves are quadratic Béziers, and GDI's PolyBezierTo only takes cubics. Flattening into line segments would work at one zoom level and show corners at the next, so HotPDF elevates every quadratic segment to an exact cubic:

TrueType glyf rendering pipeline in Delphi: the loca table locates glyph records, implied on-curve midpoints are reconstructed, quadratics are elevated exactly to cubics, and GDI fills the path
Implied midpoints and exact degree elevation keep the replayed outline identical to the authored glyf curves
// Exact degree elevation: quadratic (P0, Q, P2) -> cubic (P0, C1, C2, P2)
// C1 = P0 + 2/3 (Q - P0),  C2 = P2 + 2/3 (Q - P2)
C1.X := P0.X + 2 * (Q.X - P0.X) / 3;
C1.Y := P0.Y + 2 * (Q.Y - P0.Y) / 3;
C2.X := P2.X + 2 * (Q.X - P2.X) / 3;
C2.Y := P2.Y + 2 * (Q.Y - P2.Y) / 3;
// then PolyBezierTo with C1, C2, P2: the same curve, now cubic

The cubic traces exactly the same curve. Composite glyphs recurse into their components with each component's 2.14 fixed-point scale and offset composed in; a component that names its own glyph is skipped, and nesting depth and component count are capped, so a hostile composite cannot loop the renderer

Placement is plain matrix work that is easy to get wrong in one line. Glyphs are authored on a units-per-em grid (1000 and 2048 are typical); the renderer scales by font size over units per em, applies horizontal scaling and text rise, then the text matrix, then the CTM. Compose those backwards and every glyph shrinks towards the page origin

Why CFF charstrings are harder to keep in sync

A FontFile3 program gets a Type 2 charstring interpreter: HotPDF parses the CFF INDEX structures, the Top DICT and Private DICT, local and global subroutines, then executes each glyph's charstring and emits path segments directly. Charstrings are a compact stack language, so a single miscount does not produce one wrong point. It desynchronizes the byte stream for the rest of the glyph

Three conventions carry most of that risk. The first stack-clearing operator may carry one extra leading operand, the glyph width, which has to be peeled off before the real arguments are counted. The hintmask and cntrmask operators treat any operands still on the stack as an implicit vstemhm, and the number of mask bytes that follow is the accumulated stem count divided by eight, rounded up; get the stem count wrong once and every later opcode is read from the middle of a mask. And subroutine numbers are biased: 107 when a subroutine INDEX holds fewer than 1240 entries, 1131 below 33900, and 32768 above that. An unbiased call lands on the wrong subroutine entirely

Fonts converted from Type 1 bring one older convention: endchar with four operands is the deprecated seac composition, which draws a base glyph and an accent glyph, both named by their StandardEncoding codes, with the accent offset by the given deltas. An interpreter that treats every endchar as "glyph finished" draws nothing for é or ñ in those fonts. HotPDF resolves both names through the program's charset and draws the pair. Subroutine depth and the operation count per glyph are capped, since nested callsubr chains in a crafted font can otherwise multiply without bound

CID-keyed CFF adds one indirection. The character code selects a CID, but the charstring INDEX is ordered by glyph index, and the font's charset maps GID to CID, the opposite direction from what drawing needs. HotPDF builds the inverse CID-to-GID table once per font, and for programs with several font DICTs it uses FDSelect (formats 0 and 3) to pick each glyph's own local subroutines. Hint operators are parsed to keep the stream aligned; the outline itself is filled as authored

What is a Type 3 font, and why does its colour come from the page?

A Type 3 glyph is a content stream, not an outline. HotPDF draws one by saving the graphics state, setting the CTM to the composition of font matrix, font size, text matrix and page CTM, and running the glyph procedure through the same operator interpreter that draws pages, with the font's own /Resources in scope. Repeated glyphs reuse the tokenised procedure

Two spec details catch naive implementations. Type 3 /Widths are expressed in glyph space, so advances must pass through /FontMatrix rather than the 1/1000 text-space scale every other font type uses. Take a font that declares /FontMatrix [0.01 0 0 0.01 0 0]: a renderer that assumes 1/1000 steps every advance ten times too short, and the characters pile on top of each other

The second detail is the d1 operator. ISO 32000-1 §9.6.5 says a glyph procedure that begins with d1 describes shape only, so its own colour operators (rg, g, k and their stroking twins) are ignored and the glyph paints in the caller's current fill colour. HotPDF suppresses those operators for the duration of a d1 glyph and clips painting to the declared bounding box, while a d0 glyph keeps its own colours. Ignore the rule and a d1 barcode font that the page sets in blue comes out black. Type 3 procedures may draw text in other Type 3 fonts; that nesting stops at 16 levels, and under rfpReport the cutoff appears in GetLastRenderFallbackDiagnostics as a recursion-limit entry

How character codes become glyph IDs

The bytes in a PDF text string are character codes, and ISO 32000-1 spends two subclauses on mapping them to glyphs. For simple fonts, §9.6.6 sets a strict priority: a /Differences array overrides the base encoding (WinAnsiEncoding, MacRomanEncoding or StandardEncoding), which overrides the font program's own map. HotPDF resolves that chain into a 256-entry code-to-GID table. Glyph names reach glyph indices three ways: an exact charset match inside a CFF program, gNN or glyphNN subset names read as literal indices, and Adobe Glyph List name-to-Unicode translation followed by a cmap lookup for TrueType programs

For composite fonts, §9.7 routes the code through the encoding CMap to a CID, then CIDToGIDMap picks the glyph. /Identity is the common case, but the entry may also be a stream of big-endian two-byte GIDs indexed by CID. HotPDF's own Unicode output writes that stream form for compact font subsets, so the stream path gets regular use, not just in odd third-party files:

HotPDF: Mapping PDF character codes to glyph IDs: simple fonts resolve through Differences, the base encoding, and the font program map, composite fonts through CIDToGIDMap, then a TrueType cmap fallback chain with a single-glyph GDI fallback
Both font families end in a code-to-GID table, and any unmappable code degrades a single glyph instead of the text run
// /CIDToGIDMap as a stream: big-endian Word pairs indexed by CID
if 2 * CID + 1 <= High(MapBytes) then
  GID := (MapBytes[2 * CID] shl 8) or MapBytes[2 * CID + 1]
else
  GID := 0;  // out of range maps to .notdef

When a TrueType cmap lookup is needed, HotPDF walks a fallback chain instead of trusting one subtable. Unicode subtables come first: format 4 for the Basic Multilingual Plane, format 12 for supplementary code points. The (3,0) symbol subtable follows, tried with the code as given and then with the code moved into the F000 private-use range, which is how a symbol font such as Wingdings answers for plain single-byte codes. The Macintosh (1,0) subtable in format 0 or 6 is last. Format 2 subtables, which map legacy multi-byte code pages like Shift-JIS and Big5, are not consulted; embedded CJK fonts normally carry format 4 or 12 anyway. A code that no route resolves is drawn from the installed face for that one glyph, and the rest of the run stays on the embedded outlines

Small text, stroked text, and fonts that are not embedded

Outlines are filled as authored, without running TrueType instructions or CFF hints. We chose exact positions over hinting: hinting snaps each glyph to whole pixels, and at small sizes that spaces text unevenly. To keep thin stems from dropping out instead, glyphs up to 64 pixels are filled through a 4×4 supersampled coverage mask and glyphs up to 256 pixels through a 2× mask, both at their sub-pixel positions; larger glyphs are filled as a plain nonzero-winding GDI path. Text render modes 0, 1 and 2 (fill, stroke, both) use the same outlines, and a sub-pixel stroke width keeps its real width on small glyphs, which is what faux-bold text stroked with a hairline relies on

The installed-font path borrows the same approach. When a glyph has to come from a Windows face, small filled glyphs are taken from that face's unhinted outline and placed through the same coverage mask, so fallback text lands at the same sub-pixel positions as embedded text; plain GDI text output is reserved for glyphs the face lacks and for large ones. None of that recreates a typeface the machine does not have, so it pays to know which fonts will take this path before a customer does. The page's font resources tell you:

uses
  Classes, SysUtils, HPDFDoc, HPDFObjs;

// Your own helper, not part of HotPDF: returns the FontDescriptor of a page
// font. A Type0 font keeps its descriptor in the descendant CIDFont
function FontDescriptorOf(Pdf: THotPDF; Font: THPDFDictionaryObject): THPDFDictionaryObject;
var
  Idx: Integer;
  Kids: THPDFObject;
begin
  Result := nil;
  if Font = nil then
    Exit;
  Idx := Font.FindValue('DescendantFonts');
  if Idx >= 0 then
  begin
    Kids := Pdf.ResolveLoadedObject(Font.GetIndexedItem(Idx));
    if not (Kids is THPDFArrayObject) or (THPDFArrayObject(Kids).Items.Count = 0) then
      Exit;
    Font := Pdf.ResolveLoadedDictionary(THPDFArrayObject(Kids).GetIndexedItem(0));
    if Font = nil then
      Exit;
  end;
  Idx := Font.FindValue('FontDescriptor');
  if Idx >= 0 then
    Result := Pdf.ResolveLoadedDictionary(Font.GetIndexedItem(Idx));
end;

procedure ListFontCarriers(Pdf: THotPDF; PageIndex: Integer; Log: TStrings);
var
  I: Integer;
  Info: THPDFLoadedFontInfo;
  Desc: THPDFDictionaryObject;
  Carrier: string;
begin
  for I := 0 to Pdf.GetLoadedFontCount(PageIndex) - 1 do
  begin
    if not Pdf.GetLoadedFontInfo(PageIndex, I, Info) then
      Continue;
    Desc := FontDescriptorOf(Pdf, Pdf.GetLoadedFontDict(PageIndex, I));
    if Info.Subtype = 'Type3' then
      Carrier := 'Type 3 procedures, drawn from the file'
    else if (Desc <> nil) and (Desc.FindValue('FontFile2') >= 0) then
      Carrier := 'FontFile2 TrueType, drawn from the file'
    else if (Desc <> nil) and (Desc.FindValue('FontFile3') >= 0) then
      Carrier := 'FontFile3 CFF/OpenType, drawn from the file'
    else if (Desc <> nil) and (Desc.FindValue('FontFile') >= 0) then
      Carrier := 'FontFile Type 1, installed face'
    else
      Carrier := 'not embedded, installed face';
    Log.Add(Format('%s  %s  %s', [string(Info.ResourceName),
      string(Info.FontName), Carrier]));
  end;
end;

The helper is there because GetLoadedFontInfo reads IsEmbedded from the font dictionary's own descriptor, and a Type0 font keeps its descriptor under /DescendantFonts, so for a Type0 font the flag describes the outer dictionary, while the program itself sits in the descendant CIDFont. The listing covers the page's own /Resources; fonts used only inside Form XObjects need the same walk over the XObject's resources

Axial and radial shading patterns are another place in the renderer where the spec's exact wording decides the pixels, and the generation side has its own font story in how EndDoc orders font subsets

Embedded TrueType, CFF and Type 3 rendering ships in the page renderer of the HotPDF Delphi Component, a native VCL library for Delphi and C++Builder with no external DLLs, so a document that carries its fonts renders with them on a build server, in a Windows container, or on a desktop that has never seen the typeface