UNPKG

pdf-lib

Version:

Library for creating and modifying PDF files in JavaScript

1,725 lines (1,567 loc) 1.89 MB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : factory(global.PDFLib = {}); }(typeof self !== 'undefined' ? self : this, function (exports) { var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; var _freeGlobal = freeGlobal; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = _freeGlobal || freeSelf || Function('return this')(); var _root = root; /** Built-in value references. */ var Symbol$1 = _root.Symbol; var _Symbol = Symbol$1; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Built-in value references. */ var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; } catch (e) {} var result = nativeObjectToString.call(value); { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } var _getRawTag = getRawTag; /** Used for built-in method references. */ var objectProto$1 = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString$1 = objectProto$1.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString$1.call(value); } var _objectToString = objectToString; /** `Object#toString` result references. */ var nullTag = '[object Null]', undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag$1 && symToStringTag$1 in Object(value)) ? _getRawTag(value) : _objectToString(value); } var _baseGetTag = baseGetTag; /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } var isObjectLike_1 = isObjectLike; /** `Object#toString` result references. */ var numberTag = '[object Number]'; /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a number, else `false`. * @example * * _.isNumber(3); * // => true * * _.isNumber(Number.MIN_VALUE); * // => true * * _.isNumber(Infinity); * // => true * * _.isNumber('3'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike_1(value) && _baseGetTag(value) == numberTag); } var isNumber_1 = isNumber; /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } var _arrayMap = arrayMap; /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return _arrayMap(props, function(key) { return object[key]; }); } var _baseValues = baseValues; /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } var _baseTimes = baseTimes; /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike_1(value) && _baseGetTag(value) == argsTag; } var _baseIsArguments = baseIsArguments; /** Used for built-in method references. */ var objectProto$2 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$1 = objectProto$2.hasOwnProperty; /** Built-in value references. */ var propertyIsEnumerable = objectProto$2.propertyIsEnumerable; /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) { return isObjectLike_1(value) && hasOwnProperty$1.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; var isArguments_1 = isArguments; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; var isArray_1 = isArray; /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } var stubFalse_1 = stubFalse; var isBuffer_1 = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? _root.Buffer : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse_1; module.exports = isBuffer; }); /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } var _isIndex = isIndex; /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER$1 = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1; } var isLength_1 = isLength; /** `Object#toString` result references. */ var argsTag$1 = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag$1 = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag$1] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike_1(value) && isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)]; } var _baseIsTypedArray = baseIsTypedArray; /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } var _baseUnary = baseUnary; var _nodeUtil = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && _freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); module.exports = nodeUtil; }); /* Node.js helper references. */ var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray; var isTypedArray_1 = isTypedArray; /** Used for built-in method references. */ var objectProto$3 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$2 = objectProto$3.hasOwnProperty; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray_1(value), isArg = !isArr && isArguments_1(value), isBuff = !isArr && !isArg && isBuffer_1(value), isType = !isArr && !isArg && !isBuff && isTypedArray_1(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? _baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty$2.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. _isIndex(key, length) ))) { result.push(key); } } return result; } var _arrayLikeKeys = arrayLikeKeys; /** Used for built-in method references. */ var objectProto$4 = Object.prototype; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$4; return value === proto; } var _isPrototype = isPrototype; /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } var _overArg = overArg; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = _overArg(Object.keys, Object); var _nativeKeys = nativeKeys; /** Used for built-in method references. */ var objectProto$5 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$3 = objectProto$5.hasOwnProperty; /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!_isPrototype(object)) { return _nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty$3.call(object, key) && key != 'constructor') { result.push(key); } } return result; } var _baseKeys = baseKeys; /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } var isObject_1 = isObject; /** `Object#toString` result references. */ var asyncTag = '[object AsyncFunction]', funcTag$1 = '[object Function]', genTag = '[object GeneratorFunction]', proxyTag = '[object Proxy]'; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject_1(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = _baseGetTag(value); return tag == funcTag$1 || tag == genTag || tag == asyncTag || tag == proxyTag; } var isFunction_1 = isFunction; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength_1(value.length) && !isFunction_1(value); } var isArrayLike_1 = isArrayLike; /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object); } var keys_1 = keys; /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object == null ? [] : _baseValues(object, keys_1(object)); } var values_1 = values; /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike_1(value) && _baseGetTag(value) == symbolTag); } var isSymbol_1 = isSymbol; /** Used as references for various `Number` constants. */ var NAN = 0 / 0; /** * The base implementation of `_.toNumber` which doesn't ensure correct * conversions of binary, hexadecimal, or octal string values. * * @private * @param {*} value The value to process. * @returns {number} Returns the number. */ function baseToNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol_1(value)) { return NAN; } return +value; } var _baseToNumber = baseToNumber; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** Used to convert symbols to primitives and strings. */ var symbolProto = _Symbol ? _Symbol.prototype : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray_1(value)) { // Recursively convert values (susceptible to call stack limits). return _arrayMap(value, baseToString) + ''; } if (isSymbol_1(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } var _baseToString = baseToString; /** * Creates a function that performs a mathematical operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @param {number} [defaultValue] The value used for `undefined` arguments. * @returns {Function} Returns the new mathematical operation function. */ function createMathOperation(operator, defaultValue) { return function(value, other) { var result; if (value === undefined && other === undefined) { return defaultValue; } if (value !== undefined) { result = value; } if (other !== undefined) { if (result === undefined) { return other; } if (typeof value == 'string' || typeof other == 'string') { value = _baseToString(value); other = _baseToString(other); } else { value = _baseToNumber(value); other = _baseToNumber(other); } result = operator(value, other); } return result; }; } var _createMathOperation = createMathOperation; /** * Adds two numbers. * * @static * @memberOf _ * @since 3.4.0 * @category Math * @param {number} augend The first number in an addition. * @param {number} addend The second number in an addition. * @returns {number} Returns the total. * @example * * _.add(6, 4); * // => 10 */ var add = _createMathOperation(function(augend, addend) { return augend + addend; }, 0); var add_1 = add; /** * The base implementation of `_.sum` and `_.sumBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { var current = iteratee(array[index]); if (current !== undefined) { result = result === undefined ? current : (result + current); } } return result; } var _baseSum = baseSum; /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } var identity_1 = identity; /** * Computes the sum of the values in `array`. * * @static * @memberOf _ * @since 3.4.0 * @category Math * @param {Array} array The array to iterate over. * @returns {number} Returns the sum. * @example * * _.sum([4, 2, 8, 6]); * // => 20 */ function sum(array) { return (array && array.length) ? _baseSum(array, identity_1) : 0; } var sum_1 = sum; /* tslint:disable no-bitwise */ // export const writeToDebugFile = (data: any, postfix = 0) => { // // eslint-disable-next-line // const fs = require('fs'); // fs.writeFileSync(`/Users/user/Desktop/pdf-lib/debug${postfix}`, data); // }; var error = function (msg) { throw new Error(msg); }; var sizeInBytes = function (n) { return 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 = function (n) { var bytes = new Uint8Array(sizeInBytes(n)); for (var i = 1; i <= bytes.length; i++) { bytes[i - 1] = n >> ((bytes.length - i) * 8); } return bytes; }; // Arrays and TypedArrays in JS both have .reverse() methods, which would seem // to negate the need for this function. However, not all runtimes support this // method (e.g. React Native), so using this function compensates for that. var reverseArray = function (array) { for (var i = 0; i < Math.floor(array.length / 2); i++) { var leftIdx = i; var rightIdx = array.length - i - 1; var temp = array[i]; array[leftIdx] = array[rightIdx]; array[rightIdx] = temp; } return array; }; var and = function () { var predicates = []; for (var _i = 0; _i < arguments.length; _i++) { predicates[_i] = arguments[_i]; } return function () { var values = []; for (var _i = 0; _i < arguments.length; _i++) { values[_i] = arguments[_i]; } return predicates.every(function (predicate) { return predicate.apply(void 0, values); }); }; }; var or = function () { var predicates = []; for (var _i = 0; _i < arguments.length; _i++) { predicates[_i] = arguments[_i]; } return function () { var values = []; for (var _i = 0; _i < arguments.length; _i++) { values[_i] = arguments[_i]; } return predicates.some(function (predicate) { return predicate.apply(void 0, values); }); }; }; var not = function (predicate) { return function () { var values = []; for (var _i = 0; _i < arguments.length; _i++) { values[_i] = arguments[_i]; } return !predicate.apply(void 0, values); }; }; var toBoolean = function (boolStr) { if (boolStr === 'true') return true; if (boolStr === 'false') return false; throw new Error("\"" + boolStr + "\" cannot be converted to a boolean"); }; var charCode = function (charStr) { if (charStr.length !== 1) { throw new Error('"char" must be exactly one character long'); } return charStr.charCodeAt(0); }; var charFromCode = function (code) { return String.fromCharCode(code); }; var addStringToBuffer = function (str, buffer) { for (var i = 0; i < str.length; i += 1) { buffer[i] = str.charCodeAt(i); } return buffer.subarray(str.length); }; var arrayToString = function (arr, startAt, stopAt) { if (startAt === void 0) { startAt = 0; } var stopIdx = stopAt === undefined || stopAt >= arr.length ? arr.length : stopAt; var str = ''; for (var i = startAt; i < stopIdx; i += 1) { str += charFromCode(arr[i]); } return str; }; var arrayCharAt = function (arr, idx) { return String.fromCharCode(arr[idx]); }; var trimArray = function (arr) { var idx = 0; while (String.fromCharCode(arr[idx]).match(/^[\0\t\n\f\r ]/) && idx < arr.length) { idx += 1; } return arr.subarray(idx); }; var PERCENT_SIGN_CODE = charCode('%'); var NEWLINE_CODE = charCode('\n'); var CARRIAGE_RETURN_CODE = charCode('\r'); var isEOLMarker = function (code) { return code === NEWLINE_CODE || code === CARRIAGE_RETURN_CODE; }; var trimArrayAndRemoveComments = function (arr) { var strippedComment = true; var newArray = arr; while (strippedComment) { newArray = trimArray(newArray); if (newArray[0] === PERCENT_SIGN_CODE) { var idx = 0; while (!isEOLMarker(newArray[idx]) && idx < newArray.length) idx += 1; var foundEOLMarker = isEOLMarker(newArray[idx]); if (foundEOLMarker) newArray = newArray.subarray(idx); strippedComment = foundEOLMarker; } else { strippedComment = false; } } return newArray; }; var arraysAreEqual = function (arr1, arr1Start, arr1Stop, arr2, arr2Start, arr2Stop) { var arr1Length = arr1Stop - arr1Start; if (arr1Length !== arr2Stop - arr2Start) return false; for (var i = 0; i < arr1Length; i += 1) { if (arr1[arr1Start + i] !== arr2[arr2Start + i]) return false; } return true; }; var arrayIndexOf = function (arr, targetStr, startFrom) { if (startFrom === void 0) { startFrom = 0; } var targetArr = targetStr.split('').map(function (c) { return c.charCodeAt(0); }); var currIdx = startFrom; while (!arraysAreEqual(arr, currIdx, currIdx + targetStr.length, targetArr, 0, targetArr.length)) { currIdx += 1; if (currIdx >= arr.length) return undefined; } return currIdx; }; var arrayIndexOneOf = function (arr, targetStrings, startFrom) { if (startFrom === void 0) { startFrom = 0; } var targetArrs = targetStrings.map(function (str) { return str.split('').map(charCode); }); var currIdx = startFrom; var match = null; while (!match) { currIdx += 1; if (currIdx >= arr.length) return undefined; match = targetArrs.find(function (target) { return arraysAreEqual(arr, currIdx, currIdx + target.length, target, 0, target.length); }); } return [currIdx, arrayToString(match)]; }; var arrayFindIndexOf = function (arr, predicate, startFrom) { if (startFrom === void 0) { startFrom = 0; } var currIdx = startFrom; while (!predicate(arr.subarray(currIdx, currIdx + 1)[0])) { currIdx += 1; if (currIdx >= arr.length) return undefined; } return currIdx; }; var setCharAt = function (str, idx, newChar) { return str.substring(0, idx) + newChar + str.substring(idx + 1); }; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max, nativeMin = Math.min; /** * The base implementation of `_.inRange` which doesn't coerce arguments. * * @private * @param {number} number The number to check. * @param {number} start The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. */ function baseInRange(number, start, end) { return number >= nativeMin(start, end) && number < nativeMax(start, end); } var _baseInRange = baseInRange; /** Used as references for various `Number` constants. */ var NAN$1 = 0 / 0; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol_1(value)) { return NAN$1; } if (isObject_1(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject_1(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN$1 : +value); } var toNumber_1 = toNumber; /** Used as references for various `Number` constants. */ var INFINITY$1 = 1 / 0, MAX_INTEGER = 1.7976931348623157e+308; /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber_1(value); if (value === INFINITY$1 || value === -INFINITY$1) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } var toFinite_1 = toFinite; /** * Checks if `n` is between `start` and up to, but not including, `end`. If * `end` is not specified, it's set to `start` with `start` then set to `0`. * If `start` is greater than `end` the params are swapped to support * negative ranges. * * @static * @memberOf _ * @since 3.3.0 * @category Number * @param {number} number The number to check. * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. * @see _.range, _.rangeRight * @example * * _.inRange(3, 2, 4); * // => true * * _.inRange(4, 8); * // => true * * _.inRange(4, 2); * // => false * * _.inRange(2, 2); * // => false * * _.inRange(1.2, 2); * // => true * * _.inRange(5.2, 4); * // => false * * _.inRange(-3, -2, -6); * // => true */ function inRange(number, start, end) { start = toFinite_1(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite_1(end); } number = toNumber_1(number); return _baseInRange(number, start, end); } var inRange_1 = inRange; /** * Checks if `value` is `NaN`. * * **Note:** This method is based on * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for * `undefined` and other non-number values. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN$1(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some // ActiveX objects in IE. return isNumber_1(value) && value != +value; } var _isNaN = isNaN$1; /** * Checks if `value` is `null` or `undefined`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is nullish, else `false`. * @example * * _.isNil(null); * // => true * * _.isNil(void 0); * // => true * * _.isNil(NaN); * // => false */ function isNil(value) { return value == null; } var isNil_1 = isNil; /* tslint:disable:ban-types */ var validate = function (value, predicate, msg) { if (!predicate(value)) throw new Error(msg); }; var optional = function (predicate) { return function (value) { return isNil_1(value) || predicate(value); }; }; var validateArr = function (value, predicate, msg) { validate(value, isArray_1, 'validateArr.value must be an array.'); value.forEach(function (v) { return validate(v, predicate, msg); }); }; var isInstance = function (requiredClass) { return function (value) { return value instanceof requiredClass; }; }; var isArrayOf = function (requiredClass) { return function (value) { if (!isArray_1(value)) return false; for (var i = 0; i < value.length; i++) { if (!(value[i] instanceof requiredClass)) return false; } return true; }; }; var isIdentity = function (requiredValue) { return function (value) { return value === requiredValue; }; }; var isNotIdentity = function (requiredValue) { return function (value) { return value !== requiredValue; }; }; var doesMatch = function (regex) { return function (value) { return !!value.match(regex); }; }; var isNumber$1 = function (n) { return and(isNumber_1, not(_isNaN))(n); }; var isInRange = function (lower, upper) { return function (value) { return inRange_1(value, lower, upper) || value === upper; }; }; var oneOf = function () { var allowed = []; for (var _i = 0; _i < arguments.length; _i++) { allowed[_i] = arguments[_i]; } return function (value) { return allowed.some(function (a) { return a === value; }); }; }; var PDFObjectIndex = /** @class */ (function () { function PDFObjectIndex() { var _this = this; this.index = new Map(); this.highestObjectNumber = -1; this.assign = function (key, val) { validate(key, isInstance(PDFIndirectReference), '"key" must be a PDFIndirectReference'); validate(val, isInstance(PDFObject), '"val" must be a PDFObject'); if (key.objectNumber > _this.highestObjectNumber) { _this.highestObjectNumber = key.objectNumber; } _this.index.set(key, val); return _this; }; this.nextObjectNumber = function () { _this.highestObjectNumber += 1; var ref = PDFIndirectReference.forNumbers(_this.highestObjectNumber, 0); return ref; }; this.assignNextObjectNumberTo = function (val) { var ref = _this.nextObjectNumber(); _this.assign(ref, val); return ref; }; this.lookupMaybe = function (ref) { if (ref instanceof PDFIndirectReference) return _this.index.get(ref); return ref; }; this.lookup = function (ref) { return _this.lookupMaybe(ref) || error("Failed to lookup ref: " + ref); }; } PDFObjectIndex.create = function () { return new PDFObjectIndex(); }; return PDFObjectIndex; }()); var PDFObject = /** @class */ (function () { function PDFObject() { var _this = this; this.clone = function () { throw new Error("clone() is not implemented on " + _this.constructor.name); }; this.toString = function () { throw new Error("toString() is not implemented on " + _this.constructor.name); }; this.bytesSize = function () { throw new Error("bytesSize() is not implemented on " + _this.constructor.name); }; this.copyBytesInto = function (buffer) { throw new Error("copyBytesInto() is not implemented on " + _this.constructor.name); }; } return PDFObject; }()); var __extends = (undefined && undefined.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var PDFArray$$1 = /** @class */ (function (_super) { __extends(PDFArray$$1, _super); function PDFArray$$1(array, index) { var _this = _super.call(this) || this; _this.push = function () { var val = []; for (var _i = 0; _i < arguments.length; _i++) { val[_i] = arguments[_i]; } validateArr(val, isInstance(PDFObject), 'PDFArray.push() requires arguments to be PDFObjects'); (_a = _this.array).push.apply(_a, val); return _this; var _a; }; _this.set = function (idx, val) { validate(idx, isNumber_1, 'PDFArray.set() requires indexes to be numbers'); validate(val, isInstance(PDFObject), 'PDFArray.set() requires values to be PDFObjects'); _this.array[idx] = val; return _this; }; _this.get = function (idx) { validate(idx, isNumber_1, 'PDFArray.get() requires indexes to be numbers'); return _this.array[idx]; }; _this.forEach = function (fn) { return _this.array.forEach(fn); }; _this.map = function (fn) { return _this.array.map(fn); }; _this.splice = function (start, deleteCount) { return _this.array.splice(start, deleteCount); }; _this.clone = function () { return PDFArray$$1.fromArray(_this.array.slice(), _this.index); }; _this.toString = function () { var bufferSize = _this.bytesSize(); var buffer = new Uint8Array(bufferSize); _this.copyBytesInto(buffer); return arrayToString(buffer); }; _this.bytesSize = function () { return 2 + // "[ " _this.array .map(function (e) { if (e instanceof PDFIndirectObject) return e.toReference().length + 1; else if (e instanceof PDFObject) return e.bytesSize() + 1; return error("Not a PDFObject: " + e); }) .reduce(add_1, 0) + 1; }; // "]"; _this.copyBytesInto = function (buffer) { var remaining = addStringToBuffer('[ ', buffer); _this.array.forEach(function (e, idx) { if (e instanceof PDFIndirectObject) { remaining = addStringToBuffer(e.toReference(), remaining); } else if (e instanceof PDFObject) { remaining = e.copyBytesInto(remaining); } else { error("Not a PDFObject: " + e); } remaining = addStringToBuffer(' ', remaining); }); remaining = addStringToBuffer(']', remaining); return remaining; }; validateArr(array, isInstance(PDFObject), 'Cannot construct PDFArray from array whose elements are not PDFObjects'); validate(index, isInstance(PDFObjectIndex), '"index" must be a an instance of PDFObjectIndex'); _this.array = array; _this.index = index; return _this; } PDFArray$$1.fromArray = function (array, index) { return new PDFArray$$1(array, index); }; return PDFArray$$1; }(PDFObject)); /** `Object#toString` result references. */ var boolTag$1 = '[object Boolean]'; /** * Checks if `value` is classified as a boolean primitive or object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. * @example * * _.isBoolean(false); * // => true * * _.isBoolean(null); * // => false */ function isBoolean(value) { return value === true || value === false || (isObjectLike_1(value) && _baseGetTag(value) == boolTag$1); } var isBoolean_1 = isBoolean; var __extends$1 = (undefined && undefined.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var PDFBoolean = /** @class */ (function (_super) { __extends$1(PDFBoolean, _super); function PDFBoolean(bool) { var _this = _super.call(this) || this; _this.clone = function () { return PDFBoolean.fromBool(_this.boolean); }; _this.toString = function () { return _this.boolean.toString(); }; _this.bytesSize = function () { return _this.toString().length; }; _this.copyBytesInto = function (buffer) { return addStringToBuffer(_this.toString(), buffer); }; validate(bool, isBoolean_1, 'Can only construct PDFBooleans from Booleans'); _this.boolean = bool; return _this; } PDFBoolean.fromBool = function (bool) { return new PDFBoolean(bool); }; PDFBoolean.fromString = function (boolStr) { return new PDFBoolean(toBoolean(boolStr)); }; return PDFBoolean; }(PDFObject)); /** * A specialized version of `_.for