Friday, 10 August 2012

Generate PDF with apex trigger

Question:
I am currently trying to have a PDF created based on a field update.
The issue is that it seems that getContent() and getContentAsPDF() don't work when called within a trigger.

Solution:
Tried separating this logic into a class with @future, and then calling it to do your logic asynchronously.
global class pdfCreator
{
    @future (callout=true)
    public static void createPDF(ID Id)
     {
        PageReference pdf = Page.AccountsPDF;
        pdf.getParameters().put('id', String.valueOf(Id));

        Attachment attach = new Attachment();
        attach.ParentId = Id;
        attach.name = 'name.pdf';
        attach.body = pdf.getContentAsPDF();
        insert attach;
     }
}
trigger CreatePDF on Contract_Custom__c (after update) {

    for(Contract_Custom__c a : Trigger.New)
    {
    	Id id = a.id;
    	pdfCreator.createPDF(Id);
    }
}

2 comments:

  1. As per the salesforce docs :-

    "The getContent and getContentAsPDFPageReference methods cannot be used in methods with the future annotation."
    Link -

    http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_annotation_future.htm


    ReplyDelete
  2. As per the salesforce docs :-

    "Salesforce is a shit garbage CRM masquerading as a "platform" but wholly unsuited to serious development."

    ReplyDelete

Labels