AI Agents for Lawyers

Playbooks

Extract Data from PDFs and Scans with AI: Contracts, Invoices and Court Files

How lawyers extract data from PDFs and scans with AI: OCR first, a fixed schema, a full lease-extraction prompt, batch runs in Cowork or n8n, and sampling.

By Dr. Niklas SchmidtUpdated 13 November 202611 min read
On this page
  1. Where AI extraction is reliable, and where it is not
  2. The worked example: 50 commercial leases into one spreadsheet
  3. Scans, tables and handwriting: OCR first, vision second
  4. Batch processing: Cowork, Claude Code or n8n
  5. Accuracy checks and sampling
  6. Confidentiality: which tool may see the file
  7. Invoices and court files: what changes
  8. A setup that works this week

AI can pull parties, dates, rent, break options and liability caps out of PDFs and scans into a spreadsheet for a few dollars of tokens, and extraction is one of the four tasks where Vals.ai's 2025 testing found legal AI beating lawyers. The catch is scans, tables and handwriting, which need an OCR pass, a fixed schema and a sampling check before anyone relies on the numbers.

Where AI extraction is reliable, and where it is not

The Vals.ai VLAIR study of 27 February 2025 put Harvey, CoCounsel, Vincent AI and Oliver against a lawyer control group on seven tasks. The AI tools won four, document extraction among them, alongside Q&A, summarisation and transcript analysis; lawyers won redlining and EDGAR research; chronology tied (summary by Good Journey Consulting). The vendors have since built on that strength at scale: Harvey reported more than 20 million terms extracted through its Agent Builder, with Ashurst saying a lease-summary workflow "saves hours" (Harvey, 9 Mar 2026), and Thomson Reuters' next-generation CoCounsel Legal runs Tabular Analysis across 10,000 documents and 100 questions (Thomson Reuters, 20 Aug 2026).

Benchmarks run on clean inputs. Real files arrive as thirty-year-old leases scanned at an angle, invoices with line-item tables, and court bundles mixing pleadings, exhibits and handwritten notes; reliability depends on the input more than the model.

Input typeReliability as of Sep 2026What to do
Native PDF with a text layer (most modern contracts)High for parties, dates, defined amountsDirect extraction against a fixed schema
Clean printed scanHigh after OCR; vision-only acceptable for short documentsOCR first for anything a client will rely on
Poor scan, fax, skewed or faded pagesMediumOCR plus vision cross-check; every low-confidence field flagged
Tables (rent schedules, invoice lines, cap tables)Medium; columns drift across page breaksAsk for row-by-row output with page references; recompute totals
Handwriting (margin notes, signatures, court stamps, dates)LowRoute to a person; never let the model guess
Mixed court bundlesVariableSplit into documents and classify before extracting anything

The worked example: 50 commercial leases into one spreadsheet

A client wants a rent-roll style summary of its 50 leases by Friday. The manual route is an associate and two days; the AI route is a schema, a prompt and an afternoon, most of it checking. Define the fields before opening a file, because a schema written after reading three leases will be shaped by those three leases.

FieldFormatRule
Landlord, tenant, guarantorNames as writtenGuarantor null if none
PremisesAddress as writtenNo normalisation
Commencement and expiry datesISO 8601 (YYYY-MM-DD)Both required; term in months derived and checked
Annual rent and currencyNumber plus ISO currency codeExclusive of VAT unless the lease says otherwise; flag if unclear
Rent reviewType (open market, index-linked, fixed uplift, none) plus datesDates as a list
Break optionParty, date, notice months, conditionsNull if none; conditions verbatim
Assignment and sublettingVerbatim consent standardFor example "not to be unreasonably withheld"
Repair obligationFull repairing, internal only, otherQuote the operative words
DepositNumber or nullFlag if held by a third party
Governing lawJurisdictionFlag if absent

The prompt that produces one row per lease:

Role: You are extracting data from one commercial lease for a legal team.
Work only from the document text provided. Do not use outside knowledge.

Task: Return a single JSON object with the fields below. For every field give:
  "value"        - the extracted value, normalised as instructed
  "quote"        - the verbatim words from the lease that support it (max 40 words)
  "page"         - the page number where the quote appears
  "needs_review" - true if the value is illegible, ambiguous, absent, or appears
                   in more than one place with different content

