I'm currently trying to upload my Visualforce-rendered PDF to the Files related list of my record.

I understand PageReference and getContentAsPDF() both behave as Callouts and thus needs to be separated into two transactions. I've looked over some other topics discussing but unfortunately, due to my lack of expertise on this, it still wasn't clear to me and I can't seem to get it right.

Most commonly, I get the "Too many nested getContent calls" Visualforce error. On a bad day, I will encounter recursive issues while playing around with the code - running on a loop. I'm looking to prevent this.

Here is my code:

public static boolean inFutureContext = false;

public pagereference updateInvoiceInfo(){
    String filename = 'Sample_Invoice';  
    String parentId = invoice.Id;
    Blob body;

    try {
        PageReference pdf = Page.invoiceVF;
        pdf.getParameters().put('id', parentId);
        body = pdf.getContentAsPdf();
    } catch (VisualforceException e) {
        body = Blob.valueOf('There was an error encountered.');

    if(inFutureContext == false){
        generatePDF(body, filename, parentId);
    return null;

public static void generatePDF(Blob body, String parentId, String filename) {
    inFutureContext = true;

    ContentVersion cont = new ContentVersion();
    cont.Title = filename;
    cont.PathOnClient = fileName;
    cont.VersionData = body;
    insert cont;

    Id conDocument = [SELECT ContentDocumentId FROM ContentVersion WHERE Id =:cont.Id].ContentDocumentId;

    ContentDocumentLink cDocLink = new ContentDocumentLink();
    cDocLink.ContentDocumentId = conDocument;
    cDocLink.LinkedEntityId = parentId;
    cDocLink.ShareType = 'V';
    cDocLink.Visibility = 'AllUsers';
    insert cDocLink;

As such, how would we separate the transactions involving getContentAsPdf() and PageReference?

What am I missing on this code? How would the community re-structure this?

Thanks in advance!


You must log in to answer this question.

Browse other questions tagged .