Generate PDF in NodeJS using “node-phantom” module

27 / Jun / 2014 by Sakshi Tyagi 2 comments

PhantomJS is used to emulate browsers through command line, for generating PDFs, web page manipulation, headless testing and much more interesting stuff.

Npm provides us a module called “node-phantom” which helps us to use PhantomJS in our NodeJS application in a non-fussy way. A prerequisite for using this module is, you must have PhantomJS binary installed on your system.

Then you have to run npm install node-phantom and require the module var phantom = require('node-phantom') in your application.

Let us consider a code snippet which make use of this module for generating PDF:

[js]
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();
});
}
});
});
[/js]

Here, we first get the html content we want to display on pdf. “ejs” templating engine is used to render this html we have in “htmlFileContent” variable. Next, we start with

Next, we start with create(callback) method in which we get two parameters error and an object of phantomJS. Method “createPage” is called to create a webpage. It returns us the page object on which we can call several functions and set properties like:

1. page.settings : For setting values for enabling and disabling various
properties for example: javascriptEnabled, localToRemoteUrlAccessEnabled etc.
2. page.onResourceRequested() : For tracking the request, when a page requests a resource from a remote server.
3. page.onResourceReceived() : For tracking the response similarly.
4. page.onLoadFinished() : For debugging, to see if the requested resource is generated or not. Called when resource is loaded and return status.
5. page.set() : This method is a useful one, as it allow us to set values for various configuration variables for page for example “viewportSize”, “paperSize” and most important “content”.

Once the page or pdf generation is done, we call ph.exit() to terminate the pdf generation.

So, this was a very simple example of using the power, PhantomJS provides us with our NodeJS application.

Thanks 🙂

FOUND THIS USEFUL? SHARE IT

comments (2)

  1. Alex

    I’m working in MacOS X 10.11.2 El Capitan. I have phantomjs –version 2.1.1. I got the next error:
    phantom stdout: TypeError: undefined is not an object (evaluating ‘phantom.args[0]’)

    phantomjs://code/bridge.js:3 in global code

    Can you help me out to solve that?

    Reply
  2. Suhail

    Hi IntelliGrape,
    I tried to make pdf using your sample code. I have .hbs page for charts. I wants to create a pdf for those charts. It now working for me.
    Please advise.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *