Guides / Invoice PDF in Python

Generate PDF invoices in Python

Turn a Python dict into an itemized invoice PDF with one HTTP request. No ReportLab layout code, no headless Chrome on your server.

What you need

  • Python 3.8+ and pip install requests
  • A free SlipKiln API key (50 documents a month, no card). Put it in SLIPKILN_KEY.

1. Send the invoice data

The built-in invoice template takes your line items and computes subtotal, tax and total for you. The response body is the PDF.

import os
import requests

API = "https://api.slipkiln.com/v1/render/template"
KEY = os.environ["SLIPKILN_KEY"]  # keep keys server-side

invoice = {
    "number": "INV-1042",
    "issue_date": "2026-11-20",
    "due_date": "2026-12-20",
    "currency": "USD",
    "customer": {"name": "Acme Co.", "email": "ap@acme.example",
                 "address": ["100 Main St", "Denver, CO 80202"]},
    "items": [
        {"description": "Consulting", "qty": 10, "unit_price": 120},
        {"description": "Hosting (November)", "qty": 1, "unit_price": 49},
    ],
    "tax_rate": 8.25,
    "notes": "Thank you for your business. Net 30.",
}

r = requests.post(
    API,
    headers={"Authorization": f"Bearer {KEY}"},
    json={"template": "invoice", "data": invoice},
    timeout=30,
)
if r.status_code != 200:
    raise RuntimeError(r.json().get("message", r.text))
with open("INV-1042.pdf", "wb") as f:
    f.write(r.content)
print("documents this month:", r.headers.get("x-usage-month"))

Fields: number, issue_date and due_date are printed as given. currency is an ISO 4217 code (default USD). items takes up to 500 rows of {description, qty, unit_price}. tax_rate is a percent. Full reference in the docs.

2. Add your logo and colors

Every template accepts a brand object. Logos must be inlined as base64 data: URIs, because the renderer has no network access.

import base64

with open("logo.png", "rb") as f:
    logo = "data:image/png;base64," + base64.b64encode(f.read()).decode()

invoice["brand"] = {
    "name": "Northwind Studio",
    "logo": logo,             # data: URI only; remote URLs are blocked
    "color": "#0f766e",       # accent color
    "email": "billing@northwind.example",
    "website": "northwind.example",
    "address": ["12 Market St", "Boulder, CO 80302"],
}

3. Handle limits and retries

The API allows 60 requests a minute per key. On 429 or 503, wait and retry. Other errors return JSON like {"error":"invalid_request","message":"…"} and should not be retried. Failed renders don't count toward your quota.

import time

def render(payload, attempts=4):
    for i in range(attempts):
        r = requests.post(API, headers={"Authorization": f"Bearer {KEY}"},
                          json=payload, timeout=30)
        if r.status_code == 200:
            return r.content
        if r.status_code in (429, 503):           # rate limited / busy
            wait = float(r.headers.get("retry-after", 2 ** i))
            time.sleep(wait)
            continue
        raise RuntimeError(f"{r.status_code}: {r.json().get('message')}")
    raise RuntimeError("gave up after retries")

4. Serve it from a web app

# views.py (Django). Flask/FastAPI look the same: return the bytes with a PDF content type.
from django.http import HttpResponse

def invoice_pdf(request, number):
    data = build_invoice_dict(number)   # your own lookup
    pdf = render({"template": "invoice", "data": data})
    resp = HttpResponse(pdf, content_type="application/pdf")
    resp["Content-Disposition"] = f'attachment; filename="{number}.pdf"'
    return resp

Need your own layout?

Render any HTML instead. Build it with Jinja2 (or any template engine) and post it to /v1/render/html. Inline your CSS, fonts and images as data: URIs.

from jinja2 import Template

html = Template(open("invoice.html").read()).render(invoice=invoice)
r = requests.post("https://api.slipkiln.com/v1/render/html",
                  headers={"Authorization": f"Bearer {KEY}"},
                  json={"html": html, "options": {"format": "Letter",
                        "margin": {"top": "15mm", "bottom": "15mm"}}},
                  timeout=30)

Why not ReportLab, WeasyPrint or pdfkit?

They work, and for some teams they're the right call. ReportLab means positioning text in code. WeasyPrint and wkhtmltopdf (behind pdfkit) each support a different subset of modern CSS, and wkhtmltopdf is no longer maintained. Running Chromium yourself gives the best CSS support but adds memory, fonts and sandboxing to your ops list (see what breaks with self-hosted Chrome). An API trades a per-document cost for none of that: free up to 50 a month, then $9 for 1,000.

Related

Updated November 2026.