Productivity, PDF & Writing

Generating PDF Invoices in Node.js: A Small Working Example With Real Tests

Build a PDF invoice with PDFKit and Node.js: integer-cent money, correct tax rounding, multi-page tables with repeated headers and page numbers, and tests that read the generated PDF back and check the numbers.

By Rajib Roy Published 5 min read

Sooner or later, a small web app needs to produce an invoice, and the first version usually looks fine and is wrong in the details. Totals that are a cent out. A table that runs off the bottom of the page. A second page with no header and no page number. All of these are avoidable, and the fixes are small.

This post builds a PDF invoice generator in Node.js with PDFKit, shows the decisions that matter, and tests it by reading the PDF back and checking what's inside. It is a teaching example. Check what your country requires on an invoice before you use anything like it, since that varies and I'm not giving tax or legal advice.

Decision 1: money is integers

JavaScript numbers are binary floating point, so 0.1 + 0.2 is not 0.3. On a single invoice a rounding slip is cosmetic; across thousands of invoices it becomes an accounting argument. The standard answer is to store money as an integer number of minor units (cents) and only format it for display. So a line has a quantity and a unitCents, both required to be non-negative integers, and the code throws if you pass 10.5 cents.

Decision 2: tax is calculated once, and rounded once

If you round the tax on each line and then add them up, you can get a different total from rounding the tax on the subtotal. Which is right depends on your jurisdiction and policy, and I won't claim either is universal. What matters is to choose one and make it deterministic. This code computes the tax once on the subtotal, using basis points (2000 means 20.00%) and integer arithmetic with round-half-up. The tests include a case where three items of 3.33 give a subtotal of 9.99, tax of 2.00 and a total of 11.99.

Decision 3: paginate on purpose

PDFKit will happily draw text off the bottom of a page unless you check. The code tracks the vertical position, and when the next row wouldn't fit, it starts a new page and draws the table header again. It also keeps the totals block together: if there isn't room for three rows, they move to a new page rather than splitting. Page numbers need the total count, which isn't known until the end, so the document uses bufferPages and goes back to write "Page 1 of 3" on every page before finishing.

Why PDFKit, and what the alternatives cost

PDFKit draws pages directly from code, with no browser involved, so it is light to run and its output is predictable. The price is that you position everything yourself, as the table code shows. The other common route is to design the invoice in HTML and print it to PDF with a headless browser. That is friendlier for designers and handles rich layout, and it brings a much heavier dependency to deploy and keep updated. I haven't compared the two on speed, memory or output size, so I make no claim about which is better for you. For a plain invoice with a table and totals, direct drawing is a perfectly reasonable choice.

The code

invoice.js

// Generate a PDF invoice with PDFKit. Money is handled in integer minor units (cents), never floats.
const PDFDocument = require('pdfkit');

/** Round half up for non-negative integers: round(n * num / den). */
function mulDiv(n, num, den) {
  return Math.floor((n * num * 2 + den) / (den * 2));
}

/** taxBps = tax rate in basis points (2000 = 20.00%). Tax is calculated once on the subtotal, then rounded. */
function totals(lines, taxBps) {
  for (const l of lines) {
    if (!Number.isInteger(l.qty) || !Number.isInteger(l.unitCents) || l.qty < 0 || l.unitCents < 0) {
      throw new Error(`line "${l.description}": qty and unitCents must be non-negative integers`);
    }
  }
  const subtotal = lines.reduce((sum, l) => sum + l.qty * l.unitCents, 0);
  const tax = mulDiv(subtotal, taxBps, 10000);
  return { subtotal, tax, total: subtotal + tax };
}

/** Format minor units. The number of decimals depends on the currency: USD has 2, JPY has 0, KWD has 3. */
function money(minor, currency = 'USD', locale = 'en-US') {
  const fmt = new Intl.NumberFormat(locale, { style: 'currency', currency });
  const digits = fmt.resolvedOptions().maximumFractionDigits;
  return fmt.format(minor / 10 ** digits);
}

const LEFT = 50, RIGHT = 545, ROW = 20, BOTTOM = 740;
const COLS = { desc: 50, qty: 330, unit: 390, amount: 470 };

