Test Failed
Pull Request — master (#455)
by
unknown
06:50
created

Page::getXObjectForFpdf()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 6
ccs 0
cts 1
cp 0
crap 2
rs 10
1
<?php
2
3
/**
4
 * @file
5
 *          This file is part of the PdfParser library.
6
 *
7
 * @author  Sébastien MALOT <[email protected]>
8
 * @date    2017-01-03
9
 *
10
 * @license LGPLv3
11
 * @url     <https://github.com/smalot/pdfparser>
12
 *
13
 *  PdfParser is a pdf library written in PHP, extraction oriented.
14
 *  Copyright (C) 2017 - Sébastien MALOT <[email protected]>
15
 *
16
 *  This program is free software: you can redistribute it and/or modify
17
 *  it under the terms of the GNU Lesser General Public License as published by
18
 *  the Free Software Foundation, either version 3 of the License, or
19
 *  (at your option) any later version.
20
 *
21
 *  This program is distributed in the hope that it will be useful,
22
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
23
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24
 *  GNU Lesser General Public License for more details.
25
 *
26
 *  You should have received a copy of the GNU Lesser General Public License
27
 *  along with this program.
28
 *  If not, see <http://www.pdfparser.org/sites/default/LICENSE.txt>.
29
 */
30
31
namespace Smalot\PdfParser;
32
33
use Smalot\PdfParser\Element\ElementArray;
34
use Smalot\PdfParser\Element\ElementMissing;
35
use Smalot\PdfParser\Element\ElementNull;
36
use Smalot\PdfParser\Element\ElementXRef;
37
38
class Page extends PDFObject
39
{
40
    /**
41
     * @var Font[]
42
     */
43
    protected $fonts = null;
44
45
    /**
46
     * @var PDFObject[]
47
     */
48
    protected $xobjects = null;
49
50
    /**
51
     * @var array
52
     */
53
    protected $dataTm = null;
54
55
    /**
56
     * @return Font[]
57
     */
58 23
    public function getFonts()
59
    {
60 23
        if (null !== $this->fonts) {
61 19
            return $this->fonts;
62
        }
63
64 23
        $resources = $this->get('Resources');
65
66 23
        if (method_exists($resources, 'has') && $resources->has('Font')) {
67 20
            if ($resources->get('Font') instanceof ElementMissing) {
0 ignored issues
show
Bug introduced by
The method get() does not exist on Smalot\PdfParser\Element. ( Ignorable by Annotation )

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

67
            if ($resources->/** @scrutinizer ignore-call */ get('Font') instanceof ElementMissing) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
68 1
                return [];
69
            }
70
71 19
            if ($resources->get('Font') instanceof Header) {
72 13
                $fonts = $resources->get('Font')->getElements();
73
            } else {
74 8
                $fonts = $resources->get('Font')->getHeader()->getElements();
75
            }
76
77 19
            $table = [];
78
79 19
            foreach ($fonts as $id => $font) {
80 19
                if ($font instanceof Font) {
81 19
                    $table[$id] = $font;
82
83
                    // Store too on cleaned id value (only numeric)
84 19
                    $id = preg_replace('/[^0-9\.\-_]/', '', $id);
85 19
                    if ('' != $id) {
86 19
                        $table[$id] = $font;
87
                    }
88
                }
89
            }
90
91 19
            return $this->fonts = $table;
92
        }
93
94 5
        return [];
95
    }
96
97 21
    public function getFont(string $id): ?Font
98
    {
99 21
        $fonts = $this->getFonts();
100
101 21
        if (isset($fonts[$id])) {
102 18
            return $fonts[$id];
103
        }
104
105
        // According to the PDF specs (https://www.adobe.com/content/dam/acom/en/devnet/pdf/pdfs/PDF32000_2008.pdf, page 238)
106
        // "The font resource name presented to the Tf operator is arbitrary, as are the names for all kinds of resources"
107
        // Instead, we search for the unfiltered name first and then do this cleaning as a fallback, so all tests still pass.
108
109 4
        if (isset($fonts[$id])) {
110
            return $fonts[$id];
111
        } else {
112 4
            $id = preg_replace('/[^0-9\.\-_]/', '', $id);
113 4
            if (isset($fonts[$id])) {
114 1
                return $fonts[$id];
115
            }
116
        }
117
118 3
        return null;
119
    }
120
121
    /**
122
     * Support for XObject
123
     *
124
     * @return PDFObject[]
125
     */
126 4
    public function getXObjects()
127
    {
128 4
        if (null !== $this->xobjects) {
129 3
            return $this->xobjects;
130
        }
131
132 4
        $resources = $this->get('Resources');
133
134 4
        if (method_exists($resources, 'has') && $resources->has('XObject')) {
135 4
            if ($resources->get('XObject') instanceof Header) {
136 4
                $xobjects = $resources->get('XObject')->getElements();
137
            } else {
138
                $xobjects = $resources->get('XObject')->getHeader()->getElements();
139
            }
140
141 4
            $table = [];
142
143 4
            foreach ($xobjects as $id => $xobject) {
144 4
                $table[$id] = $xobject;
145
146
                // Store too on cleaned id value (only numeric)
147 4
                $id = preg_replace('/[^0-9\.\-_]/', '', $id);
148 4
                if ('' != $id) {
149 4
                    $table[$id] = $xobject;
150
                }
151
            }
152
153 4
            return $this->xobjects = $table;
154
        }
155
156
        return [];
157
    }
158
159 4
    public function getXObject(string $id): ?PDFObject
160
    {
161 4
        $xobjects = $this->getXObjects();
162
163 4
        if (isset($xobjects[$id])) {
164 4
            return $xobjects[$id];
165
        }
166
167
        return null;
168
        /*$id = preg_replace('/[^0-9\.\-_]/', '', $id);
169
170
        if (isset($xobjects[$id])) {
171
            return $xobjects[$id];
172
        } else {
173
            return null;
174
        }*/
175
    }
176
177 13
    public function getText(self $page = null): string
178
    {
179 13
        if ($contents = $this->get('Contents')) {
180 13
            if ($contents instanceof ElementMissing) {
181
                return '';
182 13
            } elseif ($contents instanceof ElementNull) {
183
                return '';
184 13
            } elseif ($contents instanceof PDFObject) {
0 ignored issues
show
introduced by
$contents is never a sub-type of Smalot\PdfParser\PDFObject.
Loading history...
185 10
                $elements = $contents->getHeader()->getElements();
186
187 10
                if (is_numeric(key($elements))) {
188
                    $new_content = '';
189
190
                    foreach ($elements as $element) {
191
                        if ($element instanceof ElementXRef) {
192
                            $new_content .= $element->getObject()->getContent();
193
                        } else {
194
                            $new_content .= $element->getContent();
195
                        }
196
                    }
197
198
                    $header = new Header([], $this->document);
199 10
                    $contents = new PDFObject($this->document, $header, $new_content, $this->config);
200
                }
201 3
            } elseif ($contents instanceof ElementArray) {
202
                // Create a virtual global content.
203 3
                $new_content = '';
204
205 3
                foreach ($contents->getContent() as $content) {
206 3
                    $new_content .= $content->getContent()."\n";
207
                }
208
209 3
                $header = new Header([], $this->document);
210 3
                $contents = new PDFObject($this->document, $header, $new_content, $this->config);
211
            }
212
213 13
            /*
214
             * Elements referencing each other on the same page can cause endless loops during text parsing.
215
             * To combat this we keep a recursionStack containing already parsed elements on the page.
216
             * The stack is only emptied here after getting text from a page.
217
             */
218
            $contentsText = $contents->getText($this);
0 ignored issues
show
Bug introduced by
The method getText() does not exist on Smalot\PdfParser\Element. ( Ignorable by Annotation )

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

218
            /** @scrutinizer ignore-call */ 
219
            $contentsText = $contents->getText($this);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
219 4
            PDFObject::$recursionStack = [];
220
221 4
            return $contentsText;
222 4
        }
223
224 4
        return '';
225
    }
226 4
227 4
    /**
228
     * Return true if the current page is a (setasign\Fpdi\Fpdi) FPDI/FPDF document
229 4
     *
230
     * @return bool true is the current page is a FPDI/FPDF document
231
     */
232
    public function isFpdf(): bool
233
    {
234
        if (\array_key_exists('Producer', $this->document->getDetails()) &&
235
            \is_string($this->document->getDetails()['Producer']) &&
236
            str_starts_with($this->document->getDetails()['Producer'], 'FPDF')) {
237
            return true;
238
        }
239
240
        return false;
241
    }
242
243
    /**
244
     * Return the page number of the PDF document of the page object
245 4
     *
246 1
     * @return int the page number
247 4
     */
248
    public function getPageNumber(): int
249
    {
250
        $pages = $this->document->getPages();
251
        $numOfPages = \count($pages);
252
        for ($pageNum = 0; $pageNum < $numOfPages; ++$pageNum) {
253
            if ($pages[$pageNum] === $this) {
254
                break;
255
            }
256
        }
257
258
        return $pageNum;
259
    }
260
261
    /**
262
     * Return the xObject if the document is from fpdf
263 3
     *
264
     * @return object The xObject for the page
265
     */
266
    public function getXObjectForFpdf()
267
    {
268
        $pageNum = $this->getPageNumber();
269
        $xObjects = $this->getXObjects();
270
271
        return $xObjects[$pageNum];
272
    }
273
274 8
    /**
275
     * Return a PDFObject if document is from fpdf
276
     *
277
     * @return object The xObject for the page
278
     */
279 8
    public function getPDFObjectForFpdf()
280 8
    {
281 8
        $xObject = $this->getXObjectForFpdf();
282 8
        $new_content = $xObject->getContent();
283
        $header = $xObject->getHeader();
284
        $config = $xObject->config;
285
286
        return new PDFObject($xObject->document, $header, $new_content, $config);
287
    }
288
289
    /**
290
     * Return page if document is from fpdf
291
     *
292
     * @return object The page
293
     */
294
    public function getPageForFpdf()
295 8
    {
296 8
        $xObject = $this->getXObjectForFpdf();
297 8
        $new_content = $xObject->getContent();
298
        $header = $xObject->getHeader();
299 8
        $config = $xObject->config;
300 8
301 8
        return new self($xObject->document, $header, $new_content, $config);
302
    }
303
304
    public function getTextArray(self $page = null): array
305
    {
306 8
        if ($this->isFpdf()) {
307
            $xObject = $this->getXObjectForFpdf();
308
            $pdfObject = $this->getPDFObjectForFpdf();
309
310
            return $pdfObject->getTextArray($xObject);
311
        }
312
        if ($contents = $this->get('Contents')) {
313
            if ($contents instanceof ElementMissing) {
314
                return [];
315
            } elseif ($contents instanceof ElementNull) {
316
                return [];
317 7
            } elseif ($contents instanceof PDFObject) {
0 ignored issues
show
introduced by
$contents is never a sub-type of Smalot\PdfParser\PDFObject.
Loading history...
318
                $elements = $contents->getHeader()->getElements();
319 7
320 7
                if (is_numeric(key($elements))) {
321
                    $new_content = '';
322 7
323 7
                    /** @var PDFObject $element */
324 7
                    foreach ($elements as $element) {
325 7
                        if ($element instanceof ElementXRef) {
326 7
                            $new_content .= $element->getObject()->getContent();
327 7
                        } else {
328 5
                            $new_content .= $element->getContent();
329 5
                        }
330 5
                    }
331
332
                    $header = new Header([], $this->document);
333 5
                    $contents = new PDFObject($this->document, $header, $new_content, $this->config);
334 5
                } else {
335 5
                    try {
336
                        $contents->getTextArray($this);
337
                    } catch (\Throwable $e) {
338 5
                        return $contents->getTextArray();
339 5
                    }
340 5
                }
341
            } elseif ($contents instanceof ElementArray) {
342 5
                // Create a virtual global content.
343 5
                $new_content = '';
344
345 7
                /** @var PDFObject $content */
346 7
                foreach ($contents->getContent() as $content) {
347 7
                    $new_content .= $content->getContent()."\n";
348 5
                }
349
350 7
                $header = new Header([], $this->document);
351 7
                $contents = new PDFObject($this->document, $header, $new_content, $this->config);
352 7
            }
353 7
354 7
            return $contents->getTextArray($this);
0 ignored issues
show
Bug introduced by
The method getTextArray() does not exist on Smalot\PdfParser\Element. ( Ignorable by Annotation )

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

354
            return $contents->/** @scrutinizer ignore-call */ getTextArray($this);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
355
        }
356
357 7
        return [];
358 7
    }
359 5
360
    /**
361 7
     * Gets all the text data with its internal representation of the page.
362 7
     *
363
     * Returns an array with the data and the internal representation
364 7
     */
365 7
    public function extractRawData(): array
366 7
    {
367 7
        /*
368 7
         * Now you can get the complete content of the object with the text on it
369
         */
370 7
        $extractedData = [];
371
        $content = $this->get('Contents');
372
        $values = $content->getContent();
373
        if (isset($values) && \is_array($values)) {
374
            $text = '';
375 7
            foreach ($values as $section) {
376
                $text .= $section->getContent();
377
            }
378
            $sectionsText = $this->getSectionsText($text);
379
            foreach ($sectionsText as $sectionText) {
380
                $commandsText = $this->getCommandsText($sectionText);
381
                foreach ($commandsText as $command) {
382
                    $extractedData[] = $command;
383
                }
384
            }
385
        } else {
386
            if ($this->isFpdf()) {
387
                $content = $this->getXObjectForFpdf();
388
            }
389
            $sectionsText = $content->getSectionsText($content->getContent());
0 ignored issues
show
Bug introduced by
The method getSectionsText() does not exist on Smalot\PdfParser\Element. ( Ignorable by Annotation )

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

389
            /** @scrutinizer ignore-call */ 
390
            $sectionsText = $content->getSectionsText($content->getContent());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
390 5
            foreach ($sectionsText as $sectionText) {
391
                $extractedData[] = ['t' => '', 'o' => 'BT', 'c' => ''];
392 5
393 5
                $commandsText = $content->getCommandsText($sectionText);
0 ignored issues
show
Bug introduced by
The method getCommandsText() does not exist on Smalot\PdfParser\Element. ( Ignorable by Annotation )

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

393
                /** @scrutinizer ignore-call */ 
394
                $commandsText = $content->getCommandsText($sectionText);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
394
                foreach ($commandsText as $command) {
395 5
                    $extractedData[] = $command;
396 5
                }
397 5
            }
398
        }
399
400
        return $extractedData;
401
    }
402 5
403 5
    /**
404 5
     * Gets all the decoded text data with it internal representation from a page.
405
     *
406
     * @param array $extractedRawData the extracted data return by extractRawData or
407
     *                                null if extractRawData should be called
408
     *
409
     * @return array An array with the data and the internal representation
410 5
     */
411
    public function extractDecodedRawData(array $extractedRawData = null): array
412
    {
413
        if (!isset($extractedRawData) || !$extractedRawData) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $extractedRawData of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
414
            $extractedRawData = $this->extractRawData();
415
        }
416
        $currentFont = null; /** @var Font $currentFont */
417
        $clippedFont = null;
418
        $fpdfPage = null;
419 5
        if ($this->isFpdf()) {
420 3
            $fpdfPage = $this->getPageForFpdf();
421 3
        }
422
        foreach ($extractedRawData as &$command) {
423
            if ('Tj' == $command['o'] || 'TJ' == $command['o']) {
424
                $data = $command['c'];
425
                if (!\is_array($data)) {
426
                    $tmpText = '';
427
                    if (isset($currentFont)) {
428 5
                        $tmpText = $currentFont->decodeOctal($data);
429 5
                        //$tmpText = $currentFont->decodeHexadecimal($tmpText, false);
430 5
                    }
431
                    $tmpText = str_replace(
432
                            ['\\\\', '\(', '\)', '\n', '\r', '\t', '\ '],
433
                            ['\\', '(', ')', "\n", "\r", "\t", ' '],
434
                            $tmpText
435
                    );
436
                    $tmpText = utf8_encode($tmpText);
437
                    if (isset($currentFont)) {
438
                        $tmpText = $currentFont->decodeContent($tmpText);
439
                    }
440
                    $command['c'] = $tmpText;
441 5
                    continue;
442
                }
443
                $numText = \count($data);
444
                for ($i = 0; $i < $numText; ++$i) {
445
                    if (0 != ($i % 2)) {
446
                        continue;
447
                    }
448
                    $tmpText = $data[$i]['c'];
449
                    $decodedText = isset($currentFont) ? $currentFont->decodeOctal($tmpText) : $tmpText;
450
                    $decodedText = str_replace(
451 5
                            ['\\\\', '\(', '\)', '\n', '\r', '\t', '\ '],
452 3
                            ['\\', '(', ')', "\n", "\r", "\t", ' '],
453 3
                            $decodedText
454
                    );
455
                    $decodedText = utf8_encode($decodedText);
456
                    if (isset($currentFont)) {
457
                        $decodedText = $currentFont->decodeContent($decodedText);
458
                    }
459
                    $command['c'][$i]['c'] = $decodedText;
460
                    continue;
461
                }
462 5
            } elseif ('Tf' == $command['o'] || 'TF' == $command['o']) {
463 3
                $fontId = explode(' ', $command['c'])[0];
464 3
                // If document is a FPDI/FPDF the $page has the correct font
465
                $currentFont = isset($fpdfPage) ? $fpdfPage->getFont($fontId) : $this->getFont($fontId);
466
                continue;
467
            } elseif ('Q' == $command['o']) {
468
                $currentFont = $clippedFont;
469
            } elseif ('q' == $command['o']) {
470 5
                $clippedFont = $currentFont;
471 4
            }
472 4
        }
473
474
        return $extractedRawData;
475
    }
476
477
    /**
478
     * Gets just the Text commands that are involved in text positions and
479
     * Text Matrix (Tm)
480
     *
481 5
     * It extract just the PDF commands that are involved with text positions, and
482
     * the Text Matrix (Tm). These are: BT, ET, TL, Td, TD, Tm, T*, Tj, ', ", and TJ
483
     *
484
     * @param array $extractedDecodedRawData The data extracted by extractDecodeRawData.
485
     *                                       If it is null, the method extractDecodeRawData is called.
486
     *
487
     * @return array An array with the text command of the page
488
     */
489
    public function getDataCommands(array $extractedDecodedRawData = null): array
490
    {
491
        if (!isset($extractedDecodedRawData) || !$extractedDecodedRawData) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $extractedDecodedRawData of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
492
            $extractedDecodedRawData = $this->extractDecodedRawData();
493
        }
494
        $extractedData = [];
495
        foreach ($extractedDecodedRawData as $command) {
496 5
            switch ($command['o']) {
497
                /*
498
                 * BT
499
                 * Begin a text object, inicializind the Tm and Tlm to identity matrix
500
                 */
501
                case 'BT':
502
                    $extractedData[] = $command;
503
                    break;
504
505
                /*
506
                 * ET
507
                 * End a text object, discarding the text matrix
508
                 */
509
                case 'ET':
510
                    $extractedData[] = $command;
511
                    break;
512 5
513 5
                /*
514 5
                 * leading TL
515
                 * Set the text leading, Tl, to leading. Tl is used by the T*, ' and " operators.
516
                 * Initial value: 0
517
                 */
518
                case 'TL':
519 5
                    $extractedData[] = $command;
520
                    break;
521
522
                /*
523
                 * tx ty Td
524
                 * Move to the start of the next line, offset form the start of the
525
                 * current line by tx, ty.
526
                 */
527
                case 'Td':
528
                    $extractedData[] = $command;
529
                    break;
530
531
                /*
532
                 * tx ty TD
533
                 * Move to the start of the next line, offset form the start of the
534
                 * current line by tx, ty. As a side effect, this operator set the leading
535
                 * parameter in the text state. This operator has the same effect as the
536 4
                 * code:
537
                 * -ty TL
538 4
                 * tx ty Td
539 4
                 */
540
                case 'TD':
541
                    $extractedData[] = $command;
542
                    break;
543
544
                /*
545 4
                 * a b c d e f Tm
546
                 * Set the text matrix, Tm, and the text line matrix, Tlm. The operands are
547
                 * all numbers, and the initial value for Tm and Tlm is the identity matrix
548
                 * [1 0 0 1 0 0]
549
                 */
550 4
                case 'Tm':
551
                    $extractedData[] = $command;
552
                    break;
553
554
                /*
555 4
                 * T*
556 4
                 * Move to the start of the next line. This operator has the same effect
557 4
                 * as the code:
558 4
                 * 0 Tl Td
559
                 * Where Tl is the current leading parameter in the text state.
560 4
                 */
561 4
                case 'T*':
562
                    $extractedData[] = $command;
563 4
                    break;
564 4
565 4
                /*
566 4
                 * string Tj
567 4
                 * Show a Text String
568
                 */
569
                case 'Tj':
570
                    $extractedData[] = $command;
571
                    break;
572 4
573 4
                /*
574 4
                 * string '
575 4
                 * Move to the next line and show a text string. This operator has the
576 4
                 * same effect as the code:
577 4
                 * T*
578
                 * string Tj
579
                 */
580
                case "'":
581
                    $extractedData[] = $command;
582
                    break;
583 4
584
                /*
585
                 * aw ac string "
586
                 * Move to the next lkine and show a text string, using aw as the word
587
                 * spacing and ac as the character spacing. This operator has the same
588
                 * effect as the code:
589
                 * aw Tw
590
                 * ac Tc
591
                 * string '
592
                 * Tw set the word spacing, Tw, to wordSpace.
593
                 * Tc Set the character spacing, Tc, to charsSpace.
594
                 */
595 4
                case '"':
596 2
                    $extractedData[] = $command;
597 2
                    break;
598
599
                /*
600
                 * array TJ
601
                 * Show one or more text strings allow individual glyph positioning.
602
                 * Each lement of array con be a string or a number. If the element is
603
                 * a string, this operator shows the string. If it is a number, the
604 4
                 * operator adjust the text position by that amount; that is, it translates
605 4
                 * the text matrix, Tm. This amount is substracted form the current
606 4
                 * horizontal or vertical coordinate, depending on the writing mode.
607 4
                 * in the default coordinate system, a positive adjustment has the effect
608 4
                 * of moving the next glyph painted either to the left or down by the given
609 4
                 * amount.
610 4
                 */
611
                case 'TJ':
612
                    $extractedData[] = $command;
613
                    break;
614
                default:
615
            }
616
        }
617
618
        return $extractedData;
619
    }
