在docxtemplater 和 open-docxtemplater-image-module按word模板导出图片 遇到个坑记录下
主要是一直提示 Cannot read property ‘part’ of undefined
在网上搜了好多博客,以及npm官方实例代码测试,都不行,也没找到答案。
最后功夫不负有心人 在github描述发现了这句
真的坑,根据官方或者博客装最新docxtemplater,一准报错,于是赶紧
npm install docxtemplater@3.5 看到控制台没错,我就知道成功了,快两个小时的搜搜查查没白费。
我的模板
导出实例
开心
成功代码
// 模板导出word
const Docxtemplater = require('docxtemplater')
const ImageModule = require('open-docxtemplater-image-module')
const PizZip = require('pizzip');
const path = require('path')// /读取模板文件
var content = fs.readFileSync(path.join(__dirname, '../../docx_template/交底记录导出样板.docx'), 'binary');
console.log(path.join(__dirname, '../../image/tmp/16214454071121001.png'));
var zip = new PizZip(content);
var doc = new Docxtemplater();
// console.log(zip);
var opts = {
centered: true,
getImage: function (tagValue, image) {
console.log(__dirname);
return fs.readFileSync(path.join(__dirname, '../../image/tmp/' + tagValue));
},
getSize: function (img, tagValue, image) {
return [80, 30];
}
}
doc.attachModule(new ImageModule(opts))
.loadZip(zip)
.setData({
image: "16216095120611001.png",
name: 'test'
});
try {
/*
render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
*/
doc.render();
} catch (error) {
var err = {
message: error.message,
name: error.name,
stack: error.stack,
properties: error.properties,
}
// console.log(JSON.stringify(err));
/*
The error thrown here contains additional information when logged with JSON.stringify (it contains a property object).
*/
throw error;
}
var buf = doc.getZip().generate({ type: 'nodebuffer' });
/* buf is a nodejs buffer, you can either write it to a file or do anything else with it.*/
fs.writeFileSync(path.join(__dirname, '../../docx/test.docx'), buf);