文章目录
概要
在使用uniapp开发安卓、iOS APP的时候遇到一个需求,预览PDF,特此记录
技术栈
uniapp + vue2 + pfdjs + webview
完整代码
javascript
<template>
<view class="pdf-module" style="width: 100%; height: 100vh">
<web-view :src="allUrl" :webview-styles="webviewStyles"></web-view>
</view>
</template>
<script>
export default {
data() {
return {
allUrl: '',
viewerUrl: '/static/pdf/web/viewer.html',
webviewStyles: {
progress: { color: '#007aff' }
}
}
},
onLoad(option) {
const encodedPdfUrl = encodeURIComponent(option.url)
const baseUrl = this.getBaseUrl()
this.allUrl = `${baseUrl}${this.viewerUrl}?file=${encodedPdfUrl}`
},
methods: {
getBaseUrl() {
const platform = uni.getSystemInfoSync().platform
return platform === 'ios' ? '/' : ''
}
}
}
</script>
<style scoped>
.pdf-module {
margin: 0;
padding: 0;
box-sizing: border-box;
}
</style>
效果图

小结
javascript
注释 / 删除 同源校验逻辑
// 原错误代码(大概1802行)
if (fileOrigin !== viewerOrigin) {
throw new Error('file origin does not match viewer\'s');
}
// 修改后(注释掉校验)
// if (fileOrigin !== viewerOrigin) {
// throw new Error('file origin does not match viewer\'s');
// }
