Helenis API
Start for free

BusinessInvoice Processing

Invoice OCR API: PDF Invoices and Receipt Photos to Accounting JSON

Invoice OCR API tutorial: turn PDF invoices, scans and receipt photos into accounting JSON with Python, and re-add every total to catch misread figures.

Invoice OCR API cover: a receipt sticker, an arrow and a JSON response with the supplier, VAT ID, invoice number, a 49.99 EUR total and consistent set to true.
A Dutch invoice parsed to JSON, with every total re-added: consistent is true.

In a lot of companies, accounts payable still means retyping. A supplier PDF arrives, someone copies the supplier, the VAT number, the dates, every line and the tax breakdown into the accounting system, then opens the next one. Receipts are worse: a phone photo of a creased till slip, in whatever language the trip happened in.

An invoice OCR API should take that work away. Reading characters is no longer the hard part. The hard part is turning a page into the fields an ERP expects, on layouts you have never seen, and knowing when the result is wrong. A model that misreads 49.99 as 48.99 does not warn you; it returns a plausible number with full confidence.

This article builds a pipeline around the Invoice & Receipt Parser API: PDFs, scans, receipt photos and e-invoice XML go in, one accounting JSON shape comes out, and arithmetic checks decide which documents are posted automatically and which need a person.

Why invoice extraction is harder than OCR

Plain OCR gives you text in reading order. Accounting needs a record: who issued the document, what was sold, at which tax rate, and what is left to pay. Getting there hits the same problems on every project:

  • Layouts have no limit. Columns move, totals sit in a footer box or halfway down the page, and one field has a dozen labels ("Invoice no.", "Factuurnummer", "Rechnungsnummer").
  • Net or gross is ambiguous. B2B invoices usually print net line amounts and add VAT at the bottom; receipts print gross amounts. Post a gross line as net and every figure downstream is off by the VAT rate.
  • Tax comes by rate. A restaurant bill can carry two VAT rates; a Polish receipt labels its rates with letters (PTU A, B, C). The ledger needs base and amount per rate.
  • Identifiers depend on the country. A VAT number, but also a SIRET in France, a KvK number in the Netherlands, an EIN in the US.
  • Errors are silent. A template parser fails loudly when a layout changes. A language model fails quietly: a blurred digit becomes a believable one.

The last point decides whether you can automate at all. The others are parsing problems; that one is a trust problem.

Templates, plain OCR and LLM extraction compared

Approach New layouts Line items and taxes Detects its own errors Cost of a new supplier
Templates per supplier (regex or zones) No, one template each Yes, once written Partly: a missing field fails Developer time, again at every layout change
Plain OCR + rules Somewhat Weak: tables come back as text No Rule tuning
Vision model alone Yes Yes No: a misread figure looks right None
Vision model + arithmetic checks Yes Yes Yes: totals re-added by code None
Structured e-invoice (CII or UBL XML) Not needed Exact Not needed: the data is the source None

The API combines the last two rows: an embedded e-invoice XML is read without AI; otherwise a vision model copies what is printed, never computing, and the service re-adds every figure.

What a parsed invoice contains

One response shape covers invoices, receipts, credit notes and utility bills:

  • Document: document_type, number, ISO 8601 dates (issue_date, due_date, delivery_date), purchase_order and an ISO 4217 currency.
  • Parties: the supplier with name, vat_id, typed tax_ids, business address and country. The customer is reduced to a company name, its identifiers and its country; a private customer's contact details never come back.
  • Lines and totals: quantity, unit price, discount, tax rate and amount per line; amounts_include_tax; then subtotal, charges, taxes by rate, tax_total, total, amount_paid and amount_due.
  • Payment and bookkeeping: terms, the supplier's iban and bic, an expense_category, the reading method, pages_read and the validation block.

Empty fields are left out, so read optional ones with .get().

Parse a PDF invoice with Python

POST /v1/invoices/parse takes a JSON body with a url; POST /v1/invoices/parse/upload takes a multipart file. Both accept an optional pages range ("1-2") and a password for encrypted PDFs.

Python
import requests

HOST = "invoice-receipt-parser-pdf-image-to-json.p.rapidapi.com"
API = f"https://{HOST}"
HEADERS = {"x-rapidapi-key": "YOUR_API_KEY", "x-rapidapi-host": HOST}

pdf_url = "https://raw.githubusercontent.com/invoice-x/invoice2data/master/tests/compare/saeco.pdf"
response = requests.post(
    f"{API}/v1/invoices/parse", headers=HEADERS, json={"url": pdf_url}, timeout=120
)
response.raise_for_status()
invoice = response.json()

print(invoice["supplier"]["name"], invoice["supplier"].get("vat_id"))
print(
    invoice["number"],
    invoice["issue_date"],
    invoice["totals"]["total"],
    invoice["currency"],
)

