Skip to content
AgenticAIWiki
  1. Learn
  2. Part 4
  3. 27. Parsing complex documents
  4. 27.1

Lesson 27.1 · 1 of 5 · 6 min read · Reviewed 24 Nov 2026

Why PDFs are hard: layout, columns and reading order

By the end, you can

  • Explain why text pulled from a PDF often comes out scrambled.
  • Spot the layout problems that will hurt retrieval before you index a document.

What a PDF actually stores

A Word file or a web page knows that a run of text is a heading, a paragraph or a table cell. A PDF usually doesn’t. At its core a PDF page is a list of drawing instructions: put these characters, in this font, at these coordinates. That is perfect for printing and poor for reading by machine.

So “extracting text” from a PDF means rebuilding the structure from positions: which characters form words, which words form lines, which lines form paragraphs, and in what order a person would read them. Some PDFs include extra tags that describe structure (tagged PDF, used for accessibility), but many don’t, and the tags are not always right.

Where it goes wrong

Problem What you see in the extracted text
Multiple columns Lines from the left and right columns interleaved
Reading order A sidebar or caption dropped into the middle of a paragraph
Headers and footers “Annual report 2025, page 14” repeated inside every chunk
Hyphenation and line breaks “reim- bursement” split into two tokens
Tables Cells flattened into a stream of numbers with no headers (27.3)
Scanned pages No text at all, because the page is only an image; you need OCR
Odd fonts and ligatures “fi” as one glyph, or characters mapped to the wrong letters

A worked example

A page has two columns:

Left column                      Right column
The refund window is             Section 3 covers
30 days from delivery.           shipping costs.

A simple extractor that reads each line from left to right gives:

The refund window is Section 3 covers
30 days from delivery. shipping costs.

Embed that as one chunkChunking: Splitting documents into smaller passages before embedding and indexing them. and the vector mixes two topics. A question about refunds may still find it, but the model now reads “the refund window is Section 3”, and the citation looks broken. A layout-aware parser (27.2) detects the columns first and reads the left column top to bottom, then the right.

Why this matters for RAG

Retrieval quality starts at parsing. If chunks contain mixed sentences, repeated footers or missing tables, no embedding modelEmbedding model: A model trained to turn text (or images) into embeddings for search and comparison, rather than to generate text. or rerankerReranking: Re-scoring an initial set of retrieved results with a more accurate model to put the best ones first. can fully recover. Teams often spend weeks tuning search when the real problem is in the first step.

A quick health check before indexing

  1. Pick five documents that look different: two-column, tables, scanned, slides exported to PDF.
  2. Extract them with your current tool and read the output.
  3. Look for interleaved lines, repeated headers, missing numbers and empty pages.
  4. Count pages with no text: they need OCR or page images (27.4).
  5. Keep the page number with every piece of text, so answers can cite it.

Common mistakes

  • Assuming “the PDF opened fine” means the text came out fine.
  • Stripping page numbers early, then being unable to cite pages later.
  • Testing the parser on one clean document and indexing thousands of messy ones.

Key points

  • A PDF stores characters and their positions on the page, not paragraphs, headings or reading order.
  • Naive extraction reads across the page line by line, so two columns get interleaved into nonsense.
  • Headers, footers, footnotes, hyphenation and tables add noise; scanned pages may have no text layer at all.
  • Check a sample of extracted text by eye before you chunk and embed it.
Hands-on labRuns in the Playground

Fix reading order on a two-column page

Rebuild reading order from word positions, the way a PDF stores text, and see why reading straight across scrambles two columns.

You will have: A script that prints the naive extraction, the column-aware extraction and the footer it removed.

Steps

  1. Read the words with their x and y positions.
  2. Naive extraction: sort by y, then x, and join each line. Print it.
  3. Detect full-width lines (title, footer) and the column split from the x positions.
  4. Column-aware extraction: title first, then the left column top to bottom, then the right column.
  5. Drop the footer line that matches a page-number pattern and print what you removed.

