Mytutorialrack

Creating PDFs Using LWC

In Salesforce, the most common way to create PDFs is by using a Visualforce page. However, there are other methods too, like using Lightning Web Components (LWC) with third-party libraries such as jsPDF. In Salesforce, Creating PDFs Using LWC(Lightning Web Components ) to build modern, interactive user interfaces. With the help of a popular third-party library like jsPdf, you can easily generate PDFs. In this blog post, we’ll guide you through the process step by step with a simple example.

What Are Lightning Web Components (LWC)?

Lightning Web Components (LWC) is a framework for creating modern user interfaces on the web, mobile apps, and digital experiences on the Salesforce Platform. With LWC, developers can use W3C web standards to build custom HTML elements with JavaScript and HTML, applying foundational concepts like HTML templates and shadow DOM while working seamlessly with Salesforce data. LWC is backwards compatible with Aura components; they can coexist and interoperate on a page.

Why Use jsPdf for Creating PDFs Using LWC?

jsPdf is a lightweight JavaScript library that enables you to generate PDF documents in the browser. It is perfect for creating PDFs dynamically, without needing a backend service. This makes jsPdf a great option when working with LWC since it allows your users to download or view PDFs directly from their web browser.

Step-by-Step Guide to Creating a PDF in LWC

Download the jsPdf and Upload it as Static Resources

  • Download jsPdf: Go to the jsPdf GitHub repository and download the file(jspdf.umd.min.js file).
  • Upload as a Static Resource: In Salesforce, Go to Setup then Static Resources and upload the jsPdf file. Name the resource –

Create the LWC Component

  • Now, let’s create an LWC component named ‘pdfGenerator‘ in that we use jsPdf library which we have uploaded as static resource.
pdfGenerator.html

<template>
    <lightning-card title="PDF Generator" icon-name="custom:custom63">
        <div class="slds-m-around_medium">
            <lightning-input label="Enter Title" value={title} onchange={handleTitleChange}></lightning-input>
            <lightning-textarea label="Content" value={content} onchange={handleContentChange}></lightning-textarea>
            <lightning-button variant="brand" label="Generate PDF" title="Generate PDF" onclick={generatePdf} class="slds-m-top_medium"></lightning-button>
        </div>
    </lightning-card>
</template>

pdfGenerator.js

import { LightningElement, track } from 'lwc';
import { loadScript } from 'lightning/platformResourceLoader';
import jsPdf from '@salesforce/resourceUrl/jsPDFLibrary';

export default class PdfGenerator extends LightningElement {
    @track title = '';
    @track content = '';

    jsPdfInitialized = false;

    
    renderedCallback() {
        if (this.jsPdfInitialized) {
            return;
        }
        this.jsPdfInitialized = true;

        loadScript(this, jsPdf)
            .then(() => {
                console.log('jsPdf loaded successfully');
            })
            .catch(error => {
                console.error('Error loading jsPdf', error);
            });
    }

    handleTitleChange(event) {
        this.title = event.target.value;
    }

    handleContentChange(event) {
        this.content = event.target.value;
    }

    generatePdf() {
        
        if (typeof window.jspdf !== 'undefined' && window.jspdf.jsPDF) {
            
            const doc = new window.jspdf.jsPDF();
           
            doc.setFontSize(22);
            doc.text(this.title || 'Untitled Document', 20, 20);
            
            doc.setFontSize(16);
            doc.text(this.content || 'No content provided.', 20, 40);
           
            doc.save('generatedDocument.pdf');
        } else {
            console.error('jsPdf library not loaded');
        }
    }
}
pdfGenerator.js-meta.xml

<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
	<apiVersion>62.0</apiVersion>
	<isExposed>true</isExposed>
	<targets>
		<target>lightning__AppPage</target>
		<target>lightning__HomePage</target>
		<target>lightning__RecordPage</target>
		<target>lightning__RecordAction</target>
	</targets>
</LightningComponentBundle>
Creating PDFs Using LWC

In this , the title and content entered in the form will be dynamically added to the generated PDF.

Here’s how it works:

User Input:

  • The user enters a title in the input field.
  • The user enters content in the textarea field.

Handling Input Changes:

  • The handleTitleChange and handleContentChange methods store the user input in tracked variables (title and content).

Generating the PDF:

  • When the user clicks on the “Generate PDF” button, the generatePdf() function runs.
  • The function creates a new jsPdf document.
  • It sets the title at the top of the PDF.
  • It adds the content below the title.
  • Finally the PDF is downloaded using doc.save('generatedDocument.pdf').

Conclusion

With the help of Lightning Web Components (LWC) and jsPdf together is a powerful way to create/generate PDFs directly without VisualForce Page.This guide showed you ,how to load a third-party library as a static resource, capture user inputs, and generate a simple PDF document using jsPdf library.

This approach makes it easy to generate reports, invoices, or any other PDF documents dynamically. You can also customize the PDF further by adding images, tables, or advanced formatting.

You can deepen your understanding of Data Cloud by exploring our comprehensive course on Salesforce Data Cloud and Agentforce – Building Agents and also check out our latest blogs on our websites for additional knowledge about salesforce.

Share:

Recent Posts