最近接了一个需求需要在移动端预览pdf,并切要能缩放,百度发现大多推荐vue-pdf,但是vue-pdf这个包,安装之后运行报错,解决之后的实现效果不符合需求需要,而且,实现缩放功能的时候,整个canvas画布整个放大,虽然有放大效果,但是,画布无法滚动,交互体验实在是太差,最后找到pdfh5这个包,预览效果不错,而且支持手势缩放和分页功能。
pdfh5 的github地址:
https://github.com/gjTool/pdfh5
功能实现效果如下图:
1. 首先引入pdfh5包
npm i --save pdfh5
2. 代码实现如下:
<template>
<div :class="$style.pdf" v-show="visible">
<div @click="visible = false" :class="$style.iconContain">
<span :class="$style.iconClose" class="xiaoicon"></span>
</div>
<div id="preViewPdf"></div>
</div>
</template>
<script>
import Pdfh5 from "pdfh5"
import "pdfh5/css/pdfh5.css"
export default {
name: 'pdfH5',
data() {
return {
visible: false,
pdfh5: null
}
},
methods:{
openPdf(url){
this.visible = true
//实例化
this.pdfh5 = new Pdfh5("#preViewPdf", {
pdfurl: url
})
},
}
}
</script>
<style lang="scss" module>
*{
padding: 0;
margin: 0;
}
html,body {
width: 100%;
height: 100%;
}
.pdf{
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: #000;
overflow: hidden;
z-index: 200;
}
.iconContain{
position: fixed;
top: .426667rem;
right: .426667rem;
width: .64rem;
height: .64rem;
line-height: .64rem;
text-align: center;
background: rgba(0, 0, 0, 0.4);
z-index: 200;
border-radius: 50%;
}
.iconClose{
display: block;
color:#fff;
}
</style>
3. 组件引入方式:
// 引入租金啊
<PreviewpdfH5 ref="PreviewpdfH5"></PreviewpdfH5>
//显示组件:
this.$refs.PreviewpdfH5.openPdf(item.url)