How to Watermark a Visualforce PDF

Ever wanted to produce something like this, such as a quote or proof, in a Visualforce PDF?

Rendering PDFs is a very handy piece of Visualforce functionality, allowing the easy capture of Salesforce information into immutably formatted files that will display correctly wherever they’re opened. However, the PDF rendering capability has its quirks, not always displaying exactly as its HTML/CSS counterpart might.

One such quirk is watermarking a PDF that has tables. From the realm of HTML/CSS, watermarks should be fairly simple to produce: make all tables have transparent backgrounds, throw a background image to the body element, and viola! However, the minute that Visualforce page is converted to PDF, table transparency is gone. White space now overrides the body background where tables exist.

Fortunately, it is still possible to generate something that looks like a watermark, though there are constraints to the type of image file that will work. Essentially, the watermark image must overlay the text, so image files with transparency data are necessary. PNG files work the best because they preserve any level of transparency. GIF files could also work, but are not recommended because GIFs will only handle 100% transparency. Anything less than that becomes completely opaque and not very watermark-like.


The Ninja Trick:

In order to create a PDF watermark like the one shown in the image above, insert the following code almost verbatim into your Visualforce code, wrapped in something like a div or an apex:outputPanel:

<img src="{!URLFOR($Resource.Watermark)}" width="100%" height="100%" 
     style="position: fixed;background-repeat:repeat;left: 0cm; top:0cm; z-index:0"/>


Just make sure to replace the image URL with your static resource image. Here is a thumbnail with a link to the full-size version of the file I used as my watermark to get you started.

Note: I recommend making your watermark image the size of a PDF page, even if most of it is transparent. That way, you are guaranteed that your watermarks show up where they are expected. If you want multiple watermarks on one page, same recommendation applies. Just place all the watermarks you want (on a single page) inside the source watermark file (which should be a PDF page large).