src/pypdf/generic/_color.py
1from collections.abc import Sequence
2from dataclasses import dataclass, field
3from typing import ClassVar, Union
4
5
6@dataclass
7class Color:
8 """
9 A factory class to generate one of class DeviceGray, DeviceRGB or DeviceCMYK. Call with
10 Color.from_normalized_values() on a tuple of length 1 for grayscale, 3 for RGB, or 4 for CMYK.
11 """
12 color_operator: ClassVar[str] = field(init=False)
13 _ordered_fields: ClassVar[tuple[str, ...]]
14
15 @classmethod
16 def from_normalized_values(
17 cls,
18 color: Sequence[float] | None,
19 operator: str | None = None,
20 ) -> Union["Color", None]:
21 """
22 Method to instantiate a color class. Can be called with value of None for cases where an appearance
23 characteristics dictionary contains an empty "/BG" or "/BC" value, which returns None and signifies
24 transparent color. See Table 189, "Entries in an appearance characteristics dictionary" of the PDF
25 specification 1.7.
26
27 Args:
28 color: A sequence of 1 (for DeviceGray), 3 (for DeviceRGB) or 4 (for DeviceCMYK) float values
29 in the range of 0.0 to 1.0 (representing normalized color channel values), or None to return None.
30 operator: The non-stroking color operator the values are the operands of, that is, "g", "rg" or "k"
31 (Table 73, "Colour operators" of the PDF specification 2.0), as in a default appearance string.
32 If given, None is returned unless it is the operator of the color class the values result in.
33 """
34 color_types: dict[int, type[Color]] = {
35 1: DeviceGray,
36 3: DeviceRGB,
37 4: DeviceCMYK,
38 }
39
40 if (
41 color is not None
42 and (color_length := len(color)) in color_types
43 and (operator is None or color_types[color_length].color_operator == operator)
44 and all(isinstance(val, (int, float)) and 0.0 <= val <= 1.0 for val in color)
45 ):
46 # Create instance of the appropriate subclass
47 color_subclass = color_types[color_length]
48 kwargs = dict(zip(color_subclass._ordered_fields, color))
49 return color_subclass(**kwargs)
50
51 return None
52
53 def as_operator(self, stroke: bool = False) -> str:
54 """
55 Returns the PDF color operator as a string.
56
57 Args:
58 stroke: Returns stroke (i.e., uppercase) color operator if True
59 """
60 values = [f"{round(getattr(self, field), 3):g}" for field in self._ordered_fields]
61 return f"{' '.join(values)} {self.color_operator.upper() if stroke else self.color_operator}"
62
63
64@dataclass
65class DeviceGray(Color):
66 gray: float = 0.0
67
68 color_operator = "g"
69 _ordered_fields = ("gray",)
70
71
72@dataclass
73class DeviceRGB(Color):
74 red: float = 0.0
75 green: float = 0.0
76 blue: float = 0.0
77
78 color_operator = "rg"
79 _ordered_fields = ("red", "green", "blue")
80
81
82@dataclass
83class DeviceCMYK(Color):
84 cyan: float = 0.0
85 magenta: float = 0.0
86 yellow: float = 0.0
87 black: float = 1.0
88
89 color_operator = "k"
90 _ordered_fields = ("cyan", "magenta", "yellow", "black")