Completed
Pull Request — master (#349)
by
unknown
04:33 queued 02:38
created

Page::getFont()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 22
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4.016

Importance

Changes 4
Bugs 1 Features 0
Metric Value
cc 4
eloc 10
c 4
b 1
f 0
nc 4
nop 1
dl 0
loc 22
ccs 9
cts 10
cp 0.9
crap 4.016
rs 9.9332
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 16
    public function getFonts()
59
    {
60 16
        if (null !== $this->fonts) {
61 14
            return $this->fonts;
62
        }
63
64 16
        $resources = $this->get('Resources');
65
66 16
        if (method_exists($resources, 'has') && $resources->has('Font')) {
67 15
            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 14
            if ($resources->get('Font') instanceof Header) {
72 9
                $fonts = $resources->get('Font')->getElements();
73
            } else {
74 7
                $fonts = $resources->get('Font')->getHeader()->getElements();
75
            }
76
77 14
            $table = [];
78
79 14
            foreach ($fonts as $id => $font) {
80 14
                if ($font instanceof Font) {
81 14
                    $table[$id] = $font;
82
83
                    // Store too on cleaned id value (only numeric)
84 14
                    $id = preg_replace('/[^0-9\.\-_]/', '', $id);
85 14
                    if ('' != $id) {
86 14
                        $table[$id] = $font;
87
                    }
88
                }
89
            }
90
91 14
            return $this->fonts = $table;
92
        }
93
94 4
        return [];
95
    }
96
97
    /**
98
     * @param string $id
99
     *
100
     * @return Font|null
101
     */
102 14
    public function getFont($id)
103
    {
104 14
        $fonts = $this->getFonts();
105
106 14
        if (isset($fonts[$id])) {
107 13
            return $fonts[$id];
108
        }
109
110
        // According to the PDF specs (https://www.adobe.com/content/dam/acom/en/devnet/pdf/pdfs/PDF32000_2008.pdf, page 238)
111
        // "The font resource name presented to the Tf operator is arbitrary, as are the names for all kinds of resources"
112
        // Instead, we search for the unfiltered name first and then do this cleaning as a fallback, so all tests still pass.
113
114 3
        if (isset($fonts[$id])) {
115
            return $fonts[$id];
116
        } else {
117 3
            $id = preg_replace('/[^0-9\.\-_]/', '', $id);
118 3
            if (isset($fonts[$id])) {
119 1
                return $fonts[$id];
120
            }
121
        }
122
123 2
        return null;
124
    }
125
126
    /**
127
     * Support for XObject
128
     *
129
     * @return PDFObject[]
130
     */
131 3
    public function getXObjects()
132
    {
133 3
        if (null !== $this->xobjects) {
134 2
            return $this->xobjects;
135
        }
136
137 3
        $resources = $this->get('Resources');
138
139 3
        if (method_exists($resources, 'has') && $resources->has('XObject')) {
140 3
            if ($resources->get('XObject') instanceof Header) {
141 3
                $xobjects = $resources->get('XObject')->getElements();
142
            } else {
143
                $xobjects = $resources->get('XObject')->getHeader()->getElements();
144
            }
145
146 3
            $table = [];
147
148 3
            foreach ($xobjects as $id => $xobject) {
149 3
                $table[$id] = $xobject;
150
151
                // Store too on cleaned id value (only numeric)
152 3
                $id = preg_replace('/[^0-9\.\-_]/', '', $id);
153 3
                if ('' != $id) {
154 3
                    $table[$id] = $xobject;
155
                }
156
            }
157
158 3
            return $this->xobjects = $table;
159
        }
160
161
        return [];
162
    }
163
164
    /**
165
     * @param string $id
166
     *
167
     * @return PDFObject|null
168
     */
169 3
    public function getXObject($id)
170
    {
171 3
        $xobjects = $this->getXObjects();
172
173 3
        if (isset($xobjects[$id])) {
174 3
            return $xobjects[$id];
175
        }
176
177
        return null;
178
        /*$id = preg_replace('/[^0-9\.\-_]/', '', $id);
179
180
        if (isset($xobjects[$id])) {
181
            return $xobjects[$id];
182
        } else {
183
            return null;
184
        }*/
185
    }
186
187
    /**
188
     * @param Page $page
189
     *
190
     * @return string
191
     */
192 8
    public function getText(self $page = null)
193
    {
194 8
        if ($contents = $this->get('Contents')) {
195 8
            if ($contents instanceof ElementMissing) {
196
                return '';
197 8
            } elseif ($contents instanceof ElementNull) {
198
                return '';
199 8
            } elseif ($contents instanceof PDFObject) {
0 ignored issues
show
introduced by
$contents is never a sub-type of Smalot\PdfParser\PDFObject.
Loading history...
200 6
                $elements = $contents->getHeader()->getElements();
201
202 6
                if (is_numeric(key($elements))) {
203
                    $new_content = '';
204
205
                    foreach ($elements as $element) {
206
                        if ($element instanceof ElementXRef) {
207
                            $new_content .= $element->getObject()->getContent();
208
                        } else {
209
                            $new_content .= $element->getContent();
210
                        }
211
                    }
212
213
                    $header = new Header([], $this->document);
214 6
                    $contents = new PDFObject($this->document, $header, $new_content);
215
                }
216 3
            } elseif ($contents instanceof ElementArray) {
217
                // Create a virtual global content.
218 3
                $new_content = '';
219
220 3
                foreach ($contents->getContent() as $content) {
221 3
                    $new_content .= $content->getContent()."\n";
222
                }
223
224 3
                $header = new Header([], $this->document);
225 3
                $contents = new PDFObject($this->document, $header, $new_content);
226
            }
227
228 8
            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

228
            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...
229
        }
230
231
        return '';
232
    }
233
234
    /**
235
     * @param Page $page
236
     *
237
     * @return array
238
     */
239 3
    public function getTextArray(self $page = null)
240
    {
241 3
        if ($contents = $this->get('Contents')) {
242 3
            if ($contents instanceof ElementMissing) {
243
                return [];
244 3
            } elseif ($contents instanceof ElementNull) {
245
                return [];
246 3
            } elseif ($contents instanceof PDFObject) {
0 ignored issues
show
introduced by
$contents is never a sub-type of Smalot\PdfParser\PDFObject.
Loading history...
247 3
                $elements = $contents->getHeader()->getElements();
248
249 3
                if (is_numeric(key($elements))) {
250
                    $new_content = '';
251
252
                    /** @var PDFObject $element */
253
                    foreach ($elements as $element) {
254
                        if ($element instanceof ElementXRef) {
255
                            $new_content .= $element->getObject()->getContent();
256
                        } else {
257
                            $new_content .= $element->getContent();
258
                        }
259
                    }
260
261
                    $header = new Header([], $this->document);
262 3
                    $contents = new PDFObject($this->document, $header, $new_content);
263
                }
264
            } elseif ($contents instanceof ElementArray) {
265
                // Create a virtual global content.
266
                $new_content = '';
267
268
                /** @var PDFObject $content */
269
                foreach ($contents->getContent() as $content) {
270
                    $new_content .= $content->getContent()."\n";
271
                }
272
273
                $header = new Header([], $this->document);
274
                $contents = new PDFObject($this->document, $header, $new_content);
275
            }
276
277 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

277
            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...
278
        }
279
280
        return [];
281
    }
282
283
    /**
284
     * Gets all the text data with its internal representation of the page.
285
     *
286
     * @return array An array with the data and the internal representation
287
     */
288 6
    public function extractRawData()
289
    {
290
        /*
291
         * Now you can get the complete content of the object with the text on it
292
         */
293 6
        $extractedData = [];
294 6
        $content = $this->get('Contents');
295 6
        $values = $content->getContent();
296 6
        if (isset($values) and \is_array($values)) {
297
            $text = '';
298
            foreach ($values as $section) {
299
                $text .= $section->getContent();
300
            }
301
            $sectionsText = $this->getSectionsText($text);
302
            foreach ($sectionsText as $sectionText) {
303
                $commandsText = $this->getCommandsText($sectionText);
304
                foreach ($commandsText as $command) {
305
                    $extractedData[] = $command;
306
                }
307
            }
308
        } else {
309 6
            $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

309
            /** @scrutinizer ignore-call */ 
310
            $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...
310 6
            foreach ($sectionsText as $sectionText) {
311 6
                $extractedData[] = ['t' => '', 'o' => 'BT', 'c' => ''];
312
313 6
                $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

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