Guides

PDF to Markdown for RAG: what works and what breaks

Converting PDF to Markdown for RAG is easy when the PDF has a text layer and hard when it has tables, columns or no text at all. Which tool fits which PDF, what breaks, and how to chunk the output.

Sid Mishra12 min read
A PDF page turning into Markdown as returned: the headings 1 Introduction and 3 Model Architecture as plain text and a --- rule between pages. Checks: text in reading order and page rules kept; tables and headings need a layout model or a clean-up. Footer: a real run, 15 pages, 2.2 MB to 39.6 KB, 2
On this page

TL;DR

  • To convert one PDF to Markdown now: paste its link into our free converter (no account), or run docling file.pdf locally. You get a .md file back in seconds.

  • For RAG, pick the tool by the PDF, not the brand. A PDF with a text layer and mostly prose converts cleanly with almost anything. Tables, equations and multi-column layouts need a layout model (Docling, Marker or PyMuPDF 2.x). A scan has no text at all and needs OCR first.

  • What breaks most often: tables flattened into lines of cells, headings that come out as plain text, page numbers and running headers inside your chunks, words hyphenated across lines, and equations scrambled.

  • Clean before you chunk: drop page numbers, re-join wrapped lines, restore headings, and keep the page number with every chunk so answers can cite it. The 30-line script below does all four.

  • For a whole site of PDFs that changes: crawl it on a schedule and re-convert only the documents that changed, rather than re-embedding the library every night.

A PDF describes where ink goes on a printed page. It doesn't say "this is a heading" or "these cells are a table"; it says "draw these glyphs at these coordinates". Every PDF to Markdown converter is guessing the structure back from the layout, and how well it guesses depends far more on the PDF than on the converter.

That's why one tool gives you perfect Markdown from a policy document and garbage from a financial report. Below: how to tell which kind of PDF you have, what each kind of tool gets right, a real conversion with its numbers, and the clean-up that makes the output worth embedding.

Which PDF to Markdown tool should I use?

A decision diagram: does the PDF have a text layer, do its tables or equations matter, and is it one file or a whole site of PDFs, leading to OCR, a layout model, or a text-layer extractor

Ask three questions, in this order.

1. Does the PDF have a text layer? Open it and try to select a sentence. If the cursor won't take the text, it's a scan: a picture of a page. No converter can read it without OCR (optical character recognition) first. Government notices, older filings and anything that came off a scanner are usually like this.

2. Do the tables, equations or columns matter to your answers? If the PDF is mostly prose (policies, manuals, contracts, docs), a text-layer extractor is enough and it's fast and cheap. If the answers live in tables (rate cards, financial statements, spec sheets) you need a tool with a layout model that rebuilds table structure, or your retriever will see cell values with no row or column attached.

3. Is it one file, a folder, or a website full of PDFs? One file: a free converter. A folder on your machine: a local library. PDFs that a website publishes and keeps replacing: a crawler that finds them, converts them and tells you when one changes.

Your PDFs

Use

Why

A few, with a text layer, mostly prose

A free converter or any library

Text in reading order is all you need

Tables or equations carry the answers

Docling, Marker, PyMuPDF 2.x, or a hosted parser such as LlamaParse

They rebuild tables as Markdown or HTML

Scans with no text layer

An OCR-capable tool (Docling, Marker, PyMuPDF with RapidOCR, Azure via MarkItDown)

There's no text to extract until OCR makes some

Hundreds, published on a site, updated over time

A crawler that parses documents (MeshArc)

Finds new PDFs, skips the ones that didn't change

What breaks when you convert PDF to Markdown?

These are the failures that hurt retrieval, roughly in order of how often they turn up.

Tables become lines of text. A text-layer extractor reads a table cell by cell, left to right, top to bottom. You get the header cells on one line and then a run of numbers, and the link between a number and its row and column is gone. An embedding of that chunk is close to useless for "what does the Pro plan cost a year?". Layout tools fix this: Marker emits formatted tables in its Markdown (and HTML blocks with its table converter), Docling rebuilds table structure, and PyMuPDF's find_tables() exports tables as Markdown.

