Utils.java
43.1 KB
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
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* com.adobe.aemfd.docmanager.Document
* com.adobe.aemfd.docmanager.TempFileManager
* com.adobe.aemfd.pdfdocmanager.SharedPdfDocument
* com.adobe.aemfd.pdfdocmanager.SharedPdfDocumentContext
* com.adobe.forms.option.LCFormsOptions
* com.adobe.internal.io.ByteArrayByteReader
* com.adobe.internal.io.ByteReader
* com.adobe.internal.pdftoolkit.core.cos.CosArray
* com.adobe.internal.pdftoolkit.core.cos.CosCloneMgr
* com.adobe.internal.pdftoolkit.core.cos.CosDictionary
* com.adobe.internal.pdftoolkit.core.cos.CosDocument
* com.adobe.internal.pdftoolkit.core.cos.CosObject
* com.adobe.internal.pdftoolkit.core.cos.CosStream
* com.adobe.internal.pdftoolkit.core.cos.CosString
* com.adobe.internal.pdftoolkit.core.exceptions.PDFException
* com.adobe.internal.pdftoolkit.core.exceptions.PDFIOException
* com.adobe.internal.pdftoolkit.core.exceptions.PDFInvalidDocumentException
* com.adobe.internal.pdftoolkit.core.exceptions.PDFInvalidXMLException
* com.adobe.internal.pdftoolkit.core.exceptions.PDFSecurityException
* com.adobe.internal.pdftoolkit.core.fontset.PDFFontSet
* com.adobe.internal.pdftoolkit.core.types.ASName
* com.adobe.internal.pdftoolkit.core.types.ASString
* com.adobe.internal.pdftoolkit.pdf.digsig.PDFDocMDPPermissions
* com.adobe.internal.pdftoolkit.pdf.digsig.PDFSignature
* com.adobe.internal.pdftoolkit.pdf.document.PDFCatalog
* com.adobe.internal.pdftoolkit.pdf.document.PDFDocument
* com.adobe.internal.pdftoolkit.pdf.document.PDFEncryption
* com.adobe.internal.pdftoolkit.pdf.document.PDFNameDictionary
* com.adobe.internal.pdftoolkit.pdf.document.PDFNamedXFAResources
* com.adobe.internal.pdftoolkit.pdf.document.PDFOpenOptions
* com.adobe.internal.pdftoolkit.pdf.document.PDFPermissions
* com.adobe.internal.pdftoolkit.pdf.document.PDFSaveFullOptions
* com.adobe.internal.pdftoolkit.pdf.document.PDFSaveIncrementalOptions
* com.adobe.internal.pdftoolkit.pdf.document.PDFSaveOptions
* com.adobe.internal.pdftoolkit.pdf.document.PDFStream
* com.adobe.internal.pdftoolkit.pdf.graphics.PDFRectangle
* com.adobe.internal.pdftoolkit.pdf.interactive.annotation.PDFAnnotation
* com.adobe.internal.pdftoolkit.pdf.interactive.annotation.PDFAnnotationIterator
* com.adobe.internal.pdftoolkit.pdf.interactive.annotation.PDFAnnotationWidget
* com.adobe.internal.pdftoolkit.pdf.interactive.annotation.PDFAppearance
* com.adobe.internal.pdftoolkit.pdf.interactive.forms.PDFFieldSignature
* com.adobe.internal.pdftoolkit.pdf.interactive.forms.PDFInteractiveForm
* com.adobe.internal.pdftoolkit.pdf.interchange.metadata.PDFMetadata
* com.adobe.internal.pdftoolkit.pdf.page.PDFPage
* com.adobe.internal.pdftoolkit.pdf.page.PDFPageTree
* com.adobe.internal.pdftoolkit.services.ap.AppearanceService
* com.adobe.internal.pdftoolkit.services.ap.extension.APExtensionOptions
* com.adobe.internal.pdftoolkit.services.ap.spi.APContext
* com.adobe.internal.pdftoolkit.services.ap.spi.APResources
* com.adobe.internal.pdftoolkit.services.ap.spi.TextFormatter
* com.adobe.internal.pdftoolkit.services.digsig.SignatureFieldInterface
* com.adobe.internal.pdftoolkit.services.digsig.SignatureFieldPDF
* com.adobe.internal.pdftoolkit.services.digsig.SignatureManager
* com.adobe.internal.pdftoolkit.services.fdf.FDFDocument
* com.adobe.internal.pdftoolkit.services.fdf.FDFService
* com.adobe.internal.pdftoolkit.services.formflattener.FormFlattener
* com.adobe.internal.pdftoolkit.services.javascript.JavaScriptHandler
* com.adobe.internal.pdftoolkit.services.xfa.XFADOMService
* com.adobe.internal.pdftoolkit.services.xfa.XFAProcessingOptions
* com.adobe.internal.pdftoolkit.services.xfa.XFAService
* com.adobe.internal.pdftoolkit.services.xfa.XFAService$XFAElement
* com.adobe.internal.pdftoolkit.services.xfdf.XFDFService
* org.apache.commons.lang3.StringEscapeUtils
*/
package com.adobe.fd.forms.internal.utils;
import com.adobe.aemfd.docmanager.Document;
import com.adobe.aemfd.docmanager.TempFileManager;
import com.adobe.aemfd.pdfdocmanager.SharedPdfDocument;
import com.adobe.aemfd.pdfdocmanager.SharedPdfDocumentContext;
import com.adobe.fd.forms.api.AcrobatVersion;
import com.adobe.fd.forms.api.CacheStrategy;
import com.adobe.fd.forms.api.PDFFormRenderOptions;
import com.adobe.fd.forms.internal.logging.FormsServiceLogger;
import com.adobe.fd.forms.internal.utils.JSUtils;
import com.adobe.fd.forms.internal.utils.ServiceUtil;
import com.adobe.fd.forms.internal.utils.StringUtils;
import com.adobe.fd.forms.internal.utils.XMLUtils;
import com.adobe.fd.output.api.PDFOutputOptions;
import com.adobe.fd.output.api.PaginationOverride;
import com.adobe.fd.output.api.PrintConfig;
import com.adobe.fd.output.api.PrintedOutputOptions;
import com.adobe.fd.output.api.RenderType;
import com.adobe.fd.output.internal.PDFPageAndAnnotation;
import com.adobe.forms.option.LCFormsOptions;
import com.adobe.internal.io.ByteArrayByteReader;
import com.adobe.internal.io.ByteReader;
import com.adobe.internal.pdftoolkit.core.cos.CosArray;
import com.adobe.internal.pdftoolkit.core.cos.CosCloneMgr;
import com.adobe.internal.pdftoolkit.core.cos.CosDictionary;
import com.adobe.internal.pdftoolkit.core.cos.CosDocument;
import com.adobe.internal.pdftoolkit.core.cos.CosObject;
import com.adobe.internal.pdftoolkit.core.cos.CosStream;
import com.adobe.internal.pdftoolkit.core.cos.CosString;
import com.adobe.internal.pdftoolkit.core.exceptions.PDFException;
import com.adobe.internal.pdftoolkit.core.exceptions.PDFIOException;
import com.adobe.internal.pdftoolkit.core.exceptions.PDFInvalidDocumentException;
import com.adobe.internal.pdftoolkit.core.exceptions.PDFInvalidXMLException;
import com.adobe.internal.pdftoolkit.core.exceptions.PDFSecurityException;
import com.adobe.internal.pdftoolkit.core.fontset.PDFFontSet;
import com.adobe.internal.pdftoolkit.core.types.ASName;
import com.adobe.internal.pdftoolkit.core.types.ASString;
import com.adobe.internal.pdftoolkit.pdf.digsig.PDFDocMDPPermissions;
import com.adobe.internal.pdftoolkit.pdf.digsig.PDFSignature;
import com.adobe.internal.pdftoolkit.pdf.document.PDFCatalog;
import com.adobe.internal.pdftoolkit.pdf.document.PDFDocument;
import com.adobe.internal.pdftoolkit.pdf.document.PDFEncryption;
import com.adobe.internal.pdftoolkit.pdf.document.PDFNameDictionary;
import com.adobe.internal.pdftoolkit.pdf.document.PDFNamedXFAResources;
import com.adobe.internal.pdftoolkit.pdf.document.PDFOpenOptions;
import com.adobe.internal.pdftoolkit.pdf.document.PDFPermissions;
import com.adobe.internal.pdftoolkit.pdf.document.PDFSaveFullOptions;
import com.adobe.internal.pdftoolkit.pdf.document.PDFSaveIncrementalOptions;
import com.adobe.internal.pdftoolkit.pdf.document.PDFSaveOptions;
import com.adobe.internal.pdftoolkit.pdf.document.PDFStream;
import com.adobe.internal.pdftoolkit.pdf.graphics.PDFRectangle;
import com.adobe.internal.pdftoolkit.pdf.interactive.annotation.PDFAnnotation;
import com.adobe.internal.pdftoolkit.pdf.interactive.annotation.PDFAnnotationIterator;
import com.adobe.internal.pdftoolkit.pdf.interactive.annotation.PDFAnnotationWidget;
import com.adobe.internal.pdftoolkit.pdf.interactive.annotation.PDFAppearance;
import com.adobe.internal.pdftoolkit.pdf.interactive.forms.PDFFieldSignature;
import com.adobe.internal.pdftoolkit.pdf.interactive.forms.PDFInteractiveForm;
import com.adobe.internal.pdftoolkit.pdf.interchange.metadata.PDFMetadata;
import com.adobe.internal.pdftoolkit.pdf.page.PDFPage;
import com.adobe.internal.pdftoolkit.pdf.page.PDFPageTree;
import com.adobe.internal.pdftoolkit.services.ap.AppearanceService;
import com.adobe.internal.pdftoolkit.services.ap.extension.APExtensionOptions;
import com.adobe.internal.pdftoolkit.services.ap.spi.APContext;
import com.adobe.internal.pdftoolkit.services.ap.spi.APResources;
import com.adobe.internal.pdftoolkit.services.ap.spi.TextFormatter;
import com.adobe.internal.pdftoolkit.services.digsig.SignatureFieldInterface;
import com.adobe.internal.pdftoolkit.services.digsig.SignatureFieldPDF;
import com.adobe.internal.pdftoolkit.services.digsig.SignatureManager;
import com.adobe.internal.pdftoolkit.services.fdf.FDFDocument;
import com.adobe.internal.pdftoolkit.services.fdf.FDFService;
import com.adobe.internal.pdftoolkit.services.formflattener.FormFlattener;
import com.adobe.internal.pdftoolkit.services.javascript.JavaScriptHandler;
import com.adobe.internal.pdftoolkit.services.xfa.XFADOMService;
import com.adobe.internal.pdftoolkit.services.xfa.XFAProcessingOptions;
import com.adobe.internal.pdftoolkit.services.xfa.XFAService;
import com.adobe.internal.pdftoolkit.services.xfdf.XFDFService;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.xml.transform.dom.DOMSource;
import org.apache.commons.lang3.StringEscapeUtils;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Utils {
public static FormsServiceLogger logger = new FormsServiceLogger(Utils.class);
public static final String EMPTY_DATA = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><xfa:datasets xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\"><xfa:data></xfa:data></xfa:datasets>";
private static final byte[] xmptag = new byte[]{60, 120, 58, 120, 109, 112, 109, 101, 116, 97};
private static final byte[] xmpendtag = new byte[]{60, 47, 120, 58, 120, 109, 112, 109, 101, 116, 97};
private static final byte[] xdpendtag = new byte[]{60, 47, 120, 100, 112, 58, 120, 100, 112};
public static final String FDF_DATATYPE = "FDF";
public static final String XFDF_DATATYPE = "XFDF";
public static final String XDP_DATATYPE = "XDP";
public static final String XML_DATATYPE = "XML";
public static final String DATASETS_ASSTRING = "datasets";
private Utils() {
}
public static byte[] getBytes(Document doc) throws IOException {
if (doc == null) {
return new byte[0];
}
return StringUtils.inputStreamToBytes(doc.getInputStream(), 8);
}
public static PDFDocument createPDFDocument(Document doc) throws PDFException, IOException {
if (doc != null) {
return SharedPdfDocumentContext.toPDFDocument((Document)doc, (PDFOpenOptions)PDFOpenOptions.newInstance());
}
return null;
}
public static PDFDocument getSharedPDFDocument(Document doc) {
SharedPdfDocument sharedDoc;
if (doc != null && doc instanceof SharedPdfDocument && (sharedDoc = (SharedPdfDocument)doc).getPDFDocument() != null) {
return sharedDoc.getPDFDocument();
}
return null;
}
public static boolean hasPermSig(PDFDocument oPdfDocument) throws PDFSecurityException, PDFIOException, PDFInvalidDocumentException {
return SignatureManager.newInstance((PDFDocument)oPdfDocument).hasPermissionsSignature();
}
public static boolean hasRegularSig(PDFDocument oPdfDocument) throws PDFSecurityException, PDFIOException, PDFInvalidDocumentException {
return SignatureManager.newInstance((PDFDocument)oPdfDocument).hasSignedSignatureFields();
}
public static boolean hasSignature(PDFDocument pdfDoc, boolean isPDFTemplate) throws PDFInvalidDocumentException, PDFIOException, PDFSecurityException {
boolean hasAnySig = Utils.hasPermSig(pdfDoc);
if (isPDFTemplate && !hasAnySig) {
hasAnySig = Utils.hasRegularSig(pdfDoc);
}
return hasAnySig;
}
public static Document toDocument(PDFDocument pdfDoc) throws PDFSecurityException, PDFIOException, PDFInvalidDocumentException {
PDFSaveIncrementalOptions saveOptions = null;
saveOptions = Utils.hasSignature(pdfDoc, true) ? PDFSaveIncrementalOptions.newInstance() : PDFSaveFullOptions.newInstance();
saveOptions.setCloseAfterSave(true);
return SharedPdfDocumentContext.toDocument((PDFDocument)pdfDoc, (PDFSaveOptions)saveOptions);
}
public static byte[] exportXFAData(PDFDocument pdf) throws PDFInvalidDocumentException, PDFIOException, PDFSecurityException, PDFInvalidXMLException, IOException {
ByteArrayOutputStream xmlStream = new ByteArrayOutputStream();
XFAService.exportElement((PDFDocument)pdf, (XFAService.XFAElement)XFAService.XFAElement.DATASETS, (OutputStream)xmlStream);
byte[] bytes = xmlStream.toByteArray();
xmlStream.close();
return bytes;
}
public static PDFDocument importXFAData(PDFDocument oPdfDocument, byte[] data) throws Exception {
if (oPdfDocument != null) {
XFAService.importElement((PDFDocument)oPdfDocument, (XFAService.XFAElement)XFAService.XFAElement.DATASETS, (InputStream)new ByteArrayInputStream(data));
Utils.syncDataAndGenerateAppearance(oPdfDocument, true);
}
return oPdfDocument;
}
public static PDFDocument createPDFDocument(byte[] pdf) throws PDFSecurityException, PDFIOException, PDFInvalidDocumentException {
return PDFDocument.newInstance((ByteReader)new ByteArrayByteReader(pdf), (PDFOpenOptions)PDFOpenOptions.newInstance());
}
public static byte[] getXDPFromPDF(PDFDocument pdfDocument) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
if (XFAService.getFullStream((PDFDocument)pdfDocument, (OutputStream)out)) {
return out.toByteArray();
}
throw new Exception();
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
public static byte[] getMetaData(PDFDocument pdfDoc) throws Exception {
PDFMetadata metaData = pdfDoc.requireCatalog().getMetadata();
byte[] bytes = null;
if (metaData != null) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
metaData.getData((OutputStream)os);
byte[] arrby = os.toByteArray();
return arrby;
}
finally {
if (os != null) {
os.close();
}
}
}
return bytes;
}
public static byte[] overlayXMPMetadataFromPdf(PDFDocument pdfDocument, byte[] xdpBytes) throws Exception {
byte[] metaData = Utils.getMetaData(pdfDocument);
if (metaData != null) {
int metaDataEndIndex = StringUtils.findArraySegmentReverse(xdpBytes, xmpendtag);
if (metaDataEndIndex != -1) {
int metaDataIndex = StringUtils.findArraySegmentReverse(xdpBytes, metaDataEndIndex, xmptag);
int oldMetadatalen = metaDataEndIndex + xmpendtag.length - metaDataIndex;
xdpBytes = StringUtils.replaceArraySegment(xdpBytes, metaDataIndex, oldMetadatalen, metaData, 0, metaData.length - 1);
} else {
metaDataEndIndex = StringUtils.findArraySegmentReverse(xdpBytes, xdpendtag);
xdpBytes = StringUtils.replaceArraySegment(xdpBytes, metaDataEndIndex, 0, metaData, 0, metaData.length);
}
}
return xdpBytes;
}
public static LCFormsOptions create(PDFFormRenderOptions options) throws IOException {
CacheStrategy cacheStrategy;
LCFormsOptions lcOptions = new LCFormsOptions();
lcOptions.setContentRoot(options.getContentRoot());
lcOptions.setRenderType("pdf");
lcOptions.setTaggedPDF(options.getTaggedPDF() ? "1" : "0");
lcOptions.setLocale(options.getLocale());
lcOptions.setSubmitUrl(options.getSubmitUrls() != null ? options.getSubmitUrls().get(0) : null);
CacheStrategy cacheStrategy2 = cacheStrategy = options.getCacheStrategy() != null ? options.getCacheStrategy() : CacheStrategy.AGGRESSIVE;
if (cacheStrategy != CacheStrategy.AGGRESSIVE) {
lcOptions.setUseRenderCache("false");
}
if (cacheStrategy == CacheStrategy.NONE) {
lcOptions.setPreRenderCache("false");
}
if (options.getXci() != null) {
lcOptions.setXciBytes(new String(Utils.getBytes(options.getXci()), "UTF-8"));
}
if (options.getAcrobatVersion() != null) {
lcOptions.setPdfVersion(options.getAcrobatVersion().getPdfVersion());
lcOptions.setExtensionLevel(options.getAcrobatVersion().getExtensionLevel());
}
lcOptions.setDebugDir(options.getDebugDir());
return lcOptions;
}
public static LCFormsOptions create(PDFOutputOptions options) throws IOException {
LCFormsOptions lcOptions = new LCFormsOptions();
lcOptions.setContentRoot(options.getContentRoot());
lcOptions.setRenderType("print.pdf");
lcOptions.setTaggedPDF(options.getTaggedPDF() ? "1" : "0");
lcOptions.setLocale(options.getLocale());
lcOptions.setLinearized(options.getLinearizedPDF() ? "1" : "0");
if (options.getXci() != null) {
lcOptions.setXciBytes(new String(Utils.getBytes(options.getXci()), "UTF-8"));
}
if (options.getAcrobatVersion() != null) {
lcOptions.setPdfVersion(options.getAcrobatVersion().getPdfVersion());
lcOptions.setExtensionLevel(options.getAcrobatVersion().getExtensionLevel());
}
lcOptions.setDebugDir(options.getDebugDir());
return lcOptions;
}
public static LCFormsOptions create(PrintedOutputOptions options) throws IOException {
LCFormsOptions lcOptions = new LCFormsOptions();
lcOptions.setContentRoot(options.getContentRoot());
lcOptions.setLocale(options.getLocale());
if (options.getPrintConfig() != null) {
lcOptions.setRenderType(options.getPrintConfig().getRenderType().getText());
lcOptions.setXdcUri(options.getPrintConfig().getXdcUri());
}
if (options.getXci() != null) {
lcOptions.setXciBytes(new String(Utils.getBytes(options.getXci()), "UTF-8"));
}
if (options.getCopies() > 0) {
lcOptions.setNumCopies("" + options.getCopies() + "");
}
if (options.getPaginationOverride() != null) {
lcOptions.setPaginationOverride(options.getPaginationOverride().getXciString());
}
lcOptions.setDebugDir(options.getDebugDir());
return lcOptions;
}
public static void removeXFAImagesFromDisc(Map<String, String> xfaImageMap) {
try {
if (xfaImageMap != null && xfaImageMap.size() > 0) {
for (Map.Entry<String, String> mapEntry : xfaImageMap.entrySet()) {
String key = mapEntry.getKey();
String value = mapEntry.getValue();
try {
File f = new File(value);
if (!f.exists()) continue;
f.delete();
}
catch (Exception e) {
logger.warn("AEM_FRM_001_004", new String[]{e.getMessage()}, e);
}
}
}
}
catch (Exception t) {
logger.warn("AEM_FRM_001_004", new String[]{t.getMessage()}, t);
}
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
public static Map<String, String> extractXFAImagesFromPDF(PDFDocument inPdfDocument, TempFileManager tempFileManager) {
HashMap<String, String> xfaImageMap;
block17 : {
xfaImageMap = null;
try {
ASName asNamesName;
int arrSize;
PDFCatalog pdfCatalog = inPdfDocument.requireCatalog();
PDFNameDictionary namedDictionary = pdfCatalog.getNameDictionary();
ASName asName = ASName.create((String)"XFAImages");
if (!namedDictionary.dictionaryContains(asName)) break block17;
CosDictionary xfaCosDictionary = namedDictionary.getDictionaryDictionaryValue(asName);
CosArray cosArray = xfaCosDictionary.getCosArray(asNamesName = ASName.create((String)"Names"));
int n = arrSize = cosArray != null ? cosArray.size() : 0;
if (arrSize > 0) {
xfaImageMap = new HashMap<String, String>();
}
for (int i = 0; i < arrSize; i += 2) {
CosObject imageValueObject;
CosObject imageKeyObject = cosArray.get(i);
if (imageKeyObject.getType() != 4) continue;
CosString imageName = (CosString)imageKeyObject;
if (i + 1 >= arrSize || (imageValueObject = cosArray.get(i + 1)).getType() != 7) continue;
String[] arr = imageName.asString().split("/+|\\\\+");
String fileName = arr[arr.length - 1];
String suffix = null;
int fileNmExtnIndx = fileName.lastIndexOf(".");
if (fileNmExtnIndx != -1) {
suffix = fileName.substring(fileNmExtnIndx);
fileName = fileName.substring(0, fileNmExtnIndx);
}
CosStream extractedImage = (CosStream)imageValueObject;
File tempFile = null;
FileOutputStream fos = null;
try {
tempFile = tempFileManager.getTempFile(fileName, suffix);
fos = new FileOutputStream(tempFile);
extractedImage.copyStream((Object)fos, false);
xfaImageMap.put(imageName.asString(), tempFile.getAbsolutePath());
}
catch (Exception e) {
logger.warn("AEM_FRM_001_004", new String[]{e.getMessage()}, e);
}
finally {
if (fos != null) {
try {
fos.close();
}
catch (IOException e) {}
}
}
}
}
catch (Exception e) {
logger.warn("AEM_FRM_001_004", new String[]{e.getMessage()}, e);
}
}
return xfaImageMap;
}
public static String buildImageResourceString(Map<String, String> xfaImageMap) {
String begin_resources = "<status><resources>";
String end_resources = "</resources></status>";
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(begin_resources);
if (xfaImageMap != null) {
Formatter formatter = new Formatter(stringBuilder);
for (Map.Entry<String, String> xfaImageEntry : xfaImageMap.entrySet()) {
String imageTemplateUri = StringEscapeUtils.escapeXml11((String)xfaImageEntry.getKey());
String imageAbsoluteUri = StringEscapeUtils.escapeXml11((String)xfaImageEntry.getValue());
formatter.format("<resource container=\"image\" templateHref=\"%s\" href=\"%s\" normalizedFileName=\"\" />", imageTemplateUri, imageAbsoluteUri);
}
}
stringBuilder.append(end_resources);
return stringBuilder.toString();
}
public static boolean areDataChangesAllowed(PDFDocument oPdfDocument) throws Exception {
if (!Utils.isFillingFormFieldsAllowed(oPdfDocument)) {
return false;
}
return Utils.areChangesAllowed(oPdfDocument);
}
private static boolean isFillingFormFieldsAllowed(PDFDocument oPdfDocument) {
boolean isFieldFillAllowed = true;
try {
Map encryptionParamMap;
PDFEncryption pdfEncryption = oPdfDocument.getEncryption();
if (pdfEncryption != null && (encryptionParamMap = pdfEncryption.getEncryptParameters()) != null && !encryptionParamMap.isEmpty()) {
Integer p = (Integer)encryptionParamMap.get("P");
int sixth = 32;
int ninth = 256;
if (p != null) {
isFieldFillAllowed = (p & ninth) != 0 || (p & sixth) != 0;
}
}
}
catch (Exception e) {
logger.warn("AEM_FRM_001_004", new String[]{e.getMessage()}, e);
}
return isFieldFillAllowed;
}
public static boolean areChangesAllowed(PDFDocument oPdfDocument) throws Exception {
SignatureManager oSM = SignatureManager.newInstance((PDFDocument)oPdfDocument);
PDFDocMDPPermissions perms = oSM.getPDFDocMDPPermissions();
if (perms == null || perms != PDFDocMDPPermissions.NoChanges) {
return true;
}
return false;
}
public static boolean isAcroForm(PDFDocument oPdfDocument) throws Exception {
boolean retVal = false;
PDFInteractiveForm oInteractiveForm = oPdfDocument.getInteractiveForm();
if (oInteractiveForm != null) {
retVal = !oInteractiveForm.hasXFA();
}
return retVal;
}
public static boolean isXFAForm(PDFDocument oPdfDocument) throws Exception {
boolean retVal = false;
PDFInteractiveForm oInteractiveForm = oPdfDocument.getInteractiveForm();
if (oInteractiveForm != null) {
retVal = oInteractiveForm.hasXFA();
}
return retVal;
}
public static PDFDocument importDataToAcroform(PDFDocument oPdfDocument, byte[] oDataBytes, boolean bGenerateAppearances) throws Exception {
String sDataFlavor = Utils.getDataFlavor(oDataBytes);
if (sDataFlavor.equals("FDF")) {
oPdfDocument = Utils.mergeFDFDataIntoPDFDocument(oPdfDocument, oDataBytes, bGenerateAppearances);
} else if (sDataFlavor.equals("XFDF")) {
oPdfDocument = Utils.mergeXFDFDataIntoPDFDocument(oPdfDocument, oDataBytes, bGenerateAppearances);
} else if (sDataFlavor.equals("XDP") || sDataFlavor.equalsIgnoreCase("XML")) {
byte[] oConvertedDataBytes = Utils.convertXDPtoXFDF(oDataBytes);
oPdfDocument = Utils.mergeXFDFDataIntoPDFDocument(oPdfDocument, oConvertedDataBytes, bGenerateAppearances);
}
return oPdfDocument;
}
public static PDFDocument mergeXFDFDataIntoPDFDocument(PDFDocument oPdfDocument, byte[] data, boolean bGenerateAppearances) throws Exception {
PDFInteractiveForm pdfIForm = oPdfDocument.getInteractiveForm();
if (pdfIForm != null) {
ByteArrayInputStream oDataStream = new ByteArrayInputStream(data);
XFDFService.importFormData((PDFDocument)oPdfDocument, (InputStream)oDataStream);
oDataStream.close();
oDataStream = new ByteArrayInputStream(data);
XFDFService.importAnnotations((PDFDocument)oPdfDocument, (InputStream)oDataStream);
oDataStream.close();
if (bGenerateAppearances) {
JSUtils.executeEventsAndGenerateAppearances(oPdfDocument, true);
} else if (oPdfDocument.getInteractiveForm().hasNeedAppearances()) {
oPdfDocument.getInteractiveForm().removeNeedAppearances();
}
}
return oPdfDocument;
}
public static PDFDocument mergeFDFDataIntoPDFDocument(PDFDocument oPdfDocument, byte[] data, boolean bGenerateAppearances) throws Exception {
PDFInteractiveForm pdfIForm = oPdfDocument.getInteractiveForm();
if (pdfIForm != null) {
ByteArrayByteReader oFDFStream = new ByteArrayByteReader(data);
FDFDocument oFDFDocument = FDFDocument.newInstance((ByteReader)oFDFStream);
oFDFStream.close();
FDFService oFDFService = new FDFService(oPdfDocument);
oFDFService.importForm(oFDFDocument);
if (bGenerateAppearances) {
JSUtils.executeEventsAndGenerateAppearances(oPdfDocument, true);
} else if (pdfIForm.hasNeedAppearances()) {
pdfIForm.removeNeedAppearances();
}
}
return oPdfDocument;
}
public static String getDataFlavor(byte[] rawData) {
byte[] fields;
if (rawData == null || rawData.length == 0) {
return null;
}
if (StringUtils.exists(rawData, 0, "%FDF")) {
return "FDF";
}
byte[] bXFDF = StringUtils.getXMLBlockBytes(rawData, "xfdf");
if (bXFDF != null && (fields = StringUtils.getXMLBlockBytes(bXFDF, "fields")) != null) {
return "XFDF";
}
if (StringUtils.exists(rawData, 0, "<xfa:datasets")) {
return "XDP";
}
return "XML";
}
public static byte[] convertXDPtoXFDF(byte[] xdpData) throws Exception {
org.w3c.dom.Document doc = XMLUtils.loadXMLbytes(xdpData, false);
byte[] xfdfBytes = Utils.convertFromXFAtoXFDFData(doc);
return xfdfBytes;
}
public static byte[] convertFromXFAtoXFDFData(org.w3c.dom.Document oXFA) throws Exception {
NodeList oFieldList;
if (oXFA == null) {
return null;
}
Element rootElem = oXFA.getDocumentElement();
if (rootElem == null) {
return null;
}
Node root = XMLUtils.selectNode(rootElem, "xfa:datasets/xfa:data", 0);
if (root == null) {
root = rootElem;
} else if ((root = root.getFirstChild()).getNodeType() == 3) {
root = root.getNextSibling();
}
String initDocTemplate = "<?xml version='1.0' encoding='UTF-8'?> <xfdf xmlns='http://ns.adobe.com/xfdf/' xml:space='preserve' ><fields></fields></xfdf>";
org.w3c.dom.Document xfdfDom = Utils.createDomFromTemplate(initDocTemplate);
Element fieldsElem = XMLUtils.getChildElement(xfdfDom.getDocumentElement(), "fields");
if (root != null && (oFieldList = root.getChildNodes()) != null) {
for (int i = 0; i < oFieldList.getLength(); ++i) {
Node oChildNode = oFieldList.item(i);
if (oChildNode == null || oChildNode.getNodeType() != 1) continue;
Utils.convertFromXFANodeToXFDFDataNode((Element)oChildNode, fieldsElem);
}
}
return XMLUtils.toXML(new DOMSource(xfdfDom));
}
public static void convertFromXFANodeToXFDFDataNode(Element root, Element targetDom) throws Exception {
if (root != null) {
String origName;
String name;
boolean isRichText;
org.w3c.dom.Document fieldDom = XMLUtils.loadXMLbytes("<field name=''><value/><value-richtext/></field>".getBytes(), false);
Element fieldElem = fieldDom.getDocumentElement();
if (targetDom != null) {
fieldElem = (Element)XMLUtils.copyNodes(fieldElem, targetDom);
}
if ((name = root.getNodeName()) != null && (origName = root.getAttributeNS("http://ns.adobe.com/xfdf-transition/", "original")) != null && origName.length() > 0) {
name = origName;
}
fieldElem.setAttribute("name", name);
String ct = root.getAttributeNS("http://www.xfa.org/schema/xfa-data/1.0/", "contentType");
boolean bl = isRichText = ct != null && ct.length() > 0 ? ct.trim().equalsIgnoreCase("text/html") : false;
if (isRichText) {
Element elem = XMLUtils.getChildElement(fieldElem, "value");
if (elem != null) {
fieldElem.removeChild(elem);
}
elem = XMLUtils.getChildElement(fieldElem, "value-richtext");
Element bodyElem = XMLUtils.getChildElement(root, "body");
if (bodyElem == null) {
bodyElem = XMLUtils.createElement(elem.getOwnerDocument(), "body", "");
Element pElem = XMLUtils.createElement(elem.getOwnerDocument(), "p", "");
NodeList oNodeList = root.getChildNodes();
for (int i = 0; i < oNodeList.getLength(); ++i) {
XMLUtils.copyNodes(oNodeList.item(i), pElem);
}
XMLUtils.copyNodes(pElem, bodyElem);
}
elem = (Element)XMLUtils.copyNodes(bodyElem, elem);
elem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xfa", "http://www.xfa.org/schema/xfa-data/1.0/");
} else {
NodeList oFieldList;
String val;
Element elem = XMLUtils.getChildElement(fieldElem, "value-richtext");
if (elem != null) {
fieldElem.removeChild(elem);
}
if ((val = XMLUtils.getNodeTextValue(root)) != null && val.length() > 0) {
elem = XMLUtils.getChildElement(fieldElem, "value");
if (elem != null) {
XMLUtils.appendText(elem, val);
}
} else {
elem = XMLUtils.getChildElement(fieldElem, "value");
if (elem != null) {
fieldElem.removeChild(elem);
}
}
if ((oFieldList = root.getChildNodes()) != null) {
for (int i = 0; i < oFieldList.getLength(); ++i) {
Node oChildNode = oFieldList.item(i);
if (oChildNode == null || oChildNode.getNodeType() != 1) continue;
Utils.convertFromXFANodeToXFDFDataNode((Element)oChildNode, fieldElem);
}
}
}
}
}
private static org.w3c.dom.Document createDomFromTemplate(String xmlString) throws Exception {
return XMLUtils.loadXMLbytes(xmlString.getBytes(), false);
}
public static PDFDocument generateAppearances(PDFDocument oPdfDocument) throws Exception {
boolean isXFA = Utils.isXFAForm(oPdfDocument);
XFAProcessingOptions xfaProcessingOptions = null;
if (isXFA) {
xfaProcessingOptions = new XFAProcessingOptions(true, true);
}
PDFFontSet fontSet = ServiceUtil.getFontManagerService().getPdfFontSet();
AppearanceService.generateAppearances((PDFDocument)oPdfDocument, (APContext)new APContext(new APResources(fontSet, Locale.ROOT, new HashMap()), true, null), (TextFormatter)null);
return oPdfDocument;
}
public static byte[] exportXFDFData(PDFDocument oPdfDocument) throws IOException, PDFException {
PDFInteractiveForm pdfIForm = oPdfDocument.getInteractiveForm();
if (pdfIForm == null) {
return null;
}
ByteArrayOutputStream oOutStream = new ByteArrayOutputStream();
XFDFService.exportFormData((PDFDocument)oPdfDocument, (OutputStream)oOutStream);
return oOutStream.toByteArray();
}
public static byte[] exportXFDFAnnots(PDFDocument oPdfDocument) throws IOException, PDFException {
PDFInteractiveForm pdfIForm = oPdfDocument.getInteractiveForm();
if (pdfIForm == null) {
return null;
}
ByteArrayOutputStream oOutStream = new ByteArrayOutputStream();
XFDFService.exportAnnotations((PDFDocument)oPdfDocument, (OutputStream)oOutStream);
return oOutStream.toByteArray();
}
public static byte[] exportDataFromXFAResourceDictionary(PDFDocument oPdfDocument) throws IOException, PDFException {
PDFNameDictionary pdfNameDict;
PDFStream pdfStream;
PDFNamedXFAResources pdfNamedXFAResources;
ByteArrayOutputStream out = new ByteArrayOutputStream();
if (oPdfDocument != null && (pdfNameDict = oPdfDocument.requireCatalog().getNameDictionary()) != null && (pdfNamedXFAResources = pdfNameDict.getNamedXFAResources()) != null && (pdfStream = (PDFStream)pdfNamedXFAResources.getEntry((Object)new ASString("datasets"))) != null) {
pdfStream.getStreamData((OutputStream)out);
}
return out.toByteArray();
}
public static byte[] mergeDataWithAnnots(byte[] oExportedDataBytes, byte[] oExportedAnnotsBytes) {
byte[] oMergedBytes = new byte[]{};
try {
org.w3c.dom.Document oRootDoc1 = XMLUtils.loadXMLbytes(oExportedDataBytes, false);
org.w3c.dom.Document oRootDoc2 = XMLUtils.loadXMLbytes(oExportedAnnotsBytes, false);
Element oRootElem2 = oRootDoc2.getDocumentElement();
NodeList oChildren2 = oRootElem2.getChildNodes();
Element oRootElem1 = oRootDoc1.getDocumentElement();
for (int i = 0; i < oChildren2.getLength(); ++i) {
Node oImportedNode = oRootDoc1.importNode(oChildren2.item(i), true);
oRootElem1.appendChild(oImportedNode);
}
oMergedBytes = XMLUtils.toXML(new DOMSource(oRootDoc1));
}
catch (Exception e) {
oMergedBytes = oExportedDataBytes;
logger.warn("AEM_FRM_001_004", new String[]{e.getMessage()}, e);
}
return oMergedBytes;
}
public static Map retrieveSignatureAppearances(PDFDocument pdfDocument) throws Exception {
HashMap<String, CosObject> signatureAppearancesMap = new HashMap<String, CosObject>();
SignatureManager sigMgr = SignatureManager.newInstance((PDFDocument)pdfDocument);
Iterator sigFieldIter = sigMgr.getPDFSignatureFieldIterator();
if (sigFieldIter == null) {
return signatureAppearancesMap;
}
SignatureFieldInterface signatureField = null;
PDFAnnotationWidget sigAnnot = null;
String qualifiedName = null;
CosObject cosObject = null;
while (sigFieldIter.hasNext()) {
signatureField = (SignatureFieldInterface)sigFieldIter.next();
sigAnnot = signatureField.getPDFField().getPDFFieldSignature().getAnnotation();
if (!signatureField.isSigned() || sigAnnot == null || sigAnnot.getAppearance() == null) continue;
qualifiedName = signatureField.getQualifiedName();
cosObject = sigAnnot.getAppearance().getCosObject();
signatureAppearancesMap.put(qualifiedName, cosObject);
}
return signatureAppearancesMap;
}
public static void overlaySignatureAppearances(PDFDocument flatPDF, Map signatureAppearances, boolean removeAllSignatureFields) throws Exception {
PDFAnnotationIterator annotIter = null;
SignatureManager sigMgr = SignatureManager.newInstance((PDFDocument)flatPDF);
if (flatPDF.requirePages() != null && flatPDF.requirePages().getAnnotationsIterator() != null) {
annotIter = flatPDF.requirePages().getAnnotationsIterator();
ArrayList<PDFPageAndAnnotation> pageAndAnnotationList = new ArrayList<PDFPageAndAnnotation>();
PDFPageAndAnnotation pageAndAnnotation2 = null;
PDFPage page = null;
PDFAnnotation pdfAnnotation = null;
while (annotIter.hasNext()) {
CosObject cosObject;
pdfAnnotation = annotIter.next();
if (!pdfAnnotation.getRect().hasNonZeroDimensions() || (cosObject = (CosObject)signatureAppearances.get(pdfAnnotation.getID())) == null) continue;
page = pdfAnnotation.getPage();
CosCloneMgr cloner = new CosCloneMgr(flatPDF.getCosDocument());
CosObject clonedAppearanceCos = cloner.clone(cosObject);
pageAndAnnotation2 = new PDFPageAndAnnotation(page, pdfAnnotation, clonedAppearanceCos);
pageAndAnnotationList.add(pageAndAnnotation2);
}
if (sigMgr != null && sigMgr.hasSignatureFields()) {
Iterator sigFieldIter = sigMgr.getDocSignatureFieldIterator();
SignatureFieldInterface field = null;
while (sigFieldIter.hasNext()) {
field = (SignatureFieldInterface)sigFieldIter.next();
if (signatureAppearances.get(field.getQualifiedName()) == null) continue;
sigFieldIter.remove();
}
}
for (PDFPageAndAnnotation pageAndAnnotation2 : pageAndAnnotationList) {
page = pageAndAnnotation2.getPage();
pdfAnnotation = pageAndAnnotation2.getPdfAnnotation();
CosObject appearanceCosObject = pageAndAnnotation2.getAppearanceCosObject();
pdfAnnotation.getCosDictionary().put(ASName.k_AP, appearanceCosObject);
pdfAnnotation.getCosDictionary().put(ASName.k_FT, ASName.k_Tx);
pdfAnnotation.getCosDictionary().put(ASName.k_Ff, 1);
page.addAnnotation(pdfAnnotation);
}
}
if (removeAllSignatureFields && sigMgr != null) {
sigMgr.removeAllSignatureFields();
if (sigMgr.hasPermissionsSignature()) {
PDFPermissions perms = flatPDF.requireCatalog().getPermissions();
perms.setDocMDP(null);
}
}
Utils.removeEmptyAcroformElement(flatPDF);
}
public static void removeEmptyAcroformElement(PDFDocument pdf) {
try {
Iterator iter;
PDFInteractiveForm interactiveForm = pdf.getInteractiveForm();
if (interactiveForm != null && (iter = interactiveForm.iterator()) != null && !iter.hasNext()) {
pdf.requireCatalog().setInteractiveForm(null);
}
}
catch (Exception e) {
logger.warn("AEM_FRM_001_004", new String[]{e.getMessage()}, e);
}
}
public static void syncDataAndGenerateAppearance(PDFDocument oPdfDocument, boolean generateServerAppearance) throws Exception {
boolean isShellPDF = oPdfDocument.requireCatalog().getNeedsRendering();
if (generateServerAppearance && !isShellPDF) {
XFAProcessingOptions xfaProcessingOptions = new XFAProcessingOptions(true, true);
xfaProcessingOptions.registerJavaScriptHandler(JSUtils.getJSHandler(oPdfDocument));
XFADOMService.getXFADOM((PDFDocument)oPdfDocument, (XFAProcessingOptions)xfaProcessingOptions, (boolean)false, (boolean)true);
Utils.generateAppearances(oPdfDocument);
}
}
public static PDFDocument flattenForm(PDFDocument oPdfDocument, PDFFontSet oFontSet, boolean bForcedAppearanceGen, boolean retainUnsignedSignatureFields) throws Exception {
PDFInteractiveForm oInteractiveForm;
if (bForcedAppearanceGen && (oInteractiveForm = oPdfDocument.getInteractiveForm()) != null) {
oInteractiveForm.setNeedAppearances(true);
}
APResources apResources = new APResources(oFontSet, Locale.ROOT, null);
APContext apContext = new APContext(apResources, true, null);
FormFlattener.flattenDocument((APContext)apContext, (PDFDocument)oPdfDocument, (TextFormatter)null);
SignatureManager sigMgr = SignatureManager.newInstance((PDFDocument)oPdfDocument);
Iterator sigFieldIter = sigMgr.getDocSignatureFieldIterator();
while (sigFieldIter.hasNext()) {
SignatureFieldInterface sigField = (SignatureFieldInterface)sigFieldIter.next();
boolean bIsSigned = sigField.isSigned();
if (!bIsSigned && (bIsSigned || retainUnsignedSignatureFields)) continue;
sigFieldIter.remove();
}
if (sigMgr != null && sigMgr.hasPermissionsSignature()) {
PDFPermissions perms = oPdfDocument.requireCatalog().getPermissions();
perms.setDocMDP(null);
}
Utils.removeEmptyAcroformElement(oPdfDocument);
return oPdfDocument;
}
}