pdf-lib
Version:
Library for creating and modifying PDF files in JavaScript
35 lines (34 loc) • 1.4 kB
JavaScript
import { PDFName } 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 Name.
*
* If so, returns a tuple containing (1) an object representing the parsed PDF Name
* and (2) a subarray of the input with the characters making up the parsed name
* removed. The "onParseName" parse handler will also be called with the PDFName
* object.
*
* If not, null is returned.
*/
var parseName = function (input, _a) {
var onParseName = (_a === void 0 ? {} : _a).onParseName;
var trimmed = trimArrayAndRemoveComments(input);
var nameRegex = /^\/([^\0\t\n\f\r \][<>(/]*)/;
// Search for first character that isn't part of a name
var idx = 1; // Skip the leading '/'
while (trimmed[idx] !== undefined &&
String.fromCharCode(trimmed[idx]).match(/^[^\0\t\n\f\r \][<>(/]/)) {
idx += 1;
}
// Try to match the regex up to that character to see if we've got a name
var result = arrayToString(trimmed, 0, idx).match(nameRegex);
if (!result)
return undefined;
var fullMatch = result[0], name = result[1];
var pdfName = PDFName.fromEncoded(name);
if (onParseName)
onParseName(pdfName);
return [pdfName, trimmed.subarray(fullMatch.length)];
};
export default parseName;