DEV Community

qing
qing

Posted on

Build a Markdown-to-PDF Converter with Python

Build a Markdown-to-PDF Converter with Python

tags: python, tools, automation, tutorial


tags: python, tools, automation, tutorial


You’ve got a Markdown file and need a polished PDF—maybe for a report, a user guide, or to share with a client who doesn’t want to deal with .md files. Instead of manually copying content into Word or relying on clunky online converters, you can build your own Markdown-to-PDF converter in Python today. It’s fast, customizable, and gives you full control over the output.

In this post, we’ll walk through building a working converter using the open-source markdown-pdf library. You’ll get a script that turns any .md file into a professional PDF with a table of contents, custom metadata, and multi-section formatting—all in under 10 minutes.

Why Build Your Own Converter?

Online tools are convenient, but they come with limitations: privacy concerns, lack of customization, and inconsistent formatting. Libraries like pdfkit or Spire.Doc work, but often require external dependencies (like wkhtmltopdf) or commercial licenses.

The markdown-pdf library is:

  • Open source and free
  • Pure Python (no external binaries needed)
  • Supports table of contents (TOC) generation
  • Lets you add metadata (title, author, etc.)
  • Handles multi-section PDFs with page breaks

It’s lightweight, reliable, and perfect for scripts, CLI tools, or backend services.

Step 1: Install the Library

First, install markdown-pdf via pip:

pip install markdown-pdf
Enter fullscreen mode Exit fullscreen mode

This installs the markdown_pdf module, which provides the MarkdownPdf and Section classes we’ll use.

Step 2: Create Your Converter Script

Here’s a complete, working Python script that converts a Markdown file to PDF with a TOC, custom title, and multiple sections:

from markdown_pdf import MarkdownPdf, Section

# Create PDF instance with TOC up to heading level 2
pdf = MarkdownPdf(toc_level=2)

# Set document metadata
pdf.meta["title"] = "User Guide"
pdf.meta["author"] = "Your Name"

# Add sections (each starts on a new page)
# Section 1: Title (not in TOC)
pdf.add_section(Section("# Welcome to the Guide\n", toc=False))

# Section 2: Main content with headings
pdf.add_section(Section(
    "# Introduction\n\n"
    "This guide explains how to use our software.\n\n"
    "## Features\n\n"
    "- Fast processing\n"
    "- Easy setup\n"
    "- Customizable output\n"
))

# Section 3: Additional content
pdf.add_section(Section(
    "## Advanced Tips\n\n"
    "### Using CLI\n\n"
    "Run the converter from terminal:\n\n"
    "`python convert.py input.md`\n\n"
    "### Customizing Styles\n\n"
    "You can modify CSS for better formatting."
))

# Save to file
pdf.save("guide.pdf")

print("✅ PDF generated successfully: guide.pdf")
Enter fullscreen mode Exit fullscreen mode

Run this script:

python converter.py
Enter fullscreen mode Exit fullscreen mode

You’ll get a guide.pdf file with:

  • A title page (not in TOC)
  • A table of contents listing “Introduction”, “Features”, “Advanced Tips”, and “Using CLI”
  • Page breaks between sections
  • Custom metadata visible in PDF readers

Step 3: Convert a Real Markdown File

Want to convert an actual .md file instead of hardcoded content? Here’s a reusable function:

def convert_md_to_pdf(md_file: str, pdf_file: str, toc_level: int = 2):
    from markdown_pdf import MarkdownPdf, Section

    with open(md_file, "r", encoding="utf-8") as f:
        markdown_content = f.read()

    pdf = MarkdownPdf(toc_level=toc_level)
    pdf.meta["title"] = md_file.replace(".md", "")

    # Add entire file as one section (in TOC)
    pdf.add_section(Section(markdown_content, toc=True))

    pdf.save(pdf_file)
    print(f"✅ Converted {md_file}{pdf_file}")

# Usage
convert_md_to_pdf("README.md", "output.pdf")
Enter fullscreen mode Exit fullscreen mode

This lets you drop any Markdown file into your project and generate a PDF instantly.

Step 4: Customize Further (Optional)

You can extend the converter with more features:

Add Multiple Files as Sections

If you have multiple .md files (e.g., intro.md, features.md, faq.md), combine them into one PDF:

files = ["intro.md", "features.md", "faq.md"]
pdf = MarkdownPdf(toc_level=2)
pdf.meta["title"] = "Complete Documentation"

for file in files:
    with open(file, "r", encoding="utf-8") as f:
        content = f.read()
    pdf.add_section(Section(content, toc=True))

pdf.save("documentation.pdf")
Enter fullscreen mode Exit fullscreen mode

Hide Specific Headings from TOC

Use toc=False in Section() to exclude certain parts:

pdf.add_section(Section("# Appendix\n", toc=False))
Enter fullscreen mode Exit fullscreen mode

Set Page Metadata

You can add author, subject, and keywords:

pdf.meta["author"] = "Dev Team"
pdf.meta["subject"] = "API Documentation"
pdf.meta["keywords"] = "markdown, pdf, python"
Enter fullscreen mode Exit fullscreen mode

Common Pitfalls & Fixes

❌ TOC Not Showing Up

Make sure you set toc_level in MarkdownPdf() and use toc=True in Section():

pdf = MarkdownPdf(toc_level=2)  # Required
pdf.add_section(Section("# Title", toc=True))  # Must be True
Enter fullscreen mode Exit fullscreen mode

❌ Headings Not in TOC

Only headings up to toc_level are included. If your TOC level is 2, ### headings won’t appear.

❌ File Not Found

Ensure your .md file path is correct. Use os.path.abspath() to verify:

import os
print(os.path.abspath("README.md"))
Enter fullscreen mode Exit fullscreen mode

When to Use This Approach

This converter is ideal for:

  • Generating user guides from documentation
  • Creating PDF reports from Markdown notes
  • Automating CI/CD pipelines that output PDFs
  • Building CLI tools for developers

It’s not ideal for:

  • Complex layouts with images, tables, or custom CSS (use pdfkit + wkhtmltopdf for that)
  • Commercial products requiring advanced typography (consider IronPDF or Aspose)

Take Action Today

You don’t need to wait for a perfect solution. Copy the script above, drop in your Markdown file, and generate a PDF in seconds. Then, customize it: add your logo, change the title, or combine multiple docs.

Try it now:

  1. Create a test.md file with some Markdown
  2. Run the convert_md_to_pdf() function
  3. Open output.pdf and see your content transformed

If you build something cool with this, share it on Dev.to or GitHub. And if you hit a snag, drop a comment below—I’ll help you debug it.

Build fast, ship today, and turn your Markdown into professional PDFs with just a few lines of Python.


If you found this helpful, consider buying me a coffee ☕ — it keeps these articles coming!

Also check out my AI tools collection: AI 次元世界 — free AI tools for developers.

Top comments (0)