forked from christian-vigh-phpclasses/PdfToText
-
Notifications
You must be signed in to change notification settings - Fork 1
/
PdfToText.phpclass
executable file
·13103 lines (10380 loc) · 481 KB
/
PdfToText.phpclass
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
/**************************************************************************************************************
NAME
PdfToText.phpclass
DESCRIPTION
A class for extracting text from Pdf files.
Usage is very simple : just instantiate a PdfToText object, specifying an input filename, then use the
Text property to retrieve PDF textual contents :
$pdf = new PdfToText ( 'sample.pdf' ) ;
echo $pdf -> Text ; // or : echo ( string ) $pdf ;
Or :
$pdf = new PdfToText ( ) ;
// Modify any property here before loading the file ; for example :
// $pdf -> BlockSeparator = " " ;
$pdf -> Load ( 'sample.pdf' ) ;
echo $pdf -> Text ;
AUTHOR
Christian Vigh, 04/2016.
HISTORY
[Version : 1.6.7] [Date : 2017/05/31] [Author : CV]
. Added CID fonts
. Changed the way CID font maps are searched and handled
(...)
[Version : 1.0] [Date : 2016/04/16] [Author : CV]
Initial version.
**************************************************************************************************************/
/*==============================================================================================================
class PdfToTextException et al -
Implements an exception thrown when an error is encountered while decoding PDF files.
==============================================================================================================*/
// PdfToText exception -
// Base class for all other PdfToText exceptions.
class PdfToTextException extends Exception
{
public static $IsObject = false ;
} ;
// PdfToTextDecodingException -
// Thrown when unexpected data is encountered while analyzing PDF contents.
class PdfToTextDecodingException extends PdfToTextException
{
public function __construct ( $message, $object_id = false )
{
$text = "Pdf decoding error" ;
if ( $object_id !== false )
$text .= " (object #$object_id)" ;
$text .= " : $message" ;
parent::__construct ( $text ) ;
}
}
// PdfToTextDecryptionException -
// Thrown when something unexpected is encountered while processing encrypted data.
class PdfToTextDecryptionException extends PdfToTextException
{
public function __construct ( $message, $object_id = false )
{
$text = "Pdf decryption error" ;
if ( $object_id !== false )
$text .= " (object #$object_id)" ;
$text .= " : $message" ;
parent::__construct ( $text ) ;
}
}
// PdfToTextTimeoutException -
// Thrown when the PDFOPT_ENFORCE_EXECUTION_TIME or PDFOPT_ENFORCE_GLOBAL_EXECUTION_TIME option is set, and
// the script took longer than the allowed execution time limit.
class PdfToTextTimeoutException extends PdfToTextException
{
// Set to true if the reason why the max execution time was reached because of too many invocations of the Load() method
// Set to false if the max execution time was reached by simply processing one PDF file
public $GlobalTimeout ;
public function __construct ( $message, $global, $php_setting, $class_setting )
{
$text = "PdfToText max execution time reached " ;
if ( ! $global )
$text .= "for one single file " ;
$text .= "(php limit = {$php_setting}s, class limit = {$class_setting}s) : $message" ;
$this -> GlobalTimeout = $global ;
parent::__construct ( $text ) ;
}
}
// PdfToTextFormException -
// Thrown if the xml template passed to the GetFormData() method contains an error.
class PdfToTextFormException extends PdfToTextException
{
public function __construct ( $message )
{
$text = "Pdf form template error" ;
$text .= " : $message" ;
parent::__construct ( $text ) ;
}
}
// PdfToTextCaptureException -
// Thrown if the xml template passed to the SetCaptures() method contains an error.
class PdfToTextCaptureException extends PdfToTextException
{
public function __construct ( $message )
{
$text = "Pdf capture template error" ;
$text .= " : $message" ;
parent::__construct ( $text ) ;
}
}
/*==============================================================================================================
Custom error reporting functions.
==============================================================================================================*/
if ( ! function_exists ( 'warning' ) )
{
function warning ( $message )
{
trigger_error ( $message, E_USER_WARNING ) ;
}
}
if ( ! function_exists ( 'error' ) )
{
function error ( $message )
{
if ( is_string ( $message ) )
trigger_error ( $message, E_USER_ERROR ) ;
else if ( is_a ( $message, '\Exception' ) )
throw $message ;
}
}
/*==============================================================================================================
Backward-compatibility issues.
==============================================================================================================*/
// hex2bin -
// This function appeared only in version 5.4.0
if ( ! function_exists ( 'hex2bin' ) )
{
function hex2bin ( $hexstring )
{
$length = strlen ( $hexstring ) ;
$binstring = '' ;
$index = 0 ;
while ( $index < $length )
{
$byte = substr ( $hexstring, $index, 2 ) ;
$ch = pack ( 'H*', $byte ) ;
$binstring .= $ch ;
$index += 2 ;
}
return ( $binstring ) ;
}
}
/*==============================================================================================================
class PfObjectBase -
Base class for all PDF objects defined here.
==============================================================================================================*/
abstract class PdfObjectBase // extends Object
{
// Possible encoding types for streams inside objects ; "unknown" means that the object contains no stream
const PDF_UNKNOWN_ENCODING = 0 ; // No stream decoding type could be identified
const PDF_ASCIIHEX_ENCODING = 1 ; // AsciiHex encoding - not tested
const PDF_ASCII85_ENCODING = 2 ; // Ascii85 encoding - not tested
const PDF_FLATE_ENCODING = 3 ; // Flate/deflate encoding
const PDF_TEXT_ENCODING = 4 ; // Stream data appears in clear text - no decoding required
const PDF_LZW_ENCODING = 5 ; // Not implemented yet
const PDF_RLE_ENCODING = 6 ; // Runtime length encoding ; not implemented yet
const PDF_DCT_ENCODING = 7 ; // JPEG images
const PDF_CCITT_FAX_ENCODING = 8 ; // CCITT Fax encoding - not implemented yet
const PDF_JBIG2_ENCODING = 9 ; // JBIG2 filter encoding (black/white) - not implemented yet
const PDF_JPX_ENCODING = 10 ; // JPEG2000 encoding - not implemented yet
// Regular expression used for recognizing references to a font (this list is far from being exhaustive, as it seems
// that you can specify almost everything - however, trying to recognize everything would require to develop a complete
// parser)
protected static $FontSpecifiers = '
(/F \d+ (\.\d+)? ) |
(/R \d+) |
(/f-\d+-\d+) |
(/[CT]\d+_\d+) |
(/TT \d+) |
(/OPBaseFont \d+) |
(/OPSUFont \d+) |
(/[0-9a-zA-Z]) |
(/F\w+) |
(/[A-Za-z][A-Za-z0-9]* ( [\-+] [A-Za-z][A-Za-z0-9]* ))
' ;
// Maps alien Unicode characters such as special spaces, letters with ligatures to their ascii string equivalent
protected static $UnicodeToSimpleAscii = false ;
/*--------------------------------------------------------------------------------------------------------------
Constructor -
Performs static initializations such as the Unicode to Ascii table.
*-------------------------------------------------------------------------------------------------------------*/
public function __construct ( )
{
if ( self::$UnicodeToSimpleAscii === false )
{
$charset_file = dirname ( __FILE__ ) . "/Maps/unicode-to-ansi.map" ;
include ( $charset_file ) ;
self::$UnicodeToSimpleAscii = ( isset ( $unicode_to_ansi ) ) ? $unicode_to_ansi : array ( ) ;
}
// parent::__construct ( ) ;
}
/*--------------------------------------------------------------------------------------------------------------
NAME
CodePointToUtf8 - Encodes a Unicode codepoint to UTF8.
PROTOTYPE
$char = $this -> CodePointToUtf8 ( $code ) ;
DESCRIPTION
Encodes a Unicode codepoint to UTF8, trying to handle all possible cases.
PARAMETERS
$code (integer) -
Unicode code point to be translated.
RETURN VALUE
A string that contains the UTF8 bytes representing the Unicode code point.
*-------------------------------------------------------------------------------------------------------------*/
protected function CodePointToUtf8 ( $code )
{
if (gettype($code) == "string") return $code;
if ( $code )
{
$result = '' ;
while ( $code )
{
$word = ( $code & 0xFFFF ) ;
if ( ! isset ( self::$UnicodeToSimpleAscii [ $word ] ) )
{
$entity = "&#$word;" ;
$result .= mb_convert_encoding ( $entity, 'UTF-8', 'HTML-ENTITIES' ) . $result ;
}
else
$result .= self::$UnicodeToSimpleAscii [ $word ] ;
$code = ( integer ) ( $code / 0xFFFF ) ; // There is no unsigned right-shift operator in PHP...
}
return ( $result ) ;
}
// No translation is apparently possible : use a placeholder to signal this situation
else
{
if ( strpos ( PdfToText::$Utf8Placeholder, '%' ) === false )
{
return ( PdfToText::$Utf8Placeholder ) ;
}
else
return ( sprintf ( PdfToText::$Utf8Placeholder, $code ) ) ;
}
}
/*--------------------------------------------------------------------------------------------------------------
DecodeRawName -
Decodes a string that may contain constructs such as '#xy', where 'xy' are hex digits.
*-------------------------------------------------------------------------------------------------------------*/
public static function DecodeRawName ( $str )
{
return ( rawurldecode ( str_replace ( '#', '%', $str ) ) ) ;
}
/*--------------------------------------------------------------------------------------------------------------
NAME
GetEncodingType - Gets an object encoding type.
PROTOTYPE
$type = $this -> GetEncodingType ( $object_id, $object_data ) ;
DESCRIPTION
When an object is a stream, returns its encoding type.
PARAMETERS
$object_id (integer) -
PDF object number.
$object_data (string) -
Object contents.
RETURN VALUE
Returns one of the following values :
- PdfToText::PDF_ASCIIHEX_ENCODING :
Hexadecimal encoding of the binary values.
Decoding algorithm was taken from the unknown contributor and not tested so far, since I
couldn't find a PDF file with such an encoding type.
- PdfToText::PDF_ASCII85_ENCODING :
Obscure encoding format.
Decoding algorithm was taken from the unknown contributor and not tested so far, since I
couldn't find a PDF file with such an encoding type.
- PdfToText::PDF_FLATE_ENCODING :
gzip/deflate encoding.
- PdfToText::PDF_TEXT_ENCODING :
Stream data is unencoded (ie, it is pure ascii).
- PdfToText::PDF_UNKNOWN_ENCODING :
The object data does not specify any encoding at all. It can happen on objects that do not have
a "stream" part.
- PdfToText::PDF_DCT_ENCODING :
a lossy filter based on the JPEG standard.
The following constants are defined but not yet implemented ; an exception will be thrown if they are
encountered somewhere in the PDF file :
- PDF_LZW_ENCODING :
a filter based on LZW Compression; it can use one of two groups of predictor functions for more
compact LZW compression : Predictor 2 from the TIFF 6.0 specification and predictors (filters)
from the PNG specification
- PDF_RLE_ENCODING :
a simple compression method for streams with repetitive data using the run-length encoding
algorithm and the image-specific filters.
PDF_CCITT_FAX_ENCODING :
a lossless bi-level (black/white) filter based on the Group 3 or Group 4 CCITT (ITU-T) fax
compression standard defined in ITU-T T.4 and T.6.
PDF_JBIG2_ENCODING :
a lossy or lossless bi-level (black/white) filter based on the JBIG2 standard, introduced in
PDF 1.4.
PDF_JPX_ENCODING :
a lossy or lossless filter based on the JPEG 2000 standard, introduced in PDF 1.5.
*-------------------------------------------------------------------------------------------------------------*/
protected function GetEncodingType ( $object_id, $object_data )
{
$status = preg_match ( '# / (?P<encoding> (ASCIIHexDecode) | (AHx) | (ASCII85Decode) | (A85) | (FlateDecode) | (Fl) | (DCTDecode) | (DCT) | ' .
'(LZWDecode) | (LZW) | (RunLengthDecode) | (RL) | (CCITTFaxDecode) | (CCF) | (JBIG2Decode) | (JPXDecode) ) \b #imsx',
$object_data, $match ) ;
if ( ! $status )
return ( self::PDF_TEXT_ENCODING ) ;
switch ( strtolower ( $match [ 'encoding' ] ) )
{
case 'asciihexdecode' :
case 'ahx' : return ( self::PDF_ASCIIHEX_ENCODING ) ;
case 'ascii85decode' :
case 'a85' : return ( self::PDF_ASCII85_ENCODING ) ;
case 'flatedecode' :
case 'fl' : return ( self::PDF_FLATE_ENCODING ) ;
case 'dctdecode' :
case 'dct' : return ( self::PDF_DCT_ENCODING ) ;
case 'lzwdecode' :
case 'lzw' : return ( self::PDF_LZW_ENCODING ) ;
case 'ccittfaxdecode' :
case 'ccf' :
case 'runlengthdecode' :
case 'rl' :
case 'jbig2decode' :
case 'jpxdecode' :
if ( PdfToText::$DEBUG > 1 )
warning ( "Encoding type \"{$match [ 'encoding' ]}\" not yet implemented for pdf object #$object_id." ) ;
default : return ( self::PDF_UNKNOWN_ENCODING ) ;
}
}
/*--------------------------------------------------------------------------------------------------------------
NAME
GetObjectReferences - Gets object references from a specified construct.
PROTOTYPE
$status = $this -> GetObjectReferences ( $object_id, $object_data, $searched_string, &$object_ids ) ;
DESCRIPTION
Certain parameter specifications are followed by an object reference of the form :
x 0 R
but it can also be an array of references :
[x1 0 R x2 0 R ... xn 0 r]
Those kind of constructs can occur after parameters such as : /Pages, /Contents, /Kids...
This method extracts the object references found in such a construct.
PARAMETERS
$object_id (integer) -
Id of the object to be analyzed.
$object_data (string) -
Object contents.
$searched_string (string) -
String to be searched, that must be followed by an object or an array of object references.
This parameter can contain constructs used in regular expressions. Note however that the '#'
character must be escaped, since it is used as a delimiter in the regex that is applied on
object data.
$object_ids (array of integers) -
Returns on output the ids of the pdf object that have been found after the searched string.
RETURN VALUE
True if the searched string has been found and is followed by an object or array of object references,
false otherwise.
*-------------------------------------------------------------------------------------------------------------*/
protected function GetObjectReferences ( $object_id, $object_data, $searched_string, &$object_ids )
{
$status = true ;
$object_ids = array ( ) ;
if ( preg_match ( "#$searched_string \s* \\[ (?P<objects> [^\]]+ ) \\]#ix", $object_data, $match ) )
{
$object_list = $match [ 'objects' ] ;
if ( preg_match_all ( '/(?P<object> \d+) \s+ \d+ \s+ R/x', $object_list, $matches ) )
{
foreach ( $matches [ 'object' ] as $id )
$object_ids [] = ( integer ) $id ;
}
else
$status = false ;
}
else if ( preg_match ( "#$searched_string \s+ (?P<object> \d+) \s+ \d+ \s+ R#ix", $object_data, $match ) )
{
$object_ids [] = ( integer ) $match [ 'object' ] ;
}
else
$status = false ;
return ( $status ) ;
}
/*--------------------------------------------------------------------------------------------------------------
NAME
GetStringParameter - Retrieve a string flag value.
PROTOTYPE
$result = $this -> GetStringParameter ( $parameter, $object_data ) ;
DESCRIPTION
Retrieves the value of a string parameter ; for example :
/U (parameter value)
or :
/U <hexdigits>
PARAMETERS
$parameter (string) -
Parameter name.
$object_data (string) -
Object containing the parameter.
RETURN VALUE
The parameter value.
NOTES
description
*-------------------------------------------------------------------------------------------------------------*/
protected function GetStringParameter ( $parameter, $object_data )
{
if ( preg_match ( '#' . $parameter . ' \s* \( \s* (?P<value> [^)]+) \)#ix', $object_data, $match ) )
$result = $this -> ProcessEscapedString ( $match [ 'value' ] ) ;
else if ( preg_match ( '#' . $parameter . ' \s* \< \s* (?P<value> [^>]+) \>#ix', $object_data, $match ) )
{
$hexdigits = $match [ 'value' ] ;
$result = '' ;
for ( $i = 0, $count = strlen ( $hexdigits ) ; $i < $count ; $i += 2 )
$result .= chr ( hexdec ( substr ( $hexdigits, $i, 2 ) ) ) ;
}
else
$result = '' ;
return ( $result ) ;
}
/*--------------------------------------------------------------------------------------------------------------
GetUTCDate -
Reformats an Adobe UTC date to a format that can be understood by the strtotime() function.
Dates are specified in the following format :
D:20150521154000Z
D:20160707182114+02
with are both recognized by strtotime(). However, another format can be specified :
D:20160707182114+02'00'
which is not recognized by strtotime() so we have to get rid from the '00' part.
*-------------------------------------------------------------------------------------------------------------*/
protected function GetUTCDate ( $date )
{
if ( $date )
{
if ( ( $date [0] == 'D' || $date [0] == 'd' ) && $date [1] == ':' )
$date = substr ( $date, 2 ) ;
if ( ( $index = strpos ( $date, "'" ) ) !== false )
$date = substr ( $date, 0, $index ) ;
}
return ( $date ) ;
}
/*--------------------------------------------------------------------------------------------------------------
IsCharacterMap -
Checks if the specified text contents represent a character map definition or not.
*-------------------------------------------------------------------------------------------------------------*/
protected function IsCharacterMap ( $decoded_data )
{
// preg_match is faster than calling strpos several times
return ( preg_match ( '#(begincmap)|(beginbfrange)|(beginbfchar)|(/Differences)#ix', $decoded_data ) ) ;
}
/*--------------------------------------------------------------------------------------------------------------
IsFont -
Checks if the current object contents specify a font declaration.
*-------------------------------------------------------------------------------------------------------------*/
protected function IsFont ( $object_data )
{
return
(
stripos ( $object_data, '/BaseFont' ) !== false ||
( ! preg_match ( '#/Type \s* /FontDescriptor#ix', $object_data ) &&
preg_match ( '#/Type \s* /Font#ix', $object_data ) )
) ;
}
/*--------------------------------------------------------------------------------------------------------------
IsFormData -
Checks if the current object contents specify references to font data.
*-------------------------------------------------------------------------------------------------------------*/
protected function IsFormData ( $object_data )
{
return
(
preg_match ( '#\bR \s* \( \s* datasets \s* \)#imsx', $object_data )
) ;
}
/*--------------------------------------------------------------------------------------------------------------
IsFontMap -
Checks if the code contains things like :
<</F1 26 0 R/F2 22 0 R/F3 18 0 R>>
which maps font 1 (when specified with the /Fx instruction) to object 26, 2 to object 22 and 3 to
object 18, respectively, in the above example.
*-------------------------------------------------------------------------------------------------------------*/
protected function IsFontMap ( $object_data )
{
$object_data = self::UnescapeHexCharacters ( $object_data ) ;
if ( preg_match ( '#<< \s* ( ' . self::$FontSpecifiers . ' ) \s+ .* >>#imsx', $object_data ) )
return ( true ) ;
else
return ( false ) ;
}
/*--------------------------------------------------------------------------------------------------------------
IsImage -
Checks if the code contains things like :
/Subtype/Image
*-------------------------------------------------------------------------------------------------------------*/
protected function IsImage ( $object_data )
{
if ( preg_match ( '#/Subtype \s* /Image#msx', $object_data ) )
return ( true ) ;
else
return ( false ) ;
}
/*--------------------------------------------------------------------------------------------------------------
IsObjectStream -
Checks if the code contains an object stream (/Type/ObjStm)
/Subtype/Image
*-------------------------------------------------------------------------------------------------------------*/
protected function IsObjectStream ( $object_data )
{
if ( preg_match ( '#/Type \s* /ObjStm#isx', $object_data ) )
return ( true ) ;
else
return ( false ) ;
}
/*--------------------------------------------------------------------------------------------------------------
NAME
IsPageHeaderOrFooter - Check if the specified object contents denote a text stream.
PROTOTYPE
$status = $this -> IsPageHeaderOrFooter ( $stream_data ) ;
DESCRIPTION
Checks if the specified decoded stream contents denotes header or footer data.
PARAMETERS
$stream_data (string) -
Decoded stream contents.
*-------------------------------------------------------------------------------------------------------------*/
protected function IsPageHeaderOrFooter ( $stream_data )
{
if ( preg_match ( '#/Type \s* /Pagination \s* /Subtype \s*/((Header)|(Footer))#ix', $stream_data ) )
return ( true ) ;
else if ( preg_match ( '#/Attached \s* \[ .*? /((Top)|(Bottom)) [^]]#ix', $stream_data ) )
return ( true ) ;
else
return ( false ) ;
}
/*--------------------------------------------------------------------------------------------------------------
NAME
IsText - Check if the specified object contents denote a text stream.
PROTOTYPE
$status = $this -> IsText ( $object_data, $decoded_stream_data ) ;
DESCRIPTION
Checks if the specified object contents denote a text stream.
PARAMETERS
$object_data (string) -
Object data, ie the contents located between the "obj" and "endobj" keywords.
$decoded_stream_data (string) -
The flags specified in the object data are not sufficient to be sure that we have a block of
drawing instructions. We must also check for certain common instructions to be present.
RETURN VALUE
True if the specified contents MAY be text contents, false otherwise.
NOTES
I do not consider this method as bullet-proof. There may arise some cases where non-text blocks can be
mistakenly considered as text blocks, so it is subject to evolve in the future.
*-------------------------------------------------------------------------------------------------------------*/
protected function IsText ( $object_data, $decoded_stream_data )
{
if ( preg_match ( '# / (Filter) | (Length) #ix', $object_data ) &&
! preg_match ( '# / (Type) | (Subtype) | (Length1) #ix', $object_data ) )
{
if ( preg_match ( '/\\b(BT|Tf|Td|TJ|Tj|Tm|Do|cm)\\b/', $decoded_stream_data ) )
return ( true ) ;
}
else if ( preg_match ( '/\\b(BT|Tf|Td|TJ|Tj|Tm|Do|cm)\\b/', $decoded_stream_data ) )
return ( true ) ;
return ( false ) ;
}
/*--------------------------------------------------------------------------------------------------------------
NAME
PregStrReplace - Replace string(s) using regular expression(s)
PROTOTYPE
$result = PdfToText::PregStrReplace ( $pattern, $replacement, $subject, $limit = -1,
&$match_count = null )
DESCRIPTION
This function behaves like a mix of str_replace() and preg_replace() ; it allows to search for strings
using regular expressions, but the replacements are plain-text strings and no reference to a capture
specified in the regular expression will be interpreted.
This is useful when processing templates, which can contain constructs such as "\00" or "$", which are
interpreted by preg_replace() as references to captures.
The function has the same parameters as preg_replace().
RETURN VALUE
Returns the substituted text.
*-------------------------------------------------------------------------------------------------------------*/
public static function PregStrReplace ( $pattern, $replacement, $subject, $limit = -1, &$match_count = null )
{
// Make sure that $pattern and $replacement become arrays of the same size
if ( is_array ( $pattern ) )
{
if ( is_array ( $replacement ) )
{
if ( count ( $pattern ) !== count ( $replacement ) )
{
warning ( "The \$replacement parameter should have the same number of element as \$pattern." ) ;
return ( $subject ) ;
}
}
else
$replacement = array_fill ( $replacement, count ( $pattern ), $replacement ) ;
}
else
{
if ( is_array ( $replacement ) )
{
warning ( "Expected string for the \$replacement parameter." ) ;
return ( $subject ) ;
}
$pattern = array ( $pattern ) ;
$replacement = array ( $replacement ) ;
}
// Upper limit
if ( $limit < 1 )
$limit = PHP_INT_MAX ;
// Loop through each supplied pattern
$current_subject = $subject ;
$count = 0 ;
for ( $i = 0, $pattern_count = count ( $pattern ) ; $i < $pattern_count ; $i ++ )
{
$regex = $pattern [$i] ;
// Get all matches for this pattern
if ( preg_match_all ( $regex, $current_subject, $matches, PREG_OFFSET_CAPTURE ) )
{
$result = '' ; // Current output result
$last_offset = 0 ;
// Process each match
foreach ( $matches [0] as $match )
{
$offset = ( integer ) $match [1] ;
// Append data from the last seen offset up to the current one
if ( $last_offset < $offset )
$result .= substr ( $current_subject, $last_offset, $offset - $last_offset ) ;
// Append the replacement string for this match
$result .= $replacement [$i] ;
// Compute next offset in $current_subject
$last_offset = $offset + strlen ( $match [0] ) ;
// Limit checking
$count ++ ;
if ( $count > $limit )
break 2 ;
}
// Append the last part of the subject that has not been matched by anything
$result .= substr ( $current_subject, $last_offset ) ;
// The current subject becomes the string that has been built in the steps above
$current_subject = $result ;
}
}
/// All done, return
return ( $current_subject ) ;
}
/*--------------------------------------------------------------------------------------------------------------
NAME
ProcessEscapedCharacter - Interprets a character after a backslash in a string.
PROTOTYPE
$ch = $this -> ProcessEscapedCharacter ( $ch ) ;
DESCRIPTION
Interprets a character after a backslash in a string and returns the interpreted value.
PARAMETERS
$ch (char) -
Character to be escaped.
RETURN VALUE
The escaped character.
NOTES
This method does not process octal sequences.
*-------------------------------------------------------------------------------------------------------------*/
protected function ProcessEscapedCharacter ( $ch )
{
switch ( $ch )
{
// Normally, only a few characters should be escaped...
case '(' : $newchar = "(" ; break ;
case ')' : $newchar = ")" ; break ;
case '[' : $newchar = "[" ; break ;
case ']' : $newchar = "]" ; break ;
case '\\' : $newchar = "\\" ; break ;
case 'n' : $newchar = "\n" ; break ;
case 'r' : $newchar = "\r" ; break ;
case 'f' : $newchar = "\f" ; break ;
case 't' : $newchar = "\t" ; break ;
case 'b' : $newchar = chr ( 8 ) ; break ;
case 'v' : $newchar = chr ( 11 ) ; break ;
// ... but should we consider that it is a heresy to escape other characters ?
// For the moment, no.
default : $newchar = $ch ; break ;
}
return ( $newchar ) ;
}
/*--------------------------------------------------------------------------------------------------------------
NAME
ProcessEscapedString - Processes a string which can have escaped characters.
PROTOTYPE
$result = $this -> ProcessEscapedString ( $str, $process_octal_escapes = false ) ;
DESCRIPTION
Processes a string which may contain escape sequences.
PARAMETERS
$str (string) -
String to be processed.
$process_octal_escapes (boolean) -
When true, octal escape sequences such as \037 are processed.
RETURN VALUE
The processed input string.
*-------------------------------------------------------------------------------------------------------------*/
protected function ProcessEscapedString ( $str, $process_octal_escapes = false )
{
$length = strlen ( $str ) ;
$offset = 0 ;
$result = '' ;
$ord0 = ord ( '0' ) ;
while ( ( $backslash_index = strpos ( $str, '\\', $offset ) ) !== false )
{
if ( $backslash_index + 1 < $length )
{
$ch = $str [ ++ $backslash_index ] ;
if ( ! $process_octal_escapes )
{
$result .= substr ( $str, $offset, $backslash_index - $offset - 1 ) . $this -> ProcessEscapedCharacter ( $ch ) ;
$offset = $backslash_index + 1 ;
}
else if ( $ch < '0' || $ch > '7' )
{
$result .= substr ( $str, $offset, $backslash_index - $offset - 1 ) . $this -> ProcessEscapedCharacter ( $ch ) ;
$offset = $backslash_index + 1 ;
}
else
{
$result .= substr ( $str, $offset, $backslash_index - $offset - 1 ) ;
$ord = ord ( $ch ) - $ord0 ;
$count = 0 ;
$backslash_index ++ ;
while ( $backslash_index < $length && $count < 2 &&
$str [ $backslash_index ] >= '0' && $str [ $backslash_index ] <= '7' )
{
$ord = ( $ord * 8 ) + ( ord ( $str [ $backslash_index ++ ] ) - $ord0 ) ;
$count ++ ;
}
$result .= chr ( $ord ) ;
$offset = $backslash_index ;
}
}
else
break ;
}
$result .= substr ( $str, $offset ) ;
return ( $result ) ;
}
/*--------------------------------------------------------------------------------------------------------------
NAME
Unescape - Processes escape sequences from the specified string.
PROTOTYPE
$value = $this -> Unescape ( $text ) ;
DESCRIPTION
Processes escape sequences within the specified text. The recognized escape sequences are like the
C-language ones : \b (backspace), \f (form feed), \r (carriage return), \n (newline), \t (tab).
All other characters prefixed by "\" are returned as is.
PARAMETERS
$text (string) -
Text to be unescaped.
RETURN VALUE
Returns the unescaped value of $text.
*-------------------------------------------------------------------------------------------------------------*/
public static function Unescape ( $text )
{
$length = strlen ( $text ) ;
$result = '' ;
$ord0 = ord ( 0 ) ;