一、原始window.print()
<el-button class="printBox" type="primary" @click="printFn()" >打印</el-button>
...
printFn(){
window.print()
}
二、指定区域的打印
优点:可以指定dom元素的打印
缺点:打印完可能造成页面部分不能用,如:表单不可输入,按钮触发不生效问题
<div id="printContent">
...打印区域...
</div>
printFn() {
let newstr = document.getElementById("printContent").innerHTML;
let oldstr = document.body.innerHTML;
document.body.innerHTML = newstr;
window.print();
document.body.innerHTML = oldstr;
return false;
}
三、生成 iframe 然后打印(推荐)
<div id="printContent">
<el-table
:data="subject"
:stripe="false"
style="width: 100%;"
:header-row-class-name="addClass"
:span-method="arraySpanMethod"
:row-style="cellStyle"
:header-cell-style="{ 'text-align': 'center' }"
:cell-style="{ 'text-align': 'center' }"
border
>
...表格内容
/el-table>
</div>
printFn() {
var iframe = document.getElementById("print-iframe");
if (!iframe) {
var el = document.getElementById("printContent");
iframe = document.createElement("IFRAME");
var doc = null;
iframe.setAttribute("id", "print-iframe");
iframe.setAttribute(
"style",
"position:absolute;width:0px;height:0px;left:-500px;top:-500px;"
);
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
doc.write(
'<style media="print">@page {size: auto;margin: 0mm;}</style>'
);
doc.write(
'<style media="print">table {border-collapse: collapse; width: 100%;} th, td {border: 1px solid #dfe6ec; padding: 8px 0;}</style>'
);
doc.write("<div>" + el.innerHTML + "</div>");
doc.close();
iframe.contentWindow.focus();
}
setTimeout(function() {
iframe.contentWindow.print();
}, 50);
if (navigator.userAgent.indexOf("MSIE") > 0) {
document.body.removeChild(iframe);
}
}
四、使用第三方库 print.js
import Print from "@/utils/print.min.js";
printFn() {
setTimeout(function() {
Print({
printable: "printPage",
type: "html",
scanStyles: false,
targetStyles: ["*"],
style:
"table {border-collapse: collapse; width: 100%;} th, td {border: 1px solid #dfe6ec; padding: 4px 0;}"
});
}, 500);
},