Sub topic 4
Layout, Reading Order and Tables
This chapter covers what happens to a page's structure when you pull text out of it. It assumes you can run the PDF extraction from the previous chapters, that you know what a native-text PDF is, and that you have called an LLM with a prompt. Everything here applies to text from native PDFs and to text produced by OCR.
Why structure gets lost
A PDF does not store paragraphs, rows or columns. It stores drawing instructions of the form "put these characters at x=72, y=640 in this font." A text extractor has to guess which characters belong together and in what order to read them.
Plain extraction returns a flat stream of characters. The page's two-dimensional structure is flattened into one dimension, and some of it is lost along the way. The LLM only sees the flat result. If the flattening scrambles the page, the model is working from a scrambled document, and no prompt can reliably repair that.
Three kinds of damage are common:
- Wrong reading order. Text from different columns or boxes is interleaved.
- Broken tables. Cells from a row are separated, or cells from different rows are merged.
- Lost associations. A label such as "Total" ends up many lines away from its value.
Reading order
Reading order is the sequence in which a human would read the text on a page. For a single-column letter it matches the top-to-bottom order of the characters. For a page with a sidebar, two columns, a header block and a footer, it does not.
Many extractors return text in the order the PDF's drawing instructions were written. That order depends on the program that generated the file. It often follows the visual layout, but not always. A page where the "Bill To" address is drawn after the line items can come out in that order.
Typical failures:
| Layout | What goes wrong | Effect on extraction |
|---|---|---|
| Two-column article | Lines from the left and right columns alternate | Sentences are cut in the middle |
| Invoice header with vendor on the left and invoice number on the right | The two blocks merge into one line | Vendor and number are hard to separate |
| Page headers and footers | Repeated text appears between body paragraphs | Noise inside the content |
| Sidebars and call-out boxes | Box text is inserted mid-paragraph | The model attaches it to the wrong field |
Layout-preserving extraction
Many libraries can preserve the visual arrangement by placing text at roughly its original horizontal position. In pypdf, pass extraction_mode="layout":
from pypdf import PdfReader
reader = PdfReader("invoice.pdf")
page = reader.pages[0]
default_text = page.extract_text()
layout_text = page.extract_text(extraction_mode="layout")
print("--- default ---")
print(default_text[:600])
print("--- layout ---")
print(layout_text[:600])Layout mode pads lines with spaces so that columns stay aligned. Two blocks side by side in the PDF remain side by side in the text. This helps a model see that "Invoice No." and its value sit next to each other. It also makes the text longer, because of the padding, so it costs more tokens.
Always compare both outputs on a few real documents before choosing. Neither mode wins on every file.
Other fixes for reading order
- Crop regions. If every document of a type has the same template, extract each region (header, body, totals box) separately and label each one in the prompt.
- Strip repeated lines. Remove headers and footers that appear on every page, such as page numbers and confidentiality notices, before sending the text to the model.
- Use a layout-aware tool. Libraries such as pdfplumber return the position of each word. You can sort words by their coordinates and group them into lines yourself.
Tables
Tables are the hardest case, and they matter most for invoices, statements and reports. A table has meaning in two directions: a cell's value depends on its row label and its column header. Flattened text keeps neither reliably.
Consider this table:
| Description | Qty | Unit price | Amount |
|---|---|---|---|
| Widget | 2 | 10.00 | 20.00 |
| Gadget | 1 | 15.50 | 15.50 |
A plain extractor may return it as:
Description
Qty
Unit price
Amount
Widget
2
10.00
20.00
Gadget
1
15.50
15.50A human can recover the structure. A model usually can too, but when a cell is empty or a description wraps over two lines, the grouping by four stops working and values slip into the wrong columns.
Extracting tables explicitly
pdfplumber has a table finder that uses ruling lines and text alignment:
import pdfplumber
with pdfplumber.open("invoice.pdf") as pdf:
page = pdf.pages[0]
tables = page.extract_tables()
for table in tables:
for row in table:
print(row)Each table comes back as a list of rows, and each row is a list of cell strings. Empty cells are None. This gives you structure you can trust more than a flat stream, but it depends on the PDF having detectable lines or consistent alignment. Tables without borders often need tuning through table_settings, and some will not be found at all.
Giving tables to the model
Once you have rows, convert them to a text format that keeps the column relationships visible. Markdown tables and CSV both work well. Pick one and use it consistently.
def table_to_markdown(rows):
clean = [[(cell or "").replace("\n", " ").strip() for cell in row] for row in rows]
header, *body = clean
lines = ["| " + " | ".join(header) + " |",
"| " + " | ".join("---" for _ in header) + " |"]
for row in body:
lines.append("| " + " | ".join(row) + " |")
return "\n".join(lines)
sample = [["Description", "Qty", "Amount"], ["Widget", "2", "20.00"], ["Gadget", None, "15.50"]]
print(table_to_markdown(sample))The function replaces None with an empty string and removes line breaks inside cells, because a newline would break the row. Then in your prompt, mark the table so the model knows what it is, for example by wrapping it in <table> tags next to the rest of the page text.
Tables that continue across pages
Long statements and line-item lists often continue on the next page. The second page may repeat the header row, or may not. When you process pages independently, this causes two problems:
- A page without a header row has columns the model cannot name.
- A row can be split across the page break.
Two practical remedies are to prepend the known header row to each continuation page, and to process the table's pages together in one request when they fit in the context window. The chapter on long documents covers the splitting and merging side.
Choosing a representation
OCR output and layout
Scanned pages go through OCR first, and OCR engines differ in what they return. Some return only a string. Others return words with bounding boxes, and some also return detected tables and reading order. If your engine supports it, prefer output with coordinates, because you can then apply the same line-grouping and region-cropping techniques as for native PDFs. Scans add their own problems: skewed pages produce slanted lines that break row grouping, and low resolution makes digits such as 1, 7 and 4 easy to confuse. Always keep the original page so you can fall back to an image.
Detecting bad layout
You cannot inspect every document by eye in production, so add cheap checks:
- Row consistency. Every row of an extracted table should have the same number of cells.
- Arithmetic. Line items should add up to the subtotal. A mismatch often means a column shift.
- Missing anchors. If the text should contain "Total" and does not, the page may have been read incorrectly.
- Length. A layout-mode page with a very small fraction of the expected characters suggests that text is missing or is drawn as vector shapes.
def check_rows(rows):
widths = {len(row) for row in rows}
return len(widths) == 1
def line_items_match_total(amounts, total, tolerance=0.01):
return abs(sum(amounts) - total) <= tolerance
print(check_rows([["a", "b"], ["c", "d"]]))
print(line_items_match_total([20.00, 15.50], 35.50))These checks do not prove that the extraction is right. They catch many failures, and a failed check is a good signal for sending the page to a different path, such as an image-based model (see the next chapter) or a human.
Common mistakes
- Trusting the default extraction without ever looking at the output for a multi-column page.
- Passing a flattened table to the model and asking for line items, with no check that the totals add up.
- Leaving page headers and footers in the text, which then appear as values in fields.
- Joining all pages into one string, so that a continuation table loses its header.
- Converting tables to text with newlines inside cells, which breaks the row structure.
Exercise
A two-page invoice has its line-item table split across pages. Page 2 has no header row, and the extracted rows from page 2 are being assigned to the wrong fields. Name two changes that would fix this, and one check that would detect the problem if it happened again.
Show answer
Fixes: prepend the header row from page 1 to the rows of page 2 before converting them to Markdown, or send both pages in one request so the model sees the header. Check: confirm that the sum of the extracted line-item amounts equals the invoice subtotal, or that every row has the same number of cells as the header. A column shift usually makes the sum wrong.
Exercise
You run page.extract_text() on a two-column report and the sentences are cut in the middle, with lines from both columns alternating. Give two approaches to get a usable reading order.
Show answer
Use layout-preserving extraction (extraction_mode="layout" in pypdf) so that columns keep their horizontal positions, then tell the model about the columns. Or crop each column as its own region (for example with pdfplumber's coordinates) and extract the left column and then the right column separately, in reading order.