620
621 4
    /**
622
     * Gets the Text Matrix of the text in the page
623
     *
624
     * Return an array where every item is an array where the first item is the
625
     * Text Matrix (Tm) and the second is a string with the text data.  The Text matrix
626
     * is an array of 6 numbers. The last 2 numbers are the coordinates X and Y of the
627
     * text. The first 4 numbers has to be with Scalation, Rotation and Skew of the text.
628
     *
629
     * @param array $dataCommands the data extracted by getDataCommands
630
     *                            if null getDataCommands is called
631
     *
632
     * @return array an array with the data of the page including the Tm information
633
     *               of any text in the page
634
     */
635
    public function getDataTm(array $dataCommands = null): array
636 4
    {
637 2
        if (!isset($dataCommands) || !$dataCommands) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $dataCommands of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
638 2
            $dataCommands = $this->getDataCommands();
639 2
        }
640 2
641
        /*
642
         * At the beginning of a text object Tm is the identity matrix
643
         */
644
        $defaultTm = ['1', '0', '0', '1', '0', '0'];
645
646
        /*
647
         *  Set the text leading used by T*, ' and " operators
648
         */
649 4
        $defaultTl = 0;
650 2
651 2
        /*
652 2
         * Setting where are the X and Y coordinates in the matrix (Tm)
653
         */
