uni-app 预览pdf文件
- 有一个不下载文件,预览文件的需求,一开始是要求能够预览word文档,但是这个文档只是用来观看的,不需要进行任何修改操作。为啥不预览pdf呢(其实是我菜,没办法做到在线预览word文档,甚至编辑)
- 在网上查看了很多资料,uni-app也看到了一些插件(付费的),实际我这项目是完全没必要预览word的,pdf足够,只是单存的展示一个文件内容。
解决方案
-
pdfjs (不推荐)
-
uni.openDocument({})
- uni-app 自带的打开文件的API,新开页面打开文档,支持格式:doc, xls, ppt, pdf, docx, xlsx, pptx。
- 参数:
- filePath 文件路径 (可通过 downloadFile 获得,注意跨域问题)
- fileType 文件类型 (有效值 doc, xls, ppt, pdf, docx, xlsx, pptx)
- success、fail、complete 回调函数
- H5 使用浏览器打开,当前浏览器不支持则不能打开,PDF 可直接打开,word文件会弹出下载提示
- APP 调用相关应用程序打开,没有则打不开。可以调用WPS打开。
- 参考 https://blog.csdn.net/qq_42597536/article/details/109742895
-
web-view
- 是一个 web 浏览器组件,可以用来承载网页的容器,会自动铺满整个页面(nvue 使用需要手动指定宽高)。
- 属性:
- src webview 指向网页的链接
- H5端 可以直接打开 pdf 文件,无需打开新页面,word文件会弹下载提示
- App 端 pdf文件 和 word文件 都会弹下载提示
- 看到有使用 office 网址在线打开的
http://view.officeapps.live.com/op/view.aspx?src=${url}
-
uni.openDocument({})
和 web-view
结合
- H5端 使用
web-view
APP端使用uni.openDocument({})
至少打开 PDF文件是没什么太大问题 - 自己写的测试小案例
<template>
<view>
<template v-if="isShow">
<button type="default" @click="viewFile">查看</button>
</template>
<template v-else>
<web-view :src="url"></web-view>
</template>
</view>
</template>
<script>
export default {
data() {
return {
isShow: true,
url: '',
env: '',
}
},
mounted() {
this.env = 'http://192.168.6.244:3000';
},
methods: {
viewFile() {
uni.request({
url: 'http://192.168.6.244:3000/file/',
method: "GET",
data: {
fileType: 'pdf',
},
success: (res) => {
this.url = this.env + res.data.data;
this.isShow = !this.isShow;
uni.downloadFile({
url: this.env + res.data.data,
success: res => {
uni.openDocument({
filePath: res.tempFilePath,
success: (res) => {
console.log(res, '文件打开成功');
}
})
}
})
}
});
}
}
}
</script>