打印功能的实现

记录一下打印功能的实现方式,之前做需求的时候有个预览打印的功能,这边分享一下,下次遇到不会再走弯路。
我这边是再做 react 项目的时候碰到了打印需求,网上其实有关基于 react 的打印插件,功能还是很强大的,我只用到了打印功能,并不需要引入第三方库,所以就用原生方法写了个。
因为我的打印是在弹窗的基础上打印一个表格,所以我新开了个页面,不然点击关闭按钮时,页面就回不来了。以下是实现的代码:

1
2
3
4
5
6
7
8
9
10
<div className="m-table" id="contract">
<div className="m-print">
<h3>打印功能的实现</h3>
<table></table>
</div>
</div>
<div className="m-botton">
<span onClick="{this.print}">打印</span>
<span className="e-ml20" onClick="{this.handleCancel}">关闭</span>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 打印
print = () => {
const newWindow = window.open("", "_blank");
const docStr = document.getElementById("contract").innerHTML;
newWindow.document.write(docStr);
const styles = document.createElement("style");
styles.setAttribute("type", "text/css"); // media="print"
styles.innerHTML = `
body,ol,ul,h1,h2,h3,h4,h5,h6,p,th,td,dl,dd,form,fieldset,legend,input,textarea,select{margin:0;padding:0}
table{border-collapse:collapse;border-spacing:0}
.m-print{padding: 55px 45px 45px}
.m-print h3 {
font-size: 24px;
height: 40px;
line-height: 40px;
text-align: center;
margin: 0px;
}
`;
newWindow.document.getElementsByTagName("body").item(0).appendChild(styles);
newWindow.print();
newWindow.close();
};