FrameForge › Guides › HTML to PDF in Django

HTML to PDF in Django

Send HTML (or a URL) to the FrameForge API and get a PDF back. It is rendered in real Chromium, so modern CSS, web fonts and JavaScript all work. No browser to install or babysit.

The code

Django view with requests. Set FRAMEFORGE_KEY to your API key.

import requests
from django.conf import settings
from django.http import HttpResponse
from django.template.loader import render_to_string

def invoice_pdf(request, pk):
    html = render_to_string("invoices/pdf.html", {"invoice_id": pk})
    r = requests.post(
        "https://api.frameforgeapi.com/render",
        headers={"X-API-Key": settings.FRAMEFORGE_KEY},
        json={"html": html, "format": "pdf", "width": 794, "height": 1123},
        timeout=60,
    )
    r.raise_for_status()
    resp = HttpResponse(r.content, content_type="application/pdf")
    resp["Content-Disposition"] = f'inline; filename="invoice-{pk}.pdf"'
    return resp

How it works

Rendering a URL instead of HTML

{"url": "https://example.com/report", "format": "pdf", "width": 1280, "height": 800, "fullPage": true}

Doing it yourself instead

WeasyPrint (with django-weasyprint) is a popular in-process choice for print-style documents. It needs system libraries such as Pango and does not run JavaScript.

An API makes sense when you don't want Chromium on your servers, or when you need images (PNG/JPEG) and PDFs from the same call. If you render a few PDFs a month on a server you already run, self-hosting is perfectly reasonable.

Free tool: Website to PDF. Other languages: Node.js · Python · PHP · Ruby · Go · Java · C# / .NET · curl / Bash · Next.js · Laravel · Ruby on Rails