Fields:
  landlord, tenant, guarantor (null if none)
  premises (address as written)
  commencement_date, expiry_date (YYYY-MM-DD); term_months (integer)
  annual_rent (number); rent_currency (ISO code)
  rent_review_type (open market / index-linked / fixed uplift / none); rent_review_dates (list)
  break_option: { party, date, notice_months, conditions }
  permitted_use
  assignment_consent_standard (verbatim phrase)
  repair_obligation (full repairing / internal only / other)
  deposit_amount (number or null)
  governing_law

Rules:
  If a value cannot be read with confidence, set "value" to null and
  "needs_review" to true. Never guess a number or a date.
  If the file contains a side letter or deed of variation, extract from the
  latest document and set "needs_review" to true on every field it changes.
  Do not summarise. Do not add fields. Output JSON only.

The workflow:

  1. Sort the 50 files into text-layer PDFs and scans; any PDF tool's "select text" test does this in seconds.
  2. OCR the scans (see the next section) and keep the OCR text next to the original.
  3. Run the prompt one lease per call. A 1M-token context window would hold all 50, but one document per call gives clean page references, isolates errors and makes reruns cheap.
  4. Collect the JSON objects into one file and convert to CSV or XLSX; a spreadsheet column per field, plus a hidden column per field for the quote and page.
  5. Run the automated checks in the accuracy section, then the human sample.
  6. Freeze the sheet, and record the model name, version, date and prompt version on a cover tab.

Rough arithmetic on cost: a 40-page lease runs to perhaps 15,000–20,000 words; at Anthropic's stated ratio of about 555,000 words per million tokens that is roughly 30,000–36,000 input tokens each, or 1.5–1.8 million tokens for all 50. At September 2026 API prices, Claude Sonnet 5 ($2 per million input tokens) costs under $4 for the input, Opus 5 ($5) under $10, and the JSON output adds cents.

Scans, tables and handwriting: OCR first, vision second

Claude and ChatGPT both read scanned pages by vision, and for a short document that is fine. For anything with consequences, the advice from practitioners who have compared the tools on financial documents is to run a dedicated OCR pass first (Tesseract or a commercial engine), feed the text, and use vision only as a cross-check. The same comparison reported ChatGPT's OCR as more accurate on poor scans and Claude as more likely to say "illegible" than to invent a number (CounselPro, 2026; see also Spellbook's guide to Claude for document analysis). Treat that as reported behaviour rather than a guarantee, but note which behaviour you want: for extraction, "illegible" is the right answer and a confident wrong number the worst one, which is why the prompt above makes null-plus-flag the default.

Tables need two extra rules. Ask for row-by-row output with the page number on every row, because a rent schedule that crosses a page break is where columns silently shift. Then recompute anything that can be recomputed: monthly rent times twelve against the stated annual figure, line items against the invoice total, term in months against the two dates.

Handwriting gets no automation beyond detection. Ask the model to report where handwritten content appears and route those pages to a person; a manuscript amendment to a rent figure or a court stamp date is the kind of thing that decides a dispute, and it is what vision models read worst.

Batch processing: Cowork, Claude Code or n8n

Fifty files can be dragged into a chat one at a time. Five hundred cannot, and a recurring stream such as supplier invoices needs a pipeline.

RouteWhat it isGood forWatch out
Claude Cowork (merged into the Claude app on 17 Sep 2026)Desktop agent with sandboxed file and shell access20–200 files in a folder, no code, one-off jobsGive it a copy of the folder, never the originals
Claude CodeTerminal agent that writes and runs a script looping over files and calling the APIRepeatable jobs, hundreds of files, schema changes between runsNeeds an API key on business terms; the script must write to a new folder
n8n, self-hostedNo-code workflow: watched folder, OCR node, model call, spreadsheet rowOngoing intake such as invoices and post; EU-hosted or on-premiseSomeone has to maintain the server
Vendor grids (CoCounsel Tabular Analysis, Legora Tabular Review, Harvey)Built-in extraction tables with per-cell citationsVery large sets, diligence-grade audit trailSeat pricing; check retention terms

