Extracting Invoices and PDF Records with AI: Complex Tables and Math Cross-Checks
An engineering guide to using multimodal LLMs for multi-page scanned PDFs, handwritten overrides, strict JSON schemas, and deterministic arithmetic verification before ERP ingestion.
Separate visual transcription from business-rule resolution using strict JSON schemas and explicit ambiguity flags.
Process multi-page tables in sliding context pairs to filter carried-forward subtotals and prevent double counting.
Run deterministic Decimal or integer arithmetic checks in application code and route only mismatched rows to staff review.
Finance, customs, and logistics teams spend countless hours re-keying data from skewed PDF scans, multi-page customs declarations, delivery slips stamped with red ink over key figures, and packing lists edited in ballpoint pen. Fixed-template OCR pipelines break as soon as a supplier shifts column widths or splits a table across a page boundary. Yet sending an entire PDF straight to a large language model (LLM) and trusting its raw text output introduces a different failure mode: silent hallucinations on unit prices, decimal points, or skipped line items.
Deploying Document AI reliably in production requires splitting the pipeline into two distinct layers: a visual extraction layer constrained by strict schemas, and a deterministic verification layer implemented in standard application code.
Multi-Page PDF Ingestion and Strict Schema Enforcement
Instead of relying solely on embedded PDF text layers, which frequently scramble column reading order on legacy scans, rasterizing each page into controlled images gives the multimodal model an exact visual layout. According to Anthropic's Vision documentation, image dimensions and clarity directly affect fine-print legibility, token usage, and latency. Rendering A4 documents at roughly 150 to 200 DPI typically preserves small decimal digits and tax IDs without inflating payload size unnecessarily.
Company blog
Read next
Every extraction call should enforce a strict JSON Schema, such as OpenAI's Structured Outputs (strict: true), so that returned payloads always match typed fields: invoice_number, issue_date, currency, an array of line_items (description, quantity, unit price, tax rate, line total), and summary totals (subtotal, tax_amount, grand_total).
When a line-item table spans 3 to 10 pages, processing each page in isolation causes two recurring bugs: middle pages lose their column headers, and subtotal rows labeled "Carried forward" or "Brought forward" get extracted as billable items. A practical fix is feeding page N alongside header context from page 1 (or the bottom band of page N-1) while including a boolean is_carry_forward flag in the item schema so downstream code excludes subtotal rows from summation.
Separating Handwritten Notes, Stamps, and Ambiguous Cells
Real-world trade and accounting documents often layer printed figures with field corrections: crossed-out quantities, handwritten actual-received counts in the margin, or wet ink stamps overlapping unit totals. Forcing a model to emit a single scalar number for a contested cell pressures it to guess and erases the audit trail.
A safer schema design records printed_value, handwritten_note, is_ambiguous (boolean), and ambiguity_reason (string) on numeric and quantity fields. Under this pattern, the vision model focuses strictly on faithful transcription of what appears on the page, leaving policy decisions, such as whether a warehouse supervisor's handwritten correction overrides the printed quantity, to deterministic backend logic.
Deterministic Math Cross-Checks and Review Routing
An LLM should never be trusted to verify its own multiplication or column sums in prose. Immediately after receiving schema-valid JSON, backend code should parse all monetary amounts into exact Decimal types (or integer minor units such as cents) and run three mandatory checks:
01Row-level math check: verify abs((qty x unit_price - discount) - line_total) <= rounding_tolerance for every entry in line_items.
02Vertical sum check: sum all line_total values where is_carry_forward is false, verify equality against subtotal, and confirm subtotal + tax_amount == grand_total.
03Master-data and format check: validate tax registration format, currency precision, and purchase order (PO) references against internal records.
Based on these outcomes, documents are routed into three operational queues before entering enterprise systems:
Routing Tier
Trigger Condition
System Action
Staff Workload
Auto-Accept
All row math and vertical totals match, is_ambiguous = false
Create draft ERP voucher or pass to downstream posting
No manual page inspection; periodic batch sampling only
Flagged Line Review
Minor rounding drift or handwritten_note / is_ambiguous = true
Hold posting, crop the flagged row image next to extracted values
Operator inspects only highlighted cells rather than the full PDF
Reject / Re-key
Major total mismatch, missing table pages, or illegible scan
Route document to exception queue with original PDF attached
Accounting staff re-keys document or requests a cleaner scan
This routing pattern keeps reviewers off clean, mathematically verified invoices and concentrates human attention on genuine exceptions.
Documentation Basis and Engineering Limitations
The architectural patterns above build on two official vendor specifications: Anthropic's Vision guide (which details image input limits, resolution trade-offs, and visual text reading behavior) and OpenAI's Structured Outputs guide (which documents schema-constrained JSON generation).
From ToanKhonTech's engineering perspective, three practical caveats apply before moving such a pipeline into production. First, strict JSON Schema enforcement guarantees structural validity of keys and data types, not factual accuracy of the extracted digits. Second, low-resolution scans under 100 DPI, heavy camera glare, or faded carbon-copy handwriting will still trigger high ambiguity rates and must escalate to human operators. Third, rounding tolerances (often 1 to 2 minor currency units depending on whether VAT is rounded per line or at the invoice total) must be calibrated per tax jurisdiction and supplier convention.
References
Sources used to check this article. Any ToanKhonTech test results are identified separately in the text.