PDFPipe

FastAPI / invoices

Invoice PDFs in FastAPI

Post your invoice HTML to a render API from an async endpoint returning StreamingResponse, then return StreamingResponse over the httpx byte iterator. No browser binary in your FastAPI deployment.

Why invoices become PDFs

An invoice is a legal record of a demand for payment, and in most jurisdictions it has to be retained in a form that cannot change after issue. A page that re-renders from live data is not that. That is the difference between a document and a view of a database, and it is why finance teams and anyone billing customers keep asking for this.

What a invoice has to carry

Before any of the code below matters, the template has to produce a document that is actually a invoice. These are the fields that make it one, and the ones a reader or an auditor will look for first.

  • an invoice number that is sequential and never reused
  • the issue date, and separately the payment due date
  • supplier and customer legal names with addresses, not trading names
  • tax registration numbers for both parties where the jurisdiction requires them
  • per-line quantity, unit price, tax rate and line total
  • the tax subtotal broken out by rate, then the gross total

Turning your Jinja2Templates template into a document

You already have the markup. Templates.get_template("invoice.html").render(context) gives you it as a string, which is the only input the render needs. TemplateResponse is for returning HTML to a browser. When the HTML is going to a renderer you want the string, so call the underlying Jinja template directly rather than unwrapping a Response you never send.

The FastAPI implementation

httpx is the client most projects here already have. The render happens in an async endpoint returning StreamingResponse, and you return StreamingResponse over the httpx byte iterator.

python
# routers/invoices.py
import httpx
from fastapi import APIRouter, Depends
from fastapi.responses import StreamingResponse
from fastapi.templating import Jinja2Templates

router = APIRouter()
templates = Jinja2Templates(directory="templates")


@router.get("/invoices/{invoice_id}.pdf")
async def invoice_pdf(invoice_id: int, db=Depends(get_db)):
    invoice = await db.get_invoice(invoice_id)

    # The template directly, not TemplateResponse: we want the string, and
    # TemplateResponse is for HTML you are actually sending to a browser.
    html = templates.get_template("invoice.html").render(invoice=invoice)

    client = httpx.AsyncClient(timeout=60.0)
    request = client.build_request(
        "POST",
        "https://api.pdfpipe.xyz/v1/pdf",
        headers={"Authorization": f"Bearer {settings.pdfpipe_key}"},
        json={"html": html, "options": {"format": "A4", "printBackground": True}},
    )
    upstream = await client.send(request, stream=True)
    upstream.raise_for_status()

    return StreamingResponse(
        upstream.aiter_bytes(),
        media_type="application/pdf",
        background=BackgroundTask(upstream.aclose),
    )

The CSS that makes a invoice page correctly

The layout problem specific to this document is that line items are unbounded, so the table has to break across pages while the totals block stays whole and the column headers repeat. These rules handle it.

css
/* Line items run past one page. Repeat the header, keep the
   totals block whole, and never strand a single row. */
thead { display: table-header-group; }
tfoot { display: table-footer-group; }
tr    { break-inside: avoid; }

.totals {
  break-inside: avoid;
  break-before: auto;
}

@page {
  size: A4;
  margin: 18mm 16mm 22mm;
}

What goes wrong in FastAPI

Calling a synchronous HTTP client inside an async def endpoint blocks the event loop for the whole render, which stalls every other request on that worker. Either use httpx.AsyncClient, or declare the endpoint def rather than async def so it runs in the threadpool.

What people try first

Most FastAPI projects reach for WeasyPrint called from a background task, which moves the memory cost off the request but not out of the process. That works until it is running on more than one machine, at which point the browser becomes the thing you operate rather than the thing you use.

Where the invoice lives afterwards

Rendering is the short part. Invoices are kept for the statutory retention period, which in most jurisdictions runs to six years or more. That means the file has to be stored, not regenerated, and the stored copy has to be the one that was sent.

Getting the document right

  • Check the total. A rounding difference between what you display and what you charge is the kind of error that surfaces during an audit rather than on the day.
  • Generation is triggered by an order completing, or a billing cycle closing, so size the timeout for that path rather than for a health check.
  • Volume arrives in bursts, so queue the render rather than doing it inside the request that triggered it.
  • Backgrounds are painted by default here, so a design that uses colour needs nothing set. Only an explicit print_background of false turns them off.

Frequently asked

Do I need Chromium installed to generate invoices from FastAPI?

No. The render happens over HTTP, so your FastAPI deployment stays the size it is now. That is the main reason to use an API rather than WeasyPrint called from a background task, which moves the memory cost off the request but not out of the process.

How do I stop a long invoice using all the memory?

Return StreamingResponse over the httpx byte iterator. Calling a synchronous HTTP client inside an async def endpoint blocks the event loop for the whole render, which stalls every other request on that worker. Either use httpx.AsyncClient, or declare the endpoint def rather than async def so it runs in the threadpool.

What has to be on a invoice?

At minimum: an invoice number that is sequential and never reused; the issue date, and separately the payment due date; supplier and customer legal names with addresses, not trading names. The one to get right before anything else is the total. A rounding difference between what you display and what you charge is the kind of error that surfaces during an audit rather than on the day.

Do I need to store the generated invoices?

Depends on the document, and this one has a clear answer: invoices are kept for the statutory retention period, which in most jurisdictions runs to six years or more. That means the file has to be stored, not regenerated, and the stored copy has to be the one that was sent.

Can I keep my existing invoice template?

Yes, if it produces HTML. Whatever renders your invoice view today can render the same markup for the PDF, which is why the CSS above is the only new thing you write.

Related

Other FastAPI documents, and the same invoice in other stacks.

100 free documents a month, no card.