@pdfme/pdf-lib
Version:
Create and modify PDF files with JavaScript
1,371 lines • 623 kB
JavaScript
import { Encodings, Font, FontNames } from "@pdf-lib/standard-fonts";
import pako from "pako";
import UPNGModule from "@pdf-lib/upng";
import ColorParser from "color";
import { NodeType, parse } from "node-html-better-parser";
//#region src/utils/base64.ts
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var lookup = new Uint8Array(256);
for (let i = 0; i < 64; i++) lookup[chars.charCodeAt(i)] = i;
var encodeToBase64 = (bytes) => {
let base64 = "";
const len = bytes.length;
for (let i = 0; i < len; i += 3) {
base64 += chars[bytes[i] >> 2];
base64 += chars[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
base64 += chars[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
base64 += chars[bytes[i + 2] & 63];
}
if (len % 3 === 2) base64 = base64.substring(0, base64.length - 1) + "=";
else if (len % 3 === 1) base64 = base64.substring(0, base64.length - 2) + "==";
return base64;
};
var decodeFromBase64 = (base64) => {
let bufferLength = base64.length * .75;
const len = base64.length;
let i;
let p = 0;
let encoded1;
let encoded2;
let encoded3;
let encoded4;
if (base64[base64.length - 1] === "=") {
bufferLength--;
if (base64[base64.length - 2] === "=") bufferLength--;
}
const bytes = new Uint8Array(bufferLength);
for (i = 0; i < len; i += 4) {
encoded1 = lookup[base64.charCodeAt(i)];
encoded2 = lookup[base64.charCodeAt(i + 1)];
encoded3 = lookup[base64.charCodeAt(i + 2)];
encoded4 = lookup[base64.charCodeAt(i + 3)];
bytes[p++] = encoded1 << 2 | encoded2 >> 4;
bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
}
return bytes;
};
var DATA_URI_PREFIX_REGEX = /^(data)?:?([\w/+]+)?;?(charset=[\w-]+|base64)?.*,/i;
/**
* If the `dataUri` input is a data URI, then the data URI prefix must not be
* longer than 100 characters, or this function will fail to decode it.
*
* @param dataUri a base64 data URI or plain base64 string
* @returns a Uint8Array containing the decoded input
*/
var decodeFromBase64DataUri = (dataUri) => {
const trimmedUri = dataUri.trim();
const res = trimmedUri.substring(0, 100).match(DATA_URI_PREFIX_REGEX);
if (!res) return decodeFromBase64(trimmedUri);
const [fullMatch] = res;
return decodeFromBase64(trimmedUri.substring(fullMatch.length));
};
//#endregion
//#region src/utils/strings.ts
var toCharCode = (character) => character.charCodeAt(0);
var toCodePoint = (character) => character.codePointAt(0);
var toHexStringOfMinLength = (num, minLength) => padStart(num.toString(16), minLength, "0").toUpperCase();
var toHexString = (num) => toHexStringOfMinLength(num, 2);
var charFromCode = (code) => String.fromCharCode(code);
var charFromHexCode = (hex) => charFromCode(parseInt(hex, 16));
var padStart = (value, length, padChar) => {
let padding = "";
for (let idx = 0, len = length - value.length; idx < len; idx++) padding += padChar;
return padding + value;
};
var stringAsByteArray = (str) => {
const buffer = new Uint8Array(str.length);
copyStringIntoBuffer(str, buffer, 0);
return buffer;
};
var copyStringIntoBuffer = (str, buffer, offset) => {
const length = str.length;
for (let idx = 0; idx < length; idx++) buffer[offset++] = str.charCodeAt(idx);
return length;
};
var addRandomSuffix = (prefix, suffixLength = 4) => `${prefix}-${Math.floor(Math.random() * 10 ** suffixLength)}`;
var escapeRegExp = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
var cleanText = (text) => text.replace(/\t|\u0085|\u2028|\u2029/g, " ").replace(/[\b\v]/g, "");
var escapedNewlineChars = [
"\\n",
"\\f",
"\\r",
"\\v"
];
var newlineChars = [
"\n",
"\f",
"\r",
"\v"
];
var isNewlineChar = (text) => /^[\n\f\r\v]$/.test(text);
var lineSplit = (text) => text.split(/[\n\f\r\v]/);
var mergeLines = (text) => text.replace(/[\n\f\r\v]/g, " ");
var charAtIndex = (text, index) => {
const cuFirst = text.charCodeAt(index);
let cuSecond;
const nextIndex = index + 1;
let length = 1;
if (cuFirst >= 55296 && cuFirst <= 56319 && text.length > nextIndex) {
cuSecond = text.charCodeAt(nextIndex);
if (cuSecond >= 56320 && cuSecond <= 57343) length = 2;
}
return [text.slice(index, index + length), length];
};
var charSplit = (text) => {
const chars = [];
for (let idx = 0, len = text.length; idx < len;) {
const [c, cLen] = charAtIndex(text, idx);
chars.push(c);
idx += cLen;
}
return chars;
};
var buildWordBreakRegex = (wordBreaks) => {
const newlineCharUnion = escapedNewlineChars.join("|");
const escapedRules = ["$"];
for (let idx = 0, len = wordBreaks.length; idx < len; idx++) {
const wordBreak = wordBreaks[idx];
if (isNewlineChar(wordBreak)) throw new TypeError(`\`wordBreak\` must not include ${newlineCharUnion}`);
escapedRules.push(wordBreak === "" ? "." : escapeRegExp(wordBreak));
}
const breakRules = escapedRules.join("|");
return new RegExp(`(${newlineCharUnion})|((.*?)(${breakRules}))`, "gm");
};
var breakTextIntoLines = (text, wordBreaks, maxWidth, computeWidthOfText) => {
const regex = buildWordBreakRegex(wordBreaks);
const words = cleanText(text).match(regex);
let currLine = "";
let currWidth = 0;
const lines = [];
const pushCurrLine = () => {
if (currLine !== "") lines.push(currLine);
currLine = "";
currWidth = 0;
};
for (let idx = 0, len = words.length; idx < len; idx++) {
const word = words[idx];
if (isNewlineChar(word)) pushCurrLine();
else {
const width = computeWidthOfText(word);
if (currWidth + width > maxWidth) pushCurrLine();
currLine += word;
currWidth += width;
}
}
pushCurrLine();
return lines;
};
var dateRegex = /^D:(\d\d\d\d)(\d\d)?(\d\d)?(\d\d)?(\d\d)?(\d\d)?([+\-Z])?(\d\d)?'?(\d\d)?'?$/;
var parseDate = (dateStr) => {
const match = dateStr.match(dateRegex);
if (!match) return void 0;
const [, year, month = "01", day = "01", hours = "00", mins = "00", secs = "00", offsetSign = "Z", offsetHours = "00", offsetMins = "00"] = match;
const tzOffset = offsetSign === "Z" ? "Z" : `${offsetSign}${offsetHours}:${offsetMins}`;
return /* @__PURE__ */ new Date(`${year}-${month}-${day}T${hours}:${mins}:${secs}${tzOffset}`);
};
var findLastMatch = (value, regex) => {
if (value.length > 1e4) return {
match: void 0,
pos: 0
};
let position = 0;
let lastMatch;
let iterations = 0;
const MAX_ITERATIONS = 1e3;
while (position < value.length) {
if (++iterations > MAX_ITERATIONS) return {
match: lastMatch,
pos: position
};
const match = value.substring(position).match(regex);
if (!match) return {
match: lastMatch,
pos: position
};
lastMatch = match;
position += (match.index ?? 0) + match[0].length;
}
return {
match: lastMatch,
pos: position
};
};
//#endregion
//#region src/utils/arrays.ts
var last = (array) => array[array.length - 1];
var typedArrayFor = (value) => {
if (value instanceof Uint8Array) return value;
const length = value.length;
const typedArray = new Uint8Array(length);
for (let idx = 0; idx < length; idx++) typedArray[idx] = value.charCodeAt(idx);
return typedArray;
};
var mergeIntoTypedArray = (...arrays) => {
const arrayCount = arrays.length;
const typedArrays = [];
for (let idx = 0; idx < arrayCount; idx++) {
const element = arrays[idx];
typedArrays[idx] = element instanceof Uint8Array ? element : typedArrayFor(element);
}
let totalSize = 0;
for (let idx = 0; idx < arrayCount; idx++) totalSize += arrays[idx].length;
const merged = new Uint8Array(totalSize);
let offset = 0;
for (let arrIdx = 0; arrIdx < arrayCount; arrIdx++) {
const arr = typedArrays[arrIdx];
for (let byteIdx = 0, arrLen = arr.length; byteIdx < arrLen; byteIdx++) merged[offset++] = arr[byteIdx];
}
return merged;
};
var mergeUint8Arrays = (arrays) => {
let totalSize = 0;
for (let idx = 0, len = arrays.length; idx < len; idx++) totalSize += arrays[idx].length;
const mergedBuffer = new Uint8Array(totalSize);
let offset = 0;
for (let idx = 0, len = arrays.length; idx < len; idx++) {
const array = arrays[idx];
mergedBuffer.set(array, offset);
offset += array.length;
}
return mergedBuffer;
};
var arrayAsString = (array) => {
let str = "";
for (let idx = 0, len = array.length; idx < len; idx++) str += charFromCode(array[idx]);
return str;
};
var byAscendingId = (a, b) => a.id - b.id;
var sortedUniq = (array, indexer) => {
const uniq = [];
for (let idx = 0, len = array.length; idx < len; idx++) {
const curr = array[idx];
const prev = array[idx - 1];
if (idx === 0 || indexer(curr) !== indexer(prev)) uniq.push(curr);
}
return uniq;
};
var isArrayEqual = (arr1, arr2) => {
if (arr1.length !== arr2.length) return false;
for (let i = 0, ii = arr1.length; i < ii; i++) if (arr1[i] !== arr2[i]) return false;
return true;
};
var reverseArray = (array) => {
const arrayLen = array.length;
for (let idx = 0, len = Math.floor(arrayLen / 2); idx < len; idx++) {
const leftIdx = idx;
const rightIdx = arrayLen - idx - 1;
const temp = array[idx];
array[leftIdx] = array[rightIdx];
array[rightIdx] = temp;
}
return array;
};
var sum = (array) => {
let total = 0;
for (let idx = 0, len = array.length; idx < len; idx++) total += array[idx];
return total;
};
var range = (start, end) => {
const arr = Array(end - start);
for (let idx = 0, len = arr.length; idx < len; idx++) arr[idx] = start + idx;
return arr;
};
var pluckIndices = (arr, indices) => {
const plucked = Array(indices.length);
for (let idx = 0, len = indices.length; idx < len; idx++) plucked[idx] = arr[indices[idx]];
return plucked;
};
var canBeConvertedToUint8Array = (input) => input instanceof Uint8Array || input instanceof ArrayBuffer || typeof input === "string";
var toUint8Array = (input) => {
if (typeof input === "string") return decodeFromBase64DataUri(input);
else if (input instanceof ArrayBuffer) return new Uint8Array(input);
else if (input instanceof Uint8Array) return input;
else throw new TypeError("`input` must be one of `string | ArrayBuffer | Uint8Array`");
};
//#endregion
//#region src/utils/async.ts
/**
* Returns a Promise that resolves after at least one tick of the
* Macro Task Queue occurs.
*/
var waitForTick = () => new Promise((resolve) => {
setTimeout(() => resolve(), 0);
});
//#endregion
//#region src/utils/unicode.ts
/**
* Encodes a string to UTF-8.
*
* @param input The string to be encoded.
* @param byteOrderMark Whether or not a byte order marker (BOM) should be added
* to the start of the encoding. (default `true`)
* @returns A Uint8Array containing the UTF-8 encoding of the input string.
*
* -----------------------------------------------------------------------------
*
* JavaScript strings are composed of Unicode code points. Code points are
* integers in the range 0 to 1,114,111 (0x10FFFF). When serializing a string,
* it must be encoded as a sequence of words. A word is typically 8, 16, or 32
* bytes in size. As such, Unicode defines three encoding forms: UTF-8, UTF-16,
* and UTF-32. These encoding forms are described in the Unicode standard [1].
* This function implements the UTF-8 encoding form.
*
* -----------------------------------------------------------------------------
*
* In UTF-8, each code point is mapped to a sequence of 1, 2, 3, or 4 bytes.
* Note that the logic which defines this mapping is slightly convoluted, and
* not as straightforward as the mapping logic for UTF-16 or UTF-32. The UTF-8
* mapping logic is as follows [2]:
*
* • If a code point is in the range U+0000..U+007F, then view it as a 7-bit
* integer: 0bxxxxxxx. Map the code point to 1 byte with the first high order
* bit set to 0:
*
* b1=0b0xxxxxxx
*
* • If a code point is in the range U+0080..U+07FF, then view it as an 11-bit
* integer: 0byyyyyxxxxxx. Map the code point to 2 bytes with the first 5 bits
* of the code point stored in the first byte, and the last 6 bits stored in
* the second byte:
*
* b1=0b110yyyyy b2=0b10xxxxxx
*
* • If a code point is in the range U+0800..U+FFFF, then view it as a 16-bit
* integer, 0bzzzzyyyyyyxxxxxx. Map the code point to 3 bytes with the first
* 4 bits stored in the first byte, the next 6 bits stored in the second byte,
* and the last 6 bits in the third byte:
*
* b1=0b1110zzzz b2=0b10yyyyyy b3=0b10xxxxxx
*
* • If a code point is in the range U+10000...U+10FFFF, then view it as a
* 21-bit integer, 0bvvvzzzzzzyyyyyyxxxxxx. Map the code point to 4 bytes with
* the first 3 bits stored in the first byte, the next 6 bits stored in the
* second byte, the next 6 bits stored in the third byte, and the last 6 bits
* stored in the fourth byte:
*
* b1=0b11110xxx b2=0b10zzzzzz b3=0b10yyyyyy b4=0b10xxxxxx
*
* -----------------------------------------------------------------------------
*
* It is important to note, when iterating through the code points of a string
* in JavaScript, that if a character is encoded as a surrogate pair it will
* increase the string's length by 2 instead of 1 [4]. For example:
*
* ```
* > 'a'.length
* 1
* > '💩'.length
* 2
* > '語'.length
* 1
* > 'a💩語'.length
* 4
* ```
*
* The results of the above example are explained by the fact that the
* characters 'a' and '語' are not represented by surrogate pairs, but '💩' is.
*
* Because of this idiosyncrasy in JavaScript's string implementation and APIs,
* we must "jump" an extra index after encoding a character as a surrogate
* pair. In practice, this means we must increment the index of our for loop by
* 2 if we encode a surrogate pair, and 1 in all other cases.
*
* -----------------------------------------------------------------------------
*
* References:
* - [1] https://www.unicode.org/versions/Unicode12.0.0/UnicodeStandard-12.0.pdf
* 3.9 Unicode Encoding Forms - UTF-8
* - [2] http://www.herongyang.com/Unicode/UTF-8-UTF-8-Encoding.html
* - [3] http://www.herongyang.com/Unicode/UTF-8-UTF-8-Encoding-Algorithm.html
* - [4] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length#Description
*
*/
var utf8Encode = (input, byteOrderMark = true) => {
const encoded = [];
if (byteOrderMark) encoded.push(239, 187, 191);
for (let idx = 0, len = input.length; idx < len;) {
const codePoint = input.codePointAt(idx);
if (codePoint < 128) {
const byte1 = codePoint & 127;
encoded.push(byte1);
idx += 1;
} else if (codePoint < 2048) {
const byte1 = codePoint >> 6 & 31 | 192;
const byte2 = codePoint & 63 | 128;
encoded.push(byte1, byte2);
idx += 1;
} else if (codePoint < 65536) {
const byte1 = codePoint >> 12 & 15 | 224;
const byte2 = codePoint >> 6 & 63 | 128;
const byte3 = codePoint & 63 | 128;
encoded.push(byte1, byte2, byte3);
idx += 1;
} else if (codePoint < 1114112) {
const byte1 = codePoint >> 18 & 7 | 240;
const byte2 = codePoint >> 12 & 63 | 128;
const byte3 = codePoint >> 6 & 63 | 128;
const byte4 = codePoint >> 0 & 63 | 128;
encoded.push(byte1, byte2, byte3, byte4);
idx += 2;
} else throw new Error(`Invalid code point: 0x${toHexString(codePoint)}`);
}
return new Uint8Array(encoded);
};
/**
* Encodes a string to UTF-16.
*
* @param input The string to be encoded.
* @param byteOrderMark Whether or not a byte order marker (BOM) should be added
* to the start of the encoding. (default `true`)
* @returns A Uint16Array containing the UTF-16 encoding of the input string.
*
* -----------------------------------------------------------------------------
*
* JavaScript strings are composed of Unicode code points. Code points are
* integers in the range 0 to 1,114,111 (0x10FFFF). When serializing a string,
* it must be encoded as a sequence of words. A word is typically 8, 16, or 32
* bytes in size. As such, Unicode defines three encoding forms: UTF-8, UTF-16,
* and UTF-32. These encoding forms are described in the Unicode standard [1].
* This function implements the UTF-16 encoding form.
*
* -----------------------------------------------------------------------------
*
* In UTF-16, each code point is mapped to one or two 16-bit integers. The
* UTF-16 mapping logic is as follows [2]:
*
* • If a code point is in the range U+0000..U+FFFF, then map the code point to
* a 16-bit integer with the most significant byte first.
*
* • If a code point is in the range U+10000..U+10000, then map the code point
* to two 16-bit integers. The first integer should contain the high surrogate
* and the second integer should contain the low surrogate. Both surrogates
* should be written with the most significant byte first.
*
* -----------------------------------------------------------------------------
*
* It is important to note, when iterating through the code points of a string
* in JavaScript, that if a character is encoded as a surrogate pair it will
* increase the string's length by 2 instead of 1 [4]. For example:
*
* ```
* > 'a'.length
* 1
* > '💩'.length
* 2
* > '語'.length
* 1
* > 'a💩語'.length
* 4
* ```
*
* The results of the above example are explained by the fact that the
* characters 'a' and '語' are not represented by surrogate pairs, but '💩' is.
*
* Because of this idiosyncrasy in JavaScript's string implementation and APIs,
* we must "jump" an extra index after encoding a character as a surrogate
* pair. In practice, this means we must increment the index of our for loop by
* 2 if we encode a surrogate pair, and 1 in all other cases.
*
* -----------------------------------------------------------------------------
*
* References:
* - [1] https://www.unicode.org/versions/Unicode12.0.0/UnicodeStandard-12.0.pdf
* 3.9 Unicode Encoding Forms - UTF-8
* - [2] http://www.herongyang.com/Unicode/UTF-16-UTF-16-Encoding.html
* - [3] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length#Description
*
*/
var utf16Encode = (input, byteOrderMark = true) => {
const encoded = [];
if (byteOrderMark) encoded.push(65279);
for (let idx = 0, len = input.length; idx < len;) {
const codePoint = input.codePointAt(idx);
if (codePoint < 65536) {
encoded.push(codePoint);
idx += 1;
} else if (codePoint < 1114112) {
encoded.push(highSurrogate(codePoint), lowSurrogate(codePoint));
idx += 2;
} else throw new Error(`Invalid code point: 0x${toHexString(codePoint)}`);
}
return new Uint16Array(encoded);
};
/**
* Returns `true` if the `codePoint` is within the
* Basic Multilingual Plane (BMP). Code points inside the BMP are not encoded
* with surrogate pairs.
* @param codePoint The code point to be evaluated.
*
* Reference: https://en.wikipedia.org/wiki/UTF-16#Description
*/
var isWithinBMP = (codePoint) => codePoint >= 0 && codePoint <= 65535;
/**
* Returns `true` if the given `codePoint` is valid and must be represented
* with a surrogate pair when encoded.
* @param codePoint The code point to be evaluated.
*
* Reference: https://en.wikipedia.org/wiki/UTF-16#Description
*/
var hasSurrogates = (codePoint) => codePoint >= 65536 && codePoint <= 1114111;
var highSurrogate = (codePoint) => Math.floor((codePoint - 65536) / 1024) + 55296;
var lowSurrogate = (codePoint) => (codePoint - 65536) % 1024 + 56320;
var ByteOrder = /* @__PURE__ */ function(ByteOrder) {
ByteOrder["BigEndian"] = "BigEndian";
ByteOrder["LittleEndian"] = "LittleEndian";
return ByteOrder;
}(ByteOrder || {});
var REPLACEMENT = "�".codePointAt(0);
/**
* Decodes a Uint8Array of data to a string using UTF-16.
*
* Note that this function attempts to recover from erronous input by
* inserting the replacement character (�) to mark invalid code points
* and surrogate pairs.
*
* @param input A Uint8Array containing UTF-16 encoded data
* @param byteOrderMark Whether or not a byte order marker (BOM) should be read
* at the start of the encoding. (default `true`)
* @returns The decoded string.
*/
var utf16Decode = (input, byteOrderMark = true) => {
if (input.length <= 1) return String.fromCodePoint(REPLACEMENT);
const byteOrder = byteOrderMark ? readBOM(input) : ByteOrder.BigEndian;
let idx = byteOrderMark ? 2 : 0;
const codePoints = [];
while (input.length - idx >= 2) {
const first = decodeValues(input[idx++], input[idx++], byteOrder);
if (isHighSurrogate(first)) if (input.length - idx < 2) codePoints.push(REPLACEMENT);
else {
const second = decodeValues(input[idx++], input[idx++], byteOrder);
if (isLowSurrogate(second)) codePoints.push(first, second);
else codePoints.push(REPLACEMENT);
}
else if (isLowSurrogate(first)) {
idx += 2;
codePoints.push(REPLACEMENT);
} else codePoints.push(first);
}
if (idx < input.length) codePoints.push(REPLACEMENT);
return String.fromCodePoint(...codePoints);
};
/**
* Returns `true` if the given `codePoint` is a high surrogate.
* @param codePoint The code point to be evaluated.
*
* Reference: https://en.wikipedia.org/wiki/UTF-16#Description
*/
var isHighSurrogate = (codePoint) => codePoint >= 55296 && codePoint <= 56319;
/**
* Returns `true` if the given `codePoint` is a low surrogate.
* @param codePoint The code point to be evaluated.
*
* Reference: https://en.wikipedia.org/wiki/UTF-16#Description
*/
var isLowSurrogate = (codePoint) => codePoint >= 56320 && codePoint <= 57343;
/**
* Decodes the given utf-16 values first and second using the specified
* byte order.
* @param first The first byte of the encoding.
* @param second The second byte of the encoding.
* @param byteOrder The byte order of the encoding.
* Reference: https://en.wikipedia.org/wiki/UTF-16#Examples
*/
var decodeValues = (first, second, byteOrder) => {
if (byteOrder === ByteOrder.LittleEndian) return second << 8 | first;
if (byteOrder === ByteOrder.BigEndian) return first << 8 | second;
throw new Error(`Invalid byteOrder: ${byteOrder}`);
};
/**
* Returns whether the given array contains a byte order mark for the
* UTF-16BE or UTF-16LE encoding. If it has neither, BigEndian is assumed.
*
* Reference: https://en.wikipedia.org/wiki/Byte_order_mark#UTF-16
*
* @param bytes The byte array to be evaluated.
*/
var readBOM = (bytes) => hasUtf16BigEndianBOM(bytes) ? ByteOrder.BigEndian : hasUtf16LittleEndianBOM(bytes) ? ByteOrder.LittleEndian : ByteOrder.BigEndian;
var hasUtf16BigEndianBOM = (bytes) => bytes[0] === 254 && bytes[1] === 255;
var hasUtf16LittleEndianBOM = (bytes) => bytes[0] === 255 && bytes[1] === 254;
var hasUtf16BOM = (bytes) => hasUtf16BigEndianBOM(bytes) || hasUtf16LittleEndianBOM(bytes);
//#endregion
//#region src/utils/numbers.ts
/**
* Converts a number to its string representation in decimal. This function
* differs from simply converting a number to a string with `.toString()`
* because this function's output string will **not** contain exponential
* notation.
*
* Credit: https://stackoverflow.com/a/46545519
*/
var numberToString = (num) => {
let numStr = String(num);
if (Math.abs(num) < 1) {
const e = parseInt(num.toString().split("e-")[1]);
if (e) {
const negative = num < 0;
if (negative) num *= -1;
num *= Math.pow(10, e - 1);
numStr = "0." + Array(e).join("0") + num.toString().substring(2);
if (negative) numStr = "-" + numStr;
}
} else {
let e = parseInt(num.toString().split("+")[1]);
if (e > 20) {
e -= 20;
num /= Math.pow(10, e);
numStr = num.toString() + Array(e + 1).join("0");
}
}
return numStr;
};
var sizeInBytes = (n) => Math.ceil(n.toString(2).length / 8);
/**
* Converts a number into its constituent bytes and returns them as
* a number[].
*
* Returns most significant byte as first element in array. It may be necessary
* to call .reverse() to get the bits in the desired order.
*
* Example:
* bytesFor(0x02A41E) => [ 0b10, 0b10100100, 0b11110 ]
*
* Credit for algorithm: https://stackoverflow.com/a/1936865
*/
var bytesFor = (n) => {
const bytes = new Uint8Array(sizeInBytes(n));
for (let i = 1; i <= bytes.length; i++) bytes[i - 1] = n >> (bytes.length - i) * 8;
return bytes;
};
//#endregion
//#region src/utils/errors.ts
var error = (msg) => {
throw new Error(msg);
};
//#endregion
//#region src/utils/objects.ts
var values = (obj) => Object.keys(obj).map((k) => obj[k]);
var StandardFontValues = values(FontNames);
var isStandardFont = (input) => StandardFontValues.includes(input);
var rectanglesAreEqual = (a, b) => a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
//#endregion
//#region src/utils/validators.ts
var backtick = (val) => `\`${val}\``;
var singleQuote = (val) => `'${val}'`;
var formatValue = (value) => {
const type = typeof value;
if (type === "string") return singleQuote(value);
else if (type === "undefined") return backtick(value);
else return value;
};
var createValueErrorMsg = (value, valueName, values) => {
const allowedValues = Array(values.length);
for (let idx = 0, len = values.length; idx < len; idx++) {
const v = values[idx];
allowedValues[idx] = formatValue(v);
}
const joinedValues = allowedValues.join(" or ");
return `${backtick(valueName)} must be one of ${joinedValues}, but was actually ${formatValue(value)}`;
};
var assertIsOneOf = (value, valueName, allowedValues) => {
if (!Array.isArray(allowedValues)) allowedValues = values(allowedValues);
for (let idx = 0, len = allowedValues.length; idx < len; idx++) if (value === allowedValues[idx]) return;
throw new TypeError(createValueErrorMsg(value, valueName, allowedValues));
};
var assertIsOneOfOrUndefined = (value, valueName, allowedValues) => {
if (!Array.isArray(allowedValues)) allowedValues = values(allowedValues);
assertIsOneOf(value, valueName, allowedValues.concat(void 0));
};
var assertIsSubset = (values$1, valueName, allowedValues) => {
if (!Array.isArray(allowedValues)) allowedValues = values(allowedValues);
for (let idx = 0, len = values$1.length; idx < len; idx++) assertIsOneOf(values$1[idx], valueName, allowedValues);
};
var getType = (val) => {
if (val === null) return "null";
if (val === void 0) return "undefined";
if (typeof val === "string") return "string";
if (isNaN(val)) return "NaN";
if (typeof val === "number") return "number";
if (typeof val === "boolean") return "boolean";
if (typeof val === "symbol") return "symbol";
if (typeof val === "bigint") return "bigint";
if (val.constructor && val.constructor.name) return val.constructor.name;
if (val.name) return val.name;
if (val.constructor) return String(val.constructor);
return String(val);
};
var isType = (value, type) => {
if (type === "null") return value === null;
if (type === "undefined") return value === void 0;
if (type === "string") return typeof value === "string";
if (type === "number") return typeof value === "number" && !isNaN(value);
if (type === "boolean") return typeof value === "boolean";
if (type === "symbol") return typeof value === "symbol";
if (type === "bigint") return typeof value === "bigint";
if (type === Date) return value instanceof Date;
if (type === Array) return value instanceof Array;
if (type === Uint8Array) return value instanceof Uint8Array;
if (type === ArrayBuffer) return value instanceof ArrayBuffer;
if (type === Function) return value instanceof Function;
return value instanceof type[0];
};
var createTypeErrorMsg = (value, valueName, types) => {
const allowedTypes = Array(types.length);
for (let idx = 0, len = types.length; idx < len; idx++) {
const type = types[idx];
if (type === "null") allowedTypes[idx] = backtick("null");
if (type === "undefined") allowedTypes[idx] = backtick("undefined");
if (type === "string") allowedTypes[idx] = backtick("string");
else if (type === "number") allowedTypes[idx] = backtick("number");
else if (type === "boolean") allowedTypes[idx] = backtick("boolean");
else if (type === "symbol") allowedTypes[idx] = backtick("symbol");
else if (type === "bigint") allowedTypes[idx] = backtick("bigint");
else if (type === Array) allowedTypes[idx] = backtick("Array");
else if (type === Uint8Array) allowedTypes[idx] = backtick("Uint8Array");
else if (type === ArrayBuffer) allowedTypes[idx] = backtick("ArrayBuffer");
else allowedTypes[idx] = backtick(type[1]);
}
const joinedTypes = allowedTypes.join(" or ");
return `${backtick(valueName)} must be of type ${joinedTypes}, but was actually of type ${backtick(getType(value))}`;
};
var assertIs = (value, valueName, types) => {
for (let idx = 0, len = types.length; idx < len; idx++) if (isType(value, types[idx])) return;
throw new TypeError(createTypeErrorMsg(value, valueName, types));
};
var assertOrUndefined = (value, valueName, types) => {
assertIs(value, valueName, types.concat("undefined"));
};
var assertEachIs = (values, valueName, types) => {
for (let idx = 0, len = values.length; idx < len; idx++) assertIs(values[idx], valueName, types);
};
var assertRange = (value, valueName, min, max) => {
assertIs(value, valueName, ["number"]);
assertIs(min, "min", ["number"]);
assertIs(max, "max", ["number"]);
max = Math.max(min, max);
if (value < min || value > max) throw new Error(`${backtick(valueName)} must be at least ${min} and at most ${max}, but was actually ${value}`);
};
var assertRangeOrUndefined = (value, valueName, min, max) => {
assertIs(value, valueName, ["number", "undefined"]);
if (typeof value === "number") assertRange(value, valueName, min, max);
};
var assertMultiple = (value, valueName, multiplier) => {
assertIs(value, valueName, ["number"]);
if (value % multiplier !== 0) throw new Error(`${backtick(valueName)} must be a multiple of ${multiplier}, but was actually ${value}`);
};
var assertInteger = (value, valueName) => {
if (!Number.isInteger(value)) throw new Error(`${backtick(valueName)} must be an integer, but was actually ${value}`);
};
var assertPositive = (value, valueName) => {
if (![1, 0].includes(Math.sign(value))) throw new Error(`${backtick(valueName)} must be a positive number or 0, but was actually ${value}`);
};
//#endregion
//#region src/utils/pdfDocEncoding.ts
var pdfDocEncodingToUnicode = new Uint16Array(256);
for (let idx = 0; idx < 256; idx++) pdfDocEncodingToUnicode[idx] = idx;
pdfDocEncodingToUnicode[22] = toCharCode("");
pdfDocEncodingToUnicode[24] = toCharCode("˘");
pdfDocEncodingToUnicode[25] = toCharCode("ˇ");
pdfDocEncodingToUnicode[26] = toCharCode("ˆ");
pdfDocEncodingToUnicode[27] = toCharCode("˙");
pdfDocEncodingToUnicode[28] = toCharCode("˝");
pdfDocEncodingToUnicode[29] = toCharCode("˛");
pdfDocEncodingToUnicode[30] = toCharCode("˚");
pdfDocEncodingToUnicode[31] = toCharCode("˜");
pdfDocEncodingToUnicode[127] = toCharCode("�");
pdfDocEncodingToUnicode[128] = toCharCode("•");
pdfDocEncodingToUnicode[129] = toCharCode("†");
pdfDocEncodingToUnicode[130] = toCharCode("‡");
pdfDocEncodingToUnicode[131] = toCharCode("…");
pdfDocEncodingToUnicode[132] = toCharCode("—");
pdfDocEncodingToUnicode[133] = toCharCode("–");
pdfDocEncodingToUnicode[134] = toCharCode("ƒ");
pdfDocEncodingToUnicode[135] = toCharCode("⁄");
pdfDocEncodingToUnicode[136] = toCharCode("‹");
pdfDocEncodingToUnicode[137] = toCharCode("›");
pdfDocEncodingToUnicode[138] = toCharCode("−");
pdfDocEncodingToUnicode[139] = toCharCode("‰");
pdfDocEncodingToUnicode[140] = toCharCode("„");
pdfDocEncodingToUnicode[141] = toCharCode("“");
pdfDocEncodingToUnicode[142] = toCharCode("”");
pdfDocEncodingToUnicode[143] = toCharCode("‘");
pdfDocEncodingToUnicode[144] = toCharCode("’");
pdfDocEncodingToUnicode[145] = toCharCode("‚");
pdfDocEncodingToUnicode[146] = toCharCode("™");
pdfDocEncodingToUnicode[147] = toCharCode("fi");
pdfDocEncodingToUnicode[148] = toCharCode("fl");
pdfDocEncodingToUnicode[149] = toCharCode("Ł");
pdfDocEncodingToUnicode[150] = toCharCode("Œ");
pdfDocEncodingToUnicode[151] = toCharCode("Š");
pdfDocEncodingToUnicode[152] = toCharCode("Ÿ");
pdfDocEncodingToUnicode[153] = toCharCode("Ž");
pdfDocEncodingToUnicode[154] = toCharCode("ı");
pdfDocEncodingToUnicode[155] = toCharCode("ł");
pdfDocEncodingToUnicode[156] = toCharCode("œ");
pdfDocEncodingToUnicode[157] = toCharCode("š");
pdfDocEncodingToUnicode[158] = toCharCode("ž");
pdfDocEncodingToUnicode[159] = toCharCode("�");
pdfDocEncodingToUnicode[160] = toCharCode("€");
pdfDocEncodingToUnicode[173] = toCharCode("�");
/**
* Decode a byte array into a string using PDFDocEncoding.
*
* @param bytes a byte array (decimal representation) containing a string
* encoded with PDFDocEncoding.
*/
var pdfDocEncodingDecode = (bytes) => {
const codePoints = Array(bytes.length);
for (let idx = 0, len = bytes.length; idx < len; idx++) codePoints[idx] = pdfDocEncodingToUnicode[bytes[idx]];
return String.fromCodePoint(...codePoints);
};
//#endregion
//#region \0@oxc-project+runtime@0.127.0/helpers/typeof.js
function _typeof(o) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
return typeof o;
} : function(o) {
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
}, _typeof(o);
}
//#endregion
//#region \0@oxc-project+runtime@0.127.0/helpers/toPrimitive.js
function toPrimitive(t, r) {
if ("object" != _typeof(t) || !t) return t;
var e = t[Symbol.toPrimitive];
if (void 0 !== e) {
var i = e.call(t, r || "default");
if ("object" != _typeof(i)) return i;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r ? String : Number)(t);
}
//#endregion
//#region \0@oxc-project+runtime@0.127.0/helpers/toPropertyKey.js
function toPropertyKey(t) {
var i = toPrimitive(t, "string");
return "symbol" == _typeof(i) ? i : i + "";
}
//#endregion
//#region \0@oxc-project+runtime@0.127.0/helpers/defineProperty.js
function _defineProperty(e, r, t) {
return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
value: t,
enumerable: !0,
configurable: !0,
writable: !0
}) : e[r] = t, e;
}
//#endregion
//#region src/utils/Cache.ts
var _Cache;
var Cache = class {
constructor(populate) {
_defineProperty(this, "populate", void 0);
_defineProperty(this, "value", void 0);
this.populate = populate;
this.value = void 0;
}
getValue() {
return this.value;
}
access() {
if (!this.value) this.value = this.populate();
return this.value;
}
invalidate() {
this.value = void 0;
}
};
_Cache = Cache;
_defineProperty(Cache, "populatedBy", (populate) => new _Cache(populate));
//#endregion
//#region src/core/errors.ts
var MethodNotImplementedError = class extends Error {
constructor(className, methodName) {
const msg = `Method ${className}.${methodName}() not implemented`;
super(msg);
}
};
var PrivateConstructorError = class extends Error {
constructor(className) {
const msg = `Cannot construct ${className} - it has a private constructor`;
super(msg);
}
};
var UnexpectedObjectTypeError = class extends Error {
constructor(expected, actual) {
const name = (t) => t?.name ?? t?.constructor?.name;
const msg = `Expected instance of ${(Array.isArray(expected) ? expected.map(name) : [name(expected)]).join(" or ")}, but got instance of ${actual ? name(actual) : actual}`;
super(msg);
}
};
var UnsupportedEncodingError = class extends Error {
constructor(encoding) {
const msg = `${encoding} stream encoding not supported`;
super(msg);
}
};
var ReparseError = class extends Error {
constructor(className, methodName) {
const msg = `Cannot call ${className}.${methodName}() more than once`;
super(msg);
}
};
var MissingCatalogError = class extends Error {
constructor(ref) {
const msg = `Missing catalog (ref=${ref})`;
super(msg);
}
};
var MissingPageContentsEmbeddingError = class extends Error {
constructor() {
super(`Can't embed page with missing Contents`);
}
};
var UnrecognizedStreamTypeError = class extends Error {
constructor(stream) {
const msg = `Unrecognized stream type: ${stream?.contructor?.name ?? stream?.name ?? stream}`;
super(msg);
}
};
var PageEmbeddingMismatchedContextError = class extends Error {
constructor() {
super(`Found mismatched contexts while embedding pages. All pages in the array passed to \`PDFDocument.embedPages()\` must be from the same document.`);
}
};
var PDFArrayIsNotRectangleError = class extends Error {
constructor(size) {
const msg = `Attempted to convert PDFArray with ${size} elements to rectangle, but must have exactly 4 elements.`;
super(msg);
}
};
var InvalidPDFDateStringError = class extends Error {
constructor(value) {
const msg = `Attempted to convert "${value}" to a date, but it does not match the PDF date string format.`;
super(msg);
}
};
var InvalidTargetIndexError = class extends Error {
constructor(targetIndex, Count) {
const msg = `Invalid targetIndex specified: targetIndex=${targetIndex} must be less than Count=${Count}`;
super(msg);
}
};
var CorruptPageTreeError = class extends Error {
constructor(targetIndex, operation) {
const msg = `Failed to ${operation} at targetIndex=${targetIndex} due to corrupt page tree: It is likely that one or more 'Count' entries are invalid`;
super(msg);
}
};
var IndexOutOfBoundsError = class extends Error {
constructor(index, min, max) {
const msg = `index should be at least ${min} and at most ${max}, but was actually ${index}`;
super(msg);
}
};
var InvalidAcroFieldValueError = class extends Error {
constructor() {
super(`Attempted to set invalid field value`);
}
};
var MultiSelectValueError = class extends Error {
constructor() {
super(`Attempted to select multiple values for single-select field`);
}
};
var MissingDAEntryError = class extends Error {
constructor(fieldName) {
const msg = `No /DA (default appearance) entry found for field: ${fieldName}`;
super(msg);
}
};
var MissingTfOperatorError = class extends Error {
constructor(fieldName) {
const msg = `No Tf operator found for DA of field: ${fieldName}`;
super(msg);
}
};
var NumberParsingError = class extends Error {
constructor(pos, value) {
const msg = `Failed to parse number (line:${pos.line} col:${pos.column} offset=${pos.offset}): "${value}"`;
super(msg);
}
};
var PDFParsingError = class extends Error {
constructor(pos, details) {
const msg = `Failed to parse PDF document (line:${pos.line} col:${pos.column} offset=${pos.offset}): ${details}`;
super(msg);
}
};
var NextByteAssertionError = class extends PDFParsingError {
constructor(pos, expectedByte, actualByte) {
const msg = `Expected next byte to be ${expectedByte} but it was actually ${actualByte}`;
super(pos, msg);
}
};
var PDFObjectParsingError = class extends PDFParsingError {
constructor(pos, byte) {
const msg = `Failed to parse PDF object starting with the following byte: ${byte}`;
super(pos, msg);
}
};
var PDFInvalidObjectParsingError = class extends PDFParsingError {
constructor(pos) {
super(pos, `Failed to parse invalid PDF object`);
}
};
var PDFStreamParsingError = class extends PDFParsingError {
constructor(pos) {
super(pos, `Failed to parse PDF stream`);
}
};
var UnbalancedParenthesisError = class extends PDFParsingError {
constructor(pos) {
super(pos, `Failed to parse PDF literal string due to unbalanced parenthesis`);
}
};
var DecompressionBombError = class extends Error {
constructor(requested, maxSize) {
const msg = `Decompression bomb detected: requested buffer size ${requested} exceeds maximum allowed size ${maxSize}`;
super(msg);
}
};
var StalledParserError = class extends PDFParsingError {
constructor(pos) {
super(pos, `Parser stalled`);
}
};
var MissingPDFHeaderError = class extends PDFParsingError {
constructor(pos) {
super(pos, `No PDF header found`);
}
};
var MissingKeywordError = class extends PDFParsingError {
constructor(pos, keyword) {
const msg = `Did not find expected keyword '${arrayAsString(keyword)}'`;
super(pos, msg);
}
};
//#endregion
//#region src/core/syntax/CharCodes.ts
var CharCodes = /* @__PURE__ */ function(CharCodes) {
CharCodes[CharCodes["Null"] = 0] = "Null";
CharCodes[CharCodes["Backspace"] = 8] = "Backspace";
CharCodes[CharCodes["Tab"] = 9] = "Tab";
CharCodes[CharCodes["Newline"] = 10] = "Newline";
CharCodes[CharCodes["FormFeed"] = 12] = "FormFeed";
CharCodes[CharCodes["CarriageReturn"] = 13] = "CarriageReturn";
CharCodes[CharCodes["Space"] = 32] = "Space";
CharCodes[CharCodes["ExclamationPoint"] = 33] = "ExclamationPoint";
CharCodes[CharCodes["Hash"] = 35] = "Hash";
CharCodes[CharCodes["Percent"] = 37] = "Percent";
CharCodes[CharCodes["LeftParen"] = 40] = "LeftParen";
CharCodes[CharCodes["RightParen"] = 41] = "RightParen";
CharCodes[CharCodes["Plus"] = 43] = "Plus";
CharCodes[CharCodes["Minus"] = 45] = "Minus";
CharCodes[CharCodes["Dash"] = CharCodes.Minus] = "Dash";
CharCodes[CharCodes["Period"] = 46] = "Period";
CharCodes[CharCodes["ForwardSlash"] = 47] = "ForwardSlash";
CharCodes[CharCodes["Zero"] = 48] = "Zero";
CharCodes[CharCodes["One"] = 49] = "One";
CharCodes[CharCodes["Two"] = 50] = "Two";
CharCodes[CharCodes["Three"] = 51] = "Three";
CharCodes[CharCodes["Four"] = 52] = "Four";
CharCodes[CharCodes["Five"] = 53] = "Five";
CharCodes[CharCodes["Six"] = 54] = "Six";
CharCodes[CharCodes["Seven"] = 55] = "Seven";
CharCodes[CharCodes["Eight"] = 56] = "Eight";
CharCodes[CharCodes["Nine"] = 57] = "Nine";
CharCodes[CharCodes["LessThan"] = 60] = "LessThan";
CharCodes[CharCodes["GreaterThan"] = 62] = "GreaterThan";
CharCodes[CharCodes["A"] = 65] = "A";
CharCodes[CharCodes["D"] = 68] = "D";
CharCodes[CharCodes["E"] = 69] = "E";
CharCodes[CharCodes["F"] = 70] = "F";
CharCodes[CharCodes["O"] = 79] = "O";
CharCodes[CharCodes["P"] = 80] = "P";
CharCodes[CharCodes["R"] = 82] = "R";
CharCodes[CharCodes["LeftSquareBracket"] = 91] = "LeftSquareBracket";
CharCodes[CharCodes["BackSlash"] = 92] = "BackSlash";
CharCodes[CharCodes["RightSquareBracket"] = 93] = "RightSquareBracket";
CharCodes[CharCodes["a"] = 97] = "a";
CharCodes[CharCodes["b"] = 98] = "b";
CharCodes[CharCodes["d"] = 100] = "d";
CharCodes[CharCodes["e"] = 101] = "e";
CharCodes[CharCodes["f"] = 102] = "f";
CharCodes[CharCodes["i"] = 105] = "i";
CharCodes[CharCodes["j"] = 106] = "j";
CharCodes[CharCodes["l"] = 108] = "l";
CharCodes[CharCodes["m"] = 109] = "m";
CharCodes[CharCodes["n"] = 110] = "n";
CharCodes[CharCodes["o"] = 111] = "o";
CharCodes[CharCodes["r"] = 114] = "r";
CharCodes[CharCodes["s"] = 115] = "s";
CharCodes[CharCodes["t"] = 116] = "t";
CharCodes[CharCodes["u"] = 117] = "u";
CharCodes[CharCodes["x"] = 120] = "x";
CharCodes[CharCodes["LeftCurly"] = 123] = "LeftCurly";
CharCodes[CharCodes["RightCurly"] = 125] = "RightCurly";
CharCodes[CharCodes["Tilde"] = 126] = "Tilde";
return CharCodes;
}(CharCodes || {});
//#endregion
//#region src/core/document/PDFHeader.ts
var _PDFHeader;
var PDFHeader = class {
constructor(major, minor) {
_defineProperty(this, "major", void 0);
_defineProperty(this, "minor", void 0);
this.major = String(major);
this.minor = String(minor);
}
toString() {
const bc = charFromCode(129);
return `%PDF-${this.major}.${this.minor}\n%${bc}${bc}${bc}${bc}`;
}
sizeInBytes() {
return 12 + this.major.length + this.minor.length;
}
copyBytesInto(buffer, offset) {
const initialOffset = offset;
buffer[offset++] = CharCodes.Percent;
buffer[offset++] = CharCodes.P;
buffer[offset++] = CharCodes.D;
buffer[offset++] = CharCodes.F;
buffer[offset++] = CharCodes.Dash;
offset += copyStringIntoBuffer(this.major, buffer, offset);
buffer[offset++] = CharCodes.Period;
offset += copyStringIntoBuffer(this.minor, buffer, offset);
buffer[offset++] = CharCodes.Newline;
buffer[offset++] = CharCodes.Percent;
buffer[offset++] = 129;
buffer[offset++] = 129;
buffer[offset++] = 129;
buffer[offset++] = 129;
return offset - initialOffset;
}
};
_PDFHeader = PDFHeader;
_defineProperty(PDFHeader, "forVersion", (major, minor) => new _PDFHeader(major, minor));
//#endregion
//#region src/core/objects/PDFObject.ts
var PDFObject = class {
clone(_context) {
throw new MethodNotImplementedError(this.constructor.name, "clone");
}
toString() {
throw new MethodNotImplementedError(this.constructor.name, "toString");
}
sizeInBytes() {
throw new MethodNotImplementedError(this.constructor.name, "sizeInBytes");
}
copyBytesInto(_buffer, _offset) {
throw new MethodNotImplementedError(this.constructor.name, "copyBytesInto");
}
};
//#endregion
//#region src/core/objects/PDFNumber.ts
var _PDFNumber;
var PDFNumber = class PDFNumber extends PDFObject {
constructor(value) {
super();
_defineProperty(this, "numberValue", void 0);
_defineProperty(this, "stringValue", void 0);
this.numberValue = value;
this.stringValue = numberToString(value);
}
asNumber() {
return this.numberValue;
}
/** @deprecated in favor of [[PDFNumber.asNumber]] */
value() {
return this.numberValue;
}
clone() {
return PDFNumber.of(this.numberValue);
}
toString() {
return this.stringValue;
}
sizeInBytes() {
return this.stringValue.length;
}
copyBytesInto(buffer, offset) {
offset += copyStringIntoBuffer(this.stringValue, buffer, offset);
return this.stringValue.length;
}
};
_PDFNumber = PDFNumber;
_defineProperty(PDFNumber, "of", (value) => new _PDFNumber(value));
//#endregion
//#region src/core/objects/PDFArray.ts
var _PDFArray;
var PDFArray = class PDFArray extends PDFObject {
constructor(context) {
super();
_defineProperty(this, "array", void 0);
_defineProperty(this, "context", void 0);
this.array = [];
this.context = context;
}
size() {
return this.array.length;
}
push(object) {
this.array.push(object);
}
insert(index, object) {
this.array.splice(index, 0, object);
}
indexOf(object) {
const index = this.array.indexOf(object);
return index === -1 ? void 0 : index;
}
remove(index) {
this.array.splice(index, 1);
}
set(idx, object) {
this.array[idx] = object;
}
get(index) {
return this.array[index];
}
lookupMaybe(index, ...types) {
return this.context.lookupMaybe(this.get(index), ...types);
}
lookup(index, ...types) {
return this.context.lookup(this.get(index), ...types);
}
asRectangle() {
if (this.size() !== 4) throw new PDFArrayIsNotRectangleError(this.size());
const lowerLeftX = this.lookup(0, PDFNumber).asNumber();
const lowerLeftY = this.lookup(1, PDFNumber).asNumber();
const upperRightX = this.lookup(2, PDFNumber).asNumber();
const upperRightY = this.lookup(3, PDFNumber).asNumber();
return {
x: lowerLeftX,
y: lowerLeftY,
width: upperRightX - lowerLeftX,
height: upperRightY - lowerLeftY
};
}
asArray() {
return this.array.slice();
}
clone(context) {
const clone = PDFArray.withContext(context || this.context);
for (let idx = 0, len = this.size(); idx < len; idx++) clone.push(this.array[idx]);
return clone;
}
toString() {
let arrayString = "[ ";
for (let idx = 0, len = this.size(); idx < len; idx++) {
arrayString += this.get(idx).toString();
arrayString += " ";
}
arrayString += "]";
return arrayString;
}
sizeInBytes() {
let size = 3;
for (let idx = 0, len = this.size(); idx < len; idx++) size += this.get(idx).sizeInBytes() + 1;
return size;
}
copyBytesInto(buffer, offset) {
const initialOffset = offset;
buffer[offset++] = CharCodes.LeftSquareBracket;
buffer[offset++] = CharCodes.Space;
for (let idx = 0, len = this.size(); idx < len; idx++) {
offset += this.get(idx).copyBytesInto(buffer, offset);
buffer[offset++] = CharCodes.Space;
}
buffer[offset++] = CharCodes.RightSquareBracket;
return offset - initialOffset;
}
scalePDFNumbers(x, y) {
for (let idx = 0, len = this.size(); idx < len; idx++) {
const el = this.lookup(idx);
if (el instanceof PDFNumber) {
const factor = idx % 2 === 0 ? x : y;
this.set(idx, PDFNumber.of(el.asNumber() * factor));
}
}
}
};
_PDFArray = PDFArray;
_defineProperty(PDFArray, "withContext", (context) => new _PDFArray(context));
//#endregion
//#region src/core/objects/PDFBool.ts
var _PDFBool;
var ENFORCER$2 = {};
var PDFBool = class extends PDFObject {
constructor(enforcer, value) {
if (enforcer !== ENFORCER$2) throw new PrivateConstructorError("PDFBool");
super();
_defineProperty(this, "value", void 0);
this.value = value;
}
asBoolean() {
return this.value;
}
clone() {
return this;
}
toString() {
return String(this.value);
}
sizeInBytes() {
return this.value ? 4 : 5;
}
copyBytesInto(buffer, offset) {
if (this.value) {
buffer[offset++] = CharCodes.t;
buffer[offset++] = CharCodes.r;
buffer[offset++] = CharCodes.u;
buffer[offset++] = CharCodes.e;
return 4;
} else {
buffer[offset++] = CharCodes.f;
buffer[offset++] = CharCodes.a;
buffer[offset++] = CharCodes.l;
buffer[offset++] = CharCodes.s;
buffer[offset++] = CharCodes.e;
return 5;
}
}
};
_PDFBool = PDFBool;
_defineProperty(PDFBool, "True", new _PDFBool(ENFORCER$2, true));
_defineProperty(PDFBool, "False", new _PDFBool(ENFORCER$2, false));
//#endregion
//#region src/core/syntax/Delimiters.ts
var IsDelimiter = new Uint8Array(256);
IsDelimiter[CharCodes.LeftParen] = 1;
IsDelimiter[CharCodes.RightParen] = 1;
IsDelimiter[CharCodes.LessThan] = 1;
IsDelimiter[CharCodes.GreaterThan] = 1;
IsDelimiter[CharCodes.LeftSquareBracket] = 1;
IsDelimiter[CharCodes.RightSquareBracket] = 1;
IsDelimiter[CharCodes.LeftCurly] = 1;
IsDelimiter[CharCodes.RightCurly] = 1;
IsDelimiter[CharCodes.ForwardSlash] = 1;
IsDelimiter[CharCodes.Percent] = 1;
//#endregion
//#region src/core/syntax/Whitespace.ts
var IsWhitespace = new Uint8Array(256);
IsWhitespace[CharCodes.Null] = 1;
IsWhitespace[CharCodes.Tab] = 1;
IsWhitespace[CharCodes.Newline] = 1;
IsWhitespace[CharCodes.FormFeed] = 1;
IsWhitespace[CharCodes.CarriageReturn] = 1;
IsWhitespace[CharCodes.Space] = 1;
//#endregion
//#region src/core/syntax/Irregular.ts
var IsIrregular = new Uint8Array(256);
for (let idx = 0, len = 256; idx < len; idx++) IsIrregular[idx] = IsWhitespace[idx] || IsDelimiter[idx] ? 1 : 0;
IsIrregular[CharCodes.Hash] = 1;
//#endregion
//#region src/core/objects/PDFName.ts
var _PDFName;
var decodeName = (name) => name.replace(/#([\dABCDEF]{2})/g,