PDFium Delphi Component Docs

Document, annotation and form semantic comparison

Available in Small Business and Enterprise since v3.265.0 through Lib\SmallBusiness\FPdfSemanticDiff.pas, PDFiumPasSB / PDFiumLazSB and FPdfSmallBusiness; public unit names and namespaces are unchanged. Remove any stale Enterprise source copy during a manual upgrade; see the edition matrix

ComparePdfSemantics compares annotation and AcroForm widget properties independently of page rendering; form values can change even when appearance pixels stay identical

Pass TPdfDiffPagePairs from page alignment or an explicit mapping; nil selects positional pairs, and explicit mappings must cover both documents exactly once, using -1 for a missing side

Annotation identity uses its /NM name, and form-widget identity uses the fully qualified field name; identity is scoped to the mapped page and item kind

Missing names and repeated names, including multiple widgets of one field on the same page, are reported as psckAmbiguous with an explicit reason; annotation array order does not determine identity

The supported profile compares strings, flags, colors, opacity, borders, markup, line, vertex and ink geometry, URI actions, field values, choice labels and selected options, and checkbox or radio state

Optional document metadata and local destinations

CompareDocumentMetadata defaults to False and compares the standard Info values Title, Author, Subject, Keywords, Creator, Producer, CreationDate and ModDate; absent and empty values compare equally and date strings are compared literally

CompareXmpMetadata defaults to False and compares the namespace-qualified properties of the parsed XMP packets as one psikXmp item per side; bag, sequence and language-alternative containers flatten into one bounded value per property, a packet present on only one side reports every property as added or removed, and padding, packet wrapper bytes and whitespace are ignored

CompareOutlines defaults to False and compares the document bookmark hierarchy as psikOutline items keyed by their slash-separated title path; captured properties include Title, Depth, IsOpen, ChildCount, Style, Color, mapped local DirectDestination. / ActionDestination. targets, ActionUri and ActionFilePath

CompareAttachments defaults to False and compares embedded files in the document attachment tree as psikAttachment items keyed by file name; captured properties include Size, lowercase hex Sha256 payload digest, Subtype, Description, AFRelationship and string /Params metadata

ComparePageAttributes defaults to False and compares page-level geometry, rotation and labels as one psikPage item (identity Page) per mapped page; captured properties include MediaBox, CropBox, BleedBox, TrimBox, ArtBox (compared under GeometryTolerance), Rotation (0, 90, 180 or 270) and PageLabel

CompareNamedDestinations defaults to False and compares document-level named destinations in /Names /Dests and legacy /Dests as psikNamedDestination items keyed by destination name, capturing mapped Destination.TargetPair, Destination.View and fit parameters under GeometryTolerance and tallying changes in NamedDestinationChangeCount

CompareStructureTree defaults to False and compares the logical structure tree (/StructTreeRoot) as psikStructure items keyed by ID:<ElementID> when an element ID is present or by tree path Root[i]/Child[j]... otherwise; captured properties include RoleName, Depth, ChildCount, ContentItemCount, Title, AlternateText, ActualText, ExpansionText, Language, ElementID, ClassName, TableScope, TableHeaders, TableRowSpan, TableColSpan, ListNumbering, LayoutPlacement and LayoutBBox, tallying changes in StructureChangeCount

CompareOptionalContent defaults to False and compares optional-content groups (/OCProperties /OCGs) as psikOptionalContent items keyed by layer Name; captured properties include Intents, ViewState, PrintState, ExportState, EffectiveVisible, Locked, RadioGroupIndex, PageElementSubtype, Language, LanguagePreferred, MinimumZoom and MaximumZoom, tallying changes in OptionalContentChangeCount

Page link annotations capture ActionFilePath, RemoteDestination.PageNumber and RemoteDestination.Suffix for GoToR actions, ActionFilePath for Launch actions and NamedAction (NextPage, PrevPage, FirstPage, LastPage) for /S /Named actions in addition to LinkUri and local destinations

CustomAnnotationKeys names up to 64 annotation dictionary keys compared per matched annotation as Custom:<key> properties: string values compare literally, numeric values compare by number, and any other value kind reports presence only; keys absent from one side report as added or removed

