Home » Node.js

Generate PDF file using Node.js and Puppeteer API

In this article, we will learn how to create a PDF file using Node.js and puppeteer? We will be using Node.js and puppeteer which is a node library.
Submitted by Godwill Tetah, on April 27, 2019

Puppeteer is a Node library developed by Google and provides a high-level API for developers.

With Node.js already up and running, we will install puppeteer via NPM (node package manager).

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

To get started, let's install puppeteer:

Open the command prompt and type npm i puppeteer or npm install puppeteer

step 1 - Generate PDF file using Node.js and Puppeteer API

"npm" will download and install the puppeteer library together with other dependencies and Chromium.

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

// Include puppeteer module
const puppeteer = require ('puppeteer');
// file system node js module.
const fs = require ('fs');
(async function () {
	try {		
		// launch puppeteer API
		const browser = await puppeteer.launch();
		const page = await browser.newPage();
		// content of PDF file 
		await page.setContent ('WELCOME TO GOOGLE PUPPETEER API');
		await page.emulateMedia ('screen');
		await page.pdf ({
			// name of your pdf file in directory
			path: 'testpdf.pdf', 
			//  specifies the format
			format: 'A4', 
			// print background property
			printBackground: true
		});
		// console message when conversion  is complete!
		console.log ('done');
		await browser.close();
		process.exit();
	} catch (e) {
		console.log ('our error', e);
	}
} ) () ;

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

From the code above, we first of all include the puppeteer module and the file system module. The puppeteer API is then launched and it creates a new A4 page with file name test.pdf.

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

Following our code, done will be printed out when the conversion is complete.

Output Image 1 - Generate PDF file using Node.js and Puppeteer API

The Output pdf file is then stored in the default Node.js directory with name test.pdf.

Output Image 2 - Generate PDF file using Node.js and Puppeteer API

Output PDF file...

Output Image 3 - Generate PDF file using Node.js and Puppeteer API




Comments and Discussions!

Load comments ↻





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