WeasyPrint

68.1 · active · verified Mon Apr 06

WeasyPrint is an actively maintained Python library (current version 68.1) that transforms HTML and CSS documents into high-quality PDF files. It acts as an 'Awesome Document Factory' by rendering web content using web standards, making it suitable for generating reports, invoices, books, and other printable documents with precise layout control. Releases are frequent, often several times a year.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to convert a simple HTML string with embedded CSS into a PDF file using WeasyPrint. You can also load HTML from a URL or a local file. The `write_pdf` method saves the rendered document to the specified filename.

from weasyprint import HTML, CSS

html_content = """
<!DOCTYPE html>
<html>
<head>
    <title>My Document</title>
    <style>
        @page { size: A4; margin: 2cm; }
        body { font-family: sans-serif; }
        h1 { color: #336699; }
        p { line-height: 1.5; }
    </style>
</head>
<body>
    <h1>Hello, WeasyPrint!</h1>
    <p>This is a test document generated from HTML and CSS into a PDF.</p>
    <img src="https://weasyprint.org/static/logo.png" alt="WeasyPrint Logo">
</body>
</html>
"""

# You can also load from a URL: HTML('https://weasyprint.org/')
# Or from a file: HTML(filename='my_document.html')

# Create an HTML object from a string
html = HTML(string=html_content)

# Optionally, add external CSS (or inline as shown above)
# css = CSS(filename='style.css') # or CSS(string='body { font-size: 12pt; }')

# Write the PDF to a file
html.write_pdf('output.pdf')

print("PDF generated successfully as output.pdf")

view raw JSON →