There are many solutions for the task of automatically converting text in markdown format into a printable pdf file. These solutions based on Pandoc, LaTex, wkhtmltopdf, etc.
I want to share a new (at least for me) solution to this problem in Python.
This solution has the following advantages.
- All dependencies are in requrments.txt, no external binaries.
- There are no problems with non-standard encoding, pictures and the most popular markup elements.
- Ability to use different page sizes within one pdf.
- Customizable mode for creating a table of contents (bookmarks).
This method is based on the use of the libraries markdown-it-py (conversion from markdown to html) and PyMuPDF (conversion from html to pdf). A small Python class links them together.
Install
pip install markdown-pdf
Create a pdf with TOC (bookmarks) from headings up to level 2.
from markdown_pdf import MarkdownPdf
pdf = MarkdownPdf(toc_level=2)
Add three sections of markdown to the pdf. Each section starts on a new page. Headings from the first section are not included in the TOC.
from markdown_pdf import Section
pdf.add_section(Section("# Title\n", toc=False))
pdf.add_section(Section("# Head1\n\nbody\n"))
pdf.add_section(Section("## Head2\n\n### Head3\n\n"))
Set the properties of the pdf document.
pdf.meta["title"] = "User Guide"
Save to file.
pdf.save("guide.pdf")
Done!
Top comments (0)