Passed
Pull Request — master (#453)
by
unknown
02:41
created

Page::extractRawData()   B

Complexity

Conditions 8
Paths 5

Size

Total Lines 33
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 12.096

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 20
c 1
b 0
f 0
nc 5
nop 0
dl 0
loc 33
ccs 12
cts 20
cp 0.6
crap 12.096
rs 8.4444
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
            return $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

213
            return $contents->/** @scrutinizer ignore-call */ 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...
214
        }
215
216
        return '';
217
    }
218
219 4
    public function getTextArray(self $page = null): array
220
    {
221 4
        if ($contents = $this->get('Contents')) {
222 4
            if ($contents instanceof ElementMissing) {
223
                return [];
224 4
            } elseif ($contents instanceof ElementNull) {
225
                return [];
226 4
            } elseif ($contents instanceof PDFObject) {
0 ignored issues
show
introduced by
$contents is never a sub-type of Smalot\PdfParser\PDFObject.
Loading history...
227 4
                $elements = $contents->getHeader()->getElements();
228
229 4
                if (is_numeric(key($elements))) {
230
                    $new_content = '';
231
232
                    /** @var PDFObject $element */
233
                    foreach ($elements as $element) {
234
                        if ($element instanceof ElementXRef) {
235
                            $new_content .= $element->getObject()->getContent();
236
                        } else {
237
                            $new_content .= $element->getContent();
238
                        }
239
                    }
240
241
                    $header = new Header([], $this->document);
242
                    $contents = new PDFObject($this->document, $header, $new_content, $this->config);
243
                } else {
244
                    try {
245 4
                        $contents->getTextArray($this);
246 1
                    } catch (\Error $e) {
247 4
                        return $contents->getTextArray();
248
                    }
249
                }
250
            } elseif ($contents instanceof ElementArray) {
251
                // Create a virtual global content.
252
                $new_content = '';
253
254
                /** @var PDFObject $content */
255
                foreach ($contents->getContent() as $content) {
256
                    $new_content .= $content->getContent()."\n";
257
                }
258
259
                $header = new Header([], $this->document);
260
                $contents = new PDFObject($this->document, $header, $new_content, $this->config);
261
            }
262
263 3
            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

263
            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...
264
        }
265
266
        return [];
267
    }
268
269
    /**
270
     * Gets all the text data with its internal representation of the page.
271
     *
272
     * @return array An array with the data and the internal representation
273
     */
274 8
    public function extractRawData(): array
275
    {
276
        /*
277
         * Now you can get the complete content of the object with the text on it
278
         */
279 8
        $extractedData = [];
280 8
        $content = $this->get('Contents');
281 8
        $values = $content->getContent();
282 8
        if (isset($values) && \is_array($values)) {
283
            $text = '';
284
            foreach ($values as $section) {
285
                $text .= $section->getContent();
286
            }
287
            $sectionsText = $this->getSectionsText($text);
288
            foreach ($sectionsText as $sectionText) {
289
                $commandsText = $this->getCommandsText($sectionText);
290
                foreach ($commandsText as $command) {
291
                    $extractedData[] = $command;
292
                }
293
            }
294
        } else {
295 8
            $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

295
            /** @scrutinizer ignore-call */ 
296
            $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...
296 8
            foreach ($sectionsText as $sectionText) {
297 8
                $extractedData[] = ['t' => '', 'o' => 'BT', 'c' => ''];
298
299 8
                $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

299
                /** @scrutinizer ignore-call */ 
300
                $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...
300 8
                foreach ($commandsText as $command) {
301 8
                    $extractedData[] = $command;
302
                }
303
            }
304
        }
305
306 8
        return $extractedData;
307
    }
308
309
    /**
310
     * Gets all the decoded text data with it internal representation from a page.
311
     *
312
     * @param array $extractedRawData the extracted data return by extractRawData or
313
     *                                null if extractRawData should be called
314
     *
315
     * @return array An array with the data and the internal representation
316
     */
317 7
    public function extractDecodedRawData(array $extractedRawData = null): array
318
    {
319 7
        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...
320 7
            $extractedRawData = $this->extractRawData();
321
        }
322 7
        $currentFont = null; /** @var Font $currentFont */
323 7
        $clippedFont = null;
