vue实现pdf下载
使用 vue-pdf 库实现 PDF 下载
安装 vue-pdf 库
npm install vue-pdf
引入并使用 vue-pdf 组件
import pdf from 'vue-pdf'
export default {
components: { pdf },
data() {
return {
pdfUrl: '/path/to/your.pdf'
}
}
}
在模板中添加下载按钮
<template>
<div>
<pdf :src="pdfUrl"></pdf>
<button @click="downloadPdf">下载PDF</button>
</div>
</template>
实现下载方法

methods: {
downloadPdf() {
const link = document.createElement('a')
link.href = this.pdfUrl
link.download = 'document.pdf'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
}
使用 jsPDF 生成并下载 PDF
安装 jsPDF 库
npm install jspdf
创建 PDF 内容并下载

import jsPDF from 'jspdf'
methods: {
generateAndDownloadPdf() {
const doc = new jsPDF()
doc.text('Hello World!', 10, 10)
doc.save('document.pdf')
}
}
使用 axios 下载服务器上的 PDF 文件
实现下载方法
import axios from 'axios'
methods: {
async downloadPdfFromServer() {
try {
const response = await axios.get('/api/pdf', {
responseType: 'blob'
})
const url = window.URL.createObjectURL(new Blob([response.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', 'document.pdf')
document.body.appendChild(link)
link.click()
link.remove()
} catch (error) {
console.error('下载失败:', error)
}
}
}
使用 FileSaver.js 简化下载过程
安装 FileSaver.js
npm install file-saver
使用 FileSaver 下载 PDF
import { saveAs } from 'file-saver'
methods: {
downloadWithFileSaver() {
saveAs(this.pdfUrl, 'document.pdf')
}
}
注意事项
确保 PDF 文件路径正确,如果是跨域资源需要服务器配置 CORS 头
对于大文件下载,建议显示下载进度提示
在移动端使用时,某些浏览器可能需要特殊处理
如果生成复杂 PDF,考虑使用 pdf-lib 等更强大的库






