PDFiumPas Docs

Structured OCR and reflow

Enterprise TagReviewedPdfOcrSource connects explicitly approved layouts and exact-source native word bindings to searchable tagged PDF output with reviewed heading/list/table structure, explicit header relationships and scan-background policies

Requires Small Business or Enterprise, available since v3.246.0, updated 2026-10-31

FPdfOcrLayout extends the existing IPdfOcrProvider search-layer workflow with line/block reading order, optional reviewed tables, preprocessing transforms and conversions to TPdfStructuredTextPage and TPdfReflowDocument

The unit links the Small Business OCR implementation and registers pffStructuredOcr for feature availability queries

function ApplyPdfStructuredOcr(Pdf: TPdf; const Provider: IPdfOcrProvider;
  const Options: TPdfStructuredOcrOptions; out Report: TPdfStructuredOcrReport;
  const CancellationToken: IPdfCancellationToken = nil): Boolean;

function BuildPdfOcrStructuredText(const Layout: TPdfOcrPageLayout;
  const Options: TPdfStructuredOcrOptions): TPdfStructuredTextPage;

function BuildPdfOcrReflowDocument(const Layout: TPdfOcrPageLayout;
  const LayoutOptions: TPdfStructuredOcrOptions;
  const Options: TPdfReflowOptions): TPdfReflowDocument;

Provider compatibility and reading order

Existing word providers, including FPdfOcrTesseract, remain usable unchanged; InferPdfOcrLayout retains their word order, groups adjacent words into geometric lines and exposes one heuristic block per line with Source=polsHeuristic

The optional IPdfStructuredOcrProvider extends IPdfOcrProvider with RecognizePageLayout; when supported, the workflow uses the provider's explicit hierarchy instead of calling its legacy word method

ValidatePdfOcrLayout checks one layout against the item, character and grid budgets and the word, line, block and table partition rules, raising EPdfOcrLayout on the first violation; providers can call it to pre-check what the workflow itself enforces

TypeContract
TPdfOcrPageLayoutOwns Words, Lines (TPdfOcrLines), Blocks (TPdfOcrBlocks), optional Regions (TPdfOcrRegions) and Tables (TPdfOcrLayoutTables); PageNumber, PageWidth/PageHeight, ImageWidth/ImageHeight and ImageToPage capture the source page and raster geometry; MinimumConfidence sets the threshold, Source: TPdfOcrLayoutSource is polsProvider or polsHeuristic, and provider Diagnostics text counts against MaxLayoutCharacters
TPdfOcrLineFirstWord and positive WordCount partition every word exactly once in reading order
TPdfOcrBlockFirstLine and positive LineCount partition every line exactly once; Kind: TPdfOcrBlockKind selects pobParagraph, pobHeading, pobListItem or pobArtifact; Language carries optional language metadata and HeadingLevel must be 1 through 6 for headings
TPdfOcrLayoutTableFirstBlock and BlockCount own a contiguous block range and a complete bounded grid with RowCount and ColumnCount, described by Cells (TPdfOcrLayoutCells)
TPdfOcrLayoutCellDeclares RowIndex, ColumnIndex, RowSpan, ColumnSpan, a nonoverlapping FirstLine/LineCount range and IsHeader status; empty cells may own zero lines

Table metadata is authoritative only when Reviewed=True; unreviewed tables leave their source text as ordinary blocks and never silently acquire table semantics

Reviewed grids reject overlapping spans, gaps, multiply claimed blocks/lines, omitted source lines and Artifact ownership before inserting any words for that page

Semantic proposals and explicit review

Since v3.270.0, TPdfOcrSemanticReview captures an independent layout snapshot and offers reviewable heading, list, table/header and reading-order candidates before structured-text or HTML conversion

Construct the review with TPdfOcrSemanticReviewOptions.Default and a nonempty ProviderIdentity, then read its Proposal: TPdfOcrSemanticProposal; every getter returns independent word, line, block, region, table-cell, order and evidence arrays

