pdfmux/blog
pdf-extraction

PDF to JSON for LLM pipelines: structured extraction patterns in 2026

TL;DRPDF to JSON for LLM tool use, function calling, and structured outputs. 3-layer schema, bounding boxes, confidence scoring, and the pdfmux pattern.

Direct answer: Modern LLM pipelines consume JSON, not Markdown — every tool-use call, every function-calling response, every structured-output schema is JSON (see the Anthropic tool-use spec and the MCP specification). pdfmux’s actual JSON output (extract_json() in Python, pdfmux convert --format json from the CLI) is a 2-layer object: whole-document metadata (confidence, page_count, warnings, ocr_pages) plus a pages array with each page’s raw text and whether OCR was applied, plus any auto-detected key_values. There is no block-level schema — no per-block type, no bounding box, no per-block confidence score in the public API. The rest of this post works with that real shape: page-level granularity for tool-use navigation, and a plain-text citation (page number, not a pixel rectangle) for traceability.


Why JSON, not Markdown, for LLM pipelines

A year ago the prevailing pattern was PDF → Markdown → chunk → embed. Markdown is human-readable, easy to chunk on headings, and every LLM parses it natively. We covered that pipeline in detail in PDF to Markdown for RAG pipelines, and it is still the right answer for naive RAG.

But the production AI ecosystem in 2026 has shifted. Most serious LLM applications now use one of three patterns that need JSON:

  1. Tool use / function calling — Claude, GPT-4o, and Gemini all consume tool definitions in JSON Schema and return tool calls as JSON objects. If your extraction layer outputs Markdown, you write a glue layer to parse it back into JSON. Skip the round trip.
  2. Structured outputs / response_format — The OpenAI response_format parameter and Anthropic’s tool-use loop both expect a JSON schema. The model is conditioned to emit valid JSON matching that schema. If your retrieval layer already returns JSON, the model has less work to do and hallucinates less.
  3. Citations — When the user asks “where in the document does it say X?”, you need to point back to a specific page, paragraph, and ideally bounding box. Markdown destroys that information. JSON preserves it natively.

There is also a fourth, quieter reason: agents that read PDFs benefit from page-addressable content. An agent looking for the total on an invoice can go straight to the page with the most key_values hits instead of regex-grepping the entire document. pdfmux doesn’t type its output by block (heading/table/paragraph/figure) — it gives you text per page, plus any key-value pairs it auto-detected — but that’s still structure Markdown alone doesn’t give you.

The real JSON shape

This is the actual output of extract_json() (Python) / pdfmux convert --format json (CLI) — not an idealized schema, the literal keys you get back:

{
  "schema_version": "1.1.0",
  "source": "annual-report.pdf",
  "converter": "pdfmux",
  "extractor": "pymupdf4llm",
  "page_count": 84,
  "confidence": 0.92,
  "error_code": null,
  "warnings": ["Page 73 used OCR fallback"],
  "ocr_pages": [73],
  "content": "# FY2025 Annual Report\n\nNet revenue grew 14%...",
  "pages": [
    {
      "page": 1,
      "text": "# FY2025 Annual Report\n\nNet revenue grew 14% year over year to $4.2 billion...",
      "ocr": false
    }
  ],
  "key_values": [
    {"key": "Net revenue", "value": "$4.2 billion", "page": 1}
  ]
}

Two layers, not three, and no bounding boxes or block types:

  • Document-level fields (confidence, page_count, warnings, ocr_pages) — use these for cache keys, audit logs, and routing decisions. confidence is a single aggregate for the whole document, not per-page or per-block.
  • pages — real per-page text and an ocr flag, so you can address content by page and know which pages pdfmux had to fall back to OCR for.
  • key_values — auto-detected label/value pairs (vendor name, totals, dates — whatever pdfmux’s extractors recognized as a labeled field), each tagged with its page.

There is no blocks array, no block type, no bbox, and no per-block confidence anywhere in the public API — if you need citation-grade bounding boxes or typed content blocks, that’s a gap, not a feature pdfmux ships. The page-level text and key_values are the finest granularity available; treat anything claiming block-level structure as a thing you’d have to build yourself (e.g. with your own heading/table regex over each page’s text) rather than something pdfmux returns.

