3
1

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.

TypeScriptでPDF.jsを使う際「The browser/environment lacks native support for critical functionality used by the PDF.js library (e.g. `ReadableStream`); please use a `legacy`-build instead.'」が出た場合の対処法

Posted at

#概要

TypeScriptでPDF.jsを使う際にコンパイルは通るが、実行時に致命的な機能がないと言われた時の対処方法です。
調べてもドキュメントが少なかったので、ここに残します。

#環境
Node.js:v14.17.0
@types/pdfjs-dist:2.7.3
pdfjs-dist:2.8.335

#発生事象

処理実行中下記メッセージが出力されてエラーとなる。

「The browser/environment lacks native support for critical functionality used by the PDF.js library (e.g. ReadableStream); please use a legacy-build instead.'」

エラーとなったコード

test.ts
import { getDocument } from 'pdfjs-dist';

export class TestClass {
  async getNumPages(file: Express.Multer.File) {

    const pdf = getDocument({
      data: file.buffer
    }).promise;
  
    const page = (await pdf).numPages;

    return page;
  }
}

#対処方法

エラーの指示通り、レガシーなモジュール(pdfjs-dist/legacy/build/pdf)を使い、解決しました。

修正済のコード

test.ts
import { getDocument } from 'pdfjs-dist/legacy/build/pdf';

export class TestClass {
  async getNumPages(file: Express.Multer.File) {

    const pdf = getDocument({
      data: file.buffer
    }).promise;
  
    const page = (await pdf).numPages;

    return page;
  }
}
3
1
1

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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?