PyPDFForm 6.1.1__tar.gz → 6.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. {pypdfform-6.1.1 → pypdfform-6.2.0}/PKG-INFO +2 -2
  2. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/__init__.py +1 -1
  3. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/constants.py +1 -0
  4. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/hooks.py +2 -8
  5. pypdfform-6.2.0/PyPDFForm/lib/middleware/dropdown.py +391 -0
  6. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/patterns.py +48 -49
  7. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/utils.py +5 -1
  8. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/widgets/dropdown.py +8 -6
  9. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/wrapper.py +5 -3
  10. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm.egg-info/PKG-INFO +2 -2
  11. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm.egg-info/requires.txt +1 -1
  12. {pypdfform-6.1.1 → pypdfform-6.2.0}/pyproject.toml +2 -2
  13. {pypdfform-6.1.1 → pypdfform-6.2.0}/tests/test_functional.py +122 -1
  14. pypdfform-6.1.1/PyPDFForm/lib/middleware/dropdown.py +0 -223
  15. {pypdfform-6.1.1 → pypdfform-6.2.0}/LICENSE +0 -0
  16. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/cli/__init__.py +0 -0
  17. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/cli/common.py +0 -0
  18. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/cli/create.py +0 -0
  19. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/cli/entry.py +0 -0
  20. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/cli/inspect.py +0 -0
  21. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/cli/remove.py +0 -0
  22. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/cli/root.py +0 -0
  23. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/cli/schemas/__init__.py +0 -0
  24. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/cli/schemas/create.py +0 -0
  25. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/cli/schemas/update.py +0 -0
  26. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/cli/update.py +0 -0
  27. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/__init__.py +0 -0
  28. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/adapter.py +0 -0
  29. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/annotations/__init__.py +0 -0
  30. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/annotations/base.py +0 -0
  31. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/annotations/link.py +0 -0
  32. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/annotations/stamp.py +0 -0
  33. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/annotations/text.py +0 -0
  34. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/annotations/text_markup.py +0 -0
  35. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/assets/__init__.py +0 -0
  36. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/assets/blank.py +0 -0
  37. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/clone.py +0 -0
  38. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/coordinate.py +0 -0
  39. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/deprecation.py +0 -0
  40. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/egress.py +0 -0
  41. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/filler.py +0 -0
  42. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/font.py +0 -0
  43. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/image.py +0 -0
  44. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/middleware/__init__.py +0 -0
  45. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/middleware/base.py +0 -0
  46. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/middleware/checkbox.py +0 -0
  47. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/middleware/image.py +0 -0
  48. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/middleware/radio.py +0 -0
  49. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/middleware/signature.py +0 -0
  50. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/middleware/text.py +0 -0
  51. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/raw/__init__.py +0 -0
  52. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/raw/circle.py +0 -0
  53. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/raw/ellipse.py +0 -0
  54. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/raw/image.py +0 -0
  55. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/raw/line.py +0 -0
  56. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/raw/rect.py +0 -0
  57. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/raw/text.py +0 -0
  58. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/template.py +0 -0
  59. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/watermark.py +0 -0
  60. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/widgets/__init__.py +0 -0
  61. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/widgets/base.py +0 -0
  62. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/widgets/checkbox.py +0 -0
  63. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/widgets/image.py +0 -0
  64. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/widgets/radio.py +0 -0
  65. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/widgets/signature.py +0 -0
  66. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm/lib/widgets/text.py +0 -0
  67. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm.egg-info/SOURCES.txt +0 -0
  68. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm.egg-info/dependency_links.txt +0 -0
  69. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm.egg-info/entry_points.txt +0 -0
  70. {pypdfform-6.1.1 → pypdfform-6.2.0}/PyPDFForm.egg-info/top_level.txt +0 -0
  71. {pypdfform-6.1.1 → pypdfform-6.2.0}/README.md +0 -0
  72. {pypdfform-6.1.1 → pypdfform-6.2.0}/setup.cfg +0 -0
  73. {pypdfform-6.1.1 → pypdfform-6.2.0}/tests/test_bulk_create_fields.py +0 -0
  74. {pypdfform-6.1.1 → pypdfform-6.2.0}/tests/test_create_widget.py +0 -0
  75. {pypdfform-6.1.1 → pypdfform-6.2.0}/tests/test_draw_elements.py +0 -0
  76. {pypdfform-6.1.1 → pypdfform-6.2.0}/tests/test_dropdown.py +0 -0
  77. {pypdfform-6.1.1 → pypdfform-6.2.0}/tests/test_extract_middleware_attributes.py +0 -0
  78. {pypdfform-6.1.1 → pypdfform-6.2.0}/tests/test_fill_max_length_text_field.py +0 -0
  79. {pypdfform-6.1.1 → pypdfform-6.2.0}/tests/test_font_related.py +0 -0
  80. {pypdfform-6.1.1 → pypdfform-6.2.0}/tests/test_generate_appearance_streams.py +0 -0
  81. {pypdfform-6.1.1 → pypdfform-6.2.0}/tests/test_js.py +0 -0
  82. {pypdfform-6.1.1 → pypdfform-6.2.0}/tests/test_need_appearances.py +0 -0
  83. {pypdfform-6.1.1 → pypdfform-6.2.0}/tests/test_paragraph.py +0 -0
  84. {pypdfform-6.1.1 → pypdfform-6.2.0}/tests/test_signature.py +0 -0
  85. {pypdfform-6.1.1 → pypdfform-6.2.0}/tests/test_use_full_widget_name.py +0 -0
  86. {pypdfform-6.1.1 → pypdfform-6.2.0}/tests/test_widget_attr_trigger.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: PyPDFForm
