PDF generation in Django
You already have the template and the context. `render_to_string` turns the page you serve into the page you print, which is the whole point — one template, two outputs.
The code
# views.py
import os
import requests
from django.http import HttpResponse
from django.template.loader import render_to_string
def invoice_pdf(request, invoice_id):
invoice = Invoice.objects.get(pk=invoice_id)
html = render_to_string("invoices/detail.html", {"invoice": invoice}, request=request)
upstream = requests.post(
"https://api.pdfcraft.dev/v1/render",
headers={"Authorization": f"Bearer {os.environ['PDFCRAFT_API_KEY']}"},
json={
"html": html,
"options": {
"printBackground": True,
"margin": {"top": "20mm", "bottom": "20mm"},
},
},
timeout=60,
)
upstream.raise_for_status()
response = HttpResponse(upstream.content, content_type="application/pdf")
response["Content-Disposition"] = f'attachment; filename="invoice-{invoice_id}.pdf"'
return responseWhat to watch for
- `render_to_string` produces a fragment with relative URLs. Any `<img src="/static/…">` will not resolve — make static URLs absolute, or inline the images as data URIs.
- `upstream.content`, never `.text`. `.text` decodes the bytes as a string and silently destroys the PDF.
- For anything slower than a second, do this in Celery and hand the user a signed URL from `output: "url"` rather than holding a Gunicorn worker open.
Why not run the browser yourself
You can. Puppeteer and Playwright both work, and for a script you run by hand they are the right answer. The cost arrives at the point it becomes a service someone depends on: one long-lived browser per process rather than one per request, a semaphore so four renders do not become forty, a hard timeout that force-closes a hung page before it holds a slot forever, a scheduled restart because Chromium leaks, and a Chromium version you are now responsible for patching.
None of that is hard. All of it is work that has nothing to do with your product, and it fails under concurrency rather than in testing — which is the worst time to discover it.
Other frameworks
- PDF generation in Next.js
- PDF generation in Ruby on Rails
- PDF generation in Laravel
- PDF generation in AWS Lambda
- PDF generation in Cloudflare Workers
- PDF generation in Supabase Edge Functions
- PDF generation in Spring Boot
- PDF generation in FastAPI
- PDF generation in Express
- PDF generation in ASP.NET Core
- PDF generation in n8n