每次使用ReferenceError都会导致jspdf模块崩溃:未定义窗口

时间:2018-02-11 20:18:26

标签: node.js express jspdf

我正在开发一个小项目,可以在node和express中生成pdf,并且一直在尝试使用jspdf npm模块,但不管怎么说,每当我安装该软件包并要求它崩溃我的服务器时。这是我在server.js文件中要求的方式:

var jsPDF = require('jspdf')

这是我尝试运行服务器时给出的响应:

  

(window.AcroForm = function(t){var n = window.AcroForm; n.scale = function(t){return t *(r.internal.scaleFactor / 1)},n.antiScale = function(t ){return 1 / r.internal.scaleFactor * t}; var r = {fields:[],xForms:[],acroFormDictionaryRoot:null,printedOut:!1,internal:null}; e.API.acroformPlugin = r; var i = function(){for(var。in this.acroformPlugin.acroFormDictionaryRoot.Fields){var e = this.acroformPlugin.acroFormDictionaryRoot.Fields [t]; e.hasAnnotation&& a.call(this,e)} },o = function(){if(this.acroformPlugin.acroFormDictionaryRoot)抛出新错误("创建AcroformDictionary时出现异常"); this.acroformPlugin.acroFormDictionaryRoot = new n.AcroFormDictionary,this.acroformPlugin.internal = this.internal,this.acroformPlugin.acroFormDictionaryRoot._eventID = this.internal.events.subscribe(" postPutResources",1),this.internal.events.subscribe(" buildDocument",我),this.internal.events.subscribe(" putCatalog",c)中,this.internal.events.subscribe(" POS

ReferenceError: window is not defined

1 个答案:

答案 0 :(得分:0)

jsPDF库用于客户端(Web浏览器),这就是它期望窗口变量存在的原因。幸运的是,有人已经回答了如何使这个工作服务器端here。取自那个答案:

global.window = {document: {createElementNS: () => {return {}} }};
global.navigator = {};
global.btoa = () => {};

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

var doc = new jsPDF();
doc.text("Hello", 10, 10);
var data = doc.output();

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

delete global.window;
delete global.navigator;
delete global.btoa;