Issue
I am opening window.print() on a button
<button class="btn btn-primary" type="button" (click)="printDocument()"> Print </button>
on that printDocument method, I opened the doc in a new window and called window.print().
printDocument() {
let str = `<embed src="https://beta.lottoweaver.com/WeaverDoc/commonContent/www.nationallottery.co.za/playerDocument/408466_ID_PROOF_null_1614276509176.jpg" width='100%' height="100%">`;
this.OpenWindow = window.open("","","width=900, height=600, left=200, top=100");
this.OpenWindow.document.body.innerHTML = str;
this.OpenWindow.print();
}
Now, after the user cancels or print the document, I want to close the window so I tried it with @HostListener
@HostListener("window:afterprint", ["$event"])
onafterPrint(event) {
this.OpenWindow.close();
}
But this event is never called when I cancel or save from the print window.
How should I close the window after print window is closed?
Here is a working stackblitz : https://stackblitz.com/edit/angular-ivy-tnxv4w
Solution
Try this way, by opening a print window:
<div [id]="'print-section'">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolor eius error expedita nam natus, nulla veritatis? Consequuntur corporis, delectus ducimus eaque eius, eos, magnam molestias omnis quaerat quidem rem soluta.
</div>
print(): void {
const printContents = document.getElementById('print-section').innerHTML;
const popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
popupWin.document.open();
popupWin.document.write(`
<html>
<head>
<title>Print Page</title>
</head>
<body
style="font-size: 14px;
font-family: 'Source Sans Pro', 'Helvetica Neue',
Helvetica, Arial, sans-serif;
color: #333";
onload="document.execCommand('print');window.close()">${printContents}</body>
</html>`
);
popupWin.document.close();
}