vue实现页面导出
Vue 实现页面导出为 PDF 或图片
在 Vue 项目中,可以通过以下方法实现页面内容的导出功能,支持导出为 PDF 或图片格式。
使用 html2canvas 和 jsPDF 导出为 PDF
安装依赖库:
npm install html2canvas jspdf --save
实现代码示例:
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 imgWidth = 210;
const imgHeight = canvas.height * imgWidth / canvas.width;
pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
pdf.save('exported-page.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"
:filename="filename"
:paginate-x="10"
:paginate-y="10"
:enable-download="true"
>
<!-- 需要导出的内容 -->
<div id="export-content">
<!-- 页面内容 -->
</div>
</vue-html2pdf>
导出为图片
仅使用 html2canvas 导出为图片:
exportToImage() {
const element = document.getElementById('export-content');
html2canvas(element).then(canvas => {
const link = document.createElement('a');
link.download = 'exported-image.png';
link.href = canvas.toDataURL();
link.click();
});
}
注意事项
- 确保导出的内容已完全渲染,可在 mounted 或 updated 生命周期钩子中处理
- 对于大量数据,可能需要考虑分页处理
- 样式问题可能需要额外调整,特别是背景色和字体
- 跨域资源可能需要特殊处理
高级配置选项
html2canvas 提供多种配置选项:
html2canvas(element, {
scale: 2, // 提高导出质量
logging: false,
useCORS: true, // 处理跨域图片
allowTaint: true,
backgroundColor: '#FFFFFF'
});
jsPDF 也支持多种自定义:
const pdf = new jsPDF({
orientation: 'landscape',
unit: 'pt',
format: [width, height]
});






