+ Start a Discussion
SK SGSSK SGS 

generating PDF using Lightning Components

Dear Community,
I am new to Lightning experience,i have some knowledge about lightning.i tried to generate the pdf for Account or any standard or custom object.i wrote the some logic the pfd is generated with empty sheet,i want all the fields of the perticular object which is i mentioned.i think i missed some logic in my components/controllers.
can any one suggest where i did mistake and also can tell me how to generate the pdf for perticular object either custom or standard
my code is 
Apex class:
public class DataDisplayController {
    public String PDFData{get;set;}
    
    public DataDisplayController(){
        
        PDFData = '';
    }
    public PageReference downloadPDF(){
        System.PageReference pageRef = new System.PageReference('/apex/PDFGenerator');
        //ensure pdf downloads and is assigned with defined name
        pageRef.getHeaders().put('content-disposition', 'attachment; filename=TestPDF.pdf');
        
        return pageRef;
    }
    }
Component:
<aura:component >
    <aura:attribute name = "sendData" type = "Account"/>
    <lightning:button label = "Download Document" onclick = "{!c.downloadDocument}" />
    
</aura:component>

client-side controller.js
({
 downloadDocument : function(component, event, helper){

  var sendDataProc = component.get("v.sendData");
  var dataToSend = {
     "label" : "This is test"
  }; //this is data you want to send for PDF generation

  //invoke vf page js method
  sendDataProc(dataToSend, function(){
              
  });
 }
})
Helper.js
({
    helperMethod : function(component,callbackMethod) {
        var action = component.get("c.download");
        action.setCallback(this,function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
                var generatePdf = reponse.getReturnValue();
                component.set("v.sendData",generatePdf);
                console.log('pdf generated successfully');
                
            }
            else{
                console.log('unable to generate the pdf');
            }
        });
        $A.enqueueAction(action);
        
    }
})
VF Page:
<apex:page controller="DataDisplayController" showHeader="false">
    <apex:includeLightning />
    
    <apex:form>
        <apex:inputHidden id="hidData" value="{!PDFData}"/>
        <apex:actionFunction name="jsGeneratePDF" action="{!downloadPDF}"/>
        <div id = "lightning" />
        
        <script>
            function saveData(data, callback){
            var hidData = document.getElementById('{!$Component.hidData}');
            hidData.value = JSON.stringify(data);
            
            //invoke PDF Generation
            jsGeneratePDF();
         
            //invoke callback;
            if(typeof callback == 'function') callback();
        }
        
        
        function loadComponents(){
            console.log("Loading lightning component: DataProcessor");
            
            $Lightning.use("c:LightningPDFGeneratorDemoApp", function() {
                $Lightning.createComponent("c:DataProcessor",
                { 
                    sendData : saveData
                },
                "lightning",
                function(cmp) {
                    // do some stuff
                });
            });
        }
        
        loadComponents();
        </script>            
           </apex:form>
</apex:page>

<apex:page controller="DataDisplayController"  renderAs="pdf">
    {!PDFData}
</apex:page>

App:
<aura:application extends = "ltng:outApp" >
    <c:DataProcessor />
    
</aura:application>

thanks in advance
Khan AnasKhan Anas (Salesforce Developers) 
Hi,

I trust you are doing very well.

You can generate a PDF in Lightning Component in two ways.
  • You can create a Visualforce page with render as pdf and embed it in the Lightning component.
https://medium.com/@ToAnshulVerma/salesforce-lightning-generate-pdf-from-lightning-components-with-in-memory-data-cd5dffe0fe25

http://www.vermanshul.com/2017/07/lightning-generate-pdf-from-lightning.html
 
  • Use PDF.JS library or other javascript libraries to render pdf.
https://github.com/kumarrk21/PDFViewer


I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future.

Thanks and Regards,
Khan Anas
Vijay KanugondaVijay Kanugonda

Hi,

How to generate pdf from Lightning Web Component? 

we don't want to generate pdf from any vfpage or iframe

Thanks,
Vijay Kanugonda.

Brian WaughBrian Waugh
Vijay,

Total agreement. People on here just want to regurtitate the same stuff rather than get creative and try things. I'm attempting to use pageReference from a LWC to see if you can use the same .getContentAsPDF() method you can on the other pageReference object from an Apex class. I'll report back.
Brian WaughBrian Waugh
For reference, i'm looking into doing the following in an apex class:

Key takeways:
  1. Get a pagereference from a LWC component page in a community which will have information passed to it in order to populate a PDF.
  2. Use .getContentAsPDF() to generate the blob and then generate the file as a contentDocument using contentVersion.
I haven't tested the below code but here's an example of what i'm using for my test.  I'm unsure if pageReference will be able to pull content from a community page let alone a LWC component but i'll give it a shot.

 
@AuraEnabled
    public static ContentVersion generateContentVersionFile(Boolean doInsert) {
        return generateNewContentVersionVersion(null, doInsert);
    }

    @AuraEnabled
    public static ContentVersion generateNewContentVersionVersion(Id contentDocId, Boolean doInsert) {

        PageReference pr = new PageReference('/Installations/s/'); 
        ContentVersion cont = new ContentVersion();

        Blob b = pr.getContentAsPDF();

        if (contentDocId != null) {
            cont.ContentDocumentId = contentDocId;
        }

        cont.Title = 'Test PDF';
        cont.PathOnClient = 'file_' + Datetime.now().getTime() + '.pdf';
        cont.VersionData = b;
        cont.Origin = 'H';

        if (doInsert) {
            insert cont;
        }
    }

 
Dane Junkin 9Dane Junkin 9
How did it go?
Trevor RoyTrevor Roy

FWIW, this is still a pretty bad situation. I've tried to do a couple of things that didn't work, and ultimately had to resort to creating a VFP strictly for the PDF generating tasks. 

It should be noted the biggest issue seems to be the PDF renderer. It just can't handle modern CSS, which means none of the SLDS CSS seems to work. My initial plan had been to convert the LWC markup into basic HTML with SLDS styles then pass that into Blob.toPDF(). If I was smart I would have tried it with minimal content, but I'm overly ambitious and translated the whole thing, it of course failed miserably with server errors.

Recreating the whole thing as VFP with as basic CSS as I could manage still works, so I would suggest biting the bullet and taking that approach. Frustrating but for now seems like the best on-platform solution. I'm investigating other JS based approaches but unfortunately timelines won't allow me to fully research that for my current project.

 

To Salesforce:

It's really frustrating to be pushed into new dev approaches but never get full feature parity. Since PDF generation is a very common use case could you please revive the pilot program from 2017 to improve/create LWC aware PDF conversion? It's sorely needed and I'm not enjoying the duplicative effort necessary to build a nice UI and then dumb it down for a PDF.

ABHILASH AABHILASH A

Upvote the Idea for pdf Generation using LWC.

https://trailblazer.salesforce.com/ideaView?id=0874V000000lgVHQAY

PDF Generation Using Lightning Web Component.