Existing-document repair
Enterprise edition: reviewed tag creation/supplementation and automatic document remediation require the Enterprise units. Core structure editing/binding inspection and serialisation-level SaveAsRepaired remain separate core capabilities; see the edition matrix
Add FPdfDocumentRepair to apply reviewed tagging plans or run the supported automatic PDF/A repair steps with a built-in document backend
Both workflows return independent PDF bytes and leave the caller's document content and active page unchanged; a failed operation returns no partial output
Declarations
type
TPdfDocumentRepairLimits= record
MaxDocumentBytes: Integer;
MaxPages: Integer;
MaxObjects: Integer;
MaxMetadataCharacters: Integer;
CancellationToken: IPdfCancellationToken;
class function Default: TPdfDocumentRepairLimits; static;
end;
TPdfDocumentARepairContext= record
BaseSourceSha256: string;
StableObjectIdentities: Boolean;
Limits: TPdfDocumentRepairLimits;
SaveOptions: TPdfASaveOptions;
end;
IPdfDocumentARepairProvider= interface
['{8C6CB6C5-5AC8-471D-B529-62C466AE572F}']
function Supports(Category: TPdfARepairCategory): Boolean;
function RequiresStableObjectIdentities: Boolean;
function PreservesObjectIdentities: Boolean;
function Repair(const Source: TBytes; const Step: TPdfARepairStep;
const Context: TPdfDocumentARepairContext; out OutputPdf: TBytes;
out ErrorText: string): Boolean;
end;
TPdfDocumentARepairProviders= array of IPdfDocumentARepairProvider;
TPdfDocumentARepairOptions= record
Limits: TPdfDocumentRepairLimits;
SaveOptions: TPdfASaveOptions;
AllowOutputIntentUpdate: Boolean;
Providers: TPdfDocumentARepairProviders;
class function Default: TPdfDocumentARepairOptions; static;
end;
TPdfDocumentTagOptions= record
Limits: TPdfDocumentRepairLimits;
Language: string;
MinimumConfidence: Double;
InferHierarchy: Boolean;
HierarchyOptions: TPdfAutoTagHierarchyOptions;
PreserveExistingStructure: Boolean;
IncludeUnmarkedFormText: Boolean;
SupplementParentNodeID: Integer;
VerificationLongEdge: Integer;
MaxVerificationPixels: Int64;
MaxTableGridSlots: Integer;
MaxSemanticWork: Int64;
class function Default: TPdfDocumentTagOptions; static;
end;
TPdfDocumentTagSemantics= array of TPdfLayoutSemantics;
TPdfDocumentTagPlan= record
SourceBytes: TBytes;
SourceSha256: string;
Objects: TPdfAutoTagObjects;
Nodes: TPdfAutoTagNodes;
Semantics: TPdfDocumentTagSemantics;
PreservesExistingStructure: Boolean;
ExistingParentNodeID: Integer;
PreservedObjectCount, SkippedObjectCount: Integer;
end;
TPdfDocumentTagReport= record
Succeeded: Boolean;
Cancelled: Boolean;
TaggedObjectCount: Integer;
ArtifactCount: Integer;
StructureElementCount: Integer;
PreservedObjectCount, SkippedObjectCount: Integer;
SourceSha256: string;
OutputSha256: string;
ErrorMessage: string;
end;
// The returned bytes are an independent result; neither workflow mutates Pdf
function PlanPdfDocumentTags(Pdf: TPdf;
const Options: TPdfDocumentTagOptions): TPdfDocumentTagPlan;
function ApplyPdfDocumentTags(Pdf: TPdf; const Plan: TPdfDocumentTagPlan;
const Options: TPdfDocumentTagOptions; out OutputPdf: TBytes;
out Report: TPdfDocumentTagReport): Boolean;
function RepairPdfDocumentA(Pdf: TPdf; const Plan: TPdfARepairPlan;
const Options: TPdfDocumentARepairOptions;
out OutputPdf: TBytes; out Report: TPdfARepairExecutionReport): Boolean;
function RepairPdfDocumentAFromBytes(const Source: TBytes;
const Plan: TPdfARepairPlan; const Options: TPdfDocumentARepairOptions;
out OutputPdf: TBytes; out Report: TPdfARepairExecutionReport): Boolean;
Plan and apply document tags
PlanPdfDocumentTags captures a reproducible SHA-256-bound snapshot, reopens it and inventories the top-level text, image and path objects on every page
TPdfDocumentTagPlan is the planning basis returned by PlanPdfDocumentTags; it carries the captured source snapshot, its digest, the scanned Objects inventory and the generated Nodes tree, so review and edits before applying happen on this record rather than on the document
SourceBytes holds that independent reproducible snapshot; the planning scan and ApplyPdfDocumentTags both reopen these exact bytes instead of the live document, and the length must stay above zero and within MaxDocumentBytes
SourceSha256 is the hexadecimal SHA-256 digest of SourceBytes; ApplyPdfDocumentTags recomputes it over the stored snapshot and over a fresh capture of the current document, and rejects the plan when either digest no longer matches
The initial Nodes come from BuildPdfUa2AutoTagPlan: text becomes P, whilst paths and images without descriptions become explicit artifacts
Review every classification before applying it, especially images: meaningful figures need a Figure node with Artifact = False and an AlternateText value in the corresponding Objects entry
Reviewed content roles are P, H1 to H6, Figure, Caption, Span and Artifact; structure-only Sect, Div, P and Caption containers use PageIndex = -1 and ObjectIndex = -1
ParentIndex is a zero-based node index and must refer to a preceding container, or be -1 for a root node; hierarchy depth is bounded at 256
Node order determines structure reading order without changing native painting order; every page object must have exactly one classification, including artifacts
ApplyPdfDocumentTags verifies the snapshot and current source identity, assigns fresh page-local MCIDs, writes the structure tree and ParentTree, and independently reopens the exact result to check page count, extracted text and native structure availability
The legacy plan node's Mcid is neither trusted nor reused; output MCIDs are assigned consecutively per page
The default full-tagging profile rejects signed or encrypted inputs, XFA, existing marked content or structure trees, page annotations and widgets, nested Form XObjects and shading objects
This operation does not add a PDF/UA identifier or establish PDF/UA conformance; semantic correctness, meaningful alternate text and the final reading order still require author review
Supplement an existing structure tree
Since v3.247.0, set PreserveExistingStructure = True to propose tags for unmarked top-level text, images and paths in an already tagged document, including pages with existing annotations and widgets
Existing marked objects are preserved and counted in PreservedObjectCount; unmarked Form XObjects, shadings and unsupported object types are skipped and counted in SkippedObjectCount, so this workflow does not imply complete tagging of the page
SupplementParentNodeID = -1 selects a single top-level Document element automatically; otherwise explicitly choose an existing Document, Sect, Div, Part or Art container, or zero for the structure root, using IDs from the captured snapshot
The plan records PreservesExistingStructure and ExistingParentNodeID; review Nodes and figure alternate text as with full tagging, then apply with the same options and unchanged source
Supplementation allocates fresh page MCIDs, appends reviewed elements under the selected parent and binds each new MCID to its ParentTree owner without wrapping or replacing existing marked content
Before publication, existing node identities, metadata, child order, MCR/OBJR provenance and declared ParentTree owner slots are verified; native reopening also checks extracted text, annotation counts and widget names, types, flags, values and options
Affected pages must render identically at VerificationLongEdge pixels, default 256 and permitted range 16..2048; before/after renders share MaxVerificationPixels, default 67108864 and maximum 1073741824, and this finite rendering check does not prove identical appearance at every scale
Signed or encrypted sources and XFA remain rejected; cyclic/shared ParentTree nodes, conflicting structure namespaces, duplicate physical MCIDs, occupied owner slots or preservation failures return no output
Since v3.259.0, IncludeUnmarkedFormText = True also proposes uniquely invoked, unmarked text-only leaf Form streams with valid BBox and explicit resources, including deeply nested Forms; its default is False
The plan's FormTargets aligns with Objects and records exact stream identities for these candidates; Form object indices are synthetic per-page inventory indices after the native page objects, not indices for ObjectHandle
Each Form candidate starts as a whole-stream P node and receives its own MCID namespace and ParentTree entry; review the semantic role and ordering before applying, retain the same option, and preserve the captured Form targets
This text Form profile requires semantic ownership; artifact reassignment, mixed painting or child invocations within the selected leaf, missing explicit resources, invalid boxes, previously marked scopes and repeated invocations are excluded, whilst recursive call graphs reject explicitly
Invocation counts follow actual Do operators, including resource aliases and shared ancestors; resource dictionary membership alone does not establish uniqueness
Planning and application retain caller state, extracted text and bounded native pixels, and validate new Form-local bindings after native saves; an empty reviewed supplement returns an independent unchanged snapshot
Rebuild packages and clients and regenerate C++ headers after the public option/plan record additions
Built-in PDF/A repair execution
RepairPdfDocumentA supplies a concrete IPdfARepairExecutor to ExecutePdfARepairPlan, so callers no longer need a custom executor for the supported automatic steps
The current backend supports executable parcSecurity and parcMetadata steps; blocked, review-required and manual steps are skipped by the existing executor policy
An encrypted source requires modification permission and an explicit automatic, unblocked security step before a staged unencrypted copy can be created; signed documents and XFA are always rejected
TPdfDocumentARepairOptions.Default supplies default Limits and SaveOptions, with AllowOutputIntentUpdate = False; metadata repair requires explicitly setting that option to True because the save pipeline installs an ICC OutputIntent
Metadata repair uses the caller-selected TPdfASaveOptions to regenerate XMP, identifiers and the selected ICC OutputIntent through the existing PDF/A save pipeline
The caller must choose a profile appropriate for the document's actual colours; this operation does not convert colour samples, repair fonts or structure, remove arbitrary prohibited content or provide a replacement for an independent standards validator
Unsupported categories marked automatic fail explicitly; unresolved built-in validation issues or a target-profile mismatch trigger staged rollback and return no output
The exact staged and returned bytes are checked with ValidatePdfACompliance and independently reopened for the native checks in TPdf.ValidatePdfA; ValidationPassed refers to the built-in profile checks, not external certification
Concrete providers now cover colour, reviewed structure and explicit font/ToUnicode/ActualText resources; snapshot-bound recipes run ahead of metadata serialization
Provider execution and byte snapshots
Providers holds up to 256 non-nil IPdfDocumentARepairProvider instances; matching providers run in array order once per category, even where several executable steps name that category
RepairPdfDocumentAFromBytes copies unencrypted input bytes with no native save, keeping the object identities reviewed recipes rely on; the TPdf entry captures by way of a native save, so recipes have to bind that captured snapshot
Context carries the immutable BaseSourceSha256, current StableObjectIdentities, Limits and SaveOptions; each provider hands back a complete independent PDF with an unchanged page count and no encryption
RequiresStableObjectIdentities stops a snapshot-bound provider running after any step that can renumber objects, metadata repair included; schedule resource and structure repairs before metadata
PreservesObjectIdentities is a promise the provider makes; the executor additionally checks that earlier active object numbers and generations still exist, which does not on its own prove semantic identity for untrusted providers
Snapshot capture hangs on to the exact staged bytes, and rollback puts them back even when cancellation has already been asked for; provider failure, postvalidation failure or a target-profile mismatch yields no output
Providers count as trusted application components and stay responsible for their own work and allocation limits; native load/save/validation calls are synchronous
Optional reviewed hierarchy
Set InferHierarchy True before PlanPdfDocumentTags to gather bounded review text and font-size hints, then build page/heading sections, paragraphs with Span children and adjacent figure captions by way of BuildPdfUa2HierarchyPlan
HierarchyOptions governs node/text budgets, body size and heading ratios, paragraph alignment/gaps and caption prefixes; its node/text budgets are capped by Limits
Heading and caption candidates carry a confidence of at most 0.75 and paragraph groups of at most 0.8; raising MinimumConfidence suppresses the weaker inferences
The plan may be reviewed and altered before ApplyPdfDocumentTags; images still need reviewed alternate text to become Figure elements, and a caller can rebuild Plan.Nodes after editing those descriptions
Text review draws on Limits.MaxMetadataCharacters; InferHierarchy False keeps the original flat plan shape and does not collect review text or font hints
Paragraph and Caption containers take Span children, and Figure elements may own Caption containers; the resulting semantics are written and checked through the same independent-output workflow
The default full-tagging workflow retains its original input restrictions; existing-tree supplementation preserves annotation/widget relationships and optionally includes eligible nested text Forms, whilst existing structure editing provides explicit MCR/OBJR editing
Reviewed lists, tables and text metadata
Leave Plan.Semantics empty for role defaults, or supply one TPdfLayoutSemantics per node with the same Role; Plan.Nodes[].ParentIndex controls the hierarchy and ParentID must remain empty
Reviewed lists use L with one or more LI children, optionally preceded by one Caption; each item has at most one Lbl followed by exactly one LBody, which may own text or contain paragraphs and nested lists
Reviewed tables use Table, an optional leading Caption, TR rows and TH/TD cells; row and column spans must cover a complete rectangular grid without gaps, overlap or out-of-table cells
Set TableScope on headers, RowSpan/ColumnSpan on cells and ListNumbering on lists; zero spans mean one, and explicit spans are limited to 10,000
ElementID accepts unique Unicode tokens of up to 255 UTF-16 units without ASCII whitespace, control characters, commas or semicolons; headers without explicit IDs receive deterministic source-hash/node-index IDs, so keep an explicit ID when identity must survive a different source snapshot
HeaderIDs is an ASCII-whitespace-separated list of IDs targeting headers in the same table; duplicate, dangling, cross-table and cyclic relationships fail explicitly, cycles between header cells included
Use Language, AlternateText and ActualText for reviewed Unicode metadata; figure alternate text remains mandatory, artifacts cannot carry semantic metadata, and annotation-aware Link authoring uses the separate structure-editing workflow
The same metadata and grammar checks apply to new trees and existing-tree supplementation; output checks verify hierarchy, attributes, byte-ordered IDTree references and reciprocal physical MCID ownership after saving, then compare native extracted text and rendering at the selected finite verification resolution
These checks validate the supplied plan and its serialisation; they do not establish the human correctness of reading order, header meaning or alternate text, and do not constitute PDF/UA certification
Reviewed OCR to searchable tagged output
TagReviewedPdfOcrSource(Source, Reviewed, Options, OutputPdf, Report) connects explicit semantic review and native OCR bindings to actual tagged PDF bytes; Source is a seekable stream containing the exact saved PDF reviewed by every supplied page
TPdfOcrDocumentTagOptions.Default initialises Binding and Tagging options with their existing defaults; this workflow accepts supported unencrypted, untagged documents with top-level objects and rejects annotations/widgets or existing marks through the full-tagging profile
The workflow revalidates source hashes, owned native word Unicode, full quadrilaterals, page boxes and rotation before creating structure; it uses those original bytes directly rather than applying original object ordinals to a native re-save
Approved block order controls the structure independently of paint order: each reviewed page receives a Sect, headings become H1 through H6, adjacent list items become L/LI/LBody, tables become Table/TR/TH/TD, and bound words receive individual Span owners
Cells contains a TPdfOcrTableCellTagArray array of TPdfOcrTableCellTags records with zero-based ReviewIndex, TableIndex, CellIndex, explicit header Scope and HeaderCells indices into that same reviewed table; headers require a scope or header relationship, and invalid, duplicate, foreign or cyclic relationships fail without publishing output
Cell order follows reviewed row/column coordinates, spans retain the reviewed grid, and generated IDs bind header relationships within the exact source; block languages and word-level cell languages preserve the reviewed metadata
ScanBackgroundIsArtifact defaults to False; enable it explicitly after reviewing the scan background to classify unbound images and paths as artifacts, and enable UnboundTextIsArtifact only when the application explicitly approves unbound native text as artifact content
Approved artifact blocks retain artifact ownership, and confidence-filtered or absent native words never acquire semantic ownership silently; nonempty semantic blocks and source-bearing table cells require accepted bound words
The source stream's bytes and original position remain unchanged; returned bytes appear only after saved physical MCID/ParentTree, hierarchy, semantic metadata, native text and finite-resolution pixel checks, plus exact raw image payload and width/height/bit-depth/colorspace comparisons
TPdfOcrDocumentTagReport retains separate Binding and Tagging reports and independently owned Reviewed page snapshots with provider/reviewer evidence on success; failed operations return no output or reviewed snapshots
Use one shared cancellation token in Binding.CancellationToken and Tagging.Limits.CancellationToken, or set just one; distinct non-nil tokens are rejected, and native calls remain synchronous
Header meaning, alternate text and reading order still require human review; this connection publishes searchable tagged output for the stated profile and does not certify PDF/UA conformance
Limits and reports
MaxTableGridSlots defaults to 65,536 cumulative table slots and has a hard maximum of 1,000,000; MaxSemanticWork defaults to 67,108,864 work units and has a hard maximum of 1,073,741,824, including a bound on page-by-node application traversal
TPdfDocumentRepairLimits.Default selects 256 MiB per PDF, 10,000 pages, 100,000 objects or plan steps, and 1,048,576 metadata characters; hard maxima are 512 MiB, 10,000 pages, 100,000 objects and 16,777,216 metadata characters
MaxDocumentBytes caps the bytes accepted from any saved snapshot, the tag plan source, the published tagged output and the IccProfileData payload passed through TPdfASaveOptions
MaxPages bounds the page count of the document submitted for repair, and MaxObjects bounds tagged page objects, tag nodes and PDF/A repair plan steps
MaxMetadataCharacters bounds the plan language, per-node language, alternate/actual text, IDs and header-reference text, plus preserved form metadata during supplementation; it also bounds the summed metadata fields of TPdfASaveOptions in PDF/A repair
Snapshot saves use working storage that spills according to the document's existing SaveMemoryLimit; byte limits are checked before a saved snapshot is read into a byte array and before output is published
CancellationToken is polled between bounded stages and object operations; individual native save, reopen and validation calls remain synchronous
TPdfDocumentTagOptions.Default selects Language = 'en-US' and MinimumConfidence = 0.5, InferHierarchy = False and default HierarchyOptions; set the actual document language explicitly, and use the confidence threshold when generating the initial plan
TPdfDocumentTagReport returns Succeeded, Cancelled, TaggedObjectCount, ArtifactCount, StructureElementCount, source and output SHA-256 values and ErrorMessage
The report's SourceSha256 echoes the digest of the plan's SourceBytes, while OutputSha256 carries the digest of the exact returned tagged bytes and is set only when the operation succeeds
PDF/A repair returns TPdfARepairExecutionReport with applied and skipped counts, staged rollback status, validation status and ErrorText; the source document remains unchanged even when staging fails before a snapshot exists
Example
Options := TPdfDocumentTagOptions.Default;
Options.Language := 'en-US';
Plan := PlanPdfDocumentTags(Pdf, Options);
// Review Plan.Nodes and describe meaningful figures in Plan.Objects
if not ApplyPdfDocumentTags(Pdf, Plan, Options, OutputPdf, Report) then
raise Exception.Create(Report.ErrorMessage);
// OutputPdf is an independent byte array ready for explicit saving or loading
PDF/A repair example
RepairOptions := TPdfDocumentARepairOptions.Default;
// Select a target ICC profile appropriate for the actual document colors
RepairOptions.AllowOutputIntentUpdate := True;
if not RepairPdfDocumentA(Pdf, RepairPlan, RepairOptions, OutputPdf, Execution) then
raise Exception.Create(Execution.ErrorText);
See also
FPdfStandardsExecution, FPdfPreflightReport, FPdfLayout, SaveAsPdfA