PyMuPDF

pymupdfAGPL-3.0活跃维护

高性能 Python 库,用来从 PDF、EPUB 等文档中提取文本、表格和图像,并做格式转换与页面操作,适合搭建文档解析和 RAG 数据管道。

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

2.1发布于 2026-11-02 17:37 UTC11,096star +10 / 7 天835fork同步于 2026-11-10 05:29 UTC

怎么上手

由 README 提炼,执行前请确认
pip install --upgrade pymupdf
硬件要求按 README 说明

README 明确说明无需 GPU 即可处理文档;未列出具体显存或 GPU 型号要求。部分版面分析功能依赖 ONNX Runtime,需环境支持。

纯 CPU 可运行
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

基于 MuPDF 的 Python 库,用于 PDF 等文档的提取、渲染、转换与编辑

高性能 Python 库,用来从 PDF、EPUB 等文档中提取文本、表格和图像,并做格式转换与页面操作,适合搭建文档解析和 RAG 数据管道。

核心能力

  • 用 MuPDF C 引擎做像素级文本提取,带字体、颜色、位置元数据
  • find_tables() 检测表格并导出 Markdown 或 Pandas DataFrame
  • to_markdown()/to_json() 输出结构化数据供 RAG 与 LLM 管线使用
  • 支持注释、涂黑、表单填写、合并拆分与加密保存
  • 可渲染页面为任意 DPI 图像,并集成 Tesseract/RapidOCR 做 OCR

容易踩的坑

