实现el-table打印功能,样式对齐,去除滚动条
// 整个页面打印
function printTable(id) {
// let domId = '#js_index'
// if (id) {
// domId = `#${ id }`;
// }
// let wpt = document.querySelector(domId);
// let newContent = wpt.innerHTML;
// let oldContent = document.body.innerHTML;
// document.body.innerHTML = newContent;
// window.print(); //打印方法
// history.go(0);
// document.body.innerHTML = oldContent;
if (id) {
// 获取打印DOM
let el = document.getElementById(id);
// 当前页面样式
let headDom = document.getElementsByTagName("head")[0];
// 创建iframe
let iframe = document.createElement("iframe");
// 设置iframe样式
iframe.setAttribute("id", id);
iframe.setAttribute(
"style",
"position:absolute;width:0px;height:0px;left:-500px;top:-500px;"
);
// 在页面插入iframe
document.body.appendChild(iframe);
// 获取iframe内的html
let doc = iframe.contentWindow.document;
// 经需要打印的DOM插入iframe
let printMain = document.createElement("div");
printMain.setAttribute("id", id);
printMain.innerHTML = el.innerHTML;
doc.body.appendChild(printMain);
// 设置iframe内的header,添加样式文件
setTimeout(() => {
doc.getElementsByTagName("head")[0].innerHTML = headDom.innerHTML;
const table = doc.querySelectorAll('.el-table__header,.el-table__body');
const table1 = doc.querySelectorAll('.el-table');
const table2 = doc.querySelectorAll('.el-table__body-wrapper');
for (let i = 0; i < table2.length; i++) {
const tableItem = table2[i];
console.log(tableItem);
tableItem.style.maxHeight = 'unset';
}
for (let i = 0; i < table1.length; i++) {
const tableItem = table1[i];
console.log(tableItem);
tableItem.style.maxHeight = 'unset';
}
setTimeout(() => {
//el-table 打印不全的问题
for (let i = 0; i < table.length; i++) {
const tableItem = table[i];
console.log(table1);
tableItem.style.width = '100%';
const child = tableItem.childNodes;
for (let j = 0; j < child.length; j++) {
const element = child[j];
if (element.localName == 'colgroup') {
element.innerHTML = '';
}
}
}
setTimeout(function () {
iframe.contentWindow.focus();
iframe.contentWindow.print();
// 关闭iframe
doc.close();
document.body.removeChild(iframe);
}, 1000);
}, 1000)
}, 0)
} else {
window.print(); //打印方法
}
}