function tableHeader(doc) {
  doc.font('Helvetica-Bold').fontSize(10);
  const y = doc.y;
  doc.text('Description', COLS.desc, y);
  doc.text('Qty', COLS.qty, y, { width: 40, align: 'right' });
  doc.text('Unit', COLS.unit, y, { width: 70, align: 'right' });
  doc.text('Amount', COLS.amount, y, { width: 75, align: 'right' });
  doc.moveTo(LEFT, y + 14).lineTo(RIGHT, y + 14).stroke();
  doc.y = y + 20;
  doc.font('Helvetica');
}

/** Returns a Promise<Buffer>. */
function renderInvoice(inv) {
  const { subtotal, tax, total } = totals(inv.lines, inv.taxBps);
  const cur = inv.currency || 'USD';
  return new Promise((resolve, reject) => {
    const doc = new PDFDocument({ size: 'A4', margin: 50, bufferPages: true,
      info: { Title: `Invoice ${inv.number}`, Author: inv.from.name } });
    const chunks = [];
    doc.on('data', (c) => chunks.push(c));
    doc.on('end', () => resolve(Buffer.concat(chunks)));
    doc.on('error', reject);

    doc.font('Helvetica-Bold').fontSize(20).text(`Invoice ${inv.number}`, LEFT, 50);
    doc.font('Helvetica').fontSize(10).moveDown(0.5)
      .text(`Date: ${inv.date}`).text(`Due: ${inv.due}`);
    doc.moveDown().font('Helvetica-Bold').text('From').font('Helvetica').text(inv.from.name).text(inv.from.address);
    doc.moveDown().font('Helvetica-Bold').text('Bill to').font('Helvetica').text(inv.to.name).text(inv.to.address);
    doc.moveDown(2);

    tableHeader(doc);
    for (const l of inv.lines) {
      if (doc.y > BOTTOM - ROW) { doc.addPage(); tableHeader(doc); }   // repeat the header on every page
      const y = doc.y;
      doc.fontSize(10);
      doc.text(l.description, COLS.desc, y, { width: 270, lineBreak: false, ellipsis: true });
      doc.text(String(l.qty), COLS.qty, y, { width: 40, align: 'right' });
      doc.text(money(l.unitCents, cur), COLS.unit, y, { width: 70, align: 'right' });
      doc.text(money(l.qty * l.unitCents, cur), COLS.amount, y, { width: 75, align: 'right' });
      doc.y = y + ROW;
    }

    if (doc.y > BOTTOM - 70) doc.addPage();          // keep the totals block together
    doc.moveDown();
    const rows = [['Subtotal', subtotal], [`Tax (${(inv.taxBps / 100).toFixed(2)}%)`, tax], ['Total due', total]];
    for (const [label, cents] of rows) {
      const y = doc.y;
      doc.font(label === 'Total due' ? 'Helvetica-Bold' : 'Helvetica');
      doc.text(label, COLS.unit - 60, y, { width: 130, align: 'right' });
      doc.text(money(cents, cur), COLS.amount, y, { width: 75, align: 'right' });
      doc.y = y + 18;
    }

    const range = doc.bufferedPageRange();
    for (let i = range.start; i < range.start + range.count; i++) {
      doc.switchToPage(i);
      doc.font('Helvetica').fontSize(8).text(`Page ${i + 1} of ${range.count}`, LEFT, 780,
        { width: RIGHT - LEFT, align: 'center', lineBreak: false });
    }
    doc.end();
  });
}

module.exports = { renderInvoice, totals, money, mulDiv };

The function returns a promise for a Buffer, so you can write it to a file, attach it to an email or stream it from an HTTP handler. It also sets the PDF's title and author metadata, which is easy to forget and shows up in a viewer's tab.

Testing a PDF

You can't unit-test a picture, but you can test text. The tests render the invoice, write it to a temporary file and run poppler's pdftotext -layout on it, then assert on the extracted text. The first four tests need no PDF at all: they check that integers add up, that tax rounds half up on the subtotal, that bad input is rejected and that money formats correctly, including currencies with other numbers of decimals.

