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 checks annotation and AcroForm widget properties separately from rendering; a form value can differ whilst its appearance pixels remain identical

Supply the alignment's TPdfDiffPagePairs or your own mapping; nil pairs positions, whereas an explicit mapping must cover each document exactly once, with -1 for an absent side

An annotation is identified by its /NM name and a form widget by its fully qualified field name; these identities apply within the mapped page and item kind

Absent or repeated names produce psckAmbiguous with a reason, including multiple widgets for a field on one page; annotation-array position is not an identity

The supported profile checks strings, flags, colours, opacity, borders, markup, line/vertex/ink geometry, URI actions, field values, choice labels and selections, and checkbox or radio states

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 a single psikXmp item per side; bag, sequence and language-alternative containers are flattened into one bounded value per property, a packet present on only one side reports each of its properties as added or removed, and padding, packet wrapper bytes and whitespace are disregarded

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, with changes tallied in NamedDestinationChangeCount

CompareStructureTree defaults to False and compares the logical structure tree (/StructTreeRoot) as psikStructure items keyed by ID:<ElementID> where an element ID exists 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, with changes tallied 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, with changes tallied 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 alongside LinkUri and local destinations

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

Metadata changes use psikDocument with identity Document, page and annotation indexes of -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, whilst non-XYZ null-versus-zero distinctions follow the view values PDFium exposes

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

Enable CompareAppearanceStreams to compare annotation appearance content as well; the option is off by default

Choose item kinds with CompareAnnotations and CompareForms; the default GeometryTolerance is 0.001 PDF user-space points

Added, removed and altered items carry properties and bounds from both sides; BuildSemanticDiffOverlays supplies separate before/after rectangles with page and change indexes

Indexes start at zero and bounds stay in PDF user space measured in points; apply page rotation, crop and viewport transformations before drawing to a bitmap

Independent native page handles keep the caller's page selection and form focus unchanged and avoid invoking form actions

Non-widget fields, arbitrary unconfigured custom dictionaries, script actions, remote destination contents and custom Info keys are outside this profile; XFA form comparison is refused explicitly

Defaults allow 10,000 page pairs, 4,096 scanned items, 4,096 changes, 1 MiB per string, 16 MiB of strings altogether and 16,777,216 comparisons; an exhausted allowance refuses incomplete output

Complete separates a completed comparison from a refused one; even completed results can contain explicitly ambiguous identities, so consult AmbiguousCount before relying on item matches

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 the optional document metadata snapshots, whilst psikOutline, psikAttachment, psikPage, psikNamedDestination, psikStructure and psikOptionalContent hold the 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

Real Delphi/FPC Win32/Win64 acceptance runs cover 92 assertions per target, including saved/reopened input, values changed without pixel changes, Unicode identities, moved pages, ambiguity and resource limits

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;