324 7
        foreach ($extractedRawData as &$command) {
325 7
            if ('Tj' == $command['o'] || 'TJ' == $command['o']) {
326 7
                $data = $command['c'];
327 7
                if (!\is_array($data)) {
328 5
                    $tmpText = '';
329 5
                    if (isset($currentFont)) {
330 5
                        $tmpText = $currentFont->decodeOctal($data);
331
                        //$tmpText = $currentFont->decodeHexadecimal($tmpText, false);
332
                    }
333 5
                    $tmpText = str_replace(
334 5
                            ['\\\\', '\(', '\)', '\n', '\r', '\t', '\ '],
335 5
                            ['\\', '(', ')', "\n", "\r", "\t", ' '],
336
                            $tmpText
337
                    );
338 5
                    $tmpText = utf8_encode($tmpText);
339 5
                    if (isset($currentFont)) {
340 5
                        $tmpText = $currentFont->decodeContent($tmpText);
341
                    }
342 5
                    $command['c'] = $tmpText;
343 5
                    continue;
344
                }
345 7
                $numText = \count($data);
346 7
                for ($i = 0; $i < $numText; ++$i) {
347 7
                    if (0 != ($i % 2)) {
348 5
                        continue;
349
                    }
350 7
                    $tmpText = $data[$i]['c'];
351 7
                    $decodedText = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $decodedText is dead and can be removed.
Loading history...
352 7
                    $decodedText = isset($currentFont) ? $currentFont->decodeOctal($tmpText) : $tmpText;
353 7
                    $decodedText = str_replace(
354 7
                            ['\\\\', '\(', '\)', '\n', '\r', '\t', '\ '],
355 7
                            ['\\', '(', ')', "\n", "\r", "\t", ' '],
356
                            $decodedText
357
                    );
358 7
                    $decodedText = utf8_encode($decodedText);
359 7
                    if (isset($currentFont)) {
360 5
                        $decodedText = $currentFont->decodeContent($decodedText);
361
                    }
362 7
                    $command['c'][$i]['c'] = $decodedText;
363 7
                    continue;
364
                }
365 7
            } elseif ('Tf' == $command['o'] || 'TF' == $command['o']) {
366 7
                $fontId = explode(' ', $command['c'])[0];
367 7
                $currentFont = $this->getFont($fontId);
368 7
                continue;
369 7
            } elseif ('Q' == $command['o']) {
370
                $currentFont = $clippedFont;
371 7
            } elseif ('q' == $command['o']) {
372
                $clippedFont = $currentFont;
373
            }
374
        }
375
376 7
        return $extractedRawData;
377
    }
378
379
    /**
380
     * Gets just the Text commands that are involved in text positions and
381
     * Text Matrix (Tm)
382
     *
383
     * It extract just the PDF commands that are involved with text positions, and
384
     * the Text Matrix (Tm). These are: BT, ET, TL, Td, TD, Tm, T*, Tj, ', ", and TJ
385
     *
386
     * @param array $extractedDecodedRawData The data extracted by extractDecodeRawData.
387
     *                                       If it is null, the method extractDecodeRawData is called.
388
     *
389
     * @return array An array with the text command of the page
390
     */
391 5
    public function getDataCommands(array $extractedDecodedRawData = null): array
392
    {
393 5
        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...
394 5
            $extractedDecodedRawData = $this->extractDecodedRawData();
395
        }
396 5
        $extractedData = [];
