//引入工具 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 { // 新版创建解析器的正确方式(无需 import AngularParser) const parser = (tag, _variable) => { return { get(scope) { if (scope[tag] !== undefined) { return scope[tag] || ''; } // 处理特殊变量(如 $first) if (tag.startsWith('$')) { const varName = tag.slice(1); return scope[varName] || ''; } return ''; } }; }; // 加载模板文件内容到 PizZip const zip = new PizZip(content); const doc = new Docxtemplater(zip, { paragraphLoop: true, linebreaks: true, }); // const parser = new AngularParser(); // doc.setOptions({ parser }); // 设置模板中的占位符数据 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 } }); }