Skip to main content

pypdftomd

Local-first Python library and CLI for converting PDFs into layout-aware Markdown.

PyPI GitHub Release Python 3.12+ License: AGPL-3.0-or-later Packaging CI

Quickstart · Benchmarks · Architecture · Output · Install · Agent skill · Usage · Limitations · Changelog · 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 and stderr summaries 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 --analyze and --metadata, with selective whole-page OCR fallback via local Tesseract or RapidOCR.

Quickstart

Requires Python 3.12 or newer.

# Run without installing permanently
uvx pypdftomd report.pdf

# Or install the CLI and Python library with pip
pip install pypdftomd
from pathlib import Path
from pypdftomd import extract_text_from_pdf

markdown = extract_text_from_pdf(Path("report.pdf"))

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). Quality scores only; runtime and memory depend on document layout and worker count.

Extractor Models / Runtime Overall NID NID-S TEDS TEDS-S MHS MHS-S
pypdftomd 0.4.0 None (text-layer, PyMuPDF) 0.902 0.926 0.928 0.845 0.861 0.850 0.913
Docling 2.155.0 Heron + TableFormer + RapidOCR (CPU) 0.892 0.906 0.859 0.925 0.944 0.830 0.905
Liteparse 2.21.5 None (text-layer, PDFium) 0.891 0.918 0.922 0.823 0.841 0.838 0.901
OpenDataLoader hybrid 2.5.24 JRE + Docling + EasyOCR (CPU) 0.880 0.920 0.910 0.676 0.911 0.823 0.888
pdf-inspector 1.27.0 None (text-layer, Rust) 0.870 0.911 0.901 0.800 0.842 0.777 0.859
OpenDataLoader plain 2.5.24 None (JRE rules) 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-bench commit 7af1d8f4d0c09f51ea1a5c6ba5f66e993286d109, evaluator digest 99c22bd79c2fe4ada21c86c57f4ddc174a8c862f59a41f7d6635d31ce7a22942. Full-corpus rows cover the same 200 PDFs with zero missing predictions (200 NID/NID-S, 42 reference-table TEDS/TEDS-S, 107 MHS/MHS-S).
  • pypdftomd 0.4.0 configuration: ocr_fallback=False, cache_dir=None, page_breaks=False, workers=1 on PyMuPDF 2.2 (verified 2026-12-02 on the full 200-PDF corpus with zero byte diffs across repeated runs; 1 false table). 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.4.0.
  • 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 (ocr off, extract_links false), 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) without neural layout models, model weight downloads, or a 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 (verified at commit 945b64b; 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:

Preflight & Page Selection ─▶ Single-Pass Page Geometry ─▶ Region Typing
  ─▶ Exclusive Word Ownership ─▶ Region Interpretation ─▶ Reading-Order Flow & Emission
                                                               │
                                                 (opt-in --ocr-fallback)
                                                               ▼
                                                        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 /ToUnicode map.
  • 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

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.whl from GitHub Releases and install with pip install ./pypdftomd-<version>-py3-none-any.whl or uv tool install --python 3.12 <wheel-url>.
  • Source checkout: Run pip install . (or pip install ".[ocr-tesseract]" / pip install ".[ocr-rapid]").
  • Tesseract ([ocr-tesseract]): Requires the tesseract binary on PATH or the TESSERACT_CMD environment variable pointing to the executable.
  • RapidOCR ([ocr-rapid]): Installs rapidocr, onnxruntime, and opencv-python-headless for 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-fallback or --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-output is 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 (--metadata reports is_encrypted and needs_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.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 pypdftomd 0.4.1
File Size Uploaded Provenance Actions
pypdftomd-0.4.1.tar.gz 351.9 kB With provenance Details for pypdftomd-0.4.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pypdftomd 0.4.1
File Interpreter ABI Platform Actions
pypdftomd-0.4.1-py3-none-any.whl Python 3 none any Details for pypdftomd-0.4.1-py3-none-any.whl

Total release size: 729.4 kB

Release files / pypdftomd-0.4.1.tar.gz

Download URL pypdftomd-0.4.1.tar.gz
Size 351.9 kB
Tags Source
SHA-256 checksum
How to use checksums
aa1fb6224441dc57c8d68562414c4ae393de8367923702037d29236d6d58efbf
BLAKE2b-256 checksum
How to use checksums
6180b5e2e25d308a8fe83680a4b0d3e9f77e537251392743bf1359aec3de1df0
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 log

Release files / pypdftomd-0.4.1-py3-none-any.whl

Download URL pypdftomd-0.4.1-py3-none-any.whl
Size 377.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b610a50417e289e17a40a42ae5afd3000469f4d1ca0c595d96079cd51a1aed05
BLAKE2b-256 checksum
How to use checksums
f09d2512f73f0591a21f4e52102dcea16736c47fb78c0d98ad29077ac95946e6
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 log

Security for pypdftomd 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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for pypdftomd-0.4.1.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 log

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