patternjavascriptModerate
Puppeteer PDF generation from HTML templates
Viewed 0 times
puppeteer pdfheadless chrome pdfhtml to pdfpdf generation nodejsserver-side pdf
Node.js
Problem
Generating pixel-perfect PDFs from dynamic data (invoices, reports, certificates) is difficult without a browser rendering engine. Pure PDF libraries require defining every layout element in code and lack CSS support.
Solution
Use Puppeteer to launch a headless Chrome instance, navigate to an HTML template (or set page content directly), wait for all assets to load, then call page.pdf() with print media options. This produces PDFs that exactly match browser rendering.
Why
Puppeteer delegates rendering to Chrome's print engine, supporting the full CSS box model, fonts, images, and page breaks. The output is identical to printing a web page to PDF from Chrome.
Gotchas
- Puppeteer must wait for all fonts and images to load before calling page.pdf() or they will be missing
- Use page.emulateMediaType('print') to apply print CSS media queries
- Set printBackground: true to include background colors and images in the PDF
- Puppeteer is heavyweight in serverless environments — consider caching generated PDFs or using a dedicated PDF service
- Running Puppeteer in Docker requires --no-sandbox flag and installing Chrome dependencies
Code Snippets
Generate PDF from HTML with Puppeteer
const puppeteer = require('puppeteer');
async function generatePdf(htmlContent, outputPath) {
const browser = await puppeteer.launch({
headless: 'new',
args: ['--no-sandbox', '--disable-setuid-sandbox'],
});
const page = await browser.newPage();
await page.setContent(htmlContent, { waitUntil: 'networkidle0' });
await page.emulateMediaType('print');
const pdf = await page.pdf({
path: outputPath,
format: 'A4',
printBackground: true,
margin: { top: '20mm', right: '15mm', bottom: '20mm', left: '15mm' },
});
await browser.close();
return pdf;
}
const html = '<html><body><h1>Invoice #1234</h1><p>Amount due: $99.00</p></body></html>';
const pdfBuffer = await generatePdf(html, './invoice.pdf');Context
Server-side generation of dynamic PDFs from HTML templates (invoices, reports, certificates)
Revisions (0)
No revisions yet.