Skip to main content

pymupdf4llm-rs

English | 简体中文

100% Pure-Rust pymupdf4llm PDF-to-Markdown Library & CLI Tool

pymupdf4llm-rs is a zero-C-dependency, pure-Rust reimplementation of pymupdf4llm designed for high-throughput LLM & RAG document ingestion with Tokio + Rayon concurrency.


Core Highlights

  • 100% Pure Rust (no C/C++ FFI): Built-in PDF 1.0–2.0 binary parser (XRef, ObjStm, /Pages attribute inheritance, /Subtype /Form XObject recursion, FlateDecode, LZWDecode, ASCIIHexDecode) using pure-Rust flate2 (rust_backend).
  • Async & High-Concurrency Execution:
    • Zero-copy Arc<PdfDocument> shared across async page tasks.
    • Bounded tokio::sync::Semaphore + rayon work-stealing CPU pool (to_markdown_async, to_markdown_stream, batch_to_markdown_async).
    • Lock-free DashMap font & ToUnicode cache across concurrent workers.
  • Full pymupdf4llm Parity:
    • to_markdown(), to_markdown_with_options(), to_json(), to_text(), LlamaMarkdownReader.
    • page_chunks = true emitting PageChunk (metadata, toc_items, tables, images, graphics, words, text, hygiene).
    • IdentifyHeaders (character-weighted font histogram) & TocHeaders (/Outlines bookmark mapping).
    • All 4 table_strategy modes (LinesStrict, Lines, Text, Explicit), recursive X-Y Cut multi-column reading order, code blocks, lists, and page_separators.
  • Advanced Text Hygiene & High-Performance Algorithms (v0.4.1):
    • 2D SpatialGrid for $O(1)$ average-case hyperlink matching and table cell lookups.
    • UnionFind (DSU) connected components to isolate multiple independent tables per page and cluster vector graphics in $O(N \cdot \alpha(N))$.
    • Broad Encoding & CJK Support: Type0/CID /W widths, beginbfchar & array beginbfrange ToUnicode CMaps, MacRomanEncoding, WinAnsiEncoding, 70+ Adobe Glyph names, and /Rotate normalization.
    • Noise & Mojibake Cleanup (TextHygieneConfig): Ligature expansion (ff, fi, fl, ffi, ffl, ſt), PUA icon normalization & unmapped PUA/control stripping, line-wrap de-hyphenation, 3 Tr invisible OCR filtering, rotated/translucent watermark filtering, faux-bold deduplication, and optional cross-page running header/footer removal.

Quick Start

Library Usage

[dependencies]
pymupdf4llm-rs = { path = "." }
tokio = { version = "1", features = ["full"] }
use pymupdf4llm_rs::{
    to_markdown_async, MarkdownOutput, TableStrategy, ToMarkdownOptions,
};

#[tokio::main]
async fn main() -> pymupdf4llm_rs::Result<()> {
    let opts = ToMarkdownOptions::builder()
        .page_chunks(true)
        .table_strategy(TableStrategy::LinesStrict)
        .extract_words(true)
        .max_page_concurrency(8)
        .build();

    match to_markdown_async("paper.pdf", opts).await? {
        MarkdownOutput::Chunks(chunks) => {
            for chunk in chunks {
                println!(
                    "Page {}: {} chars, {} tables",
                    chunk.metadata.page,
                    chunk.text.len(),
                    chunk.tables.len()
                );
            }
        }
        MarkdownOutput::Text(md) => println!("{md}"),
    }
    Ok(())
}

Web Service / High-Concurrency Singleton (PdfEngine::global)

For web backends (Axum / Actix / Tonic) handling many concurrent uploads, use the shared PdfEngine singleton (OnceLock<Arc<PdfEngine>>) to cap global in-flight documents/pages and reuse identical parsed ToUnicode CMaps safely across requests:

use pymupdf4llm_rs::{PdfEngine, ToMarkdownOptions};

let output = PdfEngine::global()
    .extract_bytes(pdf_bytes, ToMarkdownOptions::default())
    .await?;

Python Package (pip install from PyPI or GitHub)

Install directly into any Python (>= 3.9) project via pip from PyPI (or from source via GitHub with a Rust toolchain rustc/cargo, or download prebuilt .whl files from GitHub Releases):

# Install from PyPI (recommended)
pip install pymupdf4llm-rs

# Or install directly from GitHub
pip install git+https://github.com/0passion0/pymupdf4llm-rs.git
# Or pin in requirements.txt:
# pymupdf4llm-rs @ git+https://github.com/0passion0/pymupdf4llm-rs.git@main

For local extension development:

pip install maturin pytest
maturin develop --release
pytest -v tests/test_python_api.py

