Save the Attachment as PDF using Apex Class and Visualforce Page on click button in Salesforce | How to save instantly my pdf visualforcepage as a file/attachment on click button in Salesforce | Rendering a VF page as PDF and saving it as an attachement in Salesforce

3,527 views

Hey guys, today in this post we are going to learn about How to save instantly my pdf visualforcepage as a file/attachment on click button in Salesforce.

You can use the PageReference.getContentAsPDF() method in Apex to render a Visualforce page as PDF data. Then use Apex code to convert that PDF data to an email attachment, a document, a Chatter post, and so on. To know more details about Render a Visualforce Page, Click Here.

 

Files we used to Save the Attachment as PDF using Apex Class in Visualforce Page →

savePdfVfp.vfp Visualforce It’s holds “Save Attachment” and “Cancel” Button Functionality.
savePdfVp.vfp Visualforce It is render as pdf from visualforce page.
saveVfPdfCtrl.apxc Apex Class Controller It is used to generate pdf using Bolb Apex and Save file as pdf in file/attachment in Salesforce.

 

Final Output →

save Pdf as a attachement in salesforce -- 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 Visualforce Page

Step 1:- Create Visualforce Page : savePdfVfp.vfp

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

savePdfVfp.vfp [Visualforce Page]

  1.   <apex:page standardController="Account"  extensions="saveVfPdfCtrl" showHeader="false" title="Quotation PDF" showQuickActionVfHeader="false" >
  2.     <apex:form >    
  3.         <center>   
  4.             <apex:commandButton action="{!pdfAction}"  value="Save Attachment"/> 
  5.             <apex:commandButton action="{!Cancel}"  value="Cancel" /> </center> <br/>
  6.         <center>
  7.             <apex:iframe height="700px"  width="1100px" src="/apex/savePdfVp?id={!MstrID}"/>
  8.         </center>
  9.     </apex:form><br/><br/><br/>
  10.     <footer class="slds-modal__footer"></footer>
  11. </apex:page>

 

Create Visualforce Page

Step 2:- Create Visualforce Page : savePdfVp.vfp

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

savePdfVp.vfp [Visualforce Page]

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

 

Create Apex Class Extension Controller in Visualforce

Step 3:- Create Apex Class : saveVfPdfCtrl.apxc

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

saveVfPdfCtrl.apxc [Apex Class Controller]

  1.       public class saveVfPdfCtrl {
  2.  
  3.     public String MstrId{GET;SET;}
  4.     public Account accObj{GET;SET;}
  5.  
  6.     public String PDFNo{GET;SET;}
  7.     public String EFNo{GET;SET;}
  8.     public BOOLEAN SHOW{GET;SET;}
  9.     public BOOLEAN showpdf{GET;SET;}
  10.     public ApexPages.PageReference page2{GET;SET;}
  11.     public String baseURL{GET;SET;}
  12.  
  13.     public PageReference Cancel()
  14.     {
  15.         PageReference Pdf = NEW PageReference('/'+MstrID);
  16.         pdf.setredirect(TRUE);
  17.         RETURN Pdf;
  18.     }
  19.  
  20.     public saveVfPdfCtrl(ApexPages.StandardController Controller){
  21.         baseURL = URL.getSalesforceBaseUrl().toExternalForm();
  22.         MstrId = ApexPages.currentPage().getParameters().get('id');
  23.         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 ];
  24.  
  25.     }
  26.  
  27.  
  28.  
  29.     public PageReference pdfAction()
  30.     {
  31.         PageReference savepage ;
  32.         savepage = Page.savePdfVp;
  33.         savepage.getParameters().put('id',MstrID);
  34.         system.debug('id:- '+MstrID);
  35.         BLOB pdfBlob;
  36.         IF (!Test.isRunningTest()) {
  37.             pdfBlob = savepage.getContent(); //generate the pdf BLOB
  38.         } ELSE { 
  39.             pdfBlob = BLOB.valueOf('Test');
  40.         }
  41.         List<ContentDocumentLink> notesattch = [SELECT id, ContentDocument.Title,LinkedEntityId FROM ContentDocumentLink WHERE LinkedEntityId =: MstrID ORDER BY ContentDocument.Title ASC];    
  42.         system.debug('notesattch## ' + notesattch);
  43.         IF(notesattch.size() > 0)
  44.         {
  45.             string title =  notesattch[0].ContentDocument.Title;
  46.             system.debug('title111 ' + title);
  47.             List<String> titleSplit = title.split('R');
  48.             //String FinalTitle = titleSplit[0]+'R0'+notesattch.size();
  49.             String FinalTitle = 'PO'+notesattch.size();
  50.             system.debug('FinalTitle22 ' + FinalTitle);
  51.             PDFNo=FinalTitle;
  52.  
  53.             ContentVersion conVer = NEW ContentVersion();
  54.             conVer.ContentLocation = 'S'; // TO USE S specify this document IS IN Salesforce, TO USE E FOR external files
  55.             conVer.PathOnClient = FinalTitle+'.pdf'; 
  56.             conVer.Title = FinalTitle; 
  57.             conVer.VersionData = pdfBlob;
  58.             system.debug('conVer@@ ' + conVer);
  59.             INSERT conVer;  
  60.  
  61.             Id conDoc = [SELECT ContentDocumentId FROM ContentVersion WHERE Id =:conVer.Id].ContentDocumentId;
  62.  
  63.             ContentDocumentLink conDocLink = NEW ContentDocumentLink();
  64.             conDocLink.LinkedEntityId = MstrID;
  65.             conDocLink.ContentDocumentId = conDoc; 
  66.             conDocLink.shareType = 'V';
  67.             INSERT conDocLink;
  68.             UPDATE accObj;
  69.  
  70.              PageReference pageRef = NEW PageReference( baseURL+'/lightning/r/Account/' + System.currentPageReference().getParameters().get('id')+'/view');
  71.             pageRef.setRedirect(TRUE);
  72.             //system.debug('pageRef@@@ ' + pageRef);
  73.             RETURN pageRef;
  74.  
  75.         }
  76.  
  77.  
  78.          ELSE{RETURN NULL;}
  79.  
  80.  
  81.  
  82.     }
  83.  
  84. }

 

Further post that would you like to learn in Salesforce

 

 

FAQ (Frequently Asked Questions)

How do I save a VF page rendered as a PDF?

If you try to render a Visualforce page as a PDF document, usually the PDF document is displayed in the browser. Place the “Render PDF” button on the Account page. If you click the button, the PDF page appears in the browser.

How do I email a VF page from Salesforce?

It is possible to send email using Visualforce by creating a custom controller to deliver the message. The Apex Messaging. SingleEmailMessage class handles the outbound email functionality available to Salesforce.

How do I convert files to attachments in Salesforce?

Switch to Attachments and Notes migrator app from App Menu . Click on “Attachments to Files” tab. range to convert the attachment to files.

Related Topics | You May Also Like

  • Our Free Courses →
  • 👉 Get Free Course →

    📌 Salesforce Administrators

    📌 Salesforce Lightning Flow Builder

    📌 Salesforce Record Trigger Flow Builder

 
 


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