PDF Generation for Node.js using Puppeteer
Puppeteer is basically an automated Chromium instance for Node.js. It can be used for many things like automated UI testing, automated form submission and web browsing as well as automated screenshot and PDF generation.
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://www.github.com');
await page.pdf({path: 'github.pdf', format: 'A4'});
await browser.close();
})()
So, this basically launch a browser, open a page, print the page to a PDF file and close the browser.
Puppeteer supports a lot of (options)[https://github.com/puppeteer/puppeteer/blob/v2.1.1/docs/api.md#pagepdfoptions] for generating PDFs.
Puppeteer is not limited to loading web pages. You can also load local HTML file. I will experiment with this option here.
const path = require("path");
const puppeteer = require("puppeteer");
(async () => {
const htmlFile = path.resolve("./sample.html");
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto("file://" + htmlFile);
await page.pdf({ path: "./sample.pdf", format: "Letter" });
await browser.close();
})();
- Page break: puppeteer/puppeteer#5277
Node version >= 18.x
npm install
Just for first preview. The code is not optimized for production.
npm run astro:build
npm run build:gen
npm run prod:start
- http://localhost:8080 - Astro Page preview
- http://localhost:8080/pdf - PDF generation