angulartypescriptpdfangular18ng2-pdf-viewer

ng2-pdf-viewer with Angular 18


I've tried to display a PDF in my angular 18 app, but I get a weird behavior. I've used https://www.npmjs.com/package/ng2-pdf-viewer and called the module in my standalone component.

My ts file

import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { PdfViewerModule } from 'ng2-pdf-viewer';



@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet,PdfViewerModule ],
  templateUrl: './app.component.html',
  styleUrl: './app.component.scss'
})
export class AppComponent {
  title = 'viewer';
}

My html

<pdf-viewer
      [src]="'https://vadimdez.github.io/ng2-pdf-viewer/assets/pdf-test.pdf'"
      [rotation]="0"
      [original-size]="false"
      [show-all]="true"
      [fit-to-page]="false"
      [zoom]="1"
      [zoom-scale]="'page-width'"
      [stick-to-page]="false"
      [render-text]="true"
      [external-link-target]="'blank'"
      [autoresize]="true"
      [show-borders]="false"
      style="width: 100%; height: 100vh;"
    ></pdf-viewer> 

The error

document is not defined at eval (C:\Users\anass.sbai\Desktop\viewe\viewer\node_modules\pdfjs-dist\web\pdf_viewer.mjs:431:18) at async instantiateModule (file:///C:/Users/anass.sbai/Desktop/viewe/viewer/node_modules/vite/dist/node/chun


Solution

  • You are having server side rendering enabled in your application, this project uses window object which only exists in browser, when you render on the server, window will be undefined.

    Wrap the PDF, inside a defer block inside its own component, this component will render only when on the browser, so when you use this component, make sure you wrap the component inside the defer block.

    import { Component } from '@angular/core';
    import { RouterOutlet } from '@angular/router';
    import { PdfViewerModule } from 'ng2-pdf-viewer';
    
    @Component({
      selector: 'app-pdf-viewer',
      standalone: true,
      imports: [RouterOutlet,PdfViewerModule ],
      template: `
        <pdf-viewer
          [src]="'https://vadimdez.github.io/ng2-pdf-viewer/assets/pdf-test.pdf'"
          [rotation]="0"
          [original-size]="false"
          [show-all]="true"
          [fit-to-page]="false"
          [zoom]="1"
          [zoom-scale]="'page-width'"
          [stick-to-page]="false"
          [render-text]="true"
          [external-link-target]="'blank'"
          [autoresize]="true"
          [show-borders]="false"
          style="width: 100%; height: 100vh;"
        ></pdf-viewer> 
      `,
      styleUrl: './app.component.scss'
    })
    export class PdfViewerComponent {
      title = 'viewer';
    }
    

    Then when you use this component, make sure you wrap it inside the defer block.

    @defer() {
        <app-pdf-viewer/>
    }