描述:
在页面中实现点击按钮,打印指定的内容。如图
打印功能其实还好,网上很多代码打印,主要是配置贼繁琐。
代码:
//初版
doPrint=(id) =>{ //方法
const el = document.getElementById('content');
const iframe = document.createElement('IFRAME');
let doc = null;
iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:500px;top:500px;');
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
// 引入打印的专有CSS样式,根据实际修改
//doc.write('<LINK rel="stylesheet" type="text/css" href="css/print.css">'); 此方法单页面无效,心态炸了,直接写js导出css字符串解决
doc.write(el.innerHTML);
doc.close();
// 获取iframe的焦点,从iframe开始打印
iframe.contentWindow.focus();
iframe.contentWindow.print();
if (navigator.userAgent.indexOf("MSIE") > 0)
{
document.body.removeChild(iframe);
}
}
//优化-带批量打印版-同事会在一个页面频繁打印,后发现在页面生成很多iframe标签,处理了一下
doPrint=(record) =>{ //reacord == 1 批量打印
const { printCenter: {printData }, loading } = this.props;
const { printArr } = this.state;
const del = document.getElementById('iframe')
//删除上一个
if(del){document.body.removeChild(del);}
const iframe = document.createElement('IFRAME');
let doc = null;
let html = ''
iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:500px;top:500px;');
iframe.id = 'iframe'
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
console.log('doprint',record )
if(record != 1){
//单个
html = `
<!--startprint-->
<div style="padding-top:5px;">${record.firstLine}</div>
<div>${record.secondLine}</div>
<div>${record.thirdLine}</div>
<div style="padding-bottom:10px;">${record.fourLine}</div>
<!--endprint-->
`
}else{
//批量
printArr.map((item)=>{
let txt = `<!--startprint-->
<div style="padding-top:5px;">${item.firstLine}</div>
<div>${item.secondLine}</div>
<div>${item.thirdLine}</div>
<div class="pb20" style="padding-bottom:10px;">${item.fourLine}</div>
<!--endprint-->`
html+=txt
})
}
doc.write(html);
doc.close();
// 获取iframe的焦点,从iframe开始打印
iframe.contentWindow.focus();
iframe.contentWindow.print();
if (navigator.userAgent.indexOf("MSIE") > 0){ document.body.removeChild(iframe); }
}
//html
<Modal
title="打印"
visible={this.state.visiblePrint}
onOk={this.doPrint} //调用
onCancel={this.visiblePrintHide}
>
<div id="content"> //重要
<div>{printData.firstLine}</div>
<div>{printData.secondLine}</div>
<div>{printData.thirdLine}</div>
</div>
</Modal>
配置:
设备:DL-888D打印机
纸张:热敏(40mm x 30mm)
第一步: 使用光盘下载驱动,或者官网下载
第二步: 解压出来连个文件夹,一个是驱动程序,一个是打印机设置工具,
第三步:
打印机接通电源,与电脑usb连接线接通,然后打开打印机设置工具(如不懂,点击官方视频)
点击设置打印机
第四步:
安装驱动,在电脑设置找到打印机,点击添加打印机,win10点击【我需要的打印机不在列表中】,然后
点击从磁盘安装,点击浏览找到你的最开始解压出来的驱动,选择型号DL-888D安装即可
第五步:
点击你页面按钮,调出打印窗口,点击更多设置,选择最小值(或者自定义),去除页面多于信息
第六步:
点击上图中的【使用系统对话框进行打印ctrl+shift+p】(或者电脑设置-打印机-打印机属性配置)
先选择打印机,然后点击首选项
页面设置中,点击新建,自定义标签
确认完成,再做如图配置
第七步:
选择刚刚自定义的【标签】做如图配置;如果多出一个空白页,减少缩放值(96或98);如果页面排序乱,修改边距,总有一个合适的,慢慢试。
第八步:
至此所有软件都准备完毕,下面是硬件配置
图中黑色三角必须和下面的三角对齐,我的图片没对齐,所以会出现不识别纸张,多出来及标签,对齐以后就好了
测试结果