How to save a webpage as a PDF using Puppeteer?

To save a webpage as a PDF using Puppeteer, you can follow these steps:

  1. Install Puppeteer: If you haven't already, you can install Puppeteer by running the following command in your terminal:
npm install puppeteer
  1. Create a JavaScript file: Create a new JavaScript file (e.g. savePageAsPDF.js) and require Puppeteer at the top of the file:
const puppeteer = require('puppeteer');
  1. Use Puppeteer to take a screenshot of the webpage and save it as a PDF:
(async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://www.example.com', { waitUntil: 'networkidle2' }); await page.pdf({ path: 'example.pdf', format: 'A4' }); await browser.close(); })();
  1. Run the script: Run the JavaScript file in your terminal using Node.js by running the following command:
node savePageAsPDF.js

This will open a new instance of a headless Chrome browser using Puppeteer, navigate to the specified webpage, take a screenshot, save it as a PDF file named 'example.pdf', and then close the browser.

You can customize the PDF output further by specifying options such as page size, margins, and so on in the page.pdf() method. Check out the Puppeteer documentation for more details on available options.