Hands-on tutorial

Document Parsing for AI Engineers: From PDF to Structured Data

A hands-on, step-by-step tutorial for building document parsing pipelines: native text, OCR, tables, layout, multilingual documents, validation and RAG.

This is the earlier practical tutorial. The updated Persian engineering guide is not a direct translation of this edition.

By the end, you'll have a small local Python parser, know how to inspect its intermediate outputs, and have a plan for testing more complex documents. No machine-learning training, GPU or paid API is required for the core exercise. Basic Python knowledge is enough.

Tutorial contents1. Decide what your parser should produce 2. Set up a small reproducible exercise 3. Start with native text, then inspect the geometry 4. Handle scanned and mixed pages with OCR 5. Reconstruct tables, not just their words 6. Add a layout-aware parser when the baseline fails 7. Store structured data and evidence before exporting 8. Handle multilingual and right-to-left documents carefully 9. Combine the steps into a small pipeline and debug failures 10. Evaluate the parser with ground truth before optimizing 11. Move from the notebook to a real AI application Further reading and next exercises

1. Decide what your parser should produce

Suppose you are building a search assistant for product manuals, research papers or company documents. You receive PDFs, Word documents and scans. The user asks for an item price, an instruction from a manual, or a particular paragraph. Your parser's job is to turn the document into data the downstream application can actually use—not to answer the question yet.

Keep three responsibilities separate: text extraction reads characters; layout analysis locates paragraphs, headings, tables and pictures; document parsing reconstructs the content and the relationships between those elements. OCR (Optical Character Recognition) reads text from pixels. It is not, on its own, a table or document structure parser.

GoalMinimum useful outputWhat can go wrong
Search a simple manualText, page numberWrong reading order
Extract a price listRows, columns, headers, raw cell textRight number in the wrong row
Build a cited RAG systemOrdered elements, page and region evidenceA plausible answer with no traceable source

For this tutorial our contract is: input PDF → a JSON record of pages, text candidates, words with coordinates, simple table cells and warnings. Later we will use a layout-aware converter for complex structure and derive Markdown/HTML for human reading. This is a deliberately small starting point, not a universal parser.

Why not just call an LLM on the PDF? Sometimes that is a reasonable baseline, but when the model gets a number wrong you still need to locate the source, compare outputs and measure quality. Build the evidence path first.

2. Set up a small reproducible exercise

You need Python 3.10+ and a terminal. Save these three files in an empty directory: requirements.txt, make_demo.py and parse_pdf.py. The example pins a PyMuPDF version for reproducibility; review newer releases and security fixes before using it in a real service. PyMuPDF is available under AGPL or commercial licensing; check the licensing information for your deployment.

python -m venv .venv
# Linux / macOS:
source .venv/bin/activate
# Windows PowerShell (instead of the line above):
# .\.venv\Scripts\Activate.ps1
python -m pip install -r requirements.txt
python make_demo.py demo.pdf

The generator creates demo.pdf, an entirely synthetic document with three pages:

  1. A digital text page with the title “Project guide”.
  2. A digital table containing Item, Price, Notebook (12.50) and Pen (2.00).
  3. An image-only page containing “Scan example” and reference code AB123.

Open the PDF in a viewer. Try selecting the text on each page. The first two allow text selection; the third has only pixels. The known contents give us a small ground truth for debugging. Do not start by using confidential customer files.

3. Start with native text, then inspect the geometry

Copy this snippet into inspect_pdf.py and run it with Python. It reads embedded text, not the pixels of the rendered page.

import pymupdf

with pymupdf.open("demo.pdf") as doc:
    for page in doc:
        print(f"Page {page.number + 1}")
        print(page.get_text("text", sort=True))

Expect text on pages 1 and 2, and no meaningful text on page 3. A PDF may store text drawing operations in an order unrelated to the way people read it, and some scans contain an invisible OCR text layer that can itself be wrong. A non-empty string is therefore not proof of correct extraction. See the pypdf explanation of PDF text extraction and PyMuPDF text recipes.

