Generating PDF Invoices from HTML Templates
Generation
HTML to PDF: The Use Cases
- Invoices and receipts — generate from an invoice template with order data
- Reports — render a data table as a PDF attachment
- Certificates — personalised PDFs from an HTML template
- Confirmations — booking and contract summaries
Using HTML as the source format means you can use CSS for styling, apply the same brand design as your web UI, and manage layout with Flexbox and Grid.
API Usage
curl -X POST https://api.toolkitapi.io/v1/pdf/html-to-pdf \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"html": "<h1>Invoice #1042</h1><p>Amount: $299.00</p>",
"options": {
"paper_size": "A4",
"margin": "20mm",
"orientation": "portrait"
}
}' --output invoice.pdf
Injecting Data into Templates
Use Jinja2 or your preferred templating engine server-side before sending to the API:
from jinja2 import Template
template = Template(Path("templates/invoice.html").read_text())
html = template.render(
order_id="ORD-1042",
line_items=order.items,
total=order.total,
customer=customer,
)
resp = httpx.post(
"https://api.toolkitapi.io/v1/pdf/html-to-pdf",
headers={"X-API-Key": API_KEY},
json={"html": html, "options": {"paper_size": "A4"}},
)
Path(f"invoices/{order.id}.pdf").write_bytes(resp.content)
CSS Tips for PDF
- Use
@pagerules to control margins and page size - Avoid
vh/vwunits — they don't translate to paper - Use
page-break-before: alwaysto force page breaks - Web fonts work, but embed them with
@font-facefor offline rendering
Header and Footer
Pass header_html and footer_html to add repeating page headers and footers:
{
"header_html": "<div style='font-size:9px;text-align:right'>CONFIDENTIAL</div>",
"footer_html": "<div style='font-size:9px'>Page <span class='pageNumber'></span> of <span class='totalPages'></span></div>"
}