Visualforce Force Download of PDF or Other Content
This next trick is one I’ve kind been keeping under my hat since it’s a nice polishing touch for some of my contest entries, but I figured I should probably share it with the world now (information must be free, etc). So we all know we can create Visualforce pages that render as PDF documents. It’s a pretty cool feature especially because business people love PDF files more than I love being a cynical ass (which is like… a lot). Though the one little annoyance is that normally when you create that PDF visualforce page the user is brought to it to view it where they then can download it. Many times they simply want to download it and attach it to an email or something, the viewing isn’t required and is generally just an extra few wasted seconds waiting for it to load so they can hit file->save as. I have found/built a nifty way to force download of the file using a combination of Apex and some tricky DOM manipulation. As an added bonus I’ll show you how to conditionally render the page as a PDF based on a URL param. Here we go!
The first thing we’ll need of course is our Visualforce page, we’ll keep it simple for this example. So here is our visualforce page
And now our controller
As noted in the comments the real secret here is setting the content disposition use the Apex getHeaders method. Now you are saying,
‘But Kenji if I call that page from a link it still opens in a new window it just forces the user to download the file. That’s not much better!’
Hope you dig it. Catch ya next time.