调用 window.print()打印指定区域
打印css样式配置 (根据自己需求配置即可):
@media print{
@page{
overflow:auto;
/* 设置打印方向 portrait纵向 landscape横向 */
size: A4 portrait;
/* 去除页眉页脚 */
margin: 0.5cm;
padding: 20px;
}
html{
overflow: visible;
}
body {
zoom: 0.9;
}
tr{
/* 行被截断时自动换行 */
page-break-before: always;
page-break-after: always;
page-break-inside: avoid;
}
}
把打印内容嵌入到iframe
页面,调用打印弹窗
printClick(id) {
let printContentHtml = `<style>
@media print{
@page{
/* 纵向portrait 横向landscape */
overflow:auto;
size: A4 landscape;
margin: 0.5cm;
}
html{
overflow: visible;
}
body {
zoom: 0.9;
}
tr{
/* 行被截断时自动换行 */
page-break-before: always;
page-break-after: always;
page-break-inside: avoid;
}
}
</style>`
printContentHtml = document.getElementById(id).innerHTML
const iframe = document.createElement('iframe')
iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;')
document.body.appendChild(iframe)
iframe.contentDocument.write(printContentHtml)
iframe.contentDocument.close()
iframe.contentWindow.print()
document.body.removeChild(iframe)
},