How to generate pdf from aura lightning component and send pdf file to (Notes & Attachments) Using Blob apex to generate pdf file in Salesforce | How to generate/view PDF using Lightning Components and send to “Notes & Attachments” using Apex Bolb to generate pdf in Salesforce

4,108 views

Hey guys, today in this post we are going to learn about How to generate/view PDF using Lightning Components and send to “Notes & Attachments” using Apex Bolb to generate pdf in Salesforce.

There are two methods to show a PDF in Lightning Component. First, you can create a Visualforce page and embed it in the Lightning component. Second is, usage of PDF. JS library to directly use lightning component to display the PDF. To know more about generate pdf from aura component, Click Here.

Files we used to generate pdf in Lightning Component →

SalesAccountOrderFormPDF.cmp Lightning Component It is used to display spinner loading on the page.
SalesAccountOrderFormPDFController.js JavaScript Controller It is hold Javascript doInit function to connect javascript controller to helper function.
SalesAccountOrderFormPDFHelper.js JavaScript Controller Helper It is hold Javascript SendOrderPdfHelper function to generate the pdf file from lightning component.
SendOrderPdfCtrl.apxc Apex Class Controller It is used for generate pdf using Bolb Apex in lightning component.
SalesAccountOrderFormPDFVfp.vfp Visualforce Page It is render as pdf from visualforce page.
SalesAccountOrderForm_Controller.apxc Apex Class Controller It is used for get get the current record of Account.

 

Final Output →

Why Should You Schedule Meeting?

🎯 If You Are Facing Any Of These 6 Challenges. Schedule Meeting With Me.

  • Learn Salesforce Development
  • Career Confusion
  • No Interview Call
  • Low Salary
  • No Promotion/Growth
  • No Finding New Job Opportunity
  • Why you stucking from past so many years in same company?

 

generate pdf from lightning component -- w3web.net
 

You can download file directly from github by Click Here.

 

 

Other related post that would you like to learn in Salesforce

 

  • Find the below steps ▾

 

Create Lightning Component

Step 1:- Create Lightning Component : SalesAccountOrderFormPDF.cmp

From Developer Console >> File >> New >> Lightning Component

SalesAccountOrderFormPDF.cmp [Lightning Component File]

  1.    <aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickActionWithoutHeader" access="global" 
  2.                 controller='SendOrderPdfCtrl' >
  3.  
  4.      <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
  5.     <aura:attribute name='recordId' type='Id'/>
  6.      <lightning:spinner class="slds-hide" aura:id="spinner" size="large" variant="brand" alternativeText="spinner" />
  7.  
  8. </aura:component>

 

Create JavaScript Controller

Step 2:- Create Lightning Component : SalesAccountOrderFormPDFController.js

From Developer Console >> File >> New >> Lightning Component >> JavaScript Controller

SalesAccountOrderFormPDFController.js [JavaScript Controller]

  1.    ({
  2. 	doInit : function(component, event, helper) {       
  3. 		helper.SendOrderPdfHelper(component,event,helper);
  4. 	},
  5. })

 

Create JavaScript Helper

Step 3:- Create Lightning Component : SalesAccountOrderFormPDFHelper.js

From Developer Console >> File >> New >> Lightning Component >> JavaScript Helper

SalesAccountOrderFormPDFHelper.js [JavaScript Helper File]

  1.    ({
  2.     SendOrderPdfHelper : function(component,event,helper) {
  3.         var recId = component.get('v.recordId');
  4.         // alert('recId ' + recId);
  5.         var action = component.get("c.attachedOrderFile");
  6.         action.setParams({ "orderId" : recId });
  7.         action.setCallback(this, function(response) {
  8.             var state = response.getState(); //fetch the response state
  9.             //alert('state11 ' + state);
  10.             if (state === "SUCCESS") {
  11.                 var result = response.getReturnValue();
  12.                 //alert('result ' + JSON.stringify(result));
  13.                 $A.get("e.force:closeQuickAction").fire();
  14.                 $A.get('e.force:refreshView').fire();
  15.  
  16.                 if(result == "Attachment Created Success"){                   
  17.                     var toastEvent = $A.get("e.force:showToast");
  18.                     toastEvent.setParams({
  19.                         title : 'Success',
  20.                         type: 'success',    
  21.                         message: 'Attachment Creatted Succussfully',  
  22.                     });
  23.                     toastEvent.fire();
  24.                 }
  25.  
  26.  
  27.             }
  28.             else {               
  29.             }
  30.         });
  31.         $A.enqueueAction(action); 
  32.     }
  33. })

 

