Hello All,
Today, I am going to explain how to convert the HTML to PDF in grails using Phantom JS.
Let’s start coding and follow the below steps.
1. I am going to use ubuntu operating system.
2. Install the PhantomJs on your computer. use below command :
sudo apt-get install phantomjs
3. We will also need the phantomjs script rasterize.js for converting the HTML to pdf. copy the rasterize.js from the (http://phantomjs.org) and paste any location of your computer or you can copy the js file below URL.
https://github.com/ariya/phantomjs/blob/master/examples/rasterize.js
4. We have completed all the pre-requirement step in achieving the objective.(HTML to PDF).
5. Write the code in our controller with the name convertHtmlToPdf() action.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
def convertHtmlToPdf() { String pathToPhantomJS = "/usr/bin/phantomjs" //path phantom js String pathToRasterizeJS = "/home/deepanker/phantomjs/rasterize.js" //path to your rasterize.js String paperSize = "A4" // Paper size String URL = "https://www.facebook.com/" //Change the url according to you want convert html page to pdf. File outputInstance = File.createTempFile("test", ".pdf") //file in which you want to save your pdf Process process = Runtime.getRuntime().exec(pathToPhantomJS + " " + pathToRasterizeJS + " " + URL + " " + outputInstance.absolutePath + " " + paperSize); int exitStatus = process.waitFor(); if (exitStatus != 0) { log.error("EXIT-STATUS - " + process.toString()); } response.contentType = "application/pdf" response.setHeader("Content-Disposition", "attachment; filename=test.pdf"); response.outputStream << outputFile.bytesString pathToPhantomJS = "/usr/bin/phantomjs" //path phantom js String pathToRasterizeJS = "/home/deepanker/phantomjs/rasterize.js" //path to your rasterize.js String paperSize = "A4" // Paper size String URL = "https://www.facebook.com/" //Change the url according to you want convert html page to pdf. File outputInstance = File.createTempFile("test", ".pdf") //file in which you want to save your pdf Process process = Runtime.getRuntime().exec(pathToPhantomJS + " " + pathToRasterizeJS + " " + URL + " " + outputInstance.absolutePath + " " + paperSize); int exitStatus = process.waitFor(); if (exitStatus != 0) { log.error("EXIT-STATUS - " + process.toString()); } response.contentType = "application/pdf" response.setHeader("Content-Disposition", "attachment; filename=test.pdf"); response.outputStream << outputFile.bytes response.outputStream.flush() response.outputStream.close() } response.outputStream.flush() response.outputStream.close() } |
6. Now, after hitting the convertHtmlToPdf()
action, automatically pdf file will download.
I have followed this URL: http://phantomjs.org/examples
Hope you will find this helpful.
Recent Comments