397 5
        foreach ($extractedDecodedRawData as $command) {
398 5
            switch ($command['o']) {
399
                /*
400
                 * BT
401
                 * Begin a text object, inicializind the Tm and Tlm to identity matrix
402
                 */
403 5
                case 'BT':
404 5
                    $extractedData[] = $command;
405 5
                    break;
406
407
                /*
408
                 * ET
409
                 * End a text object, discarding the text matrix
410
                 */
411 5
                case 'ET':
412
                    $extractedData[] = $command;
413
                    break;
414
415
                /*
416
                 * leading TL
417
                 * Set the text leading, Tl, to leading. Tl is used by the T*, ' and " operators.
418
                 * Initial value: 0
419
                 */
420 5
                case 'TL':
421 3
                    $extractedData[] = $command;
422 3
                    break;
423
424
                /*
425
                 * tx ty Td
426
                 * Move to the start of the next line, offset form the start of the
427
                 * current line by tx, ty.
428
                 */
429 5
                case 'Td':
430 5
                    $extractedData[] = $command;
431 5
                    break;
432
433
                /*
434
                 * tx ty TD
435
                 * Move to the start of the next line, offset form the start of the
436
                 * current line by tx, ty. As a side effect, this operator set the leading
437
                 * parameter in the text state. This operator has the same effect as the
438
                 * code:
439
                 * -ty TL
440
                 * tx ty Td
441
                 */
442 5
                case 'TD':
443
                    $extractedData[] = $command;
444
                    break;
445
446
                /*
447
                 * a b c d e f Tm
448
                 * Set the text matrix, Tm, and the text line matrix, Tlm. The operands are
449
                 * all numbers, and the initial value for Tm and Tlm is the identity matrix
450
                 * [1 0 0 1 0 0]
451
                 */
452 5
                case 'Tm':
453 3
                    $extractedData[] = $command;
454 3
                    break;
455
456
                /*
457
                 * T*
458
                 * Move to the start of the next line. This operator has the same effect
459
                 * as the code:
460
                 * 0 Tl Td
461
                 * Where Tl is the current leading parameter in the text state.
462
                 */
463 5
                case 'T*':
464 3
                    $extractedData[] = $command;
465 3
                    break;
466
467
                /*
468
                 * string Tj
469
                 * Show a Text String
470
                 */
471 5
                case 'Tj':
472 4
                    $extractedData[] = $command;
473 4
                    break;
474
475
                /*
476
                 * string '
477
                 * Move to the next line and show a text string. This operator has the
478
                 * same effect as the code:
479
                 * T*
480
                 * string Tj
481
                 */
482 5
                case "'":
483
                    $extractedData[] = $command;
484
                    break;
485
486
                /*
487
                 * aw ac string "
488
                 * Move to the next lkine and show a text string, using aw as the word
489
                 * spacing and ac as the character spacing. This operator has the same
490
                 * effect as the code:
491
                 * aw Tw
492
                 * ac Tc
493
                 * string '
494
                 * Tw set the word spacing, Tw, to wordSpace.
495
                 * Tc Set the character spacing, Tc, to charsSpace.
496
                 */
497 5
                case '"':
498
                    $extractedData[] = $command;
499
                    break;
500
501
                /*
502
                 * array TJ
503
                 * Show one or more text strings allow individual glyph positioning.
504
                 * Each lement of array con be a string or a number. If the element is
505
                 * a string, this operator shows the string. If it is a number, the
506
                 * operator adjust the text position by that amount; that is, it translates
507
                 * the text matrix, Tm. This amount is substracted form the current
508
                 * horizontal or vertical coordinate, depending on the writing mode.
509
                 * in the default coordinate system, a positive adjustment has the effect
510
                 * of moving the next glyph painted either to the left or down by the given
511
                 * amount.
512
                 */
513 5
                case 'TJ':
514 5
                    $extractedData[] = $command;
515 5
                    break;
516
                default:
517
            }
518
        }
519
520 5
        return $extractedData;
521
    }
522
523
    /**
524
     * Gets the Text Matrix of the text in the page
525
     *
526
     * Return an array where every item is an array where the first item is the
527
     * Text Matrix (Tm) and the second is a string with the text data.  The Text matrix
528
     * is an array of 6 numbers. The last 2 numbers are the coordinates X and Y of the
529
     * text. The first 4 numbers has to be with Scalation, Rotation and Skew of the text.
530
     *
531
     * @param array $dataCommands the data extracted by getDataCommands
532
     *                            if null getDataCommands is called
533
     *
534
     * @return array an array with the data of the page including the Tm information
535
     *               of any text in the page
536
     */
537 4
    public function getDataTm(array $dataCommands = null): array
538
    {
539 4
        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...
540 4
            $dataCommands = $this->getDataCommands();
541
        }
542
543
        /*
544
         * At the beginning of a text object Tm is the identity matrix
545
         */
546 4
        $defaultTm = ['1', '0', '0', '1', '0', '0'];
547
548
        /*
549
         *  Set the text leading used by T*, ' and " operators
550
         */
