Convert Django Views to PDF at the Edge
Offload PDF generation from your Django app to a low-latency Worker that speaks Stripe meters. Your templates render exactly once, the PDF streams back in seconds, and you stop managing headless Chrome boxes.
Launch Django PDFs in three steps
- Render the template server-side as HTML. Use `render_to_string` to hydrate your invoice or proposal with context before calling the API.
- POST the HTML payload to the Worker endpoint. The Worker validates the API key, rate limits by plan, launches the Cloudflare browser, and returns a binary PDF.
- Store or return the PDF with Django responses. Save the binary to S3/R2 or return an `HttpResponse` with `application/pdf` headers for inline viewing.
Django integration code
Drop this snippet into your project, replace `PDF_API_KEY`, and generate your first PDF. Pair it with the curl request for quick smoke tests.
import requests
from django.http import HttpResponse
from django.template.loader import render_to_string
PDF_API_URL = "https://api.yourdomain.com/v1/render"
PDF_API_KEY = settings.PDF_API_KEY
def invoice_pdf(request, invoice_id):
invoice = get_object_or_404(Invoice, pk=invoice_id)
html = render_to_string("billing/invoice.html", {"invoice": invoice})
res = requests.post(
PDF_API_URL,
headers={
"Authorization": f"Bearer {PDF_API_KEY}",
"Content-Type": "application/json",
},
json={"html": html, "options": {"format": "Letter"}},
timeout=30,
)
res.raise_for_status()
return HttpResponse(
res.content,
content_type="application/pdf",
headers={"Content-Disposition": f"attachment; filename=invoice-{invoice_id}.pdf"},
)
Test with curl
curl -X POST https://api.yourdomain.com/v1/render \
-H "authorization: Bearer ${PDF_API_KEY}" \
-H "content-type: application/json" \
-d '{"html":"Proposal
Generated from Django.
"}' \
--output proposal.pdf
Common pitfalls & fixes
- Avoid sending user-generated HTML without sanitising to prevent script injection.
- Set a timeout on the `requests.post` call so bad URLs do not hang your worker thread.
- Cache heavy templates so your Django view stays responsive even if the PDF API is slow.
FAQ
Can I generate PDFs from authenticated views?
Yes. Render the HTML with Django before calling the Worker. You never expose internal URLs publicly.
Do I need to manage overage billing?
No. Every render emits a Stripe meter event. Configure overage pricing once in Stripe and billing stays automatic.