admin管理员组文章数量:1406060
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 badges4 Answers
Reset to default 1The 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');
本文标签: javascriptjsPDF ReferenceError window is not definedStack Overflow
版权声明:本文标题:javascript - jsPDF ReferenceError: window is not defined - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744965490a2634921.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论