vue实现pdf下载
Vue 中实现 PDF 下载的方法
使用前端库生成 PDF
安装 html2pdf.js 或 jspdf 库,将 HTML 内容转换为 PDF 并下载。
npm install html2pdf.js
在 Vue 组件中引入并使用:
import html2pdf from 'html2pdf.js';
export default {
methods: {
downloadPDF() {
const element = document.getElementById('pdf-content');
const opt = {
margin: 10,
filename: 'document.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
};
html2pdf().from(element).set(opt).save();
}
}
};
从服务器下载 PDF

通过 API 请求获取 PDF 文件流,使用 Blob 和 URL.createObjectURL 实现下载。
downloadPDF() {
axios.get('/api/pdf', { 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();
URL.revokeObjectURL(link.href);
});
}
直接链接下载
若 PDF 文件已存储在服务器,可通过 <a> 标签直接下载。

<a href="/path/to/document.pdf" download>Download PDF</a>
动态生成 PDF 内容
使用 jspdf 动态创建 PDF 内容:
import jsPDF from 'jspdf';
generatePDF() {
const doc = new jsPDF();
doc.text('Hello World!', 10, 10);
doc.save('document.pdf');
}
注意事项
- 跨域问题需确保服务器配置正确的 CORS 头。
- 大文件下载建议分块或显示进度条。
- 移动端部分浏览器可能限制自动下载,需用户手动触发。






