PDFiumPas Docs

Reviewed repair of font and text resources

RepairPdfDocumentText applies explicit font, ToUnicode and ActualText recipes to a SHA-256-bound source snapshot, handing back independent PDF bytes

The operation keeps original object identities, clones shared font descriptors and descendants for the selected Type0 resource, and never publishes a partial result when things fail

Declarations

type
TPdfTextFontRepair= record
    FontObjectNumber, Generation: Integer;
    FontProgram: TBytes;
    CIDToGIDMap: TBytes;
    ReplaceExisting: Boolean;
  end;
  TPdfTextFontRepairs= array of TPdfTextFontRepair;
  TPdfToUnicodeEntry= record
    CharacterCode: Cardinal;
    UnicodeText: string;
  end;
  TPdfToUnicodeEntries= array of TPdfToUnicodeEntry;
  TPdfToUnicodeRepair= record
    FontObjectNumber, Generation, CodeBytes: Integer;
    Entries: TPdfToUnicodeEntries;
    ReplaceExisting: Boolean;
  end;
  TPdfToUnicodeRepairs= array of TPdfToUnicodeRepair;
  TPdfActualTextRepair= record
    ContentObjectNumber, Generation, Mcid: Integer;
    Value: string;
    ReplaceExisting: Boolean;
  end;
  TPdfActualTextRepairs= array of TPdfActualTextRepair;
  TPdfDocumentTextRepairPlan= record
    SourceSha256: string;
    Fonts: TPdfTextFontRepairs;
    ToUnicode: TPdfToUnicodeRepairs;
    ActualText: TPdfActualTextRepairs;
  end;
  TPdfDocumentTextRepairOptions= record
    ReadOptions: TPdfActiveObjectReadOptions;
    MaxRepairs, MaxFontBytes, MaxDecodedStreamBytes, MaxMappings, MaxTextCharacters: Integer;
    MaxDecodedBytes, MaxOutputBytes, MaxWork, MaxVerificationPixels: Int64;
    VerifyUnchangedPixels: Boolean;
    CancellationToken: IPdfCancellationToken;
    class function Default: TPdfDocumentTextRepairOptions; static;
  end;
  TPdfDocumentTextRepairReport= record
    Succeeded, Cancelled: Boolean;
    EmbeddedFonts, ToUnicodeMaps, ActualTextValues: Integer;
    SourceSha256, OutputSha256, ErrorMessage: string;
  end;

function RepairPdfDocumentText(const Source: TBytes;
  const Plan: TPdfDocumentTextRepairPlan; const Options: TPdfDocumentTextRepairOptions;
  out OutputPdf: TBytes; out Report: TPdfDocumentTextRepairReport): Boolean;

Source binding and resource identities

Plan.SourceSha256 is the hexadecimal SHA-256 digest of the exact input Source bytes; each recipe names an active object number and generation taken from that snapshot

Compressed object streams and incremental revisions are resolved before editing; when a native save or object-stream packer has renumbered a document, acquire fresh identities

Fonts and ToUnicode targets have to be unique within their respective arrays; several distinct MCIDs in one content stream are fine, but duplicate content-object/MCID targets are refused

Signed PDFs, signature fields, encryption and XFA call for a separately prepared source and are refused; an empty recipe hands back the exact source once the same source policy checks have run

Font embedding

TPdfTextFontRepair selects either a Type0 Identity-H or Identity-V font with exactly one indirect descendant and an indirect FontDescriptor (a TrueType program needs a CIDFontType2 descendant, whilst a bare CFF or OpenType CFF wrapper program needs a CIDFontType0 descendant), or a single-byte simple /Subtype /TrueType or /Subtype /Type1 font with bounded /FirstChar, /LastChar, /Widths and an indirect FontDescriptor

FontProgram supplies a complete standalone static font: TrueType glyf/loca programs have table ranges, outline/composite structure, metrics, glyph count, embedding policy and an ASCII PostScript name validated through the portable TrueType backend before native font loading, bare CFF programs recover their PostScript name and glyph count from the CFF Name and CharStrings indexes, and OpenType CFF wrappers reuse the sfnt directory parser

CFF programs validate through native font loading and embed as /FontFile3 with /Subtype /CIDFontType0C (bare CFF) or /Subtype /OpenType (wrapper); collections, variable, bitmap and colour fonts require another profile