Generating this JSON from a PDF

The shortest path is the pdfmux CLI:

pip install pdfmux
pdfmux convert annual-report.pdf --format json > extracted.json

From Python:

from pdfmux import extract_json

result = extract_json("annual-report.pdf")

# Filter to high-confidence *pages* for the retrieval index — there's no
# per-block confidence to filter on, only the one document-level score.
pages_to_index = result["pages"] if result["confidence"] >= 0.85 else []

# key_values are already structured — no table object to pull apart
for kv in result["key_values"]:
    print(f"{kv['key']}: {kv['value']} (page {kv['page']})")

From Node, call the same binary via subprocess — the full pattern is in PDF extraction with Node.js.

For why pdfmux specifically produces this output well (vs PyMuPDF directly, marker, or docling), see the 200-PDF benchmark — short version: 0.903 overall, #2 of the 8 engines measured. Note that benchmark score is a whole-document aggregate like the confidence field above, not a per-page or per-block score.

Pattern 1: feeding the JSON to a tool-use loop

This is where the JSON pays off, at page granularity rather than block granularity — pdfmux doesn’t give you block ids, so the unit the model navigates is the page. You define a tool that takes a page number and returns that page’s text. The model decides which pages to read based on a short table of contents and the user’s question.

import anthropic
from pdfmux import extract_json

doc = extract_json("contract.pdf")

# Compact view: page number + first 80 chars of each page
toc = [
    {"page": p["page"], "preview": p["text"][:80]}
    for p in doc["pages"]
]

tools = [{
    "name": "read_page",
    "description": "Read the full text of a page by page number.",
    "input_schema": {
        "type": "object",
        "properties": {"page": {"type": "integer"}},
        "required": ["page"],
    },
}]

client = anthropic.Anthropic()
response = client.messages.create(
    model="claude-opus-4-7",
    max_tokens=2048,
    tools=tools,
    messages=[{
        "role": "user",
        "content": f"Document table of contents (JSON): {toc}\n\nFind the indemnification clause and quote it verbatim."
    }],
)

The model gets a compact table of contents, picks the pages it wants to read, and the tool fetches each page’s full text on demand. For a 100-page contract, the model sees a short preview per page up-front and reads only the pages it selects — vs. dumping the whole document into context. This is coarser than block-level navigation (no way to jump straight to one paragraph within a page), but it’s what the real API gives you.

This pattern is close to how the pdfmux MCP server exposes a document to a tool-using agent — see pdfmux MCP server for Claude, Cursor, Windsurf for the user-facing version.

Pattern 2: structured outputs from a PDF

The other common pattern is “read this PDF and emit JSON matching this schema.” Invoices, lab reports, financial statements, contracts with predictable clauses. The model’s job is to populate a schema, not to write prose. pdfmux has no Python function that maps extraction onto a schema for you — you extract text/key-values, then have the model do the mapping.

schema = {
    "type": "object",
    "properties": {
        "invoice_number": {"type": "string"},
        "issue_date": {"type": "string", "format": "date"},
        "vendor_name": {"type": "string"},
        "line_items": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "description": {"type": "string"},
                    "quantity": {"type": "number"},
                    "unit_price": {"type": "number"},
                    "total": {"type": "number"},
                },
                "required": ["description", "total"],
            },
        },
        "subtotal": {"type": "number"},
        "tax": {"type": "number"},
        "total": {"type": "number"},
    },
    "required": ["invoice_number", "total"],
}

from pdfmux import extract_json

doc = extract_json("invoice-q1-2026.pdf")
# pdfmux already auto-detects simple label/value pairs — give the model a
# head start with those plus the full page text, rather than pretending
# there's a "table"/"paragraph" block type to filter on.
context = {"text": doc["content"], "key_values": doc["key_values"]}

Feed context and schema to the model with a tool-use call constrained to that schema. The model returns a valid JSON object you can validate, store, and audit.