升级旧版或单独装过 pymupdf-layout/pymupdf4llm 导致安装损坏时,需用 pip install --force-reinstall --no-cache-dir pymupdf 重装;无预编译 wheel 的平台会从源码编译,需要 C/C++ 工具链;OCR 需另装 rapidocr 或系统级 Tesseract,Office 转换需 pymupdf-office 且要 license key。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本2.1
  1. 2.1PyMuPDF-2.1 released最新正式版2026-11-02 · 2026-11-02 17:37 UTC

    Wheels for Windows, Linux and MacOS, and the sdist, are available on https://pypi.org and can be installed in the usual way, for example:

    python -m pip install --upgrade pymupdf
    

    Changes in version 2.1

    Fixed issues:

    • Fixed #5196
    • Fixed #5214
    • Fixed #5216
    • Fixed #5220

    Other:

    • Improve upgrade from 1.x to 2.x via pymupdf4llm or pymupdf_layout.
    • Reduced startup time using lazy internal import of large modules.
    • Retrospectively added date of 2.0 release.
    • Retrospectively marked #5115 as fixed in 2.0.
    • Use MuPDF-1.28.6.
  2. 2.0PyMuPDF-2.0 released2026-10-19 · 2026-10-19 10:03 UTC
    查看更新说明

    Wheels for Windows, Linux and MacOS, and the sdist, are available on https://pypi.org and can be installed in the usual way, for example:

    python -m pip install --upgrade pymupdf
    

    Changes in version 2.0

    Fixed issues:

    • Fixed #4994
    • Fixed #5054
    • Fixed #5055
    • Fixed #5059
    • Fixed #5067
    • Fixed #5077
    • Fixed #5082
    • Fixed #5100
    • Fixed #5101
    • Fixed #5108
    • Fixed #5112
    • Fixed #5122
    • Fixed #5125
    • Fixed #5140
    • Fixed #5152
    • Fixed #5154
    • Fixed #5165

    Other:

    • Added support for form field hierarchies.
    • Added support for radio button groups.
    • Added support for widget aliases.
    • Fixed builds with swig-4.5.
    • Fixed https://bugs.ghostscript.com/show_bug.cgi?id=709683_ Path Traversal and Arbitrary File Write in PyMuPDF CLI Font Extraction (CVE-2026-82035)
    • Fixed ignoring aspect ratio for square images.
    • Fixed potential SEGV in pymupdf.Page.get_cdrawings() if callback raises exception.
    • Fixed use with python-3.15.
    • Remove the debug timing loop from Annot.update().
    • Retrospectively marked #3478 fixed in 1.25.3.
    • Retrospectively marked #4158 fixed in 1.27.2.2
    • Retrospectively marked #4896 fixed in 1.28.0.
    • Retrospectively marked #4918 fixed in 1.28.0.
    • Supported Python versions are now 3.11-3.15.
    • Use MuPDF-1.28.5.
    • Warning for use of deprecated fitz API now uses warnings.warn() with FutureWarning.
  3. 1.28.2PyMuPDF-1.28.2 released2026-08-06 · 2026-08-06 22:16 UTC
    查看更新说明

    Wheels for Windows, Linux and MacOS, and the sdist, are available on https://pypi.org and can be installed in the usual way, for example:

    python -m pip install --upgrade pymupdf
    

    Changes in version 1.28.2 ()

    Fixed issues:

    • Fixed #4670
    • Fixed #4943
    • Fixed #5030
    • Fixed #5042
    • Fixed #5044
    • Fixed #5049

    Other:

    • Use MuPDF-1.28.2.
    • Output warning when legacy fitz module is imported.
    • Cope better with markdown containing illegal utf8 sequences.
    • Fixed building with PYMUPDF_SETUP_MUPDF_VS_UPGRADE.
    • pymupdf.Page.find_tables():
      • new args use_layout: bool = True union: bool = False refine: bool = False.
      • Improved speed.
    • Retrospectively added fix for #4936 in release 1.28.0 below.
  4. 1.28.0PyMuPDF-1.28.0 released.2026-06-29 · 2026-06-29 09:18 UTC
    查看更新说明

    Wheels for Windows, Linux and MacOS, and the sdist, are available on https://pypi.org and can be installed in the usual way, for example:

    python -m pip install --upgrade pymupdf
    

    Changes in version 1.28.0

    Fixed issues:

    • Fixed #4114
    • Fixed #4950
    • Fixed #5001
    • Fixed #5033

    Other:

    • Use MuPDF-1.28.0.
    • pymupdf.Document.init(): new arg archive to support documents with archives.
    • pymupdf.Document.convert_to_pdf(): also generate links.
    • Fixed MacOS x64 platform tag - used to be macosx_10_9_x86_64, but we actually require MacOS 10.15, so platform tag is now macosx_10_15_x86_64.
    • Support Windows builds with free thread python.
    • pymupdf.Document.save() now saves non-PDF documents in PDF format.
    • New method pymupdf.Document.apply_css().
  5. 1.27.2.3PyMuPDF-1.27.2.3 released2026-04-24 · 2026-04-24 14:23 UTC
    查看更新说明

    Wheels for Windows, Linux and MacOS, and the sdist, are available on https://pypi.org and can be installed in the usual way, for example:

    python -m pip install --upgrade pymupdf
    

    Changes in version 1.27.2.3

    • Fixed issues:

      • Fixed #4928
      • Fixed #4942
      • Fixed #4954
      • Fixed #4958
    • Other:

      • Fixed incorrect generation of lineJoin j in PDF content, introduced in 1.27.2.2.
      • Allow build to (incorrectly) claim to be thread-safe, for #4760. See setup.py for details.
      • Use pypi.org's pipcl package instead of our own pipcl.py file.

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    PyMuPDF

    Docs PyPI Version PyPI - Python Version License AGPL PyPI Downloads Github Stars Discord Forum Twitter Hugging Face

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

    PyMuPDF is a high-performance Python library for data extraction, layout 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.

    Star on GitHub


    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 — structured data with JSON & native Markdown output for RAG and AI pipelines
    • Grounded results — improved, verifiable results, see: PyMuPDF & Grounding

    Installation

    pip install --upgrade pymupdf
    

    If you have a broken installation due to upgrading PyMuPDF from earlier versions, or from running separate installation commands for pymupdf-layout or pymupdf4llm, then please use:

    pip install --force-reinstall --no-cache-dir pymupdf
    

    This will ensure a clean installation of PyMuPDF.

    Wheels

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

    PyMuPDF uses the ONNX Runtime for certain layout analysis features - ensure your Python environment can support it. For more details see PyMuPDF Layout & ONNX Runtime

    PyMuPDF Config

    After installation, run the pymupdf-config command, This will review what is installed and show information about what other packages (Python and otherwise) may be available for your system and could improve accuracy and speed.

    Optional extras

    PackagePurpose
    pymupdf-officeAdds Office document support
    pymupdf-fontsExtended font collection for text output
    rapidocrOCR engine (recommended)
    tesseract-ocrOCR engine
    # Office support
    pip install pymupdf-office
    
    # More fonts
    pip install pymupdf-fonts
    
    # OCR
    pip install rapidocr
    
    # OCR (Tesseract must be installed separately)
    # macOS
    brew install tesseract
    
    # Ubuntu / Debian
    sudo apt install tesseract-ocr
    

    OCR Support

    We compared both OCR engines on the ExtractBench document corpus:

    Document lengthPDFsPyMuPDF + TesseractPyMuPDF + RapidOCR
    Short, 1–10 pages25280.39%88.94%
    Medium, 11–50 pages9882.72%87.00%
    Long, over 50 pages2030.49%29.22%
    Overall37078.31%85.20%

    Overall, for the best OCR accuracy, it is recommended to use RapidOCR.

    Supported File Formats

    Input

    CategoryFormats
    PDF & derivativesPDF, XPS, EPUB, CBZ, MOBI, FB2, SVG, TXT, MD
    ImagesPNG, JPEG, BMP, TIFF, GIF, and more
    PyMuPDF OfficeDOC, DOCX, XLS, XLSX, PPT, PPTX, HWP, HWPX

    Output

    FormatNotes
    PDFFull fidelity conversion from Office formats
    SVGVector page rendering
    Image (PNG, JPEG, …)Page rasterisation at any DPI
    MarkdownStructure-aware, LLM-ready
    JSONBounding boxes, layout data, per-element detail
    Plain textFast, lightweight extraction

    Quick start

    Extract text

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

    Extract text with layout metadata

    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

    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

    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

    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

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

    Convert to Markdown for LLMs

    import pymupdf
    
    doc = pymupdf.open("report.pdf")
    md = doc.to_markdown()
    # Pass directly to your LLM or vector store
    print(md)
    

    Annotate and redact

    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

    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

    import pymupdf.office
    
    pymupdf.office.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

    import pymupdf.office
    
    pymupdf.office.unlock("YOUR-LICENSE-KEY")
    
    pymupdf.office.to_markdown("input.docx", "output.md")
    

    Features

    Core capabilities

    FeatureDescription
    Text extractionPlain text, rich dict (font, size, color, bbox), HTML, XML, raw blocks
    Table detectionfind_tables() — locate, extract, and export tables as Markdown or structured data
    Image extractionExtract embedded images and render any page to a high-resolution Pixmap
    RenderingRender PDF pages to images or Pixmap data for use in UI or other workflows
    OCRTesseract integration — full-page or partial OCR, configurable language
    AnnotationsRead and write highlights, underlines, squiggly lines, sticky notes, free text, ink, stamps
    RedactionAdd and permanently apply redaction annotations
    FormsRead and fill PDF AcroForm fields
    PDF creationCreate PDFs directly with the API or quickly convert from Markdown files
    PDF editingInsert, delete, and reorder pages; set metadata; merge and split documents
    DrawingDraw lines, curves, rectangles, and circles; insert HTML boxes
    EncryptionOpen password-protected PDFs; save with RC4 or AES encryption
    LinksExtract hyperlinks, internal cross-references, and URI targets
    BookmarksRead and write the outline / table of contents tree
    MetadataTitle, author, creation date, producer, subject, and custom entries
    Color spacesRGB, CMYK, greyscale; color space conversion

    LLM & AI output

    doc = pymupdf.open("document.pdf") , then:

    OutputAPI
    Markdowndoc.to_markdown(path)
    JSONdoc.to_json(path)
    Plain textdoc.to_text(path)

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


    Supported Python versions

    Python 3.11 – 3.15 (as of v2.0). 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.

    PyMuPDF processes documents without a GPU, cutting infrastructure costs significantly compared to vision-based LLM approaches.


    Recipes

    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")
    
    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")
    
    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")
    
    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 Office. 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:

    import pymupdf.office
    pymupdf.office.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 Office

    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

    Restrictions Without a License Key

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

    RestrictionDetail
    Page limitOnly the first 3 pages of any document are accessible
    Time limitEvaluation period — functionality expires after a set duration

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


    Frequently Asked Questions

    Can I use PyMuPDF and PyMuPDF Office 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 or import fitz?

    Use import pymupdf. The fitz name is a legacy alias that still works as of v1.24.0+, but import pymupdf is the recommended and future-proof approach. The two are interchangeable in existing code:

    import pymupdf          # recommended
    # import fitz           # legacy alias — still works but avoid for new code
    

    Does PyMuPDF work with Korean, Japanese, or Chinese documents?

    Yes — PyMuPDF has solid CJK support

    How do I extract Markdown from PDF for LLM?

    This is the best starting point for feeding an LLM or building a RAG pipeline.

    import pymupdf
    
    doc = pymupdf.open("report.pdf")
    md = doc.to_markdown()
    print(md)
    # Tables appear as Markdown | col1 | col2 | ... inline with the text
    

    Text extraction returns garbled characters or empty output. Why?

    This usually means the PDF uses custom font encodings without a proper character map (CMAP). The font's glyphs are present but cannot be mapped back to Unicode. In these cases:

    • Use OCR as a fallback (page.get_textpage_ocr())
    • Consider that scanned PDFs will always need OCR — text extraction on scans returns nothing

    How do I extract text from a specific area of a page?

    Pass a clip rectangle to get_text():

    import pymupdf
    
    doc = pymupdf.open("input.pdf")
    page = doc[0]
    
    # Define the area you want (x0, y0, x1, y1) in points
    clip = pymupdf.Rect(50, 100, 400, 300)
    text = page.get_text("text", clip=clip)
    

    How do I search for text and find its location on the page?

    import pymupdf
    
    doc = pymupdf.open("input.pdf")
    page = doc[0]
    
    # Returns a list of Rect objects surrounding each match
    locations = page.search_for("invoice number")
    for rect in locations:
        print(rect)  # e.g. Rect(72.0, 120.5, 210.0, 134.0)
    

    get_images shows no images but I can clearly see charts in the PDF. Why?

    Charts and diagrams created by tools like matplotlib, Excel, or R are typically rendered as vector graphics (PDF drawing commands), not raster images. get_images only lists embedded raster image objects and will not detect vector graphics. To capture these, rasterise the entire page with page.get_pixmap().

    How does OCR work in PyMuPDF? Does it require a separate Tesseract installation?

    PyMuPDF uses MuPDF's built-in Tesseract-based OCR support, so there is no Python-level pytesseract dependency. However, PyMuPDF still needs access to the Tesseract language data files (tessdata), and automatic tessdata discovery may invoke the tesseract executable (for example, to list available languages) if you do not explicitly provide a tessdata path. In practice, the recommended setup is to either install Tesseract so discovery works automatically, or configure the tessdata location yourself via the tessdata parameter or the TESSDATA_PREFIX environment variable. Over 100 languages are supported.

    PyMuPDF also supports RapidOCR - which is the recommended OCR engine - RapidOCR is a pip-installable Python package that runs ONNX models, so it doesn't need a separate Tesseract install or TESSDATA_PREFIX.

    import pymupdf
    
    doc = pymupdf.open("scanned.pdf")
    page = doc[0]
    
    # Get a text page using OCR
    tp = page.get_textpage_ocr(language="eng")
    text = page.get_text(textpage=tp)
    print(text)
    

    How do I run OCR on a standalone image file (not a PDF)?

    import pymupdf
    
    pix = pymupdf.Pixmap("image.png")
    if pix.alpha:
        pix = pymupdf.Pixmap(pix, 0)  # remove alpha channel — required for OCR
    
    # Wrap in a 1-page PDF and OCR it
    doc = pymupdf.open()
    page = doc.new_page(width=pix.width, height=pix.height)
    page.insert_image(page.rect, pixmap=pix)
    tp = page.get_textpage_ocr()
    text = page.get_text(textpage=tp)
    

    How do I highlight text in a PDF?

    import pymupdf
    
    doc = pymupdf.open("input.pdf")
    page = doc[0]
    
    # Use quads=True for accurate highlights on non-horizontal text
    quads = page.search_for("important term", quads=True)
    page.add_highlight_annot(quads)
    
    doc.save("highlighted.pdf")
    

    PyMuPDF supports all standard PDF text markers: highlight, underline, strikeout, and squiggly.

    How do I permanently redact (remove) content from a PDF?

    Redaction is a deliberate two-step process so you can review before committing:

    import pymupdf
    
    doc = pymupdf.open("input.pdf")
    page = doc[0]
    
    # Step 1: Mark the area(s) to redact
    rect = page.search_for("confidential")[0]
    page.add_redact_annot(rect, fill=(1, 1, 1))  # white fill
    
    # Step 2: Apply — permanently removes the underlying content
    page.apply_redactions()
    
    doc.save("redacted.pdf")
    

    After apply_redactions(), the original content is gone. It cannot be recovered from the saved file.

    How do I read form field values from a PDF?

    import pymupdf
    
    doc = pymupdf.open("form.pdf")
    page = doc[0]
    
    for field in page.widgets():
        print(f"{field.field_name}: {field.field_value}")
    

    How do I fill in a PDF form programmatically?

    import pymupdf
    
    doc = pymupdf.open("form.pdf")
    page = doc[0]
    
    for field in page.widgets():
        if field.field_name == "First Name":
            field.field_value = "Ada"
            field.update()
    
    doc.save("filled_form.pdf")
    

    Can I use multithreading with PyMuPDF?

    No. PyMuPDF does not support multithreaded use, even with Python's newer free-threading mode. The underlying MuPDF library only provides partial thread safety, and a fully thread-safe PyMuPDF implementation would still impose a single-threaded overhead — negating the benefit.

    Use multiprocessing instead. Each process opens the file independently and works on its own page range:

    from multiprocessing import Pool
    import pymupdf
    
    def process_pages(args):
        path, start, end = args
        doc = pymupdf.open(path)  # each process opens its own handle
        results = []
        for i in range(start, end):
            results.append(doc[i].get_text())
        return results
    
    with Pool(4) as pool:
        chunks = [("input.pdf", 0, 25), ("input.pdf", 25, 50), ...]
        all_results = pool.map(process_pages, chunks)
    

    How can I speed up repeated text extraction on the same page?

    Reuse a TextPage object. Creating a TextPage is the expensive part — once created, switching between extraction formats is cheap:

    import pymupdf
    
    page = doc[0]
    tp = page.get_textpage()  # create once
    
    text  = page.get_text("text",    textpage=tp)
    words = page.get_text("words",   textpage=tp)
    data  = page.get_text("dict",    textpage=tp)
    

    This can reduce execution time by 50–95% for repeated extractions on the same page.

    How do I read and write PDF metadata?

    import pymupdf
    
    doc = pymupdf.open("input.pdf")
    
    # Read
    print(doc.metadata)
    # {'title': '...', 'author': '...', 'subject': '...', 'keywords': '...', ...}
    
    # Write
    doc.set_metadata({
        "title": "Annual Report 2025",
        "author": "Finance Team",
        "keywords": "annual, finance, 2025"
    })
    doc.save("output.pdf")
    

    How do I read or set the table of contents / bookmarks?

    import pymupdf
    
    doc = pymupdf.open("input.pdf")
    
    # Read — returns a list of [level, title, page_number] entries
    toc = doc.get_toc()
    for level, title, page in toc:
        print(" " * level, title, "→ page", page)
    
    # Write
    new_toc = [
        [1, "Introduction",  1],
        [1, "Methods",       5],
        [2, "Data sources",  6],
    ]
    doc.set_toc(new_toc)
    doc.save("output.pdf")
    

    Documentation

    Full installation guide, API reference, cookbook, and tutorial at pymupdf.readthedocs.io.


    Licensing

    PyMuPDF and MuPDF are maintained by Artifex Software, Inc.

    • Open source — GNU AGPL v3. Free for open-source projects.
    • Commercial — separate commercial licences available from Artifex for proprietary applications.

    Contributing

    Contributions are welcome. Please open an issue before submitting large pull requests.

    ⭐ Support this project

    If you find this useful, please consider giving it a star — it helps others discover it!

    Star on GitHub