Existing-document font subset optimisation
FPdfDocumentFontSubset swaps embedded TrueType programs by way of the retained-ID subset backend, handing back independent PDF bytes and 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 | Up-to-date active-xref reader limits, 128 MiB of source bytes and 100000 object numbers by default included |
SubsetOptions: TPdfFontSubsetOptions | Per-font bytes, closure glyphs and minimum font saving; 64 MiB, 65536 glyphs and 1 percent by default |
MaxFonts: Integer | Distinct embedded programs, 1024 by default, 4096 at most |
MaxTotalGlyphs: Integer | Combined unique mapped glyphs ahead of dependency closure, 1048576 by default, 4194304 at most |
MaxTotalDecodedBytes: Int64 | Combined decoded mapping/font stream bytes, 128 MiB by default, 512 MiB at most |
MaxOutputBytes: Int64 | Ceiling on input, staged revision and final output, 512 MiB by default, MaxInt at most |
MaxWork: Int64 | Bounded graph, token, glyph-domain and decode work, 268435456 by default, 1073741824 at most |
MinimumDocumentSavingPercent: Integer | Actual serialised PDF saving, 1 by default, valid from 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 optimisation 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 | Cooperative cancellation, optional |
Reports
| Declaration | Meaning |
|---|---|
TPdfDocumentFontSubsetReport | The outcome together with a resource inventory |
Succeeded, Applied, Complete, Cancelled: Boolean | A successful operation, actually optimised output, every discovered program optimised, or observed cancellation |
FontCount, SubsetFontCount, PreservedFontCount, GlyphCount: Integer | Distinct programs, applied programs, preserved programs and the 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 for applied programs alone |
SourceByteCount, OutputByteCount: Int64 | Sizes of the documents |
Issues: TPdfDocumentFontSubsetIssues | Bounded reasons for per-program preservation |
ErrorMessage: string | Why the operation failed |
TPdfDocumentFontSubsetIssue | ObjectNumber: Integer and Reason: string |
TPdfDocumentFontSubsetIssues | Dynamic array of the issue records |
Proven font-resource profile
The optimiser 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, currently unused mappings included, together with 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 stay untouched, and every related FontName/BaseFont gets the same deterministic six-letter subset prefix for its program
Unproven identity mappings lacking both /W and /CIDSet, simple fonts lacking bounded /Widths or with unresolvable /Differences names, non-TrueType simple fonts, direct/uncertain descriptor consumers, external mappings, unsupported codecs and unsupported font formats leave the affected shared program in place, with a reason recorded
The operation reads the latest active objects, object streams included, stages replacements and rebuilds a single active revision so that old full-font bytes do not linger as incremental history; the rebuild may remove unreachable objects
Where font or document savings fall short of their thresholds, the program concerned or the entire original PDF is preserved byte for byte; a successful no-op still reports Succeeded True with Applied False. Document savings take 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 optimisation does not infer default coordinates. Conflicting outline tables, colour/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/optimised pixels through two dirty native saves. This is finite optimisation 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, independently of InstantiateVariableDefault; unsupported faces, CFF/CFF2, colour/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 non-zero 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 colour/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 optimisation
Focused Delphi Win64 execution covers embedded Segoe UI Variable and Bahnschrift defaults, including an explicit GID-zero missing-glyph case, exact source/optimised 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 or signature fields, malformed graphs, exhausted budgets and cancellation all return False with an empty OutputPdf; the input stream is never touched
Complete describes the discovered embedded-program optimisation, not PDF conformance or future editing coverage; adding new characters beyond the retained mapped repertoire calls for a suitable font to be embedded afresh