使用pdfjs-dist提取PDF文本报错Promise.withResolvers is not a function
解决pdfjs-dist运行报错:Promise.withResolvers is not a function
问题详情
我编写了一个提取PDF文本的服务,使用pdfjs-dist@4.3.136,无论是导入主构建包还是官方建议的legacy版本,运行时都报错:
TypeError: Promise.withResolvers is not a function at new PDFDocumentLoadingTask (pdf.mjs:15693:31) at Module.getDocument (pdf.mjs:15511:1) at _callee$ (pdfJsService.js:23:23) at tryCatch (pdfJsService.js:2:1) at Generator.<anonymous> (pdfJsService.js:2:1) at Generator.next (pdfJsService.js:2:1) at asyncGeneratorStep (pdfJsService.js:2:1) at _next (pdfJsService.js:2:1) at pdfJsService.js:2:1 at initializePromise (es6-promise.js:437:1)
服务代码:
import * as pdfjsLib from "pdfjs-dist/legacy/build/pdf.mjs"; // Specify the path to the worker script pdfjsLib.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/4.3.136/pdf.worker.min.js`; // Function to decode base64 string to Uint8Array function base64ToUint8Array(base64) { const binaryString = atob(base64); const len = binaryString.length; const bytes = new Uint8Array(len); for (let i = 0; i < len; i++) { bytes[i] = binaryString.charCodeAt(i); } return bytes; } // Function to extract text from a base64 encoded PDF export async function extractPdfText(base64String) { // Convert base64 string to buffer const pdfArray = base64ToUint8Array(base64String); try { const pdf = await pdfjsLib.getDocument({ data: pdfArray }).promise; let extractedText = ""; for (let i = 1; i <= pdf.numPages; i++) { const page = await pdf.getPage(i); const textContent = await page.getTextContent(); const textItems = textContent.items.map((item) => item.str).join(" "); extractedText += textItems + "\n"; } console.log("extractedText ________+++++++++++++++++++++++++____________"); console.log(extractedText); return extractedText; } catch (error) { console.error("Error parsing PDF: ", error); } }
问题原因
Promise.withResolvers()是ES2024新增的Promise API,你的运行环境(Node.js版本过低、旧版浏览器)不支持该语法,导致pdfjs-lib v4.x版本的代码执行失败。
解决方案
1. 升级运行环境(推荐)
- Node.js:升级至v21.0.0及以上版本(默认支持
Promise.withResolvers);若使用v20.x版本,需升级到v20.6.0+并添加--experimental-promise-with-resolvers启动标志。 - 浏览器:升级到支持该API的版本,如Chrome 119+、Firefox 120+、Edge 119+等。
2. 降级pdfjs-dist到兼容版本
pdfjs-dist从v4.x开始使用Promise.withResolvers,降级到v3.x版本可避免该问题:
npm uninstall pdfjs-dist npm install pdfjs-dist@3.11.174
同时修改代码中的导入和worker路径:
import * as pdfjsLib from "pdfjs-dist/legacy/build/pdf.mjs"; pdfjsLib.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js`;
3. 添加Polyfill(适配无法升级环境的场景)
在导入pdfjs-lib前,手动添加Promise.withResolvers的兼容实现:
// 放在所有导入语句之前 if (!Promise.withResolvers) { Promise.withResolvers = function () { let resolve, reject; const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); return { promise, resolve, reject }; }; } // 之后再导入pdfjs-lib import * as pdfjsLib from "pdfjs-dist/legacy/build/pdf.mjs"; // ... 其余代码不变
内容的提问来源于stack exchange,提问作者Ryan Durrant
相关产品推荐
相关产品推荐

