Salesforce PDF generation: A complete guide with Visualforce and Apex

Table of contents

    Salesforce PDF generation: A complete guide with Visualforce and Apex
    Generate and edit documents inside Salesforce

    Nutrient’s Salesforce integration handles document generation, editing, and signing natively.

    TL;DR

    This tutorial shows how to generate PDFs in Salesforce using Visualforce pages with the renderAs="pdf" attribute and Apex controllers. You’ll create a PDF from contact records and customize styling with CSS. For production document workflows with templates, eSignatures, and automation, consider Nutrient Documents for Salesforce, a low-code alternative that requires no custom Visualforce code.

    This tutorial creates a PDF table from Salesforce contact records(opens in a new tab). An Apex controller retrieves the data, and a Visualforce page renders it as a PDF.

    This tutorial uses contact records as an example, but the same techniques apply to other record types. Use these principles to generate reports, invoices, contracts, or other documents.

    What is Salesforce PDF generation?

    Salesforce PDF generation is the process of creating PDF documents directly from your customer relationship management (CRM) data using Visualforce pages and Apex code. You can generate reports, invoices, contracts, and other documents this way without leaving Salesforce.

    Each generated PDF captures the data at the time of generation. Saved PDFs don’t update when Salesforce records change; generate a new copy to include those changes.

    Nutrient Documents for Salesforce

    Nutrient Documents for Salesforce enables teams to generate documents from configured templates, edit them, and send them for signature from Salesforce. Administrators configure templates and record-page components before users can generate documents. See the document creation guide for the setup requirements and workflow.

    Signing uses Nutrient Document Web Services (DWS), which exchanges documents and signing updates with Salesforce. Review the DWS signing integration guide when assessing data handling.

    Start a free trial or contact Sales to discuss the workflow your team needs.

    What is a Visualforce page?

    Visualforce pages(opens in a new tab) are HTML pages that can be customized to display specific Salesforce data. A page designed for PDF output uses static content, such as text and tables. JavaScript-rendered charts aren’t supported by the PDF renderer.

    To create a Visualforce page, you’ll need to have a basic understanding of HTML, CSS, and Apex code. This example uses a custom Apex controller to retrieve the contact records.

    What is Apex?

    Apex(opens in a new tab) is a programming language used to write custom logic in Salesforce. You can use Apex code to create a PDF by writing code that extracts the data you need and formats it into a PDF file.

    Prerequisites

    • A Salesforce developer account(opens in a new tab) or sandbox for creating and testing the example.
    • Customize Application to edit Visualforce pages and Author Apex to edit the custom controller. See Salesforce’s page editing permissions(opens in a new tab).
    • Read access to the Contact and Account objects, the queried fields, and the records to include. Users also need access to the Visualforce page and Apex class. Broad View All Data or Modify All Data permissions aren’t required for this read-only example.

    Use the current API version available in your sandbox for the Apex class. The query uses WITH USER_MODE to enforce object and field permissions as well as record access. See Salesforce’s Apex security guidance(opens in a new tab).

    Step 1 — Create an Apex controller and Visualforce page

    The first step is to create a new Apex class and Visualforce page in your Salesforce organization.

    1. Once you’ve set up your Salesforce account, log in(opens in a new tab) to your organization.

    2. Open the Developer Console by going to Setup > Developer Console.

      Screenshot showing the Developer Console

    3. In the Developer Console, click File > New > Apex Class.

    4. 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 with sharing class PDFController {
      public List<Contact> contacts { get; private set; }
      public PDFController() {
      contacts = [
      SELECT Name, Account.Name, Phone
      FROM Contact
      WITH USER_MODE
      ORDER BY Name, Id
      LIMIT 100
      ];
      }
      }

      This controller retrieves up to 100 accessible contacts, ordered by name and ID. The limit keeps this example small; larger exports need their own filtering and batching design. with sharing enforces record sharing; WITH USER_MODE also checks object and field permissions. If a queried field is inaccessible, the query fails rather than exposing it.

    5. Save the Apex class by clicking File > Save.

    6. Now, create a new Visualforce page by clicking File > New > Visualforce Page.

    7. 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"
      showHeader="false" sidebar="false" standardStylesheets="false">
      <apex:dataTable value="{!contacts}" var="contact">
      <apex:column headerValue="Name" value="{!contact.Name}" />
      <apex:column headerValue="Account" value="{!contact.Account.Name}" />
      <apex:column headerValue="Phone" value="{!contact.Phone}" />
      </apex:dataTable>
      </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(opens in a new tab) specifies that the page should be rendered as a PDF. This table avoids form controls and Salesforce page-block styling that aren’t suited to PDF output.

    8. Save the Visualforce page by clicking File > Save.

    Step 2 — Test and preview the generated PDF

    Test the PDF generation to verify it works correctly.

    1. In Setup, enter Visualforce Pages in Quick Find. Open the page named PDFPage.

    2. Click the Preview button.

    3. The PDF opens or downloads according to your browser settings. Apex can retrieve its contents using PageReference.getContentAsPDF(); see Salesforce’s PDF rendering guide(opens in a new tab).

      Check the returned rows against your test records. Also test with the intended user’s permissions, including a contact without an account and a user who lacks access to a queried field.

      If you encounter errors, review your code and check the debug logs in the Developer Console.

    Step 3 — Customize PDF styling with CSS

    Next, customize the PDF output. Here are some options.

    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.

    1. Create a local file named PDFStyles.css.

    2. Add the following CSS:

      body {
      background-color: #f5f5f5;
      font-family: 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 CSS sets the background color, font family, font size, and table styles for the PDF.

    3. In Salesforce Setup, find Static Resources and click New. Name the resource PDFStyles, upload PDFStyles.css, and save it.

    4. 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.

    5. Save the Visualforce page by clicking File > Save.

    Preview the page again to check the table borders, spacing, and font in the rendered PDF.

    Customizing the PDF layout

    You can also customize the layout of the PDF output by modifying the Visualforce page. Here are some examples:

    • Use CSS @page rules for paper size and margins.
    • Use @page margin boxes for repeating headers and page numbers. Salesforce’s PDF formatting example(opens in a new tab) shows both.
    • Add images, logos, or other branding elements to the PDF by using the <apex:image> tag.

    With Visualforce, you control the content and formatting of the PDF, which suits documents you share outside Salesforce.

    Salesforce PDF generation workflow

    The PDF generation workflow in Salesforce follows four steps:

    1. Identify data sources — Standard objects (Accounts, Contacts) or custom objects
    2. Retrieve data — Use Salesforce Object Query Language (SOQL) queries in Apex to pull records
    3. Format output — Use PDF-compatible Visualforce components and static HTML to structure the layout
    4. Generate PDF — Set renderAs="pdf" on the Visualforce page

    For a low-code approach to this workflow, see Salesforce document generation.

    Advanced Salesforce PDF generation techniques

    TechniqueUse case
    Visualforce pagesCustom layouts, branding, complex formatting
    Apex codeDynamic content, conditional logic, personalized documents
    getContentAsPDF()Retrieve the rendered PDF as a Blob for storage or email
    External cloud servicesLarge-scale storage, additional processing (Amazon S3, Google Cloud)

    For advanced document workflows — templates, eSignatures, automation — consider Nutrient Documents for Salesforce instead of building custom Visualforce solutions.

    Limitations of PDF generation in Salesforce

    Salesforce’s built-in PDF generation has several limitations:

    • Limited styling — Visualforce supports custom PDFs, but styling options are restricted compared to dedicated PDF tools.
    • Complex layouts — Multipage PDFs with many tables, charts, and images are difficult to build in Visualforce.
    • Large datasets — Visualforce pages slow down with large datasets. Batch or paginate data for better performance.
    • No JavaScript rendering — Content that depends on JavaScript won’t appear in the PDF.
    • Font restrictions — Use the renderer’s supported font names(opens in a new tab). Web fonts aren’t supported.
    • Maintenance — Your team maintains the Apex queries, permissions, page markup, and layout tests. Review Salesforce’s PDF rendering limits(opens in a new tab) before deploying.

    For a template-based alternative to maintaining custom Visualforce pages, see Salesforce document generation.

    Best practices for Salesforce PDF generation

    PracticeWhy
    Use supported fontsUse sans-serif, serif, monospace, or Arial Unicode MS.
    Test with edge casesLong text, images, large datasets. Catch issues early.
    Add error handlingLog errors, provide fallback options.
    Optimize queriesFilter and bound SOQL queries; enforce user access.
    Compress imagesLarge images slow PDF generation.

    Troubleshooting

    • Formatting issues — Check CSS properties, element alignment, overlaps
    • Slow generation — Reduce external calls, simplify page logic
    • Garbled text — Use supported fonts only
    • Errors — Check Salesforce debug logs

    Conclusion

    This tutorial covered PDF generation in Salesforce using Visualforce and Apex. You learned to create a page that renders contact records as a PDF, customize styles with CSS, and modify layouts.

    For production document workflows, consider Nutrient Documents for Salesforce — it handles templates, generation, editing, and eSignatures without custom Visualforce code. Start a free trial or contact Sales.

    FAQ

    Create a Visualforce page with renderAs="pdf" and an Apex controller to retrieve your data. When you access the page, Salesforce renders it as a PDF that opens or downloads according to your browser settings.

    A button or link can open a Visualforce page with renderAs="pdf". Automated generation and storage need additional implementation, such as an Apex action called by Flow. Setting renderAs alone doesn’t schedule generation or save a file to a record.

    Add CSS through a Static Resource and link it to your Visualforce page using <apex:stylesheet>. You can customize fonts, colors, tables, headers, and footers. Use the renderer’s supported font names, such as sans-serif and serif, rather than assuming local or web fonts are available.

    Salesforce PDF generation has limited styling options, makes complex multipage layouts difficult, slows down with large datasets, and doesn’t support all fonts. For advanced document workflows, consider a dedicated solution like Nutrient Documents for Salesforce.

    Yes. Nutrient Documents for Salesforce is a low-code alternative that provides template-based document generation, editing, and eSignatures without custom Visualforce code. An administrator must first configure the templates and integration.

    Hulya Masharipov

    Hulya Masharipov

    Technical Writer

    Hulya is a frontend web developer and technical writer who enjoys creating responsive, scalable, and maintainable web experiences. She’s passionate about open source, web accessibility, cybersecurity privacy, and blockchain.

    Explore related topics

    Try for free Add document workflows to Salesforce