DEV Community

Cover image for Extracting tables from PDFs and scans in constant RAM (no Java or Ghostscript)
vitali84
vitali84

Posted on

Extracting tables from PDFs and scans in constant RAM (no Java or Ghostscript)

Pulling clean CSV tables out of PDFs in Python still gets weirdly painful once you leave toy examples behind.

Camelot needs Ghostscript, Tabula needs a JVM, and both give up as soon as someone hands you a scanned document or a hybrid PDF with a digital stamp slapped on top of a tilted scan. On the other hand, full document-layout deep learning models work well when you want whole-document parsing, but they are heavy when all you actually need is a CSV of the tables.

I ended up writing pdf-to-csv-table-extractor (MIT) to cover both cases in a single pip-installable package, and put a free no-login web UI on top of it at TableCSV.com (uploads stay in RAM and are discarded right after extraction).

How the pipeline works

Instead of running OCR on everything (slow) or assuming every PDF has clean vector text (breaks on scans), the extractor decides page by page:

  1. If a page has usable native PDF text, pypdfium2 reads exact word bounding boxes directly. That skips OCR completely and runs 40x to 80x faster.
  2. If a page is an image-only scan, a raster image (PNG/JPG/WebP/TIFF), or a stamped hybrid scan, it estimates the skew angle, deskews the page, finds bordered or borderless table grids with OpenCV, and runs RapidOCR (ONNX Runtime) only on the detected table regions rather than the surrounding prose.
  3. Across pages, tables with matching column schemas get merged into a single CSV. Repeated headers (including stacked 2-row headers and minor OCR typos) are deduplicated, headerless continuation pages get stitched onto the previous table, and unrelated tables on the same page stay in separate CSV files.

Cutting memory to constant RAM in v1.0.3

Earlier versions loaded all rendered pages of a PDF or multi-frame TIFF into memory up front before running extraction. That worked fine for 10-page files, not so great for 200-page scanned reports at 250 DPI.

In v1.0.3, open_input_pages() streams pages lazily into a bounded worker window:

  • With workers=1, at most 1 rendered page is held in RAM at a time.
  • With workers=N, at most N pages are in flight while keeping output order deterministic and closing PDFium/TIFF handles cleanly.

That is also what lets TableCSV.com run on a small 1-vCPU Cloud Run container and handle up to 25 digital or scanned pages per run with live page-by-page progress over SSE.

What the grid detection looks like

The CLI has a --debug-dir flag that draws the detected headers (amber) and extracted cells (blue/green) on top of the source pages. A few examples from the test suite:

16-page California WARN report (warn_report.pdf) — 643 rows merged across headerless continuation pages in 0.95 s:

California EDD WARN 16-page PDF table extraction overlay

Tilted JPEG scan (foo_scanned.pdf) — auto-deskewed (-1.74°), prose ignored, stacked 2-row header flattened:

Tilted scanned PDF auto-deskewed with OpenCV grid overlay

Two separate tables on one page (multiple_tables.pdf) — split into separate CSVs with surrounding paragraphs ignored:

Two distinct PDF tables detected on one page with prose ignored

Benchmarks and when to use something else

All sample PDFs and benchmarks/benchmark.py are in the repo. Timings below are on an Intel Core Ultra 7 270K Plus (Python 3.14, ONNX Runtime 1.32.0, 250 DPI):

Sample PDF Pages Rows Default (--text-source auto) Forced CPU OCR Notes
multiple_tables.pdf 1 10 0.05 s 0.84 s Digital PDF (native)
foo.pdf 1 5 0.08 s 1.49 s Digital PDF (native)
background_checks.pdf (56x25) 1 56 0.12 s 5.72 s Digital PDF (native)
warn_report.pdf (CA WARN) 16 643 0.95 s 17.91 s Native + auto workers
foo_scanned.pdf (tilted scan) 1 5 0.55 s (--no-borderless) 0.55 s / 1.47 s Auto-deskew + RapidOCR

On pure OCR workloads, switching to a GPU (NVIDIA CUDA or AMD ROCm) speeds up end-to-end runtime by roughly 2.8x to 3.8x. Full tables are on tablecsv.com/compare.

It is not the right tool for every job:

  • Use pdfplumber if you only deal with clean digital PDFs and want low-level access to raw character coordinates or custom rules.
  • Use Docling if you need full-document conversion (headings, body prose, figures, equations) instead of just table extraction.
  • Stick with Camelot or Tabula-py if you already have working legacy digital-only pipelines tuned around them.

Trying it out

Install locally (Python 3.11–3.14, Linux/macOS/Windows, no external OS binaries):

pip install pdf-to-csv-table-extractor

# Optional: logical ordering for right-to-left Arabic, Persian, or Urdu
pip install "pdf-to-csv-table-extractor[rtl]"
Enter fullscreen mode Exit fullscreen mode
from pdf_table_extractor import ExtractionConfig, extract_tables

cfg = ExtractionConfig(
    text_source="auto",          # native PDF text + automatic OCR fallback
    ocr_lang="en",               # 50 built-in languages (e.g. "de", "ja", "ar")
    merge="schema",              # merge matching multi-page tables
    utf8_bom=True,               # avoids garbled Excel imports for €, accents, CJK, RTL
    formula_guard="non_numeric", # blocks =CMD/@SUM while keeping -$42.50 numeric
)

result = extract_tables("bank_statement.pdf", cfg)
for table in result:
    table.to_csv(f"output/{table.slug}.csv")
    md = table.to_markdown()     # handy for RAG prompts
    df = table.to_dataframe()    # or table.to_polars()
Enter fullscreen mode Exit fullscreen mode

Or test a file in the browser without installing anything:

If you have weird PDF layouts or crooked scans that still break table extractors, feel free to share them in the comments or open an issue on GitHub.

Top comments (0)