Artificial Intelligence

n8n PDF Invoice Extraction: Build Validated JSON Automation

Build n8n PDF invoice extraction with OCR, structured JSON, validation, duplicate checks, and human review before sending approved data to your systems.

Scanned PDF invoice beside laptop running validated JSON extraction automation
Scanned PDF invoice beside laptop running validated JSON extraction automation

To extract PDF invoice data in n8n, first receive and preserve the file. Then extract text or use OCR, map the result to a fixed JSON schema, validate it, check for duplicates, and send approved records to your business system. This method supports searchable PDFs, scans, rotated pages, tables, varied layouts, and human review. An AI response is not proof that an invoice is correct or unique.

Before you start

Prepare access to the intake source, an OCR or document-AI provider if needed, and the destination system. Decide where to retain original PDFs and raw extraction results. Also decide who reviews exceptions and which fields accounting requires.

A workflow can receive files from an Email Trigger, Webhook, Google Drive Trigger, Microsoft 365, or an S3-compatible storage event. Some n8n examples use Google Drive, Extract from File (PDF), Information Extractor, a Google Gemini chat model, batch processing, and Google Sheets. Another processes PDF attachments from incoming email and saves structured results to Google Sheets. Treat these as patterns. Before production, check each current node's input format, binary behavior, limits, credentials, and privacy terms in its official documentation.

Use n8n credentials instead of hard-coded tokens. Check the current retention, region, training-use, deletion, pricing, and API-limit terms for each external OCR or AI service. For self-hosted n8n, include the database and encryption key in your backup and recovery plan.

What the workflow should trust—and what it should not

Separate invoice reading from invoice approval. The PDF is the source document. Extracted text is evidence. Normalized JSON is a working record. Validation decides whether the record can continue.

The simplest end-to-end flow is:

  • Receive the PDF and record its file name, source, received time, and a hash when your storage system supports one.
  • Preserve the original binary.
  • Check whether the PDF contains usable text. If not, route it to an appropriate extraction service.
  • Convert the extracted content into a predictable invoice JSON object.
  • Normalize dates, currency codes, decimal values, supplier names, and line items.
  • Validate required fields, arithmetic totals, confidence, and duplicate keys.
  • Send uncertain or invalid records to human review.
  • Write approved data to the destination system and archive the original PDF with its raw extraction.

Do not trust an LLM's guess when an invoice number is missing. Pause the record or send it to review when that number is missing or has low confidence. Keep raw extraction beside the normalized fields. This lets a reviewer distinguish an unreadable PDF, an OCR error, and a mapping problem. Logging only the final JSON removes that evidence.

Choose the right extraction path

Use native PDF text extraction for digital invoices. Use OCR for image-only scans and document AI for difficult layouts. An LLM is mainly useful for mapping recovered content into your schema. A staged path is safer than sending every PDF directly to a model.

MethodBest fitMain weaknessTypical role
Native PDF textSearchable, upright digital PDFsFails on image-only pages and may scramble columnsFirst extraction attempt
OCRScans, photos, rotated pagesCharacter and reading-order errorsText recovery
Document AITables, forms, varied layoutsProvider cost, setup, and retention concernsLayout-aware extraction
LLMInconsistent wording and field mappingHallucinated or misread valuesStructured interpretation

After native extraction, add an IF check. If the result is blank, unusually short, or missing expected invoice terms, branch to the appropriate extraction service instead of passing empty content downstream. For rotated pages, use orientation correction. For tables, prefer a service that returns cells, rows, or bounding boxes when line-item accuracy matters. Plain text can lose column boundaries.

An LLM helps when labels vary, such as Invoice date, Bill date, and Date of issue. Give it a strict schema and tell it to return null rather than inventing a value. Document AI helps when you need table structure or coordinates across many supplier layouts. None of these methods proves that the invoice is valid, payable, or unique.

A scanned PDF invoice is shown as a document prepared for optical character recognition.
A scanned PDF invoice is shown as a document prepared for optical character recognition.

Build the n8n workflow and JSON result

Use one workflow item per PDF. For an email attachment, filter for MIME type application/pdf. For Google Drive or Microsoft 365, download the file before extraction. Keep the binary property named invoice_pdf. Do not convert it to base64 unless the next provider specifically requires it.

  1. Add the intake trigger. Confirm that each item contains binary.invoice_pdf and file metadata. The expected result is one workflow item per PDF.
  2. Add native PDF extraction or a suitable extraction node. Store returned text in raw_text while retaining the original binary.
  3. Add an IF node that checks text quality. Route blank, very short, or failed results to a permitted retry or review.
  4. Add an Information Extractor, structured-output model, or Code node. Map available evidence into the invoice schema.
  5. Add a Code or Edit Fields node. Normalize values and attach source evidence.

Use one stable shape even when a value is unavailable:

Invoice JSON
{
  "supplier": {
    "name": "Example Supplies Ltd",
    "tax_id": null,
    "address": null
  },
  "invoice_number": "INV-1042",
  "invoice_date": "2026-11-30",
  "due_date": "2026-12-30",
  "currency": "USD",
  "subtotal": 1250.00,
  "tax": 250.00,
  "total": 1500.00,
  "line_items": [
    {
      "description": "Consulting service",
      "quantity": 10,
      "unit_price": 125.00,
      "tax_rate": 20,
      "line_total": 1250.00
    }
  ],
  "confidence": {
    "overall": 0.91,
    "invoice_number": 0.98,
    "total": 0.96
  },
  "source_evidence": {
    "invoice_number": "Invoice No: INV-1042",
    "total": "Total USD 1,500.00"
  },
  "source_file": {
    "name": "invoice-1042.pdf",
    "mime_type": "application/pdf"
  },
  "raw_text": "..."
}

