How to extend the page size of a PDF to add a watermark?

Tags: page sizewatermarkpage boundariesiText 5

I want to add a watermark to a document that doesn't cover any of the existing text (not even if the watermark is transparent). Instead, I want to add a small margin on the left side of each page and add the watermark there. Is this possible?

Posted on StackOverflow on Apr 21, 2015 by Eduardo

I will break up the question in two parts and I'll skip the part about the actual watermarking as this is already explained elsewhere on StackOverflow and in this book. I will focus on the extra requirement to add an extra margin to the right.

Take a look at the primes.pdf document. This is the source file we are going to use in the AddExtraMargin example with the following result: primes_extra_margin.pdf. As you can see, a half an inch margin was added to the left of each page.

This is how it's done:

public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
    PdfReader reader = new PdfReader(src);
    int n = reader.getNumberOfPages();
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
    // properties
    PdfContentByte over;
    PdfDictionary pageDict;
    PdfArray mediabox;
    float llx, lly, ury;
    // loop over every page
    for (int i = 1; i <= n; i++) {
        pageDict = reader.getPageN(i);
        mediabox = pageDict.getAsArray(PdfName.MEDIABOX);
        llx = mediabox.getAsNumber(0).floatValue();
        lly = mediabox.getAsNumber(1).floatValue();
        ury = mediabox.getAsNumber(3).floatValue();
        mediabox.set(0, new PdfNumber(llx - 36));
        over = stamper.getOverContent(i);
        over.setColorFill(new GrayColor(0.5f));
        over.rectangle(llx - 36, lly, 36, ury - llx);

The PdfDictionary we get with the getPageN() method is called the page dictionary. It has plenty of information about a specific page in the PDF. We are only looking at one entry: the /MediaBox. This is only a proof of concept. If you want to write a more robust application, you should also look at the /CropBox and the /Rotate entry. Incidentally, I know that these entries don't exist in primes.pdf, so I am omitting them here.

The media box of a page is an array with four values that represent a rectangle defined by the coordinates of its lower-left and upper-right corner (usually, I refer to them as llx, lly, urx and ury).

In my code sample, I change the value of llx by subtracting 36 user units. If you compare the page size of both PDFs, you'll see that we've added half an inch.

We also use these coordinates to draw a rectangle that covers the extra half inch. Now switch to the other watermark examples to find out how to add text or other content to each page.