在纯JavaScript中,您可以通过获取元素ID,将其放在新窗口中并使用window.print()来打印元素。
什么是“Angular 2”做这样的事情?我已经获得了我希望打印的组件的ViewChild,但我不确定如何访问它的html并随后打印它,或者如果这甚至是我应该做的。
答案 0 :(得分:0)
如果您需要打印一些自定义HTML,则此方法不需要新窗口。
ts:
let control_Print;
control_Print = document.getElementById('__printingFrame');
let doc = control_Print.contentWindow.document;
doc.open();
doc.write("<div style='color:red;'>I WANT TO PRINT THIS, NOT THE CURRENT HTML</div>");
doc.close();
control_Print = control_Print.contentWindow;
control_Print.focus();
control_Print.print();
html:
<iframe title="Lets print" id="__printingFrame" style="width: 0; height: 0; border: 0"></iframe>
答案 1 :(得分:-4)
HTML
<div id="printSection"></div>
<button (click)="print()">PRINT</button>
TS
print(): void {
let printContents, popupWin;
printContents = document.getElementById('printSection').innerHTML;
popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
popupWin.document.open();
popupWin.document.write(`
<html>
<head>
<title>Print tab</title>
<style>
//........Customized style.......
</style>
</head>
<body onload="window.print();window.close()">${printContents}
</body>
</html>`
);
popupWin.document.close();
}