[SalesForce] Generate PDF with REST Web service

I've created an Apex RestResource that accepts JSON string in POST method. When external system calls that endpoint and pass data, i need to retrieve the JSON and parse it into a PDF file.

Here is the apex rest class.

    @HttpPost
    global static void doPost() {

        // 1 - Getting Response
        ServiceResponse sRes = (ServiceResponse) System.JSON.deserialize(RestContext.request.requestBody.toString().trim(), ServiceResponse.class); 

        // 2 - Saving response as JSON array
        MyObj__c mObj = [SELECT Name, Id FROM MyObj__c WHERE Id =:sRes.id LIMIT 1]; 
        mObj.String_Value__c = JSON.serialize(sRes.links);
        update mObj;

        //3 - Calling PDF generation method
        ApexPages.StandardController stdCon = new ApexPages.StandardController(mObj);
        MyController con = new MyController(stdCon);
        con.generatePDF(opp.Id);  
    }

In my controller extension,

MyObj__c mObj {get; set;}

public MyController(ApexPages.StandardController stdController) {
    mObj = (MyObj__c)stdController.getRecord();

}

public void generatePDF(Id rId) {
    PageReference myPDF = Page.My_PDF; 
    myPDF.getParameters().put('id',rId);

    //PDF Generation Here//
}

public Map<String, String> myLinks{
    get{
        Map<String,String> tempLinks = new Map<String,String> ();
        if(mObj.String_Value__c != null){
            List<MyLink> links = (List<MyLinks>) System.JSON.deserialize(mObj.String_Value__c, List<MyLinks>.class);
            for(MyLinks myL: links){
                tempLinks.put(myL.title, myL.link);
            }
        }


        return tempLinks;
    }
}

When i call this endpoint it retrieves JSON and generates a PDF but I couldn't pass that value into the PDF generation method. When i look into the record, i can see String_Value__c is saved with a valid JSON (or 2nd time i call the endpoint the values appear on pdf).

How can i solve this issue ?

Best Answer

See getContentAsPDF() after insert a record in the same excution context that explains that the PDF generation call won't see any changes made in the transaction that calls it.

If you don't require the PDF results immediately, you can move the PDF generation call into some asynchronous code. If you do require the results immediately back in the client, break this out into two calls from the client done one after another: the first call would do the update and the second call would generate the PDF.

Related Topic