addAnnotation method
Implementation
Future<int> addAnnotation(int pageIndex, UPdfAnnotationSpec spec) async {
final UPdfDict? page = await mutablePage(pageIndex);
final UPdfRef? ref = await pageRef(pageIndex);
if (page == null || ref == null) return -1;
final int number = allocate();
final Map<String, Object?> annotation = <String, Object?>{
"Type": const UPdfName("Annot"),
"Subtype": UPdfName(_subtypeFor(spec.style)),
"Rect": <Object?>[spec.rect.left, spec.rect.top, spec.rect.right, spec.rect.bottom],
"F": 4,
"M": _dateString(DateTime.now()),
"CA": spec.opacity,
"C": _colorArray(spec.color),
"P": ref,
"NM": _text("u-${DateTime.now().microsecondsSinceEpoch}-$number"),
};
if (spec.contents.isNotEmpty) annotation["Contents"] = _text(spec.contents);
if (spec.author.isNotEmpty) annotation["T"] = _text(spec.author);
if (spec.title.isNotEmpty) annotation["Subj"] = _text(spec.title);
if (spec.borderWidth > 0) annotation["BS"] = UPdfDict(<String, Object?>{"W": spec.borderWidth, "S": const UPdfName("S")});
if (spec.quads.isNotEmpty) {
final List<Object?> quadPoints = <Object?>[];
for (final Rect quad in spec.quads) {
quadPoints.addAll(<Object?>[quad.left, quad.bottom, quad.right, quad.bottom, quad.left, quad.top, quad.right, quad.top]);
}
annotation["QuadPoints"] = quadPoints;
}
if (spec.style == UPdfAnnotationStyle.ink && spec.inkPaths.isNotEmpty) {
final List<Object?> inkList = <Object?>[];
for (final List<Offset> path in spec.inkPaths) {
final List<Object?> points = <Object?>[];
for (final Offset point in path) {
points.addAll(<Object?>[point.dx, point.dy]);
}
inkList.add(points);
}
annotation["InkList"] = inkList;
}
if (spec.style == UPdfAnnotationStyle.freeText) {
annotation["DA"] = UPdfString(Uint8List.fromList("${_colorOperator(const Color(0xFF000000), stroke: false)} /Helv ${UPdfSerializer.number(spec.fontSize)} Tf".codeUnits));
annotation["Q"] = spec.rtl ? 2 : 0;
}
final int appearanceNumber = allocate();
final UPdfStream? appearance = await _buildAppearance(spec);
if (appearance != null) {
put(appearanceNumber, appearance);
annotation["AP"] = UPdfDict(<String, Object?>{"N": UPdfRef(appearanceNumber, 0)});
}
put(number, UPdfDict(annotation));
final Object? existing = await document.resolve(page["Annots"]);
final List<Object?> annotations = existing is List<Object?> ? <Object?>[...existing] : <Object?>[];
annotations.add(UPdfRef(number, 0));
page["Annots"] = annotations;
return number;
}