loading...

📷 More on Screenshots with JavaScript in Node.js (creating PDFs)

benjaminmock profile image Benjamin Mock ・1 min read

Super useful puppeteer snippets 💭💭💭 (8 Part Series)

1) 📷 How to take a screenshot of a webpage with JavaScript in Node.js (using puppeteer) 2) 📷 More on Screenshots with JavaScript in Node.js (emulating devices) 3 ... 6 3) 📷 More on Screenshots with JavaScript in Node.js (creating PDFs) 4) 🗄️ The easiest way to scrape a website with Javascript (in Node.js) 5) 🍪 Screenshot or scrape webpages behind a login with JavaScript (in Node.js) 6) 🧭 Programmatically taking Screenshots while navigating & searching on webpages using JavaScript (puppeteer) 7) 👟 Executing JavaScript in the page context of puppeteer 8) 🚀 Performance measuring of a webpage with JavaScript in Node.js using puppeteer

In the previous example we created a png screenshot. But we can also generate PDFs in various formats!

// instead of calling await page.screenshot we now call
await page.pdf({
    path: 'codesnacks.pdf',
    format: 'A4'
})

For completeness, here's the full code to generate a PDF of a webpage in the A4 format:

// npm i puppeteer
const puppeteer = require('puppeteer');

// we're using async/await - so we need an async function, that we can run
const run = async () => {
  // open the browser and prepare a page
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  await page.goto('https://codesnacks.net/');

  await page.pdf({
    path: 'codesnacks.pdf',
    format: 'A4',
  });

  // close the browser
  await browser.close();
};

// run the async function
run();

Super useful puppeteer snippets 💭💭💭 (8 Part Series)

1) 📷 How to take a screenshot of a webpage with JavaScript in Node.js (using puppeteer) 2) 📷 More on Screenshots with JavaScript in Node.js (emulating devices) 3 ... 6 3) 📷 More on Screenshots with JavaScript in Node.js (creating PDFs) 4) 🗄️ The easiest way to scrape a website with Javascript (in Node.js) 5) 🍪 Screenshot or scrape webpages behind a login with JavaScript (in Node.js) 6) 🧭 Programmatically taking Screenshots while navigating & searching on webpages using JavaScript (puppeteer) 7) 👟 Executing JavaScript in the page context of puppeteer 8) 🚀 Performance measuring of a webpage with JavaScript in Node.js using puppeteer

Posted on by:

benjaminmock profile

Benjamin Mock

@benjaminmock

I'm Ben, a Frontend Developer from Germany working at ebay

Discussion

markdown guide