模版文件docx放到vue工程public下
文件内容
vue文件
html
<template>
<div>
<button @click="generateDocument">生成Word文档</button>
</div>
</template>
<script>
import PizZip from 'pizzip';
import Docxtemplater from 'docxtemplater';
import { saveAs } from 'file-saver';
import PizZipUtils from 'pizzip/utils/index.js';
function loadFile(url, callback) {
PizZipUtils.getBinaryContent(url, callback);
}
export default {
methods: {
generateDocument() {
// 假设你的模板文件位于 public 文件夹下
const templatePath = '/docx/tepmlate/testtemplate2.docx'; // 替换为你的模板路径
loadFile(templatePath, (error, content) => {
if (error) throw error;
const zip = new PizZip(content);
const doc = new Docxtemplater(zip, {
paragraphLoop: true,
linebreaks: true,
});
// 渲染文档,替换占位符
doc.render({
first_name: 'John'
});
// 生成Blob文件
const blob = doc.getZip().generate({ type: 'blob' });
// 下载文件
saveAs(blob, 'output.docx');
});
}
}
}
</script>