Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
P

PyMuPDF

> DevOps
Open source

PyMuPDF is a high performance Python library for data extraction, analysis, conversion & manipulation of PDF (and other) documents.

10.4K stars0 likes0 views
WebsiteGitHub

About

PyMuPDF is a high performance Python library for data extraction, analysis, conversion & manipulation of PDF (and other) documents.

PyMuPDF

**The PDF engine behind over 50 million monthly downloads, powering AI pipelines worldwide.**

PyMuPDF is a high-performance Python library for data extraction, analysis, conversion, rendering and manipulation of PDF (and other) documents. Built on top of MuPDF — a lightweight, fast C engine — PyMuPDF gives you precise, low-level control over documents alongside high-level convenience APIs. No mandatory external dependencies.

Why PyMuPDF?

  • Fast — powered by MuPDF, a best-in-class C rendering engine
  • Accurate — pixel-perfect text extraction with font, color, and position metadata
  • Versatile — read, write, annotate, redact, merge, split, and convert documents
  • LLM-ready — native Markdown output via PyMuPDF4LLM for RAG and AI pipelines
  • No mandatory dependencies — pip install pymupdf and you're done

Installation

bash
pip install pymupdf

Wheels are available for Windows, macOS, and Linux on Python 3.10–3.14. If no pre-built wheel exists for your platform, pip will compile from source (requires a C/C++ toolchain).

Optional extras

Package Purpose
pymupdf-fonts Extended font collection for text output
pymupdf4llm LLM/RAG-optimised Markdown and JSON extraction
pymupdfpro Adds Office document support
tesseract-ocr OCR for scanned pages and images (separate install)
bash
# More fonts
pip install pymupdf-fonts

# LLM-ready extraction
pip install pymupdf4llm

# Office support
pip install pymupdfpro

# OCR (Tesseract must be installed separately)
# macOS
brew install tesseract

# Ubuntu / Debian
sudo apt install tesseract-ocr

Supported File Formats

Input

Category Formats
PDF & derivatives PDF, XPS, EPUB, CBZ, MOBI, FB2, SVG, TXT, MD
Images PNG, JPEG, BMP, TIFF, GIF, and more
Microsoft Office (Pro) DOC, DOCX, XLS, XLSX, PPT, PPTX
Korean Office (Pro) HWP, HWPX

Output

Format Notes
PDF Full fidelity conversion from Office formats
SVG Vector page rendering
Image (PNG, JPEG, …) Page rasterisation at any DPI
Markdown Structure-aware, LLM-ready
JSON Bounding boxes, layout data, per-element detail
Plain text Fast, lightweight extraction

Quick start

Extract text

python
import pymupdf

doc = pymupdf.open("document.pdf")
for page in doc:
    print(page.get_text())

Extract text with layout metadata

python
import pymupdf

doc = pymupdf.open("document.pdf")
page = doc[0]

blocks = page.get_text("dict")["blocks"]
for block in blocks:
    if block["type"] == 0:  # text block
        for line in block["lines"]:
            for span in line["spans"]:
                print(f"{span['text']!r}  font={span['font']}  size={span['size']:.1f}")

Extract tables

python
import pymupdf

doc = pymupdf.open("spreadsheet.pdf")
page = doc[0]

tables = page.find_tables()
for table in tables:
    print(table.to_markdown())

    # or get as Pandas DataFrame
    df = table.to_pandas()

Render a page to an image

python
import pymupdf

doc = pymupdf.open("document.pdf")
page = doc[0]

pixmap = page.get_pixmap(dpi=150)
pixmap.save("page_0.png")

OCR a scanned document

python
import pymupdf

doc = pymupdf.open("scanned.pdf")
page = doc[0]

# Requires Tesseract installed and on PATH
text = page.get_textpage_ocr(language="eng").extractText()
print(text)

Convert Markdown to PDF

python
import pymupdf

md_doc = pymupdf.open("example.md")
md_doc.save("example.pdf")

Convert to Markdown for LLMs

python
import pymupdf4llm

md = pymupdf4llm.to_markdown("report.pdf")
# Pass directly to your LLM or vector store
print(md)

Annotate and redact

python
import pymupdf

doc = pymupdf.open("contract.pdf")
page = doc[0]

# Add a highlight annotation
rect = pymupdf.Rect(72, 100, 400, 120)
page.add_highlight_annot(rect)

# Add a redaction and apply it
page.add_redact_annot(rect)
page.apply_redactions()

