How to convert HTML to PDF in grails using wkhtmltopdf plugin
Posted By : Tushar Paliwal | 20-Jun-2015
Hello there, in this tutorial I'm gonna share my knowledge about how can we convert HTML content into PDF content. Recently i faced a situation where i need to convert my project HTML content into CSV content.
I investigated over internet and found many solutions, in those solutions i got huge lines of code which was really hectic to understand finally i found i killer solution which is done using grails plugin. So now we will play with grails plugin which is wkhtmltopdf.
- Introduction
This plugin provides an easy inetgration of wkhtmltopdf library with grails, which is used to convert html content into pdf format. It can obviously convert GSP into PDF.
- Integration of wkhtmltopdf plugin with grails
- Step 1 :
Put an entry in BuildConfig.groovy file.
dependencies {
compile ":wkhtmltopdf:0.1.8"
}
- Step 2 :
For using this plugin we need to install wkhtmltopdf binary into system for this, you just need to run below commands.
1. sudo apt-get remove --purge wkhtmltopdf
2. sudo apt-get install openssl build-essential xorg libssl-dev
3. wget http://wkhtmltopdf.googlecode.com/files/wkhtmltopdf-0.9.9-static-i386.tar.bz2
4. tar xvjf wkhtmltopdf-0.9.9-static-i386.tar.bz2
5. sudo chown root:root wkhtmltopdf-i386
6. sudo cp wkhtmltopdf-i386 /usr/bin/wkhtmltopdf
Now put an entry in Config.groovy file.
-
Step 3 :
grails.plugin.wkhtmltox.binary = "/usr/bin/wkhtmltopdf"
Which is location of binary installed into system for wkhtmltopdf.
-
Step 4 :
The plugin provides a service WkhtmltoxService which contains a method makePdf() so we just need to create instance of this service and use this method for conversion.
def byte[] pdfData = wkhtmltoxService.makePdf(
view: templatePath,
marginLeft: 20,
marginTop: 35,
marginBottom: 20,
marginRight: 20,
headerSpacing: 10,
)
templatePath :This is location of html content which needs to be converted into PDF.
In above method makePdf() returns raw bytes of pdf content which can be used further processing or can be used by writing into the file.
I hope this will be meaningful for you, feel free to ask any query.
THANKS
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Tushar Paliwal
Tushar is a developer with experience in Groovy and Grails , Spring and enterprise Java Technologies.