vue 实现pdf下载
Vue 实现 PDF 下载的方法
使用 jsPDF 库生成并下载 PDF
安装 jsPDF 库:
npm install jspdf
在 Vue 组件中使用 jsPDF:
import { jsPDF } from "jspdf";
export default {
methods: {
generatePDF() {
const doc = new jsPDF();
doc.text("Hello Vue!", 10, 10);
doc.save("document.pdf");
}
}
}
使用 pdf-lib 动态生成 PDF
安装 pdf-lib:
npm install pdf-lib
示例代码:
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib';
export default {
methods: {
async createPDF() {
const pdfDoc = await PDFDocument.create();
const page = pdfDoc.addPage();
const { width, height } = page.getSize();
const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
page.drawText('Vue PDF Download', {
x: 50,
y: height - 50,
size: 30,
font,
color: rgb(0, 0, 0),
});
const pdfBytes = await pdfDoc.save();
this.downloadPDF(pdfBytes, 'generated.pdf');
},
downloadPDF(pdfBytes, fileName) {
const blob = new Blob([pdfBytes], { type: 'application/pdf' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = fileName;
link.click();
}
}
}
下载服务器上的 PDF 文件
如果 PDF 文件已存在于服务器:
export default {
methods: {
downloadServerPDF() {
const link = document.createElement('a');
link.href = '/path/to/file.pdf';
link.download = 'downloaded.pdf';
link.click();
}
}
}
使用 axios 下载二进制 PDF 数据
import axios from 'axios';
export default {
methods: {
async downloadPDF() {
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', 'file.pdf');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} catch (error) {
console.error('Download failed:', error);
}
}
}
}
使用 vue-pdf-embed 显示并下载 PDF
安装 vue-pdf-embed:
npm install vue-pdf-embed
组件示例:
import VuePdfEmbed from 'vue-pdf-embed';
export default {
components: {
VuePdfEmbed
},
methods: {
downloadPDF() {
const pdfElement = this.$refs.pdfEmbed;
pdfElement.download();
}
}
}
注意事项
确保服务器正确设置 CORS 头部以允许文件下载 对于大文件下载,考虑显示进度提示 移动端设备可能需要特殊处理下载逻辑 某些浏览器可能会阻止自动下载,需要用户交互触发







