A PDF can display the word "office" perfectly and still paste it as "oce". The shaping engine replaced f, f and i with one ligature glyph, the font's own cmap has no entry that leads from that glyph back to three letters, and so a text extractor has nothing to return for it. ISO 32000-1 §9.10.3 gives the writer a way out, a ToUnicode CMap that says what each character code means, but the CMap is keyed by code, and the whole problem comes down to how those codes are assigned
Glyph-level writing is the only reliable route for text that has already been shaped. Arabic joining forms, Devanagari conjuncts and plain Latin ligatures all turn a string into a sequence of glyph identifiers that no longer lines up one-to-one with characters. An API that takes a string and a font name has no place to put that result, so the glyph run itself has to be handed to the writer, together with the text each glyph stands for
What AddCidType2Text takes and what it writes
PDFium Component exposes this as TPdf.AddCidType2Text: you pass the raw TrueType bytes, an array of TPdfCidGlyph records, a font size and an origin, and the method embeds the font as a CID Type 2 font (ISO 32000-1 §9.7.4) on the active page. Each record carries a GlyphID from the font, the UnicodeText that glyph represents, an Advance, and optional OffsetX and OffsetY values from the shaper. Advances and offsets live in the same coordinate space as the X and Y origin, so a shaper that reports positions in font units needs them scaled to the font size before they go in
The font data has to be a TrueType-outline sfnt: a standalone .ttf, or a TrueType Collection with TTCIndex picking the face. For a standalone font TTCIndex stays at zero. OpenType files built on CFF outlines (the ones that start with OTTO) belong to a different font type in PDF and are rejected by the up-front validation with "CID font data must contain a valid TrueType sfnt", before anything touches the page
uses
System.SysUtils, System.IOUtils, PDFium;
var
Pdf: TPdf;
Glyphs: TPdfCidGlyphs;
Options: TPdfCidFontOptions;
Report: TPdfCidFontReport;
begin
Pdf := TPdf.Create(nil);
try
Pdf.FileName := 'label.pdf';
Pdf.LoadDocument;
Pdf.PageNumber := 1;
// Shaper output for "office": o, the ffi ligature, c, e.
// Glyph ids are placeholders: take them from your shaper for this exact font file.
// Advances are in page units at the 11 pt size passed below
SetLength(Glyphs, 4);
Glyphs[0].GlyphID := 82; Glyphs[0].UnicodeText := 'o'; Glyphs[0].Advance := 6.1;
Glyphs[1].GlyphID := 402; Glyphs[1].UnicodeText := 'ffi'; Glyphs[1].Advance := 9.0;
Glyphs[2].GlyphID := 71; Glyphs[2].UnicodeText := 'c'; Glyphs[2].Advance := 5.3;
Glyphs[3].GlyphID := 74; Glyphs[3].UnicodeText := 'e'; Glyphs[3].Advance := 5.9;
Options := TPdfCidFontOptions.Default; // subset preferred, extraction verified
Pdf.AddCidType2Text(TFile.ReadAllBytes('NotoSans-Regular.ttf'), Glyphs,
11, 72, 700, Options, Report);
Writeln(Format('%d glyph instances, %d distinct glyphs, subset applied: %s',
[Report.GlyphCount, Report.UniqueGlyphCount,
BoolToStr(Report.SubsetApplied, True)]));
Writeln('Extracted back: ' + Report.ExtractedText);
Pdf.SaveAs('label-out.pdf');
finally
Pdf.Free;
end;
end.
The method returns True on success and raises EPdfError when validation, font loading, insertion or verification fails. The example lets the exception escape; the second listing further down catches it and reads the report
Why does every glyph instance get its own CID?
Because ToUnicode is keyed by CID, and one glyph can mean different text in different places. The tempting optimization is to deduplicate: one CID per distinct glyph identifier, reused wherever that glyph appears. The font dictionary gets shorter and the mapping table gets shorter. Then a ligature glyph that stands for "ffi" in one word turns up in another run where the shaper used it for something else, and the shared CID can carry only one of those meanings. Whichever text loses that contest becomes unextractable
AddCidType2Text therefore numbers glyph instances, one after another. The first glyph in the array becomes CID 1, the second CID 2, and so on; CID 0 is left for the font's .notdef glyph. That is also where the MaxGlyphs ceiling of 65,534 comes from, since every CID has to fit in a two-byte code. If the same glyph identifier appears five times in a run, five CIDs point at it, and Report.UniqueGlyphCount tells you how many distinct glyphs were behind Report.GlyphCount instances
The explicit CIDToGIDMap stream follows the layout in ISO 32000-1 §9.7.4.2: two bytes per CID, high byte first, with the glyph index for CID n at byte offset 2n. For the "office" run above that is four entries after the empty slot for CID 0. The generated ToUnicode CMap pairs each CID with its UnicodeText, written as UTF-16BE so a ligature can map to several code units and a supplementary-plane character to a surrogate pair. Entries go out in beginbfchar blocks of at most 100 lines, the block limit of the CMap syntax
A glyph with no text of its own, such as a decorative swash or a positioning-only glyph, is given an empty UnicodeText, and the method maps it to U+200B, a zero-width space. Every CID therefore produces something observable on extraction, and a missing mapping shows up as a gap you can actually see. The cost of the per-instance scheme is two bytes in the map and one CMap line per glyph instance. That is a fair price for text that copies and searches correctly
Subsetting through a glyph list, and three checks on the result
Subsetting is cheap to ask for here because the caller has already named every glyph in use. On Windows the method passes that list straight to the system font subsetting library (CreateFontPackage in fontsub.dll) in glyph-list mode, always adding glyph 0 so the subset keeps a .notdef. Under Free Pascal on Linux and macOS, the optional HarfBuzz subset library does the job with glyph identifiers retained. Retained identifiers matter: the CIDToGIDMap is built from the original glyph ids, so a subsetter that renumbered glyphs would quietly point every CID at the wrong outline
A subsetting call that reports success is still checked before its output is used. On Windows three conditions must hold. The result has to be smaller than the input; otherwise the subset is dropped and SubsetErrorCode is set to 1007. It must reparse as an sfnt with a readable maxp table. And its glyph count must still extend past the highest glyph id the run requested, otherwise the code becomes ERROR_INVALID_DATA (13). A missing fontsub.dll or a missing CreateFontPackage export shows up as the matching Windows error code
What happens after a rejected subset is the caller's decision, fixed up front in Options.EmbeddingMode:
pcfemSubsetPreferred, the default, falls back to embedding the complete font and setsUsedFullFontFallback; the page is correct and the file is largerpcfemSubsetRequiredraises before the font is loaded into the document, so the page is untouchedpcfemFullskips subsetting entirely and leavesSubsetAttemptedatFalse
For a batch job with a hard size budget, pcfemSubsetRequired is the honest setting, because a silent fallback to a multi-megabyte CJK font is exactly what such a budget exists to catch. Interactive tools are better served by the default. A third route moves subsetting to save time: embed with pcfemFull and save with Pdf.SaveAs(FileName, saSubsetNewFonts), which subsets fonts newly embedded in the session through PDFium's own subsetter at save time. Compare Report.OriginalFontBytes and Report.EmbeddedFontBytes on your own fonts to see which path pays off
What does VerifyExtraction actually compare?
It compares the text of the objects this call inserted, read back in insertion order, against the concatenated UnicodeText of the glyph array. TPdfCidFontOptions.Default turns VerifyExtraction on, and it is worth leaving on. The naive check would extract the whole page and search for the expected string. That passes whenever the page already contained the same words, for instance a heading repeated in a footer, even if the new run was mapped wrongly
After inserting the objects, the method regenerates the page content, reloads the text page and reads each inserted object individually. The result lands in Report.ExtractedText, the expectation in Report.ExpectedText, and Report.ExtractionMatches records the outcome. On a mismatch the method removes what it inserted and raises "CID text extraction does not match the Unicode mapping". Because Report is an out parameter written as the call proceeds, both strings are still there in your exception handler:
procedure WriteRun(Pdf: TPdf; const FontBytes: TBytes;
const Glyphs: TPdfCidGlyphs; X, Y: Double);
var
Options: TPdfCidFontOptions;
Report: TPdfCidFontReport;
begin
Options := TPdfCidFontOptions.Default;
Options.EmbeddingMode := pcfemSubsetRequired; // size budget: no full-font fallback
try
Pdf.AddCidType2Text(FontBytes, Glyphs, 11, X, Y, Options, Report);
except
on E: EPdfError do
begin
// LogLine is your own logging routine, not part of the library
if Report.SubsetAttempted and not Report.SubsetApplied then
LogLine(Format('Subset rejected, code %d: %s',
[Report.SubsetErrorCode, E.Message]))
else if Report.ExtractedText <> Report.ExpectedText then
LogLine('Expected [' + Report.ExpectedText +
'] but read back [' + Report.ExtractedText + ']')
else
LogLine(E.Message);
raise; // the page holds nothing from this call
end;
end;
end;
A mismatch nearly always traces back to the input. The usual suspects are a shaper cluster table that assigned text to the wrong glyph, a glyph array built in visual order when the text was expected in logical order, or an empty UnicodeText where the caller meant to supply one; the last case reads back as U+200B, which is easy to spot in a hex dump of ExtractedText. The price of the check is one text page rebuild per call. Turning it off for a tight loop is defensible only after a representative set of runs from the same shaper and font has passed with it on
Limits, geometry and rollback
Every size that comes from the caller is capped before allocation. MaxFontBytes defaults to 64 MiB, MaxGlyphs to 65,534 instances, and MaxUnicodeCharacters to 1,048,576 UTF-16 code units across the whole run. The font size must be finite and positive, each glyph id must be below the glyph count in the font's maxp table, and every advance and offset must be a finite number. That last rule sounds pedantic until a shaping engine fed a malformed font hands back a NaN advance, which would otherwise end up in the content stream
Geometry decides how many page objects a run becomes. When every glyph shares the same OffsetY, the run is written as a single text object with per-glyph positions, which keeps the content stream compact and gives extractors one object to read. As soon as one glyph sits on a different baseline, as Arabic and Devanagari marks often do, each glyph is written as its own text object at its own position, still in the order of the array
Failure is atomic at the page level. Validation and subsetting run before anything is inserted. If loading the font, setting character codes, inserting an object, regenerating content or verifying extraction fails later, every object the call added is removed in reverse order and the page content is regenerated. A failed call leaves the page as it found it, without half a text run on it
Where AddCidType2Text fits next to AddText and AddShapedText
Three entry points cover different starting positions. AddText takes a string and a font name and suits ordinary text that needs no contextual shaping. AddShapedText takes a string, runs it through the active shaping backend described in pluggable text shaping with Uniscribe and HarfBuzz, and records the logical text as ActualText. AddCidType2Text is the one to call when you already hold shaped output from your own engine, need exact control over glyph identifiers, or must embed a font from bytes you hold rather than one resolved by name through the provider mechanism in controlling PDF font substitution. Character-level issues such as surrogate pairs and CJK width are covered in emoji, CJK and surrogate pair handling
Variable fonts need one extra step. AddCidType2Text embeds the font program as given and does not select axis coordinates, so for a non-default instance run InstantiatePdfVariableFont first and feed the resulting static TrueType bytes, together with that instance's glyph ids and advances, into the call. Each call also numbers its CIDs from 1 with its own maps. When several runs in the same font share a page, reopen the saved file and extract each run before relying on it: PDFium's content generator caches font resources by font type and BaseFont, so a later run can end up bound to an earlier run's font dictionary even though the maps behind each run differ
Embedding is a licensing question as much as a technical one. The fsType field in a font's OS/2 table states whether embedding is allowed at all, allowed for preview and print only, or allowed for editing, and AddCidType2Text embeds whatever bytes it receives. Checking that field, and the license behind it, belongs in your font intake step
The glyph-level writer shares one page model with font provisioning and text extraction across Delphi, C++Builder and Lazarus, and the PDFium Component for Delphi product page lists the editions and the rest of the text API