PDFiumPas Docs

Existing-document structure editing

FPdfDocumentStructure reads existing structure trees, applies snapshot-bound metadata and binding edits, and explicitly normalises reviewed shared Form invocation ownership

Public declarations

type
  EPdfStructureEdit= class(Exception);
  TPdfStructureEditOptions= record
    ReadOptions: TPdfActiveObjectReadOptions;
    MaxElements, MaxContentItems, MaxOperations, MaxDepth: Integer;
    MaxTextCharacters: Integer;
    MaxOutputBytes, MaxWork: Int64;
    AllowInheritedAttributeChanges: Boolean;
    CancellationToken: IPdfCancellationToken;
    class function Default: TPdfStructureEditOptions; static;
  end;
  TPdfStructureNodeIDs= array of Integer;
  TPdfStructureContentKind= (psckMarkedContent, psckObjectReference);
  TPdfDocumentStructureContentItem= record
    Kind: TPdfStructureContentKind;
    MarkedContentID: Integer;
    PageObjectNumber, PageGeneration: Integer;
    StreamObjectNumber, StreamGeneration: Integer;
    StreamOwnerObjectNumber, StreamOwnerGeneration: Integer;
    ReferencedObjectNumber, ReferencedGeneration: Integer;
    IndirectObjectNumber, IndirectGeneration: Integer;
  end;
  TPdfDocumentStructureContentItems= array of TPdfDocumentStructureContentItem;
  TPdfDocumentStructureNode= record
    NodeID, ParentNodeID, Generation: Integer;
    RoleName: AnsiString;
    Title, AlternateText, ActualText, Language, ExpansionText: WideString;
    ElementID, TableScope, TableHeaders: AnsiString;
    TableRowSpan, TableColSpan: Integer;
    ListNumbering, LayoutPlacement, LayoutBBox, ClassName: AnsiString;
    ChildNodeIDs: TPdfStructureNodeIDs;
    ContentItems: TPdfDocumentStructureContentItems;
    ContentItemCount, FormReferenceCount, ObjectReferenceCount: Integer;
  end;
  TPdfDocumentStructureNodes= array of TPdfDocumentStructureNode;
  TPdfDocumentStructureSnapshot= record
    SourceSha256: string;
    RootObjectNumber, RootGeneration: Integer;
    Nodes: TPdfDocumentStructureNodes;
  end;
  TPdfStructureEditKind= (psekSetRole, psekSetTitle, psekSetAlternateText,
    psekSetActualText, psekSetLanguage, psekMove, psekInsertContainer,
    psekAddMarkedContent, psekAddObjectReference, psekSetExpansionText,
    psekSetElementID, psekSetTableScope, psekSetTableHeaders,
    psekRemoveContentItem, psekSetTableRowSpan, psekSetTableColSpan,
    psekSetListNumbering, psekSetLayoutPlacement, psekSetLayoutBBox,
    psekSetClassName, psekRemoveNode, psekBindPageMarkedContent);
  TPdfStructureEditOperation= record
    Kind: TPdfStructureEditKind;
    NodeID, ParentNodeID, BeforeNodeID: Integer;
    Value: WideString;
    TargetObjectNumber, TargetGeneration: Integer;
    MarkedContentID: Integer;
  end;
  TPdfStructureEditOperations= array of TPdfStructureEditOperation;
  TPdfStructureInsertedNode= record
    RequestedNodeID, ObjectNumber, Generation: Integer;
  end;
  TPdfStructureInsertedNodes= array of TPdfStructureInsertedNode;
  TPdfStructureEditReport= record
    Succeeded, Cancelled, HasStructure: Boolean;
    ElementCount, ContentItemCount, FormReferenceCount, ObjectReferenceCount: Integer;
    AppliedOperationCount, MovedElementCount: Integer;
    CreatedMarkedContents, CreatedObjectReferences, RemovedContentItems, RemovedNodes: Integer;
    BoundMarkedContents: Integer;
    SourceSha256, OutputSha256: string;
    InsertedNodes: TPdfStructureInsertedNodes;
    ErrorMessage: string;
  end;

  TPdfAnnotationRemovalOptions= record
    ReadOptions: TPdfActiveObjectReadOptions;
    RemoveOwnedStructurePeers: Boolean;
    RemoveEmptiedStructureNodes: Boolean;
    MaxOutputBytes, MaxWork: Int64;
    CancellationToken: IPdfCancellationToken;
    class function Default: TPdfAnnotationRemovalOptions; static;
  end;
  TPdfAnnotationRemovalReport= record
    Succeeded, Cancelled: Boolean;
    RemovedAnnotations, RemovedObjectReferences, RemovedStructureNodes: Integer;
    SourceSha256, OutputSha256: string;
    ErrorMessage: string;
  end;