The same call from a terminal:

Terminal
curl -X POST "https://invoice-receipt-parser-pdf-image-to-json.p.rapidapi.com/v1/invoices/parse" \
  -H "X-RapidAPI-Key: YOUR_API_KEY" \
  -H "X-RapidAPI-Host: invoice-receipt-parser-pdf-image-to-json.p.rapidapi.com" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://raw.githubusercontent.com/invoice-x/invoice2data/master/tests/compare/saeco.pdf"}'

The document is a Dutch invoice from a coffee-machine retailer, taken from the invoice2data test corpus. The real response, trimmed:

JSON
{
  "document_type": "invoice",
  "number": "VF1005193039",
  "issue_date": "2022-09-08",
  "due_date": "2022-09-22",
  "currency": "EUR",
  "supplier": {
    "name": "e-Luscious Nederland B.V. iov Saeco.com",
    "vat_id": "NL8152.54.295.B01",
    "tax_ids": [{ "type": "Kvk", "value": "04080176" }],
    "country": "NL"
  },
  "lines": [
    { "description": "Onderhoudsset CA6707/10", "code": "E103184", "quantity": 1.0, "unit_price": 49.99, "tax_rate": 21.0, "total": 49.99 }
  ],
  "amounts_include_tax": true,
  "totals": {
    "subtotal": 41.31,
    "taxes": [{ "rate": 21.0, "base": 41.31, "amount": 8.68, "label": "21 %" }],
    "tax_total": 8.68,
    "total": 49.99
  },
  "payment": { "method": "card", "iban": "NL58RABO0198723202", "bic": "RABONL2U" },
  "method": "ai",
  "pages_read": 1
}

Two details matter for accounting. The Dutch company register number comes back typed as Kvk. And amounts_include_tax: true says the 49.99 line is gross: the net base (41.31) and the VAT (8.68), which a purchase journal entry needs, are in totals.taxes.

Validate invoice totals: let the arithmetic decide

Every response ends with a validation block. The model copied the figures; the service then re-adds them:

Check What is re-added
line_math quantity × unit price, less the line discount, against each line amount
lines_sum the line amounts against the subtotal (net lines) or the total (gross lines)
tax_rates taxable base × rate against each tax amount
tax_sum the taxes by rate against the tax total
total subtotal + tax + charges − discount + tip against the grand total
amount_due total − amount paid against the amount due
iban the ISO 13616 checksum of the supplier's IBAN

Each check is ok, mismatch (with expected, found and difference) or skipped when the document does not print what it needs. One cent of rounding per line is tolerated. For the Saeco invoice:

JSON
{
  "validation": {
    "consistent": true,
    "checks": [
      { "name": "line_math", "status": "ok", "detail": "2 line(s) checked." },
      { "name": "lines_sum", "status": "ok", "expected": 49.99, "found": 49.99, "difference": 0.0 },
      { "name": "total", "status": "ok", "expected": 49.99, "found": 49.99, "difference": 0.0 },
      { "name": "amount_due", "status": "skipped", "detail": "Total, amount paid or amount due missing." },
      { "name": "iban", "status": "ok", "detail": "IBAN checksum valid." }
    ]
  }
}

consistent is true when every check that could run passed, false as soon as one figure does not add up, null when there was nothing to check. The routing rule is short, and the reviewer gets the failed check instead of a whole invoice to re-read:

Python
def route(invoice: dict) -> tuple[str, list[str]]:
    validation = invoice["validation"]
    if validation["consistent"] is True:
        return "post", []
    reasons = [
        check.get("detail")
        or f"{check['name']}: expected {check.get('expected')}, found {check.get('found')}"
        for check in validation["checks"]
        if check["status"] == "mismatch"
    ]
    return "review", reasons or ["nothing could be checked"]

About the IBAN check: an ISO 13616 IBAN carries two check digits. Move the first four characters to the end, replace each letter with two digits (A = 10 up to Z = 35), and the number modulo 97 must equal 1. An IBAN that fails is flagged and left out, so a payment run never receives an account number that cannot exist.

How often do the checks fire? On the 47-document test battery behind this API (public PDFs, receipt photos from more than a dozen countries, XML files, a generated 240-line invoice), 32 of the 37 documents read by the model passed every check. Two had nothing to check (a blurred café photo, a handwritten receipt with no legible total). Three were flagged: a partly photographed Chinese receipt, a handwritten Ukrainian bill and a Paris canteen ticket, exactly the documents a person should see.

Receipt OCR from a phone photo

Receipts arrive as files. The upload endpoint takes JPEG, PNG, WEBP, HEIC, GIF, BMP or TIFF images as well as PDFs and XML, up to 20 MB; the type is detected from the content, not the declared MIME type.

