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
LinkYogiLinkYogi 

code to download pdf by rest service

Hi All,

Below is my code:

VF Page:

<apex:page controller="SummaryPdfDispController" standardStylesheets="false" showHeader="false" sidebar="false">

<apex:form Id="status">

<apex:outputLink value="{!URLFOR($Action.Attachment.Download, attachmentId)}" target="_blank" styleClass="element">Download Dossier</apex:outputLink>

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

Apex Code:


public class SummaryPdfDispController {

public class SummaryPdfDispController 
{  //===============================  
//===Declare Variables===========  
//===============================
    public string companyUrl1 {set;get;}   
  public string cmpname {set;get;}     
public string status {set;get;}     
public integer statuscode {set;get;}     
public String blobResult {set;get;}     
public  string PageId{get;set;}     
public string  blb{get;set;}     
public id attachmentId{get;set;}     
public string Accname{get;set;}     
public string htmlRes{get;set;}     
public string CssRes{get;set;}       
public string EmailResponse{get;set;}     
transient blob downloadResponse;     
public string url;  
public List<attachment> attachmentList= new List<attachment>();     
public attachment at{get;set;}     
//===============================================================  //===Constructor to show Html and Css response on vf page========  //===============================================================
public SummaryPdfDispController ()     
{                 
cmpname=Apexpages.currentPage().getParameters().get('Cmp');         
PageId =  Apexpages.currentPage().getParameters().get('ids');          
system.debug('********-----PageId'+ PageId);       system.debug('====cmpname====='+cmpname);                                                                        
    if(PageId <> null && PageId <> '')     
   {              
url = [select link_yogi__dosiersummaryurl__c,Account.name from opportunity where id=:PageId].link_yogi__dosiersummaryurl__c;        

        HttpRequest req = new HttpRequest();             
req.setEndpoint(url);          
       req.setMethod('GET');         
req.setHeader('APIKEY', '67546e2238254a5c557205d624814a32ad35cf96');          
Http http = new Http();    
     req.setTimeout(120000);      
try      {  
       HttpResponse res=new HttpResponse();  
       if(!Test.IsRunningTest())             
res =   http.send(req);         
else            
//
           system.debug('==response=='+res.getbody());             
blb=res.getBody();             
system.debug('==========blb============>'+ blb);             
status=res.getStatus();             
statuscode=res.getStatusCode();                        
JSONParser parser = JSON.createParser(res.getBody());                  
while (parser.nextToken() != null) 
{             
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'html')) 
{                 
parser.nextToken();              
   htmlRes= parser.gettext();  
           }             
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'css'))
 {                 
parser.nextToken();                 
CssRes = parser.gettext();             
}         
}
        system.debug('==Html==='+htmlRes);          system.debug('====CSS Response=='+CssRes); 
     }
     catch(System.CalloutException e)        
{
            System.debug('System.Callout Exception for SummaryPdfDispController Constructor ' + e.getMessage());         
  }
}

    //========================================
 //===Method to Download Dossier as Pdf====
 //========================================      
public void DownloadPdf()     
{     
string url = [select link_yogi__dosierurl__c,Account.name from opportunity where id=:PageId].link_yogi__dosierurl__c];                   HttpRequest req = new HttpRequest();           
req.setEndpoint(url);         
 req.setMethod('GET');         
req.setHeader('APIKEY', '67546e2238254a5c557205d624814a32ad35cf96'); 
        Http http = new Http();     
    req.setTimeout(120000);    
 try      
 {         
HttpResponse res=new HttpResponse();       
  if(!Test.IsRunningTest())     
        res =   http.send(req);   
      else       
     // ----
           system.debug('==response=='+res.getbody());                  
        downloadResponse =res.getBodyAsBlob();      
       status=res.getStatus();            
 statuscode=res.getStatusCode();      
         system.debug('===Response==='+downloadResponse);     
   }      
  catch(System.CalloutException e)    
     {           
  System.debug('System.Callout Exception for DownloadPdf Method ' + e.getMessage());    
      }     
   if(downloadResponse <> null)        
{             
attachmentList=[select id,name,parentid from attachment where parentId =: PageId AND name=: cmpname+'.pdf'];             system.debug('==Existing company Attachments to delete=='+attachmentList);       
   if(attachmentList.isEmpty() == False)      
    {
            try         
    {             
    delete attachmentList;        
     }         
    catch(System.QueryException e)     
        {          
       System.debug('System.QueryException for DownloadPdf Method on delete operation ' + e);  
            }      
    }        
     at= new attachment();         
    at.parentId = PageId;   
          at.body = downloadResponse;    
         at.name = cmpname+'.pdf';        
     try      
       {          
       insert at;     
        }          
   catch(System.QueryException e)      
       {            
   System.debug('System.QueryException for DownloadPdf Method on insert operation ' + e);  
            }      
       attachmentId = at.id;     
        downloadResponse= null;      
       at= null;     
        system.debug('====Attachment====='+at);  
      }  
  }
}
 
Amit Chaudhary 8Amit Chaudhary 8
PDF page
<apex:page renderAs="PDF">
  <!-- Begin Default Content REMOVE THIS -->
  <h1>Congratulations</h1>
  This is your new Page
  <!-- End Default Content REMOVE THIS -->
</apex:page>

Rest Code :-
 
