Generate reports and charts using HTML on the server-side

Did you know that you can render HTML on the server-side in a headless environment? The open-source project PhantomJS makes this possible.

PhantomJS is nothing else but a headless WebKit based browser. PhantomJS can render a webpage page in the same way as Safari (also WebKit based) does but in an environment without user interface.

The use cases for PhantomJS are in the area of:

This last enumerated use case is what makes possible generating reports and charts using HTML on the server-side.

Everyone knows that HTML is not the best environment to produce reports… but it is the most flexible. Due to the text based nature of HTML you can generate HTML pages from a variety of server-side environments. Due to this flexibility, you can get pretty creative with HTML reports representing basically any information you can imagine. Dedicate report generating packages usually lack this flexibility.

If the HTML report looks the way you like in a standard web browser (e.g. Safari, Chrome) it will look the same in PhantomJS. At the end of the day PhantomJS is just a headless web browser. You just need to automate PhantomJS in command line to load the HTML report you designed and render it as PDF. If you do this on the server-side, you’ll be able to server your users PDF reports in the same way you serve PDF reports generated by traditional reporting packages.

Some people use PhantomJS to generate / render also charts or complex visualizations on the server-side. Once generated on the server-side charts can be embedded in web pages (or even HTML reports) or sent by email as standard graphic .PNG files. There are a lot of nice charting engines for JavaScript such as D3.JS that can be leveraged also on the server side via PhantomJS.

Without further ado, let me show you how easy is to render a web page as .PNG file using PhantomJS.

Step 1.

Download and unzip the PhantomJS executable. Everything is self contained in a single executable without external dependencies: phantomjs.exe

Step 2.

Create a script file named renderpng.js and paste the following script:

	var page = require('webpage').create();
	page.open("http://www.codeavenger.com/", function() {
		page.render("codeavenger.com.png");
		phantom.exit();
	});

Step 3.

From you command prompt, type:

	phantomjs renderpng.js

That’s it! In your script folder you should notice the newly created .png file!

Have fun!

14 Jan 2017