Blog Post

How to generate PDFs in Salesforce using Lightning Web Components and jsPDF

Illustration: How to generate PDFs in Salesforce using Lightning Web Components and jsPDF

This tutorial will guide you through the process of creating a Lightning web component that leverages the jsPDF library to dynamically generate PDF documents directly within Salesforce. Additionally, you’ll explore the limitations of client-side PDF generation and gain insights into when to consider alternative approaches.

Prerequisites

About Nutrient Salesforce SDK

If you work with PDF documents in Salesforce, Nutrient provides a client-side JavaScript library that can be integrated into a Lightning web component to enable opening, editing, and saving PDFs from a web browser. Some of our most popular features include the ability to:

  • View and edit PDF content directly in Salesforce

  • Collaborate on documents by highlighting text and adding notes or stamps

  • Organize documents by adding, deleting, rotating, or reordering pages

  • Programmatically fill PDF forms with information from Salesforce

  • Add an eSignature by drawing, typing, or uploading an image of your signature

  • Permanently redact sensitive information like email addresses, SSNs, phone numbers, and more

Step 1 — Setting up your development environment

  1. Open Visual Studio Code on your computer.

  2. Log in to your Salesforce developer account by pressing Control-Shift-P (on Windows) or Command-Shift-P (on macOS). Then, select SFDX: Authorize an Org > Project Default and press Enter. This action will redirect you to log in to your Salesforce organization.

Step 2 — Creating a new Lightning web component

  1. In Visual Studio Code, open the Command Palette using Control-Shift-P (on Windows) or Command-Shift-P (on macOS).

  2. Type SFDX and select SFDX: Create Lightning Web Component (not SFDX: Create Lightning Component).

  3. Enter PdfGenerator as the name of the new component.

  4. Press Enter to accept the default path, force-app/main/default/lwc.

  5. Press Enter again.

Step 3 — Designing the component

  1. Open the pdfGenerator.html file and add the following content:

<template>
	<div>
		<h1>PDF Generator</h1>
		<lightning-button
			label="Generate PDF"
			onclick="{handleGeneratePDF}"
		></lightning-button>
	</div>
</template>

Step 4 — Including a PDF generation library

Static resources play a crucial role in Salesforce development by allowing you to upload and reference external files, such as JavaScript libraries and stylesheets, within your Salesforce organization. Since Lightning web components operate within a secure context and have limitations on how external resources are loaded, using static resources is the recommended approach to bring in third-party libraries.

To generate a PDF, you’ll need a PDF generation library. One popular choice is jsPDF. Create a static resource in Salesforce to hold the jsPDF library.

  1. Log in to your Salesforce developer account.

  2. Click App Launcher (grid icon) and search for Static Resources.

  3. Click Static Resources to access the Static Resources page.

  4. Click New.

  5. Enter a name for the static resource. Name it something like jsPDFLibrary.

  6. Leave the Cache Control field set to Public.

  7. Choose the Upload File option and select the jspdf.umd.min.js file in the node_modules/jspdf/dist folder. This is the jsPDF library you want to upload. Double-check that the name of the static resource you uploaded is exactly jspdf.umd.min.js, as the name is case-sensitive.

  8. Click Save.

static resource

Step 5 — Implementing PDF generation logic

  1. Open the pdfGenerator.js file to handle PDF generation. This function will use the jsPDF library to generate the PDF document based on the content you’ve designed.

Load the static resource containing the jsPDF library using loadScript:

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

export default class PdfGenerator extends LightningElement {
	jsPDFInitialized = false;

	renderedCallback() {
		if (!this.jsPDFInitialized) {
			this.jsPDFInitialized = true;
			loadScript(this, JS_PDF)
				.then(() => {
					console.log('jsPDF library loaded successfully');
				})
				.catch((error) => {
					console.error('Error loading jsPDF library', error);
				});
		}
	}

