How to Generate PDFs From Templates in Python (Jinja2 + HTML)

Generate PDFs from templates in Python: fill a Jinja2 HTML template with your data, print it with WeasyPrint or Playwright, make a whole batch at once, fill an existing PDF form with pypdf, or send the same template to an API.

TL;DR:

What This Blog Covers:

How to generate a PDF from a template in Python: write the document once as a Jinja2 HTML template, fill it with each record’s data, and print the result to PDF.

Key Points:

  • Jinja2 fills an HTML template with your data: loops for line items, if for optional parts, and Python formatting for money and dates
  • WeasyPrint prints the HTML to PDF with its own layout engine, and Playwright prints it with headless Chromium
  • One template makes any number of PDFs: render it once for each record in a loop
  • Reusing one browser, Playwright printed 30 invoices in 1.0 second in our test, against 7.6 seconds for WeasyPrint
  • If the template is already a fillable PDF form, pypdf fills its fields instead

Best For:

Python developers who generate invoices, reports or certificates from data and want the layout in a template rather than in code.


To generate a PDF from a template in Python, keep the layout in an HTML file with Jinja2 placeholders, render it with your data, and print the HTML to PDF. The template holds the design and your code supplies the values, so a new field or a new color is an edit to one file, not to your Python.

Jinja2 is the template engine Flask uses. For the printing step you have two good choices: WeasyPrint, which lays out HTML and CSS itself, and Playwright, which drives headless Chromium (Chrome running without a window).

A developer at a laptop sends one template card marked with curly braces to three invoice PDFs while a colleague holds a printed invoice and gives a thumbs up

This guide builds one invoice, INV-2026-0142, from a template. It prints it with both engines, generates a batch of invoices, fills an existing PDF form with pypdf, and then sends the same template to an API.

Every example was run on Python 3.14 in December 2026 with Jinja2 3.1.6, WeasyPrint 70.0, Playwright 1.65.3 and pypdf 7.2.0.

Which Kind of Template Do You Have?

Template Library How the PDF is made Best for
HTML and CSS with Jinja2 tags WeasyPrint 70 Its own layout engine, no browser Invoices, statements and reports
HTML and CSS with Jinja2 tags Playwright 1.65 Headless Chromium Templates that use JavaScript, such as charts
A fillable PDF form pypdf 7.2 Writes values into the form’s fields Forms you must reuse exactly as they are
A Word document docxtpl 0.20 Fills a .docx, then LibreOffice converts it Teams that design documents in Word

Most of this guide uses the first two rows, because an HTML template is the easiest to design, version and preview. Step 7 covers PDF forms, and the FAQ covers Word.

Prerequisites

  • Python 3.10 or later. WeasyPrint 70 and Playwright 1.65 both require it. We used Python 3.14.
  • The packages:
pip install jinja2 weasyprint playwright pypdf requests
playwright install --only-shell chromium

--only-shell downloads only the headless build of Chromium, which is all PDF printing needs: 287 MB on disk in our test, against about 700 MB for a plain playwright install chromium.

  • Pango for WeasyPrint. WeasyPrint 70 needs the Pango library, version 1.44 or later. Most Linux distributions package it, and the WeasyPrint docs list the steps for macOS and Windows.

The project looks like this:

invoice-pdf/
├── invoice.json
├── render.py
├── make_weasyprint.py
├── make_playwright.py
└── templates/
    └── invoice.html

1. Write the Invoice Data

The data is plain JSON. It’s what your app would load from its database for one invoice:

{
  "invoice_number": "INV-2026-0142",
  "issued": "2026-12-01",
  "due": "2026-12-31",
  "status": "due",
  "seller": {
    "name": "Northwind Studio",
    "address": ["410 Pine Street", "Seattle, WA 98101"]
  },
  "bill_to": {
    "name": "Blue Fern Cafe",
    "address": ["22 Maple Avenue", "Portland, OR 97205"]
  },
  "items": [
    {"description": "Website redesign", "quantity": 1, "unit_price": 2400.00},
    {"description": "Menu photography, half day", "quantity": 1, "unit_price": 450.00},
    {"description": "Hosting, per month", "quantity": 12, "unit_price": 15.00}
  ],
  "subtotal": 3030.00,
  "tax_rate": 8,
  "tax": 242.40,
  "total": 3272.40,
  "notes": "Payment by bank transfer within 30 days. Thank you for your business."
}

