1.安装依赖
npm install vue-pdf --save
2.通过接口拿到文件流转换成Base64
const res = await downloadFile({
path: this.visitUrl
})
this.srcResult = await this.$utils.blobToDataURI(res)
/**
* 读取指定blob,返回转换为base64后的结果
* @param blob
* @returns {Promise<unknown>}
*/
static blobToDataURI(blob) {
return new Promise((resolve) => {
let reader = new FileReader()
reader.onload = function (e) {
resolve(e.target.result)
}
reader.readAsDataURL(blob)
})
}
3.通过vue-pdf实现预览(我使用的是vant)
<van-popup v-model="show" @close="close" position="bottom" :style="{ height: '80%',width: '100%' }">
<div class="control" v-if="pageCount > 1">
<van-button type="primary" size="small" @click="changePdfPage('up')">上一页</van-button>
<div class="interval">{{ currentPage }}/{{ pageCount }}</div>
<van-button type="primary" size="small" @click="changePdfPage('down')">下一页</van-button>
</div>
<pdf
:src="pdfSrc"
:page="currentPage"
@num-pages="pageCount = $event"
@page-loaded="currentPage = $event"
@loaded="loadPdfHandler"
@error="loadError"
/>
</van-popup>
import pdf from 'vue-pdf'
import CMapReaderFactory from 'vue-pdf/src/CMapReaderFactory.js'
open(url){
this.pdfSrc = pdf.createLoadingTask({
url,
CMapReaderFactory
})
// this.pdfSrc = url
this.show = true
},
loadPdfHandler() {
this.currentPage = 1 // 加载的时候先加载第一页
},
// 加载失败
loadError(err) {
console.log(err)
// this.$toast.fail('加载pdf失败!')
},