// openPdfReport.js /** * 通用 PDF 报告打开函数 * @param {Object} options 请求参数,包括 url 和其他 request 选项 * @param {String} reportName 报告名称或文件名前缀(用于下载) */ export function openPdfReport(options = {}, reportName = 'report') { const { url, method = 'GET', data = {}, header = {}, responseType = 'arraybuffer' } = options; if (!url) { uni.showToast({ title: '下载地址缺失', icon: 'none' }); return; } uni.request({ url, method, data, header, responseType, success: (res) => { const { statusCode, data: resData } = res; if (statusCode === 200) { // 处理 ArrayBuffer 类型(二进制 PDF 文件) if (resData instanceof ArrayBuffer) { const blob = new Blob([resData], { type: 'application/pdf' }); // #ifdef H5 const url = window.URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.target = '_blank'; link.download = `${reportName}.pdf`; document.body.appendChild(link); link.click(); document.body.removeChild(link); setTimeout(() => window.URL.revokeObjectURL(url), 1000); // #endif // #ifndef H5 // App 和 小程序端,可使用 base64 或保存到本地文件后用文件路径打开 uni.saveFile({ tempFilePath: uni.arrayBufferToBase64(resData), // 注意:需要 base64 转换插件支持 success: function(saveRes) { uni.openDocument({ filePath: saveRes.savedFilePath, fileType: 'pdf', }); }, fail: () => { uni.showToast({ title: '文件保存失败', icon: 'none' }); } }); // #endif } else if (typeof resData === 'string' && resData.startsWith('http')) { // 后端返回 PDF 的在线 URL // H5 直接打开 // #ifdef H5 window.open(resData, '_blank'); // #endif // #ifndef H5 uni.downloadFile({ url: resData, success(downloadRes) { if (downloadRes.statusCode === 200) { uni.openDocument({ filePath: downloadRes.tempFilePath, fileType: 'pdf' }); } else { uni.showToast({ title: 'PDF 打开失败', icon: 'none' }); } }, fail: () => { uni.showToast({ title: 'PDF 下载失败', icon: 'none' }); } }); // #endif } else { uni.showToast({ title: '返回数据格式错误', icon: 'none' }); } } else { uni.showToast({ title: '下载失败', icon: 'none' }); } }, fail: () => { uni.showToast({ title: '请求失败', icon: 'none' }); } }); }