doc.save("contract_redacted.pdf")

Merge PDFs

python
import pymupdf

merger = pymupdf.open()
for path in ["part1.pdf", "part2.pdf", "part3.pdf"]:
    merger.insert_pdf(pymupdf.open(path))

merger.save("merged.pdf")

Convert an Office document to PDF

python
import pymupdf.pro

pymupdf.pro.unlock("YOUR-LICENSE-KEY")

doc = pymupdf.open("presentation.pptx")
pdf_bytes = doc.convert_to_pdf()

with open("output.pdf", "wb") as f:
    f.write(pdf_bytes)

Extract LLM-ready Markdown from a Word document

python
import pymupdf4llm
import pymupdf.pro

pymupdf.pro.unlock("YOUR-LICENSE-KEY")

md = pymupdf4llm.to_markdown("document.docx")
print(md)

Features

Core capabilities

Feature Description
Text extraction Plain text, rich dict (font, size, color, bbox), HTML, XML, raw blocks
Table detection find_tables() — locate, extract, and export tables as Markdown or structured data
Image extraction Extract embedded images and render any page to a high-resolution Pixmap
Rendering Render PDF pages to images or Pixmap data for use in UI or other workflows
OCR Tesseract integration — full-page or partial OCR, configurable language
Annotations Read and write highlights, underlines, squiggly lines, sticky notes, free text, ink, stamps
Redaction Add and permanently apply redaction annotations
Forms Read and fill PDF AcroForm fields
PDF creation Create PDFs directly with the API or quickly convert from Markdown files
PDF editing Insert, delete, and reorder pages; set metadata; merge and split documents
Drawing Draw lines, curves, rectangles, and circles; insert HTML boxes
Encryption Open password-protected PDFs; save with RC4 or AES encryption
Links Extract hyperlinks, internal cross-references, and URI targets
Bookmarks Read and write the outline / table of contents tree
Metadata Title, author, creation date, producer, subject, and custom entries
Color spaces RGB, CMYK, greyscale; color space conversion

LLM & AI output (via PyMuPDF4LLM)

Output API
Markdown pymupdf4llm.to_markdown(path)
JSON pymupdf4llm.to_json(path)
Plain text pymupdf4llm.to_text(path)

Supports multi-column layouts, natural reading order and page chunking.

Supported Python versions

Python 3.10 – 3.14 (as of v1.27.x). Wheels ship for:

  • manylinux x86_64 and aarch64
  • musllinux x86_64
  • macOS x86_64 and arm64
  • Windows x86 and x86_64

Performance

PyMuPDF is built on MuPDF — one of the fastest PDF rendering engines available. Typical benchmarks against pure-Python PDF libraries show 10–50× speed improvements for text extraction and 100× or more for page rendering, with a minimal memory footprint.

For AI workloads, PyMuPDF4LLM processes documents without a GPU, cutting infrastructure costs significantly compared to vision-based LLM approaches.


Recipes

Extract all images from a PDF
python
import pymupdf
from pathlib import Path

doc = pymupdf.open("document.pdf")
out = Path("images")
out.mkdir(exist_ok=True)

for page_index, page in enumerate(doc):
    for img_index, img in enumerate(page.get_images()):
        xref = img[0]
        pix = pymupdf.Pixmap(doc, xref)
        if pix.n > 4:  # convert CMYK
            pix = pymupdf.Pixmap(pymupdf.csRGB, pix)
        pix.save(out / f"page{page_index}_img{img_index}.png")
Search for text across a document
python
import pymupdf

doc = pymupdf.open("document.pdf")
needle = "confidential"

for page in doc:
    hits = page.search_for(needle)
    if hits:
        print(f"Page {page.number}: {len(hits)} occurrence(s)")
        for rect in hits:
            page.add_highlight_annot(rect)

doc.save("highlighted.pdf")
Split a PDF into individual pages
python
import pymupdf

doc = pymupdf.open("document.pdf")
for i, page in enumerate(doc):
    out = pymupdf.open()
    out.insert_pdf(doc, from_page=i, to_page=i)
    out.save(f"page_{i + 1}.pdf")
Insert a watermark on every page
python
import pymupdf

doc = pymupdf.open("document.pdf")
for page in doc:
    page.insert_text(
        point=pymupdf.Point(72, page.rect.height / 2),
        text="DRAFT",
        fontsize=72,
        color=(0.8, 0.8, 0.8),
        rotate=45,
    )

