zoukankan      html  css  js  c++  java
  • nodejs根据word模板生成文档(方法二)

    【推荐该方法,模板比较简洁】

    1,代码,

    这里采用的模块为

    docxtemplater 和 open-docxtemplater-image-module,均为开源(docxtemplater 有收费的image模块)
    
    
      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);

    2,模板格式

    其中,模板文件格式为:

    //文本替换模板
    {name1}--------------{value1} {name2}--------------{value2} //图片替换模板 {%image}

     数据结构

  • 相关阅读:
    c++ 对特定进程的内存监控
    算法提高 快乐司机 (并不快乐)
    蓝桥 :算法提高 排列数(深度优先)
    算法提高 9-3摩尔斯电码
    算法提高 队列操作
    C++set 和 multiset的使用
    软件工程实践第三次随笔
    软件工程实践第二次随笔
    软件工程实践第一次随笔
    《构建之法》项目管理&典型用户和场景
  • 原文地址:https://www.cnblogs.com/vichang/p/10416449.html
Copyright © 2011-2022 走看看