551 4
        $defaultTl = 0;
552
553
        /*
554
         * Setting where are the X and Y coordinates in the matrix (Tm)
555
         */
556 4
        $x = 4;
557 4
        $y = 5;
558 4
        $Tx = 0;
559 4
        $Ty = 0;
560
561 4
        $Tm = $defaultTm;
562 4
        $Tl = $defaultTl;
563
564 4
        $extractedTexts = $this->getTextArray();
565 4
        $extractedData = [];
566 4
        foreach ($dataCommands as $command) {
567 4
            $currentText = $extractedTexts[\count($extractedData)];
568 4
            switch ($command['o']) {
569
                /*
570
                 * BT
571
                 * Begin a text object, inicializind the Tm and Tlm to identity matrix
572
                 */
573 4
                case 'BT':
574 4
                    $Tm = $defaultTm;
575 4
                    $Tl = $defaultTl; //review this.
576 4
                    $Tx = 0;
577 4
                    $Ty = 0;
578 4
                    break;
579
580
                /*
581
                 * ET
582
                 * End a text object, discarding the text matrix
583
                 */
584 4
                case 'ET':
585
                    $Tm = $defaultTm;
586
                    $Tl = $defaultTl;  //review this
587
                    $Tx = 0;
588
                    $Ty = 0;
589
                    break;
590
591
                /*
592
                 * leading TL
593
                 * Set the text leading, Tl, to leading. Tl is used by the T*, ' and " operators.
594
                 * Initial value: 0
595
                 */
596 4
                case 'TL':
597 2
                    $Tl = (float) $command['c'];
598 2
                    break;
599
600
                /*
601
                 * tx ty Td
602
                 * Move to the start of the next line, offset form the start of the
603
                 * current line by tx, ty.
604
                 */
605 4
                case 'Td':
606 4
                    $coord = explode(' ', $command['c']);
607 4
                    $Tx += (float) $coord[0];
608 4
                    $Ty += (float) $coord[1];
609 4
                    $Tm[$x] = (string) $Tx;
610 4
                    $Tm[$y] = (string) $Ty;
611 4
                    break;
612
613
                /*
614
                 * tx ty TD
615
                 * Move to the start of the next line, offset form the start of the
616
                 * current line by tx, ty. As a side effect, this operator set the leading
617
                 * parameter in the text state. This operator has the same effect as the
618
                 * code:
619
                 * -ty TL
620
                 * tx ty Td
621
                 */
622 4
                case 'TD':
623
                    $coord = explode(' ', $command['c']);
624
                    $Tl = (float) $coord[1];
625
                    $Tx += (float) $coord[0];
626
                    $Ty -= (float) $coord[1];
627
                    $Tm[$x] = (string) $Tx;
628
                    $Tm[$y] = (string) $Ty;
629
                    break;
630
631
                /*
632
                 * a b c d e f Tm
633
                 * Set the text matrix, Tm, and the text line matrix, Tlm. The operands are
634
                 * all numbers, and the initial value for Tm and Tlm is the identity matrix
635
                 * [1 0 0 1 0 0]
636
                 */
637 4
                case 'Tm':
638 2
                    $Tm = explode(' ', $command['c']);
639 2
                    $Tx = (float) $Tm[$x];
640 2
                    $Ty = (float) $Tm[$y];
641 2
                    break;
642
643
                /*
644
                 * T*
645
                 * Move to the start of the next line. This operator has the same effect
646
                 * as the code:
647
                 * 0 Tl Td
648
                 * Where Tl is the current leading parameter in the text state.
649
                 */
650 4
                case 'T*':
651 2
                    $Ty -= $Tl;
652 2
                    $Tm[$y] = (string) $Ty;
653 2
                    break;
654
655
                /*
656
                 * string Tj
657
                 * Show a Text String
658
                 */
659 4
                case 'Tj':
660 3
                    $extractedData[] = [$Tm, $currentText];
661 3
                    break;
662
663
                /*
664
                 * string '
665
                 * Move to the next line and show a text string. This operator has the
666
                 * same effect as the code:
667
                 * T*
668
                 * string Tj
669
                 */
670 4
                case "'":
671
                    $Ty -= $Tl;
672
                    $Tm[$y] = (string) $Ty;
673
                    $extractedData[] = [$Tm, $currentText];
674
                    break;
675
676
                /*
677
                 * aw ac string "
678
                 * Move to the next line and show a text string, using aw as the word
679
                 * spacing and ac as the character spacing. This operator has the same
680
                 * effect as the code:
681
                 * aw Tw
682
                 * ac Tc
683
                 * string '
684
                 * Tw set the word spacing, Tw, to wordSpace.
685
                 * Tc Set the character spacing, Tc, to charsSpace.
686
                 */
687 4
                case '"':
688
                    $data = explode(' ', $currentText);
689
                    $Ty -= $Tl;
690
                    $Tm[$y] = (string) $Ty;
691
                    $extractedData[] = [$Tm, $data[2]]; //Verify
692
                    break;
693
694
                /*
695
                 * array TJ
696
                 * Show one or more text strings allow individual glyph positioning.
697
                 * Each lement of array con be a string or a number. If the element is
698
                 * a string, this operator shows the string. If it is a number, the
699
                 * operator adjust the text position by that amount; that is, it translates
700
                 * the text matrix, Tm. This amount is substracted form the current
701
                 * horizontal or vertical coordinate, depending on the writing mode.
702
                 * in the default coordinate system, a positive adjustment has the effect
703
                 * of moving the next glyph painted either to the left or down by the given
704
                 * amount.
705
                 */
706 4
                case 'TJ':
707 4
                    $extractedData[] = [$Tm, $currentText];
708 4
                    break;
709
                default:
710
            }
711
        }
