Friday, June 10, 2016

Create and Email a PDF with Salesforce.com

PdfEmailer Visualforce Page
The Visualforce page simply allows the user to enter their email address and select a sample Account from the picklist. This is Account that is passed to the PdfGeneratorTemplate Visualforce page to generate the PDF.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<apex:page controller="PdfEmailController">
  <apex:sectionHeader title="PDF Example" subtitle="Email a PDF" 
    description="Example of how to email a dynamically generated PDF."/>
 
  <apex:form >
    <apex:pageMessages />
    <apex:pageBlock title="PDF Input">
 
      <apex:pageBlockButtons >
        <apex:commandButton action="{!sendPdf}" value="Send PDF"/>
      </apex:pageBlockButtons>
 
      <apex:pageBlockSection >
 
        <apex:pageBlockSectionItem >
            <apex:outputLabel value="Email to send to" for="email"/>
          <apex:inputText value="{!email}" id="email"/>
        </apex:pageBlockSectionItem>
 
        <apex:pageBlockSectionItem >
            <apex:outputLabel value="Account" for="account"/>
            <apex:selectList value="{!accountId}" id="account" size="1">
                 <apex:selectOptions value="{!accounts}"/>
            </apex:selectList>
        </apex:pageBlockSectionItem>
 
      </apex:pageBlockSection>
 
    </apex:pageBlock>
  </apex:form>
 
</apex:page>
PdfEmailerController
The Controller passes the Account ID that the user entered as a parameter for the Visualforce page being generated. It let creates the attachment from the PDF content. The Body of the attachment uses the Blob returned from the PageReference’s getContent method. You could also use the getContentAsPDF method which always returns the page as a PDF, regardless of the component’s renderAs attribute. However, this method always seems to throw an error in the test class. See the PageReference documentation for more info. The method then constructs the SimpleEmailMessage object and then sends it on its way to the recipient’s inbox.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
public with sharing class PdfEmailController {
 
  public ID accountId {get;set;}
  public String email {get;set;}
 
  public List<SelectOption> accounts {
    get {
      if (accounts == null) {
        accounts = new List<SelectOption>();
        accounts.add(new SelectOption('0017000000LgRMb','United Oil & Gas Corp.'));
        accounts.add(new SelectOption('0017000000LgRMV','Burlington Textiles Corp of America'));
      }
      return accounts;
    }
    set;
  }
 
  public PageReference sendPdf() {
 
    PageReference pdf = Page.PdfGeneratorTemplate;
    // add parent id to the parameters for standardcontroller
    pdf.getParameters().put('id',accountId);
 
    // the contents of the attachment from the pdf
    Blob body;
 
    try {
 
      // returns the output of the page as a PDF
      body = pdf.getContent();
 
    // need to pass unit test -- current bug  
    } catch (VisualforceException e) {
      body = Blob.valueOf('Some Text');
    }
 
    Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
    attach.setContentType('application/pdf');
    attach.setFileName('testPdf.pdf');
    attach.setInline(false);
    attach.Body = body;
 
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    mail.setUseSignature(false);
    mail.setToAddresses(new String[] { email });
    mail.setSubject('PDF Email Demo');
    mail.setHtmlBody('Here is the email you requested! Check the attachment!');
    mail.setFileAttachments(new Messaging.EmailFileAttachment[] { attach }); 
 
    // Send the email
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
 
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Email with PDF sent to '+email));
 
    return null;
 
  }
 
}
PdfGeneratorTemplate Visualforce Page
This is the Visualforce page that is generated in the Controller. It simply uses the StandardController and displays the Account name for the ID passed to it.
1
2
3
4
<apex:page standardController="Account" renderAs="pdf">
  <h1>Congratulations!!</h1>
  <p>You created a PDF for {!account.name}</p>
</apex:page>
Test Class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
@isTest
private class Test_PdfEmailController {
 
  static Account account;
 
  static {
 
    account = new Account();
    account.Name = 'Test Account';
    insert account;
 
  }
 
  static testMethod void testPdfEmailer() {
 
    PageReference pref = Page.PdfEmailer;
    pref.getParameters().put('id',account.id);
    Test.setCurrentPage(pref);
 
    PdfEmailController con = new PdfEmailController();    
 
    Test.startTest();
 
    System.assertEquals(2,con.accounts.size());
 
    // populate the field with values
    con.accountId = account.id;
    con.email = 'test@noemail.com';
    // submit the record
    pref = con.sendPdf();
 
    Test.stopTest(); 
 
  }
}

8 comments:

  1. I was searching for the better blog on Sales force CRM techniques to understand what CRM is and what is the use? Your blog is the right one I found to get depth knowledge. Thanks for sharing your wonderful ideas.
    Regards
    Salesforce Training in Chennai | Salesforce Training

    ReplyDelete
  2. I read your post when it was fresh. I stumbled on this link again while searching for something else. Since this appears to be favored by Google it is worth pointing out MS has changed its mind.

    In today's job market, Salesforce skills are in high demand. Community Cloud Advisors are the foundation for real-world Salesforce skills across the industry. Are you ready to prove your Salesforce skills? Get Salesforce Certification now! Salesforce certification is designed to reflect the needs of organizations and IT professionals. All departments require IT professionals to run these gadgets efficiently.
    KillerDumps offers the entire IT exam dump file and practice test simulator at a discounted price with 100% guaranteed success.

    You can get Salesforce Exam Dumps

    ReplyDelete
  3. Incredible site you have here.. It's elusive quality composing like yours nowadays. I truly appreciate people like you! Fare thee well!!

    update news

    ReplyDelete
  4. There's definately a ton to think about this issue. I truly like all the focuses you made.
    best interiors

    ReplyDelete
  5. 100% Pass Guarantee is offered by us after APICS Certified Supply Chain Professional CSCP exam preparation, with Prepare4Test’s exam dumps. You can pass the CSCP exam in the first go with good marks, and it will be easy for you to attempt all CSCP questions.

    ReplyDelete
  6. Download the Arista ACE-P-ALE1.04 Q&A PDF file easily to prepare Arista Linux Essentials exam. It is particularly designed for Arista ACE-P-ALE1.04 exam and our Arista specialists have created this ACE-P-ALE1.04 Question Dumps observing the original ACE-P-ALE1.04 exam.

    ReplyDelete

Common interview questions for Salesforce developers

Name three Governor Limits .                                                                                    Description Synchronous ...