-
Notifications
You must be signed in to change notification settings - Fork 10.2k
/
Copy pathevaluator.js
3043 lines (2815 loc) · 112 KB
/
evaluator.js
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
/* Copyright 2012 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
AbortException, assert, CMapCompressionType, createPromiseCapability,
FONT_IDENTITY_MATRIX, FormatError, IDENTITY_MATRIX, info, isArrayEqual, isNum,
isString, NativeImageDecoding, OPS, stringToPDFString, TextRenderingMode,
UNSUPPORTED_FEATURES, Util, warn
} from '../shared/util';
import { CMapFactory, IdentityCMap } from './cmap';
import {
Dict, isCmd, isDict, isEOF, isName, isRef, isStream, Name
} from './primitives';
import {
ErrorFont, Font, FontFlags, getFontType, IdentityToUnicodeMap, ToUnicodeMap
} from './fonts';
import {
getEncoding, MacRomanEncoding, StandardEncoding, SymbolSetEncoding,
WinAnsiEncoding, ZapfDingbatsEncoding
} from './encodings';
import {
getNormalizedUnicodes, getUnicodeForGlyph, reverseIfRtl
} from './unicode';
import {
getSerifFonts, getStdFontMap, getSymbolsFonts
} from './standard_fonts';
import { getTilingPatternIR, Pattern } from './pattern';
import { Lexer, Parser } from './parser';
import { bidi } from './bidi';
import { ColorSpace } from './colorspace';
import { DecodeStream } from './stream';
import { getGlyphsUnicode } from './glyphlist';
import { getLookupTableFactory } from './core_utils';
import { getMetrics } from './metrics';
import { isPDFFunction } from './function';
import { JpegStream } from './jpeg_stream';
import { MurmurHash3_64 } from './murmurhash3';
import { NativeImageDecoder } from './image_utils';
import { OperatorList } from './operator_list';
import { PDFImage } from './image';
var PartialEvaluator = (function PartialEvaluatorClosure() {
const DefaultPartialEvaluatorOptions = {
forceDataSchema: false,
maxImageSize: -1,
disableFontFace: false,
nativeImageDecoderSupport: NativeImageDecoding.DECODE,
ignoreErrors: false,
isEvalSupported: true,
};
function PartialEvaluator({ pdfManager, xref, handler, pageIndex, idFactory,
fontCache, builtInCMapCache, options = null,
pdfFunctionFactory, }) {
this.pdfManager = pdfManager;
this.xref = xref;
this.handler = handler;
this.pageIndex = pageIndex;
this.idFactory = idFactory;
this.fontCache = fontCache;
this.builtInCMapCache = builtInCMapCache;
this.options = options || DefaultPartialEvaluatorOptions;
this.pdfFunctionFactory = pdfFunctionFactory;
this.fetchBuiltInCMap = async (name) => {
if (this.builtInCMapCache.has(name)) {
return this.builtInCMapCache.get(name);
}
const data = await this.handler.sendWithPromise('FetchBuiltInCMap',
{ name, });
if (data.compressionType !== CMapCompressionType.NONE) {
// Given the size of uncompressed CMaps, only cache compressed ones.
this.builtInCMapCache.set(name, data);
}
return data;
};
}
// Trying to minimize Date.now() usage and check every 100 time
var TIME_SLOT_DURATION_MS = 20;
var CHECK_TIME_EVERY = 100;
function TimeSlotManager() {
this.reset();
}
TimeSlotManager.prototype = {
check: function TimeSlotManager_check() {
if (++this.checked < CHECK_TIME_EVERY) {
return false;
}
this.checked = 0;
return this.endTime <= Date.now();
},
reset: function TimeSlotManager_reset() {
this.endTime = Date.now() + TIME_SLOT_DURATION_MS;
this.checked = 0;
},
};
// Convert PDF blend mode names to HTML5 blend mode names.
function normalizeBlendMode(value) {
if (!isName(value)) {
return 'source-over';
}
switch (value.name) {
case 'Normal':
case 'Compatible':
return 'source-over';
case 'Multiply':
return 'multiply';
case 'Screen':
return 'screen';
case 'Overlay':
return 'overlay';
case 'Darken':
return 'darken';
case 'Lighten':
return 'lighten';
case 'ColorDodge':
return 'color-dodge';
case 'ColorBurn':
return 'color-burn';
case 'HardLight':
return 'hard-light';
case 'SoftLight':
return 'soft-light';
case 'Difference':
return 'difference';
case 'Exclusion':
return 'exclusion';
case 'Hue':
return 'hue';
case 'Saturation':
return 'saturation';
case 'Color':
return 'color';
case 'Luminosity':
return 'luminosity';
}
warn('Unsupported blend mode: ' + value.name);
return 'source-over';
}
var deferred = Promise.resolve();
var TILING_PATTERN = 1, SHADING_PATTERN = 2;
PartialEvaluator.prototype = {
clone(newOptions = DefaultPartialEvaluatorOptions) {
var newEvaluator = Object.create(this);
newEvaluator.options = newOptions;
return newEvaluator;
},
hasBlendModes: function PartialEvaluator_hasBlendModes(resources) {
if (!isDict(resources)) {
return false;
}
var processed = Object.create(null);
if (resources.objId) {
processed[resources.objId] = true;
}
var nodes = [resources], xref = this.xref;
while (nodes.length) {
var key, i, ii;
var node = nodes.shift();
// First check the current resources for blend modes.
var graphicStates = node.get('ExtGState');
if (isDict(graphicStates)) {
var graphicStatesKeys = graphicStates.getKeys();
for (i = 0, ii = graphicStatesKeys.length; i < ii; i++) {
key = graphicStatesKeys[i];
var graphicState = graphicStates.get(key);
var bm = graphicState.get('BM');
if (isName(bm) && bm.name !== 'Normal') {
return true;
}
}
}
// Descend into the XObjects to look for more resources and blend modes.
var xObjects = node.get('XObject');
if (!isDict(xObjects)) {
continue;
}
var xObjectsKeys = xObjects.getKeys();
for (i = 0, ii = xObjectsKeys.length; i < ii; i++) {
key = xObjectsKeys[i];
var xObject = xObjects.getRaw(key);
if (isRef(xObject)) {
if (processed[xObject.toString()]) {
// The XObject has already been processed, and by avoiding a
// redundant `xref.fetch` we can *significantly* reduce the load
// time for badly generated PDF files (fixes issue6961.pdf).
continue;
}
xObject = xref.fetch(xObject);
}
if (!isStream(xObject)) {
continue;
}
if (xObject.dict.objId) {
if (processed[xObject.dict.objId]) {
// stream has objId and is processed already
continue;
}
processed[xObject.dict.objId] = true;
}
var xResources = xObject.dict.get('Resources');
// Checking objId to detect an infinite loop.
if (isDict(xResources) &&
(!xResources.objId || !processed[xResources.objId])) {
nodes.push(xResources);
if (xResources.objId) {
processed[xResources.objId] = true;
}
}
}
}
return false;
},
buildFormXObject: function PartialEvaluator_buildFormXObject(resources,
xobj, smask,
operatorList,
task,
initialState) {
var dict = xobj.dict;
var matrix = dict.getArray('Matrix');
var bbox = dict.getArray('BBox');
if (Array.isArray(bbox) && bbox.length === 4) {
bbox = Util.normalizeRect(bbox);
} else {
bbox = null;
}
var group = dict.get('Group');
if (group) {
var groupOptions = {
matrix,
bbox,
smask,
isolated: false,
knockout: false,
};
var groupSubtype = group.get('S');
var colorSpace = null;
if (isName(groupSubtype, 'Transparency')) {
groupOptions.isolated = (group.get('I') || false);
groupOptions.knockout = (group.get('K') || false);
if (group.has('CS')) {
colorSpace = ColorSpace.parse(group.get('CS'), this.xref, resources,
this.pdfFunctionFactory);
}
}
if (smask && smask.backdrop) {
colorSpace = colorSpace || ColorSpace.singletons.rgb;
smask.backdrop = colorSpace.getRgb(smask.backdrop, 0);
}
operatorList.addOp(OPS.beginGroup, [groupOptions]);
}
operatorList.addOp(OPS.paintFormXObjectBegin, [matrix, bbox]);
return this.getOperatorList({
stream: xobj,
task,
resources: dict.get('Resources') || resources,
operatorList,
initialState,
}).then(function () {
operatorList.addOp(OPS.paintFormXObjectEnd, []);
if (group) {
operatorList.addOp(OPS.endGroup, [groupOptions]);
}
});
},
buildPaintImageXObject({ resources, image, isInline = false, operatorList,
cacheKey, imageCache,
forceDisableNativeImageDecoder = false, }) {
var dict = image.dict;
var w = dict.get('Width', 'W');
var h = dict.get('Height', 'H');
if (!(w && isNum(w)) || !(h && isNum(h))) {
warn('Image dimensions are missing, or not numbers.');
return Promise.resolve();
}
var maxImageSize = this.options.maxImageSize;
if (maxImageSize !== -1 && w * h > maxImageSize) {
warn('Image exceeded maximum allowed size and was removed.');
return Promise.resolve();
}
var imageMask = (dict.get('ImageMask', 'IM') || false);
var imgData, args;
if (imageMask) {
// This depends on a tmpCanvas being filled with the
// current fillStyle, such that processing the pixel
// data can't be done here. Instead of creating a
// complete PDFImage, only read the information needed
// for later.
var width = dict.get('Width', 'W');
var height = dict.get('Height', 'H');
var bitStrideLength = (width + 7) >> 3;
var imgArray = image.getBytes(bitStrideLength * height,
/* forceClamped = */ true);
var decode = dict.getArray('Decode', 'D');
imgData = PDFImage.createMask({
imgArray,
width,
height,
imageIsFromDecodeStream: image instanceof DecodeStream,
inverseDecode: (!!decode && decode[0] > 0),
});
imgData.cached = !!cacheKey;
args = [imgData];
operatorList.addOp(OPS.paintImageMaskXObject, args);
if (cacheKey) {
imageCache[cacheKey] = {
fn: OPS.paintImageMaskXObject,
args,
};
}
return Promise.resolve();
}
var softMask = (dict.get('SMask', 'SM') || false);
var mask = (dict.get('Mask') || false);
var SMALL_IMAGE_DIMENSIONS = 200;
// Inlining small images into the queue as RGB data
if (isInline && !softMask && !mask && !(image instanceof JpegStream) &&
(w + h) < SMALL_IMAGE_DIMENSIONS) {
let imageObj = new PDFImage({
xref: this.xref,
res: resources,
image,
isInline,
pdfFunctionFactory: this.pdfFunctionFactory,
});
// We force the use of RGBA_32BPP images here, because we can't handle
// any other kind.
imgData = imageObj.createImageData(/* forceRGBA = */ true);
operatorList.addOp(OPS.paintInlineImageXObject, [imgData]);
return Promise.resolve();
}
const nativeImageDecoderSupport = forceDisableNativeImageDecoder ?
NativeImageDecoding.NONE : this.options.nativeImageDecoderSupport;
// If there is no imageMask, create the PDFImage and a lot
// of image processing can be done here.
var objId = 'img_' + this.idFactory.createObjId();
if (nativeImageDecoderSupport !== NativeImageDecoding.NONE &&
!softMask && !mask && image instanceof JpegStream &&
NativeImageDecoder.isSupported(image, this.xref, resources,
this.pdfFunctionFactory)) {
// These JPEGs don't need any more processing so we can just send it.
return this.handler.sendWithPromise('obj', [
objId, this.pageIndex, 'JpegStream',
image.getIR(this.options.forceDataSchema)
]).then(function() {
// Only add the dependency once we know that the native JPEG decoding
// succeeded, to ensure that rendering will always complete.
operatorList.addDependency(objId);
args = [objId, w, h];
operatorList.addOp(OPS.paintJpegXObject, args);
if (cacheKey) {
imageCache[cacheKey] = {
fn: OPS.paintJpegXObject,
args,
};
}
}, (reason) => {
warn('Native JPEG decoding failed -- trying to recover: ' +
(reason && reason.message));
// Try to decode the JPEG image with the built-in decoder instead.
return this.buildPaintImageXObject({
resources,
image,
isInline,
operatorList,
cacheKey,
imageCache,
forceDisableNativeImageDecoder: true,
});
});
}
// Creates native image decoder only if a JPEG image or mask is present.
var nativeImageDecoder = null;
if (nativeImageDecoderSupport === NativeImageDecoding.DECODE &&
(image instanceof JpegStream || mask instanceof JpegStream ||
softMask instanceof JpegStream)) {
nativeImageDecoder = new NativeImageDecoder({
xref: this.xref,
resources,
handler: this.handler,
forceDataSchema: this.options.forceDataSchema,
pdfFunctionFactory: this.pdfFunctionFactory,
});
}
// Ensure that the dependency is added before the image is decoded.
operatorList.addDependency(objId);
args = [objId, w, h];
PDFImage.buildImage({
handler: this.handler,
xref: this.xref,
res: resources,
image,
isInline,
nativeDecoder: nativeImageDecoder,
pdfFunctionFactory: this.pdfFunctionFactory,
}).then((imageObj) => {
var imgData = imageObj.createImageData(/* forceRGBA = */ false);
this.handler.send('obj', [objId, this.pageIndex, 'Image', imgData],
[imgData.data.buffer]);
}).catch((reason) => {
warn('Unable to decode image: ' + reason);
this.handler.send('obj', [objId, this.pageIndex, 'Image', null]);
});
operatorList.addOp(OPS.paintImageXObject, args);
if (cacheKey) {
imageCache[cacheKey] = {
fn: OPS.paintImageXObject,
args,
};
}
return Promise.resolve();
},
handleSMask: function PartialEvaluator_handleSmask(smask, resources,
operatorList, task,
stateManager) {
var smaskContent = smask.get('G');
var smaskOptions = {
subtype: smask.get('S').name,
backdrop: smask.get('BC'),
};
// The SMask might have a alpha/luminosity value transfer function --
// we will build a map of integer values in range 0..255 to be fast.
var transferObj = smask.get('TR');
if (isPDFFunction(transferObj)) {
let transferFn = this.pdfFunctionFactory.create(transferObj);
var transferMap = new Uint8Array(256);
var tmp = new Float32Array(1);
for (var i = 0; i < 256; i++) {
tmp[0] = i / 255;
transferFn(tmp, 0, tmp, 0);
transferMap[i] = (tmp[0] * 255) | 0;
}
smaskOptions.transferMap = transferMap;
}
return this.buildFormXObject(resources, smaskContent, smaskOptions,
operatorList, task,
stateManager.state.clone());
},
handleTilingType(fn, args, resources, pattern, patternDict, operatorList,
task) {
// Create an IR of the pattern code.
let tilingOpList = new OperatorList();
// Merge the available resources, to prevent issues when the patternDict
// is missing some /Resources entries (fixes issue6541.pdf).
let resourcesArray = [patternDict.get('Resources'), resources];
let patternResources = Dict.merge(this.xref, resourcesArray);
return this.getOperatorList({
stream: pattern,
task,
resources: patternResources,
operatorList: tilingOpList,
}).then(function() {
return getTilingPatternIR({
fnArray: tilingOpList.fnArray,
argsArray: tilingOpList.argsArray,
}, patternDict, args);
}).then(function(tilingPatternIR) {
// Add the dependencies to the parent operator list so they are
// resolved before the sub operator list is executed synchronously.
operatorList.addDependencies(tilingOpList.dependencies);
operatorList.addOp(fn, tilingPatternIR);
}, (reason) => {
if (this.options.ignoreErrors) {
// Error(s) in the TilingPattern -- sending unsupported feature
// notification and allow rendering to continue.
this.handler.send('UnsupportedFeature',
{ featureId: UNSUPPORTED_FEATURES.unknown, });
warn(`handleTilingType - ignoring pattern: "${reason}".`);
return;
}
throw reason;
});
},
handleSetFont:
function PartialEvaluator_handleSetFont(resources, fontArgs, fontRef,
operatorList, task, state) {
// TODO(mack): Not needed?
var fontName;
if (fontArgs) {
fontArgs = fontArgs.slice();
fontName = fontArgs[0].name;
}
return this.loadFont(fontName, fontRef, resources).then((translated) => {
if (!translated.font.isType3Font) {
return translated;
}
return translated.loadType3Data(this, resources, operatorList, task).
then(function () {
return translated;
}).catch((reason) => {
// Error in the font data -- sending unsupported feature notification.
this.handler.send('UnsupportedFeature',
{ featureId: UNSUPPORTED_FEATURES.font, });
return new TranslatedFont('g_font_error',
new ErrorFont('Type3 font load error: ' + reason), translated.font);
});
}).then((translated) => {
state.font = translated.font;
translated.send(this.handler);
return translated.loadedName;
});
},
handleText(chars, state) {
const font = state.font;
const glyphs = font.charsToGlyphs(chars);
if (font.data) {
const isAddToPathSet = !!(state.textRenderingMode &
TextRenderingMode.ADD_TO_PATH_FLAG);
if (isAddToPathSet || state.fillColorSpace.name === 'Pattern' ||
font.disableFontFace || this.options.disableFontFace) {
PartialEvaluator.buildFontPaths(font, glyphs, this.handler);
}
}
return glyphs;
},
setGState: function PartialEvaluator_setGState(resources, gState,
operatorList, task,
stateManager) {
// This array holds the converted/processed state data.
var gStateObj = [];
var gStateKeys = gState.getKeys();
var promise = Promise.resolve();
for (var i = 0, ii = gStateKeys.length; i < ii; i++) {
let key = gStateKeys[i];
let value = gState.get(key);
switch (key) {
case 'Type':
break;
case 'LW':
case 'LC':
case 'LJ':
case 'ML':
case 'D':
case 'RI':
case 'FL':
case 'CA':
case 'ca':
gStateObj.push([key, value]);
break;
case 'Font':
promise = promise.then(() => {
return this.handleSetFont(resources, null, value[0], operatorList,
task, stateManager.state).
then(function (loadedName) {
operatorList.addDependency(loadedName);
gStateObj.push([key, [loadedName, value[1]]]);
});
});
break;
case 'BM':
gStateObj.push([key, normalizeBlendMode(value)]);
break;
case 'SMask':
if (isName(value, 'None')) {
gStateObj.push([key, false]);
break;
}
if (isDict(value)) {
promise = promise.then(() => {
return this.handleSMask(value, resources, operatorList,
task, stateManager);
});
gStateObj.push([key, true]);
} else {
warn('Unsupported SMask type');
}
break;
// Only generate info log messages for the following since
// they are unlikely to have a big impact on the rendering.
case 'OP':
case 'op':
case 'OPM':
case 'BG':
case 'BG2':
case 'UCR':
case 'UCR2':
case 'TR':
case 'TR2':
case 'HT':
case 'SM':
case 'SA':
case 'AIS':
case 'TK':
// TODO implement these operators.
info('graphic state operator ' + key);
break;
default:
info('Unknown graphic state operator ' + key);
break;
}
}
return promise.then(function () {
if (gStateObj.length > 0) {
operatorList.addOp(OPS.setGState, [gStateObj]);
}
});
},
loadFont: function PartialEvaluator_loadFont(fontName, font, resources) {
function errorFont() {
return Promise.resolve(new TranslatedFont('g_font_error',
new ErrorFont('Font ' + fontName + ' is not available'), font));
}
var fontRef, xref = this.xref;
if (font) { // Loading by ref.
if (!isRef(font)) {
throw new Error('The "font" object should be a reference.');
}
fontRef = font;
} else { // Loading by name.
var fontRes = resources.get('Font');
if (fontRes) {
fontRef = fontRes.getRaw(fontName);
} else {
warn('fontRes not available');
return errorFont();
}
}
if (!fontRef) {
warn('fontRef not available');
return errorFont();
}
if (this.fontCache.has(fontRef)) {
return this.fontCache.get(fontRef);
}
font = xref.fetchIfRef(fontRef);
if (!isDict(font)) {
return errorFont();
}
// We are holding `font.translated` references just for `fontRef`s that
// are not actually `Ref`s, but rather `Dict`s. See explanation below.
if (font.translated) {
return font.translated;
}
var fontCapability = createPromiseCapability();
var preEvaluatedFont = this.preEvaluateFont(font);
var descriptor = preEvaluatedFont.descriptor;
var fontRefIsRef = isRef(fontRef), fontID;
if (fontRefIsRef) {
fontID = fontRef.toString();
}
if (isDict(descriptor)) {
if (!descriptor.fontAliases) {
descriptor.fontAliases = Object.create(null);
}
var fontAliases = descriptor.fontAliases;
var hash = preEvaluatedFont.hash;
if (fontAliases[hash]) {
var aliasFontRef = fontAliases[hash].aliasRef;
if (fontRefIsRef && aliasFontRef &&
this.fontCache.has(aliasFontRef)) {
this.fontCache.putAlias(fontRef, aliasFontRef);
return this.fontCache.get(fontRef);
}
} else {
fontAliases[hash] = {
fontID: Font.getFontID(),
};
}
if (fontRefIsRef) {
fontAliases[hash].aliasRef = fontRef;
}
fontID = fontAliases[hash].fontID;
}
// Workaround for bad PDF generators that reference fonts incorrectly,
// where `fontRef` is a `Dict` rather than a `Ref` (fixes bug946506.pdf).
// In this case we should not put the font into `this.fontCache` (which is
// a `RefSetCache`), since it's not meaningful to use a `Dict` as a key.
//
// However, if we don't cache the font it's not possible to remove it
// when `cleanup` is triggered from the API, which causes issues on
// subsequent rendering operations (see issue7403.pdf).
// A simple workaround would be to just not hold `font.translated`
// references in this case, but this would force us to unnecessarily load
// the same fonts over and over.
//
// Instead, we cheat a bit by attempting to use a modified `fontID` as a
// key in `this.fontCache`, to allow the font to be cached.
// NOTE: This works because `RefSetCache` calls `toString()` on provided
// keys. Also, since `fontRef` is used when getting cached fonts,
// we'll not accidentally match fonts cached with the `fontID`.
if (fontRefIsRef) {
this.fontCache.put(fontRef, fontCapability.promise);
} else {
if (!fontID) {
fontID = this.idFactory.createObjId();
}
this.fontCache.put('id_' + fontID, fontCapability.promise);
}
assert(fontID, 'The "fontID" must be defined.');
// Keep track of each font we translated so the caller can
// load them asynchronously before calling display on a page.
font.loadedName = 'g_' + this.pdfManager.docId + '_f' + fontID;
font.translated = fontCapability.promise;
// TODO move promises into translate font
var translatedPromise;
try {
translatedPromise = this.translateFont(preEvaluatedFont);
} catch (e) {
translatedPromise = Promise.reject(e);
}
translatedPromise.then(function (translatedFont) {
if (translatedFont.fontType !== undefined) {
var xrefFontStats = xref.stats.fontTypes;
xrefFontStats[translatedFont.fontType] = true;
}
fontCapability.resolve(new TranslatedFont(font.loadedName,
translatedFont, font));
}).catch((reason) => {
// TODO fontCapability.reject?
// Error in the font data -- sending unsupported feature notification.
this.handler.send('UnsupportedFeature',
{ featureId: UNSUPPORTED_FEATURES.font, });
try {
// error, but it's still nice to have font type reported
var descriptor = preEvaluatedFont.descriptor;
var fontFile3 = descriptor && descriptor.get('FontFile3');
var subtype = fontFile3 && fontFile3.get('Subtype');
var fontType = getFontType(preEvaluatedFont.type,
subtype && subtype.name);
var xrefFontStats = xref.stats.fontTypes;
xrefFontStats[fontType] = true;
} catch (ex) { }
fontCapability.resolve(new TranslatedFont(font.loadedName,
new ErrorFont(reason instanceof Error ? reason.message : reason),
font));
});
return fontCapability.promise;
},
buildPath: function PartialEvaluator_buildPath(operatorList, fn, args) {
var lastIndex = operatorList.length - 1;
if (!args) {
args = [];
}
if (lastIndex < 0 ||
operatorList.fnArray[lastIndex] !== OPS.constructPath) {
operatorList.addOp(OPS.constructPath, [[fn], args]);
} else {
var opArgs = operatorList.argsArray[lastIndex];
opArgs[0].push(fn);
Array.prototype.push.apply(opArgs[1], args);
}
},
handleColorN: function PartialEvaluator_handleColorN(operatorList, fn, args,
cs, patterns,
resources, task) {
// compile tiling patterns
var patternName = args[args.length - 1];
// SCN/scn applies patterns along with normal colors
var pattern;
if (isName(patternName) &&
(pattern = patterns.get(patternName.name))) {
var dict = (isStream(pattern) ? pattern.dict : pattern);
var typeNum = dict.get('PatternType');
if (typeNum === TILING_PATTERN) {
var color = cs.base ? cs.base.getRgb(args, 0) : null;
return this.handleTilingType(fn, color, resources, pattern,
dict, operatorList, task);
} else if (typeNum === SHADING_PATTERN) {
var shading = dict.get('Shading');
var matrix = dict.getArray('Matrix');
pattern = Pattern.parseShading(shading, matrix, this.xref, resources,
this.handler, this.pdfFunctionFactory);
operatorList.addOp(fn, pattern.getIR());
return Promise.resolve();
}
return Promise.reject(new Error('Unknown PatternType: ' + typeNum));
}
// TODO shall we fail here?
operatorList.addOp(fn, args);
return Promise.resolve();
},
getOperatorList({ stream, task, resources, operatorList,
initialState = null, }) {
// Ensure that `resources`/`initialState` is correctly initialized,
// even if the provided parameter is e.g. `null`.
resources = resources || Dict.empty;
initialState = initialState || new EvalState();
if (!operatorList) {
throw new Error('getOperatorList: missing "operatorList" parameter');
}
var self = this;
var xref = this.xref;
var imageCache = Object.create(null);
var xobjs = (resources.get('XObject') || Dict.empty);
var patterns = (resources.get('Pattern') || Dict.empty);
var stateManager = new StateManager(initialState);
var preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager);
var timeSlotManager = new TimeSlotManager();
function closePendingRestoreOPS(argument) {
for (var i = 0, ii = preprocessor.savedStatesDepth; i < ii; i++) {
operatorList.addOp(OPS.restore, []);
}
}
return new Promise(function promiseBody(resolve, reject) {
var next = function (promise) {
promise.then(function () {
try {
promiseBody(resolve, reject);
} catch (ex) {
reject(ex);
}
}, reject);
};
task.ensureNotTerminated();
timeSlotManager.reset();
var stop, operation = {}, i, ii, cs;
while (!(stop = timeSlotManager.check())) {
// The arguments parsed by read() are used beyond this loop, so we
// cannot reuse the same array on each iteration. Therefore we pass
// in |null| as the initial value (see the comment on
// EvaluatorPreprocessor_read() for why).
operation.args = null;
if (!(preprocessor.read(operation))) {
break;
}
var args = operation.args;
var fn = operation.fn;
switch (fn | 0) {
case OPS.paintXObject:
// eagerly compile XForm objects
var name = args[0].name;
if (name && imageCache[name] !== undefined) {
operatorList.addOp(imageCache[name].fn, imageCache[name].args);
args = null;
continue;
}
next(new Promise(function(resolveXObject, rejectXObject) {
if (!name) {
throw new FormatError('XObject must be referred to by name.');
}
let xobj = xobjs.get(name);
if (!xobj) {
operatorList.addOp(fn, args);
resolveXObject();
return;
}
if (!isStream(xobj)) {
throw new FormatError('XObject should be a stream');
}
let type = xobj.dict.get('Subtype');
if (!isName(type)) {
throw new FormatError('XObject should have a Name subtype');
}
if (type.name === 'Form') {
stateManager.save();
self.buildFormXObject(resources, xobj, null, operatorList,
task, stateManager.state.clone()).
then(function() {
stateManager.restore();
resolveXObject();
}, rejectXObject);
return;
} else if (type.name === 'Image') {
self.buildPaintImageXObject({
resources,
image: xobj,
operatorList,
cacheKey: name,
imageCache,
}).then(resolveXObject, rejectXObject);
return;
} else if (type.name === 'PS') {
// PostScript XObjects are unused when viewing documents.
// See section 4.7.1 of Adobe's PDF reference.
info('Ignored XObject subtype PS');
} else {
throw new FormatError(
`Unhandled XObject subtype ${type.name}`);
}
resolveXObject();
}).catch(function(reason) {
if (self.options.ignoreErrors) {
// Error(s) in the XObject -- sending unsupported feature
// notification and allow rendering to continue.
self.handler.send('UnsupportedFeature',
{ featureId: UNSUPPORTED_FEATURES.unknown, });
warn(`getOperatorList - ignoring XObject: "${reason}".`);
return;
}
throw reason;
}));
return;
case OPS.setFont:
var fontSize = args[1];
// eagerly collect all fonts
next(self.handleSetFont(resources, args, null, operatorList,
task, stateManager.state).
then(function (loadedName) {
operatorList.addDependency(loadedName);
operatorList.addOp(OPS.setFont, [loadedName, fontSize]);
}));
return;
case OPS.endInlineImage:
var cacheKey = args[0].cacheKey;
if (cacheKey) {
var cacheEntry = imageCache[cacheKey];
if (cacheEntry !== undefined) {
operatorList.addOp(cacheEntry.fn, cacheEntry.args);
args = null;
continue;
}
}
next(self.buildPaintImageXObject({
resources,
image: args[0],
isInline: true,
operatorList,
cacheKey,
imageCache,
}));
return;
case OPS.showText: