How to give pdf.js worker in Angular CLI application

Janier picture Janier · Apr 13, 2018 · Viewed 9.2k times · Source

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?

Answer

Alexey Ryzhkov picture Alexey Ryzhkov · Jun 9, 2018

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