Inferensys

Prompt

Reading Order Recovery Prompt for Complex PDF Layouts

A practical prompt playbook for recovering the intended human reading order from complex PDF layouts with sidebars, pull quotes, and inset boxes in production AI document pipelines.
Wide-angle shot of a modern WeWork open floor plan with creative walls covered in AI system architecture diagrams, product team collaborating in standing desk area with industrial lighting.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for reading order recovery in complex document layouts.

This prompt is designed for document ingestion engineers who need to recover the intended human reading order from PDFs with mixed layouts—documents containing multi-column body text, sidebars, pull quotes, inset boxes, and callout regions. The job-to-be-done is converting a set of visually positioned text blocks into a single linear text sequence that preserves the author's intended narrative flow. This is a layout-correction step that sits between raw text extraction and downstream tasks like chunking, embedding, or structured extraction. Without reading order recovery, multi-column documents produce interleaved garbage that silently corrupts retrieval quality and breaks any pipeline that assumes coherent paragraph sequences.

Use this prompt when your PDF extraction pipeline produces text blocks with positional metadata (bounding boxes, page coordinates, column hints) but the raw extraction order is wrong. The prompt requires inputs that include the extracted text blocks, their page positions, and any available layout classification labels (e.g., 'body', 'sidebar', 'header', 'callout'). You should also provide the expected output schema—typically a JSON array of text blocks in corrected reading order with their original positions preserved for traceability. The prompt works best with models that can reason spatially and follow strict ordering constraints. It is not a replacement for a layout parser; it is a correction layer that applies human reading conventions to already-extracted regions.

Do not use this prompt when the document has a single, uninterrupted text flow with no layout complexity—simple left-to-right, top-to-bottom extraction is sufficient and cheaper. Do not use it when you lack positional metadata; the model cannot recover reading order from plain text alone. Do not use it as a substitute for OCR or text extraction; it operates on already-extracted blocks. For documents where reading order is genuinely ambiguous (e.g., artistic layouts, infographics, or documents where multiple valid reading paths exist), flag the output as uncertain and route for human review rather than forcing a single linearization. The next step after reading order recovery is typically validation against known failure modes: sidebar text interrupting body flow, callout text placed before its anchor paragraph, and footnotes separated from their referents.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Reading Order Recovery Prompt delivers value, where it breaks, and the operational prerequisites for production use.

01

Good Fit: Multi-Column Reports

Use when: Documents have a predictable two- or three-column layout with clear vertical separators. The prompt excels at re-sequencing text that naive text extraction interleaves line-by-line. Guardrail: Pre-process with layout detection to confirm column count before invoking the prompt.

02

Good Fit: Sidebar-Heavy Content

Use when: PDFs contain callout boxes, pull quotes, or inset definitions that must be anchored to their correct position in the body flow. Guardrail: Require the prompt to output explicit anchor markers so downstream systems can verify sidebar placement against the main text.

03

Bad Fit: Magazine-Style Freeform Layouts

Avoid when: Documents use overlapping text, irregular text wrapping around images, or non-rectangular text regions. The prompt lacks spatial reasoning for arbitrary layout geometry. Guardrail: Route such documents to a specialized vision model or flag for manual review before extraction.

04

Bad Fit: Scanned Handwritten Notes

Avoid when: The source is a degraded scan with handwriting, marginalia, or stamps that OCR has already garbled. The prompt cannot recover reading order from corrupted input. Guardrail: Apply OCR confidence thresholds upstream and reject pages below the quality floor before they reach the reading-order step.

05

Required Inputs

Must provide: Raw extracted text blocks with bounding box coordinates or page-position metadata. Without spatial hints, the prompt guesses reading order from text content alone, which fails on ambiguous layouts. Guardrail: Validate that every text block passed to the prompt includes page number and y-position at minimum.

06

Operational Risk: Silent Misordering