CIDToGIDMap optionally supplies a complete big-endian 16-bit CID-to-glyph map for a CIDFontType2 TrueType replacement; when empty, an existing local map stream is decoded and validated, and a source /CIDToGIDMap /Identity name value infers the explicit identity stream over the replacement font's glyph count, which also satisfies the explicit-map requirement that rejects name values; CFF descendants and simple /Subtype /TrueType fonts never carry a CIDToGIDMap, any supplied map is rejected and stale CFF entries are removed

Every map glyph must fall within the supplied font's glyph count; the map holds at most 65,536 entries and PDF widths stay unchanged

The selected Type0 or simple TrueType resource points to new descriptor (and, for Type0, descendant) objects carrying the full font's PostScript name; other resources keep their original descendants, descriptors and embedded programs. Native validation loads each replacement program through FPDFText_LoadFont as TrueType or Type1 according to the detected program kind

ReplaceExisting defaults to False and is needed to replace an existing FontFile, FontFile2 or FontFile3 declaration

ToUnicode maps

TPdfToUnicodeRepair writes explicit CharacterCode-to-UnicodeText mappings as a bounded CMap with bfchar groups of no more than 100 entries

Entries have to be strictly increasing and unique; nonempty UnicodeText values hold at most 256 UTF-16 code units with valid surrogate pairs

CodeBytes is 2 for Type0 Identity-H/V fonts and 1 for simple Type1 or TrueType fonts; other encodings need a different repair profile

Replacing a declared ToUnicode stream calls for ReplaceExisting True; missing or incomplete mappings are never guessed from appearance or glyph names

ActualText

TPdfActualTextRepair targets exactly one BDC property dictionary (inline, or referenced by name in the owning page's or Form XObject's /Resources /Properties dictionary) with the requested nonnegative Mcid in ContentObjectNumber and Generation

Value is written as a UTF-16BE string with a byte-order marker, preserving the MCID, surrounding marked content, painting operators, other dictionary keys and any existing /FlateDecode stream compression (matched named property operands are expanded into inline dictionaries so other references to the shared property name remain unaffected)

Existing ActualText demands ReplaceExisting True; an explicitly empty Value suppresses replacement text for that marked span

The edited stream must show balanced BMC/BDC/EMC nesting, at most 256 operands per operator and depth 256; ambiguous MCIDs, unresolved named property lists and inline images are rejected

Only the selected local stream changes, even when it is a Form content stream; every instance sharing that stream sees the same semantic change

Verification and limits

Source bytes stay untouched; the output is independently reopened and checked for retained page count and source policy before publication

VerifyUnchangedPixels defaults to True and compares every page at one pixel per PDF point using bounded native 32-bit scan lines; a changed glyph map or font appearance fails and yields no output

Where an absent font's substitution differs from the reviewed replacement, switch VerifyUnchangedPixels off explicitly and compare the result against an application-approved rendering; the API will not guess the intended font

Defaults stand at 128 MiB source, 4,096 recipes, 64 MiB per font and decoded stream, 1,048,576 mapping entries and text code units, 128 MiB aggregate decoded/generated data, 512 MiB staged/output bytes, 268,435,456 work units and 33,554,432 verification pixels

Hard maxima come to 100,000 recipes, 64 MiB per font, 256 MiB per decoded stream, 4,194,304 mappings, 16,777,216 text code units, 512 MiB aggregate decoded data, MaxInt output bytes, 1,073,741,824 work units and 268,435,456 verification pixels

ReadOptions bounds active-object parsing; the source size must also fit within MaxOutputBytes, and repeated decodes, generated CMaps, rewritten content and supplied font/map bytes draw down cumulative budgets

CancellationToken is polled between bounded stages, mappings and pixel scan lines; individual native font/load/render calls and bounded TrueType backend validation stay synchronous

Report brings back Succeeded, Cancelled, applied font/map/ActualText counts, source/output digests and ErrorMessage; failures clear the publication counts and output digest

Transactional standards repair

TPdfDocumentTextRepairProvider takes a deep copy of the reviewed recipe and runs it through the exact-byte/native PDF/A postvalidation and rollback workflow

Native reopening and pixel equality confirm persistence and appearance; they establish neither semantic correctness nor external PDF/A or PDF/UA certification

See also

Document repair, Structure editing, Font subsetting