Js 实现局部打印功能

时间:2022-06-13 13:19:39

1.当前页面

    var bodyHtml = window.document.body.innerHTML;
window.document.body.innerHTML = printHtml;//printHtml为当前需要打印的div的内容
window.print();
window.document.body.innerHTML = bodyHtml; 缺点: (1)移除页面内容再插入需要打印页面内容,页面会有一个大的跳动
(2)页面事件效果会丢失

2.iframe 打印

	   function myPrint(){
var el = "<div>Content should be print!</div>";
var iframe = document.createElement('IFRAME');
iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
document.body.appendChild(iframe);
var doc = iframe.contentWindow.document;
doc.write(el);
var pageStyle="html,body{height:100%}img{max-width:100%;max-height:100%;margin:0 auto}";
var style=document.createElement("style");
style.innerText= pageStyle;
doc.getElementsByTagName("head")[0].appendChild(style)
doc.close();
iframe.contentWindow.focus();
iframe.contentWindow.print();

)

缺点: 需要将所有style拷贝到iframe

3.media query 实现

	   @media print {
.no-need-print-block
{
display: none;
}
}

缺点: 一块多个地方复用的模块不好customize

4.reactComponent:

		import React, { PureComponent } from 'react';
import { string } from 'prop-types'; export default class Print extends PureComponent {
static propTypes = {
printHtml: string,
}; static defaultProps = {
printHtml: 'test html',
} setPageStyles = (iDom) => {
const styles = document.getElementsByTagName('style');
const IHead = iDom.getElementsByTagName('head')[0];
let pageStyle = '';
Array.from(styles).map((s) => {
pageStyle += s.innerHTML;
});
const style = document.createElement('style');
style.innerHTML = pageStyle;
IHead.appendChild(style);
} handlePrint = () => {
const { printHtml } = this.props;
const iFrame = this.iframe;
const iFrameWindow = iFrame.contentWindow;
const iDom = iFrameWindow.document;
iDom.write(printHtml);
this.setPageStyles(iDom);
iDom.close();
iFrameWindow.print();
} render() {
return (
<div>
<button style={{ backgroundColor: 'yellow', cursor: 'pointer' }} onClick={this.handlePrint}>print button</button>
<iframe title="print iframe" style={{ position: 'absolute', width: '0', height: '0', left: '-500px', top: '-500px' }} ref={(iframe) => { this.iframe = iframe; }}/>
</div>
);
}
}

缺点: 需要将所有style拷贝到iframe

打印方法兼容性解决方法:

   if (document.queryCommandSupported('print')) {
document.execCommand('print', false, null);
} else {
window.print();
} firefox 只打印一页问题解决: firefox 打印display: flex; display: inline-block; 改display:block;去掉float:left/right;

在desktop显示正常,但是在移动端显示变为小圆圈,无法正确展示选中取消选中效果问题解决方案:

	display: block;
width: 58px;
height: 20px;
-webkit-appearance: checkbox;
-moz-appearance: checkbox;