Metadata changes use psikDocument with identity Document, page/annotation indexes -1 and HasBounds False; they produce no overlay rectangles and add one item per side to ComparedItemCount and the shared MaxItems budget

CompareLinkDestinations defaults to False and adds direct /Dest and local GoTo destinations for link annotations; named destinations resolve through PDFium, and remote documents are never opened

DirectDestination. and ActionDestination. properties include TargetPair, View, ParameterCount, indexed Parameter[n] values and, for XYZ views, HasX, HasY and HasZoom; TargetPair is the index in the validated page-pair array, so moved pages retain their identity

View parameters use GeometryTolerance; XYZ null coordinates are distinguished from explicit zero, while non-XYZ null-versus-zero distinctions follow PDFium's exposed view values

Unresolvable local targets and inconsistent native reads reject the complete report; all new values use the existing string, item, change and comparison budgets

CompareAppearanceStreams optionally compares annotation appearance stream content; it is disabled by default

CompareAnnotations and CompareForms select the respective item kinds; GeometryTolerance defaults to 0.001 PDF user-space points

Added, removed and changed items include before/after properties and bounds; BuildSemanticDiffOverlays returns separate before/after rectangles with page and change indexes

All indexes are zero-based and bounds remain in PDF user space, in points; apply the relevant page rotation, crop and viewport transform before painting into a bitmap

Pages are loaded with independent native handles, preserving the caller's current page and form focus and avoiding form actions

The profile excludes non-widget fields, arbitrary unconfigured custom dictionaries, script actions, remote destination contents and custom Info keys; XFA form comparison is explicitly rejected

Default limits are 10,000 page pairs, 4,096 scanned items, 4,096 changes, 1 MiB per string, 16 MiB of total strings and 16,777,216 comparisons; exhausting a budget rejects incomplete output

Complete distinguishes a successful complete comparison from a rejected comparison; its changes may include explicitly ambiguous identities, so inspect AmbiguousCount before treating the results as a definitive item match

TPdfSemanticDiffReport returns the Changes array with the per-kind totals, the number of items read from both documents in ComparedItemCount, and the rejection reason in ErrorMessage when the comparison was rejected

TPdfSemanticDiffOptions holds the comparison switches, GeometryTolerance and the budget limits validated before scanning starts; its Default class function returns the preset documented above

TPdfSemanticItemKind separates psikAnnotation plain annotations from psikFormWidget AcroForm widgets; psikDocument and psikXmp hold optional document metadata snapshots, while psikOutline, psikAttachment, psikPage, psikNamedDestination, psikStructure and psikOptionalContent hold optional bookmark, embedded-file, page-attribute, named-destination, logical-structure and optional-content snapshots; identity matching never crosses item kinds

TPdfSemanticItem snapshots one compared item with its Kind, Identity, zero-based PageIndex and AnnotationIndex, HasBounds and Bounds for the annotation rectangle, and the captured Properties

TPdfSemanticProperty records one captured fact as a Name and Value pair, and TPdfSemanticProperties is the dynamic array of facts captured for an item

TPdfSemanticChangeKind classifies each outcome as psckAdded, psckRemoved, psckChanged or psckAmbiguous; changed entries with no surviving property differences are dropped

TPdfSemanticPropertyChange identifies one differing property by Name, with HasBefore and HasAfter presence flags and BeforeValue and AfterValue values; TPdfSemanticPropertyChanges is its dynamic array

TPdfSemanticChange describes one outcome with its Kind, the ItemKind and Identity of the item, the before and after item snapshots, the per-property differences in Properties, and the AmbiguityReason text carried by ambiguous identities; TPdfSemanticChanges is its dynamic array

TPdfSemanticSide selects the pssBefore or pssAfter document for an overlay rectangle

TPdfSemanticOverlay marks one rectangle with its Side, the zero-based PageIndex it came from, the ChangeIndex into Changes, the change Kind and the Bounds in PDF user space; TPdfSemanticOverlays is its dynamic array

Actual Delphi/FPC Win32/Win64 acceptance covers 92 assertions per target, including saved/reopened documents, identical-pixel value changes, Unicode identity, page movement, ambiguity and budgets

Public declarations

