代码
调用原生ctrl p 功能打印一个dom节点。
传递的dom节点最好是带完整css属性的,而不是动态生成的带class的这种节点,顶层window写的class在iframe里面的window不起作用。
const printDom = dom => {
if (
typeof HTMLElement === 'function' ?
dom instanceof HTMLElement :
(dom && (typeof dom === 'object') && (dom.nodeType === 1) && (typeof dom.nodeName === 'string'))
)
return new Error('请打印一个dom元素')
const
iframe = document.createElement('iframe'),
iframeStyle = { position: 'absolute', top: 0, left: 0, visibility: 'hidden' },
iframeBodyStyle = { display: 'flex', alignItems: 'center', justifyContent: 'center', };
Object.keys(iframeStyle).forEach(i => iframe.style[i] = iframeStyle[i])
document.body.appendChild(iframe)
const _document =
(iframe.contentWindow && iframe.contentWindow.document)?
iframe.contentWindow.document :
null
if (_document) {
const _body = _document.getElementsByTagName('body')[0]
if (_body) {
Object.keys(iframeBodyStyle).forEach(i => _body.style[i] = iframeBodyStyle[i])
_body.appendChild(dom.cloneNode(true))
iframe.contentWindow.print()
document.body.removeChild(iframe)
}
}else{
return new Error('打印失败!请检查浏览器是否支持iframe标签!')
}
}
使用
const testNode = () => {
const
tmp = document.createElement('div'),
tmpStyle = {
width: '100px',
height: '100px',
background: 'red',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
};
Object.keys(tmpStyle).forEach(i => tmp.style[i] = tmpStyle[i])
tmp.innerHTML = '打印测试'
return tmp
}
printDom(testNode())