Watermarking PDFs in Visualforce

Battle Station Invoice
Keeping on the PDF and Trailhead theme, lets take a look at adding watermarks to our PDFs.  There was recently a developer boards post about watermarking a PDF and it dovetailed nicely into the previous posts.

Styling PDFs

Fortunately the Visualforce PDF renderer makes it really easy to do our watermarking.  Because we are using CSS to stylize the rest of the PDF we just need to update our styles.

Watermark Static Resource

The first thing we need to do is add our watermark image as a static resource.  We have to use a static resource (instead of something like a dynamically generated image URL) because PDFs don’t render unless the image is hosted on the platform.

Watermark static resource

Watermarking with CSS

We want to add this draft watermark if the Station_Status__c is anything other than “Complete”  To do this, we will need to add a background to the page and only have it in the CSS when the status isn’t that value.  To do this, our update @Page CSS looks like

@page {
    <apex:outputPanel layout="none" rendered="{!station.Project_Status__c != 'Complete'}">
        background: url("{!$Resource.BattleStationDraft}") no-repeat center center;
    </apex:outputPanel>

    @bottom-left {
        content: element(footer);
    }
}

The “secret” here is to use the outputPanel with a layout of none.  That means that the content inside of it will be be outputted without any additional HTML markup.

Watermarking PDF

See entire PDF.

This entry was posted in Development, Salesforce and tagged , , . Bookmark the permalink.
  • SF Dev

    HI,

    I am trying to watermark PDF document Saved in Salesforce not a visualforce rendered as PDF.
    I have tried to follow your instructions but did not get any sucess 🙁 Below you will find an example which i am trying currently?
    Could you please check where i am making a mistake ?

    .watermark {
    background-repeat: repeat;
    background-image: url(“{!URLFOR($Resource.watermarkExample)}”);
    background-position: center;
    }

    A

    Thanks in Advance !!

  • The problem is that the body is being rendered behind the PDF and the watermark is just not visible. You may be able to do this by making a floating div that is the full size of the page and putting the zindex of it above the iframe. This however will not scroll as you would like. In your case, it may be best to pass your PDF to a 3rd party like Cloudinary to apply the watermark directly to the data and then return the updated data back to the end user.