Completed
Pull Request — master (#324)
by Jeremy
11:37 queued 08:14
created

Page::getFont()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

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

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

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

302
            /** @scrutinizer ignore-call */ 
303
            $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...
303 5
            foreach ($sectionsText as $sectionText) {
304 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

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