Python markitdown
last modified November 30, 2026 Python 3.14
In this article we show how to convert documents to Markdown with the
markitdown library.
MarkItDown is a library and command line tool from Microsoft that turns many kinds of files into Markdown: HTML pages, CSV files, Excel workbooks, Word documents, PowerPoint presentations, PDF files, ZIP archives, images, and more. It keeps the structure of a document, such as headings, lists, tables, and links, and drops the rest. The output is meant to be read by programs, especially large language models (LLMs) and text analysis tools, rather than to look perfect to people.
Note that MarkItDown reads documents and writes Markdown. It does not convert Markdown to HTML; that is the job of libraries such as Python-Markdown.
The support for each format is an optional extra; [all]
installs all of them. The examples were tested with markitdown 0.1.9
on Python 3.14, because one of its dependencies, the
onnxruntime package, has no build for Python 3.15 yet.
$ pip install 'markitdown[all]'
Converting an HTML file
We start with a small HTML page. It has a navigation bar, a heading, a paragraph with a link, a list, and a script.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Falcons</title>
</head>
<body>
<nav><a href="/">Home</a> | <a href="/https/zetcode.com/birds/">Birds</a></nav>
<h1>Falcons</h1>
<p>
Falcons are birds of prey. The <b>peregrine falcon</b> is the
fastest animal on <a href="https://en.wikipedia.org/wiki/Earth">Earth</a>.
</p>
<h2>Species</h2>
<ul>
<li>Peregrine falcon</li>
<li>Gyrfalcon</li>
<li>Saker falcon</li>
</ul>
<script>console.log('tracking');</script>
</body>
</html>
This is the page.html file. The following program converts
it to Markdown.
from markitdown import MarkItDown
md = MarkItDown()
result = md.convert('page.html')
print(result.title)
print('---')
print(result.markdown)
The convert method of a MarkItDown object
accepts a file path, a URL, or an open binary stream. It finds out the
type of the input from the file extension and the content, and passes
it to the matching converter. The result has a markdown
attribute with the text and a title attribute, which holds
the page title if the document has one.
The headings, the bold text, the links, and the list keep their meaning in Markdown. The script and the head of the page are dropped. The navigation links stay, because MarkItDown cannot know that they are not part of the content.
$ python html_page.py Falcons --- [Home](/) | [Birds](/birds/) # Falcons Falcons are birds of prey. The **peregrine falcon** is the fastest animal on [Earth](https://en.wikipedia.org/wiki/Earth). ## Species * Peregrine falcon * Gyrfalcon * Saker falcon
Converting a string
Data that is already in memory is converted with the
convert_stream method. Since a stream has no file name, we
tell MarkItDown what kind of data it contains.
import io
from markitdown import MarkItDown, StreamInfo
html = '''
<h2>Price list</h2>
<table>
<tr><th>Item</th><th>Price</th></tr>
<tr><td>Coffee</td><td>2.50</td></tr>
<tr><td>Tea</td><td>1.80</td></tr>
</table>
<p>Prices include <i>VAT</i>.</p>
'''
md = MarkItDown()
stream = io.BytesIO(html.encode('utf-8'))
result = md.convert_stream(stream, stream_info=StreamInfo(extension='.html'))
print(result.markdown)
The method needs a binary stream, so we encode the string and wrap it
in io.BytesIO. The StreamInfo object gives
hints about the data; here the extension says it is HTML. Without the
hint, MarkItDown would guess the type from the content. The HTML table
becomes a Markdown table, and the <i> element is
written as *VAT*.
$ python html_string.py ## Price list | Item | Price | | --- | --- | | Coffee | 2.50 | | Tea | 1.80 | Prices include *VAT*.
Converting a CSV file
A CSV file is turned into a single Markdown table, whose first row is the header.
name,country,population Bratislava,Slovakia,475503 Budapest,Hungary,1686222 Prague,Czechia,1384732 Vienna,Austria,2028399
This is the cities.csv file.
from markitdown import MarkItDown
md = MarkItDown()
result = md.convert('cities.csv')
print(result.markdown)
The program is the same as for HTML; only the file name changes. Tables in Markdown are easy for LLMs to read, which is one of the main uses of the library.
$ python csv_table.py | name | country | population | | --- | --- | --- | | Bratislava | Slovakia | 475503 | | Budapest | Hungary | 1686222 | | Prague | Czechia | 1384732 | | Vienna | Austria | 2028399 |
Converting an Excel workbook
Each sheet of an Excel workbook becomes a separate Markdown table under a heading with the name of the sheet. We first create a small workbook with the openpyxl library and then convert it.
from openpyxl import Workbook
from markitdown import MarkItDown
wb = Workbook()
sales = wb.active
sales.title = 'Sales'
sales.append(['Month', 'Region', 'Amount'])
sales.append(['January', 'North', 1200])
sales.append(['January', 'South', 950])
sales.append(['February', 'North', 1340])
sales.append(['February', 'South', 1010])
staff = wb.create_sheet('Staff')
staff.append(['Name', 'Role'])
staff.append(['Alice', 'manager'])
staff.append(['Paul', 'analyst'])
wb.save('report.xlsx')
md = MarkItDown()
result = md.convert('report.xlsx')
print(result.markdown)
The workbook has two sheets, Sales and Staff. MarkItDown reads it with pandas and writes each sheet as a level-two heading followed by a table. The first row of each sheet is used as the header. The Openpyxl tutorial covers creating workbooks in detail.
$ python excel_sheets.py ## Sales | Month | Region | Amount | | --- | --- | --- | | January | North | 1200 | | January | South | 950 | | February | North | 1340 | | February | South | 1010 | ## Staff | Name | Role | | --- | --- | | Alice | manager | | Paul | analyst |
Converting a Word document
Word documents keep their headings, text formatting, lists, and tables. We create a short report with the python-docx library and convert it.
from docx import Document
from markitdown import MarkItDown
doc = Document()
doc.add_heading('Quarterly report', level=1)
para = doc.add_paragraph('Sales grew by ')
para.add_run('12 percent').bold = True
para.add_run(' compared to the previous quarter.')
doc.add_heading('Highlights', level=2)
doc.add_paragraph('New office in Kosice', style='List Bullet')
doc.add_paragraph('Two new products', style='List Bullet')
table = doc.add_table(rows=1, cols=2)
table.rows[0].cells[0].text = 'Region'
table.rows[0].cells[1].text = 'Amount'
for region, amount in [('North', '2540'), ('South', '1960')]:
cells = table.add_row().cells
cells[0].text = region
cells[1].text = amount
doc.save('quarterly.docx')
md = MarkItDown()
result = md.convert('quarterly.docx')
print(result.markdown)
The headings created with add_heading become Markdown
headings, the bold run becomes **12 percent**, and the
paragraphs in the List Bullet style become a list.
The table shows a quirk: in a Word table, no row is a header unless it is marked as one. MarkItDown therefore writes an empty header row and puts Region and Amount into the first data row. Tables in real Word documents usually mark the header row, and then it is used for the Markdown header.
$ python word_document.py # Quarterly report Sales grew by **12 percent** compared to the previous quarter. ## Highlights * New office in Kosice * Two new products | | | | --- | --- | | Region | Amount | | North | 2540 | | South | 1960 |
Creating a PDF file
To have a PDF file to work with, we export the Word document from the previous section with LibreOffice running without a window.
$ soffice --headless --convert-to pdf quarterly.docx convert /home/user/python/quarterly.docx -> /home/user/python/quarterly.pdf using filter : writer_pdf_Export
Converting a PDF file
PDF files are converted with the pdfminer library, which extracts their text.
from markitdown import MarkItDown
md = MarkItDown()
result = md.convert('quarterly.pdf')
print(result.markdown)
The output is much poorer than for the Word document with the same content. A PDF file stores where each piece of text is drawn on the page, not what role it plays. There are no headings, the bold text is plain, and the table is read column by column. When we have the original document, it is better to convert that one instead of the PDF.
$ python pdf_text.py Quarterly report Sales grew by 12 percent compared to the previous quarter. Highlights New office in Kosice Two new products Region North South Amount 2540 1960
Converting a ZIP archive
A ZIP archive is converted file by file. Each file gets its own section in the result.
import zipfile
from markitdown import MarkItDown
with zipfile.ZipFile('bundle.zip', 'w') as zf:
zf.write('cities.csv')
zf.write('page.html')
md = MarkItDown()
result = md.convert('bundle.zip')
print(result.markdown)
We pack the CSV file and the HTML page into an archive with the
zipfile module. MarkItDown converts each member with the
matching converter and writes the file name as a heading before its
content.
$ python zip_archive.py Content from the zip file `bundle.zip`: ## File: cities.csv | name | country | population | | --- | --- | --- | | Bratislava | Slovakia | 475503 | | Budapest | Hungary | 1686222 | | Prague | Czechia | 1384732 | | Vienna | Austria | 2028399 | ## File: page.html [Home](/) | [Birds](/birds/) # Falcons Falcons are birds of prey. The **peregrine falcon** is the fastest animal on [Earth](https://en.wikipedia.org/wiki/Earth). ## Species * Peregrine falcon * Gyrfalcon * Saker falcon
Converting a web page
When convert gets a URL, MarkItDown downloads the page with
the requests library. Some sites have their own converters; for
Wikipedia, only the main article text is kept, without the menus and
side bars.
import requests
from markitdown import MarkItDown
session = requests.Session()
session.headers['User-Agent'] = 'markitdown-tutorial/1.0'
md = MarkItDown(requests_session=session)
result = md.convert('https://en.wikipedia.org/wiki/Gyrfalcon')
print(result.title)
print(len(result.markdown), 'characters')
for line in result.markdown.splitlines()[:6]:
print(line[:75])
Wikipedia refuses requests with the default User-Agent header of the
requests library, which identifies a generic script. We create a
requests.Session with our own User-Agent and pass it to
the MarkItDown constructor in the
requests_session parameter. The session is then used for
all downloads, so it can also carry cookies, proxies, or timeouts.
The article is long, so we print its title, its length, and the first lines, each shortened to 75 characters.
$ python web_page.py Gyrfalcon 66857 characters # Gyrfalcon Species of bird This article is about the bird. For other uses, see [Gyrfalcon (disambiguat
Image metadata
For images, MarkItDown does not recognise any text. It reports
metadata read by the external exiftool program, if it is
installed.
from PIL import Image
from markitdown import MarkItDown
img = Image.new('RGB', (640, 480), 'skyblue')
exif = Image.Exif()
exif[0x010E] = 'Falcon over the Tatras'
exif[0x013B] = 'Peter Novak'
exif.get_ifd(0x8769)[0x9003] = '2026:06:14 07:30:00'
img.save('falcon.jpg', exif=exif)
md = MarkItDown()
result = md.convert('falcon.jpg')
print(result.markdown)
We create a JPEG image with the Pillow library and store three EXIF
tags in it: a description, the name of the photographer, and the time
the photo was taken. The original time lives in a nested EXIF block,
which we reach with get_ifd(0x8769).
MarkItDown prints only a fixed set of metadata fields, such as ImageSize, Artist, and DateTimeOriginal. The description is missing from the output, because exiftool reports it as ImageDescription, which is not in that set.
$ python image_metadata.py ImageSize: 640x480 Artist: Peter Novak DateTimeOriginal: 2026:06:14 07:30:00
Image descriptions with an LLM
To describe the content of an image, MarkItDown can send it to a
multimodal LLM. The llm_client parameter takes a client
object with the interface of the OpenAI library, and
llm_model names the model. In a real program, the client
is for example openai.OpenAI(), which needs an API key. To
see what MarkItDown sends without calling any service, we pass a small
stand-in client that answers on its own.
from types import SimpleNamespace
from markitdown import MarkItDown
def create(model, messages):
content = messages[0]['content']
print('model:', model)
print('prompt:', content[0]['text'])
print('image:', content[1]['image_url']['url'][:40] + '...')
answer = 'A plain light blue rectangle without any details.'
message = SimpleNamespace(content=answer)
return SimpleNamespace(choices=[SimpleNamespace(message=message)])
completions = SimpleNamespace(create=create)
client = SimpleNamespace(chat=SimpleNamespace(completions=completions))
md = MarkItDown(llm_client=client, llm_model='some-vision-model')
result = md.convert('falcon.jpg', llm_prompt='Describe the image in one sentence.')
print('---')
print(result.markdown)
MarkItDown calls client.chat.completions.create with the
model name and one message. The message contains the prompt and the
image encoded as a base64 data: URL. The stand-in
create function prints these parts and returns an object
with the same shape as an OpenAI response, built from
SimpleNamespace objects. The llm_prompt
argument of convert replaces the default prompt. The answer
of the model is added under a Description heading after the
metadata.
$ python llm_caption.py model: some-vision-model prompt: Describe the image in one sentence. image: data:image/jpeg;base64,/9j/4AAQSkZJRgABA... --- ImageSize: 640x480 Artist: Peter Novak DateTimeOriginal: 2026:06:14 07:30:00 # Description: A plain light blue rectangle without any details.
Converting files in a batch
A typical task is to convert a set of documents and save the results
as .md files. Some inputs may be missing or in a format
that MarkItDown does not support.
from pathlib import Path
from markitdown import MarkItDown, MarkItDownException
md = MarkItDown()
out_dir = Path('markdown')
out_dir.mkdir(exist_ok=True)
sources = ['page.html', 'cities.csv', 'report.xlsx', 'quarterly.docx',
'cities.csv.gz', 'missing.pdf']
for name in sources:
path = Path(name)
try:
result = md.convert(path)
except FileNotFoundError:
print(f'{name}: no such file')
continue
except MarkItDownException as e:
print(f'{name}: {type(e).__name__}')
continue
target = out_dir / path.with_suffix('.md').name
target.write_text(result.markdown, encoding='utf-8')
print(f'{name} -> {target} ({len(result.markdown)} characters)')
The program writes the Markdown of each file into the
markdown directory. The cities.csv.gz file is
a gzip-compressed copy of the CSV file; MarkItDown has no converter for
gzip and raises UnsupportedFormatException. All errors of
the library derive from MarkItDownException; a converter
that fails on a damaged file raises
FileConversionException. A missing local file raises the
usual FileNotFoundError.
$ python batch_convert.py page.html -> markdown/page.md (222 characters) cities.csv -> markdown/cities.md (181 characters) report.xlsx -> markdown/report.md (244 characters) quarterly.docx -> markdown/quarterly.md (217 characters) cities.csv.gz: UnsupportedFormatException missing.pdf: no such file
Writing a custom converter
MarkItDown can be extended with our own converters. A converter is a
subclass of DocumentConverter with two methods:
accepts decides whether the converter handles a stream,
and convert produces the result. We write a converter for
INI configuration files.
[server] host = localhost port = 8080 [database] name = shop user = admin
This is the settings.ini file. Without a custom converter,
MarkItDown would return it as plain text.
import configparser
from markitdown import (MarkItDown, DocumentConverter, DocumentConverterResult,
StreamInfo)
class IniConverter(DocumentConverter):
def accepts(self, file_stream, stream_info: StreamInfo, **kwargs):
return (stream_info.extension or '').lower() == '.ini'
def convert(self, file_stream, stream_info: StreamInfo, **kwargs):
text = file_stream.read().decode(stream_info.charset or 'utf-8')
config = configparser.ConfigParser()
config.read_string(text)
lines = []
for section in config.sections():
lines += [f'## {section}', '', '| Key | Value |', '| --- | --- |']
for key, value in config[section].items():
lines.append(f'| {key} | `{value}` |')
lines.append('')
return DocumentConverterResult(markdown='\n'.join(lines))
md = MarkItDown()
md.register_converter(IniConverter())
print(md.convert('settings.ini').markdown)
The accepts method checks the file extension in the
StreamInfo object. The convert method reads
the bytes from the stream, decodes them, and parses them with
configparser. Each section of the file becomes a heading
with a table of its keys and values. We must not close or wrap the
stream in a text wrapper, because MarkItDown still uses it after the
converter returns.
The register_converter method adds the converter to the
MarkItDown object. Converters are tried in the order of their
priority, where lower numbers come first. Our converter gets the
default priority for specific file formats, 0, while the plain text
converter has the generic priority 10, so ours takes over
.ini files. Among converters with the same priority, the
most recently registered one is tried first. Converters can also be packaged as plugins and
enabled with MarkItDown(enable_plugins=True).
$ python ini_converter.py ## server | Key | Value | | --- | --- | | host | `localhost` | | port | `8080` | ## database | Key | Value | | --- | --- | | name | `shop` | | user | `admin` |
The command line tool
The package also installs the markitdown command. It
converts a file and prints the Markdown, or writes it to a file with the
-o option.
$ markitdown cities.csv | name | country | population | | --- | --- | --- | | Bratislava | Slovakia | 475503 | | Budapest | Hungary | 1686222 | | Prague | Czechia | 1384732 | | Vienna | Austria | 2028399 |
$ markitdown page.html -o page.md; head -3 page.md [Home](/) | [Birds](/birds/) # Falcons
Source
markitdown on GitHub, markitdown on PyPI
In this article we have converted HTML, CSV, Excel, Word, PDF, and ZIP files, web pages, and images to Markdown with the markitdown library. We have used an LLM client to describe images, converted files in a batch, and written a custom converter. For the file formats themselves, see Python CSV, Openpyxl tutorial, Python ConfigParser, and Python web scraping with BeautifulSoup.
Author
List all Python tutorials.