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
Dagny FernandesDagny Fernandes 

Generate PDF from Batch Class and schedule class and send email notification with Pdf attachment

Requirement:- is Generate the PDF and and send email notification and insert new related record to keep track of the pdf and attachment to the record.
Best Answer chosen by Dagny Fernandes
Dagny FernandesDagny Fernandes
Below is my complete process, modified few things:

set up remote site Setup->Security Controle->Remote Site setting. click on New Remote Site
User-added image
Enter the detailes as in the image and "remote site url" is your ord url

Schedule class:-
global class ScheduleFinacialNotification implements Schedulable {
global string sendSessionId;

global ScheduleFinacialNotification(String sessionId){
  this.sendSessionId = sessionId;
global void execute(SchedulableContext SC) {
     BatchSendFinacialNotification batchApex=new BatchSendFinacialNotification();
     batchApex.sessionId = this.sendSessionId;
     Database.executeBatch(batchApex,1);  }}

Batch class:-

global class BatchSendFinacialNotification implements Database.Batchable<sObject>,Database.Stateful,Database.AllowsCallouts {
public String query;
global string sessionId;
global BatchSendFinacialNotification(){
  this.sessionId  = sessionId;     
        query    = 'Select Id,Name,Project__r.Go_Live_Date__c from Service_Project_Junction__c ';
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
global void execute(Database.BatchableContext BC, List<Service_Project_Junction__c> scope) {
  //List<Service_Project_Junction__c> pojJunRecList = [Select Id,Name,Project__c,Opportunity_Deal__c,Project__r.Id,Project__r.Go_Live_Date__c,Product_Opportunity_Junction__r.Service__r.Service_Type__c,Product_Opportunity_Junction__r.Service__r.Product_Price__c,Product_Opportunity_Junction__r.No_Of_Months__c,Product_Opportunity_Junction__r.Total_Price__c,Product_Opportunity_Junction__r.No_Of_Listings__c from Service_Project_Junction__c where Opportunity_Deal__c != null AND Project__r.Go_Live_Date__c != null];
  for(Service_Project_Junction__c proRec: scope){
   Integer duration = integer.valueOf(proRec.Product_Opportunity_Junction__r.No_Of_Months__c);
   Integer totMonthTillToday = proRec.Project__r.Go_Live_Date__c.monthsBetween(;
   System.debug('Test in for loop==>'+proRec);
   if(totMonthTillToday <= duration && proRec.Project__r.Go_Live_Date__c.Day() =={
    System.debug(sessionId+'Test in if loop==>'+this.sessionId);
    ServiceInvoiceRedirectController.attachPdfToRecord( proRec.Project__r.Id, this.sessionId);
    System.debug('Test in if loop after condiyion==>');

global void finish(Database.BatchableContext BC){     

Call of REST Api class:-

global class ServiceInvoiceRedirectController
        global static void AttachPDFtoRecordREST()
            RestRequest req = RestContext.request;
            id recordId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);

            PageReference pdfPage = new PageReference('/apex/ServiceInvoicePDF?Id='+recordId);
            Blob pdf = pdfPage.getContentAsPdf(); //!Test.isRunningTest() ? pdfPage.getContentAsPdf() : Blob.ValueOf('dummy text');
            Project__c prjRec = [Select Id,Name,Builder_Name__c from Project__c where Id =: recordId];
            //Insert Invoice record for related project
         Invoice__c invoRec = new Invoice__c();
         invoRec.RecordTypeId = Constants_PicklistVariables.serInvoice;
         invoRec.Project__c = recordId;
         invoRec.Account__c = prjRec.Builder_Name__c;
         insert invoRec;
         }catch(Exception e){
         //Insert Attacment to the invoice      
         Attachment a = New Attachment();
         a.body = pdf;
         a.parentID =;
         a.ContentType  = 'application/pdf';
         a.Name = 'SER-INV-''.pdf';
         insert a;
         }catch(Exception e){
         //Create the email attachment
      Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
      efa.setFileName('pdfName.pdf');//Pleace ad pdf name from contact name project and oppty concatinate
      // Create the Singal Email Message
      Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
      email.setSubject('Financial Notification');
      email.setToAddresses(new String[] { '' });//add account email id
      email.setPlainTextBody( 'Please Find Attachment your financial report Attached with this email.');
      email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
      // Sends the email
      Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});

        // call this method from your Batch Apex
        global static void attachPdfToRecord( Id recordId, String sessionId )
         System.debug('Iam in REST API Call method');
           // String addr = '' + recordId;
            HttpRequest req = new HttpRequest();
            req.setHeader('Authorization', 'OAuth ' + sessionId);

            Http http = new Http();
            HttpResponse response = http.send(req);  

Schedule class from Developer Console in Anonymous Window:-

Datetime sysTime =;
sysTime = sysTime.addSeconds(5);
String chron_exp =' '+sysTime.second() + ' ' + sysTime.minute() + ' ' + sysTime.hour() + ' ' + + ' ' + sysTime.month() + ' ? ' + sysTime.year();
System.schedule('Job1',chron_exp , new ScheduleFinacialNotification(UserInfo.getSessionId()));