打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
nodejs根据word模板生成文档(方法二)
  const fs = require('fs')
  const JSZip = require('jszip')
  const Docxtemplater = require('docxtemplater')
  const ImageModule = require('open-docxtemplater-image-module')
  //读取模板文件
  var content = fs.readFileSync(path.join(__dirname, '../data/template/doc.docx'), 'binary');
  var zip = new JSZip(content);
  var doc = new Docxtemplater();
  var opts = {
    centered: false,
    getImage: function(tagValue, tagName) {
      console.log(__dirname);
      return fs.readFileSync(path.join(__dirname, '../data/' + tagValue));
    },
    getSize: function(img, tagValue, tagName) {
      return [150, 150];
    }
  }
  doc.attachModule(new ImageModule(opts))
  doc.loadZip(zip);
  doc.setData({
    name1: "内容已被替换1",
    name2: "内容已被替换2",
    value1: "新的值1",
    value2: "新的值2",
    image: "image1.png"
  });

  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, '../data/out/doc.docx'), buf);
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
使用nodejs将html5 canvas base64编码图片保存为文件
剥离模板代码加速Web页面加载 | Tencent AlloyTeam
nodejs按行读取文件和写入文件的demo
【全栈修炼】RESTful架构及实践 修炼宝典
5分钟教你用nodeJS手写一个mock数据服务器
Node.js基础入门第五天
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服