Python PDF Generation: ReportLab, WeasyPrint & API (6 Ways)
Generating PDFs in Python comes up constantly — invoices, reports, certificates, data exports. Python has no shortage of libraries, but each has different strengths, dependencies, and CSS support.
This guide compares six major approaches with working code examples and explains when to use each. All API examples use FUNBREW PDF — no Chromium binary required in your server.
Python PDF Generation: Six Approaches Compared
| Approach | HTML Support | CSS Quality | Dependencies | Serverless | Best For |
|---|---|---|---|---|---|
| FUNBREW PDF API | Full | High (quality = Chromium, Pro plan+) / Medium (fast = wkhtmltopdf) | requests only |
Yes | Production, SaaS, complex layouts |
| ReportLab | None | — | Medium | Yes | Data reports, charts, programmatic docs |
| WeasyPrint | Full | Medium–High | Large (Pango and other system libraries) | Difficult | HTML-to-PDF, mid-scale apps |
| xhtml2pdf | HTML5 (partial CSS) | Low–Medium | Medium (pure Python on ReportLab) | Yes | Simple documents, no binary needed |
| pdfkit (wkhtmltopdf) | Full | Medium | wkhtmltopdf binary | Difficult | Legacy wkhtmltopdf environments |
| Playwright for Python | Full | High (Chromium) | Chromium binary | Difficult | Local dev, combined with test automation |
For complex HTML layouts — charts, tables, CJK fonts — a PDF API is the most practical approach. See the PDF API vs library comparison for a detailed breakdown.
1. FUNBREW PDF API (Recommended)
Installation and Base Setup
pip install requests python-dotenv
# pdf_client.py
import os
import requests
from dotenv import load_dotenv
load_dotenv()
FUNBREW_API_KEY = os.environ["FUNBREW_API_KEY"]
# Keep only the host in a constant and write full paths at the call site
FUNBREW_BASE_URL = os.getenv("FUNBREW_BASE_URL", "https://pdf.funbrew.cloud")
AUTH_HEADERS = {"Authorization": f"Bearer {FUNBREW_API_KEY}"}
def html_to_pdf(
html: str,
engine: str | None = None,
page_size: str = "A4",
orientation: str = "Portrait",
margin_mm: dict | None = None,
) -> bytes:
"""
Convert an HTML string to PDF and return the PDF bytes (generate, then download).
Args:
html: HTML string to render
engine: "quality" (Chromium, Pro plan and above) or "fast" (wkhtmltopdf).
Omit it to let your plan decide
page_size: Paper size ("A3", "A4", "A5", "Letter", "Legal")
orientation: "Portrait" or "Landscape"
margin_mm: Margins as numbers in mm for top/right/bottom/left (0-50)
Returns:
PDF binary data (bytes)
"""
if margin_mm is None:
margin_mm = {"top": 20, "right": 15, "bottom": 20, "left": 15}
options = {"page-size": page_size, "orientation": orientation}
for side, value in margin_mm.items():
options[f"margin-{side}"] = value
if engine:
options["engine"] = engine
# 1. Generate: the response is JSON with the download URL in data.download_url
response = requests.post(
f"{FUNBREW_BASE_URL}/api/pdf/generate-from-html",
headers=AUTH_HEADERS,
json={"html": html, "options": options},
timeout=60,
)
response.raise_for_status()
download_url = response.json()["data"]["download_url"]
# 2. Download: fetch the PDF itself with the same API key
pdf_response = requests.get(download_url, headers=AUTH_HEADERS, timeout=60)
pdf_response.raise_for_status()
return pdf_response.content
The generation endpoint returns JSON (success, data.download_url and so on), not the PDF itself. Download the PDF from download_url (/api/pdf/download/{filename}) with the same API key. options accepts page-size, orientation, margin-top/right/bottom/left (mm, 0-50) and engine; the quality (Chromium) engine is available on the Pro plan and above (Free gets a 403 if it requests it).
See the API docs for the full list of request options.
Basic Usage
# generate_basic.py
from pdf_client import html_to_pdf
html = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
body { font-family: -apple-system, 'Segoe UI', sans-serif; padding: 40px; color: #1e293b; }
h1 { color: #2563eb; }
</style>
</head>
<body>
<h1>Hello, PDF!</h1>
<p>Generated with the FUNBREW PDF API from Python.</p>
</body>
</html>"""
pdf_bytes = html_to_pdf(html)
with open("output.pdf", "wb") as f:
f.write(pdf_bytes)
print(f"PDF generated: {len(pdf_bytes):,} bytes")
Invoice PDF Example
# invoice_generator.py
from datetime import date
from html import escape
from pdf_client import html_to_pdf
def build_invoice_html(
customer_name: str,
amount: int,
items: list[dict] | None = None,
company_name: str = "FUNBREW Inc.",
) -> str:
tax = int(amount * 0.1)
total = amount + tax
invoice_number = f"INV-{date.today().strftime('%Y%m%d')}-001"
issue_date = date.today().strftime("%B %d, %Y")
if not items:
items = [{"name": "Service fee", "quantity": 1, "price": amount}]
rows = "".join(
f"<tr><td>{escape(item['name'])}</td>"
f"<td style='text-align:right'>{item['quantity']}</td>"
f"<td style='text-align:right'>${item['price']:,}</td>"
f"<td style='text-align:right'>${item['price'] * item['quantity']:,}</td></tr>"
for item in items
)
return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
@page {{ size: A4; margin: 20mm 15mm; }}
* {{ box-sizing: border-box; margin: 0; padding: 0; }}
body {{
font-family: -apple-system, 'Segoe UI', sans-serif;
font-size: 12px; color: #1e293b;
-webkit-print-color-adjust: exact; print-color-adjust: exact;
}}
.header {{ display: flex; justify-content: space-between;
border-bottom: 3px solid #2563eb; padding-bottom: 16px; margin-bottom: 24px; }}
.title {{ font-size: 28px; font-weight: 700; color: #2563eb; }}
table {{ width: 100%; border-collapse: collapse; margin-top: 16px; }}
th {{ background: #dbeafe; padding: 10px; text-align: left; }}
td {{ padding: 10px; border-bottom: 1px solid #e2e8f0; }}
.total {{ text-align: right; margin-top: 16px; }}
.total-amount {{ font-size: 22px; font-weight: 700; color: #2563eb; }}
</style>
</head>
<body>
<div class="header">
<div>
<div class="title">Invoice</div>
<div>Invoice #: {invoice_number}</div>
<div>Date: {issue_date}</div>
</div>
<div style="text-align:right"><strong>{escape(company_name)}</strong></div>
</div>
<p><strong>Bill To: {escape(customer_name)}</strong></p>
<table>
<thead>
<tr><th>Item</th><th>Qty</th><th>Unit Price</th><th>Subtotal</th></tr>
</thead>
<tbody>{rows}</tbody>
</table>
<div class="total">
<p>Subtotal: ${amount:,}</p>
<p>Tax (10%): ${tax:,}</p>
<p class="total-amount">Total: ${total:,}</p>
</div>
</body>
</html>"""
def generate_invoice_pdf(customer_name: str, amount: int, items=None) -> bytes:
html = build_invoice_html(customer_name, amount, items)
return html_to_pdf(html, page_size="A4")
if __name__ == "__main__":
pdf = generate_invoice_pdf(
customer_name="Acme Corporation",
amount=15_000,
items=[
{"name": "Web Development", "quantity": 1, "price": 12_000},
{"name": "Monthly Support", "quantity": 3, "price": 1_000},
],
)
with open("invoice.pdf", "wb") as f:
f.write(pdf)
print(f"Invoice PDF: {len(pdf):,} bytes")
Error Handling and Retry
Only retry the per-minute rate-limit 429 (which carries a Retry-After header), 5xx responses and network errors. The monthly generation-limit 429 has no Retry-After and does not clear until next month, so do not retry it. Retrying a 422 (invalid input) or a 403 (feature not in your plan) will not change the result either.
# pdf_client_production.py
import time
import requests
from pdf_client import FUNBREW_BASE_URL, AUTH_HEADERS
RETRYABLE_STATUS = {500, 502, 503, 504}
def post_with_retry(url: str, payload: dict, max_attempts: int = 3) -> requests.Response:
"""Retry only the per-minute 429 (with Retry-After), 5xx and network errors."""
for attempt in range(1, max_attempts + 1):
try:
response = requests.post(url, headers=AUTH_HEADERS, json=payload, timeout=60)
except (requests.ConnectionError, requests.Timeout):
if attempt == max_attempts:
raise
time.sleep(2 ** (attempt - 1)) # 1s, 2s
continue
last_attempt = attempt == max_attempts
if response.status_code == 429 and "Retry-After" in response.headers and not last_attempt:
time.sleep(int(response.headers["Retry-After"]))
continue
if response.status_code in RETRYABLE_STATUS and not last_attempt:
time.sleep(2 ** (attempt - 1))
continue
# 422, 403, the monthly-limit 429 and the like stop here
response.raise_for_status()
return response
raise RuntimeError("unreachable")
def html_to_pdf_with_retry(html: str, options: dict | None = None) -> bytes:
response = post_with_retry(
f"{FUNBREW_BASE_URL}/api/pdf/generate-from-html",
{"html": html, "options": options or {"page-size": "A4"}},
)
download_url = response.json()["data"]["download_url"]
pdf_response = requests.get(download_url, headers=AUTH_HEADERS, timeout=60)
pdf_response.raise_for_status()
return pdf_response.content
If you resend after a 5xx or a timeout, the server may already have generated the first PDF, so you can end up with two PDFs that both count toward your monthly quota. Keep the retry count small.
2. ReportLab
Installation
pip install reportlab
Basic Usage
# reportlab_basic.py
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import mm
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate, Paragraph, Table, TableStyle, Spacer
from io import BytesIO
def generate_report_pdf(title: str, data: list[list]) -> bytes:
"""Generate a tabular report PDF with ReportLab."""
buffer = BytesIO()
doc = SimpleDocTemplate(
buffer,
pagesize=A4,
topMargin=20 * mm,
bottomMargin=20 * mm,
leftMargin=15 * mm,
rightMargin=15 * mm,
)
styles = getSampleStyleSheet()
elements = []
elements.append(Paragraph(title, styles["Title"]))
elements.append(Spacer(1, 12))
table = Table(data, colWidths=[80 * mm, 40 * mm, 40 * mm])
table.setStyle(TableStyle([
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#2563eb")),
("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
("FONTSIZE", (0, 0), (-1, 0), 11),
("ALIGN", (1, 0), (-1, -1), "RIGHT"),
("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#f1f5f9")]),
("GRID", (0, 0), (-1, -1), 0.5, colors.HexColor("#e2e8f0")),
("TOPPADDING", (0, 0), (-1, -1), 8),
("BOTTOMPADDING", (0, 0), (-1, -1), 8),
]))
elements.append(table)
doc.build(elements)
return buffer.getvalue()
if __name__ == "__main__":
data = [
["Product", "Qty", "Revenue"],
["Product A", "10", "$50,000"],
["Product B", "5", "$30,000"],
["Product C", "20", "$80,000"],
]
pdf = generate_report_pdf("Q1 Sales Report", data)
with open("report_reportlab.pdf", "wb") as f:
f.write(pdf)
print(f"ReportLab PDF: {len(pdf):,} bytes")
ReportLab key points:
- Low-level programmatic API — builds PDFs from primitives (paragraphs, tables, shapes)
- No HTML input; you compose documents with Python objects
- For Japanese text, register a TrueType font (
.ttf/.ttc) withTTFontor use a built-in CID font such asUnicodeCIDFont("HeiseiKakuGo-W5") - Excellent for chart-heavy reports via
reportlab.graphics
Embedding matplotlib Charts
# (elements is the list built inside generate_report_pdf() above)
from reportlab.lib.units import mm
from reportlab.platypus import Image as RLImage
import matplotlib.pyplot as plt
from io import BytesIO
# Generate a chart with matplotlib
fig, ax = plt.subplots(figsize=(5, 3))
ax.bar(["Q1", "Q2", "Q3", "Q4"], [120, 145, 132, 178])
ax.set_title("Quarterly Revenue")
img_buffer = BytesIO()
fig.savefig(img_buffer, format="png", dpi=150, bbox_inches="tight")
img_buffer.seek(0)
plt.close(fig)
# Embed in ReportLab
chart_img = RLImage(img_buffer, width=130 * mm, height=78 * mm)
elements.append(chart_img)
3. WeasyPrint
Installation
# macOS (Homebrew, as recommended by the official docs)
brew install weasyprint
# Debian 11+ (packages needed when installing with pip)
sudo apt install python3-pip libpango-1.0-0 libpangoft2-1.0-0 libharfbuzz-subset0
pip install weasyprint
Basic Usage
# weasyprint_basic.py
from weasyprint import HTML, CSS
from io import BytesIO
def html_to_pdf_weasyprint(html: str, base_url: str | None = None) -> bytes:
"""Convert HTML to PDF with WeasyPrint."""
buffer = BytesIO()
HTML(string=html, base_url=base_url).write_pdf(
buffer,
stylesheets=[CSS(string="@page { size: A4; margin: 20mm 15mm; }")],
)
return buffer.getvalue()
html = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
body { font-family: sans-serif; padding: 20px; }
h1 { color: #2563eb; border-bottom: 2px solid #2563eb; padding-bottom: 8px; }
table { width: 100%; border-collapse: collapse; margin-top: 16px; }
th { background: #dbeafe; padding: 8px; text-align: left; }
td { padding: 8px; border-bottom: 1px solid #e2e8f0; }
</style>
</head>
<body>
<h1>WeasyPrint Demo</h1>
<table>
<thead><tr><th>Property</th><th>Value</th></tr></thead>
<tbody>
<tr><td>Library</td><td>WeasyPrint 62.x</td></tr>
<tr><td>Engine</td><td>Cairo / Pango</td></tr>
<tr><td>JavaScript</td><td>Not supported</td></tr>
</tbody>
</table>
</body>
</html>"""
pdf = html_to_pdf_weasyprint(html)
with open("output_weasyprint.pdf", "wb") as f:
f.write(pdf)
print(f"WeasyPrint PDF: {len(pdf):,} bytes")
WeasyPrint key points:
- Supports CSS Paged Media (
@page, page margin boxes, page counters); Flexbox and Grid work for simple cases - Not a browser engine like WebKit or Gecko, so content drawn by JavaScript does not appear in the PDF
- Depends on Pango and other system libraries, so Docker images need extra packages
- Font rendering depends on the fonts installed on the system
Docker Setup for WeasyPrint
FROM python:3.12-slim-bookworm
RUN apt-get update && apt-get install -y --no-install-recommends \
libpango-1.0-0 \
libpangoft2-1.0-0 \
libharfbuzz-subset0 \
fonts-noto-cjk \
&& rm -rf /var/lib/apt/lists/*
RUN pip install --no-cache-dir weasyprint
This set of packages is for a Debian bookworm base image; fonts-noto-cjk is only needed for Japanese, Chinese or Korean text. We confirmed that WeasyPrint 70.0 renders a Japanese PDF with it.
4. xhtml2pdf
Installation
pip install xhtml2pdf
Basic Usage
# xhtml2pdf_basic.py
from io import BytesIO
from xhtml2pdf import pisa
def html_to_pdf_xhtml2pdf(html: str) -> bytes:
"""Convert HTML to PDF with xhtml2pdf."""
buffer = BytesIO()
result = pisa.CreatePDF(html, dest=buffer)
if result.err:
raise RuntimeError(f"xhtml2pdf conversion error: {result.err}")
return buffer.getvalue()
html = """<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
@page { size: A4; margin: 20mm; }
/* For Japanese or other non-Latin text, declare a TTF/OTF font with @font-face */
body { font-family: Helvetica, sans-serif; font-size: 12px; }
h1 { color: #2563eb; }
</style>
</head>
<body>
<h1>xhtml2pdf Sample</h1>
<p>Simple PDF generation without external binaries.</p>
</body>
</html>"""
pdf = html_to_pdf_xhtml2pdf(html)
with open("output_xhtml2pdf.pdf", "wb") as f:
f.write(pdf)
print(f"xhtml2pdf PDF: {len(pdf):,} bytes")
xhtml2pdf key points:
- Pure Python on top of ReportLab — no browser or external binary
- Version 0.2.28 supports Flexbox and custom properties (
var()); CSS Grid is not in its feature list - Works well for simple documents, but output will not always match a browser, so check it
- For non-Latin scripts, declare a TrueType/OpenType font with
@font-face
5. pdfkit (wkhtmltopdf)
Installation
# Install the wkhtmltopdf binary first
# macOS: brew install wkhtmltopdf
# Ubuntu: sudo apt-get install wkhtmltopdf
pip install pdfkit
Basic Usage
# pdfkit_basic.py
import pdfkit
options = {
"page-size": "A4",
"margin-top": "20mm",
"margin-bottom": "20mm",
"margin-left": "15mm",
"margin-right": "15mm",
"encoding": "UTF-8",
"enable-local-file-access": "",
}
html = """<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>body { font-family: sans-serif; padding: 40px; }</style>
</head>
<body>
<h1 style="color:#2563eb">pdfkit Sample</h1>
<p>Uses wkhtmltopdf under the hood.</p>
</body>
</html>"""
# Save to file
pdfkit.from_string(html, "output_pdfkit.pdf", options=options)
# Get as bytes
pdf_bytes = pdfkit.from_string(html, False, options=options)
print(f"pdfkit PDF: {len(pdf_bytes):,} bytes")
# From URL
# pdfkit.from_url("https://example.com", "output_url.pdf")
pdfkit key points:
- Requires the wkhtmltopdf binary to be installed on the server
- Renders with an old QtWebKit; the wkhtmltopdf GitHub repository was archived in January 2023 and is no longer updated
- Best used when you already have a wkhtmltopdf-based workflow to maintain
- For new projects, prefer WeasyPrint or a PDF API
6. Playwright for Python
Installation
pip install playwright
playwright install chromium
Basic Usage
# playwright_basic.py
import asyncio
from playwright.async_api import async_playwright
async def html_to_pdf_playwright(html: str) -> bytes:
"""Convert HTML to PDF with Playwright (async)."""
async with async_playwright() as p:
browser = await p.chromium.launch()
page = await browser.new_page()
await page.set_content(html, wait_until="networkidle")
pdf_bytes = await page.pdf(
format="A4",
margin={"top": "20mm", "bottom": "20mm", "left": "15mm", "right": "15mm"},
print_background=True,
)
await browser.close()
return pdf_bytes
async def main():
html = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
body { font-family: -apple-system, sans-serif; padding: 40px; }
h1 { color: #2563eb; }
.chart-placeholder {
width: 400px; height: 200px; background: #dbeafe;
display: flex; align-items: center; justify-content: center;
border-radius: 8px; color: #1e40af;
}
</style>
</head>
<body>
<h1>Playwright PDF Demo</h1>
<p>Captures JavaScript-rendered content into PDF.</p>
<div class="chart-placeholder">Chart area (JS rendered)</div>
</body>
</html>"""
pdf = await html_to_pdf_playwright(html)
with open("output_playwright.pdf", "wb") as f:
f.write(pdf)
print(f"Playwright PDF: {len(pdf):,} bytes")
asyncio.run(main())
Playwright key points:
- Renders with the Chromium that Playwright downloads, including JavaScript output
playwright install chromiumdownloads the browser (the official docs say browsers take "a few hundred megabytes")- Best when you already use Playwright for browser automation or E2E testing
- For production PDF generation, migrating to FUNBREW PDF API removes the Chromium dependency from your server
Use Case Guide: Which Library to Choose
Invoices and Certificates (Complex HTML Layout)
Recommendation: FUNBREW PDF API
# Reuse your existing HTML and CSS (quality needs the Pro plan or above)
pdf = html_to_pdf(invoice_html, engine="quality")
If you have an existing HTML/CSS template, two HTTP calls (generate, then download) turn it into a PDF. See the Django, FastAPI & Flask PDF integration guide for framework-specific patterns.
Data Analysis Reports (Charts and Tables)
Recommendation: ReportLab
ReportLab works directly with matplotlib charts, making it ideal for automated data pipelines.
Batch Generation (Hundreds to Thousands of PDFs)
Recommendation: FUNBREW PDF API + async concurrency
# batch_pdf.py
import asyncio
import aiohttp
from pdf_client import FUNBREW_BASE_URL, AUTH_HEADERS
from invoice_generator import build_invoice_html
async def request_json_or_bytes(session: aiohttp.ClientSession, method: str, url: str, **kwargs):
"""Wait Retry-After seconds on the per-minute 429 (up to 3 tries). POST returns JSON, GET returns bytes."""
for attempt in range(3):
async with session.request(method, url, headers=AUTH_HEADERS, **kwargs) as resp:
if resp.status == 429 and "Retry-After" in resp.headers and attempt < 2:
wait_seconds = int(resp.headers["Retry-After"])
else:
resp.raise_for_status()
return await (resp.json() if method == "POST" else resp.read())
await asyncio.sleep(wait_seconds)
async def html_to_pdf_async(
session: aiohttp.ClientSession,
html: str,
semaphore: asyncio.Semaphore,
) -> bytes:
async with semaphore:
result = await request_json_or_bytes(
session,
"POST",
f"{FUNBREW_BASE_URL}/api/pdf/generate-from-html",
json={"html": html, "options": {"page-size": "A4"}},
)
return await request_json_or_bytes(session, "GET", result["data"]["download_url"])
async def generate_pdfs_batch(html_list: list[str], concurrency: int = 5) -> list[bytes]:
"""Convert many HTML documents to PDF concurrently."""
semaphore = asyncio.Semaphore(concurrency) # cap at 5 simultaneous requests
timeout = aiohttp.ClientTimeout(total=120)
async with aiohttp.ClientSession(timeout=timeout) as session:
tasks = [html_to_pdf_async(session, html, semaphore) for html in html_list]
results = await asyncio.gather(*tasks, return_exceptions=True)
pdfs = []
for i, result in enumerate(results):
if isinstance(result, Exception):
print(f"[Warning] PDF {i} failed: {result}")
else:
pdfs.append(result)
return pdfs
async def main():
html_list = [
build_invoice_html(f"Customer {i:03d}", 10_000 + i * 500)
for i in range(1, 11)
]
pdfs = await generate_pdfs_batch(html_list, concurrency=5)
print(f"Generated {len(pdfs)} PDFs")
if __name__ == "__main__":
asyncio.run(main())
More concurrency is not automatically faster. The per-minute request limit applies per company (shared by all its API keys) and depends on the plan (Free 10, Pro 120, Business 300), and both the generate call and the download call count. You also cannot go past the monthly generation quota (30 PDFs on Free, for example). On every plan, including Free, you can also send many items in one request with /api/pdf/batch.
For more batch processing patterns, see the PDF batch processing guide.
FastAPI Integration
# FastAPI endpoint
import requests
from fastapi import FastAPI, HTTPException
from fastapi.responses import Response
from pydantic import BaseModel
from pdf_client import html_to_pdf
from invoice_generator import build_invoice_html
app = FastAPI()
class InvoiceRequest(BaseModel):
customer_name: str
amount: int
items: list[dict] | None = None
# requests is synchronous, so use def (FastAPI runs it in a threadpool) rather than async def
@app.post("/invoices/pdf")
def create_invoice_pdf(req: InvoiceRequest):
html = build_invoice_html(req.customer_name, req.amount, req.items)
try:
pdf_bytes = html_to_pdf(html, page_size="A4")
except requests.RequestException as e:
raise HTTPException(status_code=502, detail="PDF generation failed") from e
return Response(
content=pdf_bytes,
media_type="application/pdf",
headers={"Content-Disposition": 'attachment; filename="invoice.pdf"'},
)
For full Django, Flask, and FastAPI integration, see the Django, FastAPI & Flask PDF guide.
Library Comparison: CSS Support
The FUNBREW PDF API column is for the quality (Chromium) engine. The fast engine is wkhtmltopdf, the same engine pdfkit uses.
| CSS Feature | FUNBREW PDF API (quality) | WeasyPrint | xhtml2pdf (0.2.28) | pdfkit |
|---|---|---|---|---|
| Flexbox | Yes | Partial (simple cases) | Yes | Check |
| CSS Grid | Yes | Partial (simple cases) | Not listed | Check |
| CSS variables | Yes | Yes | Yes | Check |
@page rule |
Yes | Yes | Yes (size and margins) | Check |
@font-face |
Yes | Yes | Yes | Check |
print-color-adjust |
Yes (also write the -webkit- prefixed form) |
Not listed | Not listed | Check |
wkhtmltopdf (pdfkit) renders with an old QtWebKit, so check the actual output for each CSS feature you rely on. For every library, treat the table as a guide based on the official documentation.
Dependency Comparison
# FUNBREW PDF API
pip install requests
# WeasyPrint (also needs system libraries such as Pango and HarfBuzz, plus fonts for your scripts)
pip install weasyprint
# pdfkit (also needs the wkhtmltopdf binary)
pip install pdfkit
# Playwright (downloads a browser; the official docs say browsers take "a few hundred megabytes")
pip install playwright
playwright install chromium
Frequently Asked Questions
What is the easiest way to generate PDFs in Python?
The FUNBREW PDF API. Just pip install requests, POST your HTML, and download the PDF from the download_url in the JSON response. No binaries to install and no system libraries to configure, so it works in Docker and serverless environments as-is.
How do I handle Japanese text in Python PDF libraries?
With the FUNBREW PDF API, add <meta charset="UTF-8"> to your HTML and set a Japanese font in CSS. The quality (Chromium) engine environment includes the Noto CJK fonts, so you can use font-family: 'Noto Sans CJK JP', sans-serif;. Fonts can look different on the fast engine, so check the generated PDF. For WeasyPrint, you need a Japanese font installed on the system. For ReportLab, register a TrueType font with TTFont or use a built-in CID font such as UnicodeCIDFont("HeiseiKakuGo-W5"). See the Japanese font guide for details.
Should I use WeasyPrint or pdfkit for a new project?
Choose WeasyPrint. pdfkit depends on wkhtmltopdf, whose GitHub repository was archived in January 2023 and which renders with an old QtWebKit. WeasyPrint is still released (version 70.0 in September 2026) and supports CSS Paged Media. If you need browser (Chromium) rendering, the FUNBREW PDF API's quality engine (Pro plan and above) is another option.
Can I generate PDFs in a Django view?
Yes. Call html_to_pdf() in your view and return a HttpResponse with content_type="application/pdf". See the Django, FastAPI & Flask PDF guide for complete view examples including async Celery patterns.
How do I add page numbers in Python PDF generation?
The FUNBREW PDF API has no header/footer option at generation time. Add page numbers to a generated PDF with the separate /api/pdf/page-numbers endpoint. With WeasyPrint you can use CSS page margin boxes such as @page { @bottom-center { content: counter(page) "/" counter(pages); } }; Chromium supports page margin boxes from version 131. The HTML to PDF CSS tips guide has more examples.
How does Playwright compare to using the API in production?
Playwright downloads a full Chromium build (browsers take "a few hundred megabytes" according to its docs) and runs it as a separate process. This adds memory usage, cold-start latency, and operational complexity. The FUNBREW PDF API offloads the Chromium process to a managed service, so your application stays lightweight. Playwright is great for local development and E2E test workflows.
Summary
| Use Case | Recommended Approach | Reason |
|---|---|---|
| Invoices, certificates, complex HTML | FUNBREW PDF API | Chromium rendering (quality), no browser on your server |
| Data analysis reports with charts | ReportLab | matplotlib integration, programmatic control |
| Archiving existing HTML pages | WeasyPrint | CSS Paged Media, still released |
| Simple internal documents (no binary) | xhtml2pdf | Zero external dependencies |
| Combined with E2E test automation | Playwright | Reuse existing browser automation |
| High-volume batch generation / SaaS | FUNBREW PDF API | No rendering servers to run (within your plan's monthly and per-minute limits) |
Start by testing your templates in the Playground, then check the API docs for the full request reference.
Related
- PDF API Quickstart by Language — Basic API calls in Python, Node.js, PHP
- Django, FastAPI & Flask PDF Integration Guide — Framework-specific implementation patterns
- Generate PDFs with Node.js — Sister article for Node.js developers
- PDF Batch Processing Guide — Generate hundreds of PDFs efficiently
- HTML to PDF CSS Tips: @page, Page Breaks & Print Snippets — CSS best practices for PDF output
- HTML to PDF Troubleshooting — Diagnosing layout issues, timeouts, and encoding errors
- Japanese Font Guide — CJK font setup for all approaches
- PDF API vs Library Comparison — Detailed API vs OSS breakdown
- PDF API Production Checklist — Reliability, monitoring, and scaling
- Puppeteer Migration Guide — Moving from Playwright/Puppeteer to API
- API Reference — Full endpoint documentation