Use coordinates to debug reading order. A bounding box (BBox) tells you where a word or region is on a page; it is usually expressed as four coordinates. The example uses PyMuPDF's unrotated page coordinate space in points, not pixels.

import pymupdf

with pymupdf.open("demo.pdf") as doc:
    page = doc[0]
    for x0, y0, x1, y1, text, block, line, word in page.get_text("words"):
        print(text, (x0, y0, x1, y1))
    page.get_pixmap(dpi=150).save("page-1.png")

Compare the output with page-1.png. To inspect a two-column document, collect blocks with page.get_text("blocks"), draw their boxes on a copy or on a rendered image, and see whether the order crosses columns. sort=True is a helpful geometric heuristic, not a solution for every layout or RTL document. For simple layouts you can group by column and sort within each column; for complex ones use the layout parser in step 6.

For a clean born-digital PDF with correctly encoded text, native extraction is an excellent first baseline. Do not run expensive OCR on every page merely because OCR is available.

4. Handle scanned and mixed pages with OCR

Install Tesseract and the trained language data. For other operating systems follow the installation guide. The language list should include eng for this synthetic exercise; fas is Persian, ara Arabic (supported language codes).

# Ubuntu / Debian (install language data as needed):
sudo apt install tesseract-ocr tesseract-ocr-eng tesseract-ocr-fas
tesseract --list-langs
import pymupdf

with pymupdf.open("demo.pdf") as doc:
    page = doc[2]  # 0-based index: page 3
    tp = page.get_textpage_ocr(language="eng", dpi=300, full=True)
    print(page.get_text("text", textpage=tp, sort=True))

The expected candidate contains AB123. If Tesseract cannot locate its language files, supply the directory containing the .traineddata files via tessdata or the teaching script's --tessdata argument. The OCR TextPage must be passed to subsequent extraction calls; otherwise you are reading the original native layer again.

For a mixed-language document, try language="fas+eng". Start around 300 DPI and compare on your sample. Higher resolution costs more memory and time and cannot recover details that never existed in the scan. Use the Tesseract quality guide to test deskewing, rotation, contrast, noise removal or different page segmentation settings one at a time; always compare with the original image, especially for decimal points and small characters.

If your goal is to create a searchable PDF, OCRmyPDF offers a convenient separate workflow (after installing it and its dependencies):

ocrmypdf -l fas+eng --rotate-pages --deskew --skip-text input.pdf searchable.pdf

Keep input.pdf unchanged. --skip-text skips pages with text; this can miss image regions inside an otherwise digital page. A searchable PDF is still not a reconstructed table. See the OCRmyPDF cookbook for mixed and existing-OCR modes.

Routing rule: empty native text, replacement characters, missing expected regions and broken reading order are signals for review—not a perfect scan detector. A blank page is valid; a page with one native heading and a full-page scanned table is not fully parsed. For mixed pages, inspect image regions and OCR only the missing region where appropriate. The sample script supports explicit full-page OCR for selected pages; region-level recovery is a next step, not implemented in the baseline.

5. Reconstruct tables, not just their words

In the demo, page 2 contains this table:

ItemPrice
Notebook12.50
Pen2.00

Extracting a list of words is insufficient. We need to know that 12.50 belongs to Notebook, not Pen. Try PyMuPDF's table detector on the simple grid:

import pymupdf

with pymupdf.open("demo.pdf") as doc:
    for table in doc[1].find_tables().tables:
        for row in table.extract():
            print(row)

Expected rows: ['Item', 'Price'], ['Notebook', '12.50'], ['Pen', '2.00']. The Page.find_tables API documentation describes strategies based on lines and text. For borderless tables, try strategy="text" on selected pages and compare results. No detected table does not mean there was no table.

Scans, merged cells, multi-level headers and tables split across pages need more than grid-line detection. Store row and column IDs, row/column spans when known, header relationships and region coordinates. Retain the difference between an empty cell, a merged cell and a cell that could not be read. For a table split over pages, compare repeated headers, column alignment, section context and page boundaries before joining it; never merge unrelated tables just because their column counts match.

