Markdown-pdf
markdown-pdf is a Python library designed to convert Markdown documents into PDF files. It utilizes `markdown-it-py` for efficient Markdown to HTML conversion and `PyMuPDF` for robust HTML to PDF rendering. Currently at version 1.13.1, the library is actively maintained with several releases per year, continuously adding new features and improvements.
Warnings
- breaking The project's license changed from MIT to AGPL-3.0 starting with version 1.6. Users of versions 1.6 and newer must review and comply with the AGPL-3.0 license terms.
- gotcha The core PDF generation relies on `PyMuPDF`, which is licensed under AGPL-3.0. This underlying dependency means that projects linking with or distributing `markdown-pdf` are generally subject to the copyleft provisions of the AGPL-3.0 license.
- gotcha When embedding images, relative paths are resolved using the `root` parameter of the `Section` class (defaults to current working directory). Incorrect `root` settings can cause images to be missing in the output PDF.
- gotcha By default, each `Section` added to a `MarkdownPdf` instance will start on a new page. This is the intended behavior for logical document structuring but can be a 'gotcha' if you expect continuous flow.
- gotcha Rendering PlantUML and Mermaid diagrams requires enabling specific plugins (`plantuml_plugin`, `mermaid_plugin`) when initializing `MarkdownPdf`; they are not active by default.
Install
-
pip install markdown-pdf
Imports
- MarkdownPdf
from markdown_pdf import MarkdownPdf
- Section
from markdown_pdf import Section
Quickstart
from markdown_pdf import MarkdownPdf, Section
import os
# Create a PDF with a Table of Contents (up to level 2 headings) and optimized output
pdf = MarkdownPdf(toc_level=2, optimize=True)
# Add the first section. The 'toc=False' ensures its title is not in the TOC.
pdf.add_section(Section("# Document Overview\n\nThis is an introduction to the document.", toc=False))
# Add a second section with external and internal hyperlinks
text_with_links = """
# Hyperlink Section
- [External Link to GitHub](https://github.com/vb64/markdown-pdf)
- [Internal Link to Subsection](#introduction-to-python)
## Introduction to Python
Python is a versatile programming language.
"""
pdf.add_section(Section(text_with_links))
# Add a third section with custom CSS applied to its headings
text_with_css = """
# Custom Styled Header
This section demonstrates custom CSS to center its main heading.
"""
pdf.add_section(Section(text_with_css, user_css="h1 {text-align:center; font-size: 2em;}"))
# Set PDF document metadata
pdf.meta["title"] = "Markdown-pdf Example Guide"
pdf.meta["author"] = "AI Assistant"
# Define the output file name
output_filename = os.environ.get('PDF_OUTPUT_FILE', 'example_document.pdf')
# Save the generated PDF to a file
pdf.save(output_filename)
print(f"PDF '{output_filename}' generated successfully.")