vue 实现导出pdf
Vue 实现导出 PDF 的方法
在 Vue 项目中导出 PDF 可以通过多种方式实现,常见的有使用 html2canvas 和 jspdf 库,或直接调用浏览器打印功能。以下是几种具体实现方法:
使用 html2canvas 和 jspdf 生成 PDF
安装依赖库:
npm install html2canvas jspdf
在 Vue 组件中引入并使用:
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
export default {
methods: {
async exportToPDF() {
const element = document.getElementById('pdf-content');
const canvas = await html2canvas(element);
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF('p', 'mm', 'a4');
const imgWidth = 210; // A4 宽度 (mm)
const imgHeight = (canvas.height * imgWidth) / canvas.width;
pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
pdf.save('export.pdf');
}
}
}
模板部分:
<template>
<div>
<div id="pdf-content">
<!-- 需要导出的内容 -->
</div>
<button @click="exportToPDF">导出 PDF</button>
</div>
</template>
使用浏览器打印功能
直接调用浏览器的打印 API 实现 PDF 导出(需用户手动选择“保存为 PDF”):
methods: {
printPDF() {
window.print();
}
}
CSS 优化打印样式:
@media print {
body * {
visibility: hidden;
}
#pdf-content, #pdf-content * {
visibility: visible;
}
#pdf-content {
position: absolute;
left: 0;
top: 0;
}
}
使用第三方库 vue-html2pdf
安装 vue-html2pdf:
npm install vue-html2pdf
在组件中使用:
import VueHtml2pdf from 'vue-html2pdf';
export default {
components: { VueHtml2pdf },
methods: {
generatePDF() {
this.$refs.html2Pdf.generatePdf();
}
}
}
模板部分:

<template>
<div>
<vue-html2pdf
ref="html2Pdf"
:filename="'export.pdf'"
:enable-download="true"
>
<div slot="content">
<!-- 需要导出的内容 -->
</div>
</vue-html2pdf>
<button @click="generatePDF">导出 PDF</button>
</div>
</template>
注意事项
- 内容溢出:确保导出的内容宽度不超过 PDF 页面宽度,否则会被截断。
- 分页处理:长内容需手动分页,可通过计算高度动态分割。
- 图片跨域:若内容包含跨域图片,需配置
html2canvas的useCORS: true。 - 字体支持:中文字体需在
jspdf中手动注册或使用图片形式渲染。
以上方法可根据实际需求选择,html2canvas + jspdf 适合复杂内容,浏览器打印适合简单场景,vue-html2pdf 提供了更集成的解决方案。






