PDFium Delphi Component Docs

CBDT bitmap font writing

Since v3.211.0, FPdfBitmapFont writes selected CBDT/CBLC PNG glyphs into a one-page PDF 1.7 document using a colorized Type3 font, image XObjects, optional soft masks and a UTF-16BE ToUnicode CMap

Public API

uses SysUtils, FPdfProduction;

type
  TPdfBitmapFontOptions = record
    LibraryName: string;
    FaceIndex: Word;
    MaxFontBytes, MaxGlyphs, MaxDecodedBytes, MaxOutputBytes: Integer;
    PageWidth, PageHeight, FontSize, OriginX, OriginY: Double;
    class function Default: TPdfBitmapFontOptions; static;
  end;

  TPdfBitmapFontReport = record
    Applied: Boolean;
    GlyphCount, UniqueGlyphCount, OriginalFontBytes, SubsetFontBytes: Integer;
    PngBytes: Integer;
    FontCount: Integer;
    WidthPoints: Double;
    ExpectedText: UnicodeString;
    ErrorMessage: string;
  end;

function CreateHarfBuzzBitmapFontPdf(const FontProgram: TBytes;
  const Glyphs: TPdfGlyphInfos; const Options: TPdfBitmapFontOptions;
  out PdfBytes: TBytes; out Report: TPdfBitmapFontReport): Boolean;
function CreateHarfBuzzBitmapTextPdf(const FontProgram: TBytes;
  const Text: UnicodeString; const Options: TPdfBitmapFontOptions;
  out PdfBytes: TBytes; out Report: TPdfBitmapFontReport): Boolean;

Mapping and layout

Glyphs is an ordered run of original GIDs and nonzero Unicode scalar values in UnicodeValue; its Width metadata is ignored because HarfBuzz supplies the selected font's advances and bitmap extents

The glyph-oriented caller resolves characters, substitutions and reading order before this call; the helper does not shape text, resolve font families, wrap lines, create vertical text or add structure tags

Since v3.215.0, records are split into Type3 fonts containing at most 255 codes each, with a separate ToUnicode map and Widths array for every group. Text position continues across font switches; repeated GIDs share one CharProc and image across all groups even when caller-provided Unicode values differ

Supplementary-plane scalars use UTF-16 surrogate pairs in the CMap; no ActualText substitution hides the glyph mappings

FontSize, PageWidth, PageHeight, OriginX and OriginY are PDF points, with a bottom-left page origin and a baseline at the supplied origin; the page clips content outside its bounds

The helper uses HarfBuzz's largest available PNG strike with no explicit PPEM selection, scales its metrics through the font units per em and publishes positive-width, downward-height bitmap extents with horizontal nonnegative advances

Dependencies, policies and budgets

LibraryName and zero-based FaceIndex use the optional TPdfHarfBuzzSubsetBackend rules; the writer first obtains a retained-ID subset and enforces that backend's font embedding/subsetting policy

Default input, aggregate PNG bytes, aggregate four-byte expanded glyph pixels and published PDF limits are each 64 MiB; MaxFontBytes, MaxDecodedBytes and MaxOutputBytes can reduce those limits, while the subset backend retains its own 64 MiB input/output ceiling

MaxGlyphs retains its default of 255 and may be set from 1 to 65536; raise it explicitly for longer runs. FontCount reports the number of Type3 groups, each still limited to codes 1 through 255

Page dimensions and font size must be at least 0.000001 points; all supplied geometry must be finite and within 10000000 units, glyph extents within 1000000 units and advances from zero to 1000000 font units

PNG decoding is limited to noninterlaced supported grayscale, RGB, indexed, gray-alpha and RGBA payloads with 1-, 2-, 4- or 8-bit source samples as allowed by each PNG color type; images are written as 8-bit RGB or gray with an optional 8-bit soft mask

These are accepted-data and publication limits, not native allocation ceilings, a total process memory ceiling or timeouts; native parsing, compression and ordinary allocation exceptions can propagate

Results and failure

Applied means the helper published its PDF bytes, not that a native document has already loaded them; ExpectedText is the concatenation of the requested scalar mappings, and WidthPoints is the font-metric advance of the run

