Vue-pdf预览插件-vue-pdf

应用场景

在写H5项目的时候需要预览pdf文件

解决方案

步骤一:npm install --save vue-pdf

步骤二: 这是template

<template>
  <div class="pdf" v-show="fileType === 'pdf'">
    <pdf
      ref="pdf"
      :src="pdfUrl"
      :page="currentPage"
      @num-pages="pageCount=$event"
      @page-loaded="currentPage=$event"
      @loaded="loadPdfHandler">
    </pdf>

    <div class="bottom-btn" >
      <p class="arrow">
        <span @click="changePdfPage(0)" class="turn" :class="{grey: currentPage==1}">上一页</span>
        {{currentPage}} / {{pageCount}}
        <span @click="changePdfPage(1)" class="turn" :class="{grey: currentPage==pageCount}">下一页</span>
      </p>
    </div>
  </div>

</template>

步骤三:这是js

<script type='text/ecmascript-6'>
import pdf from "vue-pdf";
export default {
      components:{
      pdf
  },
  data() {
    return {
      pdfUrl:'',// pdf文件地址
      currentPage: 0, // pdf文件页码
      pageCount: 0, // pdf文件总页数
      fileType: 'pdf', // 文件类型
  } 
  },
  mounted(){
    const toast = this.$toast.loading({
      duration: 0,
      message: '加载中...',
      forbidClick: true,
      loadingType: 'spinner',
    });
    //这里给pdfUrl赋值
    this.pdfUrl = "http://file.dakawengu.com/file/2018-05-29/20180527-tianfeng.pdf";

  },
  methods:{
    // 改变PDF页码,val传过来区分上一页下一页的值,0上一页,1下一页
    changePdfPage (val) {
      // console.log(val)
      if (val === 0 && this.currentPage > 1) {
        this.currentPage--
        // console.log(this.currentPage)
      }
      if (val === 1 && this.currentPage < this.pageCount) {
        this.currentPage++
        // console.log(this.currentPage)
      }
    },
    loadPdfHandler(e){
      this.$toast.clear();
      this.currentPage = 1 // 加载的时候先加载第一页
    }
  }
};
</script>

步骤四: 这是css

<style scoped>
  .pdf{
    position: relative;
  }
  .bottom-btn{
    position: fixed;
    width: 80%;
    bottom: 0;
    left: 10%;
    margin: 5% auto;
  }
.arrow{
  text-align: center;
}
</style>

好了,不出意外的话你现在应该可以在线预览pdf了!

但是

有些同学可能会遇到pdf跨域的问题,报错如下:
Access to fetch at 'http://zlhjweb.5gzvip.idcfengye.com/fileManage/getFile?type=pdf&fileCode=a88dbe9d28ae447a9a37293bb1241ec8' from origin 'http://10.1.3.8:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

这时候你可以这样做
方法一:让后台配置跨域header,开放允许跨域。

方法二:前端设置,我没试过不知道有没有用哈哈哈,你萌可以试试看 。

created: {
    this.src = pdf.createLoadingTask(this. pdfUrl)
  }

还有些同学需要打印pdf,出现文件打印乱码的问题…
这个我目前还没遇到,等以后有空再更~~~

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值