Tutorial · Invoice Parsing

How to Extract Data from a PDF Invoice (Without Building an OCR Pipeline)

By Othmane M., founder of DocuParse API

2026-05-22 · 6 min readLast updated: 2026-11-17

You have a PDF invoice. You need the data inside it — vendor name, invoice number, total, line items — in a format your code can use. Here's a direct path from PDF to structured data.

1
endpoint
AI
checked results
0
regex needed
Free
to start
The Problem

The Two Approaches (and Why One Is Better)

Approach 1 — Build it yourself: Use pdfplumber, PyMuPDF, or Camelot to extract raw text, then write regex patterns to find the invoice number, dates, and totals. Handle the edge cases when the text extraction fails on scanned PDFs. Write different patterns for different vendor formats. Maintain all of it when vendors update their invoice templates.

This takes 1–3 weeks for a working version, and it never fully works — there's always another vendor format that breaks it.

Approach 2 — Use an API: Send the PDF to an endpoint. Receive structured JSON. Done.

This guide covers Approach 2.

Build it yourself — weeks of work
import pdfplumber
import re

# regex for every vendor format
# breaks when template changes
# no scanned PDF support
# 300+ lines of brittle code
→API call
Use an API — one afternoon
# POST /api/v1/extract, then
# GET /api/v1/documents/{id}
data = parse_document("invoice.pdf")
# merchant, total, tax, date
# line_items — all ready

The build-vs-buy decision for invoice parsing.

Quick Start

The Request

bash · 9 lines
# 1. Submit the document
curl -X POST https://docuparseapi.com/api/v1/extract \
  -H "Authorization: Bearer $DOCUPARSE_API_KEY" \
  -F "file=@invoice.pdf"
# → {"success": true, "document_id": "<id>", "status": "queued"}

# 2. Fetch the result (repeat until "status" is "completed" or "failed")
curl https://docuparseapi.com/api/v1/documents/<id> \
  -H "Authorization: Bearer $DOCUPARSE_API_KEY"

That's the complete integration. Once the status is completed, the document's data object looks like this (a real 7-line-item invoice):

response — invoice extracted✓ success · AI-checked result
merchant"Riverside Consulting LLC"
invoice_id"INV-2026-0091"
date"2026-05-01"
due_date"2026-05-31"
total"3850.00"
tax"350.00"
currency"USD"
line_items[{ description, quantity, price, line_total, vat_rate }]
✓ Every field named and typed. No parsing, no regex, no bounding boxes.
json · 72 lines
{
  "document_type": "invoice",
  "document_number": "31293737",
  "invoice_id": "31293737",
  "receipt_id": null,
  "date": "2020-12-15",
  "due_date": null,
  "currency": "USD",
  "merchant": "Nunez Inc",
  "merchant_address": "6551 Janet Gardens, Michaelberg, KS 90952",
  "merchant_email": null,
  "customer": "Alvarez Inc",
  "subtotal": "371.51",
  "tax": "37.15",
  "tax_rate": "10.00",
  "discount": null,
  "shipping": null,
  "total": "408.66",
  "payment_method": null,
  "notes": null,
  "line_items": [
    {
      "description": "Women's black cocktail dress, size 4",
      "quantity": 3,
      "price": "19.99",
      "line_total": "59.97",
      "vat_rate": "10.00"
    },
    {
      "description": "Christmas Dress Grace Karin Sleeveless Christmas dress Red Black size Large",
      "quantity": 1,
      "price": "9.99",
      "line_total": "9.99",
      "vat_rate": "10.00"
    },
    {
      "description": "Windsor womens black and Pink Bodycon Sleeveless Dress, Womens Size Small",
      "quantity": 1,
      "price": "15.83",
      "line_total": "15.83",
      "vat_rate": "10.00"
    },
    {
      "description": "Lumiere Large Multicolored Orange Short Dress NWT",
      "quantity": 4,
      "price": "4.99",
      "line_total": "19.96",
      "vat_rate": "10.00"
    },
    {
      "description": "Xhilaration Womens L Burgandy Boho Embroidered Festival Mini Dress NEW",
      "quantity": 4,
      "price": "14.95",
      "line_total": "59.80",
      "vat_rate": "10.00"
    },
    {
      "description": "Johnny Was Medium Linen Wrap Dress Dessert Rose Embroiderd Bohemian",
      "quantity": 2,
      "price": "89.99",
      "line_total": "179.98",
      "vat_rate": "10.00"
    },
    {
      "description": "Pre-Owned Women's Nah Nah Dress Size 8 Black Sheer Formal Sexy",
      "quantity": 2,
      "price": "12.99",
      "line_total": "25.98",
      "vat_rate": "10.00"
    }
  ]
}
Python