Python
with open("receipt.jpg", "rb") as f:
    response = requests.post(
        f"{API}/v1/invoices/parse/upload",
        headers=HEADERS,
        files={"file": ("receipt.jpg", f, "image/jpeg")},
        timeout=120,
    )
response.raise_for_status()
receipt = response.json()
print(
    receipt["supplier"]["name"],
    receipt["totals"]["total"],
    receipt.get("expense_category"),
)

A real Polish supermarket receipt, discount line included:

JSON
{
  "document_type": "receipt",
  "issue_date": "2020-01-09",
  "issue_time": "13:18",
  "currency": "PLN",
  "supplier": { "name": "Biedronka", "vat_id": "PL7791011327", "address": "ul. Żniwna 5, 62-025 Kostrzyn", "country": "PL" },
  "lines": [
    { "description": "ChlebPszen-Żyt550g", "quantity": 1.0, "unit_price": 1.99, "total": 1.99 },
    { "description": "Ser ż.Świat. 150g", "quantity": 1.0, "unit_price": 3.29, "total": 3.29 },
    { "description": "Polędw łos 100g", "quantity": 1.0, "unit_price": 4.99, "total": 4.99 },
    { "description": "Rabat", "total": -2.0 }
  ],
  "amounts_include_tax": true,
  "totals": { "taxes": [{ "rate": 5.0, "base": 7.88, "amount": 0.39, "label": "PTU C" }], "tax_total": 0.39, "total": 8.27, "amount_paid": 8.27 },
  "payment": { "method": "card" },
  "expense_category": "groceries"
}

The Polish tax label PTU C is kept next to the normalised 5 % rate, the Rabat discount comes through as a negative line, and the lines add up: 1.99 + 3.29 + 4.99 − 2.00 = 8.27. expense_category gives an expense app its category without a second model call.

Factur-X, ZUGFeRD, XRechnung and UBL e-invoices read exactly

The best invoice is one you do not have to read. EN 16931, the European standard for electronic invoices, defines one semantic model with two XML syntaxes: UN/CEFACT Cross Industry Invoice (CII) and OASIS UBL 2.1. Factur-X (France) and ZUGFeRD (Germany) are the same hybrid format: a PDF/A-3 that a person can read, with a CII XML file embedded in it. XRechnung, Germany's national profile of EN 16931, can use either syntax; Peppol BIS Billing 3.0 is based on UBL. With Germany and France making B2B e-invoicing mandatory, these files are increasingly common in supplier inboxes.

You do not need to detect them. When the API finds an embedded XML, it reads the XML instead of the page: exact to the cent, no AI, 1 credit whatever the page count. A bare CII or UBL XML file works too.

JSON
{
  "method": "e-invoice",
  "e_invoice": { "format": "UBL", "file": "UBL-Invoice-2.1.xml" },
  "number": "INV/2023/03/0008",
  "totals": { "subtotal": 262.9, "tax_total": 16.94, "total": 279.84, "amount_paid": 0.0, "amount_due": 279.84 }
}

method says what happened: "ai" (pages read) or "e-invoice" (XML used). The two lightest Factur-X profiles, MINIMUM and BASIC WL, carry no line items; for those the model reads the lines from the pages, the XML values win everywhere else, and method is "e-invoice+ai".

Batch-process a folder of invoices with retries and cost control

A real pipeline reads a folder, survives transient failures and does not pay for pages nobody needs. Credits are counted per page read by the model, so pages is the main cost lever: many supplier PDFs end with two pages of terms and conditions. Failed calls (a 400 not_an_invoice, a 503) cost nothing, so retrying a 503 is safe.

Python
import csv
import pathlib
import time
from concurrent.futures import ThreadPoolExecutor

import requests

HOST = "invoice-receipt-parser-pdf-image-to-json.p.rapidapi.com"
API = f"https://{HOST}"
HEADERS = {"x-rapidapi-key": "YOUR_API_KEY", "x-rapidapi-host": HOST}
SUFFIXES = {".pdf", ".jpg", ".jpeg", ".png", ".webp", ".heic", ".xml"}


class DailyLimitReached(Exception):
    pass


def parse(path: pathlib.Path, attempts: int = 3) -> dict:
    for attempt in range(attempts):
        try:
            with path.open("rb") as f:
                r = requests.post(
                    f"{API}/v1/invoices/parse/upload",
                    headers=HEADERS,
                    files={"file": (path.name, f)},
                    data={"pages": "1-3"},  # ignored for photos and e-invoices
                    timeout=180,
                )
        except (requests.Timeout, requests.ConnectionError):
            r = None
        if r is not None and r.status_code == 429:
            raise DailyLimitReached(r.text)  # resets at 00:00 UTC: stop, do not retry
        if r is not None and r.status_code < 500:
            return r.json()  # a parsed document, or {"error": {...}} for a 4xx
        time.sleep(5 * 2**attempt)  # 503 or timeout: not billed, try again
    return {"error": {"code": "gave_up"}}