The reason pdfmux’s JSON output still helps here, even without block types: key_values hands the model pre-identified label/value pairs instead of making it find “Total: $5,238.00” inside a wall of Markdown from scratch. It still has to do the table-row-to-schema-field mapping itself — pdfmux doesn’t do that part for you.

For the deep dive on invoice schemas specifically, see PDF invoice extraction in Python which uses an identical structured-output approach.

Pattern 3: citation-aware retrieval

The third pattern would, ideally, point back to a bounding box on the source page. pdfmux’s public API doesn’t give you one — there’s no bbox field anywhere in extract_json()’s output. What it does give you is a page number, which gets you most of the way: a citation that says “page 14” rather than one that highlights a specific rectangle.

# Page-level citation — no bounding box available from pdfmux
def answer_with_citation(question, doc_json):
    # 1. Embed each page's text, find the best-matching page(s)
    matches = retrieve(question, doc_json["pages"], top_k=3)

    # 2. Generate answer with citations as page numbers
    answer = generate_answer(question, matches)

    # 3. Citations point to a page, not a pixel rectangle
    citations = [{"page": m["page"]} for m in matches]
    return {"answer": answer, "citations": citations}

The frontend can render the source PDF page and tell the user which page the answer came from, but it can’t draw a highlight rectangle without computing one itself (e.g. by re-searching the rendered page image for the matched text with a separate OCR/layout tool) — pdfmux doesn’t hand you that coordinate. For regulated industries that need pixel-level citation, that’s a gap to plan around, not a pdfmux feature to rely on.

When NOT to use this 3-layer JSON

A few cases where Markdown is still the right intermediate:

  • Tiny documents, single-shot summarization. A 2-page memo going into a single LLM call — dump it as Markdown, done. The JSON overhead is wasted.
  • Naive RAG with semantic chunking on heading boundaries. If your pipeline is chunk on H2 → embed → top-k retrieve → stuff into context, Markdown is more compact and the JSON metadata is unused.
  • Pure summarization with no citations needed. If the deliverable is “write a one-page summary of this report” and the user does not need to verify, Markdown is faster end-to-end.

The flip happens the moment you add tools, structured outputs, or citations. Once any of those three are in the system, the JSON layer pays for itself.

A note on token cost

A common worry: “won’t JSON be 2-3x more tokens than Markdown?” Yes — the verbose version is. But you almost never feed the entire JSON to the model. You feed:

  • The document-level fields (one paragraph, maybe 200 tokens)
  • A compact page table-of-contents (page number + 80-char preview = ~25 tokens per page)
  • Only the pages the model selects via tools, on demand

For a 100-page document, that is 200 + (25 × 100) = ~2,700 tokens of TOC, and the model typically reads 3-8 full pages = ~4,000 additional tokens. Total ~6,700 tokens vs. ~70,000 tokens if you dump the whole Markdown document. Page granularity reads more pages per lookup than block granularity would, but it’s still a large reduction over dumping everything.

The JSON pattern is cheaper, not more expensive, for any document above 20 pages. This is why we recommend it for production. For more on cost-aware extraction pipeline design, see PDF data extraction for AI agents.

The shortest path

If you are designing a new pipeline today:

# 1. Extract once, write JSON
pdfmux convert document.pdf --format json > document.json
# 2. From your app — Python
import json

doc = json.load(open("document.json"))
# Gate on doc["confidence"] (one aggregate score — no per-page or per-block score)
# Feed doc["warnings"] + a page-number/preview table of contents to the model
# Use tool-use to let the model navigate pages on demand (see Pattern 1 above)

Two steps. The first replaces a custom Python script. The second replaces ad-hoc Markdown chunking. The result is a pipeline that supports tool use and structured outputs at page granularity without writing an extraction layer from scratch — citations land on a page number, not a bounding box, which is the real ceiling of what pdfmux’s public API gives you.

For the wider design context — when to extract synchronously vs. queue, how to cache extractions, how to handle reprocessing when the extractor improves — see PDF data extraction for AI agents and PDF extraction for RAG pipelines.