Posted by Arjun on Wednesday 13th July 2016

Create WebPage Screenshots with Node.js and PhantomJS

create WebPage Screenshots Node.js PhantomJS

To create webpage screenshots we are going to use PhantomJs. PhantomJS is a headless WebKit scriptable with a JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG. in simple terms, PhantomJS is a web browser without a graphical user interface.

Assuming you've downloaded and installed PhatomJS, create a JavaScript file (screenshot.js for example) with the following contents:

var webpage = require('webpage').create();

webpage.open('https://arjunphp.com/', function() {
    webpage.render('arjunphp.png');
    phantom.exit();
});

Running this snippet from a web-browser won't work, we need to load this script using PhantomJS.so run the script from command line.

 phantomjs screenshot.js

That's all it, you should see a file in the same path as screenshot.js named arjunphp.png, open it and you should see a full page screenshot of arjunphp.com. We could save the page as a PDF document, JPEG, PNG, and GIF.

Out of the box PhantomJS provides configurable options for screen capturing. You can find the all available settings at - http://phantomjs.org/api/webpage/property/settings.html

var webpage = require('webpage').create();
// prevents the page from running any Javascript.
webpage .settings.javascriptEnabled = false;

// disable loading images
webpage.settings.loadImages = false;

webpage.open('https://arjunphp.com/', function() {
    webpage.render('arjunphp.png');
    phantom.exit();
});