-
Notifications
You must be signed in to change notification settings - Fork 540
/
Copy pathPDFObject.php
1192 lines (1037 loc) · 47 KB
/
PDFObject.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @file
* This file is part of the PdfParser library.
*
* @author Sébastien MALOT <sebastien@malot.fr>
*
* @date 2017-01-03
*
* @license LGPLv3
*
* @url <https://github.com/smalot/pdfparser>
*
* PdfParser is a pdf library written in PHP, extraction oriented.
* Copyright (C) 2017 - Sébastien MALOT <sebastien@malot.fr>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program.
* If not, see <http://www.pdfparser.org/sites/default/LICENSE.txt>.
*/
namespace Smalot\PdfParser;
use Smalot\PdfParser\XObject\Form;
use Smalot\PdfParser\XObject\Image;
/**
* Class PDFObject
*/
class PDFObject
{
public const TYPE = 't';
public const OPERATOR = 'o';
public const COMMAND = 'c';
/**
* The recursion stack.
*
* @var array
*/
public static $recursionStack = [];
/**
* @var Document|null
*/
protected $document;
/**
* @var Header
*/
protected $header;
/**
* @var string
*/
protected $content;
/**
* @var Config|null
*/
protected $config;
/**
* @var bool
*/
protected $addPositionWhitespace = false;
public function __construct(
Document $document,
?Header $header = null,
?string $content = null,
?Config $config = null
) {
$this->document = $document;
$this->header = $header ?? new Header();
$this->content = $content;
$this->config = $config;
}
public function init()
{
}
public function getDocument(): Document
{
return $this->document;
}
public function getHeader(): ?Header
{
return $this->header;
}
public function getConfig(): ?Config
{
return $this->config;
}
/**
* @return Element|PDFObject|Header
*/
public function get(string $name)
{
return $this->header->get($name);
}
public function has(string $name): bool
{
return $this->header->has($name);
}
public function getDetails(bool $deep = true): array
{
return $this->header->getDetails($deep);
}
public function getContent(): ?string
{
return $this->content;
}
/**
* Creates a duplicate of the document stream with
* strings and other items replaced by $char. Formerly
* getSectionsText() used this output to more easily gather offset
* values to extract text from the *actual* document stream.
*
* @deprecated function is no longer used and will be removed in a future release
*
* @internal
*/
public function cleanContent(string $content, string $char = 'X')
{
$char = $char[0];
$content = str_replace(['\\\\', '\\)', '\\('], $char.$char, $content);
// Remove image bloc with binary content
preg_match_all('/\s(BI\s.*?(\sID\s).*?(\sEI))\s/s', $content, $matches, \PREG_OFFSET_CAPTURE);
foreach ($matches[0] as $part) {
$content = substr_replace($content, str_repeat($char, \strlen($part[0])), $part[1], \strlen($part[0]));
}
// Clean content in square brackets [.....]
preg_match_all('/\[((\(.*?\)|[0-9\.\-\s]*)*)\]/s', $content, $matches, \PREG_OFFSET_CAPTURE);
foreach ($matches[1] as $part) {
$content = substr_replace($content, str_repeat($char, \strlen($part[0])), $part[1], \strlen($part[0]));
}
// Clean content in round brackets (.....)
preg_match_all('/\((.*?)\)/s', $content, $matches, \PREG_OFFSET_CAPTURE);
foreach ($matches[1] as $part) {
$content = substr_replace($content, str_repeat($char, \strlen($part[0])), $part[1], \strlen($part[0]));
}
// Clean structure
if ($parts = preg_split('/(<|>)/s', $content, -1, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE)) {
$content = '';
$level = 0;
foreach ($parts as $part) {
if ('<' == $part) {
++$level;
}
$content .= (0 == $level ? $part : str_repeat($char, \strlen($part)));
if ('>' == $part) {
--$level;
}
}
}
// Clean BDC and EMC markup
preg_match_all(
'/(\/[A-Za-z0-9\_]*\s*'.preg_quote($char).'*BDC)/s',
$content,
$matches,
\PREG_OFFSET_CAPTURE
);
foreach ($matches[1] as $part) {
$content = substr_replace($content, str_repeat($char, \strlen($part[0])), $part[1], \strlen($part[0]));
}
preg_match_all('/\s(EMC)\s/s', $content, $matches, \PREG_OFFSET_CAPTURE);
foreach ($matches[1] as $part) {
$content = substr_replace($content, str_repeat($char, \strlen($part[0])), $part[1], \strlen($part[0]));
}
return $content;
}
/**
* Takes a string of PDF document stream text and formats
* it into a multi-line string with one PDF command on each line,
* separated by \r\n. If the given string is null, or binary data
* is detected instead of a document stream then return an empty
* string.
*/
private function formatContent(?string $content): string
{
if (null === $content) {
return '';
}
// Outside of (String) and inline image content in PDF document
// streams, all text should conform to UTF-8. Test for binary
// content by deleting everything after the first open-
// parenthesis ( which indicates the beginning of a string, or
// the first ID command which indicates the beginning of binary
// inline image content. Then test what remains for valid
// UTF-8. If it's not UTF-8, return an empty string as this
// $content is most likely binary. Unfortunately, using
// mb_check_encoding(..., 'UTF-8') is not strict enough, so the
// following regexp, adapted from the W3, is used. See:
// https://www.w3.org/International/questions/qa-forms-utf-8.en
// We use preg_replace() instead of preg_match() to avoid "JIT
// stack limit exhausted" errors on larger files.
$utf8Filter = preg_replace('/(
[\x09\x0A\x0D\x20-\x7E] | # ASCII
[\xC2-\xDF][\x80-\xBF] | # non-overlong 2-byte
\xE0[\xA0-\xBF][\x80-\xBF] | # excluding overlongs
[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} | # straight 3-byte
\xED[\x80-\x9F][\x80-\xBF] | # excluding surrogates
\xF0[\x90-\xBF][\x80-\xBF]{2} | # planes 1-3
[\xF1-\xF3][\x80-\xBF]{3} | # planes 4-15
\xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)/xs', '', preg_replace('/(\(|ID\s).*$/s', '', $content));
if ('' !== $utf8Filter) {
return '';
}
// Find all inline image content and replace them so they aren't
// affected by the next steps
$pdfInlineImages = [];
$offsetBI = 0;
while (preg_match('/\sBI\s(\/.+?)\sID\s(.+?)\sEI(?=\s|$)/s', $content, $text, \PREG_OFFSET_CAPTURE, $offsetBI)) {
// Attempt to detemine if this instance of the 'BI' command
// actually occured within a (string) using the following
// steps:
// Step 1: Remove any escaped slashes and parentheses from
// the alleged image characteristics data
$para = str_replace(['\\\\', '\\(', '\\)'], '', $text[1][0]);
// Step 2: Remove all correctly ordered and balanced
// parentheses from (strings)
do {
$paraTest = $para;
$para = preg_replace('/\(([^()]*)\)/', '$1', $paraTest);
} while ($para != $paraTest);
$paraOpen = strpos($para, '(');
$paraClose = strpos($para, ')');
// Check: If the remaining text contains a close parenthesis
// ')' AND it occurs before any open parenthesis, then we
// are almost certain to be inside a (string)
if (0 < $paraClose && (false === $paraOpen || $paraClose < $paraOpen)) {
// Bump the search offset forward and match again
$offsetBI = (int) $text[1][1];
continue;
}
// Step 3: Double check that this is actually inline image
// data by parsing the alleged image characteristics as a
// dictionary
$dict = $this->parseDictionary('<<'.$text[1][0].'>>');
// Check if an image Width and Height are set in the dict
if ((isset($dict['W']) || isset($dict['Width']))
&& (isset($dict['H']) || isset($dict['Height']))) {
$id = uniqid('IMAGE_', true);
$pdfInlineImages[$id] = [
preg_replace(['/\r\n/', '/\r/', '/\n/'], ' ', $text[1][0]),
preg_replace(['/\r\n/', '/\r/', '/\n/'], '', $text[2][0]),
];
$content = preg_replace(
'/'.preg_quote($text[0][0], '/').'/',
'^^^'.$id.'^^^',
$content,
1
);
} else {
// If there was no valid dictionary, or a height and width
// weren't specified, then we don't know what this is, so
// just leave it alone; bump the search offset forward and
// match again
$offsetBI = (int) $text[1][1];
}
}
// Find all strings () and replace them so they aren't affected
// by the next steps
$pdfstrings = [];
$attempt = '(';
while (preg_match('/'.preg_quote($attempt, '/').'.*?\)/s', $content, $text)) {
// Remove all escaped slashes and parentheses from the target text
$para = str_replace(['\\\\', '\\(', '\\)'], '', $text[0]);
// PDF strings can contain unescaped parentheses as long as
// they're balanced, so check for balanced parentheses
$left = preg_match_all('/\(/', $para);
$right = preg_match_all('/\)/', $para);
if (')' == $para[-1] && $left == $right) {
// Replace the string with a unique placeholder
$id = uniqid('STRING_', true);
$pdfstrings[$id] = $text[0];
$content = preg_replace(
'/'.preg_quote($text[0], '/').'/',
'@@@'.$id.'@@@',
$content,
1
);
// Reset to search for the next string
$attempt = '(';
} else {
// We had unbalanced parentheses, so use the current
// match as a base to find a longer string
$attempt = $text[0];
}
}
// Remove all carriage returns and line-feeds from the document stream
$content = str_replace(["\r", "\n"], ' ', trim($content));
// Find all dictionary << >> commands and replace them so they
// aren't affected by the next steps
$dictstore = [];
while (preg_match('/(<<.*?>> *)(BDC|BMC|DP|MP)/s', $content, $dicttext)) {
$dictid = uniqid('DICT_', true);
$dictstore[$dictid] = $dicttext[1];
$content = preg_replace(
'/'.preg_quote($dicttext[0], '/').'/',
' ###'.$dictid.'###'.$dicttext[2],
$content,
1
);
}
// Normalize white-space in the document stream
$content = preg_replace('/\s{2,}/', ' ', $content);
// Find all valid PDF operators and add \r\n after each; this
// ensures there is just one command on every line
// Source: https://ia801001.us.archive.org/1/items/pdf1.7/pdf_reference_1-7.pdf - Appendix A
// Source: https://archive.org/download/pdf320002008/PDF32000_2008.pdf - Annex A
// Note: PDF Reference 1.7 lists 'I' and 'rI' as valid commands, while
// PDF 32000:2008 lists them as 'i' and 'ri' respectively. Both versions
// appear here in the list for completeness.
$operators = [
'b*', 'b', 'BDC', 'BMC', 'B*', 'BI', 'BT', 'BX', 'B', 'cm', 'cs', 'c', 'CS',
'd0', 'd1', 'd', 'Do', 'DP', 'EMC', 'EI', 'ET', 'EX', 'f*', 'f', 'F', 'gs',
'g', 'G', 'h', 'i', 'ID', 'I', 'j', 'J', 'k', 'K', 'l', 'm', 'MP', 'M', 'n',
'q', 'Q', 're', 'rg', 'ri', 'rI', 'RG', 'scn', 'sc', 'sh', 's', 'SCN', 'SC',
'S', 'T*', 'Tc', 'Td', 'TD', 'Tf', 'TJ', 'Tj', 'TL', 'Tm', 'Tr', 'Ts', 'Tw',
'Tz', 'v', 'w', 'W*', 'W', 'y', '\'', '"',
];
foreach ($operators as $operator) {
$content = preg_replace(
'/(?<!\w|\/)'.preg_quote($operator, '/').'(?![\w10\*])/',
$operator."\r\n",
$content
);
}
// Restore the original content of the dictionary << >> commands
$dictstore = array_reverse($dictstore, true);
foreach ($dictstore as $id => $dict) {
$content = str_replace('###'.$id.'###', $dict, $content);
}
// Restore the original string content
$pdfstrings = array_reverse($pdfstrings, true);
foreach ($pdfstrings as $id => $text) {
// Strings may contain escaped newlines, or literal newlines
// and we should clean these up before replacing the string
// back into the content stream; this ensures no strings are
// split between two lines (every command must be on one line)
$text = str_replace(
["\\\r\n", "\\\r", "\\\n", "\r", "\n"],
['', '', '', '\r', '\n'],
$text
);
$content = str_replace('@@@'.$id.'@@@', $text, $content);
}
// Restore the original content of any inline images
$pdfInlineImages = array_reverse($pdfInlineImages, true);
foreach ($pdfInlineImages as $id => $image) {
$content = str_replace(
'^^^'.$id.'^^^',
"\r\nBI\r\n".$image[0]." ID\r\n".$image[1]." EI\r\n",
$content
);
}
$content = trim(preg_replace(['/(\r\n){2,}/', '/\r\n +/'], "\r\n", $content));
return $content;
}
/**
* getSectionsText() now takes an entire, unformatted
* document stream as a string, cleans it, then filters out
* commands that aren't needed for text positioning/extraction. It
* returns an array of unprocessed PDF commands, one command per
* element.
*
* @internal
*/
public function getSectionsText(?string $content): array
{
$sections = [];
// A cleaned stream has one command on every line, so split the
// cleaned stream content on \r\n into an array
$textCleaned = preg_split(
'/(\r\n|\n|\r)/',
$this->formatContent($content),
-1,
\PREG_SPLIT_NO_EMPTY
);
$inTextBlock = false;
foreach ($textCleaned as $line) {
$line = trim($line);
// Skip empty lines
if ('' === $line) {
continue;
}
// If a 'BT' is encountered, set the $inTextBlock flag
if (preg_match('/BT$/', $line)) {
$inTextBlock = true;
$sections[] = $line;
// If an 'ET' is encountered, unset the $inTextBlock flag
} elseif ('ET' == $line) {
$inTextBlock = false;
$sections[] = $line;
} elseif ($inTextBlock) {
// If we are inside a BT ... ET text block, save all lines
$sections[] = trim($line);
} else {
// Otherwise, if we are outside of a text block, only
// save specific, necessary lines. Care should be taken
// to ensure a command being checked for *only* matches
// that command. For instance, a simple search for 'c'
// may also match the 'sc' command. See the command
// list in the formatContent() method above.
// Add more commands to save here as you find them in
// weird PDFs!
if ('q' == $line[-1] || 'Q' == $line[-1]) {
// Save and restore graphics state commands
$sections[] = $line;
} elseif (preg_match('/(?<!\w)B[DM]C$/', $line)) {
// Begin marked content sequence
$sections[] = $line;
} elseif (preg_match('/(?<!\w)[DM]P$/', $line)) {
// Marked content point
$sections[] = $line;
} elseif (preg_match('/(?<!\w)EMC$/', $line)) {
// End marked content sequence
$sections[] = $line;
} elseif (preg_match('/(?<!\w)cm$/', $line)) {
// Graphics position change commands
$sections[] = $line;
} elseif (preg_match('/(?<!\w)Tf$/', $line)) {
// Font change commands
$sections[] = $line;
} elseif (preg_match('/(?<!\w)Do$/', $line)) {
// Invoke named XObject command
$sections[] = $line;
}
}
}
return $sections;
}
private function getDefaultFont(?Page $page = null): Font
{
$fonts = [];
if (null !== $page) {
$fonts = $page->getFonts();
}
$firstFont = $this->document->getFirstFont();
if (null !== $firstFont) {
$fonts[] = $firstFont;
}
if (\count($fonts) > 0) {
return reset($fonts);
}
return new Font($this->document, null, null, $this->config);
}
/**
* Decode a '[]TJ' command and attempt to use alternate
* fonts if the current font results in output that contains
* Unicode control characters.
*
* @internal
*
* @param array<int,array<string,string|bool>> $command
*/
private function getTJUsingFontFallback(Font $font, array $command, ?Page $page = null, float $fontFactor = 4): string
{
$orig_text = $font->decodeText($command, $fontFactor);
$text = $orig_text;
// If we make this a Config option, we can add a check if it's
// enabled here.
if (null !== $page) {
$font_ids = array_keys($page->getFonts());
// If the decoded text contains UTF-8 control characters
// then the font page being used is probably the wrong one.
// Loop through the rest of the fonts to see if we can get
// a good decode. Allow x09 to x0d which are whitespace.
while (preg_match('/[\x00-\x08\x0e-\x1f\x7f]/u', $text) || false !== strpos(bin2hex($text), '00')) {
// If we're out of font IDs, then give up and use the
// original string
if (0 == \count($font_ids)) {
return $orig_text;
}
// Try the next font ID
$font = $page->getFont(array_shift($font_ids));
$text = $font->decodeText($command, $fontFactor);
}
}
return $text;
}
/**
* Expects a string that is a full PDF dictionary object,
* including the outer enclosing << >> angle brackets
*
* @internal
*
* @throws \Exception
*/
public function parseDictionary(string $dictionary): array
{
// Normalize whitespace
$dictionary = preg_replace(['/\r/', '/\n/', '/\s{2,}/'], ' ', trim($dictionary));
if ('<<' != substr($dictionary, 0, 2)) {
throw new \Exception('Not a valid dictionary object.');
}
$parsed = [];
$stack = [];
$currentName = '';
$arrayTypeNumeric = false;
// Remove outer layer of dictionary, and split on tokens
$split = preg_split(
'/(<<|>>|\[|\]|\/[^\s\/\[\]\(\)<>]*)/',
trim(preg_replace('/^<<|>>$/', '', $dictionary)),
-1,
\PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE
);
foreach ($split as $token) {
$token = trim($token);
switch ($token) {
case '':
break;
// Open numeric array
case '[':
$parsed[$currentName] = [];
$arrayTypeNumeric = true;
// Move up one level in the stack
$stack[\count($stack)] = &$parsed;
$parsed = &$parsed[$currentName];
$currentName = '';
break;
// Open hashed array
case '<<':
$parsed[$currentName] = [];
$arrayTypeNumeric = false;
// Move up one level in the stack
$stack[\count($stack)] = &$parsed;
$parsed = &$parsed[$currentName];
$currentName = '';
break;
// Close numeric array
case ']':
// Revert string type arrays back to a single element
if (\is_array($parsed) && 1 == \count($parsed)
&& isset($parsed[0]) && \is_string($parsed[0])
&& '' !== $parsed[0] && '/' != $parsed[0][0]) {
$parsed = '['.$parsed[0].']';
}
// Close hashed array
// no break
case '>>':
$arrayTypeNumeric = false;
// Move down one level in the stack
$parsed = &$stack[\count($stack) - 1];
unset($stack[\count($stack) - 1]);
break;
default:
// If value begins with a slash, then this is a name
// Add it to the appropriate array
if ('/' == substr($token, 0, 1)) {
$currentName = substr($token, 1);
if (true == $arrayTypeNumeric) {
$parsed[] = $currentName;
$currentName = '';
}
} elseif ('' != $currentName) {
if (false == $arrayTypeNumeric) {
$parsed[$currentName] = $token;
}
$currentName = '';
} elseif ('' == $currentName) {
$parsed[] = $token;
}
}
}
return $parsed;
}
/**
* Returns the text content of a PDF as a string. Attempts to add
* whitespace for spacing and line-breaks where appropriate.
*
* getText() leverages getTextArray() to get the content
* of the document, setting the addPositionWhitespace flag to true
* so whitespace is inserted in a logical way for reading by
* humans.
*/
public function getText(?Page $page = null): string
{
$this->addPositionWhitespace = true;
$result = $this->getTextArray($page);
$this->addPositionWhitespace = false;
return implode('', $result).' ';
}
/**
* Returns the text content of a PDF as an array of strings. No
* extra whitespace is inserted besides what is actually encoded in
* the PDF text.
*
* @throws \Exception
*/
public function getTextArray(?Page $page = null): array
{
$result = [];
$text = [];
$marked_stack = [];
$last_written_position = false;
$sections = $this->getSectionsText($this->content);
$current_font = $this->getDefaultFont($page);
$current_font_size = 1;
$current_text_leading = 0;
$current_position = ['x' => false, 'y' => false];
$current_position_tm = [
'a' => 1, 'b' => 0, 'c' => 0,
'i' => 0, 'j' => 1, 'k' => 0,
'x' => 0, 'y' => 0, 'z' => 1,
];
$current_position_td = ['x' => 0, 'y' => 0];
$current_position_cm = [
'a' => 1, 'b' => 0, 'c' => 0,
'i' => 0, 'j' => 1, 'k' => 0,
'x' => 0, 'y' => 0, 'z' => 1,
];
$clipped_font = [];
$clipped_position_cm = [];
self::$recursionStack[] = $this->getUniqueId();
foreach ($sections as $section) {
$commands = $this->getCommandsText($section);
foreach ($commands as $command) {
switch ($command[self::OPERATOR]) {
// Begin text object
case 'BT':
// Reset text positioning matrices
$current_position_tm = [
'a' => 1, 'b' => 0, 'c' => 0,
'i' => 0, 'j' => 1, 'k' => 0,
'x' => 0, 'y' => 0, 'z' => 1,
];
$current_position_td = ['x' => 0, 'y' => 0];
$current_text_leading = 0;
break;
// Begin marked content sequence with property list
case 'BDC':
if (preg_match('/(<<.*>>)$/', $command[self::COMMAND], $match)) {
$dict = $this->parseDictionary($match[1]);
// Check for ActualText block
if (isset($dict['ActualText']) && \is_string($dict['ActualText']) && '' !== $dict['ActualText']) {
if ('[' == $dict['ActualText'][0]) {
// Simulate a 'TJ' command on the stack
$marked_stack[] = [
'ActualText' => $this->getCommandsText($dict['ActualText'].'TJ')[0],
];
} elseif ('<' == $dict['ActualText'][0] || '(' == $dict['ActualText'][0]) {
// Simulate a 'Tj' command on the stack
$marked_stack[] = [
'ActualText' => $this->getCommandsText($dict['ActualText'].'Tj')[0],
];
}
}
}
break;
// Begin marked content sequence
case 'BMC':
if ('ReversedChars' == $command[self::COMMAND]) {
// Upon encountering a ReversedChars command,
// add the characters we've built up so far to
// the result array
$result = array_merge($result, $text);
// Start a fresh $text array that will contain
// reversed characters
$text = [];
// Add the reversed text flag to the stack
$marked_stack[] = ['ReversedChars' => true];
}
break;
// set graphics position matrix
case 'cm':
$args = preg_split('/\s+/s', $command[self::COMMAND]);
$current_position_cm = [
'a' => (float) $args[0], 'b' => (float) $args[1], 'c' => 0,
'i' => (float) $args[2], 'j' => (float) $args[3], 'k' => 0,
'x' => (float) $args[4], 'y' => (float) $args[5], 'z' => 1,
];
break;
case 'Do':
if (null !== $page) {
$args = preg_split('/\s/s', $command[self::COMMAND]);
$id = trim(array_pop($args), '/ ');
$xobject = $page->getXObject($id);
// @todo $xobject could be a ElementXRef object, which would then throw an error
if (\is_object($xobject) && $xobject instanceof self && !\in_array($xobject->getUniqueId(), self::$recursionStack, true)) {
// Not a circular reference.
$text[] = $xobject->getText($page);
}
}
break;
// Marked content point with (DP) & without (MP) property list
case 'DP':
case 'MP':
break;
// End text object
case 'ET':
break;
// Store current selected font and graphics matrix
case 'q':
$clipped_font[] = [$current_font, $current_font_size];
$clipped_position_cm[] = $current_position_cm;
break;
// Restore previous selected font and graphics matrix
case 'Q':
list($current_font, $current_font_size) = array_pop($clipped_font);
$current_position_cm = array_pop($clipped_position_cm);
break;
// End marked content sequence
case 'EMC':
$data = false;
if (\count($marked_stack)) {
$marked = array_pop($marked_stack);
$action = key($marked);
$data = $marked[$action];
switch ($action) {
// If we are in ReversedChars mode...
case 'ReversedChars':
// Reverse the characters we've built up so far
foreach ($text as $key => $t) {
$text[$key] = implode('', array_reverse(
mb_str_split($t, 1, mb_internal_encoding())
));
}
// Add these characters to the result array
$result = array_merge($result, $text);
// Start a fresh $text array that will contain
// non-reversed characters
$text = [];
break;
case 'ActualText':
// Use the content of the ActualText as a command
$command = $data;
break;
}
}
// If this EMC command has been transformed into a 'Tj'
// or 'TJ' command because of being ActualText, then bypass
// the break to proceed to the writing section below.
if ('Tj' != $command[self::OPERATOR] && 'TJ' != $command[self::OPERATOR]) {
break;
}
// no break
case "'":
case '"':
if ("'" == $command[self::OPERATOR] || '"' == $command[self::OPERATOR]) {
// Move to next line and write text
$current_position['x'] = 0;
$current_position_td['x'] = 0;
$current_position_td['y'] += $current_text_leading;
}
// no break
case 'Tj':
$command[self::COMMAND] = [$command];
// no break
case 'TJ':
// Check the marked content stack for flags
$actual_text = false;
$reverse_text = false;
foreach ($marked_stack as $marked) {
if (isset($marked['ActualText'])) {
$actual_text = true;
}
if (isset($marked['ReversedChars'])) {
$reverse_text = true;
}
}
// Account for text position ONLY just before we write text
if (false === $actual_text && \is_array($last_written_position)) {
// If $last_written_position is an array, that
// means we have stored text position coordinates
// for placing an ActualText
$currentX = $last_written_position[0];
$currentY = $last_written_position[1];
$last_written_position = false;
} else {
$currentX = $current_position_cm['x'] + $current_position_tm['x'] + $current_position_td['x'];
$currentY = $current_position_cm['y'] + $current_position_tm['y'] + $current_position_td['y'];
}
$whiteSpace = '';
$factorX = -$current_font_size * $current_position_tm['a'] - $current_font_size * $current_position_tm['i'];
$factorY = $current_font_size * $current_position_tm['b'] + $current_font_size * $current_position_tm['j'];
if (true === $this->addPositionWhitespace && false !== $current_position['x']) {
$curY = $currentY - $current_position['y'];
if (abs($curY) >= abs($factorY) / 4) {
$whiteSpace = "\n";
} else {
if (true === $reverse_text) {
$curX = $current_position['x'] - $currentX;
} else {
$curX = $currentX - $current_position['x'];
}
// In abs($factorX * 7) below, the 7 is chosen arbitrarily
// as the number of apparent "spaces" in a document we
// would need before considering them a "tab". In the
// future, we might offer this value to users as a config
// option.
if ($curX >= abs($factorX * 7)) {
$whiteSpace = "\t";
} elseif ($curX >= abs($factorX * 2)) {
$whiteSpace = ' ';
}
}
}
$newtext = $this->getTJUsingFontFallback(
$current_font,
$command[self::COMMAND],
$page,
$factorX
);
// If there is no ActualText pending then write
if (false === $actual_text) {
$newtext = str_replace(["\r", "\n"], '', $newtext);
if (false !== $reverse_text) {
// If we are in ReversedChars mode, add the whitespace last
$text[] = preg_replace('/ $/', ' ', $newtext.$whiteSpace);
} else {
// Otherwise add the whitespace first
if (' ' === $whiteSpace && isset($text[\count($text) - 1])) {
$text[\count($text) - 1] = preg_replace('/ $/', '', $text[\count($text) - 1]);
}
$text[] = preg_replace('/^[ \t]{2}/', ' ', $whiteSpace.$newtext);
}
// Record the position of this inserted text for comparison
// with the next text block.
// Provide a 'fudge' factor guess on how wide this text block
// is based on the number of characters. This helps limit the
// number of tabs inserted, but isn't perfect.
$factor = $factorX / 2;
$current_position = [
'x' => $currentX - mb_strlen($newtext) * $factor,
'y' => $currentY,
];
} elseif (false === $last_written_position) {
// If there is an ActualText in the pipeline
// store the position this undisplayed text
// *would* have been written to, so the
// ActualText is displayed in the right spot
$last_written_position = [$currentX, $currentY];
$current_position['x'] = $currentX;
}
break;
// move to start of next line
case 'T*':
$current_position['x'] = 0;
$current_position_td['x'] = 0;
$current_position_td['y'] += $current_text_leading;
break;
// set character spacing
case 'Tc':
break;
// move text current point and set leading
case 'Td':
case 'TD':
// move text current point
$args = preg_split('/\s+/s', $command[self::COMMAND]);
$y = (float) array_pop($args);
$x = (float) array_pop($args);
if ('TD' == $command[self::OPERATOR]) {
$current_text_leading = -$y * $current_position_tm['b'] - $y * $current_position_tm['j'];
}
$current_position_td = [
'x' => $current_position_td['x'] + $x * $current_position_tm['a'] + $x * $current_position_tm['i'],
'y' => $current_position_td['y'] + $y * $current_position_tm['b'] + $y * $current_position_tm['j'],
];
break;
case 'Tf':
$args = preg_split('/\s/s', $command[self::COMMAND]);
$size = (float) array_pop($args);
$id = trim(array_pop($args), '/');
if (null !== $page) {
$new_font = $page->getFont($id);
// If an invalid font ID is given, do not update the font.
// This should theoretically never happen, as the PDF spec states for the Tf operator:
// "The specified font value shall match a resource name in the Font entry of the default resource dictionary"
// (https://www.adobe.com/content/dam/acom/en/devnet/pdf/pdfs/PDF32000_2008.pdf, page 435)
// But we want to make sure that malformed PDFs do not simply crash.
if (null !== $new_font) {
$current_font = $new_font;