vue中使用vue-pdf插件显示pdf

最近笔者项目比较忙,没怎么更新博客,今天来更新一下项目中所用的一个展示pdf的功能。

一、安装

npm install --save vue-pdf

二、基本示例

<template>
<div class="pdf">
  <pdf 
    ref="pdf"
    :src="pdfUrl">
  </pdf>
</div>
</template>
<script>
import pdf from 'vue-pdf'
export default {
  name: 'Pdf',
  components:{
      pdf
  },
  data(){
      return {
          pdfUrl:"http://file.dakawengu.com/file/2018-05-29/20180527-tianfeng.pdf",
      }
  }
</script>

扩展:下一页、上一页、放大、缩小、顺时针、逆时针

<template>
  <div class="main">
    <div>
      <button type="button" @click="changePdfPage(0)">上一页</button>
      <button type="button" @click="changePdfPage(1)">下一页</button>
    </div>
    <p>{{ currentPage }} / {{ pageCount }}</p>
    <div>
      <button type="button" @click="scaleD()">放大</button>
      <button type="button" @click="scaleX()">缩小</button>
    </div>
    <div>
      <button type="button" @click="clock()">顺时针</button>
      <button type="button" @click="counterClock()">逆时针</button>
    </div>
    <pdf
      ref="pdf"
      :src="src"
      :page="currentPage"
      :rotate="pageRotate"
      @num-pages="pageCount = $event"
      @page-loaded="currentPage = $event"
      @loaded="loadPdfHandler"
    ></pdf>
  </div>
</template>

<script>
// pdf预览
import pdf from "vue-pdf";
export default {
  name: "home",
  components: {
    pdf
  },
  data() {
    return {
      src:
        "http://storage.xuetangx.com/public_assets/xuetangx/PDF/PlayerAPI_v1.0.6.pdf",
      currentPage: 0, // pdf文件页码
      pageCount: 0, // pdf文件总页数
      scale: 100,
      pageRotate: 0
    };
  },
  methods: {
    // pdf加载时
    loadPdfHandler(e) {
      e;
      this.currentPage = 1; // 加载的时候先加载第一页
    },
    // 改变PDF页码,val传过来区分上一页下一页的值,0上一页,1下一页
    changePdfPage(val) {
      if (val === 0 && this.currentPage > 1) {
        this.currentPage--;
      }
      if (val === 1 && this.currentPage < this.pageCount) {
        this.currentPage++;
      }
    },
    //放大
    scaleD() {
      this.scale += 5;
      this.$refs.pdf.$el.style.width = parseInt(this.scale) + "%";
    },
    //缩小
    scaleX() {
      if (this.scale === 100) {
        return;
      }
      this.scale += -5;
      this.$refs.pdf.$el.style.width = parseInt(this.scale) + "%";
    },
    // 顺时针
    clock() {
      this.pageRotate += 90;
    },
    // 逆时针
    counterClock() {
      this.pageRotate -= 90;
    }
  }
};
</script>

<style scoped>
.main {
  width: 500px;
  margin: 0 auto;
  border: 2px solid #409eff;
  padding: 10px;
}
</style>

还有个办法,如果后端返回的是pdf的url,直接window.open(url)也行。

posted @ 2022-04-22 14:58  土小狗  阅读(1863)  评论(0编辑  收藏  举报