// NodeID zero denotes the structure root; negative IDs name new containers
// Content references and existing object identities remain immutable
function RemovePdfPageAnnotations(Source: TStream; PageIndex: Integer;
  const AnnotationObjectNumbers: array of Integer;
  const Options: TPdfAnnotationRemovalOptions;
  out OutputPdf: TBytes; out Report: TPdfAnnotationRemovalReport): Boolean;
function ReadPdfDocumentStructure(Source: TStream;
  const Options: TPdfStructureEditOptions; out Snapshot: TPdfDocumentStructureSnapshot;
  out Report: TPdfStructureEditReport): Boolean;
function ValidatePdfDocumentStructureBindings(Source: TStream;
  const Options: TPdfStructureEditOptions; out Report: TPdfStructureEditReport): Boolean;
function EditPdfDocumentStructure(Source: TStream; const ExpectedSourceSha256: string;
  const Operations: TPdfStructureEditOperations; const Options: TPdfStructureEditOptions;
  out OutputPdf: TBytes; out Report: TPdfStructureEditReport): Boolean;

Annotation removal since v3.376.0

RemovePdfPageAnnotations withdraws the listed annotations from one page's /Annots in a single incremental revision; TPdfAnnotationRemovalOptions.RemoveOwnedStructurePeers also removes the OBJR items that pointed at those annotations with their ParentTree entries, and RemoveEmptiedStructureNodes then removes the elements left without content or children, deepest first

TPdfAnnotationRemovalOptions.Default keeps both removals off and bounds the call to 512 MiB of output (MaxOutputBytes) and 64 MiB of work (MaxWork); CancellationToken cancels it. TPdfAnnotationRemovalReport returns Succeeded and Cancelled, the RemovedAnnotations, RemovedObjectReferences and RemovedStructureNodes counts, the SourceSha256 and OutputSha256 digests and an ErrorMessage

Inspect and edit a matching snapshot

ReadPdfDocumentStructure returns a source SHA-256 digest, stable indirect node IDs, direct metadata, child node IDs and content-item provenance for page MCIDs, nested Form MCR dictionaries and OBJR items

NodeID zero denotes StructTreeRoot in operations; positive IDs come from the matching snapshot, and unique negative IDs identify new containers within the current operation batch

ContentItems expose the MCID, page, stream, stream owner, referenced object and original indirect content-item identity; zero object numbers mean the corresponding value is unspecified

EditPdfDocumentStructure requires ExpectedSourceSha256 from that snapshot and executes operations in order; BeforeNodeID zero appends, whilst another value anchors insertion before an existing child of the selected parent

New containers accept any standard PDF 1.7 / 2.0 / PDF/UA structure role (such as Document, Part, Sect, Div, P, H1..H6, Figure, Table, TR, TH, TD, L, LI, Span, Form, Link or Caption) or any custom role mapped in StructTreeRoot /RoleMap and return their allocated object numbers in InsertedNodes

psekAddMarkedContent adds a new marked-content binding: TargetObjectNumber and TargetGeneration name an uncompressed or /FlateDecode-compressed content stream (including single-element [/FlateDecode] filter arrays without predictor parameters), allocate the next sequential MCID after any existing page or form MCIDs and in-stream /MCID dictionaries, wrap either the trailing unmarked top-level segment after balanced BDC/BMC...EMC operators or the whole stream in /P <</MCID N>> BDC ... EMC, and insert an MCR kid into the target element (at the end when BeforeNodeID is zero, or before the specified child element when BeforeNodeID is non-zero); both page content streams and uniquely referenced Form XObject streams automatically synchronise or allocate /StructParents, StructTreeRoot /ParentTreeNextKey and the corresponding leaf /Nums array in /ParentTree (synthesising a new /ParentTree object when StructTreeRoot lacks one)

