System.VisualforceException: Getting content from within triggers is currently not supported
(Salesforce Visualforce Error Notification)
—————————-

Hi All,
Recently I was working on a task in which we need to save a pdf page as an attachment when a new record(Contact) is inserted.

I was doing it with Trigger and its handler using Pag reference Method getContentAsPdf(). I got an exception when I was saving a record of contact. This problem will be resolved if we use @future(callout=true) annotation before the method

Sample Pdf page:

<apex:page renderAs=”pdf”>
    <!–Begin Default Content REMOVE THIS–>
    <h1> Hello </h1>
    This is your pdf page
    <!–End Default Content REMOVE THIS–>
 </apex:page>

ContactTrigger:

trigger ContactTrigger on Contact(After Insert) { 
    Set <String> setOfContactIds = new Set <String>(); 
    for (Contact objCon: trigger.new) {
        setOfContactIds.add(objCon.id); 
    }
    if (setOfContactIds.size() > 0) {
        ContactTriggerHelper.generatePdf(setOfContactIds); 
    }
}

ContactTriggerHelper:

public class ContactTriggerHelper { 
    @future(callout = true)
    public static void generatePdf(Set <String> setOfIds) {
        List <Attachment> listOfAttach = new List <Attachment>();
        for (String conId: setOfContactIds) {
            PageReference pdf = Page.ContactInPdf;
            Attachment attach = new Attachment();
            attach.ParentId = conId;
            attach.name = conId + '.pdf';
            attach.body = pdf.getContentAsPDF();
            listOfAttach.add(attach); 
        } 
        if (listOfAttach.size() > 0)
        { 
            insert listOfAttach;
        }
    }
}

Thanks