Build a Legal Exhibit from the Citations in a Memo
Find each quoted passage in the source documents, collect the cited pages into one PDF, link each citation to its exhibit page, and flag quotes with multiple matches.
A legal memo quotes contracts, emails and other records. Before it goes out, someone has to find every quoted passage in the source documents, pull the cited pages into an exhibit, and check that each quote says what the memo claims, exactly once.
This notebook does that with PyMuPDF:
- Extract each quotation and its source from the memo.
- Find every place the quote appears in the source documents, and flag quotes with multiple matches or none.
- Collect the cited pages into one PDF, with a slip sheet and a label for each exhibit and the quoted passages highlighted.
- Link each citation in the memo to its exhibit page, and add a citation index for the reviewer.
Quotes are located with locate() from the PyMuPDF grounding skill. Tested with PyMuPDF 2.2.
%pip install -q pymupdfLoad the grounding skill
locate() lives in scripts/grounding.py. It finds a quote even when the page breaks it across lines or hyphenates it. If you run this notebook inside a clone of the cookbook repository, the local copy is used; otherwise it is downloaded from GitHub.
import os
import sys
import urllib.request
LOCAL = "../skills/grounding-skill/scripts/grounding.py"
URL = "https://raw.githubusercontent.com/pymupdf/cookbook/main/skills/grounding-skill/scripts/grounding.py"
if os.path.exists(LOCAL):
sys.path.insert(0, os.path.dirname(LOCAL))
else:
urllib.request.urlretrieve(URL, "grounding.py")
from grounding import locateSample documents
Two sources, a four-page supply agreement and a two-page email, and a one-page memo that quotes them. All names are fictional. The memo cites each quote with the source's short name in parentheses, for example "..." (Agreement).
Some problems are planted: one boilerplate sentence appears twice in the agreement, one quote appears in both the agreement and the email, and one quote is not in any source. Replace these files with your own memo and sources; they need a text layer.
import pymupdf
def make_pdf(path, pages):
"""Write a simple PDF with one block of text per page."""
doc = pymupdf.open()
for text in pages:
page = doc.new_page()
rc = page.insert_textbox(pymupdf.Rect(72, 72, 523, 770), text, fontsize=11, fontname="helv")
assert rc >= 0, f"text does not fit on a page of {path}"
doc.save(path)
make_pdf("agreement.pdf", [
"""MASTER SUPPLY AGREEMENT
This Master Supply Agreement (the "Agreement") is made between Northwind Components Ltd. ("Supplier") and Halden Robotics Inc. ("Buyer").
1. Definitions
1.1 "Products" means the servo motor assemblies listed in Schedule A.
1.2 "Purchase Order Date" means the date on which Buyer issues a Purchase Order.
1.3 "Delivery Date" means the date by which Products must be delivered under section 2.3.""",
"""2. Orders and Delivery
2.1 Buyer may order Products by issuing a written Purchase Order.
2.2 Supplier shall confirm each Purchase Order within five (5) business days.
2.3 Supplier shall deliver all Products within forty-five (45) days of the Purchase Order Date.
2.4 Time is of the essence with respect to all delivery obligations under this Agreement.""",
"""3. Price and Payment
3.1 Buyer shall pay each invoice within thirty (30) days of receipt.
4. Late Delivery
4.1 If Supplier fails to deliver Products by the Delivery Date, Buyer may cancel the affected Purchase Order without liability and recover any amounts prepaid.
4.2 Supplier shall notify Buyer promptly of any expected delay and propose a revised Delivery Date.""",
"""12. General
12.1 This Agreement is governed by the laws of the State of Delaware.
12.2 Notices under this Agreement must be given in writing.
12.3 Time is of the essence with respect to all delivery obligations under this Agreement.
12.4 This Agreement is the entire agreement between the parties.""",
])
make_pdf("hart_email.pdf", [
"""From: Dana Hart, Procurement, Halden Robotics
To: Order Desk, Northwind Components
Date: 14 March 2026
Subject: Purchase Order 4471
Purchase Order 4471 was issued on 15 January 2026. The forty-five day delivery period ended on 1 March 2026, and the shipment has not arrived and no revised date has been provided.
Under section 4.1 of the Agreement, if Supplier fails to deliver Products by the Delivery Date, Buyer may cancel the affected Purchase Order without liability and recover any amounts prepaid.""",
"""Accordingly, we are cancelling Purchase Order 4471 effective immediately. Please refund the prepayment of $84,000 within ten business days.
Regards,
Dana Hart""",
])
make_pdf("memo.pdf", [
"""MEMORANDUM
To: Litigation team
From: Associate
Date: 20 March 2026
Re: Halden Robotics v. Northwind Components, cancellation of Purchase Order 4471
1. The delivery deadline. The Agreement requires that Supplier "shall deliver all Products within forty-five (45) days of the Purchase Order Date" (Agreement). It adds that "Time is of the essence with respect to all delivery obligations under this Agreement" (Agreement).
2. The right to cancel. If a delivery is late, "Buyer may cancel the affected Purchase Order without liability and recover any amounts prepaid" (Agreement).
3. Notice of cancellation. Halden's procurement lead wrote that "the shipment has not arrived and no revised date has been provided" (Hart Email). She then confirmed that "we are cancelling Purchase Order 4471 effective immediately" (Hart Email).
4. Northwind's position. Northwind is expected to argue that it had "sixty (60) days to deliver" (Agreement).""",
])
SOURCES = {"Agreement": "agreement.pdf", "Hart Email": "hart_email.pdf"}
memo = pymupdf.open("memo.pdf")
docs = {name: pymupdf.open(path) for name, path in SOURCES.items()}Step 1: Extract the citations from the memo
A citation here is a quotation in double quotes followed by a source name in parentheses. The page text is joined into one line first, so a quote that wraps onto the next line is still read whole. Adapt the pattern to your firm's citation style, for example (Agreement § 2.3) or (Ex. 4 at 12).
import re
CITE = re.compile(r'"([^"]+)"\s*\(([^)]+)\)')
def extract_citations(memo):
"""Quoted passages followed by a source name in parentheses, in memo order."""
citations = []
for page in memo:
text = " ".join(page.get_text().split())
for m in CITE.finditer(text):
citations.append({"n": len(citations) + 1, "quote": m.group(1),
"source": m.group(2), "memo_page": page.number})
return citations
citations = extract_citations(memo)
for c in citations:
print(f'{c["n"]}. ({c["source"]}) "{c["quote"]}"')1. (Agreement) "shall deliver all Products within forty-five (45) days of the Purchase Order Date" 2. (Agreement) "Time is of the essence with respect to all delivery obligations under this Agreement" 3. (Agreement) "Buyer may cancel the affected Purchase Order without liability and recover any amounts prepaid" 4. (Hart Email) "the shipment has not arrived and no revised date has been provided" 5. (Hart Email) "we are cancelling Purchase Order 4471 effective immediately" 6. (Agreement) "sixty (60) days to deliver"
Step 2: Find every match
For an exhibit, finding the quote once is not enough. If the same words appear twice, the memo's citation is ambiguous: the reviewer has to decide which passage is meant, and the pin cite may point to the wrong one. So every page of every source is searched, and the matches are counted.
Each citation gets one status:
- ok: exactly one match, in the cited source.
- multiple matches: the quote appears more than once, on one page or across pages or documents. It is linked to the first match in the cited source and flagged for review.
- wrong source: the quote exists, but not in the source the memo names.
- not found: the quote is in no source. It may be misquoted or paraphrased.
def count_on_page(page, quote):
"""How many times the quote occurs in the page text, ignoring case and line breaks."""
flags = pymupdf.TEXTFLAGS_TEXT | pymupdf.TEXT_DEHYPHENATE
text = " ".join(page.get_text(flags=flags).split()).lower()
return text.count(" ".join(quote.split()).lower())
def find_everywhere(docs, quote):
"""Every page in every source where the quote appears, with its quads and match count."""
hits = []
for source, doc in docs.items():
for page in doc:
quads = locate(page, quote)
if quads:
hits.append({"source": source, "page": page.number, "quads": quads,
"count": max(1, count_on_page(page, quote))})
return hits
def check(citation, docs):
"""Find a citation's quote and give it a status; 'hit' is the match the exhibit will use."""
hits = find_everywhere(docs, citation["quote"])
in_cited = [h for h in hits if h["source"] == citation["source"]]
matches = sum(h["count"] for h in hits)
if not hits:
status = "not found"
elif not in_cited:
status = "wrong source"
elif matches > 1:
status = "multiple matches"
else:
status = "ok"
hit = (in_cited or hits or [None])[0]
return {**citation, "hits": hits, "matches": matches, "hit": hit, "status": status}
def found_at(c):
"""Where a quote was found, e.g. 'Agreement p.2, Agreement p.4'."""
return ", ".join(f'{h["source"]} p.{h["page"] + 1}' + (f' (x{h["count"]})' if h["count"] > 1 else "")
for h in c["hits"]) or "-"
citations = [check(c, docs) for c in citations]
for c in citations:
print(f'{c["n"]} {c["status"]:17} {found_at(c):38} {c["quote"][:45]}')1 ok Agreement p.2 shall deliver all Products within forty-five 2 multiple matches Agreement p.2, Agreement p.4 Time is of the essence with respect to all de 3 multiple matches Agreement p.3, Hart Email p.1 Buyer may cancel the affected Purchase Order 4 ok Hart Email p.1 the shipment has not arrived and no revised d 5 ok Hart Email p.2 we are cancelling Purchase Order 4471 effecti 6 not found - sixty (60) days to deliver
Three quotes are clean. The "time is of the essence" sentence appears in both section 2.4 and section 12.3 of the agreement, and the right-to-cancel quote appears in the agreement and again in the email that quotes it; both are flagged as multiple matches. The "sixty (60) days" quote is in no source: the agreement says forty-five.
Step 3: Collect the cited pages into one PDF
Each cited source becomes one exhibit, lettered in the order the memo first cites it. An exhibit holds only the pages that are cited, in page order, behind a slip sheet. Every exhibit page gets a label such as EXHIBIT A-2, a footer naming the source page, and a link back to the memo.
The memo goes first in the same file, followed by a page for the citation index, so that every link stays inside one PDF and works in any viewer. The original memo and sources are not changed.
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
BLUE, RED, GREY = (0, 0.25, 0.75), (0.8, 0, 0), (0.4, 0.4, 0.4)
def assign_exhibits(citations):
"""One exhibit per cited source, lettered in order of first citation, with the pages it needs."""
exhibits = {}
for c in citations:
if c["hit"]:
ex = exhibits.setdefault(c["hit"]["source"], {"letter": LETTERS[len(exhibits)], "pages": set()})
ex["pages"].add(c["hit"]["page"])
return exhibits
def link(page, rect, target, y=0):
"""An internal link from rect to a page of the same PDF."""
page.insert_link({"kind": pymupdf.LINK_GOTO, "from": rect, "page": target,
"to": pymupdf.Point(0, y), "zoom": 0})
def slip_sheet(page, letter, source, n_pages):
page.insert_text((72, 380), f"EXHIBIT {letter}", fontsize=40, fontname="hebo")
page.insert_text((72, 415), source, fontsize=16)
s = "s" if n_pages != 1 else ""
page.insert_text((72, 440), f"{n_pages} cited page{s} from {SOURCES[source]}", fontsize=11, color=GREY)
def stamp(page, label, source, pno):
"""Exhibit label at the top right; source page and a link back to the memo in the footer."""
w, h = page.rect.width, page.rect.height
tag = f"EXHIBIT {label}"
tw = pymupdf.get_text_length(tag, fontname="hebo", fontsize=10)
box = pymupdf.Rect(w - 48 - tw, 24, w - 36, 44)
page.draw_rect(box, color=BLUE, width=1)
page.insert_text((box.x0 + 6, box.y1 - 6), tag, fontsize=10, fontname="hebo", color=BLUE)
page.insert_text((36, h - 24), f"{source}: page {pno + 1} of {SOURCES[source]}", fontsize=8, color=GREY)
back = "Back to memo"
bw = pymupdf.get_text_length(back, fontname="helv", fontsize=8)
page.insert_text((w - 36 - bw, h - 24), back, fontsize=8, color=BLUE)
link(page, pymupdf.Rect(w - 36 - bw, h - 34, w - 36, h - 20), 0)
def build_bundle(memo, docs, exhibits):
"""Memo, a page for the citation index, then each exhibit: a slip sheet and its cited pages."""
bundle = pymupdf.open()
bundle.insert_pdf(memo)
index_page = bundle.new_page().number # filled in step 5
toc = [[1, "Memo", 1], [1, "Citation index", index_page + 1]]
where = {} # (source, page) -> (bundle page, label)
for source, ex in exhibits.items():
slip = bundle.new_page()
slip_sheet(slip, ex["letter"], source, len(ex["pages"]))
toc.append([1, f'Exhibit {ex["letter"]}: {source}', slip.number + 1])
for i, pno in enumerate(sorted(ex["pages"]), start=1):
bundle.insert_pdf(docs[source], from_page=pno, to_page=pno)
target = bundle.page_count - 1
label = f'{ex["letter"]}-{i}'
where[(source, pno)] = (target, label)
stamp(bundle[target], label, source, pno)
toc.append([2, f"{label}: {source}, page {pno + 1}", target + 1])
bundle.set_toc(toc)
return bundle, index_page, where
exhibits = assign_exhibits(citations)
bundle, index_page, where = build_bundle(memo, docs, exhibits)
for (source, pno), (target, label) in where.items():
print(f"Exhibit {label}: {source} page {pno + 1} -> bundle page {target + 1}")Exhibit A-1: Agreement page 2 -> bundle page 4 Exhibit A-2: Agreement page 3 -> bundle page 5 Exhibit B-1: Hart Email page 1 -> bundle page 7 Exhibit B-2: Hart Email page 2 -> bundle page 8
Step 4: Link each citation to its exhibit page
In the memo, each found quote is underlined in blue and becomes a link that opens the exhibit page at the quoted passage, which is highlighted. The exhibit label is written in the right margin. Flagged citations also get a red margin note, and the underline's pop-up note says what to check. A quote that is not found gets a red squiggly underline and no link.
FLAG = {"multiple matches": lambda c: f'{c["matches"]} matches', "wrong source": lambda c: "wrong source",
"not found": lambda c: "NOT FOUND"}
def margin_label(page, y, text, color, used, target=None):
"""Write a short label in the right margin, below any label already on that line."""
while any(abs(y - u) < 9 for u in used):
y += 9
used.append(y)
x = page.rect.width - 66
page.insert_text((x, y), text, fontsize=7.5, color=color)
if target is not None:
link(page, pymupdf.Rect(x, y - 8, x + 60, y + 2), target)
def explain(c):
if c["status"] == "not found":
return f'Not found in any source document. Check the quote against {c["source"]}.'
linked = f'Linked to {c["hit"]["source"]} p.{c["hit"]["page"] + 1} (Exhibit {c["exhibit"]}).'
if c["status"] == "wrong source":
return f'Not in {c["source"]}; found in {found_at(c)}. {linked}'
if c["status"] == "multiple matches":
return f'Quote appears {c["matches"]} times: {found_at(c)}. {linked} Check which passage is meant.'
return linked
def link_citations(bundle, citations, where):
used = {} # memo page -> y positions of margin labels
for c in citations:
page = bundle[c["memo_page"]]
rects = page.search_for(c["quote"])
labels_here = used.setdefault(page.number, [])
if c["hit"]:
h = c["hit"]
c["target"], c["exhibit"] = where[(h["source"], h["page"])]
y = max(0, h["quads"][0].rect.y0 - 36)
for r in rects:
link(page, r, c["target"], y)
annot = page.add_underline_annot(rects)
annot.set_colors(stroke=BLUE)
margin_label(page, rects[-1].y1 - 2, f'Ex. {c["exhibit"]}', BLUE, labels_here, c["target"])
ex_page = bundle[c["target"]]
ex_annot = ex_page.add_highlight_annot(h["quads"]) # the passage on the exhibit page
ex_annot.set_info(content=f'Memo citation {c["n"]}')
ex_annot.update()
else:
annot = page.add_squiggly_annot(rects)
annot.set_colors(stroke=RED)
if c["status"] != "ok":
margin_label(page, rects[-1].y1 - 2, FLAG[c["status"]](c), RED, labels_here)
annot.set_info(content=f'Citation {c["n"]}: {explain(c)}')
annot.update()
link_citations(bundle, citations, where)Step 5: Add the citation index and save
The page after the memo lists every citation with its exhibit page and status, flagged rows in red. Each row links to its exhibit page, or to the memo when the quote was not found. The PDF also gets bookmarks for the memo, the index and every exhibit page.
def fit(text, width, size=9):
"""Shorten text with an ellipsis to fit a column width."""
if pymupdf.get_text_length(text, fontsize=size) <= width:
return text
while pymupdf.get_text_length(text + "...", fontsize=size) > width:
text = text[:-1]
return text.rstrip() + "..."
def fill_index(page, citations):
flagged = sum(c["status"] != "ok" for c in citations)
page.insert_text((72, 72), "Citation index", fontsize=18, fontname="hebo")
page.insert_text((72, 92), f"{len(citations)} quotations checked, {flagged} flagged for review. "
"Click a row to open its exhibit page.", fontsize=9, color=GREY)
cols = {"#": 72, "Quotation": 90, "Cited": 330, "Exhibit": 400, "Status": 450}
for name, x in cols.items():
page.insert_text((x, 122), name, fontsize=9, fontname="hebo")
page.draw_line((72, 127), (523, 127), color=GREY, width=0.5)
y = 144
for c in citations:
color = (0, 0, 0) if c["status"] == "ok" else RED
page.insert_text((cols["#"], y), str(c["n"]), fontsize=9)
page.insert_text((cols["Quotation"], y), fit(f'"{c["quote"]}"', 232), fontsize=9)
page.insert_text((cols["Quotation"], y + 11), fit(f"Found: {found_at(c)}", 232, 7.5), fontsize=7.5, color=GREY)
page.insert_text((cols["Cited"], y), c["source"], fontsize=9)
page.insert_text((cols["Exhibit"], y), c.get("exhibit", "-"), fontsize=9, color=BLUE)
status = "ok" if c["status"] == "ok" else FLAG[c["status"]](c)
page.insert_text((cols["Status"], y), status, fontsize=9, color=color)
link(page, pymupdf.Rect(72, y - 10, 523, y + 14), c.get("target", c["memo_page"]))
y += 30
assert y < page.rect.height - 72, "more citations than fit on one index page"
fill_index(bundle[index_page], citations)
bundle.save("memo_with_exhibits.pdf", garbage=3, deflate=True)
print(f"memo_with_exhibits.pdf: {bundle.page_count} pages")
for c in citations:
print(f'{c["n"]} Ex. {c.get("exhibit", "-"):4} {c["status"]:17} {c["quote"][:50]}')memo_with_exhibits.pdf: 8 pages 1 Ex. A-1 ok shall deliver all Products within forty-five (45) 2 Ex. A-1 multiple matches Time is of the essence with respect to all deliver 3 Ex. A-2 multiple matches Buyer may cancel the affected Purchase Order witho 4 Ex. B-1 ok the shipment has not arrived and no revised date h 5 Ex. B-2 ok we are cancelling Purchase Order 4471 effective im 6 Ex. - not found sixty (60) days to deliver
Preview
The memo with its linked citations and margin labels, the citation index, and an exhibit page with the quoted passages highlighted. Open memo_with_exhibits.pdf in any PDF viewer to follow the links.
from IPython.display import Image, display
for pno in (0, index_page, where[("Agreement", 1)][0]):
display(Image(bundle[pno].get_pixmap(dpi=60).tobytes("png")))Limits to know
- The citation pattern is simple: a quote in double quotes followed by a source name in parentheses, on one memo page. Adapt
CITEto your citation style, including curly quotes and pin cites. - Quotes are matched as written, ignoring case, line breaks and hyphenation (and, in the fallback, punctuation). An ellipsis or a bracketed change inside a quote, such as "[the] Supplier", needs to be split into parts before it is located.
- A multiple-match quote is linked to its first match in the cited source. That is a guess; the flag is there so that a person decides.
- The sources need a text layer. Run OCR on scanned exhibits first, and record which evidence came from OCR.
- Check your court's rules for exhibit labels, slip sheets and page stamps, and adjust
slip_sheet()andstamp()to match.
Next steps
- The PyMuPDF grounding skill, where
locate()comes from - Build an Evidence Pack for an AI Answer: a similar bundle for AI answers
- Catch Hallucinated Citations: tell a misquote from an invented quote, for the citations flagged as not found
- See everything on grounding with PyMuPDF: https://pymupdf.io/grounding
Discuss This Article with the Community
Have a question, a different approach, or something you built after reading this? Share it on the forum or join the Discord, we'd love to hear from you.