vue实现导出PDF
实现Vue导出PDF的方法
使用html2canvas和jspdf库
安装依赖库:
npm install html2canvas jspdf --save
在Vue组件中引入:
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
创建导出方法:
methods: {
exportToPDF() {
const element = document.getElementById('pdf-content');
html2canvas(element).then(canvas => {
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF('p', 'mm', 'a4');
const imgWidth = 210;
const pageHeight = 295;
const imgHeight = canvas.height * imgWidth / canvas.width;
let heightLeft = imgHeight;
let position = 0;
pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
while (heightLeft >= 0) {
position = heightLeft - imgHeight;
pdf.addPage();
pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
}
pdf.save('document.pdf');
});
}
}
使用vue-html2pdf插件
安装插件:
npm install vue-html2pdf --save
在组件中使用:
import VueHtml2pdf from 'vue-html2pdf'
export default {
components: {
VueHtml2pdf
},
methods: {
generateReport() {
this.$refs.html2Pdf.generatePdf()
}
}
}
模板部分:
<vue-html2pdf
ref="html2Pdf"
:html-to-pdf-options="options"
filename="my-pdf"
:paginate-x="156"
:paginate-y="180"
>
<div slot="pdf-content">
<!-- 要导出的内容 -->
</div>
</vue-html2pdf>
<button @click="generateReport">导出PDF</button>
使用pdfmake客户端生成
安装pdfmake:
npm install pdfmake --save
实现代码:
import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
pdfMake.vfs = pdfFonts.pdfMake.vfs;
methods: {
generatePDF() {
const docDefinition = {
content: [
{ text: 'PDF标题', style: 'header' },
'这是PDF内容...',
{ text: '动态内容', margin: [0, 20, 0, 0] }
],
styles: {
header: {
fontSize: 18,
bold: true
}
}
};
pdfMake.createPdf(docDefinition).download('custom.pdf');
}
}
注意事项
确保要导出的内容已完全渲染,可在mounted钩子或使用$nextTick处理异步渲染问题
对于大量数据或复杂布局,考虑分页处理避免PDF文件过大
中文支持需要额外配置字体,pdfmake需要注册中文字体
浏览器安全策略可能限制跨域资源导出,确保所有资源同源或已正确处理CORS







