Home »
Node.js
Create PDF File from static HTML using Node.js and Puppeteer API
In this article, we will learn how to create a PDF File from static HTML using Node.js and Puppeteer API?
Submitted by Godwill Tetah, on April 30, 2019
In my last article, we learnt how to create a PDF file using Node.js and puppeteer? Today we will learn how to create a PDF file from static HTML using node.js and puppeteer? We will be using Node.js and puppeteer which is a node library.
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 and puppeteer installed via NPM (node package manager).
If you don't yet have Node.js installed, visit the Node.js official website and download for your PC version.
After download, you can quickly install the puppeteer module by opening a command prompt window and type: npm I puppeteer
To get started, let's install puppeteer:
Open the command prompt and type npm i puppeteer or npm install puppeteer
"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();
const htmlContent = // defines html/css content
`<body>
<style>
h1 {
background-color: green;
}
div {
background-color: lightblue;
}
p {
background-color: yellow;
}
</style>
<h1>CSS background-color example!</h1>
<div>
This is a text inside a div element.
<p>This paragraph has its own background color.</p>
We are still in the div element.
</div>
</body>`;
await page.setContent(htmlContent);
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.
The Output pdf file is then stored in the default Node.js directory with name test.pdf.
Output PDF file...