psekAddObjectReference inserts an OBJR kid (appending when BeforeNodeID is zero or anchoring before BeforeNodeID) for an annotation that appears on exactly one page Annots array or a form or image XObject referenced by exactly one page resource dictionary, recording the target through /Obj and its page through /Pg whilst automatically assigning or reusing /StructParent on the target dictionary or stream and recording the scalar mapping in StructTreeRoot /ParentTree

CreatedMarkedContents, CreatedObjectReferences and RemovedContentItems count the appended or removed bindings; the written revision keeps every existing object identity and the wrapped stream is re-embedded (preserving /Filter /FlateDecode recompression when originally compressed) with an updated /Length whilst its other dictionary entries stay untouched

SetRole accepts an unescaped printable ASCII role name within 127 characters; title, alternate text, ActualText, language and expansion text (psekSetExpansionText for /E, ISO 32000-1 §14.9.5 / PDF/UA-1) values use validated UTF-16 text, and an empty metadata value removes that local entry

psekSetElementID sets or clears a unique Unicode /ID within 1..255 UTF-16 units without control characters and synchronises or synthesises a byte-ordered StructTreeRoot /IDTree; printable ASCII IDs keep their bytes, whilst other IDs use UTF-16BE with a BOM and hexadecimal PDF serialisation. Only a single-node /IDTree is rewritten: setting an ID in a tree whose root carries /Kids raises EPdfStructureEdit, and removing an element leaves such a tree unchanged

psekSetTableScope sets or clears /A << /O /Table /Scope /Row | /Column | /Both >> on table header cells, psekSetTableHeaders sets or clears semicolon- or comma-separated Unicode header element IDs in /A << /O /Table /Headers [...] >>, and psekSetTableRowSpan / psekSetTableColSpan set or clear positive integer /RowSpan and /ColSpan entries in /A << /O /Table ... >> (ISO 32000-1 §14.8.5.7 / PDF/UA-1)

psekSetListNumbering sets or clears /A << /O /List /ListNumbering ... >> (such as None, Disc, Circle, Square, Decimal, UpperRoman, LowerRoman, UpperAlpha, LowerAlpha, Ordered, Unordered or Description); psekSetLayoutPlacement and psekSetLayoutBBox set or clear /Placement (Block, Inline, Before, Start, End) and four-number /BBox arrays in /A << /O /Layout ... >>; and psekSetClassName sets or clears one or more /C class names on the element whilst automatically registering any new class name in StructTreeRoot /ClassMap

psekRemoveContentItem unbinds an existing MCR or OBJR item from the target structure element (matching an MCR when Value holds its non-negative MCID and optional TargetObjectNumber/TargetGeneration match its page or stream, matching an OBJR when TargetObjectNumber/TargetGeneration name the referenced object, or matching by zero-based content index via BeforeNodeID) and clears the corresponding MCID slot in /ParentTree; psekRemoveNode removes an empty structure element (with no remaining child elements or content items) from its parent's /K array and unregisters its /ID from /IDTree, incrementing RemovedNodes

UTF-16 and PDF 2.0 UTF-8 strings are decoded for inspection; existing metadata and unknown dictionary keys retain their original representation unless explicitly edited

Existing node IDs, mixed content-child order, raw MCR/OBJR values, ParentTree, IDTree, role/class maps, namespaces, attributes and associated-file entries remain intact, and new page-level MCIDs created via psekAddMarkedContent synchronise with an existing ParentTree; moving a child updates its parent pointer and both child lists

Cross-context moves pin the previous page and language when needed; an unspecified original page context that cannot be preserved is rejected

Moves that change inherited A/C attribute contexts are rejected by default; AllowInheritedAttributeChanges explicitly permits that reviewed semantic change whilst retaining local attributes

Object packing and native full saves may renumber nodes, so obtain a new snapshot before editing their output; IDs from an earlier PDF revision are not transferable to a different source digest

Transaction and verification

