我正在尝试从 pdf 文件中提取数据并将其返回。这是 astro 中服务器端的代码
import * as pdfjsLib from "pdfjs-dist";
pdfjsLib.GlobalWorkerOptions.workerSrc = "../../node_modules/pdfjs-dist/build/pdf.worker.mjs";
export const contentExtractor = async (arrayBufferPDF: ArrayBuffer): Promise<string> => {
const pdf = (pdfjsLib).getDocument(arrayBufferPDF);
return pdf.promise.then(async (pdf) => {
let totalContent = ""
const maxPages = pdf._pdfInfo.numPages;
for (let pageNumber = 1; pageNumber <= maxPages; pageNumber++) {
const page = await pdf.getPage(pageNumber);
const pageContent = await page.getTextContent();
const content = pageContent.items.map((s: any) => s.str).join(" ")
totalContent = totalContent + content
}
return totalContent
})
}
错误是
12:44:40 [ERROR] Promise.withResolvers is not a function
Stack trace:
at /Users/some-user/Documents/Projects/Github/pdf-extractor/app/node_modules/pdfjs-dist/build/pdf.mjs:3026:32
[...] See full stack trace in the browser, or rerun with --verbose.
我不明白问题出在哪里。有人可以帮我吗?
您使用的 PDF.js 版本不支持在 Node.js 中运行(即仅在浏览器中)。该错误来自于调用
Promise.withResolvers
,Node.js 不支持。
看起来,在 Node.js 下运行它的推荐方法是使用 legacy build(使用 pdfjs-dist/legacy/build/pdf.js
)。