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

The Real ROI of Salesforce AI
The Real ROI of Salesforce AI: Where Enterprises Actually See Returns in the First 6 Months
Agentforce Commerce: How AI Is Redefining the Future of Shopping
Agentforce Commerce: The Future of AI-Driven Shopping Is Here — And It’s About to Redefine How Brands Sell
Manufacturers Lead in Salesforce AI Adoption
Why US Midwest Manufacturers Are Adopting Salesforce AI Faster Than the Coasts
Salesforce eVerse Explained
Why Salesforce’s eVerse is a Game-Changer — and what it means when choosing your Salesforce Partner
Salesforce Screen Flow and Apex Purpose
Efficient Lead Conversion Using  Salesforce Screen Flow and Apex Purpose
Scroll to Top