DEV Community

Panix AI Lab
Panix AI Lab

Posted on

Extract tables from PDF invoices, receipts and bank statements to JSON, with OCR only where it's needed

Getting tables out of PDFs is one of those tasks that looks solved until you try it on real documents:

  • camelot and tabula work on clean, ruled tables, but miss borderless ones, which is how most invoices are laid out.
  • Scanned invoices and phone photos of receipts have no text layer, so text-based tools return nothing.
  • Running OCR on every page is slow and expensive, and it can make digital pages worse.
  • Cloud document AI services need an account and an API key, and your financial documents leave your system.

I built an Apify Actor for this: Invoice, Receipt & PDF Table to JSON / Markdown OCR. It uses IBM's open-source Docling (layout analysis plus the TableFormer table model) and RapidOCR, all bundled inside the Actor. There's no external API key, and documents aren't sent to a third-party AI service. This post shows what comes out and how to call it from Python or an n8n workflow.

How it decides when to OCR

Every PDF page is checked for an embedded text layer:

  • Digital pages are read straight from the text layer, with no OCR. That's fast and cheap, and logos and images inside them are never OCR'd.
  • Scanned pages, photos and image files (JPG, PNG, TIFF, BMP, WEBP) get full-page OCR.
  • Mixed PDFs are split into runs of pages of the same kind and merged back in page order. A 20-page contract with two scanned signature pages only OCRs those two pages.

You can force ocrMode: "always" when a PDF's embedded text is garbled, or "never" to skip OCR completely.

What you get

One dataset row per document. This is the output for a public sample invoice, shortened:

{
  "file_name": "wordpress-pdf-invoice-plugin-sample.pdf",
  "document_type": "pdf",
  "status": "success",
  "pages_total": 1,
  "pages_digital": 1,
  "pages_ocr": 0,
  "table_count": 3,
  "tables_json": [
    {
      "table_index": 1,
      "page_number": 1,
      "headers": ["Hrs/Qty", "Service", "Rate/Price", "Adjust", "Sub Total"],
      "rows": [
        {
          "Hrs/Qty": "1.00",
          "Service": "Web Design This is a sample description...",
          "Rate/Price": "$85.00",
          "Adjust": "0.00%",
          "Sub Total": "$85.00"
        }
      ],
      "row_count": 1,
      "column_count": 5
    }
  ],
  "full_markdown": "## From:\nDEMO - Sliced Invoices ...\n\n| Hrs/Qty | Service | Rate/Price | Adjust | Sub Total |\n|---|---|---|---|---|\n| 1.00 | Web Design ... | $85.00 | 0.00% | $85.00 |",
  "processing_time_secs": 6.1
}
Enter fullscreen mode Exit fullscreen mode

Some details that save you cleanup work:

  • Each table is a list of row objects keyed by header, so you can load it straight into pandas or a sheet.
  • Headers are always unique. Two "Amount" columns become Amount and Amount_2, so no cell gets overwritten. Empty cells are null.
  • full_markdown keeps headings, reading order and tables. It works for an LLM prompt or a RAG index.
  • A broken link or an HTML page comes back as "status": "failed" with a reason, and it never stops the rest of the batch.

Option 1: try it in the browser (1 minute)

  1. Open the Actor page and click Try for free.
  2. The input already has a sample invoice. Replace it with direct links to your own PDFs or images.
  3. Click Start, then open the Tables or Markdown view, or download JSON, CSV or Excel.

Links must return the file itself, not a preview page. Signed S3 links work, and tokens in links never show up in the log.

Option 2: Python, from invoices to a DataFrame

import pandas as pd
from apify_client import ApifyClient

client = ApifyClient("<YOUR_APIFY_TOKEN>")
run = client.actor("panix/invoice-table-json-extractor").call(run_input={
    "documentUrls": [
        "https://slicedinvoices.com/pdf/wordpress-pdf-invoice-plugin-sample.pdf",
    ],
    "ocrMode": "auto",
})

frames = []
for doc in client.dataset(run.default_dataset_id).iterate_items():
    if doc["status"] not in ("success", "partial_success"):
        print("failed:", doc["source_url"], doc["error_message"])
        continue
    for table in doc["tables_json"]:
        df = pd.DataFrame(table["rows"])
        df["file"] = doc["file_name"]
        df["page"] = table["page_number"]
        frames.append(df)

print(pd.concat(frames, ignore_index=True).head())
Enter fullscreen mode Exit fullscreen mode

Invoice layouts vary a lot. The most reliable way to get fixed fields such as invoice number, due date, total and VAT is to send full_markdown to an LLM with your schema. The Markdown already has the tables in order, so the prompt stays short.

Option 3: an n8n workflow for incoming invoices

  1. Gmail trigger (or Google Drive "new file") for invoices.
  2. Make the file reachable by a direct link (S3, GCS, or a Drive direct-download link).
  3. HTTP Request node: POST https://api.apify.com/v2/acts/panix~invoice-table-json-extractor/run-sync-get-dataset-items, header Authorization: Bearer <YOUR_APIFY_TOKEN>, body {"documentUrls": ["<link>"]}.
  4. A Code node that flattens tables_json[].rows into items, or an LLM node that pulls invoice fields out of full_markdown.
  5. Google Sheets, Airtable or your accounting tool's API.

Make and Zapier have Apify apps with a Run Actor action for step 3.

What it costs

You pay per page that was parsed:

Apify plan Digital page OCR page
Free $0.005 $0.02
Starter $0.0045 $0.018
Business and up $0.0035 $0.014

On top of that there's a start fee of $0.004 per run at the default 4 GB. On the Starter plan, a one-page digital invoice costs $0.0085 and a 3-page scanned statement costs $0.058. Failed and skipped documents are free. If you set a maximum charge per run, the Actor parses only the pages that fit and marks the rest as skipped.

Limitations

  • OCR handles Latin-script languages and Chinese best. Handwriting and blurry photos are less reliable.
  • An OCR page takes about 10–35 seconds on the default 4 GB (1 CPU). Digital pages take a few seconds. Give large scanned batches a longer run timeout.
  • Password-protected PDFs aren't supported.
  • It extracts tables and text, but it doesn't know what an "invoice total" is. Use the LLM step above for fixed fields.
  • Invoices often contain personal data. Make sure you're allowed to process them.

If a document's tables come out wrong, leave a comment or open an issue on the Actor's Issues tab with a similar sample file. I read them all.

Top comments (0)