[SalesForce] Converting from string to blob and sending email along with attachment

I have this method

public void sendEmailWithAttachment(){

        Blob b;
        String b64;
        String strUrlUTF8;
        String sampleString=generateReport();  //call generateReport method to get string
        System.debug('[Original sample string]'+sampleString);

        strUrlUTF8 = EncodingUtil.urlEncode(sampleString, 'UTF-8');
        System.debug('String strUrlUTF8: [' + strUrlUTF8 + ']');

        b = Blob.valueOf(strUrlUTF8);
        System.debug('Blob b: [' + b.toString() + ']');

        //b64 = EncodingUtil.base64Encode(b);
        //System.debug('String b64: [' + b64 + ']');

         //b = EncodingUtil.base64Decode(b64);
        //System.debug('Blob b: [' + b.toString() + ']');
        Document doc= new Document();
        Folder reportFolder = [select id from Folder where name = 'Partner Monthly Report' limit 1];
        if(reportFolder.id != null){
            doc.FolderId = reportFolder.id ;
        }
        doc.name=Monthandyear+'-'+'Partner Monthly Report';
        doc.body=b;
        insert doc;        
        String[] toaddress;                 //String array to hold the email addresses
        User usr=[SELECT id,Name,Email FROM User WHERE Name='sample' LIMIT 1];
        if(usr.Email != null){
            toaddress=new String[]{usr.Email}; 
        }
        EmailTemplate template = [SELECT Id FROM EmailTemplate WHERE Name = 'Reporttemplate' LIMIT 1];
        // Create the email attachment
        Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
            efa.setContentType('application/pdf');
            efa.setFileName(Monthandyear+'-'+'Partner Mothly Report.pdf');
            efa.setBody(b);
        Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();    
            msg.setTemplateId(template.Id);
            msg.setToAddresses(toaddress);
            if(usr.id != null){
                msg.setTargetObjectId(usr.id); //  Here you can give Id of  User , Lead , Contact 
            }
            msg.setSaveAsActivity(false);
            msg.setFileAttachments(new Messaging.EmailFileattachment[]{efa});
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { msg });  

    }

generateReport() method

 public String generateReport(){ 
        String reportContent='';
        reportContent += '<table align="right"><tr><td align="right">width="140" height="100"/></td></tr></table><br></br><br></br><br></br><br></br><br></br><br></br><br></br>';
        reportContent += '<center><table align="center" width="70%" height="60%" cellspacing="0" style="background-color:#819FF7;"><tr><td ><b>Partner Monthly Report</b></td></tr></table></center><br></br>';

        reportContent += '<center><table border="1" align="center" cellspacing="0" style="background-color:#FBFBEF;height:60%;width:70%;">';
        reportContent += '<tr ><td align="left" style="background-color:#819FF7;"><b>Cumulative Data for the month &nbsp;&nbsp;&nbsp;'+Month+'</b></td>';                
        reportContent += '<td align="right" style="background-color:#819FF7;"><b>Total Values (in Rupees)</b></td></tr>';
        reportContent += '<tr><td align="left">Cumulative Disbursement</td><td align="right">'+cumulDisbursement+'</td></tr>';
        reportContent += '<tr><td align="left">Cumulative Repayment</td><td align="right">'+cumulRepayment+'</td></tr>';
        reportContent += '<tr><td align="left">Cumulative outstanding</td><td align="right">'+cumulOutstanding+'</td></tr>';
        reportContent += '<tr><td align="left">Disbursement </td><td align="right">'+disbursementLoanTranche+'</td></tr>';
        reportContent += '<tr><td align="left">Repayment collected</td><td align="right">'+repaymentCollected+'</td></tr>';
        reportContent += '<tr><td align="left">Principal Paid</td><td align="right">'+prinicpalPaid+'</td></tr>';
        reportContent += '<tr><td align="left">Interest Paid </td><td align="right">'+interestPaid+'</td></tr>';
        reportContent += '<tr><td align="left">Repayment Rate %</td><td align="right">'+repaymentRate+'</td></tr>';
        reportContent += '<tr><td align="left">Service Fee</td><td align="right">'+serviceFeeLoanTranche+'</td></tr></table><center>';
        reportContent += '<center><table border="" align="center" cellspacing="0" style="background-color:#819FF7;height:60%;width:70%;">';
        reportContent += '<tr><td align="center"><b>Bank Balance</b></td></tr></table></center>';
        reportContent += '<center><table border="1" align="center" cellspacing="0" style="background-color:#FBFBEF;height:40%;width:70%;">';
        reportContent += '<tr><td align="left" width="76%">Axis Bank</td><td align="right">'+axisBankBalance +'</td></tr>';
        reportContent += '<tr><td align="left">DBS Bank</td><td align="right">'+dbsBankBalance+'</td></tr>';
        reportContent += '<tr><td align="right"><b>Total:&nbsp;</b></td><td align="right">'+totalBankBalance+'</td></tr></table>';                
        reportContent += '<table border="" align="center" cellspacing="0" style="background-color:#819FF7;height:60%;width:70%;">';
        reportContent += '<tr><td align="center"><b>Funds available for lending</b></td></tr></table></center>';                                   
        reportContent += '<table border="1" align="center" cellspacing="0" style="background-color:#FBFBEF;height:20%;width:70%;">';  
        reportContent += '<tr><td align="left" width="76%">Bank Balance</td><td align="right">'+totalBankBalance+'</td></tr>';
        reportContent += '<tr><td align="left">Expected repayment</td><td align="right">'+expectedRepayment+'</td></tr>';
        reportContent += '<tr><td align="left">Less: Lender Repayment(Yunus and other)</td><td align="right">'+lenderRepaymentBalance+'</td></tr>';
        reportContent += '<tr><td align="right"><b>Total:&nbsp;</b></td><td align="right">'+overallTotalBalance+'</td></tr></table><br></br></center>';
        return reportContent;
    }

The problem is i am not able to open the pdf file. It says
Adobe Reader could not open '11-07-2014-Partner Monthly Report.pdf' because it is either not a supported file type or because the file has been damaged(for example, it was sent as an email attachment and wasn't correctly decoded)
Please give any suggestion how to achieve this

Best Answer

This way it can never work. You can't just put html tags into a string, utf8-encode it and expect it to be a valid PDF... the html must be converted into the PDF format - which is not a trivial task.

The good news is that salesforce can do it for you! For the conversion you need a visualforce page. I will show you the concept, but not provide full source code.

Create a new vf-page call it MyPage and render it as PDF like this

<apex:page controller="YourController" renderas="pdf" >
    <apex:outputText escape="false" value="{!YourHtml}" ></apex:outputText>
</apex:page>

To get you html in the page, you will have to use a controller (which should be a separate apex class). It has to provide a function

public with sharing class YourController  {
    public string getYourHtml() {
        return "Her comes <b>your Html</b>";
    }
}

Test you PDF by navigating to /apex/MyPage - this should be displayed as PDF.

Now you can grab the content of the page and use it as a blob and e.g. store it as attachment or send an email:

PageReference pageRef = new PageReference('/apex/MyPage');
pageRef.getParameters().put( "id", AnObjectId ); // use this to pass parameters to your Controller, e.g. an Id or whatever
Blob pdfBlob = pageRef.getContent();

Now if you are in a context which does not support getContent() please look at this workaround

How to download a VF page as PDF and email it from a trigger?

Related Topic