javascript - jsPDF ReferenceError: window is not defined - Stack Overflow

I need to create a PDF in Javascript. I have found the npm Package "jsPDF". I have installed

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?

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?

Share Improve this question asked Dec 13, 2017 at 11:29 jRyzejRyze 1311 gold badge1 silver badge5 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 1

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

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!');
 }

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;

replace this:

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

with this:

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744965490a4603653.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信