PhantomJS and its “Render” function

Posted on by By Shraddha Tambe, in Business Intelligence, Data Visualization | 0

PhantomJS – The Headless Webkit browser & its “Render” function

In this blog, we will have a quick introduction of PhantomJS and talk about its “Screen Capture” feature to render webpages or parts of webpages into images or PDFs.

PhantomJS is a headless browser which has a JavaScript API. It can be used for headless web-testing, page automation, network monitoring and the likes. It supports various test frameworks like Jasmine, Capybara, QUnit, Mocha, WebDriver, YUI Test, BusterJS, FuncUnit, Robot Framework. It has a native support for various web standards like DOM handling, CSS selectors, SVG, JSON etc. It can access and manipulate webpages with the standard DOM API or with libraries like JQuery. As PhantomJS permits the inspection of network traffic, it is suitable to build various analyses on the network behavior and performance as well.

PhantomJS – Screen Capture using “Render” function

Among one of its many capabilities, is the capability to programmatically capture web contents, including SVG and Canvas and save them as images or PDFs.
PhantomJS uses WebKit which is an open source web browser engine. As it uses a real layout and rendering engine, it can capture a web page as a screenshot. Because PhantomJS can render anything on the web page, it can be used to convert contents not only in HTML and CSS, but also SVG and Canvas. The PDFs are generated with selectable texts and embedded fonts.
The function used for this is –

render(filename [, {format, quality}]) {void}

Renders the web page to an image buffer and saves it as the specified filename. The output format is automatically set based on the file extension.

Supported formats:

Quality:An integer between 0 and 100.

Working Example:

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

page.viewportSize = { width: 1920, height: 1080 };"", function start(status) {
page.render('google_home.jpeg', {format: 'jpeg', quality: '100'});

You can selectively render contents in the webpage by using another function –

clipRect {object}
This property defines the rectangular area of the web page to be rasterized when page.render is invoked. If no clipping rectangle is set, page.render will process the entire web page.

Working Example –

var webPage = require('webpage');
var page = webPage.create();
page.clipRect = {
  top: 14,
  left: 3,
  width: 400,
  height: 300

You might want to render only a single element, for example your content div or a SVG, for this, you can use the element.getBoundingClientRect and PhantomJS page.clipRect together to get the desired output.

Helical IT Solutions


Best Open Source Business Intelligence Software Helical Insight is Here


A Business Intelligence Framework

0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments