vue-pdf预览pdf文件流

5 篇文章 0 订阅

html

  <pdf v-for="i in numberPage" :key="i" :src="pdfUrl" :page="i" style="width:100%;height:auto" />

js

<script>
import pdf from 'vue-pdf'
export default {
 data() {
    return {
      pdfUrl: '',
      numberPage: 0
    }
  },
  created() {
    this.preview(this.$route.params.id)
  },
   methods: {
    preview(fileId) {
      const params = { fileId: fileId }
      const FUNCTION = 'preview'
      this.preview(params, FUNCTION).then(res => {
        this.loading = false // 取消加载
        if (res.size === 0) {
          this.$notify({
            title: '文件不存在',
            type: 'error',
            duration: 2500
          })
        } else {
          this.pdfUrl = this.getObjectURL(res) // 解析出pdfUrl   **注意:如果在res中拿到的便是url,则这一步可以跳过
          const loadingTask = pdf.createLoadingTask(this.pdfUrl)
          // 注意这里一定要这样写
          loadingTask.promise.then(load => {
            this.numberPage = load.numPages
          }).catch(err => {
            console.log(err)
          })
        }
      }).catch(err => {
        this.loading = false // 取消加载
        console.log(err)
        this.$notify({
          title: 'pdf预览出错',
          type: 'error',
          duration: 2500
        })
      })
    },
    // 将返回的流数据转换成url
    getObjectURL(file) {
      let url = null
      if (window.createObjectURL !== undefined) { // basic
        url = window.createObjectURL(file)
      } else if (window.webkitURL !== undefined) { // webkit or chrome
        try {
          url = window.webkitURL.createObjectURL(file)
        } catch (error) {
          console.log(error)
        }
      } else if (window.URL !== undefined) { // mozilla(firefox)
        try {
          url = window.URL.createObjectURL(file)
        } catch (error) {
          console.log(error)
        }
      }
      return url
    }
  }
}
</script>

更加具体的使用
https://download.csdn.net/download/m0_38010595/14141574

解决vue中使用vue-pdf插件提示 window is not defined

// webpack.config.js 或 webpack.base.conf.js
module.exports = {
    // 此处省略部分配置项
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist'),
        globalObject: "this"        // 关键在此项配置,需要配置为 "this", 默认为 "window"
    },
    // 此处省略部分配置项
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

星繁~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值