-
Notifications
You must be signed in to change notification settings - Fork 10.1k
/
annotation.js
3350 lines (2956 loc) · 96.9 KB
/
annotation.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 {
AnnotationActionEventType,
AnnotationBorderStyleType,
AnnotationFieldFlag,
AnnotationFlag,
AnnotationReplyType,
AnnotationType,
assert,
escapeString,
getModificationDate,
isAscii,
OPS,
RenderingIntentFlag,
shadow,
stringToPDFString,
stringToUTF16BEString,
unreachable,
Util,
warn,
} from "../shared/util.js";
import { collectActions, getInheritableProperty } from "./core_utils.js";
import {
createDefaultAppearance,
parseDefaultAppearance,
} from "./default_appearance.js";
import { Dict, isName, Name, Ref, RefSet } from "./primitives.js";
import { BaseStream } from "./base_stream.js";
import { bidi } from "./bidi.js";
import { Catalog } from "./catalog.js";
import { ColorSpace } from "./colorspace.js";
import { FileSpec } from "./file_spec.js";
import { ObjectLoader } from "./object_loader.js";
import { OperatorList } from "./operator_list.js";
import { StringStream } from "./stream.js";
import { writeDict } from "./writer.js";
import { XFAFactory } from "./xfa/factory.js";
// Represent the percentage of the height of a single-line field over
// the font size.
// Acrobat seems to use this value.
const LINE_FACTOR = 1.35;
class AnnotationFactory {
/**
* Create an `Annotation` object of the correct type for the given reference
* to an annotation dictionary. This yields a promise that is resolved when
* the `Annotation` object is constructed.
*
* @param {XRef} xref
* @param {Object} ref
* @param {PDFManager} pdfManager
* @param {Object} idFactory
* @param {boolean} collectFields
* @returns {Promise} A promise that is resolved with an {Annotation}
* instance.
*/
static create(xref, ref, pdfManager, idFactory, collectFields) {
return Promise.all([
pdfManager.ensureCatalog("acroForm"),
// Only necessary to prevent the `pdfManager.docBaseUrl`-getter, used
// with certain Annotations, from throwing and thus breaking parsing:
pdfManager.ensureCatalog("baseUrl"),
pdfManager.ensureDoc("xfaDatasets"),
collectFields ? this._getPageIndex(xref, ref, pdfManager) : -1,
]).then(([acroForm, baseUrl, xfaDatasets, pageIndex]) =>
pdfManager.ensure(this, "_create", [
xref,
ref,
pdfManager,
idFactory,
acroForm,
xfaDatasets,
collectFields,
pageIndex,
])
);
}
/**
* @private
*/
static _create(
xref,
ref,
pdfManager,
idFactory,
acroForm,
xfaDatasets,
collectFields,
pageIndex = -1
) {
const dict = xref.fetchIfRef(ref);
if (!(dict instanceof Dict)) {
return undefined;
}
const id =
ref instanceof Ref ? ref.toString() : `annot_${idFactory.createObjId()}`;
// Determine the annotation's subtype.
let subtype = dict.get("Subtype");
subtype = subtype instanceof Name ? subtype.name : null;
// Return the right annotation object based on the subtype and field type.
const parameters = {
xref,
ref,
dict,
subtype,
id,
pdfManager,
acroForm: acroForm instanceof Dict ? acroForm : Dict.empty,
xfaDatasets,
collectFields,
pageIndex,
};
switch (subtype) {
case "Link":
return new LinkAnnotation(parameters);
case "Text":
return new TextAnnotation(parameters);
case "Widget":
let fieldType = getInheritableProperty({ dict, key: "FT" });
fieldType = fieldType instanceof Name ? fieldType.name : null;
switch (fieldType) {
case "Tx":
return new TextWidgetAnnotation(parameters);
case "Btn":
return new ButtonWidgetAnnotation(parameters);
case "Ch":
return new ChoiceWidgetAnnotation(parameters);
case "Sig":
return new SignatureWidgetAnnotation(parameters);
}
warn(
`Unimplemented widget field type "${fieldType}", ` +
"falling back to base field type."
);
return new WidgetAnnotation(parameters);
case "Popup":
return new PopupAnnotation(parameters);
case "FreeText":
return new FreeTextAnnotation(parameters);
case "Line":
return new LineAnnotation(parameters);
case "Square":
return new SquareAnnotation(parameters);
case "Circle":
return new CircleAnnotation(parameters);
case "PolyLine":
return new PolylineAnnotation(parameters);
case "Polygon":
return new PolygonAnnotation(parameters);
case "Caret":
return new CaretAnnotation(parameters);
case "Ink":
return new InkAnnotation(parameters);
case "Highlight":
return new HighlightAnnotation(parameters);
case "Underline":
return new UnderlineAnnotation(parameters);
case "Squiggly":
return new SquigglyAnnotation(parameters);
case "StrikeOut":
return new StrikeOutAnnotation(parameters);
case "Stamp":
return new StampAnnotation(parameters);
case "FileAttachment":
return new FileAttachmentAnnotation(parameters);
default:
if (!collectFields) {
if (!subtype) {
warn("Annotation is missing the required /Subtype.");
} else {
warn(
`Unimplemented annotation type "${subtype}", ` +
"falling back to base annotation."
);
}
}
return new Annotation(parameters);
}
}
static async _getPageIndex(xref, ref, pdfManager) {
try {
const annotDict = await xref.fetchIfRefAsync(ref);
if (!(annotDict instanceof Dict)) {
return -1;
}
const pageRef = annotDict.getRaw("P");
if (!(pageRef instanceof Ref)) {
return -1;
}
const pageIndex = await pdfManager.ensureCatalog("getPageIndex", [
pageRef,
]);
return pageIndex;
} catch (ex) {
warn(`_getPageIndex: "${ex}".`);
return -1;
}
}
}
function getRgbColor(color, defaultColor = new Uint8ClampedArray(3)) {
if (!Array.isArray(color)) {
return defaultColor;
}
const rgbColor = defaultColor || new Uint8ClampedArray(3);
switch (color.length) {
case 0: // Transparent, which we indicate with a null value
return null;
case 1: // Convert grayscale to RGB
ColorSpace.singletons.gray.getRgbItem(color, 0, rgbColor, 0);
return rgbColor;
case 3: // Convert RGB percentages to RGB
ColorSpace.singletons.rgb.getRgbItem(color, 0, rgbColor, 0);
return rgbColor;
case 4: // Convert CMYK to RGB
ColorSpace.singletons.cmyk.getRgbItem(color, 0, rgbColor, 0);
return rgbColor;
default:
return defaultColor;
}
}
function getQuadPoints(dict, rect) {
if (!dict.has("QuadPoints")) {
return null;
}
// The region is described as a number of quadrilaterals.
// Each quadrilateral must consist of eight coordinates.
const quadPoints = dict.getArray("QuadPoints");
if (
!Array.isArray(quadPoints) ||
quadPoints.length === 0 ||
quadPoints.length % 8 > 0
) {
return null;
}
const quadPointsLists = [];
for (let i = 0, ii = quadPoints.length / 8; i < ii; i++) {
// Each series of eight numbers represents the coordinates for one
// quadrilateral in the order [x1, y1, x2, y2, x3, y3, x4, y4].
// Convert this to an array of objects with x and y coordinates.
quadPointsLists.push([]);
for (let j = i * 8, jj = i * 8 + 8; j < jj; j += 2) {
const x = quadPoints[j];
const y = quadPoints[j + 1];
// The quadpoints should be ignored if any coordinate in the array
// lies outside the region specified by the rectangle. The rectangle
// can be `null` for markup annotations since their rectangle may be
// incorrect (fixes bug 1538111).
if (
rect !== null &&
(x < rect[0] || x > rect[2] || y < rect[1] || y > rect[3])
) {
return null;
}
quadPointsLists[i].push({ x, y });
}
}
// The PDF specification states in section 12.5.6.10 (figure 64) that the
// order of the quadpoints should be bottom left, bottom right, top right
// and top left. However, in practice PDF files use a different order,
// namely bottom left, bottom right, top left and top right (this is also
// mentioned on https://github.com/highkite/pdfAnnotate#QuadPoints), so
// this is the actual order we should work with. However, the situation is
// even worse since Adobe's own applications and other applications violate
// the specification and create annotations with other orders, namely top
// left, top right, bottom left and bottom right or even top left, top right,
// bottom right and bottom left. To avoid inconsistency and broken rendering,
// we normalize all lists to put the quadpoints in the same standard order
// (see https://stackoverflow.com/a/10729881).
return quadPointsLists.map(quadPointsList => {
const [minX, maxX, minY, maxY] = quadPointsList.reduce(
([mX, MX, mY, MY], quadPoint) => [
Math.min(mX, quadPoint.x),
Math.max(MX, quadPoint.x),
Math.min(mY, quadPoint.y),
Math.max(MY, quadPoint.y),
],
[Number.MAX_VALUE, Number.MIN_VALUE, Number.MAX_VALUE, Number.MIN_VALUE]
);
return [
{ x: minX, y: maxY },
{ x: maxX, y: maxY },
{ x: minX, y: minY },
{ x: maxX, y: minY },
];
});
}
function getTransformMatrix(rect, bbox, matrix) {
// 12.5.5: Algorithm: Appearance streams
const [minX, minY, maxX, maxY] = Util.getAxialAlignedBoundingBox(
bbox,
matrix
);
if (minX === maxX || minY === maxY) {
// From real-life file, bbox was [0, 0, 0, 0]. In this case,
// just apply the transform for rect
return [1, 0, 0, 1, rect[0], rect[1]];
}
const xRatio = (rect[2] - rect[0]) / (maxX - minX);
const yRatio = (rect[3] - rect[1]) / (maxY - minY);
return [
xRatio,
0,
0,
yRatio,
rect[0] - minX * xRatio,
rect[1] - minY * yRatio,
];
}
class Annotation {
constructor(params) {
const dict = params.dict;
this.setTitle(dict.get("T"));
this.setContents(dict.get("Contents"));
this.setModificationDate(dict.get("M"));
this.setFlags(dict.get("F"));
this.setRectangle(dict.getArray("Rect"));
this.setColor(dict.getArray("C"));
this.setBorderStyle(dict);
this.setAppearance(dict);
this.setBorderAndBackgroundColors(dict.get("MK"));
this._streams = [];
if (this.appearance) {
this._streams.push(this.appearance);
}
// Expose public properties using a data object.
this.data = {
annotationFlags: this.flags,
borderStyle: this.borderStyle,
color: this.color,
backgroundColor: this.backgroundColor,
borderColor: this.borderColor,
contentsObj: this._contents,
hasAppearance: !!this.appearance,
id: params.id,
modificationDate: this.modificationDate,
rect: this.rectangle,
subtype: params.subtype,
hasOwnCanvas: false,
};
if (params.collectFields) {
// Fields can act as container for other fields and have
// some actions even if no Annotation inherit from them.
// Those fields can be referenced by CO (calculation order).
const kids = dict.get("Kids");
if (Array.isArray(kids)) {
const kidIds = [];
for (const kid of kids) {
if (kid instanceof Ref) {
kidIds.push(kid.toString());
}
}
if (kidIds.length !== 0) {
this.data.kidIds = kidIds;
}
}
this.data.actions = collectActions(
params.xref,
dict,
AnnotationActionEventType
);
this.data.fieldName = this._constructFieldName(dict);
this.data.pageIndex = params.pageIndex;
}
this._fallbackFontDict = null;
}
/**
* @private
*/
_hasFlag(flags, flag) {
return !!(flags & flag);
}
/**
* @private
*/
_isViewable(flags) {
return (
!this._hasFlag(flags, AnnotationFlag.INVISIBLE) &&
!this._hasFlag(flags, AnnotationFlag.NOVIEW)
);
}
/**
* @private
*/
_isPrintable(flags) {
return (
this._hasFlag(flags, AnnotationFlag.PRINT) &&
!this._hasFlag(flags, AnnotationFlag.INVISIBLE)
);
}
/**
* Check if the annotation must be displayed by taking into account
* the value found in the annotationStorage which may have been set
* through JS.
*
* @public
* @memberof Annotation
* @param {AnnotationStorage} [annotationStorage] - Storage for annotation
*/
mustBeViewed(annotationStorage) {
const storageEntry =
annotationStorage && annotationStorage.get(this.data.id);
if (storageEntry && storageEntry.hidden !== undefined) {
return !storageEntry.hidden;
}
return this.viewable && !this._hasFlag(this.flags, AnnotationFlag.HIDDEN);
}
/**
* Check if the annotation must be printed by taking into account
* the value found in the annotationStorage which may have been set
* through JS.
*
* @public
* @memberof Annotation
* @param {AnnotationStorage} [annotationStorage] - Storage for annotation
*/
mustBePrinted(annotationStorage) {
const storageEntry =
annotationStorage && annotationStorage.get(this.data.id);
if (storageEntry && storageEntry.print !== undefined) {
return storageEntry.print;
}
return this.printable;
}
/**
* @type {boolean}
*/
get viewable() {
if (this.data.quadPoints === null) {
return false;
}
if (this.flags === 0) {
return true;
}
return this._isViewable(this.flags);
}
/**
* @type {boolean}
*/
get printable() {
if (this.data.quadPoints === null) {
return false;
}
if (this.flags === 0) {
return false;
}
return this._isPrintable(this.flags);
}
/**
* @private
*/
_parseStringHelper(data) {
const str = typeof data === "string" ? stringToPDFString(data) : "";
const dir = str && bidi(str).dir === "rtl" ? "rtl" : "ltr";
return { str, dir };
}
/**
* Set the title.
*
* @param {string} title - The title of the annotation, used e.g. with
* PopupAnnotations.
*/
setTitle(title) {
this._title = this._parseStringHelper(title);
}
/**
* Set the contents.
*
* @param {string} contents - Text to display for the annotation or, if the
* type of annotation does not display text, a
* description of the annotation's contents
*/
setContents(contents) {
this._contents = this._parseStringHelper(contents);
}
/**
* Set the modification date.
*
* @public
* @memberof Annotation
* @param {string} modificationDate - PDF date string that indicates when the
* annotation was last modified
*/
setModificationDate(modificationDate) {
this.modificationDate =
typeof modificationDate === "string" ? modificationDate : null;
}
/**
* Set the flags.
*
* @public
* @memberof Annotation
* @param {number} flags - Unsigned 32-bit integer specifying annotation
* characteristics
* @see {@link shared/util.js}
*/
setFlags(flags) {
this.flags = Number.isInteger(flags) && flags > 0 ? flags : 0;
}
/**
* Check if a provided flag is set.
*
* @public
* @memberof Annotation
* @param {number} flag - Hexadecimal representation for an annotation
* characteristic
* @returns {boolean}
* @see {@link shared/util.js}
*/
hasFlag(flag) {
return this._hasFlag(this.flags, flag);
}
/**
* Set the rectangle.
*
* @public
* @memberof Annotation
* @param {Array} rectangle - The rectangle array with exactly four entries
*/
setRectangle(rectangle) {
if (Array.isArray(rectangle) && rectangle.length === 4) {
this.rectangle = Util.normalizeRect(rectangle);
} else {
this.rectangle = [0, 0, 0, 0];
}
}
/**
* Set the color and take care of color space conversion.
* The default value is black, in RGB color space.
*
* @public
* @memberof Annotation
* @param {Array} color - The color array containing either 0
* (transparent), 1 (grayscale), 3 (RGB) or
* 4 (CMYK) elements
*/
setColor(color) {
this.color = getRgbColor(color);
}
/**
* Set the color for background and border if any.
* The default values are transparent.
*
* @public
* @memberof Annotation
* @param {Dict} mk - The MK dictionary
*/
setBorderAndBackgroundColors(mk) {
if (mk instanceof Dict) {
this.borderColor = getRgbColor(mk.getArray("BC"), null);
this.backgroundColor = getRgbColor(mk.getArray("BG"), null);
} else {
this.borderColor = this.backgroundColor = null;
}
}
/**
* Set the border style (as AnnotationBorderStyle object).
*
* @public
* @memberof Annotation
* @param {Dict} borderStyle - The border style dictionary
*/
setBorderStyle(borderStyle) {
if (
typeof PDFJSDev === "undefined" ||
PDFJSDev.test("!PRODUCTION || TESTING")
) {
assert(this.rectangle, "setRectangle must have been called previously.");
}
this.borderStyle = new AnnotationBorderStyle();
if (!(borderStyle instanceof Dict)) {
return;
}
if (borderStyle.has("BS")) {
const dict = borderStyle.get("BS");
const dictType = dict.get("Type");
if (!dictType || isName(dictType, "Border")) {
this.borderStyle.setWidth(dict.get("W"), this.rectangle);
this.borderStyle.setStyle(dict.get("S"));
this.borderStyle.setDashArray(dict.getArray("D"));
}
} else if (borderStyle.has("Border")) {
const array = borderStyle.getArray("Border");
if (Array.isArray(array) && array.length >= 3) {
this.borderStyle.setHorizontalCornerRadius(array[0]);
this.borderStyle.setVerticalCornerRadius(array[1]);
this.borderStyle.setWidth(array[2], this.rectangle);
if (array.length === 4) {
// Dash array available
this.borderStyle.setDashArray(array[3], /* forceStyle = */ true);
}
}
} else {
// There are no border entries in the dictionary. According to the
// specification, we should draw a solid border of width 1 in that
// case, but Adobe Reader did not implement that part of the
// specification and instead draws no border at all, so we do the same.
// See also https://github.com/mozilla/pdf.js/issues/6179.
this.borderStyle.setWidth(0);
}
}
/**
* Set the (normal) appearance.
*
* @public
* @memberof Annotation
* @param {Dict} dict - The annotation's data dictionary
*/
setAppearance(dict) {
this.appearance = null;
const appearanceStates = dict.get("AP");
if (!(appearanceStates instanceof Dict)) {
return;
}
// In case the normal appearance is a stream, then it is used directly.
const normalAppearanceState = appearanceStates.get("N");
if (normalAppearanceState instanceof BaseStream) {
this.appearance = normalAppearanceState;
return;
}
if (!(normalAppearanceState instanceof Dict)) {
return;
}
// In case the normal appearance is a dictionary, the `AS` entry provides
// the key of the stream in this dictionary.
const as = dict.get("AS");
if (!(as instanceof Name) || !normalAppearanceState.has(as.name)) {
return;
}
this.appearance = normalAppearanceState.get(as.name);
}
loadResources(keys, appearance) {
return appearance.dict.getAsync("Resources").then(resources => {
if (!resources) {
return undefined;
}
const objectLoader = new ObjectLoader(resources, keys, resources.xref);
return objectLoader.load().then(function () {
return resources;
});
});
}
getOperatorList(evaluator, task, intent, renderForms, annotationStorage) {
const data = this.data;
let appearance = this.appearance;
const isUsingOwnCanvas =
data.hasOwnCanvas && intent & RenderingIntentFlag.DISPLAY;
if (!appearance) {
if (!isUsingOwnCanvas) {
return Promise.resolve(new OperatorList());
}
appearance = new StringStream("");
appearance.dict = new Dict();
}
const appearanceDict = appearance.dict;
const resourcesPromise = this.loadResources(
["ExtGState", "ColorSpace", "Pattern", "Shading", "XObject", "Font"],
appearance
);
const bbox = appearanceDict.getArray("BBox") || [0, 0, 1, 1];
const matrix = appearanceDict.getArray("Matrix") || [1, 0, 0, 1, 0, 0];
const transform = getTransformMatrix(data.rect, bbox, matrix);
return resourcesPromise.then(resources => {
const opList = new OperatorList();
opList.addOp(OPS.beginAnnotation, [
data.id,
data.rect,
transform,
matrix,
isUsingOwnCanvas,
]);
return evaluator
.getOperatorList({
stream: appearance,
task,
resources,
operatorList: opList,
fallbackFontDict: this._fallbackFontDict,
})
.then(() => {
opList.addOp(OPS.endAnnotation, []);
this.reset();
return opList;
});
});
}
async save(evaluator, task, annotationStorage) {
return null;
}
/**
* Get field data for usage in JS sandbox.
*
* Field object is defined here:
* https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/js_api_reference.pdf#page=16
*
* @public
* @memberof Annotation
* @returns {Object | null}
*/
getFieldObject() {
if (this.data.kidIds) {
return {
id: this.data.id,
actions: this.data.actions,
name: this.data.fieldName,
strokeColor: this.data.borderColor,
fillColor: this.data.backgroundColor,
type: "",
kidIds: this.data.kidIds,
page: this.data.pageIndex,
};
}
return null;
}
/**
* Reset the annotation.
*
* This involves resetting the various streams that are either cached on the
* annotation instance or created during its construction.
*
* @public
* @memberof Annotation
*/
reset() {
if (
(typeof PDFJSDev === "undefined" ||
PDFJSDev.test("!PRODUCTION || TESTING")) &&
this.appearance &&
!this._streams.includes(this.appearance)
) {
unreachable("The appearance stream should always be reset.");
}
for (const stream of this._streams) {
stream.reset();
}
}
/**
* Construct the (fully qualified) field name from the (partial) field
* names of the field and its ancestors.
*
* @private
* @memberof Annotation
* @param {Dict} dict - Complete widget annotation dictionary
* @returns {string}
*/
_constructFieldName(dict) {
// Both the `Parent` and `T` fields are optional. While at least one of
// them should be provided, bad PDF generators may fail to do so.
if (!dict.has("T") && !dict.has("Parent")) {
warn("Unknown field name, falling back to empty field name.");
return "";
}
// If no parent exists, the partial and fully qualified names are equal.
if (!dict.has("Parent")) {
return stringToPDFString(dict.get("T"));
}
// Form the fully qualified field name by appending the partial name to
// the parent's fully qualified name, separated by a period.
const fieldName = [];
if (dict.has("T")) {
fieldName.unshift(stringToPDFString(dict.get("T")));
}
let loopDict = dict;
const visited = new RefSet();
if (dict.objId) {
visited.put(dict.objId);
}
while (loopDict.has("Parent")) {
loopDict = loopDict.get("Parent");
if (
!(loopDict instanceof Dict) ||
(loopDict.objId && visited.has(loopDict.objId))
) {
// Even though it is not allowed according to the PDF specification,
// bad PDF generators may provide a `Parent` entry that is not a
// dictionary, but `null` for example (issue 8143).
//
// If parent has been already visited, it means that we're
// in an infinite loop.
break;
}
if (loopDict.objId) {
visited.put(loopDict.objId);
}
if (loopDict.has("T")) {
fieldName.unshift(stringToPDFString(loopDict.get("T")));
}
}
return fieldName.join(".");
}
}
/**
* Contains all data regarding an annotation's border style.
*/
class AnnotationBorderStyle {
constructor() {
this.width = 1;
this.style = AnnotationBorderStyleType.SOLID;
this.dashArray = [3];
this.horizontalCornerRadius = 0;
this.verticalCornerRadius = 0;
}
/**
* Set the width.
*
* @public
* @memberof AnnotationBorderStyle
* @param {number} width - The width.
* @param {Array} rect - The annotation `Rect` entry.
*/
setWidth(width, rect = [0, 0, 0, 0]) {
if (
typeof PDFJSDev === "undefined" ||
PDFJSDev.test("!PRODUCTION || TESTING")
) {
assert(
Array.isArray(rect) && rect.length === 4,
"A valid `rect` parameter must be provided."
);
}
// Some corrupt PDF generators may provide the width as a `Name`,
// rather than as a number (fixes issue 10385).
if (width instanceof Name) {
this.width = 0; // This is consistent with the behaviour in Adobe Reader.
return;
}
if (typeof width === "number") {
if (width > 0) {
const maxWidth = (rect[2] - rect[0]) / 2;
const maxHeight = (rect[3] - rect[1]) / 2;
// Ignore large `width`s, since they lead to the Annotation overflowing
// the size set by the `Rect` entry thus causing the `annotationLayer`
// to render it over the surrounding document (fixes bug1552113.pdf).
if (
maxWidth > 0 &&
maxHeight > 0 &&
(width > maxWidth || width > maxHeight)
) {
warn(`AnnotationBorderStyle.setWidth - ignoring width: ${width}`);
width = 1;
}
}
this.width = width;
}
}
/**
* Set the style.
*
* @public
* @memberof AnnotationBorderStyle
* @param {Name} style - The annotation style.
* @see {@link shared/util.js}
*/
setStyle(style) {
if (!(style instanceof Name)) {
return;
}
switch (style.name) {
case "S":
this.style = AnnotationBorderStyleType.SOLID;
break;
case "D":
this.style = AnnotationBorderStyleType.DASHED;
break;
case "B":
this.style = AnnotationBorderStyleType.BEVELED;
break;
case "I":
this.style = AnnotationBorderStyleType.INSET;
break;
case "U":
this.style = AnnotationBorderStyleType.UNDERLINE;
break;
default:
break;
}
}
/**
* Set the dash array.
*
* @public
* @memberof AnnotationBorderStyle
* @param {Array} dashArray - The dash array with at least one element
* @param {boolean} [forceStyle]
*/
setDashArray(dashArray, forceStyle = false) {
// We validate the dash array, but we do not use it because CSS does not
// allow us to change spacing of dashes. For more information, visit
// http://www.w3.org/TR/css3-background/#the-border-style.
if (Array.isArray(dashArray) && dashArray.length > 0) {