How to extract invoice data in Python

Updated · Tested with Python 3.13, pypdf 7.2.0

In short

Extract the invoice's text with pypdf, find each header value with a regular expression anchored on its label, and read each line of the table from the right: quantity, unit price, amount. Then check the invoice against itself: the lines must add up to the subtotal, and subtotal plus tax to the total. That check catches most misreadings.

An invoice has two kinds of data: single values, such as the invoice number and the total, and a table of lines. This guide pulls both out of invoice.pdf with pypdf and regular expressions, and then checks the result against itself, which is the step most scripts skip.

Start from the text

Python
from pypdf import PdfReader

text = PdfReader("invoice.pdf").pages[0].extract_text()
print(text)
Output
INVOICE
Northgate Paper Supplies Ltd
8 Mill Road, Leeds LS1 4AB
VAT number GB 284 7719 52
Invoice number: INV-2026-0418
Invoice date: 12 November 2026
Due date: 12 December 2026
Purchase order: PO-77120
Bill to
Harbor Lane Logistics Ltd
22 Quay Street, Haifa
Items
Description Quantity Unit price Amount
A4 copy paper, 80 gsm, box of 5 reams 40 18.50 740.00
Shipping labels, roll of 500 25 12.00 300.00
Packing tape, 48 mm, pack of 6 30 7.20 216.00
Delivery 1 44.00 44.00
Subtotal 1,300.00
VAT 18% 234.00
Total due 1,534.00

Always print the text before you write a single pattern. Everything below depends on what this looks like for your invoices, and it differs from one library to the next.

The header fields

Each value follows a label, so one pattern per field is enough.

Python
import json
import re
from pypdf import PdfReader

text = PdfReader("invoice.pdf").pages[0].extract_text()

def find(pattern):
    match = re.search(pattern, text)
    return match.group(1) if match else None

def money(value):
    return float(value.replace(",", "")) if value else None

invoice = {
    "invoice_number": find(r"Invoice number: (\S+)"),
    "invoice_date": find(r"Invoice date: (.+)"),
    "due_date": find(r"Due date: (.+)"),
    "purchase_order": find(r"Purchase order: (\S+)"),
    "subtotal": money(find(r"Subtotal ([\d,.]+)")),
    "vat": money(find(r"VAT \d+% ([\d,.]+)")),
    "total_due": money(find(r"Total due ([\d,.]+)")),
}
print(json.dumps(invoice, indent=2))
JSON
{
  "invoice_number": "INV-2026-0418",
  "invoice_date": "12 November 2026",
  "due_date": "12 December 2026",
  "purchase_order": "PO-77120",
  "subtotal": 1300.0,
  "vat": 234.0,
  "total_due": 1534.0
}

Two helpers do the unglamorous work. find returns None instead of crashing when a label is missing. money removes the thousands separator, because float("1,300.00") is an error.

Dates need the same care. Turn them into a standard form as soon as you have them:

Python
from datetime import datetime

print(datetime.strptime("12 November 2026", "%d %B %Y").date().isoformat())
Output
2026-11-12

The lines

Each line of the table ends with three numbers: a quantity, a unit price and an amount. Everything before them is the description.

Python
lines = []
for match in re.finditer(r"^(.+?) (\d+) ([\d,]+\.\d{2}) ([\d,]+\.\d{2})$", text, re.M):
    lines.append({
        "description": match.group(1),
        "quantity": int(match.group(2)),
        "unit_price": money(match.group(3)),
        "amount": money(match.group(4)),
    })
for line in lines:
    print(line)
Output
{'description': 'A4 copy paper, 80 gsm, box of 5 reams', 'quantity': 40, 'unit_price': 18.5, 'amount': 740.0}
{'description': 'Shipping labels, roll of 500', 'quantity': 25, 'unit_price': 12.0, 'amount': 300.0}
{'description': 'Packing tape, 48 mm, pack of 6', 'quantity': 30, 'unit_price': 7.2, 'amount': 216.0}
{'description': 'Delivery', 'quantity': 1, 'unit_price': 44.0, 'amount': 44.0}

The pattern reads from the right, which is why descriptions full of numbers ("box of 5 reams", "48 mm") do not confuse it. Anchoring on the two prices with their decimals is what makes it safe.

Check the invoice against itself

An invoice carries its own proof: the lines add up to the subtotal, and the subtotal plus tax is the total. Use it.

Python
lines_ok = round(sum(line["amount"] for line in lines), 2) == invoice["subtotal"]
total_ok = round(invoice["subtotal"] + invoice["vat"], 2) == invoice["total_due"]
print(lines_ok, total_ok)
Output
True True

If either is false, something was misread: a line was missed, a digit dropped, a column shifted. Send that invoice to a person. This one check catches most extraction errors before they reach your accounts.

Where this breaks

  • A second supplier. Their label is "Invoice No." or "Reference", their dates are 11/12/2026, their columns are in another order. Every supplier needs its own patterns.
  • Wrapped descriptions. A long description that runs onto a second line splits the row in two, and the pattern misses it.
  • Scanned invoices. There is no text; extract_text() returns an empty string. Run OCR first, as in how to OCR a scanned PDF in Python, and expect misread digits, which the check above will catch.
  • Another library. PyMuPDF and pdfminer.six put each table cell on its own line for this file, and these patterns stop matching. Keep the library fixed once your patterns work.

For the table, a table extractor can be sturdier than a pattern; see how to extract tables from a PDF.

The same fields as a service

Writing and maintaining patterns for each supplier is the real cost. 100sands replaces that part: you upload one to five invoices from a supplier, AI suggests the fields and each sample's values, you check them, and AI sets up an extraction that goes live only when it returns every value you checked on every sample. Each later invoice from that supplier comes back as JSON from one call, the same way every time, with numbers as numbers and dates as YYYY-MM-DD when their format is known.

A table field returns the line items as rows with columns, so the header and the lines can come from the same call. Keep the arithmetic check either way: it tells you whether the invoice itself adds up, which reading the values cannot. 100sands reads invoices that are PDFs or HTML files with text in them, not scans. The PDF data extraction API page shows the call and its response.

Questions

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

Read the text with pypdf, then use one regular expression per field, such as r"Invoice number: (\S+)". Convert amounts to numbers by removing thousands separators, and dates to ISO form with datetime.strptime.

How do I extract line items from an invoice?

Match each line from its right-hand end, where the numbers are: a quantity, a unit price and an amount with two decimals. Whatever comes before them is the description.

How can I tell if invoice extraction went wrong?

Add up the line amounts and compare the sum with the subtotal, then check that subtotal plus tax equals the total. If either fails, a value was misread, and the invoice should go to a person.

Does this work for scanned invoices?

Not directly. A scan has no text to match. Run OCR first, and keep the arithmetic check, because OCR misreads digits.

Try it on your own documents

A free plan every month, no credit card. See the PDF data extraction API.

Start free