頁面程式碼:
<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>
方法
//h5預覽pdf h5PdfView(item) { uni.showLoading({ title: '載入中...' }) uni.request({ url: this.baseFileURL + '/pdf/preview/' + item.resourceId, method: 'POST', responseType: 'arraybuffer' }).then(res => { uni.hideLoading() let pdfData = res.data let blob = new Blob([pdfData], { type: 'application/pdf;charset=UTF-8' }) pdfData = window.URL.createObjectURL(blob) this.h5PdfUrl = encodeURIComponent(pdfData) uni.navigateTo({ url: '/subpages/webview/webview?fileUrl=' + this.h5PdfUrl + "&isPdfView=true", }) }) }, //pdf預覽 pdfView(item) { item.fileUrl = this.baseFileURL + '/pdf/preview/' + item.resourceId // #ifdef APP-PLUS switch (uni.getSystemInfoSync().platform) { case "android": console.log("android") uni.navigateTo({ url: '/subpages/webview/webview?fileUrl=' + encodeURI(item.fileUrl) + "&isPdfView=true", }) break; case "ios": console.log("ios") uni.navigateTo({ url: '/subpages/webview/webview?fileUrl=' + encodeURI(item.fileUrl), }) break; } // #endif // #ifdef H5 this.h5PdfView(item) // #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 }
第二種方法
pdf.js
官方地址:http://mozilla.github.io/pdf.js/getting_started