环境准备
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
网友评论