Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jsPDF ReferenceError: window is not defined

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?

like image 458
jRyze Avatar asked Dec 13 '17 11:12

jRyze


2 Answers

The problem happen when jsPDF is used in server side. Check this pull request Refactor acroform.js so that it is working in node.js and enable tests for IE 11

like image 174
Leonardo Espinosa Avatar answered Oct 22 '22 01:10

Leonardo Espinosa


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!');
 }
like image 34
Castello Govender Avatar answered Oct 21 '22 23:10

Castello Govender