This plugin provides an easy integration of wkhtmltopdf
, a command line tool to render HTML into PDF.
This enables you to write a Grails View in HTML as usual, but render as PDF.
wkhtmltopdf
and wkhtmltoimage
are open source (LGPLv3) command line tools to render HTML into PDF and various image formats using the Qt WebKit rendering engine.
These run entirely "headless" and do not require a display or display service.
http://wkhtmltopdf.org/
In addition to adding the plugin as dependency to your Grails project, the wkhtmltopdf
binary must be installed.
See instructions at http://wkhtmltopdf.org/ or install using your package manager (apt-get, yum, brew etc)
Finally make sure the following command works as expected:
wkhtmltopdf www.google.com test.pdf
Put the following line into your application.groovy
(or corresponding property in application.yml
) and adjust the path to your wkhtmltopdf binary (which wkhtmltopdf
)
grails.plugin.wkhtmltopdf.binary = "/usr/local/bin/wkhtmltopdf"
Typical paths:
OS | Path |
---|---|
OS X |
/usr/local/bin/wkhtmltopdf |
Linux |
/usr/bin/wkhtmltopdf |
Windows |
C:/local/wkhtmltopdf/wkhtmltopdf.exe |
Supported, but only with mail plugin 2.0.0.RC4. (See grails/grails-mail#16)
To stream the content of a Controller-action as PDF just call /some/someAction.pdf
class SomeController {
def someAction() {
def someInstance = SomeDomainObject.get(params.id)
render( filename:"File ${someInstance.id}.pdf",
view:"/some/someGspTemplate",
model:[someInstance:someInstance],
header:"/pdf/someHeader",
footer:"/pdf/someFooter",
marginLeft:20,
marginTop:35,
marginBottom:20,
marginRight:20,
headerSpacing:10)
}
}
Or create binary PDF data and use them for any other purpose
class SomeService {
static transactional = false
def doSomething() {
def byte[] pdfData = wkhtmltoxService.makePdf(
view: "/pdf/someGspTemplate",
model: [someInstance: someInstance],
header: "/pdf/someHeader",
footer: "/pdf/someFooter",
marginLeft: 20,
marginTop: 35,
marginBottom: 20,
marginRight: 20,
headerSpacing: 10)
// DO Something e.g. send as mail
//sendAsynchronousMail {
// multipart true
// to "[email protected]"
// subject "see PDF Attachment";
// attachBytes "PDF Attachment.pdf", "application/pdf", pdfData
// body "see my pdf attachment"
//}
}
}
Write your GSPs as usual, just make sure, that the urls to the assets are absolute and reachable by the host machine
Development mode:
grails.assets.url = "http://localhost:8080/assets/"
Production:
grails.assets.url = "https://example.com/assets/"
-
wkhtmltopdf
must work ( try:wkhtmltopdf www.myhomepage.com myhomepage.pdf
) -
For
v0.12.4
& Mac OS users wkhtmltopdf/wkhtmltopdf#3241 -
Not tested on Windows (except Windows 7)