Risk: The prompt produces fluent, plausible output even when reading order is wrong. Downstream chunking and retrieval systems ingest corrupted text without detecting the error. Guardrail: Implement a deterministic post-check that verifies no paragraph is split across non-adjacent source blocks and that sidebar text appears near its anchor.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for recovering the intended human reading order from documents with mixed layouts, sidebars, and callout boxes.

The following prompt template is designed to be dropped into your document processing pipeline when you need to linearize complex PDF layouts into a single, coherent text stream. It expects pre-extracted text blocks with positional metadata—typically the output of a PDF parser or OCR engine that provides bounding box coordinates, page numbers, and font size hints. The prompt instructs the model to reconstruct the author-intended reading order, not the raw extraction order, which is critical for downstream tasks like chunking, summarization, and retrieval-augmented generation where interleaved column text or misplaced callout boxes silently corrupt results.

text
You are a document layout analyst. Your task is to reconstruct the intended human reading order from a set of text blocks extracted from a PDF page with a complex layout.

## INPUT
You will receive a JSON array of text blocks. Each block has:
- `block_id`: unique identifier
- `text`: the text content of the block
- `page`: page number
- `bbox`: bounding box coordinates [x0, y0, x1, y1] in points, where (0,0) is the top-left corner of the page
- `font_size`: approximate font size in points
- `font_style`: one of ["bold", "italic", "regular"]

[INPUT]

## CONTEXT
This document is a [DOCUMENT_TYPE] with the following layout characteristics:
[LAYOUT_DESCRIPTION]

Known layout features to account for:
[LAYOUT_FEATURES]

## INSTRUCTIONS
1. Analyze the spatial arrangement of all text blocks on each page.
2. Identify the main body text flow. In multi-column layouts, read the left column completely before starting the right column, unless visual cues indicate otherwise.
3. Identify sidebars, pull quotes, callout boxes, and inset text. These are typically offset from the main flow, have different font sizes or styles, or are enclosed in visible borders.
4. For each sidebar or callout, determine its anchor point in the main body text—the paragraph or sentence it relates to. Place the sidebar content immediately after its anchor paragraph, enclosed in [SIDEBAR_START] and [SIDEBAR_END] markers.
5. Place footnotes immediately after the paragraph containing their reference marker, enclosed in [FOOTNOTE_START] and [FOOTNOTE_END] markers.
6. Headers and footers that repeat across pages should be included only once, at the start or end of the document respectively, unless they contain page-specific information like section titles.
7. Preserve all original text exactly. Do not paraphrase, summarize, or modify wording.

## OUTPUT SCHEMA
Return a JSON object with this structure:
{
  "pages": [
    {
      "page_number": 1,
      "reading_order": [
        {
          "sequence": 1,
          "block_id": "b1",
          "content_type": "body_text" | "sidebar" | "callout" | "footnote" | "header" | "footer",
          "text": "exact text content",
          "anchor_block_id": null | "b3"
        }
      ]
    }
  ],
  "global_reading_order": "full concatenated text with markers",
  "uncertain_regions": [
    {
      "page": 1,
      "block_ids": ["b5", "b6"],
      "reason": "ambiguous column boundary"
    }
  ]
}

## CONSTRAINTS
[CONSTRAINTS]

## EXAMPLES
[EXAMPLES]

## RISK LEVEL
[RISK_LEVEL]

To adapt this template, replace the square-bracket placeholders with your specific document context. The [DOCUMENT_TYPE] should describe the document category—such as "legal contract," "academic paper," or "financial report"—which helps the model apply domain-appropriate layout conventions. The [LAYOUT_DESCRIPTION] and [LAYOUT_FEATURES] fields are where you specify known structural elements: single-column vs. multi-column, presence of sidebars, typical callout box placement, and whether footnotes appear at page bottom or document end. The [CONSTRAINTS] placeholder should include any domain-specific rules, such as "never reorder clauses in a contract" or "preserve equation numbering sequence." The [EXAMPLES] placeholder is critical for few-shot performance—provide at least two annotated page examples showing correct reading order resolution for your document type. The [RISK_LEVEL] field should be set to "high" for legal, medical, or financial documents where ordering errors could change meaning, triggering downstream human review requirements.

