vue3—pdfjs-dist—文件预览

公司vue3项目中有个pdf预览的功能,单独摸索了好几天,写出来个大概给自己提个醒

注意pdfjs-dist版本

 "pdfjs-dist": "2.0.943",
 //注意版本问题!!!当前我使用是2.0.943。
 

Preview.vue:

<template>
  <div class="pdf">
    <template v-for="item in pageNum" :key="item"  class="pdf-page">
      <canvas :id="`pdf-canvas-${item}`></canvas>
    </template>
  </div>
</template>
<script>
import { reactive,toRefs,nextTick,onMounted } from 'vue'
const PDF = require('pdfjs-dist')
//这里需要引入一个js文件
PDF.GlobalWorkerOptions.workerSrc = '/pdfjs-dist/web/pdf_viewer.js'
export default {
  name: 'PdfPreview',
  props: {
    url: {
      type: String,
      default: ''
    }
  },
  setup(props, { emit }) {
    const state = reactive({
   url:'',
     pageNum: 0,
      pdfCtx: null
    })
    onMounted(() => {
      if (props.url) {
        state.url = props.url
        loadingTaskPdf (state.url)
      } 
    })
    const loadingTaskPdf = (url) => {
      const loadingTask = PDF.getDocument(url)
      loadingTask.promise.then(pdf => {
        state.pdfCtx = pdf
        state.pageNum = pdf.numPages
        nextTick(() => {
          renderPdf()
        })
      })
    }
    const renderPdf = (num = 1) => {
      state.pdfCtx.getPage(num).then(page => {
        // 获取元素
        const canvas = document.getElementById(`pdf-canvas-${num}`)
        const ctx = canvas.getContext('2d')
        // 设置缩放值
        const viewport = page.getViewport(1.4)
        canvas.height = viewport.height 
        canvas.width = viewport.width 
        page.render({
          canvasContext: ctx,
          viewport: viewport
        })
        //是否达到最大页数
        if (num < state.pageNum) {
          renderPdf(num + 1)
        } 
      })
    }
    return {
      ...toRefs(state)
    }
  }
}
</script>
<style scoped lang="scss">
.pdf canvas{
display: block;
margin: 0 auto
}
</style>





Logo

前往低代码交流专区

更多推荐