rustedf.cloud
Menu

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 os
import 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.content

json= 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.content

A failed render costs no credit, so retrying is safe.

In Django

from django.conf import settings
from 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 FastAPI
from 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.

← All posts