6
votes

I need to create a PDF in Javascript. I have found the npm Package "jsPDF". I have installed "jsPDF" with npm install jspdf. It succesfully installed, but when I execute the fowolling code:

const jspdf = require ('jspdf');
let doc = new jspdf();

doc.setFontSize(40);
doc.text(35, 25, 'PDF with jsPDF!');

I get an error which says ReferenceError: window is not defined.

Do anybody know what's wrong in my code or if some imports are missing?

4

4 Answers

1
votes
1
votes

What ended up working for me, since I was incorporating Server Side Rendering, was creating an environment variable to see if I was in the browser then wrapping your code above with this flag.

if(process.env.BROWSER){
    const jspdf = require ('jspdf');
    let doc = new jspdf();

    doc.setFontSize(40);
    doc.text(35, 25, 'PDF with jsPDF!');
 }
0
votes

To fix this:

npm install jspdf

In the node_modules/jspdf/dist/ folder you will see a jspdf.node.min.js file replace jspdf.min.js with this.

Then the following code will generate a pdf.

//This is a fix for the ReferenceError: window is not defined
//
global.window = {document: {createElementNS: () => {return {}} }};
global.navigator = {};
global.btoa = () => {};

var fs = require('fs');
var jsPDF = require('jspdf');

var doc = new jsPDF();

doc.setFontSize(40);
doc.text(35, 25, 'PDF with jsPDF!');

var data = doc.output();

fs.writeFileSync('./document.pdf', data);

delete global.window;
delete global.navigator;
delete global.btoa;
-3
votes

replace this:

const jspdf = require ('jspdf'); let doc = new jspdf();

with this:

import jsPDF from 'jspdf'; var doc = new jsPDF('p', 'pt');