Visualforce Page Printable View

f02a62983ebcHow many times have you been asked to “can you make that a printable view, ya know, without the top and sidebar?” when you create a Visualforce Page?

If you have, you know the deal.  If not, oh don’t worry, you will before too much longer.

There is a quick and easy way to use the same VF page and APEX Controller that you already have built, using some Page variables, OutputPanels, some minor Javascript, and your “action” page attribute.

Step 1:  Create a Boolean variable and an “init” void method in your Controller

Something to the tune of:

public Boolean bolPrintableView {get;set;}

– and –

public void init() {
 String strPrintableView = ApexPages.currentPage().getParameters().get('print');
 bolPrintableView = (strPrintableView == '1');

Step 2:  Modify your VF Page attributes

<apex:page controller="YourPageController" showHeader="{!bolPrintableView}" sidebar="{!bolPrintableView}" action="{!init}">

Step 3:  Add a “Printable View” link to your VF Page

I will usually do this with an OutputPanel with the “rendered” attribute being set to the opposite of my controller’s printable view flag.  Doing this gets rid of the silly link for “Printable View” on your printed page along with any silly users clicking on the button again.

<apex:outputPanel rendered="{!NOT(bolPrintableView)}">
    <a href="/apex/YourVFPage?print=1" target="_blank">Printable View</a>

Step 4:  Use a quick Javascript function to immediately call the print dialog on load

Again I’ll usually wrap this in another OutputPanel with the “rendered” attribute being set to what the printable view flag is – we don’t want this firing on the normal view of the page!

<apex:outputPanel rendered="{!bolPrintableView}">

Optional Step 5:  Some pages just look better in Landscape mode – let’s use some CSS so it pops up like that by default.

<style type="text/css" media="print">
 @page { size: landscape; }

That’s it!  Works like a charm.  Questions?  Hit me below in the comments!