将系统的分析报告页面生成PDF,然后可以导出成PDF。
首先生成报告页面,也就是常规页面;
然后将页面转换成图片( 用到的组件 html2canvas);
最后将图片导出成PDF( 用到的组件 jspdf )。
废话不多说,直接上代码
//先引入
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
//导出方法
trainReport(){
//设置loading动画
const loading = this.$loading({
lock: true,
text: "正在生成PDF文件...",
spinner: "el-icon-loading",
background: "hsla(0,0%,100%,.9)",
});
const html = document.getElementById("content"); //需要导出的标签页
//设置宽高
let width = html.offsetWidth / 4;
let height = html.offsetHeight / 4;
let limit = 14400;
if (height > limit) {
let contentScale = limit / height;
height = limit;
width *= contentScale;
}
this.savePdf( html, loading, '总结报告',width,height);
},
savePdf(el, loading, title,width,height) {
html2canvas(el, {
scale: 2, // 处理模糊问题
dpi: 300, // 处理模糊问题
useCORS:true,
allowTaint: true
}).then((canvas) => {
let context = canvas.getContext('2d');
let orientation;
if (context) {
context.mozImageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
context.msImageSmoothingEnabled = false;
context.imageSmoothingEnabled = false;
}
const pageData = canvas.toDataURL("image/jpeg", 1.0);
// 不带分页效果
let img = new Image();
img.src = pageData;
img.onload = function () {
img.width /= 2;
img.height /= 2;
img.style.transform = 'scale(0.5)';
let pdf;
orientation = width > height ? 'l' : 'p'
pdf = new jsPDF(orientation , 'pt', [ width, height ],true);
pdf.addImage( pageData, 'JPEG', 0, 0, width, height, );
pdf.save("总结报告.pdf");
}
//带分页效果
// 内容的宽度
// const contentWidth = canvas.width;
// // 内容高度
// const contentHeight = canvas.height;
// // 一页pdf显示html页面生成的canvas高度,a4纸的尺寸[595.28,841.89];
// const pageHeight = contentWidth / 592.28 * 841.89 ;
// // 未生成pdf的html页面高度
// let leftHeight = contentHeight;
// // 页面偏移
// let position = 0;
// // a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
// const imgWidth = 595.28;
// const imgHeight = (592.28 / contentWidth) * contentHeight;
// // canvas转图片数据
// const pageData = canvas.toDataURL("image/jpeg", 1.0);
// // 新建JsPDF对象
// const PDF = new jsPDF("", "pt", "a4");
// // 判断是否分页
// if (leftHeight < pageHeight) {
// PDF.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight);
// } else {
// while (leftHeight > 0) {
// PDF.addImage(pageData, "JPEG", 0, position, imgWidth, imgHeight);
// leftHeight -= pageHeight;
// position -= 841.89;
// if (leftHeight > 0) {
// PDF.addPage();
// }
// }
// }
// // 保存文件
// PDF.save("总结报告.pdf");
})
.catch(() => {})
.finally(() => {
loading.close();
});
},