vue实现转成pdf实现打印功能
实现Vue转PDF及打印功能的方法
使用html2canvas和jspdf库
安装依赖库:
npm install html2canvas jspdf
在Vue组件中引入并实现:
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
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; // A4宽度
const imgHeight = canvas.height * imgWidth / canvas.width;
pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
pdf.save('export.pdf');
}
}
}
使用vue-html2pdf插件
安装插件:
npm install vue-html2pdf
组件实现:
import VueHtml2pdf from 'vue-html2pdf'
export default {
components: { VueHtml2pdf },
methods: {
generatePDF() {
this.$refs.html2Pdf.generatePdf()
}
}
}
模板部分:
<vue-html2pdf ref="html2Pdf">
<!-- 要导出的内容 -->
<div id="content">
<!-- 你的HTML内容 -->
</div>
</vue-html2pdf>
<button @click="generatePDF">导出PDF</button>
打印功能实现
添加打印按钮和方法:
methods: {
printPDF() {
const element = document.getElementById('content-to-print');
const opt = {
margin: 1,
filename: 'document.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
};
html2pdf().set(opt).from(element).save();
}
}
样式优化建议
为打印添加专门样式:
@media print {
body * {
visibility: hidden;
}
#content-to-print, #content-to-print * {
visibility: visible;
}
#content-to-print {
position: absolute;
left: 0;
top: 0;
}
}
注意事项
- 处理跨域图片问题,确保图片可访问
- 大文档分页处理可考虑使用jsPDF的addPage方法
- 复杂表格建议转换为图片再插入PDF
- 测试不同浏览器兼容性
以上方法可根据项目需求选择合适方案,html2canvas+jspdf组合适合定制化需求,vue-html2pdf插件提供更简单的集成方式。







