Markdown-pdf

1.13.1 · active · verified Wed Apr 15

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

Install

Imports

Quickstart

This quickstart demonstrates how to create a multi-section PDF from Markdown strings. It shows initializing `MarkdownPdf` with options like `toc_level` and `optimize`, adding individual `Section` objects with custom settings (like disabling TOC for a section or applying `user_css`), and finally setting document metadata before saving the PDF to a file.

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.")

view raw JSON →