@RestResource(urlMapping='/sendPDFEmail/*')
Global class GETPDFContent{
     @HttpPost
    global static void sendEmail(String EmailIdCSV, String Subject, String body) {

 	List<String> EmailIds = EmailIdCSV.split(',');

        PageReference ref = Page.PDF_DEMO;
        Blob b = ref.getContentAsPDF();

        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

        Messaging.EmailFileAttachment efa1 = new Messaging.EmailFileAttachment();
        efa1.setFileName('attachment_WORK.pdf');
        efa1.setBody(b);

        String addresses;
        email.setSubject( Subject +String.valueOf(DateTime.now()));
        email.setToAddresses( EmailIds  );
        email.setPlainTextBody(Body);
        email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa1});
        Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});

    }
}

Rest Call Out:-
public class SendVFAsAttachment{

    @future(callout=true)
    public static void sendVF(String EmailIdCSV, String Subject,String body,String userSessionId)
    {
        //Replace below URL with your Salesforce instance host
        String addr = 'https://shivasoft--shiva1.cs6.my.salesforce.com/services/apexrest/sendPDFEmail';
        HttpRequest req = new HttpRequest();
        req.setEndpoint( addr );
        req.setMethod('POST');
        req.setHeader('Authorization', 'OAuth ' + userSessionId);
        req.setHeader('Content-Type','application/json');

        Map<String,String> postBody = new Map<String,String>();
        postBody.put('EmailIdCSV',EmailIdCSV);
        postBody.put('Subject',Subject);
        postBody.put('body',body);
        String reqBody = JSON.serialize(postBody);

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

http://www.jitendrazaa.com/blog/salesforce/apex/send-email-with-generated-pdf-as-attachment-from-trigger/


Please mark this as solution if this will help you
 
LinkYogiLinkYogi
@Amit- this does not solve my issue. Actually, as per my code pdf is opening on the next page. my code is working also. My purpose is to download the pdf. Please let me know, do you have any solution for the same.
LinkYogiLinkYogi
Hi All,
Please reply. Your suggession would be very helpful.
LinkYogiLinkYogi
@All- I have found the solution of my problem.

Please look at the code below:
VF Page:

<apex:page controller="SummaryPdfDispController" standardStylesheets="false" showHeader="false" sidebar="false" action="{!DownloadPDF}">
</apex:page>

Apex Code:

public class SummaryPdfDispController 
{  
//===============================  
//===Declare Variables===========  
//===============================
public string companyUrl1 {set;get;}   
public string cmpname {set;get;}     
public string status {set;get;}     
public integer statuscode {set;get;}     
public String blobResult {set;get;}     
public  string PageId{get;set;}     
public string  blb{get;set;}     
public id attachmentId{get;set;}     
public string Accname{get;set;}     
public string htmlRes{get;set;}     
public string CssRes{get;set;}       
public string EmailResponse{get;set;}     
transient blob downloadResponse;     
public string url;  
public List<attachment> attachmentList= new List<attachment>();     
public attachment at{get;set;}     
//===============================================================  //===Constructor to show Html and Css response on vf page========  //===============================================================
public SummaryPdfDispController ()     
{                      
PageId =  Apexpages.currentPage().getParameters().get('ids');          
}

  //========================================
 //===Method to Download Dossier as Pdf====
 //========================================      
public pageReference DownloadPdf()     
{     

Opportunity Opp = [select name,link_yogi__dosierurl__c,Account.name from opportunity where id=:PageId];       string url = [select link_yogi__dosierurl__c,Account.name from opportunity where id=:PageId].link_yogi__dosierurl__c; 
HttpRequest req = new HttpRequest();
req.setEndpoint(url); 
req.setMethod('GET');
req.setHeader('APIKEY', '67546e2238254a5c557205d624814a32ad35cf96');
Http http = new Http();
req.setTimeout(120000);
try   
{         
HttpResponse res=new HttpResponse();          
if(!Test.IsRunningTest())         
res =   http.send(req);     
else     
res.setBody(//);         
system.debug('==response=='+res.getbody());         
blb =res.getBodyAsBlob();         
blobResult = EncodingUtil.Base64Encode(blb);         
status=res.getStatus();         
statuscode=res.getStatusCode();                             
}         
catch(System.CalloutException e)         
{           
System.debug('A Callout Exception: ' + e.getMessage());         
}            
List<Attachment> attachmentList=new List<Attachment>();         
if(blobResult <> null)
{                      
attachmentList=[select id,name,parentid from attachment where parentId =: PageId AND name=: cmpname+'.pdf'];           system.debug('==Existing company Attachments to delete=='+attachmentList);         
if(attachmentList.isEmpty() == False)         
{             
try             
{                 
delete attachmentList;             
}             
catch(System.QueryException e)             
{                 
System.debug('System.QueryException for DownloadPdf Method on delete operation ' + e);               
}          
}             
Attachment at= new Attachment(ContentType = 'application/octet-stream');             
at.parentId = PageId;            
at.body = blb;             
at.name = cmpname+'.pdf';            
system.debug('at.name** '+ at.name);            
 try
{             
insert at;             
}             
catch (System.QueryException e)
{             
system.debug('System.QueryException of method attSave for insert operation'+ e);             
}             
attachmentId = at.id;                                     
PageReference pageRef= new pageReference('/servlet/servlet.FileDownload?file= '+attachmentid);            system.debug('attachmentId** '+attachmentId );             
system.debug('at.name** '+ at.name);                          
at=null;             
blobResult=null;             
return pageRef;         
}          
else        
{           
return null;

  }
}

Note:
1. Please refer this code to reference your issue.