vueshowpdf 移动端pdf文件预览

1、安装

npm install vueshowpdf -S

2、参数

属性说明类型默认值
v-model是否显示pdf--
pdfurlpdf的文件地址String-

scale

默认放大倍数

Number1.2

minscale

最小放大倍数

Number0.8

maxscale

最大放大倍数

Number2

3、事件

名称说明回调参数
closepdf pdf关闭事件-
pdferr文件地址解析错误事件-

4、核心代码

<template>
  <div class="case-info">
    <van-cell title="附件" value="预览" is-link @click="viewPdf" class="perview" />
    <vueshowpdf class="pdf" v-model="isShowPdf" :pdfurl="pdfurl"
      :minscale='0.4' :scale='0.6' @closepdf="isShowPdf = false" @pdferr="pdfError"
    ></vueshowpdf>
  </div>
</template>

<script>
import api from '@/api.js'
import vueshowpdf from 'vueshowpdf'
export default {
  name: 'test',
  data () {
    return {
      isShowPdf: false,
      pdfUrl: '',
      pdfKey: 0
    }
  },
  components: {
    vueshowpdf
  },
  deactivated () {
    // 离开页面默认关闭pdf
    this.isShowPdf = false
    this.pdfKey++
  },
  methods: {
    // 预览pdf
    async viewPdf () {
      if (this.pdfUrl) {
        this.isShowPdf = true
      } else {
        this.$toast.loading({
          message: '加载中...',
          duration: 0,
          forbidClick: true
        })
        try {
          const res = await api.getFilePreview()
          this.$toast.clear()
          if (res.code === '0') {
            let blob = this.dataURLtoBlob(res.data)
            this.pdfurl = URL.createObjectURL(blob)
            this.isShowPdf = true
          } else {
            this.$toast(res.msg || '该原始文件不存在')
          }
        } catch (error) {
          this.$toast.clear()
        }
      }
    },
    // 将base64转换为文件
    dataURLtoBlob (dataurl) {
      const bstr = atob(dataurl)
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: 'application/pdf' })
    },
    // 关闭pdf
    closePdf () {
      this.isShowPdf = false
      this.pdfKey++
    },
    // pdf预览失败
    pdfError (errorUrl) {
      this.$toast.fail('预览失败')
      this.isShowPdf = false
      this.pdfKey++
    }
  }
}
</script>

<style lang="scss" scoped>
  .perview .van-cell__value {
    color: #468bff;
    text-decoration: underline;
  }
</style>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值