Skip to main content

Module markdown-pdf

GitHub Workflow Status GitHub Workflow Status Codacy Badge Codacy Badge PyPI - Downloads

The free, open source Python module markdown-pdf will create a PDF file from your markdown content.

When creating a PDF file you can:

  • Use UTF-8 encoded text in markdown in any language
  • Embed images used in markdown
  • Break text into pages in the desired order
  • Create a TableOfContents (bookmarks) from markdown headings
  • Tune the necessary elements using your CSS code
  • Use different page sizes within single pdf
  • Create tables in markdown
  • Use clickable hyperlinks. Thanks a lot @thongtmtrust for ideas and collaboration.
  • Render plantuml and mermaid code to pdf images with plugins.

The module utilizes the functions of two great libraries.

Installation

pip install markdown-pdf

Usage

Create a compressed pdf with TOC (bookmarks) from headings up to level 3.

from markdown_pdf import MarkdownPdf

pdf = MarkdownPdf(toc_level=3, optimize=True)

Add the first section to the pdf. The title is not included in the table of contents. After adding a section to a pdf, the page_count property in the section contains the number of pdf pages created for the added section.

from markdown_pdf import Section

section = Section("# Title\n", toc=False)
assert section.page_count == 0
pdf.add_section(section)
assert section.page_count == 1

Add a second section with external and internal hyperlinks. In the pdf file it starts on a new page.

text = """# Section with links

- [External link](https://github.com/vb64/markdown-pdf)
- [Internal link to Head1](#head1)
- [Internal link to Head3](#head3)
"""

pdf.add_section(Section(text))

Add a third section. The title is centered using CSS, included in the table of contents of the pdf file, and an image from the file img/python.png is embedded on the page.

pdf.add_section(
  Section("# <a name='head1'></a>Head1\n\n![python](img/python.png)\n\nbody\n"),
  user_css="h1 {text-align:center;}"
)

Add a next section. Two headings of different levels from this section are included in the TOC of the pdf file. The section has landscape orientation of A4 pages.

pdf.add_section(Section("## Head2\n\n### <a id='head3'></a>Head3\n\n", paper_size="A4-L"))

Add a section with a table.

text = """# Section with Table

|TableHeader1|TableHeader2|
|--|--|
|Text1|Text2|
|ListCell|<ul><li>FirstBullet</li><li>SecondBullet</li></ul>|
"""

css = "table, th, td {border: 1px solid black;}"

pdf.add_section(Section(text), user_css=css)

The sections property of the MarkdownPdf class contains a list of added sections in the order in which they were added.

assert len(pdf.sections) > 1

Set the properties of the pdf document.

pdf.meta["title"] = "User Guide"
pdf.meta["author"] = "Vitaly Bogomolov"

Save to file.

pdf.save("guide.pdf")

Or save to file-like object.

import io

out = io.BytesIO()
pdf.save_bytes(out)
assert out.getbuffer().nbytes > 0

Pdf

Settings and options

The Section class defines a portion of markdown data, which is processed according to the same rules. The next Section data starts on a new page.

The Section class can set the following attributes.

  • toc: whether to include the headers <h1> - <h6> of this section in the TOC. Default is True.
  • root: the name of the root directory from which the image file paths starts in markdown. Default ".".
  • paper_size: either the name of a paper size, as described here, or a list/tuple containing the width and height in mm. Default "A4".
  • borders: size of borders. Default (36, 36, -36, -36).

The following document properties are available for assignment (dictionary MarkdownPdf.meta) with the default values indicated.

  • creationDate: current date
  • modDate: current date
  • creator: "PyMuPDF library: https://pypi.org/project/PyMuPDF"
  • producer: ""
  • title: ""
  • author: ""
  • subject: ""
  • keywords: ""

By default, the underlaing pymupdf library generates a unique ID for a PDF file when saving it. So binary PDF files created from identical Markdown content will not be identical.

You can override this behavior by specifying the no_new_id=True option in the save/save_bytes methods.

pdf.save("guide.pdf", no_new_id=True)

out = io.BytesIO()
pdf.save_bytes(out, no_new_id=True)

In this case, the PDF files created from the same Markdown content will be identical at the binary level.

Plugins

The module allows you to process specially marked sections of code using plugins.

For example, you convert the following Markdown text to PDF:

# Title plantuml

Document with plantuml code.

```plantuml
@startuml
Alice -> Bob: Hello Bob
Bob --> Alice: Hi!
@enduml
```

End of document

Without using the plugin, you will get the following result in pdf:

Without plantuml.jpg

You can use a plugin to render plantuml code into an image.

from markdown_pdf import MarkdownPdf, Section
from markdown_pdf.pligins import Plugin

plantuml_text = """# Title plantuml

Document with plantuml code.

```plantuml
@startuml
Alice -> Bob: Hello Bob
Bob --> Alice: Hi!
@enduml
```

End of document
"""

plugins = {
  Plugin.Plantuml: {'url': 'http://www.plantuml.com/plantuml/img/'}
}

pdf = MarkdownPdf(plugins=plugins)
pdf.add_section(Section(plantuml_text))
pdf.save("plantuml.pdf")

In this case, the plugin will send the code marked as plantuml to the specified internet server and replace the code text with an image generated by the server www.plantuml.com.

In the created file plantuml.pdf, you will see the following result:

With plantuml.jpg

You can find a more detailed description of the plugins here.

Command Line Interface script

As an example, you can download the pdf file created from this README. This Python script was used to create the PDF file.

You can create your own CLI script, tailored to your needs, using this script as a starting point.

Development

git clone git@github.com:vb64/markdown-pdf.git
cd markdown-pdf
make setup PYTHON_BIN=/path/to/python3
make tests

Metadata

Release files for markdown-pdf 1.15

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for markdown-pdf 1.15
File Size Uploaded Provenance Actions
markdown_pdf-1.15.tar.gz 23.5 kB Without provenance Details for markdown_pdf-1.15.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for markdown-pdf 1.15
File Interpreter ABI Platform Actions
markdown_pdf-1.15-py3-none-any.whl Python 3 none any Details for markdown_pdf-1.15-py3-none-any.whl

Total release size: 45.0 kB

Release files / markdown_pdf-1.15.tar.gz

Download URL markdown_pdf-1.15.tar.gz
Size 23.5 kB
Tags Source
SHA-256 checksum
How to use checksums
83815768f84f1cc59cc0dfb944241fc4f696d6f432a4ee9fcf67eb521eaaa246
BLAKE2b-256 checksum
How to use checksums
5c6a85cf7f46d5fad66d81d77f81cb61a02f2e7d1e4f0110523b0d629c9a1dbb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.10

Release files / markdown_pdf-1.15-py3-none-any.whl

Download URL markdown_pdf-1.15-py3-none-any.whl
Size 21.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2a0cff8a559c177346e93e8154c8cf82e5b3cce21b5855eda68692809b9ff49d
BLAKE2b-256 checksum
How to use checksums
c84efcda0dac45684a224fe98edb90d1e40ebfe715695bae043e9e0d45a4a500
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.10

Security for markdown-pdf 1.15

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page