HTML to PDF in Python
Generate a PDF from HTML in Python with one requests call. No browser and no wkhtmltopdf to install.
Last updated
POST the HTML to /v1/render with requests and write resp.content
to a file. The render runs on the server, so requests is the only package
you need:
import os
import requests
key = os.environ.get("PDFRENDER_KEY") # optional
resp = requests.post(
"https://api.pdfrender.dev/v1/render",
json={"html": "<h1>Report</h1><p>Generated in Python.</p>", "filename": "report.pdf"},
headers={"X-API-Key": key} if key else {},
timeout=30,
)
if resp.status_code != 200:
problem = resp.json()
raise RuntimeError(f"{resp.status_code} {problem['code']}: {problem['detail']}")
with open("report.pdf", "wb") as f:
f.write(resp.content)
Errors come back as application/problem+json. Branch on the code member
(all codes). With httpx, the same call
works in httpx.Client and httpx.AsyncClient.
Fill a template with Jinja2
Render your template to a string, then send that string as html:
from jinja2 import Template
html = Template(open("invoice.html").read()).render(number="2026-001", total="240.00 EUR")
Page size, headers and page numbers belong in the template's CSS (headers and footers).
Next step
FAQ
- How do I convert HTML to PDF in Python without wkhtmltopdf?
- POST the HTML to /v1/render with requests or httpx and write the response bytes to a file. The render runs on the server, so there is no binary to install.
- Is there a Python SDK?
- No. The API is one JSON endpoint, so requests or httpx is the whole integration.