vue实现pdf
Vue 实现 PDF 预览与下载
在 Vue 项目中实现 PDF 功能通常涉及预览、下载或生成 PDF 文件。以下是几种常见实现方式:
使用 iframe 或 embed 标签预览 PDF
通过 HTML 原生标签直接嵌入 PDF 文件:
<iframe
src="/path/to/file.pdf"
width="100%"
height="600px"
style="border: none;"
></iframe>
或使用 embed 标签:
<embed
src="/path/to/file.pdf"
type="application/pdf"
width="100%"
height="600px"
/>
使用 PDF.js 库
Mozilla 开源的 PDF.js 提供更灵活的 PDF 渲染控制:
-
安装依赖:
npm install pdfjs-dist -
组件示例:
<template> <div ref="pdfViewer" class="pdf-viewer"></div> </template>
export default { props: ['pdfUrl'], mounted() { this.loadPdf() }, methods: { async loadPdf() { const loadingTask = pdfjsLib.getDocument(this.pdfUrl) const pdf = await loadingTask.promise
for (let i = 1; i <= pdf.numPages; i++) {
const page = await pdf.getPage(i)
const viewport = page.getViewport({ scale: 1.0 })
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
canvas.height = viewport.height
canvas.width = viewport.width
await page.render({
canvasContext: context,
viewport: viewport
}).promise
this.$refs.pdfViewer.appendChild(canvas)
}
}
} }

使用 vue-pdf 插件
专用 Vue 插件简化集成:
-
安装:
npm install vue-pdf -
使用示例:
<template> <pdf :src="pdfSrc" style="width: 100%"></pdf> </template>
export default { components: { pdf }, data() { return { pdfSrc: '/example.pdf' } } }

PDF 下载功能实现
通过 Blob 对象实现文件下载:
methods: {
downloadPdf() {
const link = document.createElement('a')
link.href = '/path/to/file.pdf'
link.download = 'document.pdf'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
}
动态生成 PDF
使用 jsPDF 库生成 PDF:
-
安装:
npm install jspdf -
生成示例:
import jsPDF from 'jspdf'
methods: { generatePDF() { const doc = new jsPDF() doc.text('Hello Vue!', 10, 10) doc.save('vue-generated.pdf') } }
#### 服务端生成 PDF
通过 API 调用服务端生成:
```javascript
axios.post('/generate-pdf', { data })
.then(response => {
const blob = new Blob([response.data], { type: 'application/pdf' })
const url = window.URL.createObjectURL(blob)
// 使用下载方法
})
注意事项
- 跨域问题:确保 PDF 文件与前端同源或配置 CORS
- 性能优化:大文件建议分页加载
- 移动端适配:检查浏览器兼容性
- 安全考虑:用户上传的 PDF 需做安全扫描
根据具体需求选择合适方案,预览推荐 PDF.js 或 vue-pdf,生成推荐 jsPDF,服务端集成则需配合后端 API。