Type or fieldContract
TPdfOcrSemanticReviewOptionsCarries LayoutOptions, ProviderIdentity, optional SourceSha256, the InferHeadings, InferLists, InferTables and ProposeGeometricOrder switches, HeadingRatio, the MaxHeadingCharacters, MaxTableColumns and MaxTableRows caps, MaxWork and an optional CancellationToken; Default supplies the documented defaults
TPdfOcrSemanticProposalContains ProposalID, caller-asserted ProviderIdentity, candidate Layout, original-index BlockOrder, a per-block Evidence: TPdfOcrSemanticEvidenceArray and an OrderReason
TPdfOcrSemanticEvidenceOriginalBlockIndex identifies the captured block; Origin: TPdfOcrSemanticOrigin is posProvider, posTextMarker, posGeometry or posReviewer; Confidence and Reason describe the candidate evidence
TPdfOcrSemanticApprovalRequires the matching ProposalID, explicit Confirmed=True, nonempty ReviewerIdentity, a complete original-index block permutation and reviewed block/table metadata
TPdfOcrReviewedLayoutReturns independent reviewed Layout, provider/reviewer/proposal identities, OriginalBlockOrder and remapped evidence, suitable for the existing structured-text and reflow builders

The default heading heuristic compares accepted word heights with their page median using HeadingRatio=1.4 and a 160-character limit; bullet or enumeration prefixes suggest list items, and aligned runs of separate one-line blocks can suggest rectangular tables with first-row header candidates

Existing provider table grids are validated even when unreviewed, then exposed with Reviewed=False; proposed grids and first-row headers require a new explicit decision rather than inheriting approval from provider metadata

The default retains source reading order; opt-in ProposeGeometricOrder suggests top-to-bottom/left-to-right order while keeping physical regions and tables grouped, and does not infer arbitrary column, language or author-intent semantics

Candidate confidence is the minimum accepted source-word confidence capped at 0.8 for marker inference, 0.7 for heading inference and 0.65 for table inference; these heuristic scores are not calibrated recognition or semantic probabilities

Pass the review decision to Review.Apply(Approval); it preserves source word text/geometry and block line ownership, permits explicit role/level/language and table edits, and remaps words, lines, table cells and region partitions to the approved reading order

Every supplied table must have Reviewed=True; omit rejected table candidates from the approval, and retain complete nonoverlapping grid/line coverage for accepted tables, including empty cells and supported spans

Duplicate/missing block order, stale or foreign proposal IDs, changed line ownership, split table/region ranges and reversed lines within one cell reject with EPdfOcrLayout; neither the caller's layout nor the private review snapshot changes

A proposal ID identifies one live immutable review snapshot; retain that review instance until approval is applied, and do not use the ID as a saved-PDF hash or native object identity

Since v3.271.0, optional TPdfOcrSemanticReviewOptions.SourceSha256 captures the SHA-256 of the exact saved PDF being reviewed, validates its 64 hexadecimal characters and normalizes it to lowercase in both Proposal.SourceSha256 and TPdfOcrReviewedLayout.SourceSha256; pure layout/reflow review can leave it empty, while native binding requires it

Provider and reviewer identities are caller assertions retained as provenance, not authenticated identities; the approved layout still has no native character/object binding and does not itself create Tagged PDF or certify accessibility

Semantic options reuse LayoutOptions budgets, default to 32 table columns, 1024 rows and a MaxWork of 67108864 charged work units, and support an optional CancellationToken; table limit ranges are 2..1024 columns and 2..65536 rows, MaxWork is 1..1073741824, heading characters are 1..65536 and the finite heading ratio must be greater than 1 and at most 10

ReviewOptions := TPdfOcrSemanticReviewOptions.Default;
ReviewOptions.ProviderIdentity := ProviderAndModelIdentity;
Review := TPdfOcrSemanticReview.Create(PageLayout, ReviewOptions);
try
  Proposal := Review.Proposal;
  // Present the proposal for review and fill Approval from that decision
  // Approval uses original block indexes and the matching Proposal.ProposalID
  Approval.Confirmed := UserConfirmed;
  Approval.ReviewerIdentity := ReviewerIdentity;
  if UserConfirmed then
  begin
    Reviewed := Review.Apply(Approval);
    Reflow := BuildPdfOcrReflowDocument(Reviewed.Layout,
      ReviewOptions.LayoutOptions, TPdfReflowOptions.Default);
  end;
finally
  Review.Free;
end;

Exact saved-source native bindings

function BindPdfOcrReviewedSource(Source: TStream;
  const Reviewed: TPdfOcrReviewedLayouts;
  const Options: TPdfOcrBindingOptions;
  out Binding: TPdfOcrSourceBinding;
  out Report: TPdfOcrBindingReport): Boolean;

