From d188b66af633e620358faed1b61469a516845902 Mon Sep 17 00:00:00 2001 From: Jonas Jenwald Date: Mon, 24 Jul 2023 12:21:58 +0200 Subject: [PATCH] [api-minor] Attempt to prevent Node.js-specific polyfill errors from completely breaking the library The existing Node.js-specific polyfills depend on the `node-canvas` package, which has unfortunately (repeatedly) shown to cause trouble for many users. We attempted to improve the situation by listing the relevant packages as `optionalDependencies`, but that didn't seem to really fix the problem. With this patch the library should be able to load in Node.js-environments even if polyfilling fails, and any errors will instead occur during rendering. Obviously this is *not* a proper solution, since it basically moves the problem to another part of the code-base. However for certain "simpler" use-cases, such as e.g. text-extraction, these changes should hopefully improve general usability of the PDF.js library in Node.js-environments. *Please note:* For most PDF documents rendering should still work though, since `DOMMatrix` is *currently* only used with Patterns and `Path2D` only with Type3-fonts and Patterns. --- src/display/node_utils.js | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/display/node_utils.js b/src/display/node_utils.js index bd1756aea..3dd584212 100644 --- a/src/display/node_utils.js +++ b/src/display/node_utils.js @@ -20,7 +20,7 @@ import { BaseFilterFactory, BaseStandardFontDataFactory, } from "./base_factory.js"; -import { isNodeJS } from "../shared/util.js"; +import { isNodeJS, warn } from "../shared/util.js"; if (typeof PDFJSDev !== "undefined" && PDFJSDev.test("MOZCENTRAL")) { throw new Error( @@ -33,18 +33,26 @@ if (typeof PDFJSDev !== "undefined" && !PDFJSDev.test("SKIP_BABEL")) { if (globalThis.DOMMatrix || !isNodeJS) { return; } - globalThis.DOMMatrix = __non_webpack_require__("canvas").DOMMatrix; + try { + globalThis.DOMMatrix = __non_webpack_require__("canvas").DOMMatrix; + } catch (ex) { + warn(`Cannot polyfill \`DOMMatrix\`, rendering may be broken: "${ex}".`); + } })(); (function checkPath2D() { if (globalThis.Path2D || !isNodeJS) { return; } - const { CanvasRenderingContext2D } = __non_webpack_require__("canvas"); - const { polyfillPath2D } = __non_webpack_require__("path2d-polyfill"); + try { + const { CanvasRenderingContext2D } = __non_webpack_require__("canvas"); + const { polyfillPath2D } = __non_webpack_require__("path2d-polyfill"); - globalThis.CanvasRenderingContext2D = CanvasRenderingContext2D; - polyfillPath2D(globalThis); + globalThis.CanvasRenderingContext2D = CanvasRenderingContext2D; + polyfillPath2D(globalThis); + } catch (ex) { + warn(`Cannot polyfill \`Path2D\`, rendering may be broken: "${ex}".`); + } })(); }