背景
我正在尝试将 PDF.JS 导入到 TypeScript 项目中。我正在为 pdfjs-dist
使用 DefinelyTypedbindings,通过
npm install @types/pdfjs-dist
和 npm install pdfjs-dist
安装。
问题
我似乎无法使用 TypeScript 来编译我的项目。我使用的是直接从 DefinetlyTyped 上的测试中复制的源代码。这是我试图编译的简化(仅删除)代码(来自DefiniteTyped的测试代码的精确副本也以同样的方式失败):
import { PDFJSStatic } from 'pdfjs-dist';
var PDFJS: PDFJSStatic;
PDFJS.getDocument('helloworld.pdf').then(console.log);
TypeScript 找到类型声明模块,并认为
PDFJSStatic
的导入是有效的。它不认为 PDFJS
已初始化,但如果我在 strict
中关闭 tsconfig
,代码会编译,但它会编译为:
"use strict";
exports.__esModule = true;
var PDFJS;
PDFJS.getDocument('helloworld.pdf').then(console.log);
这显然行不通。它不会将
import
语句编译成任何内容。
问题
如何将 PDF.JS 导入 TypeScript 项目并通过
@types/pdfjs-dist
中的声明文件将其编译为工作 Node.JS 代码?
我尝试过的
我尝试了
import
的不同变体,但无济于事。切换到 require
似乎也没有帮助。
我已经验证了
pdjs-dist
依赖项和 @types/pdfjs-dist
依赖项是否存在、已更新并且可以直接从 NodeJS(非 TypeScript 程序)使用。
我在 tsconfig 中尝试了
module
的各种值。他们有时会更改生成的代码,但没有人更改它以包含所需的导入。
我尝试在
/// <reference path="../node_modules/@types/pdfjs-dist/index.d.ts" />
行上方添加 import
。这并没有改变行为。
环境
tsc
版本 2.4.2、节点 8.5 和 npm
5.3。我的项目根目录中有以下 tsconfig.json
:
{
"compilerOptions": {
"allowJs":true,
"rootDir": ".",
"outDir": "dist",
"moduleResolution": "node"
},
"include": [
"src/**/*"
],
"exclude": [
"**/*.spec.ts",
"dist/**/*"
]
}
也许你可以使用
require
功能。
添加
@types/node
包,并在源代码顶部写入 require('pdfjs-dist')
。
因此,您可以像下面这样修改您的代码。
现在,这段代码就可以工作了。
import { PDFJSStatic } from 'pdfjs-dist';
const PDFJS: PDFJSStatic = require('pdfjs-dist');
PDFJS.getDocument('helloworld.pdf').then(console.log);
我认为
@types/pdfjs-dist
在实施中存在问题。
使用
@types/pdfjs-dist
2.1.0 和pdfjs-dist
“2.1.266”,根本问题似乎仍然没有完全解决,但我发现他们自己的测试的方法有效:
import { getDocument, PDFDocumentProxy, PDFPromise, Util } from 'pdfjs-dist';
(不过,这并不漂亮,因为它污染了你的命名空间。)
我也尝试过不同的方法。对我来说,最具可读性的是这个:
import * as pdfjslib from 'pdfjs-dist';
let PDFJS = pdfjslib.PDFJS;
PDFJS.disableTextLayer = true;
PDFJS.disableWorker = true;
这对我有用,无需使用
require
:
import * as pdfjslib from "pdfjs-dist";
const PDFJS = (<any>pdfjslib) as PDFJSStatic;
您只需将模块强制转换为
any
即可消除类型错误。
@types/pdfjs-dist 中的输入绝对不正确,但这应该是一个快速的解决方法。 :)
如果你碰巧使用 React,你可以使用
react-pdf
包,它在底层使用 pdfjs
。它还有自己的类型,因此您可以导入它而不需要require
。
以下作品。
import * as pdfjsLib from 'pdfjs-dist/webpack'
...
// in this example, data is a Uint8Array
const pdf = await pdfjsLib.getDocument({ data }).promise
for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
const page = await pdf.getPage(pageNum)
...
拥有一个文件“pdfjs-dist.d.ts”也没什么坏处:
declare module 'pdfjs-dist/webpack'
给它一个橡皮筋解决方案。厌倦了错误分布在多个组件中,并将 pdfjslib 移至单个组件。现在我的其他组件引用这个组件没有错误,并且只有该组件在导入时显示错误。
export { PDFDocumentLoadingTask, PDFDocumentProxy,
PDFPageProxy, getDocument } from 'pdfjs-dist';
import * as pdfjsLib from 'pdfjs-dist';
(pdfjsLib as any).GlobalWorkerOptions.workerSrc =
`//cdnjs.cloudflare.com/ajax/libs/pdf.js/3.8.162/pdf.worker.js`;
export { pdfjsLib };