function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
azar khasimazar khasim 

Was getting some error while using as rendered as PDF

I was facing some error while using this visualforce page with adding Rendered as PDF. Please Help me out.

VF Page:

<!-- RecieptForMail -->
<apex:page standardController="Reciept__c"   extensions="Reciepts" showHeader="false" applyBodyTag="true" applyHtmlTag="true" renderAs="pdf">
    <apex:form >
        <div style="font-size:13px;">
        <center>
        <h2 style="color:green;">
            Receipt
        </h2>
            </center>
           <img src="https://bren--c.ap5.visual.force.com/resource/1523623530000/BrenLogo" width="150" height="60"/>
           <br/>
        
            
        
        <div align="right">
             #61,Bren Balavana Koramangala,<br/>
             5th 'A' Block,Bangalore 560095<br/>
             Tool free : 18001028800
        </div><br/><br/>
        <b><br/>
            RECEIVED WITH THANKS FROM :<br/><br/>
            
        </b>
        <b>{!ua.emtcustomername__c}&nbsp;{!coownerName}</b><br/>
        {!ua.DMNCustomerStreet__c}<br/>
         {!ua.DMNCustomercity__c}<br/>
         {!ua.DMNCustomerstate__c}<br/>
        {!ua.DMNCustomercountry__c}-{!ua.DMNCustomerpostalcode__c}<br/><br/>
        <b>
           THE SUM OF {!wordText}<br/>
            VIDE Wire Transfer No.{!rc.InstrumentNumber__c} DATED &nbsp;  <apex:outputText value="{0,date,dd'/'MM'/'yyyy}">    
                            <apex:param value="{!rc.InstrumentDate__c}" /> 
            </apex:outputText>&nbsp; DRAWN ON {!rc.DrawnonBank__c}<br/></b>
            {!ua.unit__R.name} &nbsp; {!ua.project__R.name}<br/>
            On A/c of {!rc.CRMComments__c} payment of purchase price of Unit Number {!ua.unit__r.name}, 
            Block No {!ua.Block__r.name} at {!ua.project__r.name}. <br/><br/>
          
   <table border="1" cellspacing="0" align="left">
       <tr>
       <td width="190" height="40" style="font-size:15px;">
    Rs.
    <apex:outputText value="{0,number,###,###.00}">
                        <apex:param value="{!rc.Amount__c}" />
                    </apex:outputText>
     
       </td>
           </tr>
        </table>
        <div align="right">
            <b>
                {!ua.project__r.Legal_Entity__c}   <br/><br/>
                Authorised signatory
                </b>
        </div><br/>
        
          <div style="font-size:10px;">  Payments by Cheque are subject to realisation</div>
             <div style="font-size:8px;" align="center"> <span style="color:#848484"> Customer Copy</span></div>
        <hr/> 
      

 </div>
    </apex:form>
</apex:page>

 
Raghu NaniRaghu Nani
Can you please share the error details
azar khasimazar khasim
System.StringException: BLOB is not a valid UTF-8 string
Error is in expression '{!sendmail}' in component <apex:commandButton> in page recieptindexpage: Class.Reciepts.sendmail: line 87, column 1
Class.Reciepts.sendmail: line 87, column 1


I have marked some of my code in Bold that i was hoping the error has occured and the Line 87 was in it only.

My Controller Class :


public class Reciepts {
    public string RecID;
    public reciept__c rc{set;get;}
    public unitallocation__c ua{set;get;}
    public string wordtext{set;get;}
    public boolean includecoowner{set;get;}
    public string coownerName{set;get;}
    
    public Reciepts(apexpages.StandardController sc){
        RecID=apexpages.currentPage().getparameters().get('id');
        //RecID= 'a0E5D000002Gqoy';
        rc=[SELECT id,name,Amount__c,ApprovalStatus__c,
            unitallocation__c,InstrumentType__c,InstrumentNumber__c,drawnonbank__c,InstrumentDate__c,ReceiptDate__c,
            BankClearanceDate__c,FinanceCommentstoCustomer__c,CRMComments__c
            FROM reciept__c WHERE id=:RecID];
        
        ua=[SELECT id,unit__r.name,DMNSecondApplicantName__c,Block__r.name,customeremailDMN__c,emtcustomername__c,DMNCustomerStreet__c,DMNCustomerCity__c,
            DMNCustomerState__c,DMNCustomerCountry__c,DMNCustomerPostalCode__c,
            project__r.name,project__r.Legal_Entity__c,CustomerEmailWF__c,DMNSecondApplicantEmail__c,owner.email,DMN_Second_Applicant_Name_Frm__c
            FROM unitallocation__c WHERE id=:rc.UnitAllocation__c];
        
        wordText=convert(integer.valueof(rc.amount__c));
        wordtext=wordtext+' Rupees only'; 
    }
    //----------------------------------------------------------    
    
    //----------------------------------------------------------    
    public String[] units = new String[]{'Zero ','One ','Two ','Three ','Four ','Five ','Six ','Seven ','Eight ','Nine ','Ten ',
        'Eleven ','Twelve ','Thirteen ','Fourteen ','Fifteen ',
        'Sixteen ','Seventeen ','Eighteen ','Nineteen '};
            public String[] tens = new String[]{'','','Twenty ','Thirty ','Forty ','Fifty ','Sixty ','Seventy ','Eighty ','Ninety '};
                
