Programmatically generate Quote PDF in Lightning Component Apex controller
I've found a solution by experiment (with a hat tip to @KeithC, who got me speculating on a productive path), but I don't understand why it works/the direct path doesn't work. I would be happy to accept an answer from anyone who's able to help me understand the principle behind the behavior.
I was able to successfully complete the quote generation and insertion by the simple expedient of breaking the actual getContentAsPDF()
callout and QuoteDocument
insert into a separate @future
method, as follows:
@AuraEnabled
public static void getQuoteTemplate(Id recordId) {
insertQuoteTemplate(recordId);
}
@future(callout=true)
public static void insertQuoteTemplate(Id recordId) {
// Logic to find template Id omitted...
PageReference pr = new PageReference('/quote/quoteTemplateDataViewer.apexp?id=' + recordId + '&summlid=' + templateId);
QuoteDocument qd = new QuoteDocument();
Blob b = pr.getContentAsPDF();
qd.Document = b;
qd.QuoteId = recordId;
insert qd;
}
This is a little unfortunate, as the client-side component controller no longer has access to the result of the operation, but it does work.
The getContentAsPDF
call operates in a separate transaction. So if you make that call from within the transaction that sets up the data, that getContentAsPDF
call will not see the data at all as the transaction that sets up the data won't have committed.
Making two sequential calls from the Lightning Component - one to setup the data and then after that one to generate the PDF - is one way to work-around the problem.