Create Apex Class Controller

Step 4:- Create Apex Class : SendOrderPdfCtrl.apxc

From Developer Console >> File >> New >> Apex Class

SendOrderPdfCtrl.apxc [Apex Class Controller]

  1.    public class SendOrderPdfCtrl {
  2.    @AuraEnabled
  3.     public static String attachedOrderFile(String orderId){
  4.         Account orderItemList = [SELECT Id, Name, Phone, Industry, Rating, Description, TYPE, Website FROM Account WHERE Id=:orderId ];
  5.  
  6.          IF((orderItemList.Industry=='Technology') && (orderItemList.Type=='Technology Partner')){
  7.             PageReference PDf =  Page.SalesAccountOrderFormPDFVfp;//REPLACE attachmentPDf WITH the page you have rendered AS PDF
  8.             PDf.getParameters().put('Id', orderId);
  9.             PDf.setRedirect(TRUE);
  10.             Attachment attach = NEW Attachment();
  11.             BLOB b ;
  12.             b = PDf.getContent();
  13.             attach.Body = b;
  14.             attach.Name = orderItemList.Name +'.pdf';
  15.             attach.IsPrivate = FALSE;
  16.             attach.ParentId = orderId;
  17.             INSERT attach;
  18.  
  19.                     system.debug('attach### ' + attach);
  20.                     system.debug('orderItemList### ' + orderItemList);  
  21.              RETURN 'Attachment Created Success';
  22.  
  23.            }ELSE{
  24.               RETURN 'Attachment Created Failed';
  25.            }
  26.  
  27.         }
  28. }

 

Create Visualforce Page

Step 5:- Create Visualforce Page :
SalesAccountOrderFormPDFVfp.vfp

From Developer Console >> File >> New >> Visualforce Page

SalesAccountOrderFormPDFVfp.vfp [Visualforce Page]

  1.    <apex:page applyHtmlTag="false" showHeader="false" standardController="Account" extensions="SalesAccountOrderForm_Controller" renderAs="pdf" standardStylesheets="false"
  2.            applyBodyTag="false">
  3.     <head>
  4.         <style>
  5.             @page {
  6.             size: A4 portrait;
  7.             margin: 3mm;
  8.             }
  9.  
  10.             body {
  11.             font-family: sans-serif;
  12.             font-size: 11pt;
  13.             }
  14.             th {
  15.             min-height: 15px;
  16.             max-height: auto;
  17.             background:#ddd;
  18.             }
  19.             td {
  20.             min-height: 15px;
  21.             max-height: auto;
  22.             }
  23.         </style>
  24.     </head>
  25.     <body>
  26.         <table border="1" cellspacing="0" cellpadding="10" style="width: 100%; border-collapse: collapse; border-color: #000; text-align:left;">
  27.             <thead>
  28.                 <tr> 
  29.                     <th>Name</th>
  30.                     <th>Phone</th>
  31.                     <th>Industry</th>
  32.                     <th>Rating</th>
  33.                     <th>Description</th>
  34.                     <th>Website</th>
  35.                 </tr>     
  36.             </thead>
  37.  
  38.             <apex:repeat value="{!accObj}" var="accItem">                
  39.                 <tr width="100%" style="text-align: center;">
  40.                     <td style="text-align:left;"><apex:outputText value="{!accItem.Name}"/></td>
  41.                     <td style="text-align:left;"><apex:outputText value="{!accItem.Phone}"/></td>
  42.                     <td style="text-align:left;"><apex:outputText value="{!accItem.Industry}"/></td>
  43.                     <td style="text-align:left;"><apex:outputText value="{!accItem.Rating}"/></td>
  44.                     <td style="text-align:left;"><apex:outputText value="{!accItem.Description}"/></td>
  45.                     <td style="text-align:left;"><apex:outputText value="{!accItem.Website}"/></td>
  46.                 </tr>  
  47.  
  48.                 <apex:repeat value="{!accItem.Contacts}" var="con">                
  49.                     <tr width="100%" style="text-align: center;">
  50.                         <td style="text-align:left;"><apex:outputText value="{!con.Name}"/></td>
  51.                         <td style="text-align:left;"><apex:outputText value="{!con.FirstName}"/></td>
  52.                         <td style="text-align:left;"><apex:outputText value="{!con.LastName}"/></td>
  53.                         <td style="text-align:left;"><apex:outputText value="{!con.Email}"/></td>
  54.                         <td style="text-align:left;"><apex:outputText value="{!con.Phone}"/></td>
  55.                         <td style="text-align:left;"><apex:outputText value="{!con.Title}"/></td>
  56.                     </tr>                
  57.                 </apex:repeat> 
  58.             </apex:repeat>  
  59.  
  60.         </table>   
  61.     </body>        
  62. </apex:page>

 

