pdf-lib
Version:
Library for creating and modifying PDF files in JavaScript
33 lines (32 loc) • 1.37 kB
JavaScript
import { PDFNumber } from '../pdf-objects';
import { arrayToString, trimArrayAndRemoveComments } from '../../utils';
/**
* Accepts an array of bytes as input. Checks to see if the first characters in the
* trimmed input make up a PDF Number.
*
* If so, returns a tuple containing (1) an object representing the parsed PDF
* Number and (2) a subarray of the input with the characters making up the parsed
* number removed. The "onParseNumber" parse handler will also be called with the
* parsed PDFNumber object.
*
* If not, null is returned.
*/
var parseNumber = function (input, _a) {
var onParseNumber = (_a === void 0 ? {} : _a).onParseNumber;
var trimmed = trimArrayAndRemoveComments(input);
var numRegex = /^(([+-]?\d+(\.\d+)?)|([+-]?\.\d+))/;
// Search for the first character that isn't part of a number
var idx = 0;
while (String.fromCharCode(trimmed[idx]).match(/^[+-.\d]/))
idx += 1;
// Try to match the regex up to that character to see if we've got a number
var result = arrayToString(trimmed, 0, idx).match(numRegex);
if (!result)
return undefined;
var fullMatch = result[0], num = result[1];
var pdfNumber = PDFNumber.fromString(num);
if (onParseNumber)
onParseNumber(pdfNumber);
return [pdfNumber, trimmed.subarray(fullMatch.length)];
};
export default parseNumber;