DEV Community

Cover image for Invoice PDFs from HTML templates: a complete Node.js example
Siftwright
Siftwright

Posted on Originally published at siftwright.com

Invoice PDFs from HTML templates: a complete Node.js example

Generating an invoice PDF looks like a ten-minute job: write some HTML, hand it to a headless browser, save the file. The first version usually works. The problems arrive later. A total is off by a cent. A customer called Smith & <Sons> breaks the layout. A 26-line invoice puts the totals alone on page 2, with no line items above them. "Page 2 of 3" turns out to be harder than it looks.

This post builds a small, complete invoice generator in Node.js that deals with each of those. It has four files: money maths, an HTML template, a renderer and a check script. Every snippet below is the code we ran on 24 November 2026 with Playwright 1.63 and Chromium 158. The outputs quoted are from those runs.

For general print CSS, waiting for fonts and charts, signed URLs and batch rendering, see our longer guide to HTML to PDF at scale. This post stays with one document type and goes deeper on it.

The plan

  1. Keep every amount as an integer number of cents and do all arithmetic on integers.
  2. Render the invoice to an HTML string with a template that escapes every value.
  3. Put page size, margins and the "Page X of Y" footer in CSS, so the same HTML prints the same way wherever it is rendered.
  4. Print it with headless Chromium.
  5. Render many invoices and check the PDFs automatically, because layout bugs only show up at particular lengths.

Set-up is one dependency:

npm install playwright
npx playwright install chromium
Enter fullscreen mode Exit fullscreen mode

Step 1: money in integer cents

JavaScript numbers are binary floating point. 0.1 + 0.2 is 0.30000000000000004, and those tiny errors turn into visible ones once you multiply, round and add across many lines. The usual fix is to store amounts as integers in the smallest currency unit and only format them as currency at the very end.

// money.mjs
// All amounts are integer minor units (cents). Never store 19.99 as a float.
export const toCents = (s) => {
  const m = /^(-)?(\d+)(?:\.(\d{1,2}))?$/.exec(String(s).trim());
  if (!m) throw new Error(`Bad amount: ${s}`);
  const cents = Number(m[2]) * 100 + Number((m[3] || "0").padEnd(2, "0"));
  return m[1] ? -cents : cents;
};

// Round half away from zero, on integers only.
const roundDiv = (num, den) => {
  const q = Math.trunc(num / den), r = num - q * den;
  return Math.abs(r) * 2 >= den ? q + Math.sign(num) : q;
};

// qty may have up to 3 decimals (e.g. 1.5 hours); rate in basis points (2000 = 20%).
export function computeInvoice(lines, { taxBp = 0 } = {}) {
  const out = lines.map((l) => {
    const qtyMilli = Math.round(Number(l.qty) * 1000);
    const net = roundDiv(qtyMilli * toCents(l.unitPrice), 1000);
    return { ...l, net };
  });
  const subtotal = out.reduce((s, l) => s + l.net, 0);
  const tax = roundDiv(subtotal * taxBp, 10000); // tax on the subtotal, rounded once
  return { lines: out, subtotal, tax, total: subtotal + tax };
}

export const formatMoney = (cents, currency, locale = "en-GB") =>
  new Intl.NumberFormat(locale, { style: "currency", currency }).format(cents / 100);
Enter fullscreen mode Exit fullscreen mode

A few decisions are baked in here, and you should check them against your own rules:

  • Prices come in as strings ("19.99"), parsed without ever becoming a float. If your database stores cents already, skip toCents.
  • Quantities can be fractional (1.5 hours), so they are scaled to thousandths before multiplying.
  • Tax is rounded once, on the subtotal. The alternative, rounding tax on each line and adding it up, gives a different answer. Ten lines at 0.13 with 20% tax come to 30 cents of tax when you round per line, and 26 cents when you round once. Neither is wrong in general. Which one you must use depends on the tax rules where you invoice, so check before you copy this.
  • Half-way cases round away from zero. Some jurisdictions or accounting systems want banker's rounding instead. It is one function to change.

