Getting PDF Tables into Clean Spreadsheets: The Hard Parts
A table in a PDF looks like a table to a person and like a pile of drawing instructions to a program. That gap is the main difficulty in getting a bill of quantities, a price schedule or any other tabular document out of a PDF and into a spreadsheet. The extraction step is rarely the end: the numbers feed estimates and comparisons, so a silent error costs money.
In earlier work on a document-intelligence platform for construction, I built a PDF-to-Excel pipeline for pricing documents. This post is general technique, not a description of that system: why PDF tables are hard, what the main tools do, and how to check the result. The code runs on a synthetic document generated in the post.
Version notice. Written and run on 1 December 2026 with Python 3.13.7, PyMuPDF 2.2 (the latest release on PyPI, 25 November 2026, with its pymupdf_layout dependency), pdfplumber 0.11.11, reportlab 5.1.3 and openpyxl 3.1.5. Camelot, Docling, Tesseract, PaddleOCR and vision-language models are described from their documentation, not run.
In short
- A PDF stores positioned text and drawn lines, not rows and cells, so every extractor reconstructs a table by guessing from geometry.
- Ruled digital tables are the easy case; merged cells, wrapped descriptions, page breaks, subtotals inside the table and scanned pages are where pipelines fail.
- Pick the tool by input type: geometry-based libraries for digital PDFs, OCR or a table-structure model for scans, and a vision-language model only with checks around it. On synthetic pages, defaults were exact on ruled tables but not on borderless ones.
- Arithmetic checks (quantity times rate, subtotals, grand total) catch errors that no extractor reports about itself; keep page and bounding box for every row.
Why a PDF has no tables
A PDF page is a list of drawing operations: place this glyph at these coordinates, stroke a line between these two points, fill this rectangle. There is no row element and no cell element in the page content. What looks like a grid is lines drawn near text that happens to be aligned.
There are two kinds of document. A digital PDF, exported from a word processor or a pricing system, carries a text layer with exact characters and positions. A scanned PDF is a photograph of a page: pixels only, with no characters at all unless OCR (optical character recognition, which turns pixels into text) has added a hidden text layer. Many files are mixed, so the pipeline has to decide per page.
The libraries below recover structure in two ways. The lines approach uses ruling lines and rectangle edges as cell borders. The text approach infers column and row boundaries from where words sit. Ruled tables suit the first; borderless tables force the second, which is a heuristic and fails more often.
The hard cases
Every row of a pricing document carries money, and these failure modes recur.
| Case | What goes wrong | Usual remedy |
|---|---|---|
| Merged or spanning cells | A section heading spans all columns; the extractor returns empty cells or None for the covered ones | Classify a row whose first cell is filled and the rest empty as a heading, and carry it forward as a section label |
| Multi-line descriptions | Wrapped text arrives with line breaks, or splits into extra rows when there are no row lines | Join lines inside a cell; if there are no row lines, fold a row with no item code and no numbers into the row above |
| Tables across pages | Each page yields its own table, and the header repeats | Compare the first row with the known header and drop repeats; keep the page number |
| Subtotals and totals inside the table | They look like items and double-count if summed | Give every row a kind (item, section, subtotal, total) and use subtotals as checks, not data |
| Number formats | 1,240.00 in one locale is 1.240,00 or 1 240,00 in another; a wrong guess changes the value by a factor of 1,000 | Fix the decimal separator per document, parse with Decimal, reject anything not well formed in that locale |
| Rounded line amounts | Exact quantity times rate equality flags correct rows | Allow one unit of the last printed place |
| Rotated pages | Landscape tables on a rotated page return rotated text | Check the page rotation and the line direction before extracting; the PyMuPDF docs note that a line direction other than (1, 0) means rotated text |
| Scanned pages | No text layer; OCR misreads digits such as 0 and 8, or a decimal point | OCR with a structure-aware tool, then verify arithmetic; low-confidence cells go to a person |
The tools
The tools split by what they read: geometry libraries read the text layer and drawn lines of a digital PDF, OCR engines turn pixels into text, and table-structure models predict rows and columns from an image.
| Tool | Reads | Strength | Trade-off |
|---|---|---|---|
PyMuPDF find_tables | Digital PDFs | Strategies lines (default), lines_strict and text; returns row and cell bounding boxes | Dual-licensed AGPL 3.0 or Artifex commercial licence; check it before using it in a proprietary product |
| pdfplumber | Digital PDFs | Strategies lines, lines_strict, text and explicit; good debugging view of how the table was found | The README says it works best on machine-generated PDFs and lists OCR as not provided |
| Camelot | Digital PDFs | Lattice flavour for ruled tables, Stream for whitespace-separated ones | Lattice and Stream need a text layer; an optional ml flavour (needs PyTorch) uses a Table Transformer model for structure |
| Tesseract | Images | Mature OCR engine with an LSTM recogniser; outputs text, hOCR, TSV and more | The README makes no statement about tables, so plan to rebuild rows from word positions yourself |
| PaddleOCR | Images and PDFs | OCR plus PP-StructureV3, which outputs Markdown or JSON with table cell coordinates | Deep-learning models, so check install size and hardware first |
| Docling | PDFs, images, office files | Layout analysis, TableFormer for table structure, OCR for scans, MIT licence | Pulls a deep-learning stack, a larger install |
If tables have ruling lines, the lines strategy is stable; if they are borderless, expect to tune tolerances or fix column positions, then verify more. PyMuPDF documents tolerances (default 3 points) for snapping, joining and word grouping, and parameters that fix column or row coordinates when a layout repeats.
Which tool for which input
| Input | Start with | Verify first |
|---|---|---|
| Digital, ruled | PyMuPDF or pdfplumber, lines | Table and row counts, arithmetic |
| Digital, borderless | The default first (on the synthetic pages it relied on PyMuPDF's layout model); tune text or fix columns if it fails | Split wrapped rows, cells per row |
| Scanned or mixed | Text-layer test per page, then OCR plus a structure model | Arithmetic, low-confidence cells |
TableFormer, Docling and vision-language models
TableFormer is a transformer model that predicts table structure from an image. Its paper reports TEDS (tree-edit-distance-based similarity, a score for table structure) gains over the earlier PubTabNet model from 91 to 98.5 per cent on simple tables and from 88.7 to 95 per cent on complex ones. Those are the authors' figures on their benchmark, not a promise for your documents. The paper also says the model has a cell-detection decoder so that, for programmatic PDFs, cell content can be taken from the PDF directly rather than through OCR.
Docling packages this. Its technical report describes an MIT-licensed converter that uses a layout model trained on DocLayNet and TableFormer for table structure, and its documentation lists OCR for scans, several export formats, and support for vision-language models such as GraniteDocling. It pulls a deep-learning framework, a reason to prefer a geometry library for clean digital PDFs.
A vision-language model (VLM) reads the page image and writes the table directly. It handles messy layouts without per-layout tuning. The cost is that it can produce a plausible value that is not on the page. That is a reason for the checks in the next sections, not a reason to avoid VLMs; Trustworthy LLM Table Extraction: Layered Validation covers the wider validation stack.
A synthetic bill of quantities
The test document is a small, synthetic bill of quantities generated with reportlab: three sections, twelve items, a header that repeats across two pages, section headings spanning all columns, wrapped descriptions, a subtotal per section and a grand total. The core of the generator is below.
# excerpt from make_boq.py: styles, spans and the repeating header
style = [
("GRID", (0, 0), (-1, -1), 0.5, colors.black),
("BACKGROUND", (0, 0), (-1, 0), colors.lightgrey),
("ALIGN", (3, 0), (-1, -1), "RIGHT"),
("VALIGN", (0, 0), (-1, -1), "TOP"),
("FONTSIZE", (0, 0), (-1, -1), 8),
] + spans + [("FONTNAME", (0, r), (-1, r), "Helvetica-Bold") for r in bold]
table = Table(rows, colWidths=[40, 250, 35, 55, 55, 70], repeatRows=1)
table.setStyle(TableStyle(style))
# A short page forces the table onto several pages, repeating the header.
doc = SimpleDocTemplate(path, pagesize=(595, 400), topMargin=40, bottomMargin=40)
doc.build([Paragraph("Bill of quantities (synthetic example)", styles["Title"]), table])
One printed amount is wrong on purpose: item B3 shows 13,081.00 where 92 times 141.50 is 13,018.00, a transposition of the kind a typist or an OCR engine makes. The subtotal and grand total are computed from the true values.
Extracting with PyMuPDF
The current API, per the PyMuPDF documentation, is page.find_tables(), which returns a TableFinder whose .tables list holds Table objects. Table.extract() returns a list of lists of strings, and Table.rows gives each row a bbox. The documentation warns that tables are only valid while the page object exists, so the code reads everything inside the loop. The import name is pymupdf. Without row lines, a wrapped description can come back as an extra row, so merge_wrapped folds a row with no item code and no digits into the description above it (within one page only).
"""Extract a bill of quantities from a PDF, check it, and write an .xlsx."""
import re
from dataclasses import dataclass
from decimal import Decimal, InvalidOperation
import pymupdf
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill
HEADER = ["Item", "Description", "Unit", "Qty", "Rate", "Amount"]
CODE = re.compile(r"^[A-Z]\d+$")
CENT = Decimal("0.01")
def to_decimal(text: str, decimal_sep: str = ".") -> Decimal | None:
"""Parse '1,240.00' (or '1.240,00' with decimal_sep=',') exactly.
Returns None unless the text is well formed in the declared locale, so a
wrong declaration fails loudly instead of shifting the value.
"""
t = (text or "").strip().replace("\u2212", "-") # Unicode minus sign
negative = t.startswith("(") and t.endswith(")") # accounting style
if negative:
t = t[1:-1].strip()
thousands = re.escape("," if decimal_sep == "." else ".")
group = rf"[{thousands}\s]" # \s covers no-break and narrow no-break spaces
pattern = rf"-?(?:\d{{1,3}}(?:{group}\d{{3}})+|\d+)(?:{re.escape(decimal_sep)}\d+)?"
if not re.fullmatch(pattern, t):
return None
value = Decimal(re.sub(group, "", t).replace(decimal_sep, "."))
return -value if negative else value
@dataclass
class Row:
kind: str # item | section | subtotal | total
page: int
bbox: tuple
cells: list[str]
def classify(cells: list[str]) -> str:
code, desc = cells[0], cells[1]
if CODE.match(code):
return "item"
if code and not any(cells[1:]):
return "section"
return "total" if desc.lower().startswith("grand total") else "subtotal"
def merge_wrapped(raw: list[tuple]) -> list[tuple]:
"""Fold a row with no item code and no digits into the row above it.
raw holds (page, bbox, cells) tuples. A wrapped description line has no
code and no numbers; subtotal and total rows always carry an amount, so
they are never folded. Only rows on the same page are merged.
"""
merged: list[tuple] = []
for page, bbox, cells in raw:
text = " ".join(c for c in cells if c)
if (merged and merged[-1][0] == page and not cells[0] and text
and not any(ch.isdigit() for ch in text)):
_, b, prev = merged[-1]
prev = [prev[0], f"{prev[1]} {text}".strip(), *prev[2:]]
b = (min(b[0], bbox[0]), min(b[1], bbox[1]), max(b[2], bbox[2]), max(b[3], bbox[3]))
merged[-1] = (page, b, prev)
else:
merged.append((page, bbox, list(cells)))
return merged
def read_rows(path: str) -> list[Row]:
raw = []
with pymupdf.open(path) as doc:
for page in doc:
for table in page.find_tables().tables:
for trow, cells in zip(table.rows, table.extract()):
# None marks a cell swallowed by a merged span; join wrapped lines.
cells = [" ".join((c or "").split()) for c in cells]
if cells == HEADER: # header repeated on each page
continue
bbox = tuple(round(v, 1) for v in trow.bbox)
raw.append((page.number + 1, bbox, cells))
return [Row(classify(c), p, b, c) for p, b, c in merge_wrapped(raw)]
The number parser prevents the factor-of-1,000 error: it takes the decimal separator as an argument and returns None unless the text is well formed in that locale. A later section shows what a naive version does instead.
Checking the arithmetic
An extractor cannot tell you that it misread a digit, but a bill of quantities is redundant by construction: each amount should equal quantity times rate, each subtotal the sum of its items, and the grand total the sum of the subtotals. A single misread digit in a quantity, rate or amount breaks the line relation, and in an amount it also breaks the subtotal, whether an extractor, an OCR engine or a VLM made it. Two errors that cancel, or an error in a text column, pass. Use Decimal, not floats. The block also holds write_xlsx, used later.
def check(rows: list[Row], tol: Decimal = CENT) -> list[str]:
problems, running, grand = [], Decimal(0), Decimal(0)
for r in rows:
amount = to_decimal(r.cells[5])
if r.kind == "item":
qty, rate = to_decimal(r.cells[3]), to_decimal(r.cells[4])
if None in (qty, rate, amount):
problems.append(f"p{r.page} {r.cells[0]}: unparsable number")
continue
if abs(qty * rate - amount) > tol: # systems round lines differently
problems.append(f"p{r.page} {r.cells[0]}: {qty} x {rate} = "
f"{qty * rate:,.2f}, printed {amount:,.2f}")
running += amount
elif r.kind == "subtotal":
if amount is None:
problems.append(f"p{r.page} {r.cells[1]}: unparsable number")
elif running != amount:
problems.append(f"p{r.page} {r.cells[1]}: items sum to "
f"{running:,.2f}, printed {amount:,.2f}")
grand += amount or 0
running = Decimal(0)
elif r.kind == "total" and grand != amount:
problems.append(f"p{r.page} grand total: subtotals sum to "
f"{grand:,.2f}, printed {amount:,.2f}")
return problems
def write_xlsx(rows: list[Row], problems: list[str], path: str) -> None:
wb = Workbook()
ws = wb.active
ws.title = "BoQ"
ws.append(HEADER + ["Kind", "Page", "BBox (pt)", "Check"])
for c in ws[1]:
c.font = Font(bold=True)
flagged = {m.group(1) for p in problems if (m := re.match(r"p\d+ ([A-Z]\d+):", p))}
for r in rows:
nums = [to_decimal(x) for x in r.cells[3:6]]
bad = r.cells[0] in flagged
ws.append(r.cells[:3] + [float(n) if n is not None else None for n in nums]
+ [r.kind, r.page, str(r.bbox), "CHECK" if bad else ""])
if bad:
for c in ws[ws.max_row]:
c.fill = PatternFill("solid", fgColor="FFF2CC")
for row in ws.iter_rows(min_row=2, min_col=4, max_col=6):
for c in row:
c.number_format = "#,##0.00"
ws.freeze_panes = "A2"
wb.save(path)
Running the file on the generated PDF printed this, then a read-back of the flagged workbook rows:
19 rows: {'item': 12, 'section': 3, 'subtotal': 3, 'total': 1}
Row(kind='section', page=1, bbox=(45.0, 92.0, 550.0, 110.0), cells=['A. Substructure', '', '', '', '', ''])
Row(kind='item', page=1, bbox=(45.0, 110.0, 550.0, 136.0), cells=['A1', 'Excavate trench for strip footings, maximum depth 1.5 m, and dispose of spoil off site', 'm3', '120.00', '18.50', '2,220.00'])
Row(kind='item', page=1, bbox=(45.0, 136.0, 550.0, 154.0), cells=['A2', 'Blinding concrete, 50 mm thick', 'm2', '85.00', '9.20', '782.00'])
PROBLEMS:
p1 B3: 92.00 x 141.50 = 13,018.00, printed 13,081.00
p1 Subtotal B: items sum to 26,809.25, printed 26,746.25
# read-back of the highlighted workbook rows (openpyxl)
B3 (92, 141.5, 13081) page 1 bbox (45.0, 270.0, 550.0, 288.0)
Both relations caught the typo: the line check flagged B3 and the subtotal check flagged section B, by 63.00, which is 13,081.00 minus 13,018.00.
The line check has a one-cent tolerance because the printed amount is the product of quantity and rate rounded to the cent (both carry two decimals, so the product has up to four). Without it the check is wrong on good data: on the 300 correctly extracted item lines of the ruled benchmark documents below, exact equality failed on 167 and a tolerance of 0.01 on none (rounding.py). Subtotals are compared exactly here; a document that totals unrounded values needs a tolerance there too.
Two libraries, three layouts, measured
The generator was extended to seeded documents: 10 per layout, 30 items over 3 pages each (300 item rows, 30 pages per layout). The layouts are the ruled grid above; the same table with no lines or fills (borderless); and a ruled table with a two-row header, Quantity over Unit and Qty, and Value over Rate and Amount. Five settings ran, each with default parameters apart from the options named: PyMuPDF find_tables and pdfplumber extract_tables, each with the lines and text strategies, plus PyMuPDF lines with use_layout=False. A cell counts if it matches the ground truth exactly after whitespace normalisation.
# excerpt from bench.py: the settings compared and the metric
import pdfplumber
import pymupdf
from extract_boq import CODE
def norm(c):
return " ".join((c or "").split())
def pymupdf_tables(strategy):
def run(page):
return [t.extract() for t in page.find_tables(strategy=strategy).tables]
return run
def plumber_tables(strategy):
settings = {"vertical_strategy": strategy, "horizontal_strategy": strategy}
return lambda page: page.extract_tables(settings)
TOOLS = {
"PyMuPDF lines": ("mu", pymupdf_tables("lines")),
"PyMuPDF text": ("mu", pymupdf_tables("text")),
"pdfplumber lines": ("pl", plumber_tables("lines")),
"pdfplumber text": ("pl", plumber_tables("text")),
}
def score(extracted, truth):
"""Cell-level scoring of item rows, keyed by item code (first cell)."""
want = {r[0]: r for s in truth["sections"] for r in s["items"]}
got = {}
for table in extracted:
for cells in table:
cells = [norm(c) for c in cells]
if cells and CODE.match(cells[0]) and cells[0] not in got:
got[cells[0]] = (cells + [""] * 6)[:6]
hit = sum(sum(a == b for a, b in zip(got[k], want[k])) for k in want if k in got)
return len(want), sum(k in got for k in want), hit
Time is the median of 5 runs per page on freshly opened documents (parsing included), on a laptop shared with other work. pdfplumber took 16 to 17 ms per page with lines against 76 to 85 ms for PyMuPDF with default settings and 14 to 15 ms with use_layout=False (the default adds the layout model, explained below). These timings are indicative, from one run on one machine and one kind of page, not a ranking. Problems raised counts the pipeline's messages without merge_wrapped, including rows without 6 cells.
| Layout | Setting | Cells right | Problems raised | ms per page |
|---|---|---|---|---|
| Ruled | PyMuPDF lines | 100.0% | 0 | 77 |
| Ruled | PyMuPDF lines, use_layout=False | 100.0% | 0 | 15 |
| Ruled | PyMuPDF text | 17.1% | 416 | 87 |
| Ruled | pdfplumber lines | 100.0% | 0 | 17 |
| Ruled | pdfplumber text | 17.1% | 416 | 23 |
| Borderless | PyMuPDF lines | 97.7% | 65 | 85 |
| Borderless | PyMuPDF lines, use_layout=False | 0.0% (no table found) | 0 | 9 |
| Borderless | PyMuPDF text | 17.1% | 416 | 84 |
| Borderless | pdfplumber lines | 0.0% (no table found) | 0 | 11 |
| Borderless | pdfplumber text | 17.1% | 416 | 22 |
| Merged header | PyMuPDF lines | 100.0% | 0 | 76 |
| Merged header | PyMuPDF lines, use_layout=False | 100.0% | 0 | 14 |
| Merged header | PyMuPDF text | 17.2% | 447 | 82 |
| Merged header | pdfplumber lines | 100.0% | 0 | 16 |
| Merged header | pdfplumber text | 17.2% | 447 | 21 |
- Ruling lines are the easy case. With
lines, both libraries were exact on the ruled and merged-header layouts. - The untuned
textstrategy is not usable here. It put every number in the right row but cut columns inside words and returned 7 to 11 cells per row instead of 6, so column-wise parsing failed. Only the item code column was right (300 of 1,800 cells, plus 8 descriptions, 17 per cent). Tolerances and fixed column positions are the documented remedy and were not run. - Borderless needs a check on rows. The borderless pages have no vector drawings at all (
get_drawings()returned an empty list on page 1 of the first document, against 34 drawings on the ruled one), so no header underline or fill can have supplied edges. PyMuPDF still returned a table, because version 2.2 installs a layout model (pymupdf_layout) andfind_tableshasuse_layout=Trueby default, which lets layout analysis supply table regions. Withuse_layout=FalsePyMuPDF found no table on 30 of 30 borderless pages and was unchanged on the ruled ones. With the default, 97.7 per cent of cells were right. Every miss was a wrapped description whose second line became its own row; read as a subtotal, it broke the running sum, so the checks raised 65 problems. Withmerge_wrappedthe result was 100 per cent and 0 problems. pdfplumberlinesfound no table on 30 of 30 pages without an error, and its 0 problems mean only that no rows were left to check. Count the rows. This depends on the PyMuPDF version and its optional layout model.
Three failures, on the first generated documents:
"""Three failures on the first synthetic document (seed 0)."""
import pdfplumber
import pymupdf
from extract_boq import Row, check, classify, merge_wrapped
# 1. Silent empty result: pdfplumber 'lines' strategy on the borderless PDF.
with pdfplumber.open("pdfs/borderless_0.pdf") as pdf:
print("pdfplumber lines, borderless, page 1 tables:", pdf.pages[0].extract_tables())
# 2. Text strategy on the ruled PDF: columns are cut inside words.
with pymupdf.open("pdfs/ruled_0.pdf") as doc:
rows = doc[0].find_tables(strategy="text").tables[0].extract()
print("PyMuPDF text, ruled, rows 3 and 5:")
for r in (rows[2], rows[4]):
print(" ", r)
# 3. Borderless PDF with the default strategy: a wrapped line becomes its own row.
raw = []
with pymupdf.open("pdfs/borderless_0.pdf") as doc:
for page in doc:
for table in page.find_tables().tables:
for cells in table.extract():
raw.append((page.number + 1, (0, 0, 0, 0),
[" ".join((c or "").split()) for c in cells]))
raw = [r for r in raw if r[2][0] != "Item"]
for label, data in (("without merge_wrapped", raw), ("with merge_wrapped", merge_wrapped(raw))):
problems = check([Row(classify(c), p, b, c) for p, b, c in data])
print(f"{label}: {len(problems)} problems", *problems[:2], sep="\n ")
# output of this script
# pdfplumber lines, borderless, page 1 tables: []
# PyMuPDF text, ruled, rows 3 and 5:
# ['A. Substru', 'cture', '', '', '', '', '', '']
# ['A1', 'Screed to suspen', 'ded slab', '', 't', '43.50', '1,049.75', '45,664.12']
# without merge_wrapped: 2 problems
# p1 making good: unparsable number
# p1 Subtotal A: items sum to 283,364.75, printed 4,206,846.03
# with merge_wrapped: 0 problems
Number formats the parser must survive
A naive parser strips the thousands character and parses the rest; the strict to_decimal above accepts a number only if its grouping is well formed for the declared locale. Script: locale_cases.py.
def naive(text: str, decimal_sep: str = ".") -> Decimal | None:
"""Strip whitespace and the thousands character, then parse."""
t = re.sub(r"\s", "", text or "")
thousands = "," if decimal_sep == "." else "."
try:
return Decimal(t.replace(thousands, "").replace(decimal_sep, "."))
except InvalidOperation:
return None
| Input | Declared separator | Naive | Strict | Case |
|---|---|---|---|---|
1,240.00 | . | 1240.00 | 1240.00 | correct |
1.240,00 | , | 1240.00 | 1240.00 | correct |
1 240,00 (U+202F) | , | 1240.00 | 1240.00 | U+202F grouping |
1 240,00 | . | 124000 | None | wrong declaration |
1.240,00 | . | 1.24000 | None | wrong declaration |
1,240.00 | , | 1.24000 | None | wrong declaration |
1,240 | . | 1240 | 1240 | ambiguous |
1,24,000.00 | . | 124000.00 | None | Indian grouping |
(1,240.00) | . | None | -1240.00 | accounting negative |
A wrongly declared 1.240,00 becomes 1.24000 and 1 240,00 becomes 124000 under the naive parser, silently; the strict one returns None and the row goes to review. 1,240 stays ambiguous by nature: 1240 with a thousands comma, 1.24 with a decimal comma, and only the per-document declaration decides. Indian grouping, a trailing minus and a Swiss apostrophe (1'240.00) are rejected rather than guessed.
Provenance and the workbook
Each workbook row keeps its page number and its bounding box on that page, in PDF points, so a reviewer can open the PDF at the right place. The check column and the fill mark rows that failed a rule. The sheet holds values, not formulas; number formats such as #,##0.00 make amounts readable without changing the stored value.
Beyond arithmetic, add cheap schema checks: the header matches the expected names, every row has the header's number of cells, the unit comes from a known list, quantities are non-negative, item codes are unique and in order. Also compare the workbook text with the PDF text layer, or have a person spot-check a sample against the bounding boxes.
A checklist
- Classify each page as digital or scanned before choosing a route.
- Fix the locale (decimal and thousands separators) per document and parse with
Decimal. - Tag every row as item, section, subtotal or total, keep page and bounding box, drop repeated headers and carry section headings forward.
- Merge wrapped lines before classifying rows, so a continuation line is not mistaken for a subtotal.
- Run the three arithmetic checks (with a one-cent tolerance on lines) and a schema check, and treat any failure as a review item, never a silent fix.
- Count tables and rows per page against what you expect; zero tables is an error, and a check over zero rows proves nothing.
- Send low-confidence or failed rows to a person rather than correcting values by rule.
What this does not cover
- Synthetic documents only. The main example is one document with a planted typo; the comparison uses 30 pages per layout from one generator with clean fonts and exact glyph positions. Real documents differ, and none of the numbers here measure accuracy on them.
- Two libraries, default settings. Only PyMuPDF and pdfplumber were run, untuned; the weak
textresults say nothing about tuned settings. Camelot, Docling, Tesseract, PaddleOCR and VLMs were not run, and their descriptions come from their documentation; the post does not rank them. - No scanned or rotated test. OCR and rotation are discussed, not demonstrated.
- Checks find inconsistency, not every error. An error that preserves the arithmetic, such as a wrong item code, passes; a document whose printed totals are wrong fails correctly but needs a person.
- Licensing. The PyMuPDF licence terms, AGPL 3.0 or a commercial licence from Artifex, apply to your use; check them before adopting it.
Sources
- PyMuPDF docs: Page.find_tables (strategies, tolerances, Table API, validity note)
- PyPI: PyMuPDF (version, licence)
- PyMuPDF docs: text recipes (rotated text, line direction)
- pdfplumber README (table strategies, scanned PDFs, no OCR)
- Camelot docs: how it works (Lattice, Stream, ml flavour)
- TableFormer: Table Structure Understanding with Transformers (arXiv 2203.01017)
- Docling Technical Report (arXiv 2408.09869)
- Docling documentation (features, OCR, VLMs, exports, licence)
- Tesseract OCR README (LSTM engine, output formats)
- PaddleOCR README (PP-StructureV3, table cell coordinates)
- Wikipedia: Decimal separator (digit grouping)
- openpyxl documentation: simple usage