美文网首页
node docx模板引擎

node docx模板引擎

作者: antlove | 来源:发表于2020-12-12 16:44 被阅读0次

环境准备

yarn init --yes
yarn add pizzip docxtemplater

package.json如下

{
  "name": "node-docxtemplater",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "docxtemplater": "^3.19.7",
    "pizzip": "^3.0.6"
  }
}

input.docs


image.png

index.js

const PizZip = require('pizzip');
const Docxtemplater = require('docxtemplater');

const fs = require('fs');
const path = require('path');

// 加载input.docx
const content = fs.readFileSync(path.resolve(__dirname, 'input.docx'), 'binary');
const zip = new PizZip(content);
const doc = new Docxtemplater(zip);

// 设置参数
doc.setData({
    first_name: 'John',
    last_name: 'Doe',
    phone: '0652455478',
    description: 'New Website'
});

// 渲染
doc.render();

// 导出数据
const buf = doc.getZip().generate({type: 'nodebuffer'});
fs.writeFileSync(path.resolve(__dirname, 'output.docx'), buf);

node index.js
输出如下


image.png

相关文章

网友评论

      本文标题:node docx模板引擎

      本文链接:https://www.haomeiwen.com/subject/fyfygktx.html