pymupdf4llm-rs
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,/Pagesattribute inheritance,/Subtype /FormXObject recursion,FlateDecode,LZWDecode,ASCIIHexDecode) using pure-Rustflate2(rust_backend). - Async & High-Concurrency Execution:
- Zero-copy
Arc<PdfDocument>shared across async page tasks. - Bounded
tokio::sync::Semaphore+rayonwork-stealing CPU pool (to_markdown_async,to_markdown_stream,batch_to_markdown_async). - Lock-free
DashMapfont &ToUnicodecache across concurrent workers.
- Zero-copy
- Full
pymupdf4llmParity:to_markdown(),to_markdown_with_options(),to_json(),to_text(),LlamaMarkdownReader.page_chunks = trueemittingPageChunk(metadata,toc_items,tables,images,graphics,words,text,hygiene).IdentifyHeaders(character-weighted font histogram) &TocHeaders(/Outlinesbookmark mapping).- All 4
table_strategymodes (LinesStrict,Lines,Text,Explicit), recursive X-Y Cut multi-column reading order, code blocks, lists, andpage_separators.
- Advanced Text Hygiene & High-Performance Algorithms (
v0.4.0):- 2D
SpatialGridfor $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/Wwidths,beginbfchar& arraybeginbfrangeToUnicodeCMaps,MacRomanEncoding,WinAnsiEncoding, 70+ Adobe Glyph names, and/Rotatenormalization. - Noise & Mojibake Cleanup (
TextHygieneConfig): Ligature expansion (ff,fi,fl,ffi,ffl,ſt), PUA icon normalization & unmapped PUA/control stripping, line-wrap de-hyphenation,3 Trinvisible OCR filtering, rotated/translucent watermark filtering, faux-bold deduplication, and optional cross-page running header/footer removal.
- 2D
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 directly from GitHub)
Install directly into any Python (>= 3.9) project via pip (requires Rust toolchain rustc/cargo on the build host, or download prebuilt .whl files from GitHub Releases with zero Rust toolchain):
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.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| pymupdf4llm_rs-0.4.0.tar.gz | 102.5 kB | Without provenance | Details for pymupdf4llm_rs-0.4.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pymupdf4llm_rs-0.4.0-cp39-abi3-win_amd64.whl | CPython 3.9 | abi3 | Windows x86-64 | Details for pymupdf4llm_rs-0.4.0-cp39-abi3-win_amd64.whl |
Total release size: 921.1 kB
Release files / pymupdf4llm_rs-0.4.0.tar.gz
| Download URL | pymupdf4llm_rs-0.4.0.tar.gz |
|---|---|
| Size | 102.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
383faa75cb2b85669f796b201516699c94e802730e1872f9a24d913293cdc938
|
|
BLAKE2b-256 checksum How to use checksums |
41ff9f7deb4f217bb128f7a226e833dc4e87c9e5a50c7bba20482bf4d2904c73
|
| 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.0-cp39-abi3-win_amd64.whl
| Download URL | pymupdf4llm_rs-0.4.0-cp39-abi3-win_amd64.whl |
|---|---|
| Size | 818.6 kB |
| Tags | CPython 3.9 Windows x86-64 abi3 |
|
SHA-256 checksum How to use checksums |
8fcd968d0d780a44fdc6419973c62dfb18e780ed3a9c62d81b56cd7aa2fce66d
|
|
BLAKE2b-256 checksum How to use checksums |
61318c6273327d8cf0b580e5858fad202274cdac4c8761fef982e16787c0fb30
|
| 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.0
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.