[Fixed] window:afterprint not working after window.print() in Angular


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;

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) {

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


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.

print(): void {
    const printContents = document.getElementById('print-section').innerHTML;
    const popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
                <title>Print Page</title>
                style="font-size: 14px;
                    font-family: 'Source Sans Pro', 'Helvetica Neue',
                    Helvetica, Arial, sans-serif;
                    color: #333";

Leave a Reply

(*) Required, Your email will not be published