To extract a PDF table and check its totals, use PyMuPDF to locate the table, pandas to validate the columns and numeric values, and an explicit arithmetic check to compare each line and the grand total. The example below creates a small synthetic PDF fixture, extracts its table, checks its units and calculations, and saves the accepted rows as CSV; its sample output is illustrative, not a report of a test run.
Prerequisites and intended result
Use Python with PyMuPDF and pandas installed. The example generates its own one-page PDF, so you do not need to download a public file; the same extraction and validation steps can be adapted to a PDF you have permission to process. The fixture represents quantities in boxes and prices in US dollars.
Install the packages in your Python environment:
python -m pip install pymupdf pandas
A PDF can store table text and rules as vector elements, or it can contain only a scanned image. PyMuPDF’s Page.find_tables() detects tables using vector graphics such as lines and rectangles. This worked example draws ruled cells, so it is suitable for demonstrating structured extraction. It does not establish that every PDF table will be detected. PyMuPDF FAQ — Table Extraction
Worked example: generate, extract, and validate
The script below writes sample_invoice.pdf, extracts the first detected table, normalizes its numeric columns, checks the expected headers and units, and compares line totals and the final total. A validation failure stops the script before it saves a CSV.
Example input: The generated fixture has these data rows, with quantities in boxes and prices in US dollars.
Item Quantity (boxes) Unit price (USD) Line total (USD)
Pens 10 12.50 125.00
Notebooks 8 7.50 60.00
from pathlib import Path
import pandas as pd
import pymupdf
PDF_PATH = Path("sample_invoice.pdf")
CSV_PATH = Path("extracted_invoice.csv")
headers = [
"Item",
"Quantity (boxes)",
"Unit price (USD)",
"Line total (USD)",
]
rows = [
["Pens", "10", "12.50", "125.00"],
["Notebooks", "8", "7.50", "60.00"],
]
# Build a ruled, searchable PDF fixture.
doc = pymupdf.open()
page = doc.new_page(width=612, height=300)
page.insert_text((50, 45), "Illustrative invoice table", fontsize=14)
x_edges = [50, 210, 330, 455, 562]
y_edges = [80, 112, 144, 176]
for x in x_edges:
page.draw_line((x, y_edges[0]), (x, y_edges[-1]), width=0.8)
for y in y_edges:
page.draw_line((x_edges[0], y), (x_edges[-1], y), width=0.8)
table_rows = [headers, *rows]
for row_index, values in enumerate(table_rows):
baseline = y_edges[row_index] + 21
for column_index, value in enumerate(values):
page.insert_text(
(x_edges[column_index] + 5, baseline),
value,
fontsize=9,
)
doc.save(PDF_PATH)
doc.close()
# Extract the first table on the first page.
with pymupdf.open(PDF_PATH) as pdf:
found = pdf[0].find_tables()
if not found.tables:
raise RuntimeError("No table detected. Inspect the PDF or use OCR.")
extracted = found.tables[0].extract()
if len(extracted) != 3 or any(len(row) != 4 for row in extracted):
raise ValueError(f"Unexpected table shape: {extracted!r}")
actual_headers = [str(value).strip() for value in extracted[0]]
if actual_headers != headers:
raise ValueError(f"Header or unit mismatch: {actual_headers!r}")
df = pd.DataFrame(extracted[1:], columns=actual_headers)
for column in headers[1:]:
df[column] = pd.to_numeric(df[column], errors="raise")
if df["Item"].tolist() != ["Pens", "Notebooks"]:
raise ValueError(f"Unexpected item rows: {df['Item'].tolist()!r}")
calculated_lines = df["Quantity (boxes)"] * df["Unit price (USD)"]
if not calculated_lines.equals(df["Line total (USD)"]):
raise ValueError("At least one line total does not match quantity × price.")
grand_total = df["Line total (USD)"].sum()
if grand_total != 185.0:
raise ValueError(f"Grand total mismatch: {grand_total}")
df.to_csv(CSV_PATH, index=False)
print(df.to_string(index=False))
print(f"Grand total (USD): {grand_total:.2f}")
print(f"Saved: {CSV_PATH}")
The explicit header comparison checks both column names and units. pandas.to_numeric(..., errors="raise") makes unexpected text in a numeric column an error instead of silently treating it as a number. pandas.to_numeric
Expected output: This is illustrative output for the fixture. It shows the accepted values and the total the checks are designed to require; it is not a claim that the code was run.
Item Quantity (boxes) Unit price (USD) Line total (USD)
Pens 10 12.5 125.0
Notebooks 8 7.5 60.0
Grand total (USD): 185.00
Saved: extracted_invoice.csv
Acceptance checks and recovery
Verify the result: Confirm the output has exactly two item rows; its quantity column is labeled in boxes; both price columns are labeled in USD; each line total equals quantity multiplied by unit price; and the grand total is USD 185.00. Open the saved CSV and compare its rows with the source PDF, including decimal points and any footnotes that affect interpretation. A matching sum alone cannot prove that every row was extracted correctly.
If the script reports that no table was detected, first open the generated PDF and confirm the grid appears. For a real PDF, inspect whether the table has visible rules; PyMuPDF notes that borderless tables may need strategy="text", and colored cells without borders can be harder to detect. You can try changing the call to pdf[0].find_tables(strategy="text"), then inspect the extracted rows and repeat the checks. PyMuPDF FAQ — Table Extraction
If a table is image-only, ordinary table detection may find no usable text structure. OCR means optical character recognition: it converts text visible in an image into machine-readable text, but recognition can confuse digits, decimal points, and column boundaries. PyMuPDF offers page.get_textpage_ocr() and requires Tesseract language data; OCR output should be treated as a transcription to review and validate against the image. PyMuPDF FAQ — OCR If OCR does not preserve the columns, manually transcribe the table or use an OCR workflow that returns table structure before running numeric checks. This method is unsuitable when extraction errors cannot be reconciled against the original, such as an illegible scan or an ambiguous unit label.
PyMuPDF can OCR page content with get_textpage_ocr() and then retrieve recognized text with get_text(textpage=...); its OCR requires Tesseract language data files.
Frequently Asked Questions (FAQ)
Q1) What if the table has no grid lines?
Try calling page.find_tables(strategy="text") on the page that contains the table, then inspect the extracted cell boundaries before using the values. If the result is empty or the columns are misaligned, adjust the extraction or transcribe the cells from the page. Treat the extracted values as candidates and compare each row and total with the PDF.
Q2) What should I do when an extracted amount contains text?
Keep numeric conversion strict with errors="raise" so a value such as 60.0* stops the run for review. Check the source for a footnote, currency symbol, or OCR error before deciding how to handle it. Do not strip characters automatically unless you know what they mean and have preserved the original value for comparison. pandas can coerce invalid values to missing values with errors="coerce", but that does not resolve why they were invalid. pandas.to_numeric
pandas.to_numeric() raises an error on invalid values by default; with errors="coerce", invalid values become NaN.
Q3) Does a matching grand total prove the extraction is correct?
No. Two missed or misread rows can sometimes offset each other and leave the same total. Compare row counts, labels, units, and every line calculation with the original table as well. For image-only tables, review OCR output against the page image because recognized text may not preserve the table’s structure or decimal marks. PyMuPDF FAQ — OCR