如何在react和typescript中使用pdfjsworker?

问题描述 投票:0回答:1

我正在尝试在react+ts项目中使用pdfjs。

import React from "react";
import * as pdfjs from "pdfjs-dist"

export default function EditPdf() {
  React.useEffect(()=>{    
    const doc = pdfjs.getDocument("helloworld.pdf");
    doc.promise.then((pdf)=>{
      console.log(pdf)
    })
  },[])  
  return (
        <div>
            content
        </div>
    )
  }

我在这里导入它,但出现错误:

Error: No "GlobalWorkerOptions.workerSrc" specified.
    at get workerSrc (http://localhost:5173/node_modules/.vite/deps/pdfjs-dist.js?v=aab08523:12098:11)
    at _PDFWorker._initialize (http://localhost:5173/node_modules/.vite/deps/pdfjs-dist.js?v=aab08523:11983:7)
    at new _PDFWorker (http://localhost:5173/node_modules/.vite/deps/pdfjs-dist.js?v=aab08523:11956:10)
    at getDocument (http://localhost:5173/node_modules/.vite/deps/pdfjs-dist.js?v=aab08523:11120:69)
    at http://localhost:5173/src/EditPdf.tsx?t=1727811223984:24:17
    at commitHookEffectListMount (http://localhost:5173/node_modules/.vite/deps/chunk-W6L2VRDA.js?v=2bfcffa6:16915:34)
    at invokePassiveEffectMountInDEV (http://localhost:5173/node_modules/.vite/deps/chunk-W6L2VRDA.js?v=2bfcffa6:18324:19)
    at invokeEffectsInDev (http://localhost:5173/node_modules/.vite/deps/chunk-W6L2VRDA.js?v=2bfcffa6:19701:19)
    at commitDoubleInvokeEffectsInDEV (http://localhost:5173/node_modules/.vite/deps/chunk-W6L2VRDA.js?v=2bfcffa6:19686:15)
    at flushPassiveEffectsImpl (http://localhost:5173/node_modules/.vite/deps/chunk-W6L2VRDA.js?v=2bfcffa6:19503:13)

在网上,这似乎足够“简单”......我可以做类似的事情:

import pdfjsWorker from "pdfjs-dist/build/pdf.worker.entry";

// ...
pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker

但是

pdf.worker.entry
不存在。我在 node_modules 文件夹中搜索,找到了一个类似名称的
pdf.worker.mjs
文件。我尝试使用
import pfdjsWorker from "pdfjs-dist/build/pdf.worker.entry"
导入,但找不到此声明。最后我注意到存在一个
pdfjs.PDFWorker
类型声明,但我不确定如何使用它(没有文档)。

如何在 React+TS 项目中成功导入并使用 pdfjs + Worker?

reactjs typescript pdf.js pdfjs-dist
1个回答
0
投票

您可以尝试通过

workerSrc
授予
//mozilla.github.io/pdf.js/build/pdf.worker.mjs
。请参考此文档:https://mozilla.github.io/pdf.js/examples/

© www.soinside.com 2019 - 2024. All rights reserved.