A Python library for converting Markdown files to PDF with cross-platform support.
- Cross-platform: Automatically selects the best PDF rendering backend for your OS
- Simple API: One function to convert Markdown to PDF
- Extensible: Support for tables, fenced code blocks, syntax highlighting, and table of contents
- Customizable: Use your own CSS for styling
pip install mark2pdf[windows]This installs Playwright, which uses your installed Chrome browser for PDF generation.
pip install mark2pdf[linux]This installs WeasyPrint for PDF generation.
pip install mark2pdf[all]Installs both backends for maximum compatibility.
from mark2pdf import mark_convert
# Convert a Markdown file to PDF
mark_convert("output.pdf", md_file_path="document.md")from mark2pdf import mark_convert
md_content = """
# Hello World
This is a **Markdown** document.
- Item 1
- Item 2
- Item 3
"""
mark_convert("output.pdf", md_content=md_content)from mark2pdf import mark_convert
mark_convert(
"output.pdf",
md_file_path="document.md",
css_file_path="custom-styles.css"
)Convert Markdown to PDF.
Parameters:
pdf_file_path(str): Output PDF file pathmd_file_path(str, optional): Path to input Markdown filemd_content(str, optional): Markdown content as string (alternative to md_file_path)css_file_path(str, optional): Path to custom CSS file
Raises:
ValueError: If neither md_file_path nor md_content is providedFileNotFoundError: If md_file_path doesn't exist
mark2pdf uses platform-specific backends for PDF generation:
| Platform | Backend | Description |
|---|---|---|
| Windows | Playwright | Uses Chrome's PDF printing capabilities |
| Linux | WeasyPrint | Direct HTML-to-PDF conversion |
| macOS | Auto | Tries WeasyPrint first, then Playwright |
The conversion process:
- Parse Markdown to HTML using Python's
markdownlibrary - Apply default CSS styling (or custom CSS if provided)
- Generate PDF using the platform-appropriate backend
- Headings
- Bold, italic, strikethrough
- Lists (ordered and unordered)
- Tables
- Fenced code blocks with syntax highlighting
- Links and images
- Blockquotes
- Table of contents (via
[TOC]marker)
Run the test script:
python test.pyThis will convert a sample Markdown file to PDF using the default settings.
Install in development mode:
pip install -e .[all]MIT License