Friday, March 15, 2013

Creating visualforce page as PDF and sending that PDF to Email


Visualforce Page:

<apex:page standardController="Account" recordSetVar="accs" extensions="pdfcls" >
    <apex:form >
        <apex:pageblock >        
            <apex:pageblockButtons >
                <apex:commandButton value="send PDF" action="{!pdfmethod}"/>
            </apex:pageblockButtons>        
            <apex:pageblockTable value="{!accs}" var="a">
                <apex:column value="{!a.name}"/>
                <apex:column value="{!a.type}"/>
                <apex:column value="{!a.rating}"/>
            </apex:pageblockTable>
        </apex:pageblock>
    </apex:form>
</apex:page>

Apex Class:

public with sharing class pdfcls {

    public pdfcls(ApexPages.StandardSetController controller) {

                                                                                              }
    public blob body;                                                          
    public PageReference pdfmethod(){
        PageReference ref=page.pdftomail;
        body=ref.getContentAsPDF();
        
        Messaging.EmailFileAttachment mefa=new Messaging.EmailFileAttachment();
        mefa.setContentType('application/pdf');
        mefa.setFileName('Narayana.Pdf');
        mefa.Body=body;
        
        Messaging.SingleEmailMessage msem=new Messaging.SingleEmailMessage();
        msem.setToAddresses(new String[] {'example@gmail.com'});
        msem.setSubject('Email PDF Demo');
        msem.setPlainTextBody('sending pdf to email from salesforce visualforce');
        msem.setFileAttachments(new Messaging.EmailFileAttachment[] {mefa});
        //send email
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {msem});
            return null;        
                                    }
}

No comments:

Post a Comment