npm install vue-pdf-embed@1.1.5
<template>
<div class="pdf-preview">
<div class="pdf-wrap">
<vue-pdf-embed :source="pdfUrl" :style="getScale" class="vue-pdf-embed" :page="pageNum"/>
</div>
<div class="page-tool">
<div class="page-tool-item size14" @click="lastPage">上一页</div>
<div class="page-tool-item size14" @click="nextPage">下一页</div>
<div class="page-tool-item size14">{{pageNum}}/{{numPages}}</div>
<div class="page-tool-item size14" @click="pageZoomOut">放大</div>
<div class="page-tool-item size14" @click="pageZoomIn">缩小</div>
</div>
</div>
</template>
<script>
import VuePdfEmbed from 'vue-pdf-embed';
import { pageNumber } from '@/api/certification';
export default {
name: 'pdfView',
components: {
VuePdfEmbed,
},
props: {
// 预览pdf文件地址
pdfUrl: {
type: String,
default: '',
required: true
}
},
data() {
return {
pageNum: 1, // 当前页面
scale: 1, // 缩放比例
numPages: 0, // 总页数
pageNumInterval: null,
};
},
beforeRouteLeave(to, from, next) {
clearInterval(this.pageNumInterval);
},
watch: {
'pdfUrl'(newVal, oldVal) {
this.pageNumInterval = setInterval(() => {
pageNumber({
url: newVal
}).then(res => {
if (res.statusCode === 20000) {
if (res.data) {
clearInterval(this.pageNumInterval);
this.numPages = res.data;
}
}
});
}, 100);
},
},
computed: {
getScale() {
return `transform:scale(${this.scale})`;
},
},
methods: {
lastPage() {
if (this.pageNum > 1) {
this.pageNum -= 1;
}
},
nextPage() {
if (this.pageNum < this.numPages) {
this.pageNum += 1;
}
},
pageZoomOut() {
if (this.scale < 2) {
this.scale += 0.1;
}
},
pageZoomIn() {
if (this.scale > 1) {
this.scale -= 0.1;
}
},
}
};
</script>
<style scoped lang="less">
.pdf-preview {
position: relative;
width: 100%;
height: 100%;
background-color: #e9e9e9;
.pdf-wrap {
width: 100%;
height: 100%;
overflow: auto;
.vue-pdf-embed {
text-align: center;
width: 100%;
height: 100%;
border: 1px solid #e5e5e5;
box-sizing: border-box;
transform-origin: 0 0
}
}
.page-tool {
position: absolute;
bottom: 88px;
padding-left: 15px;
padding-right: 15px;
display: flex;
align-items: center;
background: rgb(66, 66, 66);
color: white;
border-radius: 19px;
z-index: 100;
cursor: pointer;
margin-left: 50%;
transform: translateX(-50%);
opacity: 0.8;
.page-tool-item {
padding: 8px 15px;
cursor: pointer;
white-space: nowrap;
}
}
}
</style>