在docxtemplater 和 open-docxtemplater-image-module按word模板导出图片 遇到个坑记录下

在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);
  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值