1

Trying to generate PDF with JSPDF library but getting below error message when I'm trying to preview the PDF through Community or record pages in salesforce.

Error TypeError: Cannot destructure property 'jsPDF' of 'window.jspdf' as it is undefined

Here is the code I have written in my LWC

import jsPDF from '@salesforce/resourceUrl/jsPDF';
import { loadScript } from 'lightning/platformResourceLoader';

renderedCallback() {
        Promise.all([
            loadScript(this, jsPDF)
        ]);
    }

generate() {
        const { jsPDF } = window.jspdf;
        const doc = new jsPDF('p', 'in', 'letter');
        //Sets the text color setTextColor(ch1, ch2, ch3, ch4) 
        doc.setTextColor(100);
    doc.save("abc.pdf");
    }

Looks like it's failing on const { jsPDF } = window.jspdf; this line and returning the above error.

Do you guys have any clue about this? Has anyone got jsPDF working in LWC?

3
  • 1
    Does this answer your question? How to create pdf using pdfjs library in lwc
    – identigral
    Commented Sep 8, 2023 at 17:09
  • No @identigral, Tried both but no luck.. Still getting Error TypeError: Cannot destructure property 'jsPDF' of 'window.jspdf' as it is undefined Commented Sep 8, 2023 at 19:01
  • I'm facing the same issue, were you able to resolve it?
    – AjFmO
    Commented Nov 3, 2023 at 17:43

2 Answers 2

0

Use this JSPDF lib and AutoTable lib

Load script in render callback like below

jsPdfInitialized = false;

renderedCallback() {
    if (this.jsPdfInitialized) {
        return;
    }
    this.jsPdfInitialized = true;
    loadScript(this, jsPDFScript)
        .then(() => {
            loadScript(this, jsPDFAutoTableScript);
        })
        .catch(error => {
            throw error;
        });
}
0

I finally got this working today, and your question helped me through some of it, thank you! I think you just need to do:

const doc = new window.jspdf.jsPDF('p', 'in', 'letter');

i.e.:

import jsPDF from '@salesforce/resourceUrl/jsPDF';
import { loadScript } from 'lightning/platformResourceLoader';

renderedCallback() {
        Promise.all([
            loadScript(this, jsPDF)
        ]);
    }

generate() {
        const doc = new window.jspdf.jsPDF('p', 'in', 'letter');
        //Sets the text color setTextColor(ch1, ch2, ch3, ch4) 
        doc.setTextColor(100);
    doc.save("abc.pdf");
    }

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .