vue结合vue-pdf实现pdf预览功能
准备
工具
"vue": "^2.6.14",
"vue-pdf": "^4.3.0",
安装
npm install --save vue-pdf
实现
创建PreviewPdf组件
<template>
<div class="pdf">
<a-modal
:visible="previewVisible"
@cancel="cancel"
width="90%"
:closable="false"
:keyboard="false"
>
<a-card>
<pdf
ref="pdf"
:src="pdfUrl"
:page="pageNum"
@progress="loadedRatio = $event"
@num-pages="pageTotalNum = $event"
>
</pdf>
</a-card>
<div class="info">
<div>当前页数/总页数:{{ pageNum }}/{{ pageTotalNum }}</div>
</div>
<a-space>
<a-button type="primary" @click.stop="prePage">上一页</a-button>
<a-button type="primary" @click.stop="nextPage">下一页</a-button>
<a-button type="primary" @click="enlarge">放大</a-button>
<a-button type="primary" @click="reduce">缩小</a-button>
<a-button type="primary" @click="back()">返回</a-button>
<a-button type="primary" @click="downloadFile(pdfUrl)">下载</a-button>
</a-space>
</a-modal>
</div>
</template>
<script>
import pdf from "vue-pdf";
export default {
name: "pdfPreview",
props: {
pdfUrl: {
type: String,
},
previewVisible: {
type: Boolean,
default() {
return false
}
},
},
components: {pdf},
data() {
return {
// 总页数
pageTotalNum: 1,
// 当前页数
pageNum: 1,
// 加载进度
loadedRatio: 0,
// 缩放百分比
scale: 90,
previewVisible: false
}
},
methods: {
// 切换上一页
prePage() {
let p = this.pageNum;
if (this.pageNum === 1) {
this.$message.info("没有上一页了")
return
}
p = p > 1 ? p - 1 : this.pageTotalNum;
this.pageNum = p;
},
// 切换下一页
nextPage() {
if (this.pageNum === this.pageTotalNum) {
this.$message.info("没有下一页了")
return
}
let p = this.pageNum;
p = p < this.pageTotalNum ? p + 1 : 1;
this.pageNum = p;
},
back() {
window.location.reload()
},
downloadFile(pdfUrl) {
window.location.href = pdfUrl
},
cancel() {
this.previewVisible = false
window.location.reload()
},
//放大
enlarge() {
if (this.scale == 100) {
this.$message.info("已放大到最大比例:100%")
return
}
this.scale += 5;
this.$refs.pdf.$el.style.width = parseInt(this.scale) + "%";
},
//缩小
reduce() {
if (this.scale <= 60) {
this.$message.info("已缩放至最小比例:60%")
return
}
this.scale += -5;
this.$refs.pdf.$el.style.width = parseInt(this.scale) + "%";
},
},
}
</script>
<style scoped>
.info {
margin-top: 1%;
height: 40px;
font-weight: bold;
font-size: 15px;
}
</style>
使用
模板
import PreviewPdf from "@/component/common/PreviewPdf";
components: {PreviewPdf},
<template>
<PreviewPdf
v-if="isPreview"
:pdfUrl="pdfUrl"
:preview-visible="previewVisible"
></PreviewPdf>
// 预览按钮,可能是table的操作栏...
<a @click="preview(item)">
<a-icon type="eye"></a-icon>
预览
</a>
</template>
data
isPreview: false,
pdfUrl: '',
previewVisible: false
事件
methods: {
preview(item) {
// pdfUrl就是可以通过浏览器地址栏访问的url
this.pdfUrl = 'https://xxx.xxx.xxx.cn/' + process.env.VUE_APP_BUCKET_NAME + '/' + item.filePath
// 控制PreviewPdf组件的显示
this.isPreview = true
// 控制PreviewPdf组件的对话框的显示
this.previewVisible = true
},
}