stephanrauh / ngx-extended-pdf-viewer

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

window.print is overwritten but not restored #2611

Open JohannesSchacht opened 3 days ago

JohannesSchacht commented 3 days 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 3 days 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 3 days 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 3 days ago

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

JohannesSchacht commented 3 days 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 3 days 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.