var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
import { _MatrixHelper, _TransformationStack } from './text-extraction/matrix-helper';
import { TextGlyph, TextLine, TextWord } from './text-structure';
import { _PdfContentParserHelper } from './content-parser-helper';
import { _GraphicState } from './graphic-state';
import { PdfTagType } from './text-extraction/enumerator';
import { _TextProcessingMode } from './enum';
import { _addFontResources, _getXObject, _getXObjectResources, _ignoreEscapeSequence, _isArrayEqual, _parseEncodedText } from './utils';
import { _PdfDictionary, PdfPath, _ContentParser, PdfRotationAngle } from '@syncfusion/ej2-pdf';
import { _PdfTextParser } from './pdf-text-parser';
import { PdfStructureElement } from './pdf-structure-element';
/**
 * Represents a utility for extracting data from a PDF document.
 * ```typescript
 * // Load an existing PDF document
 * let document: PdfDocument = new PdfDocument(data, password);
 * // Initialize a new instance of the `PdfDataExtractor` class
 * let extractor: PdfDataExtractor = new PdfDataExtractor(document);
 * // Extract `TextLine` from the PDF document.
 * let textLines: Array<TextLine> = extractor.extractTextLines({ startPageIndex: 0, endPageIndex: document.pageCount-1});
 * // Save the document
 * document.save('output.pdf');
 * // Destroy the document
 * document.destroy();
 * ```
 */