Since v3.271.0, this helper snapshots a seekable source from byte zero, restores its original position, verifies every reviewed page's captured SourceSha256 against those exact bytes and loads an independent document in strict mode with lifecycle actions disabled

Set the source hash on the semantic-review options before constructing the review, using the saved PDF that will be supplied for binding; resaving changes the byte identity and requires a new source-bound review even when the visible page is unchanged

Type or fieldContract
TPdfOcrSourceBindingOwns exact SourceBytes, their SourceSha256, independently copied Reviewed layouts and Words: TPdfOcrWordBindings
TPdfOcrWordBindingReviewIndex and WordIndex are zero-based indexes into the returned reviewed layouts and words; PageNumber is one-based; ObjectIndex is the native zero-based top-level page-object ordinal; PageQuad records the actual native word quadrilateral in page coordinates
TPdfOcrBindingOptionsCarries LayoutOptions, optional Password, MaxSourceBytes, MaxPages, MaxObjects, MaxWords, MaxTextCharacters, MaxLayoutItems, MaxWork, CoordinateTolerance and an optional CancellationToken; Default supplies the documented budgets
TPdfOcrBindingReportReports Succeeded, Cancelled, SourceSha256, ErrorMessage, BoundWordCount, FilteredWordCount, InspectedObjectCount, ReviewTextCharacters, NativeTextCharacters, NativeCharacterCount, FailedPageNumber/FailedWordIndex and charged Work

Binding requires a unique invisible native text object for each above-threshold word, exact owned Unicode text and agreement between all four native corners and the captured affine OCR geometry, including native device rounding, page rotation and CropBox

Native character inventories may expose supplementary Unicode as full code points or paired UTF-16 units; binding validates the reconstructed owned word and retains real spaces while excluding generated separators, and missing/zero or malformed native mappings still reject

Since v3.275.0, the OCR search-layer writer selects CID charcodes from complete Unicode characters in its cached font map, so an appropriate selected font can preserve supplementary text through actual insertion, saving, native binding and tagged output

Binding still validates the exact saved layer rather than repairing a missing font mapping; unsupported glyph coverage, unavailable native CID/charcode APIs, malformed UTF-16 and NUL reject explicitly, with current-page insertion rollback on failure or cancellation

Native object text getters can include page-generated separators, so the helper reconstructs word text only from actual nongenerated native characters owned by that object; it preserves real word spaces and does not trim or normalize the requested text

The page character model can suppress overlapping duplicates, so every invisible native object participates in quadrilateral uniqueness checks, including objects with no assigned characters; coincident objects reject instead of selecting whichever one retained extracted characters

Missing words, mismatched text/geometry, duplicate ownership, altered source maps/dimensions, repeated pages, malformed review provenance, absent inspection exports and exhausted budgets return False with an empty binding and an explicit report; cancellation likewise publishes no partial binding

Below-threshold words have no binding and increment FilteredWordCount; accepted Artifact words still have physical bindings so a later tag plan can classify their actual objects explicitly

Defaults are 64 MiB MaxSourceBytes, 4096 total source/reviewed pages, 100000 inspected objects on reviewed pages, 100000 reviewed words, 262144 cumulative layout items, 4194304 combined reviewed-text/native-character/native-owned-text units, a MaxWork of 67108864 charged work units and a 0.05 point CoordinateTolerance

Maximum options are 512 MiB source bytes, 10000 pages, 1000000 objects/words/layout items, 16777216 combined text units and 1073741824 charged work units; tolerance accepts finite 0.0001..1 point values, and indexed native word origins must be within +/-1000000000 points

Set Password for native-supported encrypted reads; credentials are limited to 4096 UTF-16 units with valid Unicode and no NUL, are not retained in the binding/report, and do not authorize writing an encrypted or signed source

Cancellation is cooperative outside native calls and accepted-data limits do not impose a native parser allocation or execution-time ceiling; callers must keep inputs stable during the call and synchronize their own custom cancellation interfaces

Object ordinals belong to the exact source snapshot and native runtime, not an independently loaded or edited caller document; rebind after resaving or replacing the engine, and verify source identity and ownership again before any later edit

This API establishes top-level object ownership without inventing native character-selection indexes; it does not itself create structure tags or establish arbitrary font/script support, recognition accuracy or accessibility conformance

