How to create apex tests unit for create pdf from visualforce page and save as attachment in Salesforce | Apex unit test for pdf attachment in Salesforce | Unit test for apexpages.standardcontroller test class | Test class for pagereference method in salesforce

1,666 views

Hey guys, today in this post we are going to learn about How to create Apex Tests Unit for create pdf from visualforce page and save as attachment in Salesforce.

This page is a simple user interface. When you’re generating a PDF file from Apex, all the action is in the Apex code. To know more about Render a Visualforce Page as PDF from Apex, Click Here.

 

 

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?

 

apex tests unit for create pdf from visualforce page and save as attachment -- 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 Apex Class Controller

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

 

Create Apex Test Class Controller

Step 2:- Create Apex Class : saveVfPdfCtrlTest.apxc

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

saveVfPdfCtrlTest.apxc [Apex Class Controller]

  1.   @isTest
  2. public class saveVfPdfCtrlTest {
  3.     static testmethod void validateStandardController(){
  4.             Account acc = NEW Account();
  5.             acc.Name='test'; 
  6.             INSERT acc;
  7.  
  8.             Contact  con = NEW Contact();
  9.             con.FirstName='test';
  10.             con.LastName='test';
  11.             con.AccountId=acc.Id;
  12.             INSERT con;
  13.  
  14.            ContentVersion content=NEW ContentVersion(); 
  15.             content.Title='Header_Picture1'; 
  16.             content.PathOnClient='/' + content.Title + '.pdf'; 
  17.             BLOB bodyBlob=BLOB.valueOf('Unit Test ContentVersion Body'); 
  18.             content.VersionData=bodyBlob; 
  19.  
  20.             content.origin = 'H';
  21.             INSERT content;
  22.             ContentDocumentLink contentlink=NEW ContentDocumentLink();
  23.             contentlink.LinkedEntityId=acc.id;
  24.             contentlink.contentdocumentid=[SELECT contentdocumentid FROM contentversion WHERE id =: content.id].contentdocumentid;
  25.             contentlink.ShareType = 'I';
  26.             contentlink.Visibility = 'AllUsers';         
  27.             INSERT contentlink;
  28.  
  29.            ContentVersion cvlist = NEW Contentversion(); 
  30.             cvlist.Title = 'CZDSTOU'; 
  31.             cvlist.PathOnClient = 'test'; 
  32.             cvlist.VersionData = EncodingUtil.base64Decode('Unit Test Attachment Body'); 
  33.             List<ContentVersion> cvl = NEW List<ContentVersion>(); 
  34.             cvl.add(cvlist); 
  35.             INSERT cvl;
  36.  
  37.           Test.startTest(); 
  38.            ApexPages.Currentpage().getParameters().put('id',acc.Id);
  39.            ApexPages.StandardController sc = NEW ApexPages.StandardController(acc);
  40.            saveVfPdfCtrl controller1 = NEW saveVfPdfCtrl(sc);
  41.            controller1.pdfAction();
  42.            controller1.Cancel();
  43.  
  44.         Test.stopTest();
  45.  
  46.     }
  47. }

Further post that would you like to learn in Salesforce

 

 

FAQ (Frequently Asked Questions)

How to save a VF page rendered as PDF to notes and attachments?

Save the Attachment as PDF using Apex Class and Visualforce Page 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.

How do I save a Visual Studio project as a PDF?

You can export a report from Visual Studio Preview tab, WinForms Print Preview, and WPF Print Preview. Expand the drop-down list with export formats and select PDF File. Specify export options in the invoked PDF Export Options dialog and click OK.

Can Salesforce generate a PDF?

Generating PDFs in Salesforce is a powerful feature that can help you create custom reports, invoices, and other documents.

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