3
- Version: 6.1.1
3
+ Version: 6.2.0
4
4
  Summary: The Python library & CLI for PDF forms.
5
5
  Author: Jinge Li
6
6
  License-Expression: MIT
@@ -27,7 +27,7 @@ License-File: LICENSE
27
27
  Requires-Dist: cryptography<51.0.0,>=50.0.0
28
28
  Requires-Dist: fonttools<5.0.0,>=4.63.0
29
29
  Requires-Dist: pikepdf<11.0.0,>=10.7.2
30
- Requires-Dist: pillow<14.0.0,>=12.2.0
30
+ Requires-Dist: pillow<14.0.0,>=13.0.0
31
31
  Requires-Dist: pypdf<7.0.0,>=6.19.0
32
32
  Requires-Dist: reportlab<6.0.0,>=4.5.1
33
33
  Provides-Extra: cli
@@ -16,7 +16,7 @@ PyPDFForm aims to make PDF form automation straightforward whether it is used
16
16
  from Python code or from the command line.
17
17
  """
18
18
 
19
- __version__ = "6.1.1"
19
+ __version__ = "6.2.0"
20
20
 
21
21
  from .lib.annotations import Annotations
22
22
  from .lib.assets.blank import BlankPage
@@ -169,6 +169,7 @@ XFA = "/XFA"
169
169
  READ_ONLY = 1 << 0
170
170
  REQUIRED = 1 << 1
171
171
  MULTILINE = 1 << 12
172
+ RADIO = 1 << 15
172
173
  COMB = 1 << 24
173
174
 
174
175
  # annotation flag bits
@@ -56,6 +56,7 @@ from .constants import (
56
56
  U,
57
57
  X,
58
58
  )
59
+ from .middleware.dropdown import DropdownOption
59
60
  from .patterns import get_widget_key
60
61
 
61
62
 
@@ -377,14 +378,7 @@ def update_dropdown_choices(annot: DictionaryObject, val: list) -> None:
377
378
  val (list): A list of strings or tuples representing the new choices for the dropdown.
378
379
  """
379
380
  annot[NameObject(Opt)] = ArrayObject(
380
- [
381
- (
382
- ArrayObject([TextStringObject(each[1]), TextStringObject(each[0])])
383
- if isinstance(each, (tuple, list))
384
- else ArrayObject([TextStringObject(each), TextStringObject(each)])
385
- )
386
- for each in val
387
- ]
381
+ [DropdownOption.from_choice(each).to_pdf() for each in val]
388
382
  )
389
383
 
390
384
 
