Markdown for RAG: Preparing Clean Context for LLMs
Quick answer: Markdown is the best intermediate format for RAG chunking because it removes presentation noise while keeping headings, lists, code fences, and pipe tables intact. Splitters get explicit topic boundaries, tables keep their header-to-cell alignment, and embeddings spend their tokens on real facts instead of markup.

Why Raw Documents Degrade RAG Retrieval
Most Retrieval-Augmented Generation (RAG) failures look like embedding or prompt problems on the surface, when the real culprit is noisy ingestion. Feeding raw HTML, uncleaned Word XML, or naive plain-text extractions straight into a vector store wastes context budget and fragments semantic boundaries.
Two opposite failure modes show up repeatedly in production pipelines:
- Markup bloat (raw HTML/XML): Navigation bars, wrapper
<div>layers, inline SVG icons, CSS classes, and tracking scripts surround the real content. Fixed-size chunkers split across opening and closing tags, filling chunks with structural syntax instead of domain facts. - Structure loss (naive plain-text stripping): Calling
.innerTextor dumping unformatted PDF strings strips out<h1>–<h3>boundaries, turns comparison tables into jumbled single-column text, and flattens code examples into prose.
Clean Markdown sits between those two extremes. It removes presentation noise while keeping the structural signals (headings, lists, fenced code blocks, and pipe tables) that both chunkers and language models rely on.
Plain Text vs. Raw HTML vs. Clean Markdown
Consider a typical documentation snippet fetched from a product page before ingestion:
<article class="doc-shell px-6 py-8">
<nav aria-label="breadcrumb"><a href="/docs">Docs</a> / Billing</nav>
<h2 id="rate-limits" class="anchor-heading">API Rate Limits</h2>
<p class="lead text-slate-600">Requests are metered per <strong>workspace key</strong>.</p>
<table class="w-full border-collapse">
<thead><tr><th>Plan</th><th>Requests / Min</th><th>Burst</th></tr></thead>
<tbody>
<tr><td>Starter</td><td>60</td><td>100</td></tr>
<tr><td>Pro</td><td>600</td><td>1,000</td></tr>
</tbody>
</table>
</article>
When converted cleanly to Markdown with navigation chrome stripped, the exact same information becomes:
## API Rate Limits
Requests are metered per **workspace key**.
| Plan | Requests / Min | Burst |
| --- | --- | --- |
| Starter | 60 | 100 |
| Pro | 600 | 1,000 |
Fast track: Convert your own files in the browser with HTML to Markdown, DOCX to Markdown, or PDF to Markdown, then inspect the
.mdoutput before it reaches an embedding model.
Notice three immediate engineering wins for retrieval:
- Zero wrapper syntax: Classes, ARIA attributes, and closing tags disappear without losing meaning.
- Intact table semantics: Column headers stay explicitly aligned to each row (
Plan→Requests / Min→Burst) rather than collapsing into disconnected lines likeStarter 60 100. - Deterministic section anchors: The
## API Rate Limitsboundary tells a Markdown-aware splitter exactly where a new topic begins.
Measuring Token Savings on Your Own Corpus
Generic averages vary wildly by template, so measure instead. The script below runs on the exact snippets shown above, with both strings defined inline so it runs as-is. It uses tiktoken with the o200k_base encoding:
import tiktoken
enc = tiktoken.get_encoding("o200k_base")
html_snippet = """<article class="doc-shell px-6 py-8">
<nav aria-label="breadcrumb"><a href="/docs">Docs</a> / Billing</nav>
<h2 id="rate-limits" class="anchor-heading">API Rate Limits</h2>
<p class="lead text-slate-600">Requests are metered per <strong>workspace key</strong>.</p>
<table class="w-full border-collapse">
<thead><tr><th>Plan</th><th>Requests / Min</th><th>Burst</th></tr></thead>
<tbody>
<tr><td>Starter</td><td>60</td><td>100</td></tr>
<tr><td>Pro</td><td>600</td><td>1,000</td></tr>
</tbody>
</table>
</article>
"""
md_snippet = """## API Rate Limits
Requests are metered per **workspace key**.
| Plan | Requests / Min | Burst |
| --- | --- | --- |
| Starter | 60 | 100 |
| Pro | 600 | 1,000 |
"""
raw_tokens = len(enc.encode(html_snippet))
md_tokens = len(enc.encode(md_snippet))
reduction = (raw_tokens - md_tokens) / raw_tokens * 100
print(f"Raw tokens: {raw_tokens}")
print(f"Markdown tokens: {md_tokens}")
print(f"Token reduction: {reduction:.1f}%")
Output for this snippet:
Raw tokens: 189
Markdown tokens: 51
Token reduction: 73.0%
That is 547 characters of HTML against 164 characters of Markdown. Part of the drop comes from removing the breadcrumb navigation, which is exactly the boilerplate a real conversion pass should strip. A tiny snippet also exaggerates the gap, because long prose paragraphs carry little markup per word. Treat 73% as the result for this table-heavy sample, not as a benchmark. Run the same check on 5–10 representative pages from your knowledge base to see which document types carry the heaviest overhead, typically CMS-rendered HTML, exported Confluence or Notion pages, and style-heavy DOCX reports.
Header-Aware Chunking Instead of Blind Character Splits
Once documents are normalized to Markdown, avoid slicing them purely by character counts (for example, every 1,000 characters regardless of context). Splitting in the middle of a table or separating a heading from its paragraph creates orphan chunks that retrieve poorly.
A two-pass strategy works reliably across technical docs and SOPs:
- Pass 1: Split on Markdown headings (
#,##,###). Attach the heading hierarchy as metadata (h1,h2,h3) on every resulting chunk so retrieved snippets retain their parent topic. - Pass 2: Sub-split only oversized sections. Apply a token-length splitter only when a single section exceeds your target window (typically 350–600 tokens, depending on your embedding model).
Example Two-Pass Python Splitter
from pathlib import Path
from langchain_text_splitters import (
MarkdownHeaderTextSplitter,
RecursiveCharacterTextSplitter,
)
clean_md = Path("sample-doc.md").read_text(encoding="utf-8")
header_splitter = MarkdownHeaderTextSplitter(
headers_to_split_on=[("#", "h1"), ("##", "h2"), ("###", "h3")],
strip_headers=False,
)
section_docs = header_splitter.split_text(clean_md)
token_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
encoding_name="o200k_base",
chunk_size=450,
chunk_overlap=50,
)
final_chunks = token_splitter.split_documents(section_docs)
Keeping strip_headers=False leaves the ## Heading inside the embedded text itself, not just in vector database metadata. That helps both dense vector similarity and BM25 keyword matching in hybrid search.
Warning: this exact snippet has a flaw. MarkdownHeaderTextSplitter only cuts at headings, so a table stays whole inside its section. The damage happens in pass 2: RecursiveCharacterTextSplitter has no concept of tables or code fences. When a section exceeds chunk_size, it will slice straight through a table row, a fenced code block, or between a header row and its data. The next section fixes that.
Table-Safe Chunking
The helper below pulls pipe tables out of a section, sends the prose through your normal splitter, and keeps every table whole. When a table exceeds max_chars, it splits between rows and repeats the two-line GFM header (| Col1 | Col2 | and |---|---|) at the top of each sub-chunk:
import re
TABLE_ROW = re.compile(r"^\s*\|.*\|\s*$")
def table_safe_chunks(section, prose_splitter, max_chars=1500):
"""Split prose normally, but never cut through a pipe table."""
chunks, prose, lines, i = [], [], section.splitlines(), 0
while i < len(lines):
if not TABLE_ROW.match(lines[i]):
prose.append(lines[i])
i += 1
continue
j = i
while j < len(lines) and TABLE_ROW.match(lines[j]):
j += 1
if prose:
chunks += prose_splitter.split_text("\n".join(prose))
prose = []
header = "\n".join(lines[i:i + 2]) # | A | B | + |---|---|
piece = header
for row in lines[i + 2:j]:
if len(piece) + len(row) + 1 > max_chars and piece != header:
chunks.append(piece)
piece = header # repeat header on sub-chunk
piece += "\n" + row
chunks.append(piece)
i = j
if prose:
chunks += prose_splitter.split_text("\n".join(prose))
return [c for c in chunks if c.strip()]
final_chunks = []
for doc in section_docs:
for text in table_safe_chunks(doc.page_content, token_splitter):
final_chunks.append({"text": text, "metadata": doc.metadata})
A small table passes through as one chunk. A 40-row table with max_chars=120 came out as six sub-chunks in testing, each starting with the same header, so any retrieved fragment still says which column is which. Fenced code blocks need the same treatment: extract them before the prose splitter runs, or raise chunk_size above your longest code example.
Wide Tables as Key-Value Rows
If a spreadsheet has 15 or more columns, even header repetition produces chunks that are mostly pipes and whitespace. When exact row lookup matters more than compact layout, serialize each row into Column: Value lines instead:
import csv
import io
def rows_to_kv(csv_text):
"""One self-contained 'Column: Value' block per spreadsheet row."""
reader = csv.DictReader(io.StringIO(csv_text))
return [
f"Row {n}\n" + "\n".join(f"{k}: {v}" for k, v in row.items() if v)
for n, row in enumerate(reader, start=1)
]
print(rows_to_kv("Plan,Region,Q1\nPro,EU,10\nStarter,US,\n")[0])
# Row 1
# Plan: Pro
# Region: EU
# Q1: 10
Each block is self-describing, so it retrieves correctly on its own and never depends on a header row that landed in a different chunk. The trade-off is size: every row repeats its column names.
PDFs, Scans, and Layout Edge Cases
Standard PDF text streams do not store semantic headings or table borders, only positioned glyphs. A converter has to guess structure from font sizes and coordinates, and multi-column layouts or financial tables often come out scrambled. Before pushing converted PDFs into an automated index, spot-check complex pages visually. If the PDF consists of scanned images rather than selectable text, run OCR first, then convert. Plain text-to-Markdown tools cannot recover text that was never encoded in the file.
RAG Markdown Converters Compared
No single converter wins on every document type. This matrix compares five common ingestion routes on the criteria that matter for RAG. Capabilities change between releases, so confirm against each project's current documentation before standardizing.
| Route | Privacy / Local Execution | Table Header Preservation | Scanned PDF / OCR | Speed / Zero-Setup | Best RAG Use Case |
|---|---|---|---|---|---|
| MD Convert (browser-local JavaScript tools) | Runs in the browser; files are not uploaded | HTML and DOCX tables become GFM pipe tables with a header row | No OCR; text-based PDFs only | Nothing to install | Confidential one-off files you want to inspect and redact before indexing |
| Microsoft MarkItDown (Python) | Local library and CLI | Converts Office and HTML tables to Markdown tables | No built-in OCR for scanned PDFs; optional add-ons exist | pip install, then a few lines of code |
Batch conversion of mixed Office files inside a Python pipeline |
| IBM Docling (layout-aware parser) | Local, after downloading models | Strongest of the five; dedicated table-structure model | Built-in OCR options | Heavier install, slower on CPU | Complex PDFs, multi-column reports, scanned documents |
| Pandoc (CLI) | Local | Pipe tables for simple cases; merged cells or block content fall back to raw HTML | No OCR; cannot read PDF input | One binary, fast | DOCX, HTML, EPUB, and LaTeX sources in CI jobs |
| Raw BeautifulSoup + html2text | Local | Depends on markup; verify output per template | None | Fast to run, but you write selectors to strip boilerplate | Scraping a known site template you control |
Choose by document type, not brand. Selectable-text pages and Office files suit lightweight converters. Scanned or layout-heavy PDFs need a layout-aware parser with OCR, and that is worth the extra setup time.
Privacy Check Before Indexing Confidential Files
Many teams inadvertently leak client contracts, internal SOPs, or financial statements when they upload raw files to hosted conversion APIs just to extract text for an internal LLM pipeline. Preprocessing locally in the browser with HTML to Markdown, DOCX to Markdown, or text-based PDF to Markdown lets you inspect, redact, and verify the exact .md output before any chunk reaches an external embedding endpoint or vector database.
You should not have to take that on trust. Verify it yourself in three steps:
- Open the converter page, press F12 (or Cmd+Option+I on macOS), and switch to the Network tab. Tick Preserve log, then clear the existing entries.
- Drop in a test file and run the conversion.
- Review the new requests. Filter by Fetch/XHR and open any entry's Payload and Size columns. You should see no request carrying your file or its contents. The only traffic expected is cookieless aggregate analytics.
One exception is worth knowing. URL to Markdown must fetch a remote page, and browsers block most cross-origin fetches, so that tool routes the request through a proxy. Only the URL you enter goes out, not a local file. Use the file-based converters for anything confidential.
The all-in-one Markdown conversion workspace (16 dedicated converters) also covers adjacent structured sources that show up in RAG pipelines, including JSON to Markdown for API exports and CSV to Markdown for spreadsheet extracts.
Pre-Ingestion Markdown Quality Checklist
Before syncing converted .md files to your vector store, verify five quick items:
- Consistent heading hierarchy: No skipped levels or duplicate page-wrapper headings.
- No leftover boilerplate: Navigation menus, cookie banners, and footer links stripped.
- Closed code fences: Every opening ````` has a matching closing fence with its language tag preserved.
- Clean relative links or stripped anchors: Avoid broken relative image or page links that add noise without retrieval value.
- UTF-8 normalization: Smart quotes, non-breaking spaces, and CRLF line endings normalized cleanly.
FAQ
Why is Markdown better than JSON or plain text for RAG?
Plain text loses headings and table structure, and JSON spends tokens on braces, quotes, and key names. Markdown keeps section boundaries, lists, code fences, and table alignment in a compact form that splitters can parse and models read naturally.
Does LangChain's MarkdownHeaderTextSplitter break tables?
No. It splits only at headings, so a table stays whole inside its section. The break happens in the second pass, where RecursiveCharacterTextSplitter can cut an oversized table mid-row. Add a table-aware step that repeats the header row on every sub-chunk.
How do I handle scanned PDFs before converting to Markdown for LLMs?
Scanned PDFs contain images, not text, so run OCR first to produce a text layer, or use a layout-aware parser with built-in OCR. Then convert to Markdown and visually check tables, columns, and numbers before indexing, because OCR errors embed just as faithfully as correct text.
Is converting confidential contracts to Markdown in the browser safe?
Browser-local conversion keeps the file on your machine, which removes the upload risk of hosted APIs. Confirm it yourself: open DevTools, watch the Network tab during conversion, and check that no request carries your file. Exclude the URL converter, which uses a proxy.