Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give pdf.js worker in Angular CLI application

Tags:

angular

pdf.js

I used pdf.js directly in angular app for some pdf purposes. It works fine.

I imported the pdfjs from the pdfjs-dist and my package.json includes pdfjs-dist.

My pdf is working fine, but in the console, I get the below error.

pdf.js:9067 GET http://localhost:4300/main.bundle.worker.js 404 (Not Found)

pdf.js:351 Warning: Setting up fake worker.

How to set up the worker properly in angular CLI application?

like image 818
Janier Avatar asked May 06 '26 11:05

Janier


2 Answers

I solved this by including the pdf.worker.js file in the bundle much the same way as assets are stored.

"assets": [
          "src/favicon.ico",
          "src/assets",
          {
            "glob": "pdf.worker.*",
            "input": "node_modules/pdfjs-dist/build/",
            "output": ""
          }              
        ],

Then you need to

import * as pdf from 'pdfjs-dist';
// ... //
pdf.GlobalWorkerOptions.workerSrc = 'pdf.worker.js';
const loadingTask = pdf.getDocument({ data: this.pdfData });
like image 67
Chris Lamothe Avatar answered May 10 '26 10:05

Chris Lamothe


I solved this issue with some days of fighting. First time I win with StackBlitz online Angular6 service. But had a problem with repeating at home.

In my case it is possible to use with Angular 6 and CLI with local file. PS: Care about similar versions of pdf.js and pdf.worker.js (I use pdf.worker.min.js) when you use local installed and worker with external link like CDN and etc.

Got version I need from CDN https://www.jsdelivr.com/package/npm/pdfjs-dist?path=build

Put your pdf.worker.js or pdf.worker.min.js to /src/assets/ And then use:

import * as pdfjsLib from 'pdfjs-dist/build/pdf
pdfjsLib.GlobalWorkerOptions.workerSrc = './assets/pdf.worker.min.js';

Specifications: got with command 'ng version'

Angular CLI: 6.0.3
Node: 8.10.0
OS: linux x64
Angular: 6.0.2

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.6.3
@angular-devkit/build-angular     0.6.3
@angular-devkit/build-optimizer   0.6.3
@angular-devkit/core              0.6.3
@angular-devkit/schematics        0.6.3
@angular/cli                      6.0.3
@ngtools/webpack                  6.0.3
@schematics/angular               0.6.3
@schematics/update                0.6.3
rxjs                              6.1.0
typescript                        2.7.2
webpack                           4.8.3
like image 43
Alexey Ryzhkov Avatar answered May 10 '26 10:05

Alexey Ryzhkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!