-
Notifications
You must be signed in to change notification settings - Fork 10.1k
/
Copy pathannotation.js
5109 lines (4508 loc) · 148 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,
AnnotationEditorType,
AnnotationFieldFlag,
AnnotationFlag,
AnnotationReplyType,
AnnotationType,
assert,
BASELINE_FACTOR,
FeatureTest,
getModificationDate,
IDENTITY_MATRIX,
info,
isArrayEqual,
LINE_DESCENT_FACTOR,
LINE_FACTOR,
OPS,
RenderingIntentFlag,
shadow,
stringToPDFString,
unreachable,
Util,
warn,
} from "../shared/util.js";
import {
collectActions,
escapeString,
getInheritableProperty,
getParentToUpdate,
getRotationMatrix,
isNumberArray,
lookupMatrix,
lookupNormalRect,
lookupRect,
numberToString,
stringToAsciiOrUTF16BE,
stringToUTF16String,
} from "./core_utils.js";
import {
createDefaultAppearance,
FakeUnicodeFont,
getPdfColor,
parseAppearanceStream,
parseDefaultAppearance,
} from "./default_appearance.js";
import { Dict, isName, isRefsEqual, Name, Ref, RefSet } from "./primitives.js";
import { Stream, StringStream } from "./stream.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 { JpegStream } from "./jpeg_stream.js";
import { ObjectLoader } from "./object_loader.js";
import { OperatorList } from "./operator_list.js";
import { XFAFactory } from "./xfa/factory.js";
class AnnotationFactory {
static createGlobals(pdfManager) {
return Promise.all([
pdfManager.ensureCatalog("acroForm"),
pdfManager.ensureDoc("xfaDatasets"),
pdfManager.ensureCatalog("structTreeRoot"),
// Only necessary to prevent the `Catalog.baseUrl`-getter, used
// with some Annotations, from throwing and thus breaking parsing:
pdfManager.ensureCatalog("baseUrl"),
// Only necessary to prevent the `Catalog.attachments`-getter, used
// with "GoToE" actions, from throwing and thus breaking parsing:
pdfManager.ensureCatalog("attachments"),
]).then(
// eslint-disable-next-line arrow-body-style
([acroForm, xfaDatasets, structTreeRoot, baseUrl, attachments]) => {
return {
pdfManager,
acroForm: acroForm instanceof Dict ? acroForm : Dict.empty,
xfaDatasets,
structTreeRoot,
baseUrl,
attachments,
};
},
reason => {
warn(`createGlobals: "${reason}".`);
return null;
}
);
}
/**
* 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
* @params {Object} annotationGlobals
* @param {Object} idFactory
* @param {boolean} [collectFields]
* @param {Object} [orphanFields]
* @param {Object} [pageRef]
* @returns {Promise} A promise that is resolved with an {Annotation}
* instance.
*/
static async create(
xref,
ref,
annotationGlobals,
idFactory,
collectFields,
orphanFields,
pageRef
) {
const pageIndex = collectFields
? await this._getPageIndex(xref, ref, annotationGlobals.pdfManager)
: null;
return annotationGlobals.pdfManager.ensure(this, "_create", [
xref,
ref,
annotationGlobals,
idFactory,
collectFields,
orphanFields,
pageIndex,
pageRef,
]);
}
/**
* @private
*/
static _create(
xref,
ref,
annotationGlobals,
idFactory,
collectFields = false,
orphanFields = null,
pageIndex = null,
pageRef = null
) {
const dict = xref.fetchIfRef(ref);
if (!(dict instanceof Dict)) {
return undefined;
}
const { acroForm, pdfManager } = annotationGlobals;
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,
annotationGlobals,
collectFields,
orphanFields,
needAppearances:
!collectFields && acroForm.get("NeedAppearances") === true,
pageIndex,
evaluatorOptions: pdfManager.evaluatorOptions,
pageRef,
};
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) {
try {
const pageIndex = await pdfManager.ensureCatalog("getPageIndex", [
pageRef,
]);
return pageIndex;
} catch (ex) {
info(`_getPageIndex -- not a valid page reference: "${ex}".`);
}
}
if (annotDict.has("Kids")) {
return -1; // Not an annotation reference.
}
// Fallback to, potentially, checking the annotations of all pages.
// PLEASE NOTE: This could force the *entire* PDF document to load,
// hence it absolutely cannot be done unconditionally.
const numPages = await pdfManager.ensureDoc("numPages");
for (let pageIndex = 0; pageIndex < numPages; pageIndex++) {
const page = await pdfManager.getPage(pageIndex);
const annotations = await pdfManager.ensure(page, "annotations");
for (const annotRef of annotations) {
if (annotRef instanceof Ref && isRefsEqual(annotRef, ref)) {
return pageIndex;
}
}
}
} catch (ex) {
warn(`_getPageIndex: "${ex}".`);
}
return -1;
}
static generateImages(annotations, xref, isOffscreenCanvasSupported) {
if (!isOffscreenCanvasSupported) {
warn(
"generateImages: OffscreenCanvas is not supported, cannot save or print some annotations with images."
);
return null;
}
let imagePromises;
for (const { bitmapId, bitmap } of annotations) {
if (!bitmap) {
continue;
}
imagePromises ||= new Map();
imagePromises.set(bitmapId, StampAnnotation.createImage(bitmap, xref));
}
return imagePromises;
}
static async saveNewAnnotations(
evaluator,
task,
annotations,
imagePromises,
changes
) {
const xref = evaluator.xref;
let baseFontRef;
const promises = [];
const { isOffscreenCanvasSupported } = evaluator.options;
for (const annotation of annotations) {
if (annotation.deleted) {
continue;
}
switch (annotation.annotationType) {
case AnnotationEditorType.FREETEXT:
if (!baseFontRef) {
const baseFont = new Dict(xref);
baseFont.set("BaseFont", Name.get("Helvetica"));
baseFont.set("Type", Name.get("Font"));
baseFont.set("Subtype", Name.get("Type1"));
baseFont.set("Encoding", Name.get("WinAnsiEncoding"));
baseFontRef = xref.getNewTemporaryRef();
changes.put(baseFontRef, {
data: baseFont,
});
}
promises.push(
FreeTextAnnotation.createNewAnnotation(xref, annotation, changes, {
evaluator,
task,
baseFontRef,
})
);
break;
case AnnotationEditorType.HIGHLIGHT:
if (annotation.quadPoints) {
promises.push(
HighlightAnnotation.createNewAnnotation(xref, annotation, changes)
);
} else {
promises.push(
InkAnnotation.createNewAnnotation(xref, annotation, changes)
);
}
break;
case AnnotationEditorType.INK:
promises.push(
InkAnnotation.createNewAnnotation(xref, annotation, changes)
);
break;
case AnnotationEditorType.STAMP:
const image = isOffscreenCanvasSupported
? await imagePromises?.get(annotation.bitmapId)
: null;
if (image?.imageStream) {
const { imageStream, smaskStream } = image;
if (smaskStream) {
const smaskRef = xref.getNewTemporaryRef();
changes.put(smaskRef, {
data: smaskStream,
});
imageStream.dict.set("SMask", smaskRef);
}
const imageRef = (image.imageRef = xref.getNewTemporaryRef());
changes.put(imageRef, {
data: imageStream,
});
image.imageStream = image.smaskStream = null;
}
promises.push(
StampAnnotation.createNewAnnotation(xref, annotation, changes, {
image,
})
);
break;
}
}
return {
annotations: await Promise.all(promises),
};
}
static async printNewAnnotations(
annotationGlobals,
evaluator,
task,
annotations,
imagePromises
) {
if (!annotations) {
return null;
}
const { options, xref } = evaluator;
const promises = [];
for (const annotation of annotations) {
if (annotation.deleted) {
continue;
}
switch (annotation.annotationType) {
case AnnotationEditorType.FREETEXT:
promises.push(
FreeTextAnnotation.createNewPrintAnnotation(
annotationGlobals,
xref,
annotation,
{
evaluator,
task,
evaluatorOptions: options,
}
)
);
break;
case AnnotationEditorType.HIGHLIGHT:
if (annotation.quadPoints) {
promises.push(
HighlightAnnotation.createNewPrintAnnotation(
annotationGlobals,
xref,
annotation,
{
evaluatorOptions: options,
}
)
);
} else {
promises.push(
InkAnnotation.createNewPrintAnnotation(
annotationGlobals,
xref,
annotation,
{
evaluatorOptions: options,
}
)
);
}
break;
case AnnotationEditorType.INK:
promises.push(
InkAnnotation.createNewPrintAnnotation(
annotationGlobals,
xref,
annotation,
{
evaluatorOptions: options,
}
)
);
break;
case AnnotationEditorType.STAMP:
const image = options.isOffscreenCanvasSupported
? await imagePromises?.get(annotation.bitmapId)
: null;
if (image?.imageStream) {
const { imageStream, smaskStream } = image;
if (smaskStream) {
imageStream.dict.set("SMask", smaskStream);
}
image.imageRef = new JpegStream(imageStream, imageStream.length);
image.imageStream = image.smaskStream = null;
}
promises.push(
StampAnnotation.createNewPrintAnnotation(
annotationGlobals,
xref,
annotation,
{
image,
evaluatorOptions: options,
}
)
);
break;
}
}
return Promise.all(promises);
}
}
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 getPdfColorArray(color) {
return Array.from(color, c => c / 255);
}
function getQuadPoints(dict, rect) {
// The region is described as a number of quadrilaterals.
// Each quadrilateral must consist of eight coordinates.
const quadPoints = dict.getArray("QuadPoints");
if (
!isNumberArray(quadPoints, null) ||
quadPoints.length === 0 ||
quadPoints.length % 8 > 0
) {
return null;
}
const newQuadPoints = new Float32Array(quadPoints.length);
for (let i = 0, ii = quadPoints.length; i < ii; i += 8) {
// 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.
const [x1, y1, x2, y2, x3, y3, x4, y4] = quadPoints.slice(i, i + 8);
const minX = Math.min(x1, x2, x3, x4);
const maxX = Math.max(x1, x2, x3, x4);
const minY = Math.min(y1, y2, y3, y4);
const maxY = Math.max(y1, y2, y3, y4);
// 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 &&
(minX < rect[0] || maxX > rect[2] || minY < rect[1] || maxY > rect[3])
) {
return null;
}
// 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).
newQuadPoints.set([minX, maxY, maxX, maxY, minX, minY, maxX, minY], i);
}
return newQuadPoints;
}
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, xref, annotationGlobals, ref, orphanFields } = params;
const parentRef = orphanFields?.get(ref);
if (parentRef) {
dict.set("Parent", parentRef);
}
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.setOptionalContent(dict);
const MK = dict.get("MK");
this.setBorderAndBackgroundColors(MK);
this.setRotation(MK, dict);
this.ref = params.ref instanceof Ref ? params.ref : null;
this._streams = [];
if (this.appearance) {
this._streams.push(this.appearance);
}
// The annotation cannot be changed (neither its position/visibility nor its
// contents), hence we can just display its appearance and don't generate
// a HTML element for it.
const isLocked = !!(this.flags & AnnotationFlag.LOCKED);
const isContentLocked = !!(this.flags & AnnotationFlag.LOCKEDCONTENTS);
// Expose public properties using a data object.
this.data = {
annotationFlags: this.flags,
borderStyle: this.borderStyle,
color: this.color,
backgroundColor: this.backgroundColor,
borderColor: this.borderColor,
rotation: this.rotation,
contentsObj: this._contents,
hasAppearance: !!this.appearance,
id: params.id,
modificationDate: this.modificationDate,
rect: this.rectangle,
subtype: params.subtype,
hasOwnCanvas: false,
noRotate: !!(this.flags & AnnotationFlag.NOROTATE),
noHTML: isLocked && isContentLocked,
isEditable: false,
structParent: -1,
};
if (annotationGlobals.structTreeRoot) {
let structParent = dict.get("StructParent");
this.data.structParent = structParent =
Number.isInteger(structParent) && structParent >= 0 ? structParent : -1;
annotationGlobals.structTreeRoot.addAnnotationIdToPage(
params.pageRef,
structParent
);
}
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(xref, dict, AnnotationActionEventType);
this.data.fieldName = this._constructFieldName(dict);
this.data.pageIndex = params.pageIndex;
}
const it = dict.get("IT");
if (it instanceof Name) {
this.data.it = it.name;
}
this._isOffscreenCanvasSupported =
params.evaluatorOptions.isOffscreenCanvasSupported;
this._fallbackFontDict = null;
this._needAppearances = false;
}
/**
* @private
*/
_hasFlag(flags, flag) {
return !!(flags & flag);
}
_buildFlags(noView, noPrint) {
let { flags } = this;
if (noView === undefined) {
if (noPrint === undefined) {
return undefined;
}
if (noPrint) {
return flags & ~AnnotationFlag.PRINT;
}
return (flags & ~AnnotationFlag.HIDDEN) | AnnotationFlag.PRINT;
}
if (noView) {
flags |= AnnotationFlag.PRINT;
if (noPrint) {
// display === 1.
return (flags & ~AnnotationFlag.NOVIEW) | AnnotationFlag.HIDDEN;
}
// display === 3.
return (flags & ~AnnotationFlag.HIDDEN) | AnnotationFlag.NOVIEW;
}
flags &= ~(AnnotationFlag.HIDDEN | AnnotationFlag.NOVIEW);
if (noPrint) {
// display === 2.
return flags & ~AnnotationFlag.PRINT;
}
// display === 0.
return flags | AnnotationFlag.PRINT;
}
/**
* @private
*/
_isViewable(flags) {
return (
!this._hasFlag(flags, AnnotationFlag.INVISIBLE) &&
!this._hasFlag(flags, AnnotationFlag.NOVIEW)
);
}
/**
* @private
*/
_isPrintable(flags) {
// In Acrobat, hidden flag cancels the print one
// (see annotation_hidden_print.pdf).
return (
this._hasFlag(flags, AnnotationFlag.PRINT) &&
!this._hasFlag(flags, AnnotationFlag.HIDDEN) &&
!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
* @param {boolean} [_renderForms] - if true widgets are rendered thanks to
* the annotation layer.
*/
mustBeViewed(annotationStorage, _renderForms) {
const noView = annotationStorage?.get(this.data.id)?.noView;
if (noView !== undefined) {
return !noView;
}
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 noPrint = annotationStorage?.get(this.data.id)?.noPrint;
if (noPrint !== undefined) {
return !noPrint;
}
return this.printable;
}
mustBeViewedWhenEditing(isEditing, modifiedIds = null) {
return isEditing ? !this.data.isEditable : !modifiedIds?.has(this.data.id);
}
/**
* @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 };
}
setDefaultAppearance(params) {
const { dict, annotationGlobals } = params;
const defaultAppearance =
getInheritableProperty({ dict, key: "DA" }) ||
annotationGlobals.acroForm.get("DA");
this._defaultAppearance =
typeof defaultAppearance === "string" ? defaultAppearance : "";
this.data.defaultAppearanceData = parseDefaultAppearance(
this._defaultAppearance
);
}
/**
* 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;
if (
this.flags & AnnotationFlag.INVISIBLE &&
this.constructor.name !== "Annotation"
) {
// From the pdf spec v1.7, section 12.5.3 (Annotation Flags):
// If set, do not display the annotation if it does not belong to one of
// the standard annotation types and no annotation handler is available.
//
// So we can remove the flag in case we have a known annotation type.
this.flags ^= AnnotationFlag.INVISIBLE;
}
}
/**
* 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) {
this.rectangle = lookupNormalRect(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 line endings; should only be used with specific annotation types.
* @param {Array} lineEndings - The line endings array.
*/
setLineEndings(lineEndings) {
if (typeof PDFJSDev !== "undefined" && PDFJSDev.test("MOZCENTRAL")) {
throw new Error("Not implemented: setLineEndings");
}
this.lineEndings = ["None", "None"]; // The default values.
if (Array.isArray(lineEndings) && lineEndings.length === 2) {
for (let i = 0; i < 2; i++) {
const obj = lineEndings[i];
if (obj instanceof Name) {
switch (obj.name) {
case "None":
continue;
case "Square":
case "Circle":
case "Diamond":
case "OpenArrow":
case "ClosedArrow":
case "Butt":
case "ROpenArrow":
case "RClosedArrow":
case "Slash":
this.lineEndings[i] = obj.name;
continue;