EPeak Daily

How one can generate an HTML desk and a PDF with Node & Google Puppeteer

0 9

Understanding NodeJS internally could be a little bit daunting (I do know it was for me as soon as). Node is a really highly effective language and it could do a whole lot of issues.

In the present day I needed to uncover the ability of Node’s built-in utility software referred to as fs (file system)

(function ($) { var bsaProContainer = $('.bsaProContainer-6'); var number_show_ads = "0"; var number_hide_ads = "0"; if ( number_show_ads > 0 ) { setTimeout(function () { bsaProContainer.fadeIn(); }, number_show_ads * 1000); } if ( number_hide_ads > 0 ) { setTimeout(function () { bsaProContainer.fadeOut(); }, number_hide_ads * 1000); } })(jQuery);

As per the fs docs:

The fs module supplies an API for interacting with the file system in a way intently modeled round customary POSIX features.

Which is only a fancy means of claiming that file system is a means in Node to work together with recordsdata for each learn and write operations.

Now file system is a humongous utility in NodeJS that has a whole lot of fancy options. On this article, nonetheless I’ll solely talk about 3:

  • Getting file info: fs.statSync
  • Deleting a file: fs.unlinkSync
  • Writing information to a file: fs.writeFileSync

One other factor we are going to cowl on this article is Google Puppeteer which is that this actually cool, slick software created by some superior of us at Google.

So what’s puppeteer? Effectively as per the docs, they are saying:

Puppeteer is a Node library which supplies a high-level API to manage headless Chrome or Chromium over the DevTools Protocol. It can be configured to make use of full (non-headless) Chrome or Chromium.

So it’s principally a software that allows you to do all of the cool browser associated issues on server. Like getting an internet site’s screenshots, crawling web sites, and producing pre-render content material for single web page purposes. You possibly can even do kind submissions by way of your NodeJS server.

Once more puppeteer is a big software, so we are going to cowl only a small however a really cool function of puppeteer. We’ll take a look at find out how to generate a pleasant PDF file primarily based on our generated HTML desk file. Within the course of we’ll study puppeteer.launch() and perceive a bit about web page() & pdf().

So to once more give a quick overview, issues we are going to cowl:

  • Producing stub information (for invoices) utilizing an internet software.
  • Creating an HTML desk with just a little little bit of styling with generated information in it, utilizing an automatic node script.
  • Studying about checking if a file exists or not utilizing fs.statSync
  • Studying about deleting a file by utilizing fs.unlinkSync
  • Studying about writing a file utilizing fs.writeFileSync
  • Making a PDF file of that HTML file generated utilizing Google puppeteer
  • Making them into npm scripts, for use later 🤗 🤩

Additionally earlier than we start right here is the complete supply code of the tutorial, for everybody to comply with alongside. You don’t have to write down something, however it’s best to write code together with this tutorial. That may show extra helpful & you’ll perceive extra. SOURCE CODE OF TUTORIAL

Earlier than we start, please guarantee that you’ve no less than the next put in in your machine

  • Node model 8.11.2
  • Node Package deal Supervisor (NPM) model 6.9.0

You don’t must, however you too can watch an introductory video (my first ever made) that talks concerning the fundamentals in studying, writing, and deleting a file in NodeJS. This may make it easier to perceive this tutorial. (Please do give me suggestions). 🤗

Let’s get began

Step 1:

In your terminal sort within the following:

npm init -y

This may initialize an empty challenge for you.

Step 2:

Second, in the identical folder, create a brand new file referred to as information.json and have some mocked information in it. You need to use the next JSON pattern.

You may get the mocked JSON stub information from right here. For producing this information I’ve used an superior software referred to as https://mockaroo.com/ It’s an internet information generator software.

The JSON information I’m going with has a construction like this:

"invoiceId": 1,
"createdDate": "3/27/2018",
"dueDate": "5/24/2019",
"deal with": "28058 Hazelcrest Heart",
"companyName": "Eayo",
"invoiceName": "Carbonated Water - Peach",
"value": 376
"invoiceId": 2,
"createdDate": "6/14/2018",
"dueDate": "11/14/2018",
"deal with": "6205 Shopko Courtroom",
"companyName": "Ounces",
"invoiceName": "Pasta - Fusili Tri - Colored",
"value": 285

You possibly can obtain the whole JSON array for this tutorial from right here.

Step 3:

Subsequent create a brand new file referred to as buildPaths.js