@@ -0,0 +1,391 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Module representing a dropdown widget.
4
+
5
+ This module defines the Dropdown class, which is a subclass of the
6
+ Widget class. It represents a dropdown form field in a PDF document.
7
+ It also defines DropdownOption, the single representation used to convert
8
+ dropdown options between public choices and PDF option arrays.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from collections import defaultdict
14
+ from dataclasses import dataclass
15
+ from typing import Any, Optional, Sequence
16
+
17
+ from pypdf.generic import ArrayObject, TextStringObject
18
+
19
+ from .base import PreparedValue, Widget
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class DropdownOption:
24
+ """
25
+ Represents one dropdown option with its displayed text and export value.
26
+
27
+ Public choices use a string when both values are equal, or a
28
+ `(display, export)` sequence when they differ. PDF option arrays store the
29
+ same pair in the opposite order, `[export, display]`, and a field's `/V`
30
+ holds the export value of the selected option.
31
+
32
+ Attributes:
33
+ display (str): The text shown for the option.
34
+ export (str): The value stored in the PDF when the option is selected.
35
+ """
36
+
37
+ display: str
38
+ export: str
39
+
40
+ @classmethod
41
+ def from_choice(cls, choice: str | Sequence[str]) -> DropdownOption:
42
+ """
43
+ Creates an option from a public choice.
44
+
45
+ Args:
46
+ choice (str | Sequence[str]): A string used as both the displayed
47
+ text and export value, or a `(display, export)` sequence.
48
+
49
+ Returns:
50
+ DropdownOption: The option described by the choice.
51
+ """
52
+ if isinstance(choice, str):
53
+ return cls(choice, choice)
54
+ display, export = choice
55
+ return cls(display, export)
56
+
57
+ @classmethod
58
+ def from_pdf(cls, entry: Any) -> DropdownOption:
59
+ """
60
+ Creates an option from an entry of a PDF `/Opt` array.
61
+
62
+ Args:
63
+ entry (Any): A text string used as both values, or an
64
+ `[export, display]` array.
65
+
66
+ Returns:
67
+ DropdownOption: The option described by the entry.
68
+ """
69
+ entry = entry.get_object()
70
+ if isinstance(entry, str):
71
+ return cls(str(entry), str(entry))
72
+ return cls(str(entry[1]), str(entry[0]))
73
+
74
+ @property
75
+ def choice(self) -> str | tuple[str, str]:
76
+ """
77
+ Returns the option in the public choices format.
78
+
79
+ Returns:
80
+ str | tuple[str, str]: The displayed text when it equals the export
81
+ value, otherwise a `(display, export)` tuple.
82
+ """
83
+ if self.display == self.export:
84
+ return self.display
85
+ return self.display, self.export
86
+
87
+ def to_pdf(self) -> ArrayObject:
88
+ """
89
+ Returns the option as an entry of a PDF `/Opt` array.
90
+
91
+ Returns:
92
+ ArrayObject: The `[export, display]` array for the option.
93
+ """
94
+ return ArrayObject(
95
+ [TextStringObject(self.export), TextStringObject(self.display)]
96
+ )
97
+
98
+
99
+ class Dropdown(Widget):
100
+ """
101
+ Represents a dropdown widget in a PDF form.
102
+
103
+ Inherits from the Widget class and provides specific functionality
104
+ for handling dropdown form fields. The stored value is an option index; string
105
+ assignments select the option whose displayed text or export value matches,
106
+ or are appended as a new choice when none does. Strings matching options that
107
+ differ are rejected. Integer indices must identify an existing option.
108
+
109
+ Key attributes:
110
+ font (str): The font of the dropdown field.
111
+ choices (List[str | Tuple[str, str]]): The available options. Each is a
112
+ string when its displayed text and export value are equal, or a
113
+ `(display, export)` tuple when they differ.
114
+ value (int): The index of the selected choice in the choices list.
115
+
116
+ Methods:
117
+ schema_definition: Returns a schema definition for the dropdown's value.
118
+ sample_value: Returns a sample value for the dropdown.
119
+ """
120
+
121
+ TYPE_SPECIFIC_PROPERTIES = frozenset({"font", "font_size", "font_color", "choices"})
122
+
123
+ def __init__(
124
+ self,
125
+ name: str,
126
+ value: int = None,
127
+ ) -> None:
128
+ """
129
+ Initializes a dropdown widget.
130
+
131
+ Besides common widget state, dropdowns register hooks for font updates
132
+ and choice replacement.
133
+
134
+ Args:
135
+ name (str): The name of the dropdown.
136
+ value (int): The initial value of the dropdown. Defaults to None.
137
+
138
+ Attributes:
139
+ font (str): The font of the dropdown field.
140
+ choices (List[str | Tuple[str, str]]): The list of choices for the
141
+ dropdown, as strings or `(display, export)` tuples.
142
+ """
143
+ super().__init__(name, value)
144
+ self.SET_ATTR_TRIGGER_HOOK_MAP.update(
145
+ {
146
+ "font": "update_text_field_font",
147
+ "choices": "update_dropdown_choices",
148
+ "font_size": "update_text_field_font_size",
149
+ "font_color": "update_text_field_font_color",
150
+ }
151
+ )
152
+
153
+ self.font: Optional[str] = None
154
+ self.font_size: Optional[float] = None
155
+ self.font_color: Optional[tuple] = None
156
+ self.choices: Optional[tuple | list] = None
157
+
158
+ @property
159
+ def value(self) -> int:
160
+ """
161
+ Gets the current value of the dropdown.
162
+
163
+ Returns:
164
+ int: The index of the selected choice.
165
+ """
166
+ return super().value
167
+
168
+ @value.setter
169
+ def value(self, value: str | int) -> None:
170
+ """
171
+ Sets the value of the dropdown.
172
+
173
+ If the value is a string, it selects the option whose displayed text
174
+ or export value matches it. If none matches, the string value is
175
+ added to the choices, and its new index is used. Integer values are checked
176
+ against the current choices before being stored.
177
+
178
+ Args:
179
+ value (str | int): The value to set. Can be a string
180
+ (displayed text or export value) or an integer (index).
181
+
182
+ Raises:
183
+ ValueError: If an integer index is outside the current choices, or
184
+ a string matches options that differ.
185
+ """
186
+ self.apply_value(self.prepare_value(value))
187
+
188
+ @property
189
+ def options(self) -> tuple[DropdownOption, ...]:
190
+ """
191
+ Returns the current choices as options with explicit export values.
192
+
193
+ Returns:
194
+ tuple[DropdownOption, ...]: The options, in choice order.
195
+ """
196
+ return tuple(DropdownOption.from_choice(each) for each in self.choices or ())
197
+
198
+ def prepare_value(self, value: Any) -> PreparedValue:
199
+ """
200
+ Prepares a dropdown selection without changing its value or choices.
201
+
202
+ Integer indices are checked against the current choices. Strings are
203
+ normalized to the index of the option whose displayed text or export
204
+ value matches, or staged as a new last option, keeping the existing
205
+ choices and their export values. New choices do not trigger hooks until
206
+ the prepared selection is applied.
207
+
208
+ Args:
209
+ value (Any): The proposed displayed text, export value, or index.
210
+
211
+ Returns:
212
+ PreparedValue: The selected index and any replacement choices.
213
+
214
+ Raises:
215
+ ValueError: If an integer index is outside the current choices, or
216
+ a string matches options that differ.
217
+ """
218
+ self.validate_choice_index(value)
219
+ if isinstance(value, str):
220
+ index = self._get_option_index(value)
221
+ if index is None:
222
+ choices = list(self.choices or ()) + [value]
223
+ return PreparedValue(len(choices) - 1, choices)
224
+ value = index
225
+
226
+ return super().prepare_value(value)
227
+
228
+ def apply_value(self, update: PreparedValue) -> None:
229
+ """
230
+ Applies a previously prepared dropdown selection.
231
+
232
+ Replacement choices are stored through the existing attribute setter
233
+ so their PDF update hook is queued before the selected index is stored.
234
+ Validation and option lookup are not repeated during application.
235
+
236
+ Args:
237
+ update (PreparedValue): The prepared selection and optional choices.
238
+ """
239
+ if update.choices is not None:
240
+ self.choices = update.choices
241
+ super().apply_value(update)
242
+
243
+ def choice_index_schema(self) -> dict:
244
+ """
245
+ Returns the schema definition for indices into the current choices.
246
+
247
+ Valid indices range from zero to the number of choices minus one. An
248
+ empty dropdown explicitly rejects every integer selection.
249
+
250
+ Returns:
251
+ dict: A dictionary representing the schema definition for indices.
252
+ """
253
+ number_of_options = len(self.choices or [])
254
+ if not number_of_options:
255
+ return {"type": "integer", "not": {}}
256
+ return {"type": "integer", "minimum": 0, "maximum": number_of_options - 1}
257
+
258
+ def validate_choice_index(self, value: object) -> None:
259
+ """
260
+ Validates an integer selection against the current dropdown choices.
261
+
262
+ Non-integer values retain their existing handling, including strings
263
+ normalized during preparation and None for an unset selection.
264
+
265
+ Args:
266
+ value (object): The proposed value of the dropdown.
267
+
268
+ Raises:
269
+ ValueError: If an integer index is outside the current choices.
270
+ """
271
+ number_of_options = len(self.choices or [])
272
+ if isinstance(value, int) and not 0 <= value < number_of_options:
273
+ msg = f"Choice index {value} must satisfy 0 <= index < {number_of_options}."
274
+ raise ValueError(msg)
275
+
276
+ def _get_option_index(self, value: str) -> int | None:
277
+ """
278
+ Gets the index of the option whose displayed text or export value matches.
279
+
280
+ Identical options, with the same displayed text and export value, are
281
+ interchangeable, so the first is used.
282
+
283
+ Args:
284
+ value (str): The displayed text or export value to search for.
285
+
286
+ Returns:
287
+ int | None: The index of the option if found, otherwise None.
288
+
289
+ Raises:
290
+ ValueError: If the value matches options that differ.
291
+ """
292
+ options = self.options
293
+ matches = [
294
+ i for i, each in enumerate(options) if value in (each.display, each.export)
295
+ ]
296
+ if len({options[i] for i in matches}) > 1:
297
+ msg = (
298
+ f"Dropdown value {value!r} matches the options at indices {matches}; "
299
+ "use an option index instead."
300
+ )
301
+ raise ValueError(msg)
302
+
303
+ return matches[0] if matches else None
304
+
305
+ def get_selected_index(self, value: Any, indices: Any) -> int | None:
306
+ """
307
+ Gets the index of the option selected by a PDF field value.
308
+
309
+ Export values are matched first, because a field's `/V` holds the export
310
+ value. Displayed text is matched only when no export value matches, so
311
+ fields filled with displayed text are still read. Among matching options,
312
+ the first index in `/I`, which can be an indirect object, is used when it
313
+ is one of them; otherwise the first match is used.
314
+
315
+ Args:
316
+ value (Any): The field's `/V` entry.
317
+ indices (Any): The field's `/I` entry.
318
+
319
+ Returns:
320
+ int | None: The index of the selected option, or None when no option
321
+ matches.
322
+ """
323
+ options = self.options
324
+ # array elements are not resolved by subscripting
325
+ hint = (
326
+ indices[0].get_object() if isinstance(indices, list) and indices else None
327
+ )
328
+ for matches in (
329
+ [i for i, each in enumerate(options) if each.export == value],
330
+ [i for i, each in enumerate(options) if each.display == value],
331
+ ):
332
+ if matches:
333
+ return hint if hint in matches else matches[0]
334
+
335
+ return None
336
+
337
+ def ambiguous_values(self) -> list[str]:
338
+ """
339
+ Returns the strings that match options that differ.
340
+
341
+ Returns:
342
+ list[str]: The sorted displayed texts and export values that a string
343
+ selection rejects.
344
+ """
345
+ matches = defaultdict(set)
346
+ for each in self.options:
347
+ matches[each.display].add(each)
348
+ matches[each.export].add(each)
349
+
350
+ return sorted(value for value, options in matches.items() if len(options) > 1)
351
+
352
+ @property
353
+ def schema_definition(self) -> dict:
354
+ """
355
+ Returns the schema definition for the dropdown.
356
+
357
+ The schema definition accepts either an integer option index bounded by
358
+ the current choices or a string value that can be normalized by the value
359
+ setter. Strings that match options that differ are excluded.
360
+
361
+ Returns:
362
+ dict: A dictionary representing the schema definition.
363
+ """
364
+ string_schema: dict = {"type": "string"}
365
+ ambiguous = self.ambiguous_values()
366
+ if ambiguous:
367
+ string_schema["not"] = {"enum": ambiguous}
368
+
369
+ return {
370
+ "anyOf": [
371
+ {
372
+ **self.choice_index_schema(),
373
+ **super().schema_definition,
374
+ },
375
+ string_schema,
376
+ ]
377
+ }
378
+
379
+ @property
380
+ def sample_value(self) -> int | None:
381
+ """
382
+ Returns a sample value for the dropdown.
383
+
384
+ The sample value is used to generate example data for the
385
+ dropdown field. It selects the last available option, or returns None
386
+ when no choices are available so sample data can omit the field.
387
+
388
+ Returns:
389
+ int | None: The last option index, or None when there are no choices.
390
+ """
391
+ return len(self.choices) - 1 if self.choices else None
@@ -26,6 +26,7 @@ from .constants import (
26
26
  HIDDEN,
27
27
  IMAGE_IMPORT_JAVASCRIPT,
28
28
  JS,
29
+ RADIO,
29
30
  SLASH,
30
31
  TU,
31
32
  A,
@@ -51,7 +52,7 @@ from .constants import (
51
52
  Yes,
52
53
  )
53
54
  from .middleware.checkbox import Checkbox
54
- from .middleware.dropdown import Dropdown
55
+ from .middleware.dropdown import Dropdown, DropdownOption
55
56
  from .middleware.image import Image
56
57
  from .middleware.radio import Radio
57
58
  from .middleware.signature import Signature
@@ -126,6 +127,16 @@ WIDGET_TYPE_PATTERNS = [
126
127
  ),
127
128
  Text,
128
129
  ),