	handleGeneratePDF() {
		if (this.jsPDFInitialized) {
			// Make sure to correctly reference the loaded jsPDF library.
			const doc = new window.jspdf.jsPDF();

			// Add content to the PDF.
			doc.text('Hello PDF!', 10, 10);

			// Save the PDF.
			doc.save('generated_pdf.pdf');
		} else {
			console.error('jsPDF library not initialized');
		}
	}
}
  1. In the pdfGenerator.js-meta.xml file, add the following lines to the targets section:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>58.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
      </targets>
</LightningComponentBundle>

Step 6 — Pushing changes to your organization

  1. Press Control-Shift-P (on Windows) or Command-Shift-P (on macOS) to open the Command Palette.

  2. Type SFDX and select SFDX: Deploy This Source to Org.

Step 7 — Verify the component in your organization

  1. Open your Salesforce organization.

  2. Click App Launcher (grid icon) and search for Sales.

  3. Click the setup gear icon, and then select Edit Page.

  4. Drag the pdfGenerator component from the custom section to the page.

  5. Save the page.

  6. Click Generate PDF to create a PDF document.

adding component to lightning page

Upon successful completion, feel free to deploy your Lightning web component to your production environment and customize it to suit your Salesforce application’s needs.

Limitations of PDF generation using jsPDF and LWC

  1. Client-side processing — jsPDF generates PDFs on the client side, which could impact performance for complex or large PDFs.

  2. Styling and layout — jsPDF is suited for basic PDFs; complex styling and layouts might require additional effort.

  3. Advanced features — Advanced elements like complex tables, interactive forms, or intricate charts may require extra handling.

Conclusion

By following the steps outlined in this tutorial, you’ve learned how to integrate a PDF generation library and create PDFs on the fly in Salesforce. While jsPDF offers a powerful solution for simple PDF generation, it’s important to consider the limitations and constraints of client-side PDF generation. For more complex PDF requirements, or if you’re looking for advanced features, you might explore other options, including integrating with server-side PDF generation services or commercial PDF libraries. Always assess your project’s specific requirements and constraints before deciding on a solution.

We offer a Salesforce PDF library that can be used to add PDF viewing, annotation, and editing to your native Salesforce application. Get started with a free trial, or contact our Sales team for licensing questions.

FAQ

Here are a few frequently asked questions about generating PDFs in Salesforce.

How can I generate PDFs in Salesforce using Lightning Web Components?

To generate PDFs in Salesforce using Lightning Web Components (LWC), you can use the jsPDF library. First, create a Lightning web component and include the jsPDF library as a static resource in Salesforce. Then, implement the PDF generation logic in the component’s JavaScript file to create and download the PDF.

What are the limitations of using jsPDF for PDF generation in Salesforce?

jsPDF generates PDFs on the client side, which may impact performance for complex or large PDFs. Additionally, jsPDF is best suited for basic PDFs; complex styling, layouts, and advanced features like interactive forms may require extra handling or alternative solutions.

What advanced PDF features can Nutrient Salesforce SDK provide?

Nutrient Salesforce SDK offers advanced features such as viewing and editing PDF content directly in Salesforce, collaborating on documents, filling PDF forms programmatically, adding eSignatures, and redacting sensitive information. It provides more sophisticated capabilities compared to basic libraries like jsPDF.

How can I deploy my Lightning web component to my Salesforce production environment?

After creating and testing your Lightning web component in your Salesforce developer environment, use the Salesforce CLI or Visual Studio Code to deploy your changes to the production environment. Ensure that the component is properly configured and tested before deployment.

Author
Hulya Masharipov Technical Writer

Hulya is a frontend web developer and technical writer at PSPDFKit who enjoys creating responsive, scalable, and maintainable web experiences. She’s passionate about open source, web accessibility, cybersecurity privacy, and blockchain.

Explore related topics

Share post
Free trial Ready to get started?
Free trial