import { readFile } from 'node:fs/promises'; import puppeteer from 'puppeteer'; const [input, output = 'invoice.pdf'] = process.argv.slice(2); if (!input) throw new Error('Pass an invoice JSON file and an optional PDF filename.'); const data = JSON.parse(await readFile(input, 'utf8')); const escape = value => String(value).replace(/[&<>"']/g, char => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', }[char])); const money = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); const isoDate = new Intl.DateTimeFormat('en-US', { dateStyle: 'medium', timeZone: 'UTC' }); const total = data.items.reduce((sum, item) => sum + item.quantity * Math.round(item.unitPrice * 100), 0); const rows = data.items.map(({ description, quantity, unitPrice }) => `${escape(description)}${escape(quantity)}${money.format(unitPrice)}${money.format(quantity * Math.round(unitPrice * 100) / 100)}` ).join(''); const html = ` ${escape(data.invoice.number)} | Sample invoice

NORTHSTAR STUDIO

Invoice.

${escape(data.invoice.number)} / ${isoDate.format(new Date(data.invoice.date))}
Payment due ${isoDate.format(new Date(data.invoice.due))}

BILL TO
${escape(data.client.name)}
${escape(data.client.address)}

${rows}
DescriptionQtyUnit priceAmount

Total ${money.format(total / 100)}

${escape(data.notes)}

`; const browser = await puppeteer.launch({ ...(process.env.PUPPETEER_EXECUTABLE_PATH ? { executablePath: process.env.PUPPETEER_EXECUTABLE_PATH } : {}), }); try { console.log(await browser.version()); const page = await browser.newPage(); await page.setContent(html, { waitUntil: 'load' }); await page.pdf({ path: output, preferCSSPageSize: true, printBackground: true, displayHeaderFooter: true, headerTemplate: '', footerTemplate: '
Page of
', }); } finally { await browser.close(); }