html:
<div id="printdiv">
<!-- 内容 -->
</div>
<iframe src="window.location.href" id="printIframe"></iframe>
JS/TS
function PrintHtml() {
var content = document.getElementById("yourId").innerHTML; // 替换"yourId"为你要打印的元素的id
var printIframe = document.getElementById('yourIframe') as HTMLIFrameElement; // 替换"yourIframe"为你定义的iframe
const printIframeWindow = printIframe.contentWindow
printIframeWindow.document.title = 'test print'
printIframeWindow.document.body.innerHTML = content;
var iframeStyle = printIframeWindow.document.createElement('style');
iframeStyle.innerHTML = "body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, form, fieldset, input, textarea, p, th, td {\
margin: 0;\
padding: 0;\
font-size: 12px;\
outline: none;\
}\
";
printIframeWindow.document.head.appendChild(iframeStyle);
printIframeWindow.addEventListener('beforeprint', () => {
console.log("print begin")
})
printIframeWindow.addEventListener('afterprint', () => {
console.log("print end")
})
setTimeout(() => {
printIframeWindow.focus()
printIframeWindow.print()
})
const removeOldIframe = () => {
const oldPrintIframe = document.getElementById('yourIframe')
oldPrintIframe && oldPrintIframe.remove && oldPrintIframe.remove()
}
}