Headings come out as plain text. "3.1 Encoder and Decoder Stacks" arrives as an ordinary line, not ### 3.1 …. That matters because most chunkers split on headings. Without them you split on character counts and cut sections in half.

Page furniture lands in your chunks. Page numbers, running headers ("Annual Report 2026 · Confidential") and footers repeat on every page. Embedded with the body text, they make unrelated chunks look similar and waste tokens in every answer.

Words and lines are broken where the page broke them. "transduc-" on one line and "tion" on the next is two tokens a search won't match. Every line ends where the printed line did, so a sentence is spread over four lines.

Equations and symbols scramble. Superscripts, subscripts and fraction bars flatten into a string like softmax(QK T √dk )V. Fine for search on the surrounding words, wrong if anyone reads it as maths.

Multi-column pages interleave. A naive extractor reads straight across both columns. Reading-order detection is the single biggest thing layout models add.

Images, charts and diagrams vanish. Their captions survive; what they show doesn't. Marker can save the images, and Docling can describe charts or turn them into tables with a vision model.

A real run: a 15-page paper, converted by a crawler

We converted one public PDF on 30 November 2026 through MeshArc's scrape (the hosted MCP server's scrape_urls, documents on): the arXiv copy of "Attention Is All You Need", a 15-page paper with equations, figures and results tables.

Result

PDF

15 pages, 2,215,244 bytes

Markdown

39,594 bytes (about 56 times smaller), 6,036 words

How it was read

Plain fetch of the text layer, no browser

Time

About 2 seconds

Cost

2 credits (a fetched PDF is 2, whatever its page count)

Page breaks

A --- rule between every page

And this is what the output looked like, which is the useful part. The first lines of page 2, as returned:

1 Introduction
Recurrent neural networks, long short-term memory [13] and gated recurrent [7] neural networks
in particular, have been firmly established as state of the art approaches in sequence modeling and
...
Attention mechanisms have become an integral part of compelling sequence modeling and transduc-
tion models in various tasks, ...

Four things from the list above, in one page: the heading is plain text, lines end where the printed lines ended, "transduc-tion" is split, and the page closes with a bare 2, its printed page number. Further on, equation (1) came back as softmax(QK T / √dk / )V across three lines. The text itself was complete and in the right order, so for prose questions it's good RAG input once cleaned. For the results tables it isn't: a text-layer read gives you their cells, not their structure. If your questions are about those numbers, run the paper through Docling or Marker instead. And because this file has no title in its metadata, there was no # heading at all: MeshArc returns the text layer page by page, and only a title the PDF itself declares becomes #.

The same call from your own code (pip install mesharc):

from mesharc import MeshArc

arc = MeshArc()  # reads MESHARC_API_KEY

page = arc.scrape(
    "https://arxiv.org/pdf/1706.03762",
    config={"parse_documents": True},   # read PDFs and .docx as text
)
print(page["verdict"], page["credits"], page["words"])   # ok 2 6036
markdown = page["markdown"]

Or with cURL:

curl -X POST https://api.mesharc.dev/api/v1/scrape \
  -H "Authorization: Bearer $MESHARC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://arxiv.org/pdf/1706.03762", "formats": "markdown", "config": {"parse_documents": true}}'

Have a PDF that's already online? Paste its link into our free converter and see what your document comes back as before you write any code.

How do I clean PDF Markdown before chunking it?

Clean each page, then chunk, and keep the page number with every chunk. This script does it with the standard library only. We ran it on an excerpt of the output above: the page numbers went, "transduction" was re-joined, and "1 Introduction", "3 Model Architecture" and "3.1 Encoder and Decoder Stacks" came back as headings.

import re

# a numbered heading such as "3.1 Encoder and Decoder Stacks"
HEADING = re.compile(r"^(\d+(\.\d+)*)\s+[A-Z][^.]{0,80}$")

