1、背景
在一些可视化平台,业务都可能会提出这样的需求,当前所展示的东西我想导出PDF或者PNG图片进行查阅;
2、DIV转图片流通过jspdf插件并下载
主要用到html2canvas与jspdf插件
const exportPDF = function () {
let element = document.getElementsByTagName('body')[0]; // 需要导出的元素
html2Canvas(element, {
allowTaint: false,
scale: 2.0,
useCORS: true
}).then(function (canvas) {
let contentWidth = canvas.width;
let contentHeight = canvas.height;
let pageHeight = contentWidth / 592.28 * 841.89;
let leftHeight = contentHeight;
let position = 0;
let imgWidth = 595.28;
let imgHeight = 592.28 / contentWidth * contentHeight;
let pageData = canvas.toDataURL('image/jpeg', 1.0); // 图片格式文件流
let PDF = new JsPDF('', 'pt', 'a4');
PDF.page = 1;
if(leftHeight < pageHeight) {
PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
PDF.setFontSize(6);
PDF.text(2, 6, moment(new Date())).format('YYYY-MM-DD HH:mm:ss');
} else {
while(leftHeight > 0) {
PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
leftHeight -= pageHeight;
position -= 841.89;
PDF.setFontSize(6);
PDF.text(2, 6, moment(new Date())).format('YYYY-MM-DD HH:mm:ss');
if (leftHeight > 0) {
PDF.addPage();
}
}
}
PDF.save('name' + '.pdf');
})
}