js 自定义打印,不打开新窗口

function customPrint(content, option = {}) {
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 = option.title || "";
printIframeWindow.document.write(content);
printIframeWindow.addEventListener('beforeprint', () => {
option.beforePrint && option.beforePrint(printIframe);
})
printIframeWindow.addEventListener('afterprint', () => {
option.afterPrint && option.afterPrint(printIframe);
removeOldIframe();
})
setTimeout(() => {
printIframeWindow.focus();
printIframeWindow.print();
})
}

 

调用方法customPrint(res.data);

posted @ 2022-11-10 11:20  Agreoself  阅读(145)  评论(0编辑  收藏  举报