当前位置: 首页 > Web前端 > HTML

html打印相关操作及实现

时间:2023-04-02 12:31:01 HTML

2020-02-19|chrome79.0.3945.130测试没问题没有兼容性测试原理是调用window.print()方法,但是这个方法只能打印当前页面的所有内容,所以解决部分打印有如下方案1:使用iframe注入需要打印的元素和样式然后调用print//示例代码函数print(){|如果元素。contentDocumentcontent.document.body.innerHTML=this.detailTableconststyleEle=document.createElement('style')/*打印时去掉页眉和页脚*/styleEle.innerHTML='@mediaprint{@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:使用@mediaprint,在当前页面设置打印操作时需要隐藏的元素@mediaprint{/*这里将不需要打印的元素设置为不显示*/.hidden-element{display:none;/*可见性:隐藏;*/}/*纸张设置为1200px宽,800px高*/@page{size:1200px800px;}}打印标签时使用的样式监听打印事件window.addEventListener('beforeprint||afterprint',()=>{});最后推荐一个插件:https://printjs.crabbly.com/#documentation欢迎交流Github