view source

PDF Table Extraction: Digital and Scanned to CSV

skill

Extract tables and text from PDF files, digital or scanned, into CSV that matches the totals printed in the document. Use when PDF data must become rows.

Apache-2.0 Requires: python3 and uv; every step can run on Python packages that uv fetches. Used when installed: poppler (pdftotext, pdffonts, pdfimages, pdftoppm), tesseract, Java 8+ for tabula. macOS/Linux.

agents that use this skill

instructions

Overview

Use this skill when the data you need sits in a PDF and has to end up as CSV rows: bank or card statements, invoices, financial reports, survey appendices, price lists. The work has three parts: find out what kind of PDF it is, extract with the method that fits the table, and prove the result against numbers the document prints. The deliverable is one CSV per table plus an extraction log. A CSV not reconciled with the document is a draft, and the log says so.

Mental model

  • A PDF stores drawing instructions, not tables. A digital PDF places each text fragment at coordinates; a table exists only as fragments that line up. A scan stores a picture, and the text must be recognized from it.
  • Every extractor guesses cell boundaries from ruling lines (drawn borders) or from whitespace alignment. Each guess fails in known ways, so only a check against the printed document proves the result.
  • Recognition (OCR) turns pixels into characters with a confidence per word. High confidence is not correctness: a lost decimal point passes silently into every later sum.
  • Numbers carry the document's conventions: separators, negatives, footnote marks. A guessed convention gives wrong values that look valid.

Rules

Classify each page first

Classify per page, since one file can mix both kinds. Replace N with the page number:

text
pdffonts -f N -l N file.pdf
pdfimages -list -f N -l N file.pdf
pdftotext -layout -f N -l N file.pdf - | head -40
ObservationMeaningPath
Fonts listed, text prints in readable order, no page-sized imageDigitalExtract directly
No fonts, one page-sized image per page, pdftotext prints almost nothingScanOCR path
Fonts and a page-sized imageA scan that already has a recognition layer, or a digital page with a background imageTreat the layer as untrusted: compare it with the rendered page before using it
Text prints garbledBroken font mappingOCR path on a rendered page

Without poppler, pdfplumber gives the same facts and renders the page, run as uv run --with pdfplumber python classify.py file.pdf:

python
import sys
import pdfplumber

with pdfplumber.open(sys.argv[1]) as pdf:
    for number, page in enumerate(pdf.pages, 1):
        fonts = sorted({char["fontname"] for char in page.chars})
        wide = [i for i in page.images if i["x1"] - i["x0"] > 0.9 * page.width]
        print(number, len(page.chars), "chars", fonts[:3], len(wide), "page-wide images")
        page.to_image(resolution=300).save(f"page{number}.png", quantize=False)

No characters and one page-wide image is a scan. quantize=False keeps the full-colour image; recognition can return nothing from the default palette image.

A scan that has been through recognition lists a font and keeps its page-sized image, hence the third row. pypdf's documentation warns that errors accumulate in such text layers and that pypdf cannot detect them.

Pick the method by table type

TableFirst choiceNotes
Drawn borders on every cellpdfplumber with its default line strategy, or Camelot latticeDeterministic; check that every drawn cell became a cell
No borders, columns aligned by whitespaceCamelot stream, or pdftotext -layout and a split on runs of two or more spacesWhitespace guessing: confirm column count on every page
Borders on some edges only, or several tables per pagepdfplumber after cropping to the table area, with explicit line positions if neededRender the detected lines with the library's debug image and look at it
ScanOCR path below, then one of the rows above on the recognized layer

Tool facts:

  • pdfplumber: built on pdfminer.six; crops pages and draws what its table finder detected. No OCR; it works best on machine-generated PDFs, not scans.
  • Camelot 2.x: MIT, Python 3.11 or later. Its built-in parsers need a text-based PDF; the default rendering backend needs no system package.
  • tabula-py wraps tabula-java (MIT; -l forces lattice, -t forces stream) and needs Java 8 or later. Use it when Java is present and the others fail.
  • pdftotext -layout keeps the physical layout; its manual calls -raw no longer recommended.

Run libraries on demand, for example uv run --with pdfplumber python extract.py, from a directory other than the one that holds the PDFs: a file there with the name of a Python module would be imported in its place.

A whitespace strategy can split a label such as Region 32 into two columns and double the row count. Check the column count of any whitespace method before trusting it.

Pages and tables that continue

  • Extract page by page with a source_page column, so a failed page can be redone alone (pdftotext -f -l, Camelot pages).
  • A table that continues usually repeats its header on the next page. Drop a row only when it equals the header text exactly, and log each dropped row with its page.
  • Rows such as "carried forward" or page subtotals are not data: log them and leave them out of sums.
  • A row split across a page break shows as a row with empty key cells at the top of the next page. Join it to the row above and log it.
  • A merged (spanning) cell leaves blank cells below it. Fill down only a label or grouping column, only where the page shows the span, and log it. A numeric cell is never filled down.
  • A footnote marker is a small character next to a value and may arrive glued to the number. pdfplumber reports each character's size: a smaller trailing digit is a marker. Move it to a note column and keep the footnote text in the log.