The Cowork warning is not theoretical. In February 2026 a venture capitalist let Cowork "organise" a desktop, approved a step to delete temporary files, and an rm -rf removed fifteen years of family photos, recovered only through an iCloud rollback; his conclusion was "Don't let Claude Cowork into your actual file system" (Futurism, Feb 2026). For extraction that means one rule: the agent works on a copy, in a folder that contains nothing else. More in Claude Cowork for lawyers.

Claude Code is the better route once a job repeats, because the output is a script the firm keeps. Clifford Chance senior associate Jamie Tso prototyped a signature-page extractor and a side-letter tabulator for roughly nothing, with a method worth copying: pick one daily pain point, write the spec before asking for code, and prototype only on synthetic files, never client data (Tso, 6 Jan 2026). Whether a non-programmer should touch a coding agent is discussed in Claude Code for lawyers.

For a standing pipeline, the reference case is a three-lawyer German employment and tenancy firm running self-hosted n8n with Nextcloud, local OCR and a local model on a German server for EUR 20–30 a month, with no client data leaving the country. After six months, mail sorting fell from two hours a day to forty minutes and file creation from 15–40 minutes to a five-minute check; the setup needs a § 43e BRAO contract and an Art. 28 GDPR processing agreement (Lyron AI case study, spring 2026). The build pattern is in n8n for law firms.

Accuracy checks and sampling

Extraction errors are quiet; nobody notices a wrong break date until the notice window has passed. The controls below are cheap because the prompt already produces what they need.

CheckHowThreshold
Quote matchScript confirms each "quote" string appears in the source text100% automated; any miss is a hallucinated value
CompletenessCount nulls per columnAny column above 10% null means the prompt or OCR needs work
ArithmeticRecompute term, rent multiples, invoice totals100% automated; mismatches go to a person
Duplicates and conflictsSame field found twice with different contentAlready flagged by needs_review; all go to a person
Human sampleEvery field in the first five documents; then a 20% random sample; plus every flagged fieldZero material errors in the sample, or widen to 100%
Second-model checkRe-run 10% of documents with a different model and diff the JSONAny disagreement goes to a person

The quote-match check is the one that catches a hallucination: a value whose quote does not exist in the document was made up, and a script finds it without anyone reading the lease. It is the principle behind the "every cell cited" design of the tabular diligence skill in Anthropic's open-source Claude for Legal corporate plugin.

Two calibration notes. Harvey's Legal Agent Benchmark run of 26 May 2026 found that verify-and-revise behaviour scored 1.5 points higher and drafting without review cost 1.2 points, so build the check into the loop rather than after it (Harvey, May 2026). And Anthropic's notes for Claude Opus 5 (24 Jul 2026) say the model now "verifies its own work without being told to", so 2025-era prompts that bolt on a final verification step can cause over-verification (Anthropic docs, Jul 2026). Test the prompt on the current model, not the one you wrote it for.

Confidentiality: which tool may see the file

Extraction means uploading whole documents, often a client's most sensitive ones, and the tier matters more than the vendor.

  • Consumer tiers of ChatGPT, Claude and Gemini train on content unless the user opts out, and OpenAI keeps consumer content 30 days even after opt-out (Sonomos, verified 1 Sep 2026). Step-by-step toggles are in AI privacy settings for lawyers.
  • Google's own page for consumer Gemini says activity is kept 18 months by default, a subset of chats is read by human reviewers, and: "Please don't enter confidential information that you wouldn't want a reviewer to see" (Google, updated 10 Aug 2026).
  • Consumer Copilot runs without a data processing agreement and is described as "not suitable for confidential or legal work"; Microsoft 365 Copilot runs under the DPA and does not train on prompts (Spellbook, 20 Jun 2026).
  • Claude Team, Enterprise and API content is never used for training, and API content is not retained by default, with one exception that matters for batch jobs: the Covered Models, Claude Fable 5 and 5.1, require 30-day retention and are not eligible for zero data retention without express authorisation as of September 2026 (Anthropic docs). For extraction under a ZDR arrangement, use Opus 5 or Sonnet 5.
  • The UK Upper Tribunal in UK v SSHD [2026] UKUT 81 (IAC) said pasting client letters into public AI tools puts them "in the public domain". BRAK's December 2024 guidance treats tools that store or forward client data for training as a breach of § 43a Abs. 2 BRAO; ÖRAK requires client data to stay on EU servers.

