2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Angular] PDF.JSを利用してPDFを表示する単純なサンプルプログラム

Last updated at Posted at 2021-05-08

2021-6-27追記 ちょっとずつ更新してます。 https://github.com/sengokyu/ex.angular-pdfjs

これはなに?

Angularコンポーネント内にPDFファイルの1ページ目を表示するサンプルです。PDF.JSを利用しています。

環境

  • Angular 12.0.0 RC2
  • pdfjs-dist 2.7.570

PDF.JSが .? を使っているので、読み込むためにAngular 12にしています。

インストール

npm i pdfjs-dist --save-dev

angular.jsonを編集

pdf.jsファイルを別途読み込むために、angular.jsonを編集します。

"scripts": [
   "node_modules/pdfjs-dist/build/pdf.js",
   "node_modules/pdfjs-dist/build/pdf.worker.js"
],

プログラム

表示処理部分

PDFを表示する処理は、Angularとは関係ないです。PDF.JSのサンプルからもらってきました。

  async showPdfPage(
    canvas: HTMLCanvasElement,
    url: string,
    scale: number,
    pageNumber: number
  ): Promise<void> {
    const pdf = await getDocument(url).promise;
    const page = await pdf.getPage(pageNumber);
    const viewport = page.getViewport({ scale });
    const canvasContext = canvas.getContext('2d');

    canvas.height = viewport.height;
    canvas.width = viewport.width;

    await page.render({ canvasContext, viewport }).promise;
  }

コンポーネントテンプレート

テンプレートはcanvas要素を置くだけです。参照するためにIDをつけています。

<canvas #pdfCanvas></canvas>

コンポーネント

テンプレートに置いたcanvas@ViewChildで参照しています。

export class AppComponent implements AfterViewInit {
  @ViewChild('pdfCanvas')
  pdfCanvas: { nativeElement: HTMLCanvasElement };
}

ここでは、AfterViewInitのなかで、先に書いた表示処理を呼びました。

  async ngAfterViewInit(): Promise<void> {
    showPdfPage(this.pdfCanvas.nativeElement, PDF_FILE_NAME, 1, 1);
  }

できあがり

こんなんできました。
このファイル https://raw.githubusercontent.com/sengokyu/ex.angular-pdfjs/main/src/assets/RoShinoStdAdobeFonts.pdf を表示しています。

image.png

プログラム全体はGitHubに置いています。
https://github.com/sengokyu/ex.angular-pdfjs

Known Issue

ブラウザコンソールにこんなWarningが出ています。どうしたものか?

Warning: Error during font loading: The CMap "baseUrl" parameter must be specified, ensure that the "cMapUrl" and "cMapPacked" API parameters are provided. pdf.js:1211

リンク

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?