654
        $x = 4;
655
        $y = 5;
656
        $Tx = 0;
657
        $Ty = 0;
658 4
659 3
        $Tm = $defaultTm;
660 3
        $Tl = $defaultTl;
661
662
        $extractedTexts = $this->getTextArray();
663
        $extractedData = [];
664
        foreach ($dataCommands as $command) {
665
            $currentText = $extractedTexts[\count($extractedData)];
666
            switch ($command['o']) {
667
                /*
668
                 * BT
669 4
                 * Begin a text object, inicializind the Tm and Tlm to identity matrix
670
                 */
671
                case 'BT':
672
                    $Tm = $defaultTm;
673
                    $Tl = $defaultTl; //review this.
674
                    $Tx = 0;
675
                    $Ty = 0;
676
                    break;
677
678
                /*
679
                 * ET
680
                 * End a text object, discarding the text matrix
681
                 */
682
                case 'ET':
683
                    $Tm = $defaultTm;
684
                    $Tl = $defaultTl;  //review this
685
                    $Tx = 0;
686 4
                    $Ty = 0;
687
                    break;
688
689
                /*
690
                 * leading TL
691
                 * Set the text leading, Tl, to leading. Tl is used by the T*, ' and " operators.
692
                 * Initial value: 0
693
                 */
694
                case 'TL':
695
                    $Tl = (float) $command['c'];
696
                    break;
697
698
                /*
699
                 * tx ty Td
700
                 * Move to the start of the next line, offset form the start of the
701
                 * current line by tx, ty.
702
                 */
703
                case 'Td':
704
                    $coord = explode(' ', $command['c']);
705 4
                    $Tx += (float) $coord[0];
706 4
                    $Ty += (float) $coord[1];
707 4
                    $Tm[$x] = (string) $Tx;
708
                    $Tm[$y] = (string) $Ty;
709
                    break;
710
711 4
                /*
712
                 * tx ty TD
713 4
                 * Move to the start of the next line, offset form the start of the
714
                 * current line by tx, ty. As a side effect, this operator set the leading
715
                 * parameter in the text state. This operator has the same effect as the
716
                 * code:
717
                 * -ty TL
718
                 * tx ty Td
719
                 */
720
                case 'TD':
721
                    $coord = explode(' ', $command['c']);
722
                    $Tl = (float) $coord[1];
723
                    $Tx += (float) $coord[0];
724
                    $Ty -= (float) $coord[1];
725
                    $Tm[$x] = (string) $Tx;
726
                    $Tm[$y] = (string) $Ty;
727
                    break;
728
729
                /*
730
                 * a b c d e f Tm
731
                 * Set the text matrix, Tm, and the text line matrix, Tlm. The operands are
732
                 * all numbers, and the initial value for Tm and Tlm is the identity matrix
733
                 * [1 0 0 1 0 0]
734 1
                 */
735
                case 'Tm':
736 1
                    $Tm = explode(' ', $command['c']);
737 1
                    $Tx = (float) $Tm[$x];
738
                    $Ty = (float) $Tm[$y];
739
                    break;
740 1
741 1
                /*
742
                 * T*
743
                 * Move to the start of the next line. This operator has the same effect
744 1
                 * as the code:
745 1
                 * 0 Tl Td
746
                 * Where Tl is the current leading parameter in the text state.
747
                 */
748 1
                case 'T*':
749
                    $Ty -= $Tl;
750
                    $Tm[$y] = (string) $Ty;
751
                    break;
752 1
753 1
                /*
754
                 * string Tj
755 1
                 * Show a Text String
756 1
                 */
757 1
                case 'Tj':
758 1
                    $extractedData[] = [$Tm, $currentText];
759 1
                    break;
760 1
761 1
                /*
762
                 * string '
763
                 * Move to the next line and show a text string. This operator has the
764
                 * same effect as the code:
765
                 * T*
766
                 * string Tj
767
                 */
768 1
                case "'":
769
                    $Ty -= $Tl;
770
                    $Tm[$y] = (string) $Ty;
771
                    $extractedData[] = [$Tm, $currentText];
772
                    break;
773
774
                /*
775 1
                 * aw ac string "
776 1
                 * Move to the next line and show a text string, using aw as the word
777 1
                 * spacing and ac as the character spacing. This operator has the same
778 1
                 * effect as the code:
779 1
                 * aw Tw
780 1
                 * ac Tc
781
                 * string '
782
                 * Tw set the word spacing, Tw, to wordSpace.
783
                 * Tc Set the character spacing, Tc, to charsSpace.
784 1
                 */
785
                case '"':
786
                    $data = explode(' ', $currentText);
787
                    $Ty -= $Tl;
788
                    $Tm[$y] = (string) $Ty;
789
                    $extractedData[] = [$Tm, $data[2]]; //Verify
790
                    break;
791
792
                /*
793
                 * array TJ
794
                 * Show one or more text strings allow individual glyph positioning.
795
                 * Each lement of array con be a string or a number. If the element is
796
                 * a string, this operator shows the string. If it is a number, the
797
                 * operator adjust the text position by that amount; that is, it translates
798
                 * the text matrix, Tm. This amount is substracted form the current
799
                 * horizontal or vertical coordinate, depending on the writing mode.
800
                 * in the default coordinate system, a positive adjustment has the effect
801
                 * of moving the next glyph painted either to the left or down by the given
802
                 * amount.
803
                 */
804
                case 'TJ':
805
                    $extractedData[] = [$Tm, $currentText];
806
                    break;
807
                default:
808
            }
809
        }
