Changing a PDF on the fly using Sitecore Media Request

Some time ago I had a fun challenge for a customer. They wanted a legal notice pdf to be appended to all PDF files which was downloaded from specific parts of the media library on the fly.

They also wanted to be able to update the legal notice pdf and use a different one for different parts of the media library.

The same concept could also be used for adding a watermark to a pdf or maybe removing all above the first three pages for non-authenticated users etc.

For altering the PDF’s I use WebSuperGoo’s ABCpdf8.

Handling the Sitecore Media Request

First thing is to catch all media requests using the Sitecore media request event, media:request.

This event is NOT in a normal out-of-the-box web.config but you can add it yourself as shown below.

Create the class..

Next thing to do is to determine if the request is for a pdf file in a specific part of the media library (using the media items path) if not exit quickly otherwise append the relevant pdf to the start of the requested pdf document.

The LegalNoticeArea class here is just a carrier class for a pdf file and a string for the root path of the media library for which this pdf has to be added.

The LegalNoticeSettings is a settings item retrived through the link database. I will not show the implementation of this now.

The code is extremely fast, but it still it adds about 1-200 milliseconds for the pdf to start downloading. This should be okay though, since the users will accept a slower response time just fine when clicking a download button compared to when they are clicking a link. Of course it take up some server resources which should be considered if pdf files are downloaded several times a second. Also make sure to cache the settings item somehow or read it in a quick manner so it does not slow up the request unnecessary.

One might argue that the best solution would be to append/modify the pdf before it was stored in the media cache but then the media cache would have to be cleared as soon as the editors alters the pdf to be appended and this does not seem so smart an idea after all.

Feel free to comment or let me know if I should post the whole code in a zipped project.

Avatar photo

Anders Laub Christoffersen

Anders has been working with Sitecore for over a decade and has in this time been the lead developer and architect on several large scale enterprise solutions all around the world. Anders was appointed the title of Sitecore Technical MVP in 2014 and has been re-appointed the title every year since then.

4 thoughts on “Changing a PDF on the fly using Sitecore Media Request

  1. Very smart.
    I really like the way how you add the legal notice. And as you said/wrote – this is perfect for adding watermarks…

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*
Website