In LWC, there isn’t a built-in way to generate PDFs, so you usually go with (Apex + Visualforce )
The Apex method returns the PDF as a Base64 string, which you can download from your LWC.
public with sharing class PdfController {
@AuraEnabled
public static String generatePdf(Id recordId){
PageReference pg = Page.MyPdfPage;
pg.getParameters().put('id', recordId);
Blob b = Test.isRunningTest() ? Blob.valueOf('test') : pg.getContentAsPDF();
return EncodingUtil.base64Encode(b);
}
}
import generatePdf from '@salesforce/apex/PdfController.generatePdf';
async downloadPdf() {
const base64 = await generatePdf({ recordId: this.recordId });
const link = document.createElement('a');
link.href = 'data:application/pdf;base64,' + base64;
link.download = 'MyFile.pdf';
link.click();
}
This works well when you want Salesforce data, merge fields, and proper formatting using VF.
답변 4개