Home → How to create a simple Node app to generate PDF from HTML
How to create a simple Node app to generate PDF from HTML
Published: 4/4/2025
Node offers lots of options for data processing and conversion. One of the common scenarios is converting websites to PDF or PNG.
Available solutions
- Puppeteer
Let's get straight to the point!
Puppeteer
Here's how you can achieve that with puppeteer. It's a straightforward library to automate browsers like Chrome:
import puppeteer from 'puppeteer';
import fs from 'fs';
import path from 'path';
const html = fs.readFileSync(path.join('example', 'index.html'), 'utf-8');
const browser = await puppeteer.launch({ headless: 'new' });
const page = await browser.newPage();
await page.setViewport({ width: 768, height: 1024 });
await page.setContent(html, { waitUntil: 'domcontentloaded' });
const pdf = await page.pdf({
format: 'Letter'
});
await browser.close();
fs.writeFileSync('output.pdf', pdf);
console.log(`✅ PDF generated: output.pdf (${pdf.length} bytes)`);
That's it. As you can see, it is a mere 15 lines of code, but it does the job. Here are some important parameters you might want to tweak:
page.setViewport({
width: 768
height: 1024
})
page.pdf({
format: "Letter",
headerTemplate: "string"
footerTemplate: "string"
landscape: false,
scale: 1,
margin: {
top: 0,
left: 0,
right: 0,
bottom: 0,
}
})