当前位置:首页 > VUE

vue页面实现pdf

2026-03-08 10:31:29VUE

在Vue中实现PDF显示或生成

使用vue-pdf库显示PDF文件

安装vue-pdf库:

npm install vue-pdf

在组件中引入并使用:

import pdf from 'vue-pdf'

export default {
  components: { pdf },
  data() {
    return {
      pdfUrl: '/path/to/document.pdf',
      pageNum: 1,
      pageCount: 0
    }
  },
  methods: {
    onPageChange(pageNum) {
      this.pageNum = pageNum
    }
  }
}

模板部分:

<template>
  <div>
    <pdf :src="pdfUrl" @num-pages="pageCount = $event" @page-loaded="pageNum = $event" />
    <p>Page {{ pageNum }} of {{ pageCount }}</p>
  </div>
</template>

使用pdf-lib生成PDF文件

安装pdf-lib库:

npm install pdf-lib

生成PDF示例代码:

import { PDFDocument, StandardFonts, rgb } from 'pdf-lib'

async function createPdf() {
  const pdfDoc = await PDFDocument.create()
  const page = pdfDoc.addPage()
  const font = await pdfDoc.embedFont(StandardFonts.Helvetica)

  page.drawText('Hello Vue PDF!', {
    x: 50,
    y: page.getHeight() - 50,
    size: 30,
    font,
    color: rgb(0, 0, 0)
  })

  const pdfBytes = await pdfDoc.save()
  return pdfBytes
}

使用jsPDF生成PDF

安装jsPDF库:

npm install jspdf

基本使用示例:

import jsPDF from 'jspdf'

function generatePDF() {
  const doc = new jsPDF()
  doc.text('Hello Vue!', 10, 10)
  doc.save('document.pdf')
}

使用iframe嵌入PDF

简单嵌入方法:

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

使用PDF.js自定义渲染

安装pdfjs-dist:

npm install pdfjs-dist

使用示例:

import * as pdfjsLib from 'pdfjs-dist/webpack'

async function renderPDF(url, canvasElement) {
  const loadingTask = pdfjsLib.getDocument(url)
  const pdf = await loadingTask.promise
  const page = await pdf.getPage(1)

  const viewport = page.getViewport({ scale: 1.0 })
  const canvas = canvasElement
  const context = canvas.getContext('2d')

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

  const renderContext = {
    canvasContext: context,
    viewport: viewport
  }

  await page.render(renderContext).promise
}

注意事项

不同方案适用于不同场景:

vue页面实现pdf

  • 显示已有PDF:vue-pdf或PDF.js
  • 生成新PDF:pdf-lib或jsPDF
  • 简单嵌入:iframe方案

PDF文件较大时考虑分页加载或使用Web Worker处理。跨域访问PDF文件需要正确配置服务器CORS头。

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

相关文章

vue实现导航栏切图

vue实现导航栏切图

Vue 实现导航栏切图 使用 Vue Router 实现基础导航 在 Vue 项目中,可以通过 Vue Router 实现导航栏的路由切换。创建一个导航栏组件,并在其中使用 <router-li…

vue 实现toast

vue 实现toast

vue 实现 toast 的方法 在 Vue 中实现 Toast 提示功能可以通过多种方式,以下是几种常见的实现方法: 使用第三方库 Vue 生态中有许多成熟的 Toast 库,例如 vue-toa…

vue 实现闪烁

vue 实现闪烁

Vue 实现闪烁效果的方法 方法一:使用 CSS 动画 在 Vue 组件中定义一个闪烁的 CSS 动画,通过绑定 class 或 style 来控制元素的闪烁效果。 <template>…

vue 实现列表

vue 实现列表

Vue 实现列表的方法 在 Vue 中实现列表通常使用 v-for 指令,结合数组或对象数据渲染动态列表。以下是几种常见的实现方式: 基础列表渲染 使用 v-for 指令遍历数组,渲染列表项。ite…

vue实现复选

vue实现复选

Vue 实现复选框 在 Vue 中实现复选框可以通过 v-model 指令绑定数据,同时结合 input 元素的 type="checkbox" 属性来实现。以下是几种常见的实现方式: 单个复选框…

vue实现active

vue实现active

Vue 实现 active 状态的方法 在 Vue 中实现 active 状态可以通过以下几种方式实现,具体取决于使用场景和需求。 使用 v-bind:class 动态绑定类名 通过 v-bind:…