vue-pdf 实现pdf在线预览

安装:

npm install --save vue-pdf

 Demo:

<template>
<div>
  <pdf 
    ref="pdf"
    :src="url">
  </pdf>
</div>
</template>

<script>
import pdf from 'vue-pdf'
export default {
  components:{
      pdf
  },
  data(){
      return {
          url:"http://storage.xuetangx.com/public_assets/xuetangx/PDF/PlayerAPI_v1.0.6.pdf",
      }
  }
</script>

但是,这样写只会显示一页...

想要全部显示,就要用v-for循环

<template>
    <div>
        <pdf v-for="i in numPages" :key="i"  :src="url" :page="i"></pdf>    
    </div>
</template>

<script>
    import pdf from 'vue-pdf'
    export default {
        components: {
            pdf
        },
        data(){
             return{
                    url: '',
                    numPages:1,
             }
         },
        mounted: function() {
          this.getNumPages("http://storage.xuetangx.com/public_assets/xuetangx/PDF/PlayerAPI_v1.0.6.pdf")
        }, 
        methods: {
            getNumPages(url) {
                var loadingTask = pdf.createLoadingTask(url)
                this.url = loadingTask
                loadingTask.promise.then(pdf => {
                    this.numPages = pdf.numPages
                }).catch((err) => {
                    console.error('pdf加载失败')
                })
            },
        }
    }
</script>        

各个属性:

  • url :pdf 文件的路径,可以是本地路径,也可以是在线路径。
  • numPages : pdf 文件总页数。

getNumPages 计算总页数,顺便给url和numPages赋值。

 

OK,满足一般需求已经够了,想要更多功能,请看官网API

2022.1.11 发现了一个BUG,有的浏览器生成的pdf是乱码,还不清楚是啥原因!

posted @ 2022-01-12 14:00  ZJTL  阅读(364)  评论(0编辑  收藏  举报