When a table contains numbers, units or IDs, validate their association with the correct row and column. An OCR engine may read every character correctly while the table reconstruction associates the wrong cells. For complex layouts, test a structure-aware engine next.

6. Add a layout-aware parser when the baseline fails

Now try a complex real document you are allowed to use, such as a public report with headings, tables and two columns. Docling provides a higher-level document representation rather than only strings. Install it separately if you need this step; its first PDF conversion may download model artifacts and take longer. The following follows its documented Python quickstart and export API:

python -m pip install docling
from pathlib import Path
from docling.document_converter import DocumentConverter

result = DocumentConverter().convert("input.pdf")
doc = result.document
doc.save_as_json(Path("document.json"))
Path("document.md").write_text(
    doc.export_to_markdown(), encoding="utf-8"
)

Use JSON to inspect the structured items and Markdown for a readable preview. Docling's document representation describes text items, tables, pictures, tree relationships and provenance. Review the pipeline options before enabling OCR, table structure or particular models; support and configuration differ between versions. Do not assume its default OCR engine works well for your languages. This optional example is documentation-based; it is not part of the small PyMuPDF fixture test.

Other reasonable alternatives include Unstructured, which exposes different PDF partitioning strategies, and direct native readers. Use the simplest engine that satisfies your measured requirements. The choice is not a universal ranking.

ToolUse it when…Check first
PyMuPDF / pypdfDigital PDF text and basic evidence are enoughReading order, encoding, license
Tesseract / OCRmyPDFYou need image-to-text or a searchable PDFLanguage data, scan quality, lost regions
DoclingHeadings, reading order, tables and common structured formats matterOCR language support, table accuracy, runtime
UnstructuredYou need categorized document elements and alternative partition strategiesDependencies, strategy selection, multi-column ordering
Vision-language model (VLM)An isolated difficult region needs an additional visual candidateHallucination, sensitive data policy, cost, verifiability

Use Unstructured's partitioning guide to understand its strategy trade-offs. For DOCX, XLSX, HTML and other natively structured inputs, use a format-aware reader (or a converter such as Docling with documented supported formats); don't flatten everything to PDF just to reuse your OCR pipeline. Word headings and spreadsheet cells already carry useful structure.

A VLM can be useful for an unusual scan or chart. Send a bounded region, ask for a literal transcription in a strict schema with unknowns left null, retain the original crop and validate the output. Treat the response as another candidate; a second model agreeing with the first does not prove correctness.

7. Store structured data and evidence before exporting

The next step is to choose a canonical representation: the version from which you generate other formats. You can use an existing document schema or design a small one. A custom DocumentIR (Intermediate Representation) is simply a structured representation of a document between extraction and export; it is not a required industry format.

{
  "page": 2,
  "kind": "table_cell",
  "table_id": "p2-t0",
  "row": 1,
  "col": 1,
  "header": "Price",
  "text_raw": "12.50",
  "value": "12.50",
  "bbox": [200, 85, 360, 120],
  "method": "native",
  "status": "unverified"
}

This is an illustrative schema for the known synthetic cell, not a literal record emitted by the teaching script. Indexes are zero-based; page numbers are one-based; the BBox describes the expected cell bounds in unrotated PDF points. In practice attach a document hash, page ID, region ID, engine/version, settings, and a transform if coordinates were produced on a resized or rotated image. If you normalize a value, keep the raw text too. Use decimals rather than binary floating point for amounts requiring exact decimal arithmetic.

The parser output should record what is known, what is missing and which regions are unresolved. JSON is useful for validation and downstream software; HTML supports more complex tables; Markdown is convenient for human readers or model prompts, but can lose merged cells and provenance. Treat Markdown as a derived view, not the only copy of your evidence. Use escaping/sanitization when displaying extracted HTML or text in a browser.

8. Handle multilingual and right-to-left documents carefully

Persian, Arabic and Hebrew add a second challenge: the logical order of Unicode text and its visual display order are different. A line such as مبلغ ۱۲٫۵۰ USD includes RTL words, a decimal number and an LTR currency code. Reversing the entire string with text[::-1] can corrupt numbers and Latin words. The Unicode Bidirectional Algorithm explains display reordering; it does not repair incorrectly extracted source text.

