vue2 使用 pdfjs 预览 pdf

533 阅读1分钟

vue2 使用 pdfjs 预览 pdf 案例

pdfjs 下载地址 unpkg.com/browse/pdfj…

第一步 :在public下新建文件夹 js, js目录下存放 pdf.min.js 和 pdf.worker.min.js

image.png

第二步: 在index.html 下引用 pdf.min.js 和 pdf.worker.min.js

image.png

做完成这两步 准备工作就已经完成了,下面是预览案例

<template>
  <div id="app">
    <div v-if="!isError" class="pdf-container" :style="{ width: pdfContainerWith +'px' }">
      <canvas v-for="index in totalPage" :key="index" :id="`canvas-${index}`"></canvas>
    </div>

    <div class="errBox" v-else>
      <el-empty description="pdf加载失败"></el-empty>
    </div>
    
    <el-backtop target=".pdf-container"></el-backtop>
    
  </div>
</template>

<script>

export default {
  data() {
    return {
      isError: false,
      pdfContainerWith: 0,
      totalPage: 0,
      pdfPath: 'https://xxxx/xxxxx.pdf'
    }
  },
  mounted() {
    this.initPdf()
  },
  methods: {
    initPdf() {
      const PDFJS = window['pdfjs-dist/build/pdf'];
        PDFJS.getDocument({
        url: this.pdfPath,
        cMapUrl: "/js/"
      }).promise.then(pdfDocument => {

          this.totalPage = pdfDocument.numPages // 页码

          for (let i = 1; i <= pdfDocument.numPages; i++) {
            pdfDocument.getPage(i).then(pdfPage => {
              let viewport = pdfPage.getViewport({ scale: 1 })
              let canvas = document.getElementById(`canvas-${i}`)

              if(i == 1) {
                this.pdfContainerWith = viewport.width + 6
              }

              canvas.width = viewport.width
              canvas.height = viewport.height

              let ctx = canvas.getContext('2d')

              let renderTask = pdfPage.render({
                canvasContext: ctx,
                viewport: viewport
              })
              return renderTask.promise
            })
          }
        }).catch(reason => {
          this.isError = true
          console.error('PDF加载失败')
        })
    },
  }
}
</script>

<style lang="scss">
html,body {
  height: 100%;
  margin: 0px;
  padding: 0px;
}
#app {
  overflow: hidden;
  height: 100%;
  background-color: #fcfcfc;
  .errBox {
    height: 100%;
    display: flex;
    justify-content: center;
  }
  .pdf-container {
    height: calc(100vh - 20px);
    overflow-y: auto;
    margin: 10px auto;
  }
    //修改滚动条样式
    .pdf-container::-webkit-scrollbar {
      -webkit-appearance: none;
      width: 6px;
      height: 6px;
    }

    .pdf-container::-webkit-scrollbar-track {
      background: rgba(0, 0, 0, 0.1);
      border-radius: 0;
    }

    .pdf-container::-webkit-scrollbar-thumb {
      cursor: pointer;
      border-radius: 5px;
      background: rgba(0, 0, 0, 0.15);
      transition: color 0.2s ease;
    }

    .pdf-container::-webkit-scrollbar-thumb:hover {
      background: rgba(0, 0, 0, 0.3);
    }
}
</style>