Amounts are numbers, not formatted strings, so the template decides how they look. The totals come from your app, which already calculates tax. The template only multiplies quantity by unit price for each line.

2. Write the Jinja2 Template

Save this as templates/invoice.html. It’s a normal HTML page with Jinja2 tags where the data goes:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Invoice {{ invoice_number }}</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap">
<style>
  @page {
    size: A4;
    margin: 20mm 18mm 24mm;
    @bottom-right {
      content: "Page " counter(page) " of " counter(pages);
      font: 9pt Inter, sans-serif;
      color: #6b7280;
    }
  }
  body { margin: 0; font: 10pt/1.5 Inter, sans-serif; color: #1f2937; }
  .header { display: flex; justify-content: space-between; align-items: flex-start;
            border-bottom: 3px solid #0e7490; padding-bottom: 12px; }
  h1 { margin: 0; font-size: 24pt; color: #0e7490; }
  .meta { text-align: right; }
  .status { display: inline-block; margin-top: 4px; padding: 2px 10px; border-radius: 4px;
            font-size: 9pt; font-weight: bold; }
  .paid { background: #dcfce7; color: #166534; }
  .due { background: #fef3c7; color: #92400e; }
  .parties { display: flex; gap: 60px; margin: 24px 0; }
  .label { font-size: 8.5pt; letter-spacing: 0.08em; color: #6b7280; }
  table { width: 100%; border-collapse: collapse; }
  th { padding: 6px 4px; border-bottom: 1px solid #d1d5db; text-align: left;
       font-size: 9pt; color: #6b7280; }
  td { padding: 8px 4px; border-bottom: 1px solid #e5e7eb; }
  tr { break-inside: avoid; }
  .num { text-align: right; }
  .totals { width: 45%; margin: 12px 0 0 auto; }
  .totals td { padding: 4px; border: 0; }
  .grand td { border-top: 2px solid #1f2937; font-size: 13pt; font-weight: bold; }
  .notes { margin-top: 28px; color: #4b5563; }
</style>
</head>
<body>
  <div class="header">
    <div>
      <h1>Invoice</h1>
      {{ invoice_number }}
    </div>
    <div class="meta">
      Issued {{ strftime(strptime(issued, "%Y-%m-%d"), "%B %d, %Y") }}<br>
      Due {{ strftime(strptime(due, "%Y-%m-%d"), "%B %d, %Y") }}<br>
      {% if status == "paid" %}
        <span class="status paid">PAID</span>
      {% else %}
        <span class="status due">DUE {{ "${:,.2f}".format(total) }}</span>
      {% endif %}
    </div>
  </div>

  <div class="parties">
    <div>
      <div class="label">FROM</div>
      <strong>{{ seller.name }}</strong>
      {% for line in seller.address %}<br>{{ line }}{% endfor %}
    </div>
    <div>
      <div class="label">BILL TO</div>
      <strong>{{ bill_to.name }}</strong>
      {% for line in bill_to.address %}<br>{{ line }}{% endfor %}
    </div>
  </div>

  <table>
    <thead>
      <tr><th>#</th><th>Description</th><th class="num">Qty</th>
          <th class="num">Unit price</th><th class="num">Amount</th></tr>
    </thead>
    <tbody>
      {% for item in items %}
      <tr>
        <td>{{ loop.index }}</td>
        <td>{{ item.description }}</td>
        <td class="num">{{ item.quantity }}</td>
        <td class="num">{{ "${:,.2f}".format(item.unit_price) }}</td>
        <td class="num">{{ "${:,.2f}".format(item.quantity * item.unit_price) }}</td>
      </tr>
      {% endfor %}
    </tbody>
  </table>

  <table class="totals">
    <tr><td>Subtotal</td><td class="num">{{ "${:,.2f}".format(subtotal) }}</td></tr>
    {% if tax %}
    <tr><td>Sales tax ({{ tax_rate }}%)</td><td class="num">{{ "${:,.2f}".format(tax) }}</td></tr>
    {% endif %}
    <tr class="grand"><td>Total</td><td class="num">{{ "${:,.2f}".format(total) }}</td></tr>
  </table>

  {% if notes %}<p class="notes">{{ notes }}</p>{% endif %}
</body>
</html>

What the Jinja2 parts do:

  • {{ invoice_number }}: prints a value. {{ seller.name }} reaches into a nested object.
  • {% for item in items %}: writes one table row per line item, and loop.index numbers them from 1.
  • {% if status == "paid" %}: shows a green PAID badge or the amount due.
  • "${:,.2f}".format(total): formats money with a thousands separator, so 3272.4 prints as $3,272.40.
  • strftime(strptime(issued, "%Y-%m-%d"), "%B %d, %Y"): turns 2026-12-01 into December 01, 2026. These two functions aren’t part of Jinja2. Step 3 adds them, and APITemplate.io’s templates provide them as built-ins.
  • @page: sets A4, the margins and a “Page 1 of 1” footer. WeasyPrint has long supported these margin boxes, and Chrome added them in version 131, so both engines print the same footer.

Long tables split across pages on their own. In a 60-line test invoice, both engines carried on to page 3 and repeated the <thead> row at the top of each page.

Tip: Load the fonts your template uses. On our Linux test machine, Chromium matched Helvetica, Arial to an Arial with no bold face and drew a thin fake bold. The Google Fonts <link> gives both engines the same Inter, bold included.

3. Render the Template With Jinja2

render.py turns the template and one invoice’s data into an HTML string. Both printing scripts import it:

from datetime import datetime

from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape

env = Environment(
    loader=FileSystemLoader("templates"),
    autoescape=select_autoescape(),  # escape <, > and & in your data
    undefined=StrictUndefined,       # fail on a missing field instead of printing nothing
)
# The two date functions APITemplate.io's templates provide
env.globals["strptime"] = datetime.strptime
env.globals["strftime"] = datetime.strftime


def render_invoice(data: dict) -> str:
    return env.get_template("invoice.html").render(**data)

Two settings matter more than they look:

  • Autoescaping. Jinja2 doesn’t escape HTML unless you turn it on. With select_autoescape(), a customer called Smith & Sons <Ltd> printed as text instead of breaking the page.
  • StrictUndefined. By default, a misspelled or missing field prints as an empty string, and you find out from a customer. StrictUndefined raises an error instead.

StrictUndefined is strict about optional fields too. Even {% if notes %} fails when notes is missing, so send optional fields as null rather than leaving them out.

4. Print the PDF With WeasyPrint

WeasyPrint reads the HTML and CSS and writes the PDF without a browser:

import json

from weasyprint import HTML

from render import render_invoice

with open("invoice.json") as f:
    data = json.load(f)

html = render_invoice(data)
HTML(string=html, base_url="templates").write_pdf("invoice-weasyprint.pdf")

Run python make_weasyprint.py, and you get a one-page A4 invoice:

The invoice INV-2026-0142 printed by WeasyPrint from the Jinja2 template, with the DUE $3,272.40 badge, the From and Bill To blocks, three line items, the totals and a Page 1 of 1 footer

base_url tells WeasyPrint where relative paths start, so <img src="logo.png"> in the template loads templates/logo.png. Without it, relative images and stylesheets are skipped.

5. Print the PDF With Playwright

Playwright prints the same HTML with headless Chromium, so the PDF matches what Chrome shows:

import json

from playwright.sync_api import sync_playwright

from render import render_invoice

with open("invoice.json") as f:
    data = json.load(f)

html = render_invoice(data)

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.set_content(html, wait_until="load")
    page.evaluate("document.fonts.ready")  # wait for the web font
    page.pdf(path="invoice-playwright.pdf", prefer_css_page_size=True, print_background=True)
    browser.close()

Two page.pdf() options do the work. prefer_css_page_size=True makes Chromium use the template’s @page size instead of its default Letter, and print_background=True keeps the colored status badge, which Chromium drops otherwise.

Both engines produced nearly identical invoices from the same template:

The same invoice printed by WeasyPrint 70 on the left and by Playwright 1.65 with Chromium 159 on the right, with the same layout, fonts, badge and totals

How to choose between them:

  • WeasyPrint: no browser to install or keep updated, and strong support for print CSS such as margin boxes and page counters. It doesn’t run JavaScript.
  • Playwright: renders anything Chrome can, including JavaScript charts and the newest CSS. It needs its own Chromium, which you keep updated with Playwright.

Our Python HTML to PDF guide compares more converters, including xhtml2pdf and pdfkit.

6. Generate PDFs in Bulk From One Template

A template pays off when you need many documents. Put the invoices in a list, invoices.json, and render the template once for each:

import json
from pathlib import Path

from weasyprint import HTML

from render import render_invoice

with open("invoices.json") as f:
    invoices = json.load(f)

out = Path("invoices")
out.mkdir(exist_ok=True)

for data in invoices:
    html = render_invoice(data)
    HTML(string=html, base_url="templates").write_pdf(out / f"{data['invoice_number']}.pdf")
    print("wrote", data["invoice_number"])

Each invoice gets its own file, named after its number, and the template’s if switches the badge for the one that’s paid:

Three invoices generated from the same template in one run: INV-2026-0142 and INV-2026-0144 with a DUE badge, and INV-2026-0143 for Harbor Books with a green PAID badge

With Playwright, start the browser once and reuse one page for the whole batch:

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()  # one browser and one page for the whole batch
    for data in invoices:
        page.set_content(render_invoice(data), wait_until="load")
        page.evaluate("document.fonts.ready")
        page.pdf(path=out / f"{data['invoice_number']}.pdf", prefer_css_page_size=True, print_background=True)
        print("wrote", data["invoice_number"])
    browser.close()

We timed 30 invoices on an Intel Core i7-1370P laptop. WeasyPrint took 7.6 seconds, about 255 ms each. Playwright took 1.0 second including the browser launch, about 35 ms each.

Tip: Don’t use wait_until="networkidle" in a batch. It waits for 500 ms without network traffic before it returns, and it made Playwright 15 times slower in our test: 527 ms per invoice instead of 35 ms.

7. Fill an Existing PDF Template With pypdf

Sometimes the template isn’t yours to redesign: a supplier’s delivery note, a tax form, a contract exported from Acrobat with form fields. Then you fill the PDF’s fields with pypdf instead of rebuilding it in HTML.

First list the field names, then write values into them:

from pypdf import PdfReader, PdfWriter

reader = PdfReader("delivery-note-form.pdf")
print(list(reader.get_form_text_fields()))  # the field names to fill

writer = PdfWriter(clone_from=reader)
writer.update_page_form_field_values(
    writer.pages[0],
    {
        "customer": "Blue Fern Cafe",
        "order_number": "SO-2026-0311",
        "delivered_on": "December 3, 2026",
        "received_by": "Maya Chen",
    },
)
writer.write("delivery-note-filled.pdf")

The script printed ['customer', 'order_number', 'delivered_on', 'received_by'], then wrote the filled copy:

A delivery note PDF form with its Customer, Order number, Delivered on and Received by fields filled in by pypdf

The fields stay editable. To lock the values in, flatten the form:

from pypdf import PdfReader, PdfWriter
from pypdf.generic import NameObject

writer = PdfWriter(clone_from=PdfReader("delivery-note-form.pdf"))
writer.update_page_form_field_values(
    writer.pages[0],
    {
        "customer": "Blue Fern Cafe",
        "order_number": "SO-2026-0311",
        "delivered_on": "December 3, 2026",
        "received_by": "Maya Chen",
    },
    flatten=True,  # draw each value into the page
)
writer.remove_annotations(subtypes="/Widget")  # remove the fields
del writer.root_object[NameObject("/AcroForm")]  # and the form itself
writer.write("delivery-note-flat.pdf")

All three lines are needed. flatten=True on its own draws each value into the page but leaves the field on top, so every value printed twice, slightly offset. Removing the widgets without the /AcroForm entry left a form pointing at fields that no longer existed, and Poppler warned about each one.

Generate PDFs From the Same Template With an API

Everything above runs in your app, so Pango or Chromium ships with it, and a batch of thousands needs a queue and workers. APITemplate.io’s PDF generation API keeps the template on its servers and renders it with Chromium. Its templates use the same Jinja2 syntax, so the invoice template moves over with a copy and paste:

  1. In the app, create a template in the HTML editor. Paste what’s inside <body> into the Template tab, and the font <link> and the rules inside <style> into the CSS tab.
  2. In the Settings tab, choose A4 and set the margins. The page-number footer is a setting there too (headers and footers), so you can leave the @page rule out.
  3. Send each invoice’s JSON to /v2/create-pdf with the template’s ID:
import json

import requests

with open("invoice.json") as f:
    data = json.load(f)

response = requests.post(
    "https://rest.apitemplate.io/v2/create-pdf",
    params={"template_id": "YOUR_TEMPLATE_ID", "export_type": "file"},
    headers={"X-API-KEY": "YOUR_API_KEY"},
    json=data,
    timeout=60,
)
response.raise_for_status()

with open(f"{data['invoice_number']}.pdf", "wb") as f:
    f.write(response.content)

With export_type=file, the response is the PDF itself. Leave it out and you get JSON with a download_url instead. For a large batch, add async=1 and a webhook_url, and the API calls your URL when each PDF is ready. We ran this code against a mock of /v2/create-pdf that checked the path, query, X-API-KEY header and body, and rendered the template above with the posted JSON.

The Free plan includes 50 PDFs a month and 3 templates. The pricing page lists Custom CSS from PDF Basic up, which is $19 a month billed yearly or $24 monthly.

FAQ

How do I generate a PDF from an HTML template in Python?

Render the template with Jinja2 to get an HTML string, then print it with WeasyPrint’s HTML(string=html).write_pdf() or Playwright’s page.pdf(). Steps 3 to 5 show both with the same template.

Is WeasyPrint or Playwright better for PDF templates?

WeasyPrint is simpler to deploy, since it needs no browser, and it handles print CSS well. Playwright is the choice when the template needs JavaScript, such as a chart library, and it was faster for batches in our test once the browser was running.

How do I fill a PDF form template with Python?

Open the form with pypdf, read the field names with get_form_text_fields(), and write values with update_page_form_field_values(). Step 7 shows how to flatten the result so the values can’t be edited.

Can I use a Word document as a PDF template in Python?

Yes. docxtpl fills a .docx template that uses Jinja2-style tags, and LibreOffice converts the result: soffice --headless --convert-to pdf invoice.docx. We tested it with docxtpl 0.20.2 and LibreOffice 26.2.

How do I add page numbers to a PDF template?

Put them in an @page margin box with counter(page) and counter(pages), as the template in step 2 does. WeasyPrint and Chromium 131 or later both print them.

Conclusion

Keep the layout in a Jinja2 HTML template and your Python code shrinks to loading data and calling one print function. WeasyPrint is the easy default, Playwright is better for JavaScript and big batches, and pypdf covers PDF forms you can’t redesign. For code-first options such as ReportLab and fpdf2, see our guide to Python PDF libraries.

Sign up for a free account and generate up to 50 PDFs or images a month for free.