pdfmux/blog
python

Receipt data extraction in Python: OCR, parsing, and totals

TL;DRExtract vendor, date, line items, and totals from receipt PDFs in Python, with OCR for photographed receipts, confidence scoring, and why receipts break invoice parsers.

Direct answer: Extract receipt data in Python with pip install pdfmux[ocr] and pdfmux.extract_json("receipt.pdf"). The returned dict auto-detects key_values (vendor name, date, totals — whatever appears as a labeled field) and tables (line items) with no schema file required, and every page carries a confidence score, which matters more for receipts than almost any other document type: most receipts are phone photos or thermal-printer scans, not clean digital PDFs, so OCR errors (a $ misread as S, a faded total) are the normal case, not the edge case. Route anything under 0.7 confidence to manual review before trusting the total.


Why receipts are a different problem than invoices

Invoice extraction and receipt extraction look similar on paper — both are “pull vendor, date, amount from a short document” — but receipts fail in ways invoices mostly don’t:

  1. They’re rarely clean digital PDFs. An invoice is usually generated by accounting software and emailed as a PDF with a text layer. A receipt is far more often a phone photo of a paper slip, a PDF export from a thermal printer with faded or smeared ink, or a screenshot of an email confirmation. All three need OCR; none of them benefit from the “just read the text layer” shortcut that works for most invoices.
  2. No standard layout. Invoices cluster around a handful of layouts (header, line-item table, totals block). Receipts range from a 58mm thermal strip with no columns at all to a full-page restaurant bill with a tip-calculation grid. There’s no single table shape to anchor a parser on.
  3. Low, uneven image quality. Thermal paper fades over weeks. Phone photos are off-angle, shadowed, or slightly blurred. A parser that assumes “the text is there, just find it” breaks constantly; a parser that assumes “some fraction of this document is unreadable and I need to know which fraction” survives.
  4. The number that matters is usually the smallest one on the page. The total is often printed in the same font size as the subtotal, tax, and tip lines directly above it — sometimes smaller than the merchant’s logo text. Naive “biggest number on the page” heuristics misfire here far more than on invoices, where the total is usually visually emphasized.

This is why “run Tesseract and regex for a dollar sign” — which works surprisingly often on invoices — has a much higher failure rate on receipts. You need per-page confidence to know when to trust the OCR output at all, not just text in roughly the right shape.

Step 1: Install with OCR support

pip install "pdfmux[ocr]"

pdfmux’s OCR runs entirely on CPU, no GPU or API keys — important here because receipt-processing pipelines are usually high-volume and low-value-per-document, so a per-page cloud OCR fee adds up fast relative to what each receipt is worth.

Step 2: Extract as structured JSON

import pdfmux

result = pdfmux.extract_json("receipt.pdf", quality="standard")

print(f"Confidence: {result['confidence']:.0%}")
print(f"Pages OCR'd: {result['ocr_pages']}")

for kv in result.get("key_values", []):
    print(f"{kv['key']}: {kv.get('normalized', kv['value'])}")

for table in result.get("tables", []):
    print(f"Line items (page {table['page']}): {len(table['rows'])} rows")

extract_json detects key-value pairs and tables automatically — no schema file needed for the common case. key_values picks up labeled fields like Total: $47.82 or Date: 11/14/2026; tables picks up anything that reads as a grid of line items (item, qty, price). Not every receipt has both — a thermal strip from a small retailer might have line items but no labeled “Total:” field, just a bolded number at the bottom.

Step 3: Find the total when it isn’t labeled

Many receipts never print the word “Total” next to the final amount, or print it in a font the OCR engine misreads. When key_values doesn’t surface it cleanly, fall back to scanning the raw page text for amount-shaped tokens and taking the last one — receipts print subtotal, tax, tip, and total in that order far more reliably than they label any of them.

import re

AMOUNT_RE = re.compile(r"\$?\s*(\d{1,4}(?:,\d{3})*\.\d{2})\b")

def guess_total(page_text: str) -> float | None:
    """Fallback: the last dollar-amount-shaped token on the page is almost
    always the total, since receipts print subtotal/tax/tip/total in that
    fixed order even when they don't label any of them."""
    amounts = [float(m.group(1).replace(",", "")) for m in AMOUNT_RE.finditer(page_text)]
    return amounts[-1] if amounts else None

for page in result["pages"]:
    kv_total = next(
        (kv["value"] for kv in result.get("key_values", [])
         if kv["key"].lower() in ("total", "amount due", "grand total") and kv["page"] == page["page"]),
        None,
    )
    total = kv_total or guess_total(page["text"])
    print(f"Page {page['page']}: total = {total}")

