Newer Version Available

This content describes an older version of this product. View Latest

Add a Save as PDF Feature to a Visualforce Page

You can add a Save as PDF element to a page to dynamically toggle between rendering the page as HTML or as a PDF file. You can also set the name for the PDF file.
The following page presents a list of contacts for an account. You can display it on screen, or download it as a PDF file by clicking the Save to PDF link.

This example has two important elements. First, the renderAs and contentType attributes of the <apex:page> component are set dynamically using expressions. The values of these expressions control into which format the page is rendered.

The other element is the <apex:form>, which provides a user interface for saving the page to PDF. The form has one element, an <apex:commandLink> that calls the saveToPdf action method. An <apex:param> component provides a name for the PDF file, which is used in the controller code to set the file name.

The form is only displayed when the page is rendered as HTML; it’s not visible in the PDF version. This display trick is accomplished by setting the rendered attribute on the <apex:form> component to false when the page is rendered as a PDF file.

Here’s the controller extension, which you can easily reuse in your own pages.

The main part of the extension is simple. The renderingService property controls whether the page is rendered in HTML or PDF. Its value defaults to null when the page is loaded, and changes to “PDF” if the saveToPdf action method is called. The renderAs attribute of the <apex:page> component references renderingService. When it’s anything other than “PDF” the page renders normally as HTML. When it’s “PDF” the page—you guessed it—renders as a PDF file.

The renderedContentType property provides a MIME type value that is used by the contentType attribute of the Visualforce <apex:page> component. Setting this value affects the server response. It adds an HTTP header that tells the client browser the format of the response—in this case, either HTML or PDF.

The renderedContentType property also sets the file name for the downloaded PDF file. It gets the file name from the renderedFileName property, which is set using the <apex:param> component in the page. Although it’s documented that appending “#” and a file name to the contentType sets the file name that’s sent to the client browser, this convention doesn’t work. Therefore, a header is set to provide the file name.

If you don’t need to set the file name for the PDF download, you can ignore the renderedContentType and renderedFileName properties. This simpler approach to adding a save to PDF function is demonstrated in Fonts Available When Using Visualforce PDF Rendering.