在 angular 11 中使用 pdfjs 创建 pdf 缩略图

create pdf thumbnail with pdfjs in angular 11

我想将 pdf 文件的第一页显示为图像。 据我所知,我无法使用打字稿库“ng2-pdf-viewer”来做到这一点,因此需要使用 javascript 库“pdfjs-dist”。 我发现 this post 描述了如何使用 pdfjs 创建缩略图。

在“ng serve”上,我收到以下错误消息:

Error: ./node_modules/pdfjs-dist/build/pdf.js 2205:45
Module parse failed: Unexpected token (2205:45)
File was processed with these loaders:
 * ./node_modules/@angular-devkit/build-angular/src/babel/webpack-loader.js
 * ./node_modules/@ngtools/webpack/src/ivy/index.js
You may need an additional loader to handle the result of these loaders.
|         intent: renderingIntent,
|         renderInteractiveForms: renderInteractiveForms === true,
>         annotationStorage: annotationStorage?.serializable || null
|       });
|     }

我发现 描述了如何通过更改 angular 生成器来解决此问题。 然后我收到以下错误:

TypeError: Cannot read property 'flags' of undefined

我只能在 angular 9.

中找到提到这个错误

因此我的问题:

我正在使用以下依赖项:

  "dependencies": {
    "@angular/animations": "~11.2.13",
    "@angular/common": "~11.2.13",
    "@angular/compiler": "~11.2.13",
    "@angular/core": "~11.2.13",
    "@angular/forms": "~11.2.13",
    "@angular/platform-browser": "~11.2.13",
    "@angular/platform-browser-dynamic": "~11.2.13",
    "@angular/router": "~11.2.13",
    "@types/pdfjs-dist": "^2.7.4",
    "pdfjs-dist": "^2.8.335",
    "rxjs": "~6.6.0",
    "tslib": "^2.0.0",
    "zone.js": "~0.11.3"
  },

将 angular 更新到版本 12.2.4 后,我自己解决了这个问题:

import { Injectable } from '@angular/core';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { from, Observable } from 'rxjs';
import { map, switchMap, take } from 'rxjs/operators';
import { getDocument, GlobalWorkerOptions, version } from 'pdfjs-dist';

@Injectable({
  providedIn: 'root'
})
export class DocumentService {
  constructor(private sanitizer: DomSanitizer) {
    GlobalWorkerOptions.workerSrc = `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${version}/pdf.worker.min.js`;
  }

  public getPdfThumbnail(pdfUrl: string) {
    return from(getDocument(pdfUrl).promise)
    .pipe(
      take(1),
      switchMap(pdf => from(pdf.getPage(1))),
      switchMap(page => {
        const canvas = document.createElement('canvas');
        const viewport = page.getViewport({ scale: 2 });
        canvas.height = viewport.height;
        canvas.width = viewport.width;

        return from(page.render({
          canvasContext: canvas.getContext('2d') as CanvasRenderingContext2D,
          viewport
        }).promise)
        .pipe(
          map(() => canvas)
        );
      }),
      switchMap(canvas => {
        return new Observable<SafeUrl>(observer => {
          canvas.toBlob(blob => {
            if (blob) {
              observer.next(this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(blob)));
              observer.complete();
            }
          }, 'image/jpeg', 0.75);
        });
      })
    );
  }
}