Passed
Pull Request — master (#553)
by Konrad
04:33 queued 02:20
created

src/Smalot/PdfParser/Page.php (1 issue)

Labels
Severity
1
<?php
2
3
/**
4
 * @file
5
 *          This file is part of the PdfParser library.
6
 *
7
 * @author  Sébastien MALOT <[email protected]>
8
 *
9
 * @date    2017-01-03
10
 *
11
 * @license LGPLv3
12
 *
13
 * @url     <https://github.com/smalot/pdfparser>
14
 *
15
 *  PdfParser is a pdf library written in PHP, extraction oriented.
16
 *  Copyright (C) 2017 - Sébastien MALOT <[email protected]>
17
 *
18
 *  This program is free software: you can redistribute it and/or modify
19
 *  it under the terms of the GNU Lesser General Public License as published by
20
 *  the Free Software Foundation, either version 3 of the License, or
21
 *  (at your option) any later version.
22
 *
23
 *  This program is distributed in the hope that it will be useful,
24
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
25
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
26
 *  GNU Lesser General Public License for more details.
27
 *
28
 *  You should have received a copy of the GNU Lesser General Public License
29
 *  along with this program.
30
 *  If not, see <http://www.pdfparser.org/sites/default/LICENSE.txt>.
31
 */
32
33
namespace Smalot\PdfParser;
34
35
use Smalot\PdfParser\Element\ElementArray;
36
use Smalot\PdfParser\Element\ElementMissing;
37
use Smalot\PdfParser\Element\ElementNull;
38
use Smalot\PdfParser\Element\ElementXRef;
39
40
class Page extends PDFObject
41
{
42
    /**
43
     * @var Font[]
44
     */
45
    protected $fonts = null;
46
47
    /**
48
     * @var PDFObject[]
49
     */
50
    protected $xobjects = null;
51
52
    /**
53
     * @var array
54
     */
55
    protected $dataTm = null;
56
57
    /**
58
     * @return Font[]
59
     */
60 28
    public function getFonts()
61
    {
62 28
        if (null !== $this->fonts) {
63 23
            return $this->fonts;
64
        }
65
66 28
        $resources = $this->get('Resources');
67
68 28
        if (method_exists($resources, 'has') && $resources->has('Font')) {
69 24
            if ($resources->get('Font') instanceof ElementMissing) {
70 1
                return [];
71
            }
72
73 23
            if ($resources->get('Font') instanceof Header) {
74 17
                $fonts = $resources->get('Font')->getElements();
75
            } else {
76 10
                $fonts = $resources->get('Font')->getHeader()->getElements();
77
            }
78
79 23
            $table = [];
80
81 23
            foreach ($fonts as $id => $font) {
82 23
                if ($font instanceof Font) {
83 23
                    $table[$id] = $font;
84
85
                    // Store too on cleaned id value (only numeric)
86 23
                    $id = preg_replace('/[^0-9\.\-_]/', '', $id);
87 23
                    if ('' != $id) {
88 22
                        $table[$id] = $font;
89
                    }
90
                }
91
            }
92
93 23
            return $this->fonts = $table;
94
        }
95
96 6
        return [];
97
    }
98
99 25
    public function getFont(string $id): ?Font
100
    {
101 25
        $fonts = $this->getFonts();
102
103 25
        if (isset($fonts[$id])) {
104 22
            return $fonts[$id];
105
        }
106
107
        // According to the PDF specs (https://www.adobe.com/content/dam/acom/en/devnet/pdf/pdfs/PDF32000_2008.pdf, page 238)
108
        // "The font resource name presented to the Tf operator is arbitrary, as are the names for all kinds of resources"
109
        // Instead, we search for the unfiltered name first and then do this cleaning as a fallback, so all tests still pass.
110
111 4
        if (isset($fonts[$id])) {
112
            return $fonts[$id];
113
        } else {
114 4
            $id = preg_replace('/[^0-9\.\-_]/', '', $id);
115 4
            if (isset($fonts[$id])) {
116 1
                return $fonts[$id];
117
            }
118
        }
119
120 3
        return null;
121
    }
122
123
    /**
124
     * Support for XObject
125
     *
126
     * @return PDFObject[]
127
     */
128 5
    public function getXObjects()
129
    {
130 5
        if (null !== $this->xobjects) {
131 4
            return $this->xobjects;
132
        }
133
134 5
        $resources = $this->get('Resources');
135
136 5
        if (method_exists($resources, 'has') && $resources->has('XObject')) {
137 5
            if ($resources->get('XObject') instanceof Header) {
138 5
                $xobjects = $resources->get('XObject')->getElements();
139
            } else {
140
                $xobjects = $resources->get('XObject')->getHeader()->getElements();
141
            }
142
143 5
            $table = [];
144
145 5
            foreach ($xobjects as $id => $xobject) {
146 5
                $table[$id] = $xobject;
147
148
                // Store too on cleaned id value (only numeric)
149 5
                $id = preg_replace('/[^0-9\.\-_]/', '', $id);
150 5
                if ('' != $id) {
151 5
                    $table[$id] = $xobject;
152
                }
153
            }
154
155 5
            return $this->xobjects = $table;
156
        }
157
158
        return [];
159
    }
160
161 4
    public function getXObject(string $id): ?PDFObject
162
    {
163 4
        $xobjects = $this->getXObjects();
164
165 4
        if (isset($xobjects[$id])) {
166 4
            return $xobjects[$id];
167
        }
168
169
        return null;
170
        /*$id = preg_replace('/[^0-9\.\-_]/', '', $id);
171
172
        if (isset($xobjects[$id])) {
173
            return $xobjects[$id];
174
        } else {
175
            return null;
176
        }*/
177
    }
178
179 15
    public function getText(self $page = null): string
180
    {
181 15
        if ($contents = $this->get('Contents')) {
182 15
            if ($contents instanceof ElementMissing) {
183
                return '';
184 15
            } elseif ($contents instanceof ElementNull) {
185
                return '';
186 15
            } elseif ($contents instanceof PDFObject) {
187 12
                $elements = $contents->getHeader()->getElements();
188
189 12
                if (is_numeric(key($elements))) {
190
                    $new_content = '';
191
192
                    foreach ($elements as $element) {
193
                        if ($element instanceof ElementXRef) {
194
                            $new_content .= $element->getObject()->getContent();
195
                        } else {
196
                            $new_content .= $element->getContent();
197
                        }
198
                    }
199
200
                    $header = new Header([], $this->document);
201 12
                    $contents = new PDFObject($this->document, $header, $new_content, $this->config);
202
                }
203 4
            } elseif ($contents instanceof ElementArray) {
204
                // Create a virtual global content.
205 4
                $new_content = '';
206
207 4
                foreach ($contents->getContent() as $content) {
208 4
                    $new_content .= $content->getContent()."\n";
209
                }
210
211 4
                $header = new Header([], $this->document);
212 4
                $contents = new PDFObject($this->document, $header, $new_content, $this->config);
213
            }
214
215
            /*
216
             * Elements referencing each other on the same page can cause endless loops during text parsing.
217
             * To combat this we keep a recursionStack containing already parsed elements on the page.
218
             * The stack is only emptied here after getting text from a page.
219
             */
220 15
            $contentsText = $contents->getText($this);
221 15
            PDFObject::$recursionStack = [];
222
223 15
            return $contentsText;
224
        }
225
226
        return '';
227
    }
228
229
    /**
230
     * Return true if the current page is a (setasign\Fpdi\Fpdi) FPDI/FPDF document
231
     *
232
     * The metadata 'Producer' should have the value of "FPDF" . FPDF_VERSION if the
233
     * pdf file was generated by FPDF/Fpfi.
234
     *
235
     * @return bool true is the current page is a FPDI/FPDF document
236
     */
237 11
    public function isFpdf(): bool
238
    {
239 11
        if (\array_key_exists('Producer', $this->document->getDetails()) &&
240 11
            \is_string($this->document->getDetails()['Producer']) &&
241 11
            0 === strncmp($this->document->getDetails()['Producer'], 'FPDF', 4)) {
242 2
            return true;
243
        }
244
245 10
        return false;
246
    }
247
248
    /**
249
     * Return the page number of the PDF document of the page object
250
     *
251
     * @return int the page number
252
     */
253 2
    public function getPageNumber(): int
254
    {
255 2
        $pages = $this->document->getPages();
256 2
        $numOfPages = \count($pages);
257 2
        for ($pageNum = 0; $pageNum < $numOfPages; ++$pageNum) {
258 2
            if ($pages[$pageNum] === $this) {
259 2
                break;
260
            }
261
        }
262
263 2
        return $pageNum;
264
    }
265
266
    /**
267
     * Return the Object of the page if the document is a FPDF/FPDI document
268
     *
269
     * If the document was generated by FPDF/FPDI it returns the
270
     * PDFObject of the given page
271
     *
272
     * @return PDFObject The PDFObject for the page
273
     */
274 1
    public function getPDFObjectForFpdf(): PDFObject
275
    {
276 1
        $pageNum = $this->getPageNumber();
277 1
        $xObjects = $this->getXObjects();
278
279 1
        return $xObjects[$pageNum];
280
    }
281
282
    /**
283
     * Return a new PDFObject of the document created with FPDF/FPDI
284
     *
285
     * For a document generated by FPDF/FPDI, it generates a
286
     * new PDFObject for that document
287
     *
288
     * @return PDFObject The PDFObject
289
     */
290 1
    public function createPDFObjectForFpdf(): PDFObject
291
    {
292 1
        $pdfObject = $this->getPDFObjectForFpdf();
293 1
        $new_content = $pdfObject->getContent();
294 1
        $header = $pdfObject->getHeader();
295 1
        $config = $pdfObject->config;
296
297 1
        return new PDFObject($pdfObject->document, $header, $new_content, $config);
298
    }
299
300
    /**
301
     * Return page if document is a FPDF/FPDI document
302
     *
303
     * @return Page The page
304
     */
305 1
    public function createPageForFpdf(): self
306
    {
307 1
        $pdfObject = $this->getPDFObjectForFpdf();
308 1
        $new_content = $pdfObject->getContent();
309 1
        $header = $pdfObject->getHeader();
310 1
        $config = $pdfObject->config;
311
312 1
        return new self($pdfObject->document, $header, $new_content, $config);
313
    }
314
315 6
    public function getTextArray(self $page = null): array
316
    {
317 6
        if ($this->isFpdf()) {
318 1
            $pdfObject = $this->getPDFObjectForFpdf();
319 1
            $newPdfObject = $this->createPDFObjectForFpdf();
320
321 1
            return $newPdfObject->getTextArray($pdfObject);
322
        } else {
323 5
            if ($contents = $this->get('Contents')) {
324 5
                if ($contents instanceof ElementMissing) {
325
                    return [];
326 5
                } elseif ($contents instanceof ElementNull) {
327
                    return [];
328 5
                } elseif ($contents instanceof PDFObject) {
329 5
                    $elements = $contents->getHeader()->getElements();
330
331 5
                    if (is_numeric(key($elements))) {
332
                        $new_content = '';
333
334
                        /** @var PDFObject $element */
335
                        foreach ($elements as $element) {
336
                            if ($element instanceof ElementXRef) {
337
                                $new_content .= $element->getObject()->getContent();
338
                            } else {
339
                                $new_content .= $element->getContent();
340
                            }
341
                        }
342
343
                        $header = new Header([], $this->document);
344
                        $contents = new PDFObject($this->document, $header, $new_content, $this->config);
345
                    } else {
346
                        try {
347 5
                            $contents->getTextArray($this);
348 1
                        } catch (\Throwable $e) {
349 5
                            return $contents->getTextArray();
350
                        }
351
                    }
352 1
                } elseif ($contents instanceof ElementArray) {
353
                    // Create a virtual global content.
354 1
                    $new_content = '';
355
356
                    /** @var PDFObject $content */
357 1
                    foreach ($contents->getContent() as $content) {
358 1
                        $new_content .= $content->getContent()."\n";
359
                    }
360
361 1
                    $header = new Header([], $this->document);
362 1
                    $contents = new PDFObject($this->document, $header, $new_content, $this->config);
363
                }
364
365 4
                return $contents->getTextArray($this);
366
            }
367
368
            return [];
369
        }
370
    }
371
372
    /**
373
     * Gets all the text data with its internal representation of the page.
374
     *
375
     * Returns an array with the data and the internal representation
376
     */
377 10
    public function extractRawData(): array
378
    {
379
        /*
380
         * Now you can get the complete content of the object with the text on it
381
         */
382 10
        $extractedData = [];
383 10
        $content = $this->get('Contents');
384 10
        $values = $content->getContent();
385 10
        if (isset($values) && \is_array($values)) {
386 1
            $text = '';
387 1
            foreach ($values as $section) {
388 1
                $text .= $section->getContent();
389
            }
390 1
            $sectionsText = $this->getSectionsText($text);
391 1
            foreach ($sectionsText as $sectionText) {
392 1
                $commandsText = $this->getCommandsText($sectionText);
393 1
                foreach ($commandsText as $command) {
394 1
                    $extractedData[] = $command;
395
                }
396
            }
397
        } else {
398 10
            if ($this->isFpdf()) {
399 1
                $content = $this->getPDFObjectForFpdf();
400
            }
401 10
            $sectionsText = $content->getSectionsText($content->getContent());
402 10
            foreach ($sectionsText as $sectionText) {
403 10
                $extractedData[] = ['t' => '', 'o' => 'BT', 'c' => ''];
404
405 10
                $commandsText = $content->getCommandsText($sectionText);
406 10
                foreach ($commandsText as $command) {
407 10
                    $extractedData[] = $command;
408
                }
409
            }
410
        }
411
412 10
        return $extractedData;
413
    }
414
415
    /**
416
     * Gets all the decoded text data with it internal representation from a page.
417
     *
418
     * @param array $extractedRawData the extracted data return by extractRawData or
419
     *                                null if extractRawData should be called
420
     *
421
     * @return array An array with the data and the internal representation
422
     */
423 9
    public function extractDecodedRawData(array $extractedRawData = null): array
424
    {
425 9
        if (!isset($extractedRawData) || !$extractedRawData) {
426 9
            $extractedRawData = $this->extractRawData();
427
        }
428 9
        $currentFont = null; /** @var Font $currentFont */
429 9
        $clippedFont = null;
430 9
        $fpdfPage = null;
431 9
        if ($this->isFpdf()) {
432 1
            $fpdfPage = $this->createPageForFpdf();
433
        }
434 9
        foreach ($extractedRawData as &$command) {
435 9
            if ('Tj' == $command['o'] || 'TJ' == $command['o']) {
436 9
                $data = $command['c'];
437 9
                if (!\is_array($data)) {
438 7
                    $tmpText = '';
439 7
                    if (isset($currentFont)) {
440 7
                        $tmpText = $currentFont->decodeOctal($data);
441
                        // $tmpText = $currentFont->decodeHexadecimal($tmpText, false);
442
                    }
443 7
                    $tmpText = str_replace(
444 7
                        ['\\\\', '\(', '\)', '\n', '\r', '\t', '\ '],
445 7
                        ['\\', '(', ')', "\n", "\r", "\t", ' '],
446
                        $tmpText
447
                    );
448 7
                    $tmpText = mb_convert_encoding($tmpText, 'UTF-8', 'ISO-8859-1');
449 7
                    if (isset($currentFont)) {
450 7
                        $tmpText = $currentFont->decodeContent($tmpText);
0 ignored issues
show
It seems like $tmpText can also be of type array; however, parameter $text of Smalot\PdfParser\Font::decodeContent() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

450
                        $tmpText = $currentFont->decodeContent(/** @scrutinizer ignore-type */ $tmpText);
Loading history...
451
                    }
452 7
                    $command['c'] = $tmpText;
453 7
                    continue;
454
                }
455 9
                $numText = \count($data);
456 9
                for ($i = 0; $i < $numText; ++$i) {
457 9
                    if (0 != ($i % 2)) {
458 7
                        continue;
459
                    }
460 9
                    $tmpText = $data[$i]['c'];
461 9
                    $decodedText = isset($currentFont) ? $currentFont->decodeOctal($tmpText) : $tmpText;
462 9
                    $decodedText = str_replace(
463 9
                        ['\\\\', '\(', '\)', '\n', '\r', '\t', '\ '],
464 9
                        ['\\', '(', ')', "\n", "\r", "\t", ' '],
465
                        $decodedText
466
                    );
467
468 9
                    $decodedText = mb_convert_encoding($decodedText, 'UTF-8', 'ISO-8859-1');
469
470 9
                    if (isset($currentFont)) {
471 7
                        $decodedText = $currentFont->decodeContent($decodedText);
472
                    }
473 9
                    $command['c'][$i]['c'] = $decodedText;
474 9
                    continue;
475
                }
476 9
            } elseif ('Tf' == $command['o'] || 'TF' == $command['o']) {
477 9
                $fontId = explode(' ', $command['c'])[0];
478
                // If document is a FPDI/FPDF the $page has the correct font
479 9
                $currentFont = isset($fpdfPage) ? $fpdfPage->getFont($fontId) : $this->getFont($fontId);
480 9
                continue;
481 9
            } elseif ('Q' == $command['o']) {
482
                $currentFont = $clippedFont;
483 9
            } elseif ('q' == $command['o']) {
484
                $clippedFont = $currentFont;
485
            }
486
        }
487
488 9
        return $extractedRawData;
489
    }
490
491
    /**
492
     * Gets just the Text commands that are involved in text positions and
493
     * Text Matrix (Tm)
494
     *
495
     * It extract just the PDF commands that are involved with text positions, and
496
     * the Text Matrix (Tm). These are: BT, ET, TL, Td, TD, Tm, T*, Tj, ', ", and TJ
497
     *
498
     * @param array $extractedDecodedRawData The data extracted by extractDecodeRawData.
499
     *                                       If it is null, the method extractDecodeRawData is called.
500
     *
501
     * @return array An array with the text command of the page
502
     */
503 7
    public function getDataCommands(array $extractedDecodedRawData = null): array
504
    {
505 7
        if (!isset($extractedDecodedRawData) || !$extractedDecodedRawData) {
506 7
            $extractedDecodedRawData = $this->extractDecodedRawData();
507
        }
508 7
        $extractedData = [];
509 7
        foreach ($extractedDecodedRawData as $command) {
510 7
            switch ($command['o']) {
511
                /*
512
                 * BT
513
                 * Begin a text object, inicializind the Tm and Tlm to identity matrix
514
                 */
515 7
                case 'BT':
516 7
                    $extractedData[] = $command;
517 7
                    break;
518
519
                    /*
520
                     * ET
521
                     * End a text object, discarding the text matrix
522
                     */
523 7
                case 'ET':
524
                    $extractedData[] = $command;
525
                    break;
526
527
                    /*
528
                     * leading TL
529
                     * Set the text leading, Tl, to leading. Tl is used by the T*, ' and " operators.
530
                     * Initial value: 0
531
                     */
532 7
                case 'TL':
533 5
                    $extractedData[] = $command;
534 5
                    break;
535
536
                    /*
537
                     * tx ty Td
538
                     * Move to the start of the next line, offset form the start of the
539
                     * current line by tx, ty.
540
                     */
541 7
                case 'Td':
542 7
                    $extractedData[] = $command;
543 7
                    break;
544
545
                    /*
546
                     * tx ty TD
547
                     * Move to the start of the next line, offset form the start of the
548
                     * current line by tx, ty. As a side effect, this operator set the leading
549
                     * parameter in the text state. This operator has the same effect as the
550
                     * code:
551
                     * -ty TL
552
                     * tx ty Td
553
                     */
554 7
                case 'TD':
555
                    $extractedData[] = $command;
556
                    break;
557
558
                    /*
559
                     * a b c d e f Tm
560
                     * Set the text matrix, Tm, and the text line matrix, Tlm. The operands are
561
                     * all numbers, and the initial value for Tm and Tlm is the identity matrix
562
                     * [1 0 0 1 0 0]
563
                     */
564 7
                case 'Tm':
565 5
                    $extractedData[] = $command;
566 5
                    break;
567
568
                    /*
569
                     * T*
570
                     * Move to the start of the next line. This operator has the same effect
571
                     * as the code:
572
                     * 0 Tl Td
573
                     * Where Tl is the current leading parameter in the text state.
574
                     */
575 7
                case 'T*':
576 5
                    $extractedData[] = $command;
577 5
                    break;
578
579
                    /*
580
                     * string Tj
581
                     * Show a Text String
582
                     */
583 7
                case 'Tj':
584 6
                    $extractedData[] = $command;
585 6
                    break;
586
587
                    /*
588
                     * string '
589
                     * Move to the next line and show a text string. This operator has the
590
                     * same effect as the code:
591
                     * T*
592
                     * string Tj
593
                     */
594 7
                case "'":
595
                    $extractedData[] = $command;
596
                    break;
597
598
                    /*
599
                     * aw ac string "
600
                     * Move to the next lkine and show a text string, using aw as the word
601
                     * spacing and ac as the character spacing. This operator has the same
602
                     * effect as the code:
603
                     * aw Tw
604
                     * ac Tc
605
                     * string '
606
                     * Tw set the word spacing, Tw, to wordSpace.
607
                     * Tc Set the character spacing, Tc, to charsSpace.
608
                     */
609 7
                case '"':
610
                    $extractedData[] = $command;
611
                    break;
612
613 7
                case 'Tf':
614 7
                case 'TF':
615 7
                    if ($this->config->getDataTmFontInfoHasToBeIncluded()) {
616 1
                        $extractedData[] = $command;
617
                    }
618 7
                    break;
619
620
                    /*
621
                     * array TJ
622
                     * Show one or more text strings allow individual glyph positioning.
623
                     * Each lement of array con be a string or a number. If the element is
624
                     * a string, this operator shows the string. If it is a number, the
625
                     * operator adjust the text position by that amount; that is, it translates
626
                     * the text matrix, Tm. This amount is substracted form the current
627
                     * horizontal or vertical coordinate, depending on the writing mode.
628
                     * in the default coordinate system, a positive adjustment has the effect
629
                     * of moving the next glyph painted either to the left or down by the given
630
                     * amount.
631
                     */
632 7
                case 'TJ':
633 7
                    $extractedData[] = $command;
634 7
                    break;
635
                default:
636
            }
637
        }
638
639 7
        return $extractedData;
640
    }
641
642
    /**
643
     * Gets the Text Matrix of the text in the page
644
     *
645
     * Return an array where every item is an array where the first item is the
646
     * Text Matrix (Tm) and the second is a string with the text data.  The Text matrix
647
     * is an array of 6 numbers. The last 2 numbers are the coordinates X and Y of the
648
     * text. The first 4 numbers has to be with Scalation, Rotation and Skew of the text.
649
     *
650
     * @param array $dataCommands the data extracted by getDataCommands
651
     *                            if null getDataCommands is called
652
     *
653
     * @return array an array with the data of the page including the Tm information
654
     *               of any text in the page
655
     */
656 6
    public function getDataTm(array $dataCommands = null): array
657
    {
658 6
        if (!isset($dataCommands) || !$dataCommands) {
659 6
            $dataCommands = $this->getDataCommands();
660
        }
661
662
        /*
663
         * At the beginning of a text object Tm is the identity matrix
664
         */
665 6
        $defaultTm = ['1', '0', '0', '1', '0', '0'];
666
667
        /*
668
         *  Set the text leading used by T*, ' and " operators
669
         */
670 6
        $defaultTl = 0;
671
672
        /*
673
         *  Set default values for font data
674
         */
675 6
        $defaultFontId = -1;
676 6
        $defaultFontSize = 0;
677
678
        /*
679
         * Setting where are the X and Y coordinates in the matrix (Tm)
680
         */
681 6
        $x = 4;
682 6
        $y = 5;
683 6
        $Tx = 0;
684 6
        $Ty = 0;
685
686 6
        $Tm = $defaultTm;
687 6
        $Tl = $defaultTl;
688 6
        $fontId = $defaultFontId;
689 6
        $fontSize = $defaultFontSize;
690
691 6
        $extractedTexts = $this->getTextArray();
692 6
        $extractedData = [];
693 6
        foreach ($dataCommands as $command) {
694 6
            $currentText = $extractedTexts[\count($extractedData)];
695 6
            switch ($command['o']) {
696
                /*
697
                 * BT
698
                 * Begin a text object, inicializind the Tm and Tlm to identity matrix
699
                 */
700 6
                case 'BT':
701 6
                    $Tm = $defaultTm;
702 6
                    $Tl = $defaultTl; // review this.
703 6
                    $Tx = 0;
704 6
                    $Ty = 0;
705 6
                    $fontId = $defaultFontId;
706 6
                    $fontSize = $defaultFontSize;
707 6
                    break;
708
709
                    /*
710
                     * ET
711
                     * End a text object, discarding the text matrix
712
                     */
713 6
                case 'ET':
714
                    $Tm = $defaultTm;
715
                    $Tl = $defaultTl;  // review this
716
                    $Tx = 0;
717
                    $Ty = 0;
718
                    $fontId = $defaultFontId;
719
                    $fontSize = $defaultFontSize;
720
                    break;
721
722
                    /*
723
                     * leading TL
724
                     * Set the text leading, Tl, to leading. Tl is used by the T*, ' and " operators.
725
                     * Initial value: 0
726
                     */
727 6
                case 'TL':
728 4
                    $Tl = (float) $command['c'];
729 4
                    break;
730
731
                    /*
732
                     * tx ty Td
733
                     * Move to the start of the next line, offset form the start of the
734
                     * current line by tx, ty.
735
                     */
736 6
                case 'Td':
737 6
                    $coord = explode(' ', $command['c']);
738 6
                    $Tx += (float) $coord[0];
739 6
                    $Ty += (float) $coord[1];
740 6
                    $Tm[$x] = (string) $Tx;
741 6
                    $Tm[$y] = (string) $Ty;
742 6
                    break;
743
744
                    /*
745
                     * tx ty TD
746
                     * Move to the start of the next line, offset form the start of the
747
                     * current line by tx, ty. As a side effect, this operator set the leading
748
                     * parameter in the text state. This operator has the same effect as the
749
                     * code:
750
                     * -ty TL
751
                     * tx ty Td
752
                     */
753 6
                case 'TD':
754
                    $coord = explode(' ', $command['c']);
755
                    $Tl = (float) $coord[1];
756
                    $Tx += (float) $coord[0];
757
                    $Ty -= (float) $coord[1];
758
                    $Tm[$x] = (string) $Tx;
759
                    $Tm[$y] = (string) $Ty;
760
                    break;
761
762
                    /*
763
                     * a b c d e f Tm
764
                     * Set the text matrix, Tm, and the text line matrix, Tlm. The operands are
765
                     * all numbers, and the initial value for Tm and Tlm is the identity matrix
766
                     * [1 0 0 1 0 0]
767
                     */
768 6
                case 'Tm':
769 4
                    $Tm = explode(' ', $command['c']);
770 4
                    $Tx = (float) $Tm[$x];
771 4
                    $Ty = (float) $Tm[$y];
772 4
                    break;
773
774
                    /*
775
                     * T*
776
                     * Move to the start of the next line. This operator has the same effect
777
                     * as the code:
778
                     * 0 Tl Td
779
                     * Where Tl is the current leading parameter in the text state.
780
                     */
781 6
                case 'T*':
782 4
                    $Ty -= $Tl;
783 4
                    $Tm[$y] = (string) $Ty;
784 4
                    break;
785
786
                    /*
787
                     * string Tj
788
                     * Show a Text String
789
                     */
790 6
                case 'Tj':
791 5
                    $data = [$Tm, $currentText];
792 5
                    if ($this->config->getDataTmFontInfoHasToBeIncluded()) {
793 1
                        $data[] = $fontId;
794 1
                        $data[] = $fontSize;
795
                    }
796 5
                    $extractedData[] = $data;
797 5
                    break;
798
799
                    /*
800
                     * string '
801
                     * Move to the next line and show a text string. This operator has the
802
                     * same effect as the code:
803
                     * T*
804
                     * string Tj
805
                     */
806 6
                case "'":
807
                    $Ty -= $Tl;
808
                    $Tm[$y] = (string) $Ty;
809
                    $extractedData[] = [$Tm, $currentText];
810
                    break;
811
812
                    /*
813
                     * aw ac string "
814
                     * Move to the next line and show a text string, using aw as the word
815
                     * spacing and ac as the character spacing. This operator has the same
816
                     * effect as the code:
817
                     * aw Tw
818
                     * ac Tc
819
                     * string '
820
                     * Tw set the word spacing, Tw, to wordSpace.
821
                     * Tc Set the character spacing, Tc, to charsSpace.
822
                     */
823 6
                case '"':
824
                    $data = explode(' ', $currentText);
825
                    $Ty -= $Tl;
826
                    $Tm[$y] = (string) $Ty;
827
                    $extractedData[] = [$Tm, $data[2]]; // Verify
828
                    break;
829
830 6
                case 'Tf':
831
                    /*
832
                     * From PDF 1.0 specification, page 106:
833
                     *     fontname size Tf Set font and size
834
                     *     Sets the text font and text size in the graphics state. There is no default value for
835
                     *     either fontname or size; they must be selected using Tf before drawing any text.
836
                     *     fontname is a resource name. size is a number expressed in text space units.
837
                     *
838
                     * Source: https://ia902503.us.archive.org/10/items/pdfy-0vt8s-egqFwDl7L2/PDF%20Reference%201.0.pdf
839
                     * Introduced with https://github.com/smalot/pdfparser/pull/516
840
                     */
841 1
                    list($fontId, $fontSize) = explode(' ', $command['c'], 2);
842 1
                    break;
843
844
                    /*
845
                     * array TJ
846
                     * Show one or more text strings allow individual glyph positioning.
847
                     * Each lement of array con be a string or a number. If the element is
848
                     * a string, this operator shows the string. If it is a number, the
849
                     * operator adjust the text position by that amount; that is, it translates
850
                     * the text matrix, Tm. This amount is substracted form the current
851
                     * horizontal or vertical coordinate, depending on the writing mode.
852
                     * in the default coordinate system, a positive adjustment has the effect
853
                     * of moving the next glyph painted either to the left or down by the given
854
                     * amount.
855
                     */
856 6
                case 'TJ':
857 6
                    $data = [$Tm, $currentText];
858 6
                    if ($this->config->getDataTmFontInfoHasToBeIncluded()) {
859 1
                        $data[] = $fontId;
860 1
                        $data[] = $fontSize;
861
                    }
862 6
                    $extractedData[] = $data;
863 6
                    break;
864
                default:
865
            }
866
        }
867 6
        $this->dataTm = $extractedData;
868
869 6
        return $extractedData;
870
    }
871
872
    /**
873
     * Gets text data that are around the given coordinates (X,Y)
874
     *
875
     * If the text is in near the given coordinates (X,Y) (or the TM info),
876
     * the text is returned.  The extractedData return by getDataTm, could be use to see
877
     * where is the coordinates of a given text, using the TM info for it.
878
     *
879
     * @param float $x      The X value of the coordinate to search for. if null
880
     *                      just the Y value is considered (same Row)
881
     * @param float $y      The Y value of the coordinate to search for
882
     *                      just the X value is considered (same column)
883
     * @param float $xError The value less or more to consider an X to be "near"
884
     * @param float $yError The value less or more to consider an Y to be "near"
885
     *
886
     * @return array An array of text that are near the given coordinates. If no text
887
     *               "near" the x,y coordinate, an empty array is returned. If Both, x
888
     *               and y coordinates are null, null is returned.
889
     */
890 2
    public function getTextXY(float $x = null, float $y = null, float $xError = 0, float $yError = 0): array
891
    {
892 2
        if (!isset($this->dataTm) || !$this->dataTm) {
893 1
            $this->getDataTm();
894
        }
895
896 2
        if (null !== $x) {
897 2
            $x = (float) $x;
898
        }
899
900 2
        if (null !== $y) {
901 2
            $y = (float) $y;
902
        }
903
904 2
        if (null === $x && null === $y) {
905
            return [];
906
        }
907
908 2
        $xError = (float) $xError;
909 2
        $yError = (float) $yError;
910
911 2
        $extractedData = [];
912 2
        foreach ($this->dataTm as $item) {
913 2
            $tm = $item[0];
914 2
            $xTm = (float) $tm[4];
915 2
            $yTm = (float) $tm[5];
916 2
            $text = $item[1];
917 2
            if (null === $y) {
918
                if (($xTm >= ($x - $xError)) &&
919
                    ($xTm <= ($x + $xError))) {
920
                    $extractedData[] = [$tm, $text];
921
                    continue;
922
                }
923
            }
924 2
            if (null === $x) {
925
                if (($yTm >= ($y - $yError)) &&
926
                    ($yTm <= ($y + $yError))) {
927
                    $extractedData[] = [$tm, $text];
928
                    continue;
929
                }
930
            }
931 2
            if (($xTm >= ($x - $xError)) &&
932 2
                ($xTm <= ($x + $xError)) &&
933 2
                ($yTm >= ($y - $yError)) &&
934 2
                ($yTm <= ($y + $yError))) {
935 2
                $extractedData[] = [$tm, $text];
936 2
                continue;
937
            }
938
        }
939
940 2
        return $extractedData;
941
    }
942
}
943