iOS使用web-view预览pdf文件,Android使用pdf.js + web-view预览。
1.下载pdf.js包
官方地址(mozilla.github.io/pdf.js/gett…)
网盘链接(pan.baidu.com/s/1E3RUiHkn…)
2.把下载的文件放到项目的根目录hybrid/html/下
3.创建previewFile.vue文件
<template>
<view class="container">
<view class="htmlBox">
<web-view v-if="resultUrl" :src="resultUrl" :update-title="false"></web-view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
viewerUrl: '/hybrid/html/web/viewer.html',
resultUrl: '',
}
},
methods: {
//加载ios地址
loadIOSUrl(fileUrl) {
//隐藏加载框
uni.hideLoading()
this.resultUrl = fileUrl;
},
//加载安卓地址
loadAndroidUrl(fileUrl) {
let that = this;
//下载文件
this.downloadPdf(fileUrl).then((tempFilePath) => {
uni.hideLoading();
console.log('下载成功', tempFilePath);
//获取本地路径
let localFilePath = plus.io.convertLocalFileSystemURL(tempFilePath)
//拼接完整路径
that.resultUrl = that.viewerUrl + '?file=' + encodeURIComponent(localFilePath)
})
.catch((error) => {
console.error('下载错误:', error);
uni.hideLoading();
});
},
//下载pdf
downloadPdf(fileUrl) {
return new Promise((resolve, reject) => {
uni.downloadFile({
url: fileUrl,
success: (res) => {
if (res.statusCode === 200) {
uni.getFileInfo({
filePath: res.tempFilePath,
success: (imgInfo) => {
if (imgInfo.size) {
resolve(res.tempFilePath);
} else {
reject(new Error('文件大小是0'));
}
},
fail: (err) => {
reject(err);
}
});
} else {
reject(new Error('下载失败: ' + res.statusCode));
}
},
fail: (err) => {
reject(err);
}
});
});
}
},
onLoad(options) {
uni.showLoading({
title: '加载中'
});
//根据设备 加载不同的地址
let port = uni.getSystemInfoSync().platform
if (port == 'android') {
console.log('Android');
this.loadAndroidUrl(options.fileUrl)
} else if (port == 'ios') {
console.log('iOS');
this.loadIOSUrl(options.fileUrl)
}
}
}
</script>
<style scoped>
.htmlBox {
padding: 0 28rpx;
flex: 1;
overflow-y: auto;
background-color: #fff;
}
</style>
4.跳转预览页面传值
uni.navigateTo({
url: '/pages/previewFile?fileUrl=' + 'http://www.pdfurl.com'
})