Generate PDFs in Salesforce with Visualforce Pages

In Salesforce, generating PDFs allows users to create professional documents from their organization’s data, making it easier to share the data with others.

The feature of rendering a document in PDF is useful for reports, invoices, contracts, and other documents that need to be shared with customers.

In this Salesforce tutorial, we will learn how to generate PDFs in Salesforce using the Visualforce pages.

In this example, I will explain the entire process of generating the PDFs, which involves creating a Visualforce page and a Visualforce controller, and ultimately, viewing the generated PDF.

Use Salesforce Visualforce Pages to Generate PDF

In this example, we will generate a PDF for the lead records. Now, navigate to the Salesforce developer console and follow the steps below.

  1. Create a controller class, LeadPDFcontroller, that will handle the logic of the visualforce page. This controller will fetch the required lead records to populate the visualforce page.
public class LeadPDFController {
    public List<Lead> leads { get; private set; }

    public LeadPDFController() {
        leads = [SELECT Name, Company, Email, Phone FROM Lead LIMIT 100];
    }
}
  1. Now, create the Visualforce page following the code below. Visualforce allows us to create a page with a PDF rendering. The key is to use the renderAs=”pdf” attribute.
<apex:page controller="LeadPDFController" renderAs="pdf" showHeader="false">
    
    <h1>Lead Report</h1>
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Company</th>
                <th>Email</th>
                <th>Phone</th>
            </tr>
        </thead>
        <tbody>
            <apex:repeat value="{!leads}" var="lead">
                <tr>
                    <td>{!lead.Name}</td>
                    <td>{!lead.Company}</td>
                    <td>{!lead.Email}</td>
                    <td>{!lead.Phone}</td>
                </tr>
            </apex:repeat>
        </tbody>
    </table>
</apex:page>

In the PDF, we will display the record details in the form of a table, so inside the table component, we have inserted the values Name, Company, Email, and Phone.

  1. After creating the Visualforce page, we will see the preview. To do this, navigate to Setup > Visualforce Pages, open the PDF Visualforce page, and click the Preview button.
Render a Visualforce page as pdf in Salesforce

In the preview, you will see that the visualforce page is rendered in a PDF format.