使用 vue-pdf 踩坑记录
嵌入小程序里的h5里有一个查看pdf的功能,在h5里可以正常打开pdf,但是在小程序的webview里却打不开。为了解决这个问题踩了好多坑😂
最初的写法
这样写虽然打开速度很快,但是在小程序中打不开,#toolbar=0 是为了去除上面的工具栏
<iframe :src="pdfUrl+ '#toolbar=0'" frameborder="0" style="width: 100%;height: 100vh"></iframe>
vue-pdf
之前就使用过vue-pdf,所以决定使用它来完成这个功能
1、虽然可以显示出pdf但是会报大量的错误

解决办法 : 降低vue-pdf的版本,从4.3.0降到4.2.0
npm install vue-pdf@4.2.0
2、会出现跨域的问题
这里我是通过配置代理还有把文件上传到服务器解决的,需要后端协助,这部分情况不同的话解决方法也不一样,水平有限不能尽述

3、多页面不能滚动显示
解决方法如下,这里我只是把代码提出来了,如果要用的话注意位置
<pdf ref="pdf" v-for="i in numPages" :key="i" :src="pdfSrc" :page="i" style="width: 100%; height: auto;">
</pdf>
import pdf from 'vue-pdf'
components: {
pdf
},
mounted () {
this.loadPdfHandler()
}
loadPdfHandler () {
//src是服务器上存放pdf的路径
this.pdfSrc = this.pdfUrl
this.pdfSrc = pdf.createLoadingTask(this.pdfSrc)
this.pdfSrc.promise.then(pdf => {
this.numPages = pdf.numPages
console.log('numPages', this.numPages)
}).catch(err => {
{
console.log('加载失败', err)
}
})
},
4、也不能算是坑,就是打开pdf的速度很慢,影响用户体验感
解决办法:加一个loading组件,要用到 vue-pdf 的事件,👉一个查看的路径,这部分我把它写到最后的总结里
5、无法显示电子签名,这个问题我会另外写一篇博文
vue-pdf 部分完整代码
<template>
<div class="wrapper">
<van-loading v-if="showLoading" size="30px" vertical>加载中...</van-loading>
<pdf ref="pdf" :src="pdfSrc" v-for="i in numPages" :key="i" :page="i" @page-loaded="lastPageLoad"
style="width: 100%; height: auto;">
</pdf>
</div>
</template>
<script>
import pdf from 'vue-pdf'
import { Loading } from 'vant'
export default {
name: 'pdf',
components: {
pdf
},
data() {
return {
pdfUrl: 'http://www.XXXpdf.com/samples/pdf.pdf',
pdfSrc: '',
numPages: 0,
showLoading: true,
}
},
mounted() {
this.loadPdfHandler()
},
methods: {
loadPdfHandler () {
//src是服务器上存放pdf的路径
this.pdfSrc = this.pdfUrl
this.pdfSrc = pdf.createLoadingTask(this.pdfSrc)
this.pdfSrc.promise.then(pdf => {
this.numPages = pdf.numPages
console.log('numPages', this.numPages)
}).catch(err => {
{
console.log('加载失败', err)
}
})
},
lastPageLoad (num) {
num === this.numPages ? this.showLoading = false : this.showLoading = true
}
},
}
</script>
以上只是个人的见解,有不对的地方还请指点,共同学习💻

浙公网安备 33010602011771号