Done when

  • The naive output contains 'The refund window is Section 3 covers'.
  • The column-aware output contains 'The refund window is 30 days from delivery.' as one run.
  • The footer 'Annual report, page 4' is removed and printed as dropped.

Open in the Playground No API key needed.

Starter code (Python)
# Words as a PDF stores them: (x, y, text). y grows down the page. Two columns split at x = 300.
WORDS = [
    (72, 60, "Refund"), (130, 60, "policy"),
    (72, 100, "The"), (100, 100, "refund"), (150, 100, "window"), (205, 100, "is"),
    (320, 100, "Section"), (380, 100, "3"), (395, 100, "covers"),
    (72, 115, "30"), (95, 115, "days"), (130, 115, "from"), (165, 115, "delivery."),
    (320, 115, "shipping"), (385, 115, "costs,"), (430, 115, "paid"),
    (72, 130, "Worn"), (115, 130, "items"), (155, 130, "only"), (190, 130, "if"), (205, 130, "faulty."),
    (320, 130, "by"), (340, 130, "the"), (365, 130, "buyer."),
    (72, 780, "Annual"), (125, 780, "report,"), (180, 780, "page"), (215, 780, "4"),
]

import re

def naive(words):
    lines = {}
    for x, y, t in sorted(words, key=lambda w: (w[1], w[0])):
        lines.setdefault(y, []).append(t)
    return [" ".join(ws) for ws in lines.values()]

def by_column(words, split=300):
    # TODO: return (text, dropped_footer). Full-width lines are those with words only left of
    # split that sit above the body (title) or near the bottom (footer). Left column, then right.
    return "", None

print("NAIVE:")
for line in naive(WORDS):
    print("  " + line)
print("BY COLUMN:", by_column(WORDS))
Show a solution
# Words as a PDF stores them: (x, y, text). y grows down the page. Two columns split at x = 300.
WORDS = [
    (72, 60, "Refund"), (130, 60, "policy"),
    (72, 100, "The"), (100, 100, "refund"), (150, 100, "window"), (205, 100, "is"),
    (320, 100, "Section"), (380, 100, "3"), (395, 100, "covers"),
    (72, 115, "30"), (95, 115, "days"), (130, 115, "from"), (165, 115, "delivery."),
    (320, 115, "shipping"), (385, 115, "costs,"), (430, 115, "paid"),
    (72, 130, "Worn"), (115, 130, "items"), (155, 130, "only"), (190, 130, "if"), (205, 130, "faulty."),
    (320, 130, "by"), (340, 130, "the"), (365, 130, "buyer."),
    (72, 780, "Annual"), (125, 780, "report,"), (180, 780, "page"), (215, 780, "4"),
]

import re

def naive(words):
    lines = {}
    for x, y, t in sorted(words, key=lambda w: (w[1], w[0])):
        lines.setdefault(y, []).append(t)
    return [" ".join(ws) for ws in lines.values()]

def by_column(words, split=300):
    rows = {}
    for x, y, t in words:
        rows.setdefault(y, []).append((x, t))
    body_ys = [y for y, ws in rows.items() if any(x >= split for x, _ in ws)]
    top, bottom = min(body_ys), max(body_ys)
    title = [y for y in rows if y < top]
    footer = [y for y in rows if y > bottom]
    line = lambda ws: " ".join(t for _, t in sorted(ws))
    left = [line([w for w in rows[y] if w[0] < split]) for y in sorted(body_ys)]
    right = [line([w for w in rows[y] if w[0] >= split]) for y in sorted(body_ys)]
    dropped = [line(rows[y]) for y in footer if re.search(r"page \d+", line(rows[y]))]
    parts = [line(rows[y]) for y in sorted(title)] + [" ".join(left), " ".join(right)]
    return parts, dropped

print("NAIVE:")
for l in naive(WORDS):
    print("  " + l)
parts, dropped = by_column(WORDS)
print("BY COLUMN:")
for p in parts:
    print("  " + p)
print("dropped footer:", dropped)
Quick checkChunks from a two-column research report read like 'The refund window is Section 3 covers 30 days from delivery shipping costs'. What is the most likely cause?
How sure are you?
Pick an answer and how sure you are