import JSZip from 'jszip'; import { saveAs } from 'file-saver'; import JSZipUtils from 'jszip-utils'; import Docxtemplater from 'docxtemplater'; import ImageModule from 'docxtemplater-image-module-free'; const loadImage = async (tagValue) => { try { const response = await fetch(tagValue); if (!response.ok) { throw new Error('Network response was not ok'); } const blob = await response.blob(); return URL.createObjectURL(blob); } catch (error) { console.error('There was a problem with the fetch operation:', error); return null; // 返回 null 或者合适的错误处理 } }; export const exportDocx = async (tempDocxPath, dataList, zipFileName) => { try { // 加载模板文件 const content = await new Promise((resolve, reject) => { JSZipUtils.getBinaryContent(tempDocxPath, (error, content) => { if (error) { reject(error); } else { resolve(content); } }); }); // 初始化 JSZip 实例,用于打包多个文件 const zip = new JSZip(); // 遍历每一条数据,生成单独的 .docx 文件 for (let i = 0; i < dataList.length; i++) { const data = dataList[i]; const imageOptions = { async getImage(tagValue) { const imageUrl = await loadImage(tagValue); console.log(imageUrl, "我在这里"); return imageUrl; }, getSize() { return [150, 150]; }, }; const doc = new Docxtemplater(zip, { modules: new ImageModule(imageOptions), }); doc.render({ image: "logo.png", }); const zipContent = doc.getZip(); // 获取 zip 对象 if (!zipContent) { throw new Error('Docxtemplater failed to load zip content.'); } // 生成 .docx 文件 const out = await zipContent.generateAsync({ type: 'blob', mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', }); // 将生成的 .docx 文件添加到 zip 包中 zip.file(`document_${i + 1}.docx`, out); } // 生成 zip 文件并保存 const zipBlob = await zip.generateAsync({ type: 'blob' }); saveAs(zipBlob, zipFileName); console.log(`文件已成功生成并打包为 ${zipFileName}`); } catch (error) { console.error('导出文件时出错:', error); throw error; } };