stephanrauh / ngx-extended-pdf-viewer

A full-blown PDF viewer for Angular 16, 17, and beyond
https://pdfviewer.net
Apache License 2.0
490 stars 184 forks source link

window.print is overwritten but not restored #2611

Closed JohannesSchacht closed 1 month ago

JohannesSchacht commented 1 month ago

I am using Angular and have the viewer embedded in a modal dialog. When the dialog is finished, window.print still points to a function in the viewer and calling window.print() crashes. I have fixed the issue by saving window.print and restoring in my code but that - i guess - is not the intended way.

stephanrauh commented 1 month ago

Can you debug PDFScriptLoaderService.ngOnDestroy(), please? This method contains code that restores the original window.print. I'd like to know why it doesn't work in your project.

Here's the code that should restore window.print:

  public ngOnDestroy() {
    this.shuttingDown = true;
    if (typeof window === 'undefined') {
      return; // fast escape for server side rendering
    }
    delete globalThis['setNgxExtendedPdfViewerSource'];

    const PDFViewerApplication: IPDFViewerApplication = this.PDFViewerApplication;
    PDFViewerApplication?.pdfViewer?.destroyBookMode();
    PDFViewerApplication?.pdfViewer?.stopRendering();
    PDFViewerApplication?.pdfThumbnailViewer?.stopRendering();

    const originalPrint = this.originalPrint;
    if (window && originalPrint && !originalPrint.toString().includes('printPdf')) {
      window.print = originalPrint;
    }
JohannesSchacht commented 1 month ago

This is the onDestroy-method that I see:

  ngOnDestroy() {
    const styles = this.document.getElementById('pdf-dynamic-css');
    if (styles?.parentElement) {
      styles.parentElement.removeChild(styles);
    }
  }
stephanrauh commented 1 month ago

That's the destroy method of DynamicCssComponent. I was referring to the class PDFScriptLoaderService.

JohannesSchacht commented 1 month ago

Sorry, I am not that fluent debugging the code. But from what I can tell, the method is never called, neither is the constructor not being called. The breakpoint in the DynamicCssComponent onDestroy is hit though.

stephanrauh commented 1 month ago

Oh, wait, that's true. The destructor of a service is only called in very specific (or exotic) cases. That's strange, because I faintly remember debugging it. Be that as it may, restoring window.print should happen in the component, not in the service.

stephanrauh commented 1 month ago

Version 22.0.0-alpha.1 fixes your bug.

Enjoy! Stephan