type
  TPdfSemanticItemKind = (psikAnnotation, psikFormWidget, psikDocument,
    psikXmp, psikOutline, psikAttachment, psikPage, psikNamedDestination,
    psikStructure, psikOptionalContent);
  TPdfSemanticChangeKind = (psckAdded, psckRemoved, psckChanged, psckAmbiguous);
  TPdfSemanticSide = (pssBefore, pssAfter);
  TPdfSemanticProperty = record
    Name: string;
    Value: WideString;
  end;
  TPdfSemanticProperties = array of TPdfSemanticProperty;
  TPdfSemanticCustomKeys = array of string;
  TPdfSemanticItem = record
    Kind: TPdfSemanticItemKind;
    Identity: WideString;
    PageIndex, AnnotationIndex: Integer;
    HasBounds: Boolean;
    Bounds: TPdfRectangle;
    Properties: TPdfSemanticProperties;
  end;
  TPdfSemanticPropertyChange = record
    Name: string;
    HasBefore, HasAfter: Boolean;
    BeforeValue, AfterValue: WideString;
  end;
  TPdfSemanticPropertyChanges = array of TPdfSemanticPropertyChange;
  TPdfSemanticChange = record
    Kind: TPdfSemanticChangeKind;
    ItemKind: TPdfSemanticItemKind;
    Identity: WideString;
    HasBefore, HasAfter: Boolean;
    BeforeItem, AfterItem: TPdfSemanticItem;
    Properties: TPdfSemanticPropertyChanges;
    AmbiguityReason: string;
  end;
  TPdfSemanticChanges = array of TPdfSemanticChange;
  TPdfSemanticOverlay = record
    Side: TPdfSemanticSide;
    PageIndex, ChangeIndex: Integer;
    Kind: TPdfSemanticChangeKind;
    Bounds: TPdfRectangle;
  end;
  TPdfSemanticOverlays = array of TPdfSemanticOverlay;
  TPdfSemanticDiffOptions = record
    CompareAnnotations, CompareForms, CompareAppearanceStreams: Boolean;
    CompareDocumentMetadata, CompareLinkDestinations: Boolean;
    CompareXmpMetadata: Boolean;
    CompareOutlines, CompareAttachments, ComparePageAttributes: Boolean;
    CompareNamedDestinations, CompareStructureTree, CompareOptionalContent: Boolean;
    CustomAnnotationKeys: TPdfSemanticCustomKeys;
    GeometryTolerance: Double;
    MaxPagePairs, MaxItems, MaxChanges, MaxStringBytes: Integer;
    MaxTotalStringBytes, MaxComparisons: Int64;
    class function Default: TPdfSemanticDiffOptions; static;
  end;
  TPdfSemanticDiffReport = record
    Complete: Boolean;
    Changes: TPdfSemanticChanges;
    AddedCount, RemovedCount, ChangedCount, AmbiguousCount: Integer;
    NamedDestinationChangeCount, StructureChangeCount, OptionalContentChangeCount: Integer;
    ComparedItemCount: Integer;
    ErrorMessage: string;
  end;

// Indices are zero based. Nil PagePairs selects positional pairing. Explicit
// pairs must cover both documents exactly once; -1 denotes an absent side
// Identity is scoped to a mapped page and item kind. Missing names and repeated
// names (including repeated widgets of one field) are reported as ambiguous
// No rendering, focus changes, form actions, or positional identity guessing
// are performed. Pages are opened independently of the caller's current page
// The supported profile covers strings, flags, colors, opacity, borders,
// markup/line/vertex/ink geometry, URI actions, field values/options/checks,
// and optionally appearance streams. Arbitrary unconfigured dictionaries,
// script actions and non-widget fields are not compared. Optional metadata
// covers standard Info tags and optional namespace-qualified XMP packet
// properties; optional local destinations use mapped page IDs
function ComparePdfSemantics(BeforePdf, AfterPdf: TPdf;
  const PagePairs: TPdfDiffPagePairs; const Options: TPdfSemanticDiffOptions;
  out Report: TPdfSemanticDiffReport): Boolean;

// Bounds remain in PDF user space, in points. Transform with the destination
// page's rotation/crop/viewport rather than treating them as bitmap pixels
function BuildSemanticDiffOverlays(const Report: TPdfSemanticDiffReport):
  TPdfSemanticOverlays;