vue3 使用docxtemplater 动态生成docx

模版文件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>

相关推荐
梅梅绵绵冰9 小时前
SpringMVC快速入门
前端
kirkWang9 小时前
HarmonyOS 6.0 服务卡片实战:把「轻食刻」装进桌面,让轻断食一眼可控
前端
1024小神9 小时前
VNBarcodeObservation的结果中observation.boundingBox 是什么类型?
前端
xun_xing9 小时前
Javascript的Iterator和Generator
前端·javascript
秃了才能变得更强9 小时前
React Native 新、旧架构集成原生模块方式
前端
1024小神9 小时前
swift中VNDetectBarcodesRequest VNImageRequestHandler 是什么?有什么作用?VN是什么意思
前端
加个鸡腿儿9 小时前
React项目实战 | 修复Table可展开行,点击一个全部展开
前端·react.js·编程语言
在泡泡里9 小时前
前端规范【五】biomejs自动化工具-ultracite
前端
_野猪佩奇_牛马版9 小时前
node/py实现 qwen多轮对话
前端
残冬醉离殇9 小时前
函数柯里化(curry)是什么?🤔
前端·javascript