Guide

How to Convert Markdown to PDF Using Python

Updated July 10, 2026

Python is the go-to language for data analysis, automation, and backend web development. Often, developers need to summarize reports or present data outputs as polished documents. Learning how to convert markdown to pdf python scripts allows you to programmatically generate clean reports, resumes, and documentation with just a few lines of code.

In this guide, we will compare the top Python libraries for PDF generation and write a practical script using WeasyPrint and the standard Python markdown library.

Top Python Libraries for Markdown-to-PDF Conversion

When searching for the right library, you have several primary paths:

  1. WeasyPrint: A highly recommended visual rendering engine for HTML and CSS that generates high-quality PDF files. It is standard-compliant and excellent at page templates.
  2. pdfkit / wkhtmltopdf: A Python wrapper for the command-line utility wkhtmltopdf. It uses the WebKit engine to render HTML pages to PDF.
  3. ReportLab: A low-level PDF drawing library. Extremely fast but requires manually positioning text and layout boxes, making it tedious for simple document rendering.

For most developers, converting Markdown to HTML first, and then using a CSS-capable HTML-to-PDF converter like WeasyPrint, yields the best results.

Step-by-Step Implementation with WeasyPrint

Let’s build a clean Python script that parses Markdown, applies custom CSS, and exports a PDF file.

Step 1: Install Dependencies

You will need the markdown parser and weasyprint libraries. Install them via pip:

pip install markdown weasyprint

Note: WeasyPrint requires system-level libraries like Gtk+ or Pango on some operating systems. Consult WeasyPrint’s official documentation for OS-specific prerequisites.

Step 2: Write the Python Conversion Script

Create a script named convert.py with the following code:

import markdown
from weasyprint import HTML, CSS

def markdown_to_pdf(input_md_path, output_pdf_path, stylesheet_path=None):
    # Read the markdown content
    with open(input_md_path, 'r', encoding='utf-8') as f:
        markdown_text = f.read()

    # Convert markdown to basic HTML structure
    html_content = markdown.markdown(
        markdown_text, 
        extensions=['extra', 'codehilite', 'toc']
    )

    # Wrap in a standard HTML document template
    full_html = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Document</title>
    </head>
    <body>
        <div class="content">
            {html_content}
        </div>
    </body>
    </html>
    """

    # Compile the PDF using WeasyPrint
    if stylesheet_path:
        HTML(string=full_html).write_pdf(
            output_pdf_path, 
            stylesheets=[CSS(stylesheet_path)]
        )
    else:
        HTML(string=full_html).write_pdf(output_pdf_path)

if __name__ == "__main__":
    markdown_to_pdf("report.md", "report.pdf", "styles.css")
    print("PDF compilation completed successfully!")

Adding Custom Layouts and Page Breaks

By utilizing WeasyPrint, you can include print-specific CSS elements. For example, to prevent code blocks from splitting across page breaks, you can add this to your styles.css:

pre {
  page-break-inside: avoid;
}

h1 {
  page-break-before: always;
}

h1:first-of-type {
  page-break-before: avoid;
}

This ensures your headers start on fresh pages, maintaining a clean structure throughout your generated report.

Conclusion

With Python’s modular library ecosystem, rendering Markdown files into professional PDFs is direct and highly customizable. WeasyPrint makes styling your documents using standard web technologies painless. If you want a quick, zero-setup option to compile files online, head over to our web-based online editor for instant results.

Written by Markdown to PDF Editorial Team

Our team specializes in document design, web standards, and developer utilities. This guide was researched and vetted against current browser printing standards and Paged.js specifications. Learn more on our About page.

Try it yourself — free, no signup

Convert your Markdown to a polished PDF right in your browser.

Open the editor