Build a Page-by-Page Font Inventory for a Document Examiner
List the fonts used on each page of a PDF, flag patterns worth a closer look, and render matching page images at one resolution so an examiner can view each page beside its font list.
A document examiner who suspects that a PDF was altered often starts with its fonts: which fonts each page uses, whether they are embedded, and whether a page carries its own copy of a font the rest of the document shares. The inventory is only useful next to the page itself, so every page is rendered at the same resolution, with a matching image that outlines where each font is used.
This notebook builds that inventory with PyMuPDF:
- List the fonts each page declares and the fonts its text actually uses, with embedding, subset tag, font object and character counts.
- Point out patterns worth a closer look, such as a font used on one page only.
- Render every page at one resolution, plus a matching image with each font's text outlined.
- Write the inventory as CSV and JSON, and an HTML page that shows each page image beside its font list.
Tested with PyMuPDF 2.2.
%pip install -q pymupdfSample document
A three-page statement of account, built the way real documents get altered. The original was produced in one session. Later, page 2 was replaced with a page made separately, a "RECEIVED" stamp was added to page 3, and a font resource that nothing uses was left on page 1.
Replace path with the PDF you are examining. Work on a copy, and keep the original untouched.
import io
import pymupdf
CSS = """
body { font-family: serif; font-size: 11pt; }
.head { font-family: sans-serif; font-weight: bold; font-size: 16pt; }
.mono { font-family: monospace; font-size: 10pt; }
.sig { font-style: italic; }
"""
def story_pdf(html):
"""Lay out HTML on A4 pages in one session, as a word processor would."""
story = pymupdf.Story(html, user_css=CSS)
buf = io.BytesIO()
writer = pymupdf.DocumentWriter(buf)
more = 1
while more:
device = writer.begin_page(pymupdf.paper_rect("a4"))
more, _ = story.place(pymupdf.Rect(72, 72, 523, 770))
story.draw(device)
writer.end_page()
writer.close()
return pymupdf.open("pdf", buf.getvalue())
original = story_pdf("""
<p class="head">Halden Robotics Inc.</p>
<p>Statement of account for Northwind Components Ltd., period ending 28 February 2026.</p>
<p class="mono">Invoice 1041 15 Jan 2026 8,200.00<br>Invoice 1057 02 Feb 2026 4,280.00</p>
<p style="page-break-before: always">Payments received during the period are listed below.</p>
<p>Balance carried forward: 12,480.00. No payments were received during the period.</p>
<p style="page-break-before: always">Please remit the balance within thirty days.</p>
<p class="sig">Dana Hart, Accounts</p>
""")
replacement = story_pdf("""
<p>Payments received during the period are listed below.</p>
<p>Balance carried forward: 2,480.00. A payment of 10,000.00 was received on 20 February 2026.</p>
""")
doc = original
doc.delete_page(1) # page 2 replaced in a separate session
doc.insert_pdf(replacement, start_at=1)
doc[2].insert_text((380, 120), "RECEIVED 12 MAR 2026", fontname="helv", fontsize=12, color=(0.8, 0, 0))
doc[0].insert_font(fontname="tiro") # a font resource that nothing uses
doc.subset_fonts()
doc.save("statement.pdf")
path = "statement.pdf"Step 1: The fonts on one page
PyMuPDF gives two views of a page's fonts, and an examiner needs both:
page.get_fonts(full=True)lists the fonts the page declares in its resources: the font object's xref, its type and encoding, whether it is embedded, and its name. An embedded subset has a six-letter tag in front of its name, such asABCDEF+Arial, which the producing software chooses.page.get_text("dict")gives every text span with the font it is drawn in, its size, colour and position. This is what the page actually uses.
A declared font that no text uses can be left behind by editing. A used font is matched to its declaration by name, without the subset tag.
import re
SUBSET = re.compile(r"^([A-Z]{6})\+(.+)$")
def split_subset(basefont):
"""'ABCDEF+Arial' -> ('ABCDEF', 'Arial'); a name without a tag -> ('', name)."""
m = SUBSET.match(basefont)
return (m.group(1), m.group(2)) if m else ("", basefont)
def page_fonts(page):
"""Fonts used by the text of one page, with their declarations, and declared fonts nothing uses."""
declared = {}
for xref, ext, ftype, basefont, resource, encoding, *_ in page.get_fonts(full=True):
tag, name = split_subset(basefont)
declared[name] = {"xref": xref, "subset_tag": tag, "embedded": ext != "n/a",
"type": ftype, "encoding": encoding, "resource": resource}
used = {}
for block in page.get_text("dict")["blocks"]:
for line in block.get("lines", []):
for span in line["spans"]:
text = span["text"].strip()
if not text:
continue
f = used.setdefault(span["font"], {"chars": 0, "sizes": set(), "colors": set(),
"sample": "", "boxes": []})
f["chars"] += len(text)
f["sizes"].add(round(span["size"], 1))
f["colors"].add(f'#{span["color"]:06x}')
f["boxes"].append([round(v, 1) for v in span["bbox"]])
if len(f["sample"]) < 40:
f["sample"] = (f["sample"] + " " + text).strip()[:40]
fonts = []
for name, f in sorted(used.items()):
d = declared.get(name, {"xref": None, "subset_tag": "", "embedded": None,
"type": "?", "encoding": "?", "resource": "?"})
fonts.append({"font": name, **d, "chars": f["chars"], "sizes": sorted(f["sizes"]),
"colors": sorted(f["colors"]), "sample": f["sample"], "boxes": f["boxes"]})
unused = sorted(n for n in declared if n not in used)
return fonts, unused
doc = pymupdf.open(path)
fonts, unused = page_fonts(doc[0])
for f in fonts:
print(f'{f["font"]:24} xref {f["xref"]:<4} tag {f["subset_tag"] or "-":7} embedded={f["embedded"]!s:5} '
f'{f["chars"]:4} chars sizes {f["sizes"]}')
print("declared but not used:", unused)Charis SIL Regular xref 9 tag UEPUMZ embedded=True 82 chars sizes [11.0] Nimbus Mono PS Regular xref 15 tag DFWGHB embedded=True 66 chars sizes [10.0] Nimbus Sans Bold xref 3 tag ARJMVK embedded=True 20 chars sizes [16.0] declared but not used: ['Times-Roman']
Step 2: Inventory every page
The same function runs on every page. Each font on each page becomes one row of the inventory. The source file's SHA-256 hash is recorded with it, so the inventory can be tied to the exact file that was examined.
import hashlib
def sha256(path):
with open(path, "rb") as f:
return hashlib.sha256(f.read()).hexdigest()
def build_inventory(path):
doc = pymupdf.open(path)
pages = []
for page in doc:
fonts, unused = page_fonts(page)
pages.append({"page": page.number + 1, "size_pt": [round(page.rect.width, 1), round(page.rect.height, 1)],
"fonts": fonts, "declared_unused": unused})
return {"source": path, "sha256": sha256(path), "page_count": doc.page_count,
"pymupdf": pymupdf.VersionBind, "pages": pages}
inventory = build_inventory(path)
for p in inventory["pages"]:
print(f'Page {p["page"]}')
for f in p["fonts"]:
embedded = {True: "embedded", False: "NOT embedded", None: "?"}[f["embedded"]]
print(f' {f["font"]:24} xref {f["xref"]!s:4} {embedded:13} {f["chars"]:4} chars "{f["sample"]}"')
for name in p["declared_unused"]:
print(f' {name:24} declared but not used')Page 1 Charis SIL Regular xref 9 embedded 82 chars "Statement of account for Northwind Compo" Nimbus Mono PS Regular xref 15 embedded 66 chars "Invoice 1041 15 Jan 2026 8,200.00 Invoic" Nimbus Sans Bold xref 3 embedded 20 chars "Halden Robotics Inc." Times-Roman declared but not used Page 2 Charis SIL Regular xref 38 embedded 143 chars "Payments received during the period are " Page 3 Charis SIL Italic xref 27 embedded 19 chars "Dana Hart, Accounts" Charis SIL Regular xref 9 embedded 44 chars "Please remit the balance within thirty d" Helvetica xref 45 NOT embedded 20 chars "RECEIVED 12 MAR 2026"
Step 3: Leads for the examiner
Across the whole document, a few patterns are worth a closer look. None of them proves anything on its own. Documents are legitimately assembled from several sources, and stamps and form fields add fonts. They tell the examiner where to look first.
- A font used on only one page.
- The same font embedded as separate font objects. Software that produces a document in one session usually embeds each font once and shares it across pages. A page with its own copy may have been produced separately.
- A font that is not embedded. The viewer substitutes a local font, so the page can look different on another machine.
- A declared font that no text uses, which editing can leave behind.
from collections import defaultdict
def leads(inventory):
"""Patterns across pages that are worth a closer look. Not findings."""
notes = []
pages_of = defaultdict(list)
objects_of = defaultdict(lambda: defaultdict(list))
not_embedded = defaultdict(list)
for p in inventory["pages"]:
for f in p["fonts"]:
pages_of[f["font"]].append(p["page"])
objects_of[f["font"]][f["xref"]].append(p["page"])
if f["embedded"] is False:
not_embedded[f["font"]].append(p["page"])
many_pages = inventory["page_count"] > 1
for font, pages in pages_of.items():
if many_pages and len(pages) == 1:
notes.append(f"{font} is used only on page {pages[0]}.")
for font, objects in objects_of.items():
if len(objects) > 1:
where = "; ".join(f"xref {x} on page{'s' if len(ps) > 1 else ''} {', '.join(map(str, ps))}"
for x, ps in objects.items())
notes.append(f"{font} is embedded as {len(objects)} separate font objects: {where}.")
for font, pages in not_embedded.items():
notes.append(f"{font} is not embedded (page {', '.join(map(str, pages))}); viewers substitute a local font.")
for p in inventory["pages"]:
for name in p["declared_unused"]:
notes.append(f"Page {p['page']} declares {name}, but none of its text uses it.")
return notes
inventory["leads"] = leads(inventory)
for note in inventory["leads"]:
print("-", note)- Nimbus Mono PS Regular is used only on page 1. - Nimbus Sans Bold is used only on page 1. - Charis SIL Italic is used only on page 3. - Helvetica is used only on page 3. - Charis SIL Regular is embedded as 2 separate font objects: xref 9 on pages 1, 3; xref 38 on page 2. - Helvetica is not embedded (page 3); viewers substitute a local font. - Page 1 declares Times-Roman, but none of its text uses it.
Every planted change shows up. The replaced page 2 uses the same serif font as pages 1 and 3, but as its own font object. The stamp on page 3 is the only text in Helvetica, which is not embedded. Page 1 still declares Times-Roman, which none of its text uses. The sans-serif heading and the monospaced figures each appear on page 1 only, which is normal for a letterhead and a table: the examiner decides which leads matter.
Step 4: Render every page at one resolution
Every page is rendered at the same DPI, so images can be compared with each other and with the inventory. At 150 dpi, one PDF point is 150 / 72 pixels, and the inventory stores each font's boxes in pixels too, so a box can be found in the image directly. Use 300 dpi or more for close examination of glyph shapes.
Two images are written per page:
page-001.png: the page as rendered, unchanged. Annotations, such as stamps added in a viewer, are included as they display.page-001-fonts.png: the same page at the same resolution, with each span's box outlined in its font's colour. Each font keeps one colour across all pages. The boxes are drawn on a copy of the page that is never saved.
The SHA-256 hash of every image is recorded, so it can be checked later that the image has not changed.
import os
DPI = 150
OUT = "font_inventory"
PALETTE = ["#1f77b4", "#d62728", "#2ca02c", "#9467bd", "#ff7f0e", "#17becf",
"#8c564b", "#e377c2", "#7f7f7f", "#bcbd22"]
def font_colors(inventory):
"""One colour per font name, the same on every page."""
names = sorted({f["font"] for p in inventory["pages"] for f in p["fonts"]})
return {name: PALETTE[i % len(PALETTE)] for i, name in enumerate(names)}
def rgb(hex_color):
return tuple(int(hex_color[i:i + 2], 16) / 255 for i in (1, 3, 5))
def render_pages(path, inventory, colors, out=OUT, dpi=DPI):
os.makedirs(out, exist_ok=True)
scale = dpi / 72
doc = pymupdf.open(path) # for the unchanged images
work = pymupdf.open(path) # a copy to draw font boxes on, never saved
inventory.update(dpi=dpi, px_per_pt=round(scale, 4))
for p in inventory["pages"]:
stem = f'page-{p["page"]:03d}'
pix = doc[p["page"] - 1].get_pixmap(dpi=dpi)
pix.save(f"{out}/{stem}.png")
page = work[p["page"] - 1]
for f in p["fonts"]:
for box in f["boxes"]:
page.draw_rect(pymupdf.Rect(box), color=rgb(colors[f["font"]]), width=0.8)
f["boxes_px"] = [[round(v * scale) for v in box] for box in f["boxes"]]
page.get_pixmap(dpi=dpi).save(f"{out}/{stem}-fonts.png")
p.update(image=f"{stem}.png", overlay=f"{stem}-fonts.png", image_px=[pix.width, pix.height],
image_sha256=sha256(f"{out}/{stem}.png"))
colors = font_colors(inventory)
render_pages(path, inventory, colors)
for p in inventory["pages"]:
print(f'{p["image"]} {p["image_px"][0]} x {p["image_px"][1]} px sha256 {p["image_sha256"][:16]}...')page-001.png 1240 x 1755 px sha256 def3cbc2b79ce0a7... page-002.png 1240 x 1755 px sha256 05936ffa6daf590f... page-003.png 1240 x 1755 px sha256 436cbe1c312983ab...
Step 5: Write the inventory
Three files go next to the images:
fonts.csv: one row per page and font, for a spreadsheet or a report table.inventory.json: everything, including every span box in points and pixels, the hashes, the DPI and the PyMuPDF version.index.html: one section per page, with the page image on the left and its font list on the right. Click an image to switch between the plain page and the outlined fonts. It needs no server: open it straight from the folder.
import csv
import html
import json
from datetime import datetime, timezone
def write_csv(inventory, out=OUT):
fields = ["page", "font", "subset_tag", "embedded", "type", "encoding", "xref", "chars", "sizes", "colors",
"sample", "image"]
with open(f"{out}/fonts.csv", "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=fields)
w.writeheader()
for p in inventory["pages"]:
for font in p["fonts"]:
w.writerow({**{k: font[k] for k in fields if k in font}, "page": p["page"], "image": p["image"],
"sizes": " ".join(map(str, font["sizes"])), "colors": " ".join(font["colors"])})
for name in p["declared_unused"]:
w.writerow({"page": p["page"], "font": name, "sample": "(declared, not used)", "image": p["image"]})
STYLE = """<style>
body { font: 14px/1.4 system-ui, sans-serif; margin: 24px; color: #222; background: #fff; }
.page { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 24px;
border-top: 1px solid #ccc; padding: 16px 0; }
@media (max-width: 800px) { .page { grid-template-columns: 1fr; } }
img { max-width: 100%; border: 1px solid #ccc; cursor: pointer; }
table { border-collapse: collapse; width: 100%; }
th, td { text-align: left; padding: 4px 6px; border-bottom: 1px solid #eee; vertical-align: top; }
.sw { display: inline-block; width: 12px; height: 12px; margin-right: 6px; vertical-align: -1px; }
.muted { color: #666; } .flag { color: #b00; }
</style>"""
def write_html(inventory, colors, out=OUT):
e = html.escape
parts = [f"<!doctype html><meta charset='utf-8'><title>Font inventory: {e(inventory['source'])}</title>", STYLE,
f"<h1>Font inventory: {e(inventory['source'])}</h1>",
f"<p class='muted'>SHA-256 {inventory['sha256']}<br>{inventory['page_count']} pages, images at "
f"{inventory['dpi']} dpi ({inventory['px_per_pt']} px per point). PyMuPDF {inventory['pymupdf']}. "
f"Created {inventory['created_utc']}.</p>",
"<h2>Leads</h2><ul>" + "".join(f"<li>{e(n)}</li>" for n in inventory["leads"]) + "</ul>"]
for p in inventory["pages"]:
rows = []
for f in p["fonts"]:
embedded = {True: "yes", False: "<span class='flag'>no</span>", None: "?"}[f["embedded"]]
rows.append(f"<tr><td><span class='sw' style='background:{colors[f['font']]}'></span>{e(f['font'])}</td>"
f"<td>{e(f['subset_tag'] or '-')}</td><td>{embedded}</td><td>{e(f['type'])}</td>"
f"<td>{f['xref']}</td><td>{f['chars']}</td><td>{', '.join(map(str, f['sizes']))}</td>"
f"<td class='muted'>{e(f['sample'])}</td></tr>")
rows += [f"<tr><td colspan='8' class='flag'>{e(n)}: declared, not used</td></tr>" for n in p["declared_unused"]]
parts.append(
f"<section class='page' id='page-{p['page']}'><div>"
f"<img src='{p['image']}' data-alt='{p['overlay']}' alt='Page {p['page']}' "
f"onclick='[this.src, this.dataset.alt] = [this.dataset.alt, this.src]'>"
f"<p class='muted'>{p['image']}, {p['image_px'][0]} x {p['image_px'][1]} px. "
f"Click to show or hide font boxes.</p></div>"
f"<div><h2>Page {p['page']}</h2><p class='muted'>{p['size_pt'][0]} x {p['size_pt'][1]} pt</p>"
"<table><tr><th>Font</th><th>Subset</th><th>Embedded</th><th>Type</th><th>Xref</th>"
"<th>Chars</th><th>Sizes</th><th>Sample</th></tr>" + "".join(rows) + "</table></div></section>")
with open(f"{out}/index.html", "w", encoding="utf-8") as fh:
fh.write("\n".join(parts))
inventory["created_utc"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
write_csv(inventory)
write_html(inventory, colors)
with open(f"{OUT}/inventory.json", "w", encoding="utf-8") as f:
json.dump(inventory, f, indent=2)
for name in sorted(os.listdir(OUT)):
print(name)fonts.csv index.html inventory.json page-001-fonts.png page-001.png page-002-fonts.png page-002.png page-003-fonts.png page-003.png
Preview
Page 2, the replaced page, beside page 1: plain on the left of each pair, outlined fonts on the right. The serif body text has the same colour on both pages because it is the same font name; the inventory shows it is a different font object. The preview embeds reduced copies of the images in the notebook; the files in font_inventory/ keep the full resolution. Open font_inventory/index.html for the full side-by-side view.
import base64
from IPython.display import HTML
def data_uri(file, shrink=2):
"""A PNG as a data: URI, reduced by 2**shrink, so the preview is stored inside the notebook."""
pix = pymupdf.Pixmap(file)
pix.shrink(shrink)
return "data:image/png;base64," + base64.b64encode(pix.tobytes("png")).decode()
cells = "".join(f'<img src="{data_uri(f"{OUT}/{p[k]}")}" width="230" style="margin:4px;border:1px solid #ccc">'
for p in inventory["pages"][:2] for k in ("image", "overlay"))
HTML(cells)Limits to know
- The inventory reports what the file contains. It cannot say who changed a document or when; the leads are starting points for an examiner, not conclusions.
- A used font is matched to its declaration by name. If a page declares two fonts with the same name, only one is reported; check the xrefs with
page.get_fonts(full=True). - Text in Type 3 fonts, text inside form fields that are not flattened, and text in images (scans) is reported differently or not at all. For scanned pages, the fonts listed belong to the OCR layer, often an invisible font such as GlyphLessFont.
- Fonts in annotations are drawn in the images but are not part of the page's text, so they are not in the font list.
Next steps
Page.get_fonts()andPage.get_text("dict")in the PyMuPDF documentation- Extract an embedded font for closer study with
Document.extract_font(), using the xref from the inventory - Know Which Evidence Came from OCR: tell born-digital text from OCR text
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.