05.2 Parsing PDFs
A PDF is the most common document format your ingestion pipeline will meet, and the one that lies to you most often. It looks like a document — pages, paragraphs, tables, a table of contents — but it is really a list of drawing instructions: "put glyph 37 at coordinates (72, 640) in font F1 at size 11". There is no paragraph, no heading, no table and often no reliable reading order inside the file. Everything you want — text, structure, tables, images — has to be reconstructed from those instructions, and how well you do it decides whether your retrieval system finds the right chunk or hallucinates around a flattened table. This lesson is the complete engineering guide to getting text out of PDFs: what the format actually contains, every mainstream parser and what it is good at, the layout problems that break naive extraction, tables, figures, structure recovery, the layout-aware and hosted alternatives, sending PDFs to a vision-language model instead, and a production parsing function with fallbacks that routes each page to the right tool.
What you'll learn
- What a PDF really is: objects, content streams, glyphs, fonts and encodings,
ToUnicodemaps, tagged PDFs, forms, annotations, attachments, metadata and outlines — and why none of it is a "document" in the sense your code wants - The born-digital vs scanned distinction, and how to detect which you are holding before you choose a parser
- The extraction toolbox in depth:
pypdf,pdfminer.six,pdfplumber, PyMuPDF (and its AGPL/commercial licence),pypdfium2, Poppler'spdftotext, and Camelot for ruled tables — with exact APIs, dated versions and licences - Every classic layout failure — reading order, columns, headers and footers, hyphenation, ligatures, rotated and RTL text, hidden text — with detection and fix strategies
- Tables: why they break, ruled vs unruled detection, extraction options, and how to represent a table so an LLM reads it correctly
- Images, charts and figures: extraction, captions, describing them with a VLM, and when to skip them
- Structure recovery: headings from font heuristics, outlines, lists, links, and page/bounding-box provenance for citations
- Layout-aware pipelines (Docling, Unstructured, marker, MinerU, MarkItDown) and hosted parsers (LlamaParse, Mistral OCR, Google Document AI, Azure AI Document Intelligence, AWS Textract) — verified versions, licences and pricing structure as of November 2026
- Sending PDFs and page images to an LLM for faithful transcription: cost model, prompt design, hallucination and omission risks, batch processing, and the hybrid strategy that escalates only hard pages
- A complete
ParsedDocumentdata model and a productionparse_pdffunction with per-page fallbacks, error isolation and quarantine
What you don't need
- Any API keys. Every classical parser here is pure Python or a CLI; the VLM section is labelled provider sample and its outputs are illustrative. You can learn and practise everything except the final model calls for free.
- A background in PDF internals. The format section assumes only that you have opened a PDF before.
- OCR engines. Scanned-document OCR is lesson 05.4; this lesson hands off to it at the boundary.
Setup
The samples need Python 3.11+ and uv. First time? Run uv init pdf-parsing --bare --python 3.13 && cd pdf-parsing (or see lesson 03.1, Part 4), then:
uv add pypdf pdfminer.six pdfplumber pypdfium2 pydantic reportlab
# or: pip install pypdf pdfminer.six pdfplumber pypdfium2 pydantic reportlabThe samples were written and checked against the versions in the table in 2.1 (verified on PyPI as of November 2026). A plain install gives you the newest release, which for pypdf is already the 7.x line, so read the Going-deeper note in 2.2 before you compare output; a newer major version of any library may change names, so check its changelog if something does not match. Add the optional tools only when their section needs them:
uv add pymupdf # AGPL-3.0 / commercial licence — read 2.5 first
uv add docling # heavy: downloads ML models on first run
uv add "unstructured[pdf]" # needs poppler-utils + tesseract on the system
uv add "markitdown[pdf]"
uv add "camelot-py[ml]" # [ml] pulls PyTorch for the neural flavour
uv add marker-pdf # needs PyTorch; slow on CPUTwo system tools are worth having:
brew install poppler # macOS: gives you pdftotext, pdfinfo, pdftoppm
sudo apt-get install poppler-utils # Debian/UbuntuWhat you must be able to do after this lesson#
- Explain what a PDF contains and why it is not a document
- Detect whether a PDF is born-digital or scanned
- Extract text with a suitable library
- Fix common layout problems such as columns and headers
- Return parsed pages in a ParsedDocument model
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "The PDF has no text layer — it's just scans." | 1.5 Born-digital vs scanned |
| "Extraction garbled the two-column layout." | 3.1 Reading order |
| "The header is in every chunk." | 3.2 Columns, headers, footers and page numbers |
| "The table came out as a wall of numbers." | Part 4: Tables |
| "Just send the PDF to GPT and ask for markdown." | Part 8: Sending PDFs to an LLM |
| "PyMuPDF is fastest — why not use it everywhere?" | 2.5 PyMuPDF |
| "Our invoices are forms — where are the field values?" | 1.4 Structure that helps you and 3.5 Forms and special content |
| "We need page numbers for citations." | 6.4 Page numbers and bounding boxes as provenance |
| "Docling handled the whole corpus." | Part 7: Layout-aware pipelines |
| "OCR the scanned contracts folder." | 10.2 The complete function — the handoff to 05.4 |
Part 1: What a PDF actually is#
1.1 A page-description format, not a document format#
When you write a .docx or .md file, the file is the document: a heading is a heading, a paragraph is a paragraph, a table has rows and cells. A PDF is different. It is a page-description format: the file tells a renderer (Acrobat, Preview, your browser's PDF viewer, or a printer) how to paint each page, and nothing more. The "document" you see is reconstructed on screen from those painting instructions every time it is displayed.
The core unit is the glyph: a shaped character from a font, placed at a position on the page. A page's text is not stored as sentences or paragraphs. It is stored as a sequence of operations in a content stream — a small program per page that says things like:
BT /F1 11 Tf 72 640 Td (Welcome to the handbook) Tj ETwhich reads as "begin text, select font F1 at size 11, move to position (72, 640), draw the string, end text". The string Welcome to the handbook may appear in the file exactly like that — or it may appear as a run of character codes like (\000\001\002) that only make sense through the font's encoding table. The renderer knows which glyph each code maps to; naive text extraction has to reproduce that mapping itself.
Three consequences follow, and they explain almost every extraction failure you will ever see:
- There is no reading order. The content stream can place text in any order — a two-column page may store the entire left column, then the right column, or worse, interleave them line by line. The order text appears in the file is the order it was written, which is often not the order a human reads.
- There are no paragraphs, headings or lists. A "heading" is just text drawn in a bigger font. A "list item" is text preceded by a drawn bullet glyph (often a
•character or a vector shape). A "table" is text and drawn lines placed at coordinates — sometimes with ruling lines, sometimes with nothing but whitespace. - Text may not be text at all. A scanned page is a single image per page. A page can mix real text with images of text. Vector graphics (logos, charts, diagrams) contain no text whatsoever.
Lesson 03.6 builds a minimal valid PDF by hand — numbered objects, a content stream, an xref table of byte offsets and a trailer — which is a great way to see the anatomy. This lesson takes that file format and asks the practical question: how do you get reliable text back out?
1.2 Inside the file: objects, content streams and the xref table#
A PDF file is a sequence of indirect objects, each numbered (12 0 obj ... endobj), followed by a cross-reference (xref) table that records the byte offset of every object so a reader can jump straight to it, and a trailer that names the root object. Objects form a graph: the /Catalog object points to the page tree, each page points to its content stream, fonts, resources and annotations. Objects can be compressed into object streams and the xref itself can be a stream — modern "PDF 1.5+" files often have neither visible xref nor plain objects, which is why you should never parse a PDF by scanning bytes yourself.
The pieces you will meet:
| Piece | What it holds | Why extraction cares |
|---|---|---|
| Catalog / page tree | Document root, page count, page order | Page ordering and labels |
| Page objects | MediaBox (page size in points), rotation, resources | Page geometry for bounding boxes |
| Content streams | The drawing program: text, lines, images, clipping | Where every glyph and line actually is |
| Font objects | Font subtype, encoding, widths, embedded font file | Whether character codes map to real Unicode |
| Images (XObjects) | Embedded raster images, sometimes with masks | Scanned pages, figures, logos |
| Annotations | Links, comments, highlights, form widgets | Links to preserve, form fields to read |
| AcroForm | Interactive form field definitions and values | Invoice/form extraction without OCR |
| Names / EmbeddedFiles | File attachments | Contracts with appendices attached |
| Document info + XMP | Title, author, dates, keywords | Cheap document metadata |
| Outline (bookmarks) | The visible table of contents | A ready-made section tree when present |
PDF coordinates are in points (1/72 inch), origin at the bottom-left of the page — the opposite of screen coordinates, which trip up everyone writing layout code.
1.3 Text, fonts and encodings: why "the text" isn't simply there#
This is the subtlest part of the format, and the reason two extractors can return different text for the same file.
When text is drawn, each character is a character code interpreted through the current font's encoding. For simple fonts (Type1, TrueType), the encoding maps codes to glyph names or directly to characters — often a standard encoding like WinAnsi (close to Latin-1) or MacRoman. For CID fonts (used for CJK text and many embedded fonts), the codes are glyph indices into a character collection, and the mapping back to Unicode lives in a ToUnicode CMap — a table the producer optionally embeds. If a font has no ToUnicode map, the codes are meaningless outside the font, and extraction can only guess or fall back to OCR.
Practical consequences:
- Ligatures. Typesetters merge
fi,fl,ffiinto single glyphs (often codes like U+FB01fi). Good extractors normalise them back tofi; bad ones leavefior drop them. PyMuPDF has flags controlling ligature handling; checkpymupdf.TEXT_PRESERVE_LIGATURESin its flags table. - Subset fonts. PDF producers routinely embed subset fonts containing only the glyphs used, with renamed fonts like
ABCDEF+Helvetica. Extraction must not assume standard font names. - Custom encodings. Some producers write their own encoding tables or (pathologically) store text as glyph indices with no usable map. The Xpdf manual's BUGS section admits: "Some PDF files contain fonts whose encodings have been mangled beyond recognition. There is no way (short of OCR) to extract text from these files."
- ActualText. Tagged PDFs can carry an
/ActualTextreplacement — the "real" text for accessibility, which may differ from the drawn glyphs (e.g. forx²drawn asx+ superscript2, ActualText might bex²). Extractors differ in whether they honour it. - Hidden text. OCR tools (including OCRmyPDF) add an invisible text layer over a scan so the PDF becomes searchable. If a page has both a scan image and an OCR text layer, naive extraction returns the OCR text — usually what you want — but badly aligned OCR layers can produce garbage.
pdftotexthas-noinvisto drop invisible text; the flip side is real hidden text (watermarks, white-on-white) that you may want to know about.
1.4 Structure that helps you: tagged PDFs, outlines, forms, metadata#
Not all PDFs are equally bare. Some carry explicit structure that extraction can use instead of guessing:
- Tagged PDFs set
/MarkInfo << /Marked true >>in the /Catalog and carry a structure tree (/StructTreeRoot) that says "this content is a heading level 2", "this is a table with this header row", "this image has this alt text". Tagged PDFs are what accessibility tooling (screen readers) consumes, and they are the best-case input for document AI — Docling and other layout-aware tools exploit them when present. Most consumer PDFs (Word/LibreOffice exports aimed at accessibility, government forms) are tagged; most PDFs found in the wild are not. - Outlines (bookmarks) are the clickable table of contents in the sidebar — a nested list of titles with page destinations.
pypdf'sreader.outlineand PyMuPDF'sdoc.get_toc()return them. When present, they give you a free section tree for structure recovery. - AcroForm fields are interactive form fields (text boxes, checkboxes, dropdowns) with names and values stored separately from the page content.
pypdf'sreader.get_fields()returns them as a dict — often the cleanest way to read an invoice or application form that was never scanned. - Annotations include links (
/Linkannots with URI or GoTo destinations), comments and highlights. PyMuPDF'spage.get_links()extracts them; preserving links matters if your chunks should cite sources. - Attachments live in the
/Names→/EmbeddedFilestree;pypdf'sreader.attachmentsmaps filenames to bytes. - Metadata comes in two flavours: the document information dictionary (
reader.metadatain pypdf — title, author, subject, keywords, creator, producer, creation/mod dates) and an XMP metadata stream (reader.xmp_metadata) with richer, standardised fields. Both are optional and frequently wrong or empty — treat them as hints, not truth. - Page labels (
/PageLabels) let a document number its pages "i, ii, iii, 1, 2, 3" independently of the physical page index. Important for citations: the number a human sees may not be the index your parser uses.
1.5 Born-digital vs scanned: the first routing decision#
Before choosing any parser, answer one question: does this page have a text layer?
- Born-digital PDFs were produced by software (Word, LaTeX, a browser print dialog, a report generator). Their content streams contain real text operations, and a good extractor recovers nearly all of it.
- Scanned PDFs are photographs or scans of paper, one image per page, with no text operations at all. Extraction returns nothing — or worse, returns the imperfect OCR text layer somebody added later.
- Mixed PDFs have some born-digital pages and some scans (a report with an appendix of scanned forms).
Detection is a heuristic, not a certainty: extract text per page and compare against what a text page "should" yield. A US Letter page (612×792 pt) of body text typically yields on the order of 1,000–3,000 characters (a sparse page, such as a title page, far fewer); a page yielding tens of characters is almost certainly image-only. The demo below formalises that check in pure Python (no PDF library needed), using a deliberately low expectation of about 730 characters per Letter page so that sparse pages are not flagged:
# born_digital_check.py — run it: python born_digital_check.py
def page_coverage(text_len, page_area_pt2=612 * 792, expected_chars_per_pt2=0.0015):
"""Heuristic: expect ~1.5 chars per 1000 pt^2 (about 730 characters on a Letter page),
deliberately below a typical text page so sparse pages are not flagged.
Below ~40% of expected => probably scanned or image-only."""
expected = page_area_pt2 * expected_chars_per_pt2
ratio = text_len / expected if expected else 0.0
return ratio, ("born-digital" if ratio >= 0.4 else "suspect-scanned")
for n in [50, 900, 2500, 8000]:
r, verdict = page_coverage(n)
print(f" {n:5d} chars -> coverage {r:.2f} -> {verdict}") 50 chars -> coverage 0.07 -> suspect-scanned
900 chars -> coverage 1.24 -> born-digital
2500 chars -> coverage 3.44 -> born-digital
8000 chars -> coverage 11.00 -> born-digitalThis one number drives the whole pipeline: born-digital pages go to a text extractor; suspect pages go to OCR or a vision model (05.4 and Part 8). A page can also be partially text — a born-digital page that is mostly a figure — so the check belongs per page, not per file.
Part 2: The extraction toolbox#
2.1 The landscape at a glance#
As of November 2026, these are the tools that matter, with the versions the samples were checked against and licences, all verified on PyPI as of November 2026 (a plain install gives you the newest release):
| Tool | Version | Licence | What it is best at | Watch out for |
|---|---|---|---|---|
| pypdf | 6.21.4 | BSD-3-Clause | Metadata, encryption, outlines, forms, merging/splitting; pure Python | Slow on huge files; text quality is "plain" |
| pdfminer.six | 20260107 | MIT | Layout-object analysis (boxes, lines, chars) with tunable parameters | Slow; dated versioning scheme |
| pdfplumber | 0.11.10 | MIT | Character-level geometry, cropping, table extraction; built on pdfminer.six | Slow on big documents; tables need tuning |
| PyMuPDF | 2.1 | AGPL-3.0 / commercial | Speed, dict/words/blocks extraction, images, links, Markdown output |
Licence; the 2.x API renamed fitz → pymupdf |
| pypdfium2 | 5.14.0 | BSD-3 / Apache-2.0 | PDFium bindings: fast text and rendering, search | Lower-level API; text quality like PDFium's |
Poppler pdftotext |
(system) | GPL-2.0 (utils) | Battle-tested CLI, -layout mode |
No Python API; you shell out |
| camelot-py | 2.0.0 | MIT | Ruled tables (lattice), text-aligned tables (network/stream), ML flavour |
Java-free now but ml needs PyTorch |
| tabula-py | 2.10.0 | MIT | Table extraction via tabula-java | Needs a Java runtime |
| Docling (IBM) | 2.147.0 | MIT | Layout-aware PDF→DoclingDocument→Markdown/JSON; reads structure, formulas, tables | Heavy; model downloads on first run |
| Unstructured | 0.27.36 | Apache-2.0 | partition_pdf into typed elements; many formats |
PDF path needs poppler + tesseract installed |
| marker (datalab-to) | 2.1.0 (marker-pdf) |
Apache-2.0 | Local PDF→Markdown with layout model + optional VLM cleanup | Needs PyTorch; GPU strongly preferred |
| MinerU | 4.1.7 | Apache-2.0 + extra terms | PDF→Markdown, strong on papers/forms/tables | Custom licence terms; heavy install |
| MarkItDown (Microsoft) | 0.1.9 | MIT | Universal file→Markdown front door (PDF via pdfminer) | PDF support is only as good as its backend |
| Hosted parsers | — | service | LlamaParse, Mistral OCR, Document AI, Azure DI, Textract | Per-page pricing; data leaves your infra |
2.2 pypdf: the all-rounder#
pypdf is the pure-Python library you install first — not because it extracts the prettiest text, but because it does everything around the text: metadata, encryption, outlines, forms, attachments, and page surgery. The samples were checked on version 6.21.4 (BSD-3-Clause, Python ≥3.9); the current release is 7.0.1, which a plain install gives you (see the note below).
# s2_2_pypdf_basics.py
"""pypdf: metadata, encryption check, per-page text. Illustrative output."""
from pypdf import PdfReader
reader = PdfReader("handbook.pdf") # or PdfReader("handbook.pdf", password="...")
print("pages:", len(reader.pages))
print("encrypted:", reader.is_encrypted) # stays True even after decrypt()
print("header:", reader.pdf_header) # e.g. '%PDF-1.7' (a str)
meta = reader.metadata # DocumentInformation or None
if meta:
print("title:", meta.title, "| author:", meta.author,
"| created:", meta.creation_date)
# decrypt() returns a PasswordType enum: NOT_DECRYPTED / USER_PASSWORD / OWNER_PASSWORD
if reader.is_encrypted:
result = reader.decrypt("") # try empty password first — many "encrypted" PDFs use it
print("decrypt result:", result)
# outline = the sidebar bookmarks, possibly nested lists of Destination objects
print("outline entries:", len(reader.outline))
# AcroForm fields as {field_name: {/V: value, /T: name, ...}}
fields = reader.get_fields()
if fields:
for name, f in list(fields.items())[:5]:
print("field:", name, "->", f.get("/V"))
# text: plain mode, or "layout" mode to keep column-ish spacing
for i, page in enumerate(reader.pages[:2]):
text = page.extract_text()
print(f"--- page {i + 1}: {len(text)} chars ---")
print(text[:300])
# visitor_text callback: your own per-line hook with font size + position.
# Useful for heading detection (Part 6) — see 6.1.
def visitor(text, cm, tm, font_dict, font_size):
pass # collect (text, font_size, tm[5]) here
# layout mode keeps horizontal positioning; layout_mode_space_vertically=False
# removes blank/whitespace-only lines
page0 = reader.pages[0]
layout_text = page0.extract_text(
extraction_mode="layout", layout_mode_space_vertically=False
)
print("layout-mode chars:", len(layout_text))
# memory guard: a pathological content stream can need ~10 GB RAM to parse
# (pypdf docs). Check the stream size before extract_text on untrusted files.
# get_contents() returns ONE ContentStream (a dict subclass), not a list —
# iterating it would walk dict keys, so take .get_data() on the object itself:
cs = page0.get_contents()
size = len(cs.get_data()) if cs is not None else 0
print("page 0 content stream bytes:", size)pages: 12
encrypted: False
header: %PDF-1.7
title: Acme Product Handbook | author: Docs Team | created: 2026-01-15 09:30:00+00:00
outline entries: 9
field: customer.name -> Priya Nair
--- page 1: 1842 chars ---
Acme Product Handbook
Version 3.2 — January 2026
1. Introduction
Welcome to the Acme product handbook...
layout-mode chars: 1903
page 0 content stream bytes: 48213Key API points, all verified against the pypdf docs:
meta.creation_dateandmeta.modification_datereturn parseddatetimeobjects (Nonewhen absent or unparseable); the*_rawvariants (creation_date_raw,modification_date_raw) give the originalD:YYYYMMDDHHmmssstring.extract_text()acceptsextraction_mode="plain"(default) or"layout", plusvisitor_text/visitor_operand_beforecallbacks that receive each text fragment with its font dictionary, font size and transformation matrices — the hook you need for heading detection.page.extract_text(0)extracts only horizontally-oriented text;extract_text((0, 90))adds text rotated 90°. Rotated pages are a classic failure (3.4).reader.get_fields()returns AcroForm fields — check it before OCRing a form PDF.PdfReader(stream, strict=False, password=None):strict=Trueturns correctable problems into exceptions — useful in tests, dangerous in production.- pypdf warns that extracting a page's text "requires parsing its whole content stream" and has seen ~10 GB RAM needed for a ~300 MB uncompressed stream. On untrusted input, check
len(page.get_contents().get_data())first (10.3).
2.3 pdfminer.six: layout objects#
pdfminer.six (version 20260107 — the project moved to date-based versioning — MIT, Python ≥3.10) is the engine underneath pdfplumber and several other tools. Its distinguishing feature is that it doesn't just give you text: extract_pages yields a tree of layout objects — pages containing text boxes, which contain text lines, which contain characters — each with coordinates, font name, size and colour. When you need to understand where things are, not just what they say, this is the model.
# s2_3_pdfminer.py
"""pdfminer.six: high-level text and layout-object extraction. Illustrative."""
from pdfminer.high_level import extract_text, extract_pages
from pdfminer.layout import LAParams, LTTextContainer, LTChar, LTFigure
# One call for plain text. laparams=None uses defaults tuned for reading order.
text = extract_text("handbook.pdf", page_numbers=[0, 1]) # zero-indexed pages
print(text[:400])
# LAParams controls layout analysis: line_overlap, char_margin, line_margin,
# word_margin, boxes_flow (float -1.0..+1.0 weighting horizontal vs vertical
# position in box ordering; None disables advanced layout analysis),
# detect_vertical (vertical CJK text).
laparams = LAParams(
line_overlap=0.5,
char_margin=2.0,
line_margin=0.5,
word_margin=0.1,
boxes_flow=0.5, # -1.0 => only x-position matters, +1.0 => only y;
# for multi-column pages try negative values or None
detect_vertical=True,
)
text2 = extract_text("handbook.pdf", laparams=laparams)
# extract_pages gives you the object tree per page:
for page_layout in extract_pages("handbook.pdf", page_numbers=[0]):
for element in page_layout:
if isinstance(element, LTTextContainer): # LTTextBoxHorizontal etc.
print(f"textbox bbox={element.bbox} text={element.get_text()[:60]!r}")
elif isinstance(element, LTFigure): # vector drawings / image forms
print(f"figure bbox={element.bbox}")
# LTChar gives per-character detail: fontname, size, adv, upright,
# get_text() — the raw material for your own layout logic.Acme Product Handbook
Version 3.2 — January 2026
1. Introduction
Welcome to the Acme product handbook. This guide covers installation,
configuration and day-to-day operation of the Acme platform.
textbox bbox=(56.8, 730.4, 300.1, 745.9) text='Acme Product Handbook\n'
textbox bbox=(56.8, 705.2, 290.4, 718.7) text='Version 3.2 — January 2026\n'
figure bbox=(400.0, 600.0, 560.0, 720.0)Other entry points: pdf2txt.py is its CLI (pdf2txt.py -t html -o out.html file.pdf — output types text, xml, html, hocr, tag), and dumppdf.py dumps the raw object structure — invaluable when a file won't parse and you need to see what's inside.
2.4 pdfplumber: characters, geometry and tables#
pdfplumber (0.11.10, MIT, Python ≥3.8) wraps pdfminer.six and exposes the page as inspectable geometry: .chars (one dict per character), .lines, .rects, .curves, .images, .annots. It is the tool you reach for when text extraction isn't enough — when you need to see the layout: crop a region, dedupe overlapping text, or find tables. It depends on pdfminer.six, so installing it pulls that in too.
# s2_4_pdfplumber.py
"""pdfplumber: page geometry, cropping, tables. Illustrative output."""
import pdfplumber
with pdfplumber.open("invoice.pdf") as pdf:
page = pdf.pages[0]
print("page size (pt):", page.width, "x", page.height)
print("rotation:", getattr(page, "rotation", "n/a"))
# every character is a dict: text, x0, x1, top, bottom, size, fontname, ...
print("chars on page:", len(page.chars))
first = page.chars[0]
print("first char:", {k: first[k] for k in ("text", "x0", "top", "size", "fontname")})
# extract_text with layout keeps spacing; tolerances control word/line grouping
plain = page.extract_text()
layout = page.extract_text(layout=True, x_density=7.25, y_density=13)
# words: merged char dicts with extra attrs
words = page.extract_words(x_tolerance=3, y_tolerance=3, keep_blank_chars=False)
# crop to a region (e.g. a known table area) and extract only inside it
table_area = page.crop((50, 300, 550, 500))
print("chars in crop:", len(table_area.chars))
# the flagship: table extraction. Strategies: "lines" (ruled), "text"
# (whitespace-aligned), "explicit" (your own lines), "lines_strict"/"text_strict".
tables = page.extract_tables(table_settings={
"vertical_strategy": "lines",
"horizontal_strategy": "lines",
"snap_tolerance": 3,
"join_tolerance": 3,
})
for t in tables:
for row in t[:4]:
print(row)
# other page objects you'll use for layout decisions:
print("lines:", len(page.lines), "rects:", len(page.rects),
"curves:", len(page.curves), "images:", len(page.images))
# render the page (or a crop) for debugging — needs Pillow
# im = page.to_image(resolution=150).original
# im.save("page1_debug.png")page size (pt): 612.0 x 792.0
chars on page: 2314
first char: {'text': 'A', 'x0': 56.8, 'top': 58.2, 'size': 16.0, 'fontname': 'Helvetica-Bold'}
chars in crop: 812
['Item', 'Qty', 'Unit price', 'Total']
['Widget A', '2', '10.00', '20.00']
['Widget B', '1', '15.50', '15.50']
lines: 14 rects: 22 curves: 0 images: 1pdfplumber specifics worth remembering:
- Coordinates are
(x0, top, x1, bottom)style floats in PDF points;page.chars[i]carriessize,fontname,upright,non_stroking_color— everything Part 6 needs for font heuristics. .dedupe_chars()removes duplicate overlapping characters — essential before OCR-added text layers, where the invisible OCR text sits exactly on top of visible text and naive extraction doubles everything..to_dict()gives the whole page as JSON-able structure;.to_image()returns aPageImageyou can annotate and save for debugging — its imaging backend has its own dependency, so check the docs for your version.- Table extraction is heuristic:
vertical_strategy/horizontal_strategycan be"lines","text","explicit"or strict variants. Ruled tables →"lines"; borderless aligned tables →"text". Tuningsnap_tolerance,join_tolerance,edge_min_length,min_words_vertical/min_words_horizontalis normal work — see Part 4.
2.5 PyMuPDF: speed and structure (the licence question)#
PyMuPDF (version 2.1) is the performance leader and the richest API: import pymupdf (the old import fitz name is deprecated), pymupdf.open(path), index pages with doc[i]. Its page.get_text() offers the most output formats of any library — "text", "blocks", "words", "dict", "json", "rawdict", "rawjson", "html", "xhtml", "xml" — with sort=True for reading-order sorting, clip= for regions, flags= for ligature/space control, and a reusable textpage= for speed. It also extracts images, links, drawings, annotations and form fields, renders pages, and — since 2.x absorbed the pymupdf4llm package — converts whole documents to Markdown via doc.to_markdown().
# s2_5_pymupdf.py
"""PyMuPDF: the Swiss-army extraction API. Illustrative output."""
import pymupdf # v2.x; "import fitz" still works but is the deprecated name
with pymupdf.open("handbook.pdf") as doc:
print("pages:", doc.page_count, "| metadata:", doc.metadata.get("title"))
print("toc:", doc.get_toc()) # outline -> [(lvl, title, page), ...]
print("labels:", doc.get_page_labels()) # /PageLabels if present
page = doc[0]
print("rect:", page.rect, "| rotation:", page.rotation)
# the big one: get_text modes
plain = page.get_text("text")
blocks = page.get_text("blocks") # [(x0,y0,x1,y1,text,block_no,type)]
words = page.get_text("words") # [(x0,y0,x1,y1,word,block,line,word_no)]
d = page.get_text("dict") # nested: blocks->lines->spans->chars
# d["blocks"] entries: {"type":0 text / 1 image, "bbox":..., "lines":[{"spans":[{"text","font","size","flags","bbox","chars"}]}]}
# sort=True reorders blocks/words by (y1, x0) — cheap reading-order fix
sorted_blocks = page.get_text("blocks", sort=True)
# html/xhtml/xml keep some structure (spans with font info); rawdict adds per-char
html = page.get_text("html")
# images on the page: (xref, smask, width, height, bpc, colorspace, ...)
for img in page.get_images(full=True):
xref = img[0]
pix = pymupdf.Pixmap(doc, xref)
print("image xref", xref, pix.width, "x", pix.height)
pix = None
# links and annots
print("links:", page.get_links())
# render a page for OCR/VLM handoff (Part 8/10)
pixmap = page.get_pixmap(dpi=200)
pixmap.save("page1.png")
# document-level Markdown (the old pymupdf4llm API, now built in)
md = doc.to_markdown()
print(md[:300])pages: 12 | metadata: Acme Product Handbook
toc: [[1, 'Introduction', 1], [1, 'Installation', 3], [2, 'Configuration', 5]]
labels: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
rect: Rect(0.0, 0.0, 612.0, 792.0) | rotation: 0
image xref 12 640 x 480
links: [{'kind': 2, 'from': Rect(72.0, 300.0, 200.0, 315.0), 'uri': 'https://docs.acme.example/install'}]
# Acme Product Handbook
Version 3.2 — January 2026
## 1. Introduction
Welcome to the Acme product handbook...PyMuPDF details that matter:
- Speed: it wraps MuPDF (C), so bulk extraction is dramatically faster than pdfminer/pdfplumber. It also opens many non-PDF formats (XPS, EPUB, images, Office formats via its "PyMuPDF Office" support — a separate commercial package,
pip install pymupdf-office, key-licensed and not part ofpymupdfitself) — handy but out of scope here (05.3 covers Office files properly with open tools). sort=Truecaveat: for"text"/"words"it re-synthesises lines in reading sequence; for"blocks"/"dict"it sorts by block bbox(y1, x0). It fixes simple cases, not true multi-column reading order — see 3.1.flags: bitmask controlling ligature preservation, space insertion and image extraction per call; see PyMuPDF's "Text Extraction Flags" table.- Encryption:
doc.needs_pass,doc.authenticate(password). to_markdown()/to_json()/use_layout(): thepymupdf4llmfunctionality moved intoDocumentin 2.x. The standalonepymupdf4llmpackage still exists but is now "an empty package required by pymupdf-2.x" for pip-compatibility — don't install it separately;pip install pymupdfincludes the code.- Forms: for AcroForm key-value pairs iterate
page.widgets()(or start atpage.first_widgetand follow.next) — eachWidgetexposes.field_name,.field_value,.field_type/.field_type_string(checkbox/radio "on" values come from.on_state()).pymupdf4llm.get_key_values()exists only on the legacy 1.x line; on the 2.x line the samples were checked against that package is an empty compat shim. - Licence: AGPL-3.0 or commercial. Re-read the warning in Setup before depending on it.
2.6 pypdfium2 and Poppler: the rendering engines#
pypdfium2 (5.14.0, BSD-3/Apache-2.0) binds PDFium — the same engine Chrome and Android use to render PDFs — so its text extraction and rendering match what users actually see. Its API is lower-level but very capable: open a PdfDocument, index pages, get a TextPage for text and search, or render() a page to a bitmap for OCR/VLM input.
# s2_6_pypdfium2.py
"""pypdfium2: PDFium bindings. Illustrative output."""
import pypdfium2 as pdfium
pdf = pdfium.PdfDocument("handbook.pdf") # path, bytes or stream
print("pdf version:", pdf.get_version()) # int | None: 17 means PDF 1.7
print("pages:", len(pdf))
page = pdf[0]
width, height = page.get_size() # points
print("page size:", width, "x", height)
# text: a TextPage helper per page
textpage = page.get_textpage()
all_text = textpage.get_text_bounded() # whole page
print(all_text[:200])
# bounded extraction uses PDF coords: bottom is measured from the bottom!
region = textpage.get_text_bounded(left=50, bottom=600, right=560, top=750)
span = textpage.get_text_range(index=0, count=50) # char range
searcher = textpage.search("handbook", match_case=False)
match = searcher.get_next() # (char_index, char_count) or None
# render for OCR/VLM (scale=1 -> 72 dpi; scale=2 -> 144 dpi)
bitmap = page.render(scale=2, rotation=0)
pil_image = bitmap.to_pil()
pil_image.save("page1_pypdfium.png")
# TOC
for bm in pdf.get_toc(max_depth=15):
print(" " * bm.level, bm.get_title(), "->", bm.get_dest())
pdf.close()pdf version: 17
pages: 12
page size: 612.0 x 792.0
Acme Product Handbook
Version 3.2 — January 2026
1. Introduction
Welcome to the Acme product handbook. This guide covers installation,
configuration and day-to-day operation of the Acme platform.
Introduction -> page 1
Installation -> page 3Poppler pdftotext is the command-line workhorse — the same engine inside many Linux document tools. Install poppler-utils (or poppler on macOS via Homebrew) and you get pdftotext, pdfinfo, pdftoppm (page→image), pdftohtml, pdfimages:
# plain text, one file per page range
pdftotext handbook.pdf handbook.txt
# -layout keeps the physical layout (columns stay columns-ish)
pdftotext -layout handbook.pdf handbook_layout.txt
# -raw keeps content-stream order (sometimes useful, usually not)
pdftotext -raw handbook.pdf -
# metadata without any Python
pdfinfo handbook.pdf
# pages to PNG at 200 dpi (for OCR/VLM routes)
pdftoppm -png -r 200 handbook.pdf pagepdftotext -layout output (illustrative):
Acme Product Handbook Version 3.2 — January 2026
1. Introduction
Welcome to the Acme product handbook. This guide covers installation,
configuration and day-to-day operation of the Acme platform.Useful flags (verified against Poppler's man page — don't confuse it with Xpdf's pdftotext, a different tool whose -margin* options Poppler does not have): -f N -l M for page ranges, -enc UTF-8 for output encoding, -nopgbrk to drop form feeds, -upw/-opw for passwords, -remove-hyphens to control end-of-line hyphen joining, and -x/-y/-W/-H to crop a pixel region — the Poppler-native cheap header/footer trim. For provenance without a Python dependency, -bbox/-bbox-layout emit XHTML and -tsv emits TSV, both carrying per-word (and per-line/block) bounding boxes — the cheapest geometry source if you don't want pdfplumber's object model (6.4). The -layout vs default modes are the key decision: default mode "undoes" physical layout into reading order (good for single-column prose), -layout preserves spacing (better for tables and multi-column pages).
2.7 Camelot and ruled-table specialists#
For PDFs whose main payload is tables with ruling lines — invoices, financial statements, statistical reports — dedicated table extractors beat generic text extraction:
# s2_7_camelot.py
"""camelot-py: table extraction. Illustrative output."""
import camelot
# flavor="lattice" -> ruled tables: grid detection from ruling lines
# flavor="stream" -> borderless tables aligned by whitespace gaps
# flavor="network" -> borderless tables aligned by text position; "hybrid" blends both
# flavor="ml" -> Table Transformer model on the page image (needs camelot-py[ml])
# flavor="auto" -> picks lattice or network per page
tables = camelot.read_pdf("financials.pdf", pages="1-3", flavor="lattice")
print("tables found:", tables.n)
for i, t in enumerate(tables):
print(f"--- table {i}: accuracy={t.parsing_report['accuracy']:.1f} "
f"whitespace={t.parsing_report['whitespace']:.1f} "
f"confidence={t.parsing_report['confidence']:.2f}")
df = t.df # pandas DataFrame — the usual output you want
print(df.head())
# t.data is the raw list-of-lists if you don't want pandastabula-py (2.10.0, MIT) is the older alternative; it wraps tabula-java, so it needs a Java runtime installed — one more system dependency for marginal benefit over camelot/pdfplumber in 2026. Mention it, don't build on it.
Part 3: Layout problems and fixes#
Deep-dive
pypdf's own documentation lists "Why Text Extraction is hard" as a set of open questions — should paragraphs keep the PDF's line breaks? Should page numbers, headers and footers be included? Should outlines, formatting, tables, captions, ligatures, footnotes, hyperlinks be extracted, and where? There is no single right answer; the right answer is your answer, encoded deliberately. This part walks the classic failures and the fixes.
3.1 Reading order#
The content stream order is write order, not read order. sort=True (PyMuPDF) or pdftotext's default mode fixes simple cases by sorting blocks top-to-bottom, left-to-right — but a two-column page sorted that way interleaves the columns line by line:
# reading_order.py — run it: python reading_order.py
# Simulate two-column page blocks: (x0, y0, x1, y1, text)
blocks = [
(50, 100, 300, 115, "Left col line 1"),
(320, 100, 560, 115, "Right col line 1"),
(50, 120, 300, 135, "Left col line 2"),
(320, 120, 560, 135, "Right col line 2"),
(50, 40, 560, 55, "Header"),
]
def naive_order(blocks):
return [t for *_, t in blocks]
def xy_sort(blocks):
return [t for *_, t in sorted(blocks, key=lambda b: (b[1], b[0]))]
def column_aware(blocks, split_x=300):
"""Crude 2-column fix: split at x, sort each column by y, concat."""
left = sorted([b for b in blocks if b[0] < split_x], key=lambda b: b[1])
right = sorted([b for b in blocks if b[0] >= split_x], key=lambda b: b[1])
return [t for *_, t in left + right]
print("file order :", naive_order(blocks))
print("xy-sorted :", xy_sort(blocks))
print("column-aware :", column_aware(blocks))file order : ['Left col line 1', 'Right col line 1', 'Left col line 2', 'Right col line 2', 'Header']
xy-sorted : ['Header', 'Left col line 1', 'Right col line 1', 'Left col line 2', 'Right col line 2']
column-aware : ['Header', 'Left col line 1', 'Left col line 2', 'Right col line 1', 'Right col line 2']Real multi-column detection is the XY-cut algorithm: recursively split the page's whitespace into rectangles, then order the rectangles. pdfminer.six approximates it via LAParams.boxes_flow; layout-aware tools (Docling, marker, hosted parsers) do it properly with layout models. When columns matter, prefer those over hand-rolled heuristics — but know the heuristic exists, because you will debug it.
3.2 Columns, headers, footers and page numbers#
Three related problems:
- Running headers/footers repeat on every page ("Acme Handbook v3.2", "Page 3 of 12", "Confidential"). Left in, they pollute every chunk and can dominate embeddings. Detection is repetition + position: a line appearing on most pages near the top or bottom margin is boilerplate. The demo below finds them with pure Python:
# boilerplate.py — run it: python boilerplate.py
from collections import defaultdict
def find_repeated(entries, min_pages=2):
"""entries: (page_no, y_from_top, text). Return lines on >= min_pages."""
by_text = defaultdict(set)
for page_no, y, text in entries:
t = " ".join(text.split())
if t:
by_text[t].add(page_no)
return {t: sorted(ps) for t, ps in by_text.items() if len(ps) >= min_pages}
entries = [
(1, 20, "Acme Handbook v3.2"), (1, 40, "Page 1 of 12"), (1, 750, "Acme Corp - Internal"),
(2, 20, "Acme Handbook v3.2"), (2, 40, "Page 2 of 12"), (2, 750, "Acme Corp - Internal"),
(3, 20, "Acme Handbook v3.2"), (3, 40, "Page 3 of 12"), (3, 750, "Acme Corp - Internal"),
]
for t, ps in sorted(find_repeated(entries).items()):
print(f" {t!r} on pages {ps}")
# "Page N of 12" differs per page -> normalize digits before comparing,
# or match by y-position band instead of exact text. 'Acme Corp - Internal' on pages [1, 2, 3]
'Acme Handbook v3.2' on pages [1, 2, 3]Note Page N of 12 did not match — its text differs per page. Real detectors normalise digits (Page \d+ of \d+) or cluster by position. This is 05.5's job downstream, but you want page numbers and bboxes now so cleaning can act per page.
- Page numbers are the worst case: they differ every page, so repetition detection misses them. Detect by position (a lone short line in the bottom ~5% or top ~5% of the page) plus pattern (
^\d+$,Page \d+, roman numerals). Keep the printed number for citations (6.4); drop it from chunk text. - Two-column interleaving is fixed by column-aware ordering or a layout-aware tool (3.1).
3.3 Hyphenation, ligatures, Unicode and invisible text#
- Hyphenation at line breaks: justified text breaks words with
-at line end (exam-/ple). Joining rules: if a line ends with-and the next begins lowercase, join without space; butwell-+knownvsco-+operateneed care, and real hyphens in compounds (long-term) must survive. Most libraries do not rejoin for you; 05.5 owns the general fix. PyMuPDF is the exception: itsTEXT_DEHYPHENATEflag (16) joins words split across line breaks duringget_text— handy, but verify it doesn't merge genuine compounds (long-+term) before enabling it corpus-wide. - Ligatures:
fi/fl/ffsingle glyphs. PyMuPDF flags control preservation; pdfplumber/pdfminer usually normalise viaToUnicode. Check output forfibefore assuming clean text. - Unicode: extractors output Unicode when
ToUnicodemaps exist; otherwise you get glyph codes or.notdefboxes. Mojibake (éforé) signals an encoding mishap — fix belongs to 05.5. - Invisible text: OCR layers and hidden watermarks.
pdftotext -noinvisdrops rendering-mode-3 text; in Python, check char flags/render modeinrawdictoutput. Decide deliberately whether OCR-layer text is your text (usually yes for scans) or a duplicate (dedupe against the image).
3.4 Rotated text, RTL and CJK scripts#
- Rotated pages (
/Rotate 90/180/270): most libraries return text in unrotated page coordinates — PyMuPDF documents this explicitly: coordinates pertain to the unrotated page and you applypage.rotation_matrixyourself. Text within a page can also be rotated (watermarks, sidebars):extract_text(0)in pypdf extracts only upright text;(0, 90)adds 90°-rotated text. pdfminerLAParams.detect_vertical=Truecatches vertical CJK. - RTL scripts (Arabic, Hebrew): logical vs visual order differs; extractors return logical order usually, but bidi reordering for display is your problem downstream. CJK has no spaces — "words" aren't whitespace-delimited; tokenization implications are 02.2's territory.
- Vertical text: common in CJK docs and some tables; pdfminer's
detect_verticaland PyMuPDF's flags handle it; verify visually when it matters.
3.5 Math, special symbols and forms#
- Math/formulas are positioned glyphs, not linear text:
x²may extract asx2orx+ stray2. LaTeX-aware tools (marker, MinerU, Docling, Mathpix-style services) reconstruct$$...$$; classical extractors give you fragments. For a corpus heavy in papers, this alone justifies a layout-aware pipeline. - Checkboxes/radio buttons in forms are vector drawings or ZapfDingbats glyphs (
\u2713-like), not text —get_fields()on AcroForms is the reliable path; otherwise you infer from positions. - Stamps/signatures are images; there is no text to extract.
3.6 Footnotes, endnotes and sidebars#
Small-print notes are a distinct layout problem because the marker and the note live in different places, and naive extraction loses the pairing:
- Footnotes sit at the bottom of the page, usually in smaller type, often below a horizontal rule; endnotes collect at the document's end instead. The in-text marker is a superscript — a small raised character (
1,*,†) that extractors may return as a separate char, fuse to the wrong word, or drop entirely. - Association is the hard part. Matching marker
3to note3by text works until numbering restarts per chapter; matching by position fails when a note spills onto the next page. The robust signal is geometry plus font: notes cluster in the bottom band (below the body text's lowestbottom), in a smallersize, and the separator is apage.lines/page.rectsrule you can detect. Assignkind="footnote"— theTextBlockliteral in Part 9 already has it — and keep the marker's bbox with the note's so downstream can reattach them. - Reading order. Extraction typically emits footnote text after the page's main text — or interleaved, if the note sits in a margin band. Decide deliberately: keep notes where they were found (simplest, preserves provenance) or relocate them after their anchor paragraph. What you must not do is let a footnote orphan into the next chunk boundary — 05.6 should treat marker+note as one unit.
- Sidebars and margin notes are the same problem rotated: a narrow x-band beside the main column (pull quotes, "did you know" boxes, legal disclaimers). Detect them like mini-columns — cluster word
x0s; a band separated from body text by a gutter is a sidebar, not a second column. Tagkind="sidebar"and keep its bbox; whether to interleave it into reading flow or append it after the section is a corpus decision — for retrieval, keeping it adjacent to the section it comments on usually wins. - The failure mode to test for: after re-flow, footnote
2's text lands after footnote3's, or a marker attaches to the neighbouring sentence. Spot-check pages with dense notes — this is exactly the kind of silent corruption 05.10 should sample for.
3.7 Why extraction is hard: the honest summary#
pypdf's docs list the undecidable questions — paragraph boundaries, page numbers, headers, outlines, formatting, tables, captions, ligatures, SVG text, formulas, whitespace, footnotes, links, linearization. The meta-lesson: every extractor made different choices, and none is universally right. Your job is to know which choices each tool made, detect when they fail on your corpus, and route around them — which is exactly what Part 10 automates.
Part 4: Tables#
Deep-dive
Tables are where PDF extraction goes to die. A born-digital table is just text and lines at coordinates; nothing in the format says "this is a 4×6 table with header row". Everything downstream — chunking, retrieval, citation — inherits whatever you decide here.
4.1 Why tables break#
- Ruled tables have visible grid lines: detectable geometry (pdfplumber
"lines"strategy, camelotlattice). - Borderless tables rely on whitespace alignment: harder;
"text"strategy or layout models. - Merged cells break row/column assumptions; continuation rows have empty leading cells.
- Tables spanning pages repeat headers (or don't); naive concatenation loses the header context.
- Nested/complex tables and tables inside figures defeat every heuristic.
- Flattened alternative: the content stream may place each character independently — the worst case pypdf warns about — making even column detection unreliable.
4.2 Detecting tables: ruled vs unruled#
Heuristic signals, in order of reliability:
- Ruling lines: count horizontal/vertical lines and rectangles (
page.lines,page.rects,page.curvesin pdfplumber). Many aligned lines forming a grid → ruled table. pdfplumber's"lines"strategy and camelot'slatticeexploit this. - Whitespace columns: cluster
char/wordx-positions into columns and y-positions into rows; consistent gutters → borderless table. pdfplumber"text"strategy, camelotnetwork/stream, pdfminer's layout analysis approximate this. - Repeated structure across pages: same x-columns recurring → likely a table even without lines.
- Font/size signals: bold first row + numeric columns → probable header + data.
4.3 Extracting: pdfplumber and Camelot#
pdfplumber's extract_tables (settings shown in 2.4) returns list[list[str|None]] per table — rows of cell strings, None for empty cells; find_tables() additionally gives each table's bbox for provenance. Camelot returns pandas DataFrames plus a parsing_report: accuracy and whitespace are percentages in [0, 100] (whitespace = share of empty cells), and confidence in [0, 1] combines them. A whitespace above ~30 usually means a bad extraction — drop or escalate; tables.filter(min_accuracy=90, max_whitespace=20) applies such thresholds for you. For ML-grade recovery, camelot's flavor="ml" uses a Table Transformer model on the page image; Docling and hosted parsers do the same internally.
4.4 Representing tables for LLMs#
Once you have list[list[str]], choose a representation — this decision matters more than the extractor:
| Format | Pros | Cons |
|---|---|---|
| Markdown table | Compact, LLMs read it natively, survives chunking | Merged cells/empty cells awkward; wide tables wrap badly |
| CSV | Exact, parseable, no ambiguity | No header semantics in-band; LLMs sometimes mangle delimiters |
HTML <table> |
Preserves the most structure (colspan/rowspan) | Verbose tokens; models occasionally emit broken HTML |
| JSON rows | Unambiguous, schema-able | Most tokens; loses visual layout |
| Row-sentences ("Item A, qty 2, unit price 10.00, total 20.00") | Most robust for retrieval/Q&A; each row self-contained | Loses columnar comparison; verbose |
Rules of thumb: repeat the header on continuation pages and inside chunks; keep the caption adjacent to the table; for very wide tables, prefer JSON or row-sentences; for prose-QA corpora, row-sentences often retrieve best because each row is independently meaningful. Whatever you choose, record it in chunk metadata (05.8) so downstream knows the shape.
4.5 Hard cases: merged cells, spanning pages, huge tables#
- Merged cells: cell text appears once, spanning rows/cols. Extractors give you the text in one cell and
Noneelsewhere — reconstruct spans only if your use case needs them (financial statements do; most RAG corpora don't). - Tables spanning pages: detect repeated header rows across consecutive pages; merge into one logical table with page provenance per row.
- Huge tables (hundreds of rows): don't chunk blindly — keep header + a window of rows per chunk, or summarise with an LLM (10A.2 territory). A 500-row table as one chunk destroys retrieval precision.
- When extraction returns garbage (parsing_report accuracy low, empty cells everywhere, row/column counts implausible): escalate to the page image and a VLM (4.6).
4.6 When to send the page image instead#
If a page is table-dominant and classical extraction is unreliable, rasterise the page (page.get_pixmap() PyMuPDF, page.render() pypdfium2, pdftoppm) and send the image to a vision model with a table-transcription prompt (Part 8). VLMs read borderless and complex tables far better than heuristics — at per-page cost and with hallucination risk, so spot-check. This is the core of the hybrid strategy in 8.5.
Part 5: Images, charts and figures#
Deep-dive
PDFs embed images as XObjects; text extractors mostly ignore them (PyMuPDF's "dict"/"blocks" modes include image blocks with bboxes; page.get_images(full=True) lists xrefs).
- Extracting embedded images: PyMuPDF
page.get_images()+pymupdf.Pixmap(doc, xref)gives you the raw image;page.get_image_info()/get_image_bbox()give placement. pdfplumber'spage.imagesgives bounding boxes. Decide per use case: logos/icons → skip; photos in reports → maybe keep as assets; scanned pages → the image is the content (OCR route). - Captions and alt text: captions are usually text near the image bbox ("Figure 3: ...") — associate by proximity. True alt text exists only in tagged PDFs (structure elements'
/Alt) — check for it, don't assume it. - Describing figures with a VLM: for charts/diagrams that carry information (a bar chart of quarterly revenue, an architecture diagram), send the cropped image region to a VLM with a "describe faithfully, transcribe any labels" prompt. Costs per image; hallucination risk on numbers — for data extraction prefer OCR+structure or dedicated chart-to-data tools; for prose context a description suffices.
- Charts to data: reconstructing underlying data from a chart image is a research-grade problem; don't promise it. If the data matters, look for the source spreadsheet or ask for a data feed.
- When to skip: decorative images, logos, page-background scans, images already covered by adjacent text. Default to extracting image inventory (count, bbox, size) always — it's cheap provenance — and decide content extraction per corpus.
Part 6: Structure recovery#
Deep-dive
Text out of a PDF is a bag of lines; your downstream needs structure. Three sources, in decreasing reliability:
6.1 Headings from font size and weight#
No "heading" tag exists in untagged PDFs — but headings look different: larger font size, bold weight, often distinct font name, frequently followed by whitespace. Heuristic: cluster spans by (fontname, size, flags); a span whose size/weight is an outlier above body text and sits alone on its line is a heading candidate. pypdf's visitor_text gives you (text, font_dict, font_size) per fragment; PyMuPDF "dict" gives size, font, flags per span; pdfplumber chars gives size, fontname. Bold detection: fontname containing Bold/Black/Heavy, or PyMuPDF flags bit 4 (bold) / pdfminer upright+font descriptor. This is heuristic — validate against your corpus's actual styles, and prefer the PDF outline when present.
6.2 The PDF outline and section trees#
reader.outline (pypdf) / doc.get_toc() (PyMuPDF) / pdf.get_toc() (pypdfium2) return the bookmark tree: (level, title, page) — a ready-made section hierarchy if the producer bothered to write it. Many do (Word, LaTeX, browsers); many don't. When present, use it as the authoritative skeleton and reconcile with font heuristics; when absent, build the tree from heading candidates.
6.3 Lists, links and references#
- Lists: bullets are glyphs (
•,–,◦) or small vector drawings at line start; numbered lists are text matching^\d+[.)]or^[a-z][.)]. Detect by pattern + position; preserve numbering text verbatim. - Links:
page.get_links()(PyMuPDF),/Annotswith/Subtype /Link(pypdf raw), or pdfplumberpage.annots. URI links and GoTo (internal page) links; keep them as citation targets. - References/citations: "see Section 3.2" or "[12]" are just text — resolve them only if your corpus needs it; cross-reference resolution is a Module 07 concern.
6.4 Page numbers and bounding boxes as provenance#
Whatever structure you recover, keep the geometry: every block should carry page (physical index and printed label), bbox in points, and the parser+version that produced it. This is the provenance 05.8 formalises and the citation backbone for RAG — a chunk that can say "page 7, top-left region" is worth far more than one that can't. Physical page index vs printed page label vs PDF page label (/PageLabels) are three different numbers; store all you can.
Part 7: Layout-aware pipelines and hosted parsers#
Deep-dive
When classical extraction isn't enough — complex layouts, tables, formulas, scans — a whole ecosystem exists between "hand-rolled heuristics" and "send it to a VLM".
7.1 Local layout-aware pipelines#
These run ML models locally to understand page layout, then emit structured output (usually Markdown or a document tree):
- Docling (IBM, 2.147.0, MIT, Python ≥3.10 <4.0):
DocumentConverter().convert(path)→result.document.export_to_markdown()/.export_to_dict()/.iterate_items(). Handles PDF, DOCX, PPTX, HTML, images; has a VLM pipeline option (--pipeline vlm). Heavy first run (model downloads), CPU-capable but GPU-preferred. - Unstructured (0.27.36, Apache-2.0, Python ≥3.11 <3.14):
partition_pdf(filename=..., strategy="auto")→ typed elements (Title, NarrativeText, Table, Image, ListItem...) viaunstructured.partition.pdf. Theunstructured[pdf]extra still needs poppler-utils and tesseract on the system. Suited to RAG element pipelines. - marker (
marker-pdf2.1.0, Apache-2.0):marker_single file.pdfCLI →file.md+ extracted images;--mode balanced|fast,--use_llmfor VLM cleanup,--output_format markdown|json|html|chunks. Needs PyTorch; GPU strongly preferred, CPU slow. - MinerU (4.1.7): strong on papers, forms, tables → Markdown/JSON. CLI
mineru parse doc.pdf --pages all -o doc.md(defaults to first 10 pages and a 30k-char stdout window — read the CLI docs). Licence: Apache-2.0 plus extra terms — commercial licence required above 100M MAU or $20M monthly revenue, and online services must attribute MinerU. - OpenDataLoader PDF (
opendataloader-pdf2.5.20, Apache-2.0 for the core from 2.0 on; earlier releases were MPL-2.0): a PDF-first extractor whose core is Java (so you need Java 11+ installed) with a Python wrapper (opendataloader_pdf.convert(...)). It returns JSON with bounding boxes and element types, Markdown, HTML or plain text, can read an existing structure tree, and has a hybrid mode that keeps simple pages on a fast local path and sends hard ones (borderless tables, scans, formulas) to a local AI backend. Its speed and accuracy numbers are the project's own benchmark claims: re-measure on your documents (05.10) before believing them. Source: the project's GitHub README, read November 2026. - Open-weight document VLMs (olmOCR, PaddleOCR-VL, DeepSeek-OCR, Granite-Docling, Chandra and similar): small vision-language models trained to turn a page image into Markdown, run on your own GPU. They sit between the layout pipelines above and the frontier-model route of Part 8. Their licences differ sharply (one has revenue limits), so they are compared, with licences and hardware needs, in 05.4, 2.4.1.
- MarkItDown (Microsoft, 0.1.9, MIT):
markitdown[pdf]→MarkItDown().convert(path).text_content. A universal file→Markdown front door; its PDF path uses pdfminer.six-class extraction, so treat it as convenience, not quality. Has amarkitdown-ocrplugin and optional cloud converters (Azure Document Intelligence / Content Understanding) for scanned docs.
7.2 Hosted parsers and OCR services#
When accuracy matters more than cost-per-page or data residency, hosted document AI wins. All prices below are pay-as-you-go list prices as of November 2026 — verify before budgeting:
| Service | What it does | Price structure (Nov 2026) |
|---|---|---|
| LlamaParse (LlamaIndex) | PDF→Markdown/JSON, layout-aware, citations, 130+ formats | Credits: $1.50/1K credits PAYG, $1.25/1K on Pro. Parse tiers: Fast 1, Cost-effective 3, Agentic 10, Agentic Plus 45 credits/page (+3 layout extraction; presets like Invoice 90). Re-parse of cached file = 0 credits |
| Mistral OCR | POST /v1/ocr → Markdown + bounding boxes + block confidence |
OCR 4.1: $4/1K pages ($5/1K annotated); OCR 3: $2/1K. Batch API 50% off |
| AWS Textract | DetectDocumentText (OCR), AnalyzeDocument (Tables/Forms/Queries/LAYOUT/Signatures), AnalyzeExpense/ID | DetectDocumentText $1.50/1K pages; Tables $15/1K; Forms $50/1K; Queries $15/1K; Layout $4/1K; Signatures $3.50/1K; Expense ~$10/1K; ID $25/1K. 3-month free tier |
| Google Document AI | Processors: Enterprise Document OCR, Layout Parser, Form Parser, Custom extractor/splitter/classifier | Enterprise OCR $1.50/1K (first 1K free); Layout Parser $10/1K; Form Parser/Custom extractor $30/1K; Custom splitter/classifier $5/1K; pretrained Invoice/Expense bill per "count" (up to 10 pages) |
| Azure AI Document Intelligence | prebuilt-read, prebuilt-layout, prebuilt-invoice/receipt/idDocument, custom models | Read $1.50/1K; Layout & prebuilts $10/1K; custom extraction $30/1K; classifier $3/1K; add-ons ~$6/1K each; queryFields ~$10/1K. F0 free tier 500 pages/mo but only first 2 pages per request |
Notes: Textract and Document AI are the heavyweight enterprise options (AWS/GCP ecosystems, strongest forms/tables/extraction); Mistral OCR is the simplest synchronous "PDF→Markdown" API; LlamaParse is the most LLM-pipeline-native (citations, confidence, SDKs). Reducto (parse, extract, split and classify APIs with citations and bounding boxes) is the other hosted option you will meet; its page-based pricing was checked on 8 November 2026 in 09.2, 2.4, so it is not repeated here. Watch the Mistral price by route: the first-party API charges $4/1K pages (OCR 4.1), while OpenRouter's mistral-ocr engine charges $2/1K — same product name, two prices (03.6). All send document content to a third party — privacy review per 02.9, Part 9 before routing customer documents through them.
7.3 Choosing#
| Scenario | Recommendation |
|---|---|
| Simple born-digital text PDFs, bulk | pypdf/pdfplumber or PyMuPDF/pypdfium2 |
| Tables matter, ruled grids | pdfplumber / camelot lattice |
| Borderless/complex tables, formulas | Docling, marker, MinerU, or hosted |
| Scanned docs | OCR pipeline (05.4) or Mistral OCR / Textract / VLM |
| Need Markdown fast, permissive licence | Docling or MarkItDown (MIT). PyMuPDF's doc.to_markdown() is quick too, but it is AGPL/commercial: only if 2.5 is acceptable for your product |
| Enterprise forms/invoices at scale | Textract / Document AI / Azure DI custom models |
| Best accuracy, budget OK, privacy OK | LlamaParse Agentic / Mistral OCR / VLM hybrid |
Part 8: Sending PDFs to an LLM#
Deep-dive
Lesson 03.6 owns the request mechanics — input_file on OpenAI Responses, document blocks on Anthropic, PDF parts on Gemini, OpenRouter's file-parser plugin — and its media-token estimator shows how to cost a PDF before sending. This part covers the data-engineering decisions on top.
8.1 The two routes#
- Whole PDF: send the file; the provider extracts text and renders page images for the model (03.6, 4.1). Simplest; billed per page-image + text tokens; page limits apply (Anthropic 600 pages/request, Gemini 1,000, OpenAI 50 MB).
- Page images: rasterise pages yourself (
get_pixmap,pdftoppm,page.render) and sendinput_image/imageparts. More control — you choose DPI, crop regions, split pages — and you can mix with your own extracted text. More code; same per-page cost class.
For transcription (PDF→clean text/Markdown), the prompt is everything: ask for faithful transcription, not summarisation.
8.2 What it costs: page-based billing#
Cost is driven by page count × per-page tokens, not file size. Per 03.6: Anthropic charges ~1,500–3,000 text tokens per page plus each page's image at image rates; Gemini charges a media_resolution budget per page (280/560/1,120 tokens); OpenAI bills extracted text + page images per its vision rules. Estimate with the 03.6 estimator, confirm with counting endpoints (03.7), and batch large jobs (03.9). A pure-Python sketch:
# vlm_cost.py — run it: python vlm_cost.py
def vlm_cost_per_page(page_image_tokens, page_text_tokens,
input_usd_per_1m, output_usd_per_1m, out_tokens=900):
"""Parameters are YOUR prices — plug in real ones from the provider's
pricing page; never hard-code. Output tokens ~ markdown for one page."""
return ((page_image_tokens + page_text_tokens) / 1e6 * input_usd_per_1m
+ out_tokens / 1e6 * output_usd_per_1m)
for img_tok in [560, 1120, 2500]: # e.g. Gemini media_resolution budgets
c = vlm_cost_per_page(img_tok, 1800, 0.10, 0.40) # example prices
print(f" image={img_tok}tok + 1800 text tok -> ~${c:.4f}/page")
print(f" 300-page doc ~ ${vlm_cost_per_page(1120, 1800, 0.10, 0.40) * 300:.2f}") image=560tok + 1800 text tok -> ~$0.0006/page
image=1120tok + 1800 text tok -> ~$0.0007/page
image=2500tok + 1800 text tok -> ~$0.0008/page
300-page doc ~ $0.20(Prices above are placeholders to show the arithmetic; a frontier model costs substantially more — always compute from the live price table.)
8.3 Faithful transcription prompts#
The failure mode is the model helpfully summarising. Prompt gallery (adapt per provider; mechanics in 03.6):
- Whole-document: "Transcribe this PDF to Markdown faithfully. Preserve headings, lists, tables (as Markdown tables), and page breaks as
<!-- page N -->. Do not summarise, interpret, or omit anything. Mark illegible regions[illegible]." - Page-by-page: same prompt per page image; stitch with page markers so you keep provenance.
- Tables: "Reproduce each table as a Markdown table with the header row repeated. If a cell is unreadable write
?." - Forms: "Extract all form fields as JSON: {field_name: value}."
Provider sample — OpenAI Responses, page-image route (illustrative; request shape per 03.6):
# s8_3_vlm_transcribe.py
"""Send one rendered PDF page to a VLM for faithful transcription."""
import base64
from pathlib import Path
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
client = OpenAI()
img_b64 = base64.b64encode(Path("page1.png").read_bytes()).decode("ascii")
r = client.responses.create(
model="gpt-6-luna",
input=[{"role": "user", "content": [
{"type": "input_image",
"image_url": f"data:image/png;base64,{img_b64}", "detail": "high"},
{"type": "input_text", "text":
"Transcribe this page to Markdown faithfully. Preserve headings, lists and "
"tables. Do not summarise. Mark illegible regions [illegible]."},
]}],
reasoning={"effort": "none"},
max_output_tokens=4000,
)
print(r.output_text)<!-- page 1 -->
# Acme Product Handbook
Version 3.2 — January 2026
## 1. Introduction
Welcome to the Acme product handbook. This guide covers installation, ...Anthropic (document block with base64 PDF), Gemini (PDF Part), and OpenRouter (file part / file-parser plugin) variants are in 03.6, 4.3–4.6; the prompt is what changes for transcription.
8.4 The risks: hallucination, omission, cost#
- Hallucination: VLMs invent plausible text on degraded scans — the same failure as OCR post-correction (05.4). Mitigate: faithful-transcription prompts, cross-check against a classical extraction or second engine, human review of low-confidence pages.
- Omission: dense pages lose content silently — especially footnotes, marginalia, table cells. Mitigate: page-by-page (not whole-doc) processing, output length checks, spot-diff against
charscount. - Cost/latency: per-page pricing × thousands of pages adds up; batch APIs (03.9) cut cost ~50% on supported providers; cache by content hash (05.9).
- Verification strategy: sample N pages per document, run both classical and VLM extraction, diff; escalate the whole document if divergence is high.
8.5 The hybrid strategy#
The production answer is almost never "VLM everything" or "classical everything":
flowchart TD
A[PDF page] --> B["Text coverage check<br/>(1.5)"]
B -->|born-digital| C[Classical extract<br/>pypdf/pdfplumber/PyMuPDF]
B -->|suspect-scanned| D{OCR route<br/>05.4}
C --> E{Quality gates:<br/>tables found? garbage ratio?<br/>reading order sane?}
E -->|pass| F[ParsedDocument]
E -->|fail: hard table / garbled / dense figure| G[Escalate page to VLM<br/>rasterise + transcribe]
D --> H{OCR confidence / VLM needed?}
H -->|pass| F
H -->|low confidence| G
G --> FClassical first (cheap, deterministic, private), escalate only the pages that fail quality gates (accurate where it counts, cost bounded). The gates themselves are 05.10's subject; here you implement the routing.
Part 9: The ParsedDocument model#
Everything above produces heterogeneous output; your pipeline needs one shape. This model is defined here in full — 05.5 cleans inside it, 05.6 chunks it, 05.8 extends its metadata. Keep it deliberately flat and provenance-rich.
# parsed_document.py — the module's canonical parse output (pydantic 2.x)
from __future__ import annotations
from typing import Literal
from pydantic import BaseModel, Field
class BBox(BaseModel):
"""Axis-aligned rectangle in points, top-left origin — the convention
pdfplumber and PyMuPDF emit (they flip PDF's native bottom-left origin)."""
x0: float
y0: float
x1: float
y1: float
class TextBlock(BaseModel):
kind: Literal["heading", "paragraph", "list_item", "caption",
"header", "footer", "footnote", "sidebar", "other"] = "paragraph"
text: str
page: int # 1-based physical page index
page_label: str | None = None # printed label if /PageLabels exists
bbox: BBox | None = None
level: int | None = None # heading level 1-6 when known
font_size: float | None = None # for debugging heading heuristics
class TableBlock(BaseModel):
rows: list[list[str | None]]
page: int
bbox: BBox | None = None
caption: str | None = None
header_rows: int = 1 # how many leading rows are headers
format: Literal["markdown", "csv", "json", "rows"] = "markdown"
class ImageBlock(BaseModel):
page: int
bbox: BBox | None = None
xref: int | None = None # PDF image object id when known
caption: str | None = None
description: str | None = None # VLM-generated, if produced
class ParsedPage(BaseModel):
page_number: int # 1-based
page_label: str | None = None
width: float # points
height: float
rotation: int = 0
text_blocks: list[TextBlock] = Field(default_factory=list)
tables: list[TableBlock] = Field(default_factory=list)
images: list[ImageBlock] = Field(default_factory=list)
links: list[dict] = Field(default_factory=list)
char_count: int = 0
coverage_ratio: float = 0.0 # born-digital heuristic from 1.5
needs_ocr: bool = False
needs_review: bool = False # every engine failed — quarantined
warnings: list[str] = Field(default_factory=list)
class ParseInfo(BaseModel):
parser: str # e.g. "pdfplumber", "pymupdf", "vlm"
parser_version: str
encrypted: bool = False
page_count: int
toc: list[tuple[int, str, int]] = Field(default_factory=list) # (level,title,page)
form_fields: dict[str, str] = Field(default_factory=dict)
metadata: dict[str, str] = Field(default_factory=dict)
attachments: list[str] = Field(default_factory=list)
class ParsedDocument(BaseModel):
source: str # path or URI
source_hash: str # sha256 of raw file bytes — change detection (05.9)
info: ParseInfo
pages: list[ParsedPage]
warnings: list[str] = Field(default_factory=list)
# `content_hash` is deliberately absent: 05.8 defines it as the SHA-256 of
# the canonical *cleaned* text — computed by the cleaning/metadata stages
# (05.5/05.8), never at parse time. `source_hash` (raw bytes) is the
# parse-time key; the two hashes answer different questions.Filling it is mechanical: each parser adapter maps its native output into these types. PyMuPDF "dict" → TextBlocks; pdfplumber find_tables()+.extract() → TableBlocks (with bbox); page.get_images/page.images → ImageBlocks; get_toc/outline → info.toc; get_fields/metadata/attachments → info. The adapters are where per-parser quirks live — keep them thin.
Part 10: A production parsing function#
Deep-dive
10.1 The pipeline#
flowchart LR
F[PDF file] --> P[Probe: pypdf<br/>pages, encrypted, metadata,<br/>outline, forms, attachments]
P --> Q{Per-page<br/>coverage check}
Q -->|born-digital| R[Classical extract<br/>pdfplumber/PyMuPDF<br/>blocks+tables+images]
Q -->|suspect| S[OCR/VLM route<br/>→ 05.4]
R --> T[Quality gates:<br/>empty pages? garbage?<br/>table failures?]
T -->|fail| U[Escalate page<br/>to VLM]
T -->|pass| V[ParsedDocument]
S --> V
U --> V
V --> W[Quarantine failures<br/>+ warnings]10.2 The complete function with fallbacks#
# parse_pdf.py — the module's reference parser. Illustrative output.
"""parse_pdf: probe -> per-page route (pdfplumber, PyMuPDF fallback)
-> ParsedDocument, with per-page isolation and quarantine."""
from __future__ import annotations
import hashlib
from pathlib import Path
# models live in parsed_document.py — same folder:
# from parsed_document import (BBox, TextBlock, TableBlock, ImageBlock,
# ParsedPage, ParseInfo, ParsedDocument)
def _sha256_file(path: Path) -> str:
"""Streamed hash — don't slurp a 2 GB PDF into memory for it."""
h = hashlib.sha256()
with open(path, "rb") as fh:
for chunk in iter(lambda: fh.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def _flatten_outline(items, level: int = 1):
"""reader.outline is a nested list: Destination | [children...]."""
for item in items or []:
if isinstance(item, list):
yield from _flatten_outline(item, level + 1)
else:
yield level, item
def _probe(path: Path):
"""pypdf pass: metadata, encryption, TOC, forms, attachments. Cheap."""
import pypdf
from pypdf import PdfReader
reader = PdfReader(str(path))
info = ParseInfo(
# record the version actually installed: lineage must not lie after an upgrade
parser="pypdf", parser_version=pypdf.__version__,
encrypted=reader.is_encrypted,
page_count=len(reader.pages),
)
meta = reader.metadata # DocumentInformation — a dict subclass
if meta: # keys are '/Title', '/Author', ...
info.metadata = {k.lstrip("/"): str(v)
for k, v in meta.items() if v}
try:
for level, dest in _flatten_outline(reader.outline):
page_no = reader.get_destination_page_number(dest)
if page_no is not None:
info.toc.append((level, str(dest.title or ""), page_no + 1))
except Exception:
pass # malformed outlines are common
try:
info.attachments = list(reader.attachments.keys())
except Exception:
pass
try:
fields = reader.get_fields() or {}
info.form_fields = {k: str(v.get("/V", "")) for k, v in fields.items()}
except Exception:
pass
if reader.is_encrypted:
reader.decrypt("") # empty password covers many 'encrypted' PDFs
return reader, info
def _coverage(text_len: int, area: float = 612 * 792) -> float:
return text_len / (area * 0.0015) if area else 0.0
def _lines_from_chars(chars, y_tol: float = 2.0):
"""Group pdfplumber char dicts into visual lines by 'top' coordinate.
Simplified: same-baseline chars across columns merge into one line —
real reading order is 3.1's XY-cut problem, not solved here."""
rows: list[list[dict]] = []
for ch in sorted(chars, key=lambda c: (c["top"], c["x0"])):
if rows and abs(ch["top"] - rows[-1][0]["top"]) <= y_tol:
rows[-1].append(ch)
else:
rows.append([ch])
return rows
def _extract_page_pdfplumber(page, page_no: int) -> ParsedPage:
"""One page via pdfplumber: line-grouped text + tables + image bboxes."""
out = ParsedPage(page_number=page_no, width=float(page.width),
height=float(page.height), rotation=int(page.rotation))
text = page.extract_text() or ""
out.char_count = len(text)
out.coverage_ratio = _coverage(out.char_count, page.width * page.height)
out.needs_ocr = out.coverage_ratio < 0.4
for row in _lines_from_chars(page.chars):
chars = sorted(row, key=lambda c: c["x0"])
line_text = "".join(c["text"] for c in chars).strip()
if not line_text:
continue
out.text_blocks.append(TextBlock(
kind="paragraph", text=line_text, page=page_no,
bbox=BBox(x0=min(c["x0"] for c in chars),
y0=min(c["top"] for c in chars),
x1=max(c["x1"] for c in chars),
y1=max(c["bottom"] for c in chars)),
font_size=max(c.get("size", 0.0) for c in chars) or None))
# find_tables() (not extract_tables) keeps each table's bbox
for tbl in page.find_tables() or []:
x0, top, x1, bottom = tbl.bbox
out.tables.append(TableBlock(
rows=tbl.extract() or [], page=page_no,
bbox=BBox(x0=x0, y0=top, x1=x1, y1=bottom)))
for im in page.images: # image dicts carry x0/top/x1/bottom
out.images.append(ImageBlock(
page=page_no,
bbox=BBox(x0=im["x0"], y0=im["top"],
x1=im["x1"], y1=im["bottom"])))
return out
def _extract_page_pymupdf(pymupdf_page, page_no: int) -> ParsedPage:
"""Fallback adapter: PyMuPDF 'dict' mode -> ParsedPage."""
out = ParsedPage(page_number=page_no,
width=float(pymupdf_page.rect.width),
height=float(pymupdf_page.rect.height),
rotation=int(pymupdf_page.rotation))
for b in pymupdf_page.get_text("dict").get("blocks", []):
r = b["bbox"]
bbox = BBox(x0=r[0], y0=r[1], x1=r[2], y1=r[3])
if b.get("type") == 0: # text block -> lines -> spans
for line in b.get("lines", []):
text = "".join(s.get("text", "")
for s in line.get("spans", [])).strip()
if not text:
continue
size = max((s.get("size", 0.0)
for s in line.get("spans", [])), default=0.0)
out.text_blocks.append(TextBlock(
kind="paragraph", text=text, page=page_no,
bbox=bbox, font_size=size or None))
elif b.get("type") == 1: # image block
out.images.append(ImageBlock(page=page_no, bbox=bbox))
out.char_count = len(pymupdf_page.get_text("text"))
out.coverage_ratio = _coverage(
out.char_count,
pymupdf_page.rect.width * pymupdf_page.rect.height)
out.needs_ocr = out.coverage_ratio < 0.4
return out
def _page_dims(reader, i: int) -> tuple[float, float]:
"""Best-effort page size from the pypdf probe, for quarantine pages."""
try:
mb = reader.pages[i].mediabox
return float(mb.width), float(mb.height)
except Exception:
return 0.0, 0.0
def parse_pdf(path: str | Path) -> ParsedDocument:
"""Probe once -> pdfplumber per page -> PyMuPDF fallback -> quarantine."""
path = Path(path)
doc_hash = _sha256_file(path)
warnings: list[str] = []
reader, info = _probe(path) # reader stays open for _page_dims
engines = [("pypdf", info.parser_version)]
pages: list[ParsedPage | None] = [None] * info.page_count
pending: set[int] = set()
# Route 1: pdfplumber — richest geometry, slowest.
try:
import pdfplumber
with pdfplumber.open(str(path)) as pdf:
engines.append(("pdfplumber",
getattr(pdfplumber, "__version__", "?")))
if len(pdf.pages) != info.page_count:
warnings.append(
f"page-count mismatch: pypdf={info.page_count} "
f"pdfplumber={len(pdf.pages)}")
info.page_count = len(pdf.pages)
pages = [None] * info.page_count
for i, page in enumerate(pdf.pages):
try:
pages[i] = _extract_page_pdfplumber(page, i + 1)
except Exception as exc: # per-page isolation
pending.add(i)
pages[i] = ParsedPage(
page_number=i + 1, width=float(page.width),
height=float(page.height),
warnings=[f"pdfplumber: {exc}"])
except Exception as exc:
warnings.append(f"pdfplumber could not open file: {exc}")
# Route 2: PyMuPDF — per-page fallback, or whole file if route 1 never ran.
failed = sorted(pending | {i for i, p in enumerate(pages) if p is None})
if failed:
try:
import pymupdf
with pymupdf.open(str(path)) as doc:
engines.append(("pymupdf", pymupdf.pymupdf_version))
if doc.needs_pass:
doc.authenticate("") # empty password only; real ones -> quarantine
for i in failed:
try:
parsed = _extract_page_pymupdf(doc[i], i + 1)
prior = pages[i]
if prior is not None and prior.warnings:
# keep route-1's error for audit
parsed.warnings = prior.warnings + [
"recovered via pymupdf fallback"]
pages[i] = parsed
except Exception as exc:
w, h = _page_dims(reader, i)
p = pages[i] or ParsedPage(page_number=i + 1,
width=w, height=h)
p.needs_review = True
p.warnings.append(f"pymupdf fallback failed: {exc}")
pages[i] = p
except Exception as exc:
warnings.append(f"pymupdf fallback unavailable: {exc}")
for i in failed:
w, h = _page_dims(reader, i)
p = pages[i] or ParsedPage(page_number=i + 1,
width=w, height=h)
p.needs_review = True
p.warnings.append(f"no engine could parse this page: {exc}")
pages[i] = p
# Nothing may be silently dropped — sweep any page no route reached.
for i, p in enumerate(pages):
if p is None:
w, h = _page_dims(reader, i)
pages[i] = ParsedPage(page_number=i + 1, width=w, height=h,
needs_review=True,
warnings=["page missing from all routes"])
reader.close()
# Route 3 boundary: scanned pages -> 05.4's OCR pipeline; VLM escalation
# for hard pages is the quality-gate path in 8.5/10.5.
for p in pages:
if p.needs_review:
p.warnings.append("quarantined — route to manual review or fix the file")
elif p.needs_ocr:
p.warnings.append("routed to OCR/VLM — see 05.4")
info.parser = "+".join(name for name, _ in engines)
info.parser_version = ", ".join(f"{n}=={v}" for n, v in engines)
return ParsedDocument(source=str(path), source_hash=doc_hash,
info=info,
pages=[p for p in pages if p is not None],
warnings=warnings)The shape is the contract: probe once with pypdf (cheap, and it reads everything around the text — metadata, outline→info.toc, AcroForm fields, attachments), route per page (pdfplumber first for its geometry; any page it fails on retries once through the PyMuPDF "dict" adapter), and isolate failures — a page that beats both engines is marked needs_review and quarantined with both exceptions in warnings, while needs_ocr pages are handed to the OCR route (05.4 fills them in; VLM escalation is the quality-gate path in 8.5). source_hash covers the raw bytes for change detection; the content_hash of 05.8 is deliberately not here — it hashes canonical cleaned text, which doesn't exist until 05.5 runs.
What remains honestly simplified: _lines_from_chars is a tolerance bucket, not pdfminer's XY-cut — same-baseline text in two columns still merges into one line until real ordering (3.1) or a layout-aware tool takes over; blocks are per-line rather than merged into paragraphs by font/size (6.1); footnote/sidebar association (3.6) and heading detection are downstream work for 05.5–05.8. What is not simplified: every block carries page + bbox + font_size, tables keep Table.bbox, images keep placement — the provenance 6.4 insists on.
10.3 Scale and robustness#
- Big files: iterate pages, don't hold the document; pdfplumber/pdfminer are the slow path — for bulk use PyMuPDF or pypdfium2, or shard by page range across processes (
ProcessPoolExecutor— parsing is CPU-bound and pages are independent). - Memory: pypdf's warning about giant content streams applies; check
get_contents().get_data()sizes on untrusted input. pdfplumber holds per-page object lists — fine per page, don't accumulate all pages'.chars. - Encrypted:
is_encrypted→decrypt(password); try the empty password first (many "encrypted" PDFs use it). Never brute-force passwords — that's both slow and a security smell; route to a human or reject. - Corrupt/malformed:
strict=Falseeverywhere in production; wrap per-file and per-page in try/except; quarantine failures to afailed/folder with the exception + file hash rather than dropping silently. - Timeouts: wrap CLI tools (
pdftotext,marker_single) in subprocess timeouts; for libraries, per-page work is bounded enough that file-level timeouts suffice. - Idempotent outputs: deterministic page order, stable block ordering (sort by
(page, y, x)),source_hash-keyed outputs — re-running on the same file produces an identicalParsedDocument(05.9 depends on this). - Hidden traps: linearized PDFs, object streams,
/PieceInfoprivate data, PDF portfolios (a PDF containing other PDFs —reader.attachments/embedded files), and PDFs that are actually something else (check the%PDF-magic bytes, not the extension — 03.6, 1.6).
10.4 The failure gallery#
| Failure | Symptom | Detection | Fix |
|---|---|---|---|
| Two-column interleave | sentences from left/right columns alternate | x-position clustering shows two bands | column-aware sort or layout-aware tool |
| Header/footer pollution | same line in every chunk | repetition across pages + edge position | strip by page+bbox before chunking |
| Hyphenation | exam-/ple splits |
lines ending - + lowercase next |
rejoin in cleaning (05.5) |
| Ligature garbage | fi/fl or missing chars |
unicode scan for PUA/ligature codepoints | normalise or extractor flags |
| Flattened table | numbers attach to wrong rows | table detector finds grid but extraction empty | pdfplumber/camelot/VLM route |
| Scanned page | ~0 chars extracted | coverage_ratio < 0.4 | OCR/VLM route |
| Rotated page | text extracted but jumbled/sideways | /Rotate ≠ 0 or vertical char runs |
derotate or rotation-aware extract |
| Hidden OCR layer | doubled text on scans | char count ≫ visual text; invisible render mode | dedupe chars; -noinvis |
| Password-protected | is_encrypted, empty extract |
probe | decrypt with provided password only |
| Huge file | minutes per page, GBs RAM | page count, stream sizes | shard pages, faster engine, streaming |
| Corrupt xref | parser exception on open | try/except at open | quarantine; try alternate parser |
| Math mangled | x2 for x², broken formulas |
domain knowledge / spot check | LaTeX-aware tool (marker/MinerU/Docling) |
| Form fields missed | text extract empty on a form | get_fields() returns values |
use AcroForm fields first |
10.5 The decision table#
| Document type | First choice | Escalate to |
|---|---|---|
| Born-digital prose PDF | pypdf/pdfplumber text | — |
| Bulk corpus, speed matters | PyMuPDF / pypdfium2 | — |
| Tables (ruled) | pdfplumber / camelot lattice |
VLM page image |
| Tables (borderless/complex) | Docling / marker / hosted | VLM |
| Scanned | OCR (05.4) | VLM transcription |
| Forms | get_fields() / AcroForm |
VLM field extraction |
| Markdown output wanted | doc.to_markdown() / Docling / MarkItDown |
— |
| Enterprise accuracy | Textract / Document AI / Azure DI | — |
| Mixed bag, budget OK | hybrid: classical → per-page VLM | — |
Common misconceptions#
| Misconception | Reality |
|---|---|
| "A PDF is a document format like DOCX." | It's a page-description format: glyphs at coordinates. Structure must be reconstructed. |
| "If text extracts, the PDF parsed correctly." | Extraction can return plausible-looking garbage: wrong order, flattened tables, hidden text. Always spot-check. |
"pdftotext/any extractor gives reading order." |
File order ≠ read order. Multi-column pages interleave unless you sort or use a layout-aware tool. |
| "Scanned PDFs have no text, so extraction returns empty." | Often there's an invisible OCR text layer — which may be duplicated, misaligned, or absent entirely. Check per page. |
| "PyMuPDF is always the best choice." | Fastest and richest, but AGPL/commercial licence and sometimes too much structure you don't need. Match tool to job. |
| "Tables are just text with spaces." | They're geometry problems: ruled vs borderless, merged cells, spanning pages. Dedicated extractors exist for a reason. |
| "Sending the PDF to GPT is always simplest and best." | It's per-page cost, page limits, hallucination/omission risk, and your data leaves the building. Classical first, VLM for hard pages. |
| "A VLM transcription is ground truth." | It hallucinates and omits like any generative model. Verify by sampling and cross-checking. |
| "Metadata (title/author) is reliable." | Frequently empty or wrong. Treat as hints; content hash + page/bbox provenance is what you can trust. |
| "Encrypted means unusable." | Many PDFs use an empty user password — decrypt("") opens them. Real passwords: ask, never brute-force. |
| "One parser for the whole corpus." | Documents differ wildly. Route per page/per document by coverage and quality gates. |
Key takeaways#
- A PDF is drawing instructions, not a document: no paragraphs, headings, tables or reading order — all reconstructed.
- Born-digital vs scanned is the first routing decision; detect per page via text coverage, not per file.
- The toolbox: pypdf (metadata/forms/encryption), pdfminer.six (layout objects), pdfplumber (geometry+tables), PyMuPDF (speed+structure, AGPL), pypdfium2 (PDFium), Poppler (CLI), camelot (ruled tables), Docling/Unstructured/marker/MinerU/MarkItDown (layout-aware→Markdown), hosted (LlamaParse/Mistral OCR/Document AI/Azure DI/Textract).
- Layout failures — columns, headers/footers, hyphenation, ligatures, rotated/RTL text, hidden text, math — are detectable and routable, not mysterious.
- Tables need dedicated extraction and a deliberate representation choice (Markdown/CSV/JSON/row-sentences) with headers preserved.
- Structure recovery uses outlines, font heuristics, links and — above all — page/bbox provenance for citations.
- LLM/VLM conversion is a first-class option but per-page cost, hallucination and omission make the hybrid strategy (classical → escalate hard pages) the production default.
- The
ParsedDocumentmodel + probe→route→isolate pipeline is the contract the rest of the module builds on.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Page-description format | A format storing how to paint each page (glyphs at coordinates), not document structure |
| Glyph | The visual shape of a character in a font |
| Content stream | The per-page drawing program inside a PDF (text, lines, images) |
| Indirect object / xref table | Numbered PDF objects + the byte-offset index that locates them |
| Font encoding / ToUnicode CMap | How character codes map to glyphs / to Unicode characters |
| CID font | A font addressed by character-collection IDs (common for CJK and embedded fonts) |
| Ligature | A single glyph for a multi-letter combination (fi, fl) |
| Tagged PDF | A PDF with a structure tree (/StructTreeRoot) marking headings, tables, alt text |
| AcroForm | Interactive PDF form fields with names and stored values |
| Outline / bookmarks | The sidebar table-of-contents tree of a PDF |
| Born-digital vs scanned | PDF with real text operations vs one that is only page images |
| Text coverage / coverage ratio | Extracted-chars heuristic for detecting scanned pages |
| Reading order / XY-cut | The order a human reads vs the recursive whitespace-split algorithm that approximates it |
| Header/footer boilerplate | Repeated marginal text detected by repetition + position |
| Footnote, endnote, sidebar | Small-print notes: in-text markers paired with bodies at page bottom or document end; margin bands beside the main column |
| pdfplumber geometry objects | .chars, .lines, .rects, .curves, .images, .annots per page |
Table strategy (lines/text/explicit) |
How pdfplumber/camelot detect table grids |
| Parsing report | camelot's per-table accuracy/whitespace quality metrics |
| Layout-aware pipeline | ML-based PDF→structured-document tools (Docling, marker, MinerU) |
| Hosted document AI | Per-page-priced parsing/OCR services (Textract, Document AI, Azure DI, LlamaParse, Mistral OCR) |
| Faithful transcription | Prompting a VLM to reproduce text exactly rather than summarise |
| Hybrid strategy | Classical extraction first; escalate only failed/hard pages to VLM |
ParsedDocument |
This lesson's canonical parse-output model (pages, blocks, tables, provenance) |
| Provenance (page/bbox) | The page number and coordinates recording where extracted content came from |
All terms are also collected in the glossary.
Exercises#
- Toy PDF + probe. Generate the running corpus with
scripts/make_corpus.pyfrom 05.1, Part 8 (it writesdata/corpus/handbook/product-handbook.pdf, a real text-layer PDF) and open that file withpypdf: printlen(reader.pages),reader.metadata,reader.pdf_header. Then tryreader.is_encrypted. - Coverage router. Extend
page_coverageinto a functionroute_page(text, area)returning"text" | "ocr" | "vlm"with two thresholds, and test it on synthetic char counts including edge cases (empty string, exactly-at-threshold). - Boilerplate detector. Improve
find_repeatedto also catchPage \d+ of \d+by normalising digits before grouping, and to flag lines only in the top/bottom 8% of the page as header/footer candidates. - Table representation. Take a 4×5
list[list[str]]table and write three renderers: Markdown, CSV, and row-sentences. Compare token counts roughly (chars/4) and argue which you'd pick for a support-ticket corpus. - Font-heuristic headings. Using pdfplumber
chars, group spans by(fontname, size)on a real PDF and list candidate headings (size > body median + 2). Check against the PDF outline — where do they disagree? - Cost model. Using
vlm_cost_per_page, compute the cost of transcribing a 250-page contract at threemedia_resolutionbudgets with your chosen provider's real prices (look them up — don't use the placeholders). - Hybrid gate. Write the quality-gate function
needs_escalation(page: ParsedPage) -> boolimplementing three rules: coverage < 0.4, any table with >50% empty cells, orchar_count == 0with images present. - Licence audit. For each library in the comparison table, look up its licence and write one sentence on whether you could ship it inside a commercial SaaS product.
- Footnote associator. Using pdfplumber
chars/lines/rects, writefind_footnotes(page)returning(marker_bbox, marker_text, note_text, note_bbox)per footnote: cluster chars in the bottom ~15% of the page below the lowest body-textbottom, split notes on the separator rule inpage.lines, and match each note's leading^\d+/^[*†‡]marker to the nearest superscript char (smallersize, raisedtop) in the body. Generate a two-footnote test PDF with reportlab and check the pairings.
Hints and worked answers
reader = PdfReader("data/corpus/handbook/product-handbook.pdf"). Expect 2 pages (the generator writes 67 lines at up to 46 lines per page),reader.metadataasNone(the generator writes no/Infodictionary, so guard withif reader.metadata:),reader.pdf_header == "%PDF-1.4"andreader.is_encrypted == False. The point ofNoneis the lesson: metadata is optional.- A shape that works:
ratio = len(text) / (area * 0.0015);if ratio >= 0.4: "text",elif ratio >= 0.1: "ocr", else"vlm"(a page with almost nothing may be a photo, where classical OCR also fails). Edge cases:""gives ratio 0.0 and must not divide by zero whenarea == 0; a value exactly at 0.4 goes to"text"because the comparison is>=. Write one test per branch and one per boundary. - Normalise with
re.sub(r"\d+", "#", text)before grouping, soPage 1 of 12andPage 2 of 12both becomePage # of #. Keepy_from_top / page_heightwith each entry and only report a repeated line when its ratio is below 0.08 or above 0.92 on most of its pages. Test with a body line that repeats mid-page (for example a table header): it must not be flagged. - Cell-wise the three renderers are short: Markdown joins with
" | "and adds a---row; CSV usescsv.writerintoio.StringIO; row-sentences use", ".join(f"{h} {v}" ...). Token estimate islen(text) / 4. Typically Markdown is the cheapest and row-sentences the most verbose; for tickets, where each row is queried alone, row-sentences usually retrieve best, and the extra tokens buy self-contained chunks. - Group
page.charsby(fontname, round(size, 1)); compute the median size weighted by character count (that is the body size); candidates are runs whose size is at least 2 pt above it, or bold at body size, alone on their line. Disagreements with the outline usually fall in three classes: running headers set in a larger font (false positives), unbookmarked sub-headings (outline misses), and bookmarks whose titles differ from the printed ones. cost = vlm_cost_per_page(image_tokens, text_tokens, in_price, out_price) * 250. Use the provider's pricing page forin_price/out_priceand the 03.6 estimator for tokens, then report all three results and whichmedia_resolutionyou would choose and why (a contract with small print needs the higher budgets).def needs_escalation(page): return page.coverage_ratio < 0.4 or any(t.rows and sum(c in (None, "") for r in t.rows for c in r) / sum(len(r) for r in t.rows) > 0.5 for t in page.tables) or (page.char_count == 0 and bool(page.images)). Guard against emptyrows(division by zero) and write one test per rule, then one page that triggers none.- Use PyPI's licence field and the project's licence file, because they can differ (PyMuPDF is AGPL-3.0 or commercial; MinerU is Apache-2.0 plus extra terms). Typical answers: MIT/BSD/Apache libraries can ship in SaaS with notices kept; AGPL needs your service's source offered to users, or a commercial licence; GPL command-line tools such as Poppler are usually fine when you only call them as a separate process, but get legal advice.
- Build the test PDF with reportlab: two paragraphs with superscript markers (draw the marker with a smaller font size and a raised y), a horizontal
canvas.line, and two notes below it. In pdfplumber the rule shows up inpage.lines(or as a thin rect inpage.rects); notes are the chars whosetopis below it. Expected: two tuples whosemarker_textvalues are1and2. Also test a page with no footnotes (return[]).
Check yourself#
- Why is a PDF called a "page-description format" rather than a "document format"?Because it stores how to paint each page — glyph positions, fonts, lines — not document structure. "Document" properties (paragraphs, headings, tables, order) must be reconstructed.
- What three things does a PDF not store that a DOCX does?Paragraph boundaries, semantic structure (headings/lists/tables as objects), and reading order.
- What is a
ToUnicodeCMap, and what happens when it's missing?The table mapping glyph codes back to Unicode characters. Without it, extraction sees shapes, not letters — output may be glyph codes or garbage; OCR may be the only recourse. - How do you detect whether a PDF page is born-digital or scanned?Per-page text coverage: extract text and compare char count against expected density for the page area; very low coverage ⇒ image-only/scanned.
- Which tool would you pick for bulk extraction of 10,000 simple PDFs, and why?PyMuPDF or pypdfium2 — C-backed engines, dramatically faster than pdfminer/pdfplumber on bulk workloads.
- Why is PyMuPDF's licence a production concern?It's AGPL-3.0 or commercial: using it in a networked service you distribute may require releasing your source or buying a licence.
- What does
sort=Truefix, and what does it not fix?It reorders blocks/words by coordinates — fixes simple ordering. It does not solve true multi-column reading order (XY-cut) or semantic structure. - Name three ways headers/footers/page numbers break chunk quality and how to detect them.They repeat into every chunk (embedding pollution), waste tokens, and can dominate retrieval. Detect by repetition across pages + position near margins; page numbers need pattern/position detection since they differ per page.
- What's the difference between
vertical_strategy: "lines"and"text"in pdfplumber?"lines"detects tables from ruling lines (ruled grids);"text"infers them from whitespace/text alignment (borderless). - When would you choose row-sentences over a Markdown table for LLM consumption?When rows must be independently retrievable/self-contained (support tickets, Q&A) — each row-sentence is a coherent unit; Markdown tables are better for preserving columnar comparison.
- What does
reader.get_fields()give you that text extraction doesn't?AcroForm field names and values — the cleanest read of interactive forms, no OCR needed. - Why is per-page (not per-file) routing essential in a parsing pipeline?Because coverage, quality and failure modes differ per page in mixed documents; per-file routing mis-handles documents that are part scan, part text.
- What are the three main risks of sending a PDF to a VLM for transcription?Hallucination (invented text), omission (dropped content), and per-page cost/latency at scale.
- What is the hybrid strategy, and why is it the production default?Classical extraction first (cheap, deterministic, private), escalating only pages that fail quality gates to a VLM — accurate where needed, cost bounded.
- What provenance must every extracted block carry for citations to work?Page number (physical index + printed label) and bounding box, plus parser name/version — enough to cite and to debug.
Further resources#
- pypdf documentation — https://pypdf.readthedocs.io/ (extract-text guide incl. the "Why Text Extraction is hard" section)
- pdfminer.six documentation — https://pdfminersix.readthedocs.io/
- pdfplumber documentation — https://github.com/jsvine/pdfplumber
- PyMuPDF documentation — https://pymupdf.readthedocs.io/ (text extraction appendix, pymupdf4llm API, licence page)
- pypdfium2 — https://pypdfium2.readthedocs.io/
- Docling — https://docling-project.github.io/docling/
- Unstructured docs — https://docs.unstructured.io/
- marker — https://github.com/datalab-to/marker
- MinerU — https://opendatalab.github.io/MinerU/
- MarkItDown — https://github.com/microsoft/markitdown
- camelot-py — https://camelot-py.readthedocs.io/
- ISO 32000-2:2020 (PDF 2.0 spec) — https://www.iso.org/standard/75839.html — the authoritative format reference (paywalled; the free PDF 1.7 reference is Adobe's https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf)
- Poppler utilities — https://poppler.freedesktop.org/
← 05.1 — Data Sources, Formats and the Ingestion Mindset | Module 05 overview | 05.3 — Parsing HTML, Web Pages and Office Files →