invoice.test.js

const test = require('node:test');
const assert = require('node:assert/strict');
const { execFileSync, spawnSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { renderInvoice, totals, money, mulDiv } = require('./invoice');

const base = {
  number: 'INV-1042', date: '2026-11-17', due: '2026-12-17', currency: 'USD', taxBps: 2000,
  from: { name: 'Example Studio Ltd', address: '1 Sample Street' },
  to: { name: 'Client Co', address: '2 Test Road' },
};

test('floats would get this wrong; integer cents do not', () => {
  assert.notEqual(0.1 + 0.2, 0.3);                       // the classic
  assert.equal(totals([{ description: 'a', qty: 3, unitCents: 10 }, { description: 'b', qty: 1, unitCents: 20 }], 0).subtotal, 50);
});

test('tax is rounded half up, once, on the subtotal', () => {
  assert.equal(mulDiv(1, 5000, 10000), 1);               // 0.5 rounds up
  assert.equal(mulDiv(999, 2000, 10000), 200);           // 199.8 -> 200
  const t = totals([{ description: 'x', qty: 1, unitCents: 333 }, { description: 'y', qty: 1, unitCents: 333 }, { description: 'z', qty: 1, unitCents: 333 }], 2000);
  assert.deepEqual(t, { subtotal: 999, tax: 200, total: 1199 });
});

test('rejects fractional cents and negative quantities', () => {
  assert.throws(() => totals([{ description: 'bad', qty: 1, unitCents: 10.5 }], 0), /integers/);
  assert.throws(() => totals([{ description: 'bad', qty: -1, unitCents: 10 }], 0), /integers/);
});

test('money formats minor units, and respects currencies with other decimal places', () => {
  assert.equal(money(123456, 'USD'), '$1,234.56');
  assert.equal(money(5, 'USD'), '$0.05');
  assert.equal(money(1000, 'JPY', 'ja-JP'), '\uFFE51,000');      // yen have no minor unit: 1000 is 1,000 yen, not 10
  assert.equal(money(1500, 'KWD'), 'KWD\u00A01.500');            // Kuwaiti dinar has three decimals
});

// The PDF-content tests need poppler's pdftotext and pdfinfo; they are skipped if those are not installed.
const havePoppler = spawnSync('pdftotext', ['-v']).error === undefined && spawnSync('pdfinfo', ['-v']).error === undefined;

function pdfText(buf) {
  const f = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'inv-')), 'x.pdf');
  fs.writeFileSync(f, buf);
  return {
    text: execFileSync('pdftotext', ['-layout', f, '-']).toString(),
    pages: Number(/Pages:\s+(\d+)/.exec(execFileSync('pdfinfo', [f]).toString())[1]),
  };
}

test('one-page invoice contains the numbers it should', { skip: !havePoppler && 'poppler not installed' }, async () => {
  const lines = [{ description: 'Design work', qty: 10, unitCents: 7500 }, { description: 'Hosting', qty: 1, unitCents: 1250 }];
  const buf = await renderInvoice({ ...base, lines });
  assert.equal(buf.subarray(0, 5).toString(), '%PDF-');
  const { text, pages } = pdfText(buf);
  assert.equal(pages, 1);
  for (const s of ['Invoice INV-1042', 'Example Studio Ltd', 'Client Co', 'Design work', '$750.00', '$12.50', '$762.50', '$152.50', '$915.00', 'Page 1 of 1']) {
    assert.ok(text.includes(s), `missing ${s}`);
  }
});

test('a long invoice paginates, repeats the header, and keeps totals on the last page', { skip: !havePoppler && 'poppler not installed' }, async () => {
  const lines = Array.from({ length: 70 }, (_, i) => ({ description: `Item ${i + 1}`, qty: 1, unitCents: 1000 + i }));
  const buf = await renderInvoice({ ...base, lines });
  const { text, pages } = pdfText(buf);
  assert.ok(pages >= 3, `expected at least 3 pages, got ${pages}`);
  assert.equal((text.match(/Description/g) || []).length, pages);           // header on every page
  const { total } = totals(lines, base.taxBps);
  assert.ok(text.includes(money(total)), 'grand total missing');
  const lastPage = text.split('\f').filter(Boolean).pop();
  assert.ok(lastPage.includes('Total due'), 'totals should sit on the last page');
  assert.ok(text.includes(`Page ${pages} of ${pages}`));
});

test('document title metadata is set', { skip: !havePoppler && 'poppler not installed' }, async () => {
  const buf = await renderInvoice({ ...base, lines: [{ description: 'x', qty: 1, unitCents: 100 }] });
  const f = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'inv-')), 'm.pdf');
  fs.writeFileSync(f, buf);
  assert.match(execFileSync('pdfinfo', [f]).toString(), /Title:\s+Invoice INV-1042/);
});

All seven pass. The one-page test checks the invoice number, both parties, the line items, each formatted amount, the tax and total, and "Page 1 of 1". The long-invoice test generates seventy lines, which comes out at three pages, and checks that the word "Description" (the table header) appears once per page, that the grand total computed independently is in the text, that "Total due" is on the last page and that the last footer reads "Page N of N".

I also rendered a 45-line invoice to images and looked at it. Two pages, with the header at the top of page two and the subtotal, tax and total at the bottom of the second page. The tests can't judge how nice it looks, but they do prove the numbers and the pagination.

Currencies are not all two decimals

I called the field unitCents for readability, but the rule is really "minor units", and the number of decimals depends on the currency. The US dollar has two, the Japanese yen has none, and the Kuwaiti dinar has three. If you divide every amount by 100 you will show a thousand yen as ten yen. The money helper asks Intl.NumberFormat how many decimals the currency uses and divides by that power of ten. The tests check that 123,456 minor units of USD formats as $1,234.56, that 1,000 yen formats as 1,000 yen and not 10, and that 1,500 Kuwaiti dinar minor units formats with three decimals. If you only ever invoice in one currency, this is one less thing to worry about; if you invoice in several, test every currency you support.

What I'd add next

  • Your logo and fonts. PDFKit can embed images and TrueType fonts; the built-in Helvetica only covers basic Latin characters, so names with other scripts need an embedded font.
  • Per-line tax. If your invoices mix tax rates, switch to per-line rates and decide the rounding rule on purpose.
  • Wrapped descriptions. The example truncates a long description to one line. Real invoices need row heights that grow.
  • Invoice numbers from the database. Generate them in a transaction. Gaps and duplicates are accounting problems.
  • Legal fields. Tax IDs, registration numbers, payment terms and wording required in your country. Ask an accountant.

What I haven't verified

  • Non-Latin text, custom fonts, images and other page sizes.
  • Descriptions longer than one line.
  • Compliance with any country's invoicing rules, including e-invoicing formats.
  • How the PDF looks in every viewer; I checked it by rendering with poppler only.

If you'd like invoicing, receipts or reports built into a product, I take on that kind of work.

Build with me

Need documents generated from your app?

I build invoice, receipt and report generation for web apps, with tests that check the numbers as well as the layout.

See services Get in touch

What I ran this against

  • Node.js 24.22.1 with PDFKit 0.20.2, run on 17 November 2026 on Linux using the built-in node:test runner. 7 tests pass.
  • The tests read the generated PDF back with poppler's pdftotext and pdfinfo (poppler 25.03.0): they check a one-page invoice's text and totals, that a 70-line invoice paginates to at least three pages with the table header on every page, that the totals sit on the last page with the right grand total, and that the PDF title is set. Those three tests are skipped automatically if poppler isn't installed.
  • I also rendered a 45-line invoice to images and looked at both pages by eye to check the layout, the repeated header and the page numbers.
  • I did not test it with non-Latin text, custom fonts, logos, other page sizes or very long descriptions beyond a single line, and I didn't check any invoice against a country's legal requirements.

Sources checked

  • PDFKit documentation (documents, text, bufferPages and switchToPage for page numbers, document info metadata): pdfkit.org.
  • Node.js documentation, the node:test runner and Intl.NumberFormat: nodejs.org/api/test.html.
  • MDN Web Docs, Intl.NumberFormat (currency formatting): developer.mozilla.org.