Generate a PDF and Attach it to record from a trigger in Salesforce — RESTful Webservice

Attaching the PDF using RESTful services.

I have posted an article on the step-by-step instruction on doing the same the SOAP way.

Here you go:
Step 1: create a REST resource class and in the post method add the logic to generate the PDF
Step 2: Create a class which has future Method (with callout=true). This future method will call the REST Resource
Step 3: Finally create a trigger that will call this future method.

In this scenario I will create a account and a pdf will be attached to it after the insert.

First lets create the VF page to generate the pdf, a simple one. Lets call it, pdfRenderPage


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

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

</apex:page>

Create the Rest Resource which will insert the pdf attachement.

/********
Copyright (c) <2014> <junglee Force(jungleeforce@gmail.com)>
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
**********/
@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;
    }
}

Next create a class with the future method:

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);
       }
    }
}

FInally create the trigger:

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);

}

All of this would work only if you add the host in my case it’s https://ap1.salesforce.com, add it to the remote site setting. So go to Setup-> Admin Setup -> security Controls -> Remote Site Settings. Click on new, give it a name(RESTTest), add the Remote Site URL(just copy paste the url from the address bar), it will only take the host and truncate the rest when you save it.

Test Class:

@isTest
public class AddPDFtoRecordTest{
    @isTest static void addPDFtoRecordTestMethod() { 
        account a = new account();
        a.name= 'test PDF';
        insert a;
        
        List<String> accountIdList = new List<String>();
        accountIdList.add(a.Id);
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();
    
        req.requestURI = 'https://'+URL.getSalesforceBaseUrl().getHost()+'/services/apexrest/addPDFtoRecord/';  
        req.httpMethod = 'POST';
        req.requestBody = Blob.valueOf('{"accountIdList":'+JSON.serialize(accountIdList)+'}');
        req.addHeader('Content-Type', 'application/json');
        RestContext.request = req;
        RestContext.response = res;
    
        AddPDFtoRecordREST.doPost(accountIdList);              
    }
}

You can find the code on gitHub