I know more or less how to do this, but I think I’m getting burned by the complexity of this command due to inexperience.
I’m trying to feed some raw html into wkhtmltopdf. I can do this from the command line like this:
echo "<p>Hello</p>" | wkhtmltopdf - ~/somePdf.pdf
That works fine, but how do I do this from a Java app? Here’s a couple things I’ve tried:
String[] cmd = { "echo", html.body(), "|", "wkhtmltopdf", "-", "/home/sam/yourPdf.pdf" };
Runtime.getRuntime().exec(cmd);
OR
Runtime.getRuntime().exec("echo " + html.body() + " | wkhtmltopdf - /home/sam/yourPdf.pdf");
Neither one of these produces a file in my home folder.
I’ve read that wkhtmltopdf will output to STDERR, but I’m not sure how to view that from Eclipse. I was told it should be available in my Console view, but I don’t see anything there.
Any help is appreciated, thanks!
Edit
The accepted answer will work for wkhtmltopdf, but for anyone else using the Play! framework who finds this post, there is a Play! module that generates a PDF based on a scala template. It works really well, but don’t forget to set media="print" in your stylesheet 🙂
You cannot do this directly, because you are running two commands and you create a pipe. Neither the
Runtime.exec()nor theProcessBuilder.command()methods are made for this. The easiest way to still achieve something akin to this from Java is to put all that stuff into a shell script and call that script withRuntime.exec().EDIT:
You can also skip the shell script and call
That save you writing the shell script, but you may have to fiddle with the quotes a little to get it right.