安裝方式:
npm i --save vue-pdf
1. 使用元件:
<PreViewPdf ref="PreViewPdf"></PreViewPdf>
this.$refs.PreViewPdf.openPdf(item.oss_url)
2. 項目抛出如下錯誤:
通過查閱vue-pdf的github項目的issue發現也有其他人出現這個問題,解決方案是在自己的項目引入pdfjs-dist依賴包,并指定該包的項目固定為2.5.207,即可解決問問題。(詳細問題描述)
但個人認為這是vue-pdf的bug,作者應該後期會修複,pdfjs-dist這個包本身也是可以實作pdf預覽的,vue-pdf是在此基礎上包一層能力,pdfjs的版本依賴應該是在vue-pdf的package.json去修複指定,我們目前的處理方案就是在自己的項目去強行指定版本,如果後期作者修複或者更新這個包,我們自己項目可能需要同步修改一下。
npm i --save [email protected]
元件代碼實作如下:
<template>
<div class="pdf" v-show="visible">
<div class="arrow">
<span class="xiaoicon icon" @click="visible=false;currentPage=0;pageCount=0"></span>
<button @click.stop="scaleX">縮小</button>
<!-- // 上一頁 -->
<span @click="changePdfPage(0)" class="turn" :class="{grey: currentPage==1}">上一頁</span>
{{currentPage}} / {{pageCount}}
<!-- // 下一頁 -->
<span @click="changePdfPage(1)" class="turn" :class="{grey: currentPage==pageCount}">下一頁</span>
<button @click.stop="scaleD">放大</button>
</div>
<div class="pdfClass"
:style="{
width: scale + '%',
}">
<pdf
ref="wrapper"
:src="pdfSrc"
:page="currentPage"
@num-pages="pageCount=$event"
@page-loaded="currentPage=$event"
@loaded="loadPdfHandler" >
</pdf>
</div>
</div>
</template>
<script>
import pdf from 'vue-pdf'
// CMapReaderFactory 解決pdf中文亂碼問題
import CMapReaderFactory from 'vue-pdf/src/CMapReaderFactory.js'
export default {
metaInfo: { // 這裡是給頁面修改
title: '',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=2,user-scalable=yes' }
]
},
components: {pdf},
data () {
return {
scale: 100,
visible: false,
currentPage: 0, // pdf檔案頁碼
pageCount: 0, // pdf檔案總頁數
pdfSrc: '' // pdf檔案位址
}
},
created() {
// 有時PDF檔案位址會出現跨域的情況,這裡最好處理一下
if(this.pdfSrc){
this.pdfSrc = pdf.createLoadingTask({url: this.pdfSrc, CMapReaderFactory })
}
},
methods: {
// 改變PDF頁碼,val傳過來區分上一頁下一頁的值,0上一頁,1下一頁
changePdfPage (val) {
// console.log(val)
if (val === 0 && this.currentPage > 1) {
this.currentPage--
console.log(this.currentPage)
}
if (val === 1 && this.currentPage < this.pageCount) {
this.currentPage++
console.log(this.currentPage)
}
},
// pdf加載時
loadPdfHandler () {
this.currentPage = 1 // 加載的時候先加載第一頁
},
openPdf(url){
this.visible = true
this.pdfSrc = pdf.createLoadingTask({url: url, CMapReaderFactory })
},
//放大
scaleD() {
this.scale += 5
},
//縮小
scaleX() {
if (this.scale == 100) {
return
}
this.scale += -5
},
}
}
</script>
<style scoped>
.pdf{
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: #000;
overflow: hidden;
z-index: 200;
}
.arrow{
height: 1.066667rem;
line-height: 1.066667rem;
color: #fff;
text-align: center;
position: relative;
}
.icon{
font-size: .32rem;
color: #fff;
position: absolute;
top: 0;
left: .213333rem;
}
.pdfClass{
overflow: auto;
}
</style>
界面運作效果如下:
縮放效果如下:
如上圖效果知道,vue-pdf雖然能是達到線上預覽的基本效果,但是存在如下不友好問題,影響使用者互動效果:
1. pdf畫布沒有鋪滿整個頁面;
2. 縮放效果不好,隻是在整個容器的基礎上進行縮放,字型會變形;
3. 而且縮放之後,超出頁面的部分不能滾動,顯然不滿足使用者互動需求
經過查找實踐,最後發現pdfh5能達到,滿屏和手勢縮放的移動端互動效果,實作方式如下。