vue 实现导出pdf
Vue 实现导出 PDF 的方法
使用 html2pdf.js 库
安装 html2pdf.js:
npm install html2pdf.js
在 Vue 组件中引入并使用:
import html2pdf from 'html2pdf.js';
export default {
methods: {
exportToPDF() {
const element = document.getElementById('content-to-export');
const opt = {
margin: 1,
filename: 'document.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
};
html2pdf().from(element).set(opt).save();
}
}
}
使用 jsPDF 和 html2canvas
安装依赖:
npm install jspdf html2canvas
在 Vue 组件中实现:
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';
export default {
methods: {
async exportToPDF() {
const element = document.getElementById('content-to-export');
const canvas = await html2canvas(element);
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF('p', 'mm', 'a4');
const imgWidth = 210;
const imgHeight = canvas.height * imgWidth / canvas.width;
pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
pdf.save('document.pdf');
}
}
}
使用 vue-html2pdf 插件
安装插件:
npm install vue-html2pdf
在 Vue 组件中使用:
import VueHtml2pdf from 'vue-html2pdf';
export default {
components: { VueHtml2pdf },
methods: {
generateReport() {
this.$refs.html2Pdf.generatePdf();
}
}
}
模板部分:
<vue-html2pdf
ref="html2Pdf"
:filename="filename"
:pdf-quality="2"
:enable-download="true"
>
<div slot="pdf-content">
<!-- 要导出的内容 -->
</div>
</vue-html2pdf>
<button @click="generateReport">导出 PDF</button>
注意事项
- 确保导出的内容在 DOM 中可见
- 对于复杂布局,可能需要调整 html2canvas 的 scale 参数
- 中文支持可能需要引入额外的字体
- 大文档导出可能需要优化性能
中文支持方案
对于需要支持中文的情况,可以在 jsPDF 中加载中文字体:
const pdf = new jsPDF();
pdf.addFileToVFS('NotoSansSC-Regular.ttf', fontData);
pdf.addFont('NotoSansSC-Regular.ttf', 'NotoSansSC', 'normal');
pdf.setFont('NotoSansSC');
服务器端生成方案
对于更复杂的 PDF 生成需求,可以考虑:

- 使用 Puppeteer 在服务器端生成
- 调用专业的 PDF 生成 API
- 使用 PDFKit 等库进行编程式生成