Since v3.247.0, psekBindPageMarkedContent attaches an already present, uniquely declared page MCID to an existing or newly inserted element without rewriting the page content; TargetObjectNumber/TargetGeneration identify the page dictionary and MarkedContentID identifies the MCID

The binder decodes bounded page content sequences, resolves named BDC properties, skips inline-image payloads and rejects absent, repeated or already owned MCIDs; it allocates or updates the page ParentTree entry without replacing another element's owner slot and increments BoundMarkedContents on success

Since v3.258.0, ValidatePdfDocumentStructureBindings checks both directions of each structure-declared page/Form MCR and OBJR relationship. Every nonnull ParentTree array slot requires one declared MCID owner; each scalar value identifies one structure element, and since internal v3.413.4 multiple OBJR items may refer to the same object through that same owner, including one reference per rendered page. Conflicting elements, orphan keys/slots, duplicate MCID claims, inconsistent namespaces and invalid number trees reject without modifying source bytes or position

Removing one of several OBJR items keeps the object's StructParent and scalar ParentTree entry; only removing the last reference withdraws that inverse binding. This edits logical references without removing the painted XObject or splitting individual invocations; ISO 32000-1 14.7.4.3 Note 2 distinguishes cross-page references from repeated renditions on one page

Each declared MCR must have one physical MCID declaration in its page or stream namespace. Explicit Stm references retain original BDC stream provenance across continued page contents and split operands. Comments, strings and inline-image payloads cannot create declarations, whilst StructParent and StructParents cannot both appear on one owner

Unclaimed physical MCIDs remain available for subsequent binding, including tag-supplement staging; passing this declared-ownership check does not establish complete tag coverage, semantic correctness or PDF/UA conformance. Existing item/depth/work/cancellation budgets apply, and ParentTree slots share the cumulative content-item limit

The input is captured once into bounded independent storage, its stream position is restored, and the original source is never modified

Successful edits append an independent revision; an empty operation list returns the exact original bytes

The returned revision is independently parsed before publication to verify node identities, child order and every retained raw content relationship

Potential signatures and signature fields may be inspected but cannot be edited; encrypted input, cyclic/multiply owned trees, inconsistent parent pointers, inactive references, unsupported child objects and exhausted limits return False without output

On failed edits, applied/moved counts and inserted-node reports are cleared; a successful read without a structure tree returns HasStructure False and no nodes

Default limits are 128 MiB source bytes, 100000 elements, 1000000 content items, 100000 operations, depth 128, 1048576 text characters, 512 MiB model/staging/output bytes and 67108864 work units

Hard maxima are 100000 elements, 1000000 content items, 100000 operations, depth 128, 16777216 text characters, MaxInt output bytes and 1073741824 work units; active-object reader limits apply independently

This profile preserves and edits existing bindings, adds or removes explicit MCID/OBJR relationships and can synthesise a missing ParentTree when adding content; semantic correctness and PDF/UA conformance still require separate review and validation

For new top-level tags and optional heading/paragraph/caption inference, use PlanPdfDocumentTags; automatic hierarchy decisions remain reviewable heuristics

Content references and parent relationships follow ISO 32000 logical structure

Form invocation scopes

ReadPdfStructureFormScopes returns a TPdfStructureFormScopes array of bounded active stream/page identities, actual invocation counts and eligibility hints for unmarked text-only leaf Form supplementation, preserving source bytes and position

Each TPdfStructureFormScope carries the form and owner-page object identities plus InvocationCount and the HasMarks, HasLocalText, TextOnly, HasExplicitResources and HasBBox eligibility hints

Counts follow Do operators through nested resources, aliases and shared ancestors; cycles, inactive resources and exhausted budgets reject explicitly

Marked-content creation in Forms requires exactly one actual invocation in the document, including nested invocations; resource membership alone is insufficient

Namespace map since internal v3.431.81

ReadPdfStructureNamespaces reads the active structure tree’s element namespaces and role mappings into a TPdfStructureNamespaceEntries array, preserving the source bytes and stream position; it returns False for a nil stream, a document without a structure tree or a rejected read

Each TPdfStructureNamespaceEntry carries the element’s RoleName and NamespaceUri with their MappedRoleName and MappedNamespaceUri targets resolved through /RoleMap and /Namespace mappings, the InvalidNamespace and InvalidRoleMap rejection flags, and the table attributes TableColSpan, TableRowSpan and TableScope

