After OCR, check three equalities. The sum of line items before VAT should match the subtotal, the subtotal with VAT should match the invoice total, and the total after deducting any prepayment and applying any explicitly stated rounding adjustment should match the amount due. These checks apply to a single invoice in one currency with line items before VAT. For example, an invoice for 1,200.00 with a prepayment of 200.00 may correctly show an amount due of 1,000.00.
This instruction applies if OCR or AI is already extracting fields from a PDF. For example, use one approved supplier invoice template with two decimal places, line totals before VAT, no separate document-wide discounts or surcharges, and no prior balance carried over. The output will show the discrepancy for each of the three equalities and let you point a reviewer to the relevant part of the invoice.
If the input is a batch of pages from different documents, first prepare it by splitting scans into separate documents. The field extraction and handoff setup is described in the article on how to prepare document recognition.
- Mark three amounts on the invoice
- Normalize numbers
- Verify three equalities
- Run the sample cases
- Analyze discrepancies
Step 1. Mark three different amounts on the invoice
Take the PDF and the extraction result. In the record, note where the template prints the net total, the gross total, and the amount remaining to pay. For each field, save the page number, the region link if the engine provides one, the source text, and the normalized value. Make sure the table was extracted from all pages and that the repeated header and the "Total" row were not included in the line items list.
| Sample field | What to extract | What to verify in the PDF |
|---|---|---|
line_net |
The amount of each line before VAT | Specifically the amount column, taking into account any discounts already included in the line |
subtotal |
Subtotal before VAT | The label next to the subtotal, especially if there are two total columns |
tax |
Stated VAT amount | The tax amount in the document currency |
total |
Invoice total with VAT | The total charges on the current invoice |
prepaid, rounding |
Prepayment and signed rounding adjustment to the amount due | Separate amounts and the sign of the adjustment |
due |
Amount due | The remaining balance field, which may appear next to the total |
The names in the table refer to the tutorial script. For example, the Microsoft Document Intelligence v4.0 schema distinguishes InvoiceTotal and AmountDue. In its example, the amount due is higher than the current invoice total because of a prior balance. The field Items.*.Amount is described as the line item amount. Confirm the meaning of the column for your own template in the PDF. Microsoft field schema.
For an optional field, record the amount read, confirmed absence, or unknown value. Zero is acceptable for the second case. When a prepayment line exists but OCR did not read it, leave the value unknown and send the document for review. The result of this step is that each number has a label and a location in the document, or a documented reason for omission.
Step 2. Convert amounts to one format
Store money as strings in a fixed format, for example "1200.00", and convert them to whole minor currency units before adding. For rubles, that means kopeks. Converting 1 200,00 to 1200.00 is appropriate if the input template explicitly uses a decimal comma and a space as the thousands separator. For the entry 1.200 without a known format, first clarify the template rules. It is better to show ambiguous source text in full.
The code below accepts already normalized amounts. It requires two decimal places, and a minus sign is allowed only for the rounding adjustment. Formats with a currency symbol, spaces, or a missing fractional part are rejected. The 12-digit limit before the decimal point applies to this example. Separately confirm the shared currency code for all amounts, including tax and prepayment. Python documentation on full-string validation.
Step 3. Check the three equalities separately
- Subtotal = sum of line items before VAT. If the invoice includes a document-wide discount or surcharge, create a separate field for it and use your template's formula. In Peppol BIS Billing, this is covered in BR-CO-13. Subtotal in the Peppol specification.
- Invoice total = printed subtotal + printed VAT amount. For this check, use the extracted VAT amount. Validate the tax rate and the line-level tax recalculation separately. Total including tax in the Peppol specification.
- Amount due = printed total − prepayment + rounding adjustment. If the agreed template includes an old balance, credit, or installment plan, first clarify the meaning of the amount due and the formula. Peppol rules are shown here as a documented example of an e-invoice structure. Amount due in the Peppol specification.
For the second and third equalities, use the printed amounts from the previous field, even if a discrepancy was already found there. For example, suppose the PDF subtotal is 1,000.00 and OCR missed a line for 300.00. The first equality will expose the line-item problem. The second will still show whether the printed subtotal, VAT, and total are consistent with each other. If you check every field against the sum of extracted lines, one missed item can trigger three alerts at once.
Step 4. Run the check on a sample invoice
Save the block in check_invoice.py and run python3 check_invoice.py. Only the Python standard library is needed. The input is a dictionary from one approved template after currency and completeness validation. The function returns pairs in the form "field → extracted amount minus calculated amount" in minor currency units. If there are no discrepancies, the dictionary will be empty.
import re
def minor_units(value, field, *, signed=False):
pattern = r"-?[0-9]{1,12}\.[0-9]{2}" if signed else r"[0-9]{1,12}\.[0-9]{2}"
if not isinstance(value, str) or not re.fullmatch(pattern, value):
raise ValueError(f"invalid or missing amount: {field}")
return int(value.replace(".", ""))
def reconcile(invoice):
lines = invoice.get("line_net")
if not isinstance(lines, list) or not lines:
raise ValueError("missing line amounts")
lines_sum = sum(minor_units(v, f"line_net[{i}]") for i, v in enumerate(lines))
subtotal = minor_units(invoice.get("subtotal"), "subtotal")
tax = minor_units(invoice.get("tax"), "tax")
total = minor_units(invoice.get("total"), "total")
prepaid = minor_units(invoice.get("prepaid"), "prepaid")
rounding = minor_units(invoice.get("rounding"), "rounding", signed=True)
due = minor_units(invoice.get("due"), "due")
differences = {
"subtotal": subtotal - lines_sum,
"total": total - (subtotal + tax),
"due": due - (total - prepaid + rounding),
}
return {field: delta for field, delta in differences.items() if delta}
invoice = {
"line_net": ["700.00", "300.00"],
"subtotal": "1000.00",
"tax": "200.00",
"total": "1200.00",
"prepaid": "200.00",
"rounding": "0.00",
"due": "1000.00",
}
if __name__ == "__main__":
print(reconcile(invoice))
print(reconcile({**invoice, "due": "1200.00"}))
A local run on synthetic data produced {} for the original invoice and {'due': 20000} when the total was substituted for the amount due. Additional checks confirmed the following results. Cloud OCR and accounting system integration were not run in this test.
| Change in the sample input | Expected and actual result |
|---|---|
| Remove the 300.00 line | {'subtotal': 30000} |
| Change the amount due to 1,000.01 | {'due': 1} |
| Set rounding to -0.01 and the amount due to 999.99 | {} |
Replace the advance payment value with None |
ValueError with field prepaid |
Enter 1,000.00 in the total field |
ValueError with field total |
| Replace the line items with 710.00 and 290.00 | {}even though both amounts differ from the PDF |
The last line shows the method's limit. Errors that cancel each other out still pass the arithmetic check. That is why content verification should use an independent source, such as the original supplier order lines or a PDF comparison. The model's confidence can suggest which field to show first, but the decision on a discrepancy still belongs to the rules and the responsible employee.
Step 5. Show the reviewer the specific discrepancy
If there is a format error or a missing value, pass the field name, the original text, and the page. If there is a nonzero discrepancy, show the label and a field fragment, the calculated amount, and the difference with a sign. For due: 20000 in the example, that means “recognized 1,200.00, the invoice data expects 1,000.00, difference +200.00.” The reviewer will immediately see that the total and the balance after the advance payment should be compared.
If only the subtotal is off, start with line completeness and the “no VAT” flag. If the total is off, check the tax column and the currency. If only the amount due is off, check the advance payment, the rounding sign, and which total OCR linked to. Do not hide a penny behind a broad tolerance until the process owner has identified the cause and the rule for that specific template.
An empty result confirms arithmetic consistency. Before writing to the accounting system, keep the counterparty check, duplicate check, and order link in place. Leave payment approval and tax validation to the company process.
Frequently asked questions
What should I do if the invoice has only one “Total” field?
Clarify, according to the agreed template, whether it also means the amount due. If so, record that both values come from the same field. This comparison tests application of the rule for advance payments and rounding, but with zero adjustments it does not provide independent confirmation of the balance. If the field meaning is unknown, leave due blank for manual review.
How should shipping and discounts be handled?
Include shipping shown as a separate line item without VAT in the line list. For shipping or a discount on the entire invoice, create a separate field and define whether it is included in the printed subtotal. First test the formula on a PDF with both a discount and shipping. The sample function is designed for a template without such document-level adjustments.
Microsoft, OpenPeppol, and Python documentation checked on November 22, 2026.
How Vladimir Lomtev's AI studio helps with invoice reconciliation
Vladimir Lomtev's AI studio can analyze a live incoming invoice workflow, prepare PDF field extraction, and build amount reconciliation with exception handoff to the accounting process. For an initial discussion, choose one common vendor template and prepare two anonymized examples — an invoice with an advance payment and an invoice with a discrepancy the accountant should see first.
Bottom line
Start with an invoice where the advance payment changes the amount due. Label the fields from the PDF, then check the subtotal, the VAT-inclusive total, and the balance independently. The finished result shows at which equality the difference appeared and which part of the document should be opened for review.



