Newer Version Available
Add a Save as PDF Feature to a Visualforce Page
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.
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.