ng2-pdf-viewer

repository·master·Indexed 23 days ago

https://github.com/vadimdez/ng2-pdf-viewer

An Angular 5+ component for rendering PDF files using pdf.js. It supports features such as text selection, zooming, rotation, and both single-page and all-page viewing modes. The library provides a <pdf-viewer> component with configurable inputs for source handling, zoom scaling, and text rendering modes, as well as events for loading progress and page rendering.

Tokens
3.6K
Snippets
15
Records
20
Agent score
79%

What's inside ng2-pdf-viewer

  1. Set a version-specific custom path to the PDF worker

    master

    In rare cases where multiple versions of pdf.worker are required on the same page, you can override the custom path for a specific version by appending the version number to the global variable name. This prevents conflicts with the global pdfWorkerSrc setting.

    (window as any)["pdfWorkerSrc2.14.305"] = '/pdf.worker.mjs';
  2. Install ng2-pdf-viewer

    master

    Install the package using npm based on your Angular version:

    • Angular >= 12: npm install ng2-pdf-viewer (includes Partial Ivy compiled bundles).
    • Angular >= 4: npm install ng2-pdf-viewer@^7.0.0.
    • Angular < 4: npm install ng2-pdf-viewer@~3.0.8.
    npm install ng2-pdf-viewer
  3. Set up ng2-pdf-viewer in an Angular application

    master

    To use the PDF viewer, first import PdfViewerModule into your Angular module (e.g., AppModule). Then, use the <pdf-viewer> component in your component's template.

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { AppComponent } from './app.component';
    import { PdfViewerModule } from 'ng2-pdf-viewer';
    
    @NgModule({
      imports: [BrowserModule, PdfViewerModule],
      declarations: [AppComponent],
      bootstrap: [AppComponent]
    })
    class AppModule {}
    
    platformBrowserDynamic().bootstrapModule(AppModule);
    import { Component } from '@angular/core';
    
    @Component({
      selector: 'example-app',
      template: `
      <pdf-viewer [src]="pdfSrc"
                  [render-text]="true"
                  [original-size]="false"
                  style="width: 400px; height: 500px"
      ></pdf-viewer>
      `
    })
    export class AppComponent {
      pdfSrc = "https://vadimdez.github.io/ng2-pdf-viewer/assets/pdf-test.pdf";
    }
  4. Set a custom path to the PDF worker

    master

    By default, the PDF worker is loaded from cdn.jsdelivr.net. To host the worker locally or use a specific path, set the pdfWorkerSrc property on the global window object.

    Important: This must be set before the pdf-viewer component is rendered in the DOM.

    (window as any).pdfWorkerSrc = '/pdf.worker.mjs';
  5. Configure the PDF.js worker source

    master

    The component requires a PDF.js worker to function. It attempts to resolve the worker source automatically using the version of pdfjs-dist currently in use.

    If you need to specify a custom worker source (e.g., from a local asset or a specific CDN), you can set the pdfWorkerSrc<version> property on the window object before the component initializes.

    Example for version 4.0.0:

    (window as any).pdfWorkerSrc4.0.0 = '/assets/pdf.worker.min.mjs';
  6. Render a local PDF file

    master

    To render a PDF file selected by a user from their local machine, use a FileReader to convert the file into an ArrayBuffer, which can then be assigned to the [src] property.

    Template:

    <input (change)="onFileSelected()" type="file" id="file">

    Component Logic:

    onFileSelected() {
      let $img: any = document.querySelector('#file');
    
      if (typeof (FileReader) !== 'undefined') {
        let reader = new FileReader();
    
        reader.onload = (e: any) => {
          this.pdfSrc = e.target.result;
        };
    
        reader.readAsArrayBuffer($img.files[0]);
      }
    }
  7. Configure the [page] property

    master

    The [page] property specifies the page number to display. It is required if [show-all] is set to false.

    • One-way binding: [page]="1"
    • Two-way binding: [(page)]="pageVariable" (requires the container to have a defined height, e.g., pdf-viewer { height: 100vh; } to ensure scrolling updates the variable).

    Note: [show-all] is optional if [page] is used.

    [page]="1"
  8. Search within a PDF using the eventBus

    master

    To implement search functionality, access the eventBus via a @ViewChild reference to the PdfViewerComponent. You can then use the .dispatch() method to send a 'find' event with a configuration object.

    Supported options in the dispatch object:

    • query: The string to search for.
    • type: Set to 'again' for subsequent searches.
    • caseSensitive: Boolean indicating if the search should respect case.
    • findPrevious: Boolean to find the previous occurrence.
    • highlightAll: Boolean to highlight all matches.
    • phraseSearch: Boolean to treat the query as a phrase.
    @ViewChild(PdfViewerComponent) private pdfComponent: PdfViewerComponent;
    
    search(stringToSearch: string) {
      this.pdfComponent.eventBus.dispatch('find', {
        query: stringToSearch, 
        type: 'again', 
        caseSensitive: false, 
        findPrevious: undefined, 
        highlightAll: true, 
        phraseSearch: true
      });
    }
  9. Configure text rendering and selection

    master

    Use these properties to enable text interaction within the PDF:

    • [render-text]: (boolean) Enables the text layer, allowing users to select text.
    • [render-text-mode]: (RenderTextMode) Controls the selection mode when [render-text] is true:
      • 0 (RenderTextMode.DISABLED): Disables the text selection layer.
      • 1 (RenderTextMode.ENABLED): Enables the text selection layer.
      • 2 (RenderTextMode.ENHANCED): Enables enhanced text selection.
    • [external-link-target]: (string) Defines the target for links within the text layer. Options: 'blank', 'none', 'self', 'parent', 'top'.
    [render-text]="true"
    [render-text-mode]="1"
    [external-link-target]="'blank'"
  10. Configure the [src] property

    master

    The [src] property is required and accepts a string, object, or UInt8Array. It defines the location of the PDF.

    Basic usage (URL): [src]="'https://example.com/test.pdf'"

    Advanced usage (Options object): You can pass an object to [src] for more control (similar to pdf.js). For example, to load a protected PDF with credentials:

    {
      url: 'https://vadimdez.github.io/ng2-pdf-viewer/assets/pdf-test.pdf',
      withCredentials: true
    }
    [src]="'https://vadimdez.github.io/ng2-pdf-viewer/assets/pdf-test.pdf'"
  11. Configure display and layout

    master

    Control the visual layout of the viewer:

    • [show-all]: (boolean) If true, shows all pages at once. If false, shows a single page.
    • [stick-to-page]: (boolean) Sticks the view to the page. Works with [show-all]="true" and [page].
    • [rotation]: (number) Rotates the PDF in 90-degree increments (e.g., 0, 90, 180).
    • [show-borders]: (boolean) Shows page borders.
    • [autoresize]: (boolean) Enables auto-resize. Requirement: [original-size] must be false and the pdf-viewer tag must have max-width or display set.
    [show-all]="true"
    [stick-to-page]="true"
    [rotation]="90"
    [show-borders]="true"
    [autoresize]="true"