src/pypdf/annotations/_markup_annotations.py
1import uuid
2from abc import ABC
3from typing import Any, Literal, TypeAlias
4
5from ..constants import AnnotationFlag
6from ..generic import ArrayObject, DictionaryObject
7from ..generic._base import (
8 BooleanObject,
9 FloatObject,
10 IndirectObject,
11 NameObject,
12 NumberObject,
13 TextStringObject,
14)
15from ..generic._rectangle import RectangleObject
16from ..generic._utils import hex_to_rgb
17from ._base import NO_FLAGS, AnnotationDictionary
18
19Vertex: TypeAlias = tuple[float, float]
20
21
22def _get_bounding_rectangle(vertices: list[Vertex]) -> RectangleObject:
23 x_min, y_min = vertices[0][0], vertices[0][1]
24 x_max, y_max = vertices[0][0], vertices[0][1]
25 for x, y in vertices:
26 x_min = min(x_min, x)
27 y_min = min(y_min, y)
28 x_max = max(x_max, x)
29 y_max = max(y_max, y)
30 return RectangleObject((x_min, y_min, x_max, y_max))
31
32
33class MarkupAnnotation(AnnotationDictionary, ABC):
34 """
35 Base class for all markup annotations.
36
37 Args:
38 title_bar: Text to be displayed in the title bar of the annotation;
39 by convention this is the name of the author
40 in_reply_to: The annotation that this annotation is "in reply to"
41 (PDF 1.5). Can be either an annotation (previously added using
42 :meth:`~pypdf.PdfWriter.add_annotation`) or a reference to the
43 target annotation.
44 reply_type: The relationship between this annotation and the one
45 specified by ``in_reply_to``. Either ``"R"`` (a reply, default)
46 or ``"Group"`` (grouped with the parent annotation). Raises
47 ``ValueError`` if a non-default value is provided without
48 ``in_reply_to``.
49 annotation_name: A text string uniquely identifying this annotation
50 among all annotations on its page. Automatically generated when
51 ``in_reply_to`` is set and no name is provided. Raises
52 ``ValueError`` if provided without ``in_reply_to``.
53
54 """
55
56 def __init__(
57 self,
58 *,
59 title_bar: str | None = None,
60 in_reply_to: DictionaryObject | IndirectObject | None = None,
61 reply_type: Literal["R", "Group"] = "R",
62 annotation_name: str | None = None,
63 ) -> None:
64 if title_bar is not None:
65 self[NameObject("/T")] = TextStringObject(title_bar)
66 if annotation_name is not None and in_reply_to is None:
67 raise ValueError(
68 "annotation_name is only supported when in_reply_to is set"
69 )
70 if reply_type != "R" and in_reply_to is None:
71 raise ValueError(
72 "reply_type is only meaningful when in_reply_to is set"
73 )
74 if in_reply_to is not None:
75 if isinstance(in_reply_to, IndirectObject):
76 ref: IndirectObject = in_reply_to
77 else:
78 indirect_ref = getattr(in_reply_to, "indirect_reference", None)
79 if not isinstance(indirect_ref, IndirectObject):
80 raise ValueError(
81 "in_reply_to must be a registered annotation "
82 "(added via writer.add_annotation() first)"
83 )
84 ref = indirect_ref
85 self[NameObject("/IRT")] = ref
86 self[NameObject("/RT")] = NameObject(f"/{reply_type}")
87 if annotation_name is None:
88 annotation_name = str(uuid.uuid4())
89 self[NameObject("/NM")] = TextStringObject(annotation_name)
90
91
92class Text(MarkupAnnotation):
93 """
94 A text annotation.
95
96 Args:
97 rect: array of four integers ``[xLL, yLL, xUR, yUR]``
98 specifying the clickable rectangular area
99 text: The text that is added to the document
100 open:
101 flags:
102
103 """
104
105 def __init__(
106 self,
107 *,
108 rect: RectangleObject | tuple[float, float, float, float],
109 text: str,
110 open: bool = False,
111 flags: int = NO_FLAGS,
112 **kwargs: Any,
113 ) -> None:
114 super().__init__(**kwargs)
115 self[NameObject("/Subtype")] = NameObject("/Text")
116 self[NameObject("/Rect")] = RectangleObject(rect)
117 self[NameObject("/Contents")] = TextStringObject(text)
118 self[NameObject("/Open")] = BooleanObject(open)
119 self[NameObject("/Flags")] = NumberObject(flags)
120
121
122class FreeText(MarkupAnnotation):
123 """A FreeText annotation"""
124
125 def __init__(
126 self,
127 *,
128 text: str,
129 rect: RectangleObject | tuple[float, float, float, float],
130 font: str = "Helvetica",
131 bold: bool = False,
132 italic: bool = False,
133 font_size: str = "14pt",
134 font_color: str = "000000",
135 border_color: str | None = "000000",
136 background_color: str | None = "ffffff",
137 **kwargs: Any,
138 ) -> None:
139 super().__init__(**kwargs)
140 self[NameObject("/Subtype")] = NameObject("/FreeText")
141 self[NameObject("/Rect")] = RectangleObject(rect)
142
143 # Table 225 of the 1.7 reference ("CSS2 style attributes used in rich text strings")
144 font_str = "font: "
145 if italic:
146 font_str = f"{font_str}italic "
147 else:
148 font_str = f"{font_str}normal "
149 if bold:
150 font_str = f"{font_str}bold "
151 else:
152 font_str = f"{font_str}normal "
153 font_str = f"{font_str}{font_size} {font}"
154 font_str = f"{font_str};text-align:left;color:#{font_color}"
155
156 default_appearance_string = ""
157 if font_color:
158 for st in hex_to_rgb(font_color):
159 default_appearance_string = f"{default_appearance_string}{st} "
160 default_appearance_string = f"{default_appearance_string}rg"
161
162 self.update(
163 {
164 NameObject("/Subtype"): NameObject("/FreeText"),
165 NameObject("/Rect"): RectangleObject(rect),
166 NameObject("/Contents"): TextStringObject(text),
167 # font size color
168 NameObject("/DS"): TextStringObject(font_str),
169 NameObject("/DA"): TextStringObject(default_appearance_string),
170 }
171 )
172 if border_color is None:
173 # Border Style
174 self[NameObject("/BS")] = DictionaryObject(
175 {
176 # width of 0 means no border
177 NameObject("/W"): NumberObject(0)
178 }
179 )
180 if background_color is not None:
181 self[NameObject("/C")] = ArrayObject(
182 [FloatObject(n) for n in hex_to_rgb(background_color)]
183 )
184
185
186class Line(MarkupAnnotation):
187 def __init__(
188 self,
189 p1: Vertex,
190 p2: Vertex,
191 rect: RectangleObject | tuple[float, float, float, float],
192 text: str = "",
193 **kwargs: Any,
194 ) -> None:
195 super().__init__(**kwargs)
196 self.update(
197 {
198 NameObject("/Subtype"): NameObject("/Line"),
199 NameObject("/Rect"): RectangleObject(rect),
200 NameObject("/L"): ArrayObject(
201 [
202 FloatObject(p1[0]),
203 FloatObject(p1[1]),
204 FloatObject(p2[0]),
205 FloatObject(p2[1]),
206 ]
207 ),
208 NameObject("/LE"): ArrayObject(
209 [
210 NameObject("/None"),
211 NameObject("/None"),
212 ]
213 ),
214 NameObject("/IC"): ArrayObject(
215 [
216 FloatObject(0.5),
217 FloatObject(0.5),
218 FloatObject(0.5),
219 ]
220 ),
221 NameObject("/Contents"): TextStringObject(text),
222 }
223 )
224
225
226class PolyLine(MarkupAnnotation):
227 def __init__(
228 self,
229 vertices: list[Vertex],
230 **kwargs: Any,
231 ) -> None:
232 super().__init__(**kwargs)
233 if len(vertices) == 0:
234 raise ValueError("A polyline needs at least 1 vertex with two coordinates")
235 coord_list = []
236 for x, y in vertices:
237 coord_list.append(NumberObject(x))
238 coord_list.append(NumberObject(y))
239 self.update(
240 {
241 NameObject("/Subtype"): NameObject("/PolyLine"),
242 NameObject("/Vertices"): ArrayObject(coord_list),
243 NameObject("/Rect"): RectangleObject(_get_bounding_rectangle(vertices)),
244 }
245 )
246
247
248class Rectangle(MarkupAnnotation):
249 def __init__(
250 self,
251 rect: RectangleObject | tuple[float, float, float, float],
252 *,
253 interior_color: str | None = None,
254 border_color: str | None = None,
255 **kwargs: Any,
256 ) -> None:
257 super().__init__(**kwargs)
258 self.update(
259 {
260 NameObject("/Type"): NameObject("/Annot"),
261 NameObject("/Subtype"): NameObject("/Square"),
262 NameObject("/Rect"): RectangleObject(rect),
263 }
264 )
265
266 if border_color is not None:
267 self[NameObject("/C")] = ArrayObject(
268 [FloatObject(n) for n in hex_to_rgb(border_color)]
269 )
270
271 if interior_color:
272 self[NameObject("/IC")] = ArrayObject(
273 [FloatObject(n) for n in hex_to_rgb(interior_color)]
274 )
275
276
277class Highlight(MarkupAnnotation):
278 def __init__(
279 self,
280 *,
281 rect: RectangleObject | tuple[float, float, float, float],
282 quad_points: ArrayObject,
283 highlight_color: str = "ff0000",
284 printing: bool = False,
285 **kwargs: Any,
286 ) -> None:
287 super().__init__(**kwargs)
288 self.update(
289 {
290 NameObject("/Subtype"): NameObject("/Highlight"),
291 NameObject("/Rect"): RectangleObject(rect),
292 NameObject("/QuadPoints"): quad_points,
293 NameObject("/C"): ArrayObject(
294 [FloatObject(n) for n in hex_to_rgb(highlight_color)]
295 ),
296 }
297 )
298 if printing:
299 self.flags = AnnotationFlag.PRINT
300
301
302class Ellipse(MarkupAnnotation):
303 def __init__(
304 self,
305 rect: RectangleObject | tuple[float, float, float, float],
306 *,
307 interior_color: str | None = None,
308 **kwargs: Any,
309 ) -> None:
310 super().__init__(**kwargs)
311
312 self.update(
313 {
314 NameObject("/Type"): NameObject("/Annot"),
315 NameObject("/Subtype"): NameObject("/Circle"),
316 NameObject("/Rect"): RectangleObject(rect),
317 }
318 )
319
320 if interior_color:
321 self[NameObject("/IC")] = ArrayObject(
322 [FloatObject(n) for n in hex_to_rgb(interior_color)]
323 )
324
325
326class Polygon(MarkupAnnotation):
327 def __init__(
328 self,
329 vertices: list[tuple[float, float]],
330 **kwargs: Any,
331 ) -> None:
332 super().__init__(**kwargs)
333 if len(vertices) == 0:
334 raise ValueError("A polygon needs at least 1 vertex with two coordinates")
335
336 coord_list = []
337 for x, y in vertices:
338 coord_list.append(NumberObject(x))
339 coord_list.append(NumberObject(y))
340 self.update(
341 {
342 NameObject("/Type"): NameObject("/Annot"),
343 NameObject("/Subtype"): NameObject("/Polygon"),
344 NameObject("/Vertices"): ArrayObject(coord_list),
345 NameObject("/IT"): NameObject("/PolygonCloud"),
346 NameObject("/Rect"): RectangleObject(_get_bounding_rectangle(vertices)),
347 }
348 )