How to extract data from a PDF as JSON: four methods compared

Updated · Tested with Python 3.13, pypdf 7.2.0, PyMuPDF 2.2

In short

There are four ways to turn a PDF's text into named values: patterns that match what surrounds a value, positions on the page, a language model, and rules that a model builds once and tests against sample documents. Patterns and positions are free and repeatable but tied to one layout. A language model handles any layout, costs money per page, and can return values that are not in the document.

Getting the text out of a PDF is the easy half. The harder half is turning a page of text into the handful of values you want, with names. There are four ways to do it, and they differ in what they cost, how often they are wrong, and how they fail.

MethodSetupPer documentSame answer every timeCopes with new layouts
1. Patterns on the textAn hour per kind of documentFreeYesNo
2. PositionsAn hour per kind of documentFreeYesNo
3. A language modelA promptPaid, every timeNot guaranteedYes
4. Rules built and tested from samplesA few samples per kind of documentSmallYesNo, by design

The example throughout is company-extract.pdf, and the goal is this:

JSON
{
  "company_name": "Harbor Lane Logistics Ltd",
  "company_number": "51-482913-6",
  "status": "Active",
  "share_capital": 1250.5
}

1. Patterns on the text

Extract the text, then describe each value by what surrounds it.

Python
import json
import re
from pypdf import PdfReader

text = PdfReader("company-extract.pdf").pages[0].extract_text()

fields = {
    "company_name": re.search(r"Company name (.+)", text).group(1),
    "company_number": re.search(r"Company number ([\d-]+)", text).group(1),
    "status": re.search(r"Status (\w+)", text).group(1),
    "share_capital": float(re.search(r"Share capital ([\d,.]+)", text).group(1).replace(",", "")),
}
print(json.dumps(fields, indent=2))

This prints exactly the JSON above.

Good for: values that follow a label, in documents whose wording is stable. Fails when: the label is reworded, the value wraps onto a second line, or two values share a label. It fails loudly here, since re.search returns None and the next call raises an error; in real code, catch that and report which field was missing.

2. Positions

Describe each value by where it is: inside a rectangle, or to the right of a label.

Python
import pymupdf

with pymupdf.open("company-extract.pdf") as doc:
    page = doc[0]
    label = page.search_for("Company number")[0]
    right_of_label = pymupdf.Rect(label.x1, label.y0 - 2, page.rect.width, label.y1 + 2)
    print(page.get_text("text", clip=right_of_label).strip())
Output
51-482913-6

Good for: forms and tables, where the same label appears more than once or a value has no label at all, and for scans, where OCR text is too noisy for patterns. Fails when: the layout shifts. Fixed rectangles then return the wrong text with no error; measuring from a label, as here, is much safer. Template-based extraction shows both.

3. A language model

Give a model the text, or a picture of the page, with a description of the fields you want, and ask for JSON. There is nothing to set up per kind of document, and it handles layouts nobody prepared for. That is a real strength, and for documents that each look different it is often the only practical method.

What you take on in return:

  • It is not repeatable. The same document can give a different answer on another day or after a model update.
  • It can be wrong plausibly. A model that cannot find a value may supply a likely-looking one. A pattern returns nothing; a model returns something.
  • You pay per page, for ever, and wait seconds instead of milliseconds.
  • Your documents go to the model's provider, which matters for some of them.

Ask for JSON that follows a fixed schema, tell the model to return null when a value is not present, and check every value afterwards. Can ChatGPT extract data from PDFs? goes further.

4. Rules built and tested from samples

The fourth way uses a model where it is strong and rules where they are strong. A model looks at a few sample documents and writes the extraction rules; the rules are then run on every sample and corrected until each value matches; after that, documents are read by the rules alone.

This is how 100sands works, for PDFs and HTML files that contain text. You upload one to five samples, AI suggests the fields and each sample's values, and you check and correct them. AI then sets up the extraction, which goes live only when it returns every value you checked on every sample. Every later document of that kind comes back from one call:

Shell
curl https://api.100sands.com/v1/document-types/42/extract \
  -H "Authorization: Bearer $SANDS_API_KEY" \
  -F [email protected]

The response has this shape:

JSON
{
  "id": "ext_...",
  "documentType": { "id": 42, "name": "Company registry extract" },
  "version": 2,
  "fileName": "company-extract.pdf",
  "pages": 1,
  "createdAt": "2026-12-04T09:30:00Z",
  "fields": {
    "companyName": "Harbor Lane Logistics Ltd",
    "companyNumber": "51-482913-6",
    "status": "Active",
    "registered": "2019-03-14",
    "shareCapital": 1250.5
  }
}

You get the repeatability and the speed of rules without writing them: AI is used at setup, not on every document, and reading a document takes milliseconds a page. A value that is not in the document comes back as null, never a guess. It does not read scans. Like methods 1 and 2, it is for documents that look the same every time; it is not meant for one-off layouts.

Whatever you choose: check the values

The method matters less than what you do with its output.

  • Shape. A company number matches a pattern. A date parses. An amount is a number.
  • Arithmetic. Lines add up to a total; a total minus tax equals the subtotal.
  • Lookup. A supplier's name is in your list of suppliers.
  • Missing is not empty. Decide what null means for each field, and never let a failed extraction pass as a blank.

A wrong value that looks right costs more than a missing one. Build the checks first.

How to choose

  • A few kinds of document, in volume: methods 1, 2 or 4.
  • Hundreds of kinds, a few of each: method 3, with checks.
  • Scans: positions or method 4, after OCR.
  • Money, identity or anything a regulator may ask about: a method that gives the same answer every time and can show where a value came from.

Questions

How do I extract specific data from a PDF in Python?

Extract the text with pypdf, then use a regular expression per value, such as re.search(r"Company number ([\d-]+)", text). For values best found by their place on the page, use PyMuPDF's search_for and read the text to the right of the label.

What is the most reliable way to extract data from PDFs?

For documents that look the same every time, rules: patterns, positions or a tested template. They give the same answer for the same file and fail visibly. Whatever the method, check formats and arithmetic on the output.

Should I use an LLM to extract data from PDFs?

Use one when layouts vary too much to write rules for. Require JSON that follows a schema, allow null for missing values, and verify each value, because a model can return a plausible value that is not on the page.

Try it on your own documents

A free plan every month, no credit card. See the PDF data extraction API.

Start free