Read PDF Invoices in Python Using PDF.co’s AI Invoice Parser

Extract invoice details, vendor information, payment amounts, and line items into JSON using Python. No parsing template is required. See the AI Invoice Parser documentation.

Step 1: Prepare Your Environment

You’ll need Python 3, a PDF.co account, and a PDF invoice.

Install the required package:

python -m pip install requests

Get your API key from the PDF.co dashboard. Prepare a direct download URL for your invoice, or upload it to PDF.co’s file storage and use its file link.

Use one invoice per source PDF; a single invoice may contain multiple pages.

Step 2: Create the Python Script

Save this complete sample as read_invoice.py:

import json
import time
from pathlib import Path

import requests

API_KEY = "YOUR_PDFCO_API_KEY"
SOURCE_URL = "YOUR_INVOICE_PDF_URL"
BASE_URL = "https://api.pdf.co/v1"
OUTPUT_FILE = Path.cwd() / "invoice.json"


def api_post(endpoint, payload):
    response = requests.post(
        BASE_URL + endpoint,
        headers={"x-api-key": API_KEY},
        json=payload,
        timeout=60,
    )
    response.raise_for_status()
    data = response.json()
    if data.get("error"):
        raise RuntimeError(data.get("message", "PDF.co request failed"))
    return data


def main():
    job = api_post("/ai-invoice-parser", {"url": SOURCE_URL})
    deadline = time.monotonic() + 600

    while time.monotonic() < deadline:
        result = api_post("/job/check", {"jobid": job["jobId"]})
        status = result.get("status")

        if status == "success":
            if isinstance(result.get("body"), dict):
                invoice_data = result["body"]
            else:
                output_url = result.get("url") or job.get("url")
                if not output_url:
                    raise RuntimeError("Completed job has no result URL")

                response = requests.get(output_url, timeout=60)
                response.raise_for_status()
                document = response.json()

                if document.get("error") or document.get("status") == "error":
                    raise RuntimeError(
                        document.get("message", "Parsing failed")
                    )

                invoice_data = document.get("body", document)

            OUTPUT_FILE.write_text(
                json.dumps(invoice_data, indent=2, ensure_ascii=False),
                encoding="utf-8",
            )
            print(f"Saved invoice data to {OUTPUT_FILE}")
            return

        if status != "working":
            raise RuntimeError(
                result.get("message") or f"Job status: {status}"
            )

        time.sleep(3)

    raise TimeoutError("Invoice parsing did not finish within 10 minutes")


if __name__ == "__main__":
    main()

Replace YOUR_PDFCO_API_KEY with your API key and YOUR_INVOICE_PDF_URL with your invoice’s accessible file link. Keep your API key private.

Step 3: Run the Program

Open a terminal in the folder containing the script and run:

python read_invoice.py

The script submits the invoice, receives a job ID, and checks the job every three seconds. Once processing succeeds, it retrieves the extracted data and saves invoice.json in your working directory.

The Job Check documentation explains the processing statuses.

Step 4: Review the Extracted Data

Open invoice.json. Depending on the information present in your invoice, the result includes sections such as:

  • vendor and customer: Supplier and recipient details.
  • invoice: Invoice number, date, and order references.
  • paymentDetails: Totals, taxes, and payment information.
  • lineItems: Item descriptions, quantities, and prices.

Check the extracted values against the source invoice before using them in your accounting or reporting workflow.

In this tutorial, you learned how to parse a PDF Invoice with PDF.co in Python.

Related Tutorials

See Related Tutorials