Course 13 of 90  ·  Multimodal AI
Technical 20 min Module 2 of 6
Module 2 of 6

Document AI: PDFs, Invoices, and Forms

An accounts payable team processing 10,000 invoices a month needs more than character recognition. This module covers how modern document AI pipelines combine layout detection, table extraction, and language model reasoning to turn a wall of scanned text into structured, queryable data your systems can act on.

By the end of this module you will be able to

Why OCR Alone Fails

Optical character recognition solves one problem well: it converts pixels to characters. It has no model of what those characters mean or how they relate to each other spatially. Feed a scanned invoice through a standard OCR engine and you get a flat string. The line items that were arranged in columns become a single run of text. A table with six columns and forty rows becomes a string that requires extensive parsing to recover any structure at all.

Three failure modes appear consistently across document types:

Tables collapse to flat strings. OCR reads left to right, row by row, with no understanding that cells belong to a column or that a row is a logical unit. A financial statement with subtotals and spanning headers becomes meaningless when linearized this way.

Multi-column forms become gibberish. A two-column form field layout is read across both columns simultaneously, interleaving labels with values and destroying the field-value relationship that makes the form useful.

Regions have no semantic identity. OCR cannot distinguish a document header from a footer, a table from a paragraph, or a signature block from a line item. Downstream systems receive undifferentiated text and must re-infer structure that was present in the original document.

The invoice problem A scanned invoice contains a header region (vendor name, address, invoice number, date), a table region (line items with quantities, unit prices, descriptions), and a footer region (total, payment terms, bank details). OCR collapses all three into a single text block with no region boundaries. Document AI preserves them.

The Four Pipeline Stages

Modern document AI pipelines add three stages before OCR and one stage after it, each addressing a different structural gap.

Stage 1
Layout Detection
A vision model segments the document image into labeled regions: header, table, paragraph, list, footer, figure. Each region is a bounding box with a semantic class. This runs before any text is read.
Stage 2
Table Extraction
Regions classified as tables are processed to identify row and column structure, cell boundaries, and spanning cells. The output is a grid object, not a text string, preserving the relational information that makes tables useful.
Stage 3
OCR Per Region
Character recognition runs on each region separately, with awareness of the region type. A table cell gets different processing than a paragraph. Some approaches skip this stage entirely by reading pixels directly.
Stage 4
LLM Normalization
A language model receives the structured output and validates, corrects, and normalizes it: resolving date formats, currency symbols, ambiguous abbreviations, and field mappings to a target schema.

Three Model Families and When to Use Each

LayoutLM family (Microsoft). LayoutLM models are transformer architectures pretrained on document images with the addition of 2D position embeddings. Unlike standard language models that process text in sequence, LayoutLM conditions on both the token content and its spatial position on the page. This lets the model learn that a number appearing directly below a column header labeled "Unit Price" is a price, not just a number. The family has evolved through several versions, each incorporating more visual signal from the document image. LayoutLM-class models are the standard approach for structured forms and invoices where the field layout is consistent across documents.

Donut (Document understanding transformer). Donut takes a different architectural stance: it treats document understanding as an end-to-end vision task without an explicit OCR step. The model reads the document image directly and produces structured output through a sequence decoder, learning to extract fields without an intermediate text representation. This makes Donut faster and less dependent on OCR quality, which matters when input documents are low-resolution or degraded. The tradeoff is that end-to-end models require more training data to match the precision of pipeline approaches on complex layouts.

Vision-language models as document readers. General-purpose vision-language models trained on broad web data have developed substantial ability to read and reason about documents. Given a high-resolution document image, a capable VLM can extract specific fields, describe table contents, and answer questions about what it sees. The advantage is flexibility: the same model handles invoices, contracts, slide decks, and forms without task-specific training. The limitation is that VLMs are less precise than fine-tuned document models on consistent structured layouts, and their output requires more careful post-processing to enforce schema compliance.

Choosing the Right Approach

The choice of approach depends on three variables: document structure consistency, input quality, and required output precision.

Simple single-column text documents where layout is minimal and the content is flowing prose: standard OCR with post-processing is sufficient. Legal agreements with no tables, plain memos, and single-column reports fall here. Adding a full document AI pipeline adds complexity without adding value.