Use YYYY-MM-DD dates, uppercase three-letter currency codes where the source supports them, and numeric values instead of formatted strings. Convert decimal commas carefully: 1.250,00 and 1,250.00 do not mean the same thing in every locale. Preserve the printed value in source_evidence when conversion could be ambiguous.

Ask the extractor for null when a field is missing, an empty array when line items are absent, and no extra keys. Use deterministic cleanup in a Code node. Do not calculate a missing total from partial evidence unless your accounting rules explicitly allow it.

Validate totals, duplicates, and exceptions

Validate records after extraction and before delivery. Check required fields, formats, arithmetic, duplicate keys, and confidence before writing to accounting or payment systems. A passing arithmetic check is a control, not proof that the invoice is correct.

Useful checks include:

  • supplier.name, invoice_number, invoice_date, currency, and total are present.
  • Dates parse correctly and follow the chosen format.
  • Currency is allowed by your business process.
  • Monetary values are numeric and not negative unless credit notes are supported.
  • total is close enough to subtotal + tax under your documented rounding rule.
  • Each required line item has a description, quantity, unit price, and line total.
  • Required-field confidence meets your review threshold.

Do not assume that subtotal plus tax always equals total. Discounts, shipping, credits, withholding, multiple tax rates, and rounding can explain a difference. Store a validation_errors array instead of silently changing a value.

For duplicate detection, calculate a stable key from normalized supplier identity, invoice number, currency, and total. A file hash helps too, but it will not catch the same invoice downloaded again with a different file name. Store the key in a database with a unique constraint, or query the destination before insertion. Make the final write idempotent. A repeated webhook or retry should update or skip the existing record, not create another payable.

A PDF can contain several invoices. Detect page ranges or invoice-number changes before extraction, or use a service that returns multiple documents. Split the binary into one item per invoice when possible. If the pages cannot be separated reliably, send the whole file to review instead of attaching one total to several records.

Use retries only for transient provider errors, such as timeouts or rate limits. Follow the provider's current retry guidance. Do not retry validation failures. Route these cases to review:

  • missing invoice number or supplier;
  • unreadable or password-protected PDF;
  • conflicting totals or dates;
  • low confidence on a required field;
  • duplicate key found;
  • multiple invoices detected but not separated;
  • extraction or model failure after permitted retries.

The review branch can create an approval task, send a restricted email containing a review link, or write a row to a queue. Let the reviewer edit normalized fields while preserving the original extraction and recording who approved the change.

A PDF invoice is displayed on a laptop during data validation.
A PDF invoice is displayed on a laptop during data validation.

Deliver approved records and verify the workflow

Connect the approved branch only after validation and duplicate checks. Google Sheets suits a queue or audit view. PostgreSQL or MySQL provides a stronger base for unique constraints, status changes, and idempotent upserts. Accounting connectors such as QuickBooks or Xero need provider-specific field mapping and current API permissions. Check their official documentation before enabling writes.

  1. Store the original PDF in controlled Google Drive, S3-compatible storage, or Microsoft 365 storage. Save its object key instead of copying the document into every system.
  2. Insert or upsert the validated JSON into a database with status approved or ready_for_posting.
  3. Send only the fields required by the accounting system, including the stored source reference and duplicate key.
  4. Record the destination response, n8n execution ID, and final status in an audit table.
  5. Notify accounts payable or start an approval workflow when the amount, supplier, or policy requires human authorization.

Test with all of these: a searchable text PDF, a scanned invoice, a rotated scan, a two-page invoice with a table, a credit note, a missing-field invoice, a duplicate file, a password-protected PDF, and a document containing multiple invoices. Include a supplier layout that was not used while designing the prompt. Each test should produce a correct validated record or a clear review status. It should never produce a plausible record with hidden uncertainty.

Monitor received, extracted, reviewed, approved, rejected, duplicated, and failed documents. Log provider, operation, duration, status, and error category. Keep full invoice text and personal data out of ordinary logs. Restrict access to raw files and extracted text. When a prompt, provider, or node version changes, rerun the test set. Stop the rollout if required fields, totals, or duplicate handling regress.

For self-hosted n8n, back up the database and encryption key according to your deployment design. Verify that a restore works before changing versions or infrastructure. Keep failed executions available for diagnosis while applying retention rules to invoice content. Completion means the original PDF is preserved, structured JSON exists, validation errors are visible, duplicates are controlled, and only approved data reaches the destination.

Conclusion

Build the first version around deterministic controls. Preserve the PDF, detect empty extraction, select the right extraction path, normalize one schema, validate before delivery, and make writes idempotent. Use human review for uncertainty instead of hiding it behind an AI-generated value.

Frequently Asked Questions

Can n8n extract data directly from a scanned PDF invoice?

Yes. A native PDF text node may return little or no text from a scan. Detect that result, then send the binary PDF to an appropriate extraction service before structured extraction. Keep the original file and recovered text together so a reviewer can investigate errors.

Should I use an LLM or OCR for invoice extraction?

Use OCR to recover text from image-only pages. Use an LLM to map that recovered content into your JSON schema. For difficult tables and varied layouts, document AI may provide more useful structure. Validate required fields, totals, confidence, and duplicates before delivery.

How do I stop n8n retries from creating duplicate invoices?

Create an idempotency key from normalized supplier identity, invoice number, currency, and total. Enforce uniqueness in a database and keep a file hash as a second signal. On a repeated webhook or retry, update or skip the existing record instead of inserting another payable.

Sources

AI & Local Compute Desk

Think Tech Editorial

Practical guides on running local language models, GPU sizing, and private AI workflows.