Guides / Generate PDFs in Python

Frameworks · Updated 2026-12-03

Generate PDFs in Python

This guide renders PDFs from Python with one HTTP call. You send a template id and a dictionary of data, and you get back a link or the file itself. There is nothing to install besides requests: no wkhtmltopdf binary, no Chrome, no system fonts.

The free plan includes 500 documents a month.

#1. Set up

Sign up, open API keys in the dashboard and create a key. Then:

pip install requests
export DEVILPDF_API_KEY="dp_live_..."

Keep the key in an environment variable or your secrets manager. Never commit it.

#2. Render an invoice

Every account has seven starter templates: invoice, quote, receipt, statement, report, packing-slip and certificate.

render.py
import os
import requests

res = requests.post(
    "https://devilpdf.com/v1/render",
    headers={"Authorization": f"Bearer {os.environ['DEVILPDF_API_KEY']}"},
    json={
        "template": "invoice",
        "data": {
            "number": "INV-1001",
            "issue_date": "2026-12-03",
            "due_date": "2027-01-02",
            "company": {"name": "Northwind Studio", "address": "410 Bay Street\nToronto, ON M5H 2Y4"},
            "customer": {"name": "Acme Robotics Inc.", "address": "2200 Mission Street\nSan Francisco, CA 94110"},
            "items": [
                {"name": "Brand identity system", "quantity": 1, "unit_price": 4800},
                {"name": "Front-end development", "description": "Billed hourly", "quantity": 46, "unit_price": 135},
            ],
            "tax_rate": 13,
            "tax_label": "HST",
        },
        "filename": "INV-1001",
    },
    timeout=60,
)
doc = res.json()
if not res.ok:
    raise RuntimeError(f"{doc['error']['type']}: {doc['error']['message']}")
print(doc["url"], doc["pages"])

requests sets the Content-Type: application/json header for you when you pass json=. The response is a document object: id, pages, and url, a signed download link. The invoice template computes the subtotal, tax and total from items, so you only send line items.

To see every field a starter accepts, fetch GET /v1/templates/invoice and read sample_data.

#3. Get the bytes and save them

Add "output": "file" and the response body is the PDF. DevilPDF keeps no copy.

save.py
import os
import requests

API = "https://devilpdf.com/v1/render"
HEADERS = {"Authorization": f"Bearer {os.environ['DEVILPDF_API_KEY']}"}


def render_pdf(body: dict) -> bytes:
    res = requests.post(API, headers=HEADERS, json={**body, "output": "file"}, timeout=60)
    if not res.ok:
        error = res.json()["error"]
        raise RuntimeError(f"{error['type']}: {error['message']}")
    return res.content


pdf = render_pdf({
    "template": "certificate",
    "data": {
        "title": "Certificate of Completion",
        "recipient": {"name": "Amara Okonkwo"},
        "description": "has completed the 12-week Applied Data Engineering programme.",
        "issued_on": "2026-12-03",
        "issuer": {"name": "Ledger School of Technology"},
    },
})

with open("certificate.pdf", "wb") as f:
    f.write(pdf)
print(f"Saved certificate.pdf ({len(pdf)} bytes)")

Errors always come back as JSON with an error object, so check res.ok before treating the body as a file.

#Flask

Return the PDF from a route. The key never reaches the browser.

app.py
import io
import os

import requests
from flask import Flask, abort, send_file

app = Flask(__name__)


@app.get("/invoices/<number>.pdf")
def invoice_pdf(number):
    order = load_order(number)
    if order is None:
        abort(404)
    res = requests.post(
        "https://devilpdf.com/v1/render",
        headers={"Authorization": f"Bearer {os.environ['DEVILPDF_API_KEY']}"},
        json={"template": "invoice", "data": order, "output": "file"},
        timeout=60,
    )
    if not res.ok:
        abort(502, res.json()["error"]["message"])
    return send_file(
        io.BytesIO(res.content),
        mimetype="application/pdf",
        download_name=f"invoice-{number}.pdf",
    )


def load_order(number):
    # Replace with your database lookup.
    return {"number": number, "items": [{"name": "Consulting", "quantity": 3, "unit_price": 150}]}

#Django

Same request, returned as an HttpResponse. Put render_pdf from step 3 in a module such as billing/pdf.py.

views.py
from django.http import HttpResponse
from django.shortcuts import get_object_or_404

from .models import Invoice
from .pdf import render_pdf


def invoice_pdf(request, number):
    invoice = get_object_or_404(Invoice, number=number)
    pdf = render_pdf({
        "template": "invoice",
        "data": {
            "number": invoice.number,
            "customer": {"name": invoice.customer_name},
            "items": [
                {"name": line.name, "quantity": line.quantity, "unit_price": float(line.unit_price)}
                for line in invoice.lines.all()
            ],
        },
    })
    response = HttpResponse(pdf, content_type="application/pdf")
    response["Content-Disposition"] = f'inline; filename="invoice-{invoice.number}.pdf"'
    return response

Convert Decimal fields with float() or str() before sending, because json cannot serialize Decimal. A number sent as text still works in the template's calculations.

A render normally takes well under a second, so calling it inside a request is fine. If you generate PDFs in bulk, run them from a task queue such as Celery, or hand the whole set to POST /v1/render/batch and receive a webhook when it is done. See async and batch.

#Other languages

Add locale to the request. The starter's labels, dates and money follow, and right-to-left languages mirror the layout.

pdf = render_pdf({
    "template": "invoice",
    "locale": "ar",
    "data": {
        "number": "INV-1002",
        "currency": "SAR",
        "customer": {"name": "شركة الأفق للتجارة"},
        "items": [{"name": "استشارات", "quantity": 3, "unit_price": 1250}],
    },
})

#Next steps