UNPKG

pdf-lib

Version:

Library for creating and modifying PDF files in JavaScript

55 lines (54 loc) 2 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var pdf_objects_1 = require("../pdf-objects"); var utils_1 = require("../../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 = utils_1.trimArrayAndRemoveComments(input); if (utils_1.arrayCharAt(trimmed, 0) !== '(') return undefined; var parensStack = []; var isEscaped = false; for (var idx = 0; idx < trimmed.length; idx += 1) { var c = utils_1.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 = utils_1.arrayToString(trimmed, 1, idx); var pdfString = pdf_objects_1.PDFString.fromString(str); if (onParseString) onParseString(pdfString); return [pdfString, trimmed.subarray(idx + 1)]; } } return undefined; // Parenthesis didn't balance out }; exports.default = parseString;