HasAlternativeText records /Alt or /ActualText key presence directly from the element dictionary — ISO 14289-2 8.2.5.28.2/1 tests key presence, not content, and the native snapshot cannot tell a present-but-empty text from an absent key. IsRootChild marks entries whose parent node is the StructTreeRoot itself, the scope ISO 14289-2 8.2.5.2 applies to, because the native page snapshot omits a root with no /K. ParentNodeIndex keeps the zero-based parent position in the active tree, which includes empty cells and preserves their table attributes

Snapshot Form usage since internal v3.411.0

type
  TPdfStructureFormUsage=record
    ObjectNumber,Generation,FirstPageIndex:Integer;
    PageInvocationCount,AppearanceInvocationCount:Integer;
    HasOtherUses:Boolean;
  end;
  TPdfStructureFormUsages=array of TPdfStructureFormUsage;
function ReadPdfStructureFormUsage(Source:TStream;
  const Options:TPdfStructureEditOptions;out Usage:TPdfStructureFormUsages;
  out Report:TPdfStructureEditReport):Boolean;

This separate reader counts the actual Do calls from every page and every N/R/D annotation appearance state, including unselected named states, nested calls, aliases and shared ancestors; it leaves the page-only traversal and record layout of ReadPdfStructureFormScopes untouched

Each entry retains the exact active stream object number and generation, the zero-based first owner-page index, and separate page and appearance invocation counts; an appearance root stream counts as one appearance invocation even when its optional Type or Subtype labels are absent

A Form found only through an ancillary graph has zero page/appearance counts, FirstPageIndex = -1 and true HasOtherUses; unreferenced Forms outside the scanned entry points are not added to the usage array

HasOtherUses excludes streams reached through soft-mask, Pattern or Type3 CharProcs resource graphs, or external/reference Form content, from an exclusive page-owner proof; ancillary traversal follows complete dictionary references without trusting Type labels and conservatively includes resource aliases that may never be painted

Since internal v3.413.1, missing-resource fallback follows the content consumer: soft-mask groups use their owning renderer page, Type3 glyphs use font resources or the font-use context, and resource-less patterns keep a conservative local fallback; nested Forms retain their effective resources and the parser-page category fallback. Image samples, font programmes and function data do not acquire drawing-resource fallback merely because their stream dictionary lacks Resources, even when opaque data carries a misleading Subtype label

Since internal v3.413.2, an auxiliary content stream with its own explicit XObject dictionary uses decoded Do calls to follow that resource edge, including nested Forms, comments, escaped names and inline-image boundaries; unused local aliases do not establish another use. This additional evidence sets HasOtherUses without adding to the page or appearance invocation counts

Since internal v3.413.3, soft masks and nested auxiliary Forms also follow calls through inherited resources, and Type3 glyphs use their font or font-use resource context; absent resource categories can fall back to the parser-page category, whilst an existing category with a missing name refuses review. The same mask stream is reviewed separately for each owning page, and a nested mask inside Type3 content keeps the renderer page rather than the font's parser context

Since internal v3.414.1, recognised indirect Type3 fonts defer CharProcs traversal until a font is selected by Tf, an ExtGState Font entry or another selected glyph programme; opaque references to a font or its CharProcs retain every owning font context. Resource-category shadowing and parser/renderer page contexts are preserved, whilst direct or unrecognised font dictionaries keep conservative traversal

Since internal v3.414.3, recognised indirect tiling and shading Pattern definitions defer ancillary traversal until selected by scn or SCN, selected from nested or auxiliary content, or reached through an opaque reference. Known resource dictionaries and Pattern maps are classified by their actual consumer edges; a private reference to the same map still keeps its full closure, and objects reused as masks or other consumers retain conservative treatment

Pattern registration follows nested definitions without decoding their unused content; selected tiling streams share the existing per-stream/cumulative decoded-byte and work limits, and registration/context inventories are bounded by MaxDepth and MaxContentItems. Missing required tiling Resources and direct or unrecognised definitions keep conservative handling

