Generating and Attaching PDFs in Salesforce using Visualforce, Apex, and Aura Components
Salesforce provides multiple ways to generate and manage PDFs dynamically. In this blog, we’ll explore a solution that leverages Visualforce pages, Apex classes, and Aura components to generate an Account details PDF and attach it to the respective record in Salesforce.
- Overview of the Solution
Use Case
- Generate a PDF document containing Account details.
- Attach the generated PDF as a file to the Account record.
- Provide a Lightning UI for users to generate and save the PDF effortlessly.
Components Used
- Visualforce Page → Renders Account details as a PDF.
- Apex Controller → Generates the PDF and saves it as an attachment.
- Aura Component → Provides a button to trigger PDF generation.
- Visualforce Page for PDF Generation
The Visualforce page renders Account details dynamically in a PDF format using the renderAs=”pdf” attribute.
Code: Visualforce Page
<apex:page standardcontroller=”Account” extensions=”attachPDFToAccount” renderAs=”pdf” >
<apex:sectionHeader title=”Account Details PDF” />
<apex:pageBlock title=”Account Information”>
<apex:outputText value=”Account Name: {!Account.Name}” />
<br/>
<apex:outputText value=”Industry: {!Account.Industry}” />
<br/>
<apex:outputText value=”Phone: {!Account.Phone}” />
</apex:pageBlock>
</apex:page>
Key Features
- Uses the standard Account controller to fetch Account details.
- The renderAs=”pdf” directive ensures the output is automatically formatted as a PDF.
- The “attachPDFToAccount” is an Apex Class Name to bind the Apex Class in Visualforce Page
- Apex Class to Handle PDF Generation and Attachment
This Apex class is responsible for generating the PDF from the Visualforce page and attaching it to the Account record.
Code: Apex Class
public with sharing class attachPDFToAccount {
private ApexPages.StandardController controller;
private Id recordId;
public attachPDFToAccount(ApexPages.StandardController controller) {
this.controller = controller;
this.recordId = controller.getRecord().Id;
System.debug(‘Record ID: ‘ + recordId);
}
@AuraEnabled
public static void savePdfAttachment(Id recordId) {
System.debug(‘Processing PDF for Account ID: ‘ + recordId);
if (recordId == null) {
System.debug(‘No Account ID provided.’);
return;
}
try {
PageReference page = new PageReference(‘ https://orgfarm-53f7ce72cb-dev-ed–c.develop.vf.force.com /apex/SavePdfAsAttachment?id=’ + recordId);
Blob pdfBlob = page.getContentAsPDF();
ContentVersion cv = new ContentVersion();
cv.Title = ‘SampleAccount.pdf’;
cv.PathOnClient = ‘SampleAccount.pdf’;
cv.VersionData = pdfBlob;
cv.IsMajorVersion = true;
insert cv;
Id contentDocId = [SELECT ContentDocumentId FROM ContentVersion WHERE Id = :cv.Id].ContentDocumentId;
ContentDocumentLink cdl = new ContentDocumentLink();
cdl.ContentDocumentId = contentDocId;
cdl.LinkedEntityId = recordId;
cdl.ShareType = ‘V’;
insert cdl;
System.debug(‘Successfully attached PDF to Account ID: ‘ + recordId);
} catch (Exception e) {
System.debug(‘Error generating or attaching PDF: ‘ + e.getMessage());
}
}
}
Key Features
- Retrieves the Account record ID.
- Uses PageReference.getContentAsPDF() to generate the PDF.
- Stores the generated PDF in ContentVersion (modern replacement for Attachments).
- Links the generated PDF to the Account using ContentDocumentLink.
- The “SavePdfAsAttachment” is the Vf Page Name
- The PDF File URL is the org id of the visualforce page which we will get after preview the vf page.
- Aura Component for UI Interaction
The Aura component provides a user-friendly interface for generating and saving the PDF.
Code: Aura Component (.cmp file)
<aura:component controller=”attachPDFToAccount”
implements=”force:appHostable, flexipage:availableForAllPageTypes, flexipage:availableForRecordHome, force:hasRecordId”
access=”global”>
<aura:attribute name=”recordId” type=”Id” />
<aura:attribute name=”message” type=”String” />
<aura:attribute name=”vfUrl” type=”String”
default=”/apex/SavePdfAsAttachment” />
<aura:handler name=”init” value=”{!this}” action=”{!c.doInit}” />
<lightning:card title=”Save PDF”>
<p class=”slds-m-around_medium”>
<lightning:button label=”Save as PDF” variant=”brand” onclick=”{!c.savePdf}” />
</p>
<p class=”slds-m-around_medium”>
<lightning:formattedText value=”{!v.message}” />
</p>
<div>
<iframe src=”{!v.vfUrl}” width=”100%” height=”500px”></iframe>
</div>
</lightning:card>
</aura:component>
Key Features
- The “attachPDFToAccount” is the Apex Class
- By using an <iframe>, we can load the Visualforce page inside the Lightning component, displaying the PDF output.
- The “src” is dynamically set to the Visualforce page URL that generates the PDF.
- This allows users to preview the PDF within the Lightning UI.
Code: Aura Controller (.js file)
({
doInit: function (component, event, helper) {
var recordId = component.get(“v.recordId”);
component.set(“v.vfUrl”, ” https://orgfarm-53f7ce72cb-dev-ed–c.develop.vf.force.com /apex/SavePdfAsAttachment?id=” + recordId);
},
savePdf: function (component, event, helper) {
var recordId = component.get(“v.recordId”);
var action = component.get(“c.savePdfAttachment”);
action.setParams({ recordId: recordId });
action.setCallback(this, function(response) {
var state = response.getState();
if (state === “SUCCESS”) {
component.set(“v.message”, “PDF Saved Successfully!”);
} else {
component.set(“v.message”, “Error saving PDF.”);
}
});
$A.enqueueAction(action);
}
})
Key Features
- Dynamically sets the Visualforce page URL for generating the PDF.
- Calls the Apex method savePdfAttachment to attach the PDF.
- Displays a success or error message to the user.
- Summary
Component | Function |
Visualforce Page | Generates PDF for Account details |
Apex Class | Converts page to PDF and attaches it to Account |
Aura Component | Provides UI for generating and saving PDF |
This solution efficiently generates and stores Account details as a PDF file in Salesforce, improving document management and automation.