Why is it so hard to print a PDF file in Java? Given that Java and PDFs normally play so well together (they are both, after all, pin-up software of code abd document portability respectively), I just assumed that it would be a very straight-forward thing to do. Certainly there are lots of available tools to create, edit, and read PDFs in Java (iText, JasperReports and others), but printing support seems to be sadly lacking.
I’ve looked at the javax.print API, but the conclusion conclusion I’ve reached after experimentating with my own code, is that it doesn’t support printing PDFs at all. Almost all the posts I’ve read on the web/discussion forums/mailing lists seem to concur with this fact. What a disappointment!
Several posts suggest using an external call to Acrobat, but my installed version (6.0) doesn’t seem to support the command line switches that are mentioned in a few places on the web.
As some context, I produce my PDF file using Apache FOP: starting with a simple XML file of my own flavour, I use an XSLT stylesheet to create a valid XHTML file. I then use another XSLT stylesheet to generate an XSL:FO file from the XHTML. Finally, I use FOP to generate my PDF file from the XSL:FO file. As cumbersome as it sounds, this is all working just fine. I can view and print my PDFs perfectly in Acrobat and Acrobat Reader.
The XSL Formatting Objects spec seems like a huge behemouth in terms of a standard (the entire XSL standard itself, of which XSL:FO is a part, probably weighs about as much as our car!). For my current project, however, I need the ability to control all sorts of typesetting features like leading, padding, font sizes, margins and borders, hyphenation of words and so on. The layout specification abilities of XSL:FO and FOP are largely up to this task, although FOP lacks a number of very useful parts of the XSL:FO spec in its current incarnation (0.20.5). I also use the intermediate formats for other reasons (e.g. the XHTML for web viewing, and to produce plain text output to send via email)
In the absence of java PDF printing support, I’ve currently settled on using XPDF’s pdftops tool (making an external Runtime.exec call) to convert my PDF to PostScript, and then printing the postscript file using the javax.print APIs.
This works OK, but not perfectly (I have some issues with page margins when converting to postscript), and I feel like there MUST be a better way. I have tried using FOP to produce PostScript from the XSL:FO files, but this doesn’t seem to work for my data (it just processes for ever without creating any useful output).
Anyway, be warned: printing PDFs in Java is much more of a headache than it should be!
No Comments so far
Leave a comment
Leave a comment
Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
