安裝:npm i html2canvas --save
安裝:npm i jspdf
const PrintOrDownload = (isPrint, targetDom, printCont, nameTitle) => {
// 獲取節(jié)點(diǎn)高度,后面為克隆節(jié)點(diǎn)設(shè)置高度。
let height = targetDom.height;
// 克隆節(jié)點(diǎn)登下,默認(rèn)為false做粤,不復(fù)制方法屬性抹剩,為true是全部復(fù)制。
let cloneDom = targetDom.cloneNode(true);
// 設(shè)置克隆節(jié)點(diǎn)的css屬性,因?yàn)橹暗膶蛹?jí)為0,我們只需要比被克隆的節(jié)點(diǎn)層級(jí)低即可楼入。
//cloneDom.style.backgroundColor = 'red';
cloneDom.style.position = 'absolute';
cloneDom.style.top = '0';
cloneDom.style.index = '-1';
cloneDom.style.padding = '40px 60px';
cloneDom.style.height = height;
// 將克隆節(jié)點(diǎn)動(dòng)態(tài)追加到body后面。
document.getElementById(printCont)?.appendChild(cloneDom);
// 插件生成base64img圖片牧抽。
html2canvas(cloneDom, {
useCORS: true,
// 畫(huà)布開(kāi)始渲染的y坐標(biāo)位置
y: 0,
}).then((canvas) => {
let contentWidth = canvas.width;
let contentHeight = canvas.height;
// 一頁(yè)pdf顯示html頁(yè)面生成的canvas高度;
let pageHeight = (contentWidth / 592.28) * 841.89;
// 未生成pdf的html頁(yè)面高度
let leftHeight = contentHeight;
// 頁(yè)面偏移
let position = 0;
// a4紙的尺寸[595.28,841.89]嘉熊,html頁(yè)面生成的canvas在pdf中圖片的寬高
let imgWidth = 595.28;
let imgHeight = (595.28 / contentWidth) * contentHeight;
let pageData = canvas.toDataURL('image/jpeg', 1.0);
// console.log('pageData', pageData);
let pdf = new JsPDF(null, 'pt', 'a4');
// 有兩個(gè)高度需要區(qū)分,一個(gè)是html頁(yè)面的實(shí)際高度扬舒,和生成pdf的頁(yè)面高度(841.89)
// 當(dāng)內(nèi)容未超過(guò)pdf一頁(yè)顯示的范圍阐肤,無(wú)需分頁(yè)
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;
// 避免添加空白頁(yè)
position -= 841.89;
if (leftHeight > 0) {
pdf.addPage();
}
}
}
if (isPrint) {
//打印
// pdf.autoPrint()
// pdf.output('dataurlnewwindow')
var opener = window.open();
var cont = document.getElementById(printCont).innerHTML;
opener.document.write(cont);
// setTimeout(() => {
opener.print();
// }, 1000)
} else {
//下載
pdf.save(nameTitle || 'MyCoreHub' + '.pdf');
}
document.getElementById(printCont)?.removeChild(cloneDom);
});
};
使用:
PrintOrDownload(true, pdfs.value, 'agreemnet-content', 'title值')