文件流使用vue-pdf预览pdf文件

2022-07-16 12:28:59

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失败!')
    },
  • 作者:前端码农-虚空
  • 原文链接:https://blog.csdn.net/xukong6991456/article/details/124177906
    更新时间:2022-07-16 12:28:59