Process Markdown with Python: Convert, Analyze and Generate
Markdown is the most popular writing format for technical docs, READMEs and blogs. Python offers several libraries to convert Markdown to HTML, PDF and other formats.
Installation
pip install markdown mistune weasyprint
Markdown to HTML with markdown
import markdown
text_md = """
# Main Title
This is a paragraph with **bold** and *italic* text.
## Feature List
- Easy to learn
- Compatible with many editors
- Exportable to multiple formats
```python
print("Hello world")
"""
html = markdown.markdown(text_md, extensions=["fenced_code", "tables", "toc"]) print(html)
with open("document.html", "w", encoding="utf-8") as f: f.write(f"
{html}") print("HTML generated: document.html")
## Markdown Extensions
```python
import markdown
def md_to_full_html(md_path, html_path, title="Document"):
with open(md_path, encoding="utf-8") as f:
content = f.read()
md = markdown.Markdown(extensions=[
"fenced_code", # Code blocks with ```
"codehilite", # Syntax highlighting
"tables", # GFM-style tables
"toc", # Table of contents
"meta", # YAML metadata at the top
"nl2br", # Newlines as <br>
"footnotes", # Footnotes
])
body = md.convert(content)
toc = md.toc
html = f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{title}</title>
<style>
body {{ font-family: Georgia, serif; max-width: 800px; margin: 0 auto; padding: 2em; }}
pre {{ background: #f4f4f4; padding: 1em; border-radius: 4px; overflow-x: auto; }}
code {{ font-family: monospace; }}
table {{ border-collapse: collapse; width: 100%; }}
th, td {{ border: 1px solid #ddd; padding: 8px; }}
</style>
</head>
<body>
<nav>{toc}</nav>
{body}
</body>
</html>"""
with open(html_path, "w", encoding="utf-8") as f:
f.write(html)
print(f"HTML generated: {html_path}")
md_to_full_html("README.md", "README.html", "Project Documentation")
Markdown to PDF
import markdown
from weasyprint import HTML
def md_to_pdf(md_path, pdf_path):
with open(md_path, encoding="utf-8") as f:
content = f.read()
html_body = markdown.markdown(content, extensions=["tables", "fenced_code", "toc"])
html_full = f"""
<html><head>
<meta charset="utf-8">
<style>
body {{ font-family: Arial, sans-serif; font-size: 12pt; }}
pre {{ background: #f0f0f0; padding: 8px; font-size: 10pt; }}
h1 {{ color: #333; border-bottom: 2px solid #333; }}
h2 {{ color: #555; }}
table {{ border-collapse: collapse; }}
td, th {{ border: 1px solid #ccc; padding: 6px; }}
</style></head>
<body>{html_body}</body></html>
"""
HTML(string=html_full).write_pdf(pdf_path)
print(f"PDF generated: {pdf_path}")
md_to_pdf("document.md", "document.pdf")
Extract Headings and Structure
import re
def extract_structure(md_path):
with open(md_path, encoding="utf-8") as f:
lines = f.readlines()
structure = []
for line in lines:
m = re.match(r'^(#{1,6})\s+(.+)', line)
if m:
level = len(m.group(1))
title = m.group(2).strip()
structure.append((level, title))
print(" " * (level-1) + f"H{level}: {title}")
return structure
extract_structure("documentation.md")
Convert Entire Markdown Directory to HTML
import markdown
from pathlib import Path
def convert_md_dir(input_dir, output_dir):
Path(output_dir).mkdir(exist_ok=True)
md_files = list(Path(input_dir).rglob("*.md"))
for i, md_file in enumerate(md_files, 1):
with open(md_file, encoding="utf-8") as f:
html = markdown.markdown(f.read(), extensions=["tables", "fenced_code"])
html_file = Path(output_dir) / (md_file.stem + ".html")
with open(html_file, "w", encoding="utf-8") as f:
f.write(f"<html><body>{html}</body></html>")
print(f" [{i}/{len(md_files)}] {md_file.name} -> {html_file.name}")
print(f"Converted {len(md_files)} files")
convert_md_dir("docs/", "docs_html/")
Additional Resource
For converting Markdown files to PDF, HTML or DOCX without any coding, use KaijuConverter — free and no registration required.
Related conversions
Document conversions that follow this topic naturally: