# Python PDF generation libraries

Python PDF generation libraries create PDF documents from code, templates, or HTML. An HTML renderer lays out each page from markup and CSS rather than from drawing commands at fixed coordinates. These libraries let apps generate invoices, reports, and certificates as PDF files.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [PyMuPDF](#pymupdf) | 168.7M | 11.2K | Nov 2026 | AGPL-3.0 or commercial |
| [ReportLab](#reportlab) | 90.0M | 88 | Oct 2026 | BSD |
| [WeasyPrint](#weasyprint) | 44.5M | 9.8K | Sep 2026 | BSD |
| [pydyf](#pydyf) | 42.5M | 158 | Oct 2026 | BSD |
| [fpdf2](#fpdf) | 22.7M | 1.6K | Oct 2026 | LGPL-3.0-only |
| [pdfkit](#pdfkit) | 5.0M | 2.0K | Nov 2021 | MIT |
| [xhtml2pdf](#xhtmltwopdf) | 4.3M | 2.4K | Oct 2026 | Apache-2.0 |
| [borb](#borb) | 377.1K | 3.6K | Aug 2026 | AGPL-3.0-or-later |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[PyMuPDF](#pymupdf) has the most monthly downloads in this comparison, at 168.7M, a count that covers all its PDF work.

## Capabilities

| Library | HTML document input | Text/table layout |
| --- | --- | --- |
| [PyMuPDF](#pymupdf) | Yes | Yes |
| [ReportLab](#reportlab) | No | Yes |
| [WeasyPrint](#weasyprint) | Yes | Yes |
| [pydyf](#pydyf) | No | No |
| [fpdf2](#fpdf) | Yes | Yes |
| [pdfkit](#pdfkit) | Yes | Yes |
| [xhtml2pdf](#xhtmltwopdf) | Yes | Yes |
| [borb](#borb) | Undocumented | Yes |

## Libraries

### PyMuPDF

[GitHub](https://github.com/pymupdf/PyMuPDF) · [PyPI](https://pypi.org/project/pymupdf) · [Docs](https://pymupdf.readthedocs.io/en/latest/story-class.html)

Extracts, analyzes, converts, and edits PDF and other documents.

- Downloads / mo: 168.7M
- Stars: 11.2K
- Last release: 2.1
- License: AGPL-3.0 or commercial
- Capabilities: [From the PyMuPDF docs](https://pymupdf.readthedocs.io/en/latest/story-class.html)

```sh
python3 -m pip install PyMuPDF
```

**vb64/markdown-pdf** (163 stars)

[vb64/markdown-pdf](https://github.com/vb64/markdown-pdf) 

```python
def add_section(self, section: Section, user_css: typing.Optional[str] = None) -> str:
    """Add markdown section to pdf."""
    where = section.rect + section.borders
    html = self.m_d.render(self.apply_plugins(section.text))
    story = fitz.Story(html=html, archive=section.root, user_css=user_css)
    more = 1
    while more:  # loop outputting the story
        self.page_num += 1
        section.page_count += 1
        device = self.writer.begin_page(section.rect)
        more, _ = story.place(where)  # layout into allowed rectangle
        story.element_positions(self._recorder, {"toc": section.toc, "pdfile": self})
        story.draw(device)
        self.writer.end_page()

    self.sections.append(section)

    return html

```

[markdown_pdf/__init__.py](https://github.com/vb64/markdown-pdf/blob/10c36d6e84de5c2d91c0c34dbf51cb49213ed428/markdown_pdf/__init__.py#L120-L137) · [More projects using PyMuPDF →](https://dashboard.exa.ai/playground/search?q=pymupdf%20GitHub%20projects)

**Quickstart**

```python
import pymupdf
document = pymupdf.open()
page = document.new_page()
page.insert_text((72, 72), 'Hello World!')
document.save('hello.pdf')

```

From [recipes-text.rst](https://pymupdf.readthedocs.io/en/latest/recipes-text.html)

### ReportLab

[GitHub](https://github.com/MrBitBucket/reportlab-mirror) · [PyPI](https://pypi.org/project/reportlab) · [Docs](https://docs.reportlab.com/reportlab/userguide/ch5_platypus/)

Creates PDF documents with drawing APIs and a page-layout engine for report content.

- Downloads / mo: 90.0M
- Stars: 88
- Last release: 5.1.0
- License: BSD
- Capabilities: [From the ReportLab docs](https://docs.reportlab.com/reportlab/userguide/ch5_platypus/)

**Strengths**

- **Separates report content from layout.** Build reports from paragraph styles, page templates, and flowing content.
- **Repeats table headers across pages.** Split long tables across pages and repeat their header rows.

**Watch out for**

- **Frames reject oversized content.** Resize or split elements that cannot fit inside a frame.

```sh
python3 -m pip install reportlab
```

**ossf/cve-bin-tool** (1.8K stars)

[ossf/cve-bin-tool](https://github.com/ossf/cve-bin-tool) 

```python
def showtable(self, ident, widths=None):
    """
    Displays a table.

    Parameters:
    - ident: The identifier of the table.
    - widths: The widths of the columns (optional).
    """
    if self.table_ident == ident:
        self._spacer()
        tbl = Table(self.table_data, colWidths=widths, repeatRows=1)
        tbl.setStyle(self.table_style)
        self.contents.append(tbl)
        self.table_ident = None
        # Optional notes if data in columns truncated
        if len(self.note_data) > 0:
            notes = ["<br/><u>Notes</u>"]
            i = 1
            for d in self.note_data:
                notes.append(str(i) + ". " + d)
                i += 1
            self.paragraph("<br/>".join(notes))
            self.note_data = []
        self._spacer()

```

[cve_bin_tool/output_engine/pdfbuilder.py](https://github.com/ossf/cve-bin-tool/blob/cb54cec50258577650303d063aaa0b180c29923b/cve_bin_tool/output_engine/pdfbuilder.py#L356-L379) · [More projects using ReportLab →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20reportlab%20for%20report%20tables%2C%20searchable%20OCR%20text%20layers%20and%20PDF%20shading%20functions&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from reportlab.pdfgen import canvas
def hello(c):
    c.drawString(100,100,"Hello World")
c = canvas.Canvas("hello.pdf")
hello(c)
c.showPage()
c.save()

```

From [README.md](https://docs.reportlab.com/reportlab/userguide/ch2_graphics/)

### WeasyPrint

[GitHub](https://github.com/Kozea/WeasyPrint) · [PyPI](https://pypi.org/project/weasyprint) · [Docs](https://doc.courtbouillon.org/weasyprint/stable/first_steps.html)

Produces documents.

- Downloads / mo: 44.5M
- Stars: 9.8K
- Last release: 70.0
- License: BSD
- Capabilities: [From the WeasyPrint docs](https://doc.courtbouillon.org/weasyprint/stable/first_steps.html)

```sh
pip install weasyprint
```

**Quickstart**

```python
from weasyprint import HTML
HTML('https://weasyprint.org/').write_pdf('/tmp/weasyprint-website.pdf')


```

From [first_steps.rst](https://doc.courtbouillon.org/weasyprint/stable/first_steps.html) · [Find projects using WeasyPrint →](https://dashboard.exa.ai/playground/search?q=weasyprint%20GitHub%20projects)

### pydyf

[GitHub](https://github.com/CourtBouillon/pydyf) · [PyPI](https://pypi.org/project/pydyf) · [Docs](https://doc.courtbouillon.org/pydyf/stable/)

Writes PDF objects and content streams through a low-level Python interface.

- Downloads / mo: 42.5M
- Stars: 158
- Last release: 0.13.0
- License: BSD
- Capabilities: [From the pydyf docs](https://doc.courtbouillon.org/pydyf/stable/)

**Strengths**

- **Builds PDF objects directly.** Construct dictionaries, arrays, streams, and page resources explicitly.
- **Draws vector paths and graphics.** Control rectangles, line styles, transforms, and fills through a content stream.

**Watch out for**

- **Text needs explicit font resources.** Supply font dictionaries and page resources when constructing text streams.

```sh
python3 -m pip install pydyf
```

**Kozea/WeasyPrint** (9.8K stars)

[Kozea/WeasyPrint](https://github.com/Kozea/WeasyPrint) 

```python
@staticmethod
def create_stitching_function(domain, encode, bounds, sub_functions):
    return pydyf.Dictionary({
        'FunctionType': 3,
        'Domain': pydyf.Array(domain),
        'Encode': pydyf.Array(encode),
        'Bounds': pydyf.Array(bounds),
        'Functions': pydyf.Array(sub_functions),
    })

```

[weasyprint/pdf/stream.py](https://github.com/Kozea/WeasyPrint/blob/69b19deb03ddf53907899ec450da03117c6a0a8c/weasyprint/pdf/stream.py#L317-L325) · [More projects using pydyf →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20pydyf%20for%20report%20tables%2C%20searchable%20OCR%20text%20layers%20and%20PDF%20shading%20functions&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import pydyf
document = pydyf.PDF()
document.add_page(pydyf.Dictionary({
    'Type': '/Page',
    'Parent': document.pages.reference,
    'MediaBox': pydyf.Array([0, 0, 200, 200]),
}))
with open('document.pdf', 'wb') as f:
    document.write(f)

```

From [common_use_cases.rst](https://doc.courtbouillon.org/pydyf/stable/first_steps.html)

### fpdf2

[GitHub](https://github.com/py-pdf/fpdf2) · [PyPI](https://pypi.org/project/fpdf2) · [Docs](https://py-pdf.github.io/fpdf2/Tutorial.html)

Builds PDF documents with text, images, tables, font embedding, and page-break controls.

- Downloads / mo: 22.7M
- Stars: 1.6K
- Last release: 2.9.0
- License: LGPL-3.0-only
- Capabilities: [From the fpdf2 docs](https://py-pdf.github.io/fpdf2/Tutorial.html)

**Strengths**

- **Breaks flowing text across pages.** Cells and write text trigger page breaks at the configured bottom margin.
- **Builds tables from row data.** Add rows and cells through the table context manager.

**Watch out for**

- **Complex scripts need shaping setup.** Install uharfbuzz and enable set_text_shaping for complex script rendering.
- **Opening restrictions need user passwords.** Set a user password when opening the document must require authentication.

```sh
python3 -m pip install fpdf2
```

**ocrmypdf/OCRmyPDF** (35.3K stars)

[ocrmypdf/OCRmyPDF](https://github.com/ocrmypdf/OCRmyPDF) 

```python
def render(self, output_path: Path) -> None:
    """Render page to PDF file.

    Args:
        output_path: Output PDF file path
    """
    # Create PDF with custom page size
    pdf = FPDF(
        unit="pt",
        format=(
            self.coord_transform.page_width_pt,
            self.coord_transform.page_height_pt,
        ),
    )
    pdf.set_auto_page_break(auto=False)

    # Enable text shaping for complex scripts
    pdf.set_text_shaping(True)

    # Disable cell margin to ensure precise text positioning
    # fpdf2's cell() adds c_margin padding by default, which shifts text
    pdf.c_margin = 0

    # Set text mode for invisible text
    if self.invisible_text:
        pdf.text_mode = TextMode.INVISIBLE
    else:
        pdf.text_mode = TextMode.FILL

    # Render content to PDF
    self.render_to_pdf(pdf)

    # Write PDF
    pdf.output(str(output_path))

```

[src/ocrmypdf/fpdf_renderer/renderer.py](https://github.com/ocrmypdf/OCRmyPDF/blob/86a5e723ea2b612e8df4a647056b0ebf3b3c97a5/src/ocrmypdf/fpdf_renderer/renderer.py#L271-L304) · [More projects using fpdf2 →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20fpdf2%20for%20report%20tables%2C%20searchable%20OCR%20text%20layers%20and%20PDF%20shading%20functions&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from fpdf import FPDF
pdf = FPDF()
pdf.add_page()
pdf.set_font("helvetica", style="B", size=16)
pdf.cell(40, 10, "Hello World!")
pdf.output("tuto1.pdf")

```

From [Tables.html](https://py-pdf.github.io/fpdf2/Tutorial.html)

### pdfkit

[GitHub](https://github.com/JazzCore/python-pdfkit) · [PyPI](https://pypi.org/project/pdfkit) · [Docs](https://api.github.com/repos/JazzCore/python-pdfkit/contents/README.rst)

Converts HTML to PDF through wkhtmltopdf and the WebKit rendering engine.

- Downloads / mo: 5.0M
- Stars: 2.0K
- Last release: 1.0.0
- License: MIT
- Capabilities: [From the pdfkit docs](https://api.github.com/repos/JazzCore/python-pdfkit/contents/README.rst)

```sh
python3 -m pip install pdfkit
```

**sukeesh/Jarvis** (3.8K stars)

[sukeesh/Jarvis](https://github.com/sukeesh/Jarvis) 

```python
def md_to_pdf(self, jarvis):
    jarvis.say('')
    jarvis.say('This option will help you convert Markdown files to PDF')
    while True:
        md_file = jarvis.input('Enter the full path of the Markdown file (or type "quit" to exit): ').strip()
        if md_file.lower() in ['q', 'quit', 'exit']:
            jarvis.say("Goodbye!", Fore.CYAN)
            break

        if not os.path.isfile(md_file):
            jarvis.say('The file does not exist. Please try again.', Fore.RED)
            continue

        if not md_file.lower().endswith('.md'):
            jarvis.say('The file must be a Markdown (.md) file.', Fore.RED)
            continue

        try:
            with open(md_file, 'r', encoding='utf-8') as f:
                md_content = f.read()

            # Convert Markdown to HTML 
            html_content = markdown.markdown(md_content, extensions=['fenced_code', 'tables', 'toc'])

            # Process HTML to convert relative image paths to absolute paths
            html_content = self.convert_image_paths(html_content, os.path.dirname(os.path.abspath(md_file)))

            pdf_file = os.path.splitext(md_file)[0] + '.pdf'

            options = {
                'enable-local-file-access': None,
            }
            config = pdfkit.configuration()

            # Convert HTML to PDF 
            pdfkit.from_string(html_content, pdf_file, options=options, configuration=config)

            jarvis.say(f"Converted '{md_file}' to '{pdf_file}'.", Fore.GREEN)
        except Exception as e:
            jarvis.say(f"An error occurred: {e}", Fore.RED)
        break

```

[jarviscli/plugins/mdtopdf.py](https://github.com/sukeesh/Jarvis/blob/0c62c730de3af69d0105d0bbc7c65feee25c6f67/jarviscli/plugins/mdtopdf.py#L18-L58) · [More projects using pdfkit →](https://dashboard.exa.ai/playground/search?q=pdfkit%20GitHub%20projects)

**microsoft/intelligence-toolkit** (112 stars)

[microsoft/intelligence-toolkit](https://github.com/microsoft/intelligence-toolkit) 

```python
def add_download_pdf(
    name, text, button_text="Download PDF", is_markdown=True, disabled=False
):
    if not name.endswith(".pdf"):
        name += ".pdf"
    # Convert text to HTML if it's in Markdown format
    text = markdown2.markdown(text) if is_markdown else text
    text = f"<style>{style_pdf}</style> \n\n {text} <hr>{text_label}"

    # Generate PDF from HTML string
    config_pdf = config_pdfkit()

    with st.spinner("Preparing PDF download..."):
        with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as temp_file:
            pdfkit.from_string(
                text, temp_file.name, options=pdfkit_options, configuration=config_pdf
            )

            # Provide download button for the generated PDF
            with open(temp_file.name, "rb") as f:
                st.download_button(
                    button_text,
                    f,
                    file_name=name,
                    mime="application/pdf",
                    disabled=disabled,
                )

```

[app/util/download_pdf.py](https://github.com/microsoft/intelligence-toolkit/blob/5a539a10d19809a3c82607640e1f89f89ce0ca14/app/util/download_pdf.py#L16-L42) · [More projects using pdfkit →](https://dashboard.exa.ai/playground/search?q=pdfkit%20GitHub%20projects)

**Quickstart**

```python
import pdfkit
pdfkit.from_string('Hello!', 'out.pdf')

```

From [README.rst](https://api.github.com/repos/JazzCore/python-pdfkit/contents/README.rst)

### xhtml2pdf

[GitHub](https://github.com/xhtml2pdf/xhtml2pdf) · [PyPI](https://pypi.org/project/xhtml2pdf) · [Docs](https://xhtml2pdf.readthedocs.io/en/latest/)

Generates PDF from HTML and CSS.

- Downloads / mo: 4.3M
- Stars: 2.4K
- Last release: 0.2.28
- License: Apache-2.0
- Capabilities: [From the xhtml2pdf docs](https://xhtml2pdf.readthedocs.io/en/latest/)

```sh
pip install xhtml2pdf[all]
```

**nigma/django-easy-pdf** (366 stars)

[nigma/django-easy-pdf](https://github.com/nigma/django-easy-pdf) 

```python
def html_to_pdf(content, encoding="utf-8",
                link_callback=fetch_resources, **kwargs):
    """
    Converts html ``content`` into PDF document.

    :param unicode content: html content
    :returns: PDF content
    :rtype: :class:`bytes`
    :raises: :exc:`~easy_pdf.exceptions.PDFRenderingError`
    """
    src = BytesIO(content.encode(encoding))
    dest = BytesIO()

    pdf = pisa.pisaDocument(src, dest, encoding=encoding,
                            link_callback=link_callback, **kwargs)
    if pdf.err:
        logger.error("Error rendering PDF document")
        for entry in pdf.log:
            if entry[0] == xhtml2pdf.default.PML_ERROR:
                logger_x2p.error("line %s, msg: %s, fragment: %s", entry[1], entry[2], entry[3])
        raise PDFRenderingError("Errors rendering PDF", content=content, log=pdf.log)

    if pdf.warn:
        for entry in pdf.log:
            if entry[0] == xhtml2pdf.default.PML_WARNING:
                logger_x2p.warning("line %s, msg: %s, fragment: %s", entry[1], entry[2], entry[3])

    return dest.getvalue()

```

[easy_pdf/rendering.py](https://github.com/nigma/django-easy-pdf/blob/327605b91a445b453d8969b341ef74b12ab00a83/easy_pdf/rendering.py#L51-L78) · [More projects using xhtml2pdf →](https://dashboard.exa.ai/playground/search?q=xhtml2pdf%20GitHub%20projects)

**Quickstart**

```python
import io

from xhtml2pdf import pisa

output = io.BytesIO()

pisa.CreatePDF(
    "<html><body><p>To PDF or not to PDF</p></body></html>",  # page data
    dest=output,                                              # destination "file"
)

# You can get the PDF file bytes with `.getbuffer()`
print(len(output.getbuffer()))


```

From [quickstart.rst](https://xhtml2pdf.readthedocs.io/en/latest/quickstart.html)

### borb

[GitHub](https://github.com/borb-pdf/borb) · [PyPI](https://pypi.org/project/borb) · [Docs](https://api.github.com/repos/borb-pdf/borb/contents/README.md)

Reads, creates, and edits PDF files.

- Downloads / mo: 377.1K
- Stars: 3.6K
- Last release: 3.0.9
- License: AGPL-3.0-or-later
- Capabilities: [From the borb docs](https://api.github.com/repos/borb-pdf/borb/contents/README.md)

```sh
python3 -m pip install borb
```

**Quickstart**

```python
from pathlib import Path
from borb.pdf import Document, Page, PageLayout, SingleColumnLayout, Paragraph, PDF
d: Document = Document()
p: Page = Page()
d.append_page(p)
l: PageLayout = SingleColumnLayout(p)
l.append_layout_element(Paragraph('Hello World!'))
PDF.write(what=d, where_to="assets/output.pdf")

```

From [README.md](https://api.github.com/repos/borb-pdf/borb/contents/README.md) · [Find projects using borb →](https://dashboard.exa.ai/playground/search?q=borb%20GitHub%20projects)

## FAQ

### Which Python PDF generation library should I use?

[ReportLab](#reportlab) suits reports with flowing layouts, tables, and page templates. [WeasyPrint](#weasyprint) suits documents written as HTML and CSS. [fpdf2](#fpdf) suits pages built from text, tables, and images in Python.

### What is PyMuPDF?

[PyMuPDF](#pymupdf) creates, converts, and edits PDF documents and lays out HTML and CSS through its Story feature. It also extracts and analyzes content from existing PDFs.

### What is WeasyPrint?

[WeasyPrint](#weasyprint) renders HTML and CSS to PDF, including paged media layout. It relies on system libraries for rendering.

### What is ReportLab?

[ReportLab](#reportlab) draws PDF pages on a canvas and builds flowing reports with tables, page templates, and styles through its Platypus layer.

### What is xhtml2pdf?

[xhtml2pdf](#xhtmltwopdf) generates PDF from HTML and CSS on top of ReportLab. It supports a documented subset of markup and styles rather than full browser CSS.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python PDF generation libraries ReportLab fpdf2 pydyf pdfme code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
