目录

vue3-使用docxtemplater-动态生成docx

目录

vue3 使用docxtemplater 动态生成docx

模版文件docx放到vue工程public下

https://i-blog.csdnimg.cn/direct/df8dfdcdd2184c21a7a3381195dc4913.png 文件内容

https://i-blog.csdnimg.cn/direct/e11b2c4373364efc82e948de9a9af992.png vue文件

<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>

https://i-blog.csdnimg.cn/direct/f4b1f4e3565d4d7caba4d565a02d9b0b.png https://i-blog.csdnimg.cn/direct/66387035f06747db9cbbdec02edcdf50.png