def row(path: pathlib.Path, doc: dict) -> list:
    if "error" in doc:
        return [path.name, "", "", "", "", "", "", doc["error"]["code"]]
    supplier, totals = doc.get("supplier", {}), doc.get("totals", {})
    status = "ok" if doc["validation"]["consistent"] is True else "REVIEW"
    return [
        path.name,
        supplier.get("name"),
        supplier.get("vat_id"),
        doc.get("number"),
        doc.get("issue_date"),
        doc.get("currency"),
        totals.get("total"),
        status,
    ]


files = sorted(
    p for p in pathlib.Path("inbox").iterdir() if p.suffix.lower() in SUFFIXES
)
with (
    ThreadPoolExecutor(max_workers=4) as pool,
    open("invoices.csv", "w", newline="", encoding="utf-8") as out,
):
    writer = csv.writer(out)
    writer.writerow(
        ["file", "supplier", "vat_id", "number", "date", "currency", "total", "status"]
    )
    for path, doc in zip(files, pool.map(parse, files)):
        writer.writerow(row(path, doc))

A few habits on top of that script:

  • Timeouts. One page takes 2 to 8 seconds, a dense 6-page invoice 14.
  • Long documents. Up to 30 pages per call, read in parallel batches of 3. A 240-line, 6-page test invoice came back with all 240 lines exact and totals to the cent.
  • Duplicates. Invoices often arrive twice. Deduplicate on supplier vat_id plus number.
  • Supplier checks. Consistent figures do not prove the supplier exists. For French suppliers, the French Company Data API checks a SIREN, SIRET or VAT number against the official registers.
  • Keep the evidence. Store the validation block with the posted entry, for auditors.

On cost: BASIC is free for 2 pages a day; PRO is $4.99 a month for 480 pages (about $0.01 a page), ULTRA $14.99 for 1,440, MEGA $49.99 for 4,800. Popular invoice APIs on RapidAPI charge $0.015 to $0.12 per document, and Veryfi starts at $0.08 with a $500 monthly minimum. Plans are on the invoice parser page, parameters in the API reference. The same approach of a model reading and code checking drives the resume parser and the HS code classifier.

Run it without code on Apify

If the pipeline starts in a spreadsheet rather than a codebase, the same parser runs as an Apify Actor, Invoice & Receipt Parser. Paste PDF or image links and get one row per document, with supplier, totals, taxes and the checks, ready to export to CSV or Excel or to push to Google Sheets, for $0.01 per page read.

What the invoice OCR API does not do

  • No bounding boxes. You get fields, not coordinates on the page, so a review screen cannot highlight values on the original image.
  • No bank statements. Invoices, receipts, bills and credit notes only; anything else returns 400 not_an_invoice, not billed.
  • Bad photos stay bad photos. Crumpled, faded or handwritten receipts are read as well as possible; the checks tell you when the result does not add up.
  • No automatic second reading. A mismatch is reported, not retried with another model. Hierarchical invoices with section subtotals are the likeliest to trigger one.
  • 20 MB and 30 pages per call. Split longer documents with pages.

Frequently asked questions

How do I extract data from a PDF invoice with Python?

Post the PDF (by URL or as a multipart upload) to an invoice parsing API with requests and read the JSON. Template libraries such as invoice2data work when you can write one template per supplier; an AI-based API fits unknown layouts, provided it tells you when the figures do not add up.

How accurate is invoice OCR?

Character recognition is rarely the weak point now; field mapping and misread figures are. What matters is whether errors are detected: here every line, tax and total is re-added by code, and consistent turns false as soon as a figure is off. E-invoices read from their XML are exact.

How do I read a Factur-X or ZUGFeRD invoice?

It is a PDF/A-3 with a CII XML invoice attached. Extract the attachment with a PDF library and map the CII elements yourself, or send the PDF here: the XML is found, read without AI, and returned as the same JSON with method: "e-invoice".

Are invoices stored, and is it GDPR-friendly?

Helenis does not store the files or the results; the AI provider keeps requests temporarily for abuse monitoring only. The output never contains a private person's contact details, and masked card and bank numbers are dropped.

Get started

Invoice & Receipt Parser API

Invoice & receipt parser: PDF, scan or photo to JSON with VAT IDs, lines, taxes and math checks.

  • Invoice Processing
  • OCR
  • E-Invoicing
  • Python
  • Accounting