关键点
css: page-break-after:always 页面分页
function printSet(){
var header = document.querySelector(".no-show").querySelector(".th-header"); //获取需要重复显示的表头元素节点。
var css = "page-break-after:always";
var currentHeight = 0;
var page = 1;
var all = document.querySelectorAll(".data-coloum"); //获取所有列数据
var oldItem ="";
var deleArr = document.querySelector(".no-show").querySelectorAll(".th-header"); // 避免删除后,再次打印,表头重复显示问题
deleArr.forEach((item,index)=>{
if(index>=1){
item.parentNode.removeChild(item); // 移除表头
}
})
for(var item of all){
if(page === 1){ // 第一页可能存在标题等信息 高度需要比其他页小点
if(currentHeight>750){ // 设置每页表格显示的高度。
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); //将本页在新窗口中打开,方便打印完成后关闭
var prnhtml = document.getElementById('print').innerHTML; 获取页面需要打印节点的内容
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 //将打印的部分覆盖新打开窗帘的body元素;
// console.log(prnhtml)
newWin.print();//打印
newWin.close();//关闭打印窗口
},
注意点:
1.页面如果需要展示一个显示效果,一个打印效果,则需要用定位将打印效果的节点移出到窗口显示当中,打印中css标注为no-show;
2.执行打印方法后,表头会在合适的位置插入到打印的页面中,因此每次打印前,需要移除重复的表头;
3.通过currentHeight定义每页列表显示的高度总和;
4.window.open相当于是打开一个新页面,样式文件需要写在内联或者直接加在innerHTML中。
5.打印的内容用id标注print