Keep the original Unicode string. For search, create a separate normalized form using NFC and deliberate language-specific mappings. For Persian, you may map Arabic yeh/kaf to Persian variants when your application requires that search behavior:

import unicodedata

def normalize_for_search(text):
    text = unicodedata.normalize("NFC", text)
    return text.translate(str.maketrans({
        "ي": "ی", "ك": "ک"
    }))

raw = "مبلغ ۱۲٫۵۰ USD"
search_text = normalize_for_search(raw)
# Keep raw as well; do not reverse or strip every symbol.

Use Python's Unicode normalization API. Do not automatically delete zero-width non-joiners, punctuation, minus signs, percent signs or decimal separators; they may carry meaning. Map digit scripts only in a defined numeric/search normalization layer, preserving leading zeros in identifiers and original strings. Test representative combinations of Persian/Arabic/English words, dates, currency, identifiers, parentheses and mixed-direction table cells. Use RTL rendering and direction isolation for mixed text when displaying it. For incorrect extraction, inspect the raw character sequence, word boxes and page image before attempting any correction.

9. Combine the steps into a small pipeline and debug failures

The full teaching script combines native extraction, page-level routing, optional OCR, word coordinates, simple native tables and page warnings. Run it twice on the same demo with different output paths:

python parse_pdf.py demo.pdf native.json
python parse_pdf.py demo.pdf with-ocr.json --ocr --lang eng
# Optional: inspect and explicitly OCR a mixed/corrupted page:
python parse_pdf.py input.pdf review.json --ocr --lang fas+eng --ocr-page 2

Open both JSON files. In native.json, page 3 has no extraction method and requires review. In with-ocr.json, the scan has an OCR candidate; its table list remains empty because OCR did not reconstruct table cells. Page 2 contains the detected native table. Every document remains unverified; even a page labeled candidate is not accepted. The explicit --ocr-page option requests full-page OCR, retaining the original native text for comparison but not native table extraction on that page.

Input file
  -> Detect format / inspect pages
  -> Native extraction OR OCR
  -> Layout + reading order + tables (when needed)
  -> Structured document + source coordinates
  -> Validate / review unresolved regions
  -> Export JSON / Markdown / HTML
  -> Chunk + index accepted content only

Do not add all advanced models at once. When a result is wrong, compare intermediate artifacts to the page image, identify which stage failed and change only that stage. Here is a troubleshooting guide:

SymptomInvestigateTry / verify
No textImage-only, blank or broken text layerRender page; OCR if content exists
Garbled or reversed wordsFont encoding, Bidi order, reading orderInspect word boxes/raw Unicode; compare OCR
Two columns interleavedReading orderGroup columns or use layout model; check sequence
Correct digits, wrong table cellsTable detection/structureReview cell boundaries and headers; compare structure parser
Missing decimal or percentOCR/image qualityRender crop, compare DPI and language; review critical symbols
Missing figure caption or embedded textLayout/image extractionCheck regions and captions; OCR the relevant crop
Old output after code changeCache invalidationUse source hash + engine/model version + config/schema in key; run fresh
Page failed or timed outInput damage, resources, parser crashRecord failure; bound retries; review or retry a targeted region

Retries need limits. Keep raw extraction candidates separate from corrected output and use a review queue for unresolved regions. A failed stage must not silently become an empty successful result. In an automated service, only pass validated elements downstream; hold an entire document if an unresolved region could change its meaning. This sample intentionally lacks automatic acceptance, calibrated routing, merged-table reconstruction and service-grade isolation.

10. Evaluate the parser with ground truth before optimizing

Start with a small assertion against your synthetic fixture. Save the snippet below as check_demo.py and run it after the OCR example.

import json

with open("with-ocr.json", encoding="utf-8") as f:
    parsed = json.load(f)
assert parsed["page_count"] == 3
assert len(parsed["pages"]) == 3

