js打印 dom节点或者 保存dom节点为pdf

代码

调用原生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())

效果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值