Skip to main content
Skip table of contents

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

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:

PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
int n = pdfDoc.getNumberOfPages();
PdfCanvas over;
PdfDictionary pageDict;
PdfArray mediaBox;
float llx, lly, ury;
// loop over every page
for (int i = 1; i 

The PdfDictionary we get with the getPage() 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.

Click How to extend the page size of a PDF to add a watermark? if you want to see how to answer this question in iText 5.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.