/**
* @licstart The following is the entire license notice for the
- * Javascript code in this page
+ * JavaScript code in this page
*
- * Copyright 2021 Mozilla Foundation
+ * Copyright 2022 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*
* @licend The above is the entire license notice for the
- * Javascript code in this page
+ * JavaScript code in this page
*/
(function webpackUniversalModuleDefinition(root, factory) {
exports["pdfjs-dist/build/pdf"] = factory();
else
root["pdfjs-dist/build/pdf"] = root.pdfjsLib = factory();
-})(this, function() {
+})(this, () => {
return /******/ (() => { // webpackBootstrap
/******/ "use strict";
/******/ var __webpack_modules__ = ([
Object.defineProperty(exports, "__esModule", ({
value: true
}));
-exports.StatTimer = exports.RenderingCancelledException = exports.PixelsPerInch = exports.PageViewport = exports.PDFDateString = exports.LinkTarget = exports.DOMStandardFontDataFactory = exports.DOMSVGFactory = exports.DOMCanvasFactory = exports.DOMCMapReaderFactory = void 0;
-exports.addLinkAttributes = addLinkAttributes;
-exports.deprecated = deprecated;
-exports.getFilenameFromUrl = getFilenameFromUrl;
-exports.getPdfFilenameFromUrl = getPdfFilenameFromUrl;
-exports.getXfaPageViewport = getXfaPageViewport;
-exports.isDataScheme = isDataScheme;
-exports.isPdfFile = isPdfFile;
-exports.isValidFetchUrl = isValidFetchUrl;
-exports.loadScript = loadScript;
-
-var _util = __w_pdfjs_require__(2);
-
-var _base_factory = __w_pdfjs_require__(5);
-
-const DEFAULT_LINK_REL = "noopener noreferrer nofollow";
-const SVG_NS = "http://www.w3.org/2000/svg";
-const PixelsPerInch = {
- CSS: 96.0,
- PDF: 72.0,
-
- get PDF_TO_CSS_UNITS() {
- return (0, _util.shadow)(this, "PDF_TO_CSS_UNITS", this.CSS / this.PDF);
- }
-
-};
-exports.PixelsPerInch = PixelsPerInch;
-
-class DOMCanvasFactory extends _base_factory.BaseCanvasFactory {
- constructor({
- ownerDocument = globalThis.document
- } = {}) {
- super();
- this._document = ownerDocument;
- }
-
- _createCanvas(width, height) {
- const canvas = this._document.createElement("canvas");
-
- canvas.width = width;
- canvas.height = height;
- return canvas;
- }
-
-}
-
-exports.DOMCanvasFactory = DOMCanvasFactory;
-
-async function fetchData(url, asTypedArray = false) {
- if (isValidFetchUrl(url, document.baseURI)) {
- const response = await fetch(url);
-
- if (!response.ok) {
- throw new Error(response.statusText);
- }
-
- return asTypedArray ? new Uint8Array(await response.arrayBuffer()) : (0, _util.stringToBytes)(await response.text());
- }
-
- return new Promise((resolve, reject) => {
- const request = new XMLHttpRequest();
- request.open("GET", url, true);
-
- if (asTypedArray) {
- request.responseType = "arraybuffer";
- }
-
- request.onreadystatechange = () => {
- if (request.readyState !== XMLHttpRequest.DONE) {
- return;
- }
-
- if (request.status === 200 || request.status === 0) {
- let data;
-
- if (asTypedArray && request.response) {
- data = new Uint8Array(request.response);
- } else if (!asTypedArray && request.responseText) {
- data = (0, _util.stringToBytes)(request.responseText);
- }
-
- if (data) {
- resolve(data);
- return;
- }
- }
-
- reject(new Error(request.statusText));
- };
-
- request.send(null);
- });
-}
-
-class DOMCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
- _fetchData(url, compressionType) {
- return fetchData(url, this.isCompressed).then(data => {
- return {
- cMapData: data,
- compressionType
- };
- });
- }
-
-}
-
-exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
-
-class DOMStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
- _fetchData(url) {
- return fetchData(url, true);
- }
-
-}
-
-exports.DOMStandardFontDataFactory = DOMStandardFontDataFactory;
-
-class DOMSVGFactory extends _base_factory.BaseSVGFactory {
- _createSVG(type) {
- return document.createElementNS(SVG_NS, type);
- }
-
-}
-
-exports.DOMSVGFactory = DOMSVGFactory;
-
-class PageViewport {
- constructor({
- viewBox,
- scale,
- rotation,
- offsetX = 0,
- offsetY = 0,
- dontFlip = false
- }) {
- this.viewBox = viewBox;
- this.scale = scale;
- this.rotation = rotation;
- this.offsetX = offsetX;
- this.offsetY = offsetY;
- const centerX = (viewBox[2] + viewBox[0]) / 2;
- const centerY = (viewBox[3] + viewBox[1]) / 2;
- let rotateA, rotateB, rotateC, rotateD;
- rotation %= 360;
-
- if (rotation < 0) {
- rotation += 360;
- }
-
- switch (rotation) {
- case 180:
- rotateA = -1;
- rotateB = 0;
- rotateC = 0;
- rotateD = 1;
- break;
-
- case 90:
- rotateA = 0;
- rotateB = 1;
- rotateC = 1;
- rotateD = 0;
- break;
-
- case 270:
- rotateA = 0;
- rotateB = -1;
- rotateC = -1;
- rotateD = 0;
- break;
-
- case 0:
- rotateA = 1;
- rotateB = 0;
- rotateC = 0;
- rotateD = -1;
- break;
-
- default:
- throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
- }
-
- if (dontFlip) {
- rotateC = -rotateC;
- rotateD = -rotateD;
- }
-
- let offsetCanvasX, offsetCanvasY;
- let width, height;
-
- if (rotateA === 0) {
- offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
- offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
- width = Math.abs(viewBox[3] - viewBox[1]) * scale;
- height = Math.abs(viewBox[2] - viewBox[0]) * scale;
- } else {
- offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
- offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
- width = Math.abs(viewBox[2] - viewBox[0]) * scale;
- height = Math.abs(viewBox[3] - viewBox[1]) * scale;
- }
-
- this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
- this.width = width;
- this.height = height;
- }
-
- clone({
- scale = this.scale,
- rotation = this.rotation,
- offsetX = this.offsetX,
- offsetY = this.offsetY,
- dontFlip = false
- } = {}) {
- return new PageViewport({
- viewBox: this.viewBox.slice(),
- scale,
- rotation,
- offsetX,
- offsetY,
- dontFlip
- });
- }
-
- convertToViewportPoint(x, y) {
- return _util.Util.applyTransform([x, y], this.transform);
- }
-
- convertToViewportRectangle(rect) {
- const topLeft = _util.Util.applyTransform([rect[0], rect[1]], this.transform);
-
- const bottomRight = _util.Util.applyTransform([rect[2], rect[3]], this.transform);
-
- return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
- }
-
- convertToPdfPoint(x, y) {
- return _util.Util.applyInverseTransform([x, y], this.transform);
- }
-
-}
-
-exports.PageViewport = PageViewport;
-
-class RenderingCancelledException extends _util.BaseException {
- constructor(msg, type) {
- super(msg, "RenderingCancelledException");
- this.type = type;
- }
-
-}
-
-exports.RenderingCancelledException = RenderingCancelledException;
-const LinkTarget = {
- NONE: 0,
- SELF: 1,
- BLANK: 2,
- PARENT: 3,
- TOP: 4
-};
-exports.LinkTarget = LinkTarget;
-
-function addLinkAttributes(link, {
- url,
- target,
- rel,
- enabled = true
-} = {}) {
- (0, _util.assert)(url && typeof url === "string", 'addLinkAttributes: A valid "url" parameter must provided.');
- const urlNullRemoved = (0, _util.removeNullCharacters)(url);
-
- if (enabled) {
- link.href = link.title = urlNullRemoved;
- } else {
- link.href = "";
- link.title = `Disabled: ${urlNullRemoved}`;
-
- link.onclick = () => {
- return false;
- };
- }
-
- let targetStr = "";
-
- switch (target) {
- case LinkTarget.NONE:
- break;
-
- case LinkTarget.SELF:
- targetStr = "_self";
- break;
-
- case LinkTarget.BLANK:
- targetStr = "_blank";
- break;
-
- case LinkTarget.PARENT:
- targetStr = "_parent";
- break;
-
- case LinkTarget.TOP:
- targetStr = "_top";
- break;
- }
-
- link.target = targetStr;
- link.rel = typeof rel === "string" ? rel : DEFAULT_LINK_REL;
-}
-
-function isDataScheme(url) {
- const ii = url.length;
- let i = 0;
-
- while (i < ii && url[i].trim() === "") {
- i++;
- }
-
- return url.substring(i, i + 5).toLowerCase() === "data:";
-}
-
-function isPdfFile(filename) {
- return typeof filename === "string" && /\.pdf$/i.test(filename);
-}
-
-function getFilenameFromUrl(url) {
- const anchor = url.indexOf("#");
- const query = url.indexOf("?");
- const end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length);
- return url.substring(url.lastIndexOf("/", end) + 1, end);
-}
-
-function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
- if (typeof url !== "string") {
- return defaultFilename;
- }
-
- if (isDataScheme(url)) {
- (0, _util.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
- return defaultFilename;
- }
-
- const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
- const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
- const splitURI = reURI.exec(url);
- let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
-
- if (suggestedFilename) {
- suggestedFilename = suggestedFilename[0];
-
- if (suggestedFilename.includes("%")) {
- try {
- suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
- } catch (ex) {}
- }
- }
-
- return suggestedFilename || defaultFilename;
-}
-
-class StatTimer {
- constructor() {
- this.started = Object.create(null);
- this.times = [];
- }
-
- time(name) {
- if (name in this.started) {
- (0, _util.warn)(`Timer is already running for ${name}`);
- }
-
- this.started[name] = Date.now();
- }
-
- timeEnd(name) {
- if (!(name in this.started)) {
- (0, _util.warn)(`Timer has not been started for ${name}`);
- }
-
- this.times.push({
- name,
- start: this.started[name],
- end: Date.now()
- });
- delete this.started[name];
- }
-
- toString() {
- const outBuf = [];
- let longest = 0;
-
- for (const time of this.times) {
- const name = time.name;
-
- if (name.length > longest) {
- longest = name.length;
- }
- }
-
- for (const time of this.times) {
- const duration = time.end - time.start;
- outBuf.push(`${time.name.padEnd(longest)} ${duration}ms\n`);
- }
-
- return outBuf.join("");
- }
-
-}
-
-exports.StatTimer = StatTimer;
-
-function isValidFetchUrl(url, baseUrl) {
- try {
- const {
- protocol
- } = baseUrl ? new URL(url, baseUrl) : new URL(url);
- return protocol === "http:" || protocol === "https:";
- } catch (ex) {
- return false;
- }
-}
-
-function loadScript(src, removeScriptElement = false) {
- return new Promise((resolve, reject) => {
- const script = document.createElement("script");
- script.src = src;
-
- script.onload = function (evt) {
- if (removeScriptElement) {
- script.remove();
- }
-
- resolve(evt);
- };
-
- script.onerror = function () {
- reject(new Error(`Cannot load script at: ${script.src}`));
- };
-
- (document.head || document.documentElement).appendChild(script);
- });
-}
-
-function deprecated(details) {
- console.log("Deprecated API usage: " + details);
-}
-
-let pdfDateStringRegex;
-
-class PDFDateString {
- static toDateObject(input) {
- if (!input || !(0, _util.isString)(input)) {
- return null;
- }
-
- if (!pdfDateStringRegex) {
- pdfDateStringRegex = new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
- }
-
- const matches = pdfDateStringRegex.exec(input);
-
- if (!matches) {
- return null;
- }
-
- const year = parseInt(matches[1], 10);
- let month = parseInt(matches[2], 10);
- month = month >= 1 && month <= 12 ? month - 1 : 0;
- let day = parseInt(matches[3], 10);
- day = day >= 1 && day <= 31 ? day : 1;
- let hour = parseInt(matches[4], 10);
- hour = hour >= 0 && hour <= 23 ? hour : 0;
- let minute = parseInt(matches[5], 10);
- minute = minute >= 0 && minute <= 59 ? minute : 0;
- let second = parseInt(matches[6], 10);
- second = second >= 0 && second <= 59 ? second : 0;
- const universalTimeRelation = matches[7] || "Z";
- let offsetHour = parseInt(matches[8], 10);
- offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
- let offsetMinute = parseInt(matches[9], 10) || 0;
- offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
-
- if (universalTimeRelation === "-") {
- hour += offsetHour;
- minute += offsetMinute;
- } else if (universalTimeRelation === "+") {
- hour -= offsetHour;
- minute -= offsetMinute;
- }
-
- return new Date(Date.UTC(year, month, day, hour, minute, second));
- }
-
-}
-
-exports.PDFDateString = PDFDateString;
-
-function getXfaPageViewport(xfaPage, {
- scale = 1,
- rotation = 0
-}) {
- const {
- width,
- height
- } = xfaPage.attributes.style;
- const viewBox = [0, 0, parseInt(width), parseInt(height)];
- return new PageViewport({
- viewBox,
- scale,
- rotation
- });
-}
-
-/***/ }),
-/* 2 */
-/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
-
-
-
-Object.defineProperty(exports, "__esModule", ({
- value: true
-}));
-exports.VerbosityLevel = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.UNSUPPORTED_FEATURES = exports.TextRenderingMode = exports.StreamType = exports.RenderingIntentFlag = exports.PermissionFlag = exports.PasswordResponses = exports.PasswordException = exports.PageActionEventType = exports.OPS = exports.MissingPDFException = exports.IsLittleEndianCached = exports.IsEvalSupportedCached = exports.InvalidPDFException = exports.ImageKind = exports.IDENTITY_MATRIX = exports.FormatError = exports.FontType = exports.FONT_IDENTITY_MATRIX = exports.DocumentActionEventType = exports.CMapCompressionType = exports.BaseException = exports.AnnotationType = exports.AnnotationStateModelType = exports.AnnotationReviewState = exports.AnnotationReplyType = exports.AnnotationMode = exports.AnnotationMarkedState = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationBorderStyleType = exports.AnnotationActionEventType = exports.AbortException = void 0;
+exports.VerbosityLevel = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.UNSUPPORTED_FEATURES = exports.TextRenderingMode = exports.StreamType = exports.RenderingIntentFlag = exports.PermissionFlag = exports.PasswordResponses = exports.PasswordException = exports.PageActionEventType = exports.OPS = exports.MissingPDFException = exports.InvalidPDFException = exports.ImageKind = exports.IDENTITY_MATRIX = exports.FormatError = exports.FontType = exports.FeatureTest = exports.FONT_IDENTITY_MATRIX = exports.DocumentActionEventType = exports.CMapCompressionType = exports.BaseException = exports.AnnotationType = exports.AnnotationStateModelType = exports.AnnotationReviewState = exports.AnnotationReplyType = exports.AnnotationMode = exports.AnnotationMarkedState = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationBorderStyleType = exports.AnnotationActionEventType = exports.AbortException = void 0;
exports.arrayByteLength = arrayByteLength;
exports.arraysToBytes = arraysToBytes;
exports.assert = assert;
exports.bytesToString = bytesToString;
-exports.createObjectURL = createObjectURL;
exports.createPromiseCapability = createPromiseCapability;
exports.createValidAbsoluteUrl = createValidAbsoluteUrl;
exports.escapeString = escapeString;
exports.isArrayBuffer = isArrayBuffer;
exports.isArrayEqual = isArrayEqual;
exports.isAscii = isAscii;
-exports.isBool = isBool;
-exports.isNum = isNum;
-exports.isSameOrigin = isSameOrigin;
-exports.isString = isString;
exports.objectFromMap = objectFromMap;
exports.objectSize = objectSize;
-exports.removeNullCharacters = removeNullCharacters;
exports.setVerbosityLevel = setVerbosityLevel;
exports.shadow = shadow;
exports.string32 = string32;
exports.utf8StringToString = utf8StringToString;
exports.warn = warn;
-__w_pdfjs_require__(3);
+__w_pdfjs_require__(2);
const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
}
}
-function isSameOrigin(baseUrl, otherUrl) {
- let base;
+function _isValidProtocol(url) {
+ if (!url) {
+ return false;
+ }
- try {
- base = new URL(baseUrl);
+ switch (url.protocol) {
+ case "http:":
+ case "https:":
+ case "ftp:":
+ case "mailto:":
+ case "tel:":
+ return true;
- if (!base.origin || base.origin === "null") {
+ default:
return false;
+ }
+}
+
+function createValidAbsoluteUrl(url, baseUrl = null, options = null) {
+ if (!url) {
+ return null;
+ }
+
+ try {
+ if (options && typeof url === "string") {
+ if (options.addDefaultProtocol && url.startsWith("www.")) {
+ const dots = url.match(/\./g);
+
+ if (dots && dots.length >= 2) {
+ url = `http://${url}`;
+ }
+ }
+
+ if (options.tryConvertEncoding) {
+ try {
+ url = stringToUTF8String(url);
+ } catch (ex) {}
+ }
+ }
+
+ const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);
+
+ if (_isValidProtocol(absoluteUrl)) {
+ return absoluteUrl;
+ }
+ } catch (ex) {}
+
+ return null;
+}
+
+function shadow(obj, prop, value) {
+ Object.defineProperty(obj, prop, {
+ value,
+ enumerable: true,
+ configurable: true,
+ writable: false
+ });
+ return value;
+}
+
+const BaseException = function BaseExceptionClosure() {
+ function BaseException(message, name) {
+ if (this.constructor === BaseException) {
+ unreachable("Cannot initialize BaseException.");
+ }
+
+ this.message = message;
+ this.name = name;
+ }
+
+ BaseException.prototype = new Error();
+ BaseException.constructor = BaseException;
+ return BaseException;
+}();
+
+exports.BaseException = BaseException;
+
+class PasswordException extends BaseException {
+ constructor(msg, code) {
+ super(msg, "PasswordException");
+ this.code = code;
+ }
+
+}
+
+exports.PasswordException = PasswordException;
+
+class UnknownErrorException extends BaseException {
+ constructor(msg, details) {
+ super(msg, "UnknownErrorException");
+ this.details = details;
+ }
+
+}
+
+exports.UnknownErrorException = UnknownErrorException;
+
+class InvalidPDFException extends BaseException {
+ constructor(msg) {
+ super(msg, "InvalidPDFException");
+ }
+
+}
+
+exports.InvalidPDFException = InvalidPDFException;
+
+class MissingPDFException extends BaseException {
+ constructor(msg) {
+ super(msg, "MissingPDFException");
+ }
+
+}
+
+exports.MissingPDFException = MissingPDFException;
+
+class UnexpectedResponseException extends BaseException {
+ constructor(msg, status) {
+ super(msg, "UnexpectedResponseException");
+ this.status = status;
+ }
+
+}
+
+exports.UnexpectedResponseException = UnexpectedResponseException;
+
+class FormatError extends BaseException {
+ constructor(msg) {
+ super(msg, "FormatError");
+ }
+
+}
+
+exports.FormatError = FormatError;
+
+class AbortException extends BaseException {
+ constructor(msg) {
+ super(msg, "AbortException");
+ }
+
+}
+
+exports.AbortException = AbortException;
+
+function bytesToString(bytes) {
+ if (typeof bytes !== "object" || bytes === null || bytes.length === undefined) {
+ unreachable("Invalid argument for bytesToString");
+ }
+
+ const length = bytes.length;
+ const MAX_ARGUMENT_COUNT = 8192;
+
+ if (length < MAX_ARGUMENT_COUNT) {
+ return String.fromCharCode.apply(null, bytes);
+ }
+
+ const strBuf = [];
+
+ for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
+ const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
+ const chunk = bytes.subarray(i, chunkEnd);
+ strBuf.push(String.fromCharCode.apply(null, chunk));
+ }
+
+ return strBuf.join("");
+}
+
+function stringToBytes(str) {
+ if (typeof str !== "string") {
+ unreachable("Invalid argument for stringToBytes");
+ }
+
+ const length = str.length;
+ const bytes = new Uint8Array(length);
+
+ for (let i = 0; i < length; ++i) {
+ bytes[i] = str.charCodeAt(i) & 0xff;
+ }
+
+ return bytes;
+}
+
+function arrayByteLength(arr) {
+ if (arr.length !== undefined) {
+ return arr.length;
+ }
+
+ if (arr.byteLength !== undefined) {
+ return arr.byteLength;
+ }
+
+ unreachable("Invalid argument for arrayByteLength");
+}
+
+function arraysToBytes(arr) {
+ const length = arr.length;
+
+ if (length === 1 && arr[0] instanceof Uint8Array) {
+ return arr[0];
+ }
+
+ let resultLength = 0;
+
+ for (let i = 0; i < length; i++) {
+ resultLength += arrayByteLength(arr[i]);
+ }
+
+ let pos = 0;
+ const data = new Uint8Array(resultLength);
+
+ for (let i = 0; i < length; i++) {
+ let item = arr[i];
+
+ if (!(item instanceof Uint8Array)) {
+ if (typeof item === "string") {
+ item = stringToBytes(item);
+ } else {
+ item = new Uint8Array(item);
+ }
}
+
+ const itemLength = item.byteLength;
+ data.set(item, pos);
+ pos += itemLength;
+ }
+
+ return data;
+}
+
+function string32(value) {
+ return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
+}
+
+function objectSize(obj) {
+ return Object.keys(obj).length;
+}
+
+function objectFromMap(map) {
+ const obj = Object.create(null);
+
+ for (const [key, value] of map) {
+ obj[key] = value;
+ }
+
+ return obj;
+}
+
+function isLittleEndian() {
+ const buffer8 = new Uint8Array(4);
+ buffer8[0] = 1;
+ const view32 = new Uint32Array(buffer8.buffer, 0, 1);
+ return view32[0] === 1;
+}
+
+function isEvalSupported() {
+ try {
+ new Function("");
+ return true;
} catch (e) {
return false;
}
-
- const other = new URL(otherUrl, base);
- return base.origin === other.origin;
}
-function _isValidProtocol(url) {
- if (!url) {
- return false;
+class FeatureTest {
+ static get isLittleEndian() {
+ return shadow(this, "isLittleEndian", isLittleEndian());
}
- switch (url.protocol) {
- case "http:":
- case "https:":
- case "ftp:":
- case "mailto:":
- case "tel:":
- return true;
+ static get isEvalSupported() {
+ return shadow(this, "isEvalSupported", isEvalSupported());
+ }
- default:
- return false;
+ static get isOffscreenCanvasSupported() {
+ return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined");
}
+
}
-function createValidAbsoluteUrl(url, baseUrl = null, options = null) {
- if (!url) {
- return null;
+exports.FeatureTest = FeatureTest;
+const hexNumbers = [...Array(256).keys()].map(n => n.toString(16).padStart(2, "0"));
+
+class Util {
+ static makeHexColor(r, g, b) {
+ return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;
}
- try {
- if (options && typeof url === "string") {
- if (options.addDefaultProtocol && url.startsWith("www.")) {
- const dots = url.match(/\./g);
+ static scaleMinMax(transform, minMax) {
+ let temp;
- if (dots && dots.length >= 2) {
- url = `http://${url}`;
- }
+ if (transform[0]) {
+ if (transform[0] < 0) {
+ temp = minMax[0];
+ minMax[0] = minMax[1];
+ minMax[1] = temp;
}
- if (options.tryConvertEncoding) {
- try {
- url = stringToUTF8String(url);
- } catch (ex) {}
+ minMax[0] *= transform[0];
+ minMax[1] *= transform[0];
+
+ if (transform[3] < 0) {
+ temp = minMax[2];
+ minMax[2] = minMax[3];
+ minMax[3] = temp;
}
- }
- const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);
+ minMax[2] *= transform[3];
+ minMax[3] *= transform[3];
+ } else {
+ temp = minMax[0];
+ minMax[0] = minMax[2];
+ minMax[2] = temp;
+ temp = minMax[1];
+ minMax[1] = minMax[3];
+ minMax[3] = temp;
- if (_isValidProtocol(absoluteUrl)) {
- return absoluteUrl;
- }
- } catch (ex) {}
+ if (transform[1] < 0) {
+ temp = minMax[2];
+ minMax[2] = minMax[3];
+ minMax[3] = temp;
+ }
- return null;
-}
+ minMax[2] *= transform[1];
+ minMax[3] *= transform[1];
-function shadow(obj, prop, value) {
- Object.defineProperty(obj, prop, {
- value,
- enumerable: true,
- configurable: true,
- writable: false
- });
- return value;
-}
+ if (transform[2] < 0) {
+ temp = minMax[0];
+ minMax[0] = minMax[1];
+ minMax[1] = temp;
+ }
-const BaseException = function BaseExceptionClosure() {
- function BaseException(message, name) {
- if (this.constructor === BaseException) {
- unreachable("Cannot initialize BaseException.");
+ minMax[0] *= transform[2];
+ minMax[1] *= transform[2];
}
- this.message = message;
- this.name = name;
+ minMax[0] += transform[4];
+ minMax[1] += transform[4];
+ minMax[2] += transform[5];
+ minMax[3] += transform[5];
}
- BaseException.prototype = new Error();
- BaseException.constructor = BaseException;
- return BaseException;
-}();
+ static transform(m1, m2) {
+ return [m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5]];
+ }
-exports.BaseException = BaseException;
+ static applyTransform(p, m) {
+ const xt = p[0] * m[0] + p[1] * m[2] + m[4];
+ const yt = p[0] * m[1] + p[1] * m[3] + m[5];
+ return [xt, yt];
+ }
-class PasswordException extends BaseException {
- constructor(msg, code) {
- super(msg, "PasswordException");
- this.code = code;
+ static applyInverseTransform(p, m) {
+ const d = m[0] * m[3] - m[1] * m[2];
+ const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
+ const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
+ return [xt, yt];
}
-}
+ static getAxialAlignedBoundingBox(r, m) {
+ const p1 = Util.applyTransform(r, m);
+ const p2 = Util.applyTransform(r.slice(2, 4), m);
+ const p3 = Util.applyTransform([r[0], r[3]], m);
+ const p4 = Util.applyTransform([r[2], r[1]], m);
+ return [Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1])];
+ }
-exports.PasswordException = PasswordException;
+ static inverseTransform(m) {
+ const d = m[0] * m[3] - m[1] * m[2];
+ return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
+ }
-class UnknownErrorException extends BaseException {
- constructor(msg, details) {
- super(msg, "UnknownErrorException");
- this.details = details;
+ static apply3dTransform(m, v) {
+ return [m[0] * v[0] + m[1] * v[1] + m[2] * v[2], m[3] * v[0] + m[4] * v[1] + m[5] * v[2], m[6] * v[0] + m[7] * v[1] + m[8] * v[2]];
}
-}
+ static singularValueDecompose2dScale(m) {
+ const transpose = [m[0], m[2], m[1], m[3]];
+ const a = m[0] * transpose[0] + m[1] * transpose[2];
+ const b = m[0] * transpose[1] + m[1] * transpose[3];
+ const c = m[2] * transpose[0] + m[3] * transpose[2];
+ const d = m[2] * transpose[1] + m[3] * transpose[3];
+ const first = (a + d) / 2;
+ const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2;
+ const sx = first + second || 1;
+ const sy = first - second || 1;
+ return [Math.sqrt(sx), Math.sqrt(sy)];
+ }
-exports.UnknownErrorException = UnknownErrorException;
+ static normalizeRect(rect) {
+ const r = rect.slice(0);
-class InvalidPDFException extends BaseException {
- constructor(msg) {
- super(msg, "InvalidPDFException");
+ if (rect[0] > rect[2]) {
+ r[0] = rect[2];
+ r[2] = rect[0];
+ }
+
+ if (rect[1] > rect[3]) {
+ r[1] = rect[3];
+ r[3] = rect[1];
+ }
+
+ return r;
}
-}
+ static intersect(rect1, rect2) {
+ const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2]));
+ const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2]));
-exports.InvalidPDFException = InvalidPDFException;
+ if (xLow > xHigh) {
+ return null;
+ }
-class MissingPDFException extends BaseException {
- constructor(msg) {
- super(msg, "MissingPDFException");
+ const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3]));
+ const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3]));
+
+ if (yLow > yHigh) {
+ return null;
+ }
+
+ return [xLow, yLow, xHigh, yHigh];
}
-}
+ static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3) {
+ const tvalues = [],
+ bounds = [[], []];
+ let a, b, c, t, t1, t2, b2ac, sqrtb2ac;
-exports.MissingPDFException = MissingPDFException;
+ for (let i = 0; i < 2; ++i) {
+ if (i === 0) {
+ b = 6 * x0 - 12 * x1 + 6 * x2;
+ a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
+ c = 3 * x1 - 3 * x0;
+ } else {
+ b = 6 * y0 - 12 * y1 + 6 * y2;
+ a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
+ c = 3 * y1 - 3 * y0;
+ }
-class UnexpectedResponseException extends BaseException {
- constructor(msg, status) {
- super(msg, "UnexpectedResponseException");
- this.status = status;
- }
+ if (Math.abs(a) < 1e-12) {
+ if (Math.abs(b) < 1e-12) {
+ continue;
+ }
-}
+ t = -c / b;
-exports.UnexpectedResponseException = UnexpectedResponseException;
+ if (0 < t && t < 1) {
+ tvalues.push(t);
+ }
-class FormatError extends BaseException {
- constructor(msg) {
- super(msg, "FormatError");
- }
+ continue;
+ }
-}
+ b2ac = b * b - 4 * c * a;
+ sqrtb2ac = Math.sqrt(b2ac);
-exports.FormatError = FormatError;
+ if (b2ac < 0) {
+ continue;
+ }
-class AbortException extends BaseException {
- constructor(msg) {
- super(msg, "AbortException");
+ t1 = (-b + sqrtb2ac) / (2 * a);
+
+ if (0 < t1 && t1 < 1) {
+ tvalues.push(t1);
+ }
+
+ t2 = (-b - sqrtb2ac) / (2 * a);
+
+ if (0 < t2 && t2 < 1) {
+ tvalues.push(t2);
+ }
+ }
+
+ let j = tvalues.length,
+ mt;
+ const jlen = j;
+
+ while (j--) {
+ t = tvalues[j];
+ mt = 1 - t;
+ bounds[0][j] = mt * mt * mt * x0 + 3 * mt * mt * t * x1 + 3 * mt * t * t * x2 + t * t * t * x3;
+ bounds[1][j] = mt * mt * mt * y0 + 3 * mt * mt * t * y1 + 3 * mt * t * t * y2 + t * t * t * y3;
+ }
+
+ bounds[0][jlen] = x0;
+ bounds[1][jlen] = y0;
+ bounds[0][jlen + 1] = x3;
+ bounds[1][jlen + 1] = y3;
+ bounds[0].length = bounds[1].length = jlen + 2;
+ return [Math.min(...bounds[0]), Math.min(...bounds[1]), Math.max(...bounds[0]), Math.max(...bounds[1])];
}
}
-exports.AbortException = AbortException;
-const NullCharactersRegExp = /\x00+/g;
-const InvisibleCharactersRegExp = /[\x01-\x1F]/g;
+exports.Util = Util;
+const PDFStringTranslateTable = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2d8, 0x2c7, 0x2c6, 0x2d9, 0x2dd, 0x2db, 0x2da, 0x2dc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203a, 0x2212, 0x2030, 0x201e, 0x201c, 0x201d, 0x2018, 0x2019, 0x201a, 0x2122, 0xfb01, 0xfb02, 0x141, 0x152, 0x160, 0x178, 0x17d, 0x131, 0x142, 0x153, 0x161, 0x17e, 0, 0x20ac];
-function removeNullCharacters(str, replaceInvisible = false) {
- if (typeof str !== "string") {
- warn("The argument for removeNullCharacters must be a string.");
- return str;
+function stringToPDFString(str) {
+ if (str[0] >= "\xEF") {
+ let encoding;
+
+ if (str[0] === "\xFE" && str[1] === "\xFF") {
+ encoding = "utf-16be";
+ } else if (str[0] === "\xFF" && str[1] === "\xFE") {
+ encoding = "utf-16le";
+ } else if (str[0] === "\xEF" && str[1] === "\xBB" && str[2] === "\xBF") {
+ encoding = "utf-8";
+ }
+
+ if (encoding) {
+ try {
+ const decoder = new TextDecoder(encoding, {
+ fatal: true
+ });
+ const buffer = stringToBytes(str);
+ return decoder.decode(buffer);
+ } catch (ex) {
+ warn(`stringToPDFString: "${ex}".`);
+ }
+ }
}
- if (replaceInvisible) {
- str = str.replace(InvisibleCharactersRegExp, " ");
+ const strBuf = [];
+
+ for (let i = 0, ii = str.length; i < ii; i++) {
+ const code = PDFStringTranslateTable[str.charCodeAt(i)];
+ strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
}
- return str.replace(NullCharactersRegExp, "");
+ return strBuf.join("");
+}
+
+function escapeString(str) {
+ return str.replace(/([()\\\n\r])/g, match => {
+ if (match === "\n") {
+ return "\\n";
+ } else if (match === "\r") {
+ return "\\r";
+ }
+
+ return `\\${match}`;
+ });
+}
+
+function isAscii(str) {
+ return /^[\x00-\x7F]*$/.test(str);
}
-function bytesToString(bytes) {
- assert(bytes !== null && typeof bytes === "object" && bytes.length !== undefined, "Invalid argument for bytesToString");
- const length = bytes.length;
- const MAX_ARGUMENT_COUNT = 8192;
+function stringToUTF16BEString(str) {
+ const buf = ["\xFE\xFF"];
- if (length < MAX_ARGUMENT_COUNT) {
- return String.fromCharCode.apply(null, bytes);
+ for (let i = 0, ii = str.length; i < ii; i++) {
+ const char = str.charCodeAt(i);
+ buf.push(String.fromCharCode(char >> 8 & 0xff), String.fromCharCode(char & 0xff));
}
- const strBuf = [];
+ return buf.join("");
+}
- for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
- const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
- const chunk = bytes.subarray(i, chunkEnd);
- strBuf.push(String.fromCharCode.apply(null, chunk));
- }
+function stringToUTF8String(str) {
+ return decodeURIComponent(escape(str));
+}
- return strBuf.join("");
+function utf8StringToString(str) {
+ return unescape(encodeURIComponent(str));
}
-function stringToBytes(str) {
- assert(typeof str === "string", "Invalid argument for stringToBytes");
- const length = str.length;
- const bytes = new Uint8Array(length);
+function isArrayBuffer(v) {
+ return typeof v === "object" && v !== null && v.byteLength !== undefined;
+}
- for (let i = 0; i < length; ++i) {
- bytes[i] = str.charCodeAt(i) & 0xff;
+function isArrayEqual(arr1, arr2) {
+ if (arr1.length !== arr2.length) {
+ return false;
}
- return bytes;
-}
-
-function arrayByteLength(arr) {
- if (arr.length !== undefined) {
- return arr.length;
+ for (let i = 0, ii = arr1.length; i < ii; i++) {
+ if (arr1[i] !== arr2[i]) {
+ return false;
+ }
}
- assert(arr.byteLength !== undefined, "arrayByteLength - invalid argument.");
- return arr.byteLength;
+ return true;
}
-function arraysToBytes(arr) {
- const length = arr.length;
+function getModificationDate(date = new Date()) {
+ const buffer = [date.getUTCFullYear().toString(), (date.getUTCMonth() + 1).toString().padStart(2, "0"), date.getUTCDate().toString().padStart(2, "0"), date.getUTCHours().toString().padStart(2, "0"), date.getUTCMinutes().toString().padStart(2, "0"), date.getUTCSeconds().toString().padStart(2, "0")];
+ return buffer.join("");
+}
- if (length === 1 && arr[0] instanceof Uint8Array) {
- return arr[0];
- }
+function createPromiseCapability() {
+ const capability = Object.create(null);
+ let isSettled = false;
+ Object.defineProperty(capability, "settled", {
+ get() {
+ return isSettled;
+ }
- let resultLength = 0;
+ });
+ capability.promise = new Promise(function (resolve, reject) {
+ capability.resolve = function (data) {
+ isSettled = true;
+ resolve(data);
+ };
- for (let i = 0; i < length; i++) {
- resultLength += arrayByteLength(arr[i]);
- }
+ capability.reject = function (reason) {
+ isSettled = true;
+ reject(reason);
+ };
+ });
+ return capability;
+}
- let pos = 0;
- const data = new Uint8Array(resultLength);
+/***/ }),
+/* 2 */
+/***/ ((__unused_webpack_module, __unused_webpack_exports, __w_pdfjs_require__) => {
- for (let i = 0; i < length; i++) {
- let item = arr[i];
- if (!(item instanceof Uint8Array)) {
- if (typeof item === "string") {
- item = stringToBytes(item);
- } else {
- item = new Uint8Array(item);
- }
- }
- const itemLength = item.byteLength;
- data.set(item, pos);
- pos += itemLength;
- }
+var _is_node = __w_pdfjs_require__(3);
- return data;
-}
+;
-function string32(value) {
- return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
-}
+/***/ }),
+/* 3 */
+/***/ ((__unused_webpack_module, exports) => {
-function objectSize(obj) {
- return Object.keys(obj).length;
-}
-function objectFromMap(map) {
- const obj = Object.create(null);
- for (const [key, value] of map) {
- obj[key] = value;
- }
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports.isNodeJS = void 0;
+const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
+exports.isNodeJS = isNodeJS;
- return obj;
-}
+/***/ }),
+/* 4 */
+/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
-function isLittleEndian() {
- const buffer8 = new Uint8Array(4);
- buffer8[0] = 1;
- const view32 = new Uint32Array(buffer8.buffer, 0, 1);
- return view32[0] === 1;
-}
-const IsLittleEndianCached = {
- get value() {
- return shadow(this, "value", isLittleEndian());
- }
-};
-exports.IsLittleEndianCached = IsLittleEndianCached;
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports.build = exports.RenderTask = exports.PDFWorkerUtil = exports.PDFWorker = exports.PDFPageProxy = exports.PDFDocumentProxy = exports.PDFDocumentLoadingTask = exports.PDFDataRangeTransport = exports.LoopbackPort = exports.DefaultStandardFontDataFactory = exports.DefaultCanvasFactory = exports.DefaultCMapReaderFactory = void 0;
+exports.getDocument = getDocument;
+exports.setPDFNetworkStreamFactory = setPDFNetworkStreamFactory;
+exports.version = void 0;
-function isEvalSupported() {
- try {
- new Function("");
- return true;
- } catch (e) {
- return false;
- }
-}
+var _util = __w_pdfjs_require__(1);
-const IsEvalSupportedCached = {
- get value() {
- return shadow(this, "value", isEvalSupported());
- }
+var _display_utils = __w_pdfjs_require__(5);
-};
-exports.IsEvalSupportedCached = IsEvalSupportedCached;
-const hexNumbers = [...Array(256).keys()].map(n => n.toString(16).padStart(2, "0"));
+var _font_loader = __w_pdfjs_require__(7);
-class Util {
- static makeHexColor(r, g, b) {
- return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;
- }
+var _annotation_storage = __w_pdfjs_require__(8);
- static transform(m1, m2) {
- return [m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5]];
- }
+var _canvas = __w_pdfjs_require__(10);
- static applyTransform(p, m) {
- const xt = p[0] * m[0] + p[1] * m[2] + m[4];
- const yt = p[0] * m[1] + p[1] * m[3] + m[5];
- return [xt, yt];
- }
+var _worker_options = __w_pdfjs_require__(13);
- static applyInverseTransform(p, m) {
- const d = m[0] * m[3] - m[1] * m[2];
- const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
- const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
- return [xt, yt];
- }
+var _is_node = __w_pdfjs_require__(3);
- static getAxialAlignedBoundingBox(r, m) {
- const p1 = Util.applyTransform(r, m);
- const p2 = Util.applyTransform(r.slice(2, 4), m);
- const p3 = Util.applyTransform([r[0], r[3]], m);
- const p4 = Util.applyTransform([r[2], r[1]], m);
- return [Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1])];
- }
+var _message_handler = __w_pdfjs_require__(14);
- static inverseTransform(m) {
- const d = m[0] * m[3] - m[1] * m[2];
- return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
- }
+var _metadata = __w_pdfjs_require__(15);
- static apply3dTransform(m, v) {
- return [m[0] * v[0] + m[1] * v[1] + m[2] * v[2], m[3] * v[0] + m[4] * v[1] + m[5] * v[2], m[6] * v[0] + m[7] * v[1] + m[8] * v[2]];
- }
+var _optional_content_config = __w_pdfjs_require__(16);
- static singularValueDecompose2dScale(m) {
- const transpose = [m[0], m[2], m[1], m[3]];
- const a = m[0] * transpose[0] + m[1] * transpose[2];
- const b = m[0] * transpose[1] + m[1] * transpose[3];
- const c = m[2] * transpose[0] + m[3] * transpose[2];
- const d = m[2] * transpose[1] + m[3] * transpose[3];
- const first = (a + d) / 2;
- const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2;
- const sx = first + second || 1;
- const sy = first - second || 1;
- return [Math.sqrt(sx), Math.sqrt(sy)];
- }
+var _transport_stream = __w_pdfjs_require__(17);
- static normalizeRect(rect) {
- const r = rect.slice(0);
+var _xfa_text = __w_pdfjs_require__(18);
- if (rect[0] > rect[2]) {
- r[0] = rect[2];
- r[2] = rect[0];
- }
+const DEFAULT_RANGE_CHUNK_SIZE = 65536;
+const RENDERING_CANCELLED_TIMEOUT = 100;
+let DefaultCanvasFactory = _display_utils.DOMCanvasFactory;
+exports.DefaultCanvasFactory = DefaultCanvasFactory;
+let DefaultCMapReaderFactory = _display_utils.DOMCMapReaderFactory;
+exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory;
+let DefaultStandardFontDataFactory = _display_utils.DOMStandardFontDataFactory;
+exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory;
- if (rect[1] > rect[3]) {
- r[1] = rect[3];
- r[3] = rect[1];
- }
+if (_is_node.isNodeJS) {
+ const {
+ NodeCanvasFactory,
+ NodeCMapReaderFactory,
+ NodeStandardFontDataFactory
+ } = __w_pdfjs_require__(19);
+
+ exports.DefaultCanvasFactory = DefaultCanvasFactory = NodeCanvasFactory;
+ exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory = NodeCMapReaderFactory;
+ exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory = NodeStandardFontDataFactory;
+}
- return r;
- }
+let createPDFNetworkStream;
- static intersect(rect1, rect2) {
- function compare(a, b) {
- return a - b;
- }
+function setPDFNetworkStreamFactory(pdfNetworkStreamFactory) {
+ createPDFNetworkStream = pdfNetworkStreamFactory;
+}
- const orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare);
- const orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare);
- const result = [];
- rect1 = Util.normalizeRect(rect1);
- rect2 = Util.normalizeRect(rect2);
+function getDocument(src) {
+ const task = new PDFDocumentLoadingTask();
+ let source;
- if (orderedX[0] === rect1[0] && orderedX[1] === rect2[0] || orderedX[0] === rect2[0] && orderedX[1] === rect1[0]) {
- result[0] = orderedX[1];
- result[2] = orderedX[2];
- } else {
- return null;
+ if (typeof src === "string" || src instanceof URL) {
+ source = {
+ url: src
+ };
+ } else if ((0, _util.isArrayBuffer)(src)) {
+ source = {
+ data: src
+ };
+ } else if (src instanceof PDFDataRangeTransport) {
+ source = {
+ range: src
+ };
+ } else {
+ if (typeof src !== "object") {
+ throw new Error("Invalid parameter in getDocument, " + "need either string, URL, Uint8Array, or parameter object.");
}
- if (orderedY[0] === rect1[1] && orderedY[1] === rect2[1] || orderedY[0] === rect2[1] && orderedY[1] === rect1[1]) {
- result[1] = orderedY[1];
- result[3] = orderedY[2];
- } else {
- return null;
+ if (!src.url && !src.data && !src.range) {
+ throw new Error("Invalid parameter object: need either .data, .range or .url");
}
- return result;
- }
-
- static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3) {
- const tvalues = [],
- bounds = [[], []];
- let a, b, c, t, t1, t2, b2ac, sqrtb2ac;
+ source = src;
+ }
- for (let i = 0; i < 2; ++i) {
- if (i === 0) {
- b = 6 * x0 - 12 * x1 + 6 * x2;
- a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
- c = 3 * x1 - 3 * x0;
- } else {
- b = 6 * y0 - 12 * y1 + 6 * y2;
- a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
- c = 3 * y1 - 3 * y0;
- }
+ const params = Object.create(null);
+ let rangeTransport = null,
+ worker = null;
- if (Math.abs(a) < 1e-12) {
- if (Math.abs(b) < 1e-12) {
+ for (const key in source) {
+ const value = source[key];
+
+ switch (key) {
+ case "url":
+ if (typeof window !== "undefined") {
+ try {
+ params[key] = new URL(value, window.location).href;
+ continue;
+ } catch (ex) {
+ (0, _util.warn)(`Cannot create valid URL: "${ex}".`);
+ }
+ } else if (typeof value === "string" || value instanceof URL) {
+ params[key] = value.toString();
continue;
}
- t = -c / b;
-
- if (0 < t && t < 1) {
- tvalues.push(t);
- }
+ throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property.");
+ case "range":
+ rangeTransport = value;
continue;
- }
-
- b2ac = b * b - 4 * c * a;
- sqrtb2ac = Math.sqrt(b2ac);
- if (b2ac < 0) {
+ case "worker":
+ worker = value;
continue;
- }
-
- t1 = (-b + sqrtb2ac) / (2 * a);
- if (0 < t1 && t1 < 1) {
- tvalues.push(t1);
- }
-
- t2 = (-b - sqrtb2ac) / (2 * a);
-
- if (0 < t2 && t2 < 1) {
- tvalues.push(t2);
- }
- }
-
- let j = tvalues.length,
- mt;
- const jlen = j;
+ case "data":
+ if (_is_node.isNodeJS && typeof Buffer !== "undefined" && value instanceof Buffer) {
+ params[key] = new Uint8Array(value);
+ } else if (value instanceof Uint8Array) {
+ break;
+ } else if (typeof value === "string") {
+ params[key] = (0, _util.stringToBytes)(value);
+ } else if (typeof value === "object" && value !== null && !isNaN(value.length)) {
+ params[key] = new Uint8Array(value);
+ } else if ((0, _util.isArrayBuffer)(value)) {
+ params[key] = new Uint8Array(value);
+ } else {
+ throw new Error("Invalid PDF binary data: either typed array, " + "string, or array-like object is expected in the data property.");
+ }
- while (j--) {
- t = tvalues[j];
- mt = 1 - t;
- bounds[0][j] = mt * mt * mt * x0 + 3 * mt * mt * t * x1 + 3 * mt * t * t * x2 + t * t * t * x3;
- bounds[1][j] = mt * mt * mt * y0 + 3 * mt * mt * t * y1 + 3 * mt * t * t * y2 + t * t * t * y3;
+ continue;
}
- bounds[0][jlen] = x0;
- bounds[1][jlen] = y0;
- bounds[0][jlen + 1] = x3;
- bounds[1][jlen + 1] = y3;
- bounds[0].length = bounds[1].length = jlen + 2;
- return [Math.min(...bounds[0]), Math.min(...bounds[1]), Math.max(...bounds[0]), Math.max(...bounds[1])];
+ params[key] = value;
}
-}
-
-exports.Util = Util;
-const PDFStringTranslateTable = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2d8, 0x2c7, 0x2c6, 0x2d9, 0x2dd, 0x2db, 0x2da, 0x2dc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203a, 0x2212, 0x2030, 0x201e, 0x201c, 0x201d, 0x2018, 0x2019, 0x201a, 0x2122, 0xfb01, 0xfb02, 0x141, 0x152, 0x160, 0x178, 0x17d, 0x131, 0x142, 0x153, 0x161, 0x17e, 0, 0x20ac];
-
-function stringToPDFString(str) {
- const length = str.length,
- strBuf = [];
+ params.CMapReaderFactory = params.CMapReaderFactory || DefaultCMapReaderFactory;
+ params.StandardFontDataFactory = params.StandardFontDataFactory || DefaultStandardFontDataFactory;
+ params.ignoreErrors = params.stopAtErrors !== true;
+ params.fontExtraProperties = params.fontExtraProperties === true;
+ params.pdfBug = params.pdfBug === true;
+ params.enableXfa = params.enableXfa === true;
- if (str[0] === "\xFE" && str[1] === "\xFF") {
- for (let i = 2; i < length; i += 2) {
- strBuf.push(String.fromCharCode(str.charCodeAt(i) << 8 | str.charCodeAt(i + 1)));
- }
- } else if (str[0] === "\xFF" && str[1] === "\xFE") {
- for (let i = 2; i < length; i += 2) {
- strBuf.push(String.fromCharCode(str.charCodeAt(i + 1) << 8 | str.charCodeAt(i)));
- }
- } else {
- for (let i = 0; i < length; ++i) {
- const code = PDFStringTranslateTable[str.charCodeAt(i)];
- strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
- }
+ if (!Number.isInteger(params.rangeChunkSize) || params.rangeChunkSize < 1) {
+ params.rangeChunkSize = DEFAULT_RANGE_CHUNK_SIZE;
}
- return strBuf.join("");
-}
+ if (typeof params.docBaseUrl !== "string" || (0, _display_utils.isDataScheme)(params.docBaseUrl)) {
+ params.docBaseUrl = null;
+ }
-function escapeString(str) {
- return str.replace(/([()\\\n\r])/g, match => {
- if (match === "\n") {
- return "\\n";
- } else if (match === "\r") {
- return "\\r";
- }
+ if (!Number.isInteger(params.maxImageSize) || params.maxImageSize < -1) {
+ params.maxImageSize = -1;
+ }
- return `\\${match}`;
- });
-}
+ if (typeof params.cMapUrl !== "string") {
+ params.cMapUrl = null;
+ }
-function isAscii(str) {
- return /^[\x00-\x7F]*$/.test(str);
-}
+ if (typeof params.standardFontDataUrl !== "string") {
+ params.standardFontDataUrl = null;
+ }
-function stringToUTF16BEString(str) {
- const buf = ["\xFE\xFF"];
+ if (typeof params.useWorkerFetch !== "boolean") {
+ params.useWorkerFetch = params.CMapReaderFactory === _display_utils.DOMCMapReaderFactory && params.StandardFontDataFactory === _display_utils.DOMStandardFontDataFactory;
+ }
- for (let i = 0, ii = str.length; i < ii; i++) {
- const char = str.charCodeAt(i);
- buf.push(String.fromCharCode(char >> 8 & 0xff), String.fromCharCode(char & 0xff));
+ if (typeof params.isEvalSupported !== "boolean") {
+ params.isEvalSupported = true;
}
- return buf.join("");
-}
+ if (typeof params.disableFontFace !== "boolean") {
+ params.disableFontFace = _is_node.isNodeJS;
+ }
-function stringToUTF8String(str) {
- return decodeURIComponent(escape(str));
-}
+ if (typeof params.useSystemFonts !== "boolean") {
+ params.useSystemFonts = !_is_node.isNodeJS && !params.disableFontFace;
+ }
-function utf8StringToString(str) {
- return unescape(encodeURIComponent(str));
-}
+ if (typeof params.ownerDocument !== "object" || params.ownerDocument === null) {
+ params.ownerDocument = globalThis.document;
+ }
-function isBool(v) {
- return typeof v === "boolean";
-}
+ if (typeof params.disableRange !== "boolean") {
+ params.disableRange = false;
+ }
-function isNum(v) {
- return typeof v === "number";
-}
+ if (typeof params.disableStream !== "boolean") {
+ params.disableStream = false;
+ }
-function isString(v) {
- return typeof v === "string";
-}
+ if (typeof params.disableAutoFetch !== "boolean") {
+ params.disableAutoFetch = false;
+ }
-function isArrayBuffer(v) {
- return typeof v === "object" && v !== null && v.byteLength !== undefined;
-}
+ (0, _util.setVerbosityLevel)(params.verbosity);
-function isArrayEqual(arr1, arr2) {
- if (arr1.length !== arr2.length) {
- return false;
+ if (!worker) {
+ const workerParams = {
+ verbosity: params.verbosity,
+ port: _worker_options.GlobalWorkerOptions.workerPort
+ };
+ worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams);
+ task._worker = worker;
}
- for (let i = 0, ii = arr1.length; i < ii; i++) {
- if (arr1[i] !== arr2[i]) {
- return false;
+ const docId = task.docId;
+ worker.promise.then(function () {
+ if (task.destroyed) {
+ throw new Error("Loading aborted");
}
- }
- return true;
-}
+ const workerIdPromise = _fetchDocument(worker, params, rangeTransport, docId);
-function getModificationDate(date = new Date()) {
- const buffer = [date.getUTCFullYear().toString(), (date.getUTCMonth() + 1).toString().padStart(2, "0"), date.getUTCDate().toString().padStart(2, "0"), date.getUTCHours().toString().padStart(2, "0"), date.getUTCMinutes().toString().padStart(2, "0"), date.getUTCSeconds().toString().padStart(2, "0")];
- return buffer.join("");
-}
+ const networkStreamPromise = new Promise(function (resolve) {
+ let networkStream;
-function createPromiseCapability() {
- const capability = Object.create(null);
- let isSettled = false;
- Object.defineProperty(capability, "settled", {
- get() {
- return isSettled;
- }
+ if (rangeTransport) {
+ networkStream = new _transport_stream.PDFDataTransportStream({
+ length: params.length,
+ initialData: params.initialData,
+ progressiveDone: params.progressiveDone,
+ contentDispositionFilename: params.contentDispositionFilename,
+ disableRange: params.disableRange,
+ disableStream: params.disableStream
+ }, rangeTransport);
+ } else if (!params.data) {
+ networkStream = createPDFNetworkStream({
+ url: params.url,
+ length: params.length,
+ httpHeaders: params.httpHeaders,
+ withCredentials: params.withCredentials,
+ rangeChunkSize: params.rangeChunkSize,
+ disableRange: params.disableRange,
+ disableStream: params.disableStream
+ });
+ }
- });
- capability.promise = new Promise(function (resolve, reject) {
- capability.resolve = function (data) {
- isSettled = true;
- resolve(data);
- };
+ resolve(networkStream);
+ });
+ return Promise.all([workerIdPromise, networkStreamPromise]).then(function ([workerId, networkStream]) {
+ if (task.destroyed) {
+ throw new Error("Loading aborted");
+ }
- capability.reject = function (reason) {
- isSettled = true;
- reject(reason);
- };
- });
- return capability;
+ const messageHandler = new _message_handler.MessageHandler(docId, workerId, worker.port);
+ const transport = new WorkerTransport(messageHandler, task, networkStream, params);
+ task._transport = transport;
+ messageHandler.send("Ready", null);
+ });
+ }).catch(task._capability.reject);
+ return task;
}
-function createObjectURL(data, contentType = "", forceDataSchema = false) {
- if (URL.createObjectURL && typeof Blob !== "undefined" && !forceDataSchema) {
- return URL.createObjectURL(new Blob([data], {
- type: contentType
- }));
+async function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
+ if (worker.destroyed) {
+ throw new Error("Worker was destroyed");
+ }
+
+ if (pdfDataRangeTransport) {
+ source.length = pdfDataRangeTransport.length;
+ source.initialData = pdfDataRangeTransport.initialData;
+ source.progressiveDone = pdfDataRangeTransport.progressiveDone;
+ source.contentDispositionFilename = pdfDataRangeTransport.contentDispositionFilename;
}
- const digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
- let buffer = `data:${contentType};base64,`;
+ const workerId = await worker.messageHandler.sendWithPromise("GetDocRequest", {
+ docId,
+ apiVersion: '2.14.305',
+ source: {
+ data: source.data,
+ url: source.url,
+ password: source.password,
+ disableAutoFetch: source.disableAutoFetch,
+ rangeChunkSize: source.rangeChunkSize,
+ length: source.length
+ },
+ maxImageSize: source.maxImageSize,
+ disableFontFace: source.disableFontFace,
+ docBaseUrl: source.docBaseUrl,
+ ignoreErrors: source.ignoreErrors,
+ isEvalSupported: source.isEvalSupported,
+ fontExtraProperties: source.fontExtraProperties,
+ enableXfa: source.enableXfa,
+ useSystemFonts: source.useSystemFonts,
+ cMapUrl: source.useWorkerFetch ? source.cMapUrl : null,
+ standardFontDataUrl: source.useWorkerFetch ? source.standardFontDataUrl : null
+ });
- for (let i = 0, ii = data.length; i < ii; i += 3) {
- const b1 = data[i] & 0xff;
- const b2 = data[i + 1] & 0xff;
- const b3 = data[i + 2] & 0xff;
- const d1 = b1 >> 2,
- d2 = (b1 & 3) << 4 | b2 >> 4;
- const d3 = i + 1 < ii ? (b2 & 0xf) << 2 | b3 >> 6 : 64;
- const d4 = i + 2 < ii ? b3 & 0x3f : 64;
- buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
+ if (worker.destroyed) {
+ throw new Error("Worker was destroyed");
}
- return buffer;
+ return workerId;
}
-/***/ }),
-/* 3 */
-/***/ ((__unused_webpack_module, __unused_webpack_exports, __w_pdfjs_require__) => {
-
-
-
-var _is_node = __w_pdfjs_require__(4);
-
-;
-
-/***/ }),
-/* 4 */
-/***/ ((__unused_webpack_module, exports) => {
-
+class PDFDocumentLoadingTask {
+ static #docId = 0;
+ constructor() {
+ this._capability = (0, _util.createPromiseCapability)();
+ this._transport = null;
+ this._worker = null;
+ this.docId = `d${PDFDocumentLoadingTask.#docId++}`;
+ this.destroyed = false;
+ this.onPassword = null;
+ this.onProgress = null;
+ this.onUnsupportedFeature = null;
+ }
-Object.defineProperty(exports, "__esModule", ({
- value: true
-}));
-exports.isNodeJS = void 0;
-const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
-exports.isNodeJS = isNodeJS;
+ get promise() {
+ return this._capability.promise;
+ }
-/***/ }),
-/* 5 */
-/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
+ async destroy() {
+ this.destroyed = true;
+ await this._transport?.destroy();
+ this._transport = null;
+ if (this._worker) {
+ this._worker.destroy();
+ this._worker = null;
+ }
+ }
-Object.defineProperty(exports, "__esModule", ({
- value: true
-}));
-exports.BaseStandardFontDataFactory = exports.BaseSVGFactory = exports.BaseCanvasFactory = exports.BaseCMapReaderFactory = void 0;
+}
-var _util = __w_pdfjs_require__(2);
+exports.PDFDocumentLoadingTask = PDFDocumentLoadingTask;
-class BaseCanvasFactory {
- constructor() {
- if (this.constructor === BaseCanvasFactory) {
- (0, _util.unreachable)("Cannot initialize BaseCanvasFactory.");
- }
+class PDFDataRangeTransport {
+ constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {
+ this.length = length;
+ this.initialData = initialData;
+ this.progressiveDone = progressiveDone;
+ this.contentDispositionFilename = contentDispositionFilename;
+ this._rangeListeners = [];
+ this._progressListeners = [];
+ this._progressiveReadListeners = [];
+ this._progressiveDoneListeners = [];
+ this._readyCapability = (0, _util.createPromiseCapability)();
}
- create(width, height) {
- if (width <= 0 || height <= 0) {
- throw new Error("Invalid canvas size");
- }
+ addRangeListener(listener) {
+ this._rangeListeners.push(listener);
+ }
- const canvas = this._createCanvas(width, height);
+ addProgressListener(listener) {
+ this._progressListeners.push(listener);
+ }
- return {
- canvas,
- context: canvas.getContext("2d")
- };
+ addProgressiveReadListener(listener) {
+ this._progressiveReadListeners.push(listener);
}
- reset(canvasAndContext, width, height) {
- if (!canvasAndContext.canvas) {
- throw new Error("Canvas is not specified");
- }
+ addProgressiveDoneListener(listener) {
+ this._progressiveDoneListeners.push(listener);
+ }
- if (width <= 0 || height <= 0) {
- throw new Error("Invalid canvas size");
+ onDataRange(begin, chunk) {
+ for (const listener of this._rangeListeners) {
+ listener(begin, chunk);
}
-
- canvasAndContext.canvas.width = width;
- canvasAndContext.canvas.height = height;
}
- destroy(canvasAndContext) {
- if (!canvasAndContext.canvas) {
- throw new Error("Canvas is not specified");
- }
+ onDataProgress(loaded, total) {
+ this._readyCapability.promise.then(() => {
+ for (const listener of this._progressListeners) {
+ listener(loaded, total);
+ }
+ });
+ }
- canvasAndContext.canvas.width = 0;
- canvasAndContext.canvas.height = 0;
- canvasAndContext.canvas = null;
- canvasAndContext.context = null;
+ onDataProgressiveRead(chunk) {
+ this._readyCapability.promise.then(() => {
+ for (const listener of this._progressiveReadListeners) {
+ listener(chunk);
+ }
+ });
}
- _createCanvas(width, height) {
- (0, _util.unreachable)("Abstract method `_createCanvas` called.");
+ onDataProgressiveDone() {
+ this._readyCapability.promise.then(() => {
+ for (const listener of this._progressiveDoneListeners) {
+ listener();
+ }
+ });
}
-}
+ transportReady() {
+ this._readyCapability.resolve();
+ }
-exports.BaseCanvasFactory = BaseCanvasFactory;
+ requestDataRange(begin, end) {
+ (0, _util.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange");
+ }
-class BaseCMapReaderFactory {
- constructor({
- baseUrl = null,
- isCompressed = false
- }) {
- if (this.constructor === BaseCMapReaderFactory) {
- (0, _util.unreachable)("Cannot initialize BaseCMapReaderFactory.");
- }
+ abort() {}
- this.baseUrl = baseUrl;
- this.isCompressed = isCompressed;
- }
+}
- async fetch({
- name
- }) {
- if (!this.baseUrl) {
- throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.');
- }
+exports.PDFDataRangeTransport = PDFDataRangeTransport;
- if (!name) {
- throw new Error("CMap name must be specified.");
- }
+class PDFDocumentProxy {
+ constructor(pdfInfo, transport) {
+ this._pdfInfo = pdfInfo;
+ this._transport = transport;
+ Object.defineProperty(this, "fingerprint", {
+ get() {
+ (0, _display_utils.deprecated)("`PDFDocumentProxy.fingerprint`, " + "please use `PDFDocumentProxy.fingerprints` instead.");
+ return this.fingerprints[0];
+ }
- const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
- const compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE;
- return this._fetchData(url, compressionType).catch(reason => {
- throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
+ });
+ Object.defineProperty(this, "getStats", {
+ value: async () => {
+ (0, _display_utils.deprecated)("`PDFDocumentProxy.getStats`, " + "please use the `PDFDocumentProxy.stats`-getter instead.");
+ return this.stats || {
+ streamTypes: {},
+ fontTypes: {}
+ };
+ }
});
}
- _fetchData(url, compressionType) {
- (0, _util.unreachable)("Abstract method `_fetchData` called.");
+ get annotationStorage() {
+ return this._transport.annotationStorage;
}
-}
+ get numPages() {
+ return this._pdfInfo.numPages;
+ }
-exports.BaseCMapReaderFactory = BaseCMapReaderFactory;
+ get fingerprints() {
+ return this._pdfInfo.fingerprints;
+ }
-class BaseStandardFontDataFactory {
- constructor({
- baseUrl = null
- }) {
- if (this.constructor === BaseStandardFontDataFactory) {
- (0, _util.unreachable)("Cannot initialize BaseStandardFontDataFactory.");
- }
+ get stats() {
+ return this._transport.stats;
+ }
- this.baseUrl = baseUrl;
+ get isPureXfa() {
+ return !!this._transport._htmlForXfa;
}
- async fetch({
- filename
- }) {
- if (!this.baseUrl) {
- throw new Error('The standard font "baseUrl" parameter must be specified, ensure that ' + 'the "standardFontDataUrl" API parameter is provided.');
- }
+ get allXfaHtml() {
+ return this._transport._htmlForXfa;
+ }
- if (!filename) {
- throw new Error("Font filename must be specified.");
- }
+ getPage(pageNumber) {
+ return this._transport.getPage(pageNumber);
+ }
- const url = `${this.baseUrl}${filename}`;
- return this._fetchData(url).catch(reason => {
- throw new Error(`Unable to load font data at: ${url}`);
- });
+ getPageIndex(ref) {
+ return this._transport.getPageIndex(ref);
}
- _fetchData(url) {
- (0, _util.unreachable)("Abstract method `_fetchData` called.");
+ getDestinations() {
+ return this._transport.getDestinations();
}
-}
+ getDestination(id) {
+ return this._transport.getDestination(id);
+ }
-exports.BaseStandardFontDataFactory = BaseStandardFontDataFactory;
+ getPageLabels() {
+ return this._transport.getPageLabels();
+ }
-class BaseSVGFactory {
- constructor() {
- if (this.constructor === BaseSVGFactory) {
- (0, _util.unreachable)("Cannot initialize BaseSVGFactory.");
- }
+ getPageLayout() {
+ return this._transport.getPageLayout();
}
- create(width, height) {
- if (width <= 0 || height <= 0) {
- throw new Error("Invalid SVG dimensions");
- }
+ getPageMode() {
+ return this._transport.getPageMode();
+ }
- const svg = this._createSVG("svg:svg");
+ getViewerPreferences() {
+ return this._transport.getViewerPreferences();
+ }
- svg.setAttribute("version", "1.1");
- svg.setAttribute("width", `${width}px`);
- svg.setAttribute("height", `${height}px`);
- svg.setAttribute("preserveAspectRatio", "none");
- svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
- return svg;
+ getOpenAction() {
+ return this._transport.getOpenAction();
}
- createElement(type) {
- if (typeof type !== "string") {
- throw new Error("Invalid SVG element type");
- }
+ getAttachments() {
+ return this._transport.getAttachments();
+ }
- return this._createSVG(type);
+ getJavaScript() {
+ return this._transport.getJavaScript();
}
- _createSVG(type) {
- (0, _util.unreachable)("Abstract method `_createSVG` called.");
+ getJSActions() {
+ return this._transport.getDocJSActions();
}
-}
+ getOutline() {
+ return this._transport.getOutline();
+ }
-exports.BaseSVGFactory = BaseSVGFactory;
+ getOptionalContentConfig() {
+ return this._transport.getOptionalContentConfig();
+ }
-/***/ }),
-/* 6 */
-/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
+ getPermissions() {
+ return this._transport.getPermissions();
+ }
+ getMetadata() {
+ return this._transport.getMetadata();
+ }
+ getMarkInfo() {
+ return this._transport.getMarkInfo();
+ }
-Object.defineProperty(exports, "__esModule", ({
- value: true
-}));
-exports.build = exports.RenderTask = exports.PDFWorker = exports.PDFPageProxy = exports.PDFDocumentProxy = exports.PDFDocumentLoadingTask = exports.PDFDataRangeTransport = exports.LoopbackPort = exports.DefaultStandardFontDataFactory = exports.DefaultCanvasFactory = exports.DefaultCMapReaderFactory = void 0;
-exports.getDocument = getDocument;
-exports.setPDFNetworkStreamFactory = setPDFNetworkStreamFactory;
-exports.version = void 0;
+ getData() {
+ return this._transport.getData();
+ }
-var _util = __w_pdfjs_require__(2);
+ getDownloadInfo() {
+ return this._transport.downloadInfoCapability.promise;
+ }
-var _display_utils = __w_pdfjs_require__(1);
+ cleanup(keepLoadedFonts = false) {
+ return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);
+ }
-var _font_loader = __w_pdfjs_require__(7);
+ destroy() {
+ return this.loadingTask.destroy();
+ }
-var _node_utils = __w_pdfjs_require__(8);
+ get loadingParams() {
+ return this._transport.loadingParams;
+ }
-var _annotation_storage = __w_pdfjs_require__(9);
+ get loadingTask() {
+ return this._transport.loadingTask;
+ }
-var _canvas = __w_pdfjs_require__(10);
+ saveDocument() {
+ if (this._transport.annotationStorage.size <= 0) {
+ (0, _display_utils.deprecated)("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead.");
+ }
-var _worker_options = __w_pdfjs_require__(12);
+ return this._transport.saveDocument();
+ }
-var _is_node = __w_pdfjs_require__(4);
+ getFieldObjects() {
+ return this._transport.getFieldObjects();
+ }
-var _message_handler = __w_pdfjs_require__(13);
+ hasJSActions() {
+ return this._transport.hasJSActions();
+ }
-var _metadata = __w_pdfjs_require__(14);
+ getCalculationOrderIds() {
+ return this._transport.getCalculationOrderIds();
+ }
-var _optional_content_config = __w_pdfjs_require__(15);
+}
-var _transport_stream = __w_pdfjs_require__(16);
+exports.PDFDocumentProxy = PDFDocumentProxy;
-var _xfa_text = __w_pdfjs_require__(17);
+class PDFPageProxy {
+ constructor(pageIndex, pageInfo, transport, ownerDocument, pdfBug = false) {
+ this._pageIndex = pageIndex;
+ this._pageInfo = pageInfo;
+ this._ownerDocument = ownerDocument;
+ this._transport = transport;
+ this._stats = pdfBug ? new _display_utils.StatTimer() : null;
+ this._pdfBug = pdfBug;
+ this.commonObjs = transport.commonObjs;
+ this.objs = new PDFObjects();
+ this._bitmaps = new Set();
+ this.cleanupAfterRender = false;
+ this.pendingCleanup = false;
+ this._intentStates = new Map();
+ this._annotationPromises = new Map();
+ this.destroyed = false;
+ }
-const DEFAULT_RANGE_CHUNK_SIZE = 65536;
-const RENDERING_CANCELLED_TIMEOUT = 100;
-const DefaultCanvasFactory = _is_node.isNodeJS ? _node_utils.NodeCanvasFactory : _display_utils.DOMCanvasFactory;
-exports.DefaultCanvasFactory = DefaultCanvasFactory;
-const DefaultCMapReaderFactory = _is_node.isNodeJS ? _node_utils.NodeCMapReaderFactory : _display_utils.DOMCMapReaderFactory;
-exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory;
-const DefaultStandardFontDataFactory = _is_node.isNodeJS ? _node_utils.NodeStandardFontDataFactory : _display_utils.DOMStandardFontDataFactory;
-exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory;
-let createPDFNetworkStream;
+ get pageNumber() {
+ return this._pageIndex + 1;
+ }
-function setPDFNetworkStreamFactory(pdfNetworkStreamFactory) {
- createPDFNetworkStream = pdfNetworkStreamFactory;
-}
+ get rotate() {
+ return this._pageInfo.rotate;
+ }
-function getDocument(src) {
- const task = new PDFDocumentLoadingTask();
- let source;
+ get ref() {
+ return this._pageInfo.ref;
+ }
- if (typeof src === "string" || src instanceof URL) {
- source = {
- url: src
- };
- } else if ((0, _util.isArrayBuffer)(src)) {
- source = {
- data: src
- };
- } else if (src instanceof PDFDataRangeTransport) {
- source = {
- range: src
- };
- } else {
- if (typeof src !== "object") {
- throw new Error("Invalid parameter in getDocument, " + "need either string, URL, Uint8Array, or parameter object.");
- }
+ get userUnit() {
+ return this._pageInfo.userUnit;
+ }
- if (!src.url && !src.data && !src.range) {
- throw new Error("Invalid parameter object: need either .data, .range or .url");
- }
+ get view() {
+ return this._pageInfo.view;
+ }
- source = src;
+ getViewport({
+ scale,
+ rotation = this.rotate,
+ offsetX = 0,
+ offsetY = 0,
+ dontFlip = false
+ } = {}) {
+ return new _display_utils.PageViewport({
+ viewBox: this.view,
+ scale,
+ rotation,
+ offsetX,
+ offsetY,
+ dontFlip
+ });
}
- const params = Object.create(null);
- let rangeTransport = null,
- worker = null;
+ getAnnotations({
+ intent = "display"
+ } = {}) {
+ const intentArgs = this._transport.getRenderingIntent(intent);
- for (const key in source) {
- const value = source[key];
+ let promise = this._annotationPromises.get(intentArgs.cacheKey);
- switch (key) {
- case "url":
- if (typeof window !== "undefined") {
- try {
- params[key] = new URL(value, window.location).href;
- continue;
- } catch (ex) {
- (0, _util.warn)(`Cannot create valid URL: "${ex}".`);
- }
- } else if (typeof value === "string" || value instanceof URL) {
- params[key] = value.toString();
- continue;
- }
+ if (!promise) {
+ promise = this._transport.getAnnotations(this._pageIndex, intentArgs.renderingIntent);
- throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property.");
+ this._annotationPromises.set(intentArgs.cacheKey, promise);
- case "range":
- rangeTransport = value;
- continue;
+ promise = promise.then(annotations => {
+ for (const annotation of annotations) {
+ if (annotation.titleObj !== undefined) {
+ Object.defineProperty(annotation, "title", {
+ get() {
+ (0, _display_utils.deprecated)("`title`-property on annotation, please use `titleObj` instead.");
+ return annotation.titleObj.str;
+ }
- case "worker":
- worker = value;
- continue;
+ });
+ }
- case "data":
- if (_is_node.isNodeJS && typeof Buffer !== "undefined" && value instanceof Buffer) {
- params[key] = new Uint8Array(value);
- } else if (value instanceof Uint8Array) {
- break;
- } else if (typeof value === "string") {
- params[key] = (0, _util.stringToBytes)(value);
- } else if (typeof value === "object" && value !== null && !isNaN(value.length)) {
- params[key] = new Uint8Array(value);
- } else if ((0, _util.isArrayBuffer)(value)) {
- params[key] = new Uint8Array(value);
- } else {
- throw new Error("Invalid PDF binary data: either typed array, " + "string, or array-like object is expected in the data property.");
+ if (annotation.contentsObj !== undefined) {
+ Object.defineProperty(annotation, "contents", {
+ get() {
+ (0, _display_utils.deprecated)("`contents`-property on annotation, please use `contentsObj` instead.");
+ return annotation.contentsObj.str;
+ }
+
+ });
+ }
}
- continue;
+ return annotations;
+ });
}
- params[key] = value;
+ return promise;
}
- params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;
- params.CMapReaderFactory = params.CMapReaderFactory || DefaultCMapReaderFactory;
- params.StandardFontDataFactory = params.StandardFontDataFactory || DefaultStandardFontDataFactory;
- params.ignoreErrors = params.stopAtErrors !== true;
- params.fontExtraProperties = params.fontExtraProperties === true;
- params.pdfBug = params.pdfBug === true;
- params.enableXfa = params.enableXfa === true;
-
- if (typeof params.docBaseUrl !== "string" || (0, _display_utils.isDataScheme)(params.docBaseUrl)) {
- params.docBaseUrl = null;
+ getJSActions() {
+ return this._jsActionsPromise ||= this._transport.getPageJSActions(this._pageIndex);
}
- if (!Number.isInteger(params.maxImageSize)) {
- params.maxImageSize = -1;
+ async getXfa() {
+ return this._transport._htmlForXfa?.children[this._pageIndex] || null;
}
- if (typeof params.useWorkerFetch !== "boolean") {
- params.useWorkerFetch = params.CMapReaderFactory === _display_utils.DOMCMapReaderFactory && params.StandardFontDataFactory === _display_utils.DOMStandardFontDataFactory;
- }
+ render({
+ canvasContext,
+ viewport,
+ intent = "display",
+ annotationMode = _util.AnnotationMode.ENABLE,
+ transform = null,
+ imageLayer = null,
+ canvasFactory = null,
+ background = null,
+ optionalContentConfigPromise = null,
+ annotationCanvasMap = null,
+ pageColors = null
+ }) {
+ if (arguments[0]?.renderInteractiveForms !== undefined) {
+ (0, _display_utils.deprecated)("render no longer accepts the `renderInteractiveForms`-option, " + "please use the `annotationMode`-option instead.");
- if (typeof params.isEvalSupported !== "boolean") {
- params.isEvalSupported = true;
- }
+ if (arguments[0].renderInteractiveForms === true && annotationMode === _util.AnnotationMode.ENABLE) {
+ annotationMode = _util.AnnotationMode.ENABLE_FORMS;
+ }
+ }
- if (typeof params.disableFontFace !== "boolean") {
- params.disableFontFace = _is_node.isNodeJS;
- }
+ if (arguments[0]?.includeAnnotationStorage !== undefined) {
+ (0, _display_utils.deprecated)("render no longer accepts the `includeAnnotationStorage`-option, " + "please use the `annotationMode`-option instead.");
- if (typeof params.useSystemFonts !== "boolean") {
- params.useSystemFonts = !_is_node.isNodeJS && !params.disableFontFace;
- }
+ if (arguments[0].includeAnnotationStorage === true && annotationMode === _util.AnnotationMode.ENABLE) {
+ annotationMode = _util.AnnotationMode.ENABLE_STORAGE;
+ }
+ }
- if (typeof params.ownerDocument === "undefined") {
- params.ownerDocument = globalThis.document;
- }
+ if (this._stats) {
+ this._stats.time("Overall");
+ }
- if (typeof params.disableRange !== "boolean") {
- params.disableRange = false;
- }
+ const intentArgs = this._transport.getRenderingIntent(intent, annotationMode);
- if (typeof params.disableStream !== "boolean") {
- params.disableStream = false;
- }
+ this.pendingCleanup = false;
- if (typeof params.disableAutoFetch !== "boolean") {
- params.disableAutoFetch = false;
- }
+ if (!optionalContentConfigPromise) {
+ optionalContentConfigPromise = this._transport.getOptionalContentConfig();
+ }
- (0, _util.setVerbosityLevel)(params.verbosity);
+ let intentState = this._intentStates.get(intentArgs.cacheKey);
- if (!worker) {
- const workerParams = {
- verbosity: params.verbosity,
- port: _worker_options.GlobalWorkerOptions.workerPort
- };
- worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams);
- task._worker = worker;
- }
+ if (!intentState) {
+ intentState = Object.create(null);
- const docId = task.docId;
- worker.promise.then(function () {
- if (task.destroyed) {
- throw new Error("Loading aborted");
+ this._intentStates.set(intentArgs.cacheKey, intentState);
}
- const workerIdPromise = _fetchDocument(worker, params, rangeTransport, docId);
+ if (intentState.streamReaderCancelTimeout) {
+ clearTimeout(intentState.streamReaderCancelTimeout);
+ intentState.streamReaderCancelTimeout = null;
+ }
- const networkStreamPromise = new Promise(function (resolve) {
- let networkStream;
+ const canvasFactoryInstance = canvasFactory || new DefaultCanvasFactory({
+ ownerDocument: this._ownerDocument
+ });
+ const intentPrint = !!(intentArgs.renderingIntent & _util.RenderingIntentFlag.PRINT);
- if (rangeTransport) {
- networkStream = new _transport_stream.PDFDataTransportStream({
- length: params.length,
- initialData: params.initialData,
- progressiveDone: params.progressiveDone,
- contentDispositionFilename: params.contentDispositionFilename,
- disableRange: params.disableRange,
- disableStream: params.disableStream
- }, rangeTransport);
- } else if (!params.data) {
- networkStream = createPDFNetworkStream({
- url: params.url,
- length: params.length,
- httpHeaders: params.httpHeaders,
- withCredentials: params.withCredentials,
- rangeChunkSize: params.rangeChunkSize,
- disableRange: params.disableRange,
- disableStream: params.disableStream
- });
- }
+ if (!intentState.displayReadyCapability) {
+ intentState.displayReadyCapability = (0, _util.createPromiseCapability)();
+ intentState.operatorList = {
+ fnArray: [],
+ argsArray: [],
+ lastChunk: false
+ };
- resolve(networkStream);
- });
- return Promise.all([workerIdPromise, networkStreamPromise]).then(function ([workerId, networkStream]) {
- if (task.destroyed) {
- throw new Error("Loading aborted");
+ if (this._stats) {
+ this._stats.time("Page Request");
}
- const messageHandler = new _message_handler.MessageHandler(docId, workerId, worker.port);
- const transport = new WorkerTransport(messageHandler, task, networkStream, params);
- task._transport = transport;
- messageHandler.send("Ready", null);
- });
- }).catch(task._capability.reject);
- return task;
-}
+ this._pumpOperatorList(intentArgs);
+ }
-async function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
- if (worker.destroyed) {
- throw new Error("Worker was destroyed");
- }
+ const complete = error => {
+ intentState.renderTasks.delete(internalRenderTask);
- if (pdfDataRangeTransport) {
- source.length = pdfDataRangeTransport.length;
- source.initialData = pdfDataRangeTransport.initialData;
- source.progressiveDone = pdfDataRangeTransport.progressiveDone;
- source.contentDispositionFilename = pdfDataRangeTransport.contentDispositionFilename;
- }
+ if (this.cleanupAfterRender || intentPrint) {
+ this.pendingCleanup = true;
+ }
- const workerId = await worker.messageHandler.sendWithPromise("GetDocRequest", {
- docId,
- apiVersion: '2.12.313',
- source: {
- data: source.data,
- url: source.url,
- password: source.password,
- disableAutoFetch: source.disableAutoFetch,
- rangeChunkSize: source.rangeChunkSize,
- length: source.length
- },
- maxImageSize: source.maxImageSize,
- disableFontFace: source.disableFontFace,
- docBaseUrl: source.docBaseUrl,
- ignoreErrors: source.ignoreErrors,
- isEvalSupported: source.isEvalSupported,
- fontExtraProperties: source.fontExtraProperties,
- enableXfa: source.enableXfa,
- useSystemFonts: source.useSystemFonts,
- cMapUrl: source.useWorkerFetch ? source.cMapUrl : null,
- standardFontDataUrl: source.useWorkerFetch ? source.standardFontDataUrl : null
- });
+ this._tryCleanup();
- if (worker.destroyed) {
- throw new Error("Worker was destroyed");
- }
+ if (error) {
+ internalRenderTask.capability.reject(error);
- return workerId;
-}
+ this._abortOperatorList({
+ intentState,
+ reason: error instanceof Error ? error : new Error(error)
+ });
+ } else {
+ internalRenderTask.capability.resolve();
+ }
-class PDFDocumentLoadingTask {
- static get idCounters() {
- return (0, _util.shadow)(this, "idCounters", {
- doc: 0
+ if (this._stats) {
+ this._stats.timeEnd("Rendering");
+
+ this._stats.timeEnd("Overall");
+ }
+ };
+
+ const internalRenderTask = new InternalRenderTask({
+ callback: complete,
+ params: {
+ canvasContext,
+ viewport,
+ transform,
+ imageLayer,
+ background
+ },
+ objs: this.objs,
+ commonObjs: this.commonObjs,
+ annotationCanvasMap,
+ operatorList: intentState.operatorList,
+ pageIndex: this._pageIndex,
+ canvasFactory: canvasFactoryInstance,
+ useRequestAnimationFrame: !intentPrint,
+ pdfBug: this._pdfBug,
+ pageColors
});
- }
+ (intentState.renderTasks ||= new Set()).add(internalRenderTask);
+ const renderTask = internalRenderTask.task;
+ Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
+ if (this.pendingCleanup) {
+ complete();
+ return;
+ }
- constructor() {
- this._capability = (0, _util.createPromiseCapability)();
- this._transport = null;
- this._worker = null;
- this.docId = `d${PDFDocumentLoadingTask.idCounters.doc++}`;
- this.destroyed = false;
- this.onPassword = null;
- this.onProgress = null;
- this.onUnsupportedFeature = null;
+ if (this._stats) {
+ this._stats.time("Rendering");
+ }
+
+ internalRenderTask.initializeGraphics({
+ transparency,
+ optionalContentConfig
+ });
+ internalRenderTask.operatorListChanged();
+ }).catch(complete);
+ return renderTask;
}
- get promise() {
- return this._capability.promise;
- }
+ getOperatorList({
+ intent = "display",
+ annotationMode = _util.AnnotationMode.ENABLE
+ } = {}) {
+ function operatorListChanged() {
+ if (intentState.operatorList.lastChunk) {
+ intentState.opListReadCapability.resolve(intentState.operatorList);
+ intentState.renderTasks.delete(opListTask);
+ }
+ }
+
+ const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, true);
- async destroy() {
- this.destroyed = true;
- await this._transport?.destroy();
- this._transport = null;
+ let intentState = this._intentStates.get(intentArgs.cacheKey);
- if (this._worker) {
- this._worker.destroy();
+ if (!intentState) {
+ intentState = Object.create(null);
- this._worker = null;
+ this._intentStates.set(intentArgs.cacheKey, intentState);
}
- }
-}
+ let opListTask;
-exports.PDFDocumentLoadingTask = PDFDocumentLoadingTask;
+ if (!intentState.opListReadCapability) {
+ opListTask = Object.create(null);
+ opListTask.operatorListChanged = operatorListChanged;
+ intentState.opListReadCapability = (0, _util.createPromiseCapability)();
+ (intentState.renderTasks ||= new Set()).add(opListTask);
+ intentState.operatorList = {
+ fnArray: [],
+ argsArray: [],
+ lastChunk: false
+ };
-class PDFDataRangeTransport {
- constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {
- this.length = length;
- this.initialData = initialData;
- this.progressiveDone = progressiveDone;
- this.contentDispositionFilename = contentDispositionFilename;
- this._rangeListeners = [];
- this._progressListeners = [];
- this._progressiveReadListeners = [];
- this._progressiveDoneListeners = [];
- this._readyCapability = (0, _util.createPromiseCapability)();
- }
+ if (this._stats) {
+ this._stats.time("Page Request");
+ }
- addRangeListener(listener) {
- this._rangeListeners.push(listener);
- }
+ this._pumpOperatorList(intentArgs);
+ }
- addProgressListener(listener) {
- this._progressListeners.push(listener);
+ return intentState.opListReadCapability.promise;
}
- addProgressiveReadListener(listener) {
- this._progressiveReadListeners.push(listener);
- }
+ streamTextContent({
+ disableCombineTextItems = false,
+ includeMarkedContent = false
+ } = {}) {
+ const TEXT_CONTENT_CHUNK_SIZE = 100;
+ return this._transport.messageHandler.sendWithStream("GetTextContent", {
+ pageIndex: this._pageIndex,
+ combineTextItems: disableCombineTextItems !== true,
+ includeMarkedContent: includeMarkedContent === true
+ }, {
+ highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
- addProgressiveDoneListener(listener) {
- this._progressiveDoneListeners.push(listener);
+ size(textContent) {
+ return textContent.items.length;
+ }
+
+ });
}
- onDataRange(begin, chunk) {
- for (const listener of this._rangeListeners) {
- listener(begin, chunk);
+ getTextContent(params = {}) {
+ if (this._transport._htmlForXfa) {
+ return this.getXfa().then(xfa => {
+ return _xfa_text.XfaText.textContent(xfa);
+ });
}
- }
- onDataProgress(loaded, total) {
- this._readyCapability.promise.then(() => {
- for (const listener of this._progressListeners) {
- listener(loaded, total);
+ const readableStream = this.streamTextContent(params);
+ return new Promise(function (resolve, reject) {
+ function pump() {
+ reader.read().then(function ({
+ value,
+ done
+ }) {
+ if (done) {
+ resolve(textContent);
+ return;
+ }
+
+ Object.assign(textContent.styles, value.styles);
+ textContent.items.push(...value.items);
+ pump();
+ }, reject);
}
+
+ const reader = readableStream.getReader();
+ const textContent = {
+ items: [],
+ styles: Object.create(null)
+ };
+ pump();
});
}
- onDataProgressiveRead(chunk) {
- this._readyCapability.promise.then(() => {
- for (const listener of this._progressiveReadListeners) {
- listener(chunk);
- }
- });
+ getStructTree() {
+ return this._structTreePromise ||= this._transport.getStructTree(this._pageIndex);
}
- onDataProgressiveDone() {
- this._readyCapability.promise.then(() => {
- for (const listener of this._progressiveDoneListeners) {
- listener();
+ _destroy() {
+ this.destroyed = true;
+ const waitOn = [];
+
+ for (const intentState of this._intentStates.values()) {
+ this._abortOperatorList({
+ intentState,
+ reason: new Error("Page was destroyed."),
+ force: true
+ });
+
+ if (intentState.opListReadCapability) {
+ continue;
}
- });
- }
- transportReady() {
- this._readyCapability.resolve();
+ for (const internalRenderTask of intentState.renderTasks) {
+ waitOn.push(internalRenderTask.completed);
+ internalRenderTask.cancel();
+ }
+ }
+
+ this.objs.clear();
+
+ for (const bitmap of this._bitmaps) {
+ bitmap.close();
+ }
+
+ this._bitmaps.clear();
+
+ this._annotationPromises.clear();
+
+ this._jsActionsPromise = null;
+ this._structTreePromise = null;
+ this.pendingCleanup = false;
+ return Promise.all(waitOn);
}
- requestDataRange(begin, end) {
- (0, _util.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange");
+ cleanup(resetStats = false) {
+ this.pendingCleanup = true;
+ return this._tryCleanup(resetStats);
}
- abort() {}
+ _tryCleanup(resetStats = false) {
+ if (!this.pendingCleanup) {
+ return false;
+ }
-}
+ for (const {
+ renderTasks,
+ operatorList
+ } of this._intentStates.values()) {
+ if (renderTasks.size > 0 || !operatorList.lastChunk) {
+ return false;
+ }
+ }
-exports.PDFDataRangeTransport = PDFDataRangeTransport;
+ this._intentStates.clear();
-class PDFDocumentProxy {
- constructor(pdfInfo, transport) {
- this._pdfInfo = pdfInfo;
- this._transport = transport;
- Object.defineProperty(this, "fingerprint", {
- get() {
- (0, _display_utils.deprecated)("`PDFDocumentProxy.fingerprint`, " + "please use `PDFDocumentProxy.fingerprints` instead.");
- return this.fingerprints[0];
- }
+ this.objs.clear();
- });
- Object.defineProperty(this, "getStats", {
- value: async () => {
- (0, _display_utils.deprecated)("`PDFDocumentProxy.getStats`, " + "please use the `PDFDocumentProxy.stats`-getter instead.");
- return this.stats || {
- streamTypes: {},
- fontTypes: {}
- };
- }
- });
- }
+ this._annotationPromises.clear();
- get annotationStorage() {
- return this._transport.annotationStorage;
- }
+ this._jsActionsPromise = null;
+ this._structTreePromise = null;
- get numPages() {
- return this._pdfInfo.numPages;
- }
+ if (resetStats && this._stats) {
+ this._stats = new _display_utils.StatTimer();
+ }
- get fingerprints() {
- return this._pdfInfo.fingerprints;
- }
+ for (const bitmap of this._bitmaps) {
+ bitmap.close();
+ }
- get stats() {
- return this._transport.stats;
- }
+ this._bitmaps.clear();
- get isPureXfa() {
- return !!this._transport._htmlForXfa;
+ this.pendingCleanup = false;
+ return true;
}
- get allXfaHtml() {
- return this._transport._htmlForXfa;
- }
+ _startRenderPage(transparency, cacheKey) {
+ const intentState = this._intentStates.get(cacheKey);
- getPage(pageNumber) {
- return this._transport.getPage(pageNumber);
- }
+ if (!intentState) {
+ return;
+ }
- getPageIndex(ref) {
- return this._transport.getPageIndex(ref);
- }
+ if (this._stats) {
+ this._stats.timeEnd("Page Request");
+ }
- getDestinations() {
- return this._transport.getDestinations();
+ if (intentState.displayReadyCapability) {
+ intentState.displayReadyCapability.resolve(transparency);
+ }
}
- getDestination(id) {
- return this._transport.getDestination(id);
- }
+ _renderPageChunk(operatorListChunk, intentState) {
+ for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {
+ intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
+ intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
+ }
+
+ intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
+
+ for (const internalRenderTask of intentState.renderTasks) {
+ internalRenderTask.operatorListChanged();
+ }
- getPageLabels() {
- return this._transport.getPageLabels();
+ if (operatorListChunk.lastChunk) {
+ this._tryCleanup();
+ }
}
- getPageLayout() {
- return this._transport.getPageLayout();
- }
+ _pumpOperatorList({
+ renderingIntent,
+ cacheKey
+ }) {
+ const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", {
+ pageIndex: this._pageIndex,
+ intent: renderingIntent,
+ cacheKey,
+ annotationStorage: renderingIntent & _util.RenderingIntentFlag.ANNOTATIONS_STORAGE ? this._transport.annotationStorage.serializable : null
+ });
- getPageMode() {
- return this._transport.getPageMode();
- }
+ const reader = readableStream.getReader();
- getViewerPreferences() {
- return this._transport.getViewerPreferences();
- }
+ const intentState = this._intentStates.get(cacheKey);
- getOpenAction() {
- return this._transport.getOpenAction();
- }
+ intentState.streamReader = reader;
- getAttachments() {
- return this._transport.getAttachments();
- }
+ const pump = () => {
+ reader.read().then(({
+ value,
+ done
+ }) => {
+ if (done) {
+ intentState.streamReader = null;
+ return;
+ }
- getJavaScript() {
- return this._transport.getJavaScript();
- }
+ if (this._transport.destroyed) {
+ return;
+ }
- getJSActions() {
- return this._transport.getDocJSActions();
- }
+ this._renderPageChunk(value, intentState);
- getOutline() {
- return this._transport.getOutline();
- }
+ pump();
+ }, reason => {
+ intentState.streamReader = null;
- getOptionalContentConfig() {
- return this._transport.getOptionalContentConfig();
- }
+ if (this._transport.destroyed) {
+ return;
+ }
- getPermissions() {
- return this._transport.getPermissions();
- }
+ if (intentState.operatorList) {
+ intentState.operatorList.lastChunk = true;
- getMetadata() {
- return this._transport.getMetadata();
- }
+ for (const internalRenderTask of intentState.renderTasks) {
+ internalRenderTask.operatorListChanged();
+ }
- getMarkInfo() {
- return this._transport.getMarkInfo();
- }
+ this._tryCleanup();
+ }
- getData() {
- return this._transport.getData();
- }
+ if (intentState.displayReadyCapability) {
+ intentState.displayReadyCapability.reject(reason);
+ } else if (intentState.opListReadCapability) {
+ intentState.opListReadCapability.reject(reason);
+ } else {
+ throw reason;
+ }
+ });
+ };
- getDownloadInfo() {
- return this._transport.downloadInfoCapability.promise;
+ pump();
}
- cleanup(keepLoadedFonts = false) {
- return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);
- }
+ _abortOperatorList({
+ intentState,
+ reason,
+ force = false
+ }) {
+ if (!intentState.streamReader) {
+ return;
+ }
- destroy() {
- return this.loadingTask.destroy();
- }
+ if (!force) {
+ if (intentState.renderTasks.size > 0) {
+ return;
+ }
- get loadingParams() {
- return this._transport.loadingParams;
- }
+ if (reason instanceof _display_utils.RenderingCancelledException) {
+ intentState.streamReaderCancelTimeout = setTimeout(() => {
+ this._abortOperatorList({
+ intentState,
+ reason,
+ force: true
+ });
- get loadingTask() {
- return this._transport.loadingTask;
- }
+ intentState.streamReaderCancelTimeout = null;
+ }, RENDERING_CANCELLED_TIMEOUT);
+ return;
+ }
+ }
- saveDocument() {
- if (this._transport.annotationStorage.size <= 0) {
- (0, _display_utils.deprecated)("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead.");
+ intentState.streamReader.cancel(new _util.AbortException(reason.message)).catch(() => {});
+ intentState.streamReader = null;
+
+ if (this._transport.destroyed) {
+ return;
}
- return this._transport.saveDocument();
- }
+ for (const [curCacheKey, curIntentState] of this._intentStates) {
+ if (curIntentState === intentState) {
+ this._intentStates.delete(curCacheKey);
- getFieldObjects() {
- return this._transport.getFieldObjects();
- }
+ break;
+ }
+ }
- hasJSActions() {
- return this._transport.hasJSActions();
+ this.cleanup();
}
- getCalculationOrderIds() {
- return this._transport.getCalculationOrderIds();
+ get stats() {
+ return this._stats;
}
}
-exports.PDFDocumentProxy = PDFDocumentProxy;
+exports.PDFPageProxy = PDFPageProxy;
-class PDFPageProxy {
- constructor(pageIndex, pageInfo, transport, ownerDocument, pdfBug = false) {
- this._pageIndex = pageIndex;
- this._pageInfo = pageInfo;
- this._ownerDocument = ownerDocument;
- this._transport = transport;
- this._stats = pdfBug ? new _display_utils.StatTimer() : null;
- this._pdfBug = pdfBug;
- this.commonObjs = transport.commonObjs;
- this.objs = new PDFObjects();
- this.cleanupAfterRender = false;
- this.pendingCleanup = false;
- this._intentStates = new Map();
- this._annotationPromises = new Map();
- this.destroyed = false;
+class LoopbackPort {
+ constructor() {
+ this._listeners = [];
+ this._deferred = Promise.resolve();
}
- get pageNumber() {
- return this._pageIndex + 1;
- }
+ postMessage(obj, transfers) {
+ const event = {
+ data: structuredClone(obj, transfers)
+ };
- get rotate() {
- return this._pageInfo.rotate;
+ this._deferred.then(() => {
+ for (const listener of this._listeners) {
+ listener.call(this, event);
+ }
+ });
}
- get ref() {
- return this._pageInfo.ref;
+ addEventListener(name, listener) {
+ this._listeners.push(listener);
}
- get userUnit() {
- return this._pageInfo.userUnit;
+ removeEventListener(name, listener) {
+ const i = this._listeners.indexOf(listener);
+
+ this._listeners.splice(i, 1);
}
- get view() {
- return this._pageInfo.view;
+ terminate() {
+ this._listeners.length = 0;
}
- getViewport({
- scale,
- rotation = this.rotate,
- offsetX = 0,
- offsetY = 0,
- dontFlip = false
- } = {}) {
- return new _display_utils.PageViewport({
- viewBox: this.view,
- scale,
- rotation,
- offsetX,
- offsetY,
- dontFlip
- });
+}
+
+exports.LoopbackPort = LoopbackPort;
+const PDFWorkerUtil = {
+ isWorkerDisabled: false,
+ fallbackWorkerSrc: null,
+ fakeWorkerId: 0
+};
+exports.PDFWorkerUtil = PDFWorkerUtil;
+{
+ if (_is_node.isNodeJS && typeof require === "function") {
+ PDFWorkerUtil.isWorkerDisabled = true;
+ PDFWorkerUtil.fallbackWorkerSrc = "./pdf.worker.js";
+ } else if (typeof document === "object") {
+ const pdfjsFilePath = document?.currentScript?.src;
+
+ if (pdfjsFilePath) {
+ PDFWorkerUtil.fallbackWorkerSrc = pdfjsFilePath.replace(/(\.(?:min\.)?js)(\?.*)?$/i, ".worker$1$2");
+ }
}
- getAnnotations({
- intent = "display"
- } = {}) {
- const intentArgs = this._transport.getRenderingIntent(intent);
+ PDFWorkerUtil.isSameOrigin = function (baseUrl, otherUrl) {
+ let base;
- let promise = this._annotationPromises.get(intentArgs.cacheKey);
+ try {
+ base = new URL(baseUrl);
- if (!promise) {
- promise = this._transport.getAnnotations(this._pageIndex, intentArgs.renderingIntent);
+ if (!base.origin || base.origin === "null") {
+ return false;
+ }
+ } catch (e) {
+ return false;
+ }
+
+ const other = new URL(otherUrl, base);
+ return base.origin === other.origin;
+ };
+
+ PDFWorkerUtil.createCDNWrapper = function (url) {
+ const wrapper = `importScripts("${url}");`;
+ return URL.createObjectURL(new Blob([wrapper]));
+ };
+}
- this._annotationPromises.set(intentArgs.cacheKey, promise);
+class PDFWorker {
+ static #workerPorts = new WeakMap();
- promise = promise.then(annotations => {
- for (const annotation of annotations) {
- if (annotation.titleObj !== undefined) {
- Object.defineProperty(annotation, "title", {
- get() {
- (0, _display_utils.deprecated)("`title`-property on annotation, please use `titleObj` instead.");
- return annotation.titleObj.str;
- }
+ constructor({
+ name = null,
+ port = null,
+ verbosity = (0, _util.getVerbosityLevel)()
+ } = {}) {
+ if (port && PDFWorker.#workerPorts.has(port)) {
+ throw new Error("Cannot use more than one PDFWorker per port.");
+ }
- });
- }
+ this.name = name;
+ this.destroyed = false;
+ this.verbosity = verbosity;
+ this._readyCapability = (0, _util.createPromiseCapability)();
+ this._port = null;
+ this._webWorker = null;
+ this._messageHandler = null;
- if (annotation.contentsObj !== undefined) {
- Object.defineProperty(annotation, "contents", {
- get() {
- (0, _display_utils.deprecated)("`contents`-property on annotation, please use `contentsObj` instead.");
- return annotation.contentsObj.str;
- }
+ if (port) {
+ PDFWorker.#workerPorts.set(port, this);
- });
- }
- }
+ this._initializeFromPort(port);
- return annotations;
- });
+ return;
}
- return promise;
+ this._initialize();
}
- getJSActions() {
- return this._jsActionsPromise ||= this._transport.getPageJSActions(this._pageIndex);
+ get promise() {
+ return this._readyCapability.promise;
}
- async getXfa() {
- return this._transport._htmlForXfa?.children[this._pageIndex] || null;
+ get port() {
+ return this._port;
}
- render({
- canvasContext,
- viewport,
- intent = "display",
- annotationMode = _util.AnnotationMode.ENABLE,
- transform = null,
- imageLayer = null,
- canvasFactory = null,
- background = null,
- optionalContentConfigPromise = null,
- annotationCanvasMap = null
- }) {
- if (arguments[0]?.renderInteractiveForms !== undefined) {
- (0, _display_utils.deprecated)("render no longer accepts the `renderInteractiveForms`-option, " + "please use the `annotationMode`-option instead.");
-
- if (arguments[0].renderInteractiveForms === true && annotationMode === _util.AnnotationMode.ENABLE) {
- annotationMode = _util.AnnotationMode.ENABLE_FORMS;
- }
- }
-
- if (arguments[0]?.includeAnnotationStorage !== undefined) {
- (0, _display_utils.deprecated)("render no longer accepts the `includeAnnotationStorage`-option, " + "please use the `annotationMode`-option instead.");
-
- if (arguments[0].includeAnnotationStorage === true && annotationMode === _util.AnnotationMode.ENABLE) {
- annotationMode = _util.AnnotationMode.ENABLE_STORAGE;
- }
- }
+ get messageHandler() {
+ return this._messageHandler;
+ }
- if (this._stats) {
- this._stats.time("Overall");
- }
+ _initializeFromPort(port) {
+ this._port = port;
+ this._messageHandler = new _message_handler.MessageHandler("main", "worker", port);
- const intentArgs = this._transport.getRenderingIntent(intent, annotationMode);
+ this._messageHandler.on("ready", function () {});
- this.pendingCleanup = false;
+ this._readyCapability.resolve();
+ }
- if (!optionalContentConfigPromise) {
- optionalContentConfigPromise = this._transport.getOptionalContentConfig();
- }
+ _initialize() {
+ if (typeof Worker !== "undefined" && !PDFWorkerUtil.isWorkerDisabled && !PDFWorker._mainThreadWorkerMessageHandler) {
+ let workerSrc = PDFWorker.workerSrc;
- let intentState = this._intentStates.get(intentArgs.cacheKey);
+ try {
+ if (!PDFWorkerUtil.isSameOrigin(window.location.href, workerSrc)) {
+ workerSrc = PDFWorkerUtil.createCDNWrapper(new URL(workerSrc, window.location).href);
+ }
- if (!intentState) {
- intentState = Object.create(null);
+ const worker = new Worker(workerSrc);
+ const messageHandler = new _message_handler.MessageHandler("main", "worker", worker);
- this._intentStates.set(intentArgs.cacheKey, intentState);
- }
+ const terminateEarly = () => {
+ worker.removeEventListener("error", onWorkerError);
+ messageHandler.destroy();
+ worker.terminate();
- if (intentState.streamReaderCancelTimeout) {
- clearTimeout(intentState.streamReaderCancelTimeout);
- intentState.streamReaderCancelTimeout = null;
- }
+ if (this.destroyed) {
+ this._readyCapability.reject(new Error("Worker was destroyed"));
+ } else {
+ this._setupFakeWorker();
+ }
+ };
- const canvasFactoryInstance = canvasFactory || new DefaultCanvasFactory({
- ownerDocument: this._ownerDocument
- });
- const intentPrint = !!(intentArgs.renderingIntent & _util.RenderingIntentFlag.PRINT);
+ const onWorkerError = () => {
+ if (!this._webWorker) {
+ terminateEarly();
+ }
+ };
- if (!intentState.displayReadyCapability) {
- intentState.displayReadyCapability = (0, _util.createPromiseCapability)();
- intentState.operatorList = {
- fnArray: [],
- argsArray: [],
- lastChunk: false
- };
+ worker.addEventListener("error", onWorkerError);
+ messageHandler.on("test", data => {
+ worker.removeEventListener("error", onWorkerError);
- if (this._stats) {
- this._stats.time("Page Request");
- }
+ if (this.destroyed) {
+ terminateEarly();
+ return;
+ }
- this._pumpOperatorList(intentArgs);
- }
+ if (data) {
+ this._messageHandler = messageHandler;
+ this._port = worker;
+ this._webWorker = worker;
- const complete = error => {
- intentState.renderTasks.delete(internalRenderTask);
+ this._readyCapability.resolve();
- if (this.cleanupAfterRender || intentPrint) {
- this.pendingCleanup = true;
- }
+ messageHandler.send("configure", {
+ verbosity: this.verbosity
+ });
+ } else {
+ this._setupFakeWorker();
- this._tryCleanup();
+ messageHandler.destroy();
+ worker.terminate();
+ }
+ });
+ messageHandler.on("ready", data => {
+ worker.removeEventListener("error", onWorkerError);
- if (error) {
- internalRenderTask.capability.reject(error);
+ if (this.destroyed) {
+ terminateEarly();
+ return;
+ }
- this._abortOperatorList({
- intentState,
- reason: error instanceof Error ? error : new Error(error)
+ try {
+ sendTest();
+ } catch (e) {
+ this._setupFakeWorker();
+ }
});
- } else {
- internalRenderTask.capability.resolve();
- }
-
- if (this._stats) {
- this._stats.timeEnd("Rendering");
- this._stats.timeEnd("Overall");
- }
- };
+ const sendTest = () => {
+ const testObj = new Uint8Array();
+ messageHandler.send("test", testObj, [testObj.buffer]);
+ };
- const internalRenderTask = new InternalRenderTask({
- callback: complete,
- params: {
- canvasContext,
- viewport,
- transform,
- imageLayer,
- background
- },
- objs: this.objs,
- commonObjs: this.commonObjs,
- annotationCanvasMap,
- operatorList: intentState.operatorList,
- pageIndex: this._pageIndex,
- canvasFactory: canvasFactoryInstance,
- useRequestAnimationFrame: !intentPrint,
- pdfBug: this._pdfBug
- });
- (intentState.renderTasks ||= new Set()).add(internalRenderTask);
- const renderTask = internalRenderTask.task;
- Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
- if (this.pendingCleanup) {
- complete();
+ sendTest();
return;
+ } catch (e) {
+ (0, _util.info)("The worker has been disabled.");
}
+ }
- if (this._stats) {
- this._stats.time("Rendering");
- }
-
- internalRenderTask.initializeGraphics({
- transparency,
- optionalContentConfig
- });
- internalRenderTask.operatorListChanged();
- }).catch(complete);
- return renderTask;
+ this._setupFakeWorker();
}
- getOperatorList({
- intent = "display",
- annotationMode = _util.AnnotationMode.ENABLE
- } = {}) {
- function operatorListChanged() {
- if (intentState.operatorList.lastChunk) {
- intentState.opListReadCapability.resolve(intentState.operatorList);
- intentState.renderTasks.delete(opListTask);
- }
+ _setupFakeWorker() {
+ if (!PDFWorkerUtil.isWorkerDisabled) {
+ (0, _util.warn)("Setting up fake worker.");
+ PDFWorkerUtil.isWorkerDisabled = true;
}
- const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, true);
+ PDFWorker._setupFakeWorkerGlobal.then(WorkerMessageHandler => {
+ if (this.destroyed) {
+ this._readyCapability.reject(new Error("Worker was destroyed"));
+
+ return;
+ }
+
+ const port = new LoopbackPort();
+ this._port = port;
+ const id = `fake${PDFWorkerUtil.fakeWorkerId++}`;
+ const workerHandler = new _message_handler.MessageHandler(id + "_worker", id, port);
+ WorkerMessageHandler.setup(workerHandler, port);
+ const messageHandler = new _message_handler.MessageHandler(id, id + "_worker", port);
+ this._messageHandler = messageHandler;
- let intentState = this._intentStates.get(intentArgs.cacheKey);
+ this._readyCapability.resolve();
- if (!intentState) {
- intentState = Object.create(null);
+ messageHandler.send("configure", {
+ verbosity: this.verbosity
+ });
+ }).catch(reason => {
+ this._readyCapability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`));
+ });
+ }
- this._intentStates.set(intentArgs.cacheKey, intentState);
+ destroy() {
+ this.destroyed = true;
+
+ if (this._webWorker) {
+ this._webWorker.terminate();
+
+ this._webWorker = null;
}
- let opListTask;
+ PDFWorker.#workerPorts.delete(this._port);
+ this._port = null;
- if (!intentState.opListReadCapability) {
- opListTask = Object.create(null);
- opListTask.operatorListChanged = operatorListChanged;
- intentState.opListReadCapability = (0, _util.createPromiseCapability)();
- (intentState.renderTasks ||= new Set()).add(opListTask);
- intentState.operatorList = {
- fnArray: [],
- argsArray: [],
- lastChunk: false
- };
+ if (this._messageHandler) {
+ this._messageHandler.destroy();
- if (this._stats) {
- this._stats.time("Page Request");
- }
+ this._messageHandler = null;
+ }
+ }
- this._pumpOperatorList(intentArgs);
+ static fromPort(params) {
+ if (!params?.port) {
+ throw new Error("PDFWorker.fromPort - invalid method signature.");
}
- return intentState.opListReadCapability.promise;
+ if (this.#workerPorts.has(params.port)) {
+ return this.#workerPorts.get(params.port);
+ }
+
+ return new PDFWorker(params);
}
- streamTextContent({
- normalizeWhitespace = false,
- disableCombineTextItems = false,
- includeMarkedContent = false
- } = {}) {
- const TEXT_CONTENT_CHUNK_SIZE = 100;
- return this._transport.messageHandler.sendWithStream("GetTextContent", {
- pageIndex: this._pageIndex,
- normalizeWhitespace: normalizeWhitespace === true,
- combineTextItems: disableCombineTextItems !== true,
- includeMarkedContent: includeMarkedContent === true
- }, {
- highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
+ static get workerSrc() {
+ if (_worker_options.GlobalWorkerOptions.workerSrc) {
+ return _worker_options.GlobalWorkerOptions.workerSrc;
+ }
- size(textContent) {
- return textContent.items.length;
+ if (PDFWorkerUtil.fallbackWorkerSrc !== null) {
+ if (!_is_node.isNodeJS) {
+ (0, _display_utils.deprecated)('No "GlobalWorkerOptions.workerSrc" specified.');
}
- });
+ return PDFWorkerUtil.fallbackWorkerSrc;
+ }
+
+ throw new Error('No "GlobalWorkerOptions.workerSrc" specified.');
}
- getTextContent(params = {}) {
- if (this._transport._htmlForXfa) {
- return this.getXfa().then(xfa => {
- return _xfa_text.XfaText.textContent(xfa);
- });
+ static get _mainThreadWorkerMessageHandler() {
+ try {
+ return globalThis.pdfjsWorker?.WorkerMessageHandler || null;
+ } catch (ex) {
+ return null;
}
+ }
- const readableStream = this.streamTextContent(params);
- return new Promise(function (resolve, reject) {
- function pump() {
- reader.read().then(function ({
- value,
- done
- }) {
- if (done) {
- resolve(textContent);
- return;
- }
+ static get _setupFakeWorkerGlobal() {
+ const loader = async () => {
+ const mainWorkerMessageHandler = this._mainThreadWorkerMessageHandler;
- Object.assign(textContent.styles, value.styles);
- textContent.items.push(...value.items);
- pump();
- }, reject);
+ if (mainWorkerMessageHandler) {
+ return mainWorkerMessageHandler;
}
- const reader = readableStream.getReader();
- const textContent = {
- items: [],
- styles: Object.create(null)
- };
- pump();
- });
- }
+ if (_is_node.isNodeJS && typeof require === "function") {
+ const worker = eval("require")(this.workerSrc);
+ return worker.WorkerMessageHandler;
+ }
- getStructTree() {
- return this._structTreePromise ||= this._transport.getStructTree(this._pageIndex);
+ await (0, _display_utils.loadScript)(this.workerSrc);
+ return window.pdfjsWorker.WorkerMessageHandler;
+ };
+
+ return (0, _util.shadow)(this, "_setupFakeWorkerGlobal", loader());
}
- _destroy() {
- this.destroyed = true;
- const waitOn = [];
+}
- for (const intentState of this._intentStates.values()) {
- this._abortOperatorList({
- intentState,
- reason: new Error("Page was destroyed."),
- force: true
- });
+exports.PDFWorker = PDFWorker;
+{
+ PDFWorker.getWorkerSrc = function () {
+ (0, _display_utils.deprecated)("`PDFWorker.getWorkerSrc()`, please use `PDFWorker.workerSrc` instead.");
+ return this.workerSrc;
+ };
+}
- if (intentState.opListReadCapability) {
- continue;
- }
+class WorkerTransport {
+ #docStats = null;
+ #pageCache = new Map();
+ #pagePromises = new Map();
+ #metadataPromise = null;
- for (const internalRenderTask of intentState.renderTasks) {
- waitOn.push(internalRenderTask.completed);
- internalRenderTask.cancel();
- }
- }
+ constructor(messageHandler, loadingTask, networkStream, params) {
+ this.messageHandler = messageHandler;
+ this.loadingTask = loadingTask;
+ this.commonObjs = new PDFObjects();
+ this.fontLoader = new _font_loader.FontLoader({
+ docId: loadingTask.docId,
+ onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
+ ownerDocument: params.ownerDocument,
+ styleElement: params.styleElement
+ });
+ this._params = params;
- this.objs.clear();
+ if (!params.useWorkerFetch) {
+ this.CMapReaderFactory = new params.CMapReaderFactory({
+ baseUrl: params.cMapUrl,
+ isCompressed: params.cMapPacked
+ });
+ this.StandardFontDataFactory = new params.StandardFontDataFactory({
+ baseUrl: params.standardFontDataUrl
+ });
+ }
- this._annotationPromises.clear();
+ this.destroyed = false;
+ this.destroyCapability = null;
+ this._passwordCapability = null;
+ this._networkStream = networkStream;
+ this._fullReader = null;
+ this._lastProgress = null;
+ this.downloadInfoCapability = (0, _util.createPromiseCapability)();
+ this.setupMessageHandler();
+ }
- this._jsActionsPromise = null;
- this._structTreePromise = null;
- this.pendingCleanup = false;
- return Promise.all(waitOn);
+ get annotationStorage() {
+ return (0, _util.shadow)(this, "annotationStorage", new _annotation_storage.AnnotationStorage());
}
- cleanup(resetStats = false) {
- this.pendingCleanup = true;
- return this._tryCleanup(resetStats);
+ get stats() {
+ return this.#docStats;
}
- _tryCleanup(resetStats = false) {
- if (!this.pendingCleanup) {
- return false;
- }
+ getRenderingIntent(intent, annotationMode = _util.AnnotationMode.ENABLE, isOpList = false) {
+ let renderingIntent = _util.RenderingIntentFlag.DISPLAY;
+ let annotationHash = "";
- for (const {
- renderTasks,
- operatorList
- } of this._intentStates.values()) {
- if (renderTasks.size > 0 || !operatorList.lastChunk) {
- return false;
- }
- }
+ switch (intent) {
+ case "any":
+ renderingIntent = _util.RenderingIntentFlag.ANY;
+ break;
- this._intentStates.clear();
+ case "display":
+ break;
- this.objs.clear();
+ case "print":
+ renderingIntent = _util.RenderingIntentFlag.PRINT;
+ break;
- this._annotationPromises.clear();
+ default:
+ (0, _util.warn)(`getRenderingIntent - invalid intent: ${intent}`);
+ }
- this._jsActionsPromise = null;
- this._structTreePromise = null;
+ switch (annotationMode) {
+ case _util.AnnotationMode.DISABLE:
+ renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_DISABLE;
+ break;
- if (resetStats && this._stats) {
- this._stats = new _display_utils.StatTimer();
- }
+ case _util.AnnotationMode.ENABLE:
+ break;
- this.pendingCleanup = false;
- return true;
- }
+ case _util.AnnotationMode.ENABLE_FORMS:
+ renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_FORMS;
+ break;
- _startRenderPage(transparency, cacheKey) {
- const intentState = this._intentStates.get(cacheKey);
+ case _util.AnnotationMode.ENABLE_STORAGE:
+ renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_STORAGE;
+ annotationHash = this.annotationStorage.hash;
+ break;
- if (!intentState) {
- return;
+ default:
+ (0, _util.warn)(`getRenderingIntent - invalid annotationMode: ${annotationMode}`);
}
- if (this._stats) {
- this._stats.timeEnd("Page Request");
+ if (isOpList) {
+ renderingIntent += _util.RenderingIntentFlag.OPLIST;
}
- if (intentState.displayReadyCapability) {
- intentState.displayReadyCapability.resolve(transparency);
- }
+ return {
+ renderingIntent,
+ cacheKey: `${renderingIntent}_${annotationHash}`
+ };
}
- _renderPageChunk(operatorListChunk, intentState) {
- for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {
- intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
- intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
+ destroy() {
+ if (this.destroyCapability) {
+ return this.destroyCapability.promise;
}
- intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
+ this.destroyed = true;
+ this.destroyCapability = (0, _util.createPromiseCapability)();
- for (const internalRenderTask of intentState.renderTasks) {
- internalRenderTask.operatorListChanged();
+ if (this._passwordCapability) {
+ this._passwordCapability.reject(new Error("Worker was destroyed during onPassword callback"));
}
- if (operatorListChunk.lastChunk) {
- this._tryCleanup();
+ const waitOn = [];
+
+ for (const page of this.#pageCache.values()) {
+ waitOn.push(page._destroy());
}
- }
- _pumpOperatorList({
- renderingIntent,
- cacheKey
- }) {
- const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", {
- pageIndex: this._pageIndex,
- intent: renderingIntent,
- cacheKey,
- annotationStorage: renderingIntent & _util.RenderingIntentFlag.ANNOTATIONS_STORAGE ? this._transport.annotationStorage.serializable : null
- });
+ this.#pageCache.clear();
+ this.#pagePromises.clear();
- const reader = readableStream.getReader();
+ if (this.hasOwnProperty("annotationStorage")) {
+ this.annotationStorage.resetModified();
+ }
- const intentState = this._intentStates.get(cacheKey);
+ const terminated = this.messageHandler.sendWithPromise("Terminate", null);
+ waitOn.push(terminated);
+ Promise.all(waitOn).then(() => {
+ this.commonObjs.clear();
+ this.fontLoader.clear();
+ this.#metadataPromise = null;
+ this._getFieldObjectsPromise = null;
+ this._hasJSActionsPromise = null;
- intentState.streamReader = reader;
+ if (this._networkStream) {
+ this._networkStream.cancelAllRequests(new _util.AbortException("Worker was terminated."));
+ }
- const pump = () => {
- reader.read().then(({
- value,
- done
- }) => {
- if (done) {
- intentState.streamReader = null;
- return;
- }
+ if (this.messageHandler) {
+ this.messageHandler.destroy();
+ this.messageHandler = null;
+ }
- if (this._transport.destroyed) {
- return;
- }
+ this.destroyCapability.resolve();
+ }, this.destroyCapability.reject);
+ return this.destroyCapability.promise;
+ }
- this._renderPageChunk(value, intentState);
+ setupMessageHandler() {
+ const {
+ messageHandler,
+ loadingTask
+ } = this;
+ messageHandler.on("GetReader", (data, sink) => {
+ (0, _util.assert)(this._networkStream, "GetReader - no `IPDFStream` instance available.");
+ this._fullReader = this._networkStream.getFullReader();
- pump();
- }, reason => {
- intentState.streamReader = null;
+ this._fullReader.onProgress = evt => {
+ this._lastProgress = {
+ loaded: evt.loaded,
+ total: evt.total
+ };
+ };
- if (this._transport.destroyed) {
- return;
- }
+ sink.onPull = () => {
+ this._fullReader.read().then(function ({
+ value,
+ done
+ }) {
+ if (done) {
+ sink.close();
+ return;
+ }
- if (intentState.operatorList) {
- intentState.operatorList.lastChunk = true;
+ (0, _util.assert)((0, _util.isArrayBuffer)(value), "GetReader - expected an ArrayBuffer.");
+ sink.enqueue(new Uint8Array(value), 1, [value]);
+ }).catch(reason => {
+ sink.error(reason);
+ });
+ };
- for (const internalRenderTask of intentState.renderTasks) {
- internalRenderTask.operatorListChanged();
+ sink.onCancel = reason => {
+ this._fullReader.cancel(reason);
+
+ sink.ready.catch(readyReason => {
+ if (this.destroyed) {
+ return;
}
- this._tryCleanup();
- }
+ throw readyReason;
+ });
+ };
+ });
+ messageHandler.on("ReaderHeadersReady", data => {
+ const headersCapability = (0, _util.createPromiseCapability)();
+ const fullReader = this._fullReader;
+ fullReader.headersReady.then(() => {
+ if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) {
+ if (this._lastProgress) {
+ loadingTask.onProgress?.(this._lastProgress);
+ }
- if (intentState.displayReadyCapability) {
- intentState.displayReadyCapability.reject(reason);
- } else if (intentState.opListReadCapability) {
- intentState.opListReadCapability.reject(reason);
- } else {
- throw reason;
+ fullReader.onProgress = evt => {
+ loadingTask.onProgress?.({
+ loaded: evt.loaded,
+ total: evt.total
+ });
+ };
}
- });
- };
- pump();
- }
+ headersCapability.resolve({
+ isStreamingSupported: fullReader.isStreamingSupported,
+ isRangeSupported: fullReader.isRangeSupported,
+ contentLength: fullReader.contentLength
+ });
+ }, headersCapability.reject);
+ return headersCapability.promise;
+ });
+ messageHandler.on("GetRangeReader", (data, sink) => {
+ (0, _util.assert)(this._networkStream, "GetRangeReader - no `IPDFStream` instance available.");
- _abortOperatorList({
- intentState,
- reason,
- force = false
- }) {
- if (!intentState.streamReader) {
- return;
- }
+ const rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
- if (!force) {
- if (intentState.renderTasks.size > 0) {
+ if (!rangeReader) {
+ sink.close();
return;
}
- if (reason instanceof _display_utils.RenderingCancelledException) {
- intentState.streamReaderCancelTimeout = setTimeout(() => {
- this._abortOperatorList({
- intentState,
- reason,
- force: true
- });
+ sink.onPull = () => {
+ rangeReader.read().then(function ({
+ value,
+ done
+ }) {
+ if (done) {
+ sink.close();
+ return;
+ }
- intentState.streamReaderCancelTimeout = null;
- }, RENDERING_CANCELLED_TIMEOUT);
- return;
- }
- }
+ (0, _util.assert)((0, _util.isArrayBuffer)(value), "GetRangeReader - expected an ArrayBuffer.");
+ sink.enqueue(new Uint8Array(value), 1, [value]);
+ }).catch(reason => {
+ sink.error(reason);
+ });
+ };
- intentState.streamReader.cancel(new _util.AbortException(reason.message)).catch(() => {});
- intentState.streamReader = null;
+ sink.onCancel = reason => {
+ rangeReader.cancel(reason);
+ sink.ready.catch(readyReason => {
+ if (this.destroyed) {
+ return;
+ }
- if (this._transport.destroyed) {
- return;
- }
+ throw readyReason;
+ });
+ };
+ });
+ messageHandler.on("GetDoc", ({
+ pdfInfo
+ }) => {
+ this._numPages = pdfInfo.numPages;
+ this._htmlForXfa = pdfInfo.htmlForXfa;
+ delete pdfInfo.htmlForXfa;
- for (const [curCacheKey, curIntentState] of this._intentStates) {
- if (curIntentState === intentState) {
- this._intentStates.delete(curCacheKey);
+ loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
+ });
+ messageHandler.on("DocException", function (ex) {
+ let reason;
- break;
- }
- }
+ switch (ex.name) {
+ case "PasswordException":
+ reason = new _util.PasswordException(ex.message, ex.code);
+ break;
- this.cleanup();
- }
+ case "InvalidPDFException":
+ reason = new _util.InvalidPDFException(ex.message);
+ break;
+
+ case "MissingPDFException":
+ reason = new _util.MissingPDFException(ex.message);
+ break;
+
+ case "UnexpectedResponseException":
+ reason = new _util.UnexpectedResponseException(ex.message, ex.status);
+ break;
+
+ case "UnknownErrorException":
+ reason = new _util.UnknownErrorException(ex.message, ex.details);
+ break;
- get stats() {
- return this._stats;
- }
+ default:
+ (0, _util.unreachable)("DocException - expected a valid Error.");
+ }
-}
+ loadingTask._capability.reject(reason);
+ });
+ messageHandler.on("PasswordRequest", exception => {
+ this._passwordCapability = (0, _util.createPromiseCapability)();
-exports.PDFPageProxy = PDFPageProxy;
+ if (loadingTask.onPassword) {
+ const updatePassword = password => {
+ if (password instanceof Error) {
+ this._passwordCapability.reject(password);
+ } else {
+ this._passwordCapability.resolve({
+ password
+ });
+ }
+ };
-class LoopbackPort {
- constructor() {
- this._listeners = [];
- this._deferred = Promise.resolve();
- }
+ try {
+ loadingTask.onPassword(updatePassword, exception.code);
+ } catch (ex) {
+ this._passwordCapability.reject(ex);
+ }
+ } else {
+ this._passwordCapability.reject(new _util.PasswordException(exception.message, exception.code));
+ }
- postMessage(obj, transfers) {
- function cloneValue(object) {
- if (globalThis.structuredClone) {
- return globalThis.structuredClone(object, transfers);
+ return this._passwordCapability.promise;
+ });
+ messageHandler.on("DataLoaded", data => {
+ loadingTask.onProgress?.({
+ loaded: data.length,
+ total: data.length
+ });
+ this.downloadInfoCapability.resolve(data);
+ });
+ messageHandler.on("StartRenderPage", data => {
+ if (this.destroyed) {
+ return;
}
- function fallbackCloneValue(value) {
- if (typeof value === "function" || typeof value === "symbol" || value instanceof URL) {
- throw new Error(`LoopbackPort.postMessage - cannot clone: ${value?.toString()}`);
- }
+ const page = this.#pageCache.get(data.pageIndex);
- if (typeof value !== "object" || value === null) {
- return value;
- }
+ page._startRenderPage(data.transparency, data.cacheKey);
+ });
+ messageHandler.on("commonobj", ([id, type, exportedData]) => {
+ if (this.destroyed) {
+ return;
+ }
- if (cloned.has(value)) {
- return cloned.get(value);
- }
+ if (this.commonObjs.has(id)) {
+ return;
+ }
- let buffer, result;
+ switch (type) {
+ case "Font":
+ const params = this._params;
- if ((buffer = value.buffer) && (0, _util.isArrayBuffer)(buffer)) {
- if (transfers?.includes(buffer)) {
- result = new value.constructor(buffer, value.byteOffset, value.byteLength);
- } else {
- result = new value.constructor(value);
+ if ("error" in exportedData) {
+ const exportedError = exportedData.error;
+ (0, _util.warn)(`Error during font loading: ${exportedError}`);
+ this.commonObjs.resolve(id, exportedError);
+ break;
}
- cloned.set(value, result);
- return result;
- }
+ let fontRegistry = null;
- if (value instanceof Map) {
- result = new Map();
- cloned.set(value, result);
+ if (params.pdfBug && globalThis.FontInspector?.enabled) {
+ fontRegistry = {
+ registerFont(font, url) {
+ globalThis.FontInspector.fontAdded(font, url);
+ }
- for (const [key, val] of value) {
- result.set(key, fallbackCloneValue(val));
+ };
}
- return result;
- }
+ const font = new _font_loader.FontFaceObject(exportedData, {
+ isEvalSupported: params.isEvalSupported,
+ disableFontFace: params.disableFontFace,
+ ignoreErrors: params.ignoreErrors,
+ onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
+ fontRegistry
+ });
+ this.fontLoader.bind(font).catch(reason => {
+ return messageHandler.sendWithPromise("FontFallback", {
+ id
+ });
+ }).finally(() => {
+ if (!params.fontExtraProperties && font.data) {
+ font.data = null;
+ }
+
+ this.commonObjs.resolve(id, font);
+ });
+ break;
- if (value instanceof Set) {
- result = new Set();
- cloned.set(value, result);
+ case "FontPath":
+ case "Image":
+ this.commonObjs.resolve(id, exportedData);
+ break;
- for (const val of value) {
- result.add(fallbackCloneValue(val));
- }
+ default:
+ throw new Error(`Got unknown common object type ${type}`);
+ }
+ });
+ messageHandler.on("obj", ([id, pageIndex, type, imageData]) => {
+ if (this.destroyed) {
+ return;
+ }
- return result;
- }
+ const pageProxy = this.#pageCache.get(pageIndex);
- result = Array.isArray(value) ? [] : Object.create(null);
- cloned.set(value, result);
+ if (pageProxy.objs.has(id)) {
+ return;
+ }
- for (const i in value) {
- let desc,
- p = value;
+ switch (type) {
+ case "Image":
+ pageProxy.objs.resolve(id, imageData);
+ const MAX_IMAGE_SIZE_TO_STORE = 8000000;
- while (!(desc = Object.getOwnPropertyDescriptor(p, i))) {
- p = Object.getPrototypeOf(p);
- }
+ if (imageData) {
+ let length;
- if (typeof desc.value === "undefined") {
- continue;
- }
+ if (imageData.bitmap) {
+ const {
+ bitmap,
+ width,
+ height
+ } = imageData;
+ length = width * height * 4;
+
+ pageProxy._bitmaps.add(bitmap);
+ } else {
+ length = imageData.data?.length || 0;
+ }
- if (typeof desc.value === "function" && !value.hasOwnProperty?.(i)) {
- continue;
+ if (length > MAX_IMAGE_SIZE_TO_STORE) {
+ pageProxy.cleanupAfterRender = true;
+ }
}
- result[i] = fallbackCloneValue(desc.value);
- }
+ break;
- return result;
+ case "Pattern":
+ pageProxy.objs.resolve(id, imageData);
+ break;
+
+ default:
+ throw new Error(`Got unknown object type ${type}`);
+ }
+ });
+ messageHandler.on("DocProgress", data => {
+ if (this.destroyed) {
+ return;
}
- const cloned = new WeakMap();
- return fallbackCloneValue(object);
- }
+ loadingTask.onProgress?.({
+ loaded: data.loaded,
+ total: data.total
+ });
+ });
+ messageHandler.on("DocStats", data => {
+ if (this.destroyed) {
+ return;
+ }
- const event = {
- data: cloneValue(obj)
- };
+ this.#docStats = Object.freeze({
+ streamTypes: Object.freeze(data.streamTypes),
+ fontTypes: Object.freeze(data.fontTypes)
+ });
+ });
+ messageHandler.on("UnsupportedFeature", this._onUnsupportedFeature.bind(this));
+ messageHandler.on("FetchBuiltInCMap", data => {
+ if (this.destroyed) {
+ return Promise.reject(new Error("Worker was destroyed."));
+ }
- this._deferred.then(() => {
- for (const listener of this._listeners) {
- listener.call(this, event);
+ if (!this.CMapReaderFactory) {
+ return Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."));
}
+
+ return this.CMapReaderFactory.fetch(data);
});
- }
+ messageHandler.on("FetchStandardFontData", data => {
+ if (this.destroyed) {
+ return Promise.reject(new Error("Worker was destroyed."));
+ }
- addEventListener(name, listener) {
- this._listeners.push(listener);
+ if (!this.StandardFontDataFactory) {
+ return Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."));
+ }
+
+ return this.StandardFontDataFactory.fetch(data);
+ });
}
- removeEventListener(name, listener) {
- const i = this._listeners.indexOf(listener);
+ _onUnsupportedFeature({
+ featureId
+ }) {
+ if (this.destroyed) {
+ return;
+ }
- this._listeners.splice(i, 1);
+ this.loadingTask.onUnsupportedFeature?.(featureId);
}
- terminate() {
- this._listeners.length = 0;
+ getData() {
+ return this.messageHandler.sendWithPromise("GetData", null);
}
-}
-
-exports.LoopbackPort = LoopbackPort;
-const PDFWorkerUtil = {
- isWorkerDisabled: false,
- fallbackWorkerSrc: null,
- fakeWorkerId: 0
-};
-{
- if (_is_node.isNodeJS && typeof require === "function") {
- PDFWorkerUtil.isWorkerDisabled = true;
- PDFWorkerUtil.fallbackWorkerSrc = "./pdf.worker.js";
- } else if (typeof document === "object") {
- const pdfjsFilePath = document?.currentScript?.src;
-
- if (pdfjsFilePath) {
- PDFWorkerUtil.fallbackWorkerSrc = pdfjsFilePath.replace(/(\.(?:min\.)?js)(\?.*)?$/i, ".worker$1$2");
+ getPage(pageNumber) {
+ if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
+ return Promise.reject(new Error("Invalid page request."));
}
- }
-
- PDFWorkerUtil.createCDNWrapper = function (url) {
- const wrapper = `importScripts("${url}");`;
- return URL.createObjectURL(new Blob([wrapper]));
- };
-}
-class PDFWorker {
- static get _workerPorts() {
- return (0, _util.shadow)(this, "_workerPorts", new WeakMap());
- }
+ const pageIndex = pageNumber - 1,
+ cachedPromise = this.#pagePromises.get(pageIndex);
- constructor({
- name = null,
- port = null,
- verbosity = (0, _util.getVerbosityLevel)()
- } = {}) {
- if (port && PDFWorker._workerPorts.has(port)) {
- throw new Error("Cannot use more than one PDFWorker per port.");
+ if (cachedPromise) {
+ return cachedPromise;
}
- this.name = name;
- this.destroyed = false;
- this.verbosity = verbosity;
- this._readyCapability = (0, _util.createPromiseCapability)();
- this._port = null;
- this._webWorker = null;
- this._messageHandler = null;
-
- if (port) {
- PDFWorker._workerPorts.set(port, this);
+ const promise = this.messageHandler.sendWithPromise("GetPage", {
+ pageIndex
+ }).then(pageInfo => {
+ if (this.destroyed) {
+ throw new Error("Transport destroyed");
+ }
- this._initializeFromPort(port);
+ const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.ownerDocument, this._params.pdfBug);
+ this.#pageCache.set(pageIndex, page);
+ return page;
+ });
+ this.#pagePromises.set(pageIndex, promise);
+ return promise;
+ }
- return;
+ getPageIndex(ref) {
+ if (typeof ref !== "object" || ref === null || !Number.isInteger(ref.num) || ref.num < 0 || !Number.isInteger(ref.gen) || ref.gen < 0) {
+ return Promise.reject(new Error("Invalid pageIndex request."));
}
- this._initialize();
+ return this.messageHandler.sendWithPromise("GetPageIndex", {
+ num: ref.num,
+ gen: ref.gen
+ });
}
- get promise() {
- return this._readyCapability.promise;
+ getAnnotations(pageIndex, intent) {
+ return this.messageHandler.sendWithPromise("GetAnnotations", {
+ pageIndex,
+ intent
+ });
}
- get port() {
- return this._port;
+ saveDocument() {
+ return this.messageHandler.sendWithPromise("SaveDocument", {
+ isPureXfa: !!this._htmlForXfa,
+ numPages: this._numPages,
+ annotationStorage: this.annotationStorage.serializable,
+ filename: this._fullReader?.filename ?? null
+ }).finally(() => {
+ this.annotationStorage.resetModified();
+ });
}
- get messageHandler() {
- return this._messageHandler;
+ getFieldObjects() {
+ return this._getFieldObjectsPromise ||= this.messageHandler.sendWithPromise("GetFieldObjects", null);
}
- _initializeFromPort(port) {
- this._port = port;
- this._messageHandler = new _message_handler.MessageHandler("main", "worker", port);
-
- this._messageHandler.on("ready", function () {});
+ hasJSActions() {
+ return this._hasJSActionsPromise ||= this.messageHandler.sendWithPromise("HasJSActions", null);
+ }
- this._readyCapability.resolve();
+ getCalculationOrderIds() {
+ return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);
}
- _initialize() {
- if (typeof Worker !== "undefined" && !PDFWorkerUtil.isWorkerDisabled && !PDFWorker._mainThreadWorkerMessageHandler) {
- let workerSrc = PDFWorker.workerSrc;
+ getDestinations() {
+ return this.messageHandler.sendWithPromise("GetDestinations", null);
+ }
- try {
- if (!(0, _util.isSameOrigin)(window.location.href, workerSrc)) {
- workerSrc = PDFWorkerUtil.createCDNWrapper(new URL(workerSrc, window.location).href);
- }
+ getDestination(id) {
+ if (typeof id !== "string") {
+ return Promise.reject(new Error("Invalid destination request."));
+ }
- const worker = new Worker(workerSrc);
- const messageHandler = new _message_handler.MessageHandler("main", "worker", worker);
+ return this.messageHandler.sendWithPromise("GetDestination", {
+ id
+ });
+ }
- const terminateEarly = () => {
- worker.removeEventListener("error", onWorkerError);
- messageHandler.destroy();
- worker.terminate();
+ getPageLabels() {
+ return this.messageHandler.sendWithPromise("GetPageLabels", null);
+ }
- if (this.destroyed) {
- this._readyCapability.reject(new Error("Worker was destroyed"));
- } else {
- this._setupFakeWorker();
- }
- };
+ getPageLayout() {
+ return this.messageHandler.sendWithPromise("GetPageLayout", null);
+ }
- const onWorkerError = () => {
- if (!this._webWorker) {
- terminateEarly();
- }
- };
+ getPageMode() {
+ return this.messageHandler.sendWithPromise("GetPageMode", null);
+ }
- worker.addEventListener("error", onWorkerError);
- messageHandler.on("test", data => {
- worker.removeEventListener("error", onWorkerError);
+ getViewerPreferences() {
+ return this.messageHandler.sendWithPromise("GetViewerPreferences", null);
+ }
- if (this.destroyed) {
- terminateEarly();
- return;
- }
+ getOpenAction() {
+ return this.messageHandler.sendWithPromise("GetOpenAction", null);
+ }
- if (data) {
- this._messageHandler = messageHandler;
- this._port = worker;
- this._webWorker = worker;
+ getAttachments() {
+ return this.messageHandler.sendWithPromise("GetAttachments", null);
+ }
- this._readyCapability.resolve();
+ getJavaScript() {
+ return this.messageHandler.sendWithPromise("GetJavaScript", null);
+ }
- messageHandler.send("configure", {
- verbosity: this.verbosity
- });
- } else {
- this._setupFakeWorker();
+ getDocJSActions() {
+ return this.messageHandler.sendWithPromise("GetDocJSActions", null);
+ }
- messageHandler.destroy();
- worker.terminate();
- }
- });
- messageHandler.on("ready", data => {
- worker.removeEventListener("error", onWorkerError);
+ getPageJSActions(pageIndex) {
+ return this.messageHandler.sendWithPromise("GetPageJSActions", {
+ pageIndex
+ });
+ }
- if (this.destroyed) {
- terminateEarly();
- return;
- }
+ getStructTree(pageIndex) {
+ return this.messageHandler.sendWithPromise("GetStructTree", {
+ pageIndex
+ });
+ }
- try {
- sendTest();
- } catch (e) {
- this._setupFakeWorker();
- }
- });
+ getOutline() {
+ return this.messageHandler.sendWithPromise("GetOutline", null);
+ }
- const sendTest = () => {
- const testObj = new Uint8Array([255]);
+ getOptionalContentConfig() {
+ return this.messageHandler.sendWithPromise("GetOptionalContentConfig", null).then(results => {
+ return new _optional_content_config.OptionalContentConfig(results);
+ });
+ }
- try {
- messageHandler.send("test", testObj, [testObj.buffer]);
- } catch (ex) {
- (0, _util.warn)("Cannot use postMessage transfers.");
- testObj[0] = 0;
- messageHandler.send("test", testObj);
- }
- };
+ getPermissions() {
+ return this.messageHandler.sendWithPromise("GetPermissions", null);
+ }
- sendTest();
- return;
- } catch (e) {
- (0, _util.info)("The worker has been disabled.");
- }
- }
+ getMetadata() {
+ return this.#metadataPromise ||= this.messageHandler.sendWithPromise("GetMetadata", null).then(results => {
+ return {
+ info: results[0],
+ metadata: results[1] ? new _metadata.Metadata(results[1]) : null,
+ contentDispositionFilename: this._fullReader?.filename ?? null,
+ contentLength: this._fullReader?.contentLength ?? null
+ };
+ });
+ }
- this._setupFakeWorker();
+ getMarkInfo() {
+ return this.messageHandler.sendWithPromise("GetMarkInfo", null);
}
- _setupFakeWorker() {
- if (!PDFWorkerUtil.isWorkerDisabled) {
- (0, _util.warn)("Setting up fake worker.");
- PDFWorkerUtil.isWorkerDisabled = true;
+ async startCleanup(keepLoadedFonts = false) {
+ await this.messageHandler.sendWithPromise("Cleanup", null);
+
+ if (this.destroyed) {
+ return;
}
- PDFWorker._setupFakeWorkerGlobal.then(WorkerMessageHandler => {
- if (this.destroyed) {
- this._readyCapability.reject(new Error("Worker was destroyed"));
+ for (const page of this.#pageCache.values()) {
+ const cleanupSuccessful = page.cleanup();
- return;
+ if (!cleanupSuccessful) {
+ throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`);
}
+ }
- const port = new LoopbackPort();
- this._port = port;
- const id = `fake${PDFWorkerUtil.fakeWorkerId++}`;
- const workerHandler = new _message_handler.MessageHandler(id + "_worker", id, port);
- WorkerMessageHandler.setup(workerHandler, port);
- const messageHandler = new _message_handler.MessageHandler(id, id + "_worker", port);
- this._messageHandler = messageHandler;
-
- this._readyCapability.resolve();
-
- messageHandler.send("configure", {
- verbosity: this.verbosity
- });
- }).catch(reason => {
- this._readyCapability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`));
- });
- }
-
- destroy() {
- this.destroyed = true;
-
- if (this._webWorker) {
- this._webWorker.terminate();
+ this.commonObjs.clear();
- this._webWorker = null;
+ if (!keepLoadedFonts) {
+ this.fontLoader.clear();
}
- PDFWorker._workerPorts.delete(this._port);
+ this.#metadataPromise = null;
+ this._getFieldObjectsPromise = null;
+ this._hasJSActionsPromise = null;
+ }
- this._port = null;
+ get loadingParams() {
+ const params = this._params;
+ return (0, _util.shadow)(this, "loadingParams", {
+ disableAutoFetch: params.disableAutoFetch,
+ enableXfa: params.enableXfa
+ });
+ }
- if (this._messageHandler) {
- this._messageHandler.destroy();
+}
- this._messageHandler = null;
- }
- }
+class PDFObjects {
+ #objs = Object.create(null);
- static fromPort(params) {
- if (!params?.port) {
- throw new Error("PDFWorker.fromPort - invalid method signature.");
- }
+ #ensureObj(objId) {
+ const obj = this.#objs[objId];
- if (this._workerPorts.has(params.port)) {
- return this._workerPorts.get(params.port);
+ if (obj) {
+ return obj;
}
- return new PDFWorker(params);
+ return this.#objs[objId] = {
+ capability: (0, _util.createPromiseCapability)(),
+ data: null
+ };
}
- static get workerSrc() {
- if (_worker_options.GlobalWorkerOptions.workerSrc) {
- return _worker_options.GlobalWorkerOptions.workerSrc;
+ get(objId, callback = null) {
+ if (callback) {
+ const obj = this.#ensureObj(objId);
+ obj.capability.promise.then(() => callback(obj.data));
+ return null;
}
- if (PDFWorkerUtil.fallbackWorkerSrc !== null) {
- if (!_is_node.isNodeJS) {
- (0, _display_utils.deprecated)('No "GlobalWorkerOptions.workerSrc" specified.');
- }
+ const obj = this.#objs[objId];
- return PDFWorkerUtil.fallbackWorkerSrc;
+ if (!obj?.capability.settled) {
+ throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
}
- throw new Error('No "GlobalWorkerOptions.workerSrc" specified.');
+ return obj.data;
}
- static get _mainThreadWorkerMessageHandler() {
- try {
- return globalThis.pdfjsWorker?.WorkerMessageHandler || null;
- } catch (ex) {
- return null;
- }
+ has(objId) {
+ const obj = this.#objs[objId];
+ return obj?.capability.settled || false;
}
- static get _setupFakeWorkerGlobal() {
- const loader = async () => {
- const mainWorkerMessageHandler = this._mainThreadWorkerMessageHandler;
+ resolve(objId, data = null) {
+ const obj = this.#ensureObj(objId);
+ obj.data = data;
+ obj.capability.resolve();
+ }
- if (mainWorkerMessageHandler) {
- return mainWorkerMessageHandler;
- }
+ clear() {
+ this.#objs = Object.create(null);
+ }
- if (_is_node.isNodeJS && typeof require === "function") {
- const worker = eval("require")(this.workerSrc);
- return worker.WorkerMessageHandler;
- }
+}
- await (0, _display_utils.loadScript)(this.workerSrc);
- return window.pdfjsWorker.WorkerMessageHandler;
- };
+class RenderTask {
+ constructor(internalRenderTask) {
+ this._internalRenderTask = internalRenderTask;
+ this.onContinue = null;
+ }
- return (0, _util.shadow)(this, "_setupFakeWorkerGlobal", loader());
+ get promise() {
+ return this._internalRenderTask.capability.promise;
}
-}
+ cancel() {
+ this._internalRenderTask.cancel();
+ }
-exports.PDFWorker = PDFWorker;
-{
- PDFWorker.getWorkerSrc = function () {
- (0, _display_utils.deprecated)("`PDFWorker.getWorkerSrc()`, please use `PDFWorker.workerSrc` instead.");
- return this.workerSrc;
- };
}
-class WorkerTransport {
- #docStats = null;
- #pageCache = new Map();
- #pagePromises = new Map();
- #metadataPromise = null;
-
- constructor(messageHandler, loadingTask, networkStream, params) {
- this.messageHandler = messageHandler;
- this.loadingTask = loadingTask;
- this.commonObjs = new PDFObjects();
- this.fontLoader = new _font_loader.FontLoader({
- docId: loadingTask.docId,
- onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
- ownerDocument: params.ownerDocument,
- styleElement: params.styleElement
- });
- this._params = params;
-
- if (!params.useWorkerFetch) {
- this.CMapReaderFactory = new params.CMapReaderFactory({
- baseUrl: params.cMapUrl,
- isCompressed: params.cMapPacked
- });
- this.StandardFontDataFactory = new params.StandardFontDataFactory({
- baseUrl: params.standardFontDataUrl
- });
- }
+exports.RenderTask = RenderTask;
- this.destroyed = false;
- this.destroyCapability = null;
- this._passwordCapability = null;
- this._networkStream = networkStream;
- this._fullReader = null;
- this._lastProgress = null;
- this.downloadInfoCapability = (0, _util.createPromiseCapability)();
- this.setupMessageHandler();
- }
+class InternalRenderTask {
+ static #canvasInUse = new WeakSet();
- get annotationStorage() {
- return (0, _util.shadow)(this, "annotationStorage", new _annotation_storage.AnnotationStorage());
+ constructor({
+ callback,
+ params,
+ objs,
+ commonObjs,
+ annotationCanvasMap,
+ operatorList,
+ pageIndex,
+ canvasFactory,
+ useRequestAnimationFrame = false,
+ pdfBug = false,
+ pageColors = null
+ }) {
+ this.callback = callback;
+ this.params = params;
+ this.objs = objs;
+ this.commonObjs = commonObjs;
+ this.annotationCanvasMap = annotationCanvasMap;
+ this.operatorListIdx = null;
+ this.operatorList = operatorList;
+ this._pageIndex = pageIndex;
+ this.canvasFactory = canvasFactory;
+ this._pdfBug = pdfBug;
+ this.pageColors = pageColors;
+ this.running = false;
+ this.graphicsReadyCallback = null;
+ this.graphicsReady = false;
+ this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined";
+ this.cancelled = false;
+ this.capability = (0, _util.createPromiseCapability)();
+ this.task = new RenderTask(this);
+ this._cancelBound = this.cancel.bind(this);
+ this._continueBound = this._continue.bind(this);
+ this._scheduleNextBound = this._scheduleNext.bind(this);
+ this._nextBound = this._next.bind(this);
+ this._canvas = params.canvasContext.canvas;
}
- get stats() {
- return this.#docStats;
+ get completed() {
+ return this.capability.promise.catch(function () {});
}
- getRenderingIntent(intent, annotationMode = _util.AnnotationMode.ENABLE, isOpList = false) {
- let renderingIntent = _util.RenderingIntentFlag.DISPLAY;
- let lastModified = "";
-
- switch (intent) {
- case "any":
- renderingIntent = _util.RenderingIntentFlag.ANY;
- break;
-
- case "display":
- break;
+ initializeGraphics({
+ transparency = false,
+ optionalContentConfig
+ }) {
+ if (this.cancelled) {
+ return;
+ }
- case "print":
- renderingIntent = _util.RenderingIntentFlag.PRINT;
- break;
+ if (this._canvas) {
+ if (InternalRenderTask.#canvasInUse.has(this._canvas)) {
+ throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed.");
+ }
- default:
- (0, _util.warn)(`getRenderingIntent - invalid intent: ${intent}`);
+ InternalRenderTask.#canvasInUse.add(this._canvas);
}
- switch (annotationMode) {
- case _util.AnnotationMode.DISABLE:
- renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_DISABLE;
- break;
+ if (this._pdfBug && globalThis.StepperManager?.enabled) {
+ this.stepper = globalThis.StepperManager.create(this._pageIndex);
+ this.stepper.init(this.operatorList);
+ this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
+ }
- case _util.AnnotationMode.ENABLE:
- break;
+ const {
+ canvasContext,
+ viewport,
+ transform,
+ imageLayer,
+ background
+ } = this.params;
+ this.gfx = new _canvas.CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, imageLayer, optionalContentConfig, this.annotationCanvasMap, this.pageColors);
+ this.gfx.beginDrawing({
+ transform,
+ viewport,
+ transparency,
+ background
+ });
+ this.operatorListIdx = 0;
+ this.graphicsReady = true;
- case _util.AnnotationMode.ENABLE_FORMS:
- renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_FORMS;
- break;
+ if (this.graphicsReadyCallback) {
+ this.graphicsReadyCallback();
+ }
+ }
- case _util.AnnotationMode.ENABLE_STORAGE:
- renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_STORAGE;
- lastModified = this.annotationStorage.lastModified;
- break;
+ cancel(error = null) {
+ this.running = false;
+ this.cancelled = true;
- default:
- (0, _util.warn)(`getRenderingIntent - invalid annotationMode: ${annotationMode}`);
+ if (this.gfx) {
+ this.gfx.endDrawing();
}
- if (isOpList) {
- renderingIntent += _util.RenderingIntentFlag.OPLIST;
+ if (this._canvas) {
+ InternalRenderTask.#canvasInUse.delete(this._canvas);
}
- return {
- renderingIntent,
- cacheKey: `${renderingIntent}_${lastModified}`
- };
+ this.callback(error || new _display_utils.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, "canvas"));
}
- destroy() {
- if (this.destroyCapability) {
- return this.destroyCapability.promise;
+ operatorListChanged() {
+ if (!this.graphicsReady) {
+ if (!this.graphicsReadyCallback) {
+ this.graphicsReadyCallback = this._continueBound;
+ }
+
+ return;
}
- this.destroyed = true;
- this.destroyCapability = (0, _util.createPromiseCapability)();
+ if (this.stepper) {
+ this.stepper.updateOperatorList(this.operatorList);
+ }
- if (this._passwordCapability) {
- this._passwordCapability.reject(new Error("Worker was destroyed during onPassword callback"));
+ if (this.running) {
+ return;
}
- const waitOn = [];
+ this._continue();
+ }
- for (const page of this.#pageCache.values()) {
- waitOn.push(page._destroy());
+ _continue() {
+ this.running = true;
+
+ if (this.cancelled) {
+ return;
}
- this.#pageCache.clear();
- this.#pagePromises.clear();
+ if (this.task.onContinue) {
+ this.task.onContinue(this._scheduleNextBound);
+ } else {
+ this._scheduleNext();
+ }
+ }
- if (this.hasOwnProperty("annotationStorage")) {
- this.annotationStorage.resetModified();
+ _scheduleNext() {
+ if (this._useRequestAnimationFrame) {
+ window.requestAnimationFrame(() => {
+ this._nextBound().catch(this._cancelBound);
+ });
+ } else {
+ Promise.resolve().then(this._nextBound).catch(this._cancelBound);
}
+ }
- const terminated = this.messageHandler.sendWithPromise("Terminate", null);
- waitOn.push(terminated);
- Promise.all(waitOn).then(() => {
- this.commonObjs.clear();
- this.fontLoader.clear();
- this.#metadataPromise = null;
- this._getFieldObjectsPromise = null;
- this._hasJSActionsPromise = null;
+ async _next() {
+ if (this.cancelled) {
+ return;
+ }
- if (this._networkStream) {
- this._networkStream.cancelAllRequests(new _util.AbortException("Worker was terminated."));
- }
+ this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
- if (this.messageHandler) {
- this.messageHandler.destroy();
- this.messageHandler = null;
- }
+ if (this.operatorListIdx === this.operatorList.argsArray.length) {
+ this.running = false;
- this.destroyCapability.resolve();
- }, this.destroyCapability.reject);
- return this.destroyCapability.promise;
+ if (this.operatorList.lastChunk) {
+ this.gfx.endDrawing();
+
+ if (this._canvas) {
+ InternalRenderTask.#canvasInUse.delete(this._canvas);
+ }
+
+ this.callback();
+ }
+ }
}
- setupMessageHandler() {
- const {
- messageHandler,
- loadingTask
- } = this;
- messageHandler.on("GetReader", (data, sink) => {
- (0, _util.assert)(this._networkStream, "GetReader - no `IPDFStream` instance available.");
- this._fullReader = this._networkStream.getFullReader();
+}
- this._fullReader.onProgress = evt => {
- this._lastProgress = {
- loaded: evt.loaded,
- total: evt.total
- };
- };
+const version = '2.14.305';
+exports.version = version;
+const build = 'eaaa8b4ad';
+exports.build = build;
- sink.onPull = () => {
- this._fullReader.read().then(function ({
- value,
- done
- }) {
- if (done) {
- sink.close();
- return;
- }
+/***/ }),
+/* 5 */
+/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
- (0, _util.assert)((0, _util.isArrayBuffer)(value), "GetReader - expected an ArrayBuffer.");
- sink.enqueue(new Uint8Array(value), 1, [value]);
- }).catch(reason => {
- sink.error(reason);
- });
- };
- sink.onCancel = reason => {
- this._fullReader.cancel(reason);
- sink.ready.catch(readyReason => {
- if (this.destroyed) {
- return;
- }
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports.StatTimer = exports.RenderingCancelledException = exports.PixelsPerInch = exports.PageViewport = exports.PDFDateString = exports.DOMStandardFontDataFactory = exports.DOMSVGFactory = exports.DOMCanvasFactory = exports.DOMCMapReaderFactory = void 0;
+exports.deprecated = deprecated;
+exports.getFilenameFromUrl = getFilenameFromUrl;
+exports.getPdfFilenameFromUrl = getPdfFilenameFromUrl;
+exports.getXfaPageViewport = getXfaPageViewport;
+exports.isDataScheme = isDataScheme;
+exports.isPdfFile = isPdfFile;
+exports.isValidFetchUrl = isValidFetchUrl;
+exports.loadScript = loadScript;
- throw readyReason;
- });
- };
- });
- messageHandler.on("ReaderHeadersReady", data => {
- const headersCapability = (0, _util.createPromiseCapability)();
- const fullReader = this._fullReader;
- fullReader.headersReady.then(() => {
- if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) {
- if (this._lastProgress) {
- loadingTask.onProgress?.(this._lastProgress);
- }
+var _base_factory = __w_pdfjs_require__(6);
- fullReader.onProgress = evt => {
- loadingTask.onProgress?.({
- loaded: evt.loaded,
- total: evt.total
- });
- };
- }
+var _util = __w_pdfjs_require__(1);
- headersCapability.resolve({
- isStreamingSupported: fullReader.isStreamingSupported,
- isRangeSupported: fullReader.isRangeSupported,
- contentLength: fullReader.contentLength
- });
- }, headersCapability.reject);
- return headersCapability.promise;
- });
- messageHandler.on("GetRangeReader", (data, sink) => {
- (0, _util.assert)(this._networkStream, "GetRangeReader - no `IPDFStream` instance available.");
+const SVG_NS = "http://www.w3.org/2000/svg";
- const rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
+class PixelsPerInch {
+ static CSS = 96.0;
+ static PDF = 72.0;
+ static PDF_TO_CSS_UNITS = this.CSS / this.PDF;
+}
- if (!rangeReader) {
- sink.close();
- return;
- }
+exports.PixelsPerInch = PixelsPerInch;
- sink.onPull = () => {
- rangeReader.read().then(function ({
- value,
- done
- }) {
- if (done) {
- sink.close();
- return;
- }
+class DOMCanvasFactory extends _base_factory.BaseCanvasFactory {
+ constructor({
+ ownerDocument = globalThis.document
+ } = {}) {
+ super();
+ this._document = ownerDocument;
+ }
- (0, _util.assert)((0, _util.isArrayBuffer)(value), "GetRangeReader - expected an ArrayBuffer.");
- sink.enqueue(new Uint8Array(value), 1, [value]);
- }).catch(reason => {
- sink.error(reason);
- });
- };
+ _createCanvas(width, height) {
+ const canvas = this._document.createElement("canvas");
- sink.onCancel = reason => {
- rangeReader.cancel(reason);
- sink.ready.catch(readyReason => {
- if (this.destroyed) {
- return;
- }
+ canvas.width = width;
+ canvas.height = height;
+ return canvas;
+ }
- throw readyReason;
- });
- };
- });
- messageHandler.on("GetDoc", ({
- pdfInfo
- }) => {
- this._numPages = pdfInfo.numPages;
- this._htmlForXfa = pdfInfo.htmlForXfa;
- delete pdfInfo.htmlForXfa;
+}
- loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
- });
- messageHandler.on("DocException", function (ex) {
- let reason;
+exports.DOMCanvasFactory = DOMCanvasFactory;
- switch (ex.name) {
- case "PasswordException":
- reason = new _util.PasswordException(ex.message, ex.code);
- break;
+async function fetchData(url, asTypedArray = false) {
+ if (isValidFetchUrl(url, document.baseURI)) {
+ const response = await fetch(url);
- case "InvalidPDFException":
- reason = new _util.InvalidPDFException(ex.message);
- break;
+ if (!response.ok) {
+ throw new Error(response.statusText);
+ }
- case "MissingPDFException":
- reason = new _util.MissingPDFException(ex.message);
- break;
+ return asTypedArray ? new Uint8Array(await response.arrayBuffer()) : (0, _util.stringToBytes)(await response.text());
+ }
- case "UnexpectedResponseException":
- reason = new _util.UnexpectedResponseException(ex.message, ex.status);
- break;
+ return new Promise((resolve, reject) => {
+ const request = new XMLHttpRequest();
+ request.open("GET", url, true);
- case "UnknownErrorException":
- reason = new _util.UnknownErrorException(ex.message, ex.details);
- break;
+ if (asTypedArray) {
+ request.responseType = "arraybuffer";
+ }
- default:
- (0, _util.unreachable)("DocException - expected a valid Error.");
+ request.onreadystatechange = () => {
+ if (request.readyState !== XMLHttpRequest.DONE) {
+ return;
}
- loadingTask._capability.reject(reason);
- });
- messageHandler.on("PasswordRequest", exception => {
- this._passwordCapability = (0, _util.createPromiseCapability)();
+ if (request.status === 200 || request.status === 0) {
+ let data;
- if (loadingTask.onPassword) {
- const updatePassword = password => {
- this._passwordCapability.resolve({
- password
- });
- };
+ if (asTypedArray && request.response) {
+ data = new Uint8Array(request.response);
+ } else if (!asTypedArray && request.responseText) {
+ data = (0, _util.stringToBytes)(request.responseText);
+ }
- try {
- loadingTask.onPassword(updatePassword, exception.code);
- } catch (ex) {
- this._passwordCapability.reject(ex);
+ if (data) {
+ resolve(data);
+ return;
}
- } else {
- this._passwordCapability.reject(new _util.PasswordException(exception.message, exception.code));
}
- return this._passwordCapability.promise;
- });
- messageHandler.on("DataLoaded", data => {
- loadingTask.onProgress?.({
- loaded: data.length,
- total: data.length
- });
- this.downloadInfoCapability.resolve(data);
- });
- messageHandler.on("StartRenderPage", data => {
- if (this.destroyed) {
- return;
- }
+ reject(new Error(request.statusText));
+ };
- const page = this.#pageCache.get(data.pageIndex);
+ request.send(null);
+ });
+}
- page._startRenderPage(data.transparency, data.cacheKey);
+class DOMCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
+ _fetchData(url, compressionType) {
+ return fetchData(url, this.isCompressed).then(data => {
+ return {
+ cMapData: data,
+ compressionType
+ };
});
- messageHandler.on("commonobj", ([id, type, exportedData]) => {
- if (this.destroyed) {
- return;
- }
+ }
+
+}
+
+exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
- if (this.commonObjs.has(id)) {
- return;
- }
+class DOMStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
+ _fetchData(url) {
+ return fetchData(url, true);
+ }
- switch (type) {
- case "Font":
- const params = this._params;
+}
- if ("error" in exportedData) {
- const exportedError = exportedData.error;
- (0, _util.warn)(`Error during font loading: ${exportedError}`);
- this.commonObjs.resolve(id, exportedError);
- break;
- }
+exports.DOMStandardFontDataFactory = DOMStandardFontDataFactory;
- let fontRegistry = null;
+class DOMSVGFactory extends _base_factory.BaseSVGFactory {
+ _createSVG(type) {
+ return document.createElementNS(SVG_NS, type);
+ }
- if (params.pdfBug && globalThis.FontInspector?.enabled) {
- fontRegistry = {
- registerFont(font, url) {
- globalThis.FontInspector.fontAdded(font, url);
- }
+}
- };
- }
+exports.DOMSVGFactory = DOMSVGFactory;
- const font = new _font_loader.FontFaceObject(exportedData, {
- isEvalSupported: params.isEvalSupported,
- disableFontFace: params.disableFontFace,
- ignoreErrors: params.ignoreErrors,
- onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
- fontRegistry
- });
- this.fontLoader.bind(font).catch(reason => {
- return messageHandler.sendWithPromise("FontFallback", {
- id
- });
- }).finally(() => {
- if (!params.fontExtraProperties && font.data) {
- font.data = null;
- }
+class PageViewport {
+ constructor({
+ viewBox,
+ scale,
+ rotation,
+ offsetX = 0,
+ offsetY = 0,
+ dontFlip = false
+ }) {
+ this.viewBox = viewBox;
+ this.scale = scale;
+ this.rotation = rotation;
+ this.offsetX = offsetX;
+ this.offsetY = offsetY;
+ const centerX = (viewBox[2] + viewBox[0]) / 2;
+ const centerY = (viewBox[3] + viewBox[1]) / 2;
+ let rotateA, rotateB, rotateC, rotateD;
+ rotation %= 360;
- this.commonObjs.resolve(id, font);
- });
- break;
+ if (rotation < 0) {
+ rotation += 360;
+ }
- case "FontPath":
- case "Image":
- this.commonObjs.resolve(id, exportedData);
- break;
+ switch (rotation) {
+ case 180:
+ rotateA = -1;
+ rotateB = 0;
+ rotateC = 0;
+ rotateD = 1;
+ break;
- default:
- throw new Error(`Got unknown common object type ${type}`);
- }
- });
- messageHandler.on("obj", ([id, pageIndex, type, imageData]) => {
- if (this.destroyed) {
- return;
- }
+ case 90:
+ rotateA = 0;
+ rotateB = 1;
+ rotateC = 1;
+ rotateD = 0;
+ break;
- const pageProxy = this.#pageCache.get(pageIndex);
+ case 270:
+ rotateA = 0;
+ rotateB = -1;
+ rotateC = -1;
+ rotateD = 0;
+ break;
- if (pageProxy.objs.has(id)) {
- return;
- }
+ case 0:
+ rotateA = 1;
+ rotateB = 0;
+ rotateC = 0;
+ rotateD = -1;
+ break;
- switch (type) {
- case "Image":
- pageProxy.objs.resolve(id, imageData);
- const MAX_IMAGE_SIZE_TO_STORE = 8000000;
+ default:
+ throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
+ }
- if (imageData?.data?.length > MAX_IMAGE_SIZE_TO_STORE) {
- pageProxy.cleanupAfterRender = true;
- }
+ if (dontFlip) {
+ rotateC = -rotateC;
+ rotateD = -rotateD;
+ }
- break;
+ let offsetCanvasX, offsetCanvasY;
+ let width, height;
- case "Pattern":
- pageProxy.objs.resolve(id, imageData);
- break;
+ if (rotateA === 0) {
+ offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
+ offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
+ width = Math.abs(viewBox[3] - viewBox[1]) * scale;
+ height = Math.abs(viewBox[2] - viewBox[0]) * scale;
+ } else {
+ offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
+ offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
+ width = Math.abs(viewBox[2] - viewBox[0]) * scale;
+ height = Math.abs(viewBox[3] - viewBox[1]) * scale;
+ }
- default:
- throw new Error(`Got unknown object type ${type}`);
- }
- });
- messageHandler.on("DocProgress", data => {
- if (this.destroyed) {
- return;
- }
+ this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
+ this.width = width;
+ this.height = height;
+ }
- loadingTask.onProgress?.({
- loaded: data.loaded,
- total: data.total
- });
+ clone({
+ scale = this.scale,
+ rotation = this.rotation,
+ offsetX = this.offsetX,
+ offsetY = this.offsetY,
+ dontFlip = false
+ } = {}) {
+ return new PageViewport({
+ viewBox: this.viewBox.slice(),
+ scale,
+ rotation,
+ offsetX,
+ offsetY,
+ dontFlip
});
- messageHandler.on("DocStats", data => {
- if (this.destroyed) {
- return;
- }
+ }
- this.#docStats = Object.freeze({
- streamTypes: Object.freeze(data.streamTypes),
- fontTypes: Object.freeze(data.fontTypes)
- });
- });
- messageHandler.on("UnsupportedFeature", this._onUnsupportedFeature.bind(this));
- messageHandler.on("FetchBuiltInCMap", data => {
- if (this.destroyed) {
- return Promise.reject(new Error("Worker was destroyed."));
- }
+ convertToViewportPoint(x, y) {
+ return _util.Util.applyTransform([x, y], this.transform);
+ }
- if (!this.CMapReaderFactory) {
- return Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."));
- }
+ convertToViewportRectangle(rect) {
+ const topLeft = _util.Util.applyTransform([rect[0], rect[1]], this.transform);
- return this.CMapReaderFactory.fetch(data);
- });
- messageHandler.on("FetchStandardFontData", data => {
- if (this.destroyed) {
- return Promise.reject(new Error("Worker was destroyed."));
- }
+ const bottomRight = _util.Util.applyTransform([rect[2], rect[3]], this.transform);
- if (!this.StandardFontDataFactory) {
- return Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."));
- }
+ return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
+ }
- return this.StandardFontDataFactory.fetch(data);
- });
+ convertToPdfPoint(x, y) {
+ return _util.Util.applyInverseTransform([x, y], this.transform);
}
- _onUnsupportedFeature({
- featureId
- }) {
- if (this.destroyed) {
- return;
- }
+}
- this.loadingTask.onUnsupportedFeature?.(featureId);
- }
+exports.PageViewport = PageViewport;
- getData() {
- return this.messageHandler.sendWithPromise("GetData", null);
+class RenderingCancelledException extends _util.BaseException {
+ constructor(msg, type) {
+ super(msg, "RenderingCancelledException");
+ this.type = type;
}
- getPage(pageNumber) {
- if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
- return Promise.reject(new Error("Invalid page request"));
- }
+}
- const pageIndex = pageNumber - 1,
- cachedPromise = this.#pagePromises.get(pageIndex);
+exports.RenderingCancelledException = RenderingCancelledException;
- if (cachedPromise) {
- return cachedPromise;
- }
+function isDataScheme(url) {
+ const ii = url.length;
+ let i = 0;
- const promise = this.messageHandler.sendWithPromise("GetPage", {
- pageIndex
- }).then(pageInfo => {
- if (this.destroyed) {
- throw new Error("Transport destroyed");
- }
+ while (i < ii && url[i].trim() === "") {
+ i++;
+ }
+
+ return url.substring(i, i + 5).toLowerCase() === "data:";
+}
+
+function isPdfFile(filename) {
+ return typeof filename === "string" && /\.pdf$/i.test(filename);
+}
- const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.ownerDocument, this._params.pdfBug);
- this.#pageCache.set(pageIndex, page);
- return page;
- });
- this.#pagePromises.set(pageIndex, promise);
- return promise;
- }
+function getFilenameFromUrl(url) {
+ const anchor = url.indexOf("#");
+ const query = url.indexOf("?");
+ const end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length);
+ return url.substring(url.lastIndexOf("/", end) + 1, end);
+}
- getPageIndex(ref) {
- return this.messageHandler.sendWithPromise("GetPageIndex", {
- ref
- });
+function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
+ if (typeof url !== "string") {
+ return defaultFilename;
}
- getAnnotations(pageIndex, intent) {
- return this.messageHandler.sendWithPromise("GetAnnotations", {
- pageIndex,
- intent
- });
+ if (isDataScheme(url)) {
+ (0, _util.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
+ return defaultFilename;
}
- saveDocument() {
- return this.messageHandler.sendWithPromise("SaveDocument", {
- isPureXfa: !!this._htmlForXfa,
- numPages: this._numPages,
- annotationStorage: this.annotationStorage.serializable,
- filename: this._fullReader?.filename ?? null
- }).finally(() => {
- this.annotationStorage.resetModified();
- });
- }
+ const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
+ const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
+ const splitURI = reURI.exec(url);
+ let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
- getFieldObjects() {
- return this._getFieldObjectsPromise ||= this.messageHandler.sendWithPromise("GetFieldObjects", null);
- }
+ if (suggestedFilename) {
+ suggestedFilename = suggestedFilename[0];
- hasJSActions() {
- return this._hasJSActionsPromise ||= this.messageHandler.sendWithPromise("HasJSActions", null);
+ if (suggestedFilename.includes("%")) {
+ try {
+ suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
+ } catch (ex) {}
+ }
}
- getCalculationOrderIds() {
- return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);
+ return suggestedFilename || defaultFilename;
+}
+
+class StatTimer {
+ constructor() {
+ this.started = Object.create(null);
+ this.times = [];
}
- getDestinations() {
- return this.messageHandler.sendWithPromise("GetDestinations", null);
+ time(name) {
+ if (name in this.started) {
+ (0, _util.warn)(`Timer is already running for ${name}`);
+ }
+
+ this.started[name] = Date.now();
}
- getDestination(id) {
- if (typeof id !== "string") {
- return Promise.reject(new Error("Invalid destination request."));
+ timeEnd(name) {
+ if (!(name in this.started)) {
+ (0, _util.warn)(`Timer has not been started for ${name}`);
}
- return this.messageHandler.sendWithPromise("GetDestination", {
- id
+ this.times.push({
+ name,
+ start: this.started[name],
+ end: Date.now()
});
+ delete this.started[name];
}
- getPageLabels() {
- return this.messageHandler.sendWithPromise("GetPageLabels", null);
- }
+ toString() {
+ const outBuf = [];
+ let longest = 0;
- getPageLayout() {
- return this.messageHandler.sendWithPromise("GetPageLayout", null);
- }
+ for (const time of this.times) {
+ const name = time.name;
- getPageMode() {
- return this.messageHandler.sendWithPromise("GetPageMode", null);
- }
+ if (name.length > longest) {
+ longest = name.length;
+ }
+ }
- getViewerPreferences() {
- return this.messageHandler.sendWithPromise("GetViewerPreferences", null);
- }
+ for (const time of this.times) {
+ const duration = time.end - time.start;
+ outBuf.push(`${time.name.padEnd(longest)} ${duration}ms\n`);
+ }
- getOpenAction() {
- return this.messageHandler.sendWithPromise("GetOpenAction", null);
+ return outBuf.join("");
}
- getAttachments() {
- return this.messageHandler.sendWithPromise("GetAttachments", null);
- }
+}
- getJavaScript() {
- return this.messageHandler.sendWithPromise("GetJavaScript", null);
- }
+exports.StatTimer = StatTimer;
- getDocJSActions() {
- return this.messageHandler.sendWithPromise("GetDocJSActions", null);
+function isValidFetchUrl(url, baseUrl) {
+ try {
+ const {
+ protocol
+ } = baseUrl ? new URL(url, baseUrl) : new URL(url);
+ return protocol === "http:" || protocol === "https:";
+ } catch (ex) {
+ return false;
}
+}
- getPageJSActions(pageIndex) {
- return this.messageHandler.sendWithPromise("GetPageJSActions", {
- pageIndex
- });
- }
+function loadScript(src, removeScriptElement = false) {
+ return new Promise((resolve, reject) => {
+ const script = document.createElement("script");
+ script.src = src;
- getStructTree(pageIndex) {
- return this.messageHandler.sendWithPromise("GetStructTree", {
- pageIndex
- });
- }
+ script.onload = function (evt) {
+ if (removeScriptElement) {
+ script.remove();
+ }
- getOutline() {
- return this.messageHandler.sendWithPromise("GetOutline", null);
- }
+ resolve(evt);
+ };
- getOptionalContentConfig() {
- return this.messageHandler.sendWithPromise("GetOptionalContentConfig", null).then(results => {
- return new _optional_content_config.OptionalContentConfig(results);
- });
- }
+ script.onerror = function () {
+ reject(new Error(`Cannot load script at: ${script.src}`));
+ };
- getPermissions() {
- return this.messageHandler.sendWithPromise("GetPermissions", null);
- }
+ (document.head || document.documentElement).appendChild(script);
+ });
+}
- getMetadata() {
- return this.#metadataPromise ||= this.messageHandler.sendWithPromise("GetMetadata", null).then(results => {
- return {
- info: results[0],
- metadata: results[1] ? new _metadata.Metadata(results[1]) : null,
- contentDispositionFilename: this._fullReader?.filename ?? null,
- contentLength: this._fullReader?.contentLength ?? null
- };
- });
- }
+function deprecated(details) {
+ console.log("Deprecated API usage: " + details);
+}
- getMarkInfo() {
- return this.messageHandler.sendWithPromise("GetMarkInfo", null);
- }
+let pdfDateStringRegex;
- async startCleanup(keepLoadedFonts = false) {
- await this.messageHandler.sendWithPromise("Cleanup", null);
+class PDFDateString {
+ static toDateObject(input) {
+ if (!input || typeof input !== "string") {
+ return null;
+ }
- if (this.destroyed) {
- return;
+ if (!pdfDateStringRegex) {
+ pdfDateStringRegex = new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
}
- for (const page of this.#pageCache.values()) {
- const cleanupSuccessful = page.cleanup();
+ const matches = pdfDateStringRegex.exec(input);
- if (!cleanupSuccessful) {
- throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`);
- }
+ if (!matches) {
+ return null;
}
- this.commonObjs.clear();
+ const year = parseInt(matches[1], 10);
+ let month = parseInt(matches[2], 10);
+ month = month >= 1 && month <= 12 ? month - 1 : 0;
+ let day = parseInt(matches[3], 10);
+ day = day >= 1 && day <= 31 ? day : 1;
+ let hour = parseInt(matches[4], 10);
+ hour = hour >= 0 && hour <= 23 ? hour : 0;
+ let minute = parseInt(matches[5], 10);
+ minute = minute >= 0 && minute <= 59 ? minute : 0;
+ let second = parseInt(matches[6], 10);
+ second = second >= 0 && second <= 59 ? second : 0;
+ const universalTimeRelation = matches[7] || "Z";
+ let offsetHour = parseInt(matches[8], 10);
+ offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
+ let offsetMinute = parseInt(matches[9], 10) || 0;
+ offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
- if (!keepLoadedFonts) {
- this.fontLoader.clear();
+ if (universalTimeRelation === "-") {
+ hour += offsetHour;
+ minute += offsetMinute;
+ } else if (universalTimeRelation === "+") {
+ hour -= offsetHour;
+ minute -= offsetMinute;
}
- this.#metadataPromise = null;
- this._getFieldObjectsPromise = null;
- this._hasJSActionsPromise = null;
- }
-
- get loadingParams() {
- const params = this._params;
- return (0, _util.shadow)(this, "loadingParams", {
- disableAutoFetch: params.disableAutoFetch,
- enableXfa: params.enableXfa
- });
+ return new Date(Date.UTC(year, month, day, hour, minute, second));
}
}
-class PDFObjects {
- constructor() {
- this._objs = Object.create(null);
- }
+exports.PDFDateString = PDFDateString;
+
+function getXfaPageViewport(xfaPage, {
+ scale = 1,
+ rotation = 0
+}) {
+ const {
+ width,
+ height
+ } = xfaPage.attributes.style;
+ const viewBox = [0, 0, parseInt(width), parseInt(height)];
+ return new PageViewport({
+ viewBox,
+ scale,
+ rotation
+ });
+}
- _ensureObj(objId) {
- if (this._objs[objId]) {
- return this._objs[objId];
- }
+/***/ }),
+/* 6 */
+/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
- return this._objs[objId] = {
- capability: (0, _util.createPromiseCapability)(),
- data: null,
- resolved: false
- };
- }
- get(objId, callback = null) {
- if (callback) {
- this._ensureObj(objId).capability.promise.then(callback);
- return null;
- }
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports.BaseStandardFontDataFactory = exports.BaseSVGFactory = exports.BaseCanvasFactory = exports.BaseCMapReaderFactory = void 0;
- const obj = this._objs[objId];
+var _util = __w_pdfjs_require__(1);
- if (!obj || !obj.resolved) {
- throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
+class BaseCanvasFactory {
+ constructor() {
+ if (this.constructor === BaseCanvasFactory) {
+ (0, _util.unreachable)("Cannot initialize BaseCanvasFactory.");
}
-
- return obj.data;
}
- has(objId) {
- const obj = this._objs[objId];
- return obj?.resolved || false;
- }
+ create(width, height) {
+ if (width <= 0 || height <= 0) {
+ throw new Error("Invalid canvas size");
+ }
- resolve(objId, data) {
- const obj = this._ensureObj(objId);
+ const canvas = this._createCanvas(width, height);
- obj.resolved = true;
- obj.data = data;
- obj.capability.resolve(data);
+ return {
+ canvas,
+ context: canvas.getContext("2d")
+ };
}
- clear() {
- this._objs = Object.create(null);
- }
+ reset(canvasAndContext, width, height) {
+ if (!canvasAndContext.canvas) {
+ throw new Error("Canvas is not specified");
+ }
-}
+ if (width <= 0 || height <= 0) {
+ throw new Error("Invalid canvas size");
+ }
-class RenderTask {
- constructor(internalRenderTask) {
- this._internalRenderTask = internalRenderTask;
- this.onContinue = null;
+ canvasAndContext.canvas.width = width;
+ canvasAndContext.canvas.height = height;
}
- get promise() {
- return this._internalRenderTask.capability.promise;
+ destroy(canvasAndContext) {
+ if (!canvasAndContext.canvas) {
+ throw new Error("Canvas is not specified");
+ }
+
+ canvasAndContext.canvas.width = 0;
+ canvasAndContext.canvas.height = 0;
+ canvasAndContext.canvas = null;
+ canvasAndContext.context = null;
}
- cancel() {
- this._internalRenderTask.cancel();
+ _createCanvas(width, height) {
+ (0, _util.unreachable)("Abstract method `_createCanvas` called.");
}
}
-exports.RenderTask = RenderTask;
-
-class InternalRenderTask {
- static get canvasInUse() {
- return (0, _util.shadow)(this, "canvasInUse", new WeakSet());
- }
+exports.BaseCanvasFactory = BaseCanvasFactory;
+class BaseCMapReaderFactory {
constructor({
- callback,
- params,
- objs,
- commonObjs,
- annotationCanvasMap,
- operatorList,
- pageIndex,
- canvasFactory,
- useRequestAnimationFrame = false,
- pdfBug = false
+ baseUrl = null,
+ isCompressed = false
}) {
- this.callback = callback;
- this.params = params;
- this.objs = objs;
- this.commonObjs = commonObjs;
- this.annotationCanvasMap = annotationCanvasMap;
- this.operatorListIdx = null;
- this.operatorList = operatorList;
- this._pageIndex = pageIndex;
- this.canvasFactory = canvasFactory;
- this._pdfBug = pdfBug;
- this.running = false;
- this.graphicsReadyCallback = null;
- this.graphicsReady = false;
- this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined";
- this.cancelled = false;
- this.capability = (0, _util.createPromiseCapability)();
- this.task = new RenderTask(this);
- this._cancelBound = this.cancel.bind(this);
- this._continueBound = this._continue.bind(this);
- this._scheduleNextBound = this._scheduleNext.bind(this);
- this._nextBound = this._next.bind(this);
- this._canvas = params.canvasContext.canvas;
- }
+ if (this.constructor === BaseCMapReaderFactory) {
+ (0, _util.unreachable)("Cannot initialize BaseCMapReaderFactory.");
+ }
- get completed() {
- return this.capability.promise.catch(function () {});
+ this.baseUrl = baseUrl;
+ this.isCompressed = isCompressed;
}
- initializeGraphics({
- transparency = false,
- optionalContentConfig
+ async fetch({
+ name
}) {
- if (this.cancelled) {
- return;
- }
-
- if (this._canvas) {
- if (InternalRenderTask.canvasInUse.has(this._canvas)) {
- throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed.");
- }
-
- InternalRenderTask.canvasInUse.add(this._canvas);
+ if (!this.baseUrl) {
+ throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.');
}
- if (this._pdfBug && globalThis.StepperManager?.enabled) {
- this.stepper = globalThis.StepperManager.create(this._pageIndex);
- this.stepper.init(this.operatorList);
- this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
+ if (!name) {
+ throw new Error("CMap name must be specified.");
}
- const {
- canvasContext,
- viewport,
- transform,
- imageLayer,
- background
- } = this.params;
- this.gfx = new _canvas.CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, imageLayer, optionalContentConfig, this.annotationCanvasMap);
- this.gfx.beginDrawing({
- transform,
- viewport,
- transparency,
- background
+ const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
+ const compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE;
+ return this._fetchData(url, compressionType).catch(reason => {
+ throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
});
- this.operatorListIdx = 0;
- this.graphicsReady = true;
+ }
- if (this.graphicsReadyCallback) {
- this.graphicsReadyCallback();
- }
+ _fetchData(url, compressionType) {
+ (0, _util.unreachable)("Abstract method `_fetchData` called.");
}
- cancel(error = null) {
- this.running = false;
- this.cancelled = true;
+}
- if (this.gfx) {
- this.gfx.endDrawing();
- }
+exports.BaseCMapReaderFactory = BaseCMapReaderFactory;
- if (this._canvas) {
- InternalRenderTask.canvasInUse.delete(this._canvas);
+class BaseStandardFontDataFactory {
+ constructor({
+ baseUrl = null
+ }) {
+ if (this.constructor === BaseStandardFontDataFactory) {
+ (0, _util.unreachable)("Cannot initialize BaseStandardFontDataFactory.");
}
- this.callback(error || new _display_utils.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, "canvas"));
+ this.baseUrl = baseUrl;
}
- operatorListChanged() {
- if (!this.graphicsReady) {
- if (!this.graphicsReadyCallback) {
- this.graphicsReadyCallback = this._continueBound;
- }
-
- return;
- }
-
- if (this.stepper) {
- this.stepper.updateOperatorList(this.operatorList);
+ async fetch({
+ filename
+ }) {
+ if (!this.baseUrl) {
+ throw new Error('The standard font "baseUrl" parameter must be specified, ensure that ' + 'the "standardFontDataUrl" API parameter is provided.');
}
- if (this.running) {
- return;
+ if (!filename) {
+ throw new Error("Font filename must be specified.");
}
- this._continue();
+ const url = `${this.baseUrl}${filename}`;
+ return this._fetchData(url).catch(reason => {
+ throw new Error(`Unable to load font data at: ${url}`);
+ });
}
- _continue() {
- this.running = true;
+ _fetchData(url) {
+ (0, _util.unreachable)("Abstract method `_fetchData` called.");
+ }
- if (this.cancelled) {
- return;
- }
+}
- if (this.task.onContinue) {
- this.task.onContinue(this._scheduleNextBound);
- } else {
- this._scheduleNext();
- }
- }
+exports.BaseStandardFontDataFactory = BaseStandardFontDataFactory;
- _scheduleNext() {
- if (this._useRequestAnimationFrame) {
- window.requestAnimationFrame(() => {
- this._nextBound().catch(this._cancelBound);
- });
- } else {
- Promise.resolve().then(this._nextBound).catch(this._cancelBound);
+class BaseSVGFactory {
+ constructor() {
+ if (this.constructor === BaseSVGFactory) {
+ (0, _util.unreachable)("Cannot initialize BaseSVGFactory.");
}
}
- async _next() {
- if (this.cancelled) {
- return;
+ create(width, height) {
+ if (width <= 0 || height <= 0) {
+ throw new Error("Invalid SVG dimensions");
}
- this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
-
- if (this.operatorListIdx === this.operatorList.argsArray.length) {
- this.running = false;
-
- if (this.operatorList.lastChunk) {
- this.gfx.endDrawing();
+ const svg = this._createSVG("svg:svg");
- if (this._canvas) {
- InternalRenderTask.canvasInUse.delete(this._canvas);
- }
+ svg.setAttribute("version", "1.1");
+ svg.setAttribute("width", `${width}px`);
+ svg.setAttribute("height", `${height}px`);
+ svg.setAttribute("preserveAspectRatio", "none");
+ svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
+ return svg;
+ }
- this.callback();
- }
+ createElement(type) {
+ if (typeof type !== "string") {
+ throw new Error("Invalid SVG element type");
}
+
+ return this._createSVG(type);
+ }
+
+ _createSVG(type) {
+ (0, _util.unreachable)("Abstract method `_createSVG` called.");
}
}
-const version = '2.12.313';
-exports.version = version;
-const build = 'a2ae56f39';
-exports.build = build;
+exports.BaseSVGFactory = BaseSVGFactory;
/***/ }),
/* 7 */
}));
exports.FontLoader = exports.FontFaceObject = void 0;
-var _util = __w_pdfjs_require__(2);
+var _util = __w_pdfjs_require__(1);
class BaseFontLoader {
constructor({
return this.compiledGlyphs[character] = function (c, size) {};
}
- if (this.isEvalSupported && _util.IsEvalSupportedCached.value) {
+ if (this.isEvalSupported && _util.FeatureTest.isEvalSupported) {
const jsBuf = [];
for (const current of cmds) {
-Object.defineProperty(exports, "__esModule", ({
- value: true
-}));
-exports.NodeStandardFontDataFactory = exports.NodeCanvasFactory = exports.NodeCMapReaderFactory = void 0;
-
-var _base_factory = __w_pdfjs_require__(5);
-
-var _is_node = __w_pdfjs_require__(4);
-
-var _util = __w_pdfjs_require__(2);
-
-let NodeCanvasFactory = class {
- constructor() {
- (0, _util.unreachable)("Not implemented: NodeCanvasFactory");
- }
-
-};
-exports.NodeCanvasFactory = NodeCanvasFactory;
-let NodeCMapReaderFactory = class {
- constructor() {
- (0, _util.unreachable)("Not implemented: NodeCMapReaderFactory");
- }
-
-};
-exports.NodeCMapReaderFactory = NodeCMapReaderFactory;
-let NodeStandardFontDataFactory = class {
- constructor() {
- (0, _util.unreachable)("Not implemented: NodeStandardFontDataFactory");
- }
-
-};
-exports.NodeStandardFontDataFactory = NodeStandardFontDataFactory;
-
-if (_is_node.isNodeJS) {
- const fetchData = function (url) {
- return new Promise((resolve, reject) => {
- const fs = require("fs");
-
- fs.readFile(url, (error, data) => {
- if (error || !data) {
- reject(new Error(error));
- return;
- }
-
- resolve(new Uint8Array(data));
- });
- });
- };
-
- exports.NodeCanvasFactory = NodeCanvasFactory = class extends _base_factory.BaseCanvasFactory {
- _createCanvas(width, height) {
- const Canvas = require("canvas");
-
- return Canvas.createCanvas(width, height);
- }
-
- };
- exports.NodeCMapReaderFactory = NodeCMapReaderFactory = class extends _base_factory.BaseCMapReaderFactory {
- _fetchData(url, compressionType) {
- return fetchData(url).then(data => {
- return {
- cMapData: data,
- compressionType
- };
- });
- }
-
- };
- exports.NodeStandardFontDataFactory = NodeStandardFontDataFactory = class extends _base_factory.BaseStandardFontDataFactory {
- _fetchData(url) {
- return fetchData(url);
- }
-
- };
-}
-
-/***/ }),
-/* 9 */
-/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
-
-
-
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports.AnnotationStorage = void 0;
-var _util = __w_pdfjs_require__(2);
+var _murmurhash = __w_pdfjs_require__(9);
+
+var _util = __w_pdfjs_require__(1);
class AnnotationStorage {
constructor() {
this._storage = new Map();
- this._timeStamp = Date.now();
this._modified = false;
this.onSetModified = null;
this.onResetModified = null;
return Object.assign(defaultValue, value);
}
+ getRawValue(key) {
+ return this._storage.get(key);
+ }
+
setValue(key, value) {
const obj = this._storage.get(key);
}
if (modified) {
- this._timeStamp = Date.now();
-
this._setModified();
}
}
return this._storage.size > 0 ? this._storage : null;
}
- get lastModified() {
- return this._timeStamp.toString();
+ get hash() {
+ const hash = new _murmurhash.MurmurHash3_64();
+
+ for (const [key, value] of this._storage) {
+ hash.update(`${key}:${JSON.stringify(value)}`);
+ }
+
+ return hash.hexdigest();
}
}
exports.AnnotationStorage = AnnotationStorage;
+/***/ }),
+/* 9 */
+/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
+
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports.MurmurHash3_64 = void 0;
+
+var _util = __w_pdfjs_require__(1);
+
+const SEED = 0xc3d2e1f0;
+const MASK_HIGH = 0xffff0000;
+const MASK_LOW = 0xffff;
+
+class MurmurHash3_64 {
+ constructor(seed) {
+ this.h1 = seed ? seed & 0xffffffff : SEED;
+ this.h2 = seed ? seed & 0xffffffff : SEED;
+ }
+
+ update(input) {
+ let data, length;
+
+ if (typeof input === "string") {
+ data = new Uint8Array(input.length * 2);
+ length = 0;
+
+ for (let i = 0, ii = input.length; i < ii; i++) {
+ const code = input.charCodeAt(i);
+
+ if (code <= 0xff) {
+ data[length++] = code;
+ } else {
+ data[length++] = code >>> 8;
+ data[length++] = code & 0xff;
+ }
+ }
+ } else if ((0, _util.isArrayBuffer)(input)) {
+ data = input.slice();
+ length = data.byteLength;
+ } else {
+ throw new Error("Wrong data format in MurmurHash3_64_update. " + "Input must be a string or array.");
+ }
+
+ const blockCounts = length >> 2;
+ const tailLength = length - blockCounts * 4;
+ const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts);
+ let k1 = 0,
+ k2 = 0;
+ let h1 = this.h1,
+ h2 = this.h2;
+ const C1 = 0xcc9e2d51,
+ C2 = 0x1b873593;
+ const C1_LOW = C1 & MASK_LOW,
+ C2_LOW = C2 & MASK_LOW;
+
+ for (let i = 0; i < blockCounts; i++) {
+ if (i & 1) {
+ k1 = dataUint32[i];
+ k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
+ k1 = k1 << 15 | k1 >>> 17;
+ k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
+ h1 ^= k1;
+ h1 = h1 << 13 | h1 >>> 19;
+ h1 = h1 * 5 + 0xe6546b64;
+ } else {
+ k2 = dataUint32[i];
+ k2 = k2 * C1 & MASK_HIGH | k2 * C1_LOW & MASK_LOW;
+ k2 = k2 << 15 | k2 >>> 17;
+ k2 = k2 * C2 & MASK_HIGH | k2 * C2_LOW & MASK_LOW;
+ h2 ^= k2;
+ h2 = h2 << 13 | h2 >>> 19;
+ h2 = h2 * 5 + 0xe6546b64;
+ }
+ }
+
+ k1 = 0;
+
+ switch (tailLength) {
+ case 3:
+ k1 ^= data[blockCounts * 4 + 2] << 16;
+
+ case 2:
+ k1 ^= data[blockCounts * 4 + 1] << 8;
+
+ case 1:
+ k1 ^= data[blockCounts * 4];
+ k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
+ k1 = k1 << 15 | k1 >>> 17;
+ k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
+
+ if (blockCounts & 1) {
+ h1 ^= k1;
+ } else {
+ h2 ^= k1;
+ }
+
+ }
+
+ this.h1 = h1;
+ this.h2 = h2;
+ }
+
+ hexdigest() {
+ let h1 = this.h1,
+ h2 = this.h2;
+ h1 ^= h2 >>> 1;
+ h1 = h1 * 0xed558ccd & MASK_HIGH | h1 * 0x8ccd & MASK_LOW;
+ h2 = h2 * 0xff51afd7 & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16;
+ h1 ^= h2 >>> 1;
+ h1 = h1 * 0x1a85ec53 & MASK_HIGH | h1 * 0xec53 & MASK_LOW;
+ h2 = h2 * 0xc4ceb9fe & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16;
+ h1 ^= h2 >>> 1;
+ const hex1 = (h1 >>> 0).toString(16),
+ hex2 = (h2 >>> 0).toString(16);
+ return hex1.padStart(8, "0") + hex2.padStart(8, "0");
+ }
+
+}
+
+exports.MurmurHash3_64 = MurmurHash3_64;
+
/***/ }),
/* 10 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
}));
exports.CanvasGraphics = void 0;
-var _util = __w_pdfjs_require__(2);
+var _util = __w_pdfjs_require__(1);
var _pattern_helper = __w_pdfjs_require__(11);
-var _display_utils = __w_pdfjs_require__(1);
+var _image_utils = __w_pdfjs_require__(12);
+
+var _is_node = __w_pdfjs_require__(3);
+
+var _display_utils = __w_pdfjs_require__(5);
const MIN_FONT_SIZE = 16;
const MAX_FONT_SIZE = 100;
}
function addContextCurrentTransform(ctx) {
+ if (ctx._transformStack) {
+ ctx._transformStack = [];
+ }
+
if (ctx.mozCurrentTransform) {
return;
}
};
ctx.restore = function ctxRestore() {
+ if (this._transformStack.length === 0) {
+ (0, _util.warn)("Tried to restore a ctx when the stack was already empty.");
+ }
+
const prev = this._transformStack.pop();
if (prev) {
return canvasEntry;
}
+ delete(id) {
+ delete this.cache[id];
+ }
+
clear() {
for (const id in this.cache) {
const canvasEntry = this.cache[id];
}
+function drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) {
+ const [a, b, c, d, tx, ty] = ctx.mozCurrentTransform;
+
+ if (b === 0 && c === 0) {
+ const tlX = destX * a + tx;
+ const rTlX = Math.round(tlX);
+ const tlY = destY * d + ty;
+ const rTlY = Math.round(tlY);
+ const brX = (destX + destW) * a + tx;
+ const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
+ const brY = (destY + destH) * d + ty;
+ const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
+ ctx.setTransform(Math.sign(a), 0, 0, Math.sign(d), rTlX, rTlY);
+ ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight);
+ ctx.setTransform(a, b, c, d, tx, ty);
+ return [rWidth, rHeight];
+ }
+
+ if (a === 0 && d === 0) {
+ const tlX = destY * c + tx;
+ const rTlX = Math.round(tlX);
+ const tlY = destX * b + ty;
+ const rTlY = Math.round(tlY);
+ const brX = (destY + destH) * c + tx;
+ const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
+ const brY = (destX + destW) * b + ty;
+ const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
+ ctx.setTransform(0, Math.sign(b), Math.sign(c), 0, rTlX, rTlY);
+ ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth);
+ ctx.setTransform(a, b, c, d, tx, ty);
+ return [rHeight, rWidth];
+ }
+
+ ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH);
+ const scaleX = Math.hypot(a, b);
+ const scaleY = Math.hypot(c, d);
+ return [scaleX * destW, scaleY * destH];
+}
+
function compileType3Glyph(imgData) {
+ const {
+ width,
+ height
+ } = imgData;
+
+ if (!COMPILE_TYPE3_GLYPHS || width > MAX_SIZE_TO_COMPILE || height > MAX_SIZE_TO_COMPILE) {
+ return null;
+ }
+
const POINT_TO_PROCESS_LIMIT = 1000;
const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
- const width = imgData.width,
- height = imgData.height,
- width1 = width + 1;
- let i, ii, j, j0;
- const points = new Uint8Array(width1 * (height + 1));
- const lineSize = width + 7 & ~7,
- data0 = imgData.data;
- const data = new Uint8Array(lineSize * height);
- let pos = 0;
-
- for (i = 0, ii = data0.length; i < ii; i++) {
- const elem = data0[i];
+ const width1 = width + 1;
+ let points = new Uint8Array(width1 * (height + 1));
+ let i, j, j0;
+ const lineSize = width + 7 & ~7;
+ let data = new Uint8Array(lineSize * height),
+ pos = 0;
+
+ for (const elem of imgData.data) {
let mask = 128;
while (mask > 0) {
}
const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
- const outlines = [];
+ let path, outlines, coords;
+
+ if (!_is_node.isNodeJS) {
+ path = new Path2D();
+ } else {
+ outlines = [];
+ }
for (i = 0; count && i <= height; i++) {
let p = i * width1;
continue;
}
- const coords = [p % width1, i];
+ if (path) {
+ path.moveTo(p % width1, i);
+ } else {
+ coords = [p % width1, i];
+ }
+
const p0 = p;
let type = points[p];
points[p] &= type >> 2 | type << 2;
}
- coords.push(p % width1, p / width1 | 0);
+ if (path) {
+ path.lineTo(p % width1, p / width1 | 0);
+ } else {
+ coords.push(p % width1, p / width1 | 0);
+ }
if (!points[p]) {
--count;
}
} while (p0 !== p);
- outlines.push(coords);
+ if (!path) {
+ outlines.push(coords);
+ }
+
--i;
}
+ data = null;
+ points = null;
+
const drawOutline = function (c) {
c.save();
c.scale(1 / width, -1 / height);
c.translate(0, -height);
- c.beginPath();
- for (let k = 0, kk = outlines.length; k < kk; k++) {
- const o = outlines[k];
- c.moveTo(o[0], o[1]);
+ if (path) {
+ c.fill(path);
+ } else {
+ c.beginPath();
+
+ for (const o of outlines) {
+ c.moveTo(o[0], o[1]);
- for (let l = 2, ll = o.length; l < ll; l += 2) {
- c.lineTo(o[l], o[l + 1]);
+ for (let l = 2, ll = o.length; l < ll; l += 2) {
+ c.lineTo(o[l], o[l + 1]);
+ }
}
+
+ c.fill();
}
- c.fill();
c.beginPath();
c.restore();
};
this.maxY = Math.max(this.maxY, y);
}
- updateCurvePathMinMax(transform, x0, y0, x1, y1, x2, y2, x3, y3) {
+ updateRectMinMax(transform, rect) {
+ const p1 = _util.Util.applyTransform(rect, transform);
+
+ const p2 = _util.Util.applyTransform(rect.slice(2), transform);
+
+ this.minX = Math.min(this.minX, p1[0], p2[0]);
+ this.minY = Math.min(this.minY, p1[1], p2[1]);
+ this.maxX = Math.max(this.maxX, p1[0], p2[0]);
+ this.maxY = Math.max(this.maxY, p1[1], p2[1]);
+ }
+
+ updateScalingPathMinMax(transform, minMax) {
+ _util.Util.scaleMinMax(transform, minMax);
+
+ this.minX = Math.min(this.minX, minMax[0]);
+ this.maxX = Math.max(this.maxX, minMax[1]);
+ this.minY = Math.min(this.minY, minMax[2]);
+ this.maxY = Math.max(this.maxY, minMax[3]);
+ }
+
+ updateCurvePathMinMax(transform, x0, y0, x1, y1, x2, y2, x3, y3, minMax) {
const box = _util.Util.bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3);
- this.updatePathMinMax(transform, box[0], box[1]);
- this.updatePathMinMax(transform, box[2], box[3]);
+ if (minMax) {
+ minMax[0] = Math.min(minMax[0], box[0], box[2]);
+ minMax[1] = Math.max(minMax[1], box[0], box[2]);
+ minMax[2] = Math.min(minMax[2], box[1], box[3]);
+ minMax[3] = Math.max(minMax[3], box[1], box[3]);
+ return;
+ }
+
+ this.updateRectMinMax(transform, box);
}
getPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) {
this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]);
}
+ isEmptyClip() {
+ return this.minX === Infinity;
+ }
+
startNewPathAndClipBox(box) {
this.clipBox = box;
this.minX = Infinity;
const dest32DataLength = dest32.length;
const fullSrcDiff = width + 7 >> 3;
let white = 0xffffffff;
- let black = _util.IsLittleEndianCached.value ? 0xff000000 : 0x000000ff;
+ let black = _util.FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
if (transferMapGray) {
if (transferMapGray[0] === 0xff && transferMapGray[0xff] === 0) {
}
function putBinaryImageMask(ctx, imgData) {
+ if (imgData.bitmap) {
+ ctx.drawImage(imgData.bitmap, 0, 0);
+ return;
+ }
+
const height = imgData.height,
width = imgData.width;
const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
for (let i = 0; i < totalChunks; i++) {
const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
- let destPos = 3;
-
- for (let j = 0; j < thisChunkHeight; j++) {
- let elem,
- mask = 0;
-
- for (let k = 0; k < width; k++) {
- if (!mask) {
- elem = src[srcPos++];
- mask = 128;
- }
-
- dest[destPos] = elem & mask ? 0 : 255;
- destPos += 4;
- mask >>= 1;
- }
- }
-
+ ({
+ srcPos
+ } = (0, _image_utils.applyMaskImageData)({
+ src,
+ srcPos,
+ dest,
+ width,
+ height: thisChunkHeight
+ }));
ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
}
}
}
}
-function resetCtxToDefault(ctx) {
- ctx.strokeStyle = "#000000";
- ctx.fillStyle = "#000000";
+function resetCtxToDefault(ctx, foregroundColor) {
+ ctx.strokeStyle = ctx.fillStyle = foregroundColor || "#000000";
ctx.fillRule = "nonzero";
ctx.globalAlpha = 1;
ctx.lineWidth = 1;
const EO_CLIP = {};
class CanvasGraphics {
- constructor(canvasCtx, commonObjs, objs, canvasFactory, imageLayer, optionalContentConfig, annotationCanvasMap) {
+ constructor(canvasCtx, commonObjs, objs, canvasFactory, imageLayer, optionalContentConfig, annotationCanvasMap, pageColors) {
this.ctx = canvasCtx;
this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
this.stateStack = [];
this.viewportScale = 1;
this.outputScaleX = 1;
this.outputScaleY = 1;
+ this.backgroundColor = pageColors?.background || null;
+ this.foregroundColor = pageColors?.foreground || null;
if (canvasCtx) {
addContextCurrentTransform(canvasCtx);
}
+ this._cachedScaleForStroking = null;
this._cachedGetSinglePixelWidth = null;
+ this._cachedBitmapsMap = new Map();
+ }
+
+ getObject(data, fallback = null) {
+ if (typeof data === "string") {
+ return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
+ }
+
+ return fallback;
}
beginDrawing({
}) {
const width = this.ctx.canvas.width;
const height = this.ctx.canvas.height;
+ const defaultBackgroundColor = background || "#ffffff";
this.ctx.save();
- this.ctx.fillStyle = background || "rgb(255, 255, 255)";
+
+ if (this.foregroundColor && this.backgroundColor) {
+ this.ctx.fillStyle = this.foregroundColor;
+ const fg = this.foregroundColor = this.ctx.fillStyle;
+ this.ctx.fillStyle = this.backgroundColor;
+ const bg = this.backgroundColor = this.ctx.fillStyle;
+ let isValidDefaultBg = true;
+ let defaultBg = defaultBackgroundColor;
+ this.ctx.fillStyle = defaultBackgroundColor;
+ defaultBg = this.ctx.fillStyle;
+ isValidDefaultBg = typeof defaultBg === "string" && /^#[0-9A-Fa-f]{6}$/.test(defaultBg);
+
+ if (fg === "#000000" && bg === "#ffffff" || fg === bg || !isValidDefaultBg) {
+ this.foregroundColor = this.backgroundColor = null;
+ } else {
+ const cB = parseInt(defaultBg.slice(1), 16);
+ const rB = (cB && 0xff0000) >> 16;
+ const gB = (cB && 0x00ff00) >> 8;
+ const bB = cB && 0x0000ff;
+
+ const newComp = x => {
+ x /= 255;
+ return x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
+ };
+
+ const lumB = Math.round(0.2126 * newComp(rB) + 0.7152 * newComp(gB) + 0.0722 * newComp(bB));
+
+ this.selectColor = (r, g, b) => {
+ const lumC = 0.2126 * newComp(r) + 0.7152 * newComp(g) + 0.0722 * newComp(b);
+ return Math.round(lumC) === lumB ? bg : fg;
+ };
+ }
+ }
+
+ this.ctx.fillStyle = this.backgroundColor || defaultBackgroundColor;
this.ctx.fillRect(0, 0, width, height);
this.ctx.restore();
}
this.ctx.save();
- resetCtxToDefault(this.ctx);
+ resetCtxToDefault(this.ctx, this.foregroundColor);
if (transform) {
this.ctx.transform.apply(this.ctx, transform);
this.ctx.transform.apply(this.ctx, viewport.transform);
this.viewportScale = viewport.scale;
this.baseTransform = this.ctx.mozCurrentTransform.slice();
- this._combinedScaleFactor = Math.hypot(this.baseTransform[0], this.baseTransform[2]);
if (this.imageLayer) {
this.imageLayer.beginLayout();
}
endDrawing() {
- while (this.stateStack.length || this.current.activeSMask !== null) {
+ while (this.stateStack.length || this.inSMaskMode) {
this.restore();
}
this.cachedCanvases.clear();
this.cachedPatterns.clear();
+ for (const cache of this._cachedBitmapsMap.values()) {
+ for (const canvas of cache.values()) {
+ if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
+ canvas.width = canvas.height = 0;
+ }
+ }
+
+ cache.clear();
+ }
+
+ this._cachedBitmapsMap.clear();
+
if (this.imageLayer) {
this.imageLayer.endLayout();
}
heightScale /= paintHeight / newHeight;
}
- tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
+ tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight, false);
tmpCtx = tmpCanvas.context;
tmpCtx.clearRect(0, 0, newWidth, newHeight);
tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
_createMaskCanvas(img) {
const ctx = this.ctx;
- const width = img.width,
- height = img.height;
+ const {
+ width,
+ height
+ } = img;
const fillColor = this.current.fillColor;
const isPatternFill = this.current.patternFill;
- const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
- const maskCtx = maskCanvas.context;
- putBinaryImageMask(maskCtx, img);
- const objToCanvas = ctx.mozCurrentTransform;
+ const currentTransform = ctx.mozCurrentTransform;
+ let cache, cacheKey, scaled, maskCanvas;
- let maskToCanvas = _util.Util.transform(objToCanvas, [1 / width, 0, 0, -1 / height, 0, 0]);
+ if ((img.bitmap || img.data) && img.count > 1) {
+ const mainKey = img.bitmap || img.data.buffer;
+ const withoutTranslation = currentTransform.slice(0, 4);
+ cacheKey = JSON.stringify(isPatternFill ? withoutTranslation : [withoutTranslation, fillColor]);
+ cache = this._cachedBitmapsMap.get(mainKey);
+
+ if (!cache) {
+ cache = new Map();
+
+ this._cachedBitmapsMap.set(mainKey, cache);
+ }
+
+ const cachedImage = cache.get(cacheKey);
+
+ if (cachedImage && !isPatternFill) {
+ const offsetX = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]);
+ const offsetY = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]);
+ return {
+ canvas: cachedImage,
+ offsetX,
+ offsetY
+ };
+ }
+
+ scaled = cachedImage;
+ }
+
+ if (!scaled) {
+ maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height, false);
+ putBinaryImageMask(maskCanvas.context, img);
+ }
+
+ let maskToCanvas = _util.Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]);
maskToCanvas = _util.Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);
const rect = _util.Util.normalizeRect([cord1[0], cord1[1], cord2[0], cord2[1]]);
- const drawnWidth = Math.ceil(rect[2] - rect[0]);
- const drawnHeight = Math.ceil(rect[3] - rect[1]);
+ const drawnWidth = Math.round(rect[2] - rect[0]) || 1;
+ const drawnHeight = Math.round(rect[3] - rect[1]) || 1;
const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight, true);
const fillCtx = fillCanvas.context;
const offsetX = Math.min(cord1[0], cord2[0]);
fillCtx.translate(-offsetX, -offsetY);
fillCtx.transform.apply(fillCtx, maskToCanvas);
- const scaled = this._scaleImage(maskCanvas.canvas, fillCtx.mozCurrentTransformInverse);
+ if (!scaled) {
+ scaled = this._scaleImage(maskCanvas.canvas, fillCtx.mozCurrentTransformInverse);
+ scaled = scaled.img;
+
+ if (cache && isPatternFill) {
+ cache.set(cacheKey, scaled);
+ }
+ }
fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled(fillCtx.mozCurrentTransform, img.interpolate);
- fillCtx.drawImage(scaled.img, 0, 0, scaled.img.width, scaled.img.height, 0, 0, width, height);
+ drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height);
fillCtx.globalCompositeOperation = "source-in";
const inverse = _util.Util.transform(fillCtx.mozCurrentTransformInverse, [1, 0, 0, 1, -offsetX, -offsetY]);
fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, _pattern_helper.PathType.FILL) : fillColor;
fillCtx.fillRect(0, 0, width, height);
+
+ if (cache && !isPatternFill) {
+ this.cachedCanvases.delete("fillCanvas");
+ cache.set(cacheKey, fillCanvas.canvas);
+ }
+
return {
canvas: fillCanvas.canvas,
offsetX: Math.round(offsetX),
}
setLineWidth(width) {
+ if (width !== this.current.lineWidth) {
+ this._cachedScaleForStroking = null;
+ }
+
this.current.lineWidth = width;
this.ctx.lineWidth = width;
}
}
}
+ get inSMaskMode() {
+ return !!this.suspendedCtx;
+ }
+
checkSMaskState() {
- const inSMaskMode = !!this.suspendedCtx;
+ const inSMaskMode = this.inSMaskMode;
if (this.current.activeSMask && !inSMaskMode) {
this.beginSMaskMode();
}
beginSMaskMode() {
- if (this.suspendedCtx) {
+ if (this.inSMaskMode) {
throw new Error("beginSMaskMode called while already in smask mode");
}
}
endSMaskMode() {
- if (!this.suspendedCtx) {
+ if (!this.inSMaskMode) {
throw new Error("endSMaskMode called while not in smask mode");
}
copyCtxState(this.ctx, this.suspendedCtx);
this.ctx = this.suspendedCtx;
- this.current.activeSMask = null;
this.suspendedCtx = null;
}
}
save() {
- this.ctx.save();
+ if (this.inSMaskMode) {
+ copyCtxState(this.ctx, this.suspendedCtx);
+ this.suspendedCtx.save();
+ } else {
+ this.ctx.save();
+ }
+
const old = this.current;
this.stateStack.push(old);
this.current = old.clone();
}
restore() {
- if (this.stateStack.length === 0 && this.current.activeSMask) {
+ if (this.stateStack.length === 0 && this.inSMaskMode) {
this.endSMaskMode();
}
if (this.stateStack.length !== 0) {
this.current = this.stateStack.pop();
- this.ctx.restore();
+
+ if (this.inSMaskMode) {
+ this.suspendedCtx.restore();
+ copyCtxState(this.suspendedCtx, this.ctx);
+ } else {
+ this.ctx.restore();
+ }
+
this.checkSMaskState();
this.pendingClip = null;
+ this._cachedScaleForStroking = null;
this._cachedGetSinglePixelWidth = null;
}
}
transform(a, b, c, d, e, f) {
this.ctx.transform(a, b, c, d, e, f);
+ this._cachedScaleForStroking = null;
this._cachedGetSinglePixelWidth = null;
}
- constructPath(ops, args) {
+ constructPath(ops, args, minMax) {
const ctx = this.ctx;
const current = this.current;
let x = current.x,
y = current.y;
let startX, startY;
+ const currentTransform = ctx.mozCurrentTransform;
+ const isScalingMatrix = currentTransform[0] === 0 && currentTransform[3] === 0 || currentTransform[1] === 0 && currentTransform[2] === 0;
+ const minMaxForBezier = isScalingMatrix ? minMax.slice(0) : null;
for (let i = 0, j = 0, ii = ops.length; i < ii; i++) {
switch (ops[i] | 0) {
ctx.lineTo(x, yh);
}
- current.updatePathMinMax(ctx.mozCurrentTransform, x, y);
- current.updatePathMinMax(ctx.mozCurrentTransform, xw, yh);
+ if (!isScalingMatrix) {
+ current.updateRectMinMax(currentTransform, [x, y, xw, yh]);
+ }
+
ctx.closePath();
break;
x = args[j++];
y = args[j++];
ctx.moveTo(x, y);
- current.updatePathMinMax(ctx.mozCurrentTransform, x, y);
+
+ if (!isScalingMatrix) {
+ current.updatePathMinMax(currentTransform, x, y);
+ }
+
break;
case _util.OPS.lineTo:
x = args[j++];
y = args[j++];
ctx.lineTo(x, y);
- current.updatePathMinMax(ctx.mozCurrentTransform, x, y);
+
+ if (!isScalingMatrix) {
+ current.updatePathMinMax(currentTransform, x, y);
+ }
+
break;
case _util.OPS.curveTo:
x = args[j + 4];
y = args[j + 5];
ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
- current.updateCurvePathMinMax(ctx.mozCurrentTransform, startX, startY, args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
+ current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], args[j + 2], args[j + 3], x, y, minMaxForBezier);
j += 6;
break;
startX = x;
startY = y;
ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
- current.updateCurvePathMinMax(ctx.mozCurrentTransform, startX, startY, x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
+ current.updateCurvePathMinMax(currentTransform, startX, startY, x, y, args[j], args[j + 1], args[j + 2], args[j + 3], minMaxForBezier);
x = args[j + 2];
y = args[j + 3];
j += 4;
x = args[j + 2];
y = args[j + 3];
ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
- current.updateCurvePathMinMax(ctx.mozCurrentTransform, startX, startY, args[j], args[j + 1], x, y, x, y);
+ current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], x, y, x, y, minMaxForBezier);
j += 4;
break;
}
}
+ if (isScalingMatrix) {
+ current.updateScalingPathMinMax(currentTransform, minMaxForBezier);
+ }
+
current.setCurrentPoint(x, y);
}
if (this.contentVisible) {
if (typeof strokeColor === "object" && strokeColor?.getPattern) {
- const lineWidth = this.getSinglePixelWidth();
ctx.save();
ctx.strokeStyle = strokeColor.getPattern(ctx, this, ctx.mozCurrentTransformInverse, _pattern_helper.PathType.STROKE);
- ctx.lineWidth = Math.max(lineWidth, this.current.lineWidth);
- ctx.stroke();
+ this.rescaleAndStroke(false);
ctx.restore();
} else {
- const lineWidth = this.getSinglePixelWidth();
-
- if (lineWidth < 0 && -lineWidth >= this.current.lineWidth) {
- ctx.save();
- ctx.resetTransform();
- ctx.lineWidth = Math.round(this._combinedScaleFactor);
- ctx.stroke();
- ctx.restore();
- } else {
- ctx.lineWidth = Math.max(lineWidth, this.current.lineWidth);
- ctx.stroke();
- }
+ this.rescaleAndStroke(true);
}
}
this.moveText(0, this.current.leading);
}
- paintChar(character, x, y, patternTransform, resetLineWidthToOne) {
+ paintChar(character, x, y, patternTransform) {
const ctx = this.ctx;
const current = this.current;
const font = current.font;
}
if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
- if (resetLineWidthToOne) {
- ctx.resetTransform();
- ctx.lineWidth = Math.round(this._combinedScaleFactor);
- }
-
ctx.stroke();
}
}
if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
- if (resetLineWidthToOne) {
- ctx.save();
- ctx.moveTo(x, y);
- ctx.resetTransform();
- ctx.lineWidth = Math.round(this._combinedScaleFactor);
- ctx.strokeText(character, 0, 0);
- ctx.restore();
- } else {
- ctx.strokeText(character, x, y);
- }
+ ctx.strokeText(character, x, y);
}
}
get isFontSubpixelAAEnabled() {
const {
context: ctx
- } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10);
+ } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10, false);
ctx.scale(1.5, 1);
ctx.fillText("I", 0, 10);
const data = ctx.getImageData(0, 0, 10, 10).data;
}
let lineWidth = current.lineWidth;
- let resetLineWidthToOne = false;
const scale = current.textMatrixScale;
if (scale === 0 || lineWidth === 0) {
const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
- this._cachedGetSinglePixelWidth = null;
lineWidth = this.getSinglePixelWidth();
- resetLineWidthToOne = lineWidth < 0;
}
} else {
lineWidth /= scale;
for (i = 0; i < glyphsLength; ++i) {
const glyph = glyphs[i];
- if ((0, _util.isNum)(glyph)) {
+ if (typeof glyph === "number") {
x += spacingDir * glyph * fontSize / 1000;
continue;
}
if (simpleFillText && !accent) {
ctx.fillText(character, scaledX, scaledY);
} else {
- this.paintChar(character, scaledX, scaledY, patternTransform, resetLineWidthToOne);
+ this.paintChar(character, scaledX, scaledY, patternTransform);
if (accent) {
const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;
const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;
- this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform, resetLineWidthToOne);
+ this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform);
}
}
}
return;
}
+ this._cachedScaleForStroking = null;
this._cachedGetSinglePixelWidth = null;
ctx.save();
ctx.transform.apply(ctx, current.textMatrix);
for (i = 0; i < glyphsLength; ++i) {
glyph = glyphs[i];
- if ((0, _util.isNum)(glyph)) {
+ if (typeof glyph === "number") {
spacingLength = spacingDir * glyph * fontSize / 1000;
this.ctx.translate(spacingLength, 0);
current.x += spacingLength * textHScale;
setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
this.ctx.rect(llx, lly, urx - llx, ury - lly);
- this.clip();
+ this.ctx.clip();
this.endPath();
}
}
setStrokeRGBColor(r, g, b) {
- const color = _util.Util.makeHexColor(r, g, b);
+ const color = this.selectColor?.(r, g, b) || _util.Util.makeHexColor(r, g, b);
this.ctx.strokeStyle = color;
this.current.strokeColor = color;
}
setFillRGBColor(r, g, b) {
- const color = _util.Util.makeHexColor(r, g, b);
+ const color = this.selectColor?.(r, g, b) || _util.Util.makeHexColor(r, g, b);
this.ctx.fillStyle = color;
this.current.fillColor = color;
const width = bbox[2] - bbox[0];
const height = bbox[3] - bbox[1];
this.ctx.rect(bbox[0], bbox[1], width, height);
- this.current.updatePathMinMax(this.ctx.mozCurrentTransform, bbox[0], bbox[1]);
- this.current.updatePathMinMax(this.ctx.mozCurrentTransform, bbox[2], bbox[3]);
+ this.current.updateRectMinMax(this.ctx.mozCurrentTransform, bbox);
this.clip();
this.endPath();
}
}
this.save();
- const suspendedCtx = this.suspendedCtx;
- if (this.current.activeSMask) {
- this.suspendedCtx = null;
+ if (this.inSMaskMode) {
+ this.endSMaskMode();
this.current.activeSMask = null;
}
copyCtxState(currentCtx, groupCtx);
this.ctx = groupCtx;
this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
- this.groupStack.push({
- ctx: currentCtx,
- suspendedCtx
- });
+ this.groupStack.push(currentCtx);
this.groupLevel++;
}
this.groupLevel--;
const groupCtx = this.ctx;
- const {
- ctx,
- suspendedCtx
- } = this.groupStack.pop();
+ const ctx = this.groupStack.pop();
this.ctx = ctx;
this.ctx.imageSmoothingEnabled = false;
- if (suspendedCtx) {
- this.suspendedCtx = suspendedCtx;
- }
-
if (group.smask) {
this.tempSMask = this.smaskStack.pop();
this.restore();
canvas,
context
} = this.annotationCanvas;
- canvas.style.width = `calc(${width}px * var(--viewport-scale-factor))`;
- canvas.style.height = `calc(${height}px * var(--viewport-scale-factor))`;
+ const viewportScaleFactorStr = `var(--zoom-factor) * ${_display_utils.PixelsPerInch.PDF_TO_CSS_UNITS}`;
+ canvas.style.width = `calc(${width}px * ${viewportScaleFactorStr})`;
+ canvas.style.height = `calc(${height}px * ${viewportScaleFactorStr})`;
this.annotationCanvasMap.set(id, canvas);
this.annotationCanvas.savedCtx = this.ctx;
this.ctx = context;
this.ctx.setTransform(scaleX, 0, 0, -scaleY, 0, height * scaleY);
addContextCurrentTransform(this.ctx);
- resetCtxToDefault(this.ctx);
+ resetCtxToDefault(this.ctx, this.foregroundColor);
} else {
- resetCtxToDefault(this.ctx);
+ resetCtxToDefault(this.ctx, this.foregroundColor);
this.ctx.rect(rect[0], rect[1], width, height);
- this.clip();
+ this.ctx.clip();
this.endPath();
}
}
return;
}
+ const count = img.count;
+ img = this.getObject(img.data, img);
+ img.count = count;
const ctx = this.ctx;
- const width = img.width,
- height = img.height;
const glyph = this.processingType3;
- if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
- if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
- glyph.compiled = compileType3Glyph({
- data: img.data,
- width,
- height
- });
- } else {
- glyph.compiled = null;
+ if (glyph) {
+ if (glyph.compiled === undefined) {
+ glyph.compiled = compileType3Glyph(img);
}
- }
- if (glyph?.compiled) {
- glyph.compiled(ctx);
- return;
+ if (glyph.compiled) {
+ glyph.compiled(ctx);
+ return;
+ }
}
const mask = this._createMaskCanvas(img);
this.compose();
}
- paintImageMaskXObjectRepeat(imgData, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
+ paintImageMaskXObjectRepeat(img, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
if (!this.contentVisible) {
return;
}
+ img = this.getObject(img.data, img);
const ctx = this.ctx;
ctx.save();
const currentTransform = ctx.mozCurrentTransform;
ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);
- const mask = this._createMaskCanvas(imgData);
+ const mask = this._createMaskCanvas(img);
ctx.setTransform(1, 0, 0, 1, 0, 0);
const image = images[i];
const width = image.width,
height = image.height;
- const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
+ const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height, false);
const maskCtx = maskCanvas.context;
maskCtx.save();
putBinaryImageMask(maskCtx, image);
ctx.save();
ctx.transform.apply(ctx, image.transform);
ctx.scale(1, -1);
- ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
+ drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
ctx.restore();
}
return;
}
- const imgData = objId.startsWith("g_") ? this.commonObjs.get(objId) : this.objs.get(objId);
+ const imgData = this.getObject(objId);
if (!imgData) {
(0, _util.warn)("Dependent image isn't ready yet");
return;
}
- const imgData = objId.startsWith("g_") ? this.commonObjs.get(objId) : this.objs.get(objId);
+ const imgData = this.getObject(objId);
if (!imgData) {
(0, _util.warn)("Dependent image isn't ready yet");
if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
imgToPaint = imgData;
} else {
- const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
+ const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height, false);
const tmpCtx = tmpCanvas.context;
putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
imgToPaint = tmpCanvas.canvas;
const scaled = this._scaleImage(imgToPaint, ctx.mozCurrentTransformInverse);
ctx.imageSmoothingEnabled = getImageSmoothingEnabled(ctx.mozCurrentTransform, imgData.interpolate);
- ctx.drawImage(scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);
+ const [rWidth, rHeight] = drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);
if (this.imageLayer) {
const position = this.getCanvasPosition(0, -height);
imgData,
left: position[0],
top: position[1],
- width: width / ctx.mozCurrentTransformInverse[0],
- height: height / ctx.mozCurrentTransformInverse[3]
+ width: rWidth,
+ height: rHeight
});
}
const ctx = this.ctx;
const w = imgData.width;
const h = imgData.height;
- const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h);
+ const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h, false);
const tmpCtx = tmpCanvas.context;
putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
ctx.save();
ctx.transform.apply(ctx, entry.transform);
ctx.scale(1, -1);
- ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
+ drawImageAtIntegerCoords(ctx, tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
if (this.imageLayer) {
const position = this.getCanvasPosition(entry.x, entry.y);
endCompat() {}
consumePath(clipBox) {
+ const isEmpty = this.current.isEmptyClip();
+
if (this.pendingClip) {
this.current.updateClipFromPath();
}
const ctx = this.ctx;
if (this.pendingClip) {
- if (this.pendingClip === EO_CLIP) {
- ctx.clip("evenodd");
- } else {
- ctx.clip();
+ if (!isEmpty) {
+ if (this.pendingClip === EO_CLIP) {
+ ctx.clip("evenodd");
+ } else {
+ ctx.clip();
+ }
}
this.pendingClip = null;
}
getSinglePixelWidth() {
- if (this._cachedGetSinglePixelWidth === null) {
+ if (!this._cachedGetSinglePixelWidth) {
const m = this.ctx.mozCurrentTransform;
- const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
- const sqNorm1 = m[0] ** 2 + m[2] ** 2;
- const sqNorm2 = m[1] ** 2 + m[3] ** 2;
- const pixelHeight = Math.sqrt(Math.max(sqNorm1, sqNorm2)) / absDet;
-
- if (sqNorm1 !== sqNorm2 && this._combinedScaleFactor * pixelHeight > 1) {
- this._cachedGetSinglePixelWidth = -(this._combinedScaleFactor * pixelHeight);
- } else if (absDet > Number.EPSILON) {
- this._cachedGetSinglePixelWidth = pixelHeight;
+
+ if (m[1] === 0 && m[2] === 0) {
+ this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m[0]), Math.abs(m[3]));
} else {
- this._cachedGetSinglePixelWidth = 1;
+ const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
+ const normX = Math.hypot(m[0], m[2]);
+ const normY = Math.hypot(m[1], m[3]);
+ this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet;
}
}
return this._cachedGetSinglePixelWidth;
}
+ getScaleForStroking() {
+ if (!this._cachedScaleForStroking) {
+ const {
+ lineWidth
+ } = this.current;
+ const m = this.ctx.mozCurrentTransform;
+ let scaleX, scaleY;
+
+ if (m[1] === 0 && m[2] === 0) {
+ const normX = Math.abs(m[0]);
+ const normY = Math.abs(m[3]);
+
+ if (lineWidth === 0) {
+ scaleX = 1 / normX;
+ scaleY = 1 / normY;
+ } else {
+ const scaledXLineWidth = normX * lineWidth;
+ const scaledYLineWidth = normY * lineWidth;
+ scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1;
+ scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1;
+ }
+ } else {
+ const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
+ const normX = Math.hypot(m[0], m[1]);
+ const normY = Math.hypot(m[2], m[3]);
+
+ if (lineWidth === 0) {
+ scaleX = normY / absDet;
+ scaleY = normX / absDet;
+ } else {
+ const baseArea = lineWidth * absDet;
+ scaleX = normY > baseArea ? normY / baseArea : 1;
+ scaleY = normX > baseArea ? normX / baseArea : 1;
+ }
+ }
+
+ this._cachedScaleForStroking = [scaleX, scaleY];
+ }
+
+ return this._cachedScaleForStroking;
+ }
+
+ rescaleAndStroke(saveRestore) {
+ const {
+ ctx
+ } = this;
+ const {
+ lineWidth
+ } = this.current;
+ const [scaleX, scaleY] = this.getScaleForStroking();
+ ctx.lineWidth = lineWidth || 1;
+
+ if (scaleX === 1 && scaleY === 1) {
+ ctx.stroke();
+ return;
+ }
+
+ let savedMatrix, savedDashes, savedDashOffset;
+
+ if (saveRestore) {
+ savedMatrix = ctx.mozCurrentTransform.slice();
+ savedDashes = ctx.getLineDash().slice();
+ savedDashOffset = ctx.lineDashOffset;
+ }
+
+ ctx.scale(scaleX, scaleY);
+ const scale = Math.max(scaleX, scaleY);
+ ctx.setLineDash(ctx.getLineDash().map(x => x / scale));
+ ctx.lineDashOffset /= scale;
+ ctx.stroke();
+
+ if (saveRestore) {
+ ctx.setTransform(...savedMatrix);
+ ctx.setLineDash(savedDashes);
+ ctx.lineDashOffset = savedDashOffset;
+ }
+ }
+
getCanvasPosition(x, y) {
const transform = this.ctx.mozCurrentTransform;
return [transform[0] * x + transform[2] * y + transform[4], transform[1] * x + transform[3] * y + transform[5]];
exports.TilingPattern = exports.PathType = void 0;
exports.getShadingPattern = getShadingPattern;
-var _util = __w_pdfjs_require__(2);
+var _util = __w_pdfjs_require__(1);
+
+var _is_node = __w_pdfjs_require__(3);
const PathType = {
FILL: "Fill",
exports.PathType = PathType;
function applyBoundingBox(ctx, bbox) {
- if (!bbox || typeof Path2D === "undefined") {
+ if (!bbox || _is_node.isNodeJS) {
return;
}
tmpCtx.translate(-(dimx.scale * adjustedX0), -(dimy.scale * adjustedY0));
graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
+ tmpCtx.save();
this.clipBbox(graphics, adjustedX0, adjustedY0, adjustedX1, adjustedY1);
graphics.baseTransform = graphics.ctx.mozCurrentTransform.slice();
graphics.executeOperatorList(operatorList);
const bboxWidth = x1 - x0;
const bboxHeight = y1 - y0;
graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
+ graphics.current.updateRectMinMax(graphics.ctx.mozCurrentTransform, [x0, y0, x1, y1]);
graphics.clip();
graphics.endPath();
}
/***/ }),
/* 12 */
+/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
+
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports.applyMaskImageData = applyMaskImageData;
+
+var _util = __w_pdfjs_require__(1);
+
+function applyMaskImageData({
+ src,
+ srcPos = 0,
+ dest,
+ destPos = 0,
+ width,
+ height,
+ inverseDecode = false
+}) {
+ const opaque = _util.FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
+ const [zeroMapping, oneMapping] = !inverseDecode ? [opaque, 0] : [0, opaque];
+ const widthInSource = width >> 3;
+ const widthRemainder = width & 7;
+ const srcLength = src.length;
+ dest = new Uint32Array(dest.buffer);
+
+ for (let i = 0; i < height; i++) {
+ for (const max = srcPos + widthInSource; srcPos < max; srcPos++) {
+ const elem = srcPos < srcLength ? src[srcPos] : 255;
+ dest[destPos++] = elem & 0b10000000 ? oneMapping : zeroMapping;
+ dest[destPos++] = elem & 0b1000000 ? oneMapping : zeroMapping;
+ dest[destPos++] = elem & 0b100000 ? oneMapping : zeroMapping;
+ dest[destPos++] = elem & 0b10000 ? oneMapping : zeroMapping;
+ dest[destPos++] = elem & 0b1000 ? oneMapping : zeroMapping;
+ dest[destPos++] = elem & 0b100 ? oneMapping : zeroMapping;
+ dest[destPos++] = elem & 0b10 ? oneMapping : zeroMapping;
+ dest[destPos++] = elem & 0b1 ? oneMapping : zeroMapping;
+ }
+
+ if (widthRemainder === 0) {
+ continue;
+ }
+
+ const elem = srcPos < srcLength ? src[srcPos++] : 255;
+
+ for (let j = 0; j < widthRemainder; j++) {
+ dest[destPos++] = elem & 1 << 7 - j ? oneMapping : zeroMapping;
+ }
+ }
+
+ return {
+ srcPos,
+ destPos
+ };
+}
+
+/***/ }),
+/* 13 */
/***/ ((__unused_webpack_module, exports) => {
GlobalWorkerOptions.workerSrc = GlobalWorkerOptions.workerSrc === undefined ? "" : GlobalWorkerOptions.workerSrc;
/***/ }),
-/* 13 */
+/* 14 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
}));
exports.MessageHandler = void 0;
-var _util = __w_pdfjs_require__(2);
+var _util = __w_pdfjs_require__(1);
const CallbackKind = {
UNKNOWN: 0,
function wrapReason(reason) {
if (!(reason instanceof Error || typeof reason === "object" && reason !== null)) {
- (0, _util.warn)('wrapReason: Expected "reason" to be a (possibly cloned) Error.');
- return reason;
+ (0, _util.unreachable)('wrapReason: Expected "reason" to be a (possibly cloned) Error.');
}
switch (reason.name) {
exports.MessageHandler = MessageHandler;
/***/ }),
-/* 14 */
+/* 15 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
}));
exports.Metadata = void 0;
-var _util = __w_pdfjs_require__(2);
+var _util = __w_pdfjs_require__(1);
class Metadata {
#metadataMap;
exports.Metadata = Metadata;
/***/ }),
-/* 15 */
+/* 16 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
}));
exports.OptionalContentConfig = void 0;
-var _util = __w_pdfjs_require__(2);
+var _util = __w_pdfjs_require__(1);
class OptionalContentGroup {
constructor(name, intent) {
exports.OptionalContentConfig = OptionalContentConfig;
/***/ }),
-/* 16 */
+/* 17 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
}));
exports.PDFDataTransportStream = void 0;
-var _util = __w_pdfjs_require__(2);
+var _util = __w_pdfjs_require__(1);
-var _display_utils = __w_pdfjs_require__(1);
+var _display_utils = __w_pdfjs_require__(5);
class PDFDataTransportStream {
constructor(params, pdfDataRangeTransport) {
}
/***/ }),
-/* 17 */
+/* 18 */
/***/ ((__unused_webpack_module, exports) => {
exports.XfaText = XfaText;
/***/ }),
-/* 18 */
+/* 19 */
+/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
+
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports.NodeStandardFontDataFactory = exports.NodeCanvasFactory = exports.NodeCMapReaderFactory = void 0;
+
+var _base_factory = __w_pdfjs_require__(6);
+
+;
+
+const fetchData = function (url) {
+ return new Promise((resolve, reject) => {
+ const fs = require("fs");
+
+ fs.readFile(url, (error, data) => {
+ if (error || !data) {
+ reject(new Error(error));
+ return;
+ }
+
+ resolve(new Uint8Array(data));
+ });
+ });
+};
+
+class NodeCanvasFactory extends _base_factory.BaseCanvasFactory {
+ _createCanvas(width, height) {
+ const Canvas = require("canvas");
+
+ return Canvas.createCanvas(width, height);
+ }
+
+}
+
+exports.NodeCanvasFactory = NodeCanvasFactory;
+
+class NodeCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
+ _fetchData(url, compressionType) {
+ return fetchData(url).then(data => {
+ return {
+ cMapData: data,
+ compressionType
+ };
+ });
+ }
+
+}
+
+exports.NodeCMapReaderFactory = NodeCMapReaderFactory;
+
+class NodeStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
+ _fetchData(url) {
+ return fetchData(url);
+ }
+
+}
+
+exports.NodeStandardFontDataFactory = NodeStandardFontDataFactory;
+
+/***/ }),
+/* 20 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
}));
exports.AnnotationLayer = void 0;
-var _util = __w_pdfjs_require__(2);
+var _util = __w_pdfjs_require__(1);
-var _display_utils = __w_pdfjs_require__(1);
+var _display_utils = __w_pdfjs_require__(5);
-var _annotation_storage = __w_pdfjs_require__(9);
+var _annotation_storage = __w_pdfjs_require__(8);
-var _scripting_utils = __w_pdfjs_require__(19);
+var _scripting_utils = __w_pdfjs_require__(21);
-var _xfa_layer = __w_pdfjs_require__(20);
+var _xfa_layer = __w_pdfjs_require__(22);
const DEFAULT_TAB_INDEX = 1000;
const GetElementsByNameSet = new WeakSet();
+function getRectDims(rect) {
+ return {
+ width: rect[2] - rect[0],
+ height: rect[3] - rect[1]
+ };
+}
+
class AnnotationElementFactory {
static create(parameters) {
const subtype = parameters.data.annotationType;
page = this.page,
viewport = this.viewport;
const container = document.createElement("section");
- let width = data.rect[2] - data.rect[0];
- let height = data.rect[3] - data.rect[1];
+ let {
+ width,
+ height
+ } = getRectDims(data.rect);
container.setAttribute("data-annotation-id", data.id);
const rect = _util.Util.normalizeRect([data.rect[0], page.view[3] - data.rect[1] + page.view[1], data.rect[2], page.view[3] - data.rect[3] + page.view[1]]);
transform[i] = Math.sign(transform[i]);
}
- container.style.transform = `matrix(${transform.join(",")})`;
- } else {
- container.style.transform = `matrix(${viewport.transform.join(",")})`;
- }
-
- container.style.transformOrigin = `${-rect[0]}px ${-rect[1]}px`;
-
- if (!ignoreBorder && data.borderStyle.width > 0) {
- container.style.borderWidth = `${data.borderStyle.width}px`;
-
- if (data.borderStyle.style !== _util.AnnotationBorderStyleType.UNDERLINE) {
- width -= 2 * data.borderStyle.width;
- height -= 2 * data.borderStyle.width;
- }
+ container.style.transform = `matrix(${transform.join(",")})`;
+ } else {
+ container.style.transform = `matrix(${viewport.transform.join(",")})`;
+ }
+
+ container.style.transformOrigin = `${-rect[0]}px ${-rect[1]}px`;
+
+ if (!ignoreBorder && data.borderStyle.width > 0) {
+ container.style.borderWidth = `${data.borderStyle.width}px`;
+
+ if (data.borderStyle.style !== _util.AnnotationBorderStyleType.UNDERLINE) {
+ width -= 2 * data.borderStyle.width;
+ height -= 2 * data.borderStyle.width;
+ }
+
+ const horizontalRadius = data.borderStyle.horizontalCornerRadius;
+ const verticalRadius = data.borderStyle.verticalCornerRadius;
+
+ if (horizontalRadius > 0 || verticalRadius > 0) {
+ const radius = `${horizontalRadius}px / ${verticalRadius}px`;
+ container.style.borderRadius = radius;
+ }
+
+ switch (data.borderStyle.style) {
+ case _util.AnnotationBorderStyleType.SOLID:
+ container.style.borderStyle = "solid";
+ break;
+
+ case _util.AnnotationBorderStyleType.DASHED:
+ container.style.borderStyle = "dashed";
+ break;
+
+ case _util.AnnotationBorderStyleType.BEVELED:
+ (0, _util.warn)("Unimplemented border style: beveled");
+ break;
+
+ case _util.AnnotationBorderStyleType.INSET:
+ (0, _util.warn)("Unimplemented border style: inset");
+ break;
+
+ case _util.AnnotationBorderStyleType.UNDERLINE:
+ container.style.borderBottomStyle = "solid";
+ break;
+
+ default:
+ break;
+ }
+
+ const borderColor = data.borderColor || data.color || null;
+
+ if (borderColor) {
+ container.style.borderColor = _util.Util.makeHexColor(data.color[0] | 0, data.color[1] | 0, data.color[2] | 0);
+ } else {
+ container.style.borderWidth = 0;
+ }
+ }
+
+ container.style.left = `${rect[0]}px`;
+ container.style.top = `${rect[1]}px`;
+
+ if (data.hasOwnCanvas) {
+ container.style.width = container.style.height = "auto";
+ } else {
+ container.style.width = `${width}px`;
+ container.style.height = `${height}px`;
+ }
+
+ return container;
+ }
+
+ get _commonActions() {
+ const setColor = (jsName, styleName, event) => {
+ const color = event.detail[jsName];
+ event.target.style[styleName] = _scripting_utils.ColorConverters[`${color[0]}_HTML`](color.slice(1));
+ };
+
+ return (0, _util.shadow)(this, "_commonActions", {
+ display: event => {
+ const hidden = event.detail.display % 2 === 1;
+ event.target.style.visibility = hidden ? "hidden" : "visible";
+ this.annotationStorage.setValue(this.data.id, {
+ hidden,
+ print: event.detail.display === 0 || event.detail.display === 3
+ });
+ },
+ print: event => {
+ this.annotationStorage.setValue(this.data.id, {
+ print: event.detail.print
+ });
+ },
+ hidden: event => {
+ event.target.style.visibility = event.detail.hidden ? "hidden" : "visible";
+ this.annotationStorage.setValue(this.data.id, {
+ hidden: event.detail.hidden
+ });
+ },
+ focus: event => {
+ setTimeout(() => event.target.focus({
+ preventScroll: false
+ }), 0);
+ },
+ userName: event => {
+ event.target.title = event.detail.userName;
+ },
+ readonly: event => {
+ if (event.detail.readonly) {
+ event.target.setAttribute("readonly", "");
+ } else {
+ event.target.removeAttribute("readonly");
+ }
+ },
+ required: event => {
+ if (event.detail.required) {
+ event.target.setAttribute("required", "");
+ } else {
+ event.target.removeAttribute("required");
+ }
+ },
+ bgColor: event => {
+ setColor("bgColor", "backgroundColor", event);
+ },
+ fillColor: event => {
+ setColor("fillColor", "backgroundColor", event);
+ },
+ fgColor: event => {
+ setColor("fgColor", "color", event);
+ },
+ textColor: event => {
+ setColor("textColor", "color", event);
+ },
+ borderColor: event => {
+ setColor("borderColor", "borderColor", event);
+ },
+ strokeColor: event => {
+ setColor("strokeColor", "borderColor", event);
+ }
+ });
+ }
+
+ _dispatchEventFromSandbox(actions, jsEvent) {
+ const commonActions = this._commonActions;
- const horizontalRadius = data.borderStyle.horizontalCornerRadius;
- const verticalRadius = data.borderStyle.verticalCornerRadius;
+ for (const name of Object.keys(jsEvent.detail)) {
+ const action = actions[name] || commonActions[name];
- if (horizontalRadius > 0 || verticalRadius > 0) {
- const radius = `${horizontalRadius}px / ${verticalRadius}px`;
- container.style.borderRadius = radius;
+ if (action) {
+ action(jsEvent);
}
+ }
+ }
- switch (data.borderStyle.style) {
- case _util.AnnotationBorderStyleType.SOLID:
- container.style.borderStyle = "solid";
- break;
-
- case _util.AnnotationBorderStyleType.DASHED:
- container.style.borderStyle = "dashed";
- break;
-
- case _util.AnnotationBorderStyleType.BEVELED:
- (0, _util.warn)("Unimplemented border style: beveled");
- break;
+ _setDefaultPropertiesFromJS(element) {
+ if (!this.enableScripting) {
+ return;
+ }
- case _util.AnnotationBorderStyleType.INSET:
- (0, _util.warn)("Unimplemented border style: inset");
- break;
+ const storedData = this.annotationStorage.getRawValue(this.data.id);
- case _util.AnnotationBorderStyleType.UNDERLINE:
- container.style.borderBottomStyle = "solid";
- break;
+ if (!storedData) {
+ return;
+ }
- default:
- break;
- }
+ const commonActions = this._commonActions;
- const borderColor = data.borderColor || data.color || null;
+ for (const [actionName, detail] of Object.entries(storedData)) {
+ const action = commonActions[actionName];
- if (borderColor) {
- container.style.borderColor = _util.Util.makeHexColor(data.color[0] | 0, data.color[1] | 0, data.color[2] | 0);
- } else {
- container.style.borderWidth = 0;
+ if (action) {
+ action({
+ detail,
+ target: element
+ });
+ delete storedData[actionName];
}
}
-
- container.style.left = `${rect[0]}px`;
- container.style.top = `${rect[1]}px`;
-
- if (data.hasOwnCanvas) {
- container.style.width = container.style.height = "auto";
- } else {
- container.style.width = `${width}px`;
- container.style.height = `${height}px`;
- }
-
- return container;
}
_createQuadrilaterals(ignoreBorder = false) {
const link = document.createElement("a");
if (data.url) {
- if (!linkService.addLinkAttributes) {
- (0, _util.warn)("LinkAnnotationElement.render - missing `addLinkAttributes`-method on the `linkService`-instance.");
- }
-
- linkService.addLinkAttributes?.(link, data.url, data.newWindow);
+ linkService.addLinkAttributes(link, data.url, data.newWindow);
} else if (data.action) {
this._bindNamedAction(link, data.action);
} else if (data.dest) {
{
const value = field.defaultValue || "";
storage.setValue(id, {
- value,
- valueAsString: value
+ value
});
break;
}
detail: {
id: this.data.id,
name: eventName,
- value: event.target.checked
+ value: valueGetter(event)
}
});
});
element.style.backgroundColor = color === null ? "transparent" : _util.Util.makeHexColor(color[0], color[1], color[2]);
}
- _dispatchEventFromSandbox(actions, jsEvent) {
- const setColor = (jsName, styleName, event) => {
- const color = event.detail[jsName];
- event.target.style[styleName] = _scripting_utils.ColorConverters[`${color[0]}_HTML`](color.slice(1));
- };
-
- const commonActions = {
- display: event => {
- const hidden = event.detail.display % 2 === 1;
- event.target.style.visibility = hidden ? "hidden" : "visible";
- this.annotationStorage.setValue(this.data.id, {
- hidden,
- print: event.detail.display === 0 || event.detail.display === 3
- });
- },
- print: event => {
- this.annotationStorage.setValue(this.data.id, {
- print: event.detail.print
- });
- },
- hidden: event => {
- event.target.style.visibility = event.detail.hidden ? "hidden" : "visible";
- this.annotationStorage.setValue(this.data.id, {
- hidden: event.detail.hidden
- });
- },
- focus: event => {
- setTimeout(() => event.target.focus({
- preventScroll: false
- }), 0);
- },
- userName: event => {
- event.target.title = event.detail.userName;
- },
- readonly: event => {
- if (event.detail.readonly) {
- event.target.setAttribute("readonly", "");
- } else {
- event.target.removeAttribute("readonly");
- }
- },
- required: event => {
- if (event.detail.required) {
- event.target.setAttribute("required", "");
- } else {
- event.target.removeAttribute("required");
- }
- },
- bgColor: event => {
- setColor("bgColor", "backgroundColor", event);
- },
- fillColor: event => {
- setColor("fillColor", "backgroundColor", event);
- },
- fgColor: event => {
- setColor("fgColor", "color", event);
- },
- textColor: event => {
- setColor("textColor", "color", event);
- },
- borderColor: event => {
- setColor("borderColor", "borderColor", event);
- },
- strokeColor: event => {
- setColor("strokeColor", "borderColor", event);
- }
- };
-
- for (const name of Object.keys(jsEvent.detail)) {
- const action = actions[name] || commonActions[name];
-
- if (action) {
- action(jsEvent);
- }
- }
- }
-
}
class TextWidgetAnnotationElement extends WidgetAnnotationElement {
if (this.renderForms) {
const storedData = storage.getValue(id, {
- value: this.data.fieldValue,
- valueAsString: this.data.fieldValue
+ value: this.data.fieldValue
});
- const textContent = storedData.valueAsString || storedData.value || "";
+ const textContent = storedData.formattedValue || storedData.value || "";
const elementData = {
userValue: null,
formattedValue: null,
- beforeInputSelectionRange: null,
- beforeInputValue: null
+ valueOnFocus: ""
};
if (this.data.multiLine) {
this.setPropertyOnSiblings(element, "value", event.target.value, "value");
});
element.addEventListener("resetform", event => {
- const defaultValue = this.data.defaultFieldValue || "";
+ const defaultValue = this.data.defaultFieldValue ?? "";
element.value = elementData.userValue = defaultValue;
- delete elementData.formattedValue;
+ elementData.formattedValue = null;
});
let blurListener = event => {
- if (elementData.formattedValue) {
- event.target.value = elementData.formattedValue;
+ const {
+ formattedValue
+ } = elementData;
+
+ if (formattedValue !== null && formattedValue !== undefined) {
+ event.target.value = formattedValue;
}
event.target.scrollLeft = 0;
- elementData.beforeInputSelectionRange = null;
};
if (this.enableScripting && this.hasJSActions) {
if (elementData.userValue) {
event.target.value = elementData.userValue;
}
+
+ elementData.valueOnFocus = event.target.value;
});
element.addEventListener("updatefromsandbox", jsEvent => {
const actions = {
value(event) {
- elementData.userValue = event.detail.value || "";
+ elementData.userValue = event.detail.value ?? "";
storage.setValue(id, {
value: elementData.userValue.toString()
});
-
- if (!elementData.formattedValue) {
- event.target.value = elementData.userValue;
- }
+ event.target.value = elementData.userValue;
},
- valueAsString(event) {
- elementData.formattedValue = event.detail.valueAsString || "";
+ formattedValue(event) {
+ const {
+ formattedValue
+ } = event.detail;
+ elementData.formattedValue = formattedValue;
- if (event.target !== document.activeElement) {
- event.target.value = elementData.formattedValue;
+ if (formattedValue !== null && formattedValue !== undefined && event.target !== document.activeElement) {
+ event.target.value = formattedValue;
}
storage.setValue(id, {
- formattedValue: elementData.formattedValue
+ formattedValue
});
},
selRange(event) {
- const [selStart, selEnd] = event.detail.selRange;
-
- if (selStart >= 0 && selEnd < event.target.value.length) {
- event.target.setSelectionRange(selStart, selEnd);
- }
+ event.target.setSelectionRange(...event.detail.selRange);
}
};
this._dispatchEventFromSandbox(actions, jsEvent);
});
element.addEventListener("keydown", event => {
- elementData.beforeInputValue = event.target.value;
let commitKey = -1;
if (event.key === "Escape") {
return;
}
- elementData.userValue = event.target.value;
+ const {
+ value
+ } = event.target;
+
+ if (elementData.valueOnFocus === value) {
+ return;
+ }
+
+ elementData.userValue = value;
this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
source: this,
detail: {
id,
name: "Keystroke",
- value: event.target.value,
+ value,
willCommit: true,
commitKey,
selStart: event.target.selectionStart,
const _blurListener = blurListener;
blurListener = null;
element.addEventListener("blur", event => {
- if (this._mouseState.isDown) {
- elementData.userValue = event.target.value;
+ const {
+ value
+ } = event.target;
+ elementData.userValue = value;
+
+ if (this._mouseState.isDown && elementData.valueOnFocus !== value) {
this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
source: this,
detail: {
id,
name: "Keystroke",
- value: event.target.value,
+ value,
willCommit: true,
commitKey: 1,
selStart: event.target.selectionStart,
_blurListener(event);
});
- element.addEventListener("mousedown", event => {
- elementData.beforeInputValue = event.target.value;
- elementData.beforeInputSelectionRange = null;
- });
- element.addEventListener("keyup", event => {
- if (event.target.selectionStart === event.target.selectionEnd) {
- elementData.beforeInputSelectionRange = null;
- }
- });
- element.addEventListener("select", event => {
- elementData.beforeInputSelectionRange = [event.target.selectionStart, event.target.selectionEnd];
- });
if (this.data.actions?.Keystroke) {
- element.addEventListener("input", event => {
- let selStart = -1;
- let selEnd = -1;
+ element.addEventListener("beforeinput", event => {
+ const {
+ data,
+ target
+ } = event;
+ const {
+ value,
+ selectionStart,
+ selectionEnd
+ } = target;
+ let selStart = selectionStart,
+ selEnd = selectionEnd;
+
+ switch (event.inputType) {
+ case "deleteWordBackward":
+ {
+ const match = value.substring(0, selectionStart).match(/\w*[^\w]*$/);
+
+ if (match) {
+ selStart -= match[0].length;
+ }
+
+ break;
+ }
+
+ case "deleteWordForward":
+ {
+ const match = value.substring(selectionStart).match(/^[^\w]*\w*/);
+
+ if (match) {
+ selEnd += match[0].length;
+ }
+
+ break;
+ }
+
+ case "deleteContentBackward":
+ if (selectionStart === selectionEnd) {
+ selStart -= 1;
+ }
+
+ break;
+
+ case "deleteContentForward":
+ if (selectionStart === selectionEnd) {
+ selEnd += 1;
+ }
- if (elementData.beforeInputSelectionRange) {
- [selStart, selEnd] = elementData.beforeInputSelectionRange;
+ break;
}
+ event.preventDefault();
this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
source: this,
detail: {
id,
name: "Keystroke",
- value: elementData.beforeInputValue,
- change: event.data,
+ value,
+ change: data || "",
willCommit: false,
selStart,
selEnd
this._setBackgroundColor(element);
+ this._setDefaultPropertiesFromJS(element);
+
this.container.appendChild(element);
return this.container;
}
this._setBackgroundColor(element);
+ this._setDefaultPropertiesFromJS(element);
+
this.container.appendChild(element);
return this.container;
}
this._setBackgroundColor(element);
+ this._setDefaultPropertiesFromJS(element);
+
this.container.appendChild(element);
return this.container;
}
container.title = this.data.alternativeText;
}
+ this._setDefaultPropertiesFromJS(container);
+
return container;
}
this.container.className = "choiceWidgetAnnotation";
const storage = this.annotationStorage;
const id = this.data.id;
- storage.getValue(id, {
- value: this.data.fieldValue.length > 0 ? this.data.fieldValue[0] : undefined
+ const storedData = storage.getValue(id, {
+ value: this.data.fieldValue
});
let {
fontSize
optionElement.style.fontSize = fontSizeStyle;
}
- if (this.data.fieldValue.includes(option.exportValue)) {
+ if (storedData.value.includes(option.exportValue)) {
optionElement.setAttribute("selected", true);
}
} else {
selectElement.addEventListener("input", function (event) {
storage.setValue(id, {
- value: getValue(event)
+ value: getValue(event, true)
});
});
}
this._setBackgroundColor(selectElement);
+ this._setDefaultPropertiesFromJS(selectElement);
+
this.container.appendChild(selectElement);
return this.container;
}
render() {
this.container.className = "lineAnnotation";
const data = this.data;
- const width = data.rect[2] - data.rect[0];
- const height = data.rect[3] - data.rect[1];
+ const {
+ width,
+ height
+ } = getRectDims(data.rect);
const svg = this.svgFactory.create(width, height);
const line = this.svgFactory.createElement("svg:line");
line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]);
render() {
this.container.className = "squareAnnotation";
const data = this.data;
- const width = data.rect[2] - data.rect[0];
- const height = data.rect[3] - data.rect[1];
+ const {
+ width,
+ height
+ } = getRectDims(data.rect);
const svg = this.svgFactory.create(width, height);
const borderWidth = data.borderStyle.width;
const square = this.svgFactory.createElement("svg:rect");
render() {
this.container.className = "circleAnnotation";
const data = this.data;
- const width = data.rect[2] - data.rect[0];
- const height = data.rect[3] - data.rect[1];
+ const {
+ width,
+ height
+ } = getRectDims(data.rect);
const svg = this.svgFactory.create(width, height);
const borderWidth = data.borderStyle.width;
const circle = this.svgFactory.createElement("svg:ellipse");
render() {
this.container.className = this.containerClassName;
const data = this.data;
- const width = data.rect[2] - data.rect[0];
- const height = data.rect[3] - data.rect[1];
+ const {
+ width,
+ height
+ } = getRectDims(data.rect);
const svg = this.svgFactory.create(width, height);
let points = [];
render() {
this.container.className = this.containerClassName;
const data = this.data;
- const width = data.rect[2] - data.rect[0];
- const height = data.rect[3] - data.rect[1];
+ const {
+ width,
+ height
+ } = getRectDims(data.rect);
const svg = this.svgFactory.create(width, height);
for (const inkList of data.inkLists) {
this.content = content;
this.linkService.eventBus?.dispatch("fileattachmentannotation", {
source: this,
- id: (0, _util.stringToPDFString)(filename),
filename,
content
});
continue;
}
+ const {
+ width,
+ height
+ } = getRectDims(data.rect);
+
+ if (width <= 0 || height <= 0) {
+ continue;
+ }
+
if (data.annotationType === _util.AnnotationType.POPUP) {
popupAnnotations.push(data);
continue;
exports.AnnotationLayer = AnnotationLayer;
/***/ }),
-/* 19 */
+/* 21 */
/***/ ((__unused_webpack_module, exports) => {
exports.ColorConverters = ColorConverters;
/***/ }),
-/* 20 */
+/* 22 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
}));
exports.XfaLayer = void 0;
-var _util = __w_pdfjs_require__(2);
-
-var _xfa_text = __w_pdfjs_require__(17);
+var _xfa_text = __w_pdfjs_require__(18);
class XfaLayer {
static setupStorage(html, id, element, storage, intent) {
}
if (isHTMLAnchorElement) {
- if (!linkService.addLinkAttributes) {
- (0, _util.warn)("XfaLayer.setAttribute - missing `addLinkAttributes`-method on the `linkService`-instance.");
- }
-
- linkService.addLinkAttributes?.(html, attributes.href, attributes.newWindow);
+ linkService.addLinkAttributes(html, attributes.href, attributes.newWindow);
}
if (storage && attributes.dataId) {
exports.XfaLayer = XfaLayer;
/***/ }),
-/* 21 */
+/* 23 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
}));
exports.renderTextLayer = renderTextLayer;
-var _util = __w_pdfjs_require__(2);
+var _util = __w_pdfjs_require__(1);
const MAX_TEXT_DIVS_TO_RENDER = 100000;
const DEFAULT_FONT_SIZE = 30;
const canvas = this._document.createElement("canvas");
canvas.height = canvas.width = DEFAULT_FONT_SIZE;
- canvas.mozOpaque = true;
this._layoutTextCtx = canvas.getContext("2d", {
alpha: false
});
}
/***/ }),
-/* 22 */
+/* 24 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
}));
exports.SVGGraphics = void 0;
-var _util = __w_pdfjs_require__(2);
+var _util = __w_pdfjs_require__(1);
-var _display_utils = __w_pdfjs_require__(1);
+var _display_utils = __w_pdfjs_require__(5);
-var _is_node = __w_pdfjs_require__(4);
+var _is_node = __w_pdfjs_require__(3);
let SVGGraphics = class {
constructor() {
const LINE_CAP_STYLES = ["butt", "round", "square"];
const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
+ const createObjectURL = function (data, contentType = "", forceDataSchema = false) {
+ if (URL.createObjectURL && typeof Blob !== "undefined" && !forceDataSchema) {
+ return URL.createObjectURL(new Blob([data], {
+ type: contentType
+ }));
+ }
+
+ const digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
+ let buffer = `data:${contentType};base64,`;
+
+ for (let i = 0, ii = data.length; i < ii; i += 3) {
+ const b1 = data[i] & 0xff;
+ const b2 = data[i + 1] & 0xff;
+ const b3 = data[i + 2] & 0xff;
+ const d1 = b1 >> 2,
+ d2 = (b1 & 3) << 4 | b2 >> 4;
+ const d3 = i + 1 < ii ? (b2 & 0xf) << 2 | b3 >> 6 : 64;
+ const d4 = i + 2 < ii ? b3 & 0x3f : 64;
+ buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
+ }
+
+ return buffer;
+ };
+
const convertImgDataToPng = function () {
const PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
const CHUNK_WRAPPER_SIZE = 12;
writePngChunk("IDATA", idat, data, offset);
offset += CHUNK_WRAPPER_SIZE + idat.length;
writePngChunk("IEND", new Uint8Array(0), data, offset);
- return (0, _util.createObjectURL)(data, "image/png", forceDataSchema);
+ return createObjectURL(data, "image/png", forceDataSchema);
}
return function convertImgDataToPng(imgData, forceDataSchema, isMask) {
if (glyph === null) {
x += fontDirection * wordSpacing;
continue;
- } else if ((0, _util.isNum)(glyph)) {
+ } else if (typeof glyph === "number") {
x += spacingDir * glyph * fontSize / 1000;
continue;
}
this.defs.appendChild(this.cssStyle);
}
- const url = (0, _util.createObjectURL)(fontObj.data, fontObj.mimetype, this.forceDataSchema);
+ const url = createObjectURL(fontObj.data, fontObj.mimetype, this.forceDataSchema);
this.cssStyle.textContent += `@font-face { font-family: "${fontObj.loadedName}";` + ` src: url(${url}); }\n`;
}
}
/***/ }),
-/* 23 */
+/* 25 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
}));
exports.PDFNodeStream = void 0;
-var _util = __w_pdfjs_require__(2);
+var _util = __w_pdfjs_require__(1);
-var _network_utils = __w_pdfjs_require__(24);
+var _network_utils = __w_pdfjs_require__(26);
;
}
/***/ }),
-/* 24 */
+/* 26 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
exports.validateRangeRequestCapabilities = validateRangeRequestCapabilities;
exports.validateResponseStatus = validateResponseStatus;
-var _util = __w_pdfjs_require__(2);
+var _util = __w_pdfjs_require__(1);
-var _content_disposition = __w_pdfjs_require__(25);
+var _content_disposition = __w_pdfjs_require__(27);
-var _display_utils = __w_pdfjs_require__(1);
+var _display_utils = __w_pdfjs_require__(5);
function validateRangeRequestCapabilities({
getResponseHeader,
rangeChunkSize,
disableRange
}) {
- (0, _util.assert)(rangeChunkSize > 0, "Range chunk size must be larger than zero");
const returnValues = {
allowRangeRequests: false,
suggestedLength: undefined
}
/***/ }),
-/* 25 */
+/* 27 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
}));
exports.getFilenameFromContentDispositionHeader = getFilenameFromContentDispositionHeader;
-var _util = __w_pdfjs_require__(2);
+var _util = __w_pdfjs_require__(1);
function getFilenameFromContentDispositionHeader(contentDisposition) {
let needsEncodingFixup = true;
const buffer = (0, _util.stringToBytes)(value);
value = decoder.decode(buffer);
needsEncodingFixup = false;
- } catch (e) {
- if (/^utf-?8$/i.test(encoding)) {
- try {
- value = decodeURIComponent(escape(value));
- needsEncodingFixup = false;
- } catch (err) {}
- }
- }
+ } catch (e) {}
}
return value;
}
/***/ }),
-/* 26 */
+/* 28 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
}));
exports.PDFNetworkStream = void 0;
-var _util = __w_pdfjs_require__(2);
+var _util = __w_pdfjs_require__(1);
-var _network_utils = __w_pdfjs_require__(24);
+var _network_utils = __w_pdfjs_require__(26);
;
const OK_RESPONSE = 200;
}
/***/ }),
-/* 27 */
+/* 29 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
}));
exports.PDFFetchStream = void 0;
-var _util = __w_pdfjs_require__(2);
+var _util = __w_pdfjs_require__(1);
-var _network_utils = __w_pdfjs_require__(24);
+var _network_utils = __w_pdfjs_require__(26);
;
return _util.InvalidPDFException;
}
}));
-Object.defineProperty(exports, "LinkTarget", ({
- enumerable: true,
- get: function () {
- return _display_utils.LinkTarget;
- }
-}));
Object.defineProperty(exports, "LoopbackPort", ({
enumerable: true,
get: function () {
return _xfa_layer.XfaLayer;
}
}));
-Object.defineProperty(exports, "addLinkAttributes", ({
- enumerable: true,
- get: function () {
- return _display_utils.addLinkAttributes;
- }
-}));
Object.defineProperty(exports, "build", ({
enumerable: true,
get: function () {
return _api.build;
}
}));
-Object.defineProperty(exports, "createObjectURL", ({
- enumerable: true,
- get: function () {
- return _util.createObjectURL;
- }
-}));
Object.defineProperty(exports, "createPromiseCapability", ({
enumerable: true,
get: function () {
return _display_utils.loadScript;
}
}));
-Object.defineProperty(exports, "removeNullCharacters", ({
- enumerable: true,
- get: function () {
- return _util.removeNullCharacters;
- }
-}));
Object.defineProperty(exports, "renderTextLayer", ({
enumerable: true,
get: function () {
}
}));
-var _display_utils = __w_pdfjs_require__(1);
+var _util = __w_pdfjs_require__(1);
-var _util = __w_pdfjs_require__(2);
+var _api = __w_pdfjs_require__(4);
-var _api = __w_pdfjs_require__(6);
+var _display_utils = __w_pdfjs_require__(5);
-var _annotation_layer = __w_pdfjs_require__(18);
+var _annotation_layer = __w_pdfjs_require__(20);
-var _worker_options = __w_pdfjs_require__(12);
+var _worker_options = __w_pdfjs_require__(13);