Generating PDF in Node.js

There are many methods to generate PDF in Node.js. In our example we are using the Phantom module. Phantom module is used for many things like generating PDF, web page manipulation, headless testing etc. NPM has a module called node-phantom for enabling us to use PhantomJS in NodeJS applications. 

Run the npm install command and require modules in your application.

npm install node-phantom
var html = ejs.render(htmlFileContent,
            {seller: "Sakshi Tyagi", buyer: "Test Buyer"});
 phantom.create(function (error, ph) {
    ph.createPage(function (error, page) {
      page.settings = {
        loadImages: true,
        localToRemoteUrlAccessEnabled: true,
        javascriptEnabled: true,
        loadPlugins: false
       };
      page.set('viewportSize', { width: 800, height: 600 });
      page.set('paperSize', { format: 'A4', orientation: 'portrait', border: '1cm' });
      page.set('content', html, function (error) {
        if (error) {
          console.log('Error setting content: ', error);
        }
      });
 
      page.onResourceRequested = function (rd, req) {
        console.log("REQUESTING: ", rd[0]["url"]);
      }
      page.onResourceReceived = function (rd) {
        rd.stage == "end" && console.log("LOADED: ", rd["url"]);
      }
      page.onLoadFinished = function (status) {
        page.render(url, function (error) {
          if (error) console.log('Error rendering PDF: %s', error);
          console.log("PDF GENERATED : ", status);
          ph.exit();
          cb && cb();
        });
      }
    });
  });

First we get the content we want to be displayed on the pdf. To render this “ejs” template engine is used as a htmlFileContent variable. In create(callback) we get an error and an object of the phantomJS method. It will return a page object. Many functions like page.settings, page.onResourceRequested(), Page.set() etc.  Call the ph.exit() method just after the PDF is generated.