Since internal v3.414.4, ordinary Pattern selections are bound to their effective resources, parser-page fallback and renderer-page resources instead of a document-wide object flag. A selection on one page does not activate different unselected lookup contexts; missing or null Pattern categories use the parser-page fallback, whilst an existing dictionary with a missing name still shadows it

Opaque Pattern references retain all registered contexts and complete nested Pattern-resource closures, including private references discovered after the parent content was scanned. Proven content resource edges use selection evidence without changing source dictionaries; direct private references to resource maps and definitions remain conservative

Since internal v3.414.5, indirect Type3 selection is bound to effective resources and renderer-page resources, so an unselected page no longer inherits another page's font activation. A resource-less font can cache a glyph parsed under an earlier selected context, so all selected parser-resource and renderer-page combinations remain checked; private font, glyph and name-map references activate every registered context, including late discoveries

Since internal v3.414.6, ordinary Pattern selection remains pending in separate fill and stroke channels until a consumer uses that colour. Unpainted, overwritten or q/Q-discarded states no longer imply an ancillary use; valid device-colour and Pattern-space resets clear the matching channel, whilst invalid names, invalid colour arity and numeric sc/scn preserve conservative native behaviour

The current path survives q/Q independently, ends after painting or n, and spans concatenated page content streams. The graphics-state stack is limited to the smaller of MaxDepth and 256 entries and charges work for saved states; Form calls and unknown operators still consume colours conservatively rather than claiming exact geometry or inherited colour analysis

Since internal v3.415.1, text shows with native rendering mode 3 do not consume pending Pattern colours. Tr follows native single-precision rounding before integer truncation, so 3.5 is invisible but 3.99999999 rounds to visible mode 4; missing or non-numeric values reset the tracked mode to visible, and q/Q restores the saved mode

A recognised named image XObject with a ColorSpace and no active ImageMask consumes neither pending Pattern channel; a stencil image can consume only the fill channel. Missing ColorSpace and uncertain mask values retain a conservative fill check. Inline images, Form inheritance, other text modes and opaque references retain conservative handling

Source usage review and native preserving generation are separate contracts. Runtimes preceding internal v3.415.0 reject directly edited page Pattern operators even when the reader proves an exclusive Form; the bundled v3.415.0 runtime now admits the qualified Pattern source profiles whilst unsupported grammar, geometry and ownership still restore the complete transaction

Qualified Pattern replay preserves original Pattern and ColorSpace bindings, uncoloured base components and Form anchoring; cross-stream q/Q restoration and unpainted nested selections compose with the checked Form owner review. Since internal v3.415.2, native source replay accepts empty-path painting after n and empty h operations without inventing paint members; loaded older runtimes keep their existing capability boundary

Font resource dictionaries and null/stream-valued Font categories follow native dictionary fallback. Every glyph of a selected font is still conservatively considered, declared ExtGState fonts remain conservative, and inherited Form, visible-text channel selection, inline-image and geometry-specific Pattern consumption remain conservative. Direct/unrecognised definitions, reference-alias chains and other opaque closures remain outside this precision extension, distinct from the exact page/appearance invocation counts

A candidate exclusive page stream needs exactly one PageInvocationCount, zero AppearanceInvocationCount and false HasOtherUses, all from the same Report.SourceSha256 snapshot; structure ownership validation and matching the loaded native document to those source identities remain separate requirements

Since internal v3.415.3, the checked native generator honours reviewed ordinary Form identities as well as structured streams, including ordinary ancestors reached by structured-Form review. Exclusivity must cover original and current snapshots, every page, every appearance and ancillary closures; current-page native counting alone is insufficient

Since internal v3.416.0, source-preserving transactions also use this proof for ordinary Form edits detected by the optional native edit query. No Form proof is required for page-only edits, older runtimes or an ordinary edit whose optional proof is unavailable; the existing private clone path remains available under its own source checks. Mandatory structured review and errors after a write still require whole-batch restoration

A resource-less Form can resolve an old XObject name through page resources even when it is untouched. Rebinding that name to a selected private clone changes the peer's output; retire a clone by proving its stream ownership and retaining its identity rather than reassigning a shared fallback name

Source bytes and position remain unchanged; malformed/inactive resources, recursive calls or appearance states, invalid options, cancellation and exhausted source/object/invocation/depth/decoded-byte/work limits return False with an empty usage array and an error report