130
+ (
131
+ # a radio group's /DV can be /Yes or /Off too, so check it before the /DV rule
132
+ (
133
+ {Subtype: Widget},
134
+ {Parent: {FT: Btn}},
135
+ {AS: (Yes, Off)},
136
+ {Parent: {Ff: lambda flags: int(flags) & RADIO}},
137
+ ),
138
+ Radio,
139
+ ),
129
140
  (
130
141
  (
131
142
  {Subtype: Widget},
@@ -286,8 +297,8 @@ def get_radio_value(annot: DictionaryObject) -> bool:
286
297
 
287
298
  This function iterates through the appearance states (AP) of the radio button
288
299
  annotation. If the value (V) of the parent dictionary matches any of these
289
- appearance states, it means the radio button is selected, and True is returned.
290
- Otherwise, False is returned.
300
+ appearance states other than `/Off`, it means the radio button is selected, and
301
+ True is returned. Otherwise, False is returned.
291
302
 
292
303
  Args:
293
304
  annot (DictionaryObject): The radio button annotation dictionary.
@@ -296,7 +307,7 @@ def get_radio_value(annot: DictionaryObject) -> bool:
296
307
  bool: True if the radio button is selected, False otherwise.
297
308
  """
298
309
  for each in annot.get(AP, {}).get(N, []):
299
- if annot.get(Parent, {}).get(V) == each:
310
+ if each != Off and annot.get(Parent, {}).get(V) == each:
300
311
  return True
301
312
 
302
313
  return False
@@ -308,11 +319,11 @@ def update_dropdown_value(
308
319
  """
309
320
  Updates the value of a dropdown annotation, selecting an option from the list.
310
321
 
311
- This function modifies the value (V) and appearance (AP) of the dropdown
312
- annotation to reflect the selected option. Top-level dropdowns also receive
313
- the selected index (I). Child annotations write the value to their parent
314
- field dictionary. Appearance updates are skipped when `need_appearances` is
315
- enabled.
322
+ This function sets the field's value (V) to the selected option's export
323
+ value and its selected index (I), and sets the annotation's appearance (AP)
324
+ to the option's displayed text. Child annotations write V and I to their
325
+ parent field dictionary. Appearance updates are skipped when
326
+ `need_appearances` is enabled.
316
327
 
317
328
  Args:
318
329
  annot (DictionaryObject): The dropdown annotation dictionary.
@@ -320,42 +331,36 @@ def update_dropdown_value(
320
331
  need_appearances (bool): If True, skips updating the appearance stream (AP) to
321
332
  maintain compatibility with Adobe Reader's behavior for certain fields.
322
333
  """
323
- choices = widget.choices or []
324
- if Parent in annot and T not in annot:
325
- annot[NameObject(Parent)][NameObject(V)] = TextStringObject(
326
- choices[widget.value]
327
- )
328
- if not need_appearances:
329
- annot[NameObject(AP)] = TextStringObject(choices[widget.value])
330
- else:
331
- annot[NameObject(V)] = TextStringObject(choices[widget.value])
332
- annot[NameObject(I)] = ArrayObject([NumberObject(widget.value)])
333
- if not need_appearances:
334
- annot[NameObject(AP)] = TextStringObject(choices[widget.value])
334
+ option = widget.options[widget.value]
335
+ field = annot[NameObject(Parent)] if Parent in annot and T not in annot else annot
336
+ field[NameObject(V)] = TextStringObject(option.export)
337
+ field[NameObject(I)] = ArrayObject([NumberObject(widget.value)])
338
+ if not need_appearances:
339
+ annot[NameObject(AP)] = TextStringObject(option.display)
335
340
 
336
341
 
337
342
  def get_dropdown_value(annot: DictionaryObject, widget: Dropdown) -> None:
338
343
  """
339
344
  Retrieves the selected value of a dropdown annotation and updates the widget.
340
345
 
341
- This function determines the current value of the dropdown, considering
342
- whether it's a child annotation or a top-level one. A matching choice sets
343
- the widget's value to its index, including zero for the first choice. If no
344
- choice matches, the widget's value is left unchanged; an initially unselected
345
- widget remains None.
346
+ This function reads the field's value (V) and selected indices (I), from the
347
+ parent field dictionary for child annotations. V is matched against export
348
+ values, then displayed text, and I chooses among options with the same
349
+ value. A matching option sets the widget's value to its index, including
350
+ zero for the first option. If no option matches, the widget's value is left
351
+ unchanged; an initially unselected widget remains None.
346
352
 
347
353
  Args:
348
354
  annot (DictionaryObject): The dropdown annotation dictionary.
349
355
  widget (Dropdown): The Dropdown widget object to update with the retrieved value.
350
356
  """
351
- if Parent in annot and T not in annot:
352
- to_compare = annot.get(Parent, {}).get(V)
353
- else:
354
- to_compare = annot.get(V)
355
-
356
- for i, each in enumerate(widget.choices):
357
- if each == to_compare:
358
- widget.value = i
357
+ field = annot[NameObject(Parent)] if Parent in annot and T not in annot else annot
358
+ # discovered annotations are plain dictionaries, so entries can be references
359
+ value = field[NameObject(V)].get_object() if V in field else None
360
+ indices = field[NameObject(I)].get_object() if I in field else None
361
+ index = widget.get_selected_index(value, indices)
362
+ if index is not None:
363
+ widget.value = index
359
364
 
360
365
 
361
366
  def update_text_value(
@@ -429,35 +434,29 @@ def get_text_field_alignment(widget: dict) -> int | None:
429
434
  return int(widget[Q]) if Q in widget else None
430
435
 
431
436
 
432
- def get_dropdown_choices(widget: dict) -> Tuple[str, ...]:
437
+ def get_dropdown_choices(widget: dict) -> Tuple[str | Tuple[str, str], ...]:
433
438
  """
434
439
  Extracts the choices from a dropdown widget dictionary.
435
440
 
436
- This function extracts the choices from a dropdown widget dictionary. Direct
437
- string options are returned as-is. Two-item PDF option arrays return the
438
- display value stored at index 1. Empty or missing options produce an empty
439
- tuple. An explicitly empty widget option array is preserved even when its
440
- parent has options.
441
+ This function extracts the choices from a dropdown widget dictionary. Each
442
+ option is returned as a string when its displayed text and export value are
443
+ equal, or as a `(display, export)` tuple when they differ. Empty or missing
444
+ options produce an empty tuple. An explicitly empty widget option array is
445
+ preserved even when its parent has options.
441
446
 
442
447
  Args:
443
448
  widget (dict): The widget dictionary to extract the choices from.
444
449
 
445
450
  Returns:
446
- Tuple[str, ...]: The dropdown choices, or an empty tuple when none exist.
451
+ Tuple[str | Tuple[str, str], ...]: The dropdown choices, or an empty
452
+ tuple when none exist.
447
453
  """
448
454
  choices = (
449
455
  widget[Opt]
450
456
  if Opt in widget
451
457
  else extract_widget_property(widget, DROPDOWN_CHOICE_PATTERNS, (), None)
452
458
  )
453
- return tuple(
454
- (
455
- each.get_object()
456
- if isinstance(each.get_object(), str)
457
- else str(each.get_object()[1])
458
- )
459
- for each in choices
460
- )
459
+ return tuple(DropdownOption.from_pdf(each).choice for each in choices)
461
460
 
462
461
 
463
462
  def update_annotation_name(annot: DictionaryObject, val: str) -> None:
@@ -278,7 +278,8 @@ def _is_value_match(pattern_value: Any, widget_value: Any) -> bool:
278
278
 
279
279
  Nested dictionaries delegate to `find_pattern_match`. Tuple pattern values
280
280
  support matching any listed value, and a tuple containing ``"/"`` also
281
- matches PDF names with arbitrary slash-prefixed values.
281
+ matches PDF names with arbitrary slash-prefixed values. Callable pattern
282
+ values are predicates called with the widget value.
282
283
 
283
284
  Args:
284
285
  pattern_value (Any): The value from the pattern.
@@ -292,6 +293,9 @@ def _is_value_match(pattern_value: Any, widget_value: Any) -> bool:
292
293
  ):
293
294
  return find_pattern_match(pattern_value, widget_value)
294
295
 
296
+ if callable(pattern_value):
297
+ return bool(pattern_value(widget_value))
298
+
295
299
  if isinstance(pattern_value, tuple):
296
300
  if widget_value in pattern_value:
297
301
  return True
@@ -13,6 +13,7 @@ specific functionality for interacting with dropdown form fields in PDFs.
13
13
  from dataclasses import dataclass
14
14
  from typing import List, Optional, Tuple, Type
15
15
 
16
+ from ..middleware.dropdown import DropdownOption
16
17
  from .base import Field, Widget
17
18
  from .text import TextWidget
18
19
 
@@ -22,9 +23,8 @@ class DropdownWidget(TextWidget):
22
23
  Represents a dropdown widget in a PDF form.
23
24
 
24
25
  Inherits from the base TextWidget class and replaces text-field creation with
25
- ReportLab's choice-field path. The first option is used as the initial value,
26
- with a single space substituted for an empty first option to work around
27
- ReportLab behavior.
26
+ ReportLab's choice-field path. The first option's export value is used as the
27
+ initial value.
28
28
 
29
29
  Attributes:
30
30
  NONE_DEFAULTS (list): A list of parameters that default to None.
@@ -62,9 +62,11 @@ class DropdownWidget(TextWidget):
62
62
  ]
63
63
  super().__init__(name, page_number, x, y, **kwargs)
64
64
  self.acro_form_params["wkind"] = "choice"
65
- self.acro_form_params["value"] = (
66
- self.acro_form_params["options"][0] or " " # reportlab bug
67
- )
65
+ # ReportLab fails on an empty string value; a one-item list selects the
66
+ # option by its export value, including an empty one.
67
+ self.acro_form_params["value"] = [
68
+ DropdownOption.from_choice(self.acro_form_params["options"][0]).export
69
+ ]
68
70
 
69
71
 
70
72
  @dataclass