Sub topic 4
Layout, reading order and tables
This chapter assumes you can run the pypdf example from the earlier text extraction chapter. It also assumes you know that a native PDF stores positioned text, not paragraphs. Here you learn how that gap breaks extraction and what to do about it.
Why layout matters
A PDF draws characters at coordinates on a page. It has no built-in notion of "this is a paragraph" or "this is a table row". An extractor has to guess the order in which to read the characters. OCR output has the same problem, because it also returns text fragments with positions.
The guess fails in three common ways:
- Columns merge. A two-column page is read straight across, so lines from the left and right columns are interleaved.
- Tables flatten. Cells become a stream of values with no row or column boundaries. Totals and line items become hard to tell apart.
- Headers and footers intrude. Page numbers and repeated headings appear in the middle of a sentence that spans two pages.
An LLM can often repair mild disorder, but it cannot reliably tell which number belonged to which column once that structure is gone. For example, "2 450.00 900.00" could mean quantity, unit price and total, or something else.
Check the extractor's output
Try both extraction modes and compare them by eye. pypdf (version 3.17 or later) has a layout mode that keeps horizontal spacing.
from pypdf import PdfReader
reader = PdfReader("invoice.pdf")
page = reader.pages[0]
plain = page.extract_text()
layout = page.extract_text(extraction_mode="layout")
print("--- plain ---")
print(plain[:400])
print("--- layout ---")
print(layout[:400])Layout mode pads text with spaces so columns line up. That helps the model, but it costs more tokens. Use it only for pages where plain mode loses structure.
Extract tables separately
When a table matters, extract it with a tool that detects ruled lines or aligned text. pdfplumber does this and returns each table as a list of rows.
import pdfplumber
with pdfplumber.open("invoice.pdf") as pdf:
for page_number, page in enumerate(pdf.pages, start=1):
for table in page.extract_tables():
print(f"Table on page {page_number}")
for row in table:
print(" | ".join(cell or "" for cell in row))Merged cells and tables without borders often come back with None cells or shifted columns. Treat the output as a draft and inspect it.
Then put the table into the prompt in a form the model can read, such as pipe-separated rows under a label like "Line items table". The surrounding prose can go in the same prompt, so the model sees the table's position in the document.
Common errors
- Trusting the first extraction without looking at it. Print a sample page for each new document type.
- Dropping repeated headers and footers after the fact. Strip them, or tell the prompt to ignore them.
- Assuming that cells in the same row are in the same list position. Check the column count of every row.
- Using this path for pages where the layout carries the meaning, such as forms with checkboxes. The next chapter covers sending page images to vision-capable models for those cases.
Exercise
A two-column PDF yields sentences that jump between unrelated topics, but every word is present. What is the likely cause, and what is one fix?
Show answer
The extractor read lines straight across both columns, so the reading order is wrong. Re-extract with layout mode, or crop each column and extract it separately, then join the results in reading order.