HTML to PDF using PhantomJs and Grails

14 / Jul / 2015 by Arpit Jain 1 comments

Converting an html or web page into a pdf is never easy and you might face similar problem in your project as well. There is  a solution that works out of the box for this problem and all you need is installing PhantomJs on your system and calling it from your Grails or Java code.

Just follow below steps one by one and you are done with converting your html page into a good looking pdf file.

1. First you need to install PhantomJS on your system (assuming you are using linux system). use below command for this purpose.

sudo apt-get install phantomjs

2. You will also need phantomJS script “rasterize.js”  for converting web page to pdf.  Place this file into your system on any location of your choice and you can easily get this script  from below github url:

https://github.com/ariya/phantomjs/blob/master/examples/rasterize.js

3. Now, since you are done with the prerequisites of installing phantomJs and downloading rasterize.js, lets move to grails or java code. Create an endpoint that calls an external runtime process, this is the critical code that calls the operating system to run PhantomJS and execute the script.

Process process = Runtime.getRuntime().exec(pathToPhantomJS + " " + pathToRasterizeJS + " " + url + " " + pathToYourOutputFile + " " + paperSize);

Below is the grails code snippet that you can use as referance:

def downloadPdf() {
String pathToPhantomJS = "/usr/bin/phantomjs" //path to your phantom js
String pathToRasterizeJS = "/home/tothenew/Desktop/rasterize.js" //path to your rasterize.js
String paperSize = "A4"
String url = "https://www.google.co.in/" //url of your web page to which you want to convert into pdf
File outputFile = File.createTempFile("sample", ".pdf") //file in which you want to save your pdf

//TODO: also do exception handling stuff . i am not doing this for simplicity

Process process = Runtime.getRuntime().exec(pathToPhantomJS + " " + pathToRasterizeJS + " " + url + " " + outputFile.absolutePath + " " + paperSize);
int exitStatus = process.waitFor(); //do a wait here to prevent it running for ever
if (exitStatus != 0) {
log.error("EXIT-STATUS - " + process.toString());
}

response.contentType = "application/pdf"
response.setHeader("Content-Disposition", "attachment; filename=sample.pdf");
response.outputStream << outputFile.bytes
response.outputStream.flush()
response.outputStream.close()
}

Now all you need is hitting your controller action and watching your browser downloading pdf.

Furhter reading: If you want to explore phantomjs screen capture in more detail, you can refer to the example at below url:

http://phantomjs.org/screen-capture.html

FOUND THIS USEFUL? SHARE IT

comments (1 “HTML to PDF using PhantomJs and Grails”)

  1. Pingback: Diario Grails (Settimana 29 del 2015) | BME

Leave a comment -