当前位置:首页 > VUE

vue项目实现pdf

2026-01-16 20:41:13VUE

实现PDF生成与展示

在Vue项目中实现PDF功能通常涉及生成、预览或下载PDF文件。以下是几种常见场景的实现方法:

使用vue-pdf插件预览PDF

安装依赖:

npm install vue-pdf

组件中使用:

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

<script>
import pdf from 'vue-pdf'
export default {
  components: { pdf },
  data() {
    return {
      pdfUrl: '/sample.pdf' // 本地或远程PDF路径
    }
  }
}
</script>

支持分页显示:

<pdf v-for="i in numPages" :key="i" :src="pdfUrl" :page="i"></pdf>

使用jsPDF生成PDF

安装jsPDF库:

npm install jspdf

基本生成示例:

import jsPDF from 'jspdf'

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

添加图片和表格:

doc.addImage(imgData, 'JPEG', 10, 10, 50, 50)
doc.autoTable({ html: '#my-table' })

使用PDF.js处理复杂PDF

引入PDF.js库:

npm install pdfjs-dist

加载PDF文件:

const loadingTask = pdfjsLib.getDocument(url)
loadingTask.promise.then(pdf => {
  pdf.getPage(1).then(page => {
    const viewport = page.getViewport({ scale: 1.0 })
    const canvas = document.getElementById('pdf-canvas')
    const context = canvas.getContext('2d')
    canvas.height = viewport.height
    canvas.width = viewport.width

    page.render({
      canvasContext: context,
      viewport: viewport
    })
  })
})

服务器端生成PDF

使用Node.js后端生成:

const pdf = require('html-pdf')
app.post('/generate-pdf', (req, res) => {
  pdf.create(htmlTemplate).toStream((err, stream) => {
    stream.pipe(res)
  })
})

前端调用:

axios.post('/generate-pdf', { data }, { responseType: 'blob' })
  .then(response => {
    const blob = new Blob([response.data], { type: 'application/pdf' })
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = 'document.pdf'
    link.click()
  })

处理PDF表单

使用pdf-lib处理表单:

npm install pdf-lib

填写PDF表单:

import { PDFDocument } from 'pdf-lib'

async function fillForm() {
  const pdfDoc = await PDFDocument.load(pdfBytes)
  const form = pdfDoc.getForm()
  form.getTextField('name').setText('John Doe')
  const modifiedPdf = await pdfDoc.save()
}

注意事项

  • 跨域问题:预览远程PDF需配置CORS
  • 性能优化:大PDF文件建议分页加载
  • 字体支持:中文需额外配置字体包
  • 移动端适配:注意viewport设置

根据具体需求选择合适的方案,简单预览推荐vue-pdf,复杂生成推荐jsPDF或pdf-lib,服务器端处理适合需要模板的场景。

vue项目实现pdf

标签: 项目vue
分享给朋友:

相关文章

vue实现自定义登录

vue实现自定义登录

实现自定义登录的基本步骤 在Vue中实现自定义登录功能通常需要结合前端和后端技术。以下是一个基本的实现流程: 创建登录表单组件 使用Vue的单文件组件创建一个登录表单,包含用户名和密码输入框以及提交…

vue实现打印二维码

vue实现打印二维码

安装二维码生成库 使用 qrcode 或 vue-qrcode 库生成二维码。通过 npm 安装: npm install qrcode vue-qrcode 生成二维码 在 Vue 组件中引…

vue实现拖放

vue实现拖放

Vue 实现拖放功能 Vue 中实现拖放功能通常可以通过 HTML5 的原生拖放 API 或第三方库(如 vuedraggable)来实现。以下是两种方法的详细说明。 使用 HTML5 原生拖放…

vue实现triger

vue实现triger

在Vue中实现触发器(trigger)功能通常涉及自定义事件或DOM事件触发。以下是几种常见场景的实现方法: 自定义事件触发 通过$emit方法触发父组件中监听的自定义事件: // 子组件 thi…

vue 实现闪烁

vue 实现闪烁

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

vue实现详情

vue实现详情

Vue 实现详情页的常见方法 使用动态路由 在 Vue Router 中配置动态路由参数,通过 $route.params 获取详情 ID。示例路由配置: { path: '/detail/:…