For the three-line sample invoice used below (1 × 450.00, 1.5 × 85.00, 3 × 19.99, 20% VAT), this gives a subtotal of £637.47, VAT of £127.49 and a total of £764.96. Intl.NumberFormat does the currency formatting, so the same cents print as £225.02 in en-GB or 225,02 € in de-DE.

Step 2: a template that escapes everything

An invoice is full of text someone else typed: company names, addresses, line descriptions. If any of it goes into the HTML unescaped, a name with a < in it will break the layout, and on a server that also renders other pages it is a script-injection hole. The template below escapes every value. It uses plain template literals so there is no extra dependency. Handlebars or Nunjucks work just as well if you already use one, as long as auto-escaping stays on.

// template.mjs
import { formatMoney, toCents } from "./money.mjs";

const ESC = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
const esc = (v) => String(v ?? "").replace(/[&<>"']/g, (c) => ESC[c]);
// For text inside a CSS string, e.g. content: "...". Hex escapes keep quotes, backslashes and "</style>" out.
const cssStr = (v) => '"' + String(v ?? "").replace(/[^\w .,#:\/-]/g, (c) => `\\${c.codePointAt(0).toString(16)} `) + '"';
const KEEP_WITH_TOTALS = 3; // line items that always stay on the same page as the totals

export function invoiceHtml(inv, calc) {
  const money = (c) => esc(formatMoney(c, inv.currency, inv.locale));
  const row = (l) => `
      <tr><td>${esc(l.description)}</td><td class="num">${esc(l.qty)}</td>
          <td class="num">${money(toCents(l.unitPrice))}</td>
          <td class="num">${money(l.net)}</td></tr>`;
  // The last few rows go in a second table that is glued to the totals.
  const split = Math.max(0, calc.lines.length - KEEP_WITH_TOTALS);
  const body = calc.lines.slice(0, split).map(row).join("");
  const tail = calc.lines.slice(split).map(row).join("");
  // Fixed column widths so the two tables line up.
  const cols = `<colgroup><col><col style="width:16mm"><col style="width:30mm"><col style="width:30mm"></colgroup>`;
  return `<!doctype html><html lang="en"><head><meta charset="utf-8">
<title>Invoice ${esc(inv.number)}</title>
<style>
  @page {
    size: A4; margin: 18mm 16mm 22mm;
    @bottom-left  { content: ${cssStr("Invoice " + inv.number)}; font: 8pt Arial, sans-serif; color: #666; }
    @bottom-right { content: "Page " counter(page) " of " counter(pages); font: 8pt Arial, sans-serif; color: #666; }
  }
  * { box-sizing: border-box; }
  body { font: 10pt/1.45 "Helvetica Neue", Arial, sans-serif; color: #111; margin: 0; }
  header { display: flex; justify-content: space-between; margin-bottom: 10mm; }
  h1 { font-size: 20pt; margin: 0 0 2mm; }
  .parties { display: flex; gap: 12mm; margin-bottom: 8mm; }
  .parties div { flex: 1; }
  table.items { width: 100%; border-collapse: collapse; table-layout: fixed; }
  .items th { text-align: left; border-bottom: 1.5pt solid #111; padding: 2mm 1mm; }
  .items td { border-bottom: 0.5pt solid #ccc; padding: 2mm 1mm; vertical-align: top; }
  .items tr { break-inside: avoid; }   /* never split a row across pages */
  .summary { break-inside: avoid; }    /* last rows + totals + notes move as one block */
  .num { text-align: right; white-space: nowrap; }
  .totals { width: 70mm; margin: 6mm 0 0 auto; }
  .totals td { padding: 1mm; }
  .totals tr.grand td { border-top: 1.5pt solid #111; font-weight: bold; font-size: 12pt; }
  .notes { margin-top: 10mm; color: #444; }
</style></head><body>
<header>
  <div><h1>Invoice</h1>No. ${esc(inv.number)}</div>
  <div class="num">Issued ${esc(inv.issued)}<br>Due ${esc(inv.due)}</div>
</header>
<section class="parties">
  <div><strong>From</strong><br>${esc(inv.seller.name)}<br>${esc(inv.seller.address)}<br>VAT ${esc(inv.seller.vat)}</div>
  <div><strong>Bill to</strong><br>${esc(inv.buyer.name)}<br>${esc(inv.buyer.address)}</div>
</section>
<table class="items">${cols}
  <thead><tr><th>Description</th><th class="num">Qty</th><th class="num">Unit price</th><th class="num">Amount</th></tr></thead>
  <tbody>${body}</tbody>
</table>
<div class="summary">
<table class="items">${cols}<tbody>${tail}</tbody></table>
<table class="totals">
  <tr><td>Subtotal</td><td class="num">${money(calc.subtotal)}</td></tr>
  <tr><td>VAT ${esc(inv.taxBp / 100)}%</td><td class="num">${money(calc.tax)}</td></tr>
  <tr class="grand"><td>Total due</td><td class="num">${money(calc.total)}</td></tr>
</table>
<p class="notes">${esc(inv.notes)}</p>
</div>
</body></html>`;
}
Enter fullscreen mode Exit fullscreen mode

Three parts of the template are worth explaining.

The footer is CSS, not a renderer option. Chromium supports CSS page margin boxes (@bottom-left, @bottom-right and so on inside @page) since version 131, along with counter(page) and counter(pages). That gives "Page 2 of 4" with no JavaScript and no headless-browser settings. Many tutorials use Puppeteer's or Playwright's footerTemplate option instead. That also works, but it ties the footer to the code that calls page.pdf(). With margin boxes, the HTML file carries its own footer, which matters if the same template is ever rendered by a different service or opened in a browser's print dialog. The invoice number goes into a CSS string, so it gets its own escaping function. HTML escaping does not protect a CSS string.

Every row is unbreakable and the header repeats. break-inside: avoid on tr stops a wrapped description from being split across two pages. Chromium repeats a table's <thead> at the top of every page by itself, so the column headings appear on each page with no extra work.

The last three line items are glued to the totals. This is the fix for the most common invoice layout bug, which we come back to in Step 5. The final three rows live in a second table, inside a div with break-inside: avoid that also holds the totals and the payment notes. If the block does not fit at the bottom of a page, all of it moves to the next page together, so the totals always have line items above them. table-layout: fixed and a shared <colgroup> keep the columns of the two tables lined up.

Step 3: render with headless Chromium

Because size, margins and footer all live in the template, the renderer is short:

// render.mjs
import { chromium } from "playwright";

export async function htmlToPdf(browser, html) {
  const page = await browser.newPage();
  try {
    await page.setContent(html, { waitUntil: "load" });
    await page.evaluate(() => document.fonts.ready);
    return await page.pdf({
      preferCSSPageSize: true, // size, margins and footer all come from @page in the template
      printBackground: true,
      tagged: true,            // tagged PDF: better text selection and screen-reader structure
    });
  } finally {
    await page.close();
  }
}

export const launch = () => chromium.launch();
Enter fullscreen mode Exit fullscreen mode

preferCSSPageSize: true tells Chromium to use the template's @page rules instead of its own defaults. tagged: true produces a tagged PDF, which helps text selection and screen readers. Waiting for document.fonts.ready matters as soon as the template uses a web font. Without it, the first PDF can come out in a fallback font.

A driver script ties the pieces together:

// make-invoices.mjs
import { writeFile, mkdir } from "node:fs/promises";
import { computeInvoice } from "./money.mjs";
import { invoiceHtml } from "./template.mjs";
import { htmlToPdf, launch } from "./render.mjs";

const base = {
  currency: "GBP", locale: "en-GB", taxBp: 2000,
  issued: "24 Nov 2026", due: "24 Dec 2026",
  seller: { name: "Example Studio Ltd", address: "1 Sample Street, London", vat: "GB000000000" },
  buyer: { name: "Acme <Widgets> & Co", address: "42 Test Road, Leeds" },
  notes: "Payment by bank transfer within 30 days. Please quote the invoice number.",
};
const short = { ...base, number: "INV-2026-0142", lines: [
  { description: "Website audit", qty: 1, unitPrice: "450.00" },
  { description: "Consulting (hours)", qty: 1.5, unitPrice: "85.00" },
  { description: "Stock photo licence", qty: 3, unitPrice: "19.99" },
]};
const long = { ...base, number: "INV-2026-0143", lines: Array.from({ length: 65 }, (_, i) => ({
  description: `Support ticket #${1000 + i}` + (i % 7 === 0 ? " — includes a longer description that wraps onto a second line inside the cell" : ""),
  qty: (i % 4) + 1, unitPrice: "12.50",
}))};

await mkdir("out", { recursive: true });
const browser = await launch();
try {
  for (const inv of [short, long]) {
    const calc = computeInvoice(inv.lines, { taxBp: inv.taxBp });
    const t0 = Date.now();
    const pdf = await htmlToPdf(browser, invoiceHtml(inv, calc));
    await writeFile(`out/${inv.number}.pdf`, pdf);
    console.log(inv.number, `${inv.lines.length} lines`, `${(pdf.length / 1024).toFixed(0)} KB`, `${Date.now() - t0} ms`);
  }
} finally {
  await browser.close();
}
Enter fullscreen mode Exit fullscreen mode

Output:

INV-2026-0142 3 lines 71 KB 100 ms
INV-2026-0143 65 lines 160 KB 102 ms
Enter fullscreen mode Exit fullscreen mode

The three-line invoice is one A4 page. The 65-line invoice is four pages, with the column header at the top of pages 2 to 4 and "Invoice INV-2026-0143 … Page N of 4" in every footer. We checked this by extracting the text with pdftotext. The buyer name Acme <Widgets> & Co prints literally. To push the escaping harder, we also rendered an invoice whose number was X"; } </style><script>…</script> and whose seller name was an <img onerror> tag. The generated HTML contained neither a raw <script> nor a raw <img, and the PDF showed both strings as plain text, footer included.

Step 4: what we tried that did not work

Two approaches that often come up for keeping totals with the table looked fine at first and failed in testing.

Putting the totals in <tfoot>. Chromium repeats <tfoot> on every page, just as it repeats <thead>. On a three-page test invoice, "TOTAL DUE" appeared on all three pages. That might suit a running "carried forward" line, but not a grand total.

break-before: avoid on the last rows and the totals. This is the cleaner CSS solution on paper: one table, with the last rows and the totals block marked "don't break before me". On two-page invoices it worked perfectly. But in our sweep of 1 to 80 line items, it failed in 10 cases, all on three- and four-page invoices. In those cases Chromium kept the rows together but split the totals block itself, leaving "Total due" alone on the next page. The split-table approach in the template passed all 80.

Avoid rules are hints, not guarantees, and what browsers do with them varies by version. That is why the next step exists.

Step 5: test the layout, not just the code

Layout bugs depend on length. In a stripped-down test table, the naive layout (one table, totals after it) left the totals on a page with zero line items at exactly 26 and 52 rows, and looked fine at every count in between. You will not find that by opening a few sample PDFs. So we render invoices with every length from 1 to 80 lines (every fifth description long enough to wrap) and check each page of each PDF with pdftotext:

// check.mjs - needs pdftotext and pdfinfo (poppler-utils)
import { execFileSync } from "node:child_process";
import { writeFileSync } from "node:fs";
import { computeInvoice } from "./money.mjs";
import { invoiceHtml } from "./template.mjs";
import { htmlToPdf, launch } from "./render.mjs";

const text = (f, p) => execFileSync("pdftotext", ["-layout", "-f", String(p), "-l", String(p), f, "-"]).toString();
const pages = (f) => Number(/Pages:\s+(\d+)/.exec(execFileSync("pdfinfo", [f]).toString())[1]);
const browser = await launch();
let failures = 0;
for (let n = 1; n <= 80; n++) {
  const lines = Array.from({ length: n }, (_, i) => ({
    description: `Item ${i + 1}` + (i % 5 === 0 ? " with a description long enough to wrap onto a second line in the table" : ""),
    qty: 1, unitPrice: "10.00" }));
  const inv = { number: `T-${n}`, currency: "EUR", locale: "en-IE", taxBp: 2300, issued: "x", due: "y",
    seller: { name: "S", address: "A", vat: "V" }, buyer: { name: "B", address: "A" }, notes: "Thanks" };
  const f = `out/check-${n}.pdf`;
  writeFileSync(f, await htmlToPdf(browser, invoiceHtml(inv, computeInvoice(lines, inv))));
  const total = pages(f), problems = [];
  for (let p = 1; p <= total; p++) {
    const t = text(f, p), rows = (t.match(/^\s*Item \d+/gm) || []).length;
    if (!t.includes(`Page ${p} of ${total}`)) problems.push(`p${p} footer`);
    if (rows > 0 && p < total && !t.includes("Description")) problems.push(`p${p} no header`);
    if (p === total && (!t.includes("Total due") || rows < Math.min(n, 3))) problems.push(`last page has ${rows} rows`);
  }
  if (problems.length) { failures++; console.log(n, total, problems.join(", ")); }
  else if (n % 20 === 0) console.log(`ok up to ${n} lines (${total} pages)`);
}
await browser.close();
console.log(failures ? `${failures} failures` : "all 80 invoices passed");
Enter fullscreen mode Exit fullscreen mode

Result with the template above:

ok up to 20 lines (2 pages)
ok up to 40 lines (3 pages)
ok up to 60 lines (3 pages)
ok up to 80 lines (4 pages)
all 80 invoices passed
Enter fullscreen mode Exit fullscreen mode

Before we moved the payment notes inside the glued block, this same script failed on six lengths (14, 15, 38, 39, 61 and 62 lines). In each, the totals fit but the one-line "Thanks" note spilled onto a page of its own. That is the kind of thing the check catches and a person checking a few samples by eye misses. Run it in your test suite whenever the template changes, using your real fonts and your longest realistic descriptions.

One trade-off remains. When the glued block moves to a new page, those last three rows are in the second table, so the repeated column header does not appear above them. We accepted that. If it matters to you, add a small "continued" label to the block, or raise KEEP_WITH_TOTALS so the move happens less often.

Throughput

Reusing one browser matters more than anything else for speed. On a 4-vCPU container, rendering 12-line invoices:

Approach Time per invoice
Launch a new browser for every invoice 173 ms (10 runs)
One shared browser, one page at a time 69 ms (100 runs)
One shared browser, four pages at a time 34 ms (100 runs)

These are small numbers, and they are for local rendering with no network fetches. Real templates with web fonts, logos and charts are slower. The structure still holds: launch once, open and close a page per document, and limit how many pages run at the same time.

Running it without a browser fleet

All of the above assumes you are happy to run Chromium yourself. On a server you control, that is fine. Lambda layers, minimal containers and serverless platforms are where it gets awkward: the browser binary is large, needs system libraries and uses a lot of memory when several renders run in parallel.

The alternative is to render through an API. Our HTML to PDF API renders a URL rather than an HTML string, so the pattern is: write invoiceHtml() output to private storage, create a short-lived signed URL, and send that URL with "format": "pdf" and "pdfPageFormat": "A4". The HTML-to-PDF guide has the signed-URL code. Because the footer and page breaks live in the template's CSS, there are no renderer options to pass along. That is the other reason to prefer margin boxes over footerTemplate. We did not re-run the invoice through the API for this post. Run the check script against API output before you switch, as rendering engines differ in which Chromium version they use. To try a single public page first, there is a free website to PDF converter.

Checklist

  • Amounts as integer cents; decide per-line versus subtotal tax rounding deliberately.
  • Escape every value in the template, and escape CSS strings separately.
  • Page size, margins and "Page X of Y" in @page, with preferCSSPageSize: true.
  • break-inside: avoid on rows; let <thead> repeat; keep totals out of <tfoot>.
  • Glue the last few rows, the totals and the notes into one unbreakable block.
  • Render every length from 1 to your realistic maximum and check the pages automatically.
  • Reuse one browser and cap how many pages render at once.

Originally published on siftwright.com. Questions: support@siftwright.com.

Top comments (0)