Instantiate PdfExtractor once per worker/service to hold shared Rust resources (Arc<PdfEngine>, bounded semaphores, Tokio runtime, global ToUnicode CMap cache, and max_pdf_bytes / max_pages safety limits), and reuse its methods across requests:

from pymupdf4llm_rs import PdfExtractor

# Instantiate once and reuse across HTTP requests / batch workers
extractor = PdfExtractor(
    table_strategy="lines_strict",
    clean_mojibake=True,
    strip_watermarks=True,
    ignore_invisible_text=True,
    max_concurrent_docs=4,
    max_concurrent_pages=8,
    max_pdf_bytes=64 * 1024 * 1024,  # reject oversized payloads before parsing
    max_pages=500,
)

# Reuse configured defaults directly (Python GIL released during Rust parsing)
md = extractor.to_markdown("paper.pdf")
md_from_bytes = extractor.to_markdown_bytes(pdf_bytes)
chunks = extractor.to_chunks("paper.pdf", extract_words=True)

# Lightweight derived preset sharing the SAME underlying Arc<PdfEngine>
fast_text_extractor = extractor.with_options(table_strategy="text", ignore_code=True)

# Or parse once into ParsedPdf and extract multiple views without re-parsing
with extractor.open(pdf_bytes) as doc:
    meta = doc.metadata()
    toc = doc.toc()
    md = doc.to_markdown()
    chunks = doc.to_chunks()
    json_str = doc.to_json()
    plain = doc.to_text()

CLI Tool Usage

cargo run --release --features cli -- paper.pdf --page-chunks --concurrency 8 -o output.json
cargo test --features "async,cli,images"

Crate Structure

.
├── Cargo.toml
├── pyproject.toml                 # Maturin build configuration for Python wheel (abi3-py39)
├── python/pymupdf4llm_rs/         # Python wrapper, PEP 484 .pyi stubs, LlamaMarkdownReader
├── src/
│   ├── lib.rs                     # Public API (to_markdown, to_json, to_text, PageChunk)
│   ├── python.rs                  # PyO3 native extension (PdfExtractor, ParsedPdf, GIL release)
│   ├── async_engine.rs            # Tokio semaphore + Rayon bounded concurrency & streaming
│   ├── config.rs                  # ToMarkdownOptions, TableStrategy, TextHygieneConfig
│   ├── text_cleaner.rs            # Mojibake, PUA, 3 Tr OCR, watermark, faux-bold & header hygiene
│   ├── llama_reader.rs            # LlamaMarkdownReader integration
│   ├── pdf/                       # Binary lexer, Flate/LZW/A85/RLE decoders (64MB capped), CMap cache
│   ├── layout/                    # SpatialGrid, UnionFind tables, X-Y Cut columns, header detection
│   ├── markdown/                  # PageChunk & Markdown renderer, de-hyphenation, link merging
│   └── bin/pymupdf4llm.rs         # CLI binary
└── tests/
    ├── compatibility_tests.rs     # Rust integration tests (multi-column, CJK, Form XObject, async)
    └── test_python_api.py         # Pytest suite for PdfExtractor, ParsedPdf, safety bounds & threads

License

Dual-licensed under Apache-2.0 OR MIT.

Metadata

Release files for pymupdf4llm-rs 0.4.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pymupdf4llm-rs 0.4.1
File Size Uploaded Provenance Actions
pymupdf4llm_rs-0.4.1.tar.gz 102.6 kB Without provenance Details for pymupdf4llm_rs-0.4.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pymupdf4llm-rs 0.4.1
File Interpreter ABI Platform Actions
pymupdf4llm_rs-0.4.1-cp39-abi3-win_amd64.whl CPython 3.9 abi3 Windows x86-64 Details for pymupdf4llm_rs-0.4.1-cp39-abi3-win_amd64.whl

Total release size: 886.2 kB

Release files / pymupdf4llm_rs-0.4.1.tar.gz

Download URL pymupdf4llm_rs-0.4.1.tar.gz
Size 102.6 kB
Tags Source
SHA-256 checksum
How to use checksums
7eec0371d581f8b23d4d655b8d2043d4c1668f9f7b45aac2a56e5f39f37791dd
BLAKE2b-256 checksum
How to use checksums
244d3325b4cac9ffacafd8c06c66dcc192a6346cd66417c029bfc23740032006
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.11

Release files / pymupdf4llm_rs-0.4.1-cp39-abi3-win_amd64.whl

Download URL pymupdf4llm_rs-0.4.1-cp39-abi3-win_amd64.whl
Size 783.6 kB
Tags CPython 3.9 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
02c161b40de29f1f002c2f5e7e975e82ee1ccca974fcc86e164dbb0c2f46e90e
BLAKE2b-256 checksum
How to use checksums
2bb1be0c8aa438a1d4b2b5560e180330f8c00ecc82d8c4e8076bdf30eee9b531
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.11

Security for pymupdf4llm-rs 0.4.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page