在微信小程序开发中,PDF文件预览是常见的业务需求。本文将提供一套基于uniapp的完整解决方案,涵盖从后端准备到前端实现的全部细节,并包含性能优化和异常处理最佳实践。
方案概述
本方案采用"下载+预览"两步走策略:
方案概述
本方案采用"下载+预览"两步走策略:
- 使用uni.downloadFile下载PDF文件到本地临时路径
- 使用uni.openDocument打开预览
- 添加完善的错误处理和用户体验优化
完整实现代码
1. 页面结构 (pdf-preview.vue)
<template><view class="pdf-container"><button type="primary" :loading="isLoading" :disabled="isLoading"@click="handlePreview">{{ isLoading ? '加载中...' : '预览PDF文件' }}</button><uni-load-more v-if="showLoadMore" :status="loadStatus" :icon-size="16"/><uni-popup ref="errorPopup" type="message"><uni-popup-message :type="errorType" :message="errorMessage" :duration="3000"/></uni-popup></view> </template>
2. 脚本逻辑
// PDF预览处理 - 带自定义文件名 const handlePDF = () => {const url = 'https://xxxxx.xxx.cn/ainv/zhaoshangzeye-En.pdf?AWSAccessKeyId=723RBFDZAH&Expires=1759278857&Signature=wx8Sy3hpzyQZNttrPEclQqeESnM%3D'; if (url) {const fileName = `中国AI页_${locale.value === 'en' ? 'EN' : 'CN'}.pdf`;const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`;uni.showLoading({ title: '正在预览文档...' });uni.downloadFile({url: url,filePath: filePath,header: {'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15'},success: (res) => {if (res.statusCode === 200) {// #ifdef MP-WEIXINwx.openDocument({filePath: res.filePath || res.tempFilePath,fileType: 'pdf',showMenu: true, // 是否显示右上角菜单,默认 truesuccess: () => {uni.hideLoading();console.log('下载成功,文件名:', fileName);},fail: (err) => {uni.hideLoading();uni.showToast({title: 'PDF打开失败:' + err.errMsg,icon: 'none'});}});}},fail: (err) => {uni.hideLoading();console.error('PDF下载失败:', err);uni.showToast({title: 'PDF下载失败:' + err.errMsg,icon: 'none'});}});} else {uni.showToast({title: '暂无文件',icon: 'none'});} };
3.多文件预览
// 实现PDF列表预览
export default {data() {return {pdfList: [{ id: 1, name: '用户协议', url: '...' },{ id: 2, name: '隐私政策', url: '...' }]}},methods: {previewItem(item) {uni.showActionSheet({itemList: ['预览', '分享'],success: (res) => {if (res.tapIndex === 0) {this.pdfUrl = item.url;this.handlePreview();}}});}}
}
部署注意事项