The added managed source-hash fields and binding types require rebuilding clients, packages and generated C++ headers together

Preprocessing and source geometry

Set Options.Preprocessor to an IPdfOcrImagePreprocessor whose PrepareImage returns a bounded BGRA image and an explicit TPdfOcrImageMap from prepared pixels back to original rendered pixels

The map uses x' = A*x + C*y + E and y' = B*x + D*y + F; TPdfOcrImageMap.Map applies that transform to one TPdfOcrPoint, and TPdfOcrImageMap.Identity supplies an unchanged transform

Scaling, cropping and rotation are provider responsibilities; nonfinite/singular maps, changed page identity, invalid buffers and out-of-source word geometry reject before search-layer insertion

The workflow captures the native FPDF_DeviceToPage transform for the original rendered page, including intrinsic rotation and CropBox, and exposes it as ImageToPage; word geometry follows the existing native integer device-coordinate rounding and affine text-object placement

Perspective-dependent word quads and words that collapse under native rounding reject; preprocessing changes recognition input while the original page image remains in the PDF

Results and conversions

Since v3.257.0, optional TPdfOcrPageLayout.Regions groups paragraph Blocks into physical provider regions. Each TPdfOcrRegion contains FirstBlock and BlockCount; nonempty regions must partition every paragraph block exactly once in provider order. An empty region array retains compatibility with existing providers

Tesseract native layout supplies lines, paragraph blocks and physical regions through the optional structured interface. Region ownership is validated before native insertion, contributes to the layout item budget and is copied independently in returned page layouts. Conversions preserve paragraph order; physical segmentation does not assign reviewed heading, list or table semantics

The added public record fields require rebuilding clients and runtime packages together, including regenerated DCUs, PPUs and C++ headers when upgrading

Report.SearchLayer retains the existing per-page success, failure, cancellation and inserted/rejected-word diagnostics; Report.Pages (TPdfOcrPageLayouts) includes independently owned layouts only for pages whose search-layer insertion completed

Report.PreprocessedPixels records accepted prepared-image pixels; rendered and prepared pixel totals share SearchLayer.MaxTotalPixels, and each image also obeys MaxPixelsPerPage

Both conversion helpers omit below-threshold words and reviewed Artifact blocks, preserve provider block order and use captured page coordinates; neither helper changes the PDF or the caller's layout

Structured spans report SourceStartIndex=-1 and zero native source-character count, and the page reports all returned characters as unmapped: recognition results do not establish native character-index or selection ownership

Reflow converts headings and consecutive list items, and optionally emits reviewed tables with row/column spans and header cells; ToHtml uses the existing escaped HTML serializer

OCR hierarchy remains rosHeuristic in the shared models and does not imply Tagged PDF, automatic accessibility certification or automatic native reader-selection bindings

Budgets and failure behavior

TPdfStructuredOcrOptions.Default uses the existing search-layer defaults, no preprocessor, 262144 layout items, 1048576 source/metadata text units and 65536 cumulative reviewed grid slots per page

Layout items are words, lines, blocks, regions, tables and cells combined; MaxLayoutItems accepts 1..1048576, MaxLayoutCharacters accepts 1..16777216 and MaxTableGridSlots accepts 1..1048576

Reflow also enforces its own character, node, table and cell limits; builders return a complete staged result or raise EPdfOcrLayout

Cancellation is cooperative across rendering, preprocessing and provider calls; provider/native internal allocation and execution time are not universally interrupted by these accepted-data budgets

Per-page rejection leaves that page without new OCR objects; completed earlier pages retain the existing search-layer partial-success policy, including ContinueOnError

Providers must not mutate the source document reentrantly; native document/page replacement during a callback rejects, while arbitrary external callback changes remain caller-owned

uses FPdfOcrLayout;

Options := TPdfStructuredOcrOptions.Default;
if ApplyPdfStructuredOcr(Pdf, Provider, Options, Report) and
   (Length(Report.Pages) > 0) then
begin
  Page := BuildPdfOcrStructuredText(Report.Pages[0], Options);
  Reflow := BuildPdfOcrReflowDocument(Report.Pages[0], Options,
    TPdfReflowOptions.Default);
  Html := Reflow.ToHtml;
end;

Check Length(Report.Pages) before indexing when pages can be skipped for existing text or when recognition returns no successful page