Treat the labeled key_values hit as authoritative when it exists, and the position-based fallback as a lower-confidence guess — log which path produced the number so you can measure how often you’re relying on the fallback.

Step 4: Gate everything on confidence

This is the step that makes receipt extraction usable instead of merely automated. A thermal receipt photographed at an angle can come back with a plausible-looking but wrong total — OCR confidently misreading a 3 as an 8 doesn’t look like an error until someone checks the math.

LOW_CONFIDENCE = 0.70

flagged = [p for p in result["pages"] if result["confidence"] < LOW_CONFIDENCE]
# For a single-page receipt, result["confidence"] already covers the whole document.
# For a multi-page expense report PDF (several receipts stitched together),
# check each page's contribution via result["ocr_pages"] instead.

if result["confidence"] < LOW_CONFIDENCE:
    print(f"⚠️  Low confidence ({result['confidence']:.0%}) — route to manual review")
else:
    print(f"✅ {result['confidence']:.0%} confidence — safe to auto-post")

A reimbursement or bookkeeping pipeline should never silently auto-post a receipt below your confidence floor. Route it to a human queue instead — the cost of a 10-second manual glance is far lower than the cost of a wrong number reaching the books.

Step 5: Batch a folder of receipts

Expense reports and bookkeeping imports rarely arrive one receipt at a time. batch_extract processes a directory concurrently and yields results as they complete:

from pathlib import Path
import pdfmux

receipts = list(Path("./receipts").glob("*.pdf"))

rows = []
for path, outcome in pdfmux.batch_extract(receipts, output_format="json", quality="standard"):
    if isinstance(outcome, Exception):
        print(f"❌ {path.name}: {outcome}")
        continue
    import json
    data = json.loads(outcome.text)
    rows.append({"file": path.name, "confidence": data["confidence"], "needs_review": data["confidence"] < LOW_CONFIDENCE})

print(f"{len(rows)} processed, {sum(r['needs_review'] for r in rows)} flagged for review")

How the options compare for receipts

Tool Handles photos/thermal scans Structured output Per-page confidence Cost
pdfmux Yes ([ocr] extra, CPU) Tables + key-values, auto-detected Yes Free (MIT)
Raw pytesseract + regex Yes, but accuracy varies a lot with angle/lighting None — you parse raw text yourself No Free
AWS Textract (Expense API) Yes Yes, receipt-specific fields Per-field Per-page API fee
Google Document AI (Expense parser) Yes Yes, receipt-specific fields Per-field Per-page API fee

The cloud expense-parsing APIs are genuinely good at this specific task — they’re trained on large receipt datasets and will out-perform a general-purpose extractor on edge cases like heavily stylized logos. The tradeoff is cost at volume (per-page fees add up fast when receipts are high-volume and low-value-per-document) and sending receipt images — which often contain the last four digits of a card number — to a third party. For most self-hosted expense or bookkeeping tooling, a local, confidence-gated pipeline is the better default; reach for a cloud expense API only after confirming the per-page fee pencils out at your volume.

Production checklist

  • Install with the OCR extra: pip install "pdfmux[ocr]"
  • Use extract_json, not extract_text — you need key_values/tables, not just a text blob
  • Prefer the labeled key_values total; fall back to the last amount-shaped token on the page
  • Gate on confidence — route anything under ~0.70 to manual review, never auto-post blind
  • For multi-receipt batches, use batch_extract instead of looping extract_json in Python (avoids repeated process spin-up)
  • Never persist the last 4 digits of a card number from a receipt without a reason to — redact before storage if you don’t need it

FAQ

Can it read a photo of a receipt, not just a PDF? pdfmux’s pipeline is PDF-first. For a raw JPEG/PNG photo, wrap it in a single-page PDF first (most phone “scan to PDF” features do this automatically), then run the same extract_json call.

Why does the total come back as a key_value on some receipts and not others? Key-value detection looks for a labeled pattern (Total: $X, Amount Due: $X). A receipt that just bolds the number with no label won’t match — that’s exactly the case the position-based fallback in Step 3 is for.

How do I handle non-USD currencies? key_values returns the raw string as printed, so €47,82 stays €47,82. Add currency-symbol detection to your own parsing step before converting to a float — don’t assume . is always the decimal separator.

Is receipt image data sent anywhere? No. Both text extraction and OCR run locally — nothing leaves your machine, which matters here given receipts routinely contain partial card numbers and home addresses.

Keep reading

Last updated: November 2026. Benchmark figures are from the opendataloader-bench (200 real-world PDFs).