window.print()如何定制化页面?
我们在使用window.print打印页面信息的时候,往往要新增或者删除一些Dom节然后去定制化打印;
我们通过设置打印的样式确定打印区域@media print 设置具体区域;
废话少说上代码
工具类print.ts
1 // 设置打印样式 2 const getStyle = () => { 3 let styleContent = 4 ` 5 #print-container { 6 display: none; 7 } 8 @media print { 9 body > :not(.print-container) { 10 display: none; 11 } 12 html, 13 body { 14 display: block !important; 15 } 16 #print-container { 17 display: block !important; 18 } 19 } 20 `; 21 let style = document.createElement("style"); 22 style.innerHTML = styleContent; 23 return style; 24 } 25 26 // 新建DOM,将需要打印的内容填充到DOM 27 const getContainer = (html: string) => { 28 cleanPrint(); 29 let container = document.createElement("div"); 30 container.setAttribute("id", "print-container"); 31 container.innerHTML = html; 32 return container; 33 } 34 35 // 清空打印内容 36 const cleanPrint = () => { 37 let div = document.getElementById('print-container'); 38 if (div) { 39 document.querySelector('body').removeChild(div); 40 } 41 } 42 43 // 图片完全加载后再调用打印方法 44 const getLoadPromise = (dom: HTMLDivElement) => { 45 let imgs = dom.querySelectorAll("img"); 46 imgs = [].slice.call(imgs); 47 48 if (imgs.length === 0) { 49 return Promise.resolve(); 50 } 51 52 let finishedCount = 0; 53 return new Promise(resolve => { 54 function check() { 55 finishedCount++; 56 if (finishedCount === imgs.length) { 57 resolve(); 58 } 59 } 60 imgs.forEach((img: any) => { 61 img.addEventListener("load", check); 62 img.addEventListener("error", check); 63 }) 64 }); 65 } 66 67 // 定制化打印信息 68 const PrintCustomizeHtml = (html: string) => { 69 let style = getStyle(); 70 let container = getContainer(html); 71 72 document.body.appendChild(style); 73 document.body.appendChild(container); 74 75 getLoadPromise(container).then(() => { 76 window.print(); 77 document.body.removeChild(style); 78 document.body.removeChild(container); 79 }); 80 } 81 82 /** 83 * 传入html的innerHTML字符串 84 */ 85 export default PrintCustomizeHtml;
调用方式:
首先准备要打印的Dom节点信息;
1 <div id='excess-print'> 2 打印内容 3 </div>
然后调用打印节点方法:
1 /** 2 * 打印 3 */ 4 const printPage = () => { 5 let printHTML = document.getElementById("excess-print").innerHTML; 6 PrintCustomizeHtml(printHTML); 7 };
这样我们就可以进行定制化打印了!!!