Create Apex Class Controller

Step 6:- Create Apex Class : SalesAccountOrderForm_Controller.apxc

From Developer Console >> File >> New >> Apex Class

SalesAccountOrderForm_Controller.apxc [Apex Class Controller]

  1.    public class SalesAccountOrderForm_Controller {
  2.  
  3.     public String MstrId{GET;SET;}
  4.     public Account accObj{GET;SET;}
  5.  
  6.     public SalesAccountOrderForm_Controller(ApexPages.StandardController Controller){
  7.        MstrId = ApexPages.currentPage().getParameters().get('id'); 
  8.  
  9.         accObj = [SELECT Id, Name, Phone, Industry, Rating, Description, Website, TYPE, (SELECT Id, Name, FirstName, LastName, Email, AccountId, Phone, Title FROM Contacts) FROM Account WHERE Id =: MstrId ];
  10.  
  11.  
  12.     }
  13.  
  14. }

 

Further post that would you like to learn in Salesforce

 

 

FAQ (Frequently Asked Questions)

How do I render a VF page as a PDF?

We can render any page as pdf by adding renderAs attribute to and specifying “pdf” as value. renderAs value is name of any supported content converter. Currently PDF is the only supported content converter.

Can we generate PDF in aura?

You cannt generated PDF by using lightning component direcly .. use need to use the visualforce page and call its from the lightning exp. There are two methods to show a PDF in Lightning Component. First, you can create a Visualforce page and embed it in the Lightning component.

Can we render aura component as PDF?

Displaying the aura component in a separate tab then letting the user just download the page contents using regular browser functionality. Displaying the aura component in separate tab then using an external library to take screenshot of the page, then exporting as downloadable PDF.

Related Topics | You May Also Like

 
  

Our Free Courses →

👉 Get Free Course →

📌 Salesforce Administrators

📌 Salesforce Lightning Flow Builder

📌 Salesforce Record Trigger Flow Builder

👉 Get Free Course →

📌 Aura Lightning Framework

📌 Lightning Web Component (LWC)

📌 Rest APIs Integration



Hi, This is Vijay Kumar behind the admin and founder of w3web.net. I am a senior software developer and working in MNC company from more than 8 years. I am great fan of technology, configuration, customization & development. Apart of this, I love to write about Blogging in spare time, Working on Mobile & Web application development, Salesforce lightning, Salesforce LWC and Salesforce Integration development in full time. [Read full bio] | | The Sitemap where you can find all published post on w3web.net

Leave a Comment