I got into a problem when I save the pdf to lead attachment. Here is the scenario

I have a Button on detail page of a Custom Object which is Child of Lead. This button opens a VF page and renders as PDF. When I opening the VF page, I have an action method which calls SaveAttachment method and this method is responsible to get the PDF content and attach the PDF file to Leads Notes and Attachment Section.

Everything working fine but it is attaching 5 attachment every time. this support to a simple task but after spending time, I could not resolve it. Would appreciate any help here. For simplicity, here is the relavent code

VF Page header

<apex:page standardController="Quote_Application__c"  renderas="pdf"   action="{!saveAttachement}" extensions="QuickQuotePDFCntrlr"  showHeader="false" sidebar="false" standardStylesheets="false" applyBodyTag="false" applyHtmlTag="false">

public PageReference saveAttachement() { 

    if(doSave == 'No'){ return null; }

    doSave ='No';
    //PageReference pdf = new PageReference('/apex/QuickQuotePDF?id=' + recordId + '&pdfgenerated=success'); 
    PageReference pdf = ApexPages.currentPage();
    //system.debug('The url created is' + pdf);
    // create the new attachment
    Attachment attach = new Attachment();

    // the contents of the attachment from the pdf
    Blob body;

    // returns the output of the page as a PDF

    //PageReference pdf = page.QuickQuotePDF; 

    try {
        body= pdf.getContent();            
    } catch (VisualforceException e) {
        body= Blob.valueOf('blah blah blah');
    // need to pass unit test -- current bug    

    Lead Ld= [SELECT Name, Id from Lead where Id =: qquoteData.Leads__c ];
    attach.Body = Body ;
    // add the user entered name
    attach.Name = qquoteData.Name + ' ' + myDate + '.pdf';
    attach.IsPrivate = false;

    attach.ContentType = '.pdf';
    // attach the pdf to the account
    attach.ParentId = Ld.ID;
    insert attach;

    //quoteData.PdfGenerated__c = true;
    // pdf.setRedirect(false);
    return null;                                     

1 Answer 1


You're creating an infinite loop, because each new getContent call is actually in a new controller. The loop breaks when one of your calls fail by throwing a nested exception, which you end up catching and ignoring.

Instead, set a new parameter on the page reference, and check for the presence of this parameter before generating a new pdf. It could probably look like this:

public void saveAttachment() {
    if(ApexPages.currentPage().getParameters().containsKey('generatepdf')) {
    PageReference pdf = ApexPages.currentPage();
    Blob file = pdf.getContent();
    // Rest of code here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.