原理为调用 window.print() 方法,但是该方法只能对当前页面全部打印,所以有了以下方案来解决局部打印
1: 利用 iframe 将需要打印的元素和样式注入 再调用打印
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | // 示例代码 function print () { let ifElement = document.getElementById( 'ifId' ) const addHtmlPrint = () => { const content = ifElement.contentWindow || ifElement.contentDocument content.document.body.innerHTML = this .detailTable const styleEle = document.createElement( 'style' ) /* 去掉打印时的页头和页脚 */ styleEle.innerHTML = '@media print {@page { margin: 5mm; }}' content.document.getElementsByTagName( 'head' )[0].appendChild(styleEle) /* 保障 iframe 中资源加载完成,图片要用 img 形式引入 */ ifElement.onload = () => { content.print() } } this .getDetailTable() if (ifElement) { // 若已经创建,则直接打印 addHtmlPrint() } else { ifElement = document.createElement( 'iframe' ) ifElement.setAttribute( 'id' , 'ifId' ) ifElement.setAttribute( 'style' , 'display:none' ) document.body.appendChild(ifElement) addHtmlPrint() } } |
2: 利用 @media print,在当前页面设置打印操作时需要隐藏的元素
1 2 3 4 5 6 7 8 9 10 11 | @media print { /* 这里将不需要打印的元素设置为不显示 */ .hidden-element{ display : none ; /* visibility:hidden; */ } /*纸张设置为宽1200px 高800px*/ @page{ size : 1200px 800px ; } } |
联系客服