This article was first published in March 2023 and was updated in December 2024.
In this tutorial, you’ll learn how to generate a PDF in Salesforce from a contact record. You’ll start by creating a Visualforce page that generates a PDF from a contact record in Salesforce. You’ll then use an Apex controller to retrieve the data, and a PDF rendering engine to generate the output.
Please note that contact records are the data source for this tutorial because they provide an easy-to-understand example of how you can generate PDFs using Salesforce. However, the techniques used in this article can also be applied to other types of records and data sources in Salesforce. You can use the same principles to generate and send reports, invoices, contracts, or other common document types.
Introduction to PDF generation in Salesforce
PDF generation is a crucial feature in Salesforce that enables users to create professional-looking documents from their sales data. With PDF generation, users can standardize and professionalize their content, making it easier to share and collaborate with others. This feature is particularly useful for creating reports, invoices, contracts, and other documents that need to be shared with customers or internal stakeholders.
By generating PDFs directly from Salesforce data, you can ensure your documents are always up to date and accurate. This eliminates the need for manual data entry and reduces the risk of errors. Additionally, PDF generation allows you to customize the layout and design of your documents, ensuring they reflect your brand and meet your specific requirements.
About Nutrient Salesforce SDK
If you work with PDF documents in Salesforce, Nutrient provides a client-side JavaScript library that can be integrated into a Lightning web component to enable opening, editing, and saving PDFs from a web browser. Some of our most popular features include the ability to:
-
View and edit PDF content directly in Salesforce
-
Collaborate on documents by highlighting text and adding notes or stamps
-
Organize documents by adding, deleting, rotating, or reordering pages
-
Programmatically fill PDF forms with information from Salesforce
-
Add an eSignature by drawing, typing, or uploading an image of your signature
-
Permanently redact sensitive information like email addresses, SSNs, phone numbers, and more
What is a Visualforce page?
Visualforce pages are HTML pages that can be customized to display specific Salesforce data. You can create a Visualforce page that will display your data in a table or a chart and then convert that page into a PDF.
To create a Visualforce page, you’ll need to have a basic understanding of HTML, CSS, and Apex code. You’ll also need to create a custom controller that will allow you to access the data you want to display on the page.
What is Apex?
Apex is a programming language used to write custom logic in Salesforce. You can use Apex code to create a PDF by writing code that will extract the data you need and format it into a PDF file.
Prerequisites
-
A Salesforce developer account or a sandbox with the necessary permissions to create and modify Visualforce pages and Apex classes.
-
Specifically, you’ll need the following permissions:
-
Customize Application permission — This permission is required to create Visualforce pages and Apex classes.
-
View All Data or Modify All Data permission — This permission is required to access or modify contact records in Salesforce. If you don’t have this permission, you may need to work with your Salesforce administrator to grant you the necessary access.
-
If you’re using a Salesforce developer account, you’ll have these permissions by default. However, if you’re using a sandbox or another type of organization, you may need to work with your Salesforce administrator to ensure you have the necessary permissions.
Step 1 — Setting up the project
The first step is to create a new Apex class and Visualforce page in your Salesforce organization.
-
Once you’ve set up your Salesforce account, log in to your organization.
-
Open the Developer Console by going to Setup > Developer Console.
-
In the Developer Console, click File > New > Apex Class.
-
In the new Apex class window, enter a name for your class, such as
PDFController
.
Copy and paste the following code into the class editor:
public class PDFController { public List<Contact> contacts { get; set; } public PDFController() { contacts = [SELECT Name, Account.Name, Phone FROM Contact]; } }
This code defines an Apex controller class that retrieves a list of contact records from the Salesforce database and stores them in a property called contacts
.
-
Save the Apex class by clicking File > Save.
-
Now, create a new Visualforce page by clicking File > New > Visualforce Page.
-
In the new Visualforce page window, enter a name for your page, such as
PDFPage
.
Copy and paste the following code into the page editor:
<apex:page controller="PDFController" renderAs="pdf"> <apex:form> <apex:pageBlock> <apex:pageBlockTable value="{!contacts}" var="contact"> <apex:column value="{!contact.Name}" /> <apex:column value="{!contact.Account.Name}" /> <apex:column value="{!contact.Phone}" /> </apex:pageBlockTable> </apex:pageBlock> </apex:form> </apex:page>
This code defines a Visualforce page that uses the Apex controller you just created to retrieve contact records and display them in a table. The renderAs
attribute specifies that the page should be rendered as a PDF.
-
Save the Visualforce page by clicking File > Save.
Step 2 — Testing the PDF generation
Now that you’ve created your Apex controller and Visualforce page, you can test the PDF generation functionality to make sure it works as expected.
-
Open a new browser window or tab and navigate to your Setup Home. Here you’ll see the recently created Visualforce page. Click the page name,
PDFPage
, to open it. -
Click the Preview button.
-
This will open a new browser tab and display a preview of the PDF. You can also use Salesforce APIs to retrieve the PDF programmatically.
The Visualforce page will load and display a table of contact records.
If you encounter any errors or issues, review the code and make sure you followed all the steps correctly. You can also check the debug logs in the Developer Console for any error messages or stack traces.
Step 3 — Customizing the PDF output
Now that you have working PDF generation functionality, you can customize the output to meet your specific requirements. The next section provides some examples of how to do this.
Customizing the PDF styles
By default, the PDF output generated by Visualforce uses a simple black-and-white style. However, you can customize the styles by creating a new CSS file and linking it to the Visualforce page.
-
In the Developer Console, create a new file by clicking File > New > Static Resource.
-
Enter a name for your file, such as
PDFStyles
, and select thetext/css
MIME type from the dropdown menu.
Copy and paste the following CSS code into the file editor:
body { background-color: #f5f5f5; font-family: Arial, sans-serif; font-size: 12px; } h1 { color: #006699; font-size: 18px; font-weight: bold; margin-bottom: 10px; } table { border-collapse: collapse; margin-bottom: 20px; width: 100%; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } th { background-color: #f2f2f2; } .footer { margin-top: 50px; text-align: center; }
This code defines a custom set of styles for the PDF output, including a custom background color, font family, font size, and table styles.
-
Save the CSS file by clicking File > Save.
-
Now, link the CSS file to the Visualforce page by adding the following code after the opening
<apex:page>
tag:
<apex:stylesheet value="{!$Resource.PDFStyles}" />
This code links the Visualforce page to the CSS file you just created using a static resource reference.
-
Save the Visualforce page by clicking File > Save.
Now, when you preview the Visualforce page, you’ll see the PDF output with the custom styles applied.
Customizing the PDF layout
In addition to customizing the styles, you can also customize the layout of the PDF output by modifying the Visualforce page. Here are some examples of how to do this:
-
Add headers and footers to the PDF by using the
<apex:pageHeader>
and<apex:pageFooter>
tags. -
Customize the page orientation and size by using the orientation and size attributes of the
<apex:page>
tag. -
Add images, logos, or other branding elements to the PDF by using the
<apex:image>
tag.
By using Visualforce to generate PDFs in Salesforce, you have the flexibility to control the content and formatting of the PDFs. This can be useful for creating professional-looking documents and reports and for making information from Salesforce easily accessible to your users.
Working with Salesforce data
When working with Salesforce data, it’s essential to understand how to effectively generate PDF documents that showcase your data in a clear and concise manner. Salesforce provides various tools and features that enable you to create custom PDF documents using your data. Here are some key considerations when working with Salesforce data:
-
Data sources — Identify the data sources you want to use for your PDF document. This could be a specific Salesforce object, such as Accounts or Contacts, or a custom object you’ve created. Understanding your data sources is crucial for accurate and relevant PDF content.
-
Data retrieval — Use Apex code or Visualforce to retrieve the data from your data sources. You can use Salesforce Object Query Language (SOQL) to query your data and retrieve the necessary information. This step ensures your PDF documents are populated with the most current and accurate Salesforce data.
-
Data formatting — Format your data to ensure it’s presented in a clear and concise manner. You can use Visualforce components, such as tables and charts, to display your data in a visually appealing way. Proper formatting enhances readability and professionalism in your PDF documents.
-
PDF generation — Use the
renderAs
attribute in Visualforce to generate a PDF document from your data. You can also use Apex code to generate a PDF document programmatically. This flexibility allows you to tailor the PDF generation process to your specific needs and workflows.
By following these steps, you can effectively work with Salesforce data to generate high-quality PDF documents that meet your business needs. Whether you’re creating reports, invoices, or other documents, leveraging Salesforce’s tools and features will help you produce professional and accurate PDF outputs.
Advanced PDF generation techniques in Salesforce
Salesforce’s built-in PDF generation feature is versatile, but advanced techniques can enable you to create more complex, customized, and interactive PDFs. These techniques allow you to tailor PDF output for various business needs, making Salesforce an even more powerful platform for document generation. Below are some advanced techniques for generating PDFs in Salesforce.
-
Using Visualforce pages — By creating Visualforce pages, you can design custom layouts for PDF output. This technique offers greater flexibility in positioning elements, adding styles, and controlling the structure of your document. Visualforce allows you to build sophisticated interfaces for PDF generation, ensuring your PDFs align with branding and format requirements.
-
Using Apex code — Apex code can be used to generate dynamic PDFs, enabling you to pull in data programmatically and format it based on user-specific criteria. This approach allows for real-time customization of content, such as personalized reports or invoices, and can incorporate logic to tailor the data shown in a PDF.
-
Using JavaScript libraries — Integrating JavaScript libraries with Salesforce can add interactive features to PDFs, such as forms, dynamic content, and clickable elements. Although JavaScript is limited within Salesforce’s PDF rendering (especially in Visualforce), libraries like PDF.js can be utilized externally if the PDF is processed outside of Salesforce. This approach is ideal when more complex interactions are needed within a document.
-
Using external cloud services — External services, like AWS S3 or Google Cloud Storage, allow you to store, manage, and manipulate large volumes of PDFs outside of Salesforce. These services can integrate with Salesforce for seamless handling of PDFs and provide additional storage, scalability, and document management features. For example, you can generate PDFs in Salesforce, send them to an external cloud for storage, and access them when needed via API integration.
By leveraging these advanced techniques, you can create highly customized PDFs in Salesforce for complex reporting, interactive forms, and branded documents. Each method provides added flexibility, enabling you to meet unique business requirements and enhance the overall user experience.
Limitations of PDF generation in Salesforce
There are, however, several limitations of PDF generation in Salesforce that are important to consider:
-
Customizability — There aren’t a lot of customization options available when creating PDFs using Salesforce’s built-in PDF generation features. Although Visualforce offers a method for producing customized PDFs, the styling options are more limited than those offered by other tools, and the finished PDF might not be as polished or expert-looking.
-
Complex layouts can be challenging — Visualforce works best with straightforward, simple PDF layouts. If you need to create a complicated, multipage PDF with lots of tables, charts, and images, it might be challenging to do so using only Visualforce.
-
Large data sets — When working with large data sets, Visualforce pages may become sluggish and difficult to navigate. Consider alternative options, such as batching or paginating the data, if you need to create PDFs from very large data sets.
-
Limited API accessibility — Since the PDF rendering engine cannot be directly accessed through Salesforce’s APIs, creating PDFs from data stored there may be more challenging than in other settings.
-
Lack of support for specific fonts — If your Visualforce page or data uses one of these fonts, problems may arise because Salesforce’s PDF generation engine doesn’t support it.
-
Maintenance issues — As they get bigger and more complex, Visualforce pages can be complicated and challenging to maintain. It may also become more difficult to maintain Visualforce-based PDFs in the future as Salesforce continues to develop and deprecates older technologies in favor of newer ones.
Best practices and troubleshooting for PDF generation in Salesforce
To ensure your PDF generation in Salesforce is reliable and efficient and produces high-quality output, it’s essential to follow best practices and troubleshoot potential issues. Below are some tips to help you optimize the PDF generation process.
Best practices
-
Use supported fonts and font sizes
Ensure the fonts and font sizes you choose are supported by Salesforce’s PDF rendering engine. Unsupported fonts may not render correctly, leading to layout issues. Stick to standard fonts such as Arial, Times New Roman, or other system-supported fonts for consistent results.
-
Thoroughly test the PDF generation feature
Regular testing is critical to ensuring your PDFs are being generated as expected. Test various data sets, layouts, and styles across different scenarios to ensure the output is correct. Consider testing edge cases (e.g. long text, images or complex data structures) to identify potential problems early on.
-
Implement error handling mechanisms
Adding error handling mechanisms is essential for troubleshooting issues with PDF generation. Implement proper logging to capture any errors that occur during the generation process. Additionally, providing user-friendly error messages will help users understand issues, and fallback options (e.g. retry or alternative methods) can enhance the user experience.
-
Optimize the PDF generation process
To improve performance and reduce latency, optimize your Visualforce pages and Apex code. Keep the layout design simple and avoid excessive complexity in terms of data formatting or custom styles. Use efficient data retrieval methods, such as batch processing or optimized SOQL queries, to speed up the generation process.
-
Limit the use of large images and external resources
While images can enrich the appearance of your PDFs, large images or many external resources can significantly slow down the PDF generation process. Optimize image sizes before including them in your PDFs, and consider lazy loading or compressing images where possible.
Troubleshooting tips
-
Check for formatting issues
If your PDFs aren’t rendering correctly, verify the layout and styling. Ensure elements like text blocks, tables, and images are properly aligned and that there are no overlaps. Check that you’re using supported CSS properties for styling in Visualforce pages.
-
Monitor PDF generation performance
If PDF generation is slow, review your code and Visualforce pages for optimization opportunities. For example, reduce the number of calls to external services and keep page logic minimal.
-
Validate fonts and styles
If text appears garbled or uses incorrect fonts, confirm that you’re using fonts compatible with Salesforce’s PDF rendering engine. Avoid embedding custom fonts that may not be supported.
-
Use debug logs
If you encounter errors or unexpected behavior, use Salesforce’s debug logs to trace and resolve issues. Debug logs can provide insight into the specific line of code or process causing failures, helping you quickly identify and fix problems.
By following these best practices and troubleshooting tips, you can ensure your PDF generation process in Salesforce runs smoothly and reliably. Proper testing, error handling, and optimization will help you deliver high-quality PDFs to your users while avoiding common pitfalls.
Conclusion
Generating PDFs in Salesforce is a powerful feature that can help you create custom reports, invoices, and other documents. In this tutorial, you learned how to create a Visualforce page that generates a PDF from contact records in Salesforce, using an Apex controller to retrieve the data and a PDF rendering engine to generate the output.
You also learned how to customize the PDF styles and layout to meet your specific requirements. With this knowledge, you can apply the same principles to generate PDFs from other types of data in Salesforce and build powerful, custom reports for your organization.
We offer a Salesforce PDF library that can be used to add PDF viewing, annotation, and editing to your native Salesforce application. To get started with our Salesforce PDF library, you can contact our Sales team.
FAQ
Here are a few frequently asked questions about generating PDFs in Salesforce.