Extract Invoice Data With Python
Jun 16, 2026
Try it now: upload an invoice and get the data in Excel or CSV
PDF, JPG, PNG, BMP, HEIC, TIFF
Upload your invoices
Drop files here or click to upload
Up to 50 files
Uploading...
To extract invoice data with Python, use pdfplumber to read text and tables from digital PDF invoices, pytesseract to OCR scanned images, and regular expressions to pull fields like vendor, invoice number, date, and total into structured data. That stack handles most invoices from a stable vendor list. For mixed or unpredictable layouts, an AI extraction API returns the fields directly so you do not maintain a parsing template per supplier. Last updated July 2026.
If you process invoices at any real volume, Python is the obvious tool to automate the data entry. The language has mature libraries for reading PDFs, running OCR on scans, and reshaping the result into a spreadsheet or a database row. The hard part is not pulling text off the page; it is turning that messy text into clean, reliable fields (vendor, invoice number, date, line items, tax, total) across suppliers who all format their invoices differently.
This guide walks through the practical options, from a quick script you can write in an afternoon to a production pipeline, and where each one breaks down. The short version: pdfplumber reads digital PDFs and tables, pytesseract handles scanned images, and regex pulls out fields that appear in a consistent spot. That stack covers maybe 70 to 80% of invoices from a stable vendor list. For everything beyond that, an AI extraction service does the parsing for you so you do not maintain a template per vendor. Here are the questions developers ask most before they pick an approach.
Can Python extract data from a PDF invoice?
Yes, Python can extract data from a PDF invoice. For digital PDFs that contain a real text layer, libraries like pdfplumber, PyMuPDF, and pdfminer read the text directly. For scanned or photographed invoices, you add an OCR step with pytesseract first. You then use regex or table parsing to isolate the specific fields you need.
The catch is consistency. Reading the raw text is easy; the work is mapping that text to a schema when every vendor puts the invoice number, totals, and line-item table in a different place. A script tuned to one supplier rarely survives contact with the next one, which is why most teams either build a template per vendor or hand the parsing to an AI model that reads layout the way a person does.
How do you read a PDF invoice in Python?
To read a digital PDF invoice in Python, install pdfplumber (pip install pdfplumber), open the file, and call extract_text() on each page. PyMuPDF (imported as fitz) and pdfminer.six do the same job with different speed and layout trade-offs. All three only work when the PDF has a real text layer; a scanned image returns nothing.
import pdfplumber
with pdfplumber.open("invoice.pdf") as pdf:
text = "\n".join(page.extract_text() or "" for page in pdf.pages)
print(text)
pdfplumber is the usual first choice because it gives you pixel-level control over text and table detection plus visual debugging, which matters when column boundaries are ambiguous. PyMuPDF is faster on large batches. If extract_text() returns an empty string or garbled characters, the PDF is almost certainly a scan, and you need OCR before any parsing will work.
How do you extract invoice line items with Python?
To extract invoice line items in Python, use pdfplumber's extract_table() method, which returns the table as a list of rows and columns you can load straight into pandas. For invoices where the table has no ruled borders, Camelot and Tabula offer alternative detection strategies. Line-item tables are the single hardest part of invoice extraction to get right.
with pdfplumber.open("invoice.pdf") as pdf:
table = pdf.pages[0].extract_table()
import pandas as pd
df = pd.DataFrame(table[1:], columns=table[0])
The trouble is that table detection assumes a predictable grid. Multi-line descriptions, wrapped cells, merged headers, and totals rows that look like line items all throw it off, and the boundaries shift from vendor to vendor. If your suppliers use wildly different layouts, expect to spend most of your time on the table, not the header fields. This is the exact problem a model-based approach solves, which is why we built dedicated invoice line item extraction that keeps each row tied to its quantity, unit price, and amount.
How do you extract data from a scanned invoice in Python?
To extract data from a scanned invoice in Python, run the image through OCR first. Convert PDF pages to images with pdf2image, then pass them to pytesseract (a wrapper around the Tesseract engine) to get text. Once you have text, you parse it the same way you would a digital PDF. Without the OCR step, a scan returns no usable data at all.
from pdf2image import convert_from_path
import pytesseract
pages = convert_from_path("scanned_invoice.pdf", dpi=300)
text = "\n".join(pytesseract.image_to_string(p) for p in pages)
Scan quality decides everything here. Tesseract does well on clean 300 DPI scans and struggles with faded thermal print, skewed photos, and low resolution, so deskewing and thresholding the image first noticeably improves results. Open-source OCR also trails cloud OCR on accuracy for messy documents. We cover the trade-offs in detail in our guide to extracting data from a scanned invoice and the broader category of invoice OCR software.
How do you use regex to parse invoice fields in Python?
To parse invoice fields with regex in Python, use the built-in re module with named groups that target each field's pattern: a label like "Invoice No" followed by an alphanumeric code, a date format, or a currency amount near the word "Total." Named groups keep the code readable and let you pull several fields in one pass.
import re
inv = re.search(r"Invoice\s*(?:No|#)[:\s]*(?P<number>[A-Z0-9-]+)", text)
total = re.search(r"Total[:\s]*\$?(?P<amount>[\d,]+\.\d{2})", text)
Regex is fast, predictable, and auditable, which makes it great for fields that always appear in the same shape. It is also brittle: the moment a vendor writes "Amount Due" instead of "Total," or uses a different date format or currency symbol, your pattern misses. Teams that go the regex route end up maintaining a growing library of patterns per supplier, which is sustainable only with a small, stable vendor base.
What is the best Python library for invoice data extraction?
For an open-source, ready-made option, invoice2data is the most popular Python library built specifically for invoices. It extracts text using pdftotext, pdfminer, pdfplumber, or Tesseract OCR, then matches a YAML template of regex rules and exports to CSV, JSON, or XML. You write one template per vendor layout. There is no single best library; the right choice depends on your invoice variety.
Here is how the common options compare for invoice work specifically.
| Library | Best for | Reads scanned images | Needs a template per vendor |
|---|---|---|---|
| pdfplumber | Pulling text and tables out of native (text-layer) PDFs | No | Yes, you write the parsing logic |
| pypdf | Basic text extraction, splitting and merging pages | No | Yes |
| camelot | Well-ruled tables in native PDFs | No | Yes |
| pytesseract (with pdf2image) | OCR on scans and photos, returns raw text only | Yes | Yes, plus your own field parsing |
| invoice2data | Recurring invoices from a small, stable set of suppliers | Yes, via Tesseract | Yes, one YAML template each |
| Extraction API | Wide or unpredictable vendor mixes, full line items | Yes | No |
The honest trade-off: invoice2data and a custom pdfplumber-plus-regex stack both depend on templates, so they shine when you have a handful of recurring suppliers and degrade fast when new layouts arrive weekly. If your invoice mix is wide or unpredictable, a model-based service that reads any layout without a template will save far more engineering time than tuning regex by hand. That is the difference between template parsing and true invoice data extraction software.
How do you export extracted invoice data to Excel or CSV with Python?
To export extracted invoice data to Excel or CSV in Python, load your parsed fields into a pandas DataFrame and call to_excel("invoices.xlsx") or to_csv("invoices.csv"). Use one row per invoice for header fields, or one row per line item when you need the full table, and add a source-file column so every value traces back to its original document. When a whole folder needs the same treatment in one go, the no-code equivalent is batch invoice processing.
import pandas as pd
rows = [{"vendor": v, "invoice_no": n, "date": d, "total": t}]
pd.DataFrame(rows).to_excel("invoices.xlsx", index=False)
pandas handles the messy parts: mixed types, missing values, and combining many invoices into one workbook. Keep amounts as numbers rather than strings so totals and pivots work later, and normalize dates to a single format on the way in. If your end goal is a spreadsheet rather than a database, you may not need to write any code at all, which leads to the last question.
Should you build invoice extraction in Python or use an API?
Build it in Python when you have a small, stable set of vendors, predictable layouts, and engineering time to maintain templates. Use an extraction API when invoice variety is high, accuracy matters, or you do not want to own OCR, table parsing, and per-vendor rules. The break-even point comes fast: most teams spend more maintaining regex templates than the API would cost.
A hosted service handles the OCR, layout reading, field detection, line-item tables, and total validation behind one call, then returns clean JSON, Excel, or CSV. You skip the Tesseract tuning and the brittle patterns entirely. If your pipeline consumes structured objects rather than spreadsheets, the invoice to JSON output maps straight onto the dictionaries you would have built by hand. Our invoice data extraction API does exactly this: POST a PDF or image, poll for the result, and download structured data, with no template setup per vendor. If you only need a spreadsheet now and code later, you can also start with the no-code way to extract data from invoices, or convert source files first with a PDF to Excel converter for the adjacent document types your pipeline touches.
Whichever route you pick, the workflow is the same underneath: read the document, recognize the fields, validate the totals, and export. Python gives you full control and zero per-document cost at the price of maintenance; an API trades a per-document fee for someone else owning the accuracy. Match the choice to your invoice volume and how stable your vendor list is, and you will not over-engineer a problem that a single API call can solve.