# Python HTML to PDF libraries

Python HTML to PDF libraries render a web page or an HTML string as a PDF document. A dedicated renderer lays out HTML and CSS itself rather than printing the page from a headless browser. These libraries let apps generate invoices, reports, and receipts from the same templates they show on the web.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [PyMuPDF](#pymupdf) | 168.7M | 11.2K | Nov 2026 | AGPLv3 |
| [Playwright](#playwright) | 134.2M | 15.1K | Nov 2026 | Apache-2.0 |
| [WeasyPrint](#weasyprint) | 44.5M | 9.8K | Sep 2026 | BSD-3-Clause |
| [Selenium](#selenium) | 30.5M | 34.6K | Nov 2026 | Apache-2.0 |
| [PDFKit](#pdfkit) | 5.0M | 2.0K | Nov 2021 | MIT |
| [xhtml2pdf](#xhtml-pdf) | 4.3M | 2.4K | Oct 2026 | Apache-2.0 |
| [SeleniumBase](#seleniumbase) | 1.3M | 13.3K | Nov 2026 | MIT |
| [pyppeteer](#pyppeteer) | 693.2K | 3.9K | Feb 2024 | MIT |

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 | JavaScript rendering | Chrome or Firefox |
| --- | --- | --- |
| [PyMuPDF](#pymupdf) | Undocumented | No |
| [Playwright](#playwright) | Yes | Yes |
| [WeasyPrint](#weasyprint) | No | No |
| [Selenium](#selenium) | Yes | Yes |
| [PDFKit](#pdfkit) | Yes | No |
| [xhtml2pdf](#xhtml-pdf) | No | No |
| [SeleniumBase](#seleniumbase) | Yes | Yes |
| [pyppeteer](#pyppeteer) | Yes | 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 manipulates PDF and other documents.

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

```sh
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

HTML = """
<p style="font-family: sans-serif;color: blue">Hello World!</p>
"""

MEDIABOX = pymupdf.paper_rect("letter")  # output page format: Letter
WHERE = MEDIABOX + (36, 36, -36, -36)  # leave borders of 0.5 inches

story = pymupdf.Story(html=HTML)  # create story from HTML
writer = pymupdf.DocumentWriter("output.pdf")  # create the writer

more = 1  # will indicate end of input once it is set to 0

while more:  # loop outputting the story
    device = writer.begin_page(MEDIABOX)  # make new page
    more, _ = story.place(WHERE)  # layout into allowed rectangle
    story.draw(device)  # write on page
    writer.end_page()  # finish page

writer.close()  # close output file


```

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

### Playwright

[GitHub](https://github.com/microsoft/playwright-python) · [PyPI](https://pypi.org/project/playwright) · [Docs](https://playwright.dev/python/docs/api/class-page#page-pdf)

Controls browser pages and exports their print layouts as PDF.

- Downloads / mo: 134.2M
- Stars: 15.1K
- Last release: 1.65.2
- License: Apache-2.0
- Runs on: Chromium
- Capabilities: [From the Playwright docs](https://playwright.dev/python/docs/api/class-page#page-pdf)

**Strengths**

- **Executes page JavaScript.** Render script-driven content in Chromium before exporting a PDF.
- **Selects print or screen styles.** Choose the media type before generating the PDF.

**Watch out for**

- **Browser binaries need separate installation.** Install Chromium before running the PDF example.

```sh
pip install playwright
playwright install chromium
```

**unclecode/crawl4ai** (87.5K stars)

[unclecode/crawl4ai](https://github.com/unclecode/crawl4ai) 

```python
async def export_pdf(self, page: Page) -> bytes:
    """
    Exports the current page as a PDF.

    Args:
        page (Page): The Playwright page object

    Returns:
        bytes: The PDF data
    """
    pdf_data = await page.pdf(print_background=True)
    return pdf_data

```

[crawl4ai/async_crawler_strategy.py](https://github.com/unclecode/crawl4ai/blob/cae74b203a33994f7e13b9052c3b0d5c93daa0e6/crawl4ai/async_crawler_strategy.py#L1624-L1635) · [More projects using Playwright →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20playwright%20for%20paginated%20HTML%20templates%2C%20renderer%20error%20handling%20and%20browser%20PDF%20exports&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 playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto("https://playwright.dev")
    print(page.title())
    browser.close()

```

From [library-python.md](https://raw.githubusercontent.com/microsoft/playwright/main/docs/src/library-python.md)

### WeasyPrint

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

Turns HTML pages into PDF documents.

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

**Strengths**

- **Supports paged print styles.** Use CSS page rules, margins, and page counters for print layouts.
- **Renders HTML without browser automation.** Generate PDFs with WeasyPrint’s own layout engine.

**Watch out for**

- **JavaScript content needs another renderer.** Render script-generated content before passing HTML to WeasyPrint.
- **Relative assets need a base.** Set base_url for relative image and stylesheet paths in HTML strings.

```sh
pip install weasyprint
```

**Quickstart**

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


```

From [first_steps.html](https://doc.courtbouillon.org/weasyprint/stable/first_steps.html) · [Find projects using WeasyPrint →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20weasyprint%20for%20paginated%20HTML%20templates%2C%20renderer%20error%20handling%20and%20browser%20PDF%20exports&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)

### Selenium

[GitHub](https://github.com/SeleniumHQ/selenium) · [PyPI](https://pypi.org/project/selenium) · [Docs](https://www.selenium.dev/documentation/webdriver/interactions/print_page/)

Provides the official Python bindings for Selenium WebDriver.

- Downloads / mo: 30.5M
- Stars: 34.6K
- Last release: 4.53.0
- License: Apache-2.0
- Capabilities: [From the Selenium docs](https://www.selenium.dev/documentation/webdriver/interactions/print_page/)

```sh
pip install selenium
```

**bellingcat/auto-archiver** (1.2K stars)

[bellingcat/auto-archiver](https://github.com/bellingcat/auto-archiver) 

```python
@logger.catch
def _enrich_full_page_pdf(self, sb: SB, to_enrich: Metadata):
    """
    Enriches the full page PDF of the Metadata object.
    This method is called by the enrich method.
    """
    result = sb.driver.execute_cdp_cmd("Page.printToPDF", {"printBackground": True, "landscape": False})

    pdf_data = base64.b64decode(result["data"])

    pdf_filename = os.path.join(self.tmp_dir, f"pdf{random_str(6)}.pdf")
    with open(pdf_filename, "wb") as f:
        f.write(pdf_data)

    to_enrich.add_media(Media(filename=pdf_filename), id="pdf")

```

[src/auto_archiver/modules/antibot_extractor_enricher/antibot_extractor_enricher.py](https://github.com/bellingcat/auto-archiver/blob/ceef7213eb36539978065dcd49ba162315e98b70/src/auto_archiver/modules/antibot_extractor_enricher/antibot_extractor_enricher.py#L314-L328) · [More projects using Selenium →](https://dashboard.exa.ai/playground/search?q=selenium%20GitHub%20projects)

**Quickstart**

```python
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

driver.get("https://www.selenium.dev/selenium/web/web-form.html")

```

From [first_script.py](https://www.selenium.dev/documentation/webdriver/getting_started/)

### 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 its 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
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_url('http://google.com', '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/quickstart.html)

Converts HTML and CSS into PDF documents through Python.

- 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/quickstart.html)

**Strengths**

- **Defines reusable page frames.** Place fixed headers and footers in static frames.
- **Writes PDF into memory.** Write PDF data into a BytesIO destination.

**Watch out for**

- **Table rows split at boundaries.** Split long content across rows when a cell exceeds its page space.

```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=Python%20projects%20using%20xhtml2pdf%20for%20paginated%20HTML%20templates%2C%20renderer%20error%20handling%20and%20browser%20PDF%20exports&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 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.html](https://xhtml2pdf.readthedocs.io/en/latest/quickstart.html)

### SeleniumBase

[GitHub](https://github.com/seleniumbase/SeleniumBase) · [PyPI](https://pypi.org/project/seleniumbase) · [Docs](https://raw.githubusercontent.com/seleniumbase/SeleniumBase/v4.58.1/README.md)

Crawls, scrapes, and tests the web, with pytest support.

- Downloads / mo: 1.3M
- Stars: 13.3K
- Last release: 4.58.1
- License: MIT
- Capabilities: [From the SeleniumBase docs](https://raw.githubusercontent.com/seleniumbase/SeleniumBase/v4.58.1/README.md)

```sh
pip install seleniumbase
```

**Quickstart**

```python
from seleniumbase import sb_cdp

sb = sb_cdp.Chrome(fast=True)
sb.goto("https://hn.algolia.com/?query=seleniumbase")
elements = sb.find_elements("div.Story_title > a")
for element in elements:
    print("--> " + element.text)
sb.save_as_pdf("sb_news.pdf", folder="./downloaded_files/")
print("*** PDF saved to: ./downloaded_files/sb_news.pdf")

```

From [README.md](https://raw.githubusercontent.com/seleniumbase/SeleniumBase/v4.58.1/README.md) · [Find projects using SeleniumBase →](https://dashboard.exa.ai/playground/search?q=seleniumbase%20GitHub%20projects)

### pyppeteer

[GitHub](https://github.com/pyppeteer/pyppeteer) · [PyPI](https://pypi.org/project/pyppeteer) · [Docs](https://raw.githubusercontent.com/pyppeteer/pyppeteer/2.0.0/README.md)

Automates headless Chrome or Chromium through an unofficial port of Puppeteer.

- Downloads / mo: 693.2K
- Stars: 3.9K
- Last release: 2.0.0
- License: MIT
- Capabilities: [From the pyppeteer docs](https://raw.githubusercontent.com/pyppeteer/pyppeteer/2.0.0/README.md)

```sh
pip install pyppeteer
```

**jupyter/nbconvert** (1.9K stars)

[jupyter/nbconvert](https://github.com/jupyter/nbconvert) 

```python
async def main(temp_file):
    """Run main pyppeteer script."""
    args = ["--no-sandbox"] if self.disable_sandbox else []
    browser = await self._check_launch_reqs()(
        handleSIGINT=False, handleSIGTERM=False, handleSIGHUP=False, args=args
    )
    page = await browser.newPage()
    await page.emulateMedia("print")
    await page.waitFor(100)
    await page.goto(f"file://{temp_file.name}", waitUntil="networkidle0")
    await page.waitFor(100)

    pdf_params = {"printBackground": True}
    if not self.paginate:
        # Floating point precision errors cause the printed
        # PDF from spilling over a new page by a pixel fraction.
        dimensions = await page.evaluate(
            """() => {
            const rect = document.body.getBoundingClientRect();
            return {
            width: Math.ceil(rect.width) + 1,
            height: Math.ceil(rect.height) + 1,
            }
        }"""
        )
        width = dimensions["width"]
        height = dimensions["height"]
        # 200 inches is the maximum size for Adobe Acrobat Reader.
        pdf_params.update(
            {
                "width": min(width, 200 * 72),
                "height": min(height, 200 * 72),
            }
        )
    pdf_data = await page.pdf(pdf_params)

    await browser.close()
    return pdf_data

```

[nbconvert/exporters/webpdf.py](https://github.com/jupyter/nbconvert/blob/5baf14103c3bca41cf3c0abd8717a9996b857028/nbconvert/exporters/webpdf.py#L91-L128) · [More projects using pyppeteer →](https://dashboard.exa.ai/playground/search?q=pyppeteer%20GitHub%20projects)

**Quickstart**

```python
import asyncio
from pyppeteer import launch

async def main():
    browser = await launch()
    page = await browser.newPage()
    await page.goto('https://example.com')
    await page.screenshot({'path': 'example.png'})
    await browser.close()

asyncio.get_event_loop().run_until_complete(main())

```

From [README.md](https://raw.githubusercontent.com/pyppeteer/pyppeteer/2.0.0/README.md)

## FAQ

### Which Python HTML to PDF library should I use?

[WeasyPrint](#weasyprint) suits invoices, reports, and other documents styled with print CSS. [Playwright](#playwright) suits pages that need JavaScript to render. [xhtml2pdf](#xhtml-pdf) suits basic layouts converted without a browser.

### What is WeasyPrint?

[WeasyPrint](#weasyprint) turns HTML and CSS into PDF documents with print features such as page sizes, headers, and footers. It does not execute JavaScript.

### How do I convert HTML to PDF with Playwright in Python?

Open the page in headless Chromium with [Playwright](#playwright) and call `page.pdf`. The call supports print CSS, backgrounds, page sizes, and headers and footers.

### WeasyPrint vs wkhtmltopdf: which should I use?

[WeasyPrint](#weasyprint) is a maintained HTML and CSS renderer for paged documents. wkhtmltopdf, which [PDFKit](#pdfkit) wraps, carries a deprecation warning along with PDFKit itself.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python HTML to PDF libraries WeasyPrint xhtml2pdf Playwright DocRaptor CSS JavaScript pagination code examples",
    "numResults": 5
  }
}
```

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