最終效果:
1.需要先從網(wǎng)上下載一份pdf.js
的文件
地址:http://mozilla.github.io/pdf.js/getting_started/
2.可以在uniapp項目中和pages
目錄平級新建一個hybrid
文件夾,把下載好的pdf.js
文件全部放到里面,主要是利用了web文件夾下的viewer.html
文件
3.要實現(xiàn)pdf預(yù)覽,需要用到uniapp
的一個api:web-view
,因此需要新建一個.vue
文件,該文件就寫到pages
目錄下任意位置即可,寫上如下代碼:
<template>
<view style="width: 100%; height: 90vh;">
<view class="">
<web-view :src="allUrl"></web-view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
allUrl: '',
viewerUrl: '/hybrid/html/web/viewer.html', // 就是我們web目錄下的viewer.html文件路徑,注意路徑不要錯了
}
},
onLoad(params) {
// encodeURIComponent 函數(shù)可把字符串作為 URI 組件進行編碼。decodeURIComponent解碼
// 這里的 params.fileUrl 是另一個組件進入到該組件時通過 navigateTo 傳進來的pdf文件路徑
let fileUrl = encodeURIComponent(decodeURIComponent(params.fileUrl));
// 下面的路徑合起來其實是:'/hybrid/html/web/viewer.html?file=' + 線上pdf路徑
this.allUrl = this.viewerUrl + '?file=' + fileUrl
}
}
</script>
4.該文件就是上面步驟說的,跳轉(zhuǎn)時攜帶了pdf文件路徑的文件:文章來源:http://www.zghlxwxcb.cn/news/detail-400031.html
seeVideo(item) {
if (item.subjectType === '文件') {
// pdf文件預(yù)覽
// item.videos 是線上的pdf文件路徑,這里的線上pdf路徑,是用的阿里云服務(wù)器地址+pdf文件名
// '&type=' + this.trainType 是路徑跳轉(zhuǎn)時攜帶多參數(shù)的寫法,在pdfview組件中的onLoad函數(shù)中通過參數(shù)能取到fileUrl和type
uni.navigateTo({
url: "/pages/videoExercises/pdfview?fileUrl=" + encodeURIComponent(item.videos) + '&type=' + this.trainType
})
} else {
// ......
}
}
**注意事項:**以上步驟完成后,需要在web/viewer.js
文件中,搜索一下not match
,注釋掉,否則在真機上無法成功預(yù)覽pdf文件,如下代碼:
然后在真機上調(diào)試就可以成功預(yù)覽pdf文件了
說明,如果在瀏覽器上模擬app項目,會出現(xiàn)跨域的報錯提示,這個是正常的,不用理會文章來源地址http://www.zghlxwxcb.cn/news/detail-400031.html
到了這里,關(guān)于【uniapp】uniapp開發(fā)app項目實現(xiàn)在線預(yù)覽pdf文件的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!