The structure reader options apply, with additional ceilings of 8 MiB per decoded stream or concatenated page content, 32 MiB cumulative decoded content and 64 nested Form calls; these are parser and review limits rather than native-process isolation guarantees

Internal v3.413.0 delivers the reviewed Form generator in the bundled Windows modules; this reader supplies source-usage evidence, whilst the checked commit adapter retains original/current snapshot identity matching and native structural preflight

Internal v3.412.0 also reads direct annotation dictionaries produced by native annotation creation; the optional commit adapter intersects usage evidence from the original baseline and a freshly serialized document so a later appearance cannot inherit an obsolete exclusive-owner decision

Reviewed whole-object Form splitting since internal v3.414.0

type
  TPdfStructureObjectFormReview=record
    PageIndex,StreamObjectNumber,StreamGeneration,InvocationIndex:Integer;
    NodeID,BeforeKidIndex:Integer;
  end;
  TPdfStructureObjectFormReviews=array of TPdfStructureObjectFormReview;
  TPdfStructureObjectFormInstance=record
    PageIndex,StreamObjectNumber,StreamGeneration,InvocationIndex:Integer;
    OutputObjectNumber,ParentTreeKey,ObjectReferenceNumber:Integer;
    NodeID,BeforeKidIndex:Integer;
  end;
  TPdfStructureObjectFormInstances=array of TPdfStructureObjectFormInstance;
function SplitPdfStructureObjectFormInstances(Source:TStream;
  const ExpectedSourceSha256:string;const Reviews:TPdfStructureObjectFormReviews;
  const Options:TPdfStructureEditOptions;out OutputPdf:TBytes;
  out Report:TPdfStructureObjectFormSplitReport):Boolean;

This source-to-output operation splits explicitly selected page invocations of an existing whole-object Form with StructParent/OBJR ownership; it requires the exact source digest and does not infer semantic owners or logical reading order

PageIndex is zero-based, and InvocationIndex is the zero-based depth-first occurrence of that exact stream object number and generation on the selected page, including calls through shared ancestors. NodeID names an existing destination structure element; BeforeKidIndex anchors insertion before an original K child, counting both structure children and content items, or uses -1 to append. Multiple reviews at one anchor retain review-array order, even when it differs from physical invocation order

Every selected invocation receives a private stream, a new scalar ParentTree key and a new indirect OBJR with explicit Pg. Unbound shared ancestors are cloned along the selected path; an independently owned internal ancestor can be updated in place only when its page invocation is exclusive and has no appearance or uncertain ancillary uses. Shared internal ancestors require separate explicit MCID reviews through NormalizePdfStructureFormInstances first; the resulting private internal streams can then participate in this operation

Original OBJR items are retired only on pages with no remaining original page or N/R/D appearance call; the original StructParent and scalar ParentTree entry are removed only when no original invocation remains anywhere. Appearance payloads, unselected calls and opaque source aliases remain untouched; rewritten page contents retain physical MCIDs and retarget explicit page MCR Stm references without changing indirect MCR identity

TPdfStructureObjectFormSplitReport returns SplitForms, ClonedAncestors, UpdatedAncestors, RetiredSourceBindings, RetiredPageReferences, the cumulative ScanWork, source and output digests, and an Instances array of TPdfStructureObjectFormInstance, its TPdfStructureObjectFormInstances collection type, in review order. Each TPdfStructureObjectFormInstance preserves the reviewed page/stream/generation/occurrence and returns OutputObjectNumber, ParentTreeKey, ObjectReferenceNumber, NodeID and the resolved original BeforeKidIndex

Saved output is independently reparsed for reciprocal structure bindings and exactly one exclusive page call per new stream; it can then be opened and edited through the checked preserving transaction path when the optional reviewed native Form extension is available. Human semantic review and complete PDF/UA conformance remain separate requirements

Signed/encrypted sources, external or uncertain ancillary target uses, missing source page claims, nested structure content items, stale or duplicate reviews, unknown logical anchors, recursive graphs and exhausted limits refuse without changing source bytes or stream position; failed output, instance identities and mutation counts are cleared. Source-reader limits apply across page/appearance review and rewritten content, including 8 MiB per decoded stream/sequence, 32 MiB cumulative decoding and 64 Form levels

