PDFCraft
Django

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 response

What to watch for

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

Or by language