title: How to show where an extracted value came from on the page
description: How to highlight the source of an extracted value on a PDF page (field-level citations, also called grounding or provenance): search the text layer with PyMuPDF, use OCR word boxes for scans, or get a box with every value from the extraction itself. Working Python for each.
How to show where an extracted value came from on the page¶
No citation, no trust. A reviewer who can click a value and see it highlighted on the page checks it in a second. One who cannot has to re-read the document, and stops trusting the tool the first time a number is wrong.
There are three ways to get that highlight. Pick by what your documents are.
| Way | Works on | You need | Breaks when |
|---|---|---|---|
| 1. Search the PDF's text layer for the value | born-digital PDFs | PyMuPDF | the value appears twice, is formatted differently from the page ("1575" against "£1,575.00"), or the PDF is a scan |
| 2. Match the value against OCR word boxes | scans and photos | an OCR engine that returns word boxes (Tesseract, |
the OCR misreads the value, or it spans lines |
| 3. Ask the extraction to return the box with the value | anything | an extractor that returns citations | - |
1. Search the text layer (free, born-digital PDFs)¶
import pymupdf # pip install pymupdf
def highlight(pdf_path, value, out_path):
doc = pymupdf.open(pdf_path)
hits = []
for page in doc:
for rect in page.search_for(value): # every place the text appears
page.add_highlight_annot(rect)
hits.append((page.number + 1, rect))
doc.save(out_path)
return hits
print(highlight("invoice.pdf", "£1,575.00", "invoice-highlighted.pdf"))
This is enough for a demo. In production three things go wrong: the same amount is printed in four places and you
highlight all of them, the model returned 1575.0 and the page says £1,575.00, and scanned pages have no text
layer at all.
2. Match against OCR word boxes (scans)¶
Run OCR that returns a box per word, then find the run of words that equals your value. Normalise both sides first (strip currency symbols and thousands separators, compare numbers as numbers). Tesseract, AWS Textract, Azure Document Intelligence and Google Document AI all return word boxes. You still have the duplicate problem: decide which "1,575.00" is the total by looking at the words next to it.
3. Get the box with the value (any document)¶
The reliable way is for the step that extracts the value to also say where it read it. ReadAnyDoc (open source, Apache-2.0) returns a citation for every field of your schema:
import readanydoc
from pydantic import BaseModel
class Invoice(BaseModel):
invoice_number: str
total: float
out = readanydoc.extract("invoice.pdf", schema=Invoice)
for c in out.citations["total"]:
print(c.content, c.confidence, c.bbox)
# £1,575.00 high BoundingBox(page=1, left=0.71, top=0.83, width=0.12, height=0.02)
bbox is in fractions of the page and page counts from 1, so drawing it is one multiplication:
import pymupdf
doc = pymupdf.open("invoice.pdf")
for path, cites in out.citations.items():
for c in cites:
if not c.bbox:
continue # no position found: nothing is invented
page = doc[c.bbox.page - 1]
w, h = page.rect.width, page.rect.height
rect = pymupdf.Rect(c.bbox.left * w, c.bbox.top * h,
(c.bbox.left + c.bbox.width) * w, (c.bbox.top + c.bbox.height) * h)
annot = page.add_rect_annot(rect)
annot.set_colors(stroke=(0, 0.5, 0.3) if c.confidence == "high" else (0.8, 0.5, 0))
annot.update()
doc.save("invoice-cited.pdf")
What you get that the first two ways do not give you:
- The right occurrence. The box is where the value was read, not every place the same text appears.
- Scans, photos and handwriting, with the same code.
- A confidence per value, so the reviewer looks at the
lowones first. - Honest gaps. A value with no locatable source returns an empty list instead of a guessed box.
On our tests the cited box contains the value 94.9% of the time on invoices and 85.5% on credit agreements (checked against the PDF's own words; full table in Benchmarks).
In a web app¶
Send the page image and the boxes to the browser and draw a div per box with left, top, width and height
as percentages of the page image. Fractions of the page map straight onto CSS percentages. On click of a field,
scroll to its page and pulse its box.
Questions¶
What is this called? Field-level citations, grounding, provenance or source highlighting. They all mean: every extracted value points at a place on a page.
Can I get citations from Claude or GPT directly?
The model can quote the text it used, but it does not return coordinates. You still have to find that text on the
page, which is ways 1 and 2 above.
Which tools return a box for every extracted field?
ReadAnyDoc (open source), Reducto, LlamaExtract and the cloud document services for their prebuilt fields. See
how they compare.
Next¶
- Check extracted numbers before you save them
- Citations and confidence: the rules ReadAnyDoc follows
- Two real documents with every citation drawn
- Extract guide