const path = require('path');
const buildPaths = {
buildPathHtml: path.resolve('./construct.html'),
buildPathPdf: path.resolve('./construct.pdf')
module.exports = buildPaths;

So path.resolve will soak up a relative path and return us absolutely the path of that individual listing.

So path.resolve('./construct.html'); will for instance return one thing like this:

$ C:UsersAdeelDesktoparticlestutorialbuild.html

Step 4:

In the identical folder create a file referred to as createTable.js and add the next code:

createTable.js script

I do know that’s a whole lot of code, however let’s divide it into chunks and begin understanding it piece by piece.

Go to line 106

In our strive/catch block we first verify if the construct file for HTML exists within the system or not. That is the trail of the file the place our NodeJS script will generate our HTML.

if (doesFileExist(buildPathHtml){} calls doesFileExist() technique which merely returns true/false. For this we use


This technique really returns details about the file like the scale of the file, when the file was created, and so forth. Nonetheless if we offer it an invalid file path, this technique returns as a null error. Which we use right here to our profit and wrap the fs.statSync() technique in a strive/catch. If Node is efficiently capable of learn the file in our strive block, we return true — in any other case it throws an error which we get in our catch block and returns false.

If the file exists within the system we find yourself deleting the file utilizing

fs.unlinkSync(filePath); // takes in a file path & deletes it

After deleting the file, we have to generate rows to place within the desk.

Step 5:

So first we import information.json which we do at line 3 & then on line 115 we iterate every merchandise utilizing map(). You possibly can learn extra about Array.prototype.map() right here.

The map technique takes a way createRow which takes in an object by every iteration and returns a string which has content material like this:

<td>bill id</td>
<td>bill identify</td>
<td>bill value</td>
<td>bill created date</td>
<td>bill due date</td>
<td>bill deal with</td>
<td>bill sender firm identify</td>

const row = information.map(createdRow).be a part of('');

The be a part of('') half is vital right here, as a result of I need to concatenate all of my array right into a string.

An nearly comparable precept is used for producing a desk on line 117 & then the html desk on line 119.

Step 6:

The vital half is the place we write to our file on line 121:

fs.writeFileSync(buildPathHtml, html); 

It takes in 2 parameters: one is the construct path (string) and the html content material (string) and generates a file (if not created; and whether it is created, it overwrites the already current file).

One factor to notice right here we’d not want Step 4, the place we verify if the file exists & if it does then delete it. It’s because writeFileSync does that for us. I simply added that within the code for studying functions.

Step 7:

In your terminal, go within the folder path the place you’ve got the createTable.js and sort

$ npm run ./createTable.js

As quickly as you run this script, it would create a brand new file in the identical folder referred to as construct.html You possibly can open that file in your browser and it’ll look one thing like this.

Generated HTML desk.

Cool proper? Thus far so good. 😅

Additionally you possibly can add an npm script in your package deal.json like this:

"scripts": {
"construct:desk": "node ./createTable.js"

This manner as an alternative of writing npm run ./createTable.js, you possibly can simply sort in npm run construct:desk.

Subsequent up: producing a PDF from the generated HTML file.

Step 8:

First issues first we have to set up a elaborate software, so go in your terminal in your utility folder and sort in

npm set up puppeteer

Step 9:

In the identical folder the place you’ve got recordsdata createTable.js , buildPaths.js & information.json, create a brand new file referred to as createPdf.js and add content material to it like beneath:

createPdf.js script

As we did with createTable.js script, let’s break this down into chunks and begin understanding this script step-by-step.

Let’s begin with line 40: right here we name a way init() which calls the strategy on line 30. One factor to deal with is that our init() technique is an async technique. Learn extra on this async operate.

First within the init() technique we name printPdf() technique which is once more an async technique, so now we have to attend for its response. The printPdf() technique returns us a PDF occasion which we then write to a file on line 33.

So what does the printPdf() technique do? Let’s dig deep in it.

const browser = await puppeteer.launch();
const web page = await browser.newPage();
await web page.goto(buildPathHtml, { waitUntil: 'networkidle0' });
const pdf = await web page.pdf({
format: 'A4',
margin: {
prime: '20px', proper: '20px', backside: '20px', left: '20px'}
await browser.shut();
return pdf;

We first launch a headless browser occasion utilizing puppeteer by doing the next:

await puppeteer.launch(); // this returns us headless browser

which we then use to open an internet web page:

await browser.newPage(); // open a clean web page in headless browser

As soon as now we have a clean web page open we are able to navigate to a web page. Since our internet web page is regionally in our system, we merely

web page.goto(buildPathHtml, { waitUntil: 'networkidle0' });

Right here waitUntil: 'networkidle0; is vital, as a result of it tells puppeteer to attend for 500/ms till there aren’t any extra community connections.

Notice: That is why we used path.resolve() to get absolute paths, as a result of as a way to open the net web page with puppeteer, we’d like an absolute path.

After now we have an internet web page opened within the headless browser on the server, we save that web page as a pdf:

await web page.pdf({ });

As quickly as now we have a pdf model of the net web page, we have to shut the browser occasion opened by puppeteer to save lots of assets by doing this:

await browser.shut();

& then we return the pdf saved, which we then write to the file.

Step 10:

In your terminal sort

$ npm ./createPdf.js

Notice: Earlier than operating the above script, be certain that you the construct.html file generated by createTable.js script. This ensures we all the time have the construct.html previous to operating the createPdf.js script. In your package deal,json do the next.

"scripts": {
"construct:desk": "node ./createTable.js",
"prebuild:pdf": "npm run construct:desk",
"construct:pdf": "node ./createPdf.js"

Now in the event you run $ npm run construct:pdf it would execute the createTable.js script first after which createPdf.js script. You possibly can learn extra on NPM scripts on their official docs.

Once you run

$ npm run construct:pdf

It is going to run and create a construct.pdf which is able to appear like this:

Generated .pdf file on operating createPdf.js script

And that’s it, we’re completed.

You will have discovered the next:

  • How one can verify if a file exists / tet file info (in Node)
  • How one can delete a file in Node
  • How one can write to a file
  • How one can use Google Puppeteer to generate a PDF file

Supply hyperlink

Leave A Reply

Hey there!

Sign in

Forgot password?

Processing files…