var PdfDataExtractor = /** @class */ (function () {
    function PdfDataExtractor(document, callBack) {
        this._rotation = 0;
        this._textLeading = 0;
        this._textColor = [0, 0, 0];
        this._extractedText = '';
        this._textLines = [];
        this._identityMatrix = [1, 0, 0, 1, 0, 0];
        this._currentLocation = [0, 0];
        this._boundingRectangle = { x: 0, y: 0, width: 0, height: 0 };
        this._previousRect = { x: 0, y: 0, width: 0, height: 0 };
        this._textHorizontalScaling = 100;
        this._previousTextMatrix = new _MatrixHelper(0, 0, 0, 0, 0, 0);
        this._arise = 0;
        this._currentTextMatrix = new _MatrixHelper(0, 0, 0, 0, 0, 0);
        this._text = '';
        this._characterSpacing = 0;
        this._wordSpacing = 0;
        this._textScale = 1;
        this._textRise = 0;
        this._width = 0;
        this._height = 0;
        this._resultantText = '';
        this._textGlyph = [];
        this._textWord = [];
        this._textLine = [];
        this._textExtraction = [];
        this._fontCollection = new Map();
        this._ctm = new _MatrixHelper(1, 0, 0, 1, 0, 0);
        this._objects = [];
        this._isLayout = false;
        this._isRotatePage = false;
        this._parser = new _PdfTextParser();
        this._elementOrder = 0;
        this._pageElements = [];
        this._elementCollection = [];
        this._orderSet = new Set();
        this._mcidTextMap = new Map();
        this._extractTaggedText = false;
        this._elementBoundsMap = new Map();
        this._hasContentID = false;
        this._imageInfo = [];
        this._document = document;
        if (document) {
            this._crossReference = document._crossReference;
        }
        if (callBack) {
            this._canvas = callBack();
        }
        this._objects.push(this._ctm);
    }
    PdfDataExtractor.prototype.extractText = function (options) {
        var startIndex = 0;
        var endIndex = this._document.pageCount - 1;
        this._resultantText = '';
        if (options) {
            if (options.isLayout) {
                this._isLayout = true;
            }
            this._contentParser = new _PdfContentParserHelper(_TextProcessingMode.textExtraction);
            if (options.startPageIndex !== null && typeof options.startPageIndex === 'number') {
                startIndex = options.startPageIndex;
            }
            if (options.endPageIndex !== null && typeof options.endPageIndex === 'number') {
                endIndex = options.endPageIndex;
            }
        }
        this._processPages(startIndex, endIndex);
        if (this._resultantText.length) {
            this._resultantText = _ignoreEscapeSequence(this._resultantText);
        }
        this._isLayout = false;
        return this._resultantText;
    };
    PdfDataExtractor.prototype._renderTextAsLayOut = function (recordCollection, page, fontCollection, xObjectCollection) {
        var _this = this;
        var currentTd = [];
        var currentYLocation;
        var hexElement;
        var spaceBetweenWord = false;
        var differenceX = 0;
        var currentCmY = 0;
        var prevCmY = 0;
        this._hasTm = false;
        this._hasET = false;
        this._hasBeginMarkedContent = false;
        this._hasTj = false;
        var textlineMatrix = new _MatrixHelper(1, 0, 0, 1, 0, 0);
        var prevYLocation;
        var structElement = new PdfStructureElement();
        this._initialTransForm = new _MatrixHelper(1.3333333333333333, 0, 0, -1.3333333333333333, 0, page.size.height * 1.3333333333333333);
        var mcidTextMap = new Map();
        recordCollection.forEach(function (record) {
            var token = record._operator;
            var element = record._operands;
            var a;
            var b;
            var c;
            var d;
            var e;
            var f;
            var red;
            var green;
            var blue;
            var endTextPosition;
            var current;
            var prev;
            var locationY;
            var difference;
            switch (token) {
                case 'q':
                    _this._hasET = false;
                    _this._objects.unshift(_this._objects[0]);
                    _this._ctm = _this._objects[0];
                    break;
                case 'Q':
                    _this._objects.splice(0, 1);
                    _this._ctm = _this._objects[0];
                    break;
                case 'Tc':
                    _this._characterSpacing = Number(element[0]);
                    break;
                case 'Tw':
                    _this._wordSpacing = Number(element[0]);
                    break;
                case 'Tm':
                    _this._hasTm = true;
                    a = Number(element[0]);
                    b = Number(element[1]);
                    c = Number(element[2]);
                    d = Number(element[3]);
                    e = Number(element[4]);
                    f = Number(element[5]);
                    _this._textMatrix = new _MatrixHelper(a, b, c, d, e, f);
                    _this._textLineMatrix = _this._textMatrix;
                    _this._currentLocation = [0, 0];
                    _this._isTextMatrix = true;
                    textlineMatrix = _this._textLineMatrix;
                    if (_this._textMatrix._offsetY === _this._textLineMatrix._offsetY &&
                        _this._textMatrix._offsetX !== _this._textLineMatrix._offsetX) {
                        _this._textLineMatrix = _this._textMatrix;
                    }
                    if (_this._textLineMatrix._offsetY !== _this._currentTextMatrix._offsetY ||
                        ((_this._textLineMatrix._offsetX !== _this._currentTextMatrix._offsetX) && _this._hasBeginMarkedContent && !_this._hasTj)) {
                        _this._tempBoundingRectangle = { x: 0, y: 0, width: 0, height: 0 };
                        _this._hasBeginMarkedContent = false;
                    }
                    break;
                case 'Tf':
                    _this._renderFont(element);
                    break;
                case 'TL':
                    _this._textLeading = -Number(element);
                    break;
                case 'T*':
                    _this._moveToNextLine(0, _this._textLeading, textlineMatrix);
                    textlineMatrix = _this._textLineMatrix;
                    break;
                case 'BT':
                    _this._textMatrix = new _MatrixHelper(1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
                    _this._textLineMatrix = textlineMatrix = new _MatrixHelper(1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
                    break;
                case 'ET':
                    _this._hasET = true;
                    endTextPosition = (_this._textLineMatrix._offsetX - (_this._tempBoundingRectangle.width + _this._tempBoundingRectangle.x))
                        / 10;
                    if (_this._isLayout && _this._hasLeading && endTextPosition === 0 && _this._hasNoSpacing) {
                        _this._resultantText += String.fromCharCode(32);
                        _this._tempBoundingRectangle = { x: 0, y: 0, width: 0, height: 0 };
                        _this._hasLeading = false;
                    }
                    _this._currentLocation = [];
                    if (_this._isTextMatrix) {
                        _this._isTextMatrix = false;
                    }
                    _this._characterSpacing = 0;
                    _this._wordSpacing = 0;
                    break;
                case 're':
                    break;
                case 'cm':
                    a = parseFloat(element[0]);
                    b = parseFloat(element[1]);
                    c = parseFloat(element[2]);
                    d = parseFloat(element[3]);
                    e = parseFloat(element[4]);
                    f = parseFloat(element[5]);
                    _this._hasET = false;
                    currentCmY = Number(element[5]);
                    current = currentCmY;
                    prev = prevCmY;
                    _this._ctm = new _MatrixHelper(a, b, c, d, e, f)._multiply(_this._objects[0]);
                    _this._objects[0] = _this._ctm;
                    locationY = (current - prev) / 10;
                    if ((current !== prev) && _this._hasTm && (locationY < 0 || locationY >= 1)) {
                        _this._resultantText += '\r\n';
                        _this._hasTm = false;
                    }
                    prevCmY = currentCmY;
                    break;
                case 'BDC':
                    {
                        _this._hasBeginMarkedContent = true;
                        _this._hasET = true;
                        hexElement = element;
                        var markedContentId = structElement._parseContent(element);
                        if (_this._currentContentId !== markedContentId) {
                            _this._currentContentId = markedContentId;
                        }
                        if (!mcidTextMap.has(_this._currentContentId)) {
                            mcidTextMap.set(_this._currentContentId, []);
                        }
                        break;
                    }
                case 'TD':
                    _this._setTextLeading(Number(-element[1]));
                    _this._moveToNextLine(Number(element[0]), Number(element[1]), textlineMatrix);
                    textlineMatrix = _this._textLineMatrix;
                    if (_this._textLineMatrix._offsetY !== _this._currentTextMatrix._offsetY ||
                        (_this._hasBeginMarkedContent && _this._textLineMatrix._offsetX !== _this._currentTextMatrix._offsetX && !_this._hasTj)) {
                        _this._tempBoundingRectangle = { x: 0, y: 0, width: 0, height: 0 };
                        _this._hasBeginMarkedContent = false;
                    }
                    break;
                case 'Td':
                    _this._moveToNextLine(Number(element[0]), Number(element[1]), textlineMatrix);
                    textlineMatrix = _this._textLineMatrix;
                    if (_this._textLineMatrix._offsetY !== _this._currentTextMatrix._offsetY ||
                        (_this._hasBeginMarkedContent && _this._textLineMatrix._offsetX !== _this._currentTextMatrix._offsetX)) {
                        _this._tempBoundingRectangle = { x: 0, y: 0, width: 0, height: 0 };
                        _this._hasBeginMarkedContent = false;
                    }
                    if (Math.abs(_this._textLineMatrix._offsetX - _this._currentTextMatrix._offsetX) > 0 && !spaceBetweenWord && _this._hasTj) {
                        _this._differenceX = Math.abs(_this._textLineMatrix._offsetX - _this._currentTextMatrix._offsetX);
                        spaceBetweenWord = true;
                    }
                    currentTd[0] = Number(element[0]);
                    currentTd[1] = Number(element[1]);
                    break;
                case 'Tz':
                    _this._textHorizontalScaling = Number(element[0]);
                    break;
                case "'": // eslint-disable-line
                    {
                        _this._moveToNextLine(0, _this._textLeading, textlineMatrix);
                        textlineMatrix = _this._textLineMatrix;
                        currentYLocation = _this._textMatrix._offsetY;
                        _this._hasNoSpacing = false;
                        difference = 0;
                        if (_this._fontSize >= 10) {
                            difference = Math.round((currentYLocation - prevYLocation) / 10);
                        }
                        else {
                            difference = Math.round((currentYLocation - prevYLocation) / _this._fontSize);
                        }
                        if (difference < 0) {
                            difference = -difference;
                        }
                        _this._hasLeading = true;
                        if (prevYLocation !== 0 && difference >= 1) {
                            _this._resultantText += '\r\n';
                        }
                        var currentXPosition = Math.floor(_this._textLineMatrix._offsetX);
                        var prevXPosition = Math.floor(_this._currentTextMatrix._offsetX);
                        if ((prevXPosition - currentXPosition) > 0) {
                            _this._hasNoSpacing = true;
                        }
                        var backUpMatrix = _this._textLineMatrix;
                        if (_this._isRotatePage) {
                            _this._buildTextContentStream(element, page, fontCollection);
                        }
                        else {
                            _this._currentExtractedText = _this._renderTextElementFromTJ(element, page, fontCollection);
                        }
                        prevYLocation = currentYLocation;
                        if (_this._isLayout) {
                            _this._resultantText += _this._currentExtractedText;
                        }
                        else {
                            _this._textLineMatrix = backUpMatrix;
                        }
                        _this._currentTextMatrix = _this._textLineMatrix;
                        _this._textMatrix = _this._textLineMatrix;
                        if (_this._currentContentId !== null && typeof _this._currentContentId !== 'undefined') {
                            var text = _this._currentExtractedText;
                            var textCollection = mcidTextMap.get(_this._currentContentId);
                            if (text && textCollection) {
                                textCollection.push(text);
                            }
                        }
                        break;
                    }
                case 'TJ':
                    currentYLocation = _this._textMatrix._offsetY;
                    difference = 0;
                    if (_this._fontSize >= 10) {
                        difference = Math.round((currentYLocation - prevYLocation) / 10);
                    }
                    else {
                        difference = Math.round((currentYLocation - prevYLocation) / _this._fontSize);
                    }
                    if (difference < 0) {
                        difference = -difference;
                    }
                    if (spaceBetweenWord) {
                        if (differenceX > _this._fontSize) {
                            differenceX = 0;
                        }
                        spaceBetweenWord = false;
                    }
                    _this._hasTj = true;
                    if (prevYLocation !== 0 && difference >= 1) {
                        _this._resultantText += '\r\n';
                    }
                    if (_this._isRotatePage) {
                        _this._buildTextContentStream(element, page, fontCollection);
                    }
                    else {
                        _this._currentExtractedText = _this._renderTextElementFromTJ(element, page, fontCollection);
                    }
                    prevYLocation = currentYLocation;
                    if (_this._isLayout) {
                        _this._resultantText += _this._currentExtractedText;
                    }
                    _this._currentTextMatrix = _this._textLineMatrix;
                    _this._text += _this._currentExtractedText;
                    if (_this._isLayout && _this._textLineMatrix._m11 !== -1 && _this._textLineMatrix._m22 !== 1) {
                        _this._resultantText += ' ';
                    }
                    _this._textMatrix = _this._textLineMatrix;
                    _this._hasET = false;
                    _this._hasBeginMarkedContent = true;
                    if (_this._currentContentId !== null && typeof _this._currentContentId !== 'undefined') {
                        var text = _this._currentExtractedText;
                        var textCollection = mcidTextMap.get(_this._currentContentId);
                        if (text && textCollection) {
                            textCollection.push(text);
                        }
                    }
                    break;
                case 'Tj':
                    {
                        currentYLocation = _this._textMatrix._offsetY;
                        var difference_1 = 0;
                        var hex = '';
                        var hexChar = '';
                        if (_this._fontSize >= 10) {
                            difference_1 = Math.round((currentYLocation - prevYLocation) / 10);
                        }
                        else {
                            difference_1 = Math.round((currentYLocation - prevYLocation) / _this._fontSize);
                        }
                        if (difference_1 < 0) {
                            difference_1 = -difference_1;
                        }
                        if (spaceBetweenWord) {
                            if (differenceX > _this._fontSize) {
                                differenceX = 0;
                            }
                            if (typeof (hexElement) !== 'undefined' && hexElement.length > 1) {
                                hexElement[1] = hexElement[1].replace(/^</, '');
                                hex = hexElement[1].replace(/>$/, '');
                                hexChar = element[0].replace(/^\(|\)$/g, '');
                                if (hex !== '' && hex.indexOf('<') !== -1 && hexChar.length === 1 && /^[a-zA-Z]$/.test(hexChar)) {
                                    _this._hasET = false;
                                }
                            }
                            if (_this._hasET) {
                                _this._resultantText += ' ';
                            }
                            _this._hasET = false;
                            spaceBetweenWord = false;
                        }
                        _this._hasTj = true;
                        if (prevYLocation !== 0 && difference_1 >= 1) {
                            _this._resultantText += '\r\n';
                        }
                        if (_this._isRotatePage) {
                            _this._buildTextContentStream(element, page, fontCollection);
                        }
                        else {
                            _this._currentExtractedText = _this._renderTextElementFromTJ(element, page, fontCollection);
                        }
                        _this._currentTextMatrix = _this._textLineMatrix;
                        prevYLocation = currentYLocation;
                        _this._previousExtractText = _this._currentExtractedText;
                        if (_this._previousTextMatrix._offsetY !== 0 && _this._currentTextMatrix._offsetY !== 0 &&
                            _this._previousTextMatrix._offsetY + _this._previousFontSize > _this._currentTextMatrix._offsetY + _this._fontSize &&
                            _this._previousTextMatrix._offsetY < _this._currentTextMatrix._offsetY) {
                            if (_this._resultantText.length >= 2 && _this._resultantText.slice(-2) === '\r\n') {
                                _this._resultantText = _this._resultantText.slice(0, -2);
                            }
                        }
                        _this._previousFontSize = _this._fontSize;
                        if (_this._isLayout) {
                            _this._resultantText += _this._currentExtractedText;
                        }
                        _this._textMatrix = _this._textLineMatrix;
                        _this._previousTextMatrix = _this._textLineMatrix;
                        if (_this._currentContentId !== null && typeof _this._currentContentId !== 'undefined') {
                            var text = _this._currentExtractedText;
                            var textCollection = mcidTextMap.get(_this._currentContentId);
                            if (text && textCollection) {
                                textCollection.push(text);
                            }
                        }
                    }
                    break;
                case 'Do':
                    _getXObject(element, page, xObjectCollection, _this);
                    break;
                case 'RG':
                case 'k':
                case 'g':
                case 'rg':
                    red = Number(element[0]);
                    green = Number(element[1]);
                    blue = Number(element[2]);
                    _this._textColor = [red, green, blue];
            }
        });
        if (mcidTextMap && mcidTextMap.size > 0) {
            this._mcidTextMap = mcidTextMap;
        }
    };
    PdfDataExtractor.prototype._renderText = function (page, fontCollection, xObjectCollection, graphicState, imageExtraction) {
        if (!(this._contentParser)) {
            this._contentParser = new _PdfContentParserHelper((this._isExtractTextLines ||
                this._extractTaggedText) ? _TextProcessingMode.textLineExtraction
                : _TextProcessingMode.textExtraction);
        }
        var recordCollection = this._contentParser._getPageRecordCollection(page);
        var text; // eslint-disable-line
        if (this._isLayout) {
            this._renderTextAsLayOut(recordCollection, page, fontCollection, xObjectCollection);
        }
        else if (this._isExtractTextLines) {
            text = this._contentParser._processRecordCollection(recordCollection, page, fontCollection, xObjectCollection, graphicState);
            this._textLine = text;
        }
        else if (this._extractTaggedText) {
            text = this._contentParser._processRecordCollection(recordCollection, page, fontCollection, xObjectCollection, graphicState);
            this._textLine = text;
            this._renderTextAsLayOut(recordCollection, page, fontCollection, xObjectCollection);
        }
        else {
            text = this._contentParser._processRecordCollection(recordCollection, page, fontCollection, xObjectCollection, graphicState);
            this._resultantText = text;
        }
    };
    PdfDataExtractor.prototype._extractImagcollection = function (page, fontCollection, xObjectCollection, graphicState) {
        return __awaiter(this, void 0, void 0, function () {
            var recordCollection, _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        recordCollection = this._contentParser._getPageRecordCollection(page);
                        _a = this;
                        return [4 /*yield*/, this._contentParser._processImageRecordCollection(recordCollection, page, fontCollection, xObjectCollection, graphicState, this._canvas)];
                    case 1:
                        _a._imageInfo = _b.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    PdfDataExtractor.prototype._setTextLeading = function (textLeading) {
        this._textLeading = -textLeading;
    };
    PdfDataExtractor.prototype._moveToNextLine = function (tx, ty, textLineMatrix) {
        var matrix = new _MatrixHelper(1, 0, 0, 1, tx, ty);
        this._textLineMatrix = this._textMatrix = matrix._multiply(textLineMatrix);
    };
    PdfDataExtractor.prototype._updateTextMatrix = function (tj) {
        var x = -(tj * 0.001 * this._fontSize * this._textHorizontalScaling / 100);
        var point = this._textLineMatrix._transform(0.0, 0.0);
        var point2 = this._textLineMatrix._transform(x, 0.0);
        if (point[0] !== point2[0]) {
            this._textLineMatrix._offsetX = point2[0];
        }
        else {
            this._textLineMatrix._offsetY = point2[1];
        }
        return this._textLineMatrix;
    };
    PdfDataExtractor.prototype._updateTextLineMatrix = function (char, width) {
        var wordSpacing = 0;
        if (char.indexOf(' ') !== -1) {
            wordSpacing = this._wordSpacing;
        }
        var offsetX = (width * this._fontSize + this._characterSpacing + wordSpacing) * (this._textHorizontalScaling / 100);
        var matrix = new _MatrixHelper(1.0, 0.0, 0.0, 1.0, offsetX, 0.0);
        var result = matrix._multiply(this._textLineMatrix);
        this._textLineMatrix = result;
    };
    PdfDataExtractor.prototype._renderTextElementFromTJ = function (elements, page, fontCollection) {
        var extractedText = '';
        var curretFont = fontCollection.get(this._currentFont);
        var textValues = [];
        var widthTable = [];
        this._textWord = [];
        var charWidth = 0;
        var k = 0;
        var textMarix = new _MatrixHelper(this._textMatrix._m11, this._textMatrix._m12, this._textMatrix._m21, this._textMatrix._m22, this._textMatrix._offsetX, this._textMatrix._offsetY);
        var decodedList = _parseEncodedText(elements[0], curretFont);
        textValues = decodedList[0];
        widthTable = decodedList[1];
        this._previousRect = { x: 0, y: 0, width: 0, height: 0 };
        for (var j = 0; j < textValues.length; j++) {
            var word = textValues[Number.parseInt(j.toString(), 10)];
            var tj = Number(word);
            if (Number(word)) {
                this._textLineMatrix = this._updateTextMatrix(tj);
                if (Math.round(this._textLineMatrix._offsetX - this._textMatrix._offsetX) > 1 && !this._hasBeginMarkedContent) {
                    extractedText += String.fromCharCode(32);
                }
            }
            else {
                var text = word.slice(0, -1);
                text = _ignoreEscapeSequence(text);
                for (var i = 0; i < text.length; i++) {
                    var ch = text[Number.parseInt(i.toString(), 10)];
                    var matrixTransform = new _MatrixHelper(1, 0, 0, 1, 0, 0);
                    this._textMatrix = this._getTextRenderingMatrix();
                    var identity = new _MatrixHelper(1, 0, 0, 1, 0, 0);
                    identity = identity._scale(0.01, 0.01, 0.0, 0.0);
                    identity = identity._translate(0.0, 1.0);
                    this._transformations = new _TransformationStack(this._initialTransForm);
                    this._transformations._pushTransform(identity._multiply(this._textMatrix));
                    var transform = matrixTransform;
                    var matrix = transform._clone();
                    var mat = this._transformations._CurrentTransform;
                    matrix = matrix._multiply(mat);
                    matrixTransform = matrix;
                    var tempFontSize = 0;
                    if (this._textMatrix._m11 > 0) {
                        tempFontSize = this._textMatrix._m11;
                    }
                    else if (this._textMatrix._m12 !== 0 && this._textMatrix._m21 !== 0) {
                        if (this._textMatrix._m12 < 0) {
                            tempFontSize = -this._textMatrix._m12;
                        }
                        else {
                            tempFontSize = this._textMatrix._m12;
                        }
                    }
                    var height = 0;
                    if (curretFont._isType3Font) {
                        height = this._getTextHeight(curretFont, textMarix);
                    }
                    var width = widthTable[Number.parseInt(k.toString(), 10)][Number.parseInt(i.toString(), 10)];
                    var scale = void 0;
                    if (curretFont._fontMatrix) {
                        scale = curretFont._fontMatrix[0];
                    }
                    else {
                        scale = 0.001;
                    }
                    this._boundingRectangle.x = (matrix._offsetX / 1.3333333333333333) / 1.0;
                    if (this._isLayout) {
                        charWidth = this._parser._getCharacterWidth((scale * width), curretFont);
                    }
                    else {
                        charWidth = scale * width;
                    }
                    this._boundingRectangle.width = charWidth * tempFontSize;
                    if (!curretFont._isType3Font) {
                        this._boundingRectangle.y = ((matrix._offsetY / 1.3333333333333333) - ((tempFontSize * 1.0) /
                            1.3333333333333333)) / 1.0;
                        this._boundingRectangle.height = tempFontSize;
                    }
                    else {
                        this._boundingRectangle.y = ((matrix._offsetY / 1.3333333333333333) - ((height * 1.0) / 1.3333333333333333))
                            / 1.0;
                        this._boundingRectangle.height = height;
                    }
                    var right = this._tempBoundingRectangle.x + this._tempBoundingRectangle.width;
                    if (this._tempBoundingRectangle) {
                        var boundDifference = Math.round((this._boundingRectangle.x - right) / 10);
                        if ((right !== 0 && this._boundingRectangle.x !== 0) && (boundDifference > 1)) {
                            extractedText += String.fromCharCode(32);
                        }
                    }
                    extractedText += ch;
                    this._updateTextLineMatrix(ch, charWidth);
                    this._transformations._popTransform();
                    this._tempBoundingRectangle = this._boundingRectangle;
                    this._textMatrix = new _MatrixHelper(this._textLineMatrix._m11, this._textLineMatrix._m12, this._textLineMatrix._m21, this._textLineMatrix._m22, this._textLineMatrix._offsetX, this._textLineMatrix._offsetY);
                }
                if (text.length > 0) {
                    k++;
                }
            }
        }
        return extractedText;
    };
    PdfDataExtractor.prototype._getTextHeight = function (font, textMatrix) {
        var tsm = [this._fontSize * this._textHorizontalScaling / 100, 0, 0, this._fontSize, 0, this._arise];
        if (this._fontSize <= 1 && !_isArrayEqual(font._fontMatrix, [0.001, 0, 0, 0.001, 0, 0])) {
            var glyphHeight = font._boundingBox[3] - font._boundingBox[1];
            if (glyphHeight > 0) {
                tsm[3] *= glyphHeight * font._fontMatrix[3];
            }
        }
        var currentTextMatrix = [textMatrix._m11, textMatrix._m12, textMatrix._m21,
            textMatrix._m22, textMatrix._offsetX, textMatrix._offsetY];
        var ctm = [this._ctm._m11, this._ctm._m12, this._ctm._m21,
            this._ctm._m22, this._ctm._offsetX, this._ctm._offsetY];
        var matrix = this._transform(currentTextMatrix, tsm);
        var transform = this._transform(ctm, matrix);
        var height = Math.hypot(transform[2], transform[3]);
        return height;
    };
    PdfDataExtractor.prototype._transform = function (m1, m2) {
        return [m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3],
            m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5]];
    };
    PdfDataExtractor.prototype._buildTextContentStream = function (elements, page, fontCollection) {
        var curretFont = fontCollection.get(this._currentFont);
        var textValues = [];
        this._textWord = [];
        var tempString = '';
        var decodedList = _parseEncodedText(elements[0], curretFont);
        textValues = decodedList[0];
        var iszerspace = false;
        var text = '';
        var str = '';
        this._previousRect = { x: 0, y: 0, width: 0, height: 0 };
        for (var j = 0; j < textValues.length; j++) {
            var word = textValues[Number.parseInt(j.toString(), 10)];
            var digit = Number(word); // eslint-disable-line
            if (digit) {
                tempString = this._getTextWidth(text, Number(word) * -0.001, curretFont, page, tempString);
            }
            else if (digit !== 0) {
                text = word.slice(0, -1);
                if (iszerspace) {
                    text = str + text;
                    iszerspace = false;
                }
            }
            else {
                iszerspace = true;
                str = text;
            }
        }
        if (text.length > 0) {
            tempString = this._getTextWidth(text, 0, curretFont, page, tempString);
        }
        if (tempString !== '') {
            var textWord = new TextWord();
            textWord._text = tempString;
            textWord._glyphs = this._textGlyph;
            if (this._isRotatePage) {
                textWord._bounds = { x: this._textGlyph[0]._bounds.x, y: this._textGlyph[0]._bounds.y,
                    width: this._textGlyph[0]._bounds.width, height: this._height };
            }
            else {
                textWord._bounds = { x: this._textGlyph[0]._bounds.x, y: this._textGlyph[0]._bounds.y, width: this._width,
                    height: this._textGlyph[0]._bounds.width };
            }
            textWord._fontName = curretFont._name;
            textWord._fontStyle = curretFont._fontStyle;
            textWord._fontSize = this._fontSize;
            this._textWord.push(textWord);
            this._height = 0;
        }
        this._width = 0;
        this._textGlyph = [];
        var textLine1 = new TextLine();
        textLine1._text = this._extractedText;
        textLine1._wordCollection = this._textWord;
        textLine1._fontName = curretFont._name;
        textLine1._fontStyle = curretFont._fontStyle;
        textLine1._fontSize = this._fontSize;
        textLine1._pageIndex = page._pageIndex;
        var pdfPath = new PdfPath();
        for (var i = 0; i < this._textWord.length; i++) {
            pdfPath.addRectangle(this._textWord[Number.parseInt(i.toString(), 10)]._bounds);
        }
        var pathBounds = pdfPath._getBounds();
        textLine1._bounds = { x: pathBounds[0], y: pathBounds[1], width: pathBounds[2], height: pathBounds[3] };
        this._textLine.push(textLine1);
        this._textExtraction.push(this._extractedText);
        this._extractedText = '';
    };
    PdfDataExtractor.prototype._getTextWidth = function (text, extraSpacing, currentFont, page, tempString) {
        var scale = 0;
        if (currentFont._fontMatrix) {
            scale = currentFont._fontMatrix[0] * this._fontSize;
        }
        else {
            scale = 0.001 * this._fontSize;
        }
        var g = currentFont._charsToGlyphs(text); // eslint-disable-line
        for (var i = 0; i < g.length; i++) {
            var glyph = g[Number.parseInt(i.toString(), 10)]._unicode;
            var charSpacing = this._characterSpacing + (i + 1 === text.length ? extraSpacing : 0);
            var tempFontSize = 0;
            if (this._textMatrix._m11 > 0) {
                tempFontSize = this._textMatrix._m11;
            }
            else if (this._textMatrix._m12 !== 0 && this._textMatrix._m21 !== 0) {
                if (this._textMatrix._m12 < 0) {
                    tempFontSize = -this._textMatrix._m12;
                }
                else {
                    tempFontSize = this._textMatrix._m12;
                }
            }
            var width = g[Number.parseInt(i.toString(), 10)]._width;
            var w = scale * width * tempFontSize;
            if (tempFontSize < this._fontSize) {
                tempFontSize = this._fontSize;
            }
            var charWidth = void 0;
            var charHeight = void 0;
            var scaledDim = scale * width * (this._textHorizontalScaling / 100);
            this._boundingRectangle.x = this._textMatrix._offsetY;
            this._boundingRectangle.y = this._textMatrix._offsetX;
            if (glyph === ' ') {
                charWidth = w + this._wordSpacing;
                charSpacing += scaledDim + this._wordSpacing;
                this._textMatrix = this._parser._translateTextMatrix(charSpacing * (this._textHorizontalScaling / 100), 0, this._textMatrix);
            }
            else {
                charWidth = w;
            }
            if (this._textMatrix._m11 > 0) {
                charHeight = tempFontSize;
            }
            else {
                charHeight = -(tempFontSize);
            }
            if (this._textMatrix._m11 <= 0 && this._textMatrix._m22 <= 0) {
                this._boundingRectangle.width = charWidth;
                this._boundingRectangle.height = charHeight;
            }
            else {
                this._boundingRectangle.width = charHeight;
                this._boundingRectangle.height = charWidth;
            }
            if (glyph !== ' ') {
                this._textMatrix = this._parser._translateTextMatrix(scaledDim, 0, this._textMatrix);
            }
            this._extractedText += glyph;
            tempString = this._splitWords(glyph, tempString, currentFont._name, currentFont._fontStyle, page);
            if (this._previousRect) {
                this._previousRect = { x: this._boundingRectangle.x, y: this._boundingRectangle.y,
                    width: this._boundingRectangle.width, height: this._boundingRectangle.height };
            }
            else {
                this._previousRect = { x: 0, y: 0, width: 0, height: 0 };
            }
            if (glyph === ' ') {
                continue;
            }
            if (charSpacing) {
                this._textMatrix = this._parser._translateTextMatrix(charSpacing * (this._textHorizontalScaling / 100), 0, this._textMatrix);
            }
        }
        return tempString;
    };
    PdfDataExtractor.prototype._splitWords = function (glyph, tempString, fontName, fontStyle, page, rotation, textColor) {
        var _this = this;
        var isSpace = false;
        if (/\s/.test(glyph)) {
            isSpace = true;
        }
        var currentRect = this._boundingRectangle;
        var addTextWord = function (text, glyphs, width) {
            var textWord = new TextWord();
            textWord._text = text;
            textWord._glyphs = glyphs;
            var pdfPath = new PdfPath();
            for (var i = 0; i < glyphs.length; i++) {
                pdfPath.addRectangle(glyphs[Number.parseInt(i.toString(), 10)]._bounds);
            }
            var pathBounds = pdfPath._getBounds();
            textWord._bounds = { x: pathBounds[0], y: pathBounds[1], width: pathBounds[2], height: pathBounds[3] };
            textWord._fontName = fontName;
            textWord._fontStyle = fontStyle;
            textWord._fontSize = _this._fontSize;
            _this._textWord.push(textWord);
        };
        if (isSpace) {
            if (tempString) {
                if (page.rotation === PdfRotationAngle.angle90 || page.rotation === PdfRotationAngle.angle270 || rotation === 90) {
                    addTextWord(tempString, this._textGlyph, this._height);
                }
                else {
                    addTextWord(tempString, this._textGlyph, this._width);
                }
                this._textGlyph = [];
                tempString = '';
            }
            var textGlyph = new TextGlyph();
            textGlyph._text = glyph;
            textGlyph._bounds = currentRect;
            textGlyph._fontName = fontName;
            textGlyph._fontStyle = fontStyle;
            textGlyph._fontSize = this._fontSize;
            if (Array.isArray(textColor) && textColor.length === 3) {
                textGlyph._color = { r: textColor[0], g: textColor[1], b: textColor[2] };
            }
            if (page.rotation !== PdfRotationAngle.angle0) {
                textGlyph._isRotated = true;
            }
            else {
                textGlyph._isRotated = false;
            }
            this._textGlyph.push(textGlyph);
            if (page.rotation === PdfRotationAngle.angle90 || page.rotation === PdfRotationAngle.angle270 || rotation === 90) {
                addTextWord(glyph, this._textGlyph, currentRect.height);
            }
            else {
                addTextWord(glyph, this._textGlyph, currentRect.width);
            }
            this._width = 0;
            this._height = 0;
            this._textGlyph = [];
            this._previousRect = null;
        }
        else if (this._previousRect !== null && this._previousRect.width > 0) {
            var spacingFactor = currentRect.height * 0.07;
            if (spacingFactor < 2) {
                spacingFactor = 2;
            }
            var difference = void 0;
            if (page.rotation === PdfRotationAngle.angle90) {
                difference = this._previousRect.y + this._previousRect.height - currentRect.y;
            }
            else if (page.rotation === PdfRotationAngle.angle270 || rotation === 90) {
                difference = currentRect.y + currentRect.height - this._previousRect.y;
            }
            else if (page.rotation === PdfRotationAngle.angle180) {
                difference = currentRect.x + currentRect.width - this._previousRect.x;
            }
            else {
                difference = this._previousRect.x + this._previousRect.width - currentRect.x;
            }
            if (difference > 0) {
                if (spacingFactor === 2) {
                    spacingFactor = 2.5;
                }
            }
            if (Math.abs(difference) > spacingFactor) {
                if (page.rotation === PdfRotationAngle.angle90 || page.rotation === PdfRotationAngle.angle270) {
                    addTextWord(tempString, this._textGlyph, this._height);
                }
                else {
                    addTextWord(tempString, this._textGlyph, this._width);
                }
                this._width = 0;
                this._height = 0;
                this._textGlyph = [];
                tempString = '';
                this._previousRect = { x: 0, y: 0, width: 0, height: 0 };
            }
        }
        if (!isSpace) {
            var textGlyph = new TextGlyph();
            textGlyph._text = glyph;
            textGlyph._bounds = currentRect;
            textGlyph._fontName = fontName;
            textGlyph._fontStyle = fontStyle;
            textGlyph._fontSize = this._fontSize;
            if (Array.isArray(textColor) && textColor.length === 3) {
                textGlyph._color = { r: textColor[0], g: textColor[1], b: textColor[2] };
            }
            if (page.rotation !== PdfRotationAngle.angle0) {
                textGlyph._isRotated = true;
            }
            else {
                textGlyph._isRotated = false;
            }
            textGlyph._isRotated = false;
            this._textGlyph.push(textGlyph);
            if (page.rotation === PdfRotationAngle.angle90 || page.rotation === PdfRotationAngle.angle270 || rotation === 90) {
                this._height += currentRect.height;
            }
            else {
                this._width += currentRect.width;
            }
            tempString += glyph;
        }
        return tempString;
    };
    PdfDataExtractor.prototype._getTextRenderingMatrix = function () {
        var matrix = new _MatrixHelper(this._fontSize, 0, 0, -this._fontSize, 0, this._fontSize + this._arise);
        matrix = matrix._multiply(this._textLineMatrix);
        matrix = matrix._multiply(this._ctm);
        return matrix;
    };
    PdfDataExtractor.prototype._renderFont = function (fontElements) {
        var i = 0;
        for (i; i < fontElements.length; i++) {
            if (fontElements[Number.parseInt(i.toString(), 10)].indexOf('/') !== -1) {
                this._currentFont = fontElements[Number.parseInt(i.toString(), 10)].replace('/', '');
                break;
            }
        }
        this._fontSize = Number(fontElements[i + 1]);
    };
    PdfDataExtractor.prototype.extractTextLines = function (options) {
        var startIndex = 0;
        this._isExtractTextLines = true;
        this._contentParser = new _PdfContentParserHelper(_TextProcessingMode.textLineExtraction);
        if (options && typeof (options.startPageIndex) === 'number') {
            startIndex = options.startPageIndex;
        }
        var endIndex = this._document.pageCount - 1;
        if (options && typeof (options.endPageIndex) === 'number') {
            endIndex = options.endPageIndex;
        }
        this._textLine = [];
        this._processPages(startIndex, endIndex);
        this._isExtractTextLines = false;
        return this._textLine;
    };
    PdfDataExtractor.prototype.extractImages = function (options) {
        return __awaiter(this, void 0, void 0, function () {
            var startIndex, endIndex, fontCache, xObjectCache, pageIndex, page, graphicState, resource, resourceId, fontCollection, xObjectCollection;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this._document._crossReference._isDecoderSupport = true;
                        startIndex = 0;
                        this._contentParser = new _PdfContentParserHelper(_TextProcessingMode.imageExtraction);
                        if (options && typeof (options.startPageIndex) === 'number') {
                            startIndex = options.startPageIndex;
                        }
                        endIndex = this._document.pageCount - 1;
                        if (options && typeof (options.endPageIndex) === 'number') {
                            endIndex = options.endPageIndex;
                        }
                        fontCache = new Map();
                        xObjectCache = new Map();
                        pageIndex = startIndex;
                        _a.label = 1;
                    case 1:
                        if (!(pageIndex <= endIndex)) return [3 /*break*/, 5];
                        page = this._document.getPage(pageIndex);
                        if (page.rotation !== PdfRotationAngle.angle0 && !this._isLayout) {
                            this._isRotatePage = true;
                        }
                        graphicState = new _GraphicState();
                        resource = page._pageDictionary.get('Resources');
                        if (!resource) return [3 /*break*/, 3];
                        resourceId = resource._reference ? resource._reference.toString() : '';
                        fontCollection = void 0;
                        xObjectCollection = void 0;
                        if (resourceId && xObjectCache.has(resourceId)) {
                            xObjectCollection = xObjectCache.get(resourceId);
                        }
                        else {
                            xObjectCollection = _getXObjectResources(resource, this._crossReference, _TextProcessingMode.imageExtraction, page);
                            if (resourceId) {
                                xObjectCache.set(resourceId, xObjectCollection);
                            }
                        }
                        return [4 /*yield*/, this._extractImagcollection(page, fontCollection, xObjectCollection, graphicState)];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3:
                        this._isRotatePage = false;
                        _a.label = 4;
                    case 4:
                        pageIndex++;
                        return [3 /*break*/, 1];
                    case 5:
                        fontCache.clear();
                        xObjectCache.clear();
                        return [2 /*return*/, this._imageInfo];
                }
            });
        });
    };
    PdfDataExtractor.prototype._processPages = function (startIndex, endIndex, isImageExtraction) {
        var fontCache = new Map();
        var xObjectCache = new Map();
        for (var pageIndex = startIndex; pageIndex <= endIndex; pageIndex++) {
            var page = this._document.getPage(pageIndex);
            if (page.rotation !== PdfRotationAngle.angle0 && !this._isLayout) {
                this._isRotatePage = true;
            }
            var graphicState = new _GraphicState();
            var resource = page._pageDictionary.get('Resources');
            if (resource !== null && typeof resource !== 'undefined') {
                var resourceId = resource._reference ? resource._reference.toString() : ''; //eslint-disable-line
                var fontCollection = void 0;
                if (!isImageExtraction) {
                    if (resourceId && fontCache.has(resourceId)) {
                        fontCollection = fontCache.get(resourceId);
                    }
                    else {
                        fontCollection = _addFontResources(resource, this._crossReference);
                        if (resourceId) {
                            fontCache.set(resourceId, fontCollection);
                        }
                    }
                }
                var xObjectCollection = void 0;
                if (resourceId && xObjectCache.has(resourceId)) {
                    xObjectCollection = xObjectCache.get(resourceId);
                }
                else {
                    var mode = void 0;
                    if (typeof (isImageExtraction) === 'boolean' && isImageExtraction) {
                        mode = _TextProcessingMode.imageExtraction;
                    }
                    xObjectCollection = _getXObjectResources(resource, this._crossReference, mode, page);
                    if (resourceId) {
                        xObjectCache.set(resourceId, xObjectCollection);
                    }
                }
                this._renderText(page, fontCollection, xObjectCollection, graphicState, isImageExtraction);
            }
            this._isRotatePage = false;
        }
        fontCache.clear();
        xObjectCache.clear();
    };
    /**
     * Gets the root structure element of the PDF document.
     *
     * @returns {PdfStructureElement} The root structure element of the PDF document.
     *
     * ```typescript
     * // Load an existing PDF document
     * let document: PdfDocument = new PdfDocument(data, password);
     * // Initialize a new instance of the `PdfDataExtractor` class
     * let extractor: PdfDataExtractor = new PdfDataExtractor(document);
     * // Access the structure element of the PDF document
     * let rootStructureElement: PdfStructureElement = extractor.getStructureElement();
     * // Save the document
     * document.save('output.pdf');
     * // Destroy the document
     * document.destroy();
     * ```
     */
    PdfDataExtractor.prototype.getStructureElement = function () {
        if (!(this._structureElement)) {
            this._structureElement = this._getStructureTreeRoot();
        }
        return this._structureElement;
    };
    /**
     * Gets the structure elements of PDF page.
     *
     * @param {PdfPage} page PDF page
     * @returns {PdfStructureElement[]} Structure elements
     *
     * ```typescript
     * // Load an existing PDF document
     * let document: PdfDocument = new PdfDocument(data, password);
     * // Initialize a new instance of the `PdfDataExtractor` class
     * let extractor: PdfDataExtractor = new PdfDataExtractor(document);
     * // Retrieve structure elements from the first page
     * let page: PdfPage = document.getPage(0);
     * let structureElements: PdfStructureElement[] = extractor.getStructureElements(page);
     * // Save the document
     * document.save('output.pdf');
     * // Destroy the document
     * document.destroy();
     * ```
     */
    PdfDataExtractor.prototype.getStructureElements = function (page) {
        var loadedDocument = this._document;
        this._contentParser = new _PdfContentParserHelper(_TextProcessingMode.textLineExtraction);
        if (this._pageElements.length === 0 && loadedDocument) {
            var extractor = new PdfDataExtractor(loadedDocument);
            var root = extractor.getStructureElement();
            if (root) {
                this._getPageElements(root, page);
            }
        }
        return this._pageElements;
    };
    PdfDataExtractor.prototype._getPageElements = function (element, page) {
        if (element.page === page && element.tagType !== PdfTagType.documentType) {
            this._pageElements.push(element);
        }
        else if (element.childElements.length > 0) {
            for (var i = 0; i < element.childElements.length; i++) {
                this._getPageElements(element.childElements[Number.parseInt(i.toString(), 10)], page);
            }
        }
    };
    PdfDataExtractor.prototype._getStructureTreeRoot = function () {
        var structureRoot;
        var catalogDictionary = this._document._catalog._catalogDictionary;
        if (catalogDictionary && catalogDictionary.has('StructTreeRoot')) {
            var treeRoot = catalogDictionary.get('StructTreeRoot');
            if (treeRoot) {
                if (this._isSingleRootElement(treeRoot)) {
                    structureRoot = this._getStructureElement(treeRoot);
                }
                else {
                    structureRoot = PdfStructureElement._load(this._document);
                    this._getStructureElement(treeRoot, structureRoot);
                }
            }
            var collection = this._elementCollection;
            if (collection && collection.length > 0) {
                structureRoot._getTaggedContent(collection);
            }
        }
        return structureRoot;
    };
    PdfDataExtractor.prototype._getStructureElement = function (structureDictionary, parent) {
        var structureElement;
        if (structureDictionary.has('K')) {
            var elements = structureDictionary.getArray('K'); // eslint-disable-line
            if ((elements)) {
                if (Array.isArray(elements)) {
                    for (var i = 0; i < elements.length; i++) {
                        var dictionary = elements[Number.parseInt(i.toString(), 10)];
                        if (dictionary instanceof _PdfDictionary) {
                            if (parent) {
                                structureElement = PdfStructureElement._load(this._document, dictionary, this._elementOrder, parent);
                            }
                            else {
                                structureElement = PdfStructureElement._load(this._document, dictionary, this._elementOrder);
                            }
                            if (structureElement.tagType === PdfTagType.none && dictionary.has('S')) {
                                var tagType = dictionary.get('S');
                                if (tagType) {
                                    structureElement._tagType = structureElement._getTagType(tagType.name);
                                }
                            }
                            else if (structureElement.tagType === PdfTagType.none && structureElement.parent
                                && structureElement.parent.tagType !== PdfTagType.none) {
                                structureElement._tagType = structureElement.parent.tagType;
                            }
                            if (!this._orderSet.has(structureElement._order)) {
                                this._elementCollection.push(structureElement);
                                this._orderSet.add(structureElement._order);
                            }
                            this._elementOrder++;
                        }
                        if (dictionary instanceof _PdfDictionary && dictionary.has('K')) {
                            var tempElement = this._getStructureElement(dictionary, structureElement);
                            if (tempElement) {
                                structureElement._childElements.push(tempElement);
                                if (!this._orderSet.has(tempElement._order)) {
                                    this._elementCollection.push(tempElement);
                                    this._orderSet.add(tempElement._order);
                                }
                            }
                            if (parent) {
                                parent._childElements.push(structureElement);
                            }
                            else {
                                return structureElement;
                            }
                        }
                        else if (parent && structureElement && parent._childElements.indexOf(structureElement) === -1) {
                            parent._childElements.push(structureElement);
                        }
                        if (dictionary instanceof _PdfDictionary && dictionary.has('Pg')) {
                            structureElement._pageDictionary = dictionary.get('Pg');
                        }
                        if (typeof dictionary === 'number') {
                            if (parent) {
                                parent._contentId.push(dictionary);
                            }
                        }
                    }
                    return null;
                }
                else if (typeof elements === 'number') {
                    parent._contentId.push(elements);
                }
                else if (elements instanceof _PdfDictionary) {
                    if (parent) {
                        structureElement = PdfStructureElement._load(this._document, elements, this._elementOrder, parent);
                    }
                    else {
                        structureElement = PdfStructureElement._load(this._document, elements, this._elementOrder);
                    }
                    if (!this._orderSet.has(structureElement._order)) {
                        this._elementCollection.push(structureElement);
                        this._orderSet.add(structureElement._order);
                    }
                    this._elementOrder++;
                    if (structureElement.tagType === PdfTagType.none && elements !== null &&
                        typeof elements !== 'undefined' && elements.has('S')) {
                        var tagType = elements.get('S');
                        if (tagType) {
                            structureElement._tagType = structureElement._getTagType(tagType.name);
                        }
                    }
                    else if (structureElement.tagType === PdfTagType.none && structureElement.parent &&
                        structureElement.parent.tagType !== PdfTagType.none) {
                        structureElement._tagType = structureElement.parent.tagType;
                    }
                    if (elements.has('K')) {
                        var tempElement = this._getStructureElement(elements, structureElement);
                        if (tempElement) {
                            structureElement._childElements.push(tempElement);
                            if (!this._orderSet.has(tempElement._order)) {
                                this._elementCollection.push(tempElement);
                                this._orderSet.add(tempElement._order);
                            }
                        }
                    }
                    if (elements.has('Pg') && structureElement.tagType !== PdfTagType.documentType) {
                        structureElement._pageDictionary = elements.get('Pg');
                    }
                }
            }
        }
        return structureElement;
    };
    PdfDataExtractor.prototype._isSingleRootElement = function (treeRoot) {
        var isSingle = true;
        if (treeRoot.has('K')) {
            var elements = treeRoot.get('K'); // eslint-disable-line
            if (elements && elements.length > 1) {
                isSingle = false;
            }
        }
        return isSingle;
    };
    PdfDataExtractor.prototype._getFigureBounds = function (structElement, page) {
        var _this = this;
        var combinedContent = page._combineContent();
        var parser = new _ContentParser(combinedContent);
        var recordCollection = parser._readContent();
        var currentCmY = 0;
        var prevCmY = 0;
        this._hasTm = false;
        this._hasET = false;
        this._hasBeginMarkedContent = false;
        this._hasTj = false;
        this._initialTransForm = new _MatrixHelper(1.3333333333333333, 0, 0, -1.3333333333333333, 0, page.size.height * 1.3333333333333333);
        var id = [];
        var elementBounds;
        var hexElement = []; // eslint-disable-line
        var objects = [];
        recordCollection.forEach(function (record) {
            var token = record._operator;
            var element = record._operands;
            var a;
            var b;
            var c;
            var d;
            var e;
            var f;
            var current;
            var prev;
            var locationY;
            switch (token) {
                case 'q':
                    _this._hasET = false;
                    _this._objects.unshift(_this._objects[0]);
                    _this._ctm = _this._objects[0];
                    break;
                case 'cm':
                    {
                        a = parseFloat(element[0]);
                        b = parseFloat(element[1]);
                        c = parseFloat(element[2]);
                        d = parseFloat(element[3]);
                        e = parseFloat(element[4]);
                        f = parseFloat(element[5]);
                        _this._hasET = false;
                        currentCmY = Number(element[5]);
                        current = currentCmY;
                        prev = prevCmY;
                        var ctm = new _MatrixHelper(a, b, c, d, e, f)._multiply(_this._objects[0]);
                        objects[0] = ctm;
                        locationY = (current - prev) / 10;
                        if ((current !== prev) && _this._hasTm && (locationY < 0 || locationY >= 1)) {
                            _this._resultantText += '\r\n';
                            _this._hasTm = false;
                        }
                        prevCmY = currentCmY;
                        break;
                    }
                case 'BDC':
                    {
                        _this._hasBeginMarkedContent = true;
                        _this._hasET = true;
                        hexElement = element;
                        var markedContentId = structElement._parseContent(element);
                        if (id.indexOf(markedContentId) === -1) {
                            id.push(markedContentId);
                        }
                        break;
                    }
                case 'Do':
                    if (id.indexOf(structElement._contentId[0]) !== -1) {
                        var scaleMatrix = new _MatrixHelper(1, 0, 0, -1.01, 0, 1);
                        var transformMatrix = new _MatrixHelper(scaleMatrix._m11, scaleMatrix._m12, scaleMatrix._m21, scaleMatrix._m22, scaleMatrix._offsetX, scaleMatrix._offsetY).
                            _multiply(objects[0]);
                        var documentMatrix = new _MatrixHelper(1.33, 0, 0, -1.33, 0, page.size.height * 1.33);
                        transformMatrix = transformMatrix._multiply(documentMatrix);
                        if (page.rotation === PdfRotationAngle.angle270) {
                            if (transformMatrix._m11 !== 0 && transformMatrix._m12 !== 0) {
                                elementBounds = { x: transformMatrix._offsetY / 1.33,
                                    y: page.size.width - (Math.round(transformMatrix._offsetX / 1.33), 5) + transformMatrix._m11 / 1.33,
                                    width: objects[0]._m22, height: objects[0]._m12 };
                            }
                            else {
                                elementBounds = { x: transformMatrix._offsetY / 1.33, y: Math.floor(page.size.width) -
                                        (Math.round(transformMatrix._offsetX / 1.33), 5) +
                                        Math.floor(transformMatrix._m11 / 1.33), width: objects[0]._m12, height: objects[0]._m21 };
                            }
                        }
                        else if (page.rotation === PdfRotationAngle.angle90) {
                            if (transformMatrix._m11 === 0 && transformMatrix._m21 === 0) {
                                elementBounds = { x: page.size.height - (transformMatrix._offsetY / 1.33),
                                    y: (transformMatrix._offsetX / 1.33), width: objects[0]._m12, height: -objects[0]._m21 };
                            }
                            else {
                                elementBounds = { x: page.size.height - (transformMatrix._offsetY / 1.33) - objects[0]._m22,
                                    y: transformMatrix._offsetX / 1.33, width: objects[0]._m22, height: objects[0]._m11 };
                            }
                        }
                        else if (page.rotation === PdfRotationAngle.angle180) {
                            elementBounds = { x: page.size.width - (transformMatrix._offsetX / 1.33) -
                                    objects[0]._m11, y: page.size.height - objects[0]._m22 -
                                    Math.round((transformMatrix._offsetY / 1.33)),
                                width: objects[0]._m11, height: objects[0]._offsetY };
                        }
                        else {
                            if (transformMatrix._m11 === 0 && transformMatrix._m22 > 0) {
                                if (transformMatrix._m12 < 0 && transformMatrix._m21 > 0) {
                                    elementBounds = { x: (page.size.height - (transformMatrix._offsetY / 1.33)),
                                        y: Math.round((transformMatrix._offsetX / 1.33)),
                                        width: -objects[0]._m21, height: objects[0]._m12 };
                                }
                                else if (transformMatrix._m12 > 0 && transformMatrix._m21 < 0) {
                                    elementBounds = { x: (transformMatrix._offsetY / 1.33),
                                        y: (page.size.width - transformMatrix._offsetX / 1.33),
                                        width: -objects[0]._m21, height: objects[0]._m12 };
                                }
                                else if (transformMatrix._m12 < 0 && transformMatrix._m21 < 0) {
                                    elementBounds = { x: (page.size.height - (transformMatrix._offsetY / 1.33) - objects[0]._m11),
                                        y: (page.size.height - objects[0]._m21 - (transformMatrix._offsetY / 1.33)),
                                        width: objects[0]._m11, height: objects[0]._m22 };
                                }
                                else {
                                    elementBounds = { x: (page.size.width - (transformMatrix._offsetX / 1.33) - objects[0]._m11),
                                        y: page.size.height - objects[0]._m22 - transformMatrix._offsetY / 1.33,
                                        width: objects[0]._m11, height: objects[0]._m21 };
                                }
                            }
                            else {
                                elementBounds = { x: transformMatrix._offsetX / 1.33,
                                    y: Math.round(transformMatrix._offsetY / 1.33),
                                    width: objects[0]._m11, height: objects[0]._m22 };
                            }
                        }
                    }
                    break;
            }
        });
        return elementBounds;
    };
    return PdfDataExtractor;
}());
export { PdfDataExtractor };
