Audit and Fix PDF Accessibility with PyMuPDF
By Jeonghee Kim

Audit thousands of PDFs for accessibility in seconds, fix the document-level failures, and see a tagged PDF the way a screen reader does.
PyMuPDF covers the jobs every PDF accessibility program starts with: auditing thousands of PDFs in seconds, fixing document-level failures, and reading a tagged document's structure the way a screen reader does. This article gives you three tested recipes for those jobs. They run on PyMuPDF 2.1 (MuPDF 1.28).
The pressure is real. The DOJ's ADA Title II rule requires WCAG 2.1 AA for state and local government web content, PDFs included. An April 2026 interim rule pushed the first deadline to April 2027 for entities serving 50,000+ people (Duane Morris). The European Accessibility Act has applied since June 2025. Most organizations hold years of legacy PDFs and need to know which ones fail before they can fix anything.
What an accessible PDF needs, and where PyMuPDF fits
A screen reader doesn't see the page; it reads the tag tree, the language and the text layer. The table maps the core PDF/UA checks to what PyMuPDF does with each.
| Requirement | Why it matters | How PyMuPDF helps |
|---|---|---|
| Tagged (/MarkInfo + /StructTreeRoot) | Gives headings, lists, tables and reading order | Detects tagged vs. untagged files (Recipe 1) |
| Correct tag roles | A heading tagged as P is not announced as a heading | Prints the tag tree with TEXT_COLLECT_STRUCTURE (Recipe 3) |
| Document language (/Lang) | Screen reader picks the right voice and pronunciation | Checks and sets it with set_language() |
| Title + DisplayDocTitle | Window shows a title, not scan_0042.pdf | Checks and sets both |
| Real text, not image-only scans | No text means nothing to read | Finds scans and OCRs them with built-in Tesseract |
| Bookmarks on long documents | Lets users jump between sections | Checks and builds them with set_toc() |
| Alt text on figures, tagged links | Describes images and link targets | Inventories every image and link for review |
| Extraction permitted | Encryption can block assistive tech | Checks the accessibility permission bit |
Recipe 1: Audit a folder of PDFs
This script runs seven checks per file and prints PASS, FAIL or INFO. Run it over a whole archive to find the worst files first.
"""Quick PDF accessibility audit with PyMuPDF."""
import sys
import pymupdf
def audit(path):
doc = pymupdf.open(path)
cat = doc.pdf_catalog()
findings = []
def check(ok, label, detail=""):
findings.append(("PASS" if ok else "FAIL", label, detail))
# 1. Tagged? (/MarkInfo /Marked true plus a /StructTreeRoot)
marked = bool(doc.markinfo.get("Marked"))
has_tree = doc.xref_get_key(cat, "StructTreeRoot")[0] != "null"
check(marked and has_tree, "Tagged PDF (structure tree)",
f"Marked={marked}, StructTreeRoot={'yes' if has_tree else 'no'}")
# 2. Document language
check(bool(doc.language), "Document language (/Lang)", doc.language or "missing")
# 3. Title in metadata, shown in the window title bar
title = (doc.metadata or {}).get("title", "")
vp = doc.xref_get_key(cat, "ViewerPreferences/DisplayDocTitle")[1]
check(bool(title), "Title in metadata", title or "missing")
check(vp == "true", "DisplayDocTitle", vp)
# 4. Real text on every page (no image-only "scans")
no_text = [p.number + 1 for p in doc
if not p.get_text().strip() and p.get_images()]
check(not no_text, "Every page has real text",
f"image-only pages: {no_text}" if no_text else "")
# 5. Bookmarks for documents longer than a few pages
if doc.page_count > 3:
check(bool(doc.get_toc()), "Bookmarks (outline)")
# 6. Images and links on each page (need alt text / tagging)
n_img = sum(len(p.get_images()) for p in doc)
n_lnk = sum(len(p.get_links()) for p in doc)
findings.append(("INFO", "Images / links to review", f"{n_img} images, {n_lnk} links"))
# 7. Is text extraction for assistive tech permitted?
ok = bool(doc.permissions & pymupdf.PDF_PERM_ACCESSIBILITY)
check(ok, "Accessibility extraction permitted")
return findings
if __name__ == "__main__":
for path in sys.argv[1:]:
print(f"\n{path}")
for status, label, detail in audit(path):
print(f" [{status}] {label}" + (f" - {detail}" if detail else ""))Output for two test files: a report built without tags (page 2 is a scan) and an HTML page exported from LibreOffice with tagging on.
$ python a11y_audit.py report.pdf tagged.pdf
report.pdf
[FAIL] Tagged PDF (structure tree) - Marked=False, StructTreeRoot=no
[FAIL] Document language (/Lang) - missing
[FAIL] Title in metadata - missing
[FAIL] DisplayDocTitle - null
[FAIL] Every page has real text - image-only pages: [2]
[INFO] Images / links to review - 2 images, 1 links
[PASS] Accessibility extraction permitted
tagged.pdf
[PASS] Tagged PDF (structure tree) - Marked=True, StructTreeRoot=yes
[PASS] Document language (/Lang) - en
[PASS] Title in metadata - Tagged Sample
[PASS] DisplayDocTitle - true
[PASS] Every page has real text
[INFO] Images / links to review - 0 images, 0 links
[PASS] Accessibility extraction permittedTo scale it, glob a directory, write one CSV row per file, and sort by FAIL count. Opening a PDF and reading its catalog takes milliseconds, so a 10,000-file archive is a coffee break, not a project.
Recipe 2: Fix the low-hanging fruit
The document-level failures above are fixable in about 40 lines: title, language, title display, scanned pages and bookmarks.
"""Fix the metadata-level accessibility gaps PyMuPDF can repair safely."""
import sys
import pymupdf
src, dst, title, lang = sys.argv[1:5]
doc = pymupdf.open(src)
# 1. Title + language, and tell viewers to show the title, not the file name
meta = doc.metadata
meta["title"] = title
doc.set_metadata(meta)
doc.set_language(lang)
cat = doc.pdf_catalog()
doc.xref_set_key(cat, "ViewerPreferences/DisplayDocTitle", "true")
# 2. OCR image-only pages so screen readers have text to read
for page in doc:
if page.get_text().strip() or not page.get_images():
continue
pix = page.get_pixmap(dpi=300)
ocr = pymupdf.open("pdf", pix.pdfocr_tobytes(language="eng"))
n = page.number
doc.insert_pdf(ocr, start_at=n) # OCR'd page (image + invisible text) at index n
doc.delete_page(n + 1) # drop the old image-only page
print(f"OCR'd page {n + 1}")
# 3. Bookmarks: one entry per page from its largest-font line, if none exist
if not doc.get_toc():
toc = []
for page in doc:
lines = [l for b in page.get_text("dict")["blocks"] if b["type"] == 0
for l in b["lines"]]
lines = [l for l in lines if "".join(s["text"] for s in l["spans"]).strip()]
if lines:
top = max(lines, key=lambda l: max(s["size"] for s in l["spans"]))
text = " ".join("".join(s["text"] for s in top["spans"]).split())
toc.append([1, text, page.number + 1])
doc.set_toc(toc)
doc.save(dst, garbage=3, deflate=True)Re-running the audit on the output:
$ python a11y_fix.py report.pdf report_fixed.pdf "Quarterly Report" en-US
OCR'd page 2
$ python a11y_audit.py report_fixed.pdf
[FAIL] Tagged PDF (structure tree) - Marked=False, StructTreeRoot=no
[PASS] Document language (/Lang) - en
[PASS] Title in metadata - Quarterly Report
[PASS] DisplayDocTitle - true
[PASS] Every page has real text
[INFO] Images / links to review - 2 images, 1 links
[PASS] Accessibility extraction permittedThe generated bookmarks are Quarterly Report (page 1) and Appendix A: Methodology (page 2), the latter read from the OCR text.
Three things to know before you run this in production:
set_language()stores the primary subtag, soen-USbecomesen; both are valid. If you need the region, write it directly:doc.xref_set_key(cat, "Lang", "(en-US)").- OCR needs Tesseract installed with the right language packs (
kor,jpn,deu…). Replacing a page drops its annotations and links, so only do it on pure scans. - Never set
/Marked trueto make a checker go green. Claiming tags without a real structure tree is worse than having none: assistive tech trusts it and reads nothing.
Recipe 3: See what a screen reader sees
A file can pass "is it tagged?" and still be wrong. With the TEXT_COLLECT_STRUCTURE flag, PyMuPDF returns text nested inside its structure elements, so you can print the tag tree page by page.
"""Print the tag tree MuPDF sees on each page of a tagged PDF."""
import sys
import pymupdf
FLAGS = pymupdf.TEXTFLAGS_DICT | pymupdf.TEXT_COLLECT_STRUCTURE
def walk(blocks, depth=0):
for b in blocks:
if b["type"] == 2: # structure element
text = " ".join(s["text"] for blk in b["blocks"] if blk["type"] == 0
for l in blk["lines"] for s in l["spans"]).strip()
role = b["std"] if b["raw"] == b["std"] else f'{b["std"]} (raw: {b["raw"]})'
print(" " * depth + f"<{role}> {text[:50]}")
walk(b["blocks"], depth + 1)
doc = pymupdf.open(sys.argv[1])
for page in doc:
print(f"--- page {page.number + 1}")
walk(page.get_text("dict", flags=FLAGS)["blocks"])$ python tag_outline.py tagged.pdf
--- page 1
<Document>
<P (raw: Heading 1)> Tagged Sample
<P (raw: Text body)> This document was exported with tags.
<H2> Section two
<L>
<LI>
<Lbl> •
<LBody>
<P (raw: Text body)> One
<LI>
<Lbl> •
<LBody>
<P (raw: Text body)> TwoThis catches a real defect. The exporter tagged the title Heading 1 and its RoleMap maps that to P, so a screen reader announces the document title as an ordinary paragraph. The automated audit passed this file; the tag outline shows the problem. Flag any document whose first H1 is missing or whose headings skip levels.
Run this on every tagged file before you publish it. A wrong role is invisible on screen but obvious to anyone using a screen reader.
Putting it together
A practical workflow for an archive of any size:
- Run Recipe 1 across the archive and sort files by FAIL count.
- Apply Recipe 2 to fix language, title, scans and bookmarks in bulk.
- Check new and high-traffic files with Recipe 3 to confirm their tag roles.
- Re-export files that fail the tag check from their source application with tagging turned on.
- Validate with veraPDF for PDF/UA-1 and spot-test with a screen reader such as NVDA.
PyMuPDF Layout already recognizes headings, lists, tables and reading order on untagged and scanned pages, so the structure a screen reader needs is within reach of the same toolkit.
Tested with PyMuPDF 2.1 (MuPDF 1.28.6), Tesseract 5 and Python 3.13.
Sources
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.