應用場景:比賽報表pdf文件需要在線預覽跟下載,發現直接使用window.open(url, '_blank'),在pc端是可以實現預覽,但是在移動端是直接通過打開瀏覽器進行下載再預覽,經查資料發現可以使用vue-pdf組件實現預覽!!!
參考:https://www.cnblogs.com/steamed-twisted-roll/p/9648255.html GitHub地址:https://github.com/FranckFreiburger/vue-pdf#readme
安裝:
npm install --save vue-pdf
template代碼:
<template> <div class="pdf" v-show="fileType === 'pdf'"> <p class="arrow"> <!-- // 上一頁 --> <span @click="changePdfPage(0)" class="turn" :class="{grey: currentPage==1}">Preview</span> {{currentPage}} / {{pageCount}} <!-- // 下一頁 --> <span @click="changePdfPage(1)" class="turn" :class="{grey: currentPage==pageCount}">Next</span> </p> <!-- // 自己引入就可以使用,這里我的需求是做了分頁功能,如果不需要分頁功能,只要src就可以了 --> <pdf :src="pdfSrc" :page="currentPage" @num-pages="pageCount=$event" @page-loaded="currentPage=$event" @loaded="loadPdfHandler" > </pdf> </div> </template>
js代碼:<script> // 引入PDF
import pdf from 'vue-pdf' export default { metaInfo: { title: 'This is the test', meta: [ { charset: 'utf-8' }, { name: 'viewport', content: 'width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=2,user-scalable=yes' } ] }, components: {pdf}, // props: ['pdfSrc'], data () { return { currentPage: 0, // pdf文件頁碼 pageCount: 0, // pdf文件總頁數 fileType: 'pdf', // 文件類型 pdfSrc: this.$route.query.url // pdf文件地址 } }, created() { // 有時PDF文件地址會出現跨域的情況,這里最好處理一下 this.pdfSrc = pdf.createLoadingTask(this.pdfSrc) }, 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 (e) { this.currentPage = 1 // 加載的時候先加載第一頁 } } }
上面是有實現分頁功能的
下面是沒有分頁功能
template代碼:
<template> <div class="pdf-box"> <pdf v-for="i in numPages" :key="i" :src="pdfSrc" :page="i"> </pdf> </div> </template>
js代碼
import pdf from 'vue-pdf' export default { metaInfo: { meta: [ { name: 'viewport', content: 'width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=2,user-scalable=yes' } ] }, components: { pdf }, data () { return { pdfSrc: this.$utils.DecryptUrl(this.$route.query).url, // pdf文件地址 numPages: undefined, } }, mounted() { // 有時PDF文件地址會出現跨域的情況,這里最好處理一下 this.pdfSrc = pdf.createLoadingTask(this.pdfSrc) this.pdfSrc.then(pdf => { this.numPages = pdf.numPages }) } } </script>
css:
<style lang="scss" scoped> .pdf-box { -webkit-box-sizing: border-box; box-sizing: border-box; max-width: 1024px; width: 100%; margin: 0 auto; overflow-x: hidden; height: 100%; overflow-y: auto; -webkit-overflow-scrolling: touch; font-size: .28rem; span { width: 100%; } } </style>
最后:我們發現了pdf在手機預覽的時候,不可以放大,后面發現是因為入口文件設置了禁止用戶縮放放大,我們可以借助vue-meta進行單獨為這個組件設置動態meta,具體看下vue-meta使用。