pdf-lib
Version:
Library for creating and modifying PDF files in JavaScript
53 lines (52 loc) • 1.92 kB
JavaScript
import { PDFString } from '../pdf-objects';
import { arrayCharAt, 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 String.
*
* If so, returns a tuple containing (1) an object representing the parsed PDF
* String and (2) a subarray of the input with the characters making up the parsed
* string removed. The "onParseString" parse handler will also be called with the
* PDFString object.
*
* If not, returns null.
*/
var parseString = function (input, _a) {
var onParseString = (_a === void 0 ? {} : _a).onParseString;
var trimmed = trimArrayAndRemoveComments(input);
if (arrayCharAt(trimmed, 0) !== '(')
return undefined;
var parensStack = [];
var isEscaped = false;
for (var idx = 0; idx < trimmed.length; idx += 1) {
var c = arrayCharAt(trimmed, idx);
// Check for unescaped parenthesis
if (!isEscaped) {
if (c === '(')
parensStack.push(c);
else if (c === ')')
parensStack.pop();
}
// Track whether current character is being escaped or not
if (c === '\\') {
if (!isEscaped) {
isEscaped = true;
}
else {
isEscaped = false;
}
}
else if (isEscaped)
isEscaped = false;
// Once (if) the unescaped parenthesis balance out, return their contents
if (parensStack.length === 0) {
var str = arrayToString(trimmed, 1, idx);
var pdfString = PDFString.fromString(str);
if (onParseString)
onParseString(pdfString);
return [pdfString, trimmed.subarray(idx + 1)];
}
}
return undefined; // Parenthesis didn't balance out
};
export default parseString;