712 4
        $this->dataTm = $extractedData;
713
714 4
        return $extractedData;
715
    }
716
717
    /**
718
     * Gets text data that are around the given coordinates (X,Y)
719
     *
720
     * If the text is in near the given coordinates (X,Y) (or the TM info),
721
     * the text is returned.  The extractedData return by getDataTm, could be use to see
722
     * where is the coordinates of a given text, using the TM info for it.
723
     *
724
     * @param float $x      The X value of the coordinate to search for. if null
725
     *                      just the Y value is considered (same Row)
726
     * @param float $y      The Y value of the coordinate to search for
727
     *                      just the X value is considered (same column)
728
     * @param float $xError The value less or more to consider an X to be "near"
729
     * @param float $yError The value less or more to consider an Y to be "near"
730
     *
731
     * @return array An array of text that are near the given coordinates. If no text
732
     *               "near" the x,y coordinate, an empty array is returned. If Both, x
733
     *               and y coordinates are null, null is returned.
734
     */
735 1
    public function getTextXY(float $x = null, float $y = null, float $xError = 0, float $yError = 0): array
736
    {
737 1
        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...
738 1
            $this->getDataTm();
739
        }
740
741 1
        if (null !== $x) {
742 1
            $x = (float) $x;
743
        }
744
745 1
        if (null !== $y) {
746 1
            $y = (float) $y;
747
        }
748
749 1
        if (null === $x && null === $y) {
750
            return [];
751
        }
752
753 1
        $xError = (float) $xError;
754 1
        $yError = (float) $yError;
755
756 1
        $extractedData = [];
757 1
        foreach ($this->dataTm as $item) {
758 1
            $tm = $item[0];
759 1
            $xTm = (float) $tm[4];
760 1
            $yTm = (float) $tm[5];
761 1
            $text = $item[1];
762 1
            if (null === $y) {
763
                if (($xTm >= ($x - $xError)) &&
764
                    ($xTm <= ($x + $xError))) {
765
                    $extractedData[] = [$tm, $text];
766
                    continue;
767
                }
768
            }
769 1
            if (null === $x) {
770
                if (($yTm >= ($y - $yError)) &&
771
                    ($yTm <= ($y + $yError))) {
772
                    $extractedData[] = [$tm, $text];
773
                    continue;
774
                }
775
            }
776 1
            if (($xTm >= ($x - $xError)) &&
777 1
                ($xTm <= ($x + $xError)) &&
778 1
                ($yTm >= ($y - $yError)) &&
779 1
                ($yTm <= ($y + $yError))) {
780 1
                $extractedData[] = [$tm, $text];
781 1
                continue;
782
            }
783
        }
784
785 1
        return $extractedData;
786
    }
787
}
788