Python Implementation

Get your API key when you sign up at docuparseapi.com — free, no credit card.

python · 44 lines
import os, time, requests

API = "https://docuparseapi.com/api/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['DOCUPARSE_API_KEY']}"}

def parse_document(path: str) -> dict:
    # 1. Submit
    with open(path, "rb") as f:
        submit = requests.post(f"{API}/extract", headers=HEADERS,
                               files={"file": (os.path.basename(path), f)}, timeout=30).json()
    if not submit.get("success"):
        raise RuntimeError(f"[{submit['error']['code']}] {submit['error']['message']}")

    # 2. Fetch the result
    for _ in range(40):
        doc = requests.get(f"{API}/documents/{submit['document_id']}",
                           headers=HEADERS, timeout=30).json()
        if doc["status"] == "completed":
            return doc["data"]
        if doc["status"] == "failed":
            raise RuntimeError(f"Extraction failed: {submit['document_id']}")
        time.sleep(1.5)
    raise TimeoutError(submit["document_id"])


# Extract an invoice
invoice = parse_document("invoice.pdf")

# Use the data
print(f"From:     {invoice['merchant']}")
print(f"Invoice:  {invoice['invoice_id']}")
print(f"Date:     {invoice['date']}")
print(f"Due:      {invoice['due_date']}")
print(f"Subtotal: {invoice['currency']} {invoice['subtotal']}")
print(f"Tax:      {invoice['currency']} {invoice['tax']}")
print(f"Total:    {invoice['currency']} {invoice['total']}")
print()
print("Line items:")
for item in invoice.get("line_items", []):
    qty = item.get("quantity") or 1
    desc = item.get("description", "")
    price = item.get("price")
    total = item.get("line_total")
    print(f"  {qty}× {desc} @ {price} = {total}")

Output:

text · 16 lines
From:     Nunez Inc
Invoice:  31293737
Date:     2020-12-15
Due:      None
Subtotal: USD 371.51
Tax:      USD 37.15
Total:    USD 408.66

Line items:
  3× Women's black cocktail dress, size 4 @ 19.99 = 59.97
  1× Christmas Dress Grace Karin Sleeveless Christmas dress Red Black size Large @ 9.99 = 9.99
  1× Windsor womens black and Pink Bodycon Sleeveless Dress, Womens Size Small @ 15.83 = 15.83
  4× Lumiere Large Multicolored Orange Short Dress NWT @ 4.99 = 19.96
  4× Xhilaration Womens L Burgandy Boho Embroidered Festival Mini Dress NEW @ 14.95 = 59.80
  2× Johnny Was Medium Linen Wrap Dress Dessert Rose Embroiderd Bohemian @ 89.99 = 179.98
  2× Pre-Owned Women's Nah Nah Dress Size 8 Black Sheer Formal Sexy @ 12.99 = 25.98
This code is ready to run.
Get your free API key — 20 documents/month — free forever, no credit card, no expiry.
Next Steps

Working With the Extracted Data

Map to a database model

python · 30 lines
import sqlite3
import json

