How to Convert PDF to Markdown: Python & AI
Quick Answer
To convert PDF to Markdown, match the method to the file. A browser converter extracts the selectable text layer of simple digital PDFs. Layout-aware Python tools such as PyMuPDF4LLM, Docling and Marker handle columns, tables and equations. Scanned pages need OCR. No single method cleanly handles every PDF, so test one representative file first.

Choose the Right Method to Convert PDF to Markdown
PDF to Markdown is not one problem. A clean single-column report, a two-column journal paper and a scanned invoice need three different pipelines. Picking the wrong one is the main reason people end up repairing output by hand.
Choose a PDF Converter Based on Its Content
| PDF type | Typical problem | Start with | Escalate to |
|---|---|---|---|
| Single-column digital text | Almost none | MD Convert (browser) | MarkItDown |
| Multi-column academic paper | Interleaved columns | PyMuPDF4LLM | Docling or Marker |
| Scanned, image-only pages | No text layer | Docling or Marker with OCR | MarkItDown OCR plugin |
| Financial statements and tables | Borderless columns collapse | Docling (TableFormer) | Marker, then manual repair |
| Math-heavy papers | Equations become glyph soup | Marker or Docling formula enrichment | Manual LaTeX check |
| Bulk digital PDFs | Throughput and consistency | PyMuPDF4LLM | MarkItDown in a script |
Browser Converter or Python Extraction Pipeline?
Use the browser when the PDF has selectable text, a simple layout, and you want the file to stay on your machine with no setup. Use Python when you need batch processing, OCR, table models, equations or metadata for retrieval.
Can you select and copy text in the PDF?
βββ No β scanned: OCR pipeline (Docling, Marker, or PyMuPDF4LLM + OCR)
βββ Yes β Is the layout single-column with simple tables?
βββ Yes β browser converter
βββ No β layout-aware Python (PyMuPDF4LLM, Docling, Marker)
If your file lands on the browser branch, use the free PDF to Markdown converter.
Why PDF to Markdown Conversion Is Difficult: PDF Coordinates Are Not Document Structure
PDF Content Streams Position Glyphs, Not Semantic HTML Elements
Markdown is a structural format: headings, lists, tables, code fences. A PDF is a drawing format. Under ISO 32000, a page is a content stream of graphics operators. Text operators such as Tf (set font), Tm (set text matrix), Td (move) and Tj (show string) place runs of glyphs at coordinates, and the current transformation matrix (CTM) maps those coordinates onto the page.
Nothing in that stream says "this is a heading" or "these three runs form a table row." There is no DOM tree. A converter must infer structure from font size, weight, x/y position, gaps and ruling lines. Every inference is a heuristic, and heuristics fail on unusual layouts.
Content stream Extraction Inference Markdown
(Tf, Tm, Tj ops) β glyph runs + x/y β lines, blocks, columns β headings, tables,
font, size reading order guess lists, code fences
β² most errors happen here
Digital PDFs, Tagged PDFs and Scanned PDFs Are Different
| Type | What it contains | What converts well | Where it still fails |
|---|---|---|---|
| Native digital | Text layer, no structure tags | Paragraphs and headings by font size | Columns, borderless tables |
| Tagged | Text layer plus a structure tree (accessibility tags) | Reading order and headings, when tags are correct | Tags are often missing, wrong or ignored by extractors |
| Scanned | Page images only | Nothing without OCR | Everything: no characters exist |
| Hybrid | Scanned image with an OCR text layer behind it | Text, if the OCR was good | OCR errors travel into the Markdown |
Selectable text is not proof of good structure. A text layer gives you characters and positions. It does not give you reading order or table cells.
Convert a Digital PDF to Markdown in Your Browser
Use MD Convert for Selectable PDF Text
MD Convert extracts the text layer with PDF.js running inside a browser Web Worker, so the PDF is read on your device. The workflow takes three steps:
- Open the page to convert PDF to Markdown online and drop in a PDF with selectable text.
- Wait while the Web Worker extracts text and builds Markdown from font size and line structure.
- Review the preview, then copy or download the
.mdfile.
Understand the Browser Converter's Limitations
The converter reads the selectable text layer and nothing else. It does not:
- run OCR, so scanned and image-only PDFs produce no text;
- reconstruct borderless tables, so aligned columns arrive as plain lines;
- recover complex multi-column layouts, so reading order may interleave;
- translate math into LaTeX, so equations arrive as whatever glyphs the PDF encodes.
For those cases, use the Python tools below.
Convert PDF to Markdown with Python and AI Extraction Tools
Microsoft MarkItDown: A Python PDF-to-Markdown Pipeline
MarkItDown is an open-source Microsoft project (github.com/microsoft/markitdown) that converts many file types to Markdown for LLM pipelines. PDF support is an optional dependency group:
pip install "markitdown[pdf]"
markitdown input.pdf -o output.md
This is standard text-layer extraction. It does not read scanned pages. OCR is a separate package, markitdown-ocr, a plugin that sends page images to a vision-capable LLM client you supply. It needs an API key or local model endpoint, it costs tokens, and it sends page images to that provider. Install and enable it only when you accept those terms.
PyMuPDF4LLM: Fast PDF Extraction for RAG and Developers
PyMuPDF4LLM builds on PyMuPDF and targets Markdown for retrieval. It analyzes blocks and reading order, detects headings and tables, and can return per-page chunks with metadata.
pip install -U pymupdf4llm
import pymupdf4llm
pages = pymupdf4llm.to_markdown("input.pdf", page_chunks=True)
for page in pages:
print(page["metadata"]["page"], len(page["text"]))
With page_chunks=True you get a list of dictionaries, one per page, each holding a text field and a metadata field. Page-level OCR is available when an OCR engine is installed and enabled; the exact switches change between releases, so check the current documentation.
IBM Docling: Layout-Aware PDF Parsing with TableFormer and OCR
Docling is an IBM Research project (now under the Linux Foundation) that runs layout analysis and a table-structure model called TableFormer, with optional OCR and enrichment.
pip install docling
from docling.document_converter import DocumentConverter, PdfFormatOption
from docling.datamodel.base_models import InputFormat
from docling.datamodel.pipeline_options import PdfPipelineOptions, TableFormerMode
options = PdfPipelineOptions()
options.do_ocr = True
options.do_table_structure = True
options.table_structure_options.mode = TableFormerMode.ACCURATE # or FAST
options.do_formula_enrichment = True
converter = DocumentConverter(
format_options={InputFormat.PDF: PdfFormatOption(pipeline_options=options)}
)
result = converter.convert("input.pdf")
print(result.document.export_to_markdown())
FAST trades table accuracy for speed. ACCURATE is slower and better for dense tables. Formula enrichment attempts LaTeX for equations and adds processing time. Models download on first run.
Marker: Deep-Learning PDF-to-Markdown Extraction
Marker chains layout detection, Surya OCR, table recognition and equation-to-LaTeX models.
pip install marker-pdf
marker_single input.pdf --output_format markdown --output_dir output
Flag names have changed between versions, so run marker_single --help for your install. Marker runs on CPU, but it is much faster on a GPU, and first runs download several models. Check the license terms of the code and model weights before commercial use.
PDF-to-Markdown Edge-Case Benchmark: 5 Methods Γ 6 Hazards
Reproducible PDF Test Fixtures
This matrix is built around six fixtures you can recreate and run yourself:
- Single-column text: a plain report with headings and lists.
- Two-column academic paper: a two-column journal layout with footnotes.
- Borderless financial table: aligned columns, no ruling lines, currency symbols and negatives in parentheses.
- Scanned image PDF: page images with no text layer.
- LaTeX math paper: inline and display equations.
- Indented source code: a listing where indentation carries meaning.
Extraction Verdicts and Evaluation Criteria
- Preserved: the Markdown keeps the structure and content with no edits beyond cosmetic cleanup.
- Repair needed: the content is present, but order, table cells, symbols or indentation need manual or scripted correction.
- Fails: the tool produces no usable result for that hazard in its default configuration, or it lacks the capability.
The 5 Γ 6 Comparison Matrix
I have not run these five tools against a shared fixture set for this article, so the table reports expected outcomes from each tool's documented architecture, not measured results. It contains no runtime, pages-per-second or memory figures, because I have no executions to report. Treat every cell as a hypothesis and confirm it on your own files.
| Hazard | MD Convert (PDF.js) | MarkItDown | PyMuPDF4LLM | Docling | Marker |
|---|---|---|---|---|---|
| Single-column text | Preserved | Preserved | Preserved | Preserved | Preserved |
| Two-column paper | Repair needed | Repair needed | Preserved | Preserved | Preserved |
| Borderless financial table | Fails | Repair needed | Repair needed | Preserved | Repair needed |
| Scanned image PDF | Fails | Fails (OCR plugin: Repair needed) | Repair needed | Repair needed | Repair needed |
| LaTeX math paper | Fails | Fails | Repair needed | Repair needed | Preserved |
| Indented source code | Repair needed | Repair needed | Repair needed | Repair needed | Repair needed |
Notes on how to read it:
- MD Convert reads only the text layer through PDF.js. It has no OCR, no table reconstruction and no LaTeX output, so those hazards fail by design.
- MarkItDown in standard mode extracts text and offers limited layout reasoning. Scans need the separate
markitdown-ocrplugin and a vision-capable LLM. - PyMuPDF4LLM is designed for multi-column reading order and table detection. OCR depends on an installed engine, and math stays as extracted symbols.
- Docling pairs layout analysis with TableFormer, built-in OCR options and formula enrichment. OCR quality still sets the ceiling on scans.
- Marker targets equations directly with LaTeX output and uses Surya for OCR. Verify equations and numeric tables.
- Code is the weak spot everywhere: indentation is only a pattern of x positions, and no tool can prove it was meaningful.
To verify, run each tool on the same six files, diff against hand-written ground truth, and record your own verdicts.
Repair PDF-to-Markdown Output Before Using It
Repair Reading Order and Reconstruct Tables
Check three things in every converted file: page breaks that split sentences or tables, columns that interleave line by line, and numbers that lose their meaning. Currency symbols often detach from values. Negatives written as (1,204) must stay negative, not turn into 1,204.
A borderless financial table often arrives like this:
Before
Revenue 4,210 3,880
Cost of sales (2,310) (2,105)
Operating income 1,900 1,775
After manual repair against the PDF:
| Line item | FY2025 | FY2024 |
|------------------|--------:|--------:|
| Revenue | 4,210 | 3,880 |
| Cost of sales | (2,310) | (2,105) |
| Operating income | 1,900 | 1,775 |
Confirm every total against the source page. If an editable Word original exists, convert that instead: the DOCX to Markdown converter reads real heading and table structure, which is far more reliable than inferring it from coordinates.
Preserve Mathematical Expressions and Code Blocks
For math, look for broken Greek letters, lost subscripts and split fractions. Wrap inline math in $...$ and display math in $$...$$ only after you have checked the symbols against the PDF. For code, restore indentation, then put the listing in a fenced block with a language tag. Indentation recovered from x positions can be off by a space or two, and in Python or YAML that changes behavior.
Convert Markdown to PDF: Pandoc, Typst, XeLaTeX and WeasyPrint
Searches for markdown to pdf are about the opposite direction, so this section covers it with local tools only.
Use Pandoc to Convert Markdown to PDF
Pandoc converts Markdown to PDF through an external engine:
pandoc input.md -o output.pdf --pdf-engine=xelatex
pandoc input.md -o output.pdf --pdf-engine=typst
XeLaTeX needs a TeX distribution and handles Unicode and system fonts well; set one with -V mainfont="DejaVu Serif". It renders LaTeX math natively. The Typst engine needs Typst installed and compiles quickly, and Pandoc translates math into Typst syntax. Both support tables and code blocks.
Build a Local Python Markdown-to-PDF Pipeline with WeasyPrint
For a scriptable pipeline with no TeX install, combine markdown-it-py with WeasyPrint. WeasyPrint also needs Pango, which some systems install separately.
pip install markdown-it-py weasyprint
python md_to_pdf.py report.md -o report.pdf --title "Quarterly Report"
#!/usr/bin/env python3
"""Convert a Markdown file to PDF locally with markdown-it-py and WeasyPrint."""
from __future__ import annotations
import argparse
import sys
from html import escape
from pathlib import Path
from markdown_it import MarkdownIt
from weasyprint import HTML
DEFAULT_CSS = """
@page {
size: A4;
margin: 22mm 18mm 24mm 18mm;
@bottom-center {
content: counter(page) " / " counter(pages);
font-size: 9pt;
color: #666666;
}
}
html {
font-family: "DejaVu Sans", "Helvetica Neue", Arial, sans-serif;
font-size: 10.5pt;
line-height: 1.55;
color: #1a1a1a;
}
h1, h2, h3, h4, h5, h6 {
break-after: avoid;
line-height: 1.25;
}
h1 { font-size: 22pt; margin: 0 0 12pt; }
h2 { font-size: 16pt; margin: 20pt 0 8pt; border-bottom: 1px solid #dddddd; padding-bottom: 3pt; }
h3 { font-size: 13pt; margin: 16pt 0 6pt; }
p, li { orphans: 3; widows: 3; }
pre, code {
font-family: "DejaVu Sans Mono", Menlo, Consolas, monospace;
font-size: 9pt;
}
pre {
background: #f5f5f5;
border: 1px solid #e0e0e0;
border-radius: 4px;
padding: 8pt 10pt;
white-space: pre-wrap;
overflow-wrap: anywhere;
break-inside: avoid;
}
code { background: #f2f2f2; padding: 1pt 3pt; border-radius: 3px; }
pre code { background: none; padding: 0; }
table {
border-collapse: collapse;
width: 100%;
margin: 10pt 0;
font-size: 9.5pt;
break-inside: avoid;
}
thead { display: table-header-group; }
tr { break-inside: avoid; }
th, td {
border: 1px solid #cccccc;
padding: 4pt 6pt;
text-align: left;
vertical-align: top;
}
th { background: #f0f0f0; }
blockquote {
margin: 10pt 0;
padding: 2pt 12pt;
border-left: 3pt solid #bbbbbb;
color: #444444;
}
img { max-width: 100%; }
a { color: #0b57d0; text-decoration: none; }
"""
def render_pdf(source: Path, output: Path, title: str | None, extra_css: Path | None) -> None:
"""Read Markdown from `source` and write a PDF to `output`."""
text = source.read_text(encoding="utf-8")
# Tables on, raw HTML off: embedded <script>, <iframe> and similar tags
# in the Markdown are escaped instead of being rendered.
md = MarkdownIt("commonmark", {"html": False}).enable("table")
body = md.render(text)
document_title = title or source.stem.replace("-", " ").replace("_", " ")
css = DEFAULT_CSS
if extra_css is not None:
css += "\n" + extra_css.read_text(encoding="utf-8")
html_doc = (
"<!doctype html>"
'<html lang="en"><head><meta charset="utf-8">'
f"<title>{escape(document_title)}</title>"
f"<style>{css}</style></head>"
f"<body>{body}</body></html>"
)
# base_url lets relative image paths in the Markdown resolve correctly.
HTML(string=html_doc, base_url=str(source.parent.resolve())).write_pdf(str(output))
def parse_args(argv: list[str] | None) -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Convert a Markdown file to PDF with markdown-it-py and WeasyPrint."
)
parser.add_argument("input", type=Path, help="Path to the Markdown file")
parser.add_argument("-o", "--output", type=Path, help="Output PDF path (default: input name with .pdf)")
parser.add_argument("--title", help="Document title for PDF metadata")
parser.add_argument("--css", type=Path, help="Extra CSS file appended after the default styles")
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> int:
args = parse_args(argv)
if not args.input.is_file():
print(f"error: input file not found: {args.input}", file=sys.stderr)
return 1
if args.css is not None and not args.css.is_file():
print(f"error: CSS file not found: {args.css}", file=sys.stderr)
return 1
output = args.output or args.input.with_suffix(".pdf")
try:
render_pdf(args.input, output, args.title, args.css)
except UnicodeDecodeError:
print("error: input is not valid UTF-8 text", file=sys.stderr)
return 1
except OSError as exc:
print(f"error: could not read or write a file: {exc}", file=sys.stderr)
return 1
except Exception as exc: # WeasyPrint raises several library-specific errors
print(f"error: PDF rendering failed: {exc}", file=sys.stderr)
return 1
print(f"Wrote {output}")
return 0
if __name__ == "__main__":
sys.exit(main())
The @page rule sets the paper size, margins and page numbers. Headings carry break-after: avoid so they never strand at the bottom of a page, tables and code blocks carry break-inside: avoid, and thead { display: table-header-group; } repeats table headers when a table spans pages. A table taller than one page must still split, and the repeated header keeps it readable.
Which Markdown-to-PDF Workflow Should Developers Choose?
| Engine | Best for | Math | Setup weight | Main trade-off |
|---|---|---|---|---|
| Pandoc | Orchestrating any engine from one command | Depends on engine | Moderate | Needs a second tool for PDF output |
| XeLaTeX | Print-quality documents, heavy math | Native LaTeX | Heavy TeX install | Slow compiles, cryptic errors |
| Typst | Fast builds, modern templating | Typst math syntax | Light | Younger ecosystem than LaTeX |
| WeasyPrint | HTML/CSS styling control | Not built in | Light, needs Pango | No native LaTeX math |
| Python automation | Batch jobs, CI, custom styling | Not built in | Light | You own the CSS and the edge cases |
If your source is a web page rather than a Markdown file, run it through the HTML to Markdown converter first, then render it with any pipeline above.
Use PDF-Derived Markdown for RAG and LLM Context
Prepare Extracted Markdown for Retrieval-Augmented Generation
Retrieval quality depends on what you keep from the PDF. Preserve page numbers so answers can cite pages, store the source file name, keep the heading path so a chunk knows its section, and never split a table across chunks. A chunk with provenance looks like this:
---
source: annual-report-2025.pdf
page: 42
section: "Financial Statements > Income Statement"
---
| Line item | FY2025 | FY2024 |
|------------------|--------:|--------:|
| Revenue | 4,210 | 3,880 |
| Operating income | 1,900 | 1,775 |
Connect PDF Extraction to a Markdown RAG Workflow
The pipeline runs PDF β Extraction β Cleanup β Chunking β Embeddings β LLM. Extraction errors survive every later step, so the cleanup stage deserves most of the review effort. A table with shifted columns will embed cleanly and still answer wrongly. For chunk sizing, heading-aware splitting and context formatting, follow the Markdown for RAG guide.
Privacy Checklist: Verify Browser-Local PDF Conversion
Verify File Processing Through Chrome DevTools Network
Do not rely on a privacy claim you cannot check. Verify it:
- Open the converter page and press F12 to open DevTools.
- Go to the Network tab and enable Preserve log.
- Click Clear to empty the existing entries.
- Convert a test PDF.
- Filter by Fetch/XHR and inspect every request. Check the payload and request size of each one.
You should see static assets and cookieless analytics events. You should not see a request whose payload carries the PDF bytes or its extracted text. Use a harmless test file, since the point is to learn what leaves the page.
Explain Local Files, Aggregate Analytics and the URL Proxy Exception
| Activity | What happens | Leaves your device? |
|---|---|---|
| PDF conversion | PDF.js extracts text in a Web Worker | No file upload |
| Page analytics | Cookieless, aggregate usage events | Aggregate counts only, no file content |
| URL-to-Markdown | A stateless proxy fetches the page you name | Yes, the URL goes through the proxy |
The URL converter is the exception because a browser cannot fetch most third-party pages directly. PDF conversion has no such need.
PDF to Markdown: Frequently Asked Questions
What is the best way to convert PDF to Markdown?
Match the tool to the PDF. Use a browser converter for simple digital files, PyMuPDF4LLM, Docling or Marker for columns, tables and equations, and OCR for scans. Test one representative file before processing a batch.
Does Microsoft MarkItDown convert PDF to Markdown?
Yes. Install pip install "markitdown[pdf]" and run markitdown input.pdf -o output.md. It extracts the text layer. Scanned PDFs need the separate markitdown-ocr plugin and a vision-capable LLM client.
Can I convert scanned PDF files to Markdown?
Yes, but only with OCR. Docling and Marker include OCR options, PyMuPDF4LLM can use an installed OCR engine, and MarkItDown offers an LLM-based OCR plugin. Browser text-layer converters, including MD Convert, cannot read scans.
How do I preserve tables when converting PDF to Markdown?
Use a table-aware extractor such as Docling in ACCURATE mode, then verify every cell against the source page. Borderless tables usually need repair, especially negatives, currency symbols and totals.
How do I convert Markdown to PDF in Python?
Install markdown-it-py and weasyprint, render the Markdown to HTML with raw HTML disabled, and call HTML(string=...).write_pdf(). The md_to_pdf.py script in Section 7 does this with page rules and a command-line interface.
Is MD Convert's PDF converter private?
PDF conversion runs locally in your browser through PDF.js in a Web Worker, so the file is not uploaded. Analytics are cookieless and aggregate. Verify it yourself with the DevTools Network steps in Section 9.
Choose Your Conversion Workflow Next
Use the browser for digital PDFs with selectable text and simple layouts. Use PyMuPDF4LLM, Docling or Marker when columns, tables, equations or scans are involved, and plan a repair pass either way. Use Pandoc or the WeasyPrint script when you need to go from Markdown back to PDF.
The same extraction logic applies to other formats. Explore the all-in-one Markdown conversion workspace (16 dedicated converters) to handle Word, HTML and more in one place, or go straight to the free PDF to Markdown converter to test your file now.