function customPrint(content, options = {}) {
const removeOldIframe = () => {
const oldPrintIframe = document.getElementById('printIframe')
oldPrintIframe && oldPrintIframe.remove && oldPrintIframe.remove()
}
removeOldIframe()
const printIframe = document.createElement('iframe')
printIframe.id = 'printIframe'
document.body.appendChild(printIframe)
const printIframeWindow = printIframe.contentWindow
printIframeWindow.document.title = options.title || ''
printIframeWindow.document.write(content)
printIframeWindow.addEventListener('beforeprint', () => {
options.beforePrint && options.beforePrint(printIframe)
})
printIframeWindow.addEventListener('afterprint', () => {
options.afterPrint && options.afterPrint(printIframe)
removeOldIframe()
})
setTimeout(() => {
printIframeWindow.focus()
printIframeWindow.print()
})
}
打印一个标题
customPrint('<h1>hello world</h1>')
打印一个图片, 打印支持回调
customPrint(`<img src="https://img-blog.csdnimg.cn/2022020422094525927.jpeg"></img>`, {
beforePrint() {
alert('要开始打印了')
},
afterPrint() {
alert('打印窗口已关闭')
}
})