PDFToUnicodeCMap.java
20.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
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* com.adobe.internal.io.ByteWriterFactory
* com.adobe.internal.io.ByteWriterFactory$Fixed
* com.adobe.internal.io.stream.InputByteStream
* com.adobe.internal.io.stream.OutputByteStream
* com.adobe.internal.io.stream.StreamManager
* com.adobe.internal.pdftoolkit.core.cos.CosDocument
* com.adobe.internal.pdftoolkit.core.cos.CosObject
* com.adobe.internal.pdftoolkit.core.cos.CosOpenOptions
* com.adobe.internal.pdftoolkit.core.cos.CosStream
* com.adobe.internal.pdftoolkit.core.exceptions.PDFIOException
* com.adobe.internal.pdftoolkit.core.exceptions.PDFInvalidDocumentException
* com.adobe.internal.pdftoolkit.core.exceptions.PDFParseException
* com.adobe.internal.pdftoolkit.core.exceptions.PDFSecurityException
* com.adobe.internal.pdftoolkit.core.types.ASName
* com.adobe.internal.pdftoolkit.core.types.ASString
*/
package com.adobe.internal.pdftoolkit.pdf.graphics.font;
import com.adobe.internal.io.ByteWriterFactory;
import com.adobe.internal.io.stream.InputByteStream;
import com.adobe.internal.io.stream.OutputByteStream;
import com.adobe.internal.io.stream.StreamManager;
import com.adobe.internal.pdftoolkit.core.cos.CosDocument;
import com.adobe.internal.pdftoolkit.core.cos.CosObject;
import com.adobe.internal.pdftoolkit.core.cos.CosOpenOptions;
import com.adobe.internal.pdftoolkit.core.cos.CosStream;
import com.adobe.internal.pdftoolkit.core.exceptions.PDFIOException;
import com.adobe.internal.pdftoolkit.core.exceptions.PDFInvalidDocumentException;
import com.adobe.internal.pdftoolkit.core.exceptions.PDFParseException;
import com.adobe.internal.pdftoolkit.core.exceptions.PDFSecurityException;
import com.adobe.internal.pdftoolkit.core.types.ASName;
import com.adobe.internal.pdftoolkit.core.types.ASString;
import com.adobe.internal.pdftoolkit.pdf.document.PDFCosObject;
import com.adobe.internal.pdftoolkit.pdf.document.PDFCosStream;
import com.adobe.internal.pdftoolkit.pdf.document.PDFDocument;
import com.adobe.internal.pdftoolkit.pdf.filters.PDFFilter;
import com.adobe.internal.pdftoolkit.pdf.filters.PDFFilterFlate;
import com.adobe.internal.pdftoolkit.pdf.filters.PDFFilterList;
import com.adobe.internal.pdftoolkit.pdf.graphics.font.impl.AdobeGlyphList;
import com.adobe.internal.pdftoolkit.pdf.graphics.font.impl.CMapResourceBuilder;
import com.adobe.internal.pdftoolkit.pdf.graphics.font.impl.PDFFontUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Stack;
/*
* This class specifies class file version 49.0 but uses Java 6 signatures. Assumed Java 6.
*/
public class PDFToUnicodeCMap
extends PDFCosStream {
private static final byte[] prefixBytes = "/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo\n<< /Registry ( Adobe )\n/Ordering ( UCS )\n/Supplement 0\n>> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n< 0000 >< FFFF >\nendcodespacerange\n".getBytes();
private static byte[] suffixBytes = "endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n".getBytes();
private HashSet<CMapCodeMapping> toUnicodeMaps;
private PDFToUnicodeCMap(CosObject cosObject, boolean empty) throws PDFInvalidDocumentException, PDFIOException, PDFSecurityException {
super(cosObject);
if (empty) {
this.toUnicodeMaps = new HashSet();
return;
}
InputByteStream ibs = null;
try {
ibs = this.getCosStream().getStreamDecoded();
this.toUnicodeMaps = CMapResourceBuilder.parseToUnicodeMap(ibs.toInputStream(), cosObject.getDocument().getOptions().skipCorruptObjects());
}
catch (PDFParseException e) {
throw new PDFInvalidDocumentException((Throwable)e);
}
catch (IOException e) {
throw new PDFIOException((Throwable)e);
}
finally {
if (ibs != null) {
try {
ibs.close();
}
catch (IOException e) {
throw new PDFIOException("Unable to close stream.", (Throwable)e);
}
}
}
}
static PDFToUnicodeCMap getInstance(CosObject cosObject) throws PDFInvalidDocumentException, PDFIOException, PDFSecurityException {
if (PDFCosObject.checkNullCosObject(cosObject) == null) {
return null;
}
PDFToUnicodeCMap pdfObject = PDFCosObject.getCachedInstance(cosObject, PDFToUnicodeCMap.class);
if (pdfObject == null) {
try {
pdfObject = new PDFToUnicodeCMap(cosObject, false);
}
catch (Exception e) {
if (cosObject.getDocument().getOptions().skipCorruptObjects()) {
return null;
}
throw new PDFInvalidDocumentException((Throwable)e);
}
}
return pdfObject;
}
public static PDFToUnicodeCMap newInstance(PDFDocument pdfDocument) throws PDFInvalidDocumentException, PDFIOException, PDFSecurityException {
CosStream cosObject = PDFCosObject.newCosStream(pdfDocument);
return new PDFToUnicodeCMap((CosObject)cosObject, true);
}
public String toUnicode(ASString string, boolean twoByteChars) {
String result = null;
if (twoByteChars) {
char[] chars = string.getChars();
result = this.toUnicode(chars, 0, chars.length);
} else {
byte[] bytes = string.getBytes();
result = this.toUnicode(bytes, 0, bytes.length);
}
return result;
}
public String toUnicode(byte[] bytes, int start, int length) {
if (length > 0 && bytes != null) {
StringBuilder strBuf = new StringBuilder(bytes.length);
for (int i = start; i < length; ++i) {
strBuf.append(this.toUnicode(bytes[i] & 255));
}
return strBuf.toString();
}
return null;
}
public String toUnicode(char[] chars, int start, int length) {
if (length > 0 && chars != null) {
StringBuilder strBuf = new StringBuilder(chars.length);
for (int i = start; i < length; ++i) {
strBuf.append(this.toUnicode(chars[i]));
}
return strBuf.toString();
}
return null;
}
public char[] toUnicode(int charCode) {
char[] unicodeChar = new char[]{'\ufffd'};
if (this.toUnicodeMaps != null) {
for (CMapCodeMapping codeMap : this.toUnicodeMaps) {
if (!codeMap.contains(charCode)) continue;
if (codeMap.isHexData(charCode)) {
return codeMap.getHexDataAsCharArray(charCode);
}
AdobeGlyphList glyphList = AdobeGlyphList.get();
ASName glyphName = ASName.create((String)codeMap.getCharName(charCode));
return glyphList.toUnicode(glyphName);
}
}
return unicodeChar;
}
public int fromUnicode(char unicode) {
int charCodeDefault = -1;
if (this.toUnicodeMaps != null) {
for (CMapCodeMapping codeMap : this.toUnicodeMaps) {
int start = codeMap.getStartCode();
int end = codeMap.getEndCode();
for (int charCode = start; charCode <= end; ++charCode) {
char[] chars = null;
if (codeMap.isHexData(charCode)) {
chars = codeMap.getHexDataAsCharArray(charCode);
} else {
AdobeGlyphList glyphList = AdobeGlyphList.get();
ASName cmGlyphName = ASName.create((String)codeMap.getCharName(charCode));
chars = glyphList.toUnicode(cmGlyphName);
}
if (chars.length != 1 || chars[0] != unicode) continue;
return charCode;
}
}
}
return charCodeDefault;
}
PDFToUnicodeCMap getUseCMap() throws PDFInvalidDocumentException, PDFIOException, PDFSecurityException {
return PDFToUnicodeCMap.getInstance(this.getDictionaryCosObjectValue(ASName.k_UseCMap));
}
public void mergeToUnicodeCMap(ArrayList<CMapCodeMapping> toUnicodeCMap) {
if (toUnicodeCMap != null) {
this.toUnicodeMaps.addAll(toUnicodeCMap);
}
}
public Locale getLocale() {
for (CMapCodeMapping mapping : this.toUnicodeMaps) {
int startCode = mapping.startCode;
int endCode = mapping.endCode;
for (int i = startCode; i <= endCode; ++i) {
byte[] unicodeBytes;
Locale locale;
if (!mapping.isHexData(i) || (locale = PDFFontUtils.getLocaleFromUnicode(unicodeBytes = mapping.getHexData(i))) == null) continue;
return locale;
}
}
return null;
}
private Stack<CMapCodeMapping> optimize(CMapCodeMapping[] mappings) {
Stack<CMapCodeMapping> stack = new Stack<CMapCodeMapping>();
for (int i = 0; i < mappings.length; ++i) {
CMapCodeMapping current = mappings[i];
if (i == 0) {
stack.push(current);
continue;
}
CMapCodeMapping temp = stack.peek();
if (temp.equals(current)) continue;
if (this.byteRangesEqual(temp, current) && current.getStartCode() - temp.getEndCode() == 1) {
ArrayList currentDataArray = current.getData();
ArrayList tempDataArray = temp.getData();
if (currentDataArray.size() == 1 && tempDataArray.size() == 1) {
char[] currentUnicode;
char[] tempUnicode;
Object tempData = tempDataArray.get(0);
Object currentData = currentDataArray.get(0);
if (tempData instanceof byte[] && currentData instanceof byte[] && ((byte[])tempData)[0] <= 255 - current.getEndCode() + temp.getStartCode() && (currentUnicode = current.toUnicode(currentData)).length == (tempUnicode = temp.toUnicode(tempData)).length && currentUnicode[0] - tempUnicode[0] == 1 + temp.getEndCode() - temp.getStartCode()) {
boolean equal = true;
for (int idx = 1; idx < currentUnicode.length; ++idx) {
if (currentUnicode[idx] == tempUnicode[idx]) continue;
equal = false;
break;
}
if (equal) {
stack.pop();
stack.push(new CMapCodeMapping(temp.getStartCode(), current.getEndCode(), tempDataArray));
continue;
}
}
}
}
stack.push(current);
}
return stack;
}
private boolean byteRangesEqual(CMapCodeMapping first, CMapCodeMapping second) {
return first.getEndCode() / 256 == second.getStartCode() / 256;
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
public void writeToStream() throws IOException, PDFIOException, PDFSecurityException, PDFInvalidDocumentException {
OutputByteStream outStream = this.getStreamManager().getOutputByteStreamClearDocument(ByteWriterFactory.Fixed.GROWABLE, -1);
PDFFilterFlate filter = PDFFilterFlate.newInstance(this.getPDFDocument(), null);
PDFFilterList filterList = PDFFilterList.newInstance(this.getPDFDocument());
filterList.add(filter);
this.setOutputFilters(filterList);
Object[] mappings = new CMapCodeMapping[this.toUnicodeMaps.size()];
this.toUnicodeMaps.toArray(mappings);
Arrays.sort(mappings);
outStream.write(prefixBytes);
Stack<CMapCodeMapping> stack = this.optimize((CMapCodeMapping[])mappings);
this.writeRangeToStream(outStream, stack);
outStream.write(suffixBytes);
InputByteStream ibs = null;
InputStream is = null;
try {
ibs = outStream.closeAndConvert();
is = ibs.toInputStream();
this.setStreamData(is);
}
finally {
try {
if (is != null) {
is.close();
}
}
finally {
if (ibs != null) {
ibs.close();
}
}
}
}
private void writeRangeToStream(OutputByteStream outStream, List<CMapCodeMapping> list) throws IOException {
int rangesWritten = 0;
while (rangesWritten < list.size()) {
int count = list.size() - rangesWritten < 100 ? list.size() - rangesWritten : 100;
outStream.write(("" + count + " beginbfrange").getBytes());
for (int i = 0; i < count; ++i) {
outStream.write(("\n" + list.get(rangesWritten).toString()).getBytes());
++rangesWritten;
}
outStream.write("\nendbfrange\n".getBytes());
}
}
public HashSet<CMapCodeMapping> getCmapCodeMappings() {
return this.toUnicodeMaps;
}
public static class CMapCodeMapping
implements Comparable {
private final int startCode;
private final int endCode;
private final ArrayList data;
public CMapCodeMapping(int startCode) {
this.startCode = startCode;
this.endCode = startCode;
this.data = new ArrayList();
}
public CMapCodeMapping(int startCode, int endCode) {
this.startCode = startCode;
this.endCode = endCode;
this.data = new ArrayList();
}
public CMapCodeMapping(int startCode, int endCode, ArrayList data) {
this(startCode, endCode);
this.data.addAll(data);
}
public boolean equals(CMapCodeMapping codeMap) {
if (this.startCode == codeMap.startCode && this.endCode == codeMap.endCode && this.compare(this.data, codeMap.data)) {
return true;
}
return false;
}
private boolean compare(ArrayList a, ArrayList b) {
ListIterator e1 = a.listIterator();
ListIterator e2 = b.listIterator();
if (e1.hasNext() && e2.hasNext()) {
Object o1 = e1.next();
Object o2 = e2.next();
if (o1 == null) {
return o2 == null;
}
if (o1 instanceof byte[] && o2 instanceof byte[]) {
return Arrays.equals((byte[])o1, (byte[])o2);
}
return o1.equals(o2);
}
return !e1.hasNext() && !e2.hasNext();
}
public int hashCode() {
return this.startCode + this.endCode << 2;
}
public void addHexData(byte[] charDesc) {
this.data.add(charDesc);
}
public void addCharName(String charName) {
this.data.add(charName);
}
public int getStartCode() {
return this.startCode;
}
public int getEndCode() {
return this.endCode;
}
public boolean contains(int charCode) {
return charCode >= this.startCode && charCode <= this.endCode;
}
public boolean isHexData(int charCode) {
if (this.data.size() == 1) {
return this.data.get(0) instanceof byte[];
}
return this.data.get(charCode - this.startCode) instanceof byte[];
}
boolean isCharName(int charCode) {
return !this.isHexData(charCode);
}
byte[] getHexData(int charCode) {
if (this.data.size() == 1) {
return (byte[])this.data.get(0);
}
return (byte[])this.data.get(charCode - this.startCode);
}
public char[] getHexDataAsCharArray(int charCode) {
byte[] bytes;
if (this.data.size() == 1) {
bytes = (byte[])this.data.get(0);
if (charCode > this.startCode) {
byte[] newBytes = new byte[bytes.length];
System.arraycopy(bytes, 0, newBytes, 0, bytes.length);
int lowByte = 255 & bytes[bytes.length - 1];
newBytes[bytes.length - 1] = (byte)((lowByte += charCode - this.startCode) & 255);
bytes = newBytes;
}
} else {
bytes = (byte[])this.data.get(charCode - this.startCode);
}
return CMapCodeMapping.getCharsFromBytes(bytes);
}
private static char[] getCharsFromBytes(byte[] bytes) {
try {
return new String(bytes, "UTF-16BE").toCharArray();
}
catch (UnsupportedEncodingException e) {
char[] chars = null;
if (bytes != null && (chars = new char[(bytes.length + 1) / 2]).length != 0) {
int i;
for (i = 0; i < chars.length - 1; ++i) {
chars[i] = (char)(((bytes[i * 2] & 255) << 8) + (bytes[i * 2 + 1] & 255));
}
chars[chars.length - 1] = bytes.length % 2 == 0 ? (char)(((bytes[i * 2] & 255) << 8) + (bytes[i * 2 + 1] & 255)) : (char)(bytes[bytes.length - 1] & 255);
}
return chars;
}
}
public String getCharName(int charCode) {
if (this.data.size() == 1) {
return (String)this.data.get(0);
}
return (String)this.data.get(charCode - this.startCode);
}
public int compareTo(CMapCodeMapping codeMap) {
int thisVal = this.startCode;
int otherVal = codeMap.startCode;
return thisVal < otherVal ? -1 : (thisVal == otherVal ? 0 : 1);
}
public int compareTo(Object o) {
return this.compareTo((CMapCodeMapping)o);
}
public String toString() {
String startEndStr = "<" + this.getPaddedHexString(Integer.toHexString(this.startCode)) + "> <" + this.getPaddedHexString(Integer.toHexString(this.endCode)) + "> ";
StringBuilder dataStr = new StringBuilder("");
Iterator iter = this.data.iterator();
int size = this.data.size();
if (size > 1) {
dataStr.append("[");
}
while (iter.hasNext()) {
Object o = iter.next();
this.appendDataString(this.toUnicode(o), dataStr);
}
if (size > 1) {
dataStr.append("]");
}
return startEndStr + dataStr;
}
char[] toUnicode(Object o) {
if (o instanceof byte[]) {
return CMapCodeMapping.getCharsFromBytes((byte[])o);
}
if (o instanceof String) {
AdobeGlyphList glyphList = AdobeGlyphList.get();
ASName glyphName = ASName.create((String)((String)o));
return glyphList.toUnicode(glyphName);
}
throw new IllegalArgumentException("Types in data of CMapCodeMapping should be either string or byte array.");
}
private void appendDataString(char[] charArray, StringBuilder dataStr) {
dataStr.append(" <");
for (int i = 0; i < charArray.length; ++i) {
dataStr.append(this.getPaddedHexString(Integer.toHexString(charArray[i])));
}
dataStr.append(">");
}
String getPaddedHexString(String hex) {
int length = hex.length();
if (length == 1) {
return "000" + hex;
}
if (length == 2) {
return "00" + hex;
}
if (length == 3) {
return "0" + hex;
}
return hex;
}
public ArrayList getData() {
return this.data;
}
}
}