SVGs, PDFs and Java

The need to create a variety of similar pages in a PDF file recently came about. Once again unique, once again related to d-touch. When such pages require rotated text, it becomes a whole new level of fun sorting out the co-ordinates and bounds.

A different approach seemed necessary and I found myself thinking how nice a template would be, just search and replace. Then it hit me: SVGs. Images in XML, with support for including actual images and text at any angle, size or position. Perfect. Graphically creating a first draft of the template took minutes.

The other benefit of using a graphical template is how easy it is to change the design and re-run the data through.

215 SVG files don’t quite leap into a PDF on their own though, and the two image packages I intended to use rather failed to manage. One slowly loaded each and every one before giving an error refusing to accept them as images, the other was quite happy they were valid images for merging to PDF but didn’t do anything after I pressed go.

I had manual options available I wasn’t about to jump at, such as saving each one as a PDF and using BullZip PDF Printer or similar to merge them slowly by hand.

The surprisingly simple and fast solution turned out to be Java. Running the Rasteriser from the Batik SVG Toolkit on the folder of the SVGs returned a folder of PDFs, a step closer but not quite there yet.

The final step was to write a small Java wrapper for the PDF Merger Utility from the PDFBox package. This basically consisted of scanning the directory of single page PDF files, adding each one as a source for the Merger, and running it.

Yes, that is a generic catch everything that goes wrong block. No, you shouldn’t use them 😛

To compile that you’ll be needing to use something like this

And something like this to run it

Leave a Reply