810
        $this->dataTm = $extractedData;
811
812
        return $extractedData;
813
    }
814
815
    /**
816
     * Gets text data that are around the given coordinates (X,Y)
817
     *
818
     * If the text is in near the given coordinates (X,Y) (or the TM info),
819
     * the text is returned.  The extractedData return by getDataTm, could be use to see
820
     * where is the coordinates of a given text, using the TM info for it.
821
     *
822
     * @param float $x      The X value of the coordinate to search for. if null
823
     *                      just the Y value is considered (same Row)
824
     * @param float $y      The Y value of the coordinate to search for
825
     *                      just the X value is considered (same column)
826
     * @param float $xError The value less or more to consider an X to be "near"
827
     * @param float $yError The value less or more to consider an Y to be "near"
828
     *
829
     * @return array An array of text that are near the given coordinates. If no text
830
     *               "near" the x,y coordinate, an empty array is returned. If Both, x
831
     *               and y coordinates are null, null is returned.
832
     */
833
    public function getTextXY(float $x = null, float $y = null, float $xError = 0, float $yError = 0): array
834
    {
835
        if (!isset($this->dataTm) || !$this->dataTm) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->dataTm of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
836
            $this->getDataTm();
837
        }
838
839
        if (null !== $x) {
840
            $x = (float) $x;
841
        }
