//引入工具 import PizZip from 'pizzip'; import Docxtemplater from 'docxtemplater'; import JSZipUtils from 'jszip-utils'; import { saveAs } from 'file-saver'; // 加载 .docx 模板文件 function loadFile(url, callback) { JSZipUtils.getBinaryContent(url, callback); } // 下载生成的文档 export function download(file, name) { } // 生成并下载 Word 文档(templatePath是word文档模版地址,data是对应的数据) export function generateWordDocument(templatePath, data, name) { loadFile(templatePath, function (error, content) { if (error) { throw error return; } try { // 加载模板文件内容到 PizZip const zip = new PizZip(content); const doc = new Docxtemplater(zip, { paragraphLoop: true, linebreaks: true, }); // 设置模板中的占位符数据 doc.setData(data); // 渲染文档 doc.render(); // 生成最终的文档 Blob const fileWord = doc.getZip().generate({ type: 'blob', mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', }); saveAs(fileWord, name); // // 返回生成的文档 Blob // resolve(fileWord); } catch (error) { console.error('Error rendering document:', error); throw error } }); }