前段时间遇到一个需求,产品说需要把当前页面,点击导出按钮,导出为pdf,所以就有了以下代码:
部分来自于官方直连GPT4o
<div class="mian-box-contain"></div>
这里是要导出的内容,可以包含其他dom元素
<div class="export-preview-container"></div>
这里是我们导出的内容要放的盒子
上面两行是参考示例,具体结合自己的代码使用
import $ from "jquery";
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf'
export default {
data () {
return {
}
},
mounted() {
},
methods: {
formatterPdfElement($dom) {
var $copyElement = $dom.cloneNode(true);
document.querySelector('.export-preview-container').appendChild($copyElement);
this.visiblePreview = true;
this.$nextTick(() => {
var results = [{
position: 0,
height: 0
}];
var pageOffsetTop = $copyElement.offsetTop;
var pageOffsetWidth = $copyElement.offsetWidth;
// var $unitElements = $($copyElement).find('.minimum-unit'); // 遍历所有子元素不可取,应只遍历第一层子元素
var $unitElements = $($copyElement).children(); // 遍历所有子元素不可取,应只遍历第一层子元素
var perPageHeight = pageOffsetWidth / 595.28 * 841.89;
let tHeight = perPageHeight;
let insertList = [];
$unitElements.each((index, $element) => {
console.log(tHeight, 'tHeight');
console.log($($element), $($element).outerHeight(true));
tHeight -= $($element).outerHeight(true);
if (tHeight < 0) {
let remainHeight = parseInt(tHeight + $($element).outerHeight(true) + 30);
tHeight = perPageHeight - $($element).outerHeight(true);
let obj = {
index, remainHeight};
insertList.push(obj);
}
});
insertList.forEach((dif, index) => {
let remHeight = dif.remainHeight;
let domObj = document.createElement("div");
domObj.innerHTML = "";
domObj.setAttribute("style", `width:100%;height:${
remHeight}px`)
console.log('$unitElements[dif.index] :>> ', $unitElements[dif.index]);
$unitElements[dif.index].before(domObj);
})
console.log($copyElement, "241");
// return
var pdf = new jsPDF('', 'pt', 'a4');
html2canvas($copyElement, {
useCORS: true,
scale: 2,
allowTaint: true,
background: '#f0f4f7',
ignoreElements: (element) => {
if (element.className.indexOf('top-btns') > -1) {
return true;
}
return false;
}
}).then(canvas => {
var contentWidth = canvas.width;
var contentHeight = canvas.height;
var pageHeight = contentWidth / 592.28 * 841.89;
var leftHeight = contentHeight;
var position = 0;
var imgWidth = 592.28;
var imgHeight = 592.28 / contentWidth * contentHeight;
if (leftHeight < pageHeight) {
pdf.addImage(canvas.toDataURL('image/jpeg', 1), 'JPEG', 0, position, imgWidth, imgHeight)
} else {
while (leftHeight > 0) {
pdf.addImage(canvas.toDataURL('image/jpeg', 1), 'JPEG', 0, position, imgWidth, imgHeight);
leftHeight -= pageHeight;
position -= 841.89;
if (leftHeight > 0) {
pdf.addPage();
}
}
}
}).then(() => {
const name = `${
this.reportInfo.devPath}-${
this.reportInfo.startDtm}~${
this.reportInfo.endDtm}`;
pdf.internal.scaleFactor = 1.33;
pdf.save(`${
name}.pdf`);
this.isExporting = false;
this.visiblePreview = false;
});
})
},
exportReport() {
var content = document.querySelector('.mian-box-contain');
this.formatterPdfElement(content);
},
/*
* 导出pdf函数
**/
exportReportPdf() {
window.open(this.newUrl)
}
},
}