记录一下调用原生JS的window.print()实现打印功能,方便下次copy使用。
1. 打印内容与显示内容一致
window.print打印body的内容,如需打印当前页,即body中显示内容与打印内容一致,直接调用window.print()即可。
注意:@media print{}设置打印样式
2. 打印内容与显示内容不一致:
1.在当前页面中编写相应的DOM,设置style
<div id="printContent">
此处存放打印内容
</div>
#printContent{
display:none
}
- 创建一个新页面,新页面的内容来源于ID(printContent)中的内容
<button onClick={handlePrint}>Print</button>
const handlePrint = () => {
const newWindow = window.open('','printWindow');
if(newWindow === null) return;
const printDom= window.document.getElementById('printContent');
if(printDom == null) return;
const htmlString =`<html lang="en">
<head>
<meta charset="utf_8">
<link rel="icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Print</title>
<style>
@media screen{ // 设置显示效果
body {
font-family:"Roboto","Helvetica","Arial",sans-serif,
font-size: 16px;
background: white;
color: black;
}
}
@media print{ // 设置打印效果
body {
font-family:"Roboto","Helvetica","Arial",sans-serif,
font-size: 16px;
background: white;
color: black;
}
*{
-webkit-print-color-adjust: exact; // 打印背景色,如无设置则CSS中设置的背景色无法打印
print-color-adjust: exact;
}
img{
with: 100%;
height: 100%;
max-height: 400px;
}
}
</style><body>`;
const htmlStringEnd = `</body></html>`;
newWindow.document.write(`${htmlString}${printDom.innerHTML}${htmlstringEnd}`);
newWindow.print();
newindow.close();
return false;
}
说明:很多示例只有中间那段printDom.innerHTML, 因是创建新页面,建议增加完整的HTML结构,原页面的style全部失效,需要设置打印页面的样式。
Web显示效果和实际打印效果存在差异,建议在实际工作中,打印出来查看真实效果。