以下是一个基于 Vue3 和 PDF.js 的 PDF 预览组件示例:

<template>
  <div class='pdf-preview'>
    <canvas ref='canvas'></canvas>
  </div>
</template>

<script>
import pdfjsLib from 'pdfjs-dist'

export default {
  props: {
    src: {
      type: String,
      required: true
    }
  },

  mounted() {
    this.loadPDF(this.src)
  },

  methods: {
    async loadPDF(url) {
      const pdf = await pdfjsLib.getDocument(url).promise
      const page = await pdf.getPage(1)
      const canvas = this.$refs.canvas
      const context = canvas.getContext('2d')
      const viewport = page.getViewport({ scale: 1 })

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

      await page.render({
        canvasContext: context,
        viewport
      })
    }
  }
}
</script>

<style scoped>
.pdf-preview {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

canvas {
  max-width: 100%;
}
</style>

使用方式:

<template>
  <div>
    <pdf-preview src='https://example.com/sample.pdf' />
  </div>
</template>

<script>
import PdfPreview from './PdfPreview.vue'

export default {
  components: {
    PdfPreview
  }
}
</script>

在上面的示例中,我们首先引入了pdfjs-dist库,并将其作为一个依赖项安装。该库提供了一个getDocument方法来加载 PDF 文件,我们可以使用它来获取 PDF 文档对象。然后,我们使用getPage方法获取第一页,并使用getViewport方法计算页面的高度和宽度。最后,我们使用render方法将页面渲染到画布上。

在 Vue 组件中,我们将src属性作为 PDF 文件的 URL 传递给PdfPreview组件。在mounted钩子中,我们调用loadPDF方法来加载 PDF 文件并将其渲染到画布上。

这个组件可以在任何 Vue 3 应用程序中使用,只需将其复制到您的项目中并按照上面的示例使用即可。

Vue3 PDF 预览组件:使用 PDF.js 实现 PDF 文件预览

原文地址: https://www.cveoy.top/t/topic/ncJm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录