【问题标题】:Angular 7 PDFJS ComponentAngular 7 PDFJS 组件
【发布时间】:2020-10-27 20:18:12
【问题描述】:

我正在尝试将 PDFJS 封装在 Angular 7 组件中。我有以下代码,但 PDFJS 未定义。我正在使用 Angular/CLI 构建应用程序。

import { Component, OnInit, ElementRef, ViewChild, Input } from '@angular/core';
declare let PDFJS: any;

@Component({
  selector: 'app-dsgpdf',
  templateUrl: './dsgpdf.component.html',
  styleUrls: ['./dsgpdf.component.scss']
})
export class DsgpdfComponent implements OnInit {
    @ViewChild('theCanvas', { read: ElementRef }) theCanvas;


    constructor() {


    }

    ngOnInit() {
        debugger;
        //
        // If absolute URL from the remote server is provided, configure the CORS
        // header on that server.
        //
        var url = '/assets/fdcc0545-a0d7-4c30-89ef-5a908a1e2a47.pdf';
        //
        // The workerSrc property shall be specified.
        //

        let pdfWorkerSrc: string = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.0.943/pdf.worker.min.js';



        PDFJS.GlobalWorkerOptions.workerSrc = pdfWorkerSrc;
        //
        // Asynchronous download PDF
        //
        var loadingTask = PDFJS.getDocument(url);
        loadingTask.then(pdf => {
            //
            // Fetch the first page
            //
            pdf.getPage(2).then(page => {
                var scale = 1.5;
                var viewport = page.getViewport(scale);
                //
                // Prepare canvas using PDF page dimensions
                //
                var canvas = this.theCanvas.nativeElement;
                var context = canvas.getContext('2d');
                canvas.height = viewport.height;
                canvas.width = viewport.width;
                //
                // Render PDF page into canvas context
                //
                var renderContext = {
                    canvasContext: context,
                    viewport: viewport,
                };
                page.render(renderContext).then(() => {
                    debugger;
                });
            });
        });
  }

}

我也试过添加这行代码:

let PDFJS: any = require('pdfjs-dist/build/pdf');

但是,编译失败:

 error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node`.

我显然错误地导入了这个。有人可以指出我正确的方向。

第二个问题:我不想从 cdn 加载工作程序。使用 Angular/CLI 时,正确的做法是什么?

【问题讨论】:

    标签: angular pdf.js


    【解决方案1】:

    PDFJS 没有目标角度组件。配置需要额外的步骤,而且不是很直接。如果你愿意带一个额外的 angular npm 包,这里有几个开源社区创建的包作为替代品。

    以下包将帮助您将 pdfjs 集成到您的 Angular 7 中。它确实提供了基本功能,但不提供查看器。高度可配置:ng2-pdf-viewer

     import { Component } from '@angular/core';
     @Component({
      selector: 'example-app',
      template: `
      <div>
          <label>PDF src</label>
          <input type="text" placeholder="PDF src" [(ngModel)]="pdfSrc">
      </div>
      <pdf-viewer [src]="pdfSrc" 
                  [render-text]="true"
                  style="display: block;"
      ></pdf-viewer>
      `
    })
    export class AppComponent {
      pdfSrc: string = '/pdf-test.pdf';
    }
    

    另外,还有另一个包 - ng2-pdfjs-viewer 也提供了一个查看器 - 完全公开,它是由我创建的。

    用法是这样的。

    <!-- your.component.html -->
    <button (click)="openPdf();">Open Pdf</button>
    
    <ng2-pdfjs-viewer #pdfViewer style="width: 800px; height: 400px"
      [pdfJsFolder]="'pdfjs'"
      [externalWindow]="true"
      [downloadFileName]="'mytestfile.pdf'"
      [download]="false">
    </ng2-pdfjs-viewer>
    
    <!-- your.component.ts-->
    export class RateCardComponent implements OnInit {
      @ViewChild('pdfViewer') pdfViewer;
      ...
    
      private downloadFile(url: string): any {
        return this.http.get(url, { responseType: ResponseContentType.Blob }).map(
          (res) => {
            return new Blob([res.blob()], { type: "application/pdf" });
          });
      }
    
      public openPdf() {
        let url = "url to fetch pdf as byte array";
        // url can be local url or remote http request to an api/pdf file. 
        // E.g: let url = "assets/pdf-sample.pdf";
        // E.g: https://github.com/intbot/ng2-pdfjs-viewer/tree/master/sampledoc/pdf-sample.pdf
        // E.g: http://localhost:3000/api/GetMyPdf
        // Please note, for remote urls to work, CORS should be enabled at the server. Read: https://enable-cors.org/server.html
    
        this.downloadFile(url).subscribe(
          (res) => {
            this.pdfViewer.pdfSrc = res; // pdfSrc can be Blob or Uint8Array
          }
        );
      }
    

    【讨论】:

    • 仅供到达此处的任何人使用,ng2-pdf-viewer 不适用于 Angular SSR
    • 感谢您创建库ng2-pdfjs-viewer。图书馆我面临的问题很少,你能看看我faizaldong打开的最新问题吗?谢谢!
    【解决方案2】:

    为了在您的 Angular 项目中包含 pdfjs,在使用类似 npm i pdfjs-dist 的方式安装软件包后,您需要修改您的 angular.json 文件,将所有文件路径放在 scripts 部分。

    为了避免角度抱怨找不到 PDFjs(如果这是对象名称),您需要在要使用它的组件中添加类似 declare var PDFjs 的内容

    【讨论】:

    • 好的,我将 pdf.min.js 添加到脚本部分的 angular.json 中,如原始问题的编辑中所述。我还添加了 declare var PDFJS;它可以编译,但 PDFJS 仍未定义。
    • @Darthg8r 我安装了 pdfjs-dist,然后我 declared var pdfjsLib 在我的应用程序组件文件中,它在类之外,然后我可以 console.log(pdfjsLib) 看到一个对象,你可能想要检查他们的文档以查找您要使用的对象的名称
    • @lucas 2021 年 3 月,您的方法不起作用
    【解决方案3】:

    我认为您必须下载 pdf.js 脚本并将其添加到资产文件夹中的某个位置。然后,在 Angular.json 的脚本数组中执行以下操作: "scripts": ["src/assets/js/pdf.js"]

    【讨论】:

      猜你喜欢
      • 2019-10-16
      • 1970-01-01
      • 2019-07-11
      • 1970-01-01
      • 1970-01-01
      • 2019-09-21
      • 2019-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多