Over content - provides a canvas for adding items such as text or graphics on top of the existing content.
Under content - provides a canvas for adding items under the existing content, such as watermarks.
These are accessed as 2 instances of PdfContentByte objects which can be manipulated using the PdfStamper - this is opposed to using just one PdfContentByte to add items. These objects are accessed using 2 methods in the PdfStamper class:
//declarations
...
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("StampedPdf.pdf"));
int pageNumber = 1;
PdfContentByte overContent = stamper.getOverContent(pageNumber); //over content
PdfContentByte underContent = getUnderContent(pageNumber); // under content
If we wanted to add a watermark to every page, it might look like this:
PdfReader reader = new PdfReader("OriginalPdf.pdf"); //reads the original pdf
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("WatermarkedPdf.pdf")); //create a stamper which writes a new pdf to file
PdfContentByte underContent; // PdfContentByte for accessing the under content of the original pdf pages
Image watermarkImage = Image.getinstance("watermark.jpg"); //image to be added as a watermark to the pages
img.setAbsolutePosition(100,300); //set the position of the watermark
int totalPages = reader.getNumberOfPages(); //get the total number of pages in the original pdf
//for every page in the original pdf
for(int currentPage = 1, currentPage < totalPages + 1; currentPage++)
{
underContent = stamper.getUnderContent(currentPage); //get the under content of the current page
under.addImage(watermarkImage); //add the watermark to it
}
stamper.close();
There are some important things to note here. Firstly, you MUST remember to close the stamper, or the outputted pdf will be corrupt once the program has finished.
Secondly, the page orientation can be a problem here, since if you have a pdf with different page orientations, the coordinate system will have to be altered accordingly. I add the image to point (100,300) here, but this would have to be rotated 90 degrees on a landscape page. You can avoid this by calling this method on the stamper before you use it:
stamper.setRotateContents(false);
This stops the coordinate system in the landscape pages from being represented as height * width instead of width * height so essentially adds the image to the landscape page as if it were portrait.
In-depth iText information can be found in Bruno Lowagie's excellent book iText In Action http://www.manning.com/lowagie2/
No comments:
Post a Comment