前言
提示:因最近项目需求,项目需要实现vue页面内预览pdf,后端以文件流形式返回pdf地址。
一、方法概述
方法引入插件为:vue-pdfnpm install --save vue-pdf
二、方法使用
1.页面:
<!--工具条-->
<div class="sign-main-left-header">
<div class="box width300">
<div
class="tab-item"
>
{{ item.providerName }}
</div>
</div>
<div class="box">
<el-slider
class="slider"
v-model="scale"
:show-tooltip="false"
></el-slider>
<span class="slider-text">{{ scale * 2 }}%</span>
</div>
<div class="box">
<el-input
class="pages-input"
v-model="curPageNum"
@keyup.enter.native="gotoHandler"
></el-input>
<span class="pages-total">/ {{ numPages }}</span>
<span class="pages-action" @click="gotoHandler">跳转</span>
</div>
</div>
<!--pdf-->
<div class="sign-main-left-main">
<div class="pdf" :style="{ width: scale * 2 + '%' }">
<div class="pdf-body" v-loading="!tplPdf">
<pdf
ref="pdfs"
:src="pdfSrc"
v-for="(p, i) in numPages"
:key="i"
:page="p"
style="width: 100%; height: 100%"
:id="'pdf' + (i + 1)"
></pdf>
</div>
</div>
</div>
import pdf from 'vue-pdf'
import CMapReaderFactory from 'vue-pdf/src/CMapReaderFactory.js'
export default {
data() {
return {
tplPdf: '',
pdfSrc: '',
numPages: 0, // pdf页数
scale: 50, // 放大系数 0-200
curPageNum: 0, // 当前页数
contractUrl:''
}
},
components: {
pdf
},
methods: {
/**
* 获取待签约合同,src链接转换成文件流
*/
getTemplateHandler() {
// 需请求接口获取
getSingleFaxContractStream({
contractUrl: this.contractUrl,
shopId: this.$route.query.shopId
}).then(res => {
if (res.code === '1') {
this.tplPdf = res.data.pdfByte // pdf的二进制格式数据
// 拼接二进制pdf文件,并通过vue-pdf插件预览 CMapReaderFactory解决中文填词不显示bug
this.pdfSrc = pdf.createLoadingTask({
url: 'data:application/pdf;base64,' + this.tplPdf,
CMapReaderFactory
})
this.pdfSrc.then(pdf => {
this.numPages = pdf.numPages
this.curPageNum = 1
this.scale = 50
})
}
})
},
/**
* 跳转页数
*/
gotoHandler() {
if (!Number(this.curPageNum)) {
this.$message.error('请输入跳转的页数')
}
if (this.curPageNum > this.numPages) {
this.curPageNum = this.numPages
}
}
}
}
总结
如果有更好的方法或者需要改进的地方欢迎留言交流,如果对你有帮助的话,欢迎点赞收藏哦~。