PDF Table Extraction: Digital and Scanned to CSV
skillExtract 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.
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:
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| Observation | Meaning | Path |
|---|---|---|
| Fonts listed, text prints in readable order, no page-sized image | Digital | Extract directly |
No fonts, one page-sized image per page, pdftotext prints almost nothing | Scan | OCR path |
| Fonts and a page-sized image | A scan that already has a recognition layer, or a digital page with a background image | Treat the layer as untrusted: compare it with the rendered page before using it |
| Text prints garbled | Broken font mapping | OCR 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:
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
| Table | First choice | Notes |
|---|---|---|
| Drawn borders on every cell | pdfplumber with its default line strategy, or Camelot lattice | Deterministic; check that every drawn cell became a cell |
| No borders, columns aligned by whitespace | Camelot stream, or pdftotext -layout and a split on runs of two or more spaces | Whitespace guessing: confirm column count on every page |
| Borders on some edges only, or several tables per page | pdfplumber after cropping to the table area, with explicit line positions if needed | Render the detected lines with the library's debug image and look at it |
| Scan | OCR 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;
-lforces lattice,-tforces stream) and needs Java 8 or later. Use it when Java is present and the others fail. pdftotext -layoutkeeps the physical layout; its manual calls-rawno 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_pagecolumn, so a failed page can be redone alone (pdftotext -f -l, Camelotpages). - 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 as12.345,60settles it for the rest. - A value like
1.234with 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
- Render at 300 ppi:
pdftoppm -r 300 -png -gray -singlefile -f N -l N file.pdf pagewritespage.png(poppler's default is 150; without-singlefilethe 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. - 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.
- Recognize with word confidences:
tesseract page.png out --psm 6 tsv. Mode 6 assumes one uniform block; theconfcolumn is per word and-1marks rows that are not words. Add-lfor 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, whereRapidOCR()(path)returnsboxes,txtsandscores. 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. - Review every numeric word under a confidence threshold you state in the log. A wrong digit or a lost decimal point (
8.5read as85) can carry high confidence, so the totals check below still applies to every table. - 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-ocrrasterizes every page, so use--skip-textwhen some pages already have text. Add--output-type pdfto avoid the default PDF/A-2b output. Thenpdftotext -layout out.pdf -gives aligned text to split.
Validation gate
Row count: count the rows in the document independently, for example numbered rows, or lines matching a row pattern in
pdftotext -layoutoutput, and compare with the CSV per page.Column totals: sum each numeric column with the
check_totals.pyscript 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.python3 -I <path>/check_totals.py table.csv --column Amount --printed-total 1,234.50Add
--decimal ","for a comma-decimal document, and--label-columnwhen the row labels are not in the first column.Subtotals: reconcile each printed subtotal, then the grand total.
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.
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.
- poppler manual pages: https://manpages.debian.org/testing/poppler-utils/pdftotext.1.en.html , https://manpages.debian.org/testing/poppler-utils/pdffonts.1.en.html , https://manpages.debian.org/testing/poppler-utils/pdftoppm.1.en.html
- pdfplumber: https://github.com/jsvine/pdfplumber
- Camelot: https://github.com/camelot-dev/camelot
- tabula-java: https://github.com/tabulapdf/tabula-java ; tabula-py: https://github.com/chezou/tabula-py
- OCRmyPDF: https://ocrmypdf.readthedocs.io/en/latest/introduction.html , https://ocrmypdf.readthedocs.io/en/latest/cookbook.html
- Package metadata (license, Python version): https://pypi.org/project/camelot-py/ , https://pypi.org/project/ocrmypdf/
- RapidOCR: https://github.com/RapidAI/RapidOCR , https://pypi.org/project/rapidocr/
- Tesseract: https://tesseract-ocr.github.io/tessdoc/ImproveQuality.html , https://tesseract-ocr.github.io/tessdoc/Command-Line-Usage.html
- pypdf, extracting text: https://pypdf.readthedocs.io/en/stable/user/extract-text.html
- Unicode CLDR, number patterns: https://unicode.org/reports/tr35/tr35-numbers.html