nodejs根據word模板生成文檔(方法二)

【推薦該方法,模板比較簡潔】node

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,模板格式

其中,模板文件格式爲:ui

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

 數據結構spa

相關文章
相關標籤/搜索