                //This method is used to convert the integer to words
                public  string convert(long i) {
                    //
                    if( i < 20)  return units[integer.valueOf(i)];
                    if( i < 100) return tens[integer.valueOf(i)/10] + ((math.mod(i , 10) > 0)? '' + convert(math.mod(i , 10)):'');
                    if( i < 1000) return units[integer.valueOf(i)/100] + ' Hundred ' + ((math.mod(i , 100) > 0)?' and ' + convert(math.mod(i , 100)):'');
                    if( i < 10000) return units[integer.valueOf(i)/1000] + ' Thousand ' + ((math.mod(i , 1000) > 0)?' ' + convert(math.mod(i , 1000)):'');
                    if( i < 100000) return convert(i / 1000) + ' Thousand ' + ((math.mod(i , 1000) > 0)? '' + convert(math.mod(i ,1000)):'') ;
                    if( i < 1000000) return units[integer.valueOf(i)/100000] + ' Lakh ' + ((math.mod(i , 100000) > 0)? '' + convert(math.mod(i ,100000)):'') ;
                    if( i < 10000000) return convert(i / 100000) + ' Lakh ' + ((math.mod(i , 100000) > 0)? '' + convert(math.mod(i ,100000)):'') ;
                    if(i < 100000000) return units[integer.valueOf(i)/10000000] + ' Crore ' + ((math.mod(i , 10000000) > 0)? '' + convert(math.mod(i , 10000000)):'') ;
                    if(i < 1000000000) return convert(i / 10000000) + 'Crore ' + ((math.mod(i , 10000000) > 0)? '' + convert(math.mod(i , 10000000)):'') ;
                    
                    return convert(i / 1000000000) + ' Crore ' + ((math.mod(i , 1000000000) > 0) ? '' + convert(math.mod(i , 1000000000)):'') ;
                }
    
    
    public pagereference sendmail(){
         list<string> toadd=new list<string>();
        if(IncludeCoowner == true){
            coownerName='& '+ua.DMN_Second_Applicant_Name_Frm__c;
            if(!test.isRunningTest())
            toadd.add(ua.DMNSecondApplicantEmail__c);
        }
        Id profileId;
        if(!test.isRunningTest()){
            profileId=userinfo.getProfileId();
        }
        
        string profileName;
        if(test.isRunningTest()){
            profileName='Bren Crm Standard User';
        }else{
            profileName=[Select Id,Name from Profile where Id=:profileId].Name;
        }
        
        if(rc.ApprovalStatus__c != 'applied' && profileName == 'Bren Crm Standard User' && !test.isrunningtest()){
            apexpages.Message m=new apexpages.Message(apexpages.Severity.ERROR,'This Reciept Still Not Approved by Finance');
            apexpages.addMessage(m);
        }else{
            List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
            
            
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            
            Messaging.EmailFileAttachment efa1 = new Messaging.EmailFileAttachment();
            
            PageReference pr = Page.RecieptForMail;
            
            String   pageAsString;
            if(test.isRunningTest()){
                pageAsString = 'TEST';
            }else{
                
                pageAsString= pr.getContent().tostring();                                                          <=========Line 87
            }
            
            
            
            PageReference ref = Page.RecieptForMail;                                                                     
            
            blob br;
            if(test.isRunningTest()){
                br = blob.valueOf('test');
            }else{
                br = ref.getContentAsPDF();
            }
            
            
            
            efa1.setFileName('Reciept.pdf');
            efa1.setBody(br);
            

            

            toadd.add(ua.CustomerEmailWF__c);
            email.setSubject('Reciept Details'); 
            email.setToAddresses(toadd);
            
            email.setSenderDisplayName('Bren Service');
            email.setReplyTo('Query@bren.com');
            
            if(!test.isRunningTest())
                email.setCcAddresses(new list<string>{'erp.alert@bren.com',ua.owner.email});
            
            
            email.setHtmlBody(pageAsString);
            
            fileAttachments.add(efa1);
            
            email.setFileAttachments(fileAttachments);
            
            
            Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
            
            //for creating task
            task tk=new task();
            tk.WhatId=rc.id;
            tk.TaskInfo__c='Receipt';
            
            tk.OwnerId=userinfo.getUserId();
            tk.Subject = 'Reciept Sent to Customer';
            tk.Priority='normal';
            tk.Status='completed';
            insert tk;
            
            
            pagereference p=new pagereference('/'+RecID);
            return p;
        }
        return null;
    }
    public pagereference printreciept(){
        if(IncludeCoowner == true){
            coownerName='& '+ua.DMN_Second_Applicant_Name_Frm__c;
        }
        Id profileId=userinfo.getProfileId();
        String profileName=[Select Id,Name from Profile where Id=:profileId].Name;
        if(rc.ApprovalStatus__c != 'applied' && profileName == 'Bren Crm Standard User'){
            apexpages.Message m=new apexpages.Message(apexpages.Severity.ERROR,'This Reciept Still Not Approved by Finance');
            apexpages.addMessage(m);
        }else{
            //for creating task
            task tk=new task();
            tk.WhatId=rc.id;
            tk.TaskInfo__c='Receipt';
            
            tk.OwnerId=userinfo.getUserId();
            tk.Subject = 'Reciept Print Taken';
            tk.Priority='normal';
            tk.Status='completed';
            insert tk;
            pagereference p=new pagereference('/apex/RecieptForPrint');
            return p;
        }
        return null;
    }
    
}


Please Have a Look and help me out
Raghu NaniRaghu Nani
try this below line 
pageAsString = EncodingUtil.base64Encode(pr.getContent());