pypdftomd
Local-first Python library and CLI for converting PDFs into layout-aware Markdown.
Benchmarks · Architecture · Output · Install · Agent skill · Usage · Limitations · License
Overview
pypdftomd converts digital PDFs into structured Markdown on local CPU using deterministic PyMuPDF geometry for RAG ingestion and privacy-sensitive document pipelines.
- Deterministic CPU geometry: Reconstructs multi-column reading order, headings, lists, and tables directly from embedded PDF geometry without external APIs, GPUs, or neural layout models.
- Fail-loud reliability signals: Emits inline
<!-- extraction-warning: ... -->HTML comments andstderrsummaries whenever Type3 fonts, unmapped glyphs, chart grids, or OCR failures make page content unreliable. - Native link and math-font fidelity: Preserves external HTTP(S) PDF annotations as Markdown links, decodes baseline-shifted superscripts/subscripts to Unicode, and handles TeX/AMS math font families.
- Opt-in local OCR and preflight routing: Inspects encryption and page text quality via
--analyzeand--metadata, with selective whole-page OCR fallback via local Tesseract or RapidOCR.
Benchmarks and trade-offs
Full 200-document OpenDataLoader benchmark quality scores (200 NID, 42 TEDS, 107 MHS; zero missing predictions; 0 to 1, higher is better; column leaders in bold). Speed and memory are measured separately.
| Extractor | Overall | NID | NID-S | TEDS | TEDS-S | MHS | MHS-S |
|---|---|---|---|---|---|---|---|
PDFtoMD 0.3.51 (renamed pypdftomd in 0.4.0) |
0.902 | 0.926 | 0.928 | 0.845 | 0.861 | 0.850 | 0.913 |
| Docling 2.155.0 | 0.892 | 0.906 | 0.859 | 0.925 | 0.944 | 0.830 | 0.905 |
| Liteparse 2.21.5 | 0.891 | 0.918 | 0.922 | 0.823 | 0.841 | 0.838 | 0.901 |
| OpenDataLoader hybrid 2.5.24 | 0.880 | 0.920 | 0.910 | 0.676 | 0.911 | 0.823 | 0.888 |
| pdf-inspector 1.27.0 | 0.870 | 0.911 | 0.901 | 0.800 | 0.842 | 0.777 | 0.859 |
| OpenDataLoader plain 2.5.24 | 0.843 | 0.913 | 0.917 | 0.483 | 0.506 | 0.757 | 0.837 |
Benchmark pins, metric definitions, and peer settings
- Corpus and evaluator pins:
opendataloader-benchcommit7af1d8f4d0c09f51ea1a5c6ba5f66e993286d109, evaluator digest99c22bd79c2fe4ada21c86c57f4ddc174a8c862f59a41f7d6635d31ce7a22942. Full-corpus rows cover the same 200 PDFs with zero missing predictions (200NID/NID-S,42reference-table TEDS/TEDS-S,107MHS/MHS-S). - PDFtoMD 0.3.51 configuration:
ocr_fallback=False,cache_dir=None,page_breaks=False,workers=1on PyMuPDF 2.2 (evaluated prior to thepypdftomdpackage rename in0.4.0). Peer rows use pinned releases from a frozen peer comparison under their recorded extraction settings (including model and OCR differences where enabled), comparing as-run output quality rather than isolating a single mechanism. - Metrics (0 to 1, higher is better): Overall is the per-document mean of available NID, TEDS, and MHS scores averaged across all 200 documents (not the mean of the three column means). NID measures normalized text sequence similarity across the full Markdown output; NID-S measures the same text comparison after removing tables. TEDS measures table structure and cell text similarity; TEDS-S measures table structure without cell text. MHS measures heading and content grouping similarity, and MHS-S measures that grouping structure without text; the evaluator treats all heading levels (
#,##, etc.) as equivalent. - Partial and separate peer runs (not ranked above): Marker 2.0.0 was evaluated only on a 68-document hard subset (42 TEDS, 36 MHS) and cannot be ranked against full-corpus rows. PyMuPDF4LLM 2.1 was evaluated separately in a pairwise 200-document comparison against an earlier baseline on the same corpus and evaluator and was not rerun on 0.3.51.
- Peer settings: Docling (
DocumentConverter().convert(...).document.export_to_markdown(), native text plus conditional OCR) and OpenDataLoader hybrid (hybrid='docling-fast'with Docling 2.155.0 CPU backend, 97/200 routed) ran on CPU with layout and table models. Liteparse (ocroff,extract_linksfalse), pdf-inspector, and OpenDataLoader plain (table_method='cluster') ran rule-based extraction without models.
When to use pypdftomd
| Workload | Recommended path |
|---|---|
| Digital reports, papers, and multi-column PDFs | Default native mode (pypdftomd report.pdf -o report.md) |
| Unknown or mixed digital/scanned batches | Preflight with --analyze, then extract with --ocr-fallback |
| High-throughput text and tables without heading reflow | Fast mode (--fast) |
| Heavy borderless/multi-span tables or degraded scans | Consider neural layout models such as Docling |
- Where pypdftomd works well: Leads all full-corpus peers on Overall (0.902), NID (0.926), NID-S (0.928), MHS (0.850), and MHS-S (0.913) using CPU geometry alone — ahead of Docling (0.892) with zero model dependencies: no weights, no GPU. Preserving native HTTP(S) links as
[label](url)carries a small measured NID cost because the evaluator counts link syntax as text difference—a trade-off accepted for link fidelity. - Where peers lead: Docling 2.155.0 leads on TEDS (0.925 vs. 0.845) and TEDS-S (0.944 vs. 0.861), and OpenDataLoader hybrid 2.5.24 leads on TEDS-S (0.911 vs. 0.861); neural table-structure models outperform rule-based grids on borderless, multi-span, and tight-gutter layouts. Region-level OCR and semantic heading models also outperform whole-page OCR fallback and font-tier heuristics on scanned pages and unstyled headings.
Rerun every score above from pinned versions with the benchmark reproduction repository (pinned dependencies and evaluation scripts, without redistributing third-party corpus PDFs).
Architecture
Each page runs through a region-first pipeline so tables, figures, equations, and prose claim words exclusively before Markdown assembly:
flowchart LR
A["Preflight and Page Selection"] --> B["Single-Pass Page Geometry"]
B --> C["Region Typing"]
C --> D["Exclusive Word Ownership"]
D --> E["Region Interpretation"]
E --> F["Reading-Order Flow and Emission"]
F -. "Opt-in --ocr-fallback" .-> G["Local OCR Merge"]
| Element | Mechanism |
|---|---|
| Headings | Document-wide font-tier clustering with bold/TeX-bold detection, numbered-sequence and sidebar promotion, and heading vetoes for captions, lists, TOC entries, and prose fragments. |
| Multi-column reading order | Recursive layout cuts (GUTTER_EM gutters), column splitting with untouched-order preservation, and unified reading-order flow across regions. |
| Tables | Detects stroked frames, painted fill/shading rules, booktabs rule bands, and aligned borderless runs; one page analysis feeds both inline GFM tables and CSV/bbox exports. |
| Math and scripts | Identifies TeX/AMS/Symbol math fonts (cmmi, cmsy, cmex, msam, msbm, texcm, math, symbol, standardsyml), remaps malformed TeXCMMathsSymbols operators, and converts baseline-shifted or flagged runs to Unicode superscripts/subscripts. |
| Native links | Maps external HTTP(S) PDF link annotations onto decoded word spans as Markdown [label](url) links. |
| Figures and vector art | Filters raster icons smaller than 30 units, bounds vector-path inspection so complex drawings do not stall text extraction, and exports clustered dense vector figures as cropped PNGs when --images-output is set. |
What the output looks like
With --include-summary, line 1 records a machine-readable verdict alongside 1-indexed page markers, inline GFM tables, preserved links, Unicode scripts, and fail-loud page warnings:
<!-- extraction-summary: pages_with_warnings=[2] warning_counts={unmapped_glyphs:1} -->
<!-- Page 1 -->
## Quarterly Summary
Revenue rose 12 percent under the [Q4 filing](<https://example.com/q4>) with variance σ² ≤ 0.04 across sites
| Region | Units | Margin |
| --- | --- | --- |
| North | 1,420 | 31.4% |
| South | 1,185 | 28.9% |
---
<!-- Page 2 -->
<!-- extraction-warning: page contains 1 block(s) with unmapped glyphs (font lacks ToUnicode mapping; renderer shows �); equations/tables on this page may be corrupt — visually verify against the rendered page image -->
Appendix notes with partial glyph decoding.
In-band warning keys
warning_counts counts pages carrying each key (never body-prose lookalikes, which are backslash-escaped on assembly):
type3— Page uses a Type3 font lacking a usable/ToUnicodemap.unmapped_glyphs— One or more text blocks contain unresolved glyph replacement characters (\ufffd).chart_grid_table— Table was reconstructed over chart-like vector marks; cell associations may be unreliable.low_confidence— Local OCR returned low recognition confidence.empty_ocr— Local OCR produced no readable text on an image-only or unreadable page.ocr_timeout— OCR timed out or failed on the page; embedded text was retained.ocr_page_render_failed— OCR could not load or render the page.ocr_backend_unavailable— Requested OCR backend is missing; embedded text was retained.embedded_extraction_failed— Embedded page text extraction failed; page content is incomplete.table_detection_failed— Table detection failed on the page; prose-only fallback was kept.
Install
See the changelog for changes by version.
pypdftomd is published on PyPI and GitHub Releases, and requires Python 3.12 or newer.
Run ephemerally or install the CLI with uv:
# Run without installing permanently
uvx pypdftomd report.pdf
uvx --from 'pypdftomd[ocr-tesseract]' pypdftomd report.pdf --ocr-fallback
# Install the CLI tool globally
uv tool install pypdftomd
pypdftomd --help
If pypdftomd is not on your PATH after uv tool install, run uv tool update-shell and restart your shell. To install the Python library or CLI with pip:
pip install pypdftomd
# Optional local OCR backends
pip install "pypdftomd[ocr-tesseract]"
pip install "pypdftomd[ocr-rapid]"
GitHub Releases wheel fallback, source checkout, and OCR prerequisites
- GitHub Releases wheel: Download
pypdftomd-<version>-py3-none-any.whlfrom GitHub Releases and install withpip install ./pypdftomd-<version>-py3-none-any.whloruv tool install --python 3.12 <wheel-url>. - Source checkout: Run
pip install .(orpip install ".[ocr-tesseract]"/pip install ".[ocr-rapid]"). - Tesseract (
[ocr-tesseract]): Requires thetesseractbinary onPATHor theTESSERACT_CMDenvironment variable pointing to the executable. - RapidOCR (
[ocr-rapid]): Installsrapidocr,onnxruntime, andopencv-python-headlessfor detection-first PP-OCRv6; useful on photo pages or sparse captions, weaker on dense equations.
Coding agent skill
Install the pypdftomd skill in a coding agent that supports the Agent Skills format:
gh skill install MattBetancourt/pypdftomd pypdftomd
npx skills add MattBetancourt/pypdftomd --skill pypdftomd
For a manual install, copy the skills/pypdftomd folder into your agent's skill
directory. Use .agents/skills/ in the project for Codex or .claude/skills/
for Claude Code. Make sure pypdftomd (or uvx pypdftomd) is runnable in the
environment the agent uses to run commands.
Try asking your agent, “Use the pypdftomd skill to convert pages 3–7 of
report.pdf to report.md.”
Usage
CLI
# Extract Markdown to stdout or a file
pypdftomd report.pdf
pypdftomd report.pdf -o report.md
# Select pages, tune workers, and enable selective OCR fallback
pypdftomd report.pdf --pages 1-5 --workers 2 --ocr-fallback -o report.md
# Process a directory tree, or emit structured reports for several PDFs
pypdftomd ./incoming --recursive --output-dir ./reports
pypdftomd first.pdf second.pdf --json
# Check the selected local OCR backend before processing
pypdftomd --check-ocr --ocr-engine rapid
# Export images, contact sheet, and CSV tables in one run
pypdftomd report.pdf --images-output ./images --contact-sheet sheet.png --tables-output ./tables -o report.md
| Flag | Effect |
|---|---|
-o, --output PATH |
Write UTF-8 LF Markdown for one PDF to PATH (default: stdout); -o - explicitly selects stdout. |
-r, --recursive |
Include nested PDFs in directory inputs; without it, only direct PDF children are selected. |
--output-dir DIR |
Write a source-qualified Markdown or JSON report per PDF; required for multi-PDF Markdown. Mutually exclusive with -o. |
--json |
Emit structured reports with Markdown, page and warning details, and artifact paths. Multi-PDF stdout contains a documents array. |
-q, --quiet |
Suppress incidental status and batch summary lines while retaining primary output and diagnostics. |
--fail-on-warning |
Publish outputs and exit 3 if any extracted document has a page warning; hard errors exit 1. |
-V, --version |
Print the version and exit. |
--pages SPEC |
1-indexed page selection, e.g. 1-3,7 (default: all pages). |
--workers N |
Worker processes (default: auto min(cpu_count, pages, 8) capped by RAM at ~500 MiB/worker). |
--fast |
Skip heading-tier clustering and paragraph reflow while keeping reading order, tables, and warnings. |
--plain |
Omit <!-- Page N --> comments and --- page separators. |
--ocr-fallback / --force-ocr |
Opt-in OCR on unreliable/wordless pages, or force whole-page OCR (mutually exclusive). |
--ocr-engine {tesseract,rapid} |
Select local OCR backend (default: tesseract; --ocr-dpi defaults to 300). |
--check-ocr |
With no input paths, report the selected backend's availability as JSON; exit 0 if usable, 1 otherwise. |
--ocr-timeout SECONDS |
Set the positive per-page Tesseract recognition timeout (default: 60 seconds). |
--cache-dir DIR / --no-cache |
Override the cache directory or disable caching, even when the environment variable is set. |
--no-heuristics |
Disable heuristic corruption/wordless OCR routing while keeping deterministic font warnings. |
--images-output DIR |
Export embedded rasters (>=30 units) and dense vector PNGs; pair with --contact-sheet PATH. |
--render-pages DIR |
Render selected pages as full-page PNGs (--dpi defaults to 150) and exit. |
--tables-output DIR |
Export detected tables as collision-safe CSV files; add -o, --output-dir, -o -, or --json to also emit a report. |
--include-summary |
Prepend <!-- extraction-summary: ... --> as line 1 of the Markdown output. |
--analyze / --metadata / --list-images |
Print JSON routing verdict, full metadata/font-risk assessment, or embedded image inventory and exit. |
Supply one or more PDFs or directories. Directory inputs include direct PDF children in sorted order, including .PDF; --recursive includes nested PDFs. An empty directory selection fails before output is written. In a batch, a failed PDF rolls back the files it created and processing continues for the others. Aggregate JSON retains successful documents even when the batch exits with a failure, so check stderr and the exit status. Multi-PDF metadata, analysis, and image inventory return an ordered array of source/result objects.
Run pypdftomd --help (or python -m pypdftomd --help) for the full option list.
Preflight and selective OCR
Run --analyze on unknown batches to inspect verdict (text_based, needs_ocr, or mixed), pages_needing_ocr, confidence, and reasons before paying OCR cost. Use --metadata to check is_encrypted and needs_password alongside font-risk details:
pypdftomd batch_doc.pdf --analyze
pypdftomd batch_doc.pdf --metadata
OCR replaces the page's embedded text, so native table and body structure on that page is lost. When recognition fails or times out, embedded text is retained with a warning. If the backend is unavailable, the output retains embedded text and reports ocr_backend_unavailable. A page that cannot be rendered gets ocr_page_render_failed; other pages continue. No recoverable text raises an error. When possible, an OCR fallback page image is saved in --images-output, or alongside the report written by -o or --output-dir, for visual inspection.
Python API
from pathlib import Path
from pypdftomd import ExtractionOptions, extract_text_from_pdf
markdown = extract_text_from_pdf(Path("report.pdf"))
options = ExtractionOptions(ocr_fallback=True, workers=2, include_summary=True)
markdown_with_ocr = extract_text_from_pdf(Path("report.pdf"), options=options)
Preflight inspection and structured table extraction share the same page analysis and bounding boxes:
from pathlib import Path
from pypdftomd import extract_tables_with_bboxes, get_pdf_metadata
meta = get_pdf_metadata(Path("report.pdf"))
if not meta["needs_password"]:
routing = meta["extraction_assessment"]["routing"]
tables = extract_tables_with_bboxes(Path("report.pdf"), pages="1-3")
Caching
Result caching is opt-in and disabled by default when PYPDFTOMD_CACHE_DIR is unset (pass cache_dir=None to force-disable it). Enable it per call via cache_dir, on the CLI via --cache-dir, or process-wide via PYPDFTOMD_CACHE_DIR:
export PYPDFTOMD_CACHE_DIR=./.cache/pypdftomd
--cache-dir overrides the environment variable; --no-cache disables caching. Set the environment variable before the first process-wide cache use. Entries use the pypdftomd- prefix, are bounded to 128 entries, and key on document bytes, selected pages, extraction options, and backend versions. Requests that write side-effect files (images_output or output_file, including CLI -o PATH), actually run OCR fallback, or encounter degraded OCR or page/table extraction failures bypass the cache. Explicit -o - writes to stdout and remains cacheable. Cache errors and corrupt entries do not fail extraction.
Limitations
- Scanned PDFs and OCR structure: Scanned or image-only pages require
--ocr-fallbackor--force-ocr. OCR operates on whole pages and loses native table and body structure on those pages. - Table detection gaps: Table extraction is strongest on ruled and shaded grids. Borderless tables, tight sub-gutter spacing, filled callouts or parallel prose misread as grids, and contents or index pages remain known gaps; visually verify critical tables with
--render-pages. - Charts and dense vector drawings: Charts are not reconstructed into structured data (grids over chart marks emit
chart_grid_table). Dense vector figures export as rendered PNGs only when--images-outputis set. - Non-HTTP(S) links: Native HTTP(S) link annotations become Markdown links; internal PDF navigation links and other schemes keep readable labels without link targets.
- Encrypted PDFs: Password-protected PDFs must be decrypted before extraction (
--metadatareportsis_encryptedandneeds_password). - Heuristic headings and reading order: Headings and reading order remain heuristic.
License
AGPL-3.0-or-later. See LICENSE and THIRD_PARTY_NOTICES.md. PyMuPDF is used under its GNU AGPL-3.0 license rather than an Artifex commercial license, so pypdftomd retains AGPL-3.0-or-later copyleft obligations for distribution and network-service use (Section 13). THIRD_PARTY_NOTICES.md documents adapted upstream mechanisms (liteparse, pdf-inspector, and Docling) and the licenses of the runtime dependency closure. Both license files are installed in the wheel metadata's licenses directory. The agent skill files in skills/pypdftomd/ are separately licensed under the MIT License.
Metadata
Release files for pypdftomd 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 |
|---|---|---|---|---|
| pypdftomd-0.4.0.tar.gz | 351.4 kB | With provenance | Details for pypdftomd-0.4.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pypdftomd-0.4.0-py3-none-any.whl | Python 3 | none | any | Details for pypdftomd-0.4.0-py3-none-any.whl |
Total release size: 728.6 kB
Release files / pypdftomd-0.4.0.tar.gz
| Download URL | pypdftomd-0.4.0.tar.gz |
|---|---|
| Size | 351.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
5636c7b8e1b5fc26a14e8ba3c7a9ccd33f3b4d957315fc0fcf1966b9c6db7e01
|
|
BLAKE2b-256 checksum How to use checksums |
e2f29cc331368119c8218f6503f9394891352540aef75808795fa1ef05f9ede8
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 2, 2026.
Transparency logRelease files / pypdftomd-0.4.0-py3-none-any.whl
| Download URL | pypdftomd-0.4.0-py3-none-any.whl |
|---|---|
| Size | 377.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
b1310fd688deb31307d3ecf252301627edc26ed00d0c243b60b3b3fb705c0031
|
|
BLAKE2b-256 checksum How to use checksums |
a93ba3c8da8c15be4ccd3ffcb23ccc95b19a850aaabd37688609668a7a3da970
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 2, 2026.
Transparency logSecurity for pypdftomd 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.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for pypdftomd-0.4.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 2, 2026.
Transparency logA 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.