vue实现PDF导出
使用 vue-pdf 库导出 PDF
安装 vue-pdf 库
npm install @tboerc/vue-pdf --save
在组件中引入并使用
import { VuePdf } from '@tboerc/vue-pdf';
export default {
components: {
VuePdf
},
methods: {
exportPDF() {
this.$refs.pdfComponent.download('filename.pdf');
}
}
}
模板中使用
<vue-pdf ref="pdfComponent" :src="pdfSource"></vue-pdf>
<button @click="exportPDF">导出PDF</button>
使用 jsPDF 库生成 PDF
安装 jsPDF
npm install jspdf --save
基本使用方法

import jsPDF from 'jspdf';
export default {
methods: {
generatePDF() {
const doc = new jsPDF();
doc.text('Hello world!', 10, 10);
doc.save('document.pdf');
}
}
}
添加图片和样式
const doc = new jsPDF();
doc.setFontSize(16);
doc.text('标题', 105, 15, { align: 'center' });
doc.addImage(imageData, 'JPEG', 15, 40, 180, 160);
使用 html2canvas 和 jsPDF 结合导出 HTML
安装依赖
npm install html2canvas jspdf --save
实现方法

import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
export default {
methods: {
exportHTMLToPDF() {
const element = document.getElementById('content-to-export');
html2canvas(element).then(canvas => {
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF('p', 'mm', 'a4');
const imgProps = pdf.getImageProperties(imgData);
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
pdf.save('export.pdf');
});
}
}
}
使用 pdfmake 客户端生成 PDF
安装 pdfmake
npm install pdfmake --save
基本使用示例
import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
pdfMake.vfs = pdfFonts.pdfMake.vfs;
export default {
methods: {
createPDF() {
const docDefinition = {
content: [
{ text: 'PDF标题', style: 'header' },
'这是正文内容...'
],
styles: {
header: {
fontSize: 18,
bold: true
}
}
};
pdfMake.createPdf(docDefinition).download('document.pdf');
}
}
}
服务器端生成 PDF
使用 axios 请求服务器
import axios from 'axios';
export default {
methods: {
requestServerPDF() {
axios({
url: '/api/generate-pdf',
method: 'POST',
responseType: 'blob',
data: { content: 'PDF内容' }
}).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'server.pdf');
document.body.appendChild(link);
link.click();
});
}
}
}
每种方法适用于不同场景,vue-pdf适合直接显示和导出现有PDF,jsPDF适合动态生成简单PDF,html2canvas+jsPDF组合适合将HTML转为PDF,pdfmake提供更丰富的样式控制,而服务器端方案适合复杂PDF生成需求。