cells = {
    (cell["row"], cell["col"]): cell["text"]
    for cell in parsed["pages"][1]["tables"][0]["cells"]
}
assert cells[(1, 0)] == "Notebook"
assert cells[(1, 1)] == "12.50"
assert cells[(2, 1)] == "2.00"
assert "AB123" in parsed["pages"][2]["text"]
# This checks a synthetic fixture, not production quality.

Then create a gold dataset: real, authorized pages with manually checked reference text, reading order, tables and key fields. Cover different document families (native, scan, mixed, multi-column, rotated, low quality, multilingual), not just pages that your tool already handles. Freeze the evaluation split; tune on different documents. The number of pages depends on diversity and risk—a tiny fixture cannot establish accuracy on your corpus.

MeasureWhat it reveals
CER / WERCharacter/word edit distance divided by reference character/word count; define treatment of whitespace and normalization
Reading orderWhether elements appear in correct sequence
Table structure and cell contentRow/column/span relationships, header association and exact values; optionally TEDS for HTML table tree similarity
Critical-field exact matchAmounts, dates, IDs, signs and units; score association as well as text
Coverage and review rateMissing pages/regions and unresolved output; do not hide failures by scoring successful pages only
PerformanceSeconds per page, p50/p95 latency, memory, model/API cost; separate cold, warm and cache-hit runs

For example, in a hypothetical 1,000-character passage, ten substitutions give a 1% CER if there are no other edits. If one substitution changes a price from 12.50 to 12.90, the business field still fails exact match. An average score alone is not enough.

OmniDocBench is a useful reference for evaluating text, tables, formulas and reading order separately; OHR-Bench demonstrates why OCR noise matters downstream in RAG. These benchmarks are not proof of quality on your own documents or languages. Build task-specific tests and choose thresholds based on how costly errors are. Record settings, dataset version and all failure cases. Add complexity only when a controlled comparison shows a useful improvement.

11. Move from the notebook to a real AI application

When the parsed representation is good enough for your task, derive retrieval chunks from it. Keep section headings with their paragraphs, table headers with relevant rows, and figure captions with their figures. Preserve page and element IDs in chunk metadata so a RAG answer can link to evidence. Choose chunk limits using the actual embedding model's tokenizer and measure retrieval quality. Docling documents structure-aware chunking if you want a ready-made starting point. Parsing quality, retrieval quality and answer quality need separate evaluation.

For a service, put conversion behind a bounded worker or queue. Separate upload, parse, review and publication. Keep the original file and content hash, raw artifacts, configuration and versioned results. Enforce file type/size, page and pixel limits, wall-clock timeouts, memory and concurrency budgets; use an isolated non-privileged worker with no unnecessary network access. Office files can expand dramatically when decompressed. Do not expose this teaching script directly as an upload endpoint. The OCRmyPDF security guidance explains why PDFs should not be assumed safe.

Check confidentiality and retention requirements before calling any remote OCR/VLM provider. Treat instructions found inside documents as untrusted data rather than agent commands; sanitize exports and restrict who can access documents and derived artifacts. For performance, cache successful raw artifacts using content and configuration keys, distinguish cache hits from fresh evaluation, and benchmark on the real workload before adding batching or specialized models.

Release checklist: run the gold-set regression tests; confirm every page has a status; review missing or suspicious regions; verify table/critical-field correctness; verify provenance links; measure cost and latency; document unsupported inputs and rollback. Only then index or publish accepted data. These are engineering recommendations, not claims that the teaching example satisfies them.

Start with three documents and a tiny test. Make it work, find the actual bottleneck, fix that bottleneck, and measure again. That's the path from an extraction script to a dependable document parsing pipeline.

Further reading and next exercises

Try a public two-column paper, a Persian scan and a borderless table. For each, save the original, annotate a few expected regions, run two plausible routes and compare text, structure, field correctness and runtime. For a chart or form, add an explicit schema and verify values against the source rather than relying on a generated description.

The examples and proposed architecture are educational and project-independent. The three-page fixture is synthetic, not a benchmark of any commercial or open-source parser. Documentation links describe supported APIs and concepts; tool choices and production design remain application-specific.