How to generate a PDF from HTML in Python
Published 2 min read
In Python, turning HTML into a PDF often means installing a rendering library and its system
dependencies, then keeping them working in every environment. With an API it is one HTTP
request, which requests already does well. This guide shows a small function, then how to
use it in Django and FastAPI, with the rustedf.cloud API.
A function that returns the PDF
import osimport requests
API = "https://api.rustedf.com/v1/render"
def render_pdf(template_id: str, data: dict, locale: str = "en-US") -> bytes: response = requests.post( API, headers={"Authorization": f"Bearer {os.environ['RUSTEDF_KEY']}"}, json={"template_id": template_id, "locale": locale, "data": data}, timeout=40, ) if response.status_code != 200: error = response.json().get("error", {}) raise RuntimeError(error.get("message", f"Render failed ({response.status_code})")) return response.contentjson= sets the Content-Type header for you. A successful response is the PDF itself, so
response.content is the bytes of the file. On a failure the body is JSON with a stable
code and a message.
Keep the key in an environment variable. Set the timeout above the time limit of your plan, so your request does not give up before the service does.
To send the HTML instead of a saved template id, use {"html": "<h1>{{ name }}</h1>", "data": {...}}.
Pass anything a user typed through data, never inside the HTML string: values in data are
escaped, and the HTML itself is read as a template.
Retry when the service is busy
A 429 (rate limit) or a 503 (busy) carries a Retry-After header. A short loop is enough:
import time
def render_pdf_with_retry(template_id, data, locale="en-US", attempts=3): for attempt in range(attempts): response = requests.post( API, headers={"Authorization": f"Bearer {os.environ['RUSTEDF_KEY']}"}, json={"template_id": template_id, "locale": locale, "data": data}, timeout=40, ) if response.status_code in (429, 503) and attempt < attempts - 1: try: wait = int(response.headers.get("Retry-After", "2")) except ValueError: wait = 2 time.sleep(wait) continue break if response.status_code != 200: error = response.json().get("error", {}) raise RuntimeError(error.get("message", f"Render failed ({response.status_code})")) return response.contentA failed render costs no credit, so retrying is safe.
In Django
from django.conf import settingsfrom django.http import HttpResponse
def invoice_pdf(request, number): pdf = render_pdf(settings.RUSTEDF_INVOICE_TEMPLATE, build_invoice_data(number), "pt-BR") return HttpResponse( pdf, content_type="application/pdf", headers={"Content-Disposition": f'inline; filename="invoice-{number}.pdf"'}, )In FastAPI
from fastapi import FastAPIfrom fastapi.responses import Response
app = FastAPI()
@app.get("/invoices/{number}.pdf")def invoice_pdf(number: str): pdf = render_pdf(INVOICE_TEMPLATE, build_invoice_data(number), "en-US") return Response(content=pdf, media_type="application/pdf")The function is a plain def, so FastAPI runs it in a worker thread and the blocking call does
not stall the event loop.
Errors worth handling
| Status | code |
What to do |
|---|---|---|
| 401 | unauthorized |
The key is missing, wrong or revoked. |
| 402 | insufficient_credits |
No credits left. Nothing was rendered. |
| 422 | invalid_template |
The template or its data failed. Read message. |
| 429 | rate_limited |
Wait for Retry-After and retry. |
| 503 | busy |
The service is busy. Wait for Retry-After and retry. |
| 504 | render_timeout |
The document took longer than your plan allows. |
Before you rely on a template, run POST /v1/validate with the same body: it lists anything the
service did not fully support, without returning the PDF or using a credit.
Read Rendering a PDF, Authentication and Errors and limits.
Keep reading
Code and integrations
Generate a PDF in ASP.NET Core: MVC, Razor Pages and minimal APIs
Turn a Razor view into a PDF in ASP.NET Core with one API call: a view renderer, a print-ready view, an MVC action, a Razor Pages handler and the traps to avoid.
3 min read
Code and integrations
Convert a web page to PDF in C# without a headless browser
Fetch a page with HttpClient and turn its HTML into a PDF with one API call in C#. Which pages this suits, which it does not, and how to check before you rely on it.
3 min read
Code and integrations
C# PDF report generator: a paged table with totals and page numbers
Build a PDF report in C# from a list of objects: a table whose header repeats on every page, a total, page numbers and the page count, with one HTTP call.
3 min read
Code and integrations
Save a PDF in C#: to disk, as a download or in blob storage
Save the PDF returned by a render call in C#: write it to disk, send it as a download from ASP.NET Core, keep a signed link or upload it, and avoid saving an error.
2 min read