Numbers and locale

Keep the cell text as printed in a raw CSV and derive the numeric CSV from it with code, so every conversion can be traced.

  • Negatives: parentheses mark a negative in accounting style (the CLDR accounting pattern shows ($3.27) for a negative), and a trailing or leading minus is also used. Convert all to one signed form and log the rule.
  • Separators depend on the locale: CLDR shows a comma decimal and a space group separator in French (1 234,57). Decide the convention from the whole column: one value such as 12.345,60 settles it for the rest.
  • A value like 1.234 with no other evidence is ambiguous. Leave it unresolved, mark it in the log and ask. Do not pick the likelier reading.
  • Never fill a cell by guess: an unreadable or missing value stays empty, with its page, row and reason in the log.

OCR path

  1. Render at 300 ppi: pdftoppm -r 300 -png -gray -singlefile -f N -l N file.pdf page writes page.png (poppler's default is 150; without -singlefile the page number is added to the name and padded for long documents). Tesseract works best at 300 dpi or more, and may read the dark borders around scanned pages as characters.
  2. Crop away scanner borders. Tesseract's guide says it has a problem recognizing data from tables without custom segmentation, so crop a ruled table to its cells or columns before recognizing it.
  3. Recognize with word confidences: tesseract page.png out --psm 6 tsv. Mode 6 assumes one uniform block; the conf column is per word and -1 marks rows that are not words. Add -l for the document's language only when that language pack is installed. Without Tesseract, RapidOCR runs from Python packages alone: uv run --with rapidocr --with onnxruntime python ocr.py page.png, where RapidOCR()(path) returns boxes, txts and scores. Each box is one text fragment with its corner positions and a score from 0 to 1, not a table row: group fragments into rows by vertical position and into columns by horizontal position.
  4. Review every numeric word under a confidence threshold you state in the log. A wrong digit or a lost decimal point (8.5 read as 85) can carry high confidence, so the totals check below still applies to every table.
  5. For a searchable PDF, uv run --with ocrmypdf ocrmypdf --force-ocr --sidecar text.txt in.pdf out.pdf (OCRmyPDF: MPL-2.0, Python 3.11 or later, needs Tesseract). --force-ocr rasterizes every page, so use --skip-text when some pages already have text. Add --output-type pdf to avoid the default PDF/A-2b output. Then pdftotext -layout out.pdf - gives aligned text to split.

Validation gate

  1. Row count: count the rows in the document independently, for example numbered rows, or lines matching a row pattern in pdftotext -layout output, and compare with the CSV per page.

  2. Column totals: sum each numeric column with the check_totals.py script listed under Skill Resources, against the total the PDF prints. It reads parentheses, trailing minus and the locale options, skips and counts empty cells, and exits non-zero on a difference above half a cent or on any non-empty cell it cannot parse.

    text
    python3 -I <path>/check_totals.py table.csv --column Amount --printed-total 1,234.50

    Add --decimal "," for a comma-decimal document, and --label-column when the row labels are not in the first column.

  3. Subtotals: reconcile each printed subtotal, then the grand total.

  4. Sampled cells: render the page and compare cells with the picture. Cover the first and last row of every page, every flagged cell and the largest values.

  5. A failed check is reported with its numbers. Do not edit a cell to make a total match.

When the user cannot be asked, resolve nothing ambiguous: leave the cell empty and list it in the log.

Examples

Guessed convention to column-resolved. Bad: 1.234 becomes 1.234 because "the point is a decimal". Good: the same column holds 12.345,60, so the point groups thousands; the value is 1234, the rule is logged.

Total forced to match. Bad: the sum is off, so a cell is edited until it matches. Good: the check fails, the low-confidence cell is found on the page image, corrected from what the picture shows, and the log records the cell, old and new text and reason.

Output format

Files: <source>_p<first>-<last>_t<n>.csv for each table, UTF-8, one header row, a source_page column, numbers as plain signed decimals with a period; a raw-text twin when conversions happened; extraction_log.md.

The log lists per table: pages, PDF class, method, tool version and settings, rows found against expected, each total with printed value and difference, flagged and sampled cells, every transformation (dropped headers, joins, fill-down, negatives, locale), and unresolved cells with reasons.

Checklist

  • Each page is classified; scans went through OCR at about 300 ppi.
  • The method fits the table type; the column count was confirmed on every page.
  • Repeated headers, carried rows, merged cells and footnote markers are handled and logged.
  • Ambiguous numbers are unresolved, not guessed.
  • Row counts and column totals match the printed values, or the difference is reported.
  • Low-confidence and sampled cells were compared with the rendered page.
  • No cell was filled by guess; the log names every empty cell.

Composition / References

Scope limits: analysis of the extracted data, charts, spreadsheet formulas, database loading, and changing or making PDFs are separate jobs.