How to Generate PDF and Word in LWC Using Visualforce Page

how to generate pdf and word in lwc using visualforce page

Creating documents dynamically can profoundly enrich user interactions and bolster productivity within the Salesforce ecosystem. In this comprehensive walkthrough, we’ll delve into the process of creating PDF and Word documents leveraging the power of Lightning Web Components (LWC) in tandem with a Visualforce page.

Step 1: Building the Lightning Web Component

Begin by creating a Lightning web component with two buttons—’Generate PDF‘ and ‘Generate Word‘—allowing users to download the respective documents.

generateReportPdfAndWord.html:

				
					<template>
    <lightning-card title="Are you Sure you Want to Generate Pdf or word Please Click here to downLoad below">

        <div slot="footer">

        <lightning-button 
            label="Generate Pdf" 
            variant="brand" 
            icon-name="action:download"
            class="slds-p-around_x-small"
            onclick={handleGeneratePDF}>
        </lightning-button>

        <lightning-button 
                label="Generate word" 
                variant="brand" 
                icon-name="action:download"
                class="slds-p-around_x-small"
                onclick={handleGenerateWord}>
        </lightning-button>

        </div>

    </lightning-card>
</template>

				
			

generateReportPdfAndWord.js:

				
					import { LightningElement } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
export default class GenerateReportPdfAndWord extends NavigationMixin(LightningElement) {

    handleGeneratePDF(event){
        this[NavigationMixin.GenerateUrl]({
            type: 'standard__webPage',
            attributes: {
                url:'/apex/GenerateWordVfPage?pdfReport=pdf'
            }
        }).then(generatedUrl => {
            window.open(generatedUrl,'_self');
        });
    }

    handleGenerateWord(){
        this[NavigationMixin.GenerateUrl]({
            type: 'standard__webPage',
            attributes: {
                url:'/apex/GenerateWordVfPage?wordReport=word'
            }
        }).then(generatedUrl => {
            window.open(generatedUrl,'_self');
        });
    }
}

				
			

Step 2: Integrating with a Lightning Application

Next, integrate the created Lightning web component into a Lightning Application using <aura:dependency>.

CallLwcComponet.app:

				
					<aura:application >
	 <aura:dependency resource="generateReportPdfAndWord" />
</aura:application>

				
			

Step 3: Developing the Visualforce Page

Create a Visualforce page named ‘GenerateWordVfPage’ to facilitate the rendering of Lightning Web Components.

GenerateWordVfPage:

				
					<apex:page showHeader="false" sidebar="false"
   
    renderAs="{!renderValue}"
    contentType="{!ContentTypeValue}"
    controller="GenerateReportController">
    <apex:includeLightning />    
    <div id="LightningComponentid" />    
    <script>
    $Lightning.use("c:CallLwcComponent", function() {
        $Lightning.createComponent("c:generateReportPdfAndWord",
        { 
        },
        "LightningComponentid",
        function(cmp) {
            console.log('LWC Component added in VF page');
        });
    });
    </script>
    <body data-rsssl=1>
        <p>Welcome to VF Page</p>
    </body>
</apex:page>
				
			

Step 4: Apex Class Implementation

Implement the Apex class ‘GenerateReportController’ to manage document generation based on user actions.

GenerateReportController.cls:

				
					public with sharing class GenerateReportController {

    public String renderValue{get;private set;}
    public Boolean isPdf{get;private set;}
    public String ContentTypeValue{get;private set;}

    public GenerateReportController() {
        map<String,String> UrlParameterMap = ApexPages.currentPage().getParameters();
        for(String str:UrlParameterMap.keySet()){
            if(str =='pdfReport'){
                this.isPdf=true;
            }
            else if(str =='wordReport'){
                this.isPdf=false;
            }
        }

        if(this.isPdf == true){
            this.renderValue='pdf';
            this.ContentTypeValue='';
            ApexPages.currentPage().getHeaders().put('Content-Disposition', 'attachment; filename="' + getFileName() + '"');
        }
        else if(this.ispdf == false){
            this.ContentTypeValue = 'application/msword#';
            this.ContentTypeValue += this.getWordFileName()+'.doc';
        }
    }


    /**
     * @description Generate PDf File Name
     * @return   return 
     */
    private String getFileName() {
        return 'GenratePdf'+'.pdf';
    }

    /**
     * @description Generate word File Name
     * @return   return 
     */
    private String getWordFileName() {
        return 'GenerateWord';
    }

}

				
			

Output:

With these implemented steps, users can seamlessly generate PDF or Word documents by clicking the respective buttons. Upon clicking ‘Generate PDF’, the PDF document will be downloaded, while ‘Generate Word’ triggers the download of a Word document.

generate pdf or generate word

Conclusion:

By combining Lightning Web Components, Visualforce pages, and Apex classes, generating dynamic documents within Salesforce becomes straightforward, empowering users with efficient document creation capabilities.

Leave a Comment

Your email address will not be published. Required fields are marked *

Recent Posts

future-of-ai-powered-business-solutions
Dreamforce 2024: Unveiling the Future of AI-Powered Business Solutions
gitex 2024 worlds largest tech show
GITEX 2024 |  World's Largest Tech Show - ABSYZ
inclusive practices in women leadership equitable future
Inclusive Practices in Women’s Leadership: Equitable Future
salesforce dreamfest 2024 the highlights of dreamforce 2024
Dreamfest 2024: The highlights of Dreamforce 2024
DocuSign CLM the ultimate tool for managing contracts
DocuSign CLM: The Ultimate Tool for Managing Contracts
Document

How can i help you? close button

powered     by   ABSYZ
Scroll to Top