def clean_page(text: str) -> str:
    lines = text.strip().splitlines()
    if lines and re.fullmatch(r"\d{1,4}", lines[-1].strip()):
        lines = lines[:-1]                       # the printed page number
    out = []
    for line in lines:
        line = line.rstrip()
        if HEADING.match(line):
            out.append("\n## " + line)           # restore the heading the PDF lost
        elif out and out[-1].endswith("-") and line[:1].islower():
            out[-1] = out[-1][:-1] + line        # "transduc-" + "tion"
        elif out and not out[-1].startswith("\n## ") and not out[-1].endswith((".", ":", "?")):
            out[-1] += " " + line                # re-join a wrapped line
        else:
            out.append(line)
    return "\n".join(out).strip()

def chunks(markdown: str, source: str, size: int = 350, overlap: int = 40):
    for n, page in enumerate(markdown.split("\n\n---\n\n"), start=1):
        words = clean_page(page).split(" ")
        for start in range(0, len(words), size - overlap):
            text = " ".join(words[start:start + size])
            if text.strip():
                yield {"source": source, "page": n, "text": text}

A few notes on adapting it. The heading pattern only catches numbered headings; for reports with unnumbered ones, a layout tool's real heading levels are worth more than any regex. Running headers differ per document, so the dependable trick is to count lines that appear on most pages and drop those. And 350 words with a 40-word overlap is a sensible default, not a law: it's also what MeshArc uses when it writes chunks to a vector store, but tune it against your own retrieval tests.

Keep page in the chunk's metadata. "See page 7 of the 2026 policy" is the difference between an answer someone trusts and one they have to check.

How do I convert a whole site's PDFs, and keep them current?

One PDF is a tool. A regulator's guidance library, a manufacturer's manuals or a council's planning notices are a crawl: the PDFs are linked from pages, new ones appear, old ones are replaced under the same URL or quietly withdrawn.

job = arc.crawl(
    "https://example.gov/guidance/",
    limit=500,
    includePaths=["/guidance/*"],
    config={"parse_documents": True},
    wait=True,
)
for page in job.pages():
    print(page["url"], page["words"], page["credits"])

project = job.keep(name="Guidance PDFs", schedule="weekly", max_pages=500)

The crawl follows the PDF and Word files the site links to and converts each one from its text layer. Kept as a project, every later run compares each document with the last version and records it as added, modified or removed. That's the part that saves money in a RAG pipeline: you re-chunk and re-embed only the documents that changed, and a document the site failed to serve one week is held back, not deleted from your index. The guide to keeping a RAG knowledge base fresh covers the re-embedding side in full.

PDF to Markdown tools compared

Checked on each project's or vendor's own page on 30 November 2026.

Tool

Best for

Runs

Tables

Scans (OCR)

Price

Docling

Local conversion with real structure, under a permissive licence

Your machine (CPU fine)

Table structure, reading order, formulas

Yes, built in

Free, MIT

Marker

Highest fidelity on papers, forms and equations

Your machine (GPU, CPU or MPS)

Formatted tables; --use_llm merges tables across pages

Yes

Code Apache 2.0; model weights free under $5M funding or revenue, paid above. Hosted Datalab API: about 5,000 free pages a month

PyMuPDF 2.x (now includes pymupdf4llm)

Fast CPU conversion inside a Python app

Your machine

find_tables() exports tables as Markdown

With RapidOCR or Tesseract

AGPL 3.0 or an Artifex commercial licence

MarkItDown

One library for PDF, Office, HTML and more

Your machine

Built-in converters keep tables as Markdown where they can; Azure Document Intelligence for complex ones

Via a plugin (LLM vision) or Azure

Free, MIT

LlamaParse

Hosted parsing when you don't want to run models

Hosted

Not compared here

Not compared here

10,000 free credits a month, then $1.50 per 1,000; 1 to 25 credits a page by tier

Firecrawl

Teams already scraping web pages with Firecrawl

Hosted, by URL

Not stated on its billing page

Not stated on its billing page

1 credit a page plus 1 per PDF page; Standard $99 a month for 100,000 credits

MeshArc

Many PDFs published on websites, re-read over time

Hosted, by URL

Cell text in reading order, not Markdown tables

No: text layer only, so run scans through an OCR tool first

2 credits a fetched PDF of any length (4 if rendered); Free 1,000 credits once, Starter $29 a month

