Home » Node.js

How to take a screenshot using Node.js and Puppeteer API (1)?

In this article, we will learn the first method how we can take a screenshot (screen capture) of a web page/website.
Submitted by Godwill Tetah, on May 29, 2019

In my last articles, I ended on how we can create PDF files using Node.js and puppeteer. We saw the various ways how we can create PDF files using Node.js and Puppeteer. As we already know, Puppeteer is a Node library developed by Google and provides a high-level API for developers.

Today, we will learn the first method of how we can take a screenshot (screen capture) of a web page/website?

Note: You should have Node.js and puppeteer installed in your PC.

With Node.js and puppeteer already up and running, let's get started.

Open a text editor and type the following code and save it with the file name app.js:

const puppeteer = require('puppeteer'); // loads the puppeteer module
(async () => {
	const browser = await puppeteer.launch()  // opens a virtual browser

	const page = await browser.newPage()  // creates a new page

	// you can also set dimensions  
	await page.setViewport({ width: 3000, height: 100})  // sets it's  dimensions
	await page.goto('file:///E:/HDD%2080%20GB%20DATA/CODING%20TUTORIALS%20AND%20CODES/go237.com/go237%20web/New%20design/index.html')  // navigates to the url

	// NB: You can use any url of your choice, 
	// I this example, I used a webpage that was already downloaded to facilitate the tutorial
	//but if it concerns a url on the www ,  internet connection is required to navigate to the website/web page
	await page.screenshot({ path: 'myscreenshot.png', fullPage: true })  // takes a screenshot 

	console.log ('done');  // console message when conversion  is complete!
	await browser.close() // closes the browser.
})()

The file should be saved in your Node.js directory.

From the code above, we first of all include the puppeteer module,

  • Launch a virtual browser
  • Open a new page with it's dimensions
  • Navigate to the url address
  • Take a screenshot and then finally close the browser

To convert the screenshot to PDF you can add this code before the line console.log ('done');

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

You can convert to other sizes like; letter, tabloid, A1, A2, A3, A4

Run the code by initiating the file at the command prompt like a regular Node.js file.

Following our code, done will be printed out on the command line console when the conversion is complete.

take-screenshot-1-0

The Output image file is then stored in the default Node.js directory with name myscreenshot.png.

Output file:

take-screenshot-1-1



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.