###背景介绍
目前工作中需要将图片转换为pdf,并且上传到s3保存. 想到的思路就是使用jspdf,将图片添加上去,然后输出的格式为base64
.
遇到的问题
node环境下,jspdf不支持将png添加到pdf上.并且会提示window is not defiend
解决方法
1.支持png:引入png-js
模块
2.defined window:
global.window = {
document: {
createElementNS: () => {
return {}
}
}
};
global.navigator = {};
global.atob = require('atob');
具体代码如下
async convertPngToPdf(imageBase64) {
global.PNG = require('png-js');
global.window = {
document: {
createElementNS: () => {
return {}
}
}
};
global.navigator = {};
global.atob = require('atob');
const JSPDF = require('jspdf');
const doc = new JSPDF('', 'pt', 'a4');
doc.addImage(`data:image/png;base64,${imageBase64}`, 'PNG', 0, 0, 457, 842);
//将文件转换为arraybuffer,然后在转换成base64
const arraybuffer = doc.output('arraybuffer');
return new Buffer(arraybuffer, 'base64').toString('base64');
}
###参考链接
NodeJs says “ReferenceError: window is not defined” with jsPDF