In Python, read the text with pdfplumber or Tesseract at 300 dpi, have an LLM fill a JSON schema, then run 5 arithmetic checks in code. The invoice preset does it for $0.02 a page, 50 pages free.
Extract invoice data with Python: OCR, an LLM and a totals check
Tesseract at 300 dpi and a local model can hand you valid JSON for a scan whose numbers don't add up. The pipeline below runs 5 checks on every total before you save it, then sends the same scan through parserkit's invoice preset.
GuidesUpdated
Step by step
Extract invoice data with Python
Get the text: text layer first, OCR for scans
read_text()asks pdfplumber for each page's text layer. invoice-ridgeback.pdf has one, so that is all it needs. invoice-hollins-scan.pdf is a scan with no text layer, so the function renders the page at 300 dpi and runs Tesseract 5.5.0 on it. Tesseract read most lines right, but it turned the printed quantity 3.5 on the labor line intoahs)and added stray lines such asSSSandiB 8.extract_invoice.py (part 1) import json import sys import pdfplumber import pytesseract import requests # ... def read_text(path): pages = [] with pdfplumber.open(path) as pdf: for page in pdf.pages: text = page.extract_text() or "" if not text.strip(): image = page.to_image(resolution=300).original text = pytesseract.image_to_string(image) pages.append(text) return "\n\n".join(pages) # $ python -c 'from extract_invoice import read_text; print(read_text("invoice-hollins-scan.pdf"))' # Hollins Brook Plumbing & Heating INVOICE # # 62 Barre St, Montpelier, VT 05602 # ... # DESCRIPTION QTY UNIT PRICE AMOUNT # Labor, licensed plumber, hours ahs) 95.00 332.50 # Pipe insulation, 6 ft 8 4.25 34.00 # PEX pipe 3/4 in, 10 ft 3 18.90 56.70 # Ball valve 3/4 in, brass 2 24.60 49.20 # Expansion tank fittings 4 7.35 29.40 # Service call, visits 2 45.00 90.00 # Subtotal 591.80 # Sales tax 6% on 169.30 10.16 # SSS # Total (USD) 601.96 # Paid at booking 150.00 # Balance due (USD) 451.96 # Pay by check to Hollins Brook Plumbing & Heating # Terms Net 30 # # Thank you. Sales tax applies to parts only. # # Hollins Brook Plumbing & Heating Montpelier, Vermont VT plumbing license PL-04412 # iB 8Have an LLM fill a JSON schema
extract()posts the text to a local Ollama server withformatset to a JSON schema, temperature 0 and thinking off. Ollama's docs say structured outputs let you enforce a JSON schema on model responses, and on the scan qwen3:4b did return JSON that fits the schema. The values are another story. Line 1 came back as quantity 95.0, unit price 332.5 and total 591.8, which is the subtotal, and the real quantity 8 of line 2 ended up at the end of its description. The date came back asOctober 21, 2026, since the schema only asks for a string.extract_invoice.py (part 2) # ... NUMBER = {"type": ["number", "null"]} SCHEMA = { "type": "object", "properties": { "invoice_number": {"type": "string"}, "issue_date": {"type": "string"}, "vendor_name": {"type": "string"}, "currency": {"type": "string"}, "line_items": { "type": "array", "items": { "type": "object", "properties": { "description": {"type": "string"}, "quantity": NUMBER, "unit_price": NUMBER, "total": NUMBER, }, "required": ["description", "quantity", "unit_price", "total"], }, }, "subtotal": NUMBER, "shipping": NUMBER, "tax_rate": NUMBER, "tax_base": NUMBER, "tax_total": NUMBER, "total": NUMBER, "amount_paid": NUMBER, "amount_due": NUMBER, }, "required": [ "invoice_number", "issue_date", "vendor_name", "currency", "line_items", "subtotal", "shipping", "tax_rate", "tax_base", "tax_total", "total", "amount_paid", "amount_due", ], } PROMPT = "Copy the values from this invoice into JSON. Use null for anything not printed. Do not calculate or correct numbers." # ... def extract(text): reply = requests.post( "http://localhost:11434/api/chat", json={ "model": "qwen3:4b", "messages": [ {"role": "system", "content": PROMPT}, {"role": "user", "content": text}, ], "format": SCHEMA, "think": False, "stream": False, "options": {"temperature": 0}, }, timeout=600, ) reply.raise_for_status() return json.loads(reply.json()["message"]["content"]) if __name__ == "__main__": invoice = extract(read_text(sys.argv[1])) print(json.dumps(invoice, indent=2)) # $ python extract_invoice.py invoice-hollins-scan.pdf # { # "invoice_number": "HB-0518", # "issue_date": "October 21, 2026", # "vendor_name": "Hollins Brook Plumbing & Heating", # "currency": "USD", # "line_items": [ # { # "description": "Labor, licensed plumber, hours ahs)", # "quantity": 95.0, # "unit_price": 332.5, # "total": 591.8 # }, # { # "description": "Pipe insulation, 6 ft 8", # "quantity": 4.25, # "unit_price": 34.0, # "total": 34.0 # }, # ... # ], # "subtotal": 591.8, # "shipping": null, # "tax_rate": 6.0, # "tax_base": 169.3, # "tax_total": 10.16, # "total": 601.96, # "amount_paid": 150.0, # "amount_due": 451.96 # }Check the totals in code
A schema checks types, not arithmetic, so
check()tests 5 sums to the cent: quantity times unit price on each line, the lines against the subtotal, tax base times rate against the tax, subtotal plus shipping plus tax against the total, and total minus paid against the amount due. The digital invoice passes. The scan fails 3 checks, and each failure names the values to look at. The same check caught a gap in our own schema: the first version had no shipping field, so the digital invoice failed until we added one.check_invoice.py import json import sys CENT = 0.01 def off(expected, printed): return printed is None or abs(round(expected, 2) - printed) > CENT def check(inv): problems = [] for n, line in enumerate(inv["line_items"], start=1): qty, price, total = line["quantity"], line["unit_price"], line["total"] if None in (qty, price, total): problems.append(f"line {n}: quantity, unit price or total is missing") elif off(qty * price, total): problems.append(f"line {n}: {qty} x {price} = {qty * price:.2f}, printed {total:.2f}") lines = sum(line["total"] or 0 for line in inv["line_items"]) if off(lines, inv["subtotal"]): problems.append(f"lines add up to {lines:.2f}, subtotal is {inv['subtotal']}") if inv["tax_base"] is not None and inv["tax_rate"] is not None: tax = inv["tax_base"] * inv["tax_rate"] / 100 if off(tax, inv["tax_total"]): problems.append(f"tax should be {tax:.2f}, printed {inv['tax_total']}") total = (inv["subtotal"] or 0) + (inv["shipping"] or 0) + (inv["tax_total"] or 0) if off(total, inv["total"]): problems.append(f"subtotal + shipping + tax = {total:.2f}, total is {inv['total']}") if None not in (inv["total"], inv["amount_paid"]) and off(inv["total"] - inv["amount_paid"], inv["amount_due"]): problems.append(f"total - paid is not the amount due {inv['amount_due']}") return problems if __name__ == "__main__": invoice = json.load(open(sys.argv[1])) problems = check(invoice) for problem in problems: print("FAIL", problem) print(f"{len(problems)} problem(s)" if problems else "OK: lines, tax and totals add up") # $ python check_invoice.py ridgeback.json # OK: lines, tax and totals add up # $ python check_invoice.py hollins.json # FAIL line 1: 95.0 x 332.5 = 31587.50, printed 591.80 # FAIL line 2: 4.25 x 34.0 = 144.50, printed 34.00 # FAIL lines add up to 851.10, subtotal is 591.8 # 3 problem(s)Decide what happens when a check fails
Never change a number to make an invoice add up. When line 1 says 95.0 x 332.5 = 591.8, the JSON can't tell you whether the quantity, the price or the total was misread. Run the page again, or send the file and the failed checks to a person. Only an invoice that passes every check should go straight into your books.
Send the same scan to the invoice preset
One call replaces all four steps. parserkit's
invoicepreset reads the file, scan or not, checks the arithmetic before it answers, and re-reads any field that fails from a 400 DPI crop. The recorded run of the Hollins scan, the file our Tesseract and qwen3:4b pipeline failed 3 checks on, came back verified, every value checked, for 1 page at $0.02. The digital Ridgeback invoice came back verified too. Each response lists the checks it ran next to the data, as in the example below; volume rates are on pricing.
Example
The Hollins scan through the invoice preset
The recorded run of invoice-hollins-scan.pdf: the request, and the response with the checks it ran.
POSTapi.parserkit.com/v1/parse?wait=60
curl "https://api.parserkit.com/v1/parse?wait=60" \
-H "Authorization: Bearer $PARSERKIT_API_KEY" \
-F file=@invoice-hollins-scan.pdf \
-F preset=invoiceimport os
import requests
with open("invoice-hollins-scan.pdf", "rb") as file:
res = requests.post(
"https://api.parserkit.com/v1/parse",
params={"wait": 60},
headers={"Authorization": f"Bearer {os.environ['PARSERKIT_API_KEY']}"},
files={"file": file},
data={"preset": "invoice"},
)
job = res.json()
print(job["verification"]["status"], job["verification"]["coverage"])import { openAsBlob } from "node:fs";
const form = new FormData();
form.append("file", await openAsBlob("invoice-hollins-scan.pdf"), "invoice-hollins-scan.pdf");
form.append("preset", "invoice");
const res = await fetch("https://api.parserkit.com/v1/parse?wait=60", {
method: "POST",
headers: { Authorization: `Bearer ${process.env.PARSERKIT_API_KEY}` },
body: form,
});
const job = await res.json();
console.log(job.verification.status, job.verification.coverage);{
"id": "job_mcbztlqmko6mbq7kk94i",
"status": "succeeded",
"preset": "invoice",
"pages": 1,
"cost_usd": 0.02,
"verification_status": "verified",
"data": {
"invoice_number": "HB-0518",
"issue_date": "2026-10-21",
"due_date": "2026-11-20",
"purchase_order": "J-2291",
"currency": "USD",
"vendor": {
"name": "Hollins Brook Plumbing & Heating",
"address": "62 Barre St, Montpelier, VT 05602",
"email": "office@hollinsbrook.example",
"phone": "(802) 555-0163"
},
"customer": {
"name": "Dana Whitcomb",
"address": "118 Maple Ave, Barre, VT 05641"
},
"line_items": [
{
"description": "Labor, licensed plumber, hours",
"quantity": 3.5,
"unit_price": 95,
"total": 332.5
},
{
"description": "Pipe insulation, 6 ft",
"quantity": 8,
"unit_price": 4.25,
"total": 34
},
{
"description": "PEX pipe 3/4 in, 10 ft",
"quantity": 3,
"unit_price": 18.9,
"total": 56.7
}
],
"subtotal": 591.8,
"taxes": [
{
"label": "Sales tax 6% on 169.30",
"rate": 6,
"base": 169.3,
"amount": 10.16
}
],
"tax_total": 10.16,
"grand_total": 601.96,
"amount_paid": 150,
"amount_due": 451.96,
"payment": {
"terms": "Net 30"
},
"notes": "Thank you. Sales tax applies to parts only."
},
"verification": {
"status": "verified",
"math_balanced": true,
"coverage": {
"values": 46,
"checked": 46
},
"checks": [
{
"kind": "line_total",
"path": "line_items[0].total",
"status": "pass",
"expected": 332.5,
"actual": 332.5,
"difference": 0,
"message": "quantity x unit price"
},
{
"kind": "line_total",
"path": "line_items[1].total",
"status": "pass",
"expected": 34,
"actual": 34,
"difference": 0,
"message": "quantity x unit price"
},
{
"kind": "line_total",
"path": "line_items[2].total",
"status": "pass",
"expected": 56.7,
"actual": 56.7,
"difference": 0,
"message": "quantity x unit price"
},
{
"kind": "line_total",
"path": "line_items[3].total",
"status": "pass",
"expected": 49.2,
"actual": 49.2,
"difference": 0,
"message": "quantity x unit price"
},
{
"kind": "line_total",
"path": "line_items[4].total",
"status": "pass",
"expected": 29.4,
"actual": 29.4,
"difference": 0,
"message": "quantity x unit price"
},
{
"kind": "line_total",
"path": "line_items[5].total",
"status": "pass",
"expected": 90,
"actual": 90,
"difference": 0,
"message": "quantity x unit price"
}
]
},
"outputs": [
{
"name": "output.json",
"bytes": 12857
},
{
"name": "output.xlsx",
"bytes": 10448
},
{
"name": "output.csv",
"bytes": 747
},
{
"name": "quickbooks.csv",
"bytes": 678
},
{
"name": "xero.csv",
"bytes": 1450
}
],
"warnings": []
}Real response from . Trimmed to 3 of 6 line items and 6 of 11 checks, with bounding boxes, empty fields and file links left out.
Try it on this fileWhat each step returned on the 2 invoices
invoice-ridgeback.pdf has a text layer; invoice-hollins-scan.pdf is a scan.
| Step | invoice-ridgeback.pdf | invoice-hollins-scan.pdf |
|---|---|---|
| Text | pdfplumber text layer | Tesseract 5.5.0 at 300 dpi, 3.5 read as ahs) |
| JSON from qwen3:4b | Valid JSON | Valid JSON, lines 1 and 2 shifted by a column |
| check() | OK: lines, tax and totals add up | 3 checks failed |
| parserkit invoice preset | verified, every value checked | verified, every value checked |
Where this pipeline breaks
Tesseract turned 3.5 into ahs), and the model shifted line 1 by a column, so the scan came back as valid JSON with wrong numbers. Our check caught it only because we wrote 5 sums by hand, and our own first schema still missed shipping. When a check fails, the JSON can't say which value was misread, so the invoice waits for a person, and the date still comes back as printed.
parserkit's invoice preset does the reading and the sums in one call, plus each tax line and the IBAN, EIN and VAT numbers, re-reads a failing field from a 400 DPI crop, returns typed values and dates as YYYY-MM-DD, and writes QuickBooks and Xero bill files.
What we ran
Every script here ran on Python 3.12.14. The model was qwen3:4b, run locally through Ollama 0.40.15 on 2 CPU cores with 4 GB of memory, so nothing left the machine and nothing was billed. The lines under # $ in each code block are what the script printed, cut only where you see ....
Both invoices are parserkit's public samples, made up for testing. The full scripts and outputs are linked under Sources.
import platform
import subprocess
import sys
from importlib.metadata import version
TOOLS = {
"tesseract": lambda: subprocess.run(["tesseract", "--version"], capture_output=True, text=True).stdout.split()[1],
"ollama": lambda: subprocess.run(["ollama", "--version"], capture_output=True, text=True).stdout.split()[-1],
"libreoffice": lambda: subprocess.run(["soffice", "--version"], capture_output=True, text=True).stdout.split()[1],
}
print("Python", platform.python_version())
for name in sys.argv[1:]:
print(name, TOOLS[name]() if name in TOOLS else version(name))
# $ python versions.py pdfplumber pytesseract requests tesseract ollama
# Python 3.12.14
# pdfplumber 0.11.10
# pytesseract 0.3.13
# requests 2.34.2
# tesseract 5.5.0
# ollama 0.40.15FAQ
Common questions
Do I need OCR for every PDF invoice?
No. A digital PDF like invoice-ridgeback.pdf has a text layer, and pdfplumber's extract_text() reads it directly. Render the page and run Tesseract only when extract_text() comes back empty, as it does on a scan like invoice-hollins-scan.pdf. parserkit's invoice preset makes that call for you on every page.
Why check totals if the model follows a JSON schema?
Ollama's docs say structured outputs let you enforce a JSON schema on model responses. That fixes field names and types, not the arithmetic. On our scan, qwen3:4b returned valid numbers for a line of 95.0 x 332.5 with a total of 591.8, and lines that add up to 851.10 against a subtotal of 591.80. parserkit runs those sums on every invoice before it answers and names the one that fails, with both numbers.
Which model and hardware did you use?
qwen3:4b through Ollama 0.40.15 on CPU, with 2 cores and 4 GB of memory, temperature 0 and thinking off. OCR was Tesseract 5.5.0 through pytesseract 0.3.13, on Python 3.12.14 with pdfplumber 0.11.10 and requests 2.34.2.
What does the invoice preset cost?
$0.02 a page, and $0.01 a page past 5,000 pages in a month. Signing in with Google gives you $1.00 of credit, which is 50 pages free. Failed jobs cost nothing. The 1-page Hollins scan cost $0.02.
Related
- Invoice parser APILine items, taxes and totals as JSON, with every sum re-added.
- Invoice OCR APIsparserkit first for invoices with every line and total checked at $0.02 a page, then AWS Textract, Azure and Google Document AI.
- parserkit vs MindeeMindee alternative at $0.02 a page: Mindee invoice API pricing in 2026, the platform fee, expiring credits, and parserkit's checked invoices.
- parserkit vs AWS TextractAWS Textract alternative: checked fields at $0.02 a page, with protected PDFs, Office files and emails read, and no S3 bucket to set up.
- Extract tables from a PDF in Pythonpdfplumber and camelot on a 2-page price list with no ruling lines, merged cells and a scan, then the same file through the API.
- Track receipts in ExcelA free 3-sheet Excel receipt tracker with month and category totals, plus a Python script that adds rows from receipt photos.
- extract_text returns emptypdfplumber and pypdf return '' on scanned PDFs. Spot a scan in one line, then let parserkit read it with OCR and checked totals.
Start free
Send us your worst scan
Your first $1 is free: 50 pages with every check and export, no card.