When integrating this prompt into a production pipeline, always validate the output against the original block count to ensure no text was dropped during reordering. Run a spot-check eval comparing the global_reading_order field against a human-annotated ground truth for at least 20 representative pages from your document corpus. Pay particular attention to uncertain_regions—these are the model's explicit signals that it encountered ambiguous layout boundaries, and they should trigger either a human review step or a higher-confidence re-extraction pass with additional spatial context. For high-risk document types, never ship the linearized output directly to downstream consumers without first logging the uncertainty regions and, where feasible, routing pages with unresolved ambiguities for manual verification.

IMPLEMENTATION TABLE

Prompt Variables

Required and optional inputs for the Reading Order Recovery Prompt. Each placeholder must be populated before the prompt is assembled and sent to the model. Validation notes describe how to check input quality before execution.

PlaceholderPurposeExampleValidation Notes

[PAGE_TEXT_BLOCKS]

Raw text blocks extracted from a single PDF page, each with bounding box coordinates and font metadata

{"blocks": [{"text": "Introduction", "bbox": [72, 100, 200, 115], "font_size": 14, "font_weight": "bold"}]}

Must be valid JSON array. Each block requires text, bbox with 4 numbers, and font_size. Reject if bbox coordinates are negative or text is null

[PAGE_NUMBER]

The page number this content belongs to, used for error tracing and multi-page continuity checks

42

Must be a positive integer. Null allowed only for single-page documents. Reject if negative or zero

[LAYOUT_HINTS]

Optional pre-classified zone types for each block to guide reading order when layout is ambiguous

{"block_0": "body", "block_1": "sidebar", "block_2": "pull_quote"}

If provided, must map block indices to valid zone types: body, sidebar, pull_quote, header, footer, footnote, caption, callout. Unknown zone types should trigger a warning but not block execution

[DOCUMENT_TYPE]

The document category to bias reading order heuristics for domain-specific conventions

legal_contract

Must be one of: legal_contract, academic_paper, news_article, technical_manual, financial_report, general. Reject unrecognized values. Use general as fallback

[PREVIOUS_PAGE_LAST_BLOCK]

The text of the last block from the previous page to detect cross-page paragraph continuations

and therefore the parties agree to the following terms:

Null allowed for first page. If provided, must be a non-empty string. Truncate to 500 characters max to avoid context pollution

[NEXT_PAGE_FIRST_BLOCK]

The text of the first block from the next page to detect cross-page paragraph continuations

Section 4.2 outlines the termination procedures.

Null allowed for last page. If provided, must be a non-empty string. Truncate to 500 characters max

[OUTPUT_FORMAT]

Specifies whether the output should be plain text, JSON with block ordering, or annotated text with source block references

json_with_sources

Must be one of: plain_text, json_ordered_blocks, json_with_sources. Reject unrecognized values. json_with_sources is recommended for downstream traceability

[CONFIDENCE_THRESHOLD]

Minimum confidence score for the reading order decision before flagging a region for human review

0.85

Must be a float between 0.0 and 1.0. Default to 0.85 if not provided. Values below 0.7 increase false-positive flags; values above 0.95 may suppress legitimate uncertainty signals

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the reading order recovery prompt into a document ingestion pipeline with validation, retry, and human review.

The reading order recovery prompt is a post-extraction correction step, not a raw text extractor. It expects already-extracted text blocks with positional metadata (bounding boxes, page numbers, and region labels) as input. The typical pipeline flow is: raw PDF → layout detection → text extraction per region → reading order recovery → downstream chunking or structured extraction. Do not feed raw PDF bytes or OCR output directly into this prompt; the model needs spatial context to reason about reading order.

