The principle is to call the window.print() method, but this method can only print all the current page, so the following solution is to solve local printing.
1: Use iframe to inject the elements and styles that need to be printed and then call the print // Sample code function print () { let ifElement = document.getElementById('ifId') const addHtmlPrint = () => { const content = ifElement.contentWindow || ifElement.contentDocument content.document.body.innerHTML = this.detailTable const styleEle = document.createElement('style') /* Remove the header and footer when printing*/ styleEle.innerHTML = '@media print {@page { margin: 5mm; }}' content.document.getElementsByTagName('head')[0].appendChild(styleEle) /* Ensure that the resource loading in the iframe is completed, the image should be introduced in img form */ ifElement.onload = () => { content.print() } } this.getDetailTable() if (ifElement) { // If created, print it directly addHtmlPrint() } else { ifElement = document.createElement('iframe') ifElement.setAttribute('id', 'ifId') ifElement.setAttribute('style', 'display:none') document.body.appendChild(ifElement) addHtmlPrint() }} 2: Use @media print to set the print operation on the current page. @media print{ /* Here, the elements that do not need to be printed are set to not display */ .hidden-element{ display:none; /* visibility:hidden; */ } /* Paper is set to width 1200px and height 800px*/ @page{ size:1200px 800px; }}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.