關(guān)鍵點(diǎn)
css: page-break-after:always 頁(yè)面分頁(yè)
function printSet(){
var header = document.querySelector(".no-show").querySelector(".th-header"); //獲取需要重復(fù)顯示的表頭元素節(jié)點(diǎn)矩动。
var css = "page-break-after:always";
var currentHeight = 0;
var page = 1;
var all = document.querySelectorAll(".data-coloum"); //獲取所有列數(shù)據(jù)
var oldItem ="";
var deleArr = document.querySelector(".no-show").querySelectorAll(".th-header"); // 避免刪除后,再次打印释漆,表頭重復(fù)顯示問(wèn)題
deleArr.forEach((item,index)=>{
if(index>=1){
item.parentNode.removeChild(item); // 移除表頭
}
})
for(var item of all){
if(page === 1){ // 第一頁(yè)可能存在標(biāo)題等信息 高度需要比其他頁(yè)小點(diǎn)
if(currentHeight>750){ // 設(shè)置每頁(yè)表格顯示的高度悲没。
oldItem.setAttribute("style",css);
var p1 = header.cloneNode(true)
oldItem.parentNode.insertBefore(p1, item);// 插入表頭
currentHeight = 0;
page++;
} else {
currentHeight += item.offsetHeight; // 累加每一列的高度
oldItem = item;
}
} else {
if(currentHeight>800){
oldItem.setAttribute("style",css);
var p1 = header.cloneNode(true)
oldItem.parentNode.insertBefore(p1, item);
currentHeight = 0;
} else {
currentHeight += item.offsetHeight;
oldItem = item;
}
}
}
}
function sumbit () { // 確定打印
this.printSet();
var newWin = window.open(window.document.URL); //將本頁(yè)在新窗口中打開(kāi),方便打印完成后關(guān)閉
var prnhtml = document.getElementById('print').innerHTML; 獲取頁(yè)面需要打印節(jié)點(diǎn)的內(nèi)容
prnhtml += "<style>page-break-after:always @page { margin:0; } .print-show-on {display: none;} .table-box {font-size: 12px;} .red{ color: red;} .flex-box {display: flex;text-align: center;} .th-header {background-color: #f7f7f7; border-top: 1px solid #000;} .flex-item {flex:1;border-right: 1px solid #000;border-bottom: 1px solid #000;display: flex;align-items: center;justify-content: center;} .pn { text-align: left; flex:1.5;} .sc {flex:0.7} .xuhao {width: 50px;border-left: 1px solid #000; border-bottom: 1px solid #000;border-right: 1px solid #000; display: flex;align-items: center;justify-content: center;}</style>";
newWin.document.body.innerHTML = prnhtml //將打印的部分覆蓋新打開(kāi)窗簾的body元素;
// console.log(prnhtml)
newWin.print();//打印
newWin.close();//關(guān)閉打印窗口
},
注意點(diǎn):
1.頁(yè)面如果需要展示一個(gè)顯示效果男图,一個(gè)打印效果示姿,則需要用定位將打印效果的節(jié)點(diǎn)移出到窗口顯示當(dāng)中,打印中css標(biāo)注為no-show;
2.執(zhí)行打印方法后逊笆,表頭會(huì)在合適的位置插入到打印的頁(yè)面中栈戳,因此每次打印前,需要移除重復(fù)的表頭难裆;
3.通過(guò)currentHeight定義每頁(yè)列表顯示的高度總和子檀;
4.window.open相當(dāng)于是打開(kāi)一個(gè)新頁(yè)面镊掖,樣式文件需要寫(xiě)在內(nèi)聯(lián)或者直接加在innerHTML中。
5.打印的內(nèi)容用id標(biāo)注print
1598520387(1).jpg