Existing-document font subset optimization
FPdfDocumentFontSubset replaces embedded TrueType programs using the retained-ID subset backend, and returns independent PDF bytes while restoring the source stream position
Entry point
function SubsetPdfDocumentFonts(Source: TStream; const Options: TPdfDocumentFontSubsetOptions; out OutputPdf: TBytes; out Report: TPdfDocumentFontSubsetReport): Boolean;
Options
| Declaration | Purpose and default |
|---|---|
TPdfDocumentFontSubsetOptions | Record with class function Default: TPdfDocumentFontSubsetOptions |
ReadOptions: TPdfActiveObjectReadOptions | Latest active-xref reader limits, including 128 MiB source bytes and 100000 object numbers by default |
SubsetOptions: TPdfFontSubsetOptions | Per-font bytes, closure glyphs and minimum font saving; defaults to 64 MiB, 65536 glyphs and 1 percent |
MaxFonts: Integer | Distinct embedded programs, default 1024, maximum 4096 |
MaxTotalGlyphs: Integer | Combined unique mapped glyphs before dependency closure, default 1048576, maximum 4194304 |
MaxTotalDecodedBytes: Int64 | Combined decoded mapping/font stream bytes, default 128 MiB, maximum 512 MiB |
MaxOutputBytes: Int64 | Input, staged revision and final output ceiling, default 512 MiB, maximum MaxInt |
MaxWork: Int64 | Bounded graph, token, glyph-domain and decode work, default 268435456, maximum 1073741824 |
MinimumDocumentSavingPercent: Integer | Actual serialized PDF saving, default 1, valid range 0 through 100 |
RestrictToContentStreamUsage: Boolean | When True, restricts candidate character codes and CIDs to those referenced by page and Form XObject content streams (`Tf` + `Tj`/`TJ`/`'`/`"`) |
InstantiateVariableDefault: Boolean | Opt in to static default-instance optimization of supported variable TrueType FontFile2 programs, or opted-in FontFile3/OpenType glyf programs; False by default |
SubsetOpenTypeTrueType: Boolean | Since v3.254.0, independently opt in to existing FontFile3/OpenType standalone TrueType outlines consumed by TrueType or CIDFontType2 dictionaries; False by default |
VariationLibraryName: string | Optional matching HarfBuzz subset library path for that opt-in path; empty selects platform candidates without making the dependency mandatory for static fonts |
CancellationToken: IPdfCancellationToken | Optional cooperative cancellation |
Reports
| Declaration | Meaning |
|---|---|
TPdfDocumentFontSubsetReport | Outcome and resource inventory |
Succeeded, Applied, Complete, Cancelled: Boolean | Successful operation, actual optimized output, all discovered programs optimized, or observed cancellation |
FontCount, SubsetFontCount, PreservedFontCount, GlyphCount: Integer | Distinct programs, applied programs, preserved programs and total applied dependency-closure glyphs |
DefaultInstanceFontCount: Integer | Published variable programs converted to static default instances, a subset of SubsetFontCount; zero when the document is preserved or the operation fails |
OpenTypeTrueTypeFontCount: Integer | Published FontFile3/OpenType glyf programs, including independently opted-in variable defaults; zero when document saving gates preserve the original or the operation fails |
OriginalFontBytes, SubsetFontBytes: Int64 | Decoded sizes of applied programs only |
SourceByteCount, OutputByteCount: Int64 | Document sizes |
Issues: TPdfDocumentFontSubsetIssues | Bounded per-program preservation reasons |
ErrorMessage: string | Operation failure reason |
TPdfDocumentFontSubsetIssue | ObjectNumber: Integer and Reason: string |
TPdfDocumentFontSubsetIssues | Dynamic array of issue records |
Proven font-resource profile
The optimizer handles indirect FontDescriptor.FontFile2 and FontDescriptor.FontFile3 (/OpenType, /CIDFontType0C and /Type1C) streams consumed by indirect CIDFontType2 or CIDFontType0 dictionaries (whose complete glyph domain is proven either by an explicit local CIDToGIDMap stream or by a named /CIDToGIDMap /Identity mapping accompanied by an explicit /W or /W2 width array or a FontDescriptor /CIDSet stream) as well as single-byte simple /Subtype /TrueType and /Subtype /Type1 font dictionaries carrying bounded /FirstChar, /LastChar and /Widths entries
All mapped glyphs from every consumer of a shared font program are combined, including currently unused mappings, any 2-byte source codes from parent Type0 /Identity-H or /Identity-V /ToUnicode CMaps, and single-byte character codes resolved through /WinAnsiEncoding, /MacRomanEncoding, /StandardEncoding, /Differences glyph names (via the Adobe Glyph List, uniXXXX names or TrueType post format 2.0 tables) and simple /ToUnicode CMaps, then expanded through composite dependencies; this preserves the entire declared glyph domain used by page content, inherited resources, nested Forms and annotation appearances
Content streams, ToUnicode, PDF widths, CIDToGIDMap and graphics state remain unchanged, and every related FontName/BaseFont receives the same deterministic six-letter subset prefix for its program
Unproven identity mappings lacking both /W and /CIDSet, simple fonts lacking bounded /Widths or unresolvable /Differences names, non-TrueType simple fonts, direct/uncertain descriptor consumers, external mappings, unsupported codecs and unsupported font formats preserve the affected shared program with a reason
The operation reads latest active objects, including object streams, stages replacements and rebuilds one active revision so old full-font bytes do not remain as incremental history; unreachable objects may be removed by the rebuild
If font or document savings do not meet their thresholds, the corresponding program or entire original PDF is preserved byte for byte; successful no-op output still has Succeeded True and Applied False. Document savings use the floor of the actual percentage reduction, so a nonempty result cannot satisfy a 100 percent saving requirement
Opt-in OpenType TrueType programs
Set SubsetOpenTypeTrueType=True for FontFile3 streams with /Subtype /OpenType and standalone glyf outlines, as permitted for TrueType and CIDFontType2 consumers by ISO 32000-1 Table 126. The existing complete-domain inventory, retained-ID static backend, embedding policy, shared-consumer proof and savings gates all apply; output retains the FontFile3 key and OpenType subtype
Variable programs additionally require InstantiateVariableDefault=True and its optional HarfBuzz dependency. Selecting only OpenType optimization does not infer default coordinates. Conflicting outline tables, color/bitmap formats, collections, unsupported consumers and uncertain mappings retain explicit preservation reasons
The recorded Delphi/FPC Win64 profile covers static Arial/Times New Roman and Segoe UI Variable/Bahnschrift defaults, explicit CID maps, identity widths/CIDSet, WinAnsi simple fonts and shared page consumers. Independent font/PDF inspections retain mapped and .notdef outlines, advances, permissions, Unicode, widths, descriptor names and original/optimized pixels through two dirty native saves. This is finite optimization evidence and does not certify arbitrary font programs or standards conformance
Explicit collection faces and variable coordinates
Since v3.264.0, FontSelections: TPdfDocumentFontSelections selects standalone TrueType or TrueType collection faces for proven CIDFontType2 consumers, including shared fonts and opt-in OpenType streams; simple-font consumers remain outside this explicit-selection profile
Each TPdfDocumentFontSelection identifies the embedded font stream through ObjectNumber, Generation and a required hexadecimal SourceFontSha256 of its decoded bytes, with a zero-based FaceIndex: Word, optional FontProgram: TBytes replacement source and Variations: TPdfDocumentFontVariations; an empty source uses the existing embedded program
Each TPdfDocumentFontVariation contains Tag: AnsiString and Value: Single; supplied coordinates must be unique, known, finite and within the declared range, and omitted axes use their declared defaults before every axis is frozen to a static program
The original and selected programs must satisfy embedding/subsetting policy and the complete retained-GID domain; PDF widths, CIDToGIDMap, ToUnicode and content streams remain unchanged, so the selected face or coordinates must already match that document interpretation
Selection requires the optional HarfBuzz subset library through VariationLibraryName and the native PDFium runtime for publication checks, independent of InstantiateVariableDefault; unsupported faces, CFF/CFF2, color/bitmap programs, uncertain consumers or denied policy produce rejection/preservation diagnostics rather than a successful selected result
Before publishing an applied selection, every page must retain native extracted text, geometry and exact BGRA pixels including widget appearances at SelectionVerificationDpi (default 144, permitted 72 through 300); MaxSelectionVerificationPixels defaults to 67108864 and charges both source and result renders, with a hard limit of 134217728 pixels
Wrong digests, targets, coordinates, changed appearance, exhausted budgets and cancellation return empty output on failure; savings gates may preserve the original PDF unchanged, and SelectedFaceFontCount, ExplicitInstanceFontCount and SelectionVerificationPixelCount report the actual result
The recorded Delphi/FPC Win64 profile covers nonzero embedded/external collection faces, full and partial non-default coordinates, shared consumers, 17 negative/preservation cases and retained static/default-instance controls; independent inspections compare outlines, advances, permissions and unchanged PDF mappings through two dirty saves, without qualifying arbitrary fonts or all rendering resolutions
The public option/report records changed; rebuild dependent Pascal units and regenerate C++Builder headers and libraries together
Opt-in variable default instances
Since v3.216.0, InstantiateVariableDefault handles standalone variable TrueType FontFile2 programs with glyf, fvar and gvar tables when the existing inventory proves their complete mapped GID domain. The caller explicitly selects the default axis interpretation; named instances, non-default coordinates, collections, CFF2 and color/bitmap programs are not inferred
The optional native backend first checks the original font's embedding/subsetting policy and constructs a retained-ID variable subset with dependency closure, then pins every remaining axis to its declared default. The result keeps the same requested GIDs, the .notdef outline and the existing PDF CIDToGIDMap, widths, ToUnicode and content streams
The font and document saving gates apply to the final static output against the original variable input. Missing native libraries/exports, unsupported data or denied font permissions preserve that program with an issue; the option does not enable network access, change installed fonts or make an unavailable backend a successful optimization
Focused Delphi Win64 execution covers embedded Segoe UI Variable and Bahnschrift defaults, including an explicit GID-zero missing-glyph case, exact source/optimized pixels, Unicode and two dirty full saves. Independent font checks compare retained outlines and advances with default coordinates, including .notdef, and verify unchanged PDF mappings and descriptor names
The optional native dependency follows the Windows and FPC Unix compiler paths; unsupported compiler configurations report this backend unavailable when the surrounding document pipeline is available. The existing Delphi OSXARM64 document pipeline still fails compilation in its unchanged Winapi.Windows dependency and is not qualified by this release. Other unexecuted compiler/platform pairs, arbitrary source font interpretation, named/non-default instances and general conformance remain unqualified. Cancellation is checked around native calls, which are not individually interruptible or given a native allocation ceiling
Encryption, potential signatures/signature fields, malformed graphs, exhausted budgets and cancellation return False with empty OutputPdf; the input stream is never modified
Complete describes discovered embedded-program optimization, not PDF conformance or future editing coverage; adding new characters outside the retained mapped repertoire requires re-embedding a suitable font