Complete MarkItDown Tutorial: Convert Documents to Markdown for AI Pipelines
MarkItDown is an open-source library from Microsoft that enables you to convert various document formats — PDF, Word, PowerPoint, Excel, images, audio, HTML, and more — into clean Markdown. This library is invaluable for building RAG (Retrieval-Augmented Generation) pipelines, preprocessing documents for LLMs, and extracting structured content from complex files.
In this tutorial, we will learn how to install, configure, and use MarkItDown for various document conversion scenarios, from basic usage to integration with AI/ML pipelines.
Why MarkItDown?
Before MarkItDown, converting documents to an LLM-friendly format required a combination of multiple libraries: PyPDF2 for PDFs, python-docx for Word, python-pptx for PowerPoint, and so on. Each library had different APIs and inconsistent output formats.
MarkItDown simplifies everything with a single, consistent API. Key advantages include:
- One API for all formats: PDF, DOCX, PPTX, XLSX, HTML, CSV, JSON, XML, images, audio, and ZIP
- Clean Markdown output: Conversion results are neatly formatted with headings, tables, and lists
- LLM integration: Can use vision models (GPT-4o, etc.) for image descriptions
- Lightweight and fast: No GPU or heavy resources required
- Extensible: Add custom converters for new formats
- CLI and API: Use from command line or as a Python library
Installation
Basic Installation
pip install markitdown
Installation with Additional Features
MarkItDown supports several optional dependencies for specific features:
# For all features
pip install "markitdown[all]"
For PDF conversion only
pip install "markitdown[pdf]"
For image descriptions using LLM
pip install "markitdown[llm]"
For audio processing (speech-to-text)
pip install "markitdown[audio]"
For PPTX conversion
pip install "markitdown[pptx]"
For DOCX conversion
pip install "markitdown[docx]"
For XLSX conversion
pip install "markitdown[xlsx]"
Verify Installation
import markitdown
print(markitdown.version)
Basic Usage
Simple File Conversion
The most basic way to use MarkItDown is through the MarkItDown class:
from markitdown import MarkItDown
md = MarkItDown()
Convert a PDF file
result = md.convert("document.pdf")
print(result.textcontent)
The result object returned has a textcontent attribute containing the converted Markdown content.
Converting Various Formats
from markitdown import MarkItDown
md = MarkItDown()
Convert Word document
result = md.convert("report.docx")
print("=== DOCX ===")
print(result.textcontent[:500])
Convert PowerPoint
result = md.convert("presentation.pptx")
print("\n=== PPTX ===")
print(result.textcontent[:500])
Convert Excel
result = md.convert("data.xlsx")
print("\n=== XLSX ===")
print(result.textcontent[:500])
Convert HTML
result = md.convert("page.html")
print("\n=== HTML ===")
print(result.textcontent[:500])
Convert CSV
result = md.convert("dataset.csv")
print("\n=== CSV ===")
print(result.textcontent[:500])
Using the CLI
MarkItDown also provides a command-line interface:
# Convert file and print to stdout
markitdown document.pdf
Save result to file
markitdown document.pdf > output.md
Convert from stdin (pipe)
cat document.html | markitdown
Convert from URL
markitdown https://example.com/article.html
Format-Specific Conversion
PDF to Markdown
MarkItDown uses pdfminer to extract text from PDFs:
from markitdown import MarkItDown
md = MarkItDown()
result = md.convert("annual-report.pdf")
Save the result
with open("annual-report.md", "w", encoding="utf-8") as f:
f.write(result.textcontent)
print(f"Content length: {len(result.textcontent)} characters")
For PDFs containing images or scanned documents, best results are achieved by combining MarkItDown with OCR or vision models.
Word Documents (DOCX)
DOCX conversion preserves heading structure, paragraphs, tables, and lists:
from markitdown import MarkItDown
md = MarkItDown()
result = md.convert("proposal.docx")
Content will have headings (# ## ###), tables, and formatting
print(result.textcontent)
PowerPoint (PPTX)
For presentations, MarkItDown extracts text from each slide:
from markitdown import MarkItDown
md = MarkItDown()
result = md.convert("presentation.pptx")
Output will have separators per slide
Each slide becomes a section with a heading
print(result.textcontent)
Excel (XLSX) and CSV
Spreadsheets are converted to Markdown tables:
from markitdown import MarkItDown
md = MarkItDown()
Excel
result = md.convert("sales-data.xlsx")
print(result.textcontent)
Output as Markdown table:
| Month | Sales | Target |
|-------|--------|--------|
| Jan | 150 | 120 |
| Feb | 180 | 150 |
CSV
result = md.convert("dataset.csv")
print(result.textcontent)
HTML to Markdown
HTML conversion is useful for web scraping:
from markitdown import MarkItDown
md = MarkItDown()
From local file
result = md.convert("page.html")
print(result.textcontent)
From URL (if supported)
result = md.convert("https://example.com/article")
print(result.textcontent)
JSON and XML
Structured data files can also be converted:
from markitdown import MarkItDown
md = MarkItDown()
JSON
result = md.convert("config.json")
print(result.textcontent)
XML
result = md.convert("data.xml")
print(result.textcontent)
LLM Integration for Image Descriptions
One of MarkItDown's most powerful features is its ability to use vision LLM models to describe images found in documents:
Setup with OpenAI
from markitdown import MarkItDown
from openai import OpenAI
client = OpenAI(apikey="sk-your-api-key")
md = MarkItDown(llmclient=client, llmmodel="gpt-4o")
Convert image directly
result = md.convert("architecture-diagram.png")
print(result.textcontent)
Output: Detailed description of the image in Markdown format
Setup with Azure OpenAI
from markitdown import MarkItDown
from openai import AzureOpenAI
client = AzureOpenAI(
apikey="your-azure-key",
apiversion="2024-02-15-preview",
azureendpoint="https://your-resource.openai.azure.com/"
)
md = MarkItDown(llmclient=client, llmmodel="gpt-4o")
result = md.convert("screenshot.png")
print(result.textcontent)
Converting Documents with Images
When converting DOCX or PPTX files containing images, the LLM will automatically describe those images:
from markitdown import MarkItDown
from openai import OpenAI
client = OpenAI()
md = MarkItDown(llmclient=client, llmmodel="gpt-4o")
PPTX with many images and diagrams
result = md.convert("technical-presentation.pptx")
Images in the presentation will be replaced with text descriptions
print(result.textcontent)
Audio Conversion (Speech-to-Text)
MarkItDown can convert audio files to text using speech recognition:
from markitdown import MarkItDown
md = MarkItDown()
Convert audio file
result = md.convert("meeting-recording.wav")
print(result.textcontent)
Supports formats: WAV, MP3, and other audio formats
result = md.convert("podcast.mp3")
print(result.textcontent)
ZIP File Conversion
MarkItDown can process ZIP files and convert all files within them:
from markitdown import MarkItDown
md = MarkItDown()
Convert all files in ZIP
result = md.convert("project-documents.zip")
print(result.textcontent)
Each file in the ZIP will be converted and concatenated
Advanced Usage
Batch Processing
To process multiple files at once:
import os
from markitdown import MarkItDown
md = MarkItDown()
inputdir = "documents/"
outputdir = "markdown/"
os.makedirs(outputdir, existok=True)
supportedextensions = [".pdf", ".docx", ".pptx", ".xlsx", ".html", ".csv"]
for filename in os.listdir(inputdir):
ext = os.path.splitext(filename)[1].lower()
if ext in supportedextensions:
inputpath = os.path.join(inputdir, filename)
outputpath = os.path.join(outputdir, f"{os.path.splitext(filename)[0]}.md")
try:
result = md.convert(inputpath)
with open(outputpath, "w", encoding="utf-8") as f:
f.write(result.textcontent)
print(f"Success: {filename} -> {outputpath}")
except Exception as e:
print(f"Failed: {filename} - {e}")
Integration with RAG Pipelines
MarkItDown is an excellent fit for the ingestion stage of RAG pipelines:
from markitdown import MarkItDown
from langchain.textsplitter import RecursiveCharacterTextSplitter
from langchainopenai import OpenAIEmbeddings
from langchaincommunity.vectorstores import Chroma
Step 1: Convert document to Markdown
md = MarkItDown()
result = md.convert("technical-guide.pdf")
markdowncontent = result.textcontent
Step 2: Split into chunks
textsplitter = RecursiveCharacterTextSplitter(
chunksize=1000,
chunkoverlap=200,
separators=["\n## ", "\n### ", "\n#### ", "\n\n", "\n", " "]
)
chunks = textsplitter.splittext(markdowncontent)
print(f"Total chunks: {len(chunks)}")
Step 3: Create embeddings and store in vector store
embeddings = OpenAIEmbeddings()
vectorstore = Chroma.fromtexts(
texts=chunks,
embedding=embeddings,
collectionname="technical-docs"
)
Step 4: Query
retriever = vectorstore.asretriever(searchkwargs={"k": 3})
docs = retriever.invoke("How do I configure the system?")
for doc in docs:
print(doc.pagecontent[:200])
print("---")
Integration with LlamaIndex
from markitdown import MarkItDown
from llamaindex.core import Document, VectorStoreIndex
Convert document
md = MarkItDown()
result = md.convert("product-manual.pdf")
Create LlamaIndex document
document = Document(text=result.textcontent)
Build index
index = VectorStoreIndex.fromdocuments([document])
Query
queryengine = index.asqueryengine()
response = queryengine.query("What are the main features of this product?")
print(response)
Custom Converters
You can add custom converters for unsupported formats:
from markitdown import MarkItDown, DocumentConverter, DocumentConverterResult
class CustomLogConverter(DocumentConverter):
"""Converter for custom log files."""
def convert(self, localpath, kwargs) -> DocumentConverterResult:
# Read file
with open(localpath, "r") as f:
content = f.read()
# Parse and format as Markdown
lines = content.strip().split("\n")
markdownlines = ["# Log File\n"]
for line in lines:
parts = line.split(" ", 3)
if len(parts) >= 4:
timestamp = f"{parts[0]} {parts[1]}"
level = parts[2]
message = parts[3]
markdownlines.append(f"- [{level}] {timestamp} - {message}")
else:
markdownlines.append(f"- {line}")
return DocumentConverterResult(
title="Log File",
textcontent="\n".join(markdownlines)
)
Register converter
md = MarkItDown()
md.registerconverter(".log", CustomLogConverter())
Use it
result = md.convert("application.log")
print(result.textcontent)
Streaming for Large Files
To process very large files, you can divide the conversion process:
from markitdown import MarkItDown
def processlargedocument(filepath, chunkcallback):
"""Process large document and call callback for each section."""
md = MarkItDown()
result = md.convert(filepath)
# Split by level 2 headings
sections = result.textcontent.split("\n## ")
for i, section in enumerate(sections):
if i > 0:
section = "## " + section
chunkcallback(i, section)
def handlechunk(index, content):
print(f"Processing section {index}: {content[:100]}...")
# Save, embed, or process each section
processlargedocument("large-document.pdf", handlechunk)
Building a Document Ingestion Service
Here is a complete example of building a document ingestion service using FastAPI and MarkItDown:
from fastapi import FastAPI, UploadFile, File, HTTPException
from markitdown import MarkItDown
import tempfile
import os
app = FastAPI(title="Document Ingestion Service")
md = MarkItDown()
SUPPORTEDTYPES = {
"application/pdf": ".pdf",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx",
"application/vnd.openxmlformats-officedocument.presentationml.presentation": ".pptx",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx",
"text/html": ".html",
"text/csv": ".csv",
"image/png": ".png",
"image/jpeg": ".jpg",
}
@app.post("/convert")
async def convertdocument(file: UploadFile = File(...)):
if file.contenttype not in SUPPORTEDTYPES:
raise HTTPException(
statuscode=400,
detail=f"Unsupported file type: {file.contenttype}"
)
ext = SUPPORTEDTYPES[file.contenttype]
with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as tmp:
content = await file.read()
tmp.write(content)
tmppath = tmp.name
try:
result = md.convert(tmppath)
return {
"filename": file.filename,
"contenttype": file.contenttype,
"markdown": result.textcontent,
"length": len(result.textcontent)
}
except Exception as e:
raise HTTPException(statuscode=500, detail=str(e))
finally:
os.unlink(tmppath)
@app.post("/batch-convert")
async def batchconvert(files: list[UploadFile] = File(...)):
results = []
for file in files:
try:
result = await convertdocument(file)
results.append(result)
except HTTPException as e:
results.append({
"filename": file.filename,
"error": e.detail
})
return {"results": results}
Run this service with:
pip install fastapi uvicorn
uvicorn main:app --host 0.0.0.0 --port 8000
Best Practices
1. Choose the Right Installation
Do not install markitdown[all] in production if you only process PDFs. Install only the dependencies you need to reduce deployment size.
2. Validate Input
Always validate file types before attempting conversion. MarkItDown will raise an exception for unsupported formats:
import os
from markitdown import MarkItDown
ALLOWEDEXTENSIONS = {".pdf", ".docx", ".pptx", ".xlsx", ".html", ".csv"}
def safeconvert(filepath):
ext = os.path.splitext(filepath)[1].lower()
if ext not in ALLOWEDEXTENSIONS:
raise ValueError(f"Unsupported format: {ext}")
md = MarkItDown()
return md.convert(filepath)
3. Handle Errors Gracefully
Some files may be corrupt or have non-standard formatting:
from markitdown import MarkItDown
md = MarkItDown()
def convertwithfallback(filepath):
try:
result = md.convert(filepath)
if not result.textcontent.strip():
return None, "File is empty or cannot be extracted"
return result.textcontent, None
except Exception as e:
return None, f"Conversion error: {str(e)}"
content, error = convertwithfallback("document.pdf")
if error:
print(f"Warning: {error}")
else:
print(f"Successfully converted: {len(content)} characters")
4. Optimize for RAG Pipelines
When using MarkItDown for RAG, pay attention to how you chunk the results:
from markitdown import MarkItDown
md = MarkItDown()
result = md.convert("document.pdf")
Use headings as natural boundaries for chunking
Markdown headings create semantic chunk boundaries
sections = []
currentsection = []
for line in result.textcontent.split("\n"):
if line.startswith("## ") and currentsection:
sections.append("\n".join(currentsection))
currentsection = [line]
else:
currentsection.append(line)
if currentsection:
sections.append("\n".join(currentsection))
print(f"Total sections: {len(sections)}")
5. Cache Conversion Results
For frequently accessed files, cache conversion results:
import hashlib
import json
import os
from markitdown import MarkItDown
CACHEDIR = ".markitdowncache"
os.makedirs(CACHEDIR, existok=True)
def getfilehash(filepath):
with open(filepath, "rb") as f:
return hashlib.md5(f.read()).hexdigest()
def convertwithcache(filepath):
filehash = getfilehash(filepath)
cachepath = os.path.join(CACHEDIR, f"{filehash}.json")
if os.path.exists(cachepath):
with open(cachepath, "r") as f:
cached = json.load(f)
return cached["content"]
md = MarkItDown()
result = md.convert(filepath)
with open(cachepath, "w") as f:
json.dump({"content": result.textcontent, "source": filepath}, f)
return result.textcontent
6. Use LLM Only When Necessary
Enabling LLM for image descriptions adds cost and latency. Use it only when images are important for context:
from markitdown import MarkItDown
from openai import OpenAI
Without LLM - fast and free
mdbasic = MarkItDown()
With LLM - more comprehensive but has cost
client = OpenAI()
mdwithllm = MarkItDown(llmclient=client, llmmodel="gpt-4o-mini")
Use basic for text documents
result = mdbasic.convert("report.docx")
Use LLM only for documents with important images
result = mdwithllm.convert("visual-presentation.pptx")
Comparison with Other Tools
| Feature | MarkItDown | Unstructured | Docling | LlamaParse |
|---------|-----------|-------------|---------|-----------|
| Format support | Many | Many | PDF focused | PDF focused |
| Output format | Markdown | JSON/Dict | Markdown/JSON | Markdown |
| LLM integration | Yes | No | Yes | Yes (cloud) |
| Self-hosted | Yes | Yes | Yes | No |
| Price | Free | Free/Paid | Free | Paid |
| Setup complexity | Low | Medium | Medium | Low |
| Audio support | Yes | No | No | No |
| ZIP support | Yes | No | No | No |
Conclusion
MarkItDown from Microsoft is a practical and efficient solution for converting various document formats to Markdown. With a single consistent API, this library simplifies the document ingestion process that typically requires many different tools.
Key takeaways to remember:
This library is an excellent choice for teams building RAG systems, document Q&A, or document processing pipelines for AI applications. With Microsoft's backing and an active open-source community, MarkItDown continues to evolve with new format support and features.