Full webpage screenshot

For various reasons screenshots for webpages are needed. If automated test scripts fail, documentations must be created or in some other situations. With PhantomJS it is very easy to create these screenshots very fast by command-line. All what is needed a small JavaScript like this.

JavaScript

var phantom;
var console;
var system = require('system');
var fs = require('fs');
var page = require('webpage').create();

var Info = {
	isDate: function () {
		'use strict';
		var mydate = new Date().toDateString();
		return mydate;
	},
	isTime: function () {
		'use strict';
		var mytime = new Date().getTime();
		return mytime;
	}
};

var Target = {
	isLocation: function () {
		'use strict';
		var args = system.args,
		    mylocation = 'http://google.com';
		if (args.length > 1) {
			mylocation = system.args[1];
			console.log('[LOG] use argument location');
		} else {
			console.log('[LOG] use default location');
		}
		return mylocation;
	},
	isSaveFolder: function () {
		'use strict';
		var folder = 'log';
		if (!fs.exists(folder)) {
			console.log('[LOG] creat directory ' + folder);
			fs.makeDirectory(folder);
		}
		if (!fs.isWritable(folder)) {
			console.error('[LOG] ' + folder + ' is not writable!');
			phantom.exit(1);
		}
		return folder;
	}
};

page.open(Target.isLocation(), function (status) {
	'use strict';
	switch (status) {
	case 'success':
		console.log('[LOG] page open successfully' + Info.isDate());
		var folder = Target.isSaveFolder();
		page.render(folder + fs.separator + Info.isTime() + '.png');
		phantom.exit(0);
		break;
	case 'fail':
		console.error('[LOG] page not open successfully');
		phantom.exit(1);
		break;
	default:
		console.error('[LOG] fail to open with unknown status:' + status);
		phantom.exit(1);
		break;
	}
});

After save the script you can run it like:

# screenshot of softwaretester.info
$ phantomjs screenshot.js "http://softwaretester.info"