a blog for those who code

Friday, 1 January 2016

Capture Screen of Web Pages through URL in Nodejs

In this post we will be discussing about how to capture screen of web pages through URL in Node.js. The following code snippet will convert any web URL into a Jpeg image. We will be using PhantomJS which is a headless WebKit scriptable with a JavaScript API. Since PhantomJS is using WebKit, a real layout and rendering engine, it can capture a web page as a screenshot.


To use PhantomJS in Node.js we will be using phantomjs-node (phantom npm module) which acts as a bridge between PhantomJS and Node.js. To use this module you need to install PhantomJS and it should be available in the PATH environment variable. If you get any error while installing please refer to How to solve Cannot find module weak in Nodejs. Then install phantom module by using the command npm install phantom.


Code :

var phantom = require('phantom');
var cLArguments = process.argv.slice(2);

if(cLArguments.length === 1) {
  var url = cLArguments[0];
}
if(cLArguments.length > 1) {
  var url = cLArguments[0];
  var file = cLArguments[1] + '.jpg';
}

console.log(url + ' ' + file);
phantom.create(function(ph) {
  console.log('Inside Phantom');
  ph.createPage(function(page) {
    console.log('Inside Create Page');
    page.set('viewportSize', {width: 1920, height: 1080});
    page.open(url, function(status) {
      if(status === 'success') {
        console.log('Success');
page.render(file);
ph.exit();
      }
    })
  })
}, {
    dnodeOpts: {
    weak: false
    }
})

In the above code we will be getting the URL and the name of the file from the command line. Then we are starting the PhantomJS process and creating web page out of it. Then we will be setting a view-port with the height and width. After that we will be opening the URL and if it is a success we will be rendering the file.


Please Like and Share the CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment

Contact Us

Name

Email *

Message *

Sponsers

Best Hosting Plans

CC License