Validation is mandatory before downstream consumption. After the prompt returns a linearized text sequence, run at least three checks: (1) Continuity check — verify that no extracted text block was dropped by comparing input block count to output coverage. (2) Anchor proximity check — confirm that callout boxes, sidebars, and footnotes appear within a configurable token window of their anchor text in the main body. (3) Page boundary integrity — ensure text from page N does not appear before text from page N-1 unless the document layout explicitly requires it (e.g., a sidebar that references a previous page). Log all validation failures with the specific block IDs and page coordinates that triggered them.

Retry logic should be bounded and diagnostic. If validation fails, construct a retry prompt that includes the original input plus the specific validation error messages and the IDs of the offending blocks. Limit retries to two attempts. On the second failure, route the document to a human review queue with the original layout visualization, the model's two attempts, and the validation report. Do not silently accept a partially-correct reading order — downstream chunking and retrieval quality depend on correct linearization, and corrupted reading order is a silent data quality failure that compounds through the pipeline.

Model selection matters for this task. Use a model with strong spatial reasoning and long-context handling (e.g., GPT-4o, Claude 3.5 Sonnet, or Gemini 1.5 Pro). Smaller or older models frequently misorder multi-column text and place callout content at arbitrary positions. If processing high-volume document streams, consider a tiered approach: use a fast, cheaper model for simple single-column documents (validated by a layout classifier upstream) and route complex multi-column or mixed-layout documents to a more capable model with this prompt.

Log everything for observability. For each document processed, record: the layout zone count, the model used, the number of retry attempts, validation pass/fail status, and the human review outcome if escalated. This data lets you measure the prompt's real-world accuracy, identify document types that consistently fail, and build a regression test suite from production failures. When you update the prompt template, replay the logged failure cases first.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the shape, types, and validation rules for the linearized reading order output. Use this contract to build downstream parsers and evaluation checks.

Field or ElementType or FormatRequiredValidation Rule

reading_order

array of objects

Array must contain at least 1 element. Each element must match the block schema below.

reading_order[].block_id

string

Must be unique within the array. Format: block-[integer].

reading_order[].sequence_index

integer

Must be a zero-indexed, monotonically increasing integer with no gaps.

reading_order[].text

string

Must not be empty. Must not contain unresolved OCR artifacts like repeated special characters.

reading_order[].source_region

string

Must be one of: body, sidebar, callout, header, footer, footnote, table_cell, abstract, caption.

reading_order[].anchor_block_id

string or null

If source_region is sidebar or callout, must reference a valid body block_id. Otherwise null.

reading_order[].confidence

number

Float between 0.0 and 1.0. Values below 0.7 must trigger a human review flag in the application layer.

reading_order[].page_number

integer or null

If provided, must be a positive integer. Null allowed for documents without page metadata.

PRACTICAL GUARDRAILS

Common Failure Modes

Reading order recovery fails in predictable ways. These are the most common production failure modes and how to guard against them before they corrupt downstream chunking, retrieval, and extraction.

01

Sidebar Text Interrupts Body Flow

What to watch: Sidebar or callout text gets spliced mid-paragraph into the main body, breaking sentence continuity. This happens when the model treats spatial proximity as reading order. Guardrail: Require the prompt to output body text and sidebar text as separate sequences with explicit anchor markers showing where the sidebar references the main flow. Validate that no body paragraph contains a sentence fragment from a sidebar.

02

Callout Text Placed Before Its Anchor

What to watch: Pull quotes, warnings, or inset boxes appear before the paragraph that introduces them, misleading downstream summarization about what was stated first. Guardrail: Add a post-extraction check that compares the position of callout anchor phrases in the body text against the callout's placement in the recovered sequence. Flag any callout that precedes its first body-text reference by more than one paragraph.

03

Multi-Column Interleaving at Page Transitions

What to watch: At page breaks, the model continues reading across columns on the next page instead of finishing the current column first, producing garbled text that jumps between unrelated topics. Guardrail: Instruct the prompt to process each column to completion before advancing to the next page. Validate output by checking that the last sentence of a column on page N connects semantically to the first sentence of the same column on page N+1.

04

Headers and Footers Merged into Body Text

What to watch: Running headers, page numbers, and section titles in margins get absorbed into body paragraphs, contaminating chunk text with repeated boilerplate. Guardrail: Pre-process with a layout zone classifier before reading order recovery. Strip or tag header/footer regions explicitly. In the prompt, require the model to omit repeated running text that appears at identical positions across consecutive pages.

05

Table Text Flattened into Surrounding Paragraphs

What to watch: Table cells get linearized into the body text stream, making it impossible to distinguish tabular data from prose. Numbers appear mid-sentence without column context. Guardrail: Require the prompt to output tables as structured blocks with row and column markers, not as linear text. Validate that no numeric sequence matching a known table pattern appears inside a body paragraph in the output.

06

Footnote Text Injected at Detection Point Instead of Reference Point

What to watch: Footnote content appears inline where the superscript marker was detected rather than deferred to the end of the section or page, disrupting sentence flow. Guardrail: Instruct the prompt to collect all footnotes and append them at section boundaries with their reference numbers. Validate that no sentence in the body output contains a footnote-length insertion that lacks a subject-verb structure connecting to surrounding text.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test reading order recovery output quality before shipping to production. Each criterion targets a known failure mode in complex PDF layout processing.

CriterionPass StandardFailure SignalTest Method

Body Text Continuity

Main body paragraphs appear in correct reading order without interleaved sidebar or callout text

Sidebar text appears mid-paragraph in the body flow; sentences split across non-adjacent output positions

Compare output paragraph sequence against a manually verified ground-truth reading order for a 3-page multi-column test document

Sidebar Placement

Sidebar content appears at the end of the section containing its anchor, not mid-body

Sidebar text interrupts body text before the anchor paragraph; sidebar appears in a different section than its anchor

Inject a known sidebar with explicit anchor text and verify sidebar position relative to anchor in output

Callout Anchor Order

Callout or pull-quote text appears after the paragraph it references, not before

Callout text placed before its source paragraph; callout duplicated in both body and callout positions

Use a document with numbered callouts and verify output sequence: callout N appears after body paragraph N

Multi-Column Sequence

Column 1 text completes before column 2 text begins on each page; no column bleed

Line from column 2 inserted between column 1 lines; paragraph starts in column 1 and continues in column 2 mid-sentence

Diff output against single-column linearization of a known 2-column document; flag any interleaved lines

Header and Footer Exclusion

Running headers, page numbers, and footers are excluded from body text output

Page number or header text appears as a sentence in the body flow; footer legal text mixed with last paragraph

Assert that known header/footer strings do not appear in body text output for a 5-page test document

Table Text Isolation

Table content is output as a contiguous block, not interleaved with surrounding body paragraphs

Table row text appears between body sentences; table caption separated from its table by body text

Check that all table cell text appears in a single contiguous span in output, bounded by table start and end markers

Page Break Integrity

Paragraphs that span page breaks remain contiguous in output; no duplicate text at page boundaries

Last sentence of page N repeated as first sentence of page N+1; paragraph split with unrelated content inserted at break

Verify no duplicate sentences at page transitions; check that paragraph IDs assigned before extraction remain contiguous

Footnote Association

Footnote text appears immediately after the sentence containing its reference marker

Footnote text placed at end of document instead of near reference; footnote content merged with body text without separation

Use a document with 3+ footnotes and verify each footnote appears within 2 sentences of its reference marker in output

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a frontier model (GPT-4o, Claude 3.5 Sonnet). Pass the raw text extracted from each page along with bounding box metadata. Keep the output schema simple: a flat array of text blocks with sequence numbers. Skip confidence scoring and boundary validation.

code
You are given text blocks extracted from a PDF page. Each block has [TEXT] and [BOUNDING_BOX]. Reorder the blocks into the intended human reading order. Return a JSON array of objects with "sequence" and "text" fields.

Page blocks: [BLOCKS]

Watch for

  • Sidebar text interleaved mid-paragraph in body flow
  • Callout boxes placed before their anchor paragraph
  • Headers and footers injected into body text sequence
  • No validation of output completeness against input block count
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.