uniapp android和微信小程序实现PDF在线预览

在使用uniapp开发移动端时,微信开发者工具里webview能正常打开后端接口返回的pdf文件流。正式发布后,在配置了业务域名和服务器域名的前提下,预览pdf文件却只能看到白屏,因此我猜测微信小程序不能通过webview读取文件流。这个想法有问题的话请大家给与指正。

后来我通过uniapp api将文件下载在临时目录,再调用api打开,实现了微信小程序的预览。但在安卓端会调用安装的WPS打开,如果用户没有安装pdf阅读器,则无法打开,造成了不好的用户体验。因此,手机端我用pdf.js实现在线预览。

后端的api接口如下:

java 复制代码
/**
     * @功能:pdf预览
     */
    @IgnoreAuth
    @RequestMapping("/pdf/preview/**")
    public void pdfPreviewIframe(HttpServletRequest request, HttpServletResponse response) {
        String imgPath = extractPathFromPattern(request);
        // 其余处理略
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = MinioUtil.getMinioFile(imgPath);
            outputStream = response.getOutputStream();
            response.setContentType("application/pdf; charset=UTF-8");
            byte[] buf = new byte[1024];
            int len;
            while ((len = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, len);
            }
            response.flushBuffer();
        } catch (Exception e) {
            log.error("预览文件失败" + e.getMessage());
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.info("imgPath:{}", imgPath);
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

一、下载pdf.js

http://mozilla.github.io/pdf.js/getting_started

二、解压文件并引入到项目

说明:网上很多案例说,在项目目录下创建hybrid文件夹,把解压后的文件全部放到里面的方式我试了后行不通。

在static目录下新建pdfview目录,将解压后的文件拷贝到该目录下。如下图所示:

注释viewer.mjs代码,pdf.js不支持加载跨域文件,会报 "file origin does not match viewer'"错误:

三、 webview内预览pdf

html 复制代码
<template>
	<view>
		<web-view :src="fileUrl"></web-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				fileUrl: "",
				pdfViewUrl: '/static/pdfview/web/viewer.html'
			}
		},
		onLoad(options) {
			this.fileUrl = decodeURI(options.fileUrl)
			if (!!options.isPdfView) {
				this.fileUrl = this.pdfViewUrl + '?file=' + encodeURI(this.fileUrl)
			}
		},
		methods: {

		}
	}
</script>

<style>

</style>

四、app、微信小程序分别预览

TypeScript 复制代码
//pdf预览
			pdfView(item) {
				uni.showLoading({
					title: '加载中...'
				})
				item.fileUrl = this.baseFileURL + '/pdf/preview/' + item.resourceId

				// #ifdef APP-PLUS
				uni.navigateTo({
					url: '/subpages/webview/webview?fileUrl=' + encodeURI(item.fileUrl) + "&isPdfView=true",
				})
				// #endif

				//  #ifdef MP-WEIXIN
				let fileName = item.resourceId.substring(item.resourceId.lastIndexOf('/') + 1);
				uni.downloadFile({
					url: item.fileUrl, //文件地址
					filePath: wx.env.USER_DATA_PATH + '/' + fileName,
					success: function(res) {
						const filePath = res.filePath || res.tempFilePath;
						uni.openDocument({
							filePath: filePath,
							showMenu: false,
							success: function(res) {}
						});
					}
				});
				// #endif
				uni.hideLoading()
			},

五:预览效果

相关推荐
用户904706683575 小时前
uniapp Vue3版本,用pinia存储持久化插件pinia-plugin-persistedstate对微信小程序的配置
前端·uni-app
细节控菜鸡6 小时前
【2025最新】uniapp 中基于 request 封装实现多文件上传完整指南
uni-app
fakaifa6 小时前
【全开源】企业微信SCRM社群营销高级版系统+uniapp前端
uni-app·开源·企业微信·scrm·源码下载·企业微信scrm
棋子一名9 小时前
跑马灯组件 Vue2/Vue3/uni-app/微信小程序
微信小程序·小程序·uni-app·vue·js
游戏开发爱好者810 小时前
BShare HTTPS 集成与排查实战,从 SDK 接入到 iOS 真机调试(bshare https、签名、回调、抓包)
android·ios·小程序·https·uni-app·iphone·webview
2501_9160088911 小时前
iOS 26 系统流畅度实战指南|流畅体验检测|滑动顺畅对比
android·macos·ios·小程序·uni-app·cocoa·iphone
2501_9151063213 小时前
苹果软件加固与 iOS App 混淆完整指南,IPA 文件加密、无源码混淆与代码保护实战
android·ios·小程序·https·uni-app·iphone·webview
2501_9159214313 小时前
iOS 26 崩溃日志解析,新版系统下崩溃获取与诊断策略
android·ios·小程序·uni-app·cocoa·iphone·策略模式
2501_9160137416 小时前
iOS 推送开发完整指南,APNs 配置、证书申请、远程推送实现与上架调试经验分享
android·ios·小程序·https·uni-app·iphone·webview
2501_9159090620 小时前
HTML5 与 HTTPS,页面能力、必要性、常见问题与实战排查
前端·ios·小程序·https·uni-app·iphone·html5