Search code examples
javascripthtmlangularpdfjs-dist

Unable to load pdfjs-dist library in Angular but same thing working in JS


I'm using pdfjs-dist library to simply show pdf on canvas.

Firstly I've tried it in JS, which is working perfectly fine using Open Live Server.

I have downloaded pdfjs-dist using command npm install pdfjs-dist. Then:

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Render PDF</title>
    <!-- <link rel="stylesheet" href="./app.css"> -->
</head>
<body>
    <h2>Render PDF Example</h2>
    <button id="render-pdf-button">Render PDF</button>
    <div id="pdf-container"></div>
    <script type="module" src="./app.js"></script>
</body>
</html>

myapp.js:

import * as pdfjsLib from '/node_modules/pdfjs-dist/build/pdf.min.mjs';
pdfjsLib.GlobalWorkerOptions.workerSrc = '/node_modules/pdfjs-dist/build/pdf.worker.min.mjs';
var PDFAnnotate = function(container_id, url) {
    var inst = this;
    this.container_id = container_id;
    this.url = url;
    this.renderPDF = function() {
        var container = document.getElementById(inst.container_id);
        container.innerHTML = '';
        var loadingTask = pdfjsLib.getDocument(inst.url);
        loadingTask.promise.then(function(pdf) {
            inst.number_of_pages = pdf.numPages;
            for (var i = 1; i <= pdf.numPages; i++) {
                (function(pageNum) {
                    pdf.getPage(pageNum).then(function(page) {
                        var scale = 1.5;
                        var viewport = page.getViewport({ scale: scale });
                        var canvas = document.createElement('canvas');
                        var context = canvas.getContext('2d');
                        canvas.height = viewport.height;
                        canvas.width = viewport.width;
                        container.appendChild(canvas);
                        var renderContext = {
                            canvasContext: context,
                            viewport: viewport
                        };
                        page.render(renderContext);
                    });
                })(i);
            }
        }, function(reason) {
            console.error(reason);
        });
    };
    this.initRenderButton = function(button_id) {
        var button = document.getElementById(button_id);
        if (button) {
            button.addEventListener('click', function() {
                inst.renderPDF();
            });
        } else {
            console.error('Button element not found.');
        }
    };
};
var pdfAnnotate = new PDFAnnotate('pdf-container', './output.pdf');
pdfAnnotate.initRenderButton('render-pdf-button');

Above code in JS is working fine. Then I tried to use above code and run it in angular.

"pdfjs-dist": "^4.4.168",
Angular CLI: 16.0.6
Node: 18.19.0
Package Manager: npm 10.2.3

Firstly I've created folder pdf-renderer in src/assests/ and pasted myapp.js file here. Then copied its relative path and added in angular.json under scripts tag.

Then I've created component using ng create component pdf-rendering. Then:

pdf-rendering.component.html:

<h2>Render PDF Example</h2>
<button id="render-pdf-button">Render PDF</button>
<div id="pdf-container"></div>

pdf-rendering.component.ts:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-pdf-rendering',
  templateUrl: './pdf-rendering.component.html',
  styleUrls: ['./pdf-rendering.component.css']
})
export class PdfRenderingComponent implements OnInit {

  ngOnInit() {
    this.loadScript('assets/pdf-renderer/app.js');
  }
  loadScript(src: string) {
    const script = document.createElement('script');
    script.src = src;
    script.type = 'module';
    document.body.appendChild(script);
  }

}

After all that I've simply added that component in app.component.html. Now when I do ng serve, it builds fine and application gets live.

But it is not showing pdf, it is giving an error:

GET http://localhost:4200/node_modules/pdfjs-dist/build/pdf.min.mjs net::ERR_ABORTED 404 (Not Found)Understand this error

Even same /node_modules/pdfjs-dist/build/pdf.min.mjs is accessible while I run it via simple js and html (open live server) but it is giving error in angular. Guide me how can I resolve this error?


Solution

  • You need to enable it as a static file in Angular via angular.json (the server you mention probably serves complete root directory, which is why it's enabled, while ng doesn't)

    Try adding pdfjs-dist folder from node_modules to assets as is:

                  {
                    "glob": "**/*",
                    "input": "./node_modules/pdfjs-dist/",
                    "output": "/node_modules/pdfjs-dist/"
                  }
    

    path:

    {
      "projects": {
        "my-app": {
          "architect": {
            "build": {
              "builder": "@angular-devkit/build-angular:application",
              "options": {
                "assets": [
    
                  {
                    "glob": "**/*",
                    "input": "./node_modules/pdfjs-dist/",
                    "output": "/node_modules/pdfjs-dist/"
                  }
                ]
              }
            }
          }
        }
      }
    }
    

    see: Assets configuration

    FWIW, a better approach would be to use modules, and rewrite myapp.js code as an Angular component/service:

    import * as pdfjsLib from "pdfjs-dist";
    
    @Component({
      selector: 'app-pdf-rendering',
    })
    export class PdfRenderingComponent implements OnInit {
    
      ngOnInit() {
        // pdfjsLib stuff
      }
      
    }