doc.save("watermarked.pdf")

Office Document Processing

PyMuPDF can be extended with PyMuPDF Pro. This adds a conversion layer that handles Microsoft and Korean Office formats natively — no Office installation, no COM interop, no LibreOffice subprocess.

Once unlocked, pymupdf.open() accepts Office files exactly like PDFs:

python
import pymupdf.pro
pymupdf.pro.unlock("YOUR-LICENSE-KEY")

# Works identically regardless of format
for fmt in ["contract.docx", "data.xlsx", "deck.pptx", "report.hwpx"]:
    doc = pymupdf.open(fmt)
    for page in doc:
        print(page.get_text())

Get a trial license key for PyMuPDF Pro

What you can do with Office documents:

  • Extract text and images page-by-page
  • Convert to PDF with doc.convert_to_pdf()
  • Rasterise pages to PNG/JPEG for visual inspection
  • Feed directly into PyMuPDF4LLM for AI-ready output

Restrictions Without a License Key

When pymupdf.pro.unlock() is called without a key, the following restrictions apply:

Restriction Detail
Page limit Only the first 3 pages of any document are accessible
Time limit Evaluation period — functionality expires after a set duration

All other Pro features work normally within these constraints, making it straightforward to prototype before purchasing a license.


Frequently Asked Questions

Can I use PyMuPDF, PyMuPDF4LLM and PyMuPDF Pro without sending data to the cloud?

Yes, absolutely — and this is one of PyMuPDF's most significant advantages.

PyMuPDF runs entirely locally. It is a native Python library built on top of the MuPDF C engine. When you call pymupdf.open(), page.get_text(), page.find_tables(), or any other method, everything executes in-process on your own machine. No data is transmitted anywhere.

There are no telemetry calls, no licence validation callbacks, no cloud dependencies of any kind in the open-source AGPL build or the commercial build. Once the package is installed, it works fully air-gapped.

This makes PyMuPDF well-suited for:

  • Regulated industries — healthcare (HIPAA), finance, legal, government, where documents cannot leave a controlled environment
  • On-premise deployments — servers with no outbound internet access
  • Air-gapped systems — classified or sensitive environments
  • Self-hosted RAG pipelines — processing confidential documents locally before feeding an on-premise LLM
  • Saving on token costs for document pre-processing before sending data to your LLM

The only thing you need an internet connection for is the initial pip install. After that, the package and all its capabilities are entirely self-contained.

Should I import pymupdf

Issues· 67 open

View all issuesOpen on GitHub
  • #5140

    Page.get_label() raises IndexError when the page precedes the first label definition

    fix developedhas testUpdated Sep 28, 2026
  • #5073

    `pdfocr_tobytes` exposes four-byte row padding as black pixels to Tesseract

    Updated Sep 28, 2026
  • #5122

    `get_drawings()` reports a wrong start point for a subpath following a `re` with negative width/height

    fix developedhas testUpdated Sep 27, 2026
  • #5099

    insert_htmlbox auto base-direction ignores the UAX#9 first-strong rule for mixed RTL+LTR paragraphs

    enhancement-upstreamUpdated Sep 26, 2026
  • #5125

    `get_pixmap()` never returns on a tagged PDF page with many MCIDs — `pdf_lookup_mcid_in_mcids` is a linear scan, making rendering O(n²) per page

    upstream bugfix developedUpdated Sep 24, 2026
  • #5123

    SEGV in pdf_bound_annot / pdf_page_transform_box when reading annot rect (1.28.2, aarch64)

    Updated Sep 23, 2026
  • #5132

    Security contact / private vulnerability reporting

    Updated Sep 22, 2026
  • #5108

    Page.clip_to_rect() drops 'sh' (shading) operators

    upstream bugfix developedUpdated Sep 22, 2026
  • #5118

    SVG rendering: linearGradient fills come out black, text-anchor is not inherited from ancestor elements

    upstream bugUpdated Sep 22, 2026
  • #5115

    Pixmap export 'unmultiply' option has no effect

    documentation issuefix developedUpdated Sep 21, 2026

> Tags

Pythondata-scienceepubextract-datafont

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 29, 2026
CategoryDevOps
PricingOpen source

> Related tools

D
Docker
容器化平台,标准化应用交付
G
GitHub Actions
GitHub 原生 CI/CD 工作流
N
Nginx
高性能 Web 服务器与反向代理