Structured forms and invoices where the same fields appear at consistent positions across a document class: LayoutLM-class models are the appropriate choice. The spatial pretraining directly addresses the problem, and fine-tuning on a document-type-specific dataset produces high precision. This is the largest category of enterprise document AI use cases: invoices, purchase orders, insurance claims forms, tax documents.

Complex mixed-content documents where layout varies across instances, content mixes tables, figures, and prose, and the extraction task requires reasoning rather than field extraction: a VLM-as-reader approach with careful prompting and output validation is the right architecture. Research papers, annual reports, and regulatory filings with heterogeneous structure fall here.

When not to use Document AI If your documents are already born digital with structured metadata (PDF forms with embedded field data, Excel files, structured XML exports), do not run them through a document AI pipeline. Extract the structured data directly from the source. Document AI is for documents where structure exists visually but not in the underlying data format.
Document AI Pipeline
PDF Input doc image Layout Detector region bbox Table Extractor grid object OCR per region text tokens LLM Normalizer validated Structured JSON queryable stage 1 stage 2 stage 3 stage 4
Interactive: Document AI Pipeline Simulation Try it

A fake invoice is shown below. Press Run to watch the pipeline detect document regions in sequence: header, table, and footer each receive a labeled bounding box as the pipeline processes them.

Status: ready

Code Example: Layout Detection and Table Extraction

The following Python example shows the conceptual structure of a document AI call using a hypothetical SDK. Real implementations use the same logical sequence: load the document, run layout analysis, identify table regions, and extract cell data to a dictionary.

# Document AI: layout detection and table extraction
# Conceptual example using a hypothetical document_ai SDK

import document_ai as dai

# Load the document (PDF or image)
doc = dai.load("invoices/acme-2026-08.pdf")

# Stage 1: detect layout regions
layout = dai.detect_layout(doc)

# layout.regions is a list of Region objects
# each has: region_type, bounding_box, confidence
for region in layout.regions:
    print(region.region_type, region.bounding_box)
# Output: header (x=0, y=0, w=612, h=120)
#         table  (x=0, y=140, w=612, h=340)
#         footer (x=0, y=500, w=612, h=80)

# Stage 2: extract table structure from table regions
table_regions = [r for r in layout.regions
                 if r.region_type == "table"]

for table_region in table_regions:
    table = dai.extract_table(doc, table_region)

    # table.to_dict() returns rows as list of dicts
    rows = table.to_dict()
    print(rows[0])
    # Output: {"description": "Widget A",
    #           "qty": "100", "unit_price": "12.50",
    #           "total": "1250.00"}

# Stage 4: normalize and validate with an LLM
normalizer = dai.LLMNormalizer(
    schema="schemas/invoice_v2.json"
)
structured = normalizer.normalize(layout, rows)
print(structured["invoice_total"])
# Output: {"amount": 1250.00, "currency": "USD"}

The key insight in the code is the separation of concerns: layout detection runs once on the full document, table extraction runs only on regions classified as tables, and LLM normalization runs last on the already-structured output. Each stage receives the output of the previous one rather than operating on raw pixels or raw text.

Think about it first: why would Donut sometimes outperform LayoutLM on degraded document images? +
LayoutLM-class models depend on OCR output as part of their input. If the upstream OCR produces errors on a low-resolution or poorly-scanned image, those errors propagate into the model's input and degrade its output. Donut bypasses OCR entirely, reading the document image directly through a convolutional encoder. On degraded images where OCR quality is low, Donut's end-to-end approach is less sensitive to the noise that corrupts text token inputs. The tradeoff is that Donut typically requires more task-specific training data to match LayoutLM precision on high-quality inputs.
Knowledge Check
What is the primary reason OCR alone fails on structured invoice documents?
Which model family is most appropriate for structured forms and invoices where the same fields appear at consistent positions across documents?
In the four-stage document AI pipeline, what does the LLM Normalizer stage receive as input?
Before you go
Reflection: identify one document type your organization processes in volume today. Which of the three model approaches would you reach for first, and what would you need to know about the document layout consistency to confirm that choice?
Was this helpful?
Multimodal AI  ·  Course 13 of 90
You might also like
← Module 1: Vision-Language Models Module 3: Audio AI →