当前位置:首页 > VUE

vue页面实现pdf

2026-03-28 21:23:01VUE

在Vue页面中实现PDF功能

使用vue-pdf库

安装vue-pdf库:

npm install vue-pdf

在Vue组件中使用:

<template>
  <pdf :src="pdfSrc"></pdf>
</template>

<script>
import pdf from 'vue-pdf'

export default {
  components: { pdf },
  data() {
    return {
      pdfSrc: '/path/to/document.pdf'
    }
  }
}
</script>

使用PDF.js

安装pdfjs-dist:

npm install pdfjs-dist

基本实现代码:

<template>
  <div>
    <canvas v-for="page in pages" :key="page" :ref="'canvas'+page"></canvas>
  </div>
</template>

<script>
import * as pdfjsLib from 'pdfjs-dist'

export default {
  data() {
    return {
      pdfDoc: null,
      pages: []
    }
  },
  methods: {
    async loadPDF(url) {
      const loadingTask = pdfjsLib.getDocument(url)
      this.pdfDoc = await loadingTask.promise

      for(let i = 1; i <= this.pdfDoc.numPages; i++) {
        this.pages.push(i)
        this.$nextTick(() => this.renderPage(i))
      }
    },
    async renderPage(pageNum) {
      const page = await this.pdfDoc.getPage(pageNum)
      const viewport = page.getViewport({ scale: 1.0 })
      const canvas = this.$refs['canvas'+pageNum][0]
      const context = canvas.getContext('2d')

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

      const renderContext = {
        canvasContext: context,
        viewport: viewport
      }
      page.render(renderContext)
    }
  },
  mounted() {
    this.loadPDF('/path/to/document.pdf')
  }
}
</script>

使用iframe嵌入PDF

简单实现方式:

<template>
  <iframe 
    src="/path/to/document.pdf" 
    width="100%" 
    height="600px"
    style="border: none">
  </iframe>
</template>

生成PDF文件

使用jspdf库生成PDF:

npm install jspdf

示例代码:

<script>
import jsPDF from 'jspdf'

export default {
  methods: {
    generatePDF() {
      const doc = new jsPDF()
      doc.text('Hello Vue!', 10, 10)
      doc.save('vue-generated.pdf')
    }
  }
}
</script>

注意事项

确保PDF文件路径正确,如果是本地文件需要放在public目录下 考虑分页加载大PDF文件以提高性能 移动端需测试PDF查看体验 可能需要添加PDF下载按钮和打印功能

vue页面实现pdf

以上方法可根据具体需求选择使用,vue-pdf适合简单展示,PDF.js提供更多自定义选项,iframe最简单但功能有限,jspdf适合动态生成PDF内容。

标签: 页面vue
分享给朋友:

相关文章

用vue实现滑动输入条

用vue实现滑动输入条

使用 Vue 实现滑动输入条 使用原生 HTML5 input range 实现 在 Vue 模板中直接使用 <input type="range">,通过 v-model 绑定数据:…

vue 实现关闭

vue 实现关闭

Vue 实现关闭功能的方法 在Vue中实现关闭功能通常涉及组件销毁、模态框隐藏或路由跳转等场景。以下是几种常见实现方式: 销毁当前组件 使用v-if或v-show控制组件显示/隐藏,适用于局部组件:…

vue实现oauth

vue实现oauth

Vue 实现 OAuth 的步骤 安装必要的依赖 确保项目中安装了 axios 和 vue-router。OAuth 通常需要发送 HTTP 请求和处理路由跳转。 npm install axios…

vue diff实现

vue diff实现

Vue Diff 算法实现原理 Vue 的虚拟 DOM Diff 算法(即 patch 过程)是其高效渲染的核心,主要通过对比新旧虚拟节点的差异,最小化 DOM 操作。以下是关键实现要点: 同层级比…

vue实现爬虫

vue实现爬虫

Vue 实现爬虫的基本思路 Vue.js 本身是一个前端框架,主要用于构建用户界面。要实现爬虫功能,通常需要结合后端技术或浏览器自动化工具。以下是几种常见的方法: 方法一:Vue + Node.js…

vue select实现搜索

vue select实现搜索

实现 Vue Select 搜索功能的方法 在 Vue 中实现 select 组件的搜索功能,可以通过原生 HTML select 结合自定义搜索逻辑,或使用第三方库如 vue-select 来实现。…