vue-pdf本地预览

185 阅读1分钟
<template>
  <div id="page">
    <pdf v-for="index in numPages"
         :key="index"
         :src="pdfUrl"
         :page="index"></pdf>
  </div>
</template>

<script type="text/ecmascript-6">
import pdf from 'vue-pdf'
export default {
  name: 'ServiceAgreement',
  beforeRouteEnter (to, from, next) {
    if (to.meta.title) {
      document.title = to.meta.title
    }
    next()
  },
  beforeRouteLeave (to, from, next) {
    next()
  },
  data () {
    return {
      numPages: null,
      pdfUrl: '/static/serviceAgreement.pdf',
    }
  },
  components: {
    pdf
  },
  props: {},
  created () {
    this.loadPdf()
  },
  methods: {
    // 上下滚动pdf加载
    loadPdf () {
      this.pdfUrl = pdf.createLoadingTask(this.pdfUrl)
      this.pdfUrl.promise.then(pdf => {
        this.$nextTick(() => {
          this.numPages = pdf.numPages // pdf总页数
        })
      })
    }
  }
}
</script>

<style scoped lang="less">
</style>

pdf文件一定要放在public/static文件下

如果pdf报错catch,在node_modules中找到vue-pdf,src下的pdfjsWrapper.js,将

if ( pdfRender !== null ) {
   if ( canceling )
       return;
   canceling = true;
   pdfRender.cancel().catch(function(err) {
       emitEvent('error', err);
   });
   return;
}

改为

if ( pdfRender !== null ) {
   if ( canceling )
      return;
   canceling = true;
   pdfRender.cancel();
   return;
}