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:
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
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.