vue实现页面导出
Vue 实现页面导出为 PDF 或图片
在 Vue 中实现页面导出功能,通常需要将页面内容转换为 PDF 或图片格式。以下是几种常见的实现方法:
使用 html2canvas 和 jsPDF 导出为 PDF
安装依赖库:
npm install html2canvas jspdf
在 Vue 组件中使用:

import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
export default {
methods: {
exportToPDF() {
const element = document.getElementById('export-content');
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('exported-page.pdf');
});
}
}
}
使用 vue-html2pdf 插件
安装插件:
npm install vue-html2pdf
在组件中使用:

import VueHtml2pdf from 'vue-html2pdf'
export default {
components: {
VueHtml2pdf
},
methods: {
generateReport() {
this.$refs.html2Pdf.generatePdf()
}
}
}
模板部分:
<vue-html2pdf
ref="html2Pdf"
:paginate-x="156"
:pdf-quality="2"
filename="exported-file"
:enable-download="true"
>
<div slot="pdf-content">
<!-- 要导出的内容 -->
<div id="export-content">
...
</div>
</div>
</vue-html2pdf>
<button @click="generateReport">导出PDF</button>
使用浏览器原生打印功能
对于简单的打印需求,可以直接使用浏览器打印功能:
printPage() {
window.print();
}
CSS 中可以添加打印样式:
@media print {
.no-print {
display: none;
}
}
注意事项
- 导出复杂页面时,可能需要调整样式以确保打印效果
- 图片和字体需要确保在导出时能正确加载
- 对于大量数据导出,考虑分页处理
- 某些CSS属性可能在PDF中无法正确呈现
以上方法可以根据具体需求选择使用,html2canvas + jsPDF 组合提供了较大的灵活性,而 vue-html2pdf 则提供了更简单的API。