def store_invoice(conn: sqlite3.Connection, data: dict):
    conn.execute("""
        CREATE TABLE IF NOT EXISTS invoices (
            vendor TEXT,
            invoice_number TEXT PRIMARY KEY,
            invoice_date TEXT,
            due_date TEXT,
            currency TEXT,
            total REAL,
            tax REAL,
            line_items TEXT
        )
    """)
    
    conn.execute("""
        INSERT OR IGNORE INTO invoices VALUES (?,?,?,?,?,?,?,?)
    """, (
        data.get("merchant"),
        data.get("invoice_id"),
        data.get("date"),
        data.get("due_date"),
        data.get("currency"),
        float(data.get("total") or 0),
        float(data.get("tax") or 0),
        json.dumps(data.get("line_items", []))
    ))
    conn.commit()

Push to QuickBooks or Xero

The extracted fields map directly to the bill/invoice fields in accounting APIs:

python · 18 lines
# QuickBooks bill creation (using quickbooks-online SDK)
def create_quickbooks_bill(invoice_data: dict, vendor_id: str):
    from quickbooks.objects.bill import Bill
    from quickbooks.objects.billline import BillLine
    
    bill = Bill()
    bill.VendorRef = {"value": vendor_id}
    bill.TxnDate = invoice_data["date"]
    bill.DueDate = invoice_data.get("due_date")
    bill.TotalAmt = float(invoice_data["total"])
    
    for item in invoice_data.get("line_items", []):
        line = BillLine()
        line.Amount = float(item.get("line_total") or 0)
        line.Description = item.get("description")
        bill.Line.append(line)
    
    return bill.save(qb=client)

Send to a webhook or downstream service

python · 17 lines
import httpx

async def forward_invoice(invoice_data: dict, webhook_url: str):
    """Forward extracted invoice data to a webhook endpoint."""
    async with httpx.AsyncClient() as client:
        response = await client.post(webhook_url, json={
            "event": "invoice.extracted",
            "invoice": {
                "vendor": invoice_data.get("merchant"),
                "number": invoice_data.get("invoice_id"),
                "date": invoice_data.get("date"),
                "amount": invoice_data.get("total"),
                "currency": invoice_data.get("currency"),
                "items": invoice_data.get("line_items", []),
            }
        })
    return response.status_code == 200

Handling Scanned PDFs

If the invoice was created by scanning a paper document, the PDF contains an image, not machine-readable text. Regular PDF parsers return nothing from these files. DocuParse API detects scanned PDFs automatically and applies OCR — your request is identical:

python · 2 lines
# Works for both digital PDFs and scanned PDFs
invoice = parse_document("scanned_supplier_invoice.pdf")

Common Issues and Fixes

Issue: EXTRACTION_FAILED error The document may be too degraded to extract cleanly (heavy compression, very low scan resolution, or a non-invoice document). Try with a higher quality scan, or submit a digital PDF if available.

Issue: Missing fields return null Some invoices don't have due dates; some don't have line items. Check for None before using a field:

python · 3 lines
due_date = invoice.get("due_date")  # May be None
if due_date:
    # use it

Issue: Total is a string, not a number The API returns monetary values as strings to preserve decimal precision. Convert before arithmetic:

python · 1 line
total = float(invoice["total"])

Issue: Line items list is empty Not all invoices have extractable line items — some use image-embedded tables or unusual formats. The total field is always extracted when possible, even if line items are missing.

Pricing

  • Free tier: 20 PDF invoices/month, no credit card required
  • Starter and Pro: monthly plans for higher volumes — see the Starter plan and the Pro plan on current pricing
  • Billed per document, with up to 10 pages in each; 11–20 pages count as two

View full pricing

Next Steps

Where to send the extracted data

Your Python environment is ready. Your API key isn't.

20 documents/month — free forever. No credit card. No expiry.

More from the blog

All posts →