How to Automate PDF Invoice OCR and Math Reconciliation in Google Sheets Using n8n and GPT-4o-mini
Manual invoice data entry is slow, and relying solely on Large Language Models (LLMs) to extract financial figures introduces a hidden risk: arithmetic hallucinations. While models like GPT-4o-mini excel at unstructured
Manual invoice data entry is slow, and relying solely on Large Language Models (LLMs) to extract financial figures introduces a hidden risk: arithmetic hallucinations. While models like GPT-4o-mini excel at unstructured text extraction, they predict tokens rather than execute deterministic mathβoccasionally misreading a decimal point or mismatching subtotal and tax lines.
To eliminate both manual entry and silent accounting discrepancies, you can build a 6-node n8n pipeline that extracts PDF invoice data in strict JSON mode, validates the arithmetic in JavaScript, and flags discrepancies before writing rows to Google Sheets.
Skip the manual node setup: You can download the ready-to-import
.jsonworkflow, pre-formatted.csvledger template, and deployment guide directly on Payhip or inspect the architecture in the GitHub repository.
Pipeline Architecture
The workflow operates asynchronously across six sequential nodes:
-
Google Drive Trigger (
Watch Invoices Folder): Polls a designated folder for newly uploaded PDF invoices. -
Google Drive (
Download PDF Invoice): Fetches the binary file using the incoming file ID ({{ $json.id }}). -
Extract from File (
Extract PDF Text): Parses raw text directly from digital PDFs without third-party OCR API fees. -
HTTP Request (
AI Structured Extraction): Sends the extracted text to OpenAI'sgpt-4o-miniendpoint withresponse_format: { "type": "json_object" }andtemperature: 0(~$0.0005 USD per invoice). -
Code Node (
Accounting Audit Check): Runs a deterministic JavaScript reconciliation check on the extracted numbers. -
Google Sheets (
Append to Ledger): Maps all 13 verified fields into a structured accounting sheet.
Enforcing Strict JSON Extraction
To prevent conversational filler from breaking downstream nodes, configure the OpenAI HTTP Request body with a rigid schema prompt:
{
"model": "gpt-4o-mini",
"response_format": { "type": "json_object" },
"temperature": 0,
"messages": [
{
"role": "system",
"content": "Extract accounting fields from the invoice text. Return strictly a JSON object with keys: vendor_name (string), tax_id (string or null), invoice_number (string), invoice_date (YYYY-MM-DD), currency (3-letter ISO code), subtotal (number), tax_amount (number), total_amount (number), expense_category (string: Materials, Subcontractors, Software, Fuel, Office, Utilities, Other)."
},
{
"role": "user",
"content": {{ JSON.stringify($json.text) }}
}
]
}
Setting temperature: 0 eliminates sampling randomness, while json_object guarantees valid JSON syntax on every execution.
Deterministic Math Reconciliation in JavaScript
Before appending data to your ledger, the Accounting Audit Check Code node verifies whether subtotal + tax_amount equals total_amount within a $0.02 rounding tolerance:
const rawContent = $input.first().json.choices[0].message.content;
const data = JSON.parse(rawContent);
const subtotal = Number(data.subtotal || 0);
const tax = Number(data.tax_amount || 0);
const total = Number(data.total_amount || 0);
const diff = Math.abs((subtotal + tax) - total);
return [{
json: {
processed_at: new Date().toISOString(),
file_name: $('Watch Invoices Folder').first().json.name,
vendor_name: data.vendor_name || 'UNKNOWN',
tax_id: data.tax_id || '',
invoice_number: data.invoice_number || 'N/A',
invoice_date: data.invoice_date || '',
currency: data.currency || 'USD',
subtotal: subtotal,
tax_amount: tax,
total_amount: total,
expense_category: data.expense_category || 'Other',
audit_status: diff <= 0.02 ? 'VERIFIED' : 'MATH_DISCREPANCY',
variance: Number(diff.toFixed(2))
}
}];
If an invoice contains a surcharge not captured in the tax line or an OCR misread occurs, audit_status outputs MATH_DISCREPANCY alongside the exact variance amount so bookkeepers only review flagged exceptions.
Turnkey Deployment Kit
If you want to deploy this workflow immediately in n8n Cloud or Self-Hosted without wiring each node and expression from scratch, the complete package is available here:
-
Download the n8n Invoice OCR & Math Audit Kit ($29 USD) β Includes
invoice-ocr-ledger-n8n.json,Ledger_Template.csv, andSetup_Guide.pdf.
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.
