以下是一个基于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

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

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