The tier-by-tier table is in the confidentiality checklist for lawyers. The short version: business or API terms, a signed processing agreement, ZDR where available, and for German and Austrian firms an EU-hosted service or the self-hosted route above.

Invoices and court files: what changes

Invoices are the easy case and the most repetitive one. The schema is short (supplier, invoice number, date, due date, net, VAT, gross, line items), the arithmetic check is decisive, and the volume justifies an n8n watched folder feeding a spreadsheet or the practice management system.

Court files are the hard case. A bundle is many documents in one PDF, so the first pass is classification, not extraction: split at document boundaries, label each part (pleading, order, exhibit, correspondence, handwritten note), and only then run a schema per document type. Stamp dates and handwritten endorsements go to a person. For a single matter's bundle the split-classify-extract sequence in a Cowork or Claude Code session is enough; the review platforms covered in AI in e-discovery exist for the largest sets. The extraction log is itself a record: Anthropic's Compliance API keeps session transcripts for six years by default, and a New York federal court's order treating 20 million de-identified ChatGPT logs as discoverable evidence (affirmed 5 Jan 2026) shows such logs can be asked for.

A setup that works this week

  1. Pick one document family with a real deadline, leases or invoices, and write the schema before touching a file.
  2. Use the prompt above, adjusted to your fields, on business or API terms; sort scans from text PDFs and OCR the scans.
  3. Run one document per call from a copy folder, collect JSON, convert to a sheet with hidden quote and page columns.
  4. Run the quote-match and arithmetic checks by script, then the five-plus-20% human sample.
  5. Save the prompt, the model version and the sample results with the deliverable, so the next run starts from a known baseline.

Module 3 of the AI Lab for Lawyers course covers multimodal AI and file handling, which is where this scan-to-spreadsheet routine belongs in a lawyer's training. For the diligence-scale version of the same technique, see AI due diligence.

Frequently asked questions

Can AI accurately extract data from scanned PDFs?

Yes for clean printed scans once a dedicated OCR pass has produced a text layer, and with lower confidence for poor scans, faxes and skewed pages. Claude and ChatGPT can read scans directly by vision, but for anything a client will rely on run OCR first, feed the text, and instruct the model to return null and flag the field rather than guess an illegible number.

What is the best AI for extracting data from contracts into a spreadsheet?

For a one-off batch of tens of documents, any current frontier model on business or API terms with a fixed JSON schema works; Claude Sonnet 5 or Opus 5 via the API keeps zero-data-retention available. For thousands of documents with per-cell citations, vendor grids such as CoCounsel Tabular Analysis, Legora Tabular Review or Harvey are built for it, at seat prices.

How do I check AI-extracted data for errors?

Require a verbatim quote and page number for every value so a script can confirm the quote exists in the source. Recompute anything arithmetic, such as rent over term or invoice totals. Then have a person check every field in the first five documents, a 20% random sample of the rest and every field the model flagged for review, widening to 100% if the sample turns up a material error.

Is it safe to upload client PDFs to ChatGPT or Gemini for extraction?

Not on consumer tiers. Free, Plus and Pro ChatGPT accounts train on content unless the user opts out, and Google says a subset of consumer Gemini chats is read by human reviewers. A UK Upper Tribunal decision in 2026 described pasting client letters into public AI tools as putting them in the public domain. Use Team, Enterprise or API terms with a data processing agreement, and EU-hosted or local tools where bar rules require it.

Put this into practice

AI Lab for Lawyers: a live, hands-on course for practising lawyers

4 live sessions (8 hours), recordings included, taught by Dr. Niklas Schmidt of Wolf Theiss. Rated 4.7/5 from 381 ratings; alumni from Norton Rose Fulbright, Paul Hastings, Pillsbury and Taylor Wessing.

Reserve a seat · €200 Maven money-back guarantee · certificate of completion