842
843
        if (null !== $y) {
844
            $y = (float) $y;
845
        }
846
847
        if (null === $x && null === $y) {
848
            return [];
849
        }
850
851
        $xError = (float) $xError;
852
        $yError = (float) $yError;
853
854
        $extractedData = [];
855
        foreach ($this->dataTm as $item) {
856
            $tm = $item[0];
857
            $xTm = (float) $tm[4];
858
            $yTm = (float) $tm[5];
859
            $text = $item[1];
860
            if (null === $y) {
861
                if (($xTm >= ($x - $xError)) &&
862
                    ($xTm <= ($x + $xError))) {
863
                    $extractedData[] = [$tm, $text];
864
                    continue;
865
                }
866
            }
867
            if (null === $x) {
868
                if (($yTm >= ($y - $yError)) &&
869
                    ($yTm <= ($y + $yError))) {
870
                    $extractedData[] = [$tm, $text];
871
                    continue;
872
                }
873
            }
874
            if (($xTm >= ($x - $xError)) &&
875
                ($xTm <= ($x + $xError)) &&
876
                ($yTm >= ($y - $yError)) &&
877
                ($yTm <= ($y + $yError))) {
878
                $extractedData[] = [$tm, $text];
879
                continue;
880
            }
881
        }
882
883
        return $extractedData;
884
    }
885
}
886