1

I'm having trouble getting a PDF when using a PageReference to the quoteTemplateDataViewer.

This class is creating a QuoteDocument on the Quote record, but the contents of the document are blank.

When using the getContent() method, the document throws this error when trying to view: "Error, Failed to load PDF document."

Here's the code:

global class QuotePDFGenerator {
  webservice static String AttachPDFToQuote(string Id) {

      try {
        String quoteURL = '/quote/quoteTemplateDataViewer.apexp?headerHeight=156&footerHeight=94&summlid=0EH800000000fkT&id=' + Id;
        PageReference page = new PageReference(quoteURL);

        // Blob renderedPDF = page.getContent();
        // When using this method, I get "Error, Failed to load PDF document." when trying to view the PDF

        // When using `getContentAsPDF` I get a blank PDF.
        Blob renderedPDF = page.getContentAsPDF();

        QuoteDocument doc = new QuoteDocument(QuoteId = Id, Document = renderedPDF); 
        INSERT doc;

        String Name = [ SELECT Name FROM QuoteDocument WHERE QuoteId =: Id ORDER BY CreatedDate DESC LIMIT 1 ].Name;

        return Name;
      } catch(exception ex) {
        System.debug('Error: ' + ex);
        return ex.getMessage();  
      }

  }
}

Any ideas on where I'm going wrong? Thanks.

* EDIT *

I was able to solve this issue by moving the PDF generation code into a @future method. Here's the final working version:

https://gist.github.com/citrus/19ce62aded1e6d9ff8ffa25db00bad71

  • 1
    I had a similar issue in a Lightning controller. Ultimately, it only worked when I ran getContentAsPDF() in a future method, which presumably has to do with it counting as a callout but is still a bit mysterious to me. – David Reed Jul 16 '18 at 16:31
  • Thanks for the tip David. After updating my code to use @future(callout=true), the PDF is now being written to the quote document! – veronatii Jul 16 '18 at 16:44

Your Answer

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

Browse other questions tagged or ask your own question.