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
Nagarjuna Reddy.PNagarjuna Reddy.P 

Generate PDF from Account Record Page

Hello All,

I have a requirement that On click of a button from Account record page need to generate a pdf with all related contacts and opportunities of that account. and need to send that pdf to account's email address and attach to account record.

Coula any one please help me with this requirement.

Thank you All !!
AbhinavAbhinav (Salesforce Developers) 
Check this for refernce:
 
Create Visualforce Page, Render as PDF using related records data

https://salesforce.stackexchange.com/questions/210293/create-visualforce-page-render-as-pdf-using-related-records-data

Thanks!
 
Suraj Tripathi 47Suraj Tripathi 47
Hi Nagarjuna,
Here is the solution,
Vf Page 1:

<apex:page controller="PDFcontroller">
    <apex:form >
        <head>
            <script>
            function generate(){
                var ids = "{!currentRecordId}"
                console.log(ids);
            window.open("https://cacom66-dev-ed--c.visualforce.com/apex/YA2?core.apexpages.request.devconsole=1&id="+ids);
                submitButton1();
            }
            </script>
        </head>
    
        <input id="saveDraft" type="button" reRender ="none"  class="btnclass" name="" onclick="generate()"  value="Genrate PDF" style="background-color: #5483a5;color:white;font-size: 25px;text-align: center;" />
            <apex:actionFunction name="submitButton1" action="{!generate}" reRender="none" />
        </apex:form>
</apex:page>

Controller:

public class PDFcontroller {
     public String currentRecordId {get;set;}
    public PDFcontroller(){
        currentRecordId  = ApexPages.CurrentPage().getparameters().get('id');
        
    }
    public void generate(){
        GenerateCustomPDF(currentRecordId);
    }
    
    public static void GenerateCustomPDF(Id currentRecordId){
        try{
            List<Account> acclist = new List<Account>();
            acclist =[select name,email from account where Id =:currentRecordId];
             
            PageReference defaultPage = new PageReference('https://cacom66-dev-ed--c.visualforce.com/apex/YA2?core.apexpages.request.devconsole=1'); //page location
            defaultPage.getParameters().put('id',currentRecordId);
           system.debug('defaultId'+defaultPage.getParameters().get('id')); //passing in id for specific record
            Blob pageData;
            if(!Test.isRunningTest()){
               system.debug('page');
                pageData = defaultPage.getContentAsPdf();
               system.debug('page1'+pageData);
            }else{
                
                pageData = Blob.valueOf('This is a test.');
               system.debug('page1'+pageData);
                
            }
           // system.debug('blobvalue'+ EncodingUtil.base64Encode(pageData));
            //create attachment
            Attachment att = new Attachment(
                ParentId=currentRecordId,
                Body=pageData,
                Name='Account'+'.pdf'
                
            );
          
            insert att;
          List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
           string Sub = 'Account Detail Record';
            
            List<String> emailid = new List<string>();
            emailid.add(acclist[0].email);
            Messaging.EmailFileAttachment mailatt = new Messaging.EmailFileAttachment();
            mailatt.setBody(pageData);
            
            mailatt.setContentType('application/pdf');
            mailatt.setFileName('attachment.pdf');
            system.debug('page2'+ mailatt); 
            Messaging.SingleEmailMessage mess = new Messaging.SingleEmailMessage();
            system.debug('page3'); 
           // mess.setTemplateID(emailTemplate.Id);
            mess.setSubject(Sub);
            if(emailid.size()>0 && emailid!=null){
                system.debug('page6'); 
                mess.setToAddresses(emailid);
            }
            system.debug('page4'+mess); 
            mess.setFileAttachments(new Messaging.EmailFileAttachment[]{mailatt});
            mails.add(mess);
            if(mails.size()>0){
                Messaging.sendEmail(mails); 
               
            }
            
        }catch(exception e){
          
        }
        
    }

}

Vf page 2:

<apex:page renderAs="PDF" standardController="Account" extensions="GeneratePdfwithdata">
    
    <apex:form >
        <apex:pageBlock >
        <apex:pageBlockSection title="Contacts and Opportunities related to an account" >
      <apex:repeat value="{!con}" var="c">
          <b>Contacts:</b><br/>{!c.Lastname}
          </apex:repeat>
            <apex:repeat value="{!opp}" var="o">
           Opportunities: <apex:outputField value="{!o.name}"/>
          </apex:repeat>
        </apex:pageBlockSection>
        </apex:pageBlock>
        
    </apex:form>
</apex:page>

Controller 2:

public class GeneratePdfwithdata {
    public String currentRecordId {get;set;}
public Account acc{get;set;}
    public List<contact> con{get;set;}
    public List<opportunity> opp{get;set;}
 
    public GeneratePdfwithdata(ApexPages.StandardController controller) {
        currentRecordId  = ApexPages.CurrentPage().getparameters().get('id');
        system.debug(currentRecordId);
        acc = [select id ,name,(select Id from contacts),(select Id from opportunities) from Account where id =: currentRecordId ];
        //parameterValue = ApexPages.CurrentPage().getparameters().get('nameParam');
        con = [select Id,Lastname from contact where AccountId =: currentRecordId ];
         opp = [select Id,name from opportunity where AccountId =: currentRecordId ];
    }
}

Hope this will help you
Thanks
Gabriel LinusGabriel Linus
Hi Nagarjuna,

To fulfill this particular requirement, you can use Salesforce Apex code,Visualforce page and links & button. If you're seeking guidance on generating PDFs within Salesforce, you can refer to a useful resource available at, at https://arrify.com/generate-pdf-in-salesforce/. This resource offers an in-depth guide to PDF generation, complete with step-by-step instructions and code examples that can assist you in achieving your desired outcome. It is an excellent reference for anyone seeking to generate PDFs within Salesforce.