Convert Markdown to PDF in Python – Complete Guide

Casie LiuCasie Liu
4 min read

Markdown is a lightweight markup language with great advantages for editing documentation. However, in many cases, PDF is a more suitable format than Markdown, such as delivering technical documents, printing or publishing e-books, and automating reports. Yet most Markdown editors don’t support exporting directly to PDF, and manual conversion can be time-consuming.

Fortunately, you can easily convert Markdown to PDF using Python, saving time and boosting your productivity!

Install the Python Library for Markdown to PDF Conversion

To simplify this task, today’s tutorial will demonstrate using Spire.Doc for Python. This professional Python library makes it easy to convert Markdown to PDF and allows you to edit, convert, and compress Word documents without requiring Microsoft Office.

Installing Spire.Doc is straightforward—just run the pip command below:

pip install spire.doc

Additionally, Spire.Doc offers a free version suitable for small files or testing purposes.

Convert Markdown to PDF in Python

With the help of Spire.Doc, exporting Markdown files to PDF using Python is straightforward and efficient, requiring just three simple steps. In this guide, we’ll start by looking at the complete code example so you can see the whole process in action, and then break down each step to explain how it works in detail.

Code example - Convert markdown to PDF directly in Python:

from spire.doc import *
from spire.doc.common import *

# Create an object of Document class
doc = Document()

# Load a Markdown file
doc.LoadFromFile("/sample.md", FileFormat.Markdown)

# Save the file to a PDF document
doc.SaveToFile("/MarkdownToPDF.pdf", FileFormat.PDF)

doc.Dispose()

Result preview:

Convert Markdown to PDF in Python Directly

Steps explained:

  • Create an object of the Document class.

  • Load the sample markdown file.

  • Convert the markdown document to PDF through the Document.SaveToFile() method.

💡
Tip: The Document.SaveToFile() method also supports converting Markdown to Word, making it easy to generate DOCX documents directly.

The above method uses default PDF settings. If you want to customize the page layout, the next section will show you how to set PDF properties during conversion.

Customize Page Settings During Markdown-to-PDF Conversion

Sometimes, you may need to adjust the output PDF’s page settings. For example, academic papers often require A4 size, while business reports may prefer Letter format. With the PageSetup class provided by Spire.Doc, you can set the page properties during conversion without needing to modify the PDF afterward.

Code example - Convert markdown to PDF and set page size, orientation and page margins:

from spire.doc import *
from spire.doc.common import *

# Create an object of Document class
doc = Document()

# Load a Markdown file
doc.LoadFromFile("/sample.md", FileFormat.Markdown)

# Get the default section
section = doc.Sections.get_Item(0)

# Get the page settings
pageSetup = section.PageSetup

# Customize the page settings
pageSetup.PageSize = PageSize.A4()
pageSetup.Orientation = PageOrientation.Landscape
pageSetup.Margins.All = 50

# Save the Markdown document to a PDF file
doc.SaveToFile("/MarkdownToPDFPageSetup.pdf", FileFormat.PDF)

doc.Dispose()

Key steps explained:

  • Set the page size using the PageSetup.PageSize property.

  • Set page orientation with the PageSetup.Orientation property.

  • Customize the margin of the PDF using PageSetup.Margins property.

Advanced – Batch Convert Multiple Markdown Files to PDF

Earlier, we showed how to export a single Markdown file to PDF in Python. But what if you have multiple Markdown files to process? For example, in cases like large document collections or regularly scheduled reports, you can loop through a folder containing multiple files and convert each one automatically. Let’s take a look at how to implement this in code.

Code example - Convert multiple markdown files to PDF in Python:

import os
from spire.doc import *
from spire.doc.common import *

input_folder = "/folder md/"
output_folder = "/mdtopdf/"

# Loop through each file in the input folder
for filename in os.listdir(input_folder):
    if filename.lower().endswith(".md"):
        # Create a Document object
        doc = Document()

        # Specify the input file path and load markdown files
        input_path = os.path.join(input_folder, filename)
        doc.LoadFromFile(input_path, FileFormat.Markdown)

        # Specify the output file path and name
        output_filename = os.path.splitext(filename)[0] + ".pdf"
        output_path = os.path.join(output_folder, output_filename)

        # Save the document as PDF
        doc.SaveToFile(output_path, FileFormat.PDF)

        # Release resources
        doc.Dispose()

Result preview:

Convert Multiple Markdown Files to PDF in Python

Key steps explained:

  • Loop through files in the folder.

  • For each markdown document in the folder, convert it to PDF through the Document.SaveToFile() method.

💡
If you plan to batch-convert Markdown files to PDF using Python, it’s best to organize all your Markdown files in a single folder for easier processing.

Conclusion

That’s all you need to know to efficiently convert single or multiple Markdown files to PDF using Python, including customizing page settings during the process. These techniques can help you streamline documentation delivery and report generation, saving valuable time. If you have any questions or run into issues, feel free to share them in the comments!

For more tutorials, check out our home page for the latest articles and guides.

5
Subscribe to my newsletter

Read articles from Casie Liu directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Casie Liu
Casie Liu