What a thousand copies of our 15-page test paper would cost on the hosted options, at their published rates (our arithmetic):

Hosted option

Credits for 1,000 × 15 pages

Cost

MeshArc, Growth ($99 for 500,000)

2,000

$0.40

MeshArc, Starter ($29 for 100,000)

2,000

$0.58

Firecrawl, Standard monthly ($99 for 100,000)

16,000

$15.84

LlamaParse Fast, past the free 10,000

15,000

$22.50

LlamaParse Cost-effective

45,000

$67.50

That table compares price, not output. Docling and Marker rebuild tables and headings and a text-layer read doesn't, so test any hosted parser's tiers on your own documents before you pick on price.

Where MeshArc loses: tables come through as cell text, not Markdown tables; headings aren't marked (only a title stored in the PDF's own metadata becomes the # heading); equations and images aren't rebuilt; there's no OCR, so scans need another tool first; and it reads PDFs by URL, so a file on your laptop needs a local tool. If your answers live in tables, or you're converting a folder of files on disk, use Docling or Marker. MeshArc fits when the PDFs live on websites, there are lots of them, and the hard part is knowing which ones changed.

FAQ

Is there a free way to convert a PDF to Markdown?

Yes. Our free converter turns a PDF into Markdown from its link with no account, up to about 60,000 characters. Docling, Marker (for personal use and small companies) and MarkItDown are free libraries you run yourself, and LlamaParse gives 10,000 free credits a month.

Can a PDF to Markdown converter keep tables?

Some can. Docling, Marker and PyMuPDF's table detection rebuild tables; text-layer extractors, including MeshArc's, give you the cells' text in reading order. A table that is itself an image needs OCR before any tool can read it.

How do I convert a scanned PDF to Markdown?

Run OCR first, or use a tool that includes it. Docling, Marker and PyMuPDF (with RapidOCR or Tesseract) do it locally. MeshArc reads the text layer only, so convert scans with one of those. If you can't select text in the PDF, it's a scan.

What's the best Python library for PDF to Markdown?

For most RAG work, start with Docling: it's MIT-licensed, runs on CPU and keeps table structure. Marker is stronger on equations and forms but check its model licence for commercial use. PyMuPDF is the fastest, under AGPL or a paid licence.

How much does PDF to Markdown cost through an API?

It depends on whether the price is per page or per document. MeshArc charges 2 credits for a fetched PDF of any length; Firecrawl charges 1 credit plus 1 per PDF page; LlamaParse charges 1 to 25 credits a page depending on the tier. A refused PDF or a 404 costs nothing on MeshArc (pricing).

Converting a file's format is rarely the issue; what you do with the content is. Copyright and the site's terms still apply, so check before you store or republish documents, and respect robots.txt when you crawl. This isn't legal advice.

How often should I re-convert PDFs in a RAG index?

Only when they change. For a published library, a weekly crawl that compares each document with the last version is enough for most policies and manuals; re-embed the changed ones and leave the rest alone.

Try it on your own PDFs

Start with the document your team keeps asking questions about. If it's online, paste its link into our free converter and look for the failures above. If it's one of hundreds on a site, try a URL in the playground, then start free with 1,000 credits and crawl the section. More on the pipeline side: RAG pipelines that stay fresh, and for publishing your own site's content to AI tools, how to generate llms.txt. All the free tools are at mesharc.dev/tools.

ShareLinkedInX
Sid Mishra · Founder, MeshArc

Founder of MeshArc, a scraping API for sites you read more than once. Writes about web scraping, keeping RAG data fresh and spotting what changed on a site.

LinkedInXWebsite

The MeshArc newsletter

New posts and what changed, at most twice a month.

Related posts

Guides

How to generate llms.txt for any site

An llms.txt is a short Markdown map of a site for AI assistants. How to generate one from a sitemap in seconds, or from a crawl with real page descriptions and an llms-full.txt beside it, and the four things that make a generated file wrong.

25 Nov 2026 · 9 min read · Sid Mishra

Crawl a site and see what changed.

A one-time 1,000 credits to start, browser tier included, no card. The playground answers in seconds.