应用场景
在写H5项目的时候需要预览pdf文件
解决方案
步骤一:npm install --save vue-pdf
步骤二: 这是template
。
<template>
<div class="pdf" v-show="fileType === 'pdf'">
<pdf
ref="pdf"
:src="pdfUrl"
:page="currentPage"
@num-pages="pageCount=$event"
@page-loaded="currentPage=$event"
@loaded="loadPdfHandler">
</pdf>
<div class="bottom-btn" >
<p class="arrow">
<span @click="changePdfPage(0)" class="turn" :class="{grey: currentPage==1}">上一页</span>
{{currentPage}} / {{pageCount}}
<span @click="changePdfPage(1)" class="turn" :class="{grey: currentPage==pageCount}">下一页</span>
</p>
</div>
</div>
</template>
步骤三:这是js
。
<script type='text/ecmascript-6'>
import pdf from "vue-pdf";
export default {
components:{
pdf
},
data() {
return {
pdfUrl:'',// pdf文件地址
currentPage: 0, // pdf文件页码
pageCount: 0, // pdf文件总页数
fileType: 'pdf', // 文件类型
}
},
mounted(){
const toast = this.$toast.loading({
duration: 0,
message: '加载中...',
forbidClick: true,
loadingType: 'spinner',
});
//这里给pdfUrl赋值
this.pdfUrl = "http://file.dakawengu.com/file/2018-05-29/20180527-tianfeng.pdf";
},
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)
}
},
loadPdfHandler(e){
this.$toast.clear();
this.currentPage = 1 // 加载的时候先加载第一页
}
}
};
</script>
步骤四: 这是css
。
<style scoped>
.pdf{
position: relative;
}
.bottom-btn{
position: fixed;
width: 80%;
bottom: 0;
left: 10%;
margin: 5% auto;
}
.arrow{
text-align: center;
}
</style>
好了,不出意外的话你现在应该可以在线预览pdf了!
但是
有些同学可能会遇到pdf跨域的问题,报错如下:
Access to fetch at 'http://zlhjweb.5gzvip.idcfengye.com/fileManage/getFile?type=pdf&fileCode=a88dbe9d28ae447a9a37293bb1241ec8' from origin 'http://10.1.3.8:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
这时候你可以这样做
方法一:让后台配置跨域header,开放允许跨域。
方法二:前端设置,我没试过不知道有没有用哈哈哈,你萌可以试试看 。
created: {
this.src = pdf.createLoadingTask(this. pdfUrl)
}
还有些同学需要打印pdf,出现文件打印乱码的问题…
这个我目前还没遇到,等以后有空再更~~~