0

I have a requirement to attach visualforce pdf to Notes and Attachment when record gets inserted.I have followed similar steps from this blog. https://jungleeforce.wordpress.com/2014/06/11/generate-a-pdf-and-attach-it-to-record-from-a-trigger-in-salesforce-restful/

This code works fine in developer edition but in my sandbox am getting HTTP response as

System.HttpResponse[Status=Unauthorized, StatusCode=401]

and response body as

[{"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}]

Here is the complete code

<apex:page standardController="Account" renderAs="pdf">

        Hey, the Account name is {!account.Name}

        </apex:page>

    @RestResource(urlMapping='/addPDFtoRecord/*')
global with sharing class AddPDFtoRecordREST{

  @HttpPost
    global static void doPost(list<String> accountIdList) {
       list<attachment> insertAttachment = new list<attachment>();
        for(String accId: accountIdList){
            //create a pageReference instance of the VF page.
            pageReference pdf = Page.pdfRenderPage;
            //pass the Account Id parameter to the class.
            pdf.getParameters().put('id',accId);
            Attachment attach = new Attachment();
            Blob body;
            if(!test.isRunningTest()){
                body = pdf.getContent();
            }else{
                body=blob.valueOf('TestString');
            }
            attach.Body = body;
            attach.Name = 'pdfName'+accId+'.pdf';
            attach.IsPrivate = false;
            attach.ParentId = accId;//This is the record to which the pdf will be attached
            insertAttachment.add(attach);
         }
         //insert the list
         insert insertAttachment;
    }
}

    global class AccountTriggerController{

    @Future(callout=true)
    public static void addPDFAttach(string sessionId, list<id> accountIdList){
       HttpRequest req = new HttpRequest();
       req.setEndpoint('https://'+URL.getSalesforceBaseUrl().getHost()+'/services/apexrest/addPDFtoRecord/');
       req.setMethod('POST');
       req.setBody('{"accountIdList":'+JSON.serialize(accountIdList)+'}');
       req.setHeader('Authorization', 'Bearer '+ sessionId);
       req.setHeader('Content-Type', 'application/json');
       Http http = new Http();
       if(!test.isRunningTest()){
           HTTPResponse res = http.send(req);
           system.debug('res body##### '+res.getbody());
       }
    }
}

    trigger accountAfterInsert on Account (after insert) {

     list<id> accId = new list<id>();
     for(id acc: trigger.newMap.keySet()){
         accId.add(acc);
      }
        //You would need to send the session id to the future method as the you cannot use the userInfo.getSessionID() method in the future method because it is asynchronous and doesn't run in the user context.
        AccountTriggerController.addPDFAttach(userInfo.getSessionId(), accId);

}
2

You're making life hard for yourself there by using a Rest Service. Why not simply use PageReference().getContentAsPDF()? example:

global class AccountTriggerController{
    @Future(callout=true)
    public static void addPDFAttach(Id accId) {
        list<attachment> insertAttachment = new list<attachment>();
        PageReference ref = new PageReference('/apex/yourpage?id=' + accId);

        Attachment attach = new Attachment();
        Blob body;
        if(!test.isRunningTest()){
            body = pdf.getContentAsPDF();
        }else{
            body=blob.valueOf('TestString');
        }
        attach.Body = body;
        attach.Name = 'pdfName'+accId+'.pdf';
        attach.IsPrivate = false;
        attach.ParentId = accId;//This is the record to which the pdf will be attached
        insertAttachment.add(attach);

        insert insertAttachment;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.