GlyphCount counts requested records and UniqueGlyphCount counts unique GIDs including a nonpainting space glyph; OriginalFontBytes and SubsetFontBytes describe the intermediate font programs, while PngBytes counts unique extracted PNG payload bytes

The intermediate SFNT is not embedded in the PDF; only selected glyph images and font metadata are written, so the PDF size is distinct from SubsetFontBytes

Expected failures return false, empty PdfBytes, Applied = False and an English ErrorMessage; other report fields can describe partial work and must not be treated as published results

Text-oriented scalar mapping

CreateHarfBuzzBitmapTextPdf accepts Unicode text and the same options/report records, selects the requested face and resolves each Unicode scalar through the font's nominal cmap before calling the glyph writer. Supplementary pairs are decoded strictly, and malformed UTF-16, zero scalars, missing nominal glyphs and glyph-budget overflow reject without PDF bytes

The font's actual nominal space glyph may use a nonpainting CharProc with its original advance; other glyphs still require supported CBDT PNG payloads. A caller-provided semantic space mapping never hides a different visible GID

This is independent-scalar mapping, with no GSUB shaping or font fallback. ZWJ, variation selectors, regional indicators, skin-tone modifiers, keycap marks and emoji tags are explicitly rejected rather than emitted as an unshaped emoji sequence

Native extraction may normalize leading/trailing spaces; the focused profile verifies internal spaces and supplementary emoji across 255/256 and 510/511 record boundaries, with up to 1024 requested records. The 65536 hard admission limit is reviewed in code rather than qualified by a maximum-size native run

Options := TPdfBitmapFontOptions.Default;
Options.MaxGlyphs := 4096;
Options.LibraryName := SubsetLibraryPath;
if not CreateHarfBuzzBitmapTextPdf(FontProgram, Text, Options,
  PacketBytes, Report) then
  raise Exception.Create(Report.ErrorMessage);

Native writing integration

Load the returned bytes into a temporary TPdf, create a Form XObject from its page and insert that Form into the target page using the existing CreateXObjectFromPage and InsertFormObjectFromXObject methods

Options := TPdfBitmapFontOptions.Default;
Options.LibraryName := SubsetLibraryPath;
if not CreateHarfBuzzBitmapFontPdf(FontProgram, Glyphs, Options,
  PacketBytes, Report) then
  raise Exception.Create(Report.ErrorMessage);
PacketStream.WriteBuffer(PacketBytes[0], Length(PacketBytes));
PacketStream.Position := 0;
SourcePdf.LoadCustomDocument(PacketStream, False);
XObject := TargetPdf.CreateXObjectFromPage(SourcePdf, 0);
try
  if XObject = nil then
    raise Exception.Create('Cannot import bitmap font page');
  if TargetPdf.InsertFormObjectFromXObject(XObject) = nil then
    raise Exception.Create('Cannot insert bitmap font page');
finally
  XObject.Free;
end;

The target document must already have an active page; the caller owns the temporary document/stream and must free the XObject before closing the target document

Focused Delphi Win64 evidence covers a pinned CBDT sample, a selected TTC face, alpha and opaque image variants, Unicode extraction, exact image samples, native Form import and two dirty full-save/reopen generations with unchanged glyph pixels

The generated font uses d0 colorized CharProcs; this does not add direct CBDT support to FPDFText_LoadFont, FPDFText_LoadCidType2Font or TPdf.AddText, and native editing of Type3 text objects remains outside this profile

Other bitmap/color formats including sbix, arbitrary color management, PDF/A or PDF/X conformance, shaped emoji sequences, SVG/COLR conversion and unexecuted compiler/platform pairs remain unqualified

See the HarfBuzz color API and PDF Association color-font discussion for the PNG extraction and Type3 representation background

The physical Ubuntu x64 FPC 3.3.1/Qt6 profile at v3.217.0 executes scalar text, multiple Type3 fonts, optional-library rejection and two dirty native saves with independent PDF/image/metric checks; its recorded ELF PDFium/HarfBuzz libraries are separate from the Win64 runtime