-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathPdfModule.java
4135 lines (3855 loc) · 162 KB
/
PdfModule.java
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
/**********************************************************************
* Jhove - JSTOR/Harvard Object Validation Environment
* Copyright 2003-2007 by JSTOR and the President and Fellows of Harvard College
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
**********************************************************************/
package edu.harvard.hul.ois.jhove.module;
import edu.harvard.hul.ois.jhove.*;
import edu.harvard.hul.ois.jhove.module.pdf.*;
import java.io.*;
import java.util.*;
import org.xml.sax.XMLReader;
import org.xml.sax.SAXException;
import javax.xml.parsers.SAXParserFactory;
import java.util.logging.Logger;
import java.util.zip.ZipException;
/**
* Module for identification and validation of PDF files.
*/
public class PdfModule
extends ModuleBase
{
/******************************************************************
* PRIVATE CLASS FIELDS.
******************************************************************/
private static final String NAME = "PDF-hul";
private static final String RELEASE = "1.7";
private static final int [] DATE = {2012, 8, 12};
private static final String [] FORMAT = {
"PDF", "Portable Document Format"
};
private static final String COVERAGE =
"PDF 1.0-1.6; PDF/X-1 (ISO 15930-1:2001), X-1a (ISO 15930-4:2003), " +
"X-2 (ISO 15930-5:2003), and X-3 (ISO 15930-6:2003); Tagged PDF; " +
"Linearized PDF; PDF/A (ISO/CD 19005-1)";
private static final String [] MIMETYPE = {"application/pdf"};
private static final String WELLFORMED = "A PDF file is " +
"well-formed if it meets the criteria defined in Chapter " +
"3 of the PDF Reference 1.6 (5th edition, 2004)";
private static final String VALIDITY = null;
private static final String REPINFO = null;
private static final String NOTE = "This module does *not* validate " +
"data within content streams (including operators) or encrypted data";
private static final String RIGHTS = "Copyright 2003-2007 by JSTOR and " +
"the President and Fellows of Harvard College. " +
"Released under the GNU Lesser General Public License.";
private static final String ENCRYPTED = "<May be encrypted>";
/** Logger for this class. */
protected Logger _logger;
/** Font type selectors. */
public final static int F_TYPE0 = 1,
F_TYPE1 = 2,
F_TT = 3,
F_TYPE3 = 4,
F_MM1 = 5,
F_CID0 = 6,
F_CID2 = 7;
/******************************************************************
* PRIVATE INSTANCE FIELDS.
******************************************************************/
/* The maximum number of fonts that will be reported before we just
* give up and report a stub to avoid running out of memory. */
protected int DEFAULT_MAX_FONTS = 1000;
/* Constants for trailer parsing */
private static final int EOFSCANSIZE = 1024;
private static final int XREFSCANSIZE = 128; // generous...
protected RandomAccessFile _raf;
protected Parser _parser;
protected String _version;
protected Property _metadata;
protected Property _xmpProp;
protected long _eof;
protected long _startxref;
protected long _prevxref;
protected int _numFreeObjects;
protected Property _idProperty;
protected int _objCount; // Count of objects in the cross-reference table
protected int _numObjects; // Value of the "Size" entry in the trailer dictionary
protected int _numTrailers; // Count of the number of trailers (updates)
protected Map _objects; // Map of the objects in the file
protected long[] _xref; // array of object offsets from xref table
protected int[] [] _xref2; // array of int[2], giving object stream and offset when _xref[i] < 0
protected boolean _xrefIsStream; // true if xref streams rather than tables are used
protected boolean _encrypted; // equivalent to _encryptDictRef != null
protected List<Property> _docCatalogList; // Info extracted from doc cat dict
protected List<Property> _encryptList; // Info from encryption dict
protected List<Property> _docInfoList; // info from doc info dict
protected List<Property> _extStreamsList; // List of external streams
protected List<Property> _imagesList; // List of image streams
protected List<Property> _filtersList; // List of filters
protected List<Property> _pagesList; // List of PageObjects
protected Map<Integer, PdfObject> _type0FontsMap; // Map of type 0 font dictionaries
protected Map<Integer, PdfObject> _type1FontsMap; // Map of type 1 font dictionaries
protected Map<Integer, PdfObject> _mmFontsMap; // Map of multi master font dictionaries
protected Map<Integer, PdfObject> _type3FontsMap; // Map of type 3 font dictionaries
protected Map<Integer, PdfObject> _trueTypeFontsMap; // Map of TrueType font dictionaries
protected Map<Integer, PdfObject> _cid0FontsMap; // Map of CIDFont/Type1 dictionaries
protected Map<Integer, PdfObject> _cid2FontsMap; // Map of CIDFont/TrueType dictionaries
protected Map<Integer, Integer> _pageSeqMap; // Map associating page object dicts with sequence numbers
protected PdfIndirectObj _docCatDictRef;
protected PdfIndirectObj _encryptDictRef;
protected PdfIndirectObj _docInfoDictRef;
protected PdfIndirectObj _pagesDictRef;
protected PdfDictionary _docCatDict;
protected PdfDictionary _docInfoDict;
protected PageTreeNode _docTreeRoot;
protected PdfDictionary _pageLabelDict;
protected PageLabelNode _pageLabelRoot;
protected NameTreeNode _embeddedFiles;
protected NameTreeNode _destNames;
protected PdfDictionary _encryptDict;
protected PdfDictionary _trailerDict;
protected PdfDictionary _viewPrefDict;
protected PdfDictionary _outlineDict;
protected PdfDictionary _destsDict;
protected boolean _showFonts;
protected boolean _showOutlines;
protected boolean _showAnnotations;
protected boolean _showPages;
protected boolean _actionsExist;
protected boolean _pdfACompliant; // flag checking PDF/A compliance
protected boolean _recursionWarned; // Check if warning has been issued on recursive outlines.
/* These three variables track whether a message has been posted
notifying the user of omitted information. */
protected boolean _skippedFontsReported;
protected boolean _skippedOutlinesReported;
protected boolean _skippedAnnotationsReported;
protected boolean _skippedPagesReported;
/** List of profile checkers */
protected List<PdfProfile> _profile;
/** Cached object stream. */
protected ObjectStream _cachedObjectStream;
/** Object number of cached object stream. */
protected int _cachedStreamIndex;
/** Map of visited nodes when walking through an outline. */
protected Set<Integer> _visitedOutlineNodes;
/** maximum number of fonts to report full information on. */
protected int maxFonts;
/** Number of fonts reported so far. */
protected int _nFonts;
/* These are the message texts to post in case of omitted
information. */
private final static String fontsSkippedString =
"Fonts exist, but are not displayed; to display " +
"remove param value of f from the config file";
private final static String outlinesSkippedString =
"Outlines exist, but are not displayed; to display " +
"remove param value of o from the config file";
private final static String annotationsSkippedString =
"Annotations exist, but are not displayed; to display " +
"remove param value of a from the config file";
private final static String pagesSkippedString =
"Page information is not displayed; to display " +
"remove param value of p from the config file";
/* Warning messages. */
protected final static String outlinesRecursiveString =
"Outlines contain recursive references.";
/* Name-to-value array pairs for NISO metadata */
private final static String[] compressionStrings =
{ "LZWDecode", /* "FlateDecode", */ "RunLengthDecode", "DCTDecode", "CCITTFaxDecode"};
private final static int[] compressionValues =
{ 5, /* 8, */ 32773, 6, 2};
/* The value of 2 (CCITTFaxDecode) is a placeholder; additional
* checking of the K parameter is needed to determine the real
* value if that's returned. */
private final static String [] colorSpaceStrings =
{ "Lab", "DeviceRGB", "DeviceCMYK", "DeviceGray", "Indexed" };
private final static int[] colorSpaceValues =
{ 8, 2, 5, 1, 3 };
/******************************************************************
* CLASS CONSTRUCTOR.
******************************************************************/
/**
* Creates an instance of the module and initializes identifying
* information.
*/
public PdfModule ()
{
super (NAME, RELEASE, DATE, FORMAT, COVERAGE, MIMETYPE, WELLFORMED,
VALIDITY, REPINFO, NOTE, RIGHTS, true);
_logger = Logger.getLogger ("edu.harvard.hul.ois.jhove.module");
_vendor = Agent.harvardInstance();
Document doc = new Document ("PDF Reference: Adobe Portable " +
"Document Format, Version 1.4",
DocumentType.BOOK);
Agent agent = Agent.newAdobeInstance();
doc.setPublisher (agent);
doc.setDate ("2001-12");
doc.setEdition ("3rd edition");
doc.setIdentifier (new Identifier ("0-201-75839-3",
IdentifierType.ISBN));
doc.setIdentifier (new Identifier ("http://partners.adobe.com/asn/" +
"acrobat/docs/File_Format_" +
"Specifications/PDFReference.pdf",
IdentifierType.URL));
_specification.add (doc);
doc = new Document ("PDF Reference: Adobe Portable " +
"Document Format, Version 1.5",
DocumentType.BOOK);
doc.setPublisher (agent);
doc.setDate ("2003");
doc.setEdition ("4th edition");
doc.setIdentifier (new Identifier (
"http://partners.adobe.com/public/developer/en/pdf/PDFReference15_v6.pdf",
IdentifierType.URL));
_specification.add (doc);
doc = new Document ("PDF Reference: Adobe Portable " +
"Document Format, Version 1.6",
DocumentType.BOOK);
doc.setPublisher (agent);
doc.setDate ("2004-11");
doc.setEdition ("5th edition");
doc.setIdentifier (new Identifier (
"http://partners.adobe.com/public/developer/en/pdf/PDFReference16.pdf",
IdentifierType.URL));
_specification.add (doc);
doc = new Document ("Graphic technology -- Prepress " +
"digital data exchange -- Use of PDF -- " +
"Part 1: Complete exchange using CMYK data " +
"(PDF/X-1 and PDF/X-1a)",
DocumentType.STANDARD);
Agent isoAgent = Agent.newIsoInstance();
doc.setPublisher (isoAgent);
doc.setDate ("2001-12-06");
doc.setIdentifier (new Identifier ("ISO 15930-1:2001",
IdentifierType.ISO));
_specification.add (doc);
doc = new Document ("Graphic technology -- Prepress " +
"digital data exchange -- Use of PDF -- " +
"Part 4: Complete exchange using CMYK and " +
"spot colour printing data using " +
"PDF 1.4 (PDF/X-1a)",
DocumentType.STANDARD);
doc.setPublisher (isoAgent);
doc.setDate ("2003-08-04");
doc.setIdentifier (new Identifier ("ISO 15930-4:2003",
IdentifierType.ISO));
_specification.add (doc);
doc = new Document ("Graphic technology -- Prepress " +
"digital data exchange -- Use of PDF -- " +
"Part 5: Partial exchange of printing data " +
"using PDF 1.4 (PDF/X-2)",
DocumentType.STANDARD);
doc.setPublisher (isoAgent);
doc.setDate ("2003-08-05");
doc.setIdentifier (new Identifier ("ISO 15930-5:2003",
IdentifierType.ISO));
_specification.add (doc);
doc = new Document ("Graphic technology -- Prepress " +
"digital data exchange -- Use of PDF -- " +
"Part 6: Complete exchange suitable for " +
"colour-managed workflows using " +
"PDF 1.4 (PDF/X-3)",
DocumentType.STANDARD);
doc.setPublisher (isoAgent);
doc.setDate ("2003-08-06");
doc.setIdentifier (new Identifier ("ISO 15930-6:2003",
IdentifierType.ISO));
_specification.add (doc);
_signature.add (new ExternalSignature (".pdf",
SignatureType.EXTENSION,
SignatureUseType.OPTIONAL));
_signature.add (new InternalSignature ("%PDF-1.",
SignatureType.MAGIC,
SignatureUseType.MANDATORY,
0));
doc = new Document ("Document management -- Electronic " +
"document file format for long-term " +
"preservation -- Part 1: Use of PDF (PDF/A)",
DocumentType.RFC);
doc.setPublisher (isoAgent);
doc.setDate ("2003-11-30");
doc.setIdentifier (new Identifier ("ISO/CD 19005-1",
IdentifierType.ISO));
doc.setIdentifier (new Identifier
("http://www.aiim.org/documents/standards/ISO_19005-1_(E).doc",
IdentifierType.URL));
_specification.add (doc);
_profile = new ArrayList<PdfProfile> (6);
_profile.add (new LinearizedProfile (this));
TaggedProfile tpr = new TaggedProfile (this);
_profile.add (tpr);
AProfile apr = new AProfile (this);
_profile.add (apr);
// Link AProfile to TaggedProfile to save checking
// the former twice.
apr.setTaggedProfile (tpr);
AProfileLevelA apra = new AProfileLevelA (this);
_profile.add (apra);
// AProfileLevelA depends on AProfile
apra.setAProfile(apr);
X1Profile x1 = new X1Profile (this);
_profile.add (x1);
X1aProfile x1a = new X1aProfile (this);
_profile.add (x1a);
// Linking the X1 profile to the X1a profile saves checking the former twice.
x1a.setX1Profile (x1);
_profile.add (new X2Profile (this));
_profile.add (new X3Profile (this));
_showAnnotations = false;
_showFonts = false;
_showOutlines = false;
_showPages = false;
maxFonts = DEFAULT_MAX_FONTS;
}
/******************************************************************
* PUBLIC INSTANCE METHODS.
*
* Parsing methods.
******************************************************************/
/** Reset parameter settings.
* Returns to a default state without any parameters.
*/
@Override
public void resetParams ()
throws Exception
{
_showAnnotations = true;
_showFonts = true;
_showOutlines = true;
_showPages = true;
maxFonts = DEFAULT_MAX_FONTS;
}
/**
* Per-action initialization. May be called multiple times.
*
* @param param The module parameter; under command-line Jhove, the -p parameter.
* If the parameter contains the indicated characters, then the
* specified information is omitted; otherwise, it is included.
* (This is the reverse of the behavior prior to beta 3.)
* These characters may be provided as separate parameters,
* or all in a single parameter.
* <ul>
* <li>a: annotations</li>
* <li>f: fonts</li>
* <li>o: outlines</li>
* <li>p: pages</li>
* </ul><br>
* The parameter is case-independent. A null parameter is
* equivalent to the empty string.
*/
@Override
public void param (String param)
{
if (param != null) {
param = param.toLowerCase ();
if (param.indexOf ('a') >= 0) {
_showAnnotations = false;
}
if (param.indexOf ('f') >= 0) {
_showFonts = false;
}
if (param.indexOf ('o') >= 0) {
_showOutlines = false;
}
if (param.indexOf ('p') >= 0) {
_showPages = false;
}
if (param.indexOf ('n') >= 0) {
// Parse out the number after the n, and use that to set
// the maximum number of fonts reported. Default is DEFAULT_MAX_FONTS.
int n = param.indexOf ('n');
StringBuffer b = new StringBuffer ();
for (int i = n + 1; i < param.length(); i++) {
char ch = param.charAt(i);
if (Character.isDigit (ch)) {
b.append(ch);
}
else {
break;
}
}
try {
int mx = Integer.parseInt (b.toString ());
if (mx > 0) {
maxFonts = mx;
}
}
catch (Exception e) {}
}
}
}
/**
* Parse a file and stores descriptive information. A RandomAccessFile
* must be used to represent the object.
*
* @param raf A PDF file
* @param info A clean RepInfo object, which will be modified to hold
* the descriptive information
*/
@Override
public final void parse (RandomAccessFile raf, RepInfo info)
throws IOException
{
initParse ();
info.setFormat (_format[0]);
info.setMimeType (_mimeType[0]);
info.setModule (this);
_objects = new HashMap ();
_raf = raf;
Tokenizer tok = new FileTokenizer (_raf);
_parser = new Parser (tok);
_parser.setObjectMap (_objects);
List<Property> metadataList = new ArrayList<Property> (11);
/* We construct a big whopping property,
which contains up to 11 subproperties */
_metadata = new Property ("PDFMetadata",
PropertyType.PROPERTY,
PropertyArity.LIST,
metadataList);
if (_raf.length () > 10000000000L) { // that's 10^10
_pdfACompliant = false; // doesn't meet size limit in Appendix C of PDF spec
}
if (!parseHeader (info)) {
return;
}
if (!findLastTrailer (info)) {
return;
}
/* Walk through the linked trailer and cross reference
sections. */
_prevxref = -1;
boolean lastTrailer = true;
while (_startxref > 0) {
// After the first (last) trailer, parse only for next "Prev" link
if (!parseTrailer (info, !lastTrailer)) {
return;
}
if (!readXRefInfo (info)) {
return;
}
++_numTrailers;
if (_xrefIsStream) {
/* If we have an xref stream, readXRefInfo dealt with all
* the streams in a single call. */
break;
}
// Beware infinite loop on badly broken file
if (_startxref == _prevxref) {
info.setMessage (new ErrorMessage
("Cross reference tables are broken",
_parser.getOffset ()));
info.setWellFormed (false);
return;
}
_startxref = _prevxref;
lastTrailer = false;
}
if (!readDocCatalogDict (info)) {
return;
}
if (!readEncryptDict (info)) {
return;
}
if (!readDocInfoDict (info)) {
return;
}
if (!readDocumentTree (info)) {
return;
}
if (!readPageLabelTree (info)) {
return;
}
if (!readXMPData (info)) {
return;
}
findExternalStreams (info);
if (!findFilters (info)) {
return;
}
findImages (info);
findFonts (info);
/* Object is well-formed PDF. */
/* We may have already done the checksums while converting a
temporary file. */
Checksummer ckSummer = null;
if (_je != null && _je.getChecksumFlag () &&
info.getChecksum ().isEmpty()) {
ckSummer = new Checksummer ();
calcRAChecksum (ckSummer, raf);
setChecksums (ckSummer, info);
}
info.setVersion (_version);
metadataList.add(new Property ("Objects",
PropertyType.INTEGER,
new Integer (_numObjects)));
metadataList.add (new Property ("FreeObjects",
PropertyType.INTEGER,
new Integer (_numFreeObjects)));
metadataList.add (new Property ("IncrementalUpdates",
PropertyType.INTEGER,
new Integer (_numTrailers)));
if (_docCatalogList != null) {
metadataList.add (new Property("DocumentCatalog",
PropertyType.PROPERTY,
PropertyArity.LIST,
_docCatalogList));
}
if (_encryptList != null) {
metadataList.add (new Property ("Encryption",
PropertyType.PROPERTY,
PropertyArity.LIST,
_encryptList));
}
if (_docInfoList != null) {
metadataList.add (new Property ("Info",
PropertyType.PROPERTY,
PropertyArity.LIST,
_docInfoList));
}
if (_idProperty != null) {
metadataList.add (_idProperty);
}
if (_extStreamsList != null && !_extStreamsList.isEmpty ()) {
metadataList.add (new Property ("ExternalStreams",
PropertyType.PROPERTY,
PropertyArity.LIST,
_extStreamsList));
}
if (_filtersList != null && !_filtersList.isEmpty ()) {
metadataList.add (new Property ("Filters",
PropertyType.PROPERTY,
PropertyArity.LIST,
_filtersList));
}
if (_imagesList != null && !_imagesList.isEmpty ()) {
metadataList.add (new Property ("Images",
PropertyType.PROPERTY,
PropertyArity.LIST,
_imagesList));
}
if (_showFonts || _verbosity == Module.MAXIMUM_VERBOSITY) {
try { addFontsProperty (metadataList); }
catch (NullPointerException e) {
info.setMessage(new ErrorMessage ("unexpected error in parsing font property", e.toString()));
}
}
if (_nFonts > maxFonts) {
info.setMessage(new InfoMessage ("Too many fonts to report; some fonts omitted.",
"Total fonts = " + _nFonts));
}
if (_xmpProp != null) {
metadataList.add (_xmpProp);
}
addPagesProperty (metadataList, info);
if (!doOutlineStuff (info)) {
return;
}
info.setProperty (_metadata);
/* Check for profile conformance. */
if (!_parser.getPDFACompliant ()) {
_pdfACompliant = false;
}
ListIterator<PdfProfile> pter = _profile.listIterator ();
if (info.getWellFormed() == RepInfo.TRUE) {
// Well-formedness is necessary to satisfy any profile.
while (pter.hasNext ()) {
PdfProfile prof = pter.next ();
if (prof.satisfiesProfile (_raf, _parser)) {
info.setProfile (prof.getText ());
}
}
}
}
/**
* Returns true if the module hasn't detected any violations
* of PDF/A compliance. This must return true, but is not
* sufficient by itself, to establish compliance. The
* <code>AProfile</code> profiler makes the final determination.
*/
public boolean mayBePDFACompliant ()
{
return _pdfACompliant;
}
/**
* Returns the document tree root.
*/
public PageTreeNode getDocumentTree ()
{
return _docTreeRoot;
}
/**
* Returns the document information dictionary.
*/
public PdfDictionary getDocInfo ()
{
return _docInfoDict;
}
/**
* Returns the encryption dictionary.
*/
public PdfDictionary getEncryptionDict ()
{
return _encryptDict;
}
/**
* Return true if Actions have been detected in the file.
*/
public boolean getActionsExist ()
{
return _actionsExist;
}
/**
* Initialize the module. This is called at the start
* of parse restore the module to its initial state.
*/
@Override
protected final void initParse ()
{
super.initParse ();
_xref = null;
_xref2 = null;
_version = "";
_objects = null;
_numFreeObjects = 0;
_objCount = 0;
_docInfoList = null;
_extStreamsList = null;
_docCatalogList = null;
_encryptList = null;
_imagesList = null;
_filtersList = null;
_pagesList = null;
_type0FontsMap = null;
_type1FontsMap = null;
_mmFontsMap = null;
_type3FontsMap = null;
_trueTypeFontsMap = null;
_cid0FontsMap = null;
_cid2FontsMap = null;
_docCatDictRef = null;
_encryptDictRef = null;
_docInfoDictRef = null;
_pagesDictRef = null;
_docCatDict = null;
_docInfoDict = null;
_docTreeRoot = null;
_pageLabelDict = null;
_encryptDict = null;
_trailerDict = null;
_viewPrefDict = null;
_outlineDict = null;
_destsDict = null;
_pageSeqMap = null;
_pageLabelRoot = null;
_embeddedFiles = null;
_destNames = null;
_skippedFontsReported = false;
_skippedOutlinesReported = false;
_skippedAnnotationsReported = false;
_skippedPagesReported = false;
_idProperty = null;
_actionsExist = false;
_numObjects = 0;
_numTrailers = -1;
_pdfACompliant = true; // assume compliance till disproven
_xmpProp = null;
_cachedStreamIndex = -1;
_nFonts = 0;
}
protected boolean parseHeader (RepInfo info) throws IOException
{
Token token = null;
String value = null;
final String nohdr = "No PDF header";
/* Parse file header. */
boolean foundSig = false;
for (;;) {
if (_parser.getOffset() > 1024) {
break;
}
try {
token = null;
token = _parser.getNext (1024L);
}
catch (IOException ee) {
break;
}
catch (Exception e) {} // fall through
if (token == null) {
break;
}
if (token instanceof Comment) {
value = ((Comment) token).getValue ();
if (value.indexOf ("PDF-1.") == 0) {
foundSig = true;
_version = value.substring (4, 7);
/* If we got this far, take note that the signature is OK. */
info.setSigMatch(_name);
break;
}
// The implementation notes (though not the spec)
// allow an alternative signature of %!PS-Adobe-N.n PDF-M.m
if (value.indexOf ("!PS-Adobe-") == 0) {
// But be careful: that much by itself is the standard
// PostScript signature.
int n = value.indexOf ("PDF-1.");
if (n >= 11) {
foundSig = true;
_version = value.substring (n + 4);
// However, this is not PDF-A compliant.
_pdfACompliant = false;
info.setSigMatch (_name);
break;
}
}
}
// If we don't find it right at the beginning, we aren't
// PDF/A compliant.
_pdfACompliant = false;
}
if (!foundSig) {
info.setWellFormed (false);
info.setMessage (new ErrorMessage (nohdr, 0L));
return false;
}
// Check for PDF/A conformance. The next item must be
// a comment with four characters, each greater than 127
try {
token = _parser.getNext ();
String cmt = ((Comment) token).getValue ();
char[] cmtArray = cmt.toCharArray ();
int ctlcnt = 0;
for (int i = 0; i < 4; i++) {
if (cmtArray[i] > 127) {
ctlcnt++;
}
}
if (ctlcnt < 4) {
_pdfACompliant = false;
}
}
catch (Exception e) {
// Most likely a ClassCastException on a non-comment
_pdfACompliant = false;
}
return true;
}
private long lastEOFOffset(RandomAccessFile raf) throws IOException {
long offset = 0;
long flen = 0;
byte[] buf = null;
// overkill to restore fileposition, but make this
// as side-effect free as possible
long savepos = raf.getFilePointer();
flen = raf.length();
buf = new byte[(int) Math.min(EOFSCANSIZE, flen)];
offset = flen - buf.length;
raf.seek(offset);
raf.read(buf);
raf.seek(savepos);
//OK:
// flen is the total length of the file
// offset is 1024 bytes from the end of file or 0 if file is shorter than 1024
// buf contains all bytes from offset to end of file
long eofpos = -1;
// Note the limits, selected so the index never is out of bounds
for (int i = buf.length-4; i >= 1; i--) {
if (buf[i] == '%') {
if ((buf[i-1] == '%') &&
(buf[i+1] == 'E') &&
(buf[i+2] == 'O') &&
(buf[i+3] == 'F')) {
eofpos = offset+i-1;
break;
}
}
}
// if (Tracing.T_MODULE) System.out.println(flen - eofpos);
return eofpos;
}
private long lastStartXrefOffset(RandomAccessFile raf, long eofOffset) throws IOException {
long offset = 0;
long flen = 0;
byte[] buf = null;
// overkill to restore fileposition, but make this
// as side-effect free as possible
long savepos = raf.getFilePointer();
flen = raf.length();
if (eofOffset <= 0) {
eofOffset = flen;
}
if (eofOffset >= flen) {
eofOffset = flen;
}
buf = new byte[(int) Math.min(XREFSCANSIZE, eofOffset)];
offset = eofOffset - buf.length;
raf.seek(offset);
raf.read(buf);
raf.seek(savepos);
//OK:
// flen is the total length of the file
// offset is 128 bytes from the end of file or 0 if file is shorter than 128
// buf contains all bytes from offset to end of file
long xrefpos = -1;
// Note the limits, selected so the index never is out of bounds
for (int i = buf.length-9; i >= 0; i--) {
if (buf[i] == 's') {
if ((buf[i+1] == 't') &&
(buf[i+2] == 'a') &&
(buf[i+3] == 'r') &&
(buf[i+4] == 't') &&
(buf[i+5] == 'x') &&
(buf[i+6] == 'r') &&
(buf[i+7] == 'e') &&
(buf[i+8] == 'f')) {
xrefpos = offset+i;
break;
}
}
}
// if (Tracing.T_MODULE) System.out.println(flen - xrefpos);
return xrefpos;
}
/** Locate the last trailer of the file */
protected boolean findLastTrailer (RepInfo info) throws IOException
{
/* Parse file trailer. Technically, this should be the last thing in
* the file, but we follow the Acrobat convention of looking in the
* last 1024 bytes. Since incremental updates may add multiple
* EOF comments, make sure that we use the last one in the file. */
Token token = null;
String value = null;
_eof = lastEOFOffset(_raf);
if (_eof < 0L) {
info.setWellFormed (false);
info.setMessage (new ErrorMessage ("No PDF trailer",
_raf.length ()));
return false;
}
// For PDF-A compliance, this must be at the very end.
/* Fix contributed by FCLA, 2007-05-30, to test for trailing data
* properly.
*
* if (_raf.length () - _eof > 6) {
*/
if (_raf.length () - _eof > 7) {
_pdfACompliant = false;
}
/* Retrieve the "startxref" keyword. */
long startxrefoffset = lastStartXrefOffset(_raf, _eof);
_startxref = -1L;
if (startxrefoffset >= 0) {
try {
_parser.seek (startxrefoffset); // points to the 'startxref' kw
//_parser.seek (_eof - 23); // should we allow more slop?
}
catch (PdfException e) {}
while (true) {
try {
token = _parser.getNext ();
}
catch (Exception e) {
// we're starting at an arbitrary point, so there
// can be parsing errors. Ignore them till we get
// back in sync.
continue;
}
if (token == null) {
break;
}
if (token instanceof Keyword) {
value = ((Keyword) token).getValue ();
if ("startxref".equals(value)) {
try {
token = _parser.getNext ();
}
catch (Exception e) {
break; // no excuses here
}
if (token != null && token instanceof Numeric) {
_startxref = ((Numeric) token).getLongValue ();
}
}
}
}
}
if (_startxref < 0L) {
info.setWellFormed (false);
info.setMessage (new ErrorMessage ("Missing startxref keyword " +
"or value", _parser.getOffset ()));
return false;
}
return true;
}
/* Parse a "trailer" (which is not necessarily the last