src/pypdf/annotations/_non_markup_annotations.py
1from collections.abc import Sequence
2from typing import TYPE_CHECKING, Any
3
4from ..generic._base import (
5 BooleanObject,
6 NameObject,
7 NumberObject,
8 TextStringObject,
9)
10from ..generic._data_structures import ArrayObject, DictionaryObject
11from ..generic._fit import DEFAULT_FIT, Fit
12from ..generic._rectangle import RectangleObject
13from ._base import AnnotationDictionary
14
15
16class Link(AnnotationDictionary):
17 def __init__(
18 self,
19 *,
20 rect: RectangleObject | tuple[float, float, float, float],
21 border: Sequence[Any] | None = None,
22 url: str | None = None,
23 target_page_index: int | None = None,
24 fit: Fit = DEFAULT_FIT,
25 **kwargs: Any,
26 ) -> None:
27 super().__init__(**kwargs)
28 if TYPE_CHECKING:
29 from ..types import BorderArrayType # noqa: PLC0415
30
31 is_external = url is not None
32 is_internal = target_page_index is not None
33 if not is_external and not is_internal:
34 raise ValueError(
35 "Either 'url' or 'target_page_index' have to be provided. Both were None."
36 )
37 if is_external and is_internal:
38 raise ValueError(
39 "Either 'url' or 'target_page_index' have to be provided. "
40 f"{url=}, {target_page_index=}"
41 )
42
43 border_arr: BorderArrayType
44 if border is not None:
45 border_arr = [NumberObject(n) for n in border[:3]]
46 if len(border) == 4:
47 dash_pattern = ArrayObject([NumberObject(n) for n in border[3]])
48 border_arr.append(dash_pattern)
49 else:
50 border_arr = [NumberObject(0)] * 3
51
52 self.update(
53 {
54 NameObject("/Type"): NameObject("/Annot"),
55 NameObject("/Subtype"): NameObject("/Link"),
56 NameObject("/Rect"): RectangleObject(rect),
57 NameObject("/Border"): ArrayObject(border_arr),
58 }
59 )
60 if is_external:
61 self[NameObject("/A")] = DictionaryObject(
62 {
63 NameObject("/S"): NameObject("/URI"),
64 NameObject("/Type"): NameObject("/Action"),
65 NameObject("/URI"): TextStringObject(url),
66 }
67 )
68 if is_internal:
69 # This needs to be updated later!
70 dest_deferred = DictionaryObject(
71 {
72 "target_page_index": NumberObject(target_page_index),
73 "fit": NameObject(fit.fit_type),
74 "fit_args": fit.fit_args,
75 }
76 )
77 self[NameObject("/Dest")] = dest_deferred
78
79
80class Popup(AnnotationDictionary):
81 def __init__(
82 self,
83 *,
84 rect: RectangleObject | tuple[float, float, float, float],
85 parent: DictionaryObject | None = None,
86 open: bool = False,
87 **kwargs: Any,
88 ) -> None:
89 super().__init__(**kwargs)
90 self.update(
91 {
92 NameObject("/Subtype"): NameObject("/Popup"),
93 NameObject("/Rect"): RectangleObject(rect),
94 NameObject("/Open"): BooleanObject(open),
95 }
96 )
97 if parent:
98 # This needs to be an indirect object
99 try:
100 self[NameObject("/Parent")] = parent.indirect_reference
101 except AttributeError:
102 from .._utils import logger_warning # noqa: PLC0415
103
104 logger_warning(
105 "Unregistered Parent object : No Parent field set",
106 source=__name__,
107 )