Reviewed internal Form ownership since v3.322.0

type
  TPdfStructureFormBinding=record
    PageIndex,StreamObjectNumber,StreamGeneration,InvocationIndex:Integer;
    MarkedContentID,NodeID:Integer;
  end;
  TPdfStructureFormBindings=array of TPdfStructureFormBinding;
  TPdfStructureFormInstance=record
    PageIndex,StreamObjectNumber,StreamGeneration,InvocationIndex:Integer;
    OutputObjectNumber,ParentTreeKey:Integer;
  end;
  TPdfStructureFormInstances=array of TPdfStructureFormInstance;
  TPdfStructureFormNormalizeReport=record
    Succeeded,Cancelled:Boolean;
    ClonedForms,BoundMarkedContents:Integer;
    ScanWork:Int64;
    SourceSha256,OutputSha256,ErrorMessage:string;
    Instances:TPdfStructureFormInstances;
  end;
function NormalizePdfStructureFormInstances(Source:TStream;
  const ExpectedSourceSha256:string;const Bindings:TPdfStructureFormBindings;
  const Options:TPdfStructureEditOptions;out OutputPdf:TBytes;
  out Report:TPdfStructureFormNormalizeReport):Boolean;

Supply the unchanged digest from ReadPdfDocumentStructure and a reviewed destination owner for every physical MCID in every page-painted Form carrying StructParents, including already unique invocations. PageIndex is zero-based; InvocationIndex is the zero-based occurrence of the original stream identity on that page in depth-first Do traversal, including aliases and calls through shared ancestors. NodeID must name an existing positive structure element in that source snapshot

The binding list is an explicit logical decision. The normaliser does not infer roles, reading order, alternative text or ownership. It removes previous MCRs for the normalised streams and appends reviewed MCRs to each destination owner in binding-list order, retaining existing hierarchy, structure element identities, metadata and unrelated children

Each internally tagged invocation receives an independent Form stream and ParentTree namespace whilst retaining its original MCIDs, decoded content, BBox, Matrix and resource values. Shared ancestor calls are independently cloned as needed; only resource operands and private resource dictionaries change along those paths. Page content arrays and inherited resources are retained semantically, and explicit page-content MCR stream references are rebound to the merged replacement content stream

The original resource aliases can remain reachable with their old content; their obsolete StructParents claims are removed. Existing ParentTree entries for unrelated page and object content remain, normalised entries are replaced by reciprocal owner arrays, and ParentTreeNextKey advances past allocated keys. This is structure repair rather than secure content removal

Instances maps original page/stream/occurrence identities to allocated generation-zero Form object numbers. ParentTreeKey = -1 identifies an untagged ancestor clone. ClonedForms includes those ancestors; BoundMarkedContents counts supplied bindings. A later normalisation needs a fresh snapshot and bindings reconciled to the saved identities

Source bytes and stream position remain unchanged, including on failure. Publication requires a reopened complete structure model, reciprocal physical MCID/MCR/ParentTree validation and a unique actual invocation for each internally tagged output Form. Decode, object, invocation, depth, staging and cumulative work limits apply; failed calls publish no candidate bytes, instance maps or success counts

Encrypted or signed sources, missing/duplicate/unused reviews, invalid owners, cycles, external Form content, whole-object ownership that would be duplicated, annotation appearances reaching a normalised stream, and internally tagged calls enclosed by another MCID reject explicitly. Appearance reachability does not trust dictionary Type labels as graph boundaries. Appearance normalisation and automatic semantic inference remain separate capabilities

Since v3.323.0, typed object batches can edit qualified unique internal streams whilst retaining their original object identities and MCR/ParentTree ownership; direct paragraph rewriting remains separate

The supported reader profile retains exact reviewed logical order and supplementary Unicode semantic values through actual full native saves. Existing self-transformed or clipped native-source reader limitations remain explicit; preserving those documents does not certify previously unsupported native selection mappings

Repeated internally tagged Form ownership follows the distinction between whole-call content items and unique internal content items in ISO 32000-1, section 14.7.4.2