Monday, August 23, 2010

XML2PDF-Text as document watermark

This one is long due. Some time back I was working on a task that takes XML input, XSL stylesheet and runs Apache FOP processor to create a PDF document.
The PDF document should contain different sections like headers, footers, invoice lines (table) and a watermark. Each section may contain different blocks of data.
There were some different types of pages so I have developed a couple of XSL stylesheet to handle this. Please note that this was not a dynamic thing which can be used for any kind of XML2PDF conversion.

The main challenges I have faced with FOP.
1) For some reason, I had issues with my final PDF document layout. Even if everything thing looked fine, I had some overlap problems between lines. Finally figured out that was the problem with using Saxon Transformer Factory.
Setting the Xalan Transformer Factory as the default solved the problem.
System.setProperty("javax.xml.transform.TransformerFactory", "org.apache.xalan.processor.TransformerFactoryImpl");

 
2) Creating a dynamic watermark/banner.
i.e. I get some text data as part of the input document and I need to set this as PDF watermark.
Most of the APIs easily support images as watermarks but there's no direct support for using text content as watermark.
Luckily I found the solution for this by using Batik API to draw watermarks and integrated that in my stylesheet using "fo:instream-foreign-object" in FOP.
The below snippet shows the XSL code for this.

Here I wanted the watermark to be in the diagonal shape so I transformed the text, rotated it by 45degrees and did some final finishing. Here's a quick snapshot of the final outcome. You can see the 'Test Watermark' which is generated using the above XSL.

No comments: