PyPDFForm 6.1.1__tar.gz → 6.3.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 (91) hide show
  1. {pypdfform-6.1.1 → pypdfform-6.3.0}/PKG-INFO +3 -3
  2. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/__init__.py +1 -1
  3. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/cli/common.py +20 -0
  4. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/cli/create.py +4 -3
  5. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/cli/inspect.py +10 -7
  6. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/cli/remove.py +14 -5
  7. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/cli/root.py +5 -2
  8. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/cli/schemas/update.py +1 -1
  9. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/clone.py +100 -16
  10. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/constants.py +91 -4
  11. pypdfform-6.3.0/PyPDFForm/lib/default_appearance.py +722 -0
  12. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/egress.py +51 -68
  13. pypdfform-6.3.0/PyPDFForm/lib/field_tree.py +1182 -0
  14. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/filler.py +91 -50
  15. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/font.py +86 -31
  16. pypdfform-6.3.0/PyPDFForm/lib/hooks.py +848 -0
  17. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/middleware/base.py +162 -20
  18. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/middleware/checkbox.py +11 -6
  19. pypdfform-6.3.0/PyPDFForm/lib/middleware/dropdown.py +403 -0
  20. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/middleware/radio.py +26 -0
  21. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/middleware/signature.py +3 -1
  22. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/middleware/text.py +52 -8
  23. pypdfform-6.3.0/PyPDFForm/lib/patterns.py +834 -0
  24. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/template.py +126 -95
  25. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/utils.py +349 -84
  26. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/watermark.py +17 -88
  27. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/widgets/dropdown.py +8 -6
  28. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/wrapper.py +497 -170
  29. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm.egg-info/PKG-INFO +3 -3
  30. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm.egg-info/SOURCES.txt +2 -0
  31. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm.egg-info/requires.txt +2 -2
  32. {pypdfform-6.1.1 → pypdfform-6.3.0}/pyproject.toml +3 -4
  33. {pypdfform-6.1.1 → pypdfform-6.3.0}/tests/test_bulk_create_fields.py +26 -8
  34. {pypdfform-6.1.1 → pypdfform-6.3.0}/tests/test_create_widget.py +48 -66
  35. {pypdfform-6.1.1 → pypdfform-6.3.0}/tests/test_draw_elements.py +4 -10
  36. {pypdfform-6.1.1 → pypdfform-6.3.0}/tests/test_dropdown.py +26 -8
  37. {pypdfform-6.1.1 → pypdfform-6.3.0}/tests/test_font_related.py +103 -2
  38. {pypdfform-6.1.1 → pypdfform-6.3.0}/tests/test_functional.py +2098 -89
  39. {pypdfform-6.1.1 → pypdfform-6.3.0}/tests/test_generate_appearance_streams.py +18 -8
  40. {pypdfform-6.1.1 → pypdfform-6.3.0}/tests/test_need_appearances.py +4 -6
  41. {pypdfform-6.1.1 → pypdfform-6.3.0}/tests/test_paragraph.py +6 -10
  42. {pypdfform-6.1.1 → pypdfform-6.3.0}/tests/test_signature.py +86 -38
  43. {pypdfform-6.1.1 → pypdfform-6.3.0}/tests/test_use_full_widget_name.py +3 -1
  44. pypdfform-6.3.0/tests/test_widget_attr_trigger.py +3898 -0
  45. pypdfform-6.1.1/PyPDFForm/lib/hooks.py +0 -668
  46. pypdfform-6.1.1/PyPDFForm/lib/middleware/dropdown.py +0 -223
  47. pypdfform-6.1.1/PyPDFForm/lib/patterns.py +0 -517
  48. pypdfform-6.1.1/tests/test_widget_attr_trigger.py +0 -356
  49. {pypdfform-6.1.1 → pypdfform-6.3.0}/LICENSE +0 -0
  50. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/cli/__init__.py +0 -0
  51. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/cli/entry.py +0 -0
  52. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/cli/schemas/__init__.py +0 -0
  53. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/cli/schemas/create.py +0 -0
  54. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/cli/update.py +0 -0
  55. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/__init__.py +0 -0
  56. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/adapter.py +0 -0
  57. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/annotations/__init__.py +0 -0
  58. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/annotations/base.py +0 -0
  59. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/annotations/link.py +0 -0
  60. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/annotations/stamp.py +0 -0
  61. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/annotations/text.py +0 -0
  62. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/annotations/text_markup.py +0 -0
  63. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/assets/__init__.py +0 -0
  64. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/assets/blank.py +0 -0
  65. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/coordinate.py +0 -0
  66. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/deprecation.py +0 -0
  67. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/image.py +0 -0
  68. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/middleware/__init__.py +0 -0
  69. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/middleware/image.py +0 -0
  70. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/raw/__init__.py +0 -0
  71. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/raw/circle.py +0 -0
  72. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/raw/ellipse.py +0 -0
  73. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/raw/image.py +0 -0
  74. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/raw/line.py +0 -0
  75. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/raw/rect.py +0 -0
  76. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/raw/text.py +0 -0
  77. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/widgets/__init__.py +0 -0
  78. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/widgets/base.py +0 -0
  79. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/widgets/checkbox.py +0 -0
  80. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/widgets/image.py +0 -0
  81. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/widgets/radio.py +0 -0
  82. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/widgets/signature.py +0 -0
  83. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm/lib/widgets/text.py +0 -0
  84. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm.egg-info/dependency_links.txt +0 -0
  85. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm.egg-info/entry_points.txt +0 -0
  86. {pypdfform-6.1.1 → pypdfform-6.3.0}/PyPDFForm.egg-info/top_level.txt +0 -0
  87. {pypdfform-6.1.1 → pypdfform-6.3.0}/README.md +0 -0
  88. {pypdfform-6.1.1 → pypdfform-6.3.0}/setup.cfg +0 -0
  89. {pypdfform-6.1.1 → pypdfform-6.3.0}/tests/test_extract_middleware_attributes.py +0 -0
  90. {pypdfform-6.1.1 → pypdfform-6.3.0}/tests/test_fill_max_length_text_field.py +0 -0
  91. {pypdfform-6.1.1 → pypdfform-6.3.0}/tests/test_js.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.3.0
4
4
  Summary: The Python library & CLI for PDF forms.
5
5
  Author: Jinge Li
6
6
  License-Expression: MIT
@@ -27,8 +27,8 @@ 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
31
- Requires-Dist: pypdf<7.0.0,>=6.19.0
30
+ Requires-Dist: pillow<14.0.0,>=13.0.0
31
+ Requires-Dist: pypdf<8.0.0,>=6.19.0
32
32
  Requires-Dist: reportlab<6.0.0,>=4.5.1
33
33
  Provides-Extra: cli
34
34
  Requires-Dist: typer<1.0.0,>=0.26.1; 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.3.0"
20
20
 
21
21
  from .lib.annotations import Annotations
22
22
  from .lib.assets.blank import BlankPage
@@ -248,6 +248,26 @@ def load_data_options(options: list[str], schema: dict, param_hint: str) -> Any:
248
248
  return _validate_input_data(input_data, schema, "CLI options", param_hint)
249
249
 
250
250
 
251
+ def without_unnamed(values: dict) -> dict:
252
+ """
253
+ Leaves out the entries of fields without a name from a mapping by widget key.
254
+
255
+ Without full widget names, a widget whose field has no name has the key
256
+ None, which JSON can't represent: it would be written as `"null"`, which
257
+ another field may be named, and a data file couldn't fill it. Such fields
258
+ are left out of the CLI's JSON output and of the schema that fill data is
259
+ validated against. With full names, such a widget's key is `""`, which is
260
+ kept.
261
+
262
+ Args:
263
+ values (dict): A mapping by widget key, such as `PdfWrapper.data`.
264
+
265
+ Returns:
266
+ dict: A copy of the mapping without the None key.
267
+ """
268
+ return {key: value for key, value in values.items() if key is not None}
269
+
270
+
251
271
  def get_widget(wrapper: PdfWrapper, field: str, param_hint: str) -> Widget:
252
272
  """
253
273
  Look up a widget and report missing names as CLI input errors.
@@ -128,9 +128,10 @@ def extract(
128
128
  by `PdfWrapper.pages`, and writes the extracted pages to the required
129
129
  output path. Each page is extracted separately, so links and other GoTo
130
130
  actions to other pages are removed, and fields shared with other pages keep
131
- only their widgets on each page. A `ValueError` from `PdfWrapper.pages`
132
- for other references to another page's content is not converted, so the
133
- command exits with an error before writing the output.
131
+ only their widgets on each page. A `ValueError` from `PdfWrapper.pages`,
132
+ for other references to another page's content or for a shared field
133
+ with a `/Parent` cycle, is not converted, so the command exits with an
134
+ error before writing the output.
134
135
 
135
136
  Args:
136
137
  ctx (typer.Context): Typer context containing global `PdfWrapper`
@@ -13,7 +13,7 @@ import json
13
13
  import typer
14
14
 
15
15
  from .. import PdfWrapper
16
- from .common import FIELD_NAME, INPUT_PDF, get_widget
16
+ from .common import FIELD_NAME, INPUT_PDF, get_widget, without_unnamed
17
17
 
18
18
  inspect_cli = typer.Typer(
19
19
  context_settings={"help_option_names": ["--help", "-h"]}, no_args_is_help=True
@@ -55,14 +55,16 @@ def schema(
55
55
 
56
56
  The command loads the PDF with the global CLI options stored in `ctx.obj`,
57
57
  reads `PdfWrapper.schema`, serializes it as JSON, and writes it to standard
58
- output.
58
+ output. Fields without a name are left out, as `without_unnamed` describes.
59
59
 
60
60
  Args:
61
61
  ctx (typer.Context): Typer context containing global `PdfWrapper`
62
62
  options in `ctx.obj`.
63
63
  pdf (Path): Input PDF path.
64
64
  """
65
- typer.echo(json.dumps(PdfWrapper(str(pdf), **ctx.obj).schema))
65
+ form_schema = PdfWrapper(str(pdf), **ctx.obj).schema
66
+ form_schema["properties"] = without_unnamed(form_schema["properties"])
67
+ typer.echo(json.dumps(form_schema))
66
68
 
67
69
 
68
70
  @inspect_cli.command(
@@ -78,14 +80,14 @@ def data(
78
80
 
79
81
  The command loads the PDF with the global CLI options stored in `ctx.obj`,
80
82
  reads `PdfWrapper.data`, serializes it as JSON, and writes it to standard
81
- output.
83
+ output. Fields without a name are left out, as `without_unnamed` describes.
82
84
 
83
85
  Args:
84
86
  ctx (typer.Context): Typer context containing global `PdfWrapper`
85
87
  options in `ctx.obj`.
86
88
  pdf (Path): Input PDF path.
87
89
  """
88
- typer.echo(json.dumps(PdfWrapper(str(pdf), **ctx.obj).data))
90
+ typer.echo(json.dumps(without_unnamed(PdfWrapper(str(pdf), **ctx.obj).data)))
89
91
 
90
92
 
91
93
  @inspect_cli.command(
@@ -101,14 +103,15 @@ def sample(
101
103
 
102
104
  The command loads the PDF with the global CLI options stored in `ctx.obj`,
103
105
  reads `PdfWrapper.sample_data`, serializes it as JSON, and writes it to
104
- standard output.
106
+ standard output. Fields without a name are left out, as `without_unnamed`
107
+ describes.
105
108
 
106
109
  Args:
107
110
  ctx (typer.Context): Typer context containing global `PdfWrapper`
108
111
  options in `ctx.obj`.
109
112
  pdf (Path): Input PDF path.
110
113
  """
111
- typer.echo(json.dumps(PdfWrapper(str(pdf), **ctx.obj).sample_data))
114
+ typer.echo(json.dumps(without_unnamed(PdfWrapper(str(pdf), **ctx.obj).sample_data)))
112
115
 
113
116
 
114
117
  @inspect_cli.command(
@@ -11,6 +11,7 @@ either the requested output path or the original file.
11
11
  import typer
12
12
 
13
13
  from .. import PdfWrapper
14
+ from ..lib.field_tree import get_field_keys
14
15
  from .common import FIELD_NAMES, INPUT_PDF, OPTIONAL_OUTPUT_PDF, get_widget
15
16
 
16
17
  remove_cli = typer.Typer(
@@ -32,9 +33,11 @@ def field(
32
33
  Remove one or more named form fields from an existing PDF.
33
34
 
34
35
  The command loads the PDF with the global CLI options stored in `ctx.obj`,
35
- validates each requested field name before changing the document, removes
36
- the fields through `PdfWrapper.remove_fields`, and writes the modified PDF
37
- to the requested output path or back to the input file.
36
+ validates that each requested name matches a form field, including fields
37
+ without a widget on any page, before changing the document, removes the
38
+ fields through `PdfWrapper.remove_fields`, which also updates the form
39
+ actions that name them, and writes the modified PDF to the requested
40
+ output path or back to the input file.
38
41
 
39
42
  Args:
40
43
  ctx (typer.Context): Typer context containing global `PdfWrapper`
@@ -48,7 +51,13 @@ def field(
48
51
  typer.BadParameter: Raised when any requested field does not exist.
49
52
  """
50
53
  obj = PdfWrapper(str(pdf), **ctx.obj)
51
- for field_name in fields:
52
- get_widget(obj, field_name, "--field")
54
+ missing = [field_name for field_name in fields if field_name not in obj.widgets]
55
+ if missing:
56
+ field_keys = get_field_keys(
57
+ pdf.read_bytes(), getattr(obj, "use_full_widget_name")
58
+ )
59
+ for field_name in missing:
60
+ if field_name not in field_keys:
61
+ get_widget(obj, field_name, "--field")
53
62
 
54
63
  obj.remove_fields(fields).write(output or pdf)
@@ -27,6 +27,7 @@ from .common import (
27
27
  data_file_option,
28
28
  load_data_file,
29
29
  load_data_options,
30
+ without_unnamed,
30
31
  )
31
32
  from .create import create_cli
32
33
  from .inspect import inspect_cli
@@ -165,7 +166,8 @@ def fill(
165
166
  accept path objects, validates the input data, normalizes image and
166
167
  signature values, and writes the filled PDF to the requested output path or
167
168
  back to the input file. When both a data file and field options are supplied,
168
- the data file takes precedence.
169
+ the data file takes precedence. Fields without a name are left out of the
170
+ schema, as `without_unnamed` describes, so the data can't fill them.
169
171
 
170
172
  Args:
171
173
  ctx (typer.Context): Typer context containing global `PdfWrapper`
@@ -182,7 +184,8 @@ def fill(
182
184
  obj = PdfWrapper(str(pdf), **ctx.obj)
183
185
 
184
186
  schema = obj.schema
185
- for key, widget in obj.widgets.items():
187
+ schema["properties"] = without_unnamed(schema["properties"])
188
+ for key, widget in without_unnamed(obj.widgets).items():
186
189
  if isinstance(widget, (Widgets.Image, Widgets.Signature)):
187
190
  schema["properties"][key] = {
188
191
  "anyOf": [
@@ -49,7 +49,7 @@ FIELD_SCHEMA = {
49
49
  "comb": {"type": "boolean"},
50
50
  "alignment": {"type": "integer", "minimum": 0, "maximum": 2},
51
51
  "multiline": {"type": "boolean"},
52
- "max_length": {"type": "integer", "minimum": 0},
52
+ "max_length": {"type": "integer", "minimum": 1},
53
53
  "choices": {
54
54
  "type": "array",
55
55
  "items": {
@@ -17,6 +17,7 @@ from pypdf.generic import (
17
17
  DictionaryObject,
18
18
  IndirectObject,
19
19
  NameObject,
20
+ NullObject,
20
21
  StreamObject,
21
22
  )
22
23
 
@@ -25,6 +26,7 @@ from .constants import (
25
26
  AS,
26
27
  DV,
27
28
  FT,
29
+ NAMED_TARGETS,
28
30
  A,
29
31
  AcroForm,
30
32
  Annots,
@@ -33,7 +35,6 @@ from .constants import (
33
35
  Dest,
34
36
  Fields,
35
37
  GoTo,
36
- Hide,
37
38
  Kids,
38
39
  Link,
39
40
  N,
@@ -42,10 +43,8 @@ from .constants import (
42
43
  P,
43
44
  Parent,
44
45
  R,
45
- ResetForm,
46
46
  Root,
47
47
  S,
48
- SubmitForm,
49
48
  Subtype,
50
49
  T,
51
50
  V,
@@ -53,6 +52,26 @@ from .constants import (
53
52
  )
54
53
 
55
54
 
55
+ def _get_entry(obj: DictionaryObject, key: str) -> object:
56
+ """
57
+ Gets an entry of a dictionary, resolving an indirect reference.
58
+
59
+ It is `utils.get_entry`, which this module can't import, since `utils`
60
+ imports it.
61
+
62
+ Args:
63
+ obj (DictionaryObject): The dictionary to read.
64
+ key (str): The entry's key.
65
+
66
+ Returns:
67
+ object: The resolved value, or None when the entry is missing or null,
68
+ which ISO 32000-1 treats as absent.
69
+ """
70
+ value = obj.get(key)
71
+ value = value.get_object() if value is not None else None
72
+ return None if isinstance(value, NullObject) else value
73
+
74
+
56
75
  class ClonePlan:
57
76
  """
58
77
  Keeps the objects cloned with the annotations of selected pages within those pages.
@@ -70,6 +89,9 @@ class ClonePlan:
70
89
  and fields whose widgets are all not cloned, so a field shared with other
71
90
  pages keeps only the cloned part of its hierarchy. A button field's
72
91
  `/Opt` and positional on-states are updated to match its remaining kids.
92
+ Pruning a field raises `ValueError` when an entry it needs, such as an
93
+ inherited `/Opt`, is looked up along a `/Parent` chain that reaches a
94
+ cycle before the entry is found.
73
95
  * GoTo actions whose explicit destination is an excluded page are removed,
74
96
  together with any actions chained after them.
75
97
  * Any other reference to an excluded page, the page tree, the AcroForm
@@ -80,7 +102,6 @@ class ClonePlan:
80
102
  """
81
103
 
82
104
  _REMOVE = object()
83
- _NAMED_TARGETS = {ResetForm: Fields, SubmitForm: Fields, Hide: T}
84
105
 
85
106
  def __init__(
86
107
  self,
@@ -346,7 +367,7 @@ class ClonePlan:
346
367
  while stack:
347
368
  reference, prefix = stack.pop()
348
369
  node = cast(DictionaryObject, reference.get_object())
349
- if T in node:
370
+ if _get_entry(node, T) is not None:
350
371
  prefix = f"{prefix}.{node[T]}" if prefix else str(node[T])
351
372
  self._field_names.setdefault(prefix, reference)
352
373
  kids = [
@@ -381,7 +402,7 @@ class ClonePlan:
381
402
  Raises:
382
403
  ValueError: If the action names a field that is not cloned.
383
404
  """
384
- key = self._NAMED_TARGETS.get(action.get(S))
405
+ key = NAMED_TARGETS.get(action.get(S))
385
406
  if key is None or key not in action:
386
407
  return
387
408
 
@@ -396,7 +417,53 @@ class ClonePlan:
396
417
  if isinstance(name, str) and self._is_excluded(self._find_field(name)):
397
418
  self._reject(entry_path, page_number)
398
419
 
399
- def _prune_kids(self, field: DictionaryObject) -> None:
420
+ @staticmethod
421
+ def _get_inherited(
422
+ field: DictionaryObject, key: str, page_number: int, default: Any = None
423
+ ) -> Any:
424
+ """
425
+ Gets an entry of a field or of the nearest dictionary above it that has one.
426
+
427
+ It follows the `/Parent` chain as pypdf's `get_inherited` does, but
428
+ raises `ValueError` rather than pypdf's `LimitReachedError` when the
429
+ chain reaches a dictionary a second time before the entry is found. An
430
+ entry found before that is returned, so the same pages are copied. A
431
+ null entry is absent, as ISO 32000-1 specifies, so the lookup continues
432
+ past it. A `/Parent` that doesn't resolve to a dictionary, such as a
433
+ number, null, or a reference to a missing object, which ISO 32000-1
434
+ treats as null, ends the chain.
435
+
436
+ Args:
437
+ field (DictionaryObject): A source field.
438
+ key (str): The entry to look up, such as `/Opt`.
439
+ page_number (int): The 1-based source page being guarded.
440
+ default (Any): The value when no dictionary in the chain has the
441
+ entry. Defaults to None.
442
+
443
+ Returns:
444
+ Any: The entry's value, or `default`.
445
+
446
+ Raises:
447
+ ValueError: If the `/Parent` chain has a cycle before the entry is
448
+ found.
449
+ """
450
+ seen = set()
451
+ node: Any = field
452
+ while isinstance(node, DictionaryObject):
453
+ if id(node) in seen:
454
+ msg = (
455
+ f"Cannot copy page {page_number}: the /Parent chain of the "
456
+ "field has a cycle."
457
+ )
458
+ raise ValueError(msg)
459
+ seen.add(id(node))
460
+ if _get_entry(node, key) is not None:
461
+ return node[key]
462
+ parent = node.get(Parent)
463
+ node = parent.get_object() if parent is not None else None
464
+ return default
465
+
466
+ def _prune_kids(self, field: DictionaryObject, page_number: int) -> None:
400
467
  """
401
468
  Removes kids that are not cloned from a field's `/Kids`.
402
469
 
@@ -409,20 +476,25 @@ class ClonePlan:
409
476
 
410
477
  Args:
411
478
  field (DictionaryObject): A source dictionary with `/Kids`.
479
+ page_number (int): The 1-based source page being guarded.
480
+
481
+ Raises:
482
+ ValueError: If an inherited entry the field needs is looked up
483
+ along a `/Parent` chain with a cycle before it is found.
412
484
  """
413
485
  kids = field[Kids]
414
486
  keep = [index for index, kid in enumerate(kids) if not self._is_excluded(kid)]
415
487
  if len(keep) == len(kids):
416
488
  return
417
489
 
418
- options = field.get_inherited(Opt, ArrayObject())
490
+ options = self._get_inherited(field, Opt, page_number, ArrayObject())
419
491
  if (
420
- field.get_inherited(FT) == Btn
492
+ self._get_inherited(field, FT, page_number) == Btn
421
493
  and len(options) == len(kids)
422
494
  and all(kid.get_object().get(Subtype) == Widget for kid in kids)
423
495
  ):
424
496
  self._renumber_states(
425
- field, [kids[index].get_object() for index in keep], keep
497
+ field, [kids[index].get_object() for index in keep], keep, page_number
426
498
  )
427
499
  field[NameObject(Opt)] = ArrayObject(options[index] for index in keep)
428
500
  self._original_kids[id(field)] = kids
@@ -430,7 +502,10 @@ class ClonePlan:
430
502
 
431
503
  @staticmethod
432
504
  def _renumber_states(
433
- field: DictionaryObject, kids: List[DictionaryObject], keep: List[int]
505
+ field: DictionaryObject,
506
+ kids: List[DictionaryObject],
507
+ keep: List[int],
508
+ page_number: int,
434
509
  ) -> None:
435
510
  """
436
511
  Renumbers positional states after a button field's `/Kids` are pruned.
@@ -453,12 +528,17 @@ class ClonePlan:
453
528
  field (DictionaryObject): The button field.
454
529
  kids (List[DictionaryObject]): The remaining kids, in order.
455
530
  keep (List[int]): The original positions of the remaining kids.
531
+ page_number (int): The 1-based source page being guarded.
532
+
533
+ Raises:
534
+ ValueError: If the field's `/V` or `/DV` is looked up along a
535
+ `/Parent` chain with a cycle before it is found.
456
536
  """
457
537
  states = {
458
538
  NameObject(f"/{old}"): NameObject(f"/{new}") for new, old in enumerate(keep)
459
539
  }
460
540
  for key in (V, DV):
461
- value = field.get_inherited(key)
541
+ value = ClonePlan._get_inherited(field, key, page_number)
462
542
  if not (isinstance(value, NameObject) and value[1:].isdigit()):
463
543
  continue
464
544
  if value in states:
@@ -466,7 +546,7 @@ class ClonePlan:
466
546
  continue
467
547
  if key in field:
468
548
  del field[key]
469
- if field.get_inherited(key) is not None:
549
+ if ClonePlan._get_inherited(field, key, page_number) is not None:
470
550
  field[NameObject(key)] = NameObject(Off)
471
551
 
472
552
  copies: Dict[int, tuple[DictionaryObject, DictionaryObject]] = {}
@@ -581,7 +661,9 @@ class ClonePlan:
581
661
  skip (Iterable[str]): Keys of the root that are not followed.
582
662
 
583
663
  Raises:
584
- ValueError: If a reachable object refers to excluded content.
664
+ ValueError: If a reachable object refers to excluded content,
665
+ or a field to prune has a `/Parent` cycle before an entry it
666
+ inherits.
585
667
  """
586
668
  stack: List[tuple[Any, str]] = [(root, path)]
587
669
  while stack:
@@ -593,7 +675,7 @@ class ClonePlan:
593
675
  is_dict = isinstance(obj, DictionaryObject)
594
676
  if is_dict:
595
677
  if Kids in obj:
596
- self._prune_kids(obj)
678
+ self._prune_kids(obj, page_number)
597
679
  self._check_named_targets(obj, path, page_number)
598
680
  entries = (
599
681
  [(key, obj.raw_get(key)) for key in list(obj)]
@@ -631,7 +713,9 @@ class ClonePlan:
631
713
  List[List[Any]]: The cloned annotations, one list per source page.
632
714
 
633
715
  Raises:
634
- ValueError: If a selected annotation refers to excluded content.
716
+ ValueError: If a selected annotation refers to excluded content,
717
+ or a field to prune has a `/Parent` cycle before an entry it
718
+ inherits.
635
719
  """
636
720
  for page_number, selected in enumerate(self.annotations, 1):
637
721
  for index, annot in selected:
@@ -117,9 +117,14 @@ GoTo = "/GoTo"
117
117
  ResetForm = "/ResetForm"
118
118
  SubmitForm = "/SubmitForm"
119
119
  Hide = "/Hide"
120
+ Next = "/Next"
121
+ Flags = "/Flags"
120
122
  JavaScript = "/JavaScript"
121
123
  JS = "/JS"
122
124
  OpenAction = "/OpenAction"
125
+ # navigation node forward and backward actions
126
+ NA = "/NA"
127
+ PA = "/PA"
123
128
  E = "/E"
124
129
  X = "/X"
125
130
  D = "/D"
@@ -163,23 +168,107 @@ FONT_NAME_PREFIX = "/F"
163
168
  # For Adobe Acrobat
164
169
  AcroForm = "/AcroForm"
165
170
  Fields = "/Fields"
171
+ CO = "/CO"
166
172
  XFA = "/XFA"
167
173
 
174
+ # action type -> the entry that names the fields or annotations it acts on
175
+ NAMED_TARGETS = {ResetForm: Fields, SubmitForm: Fields, Hide: T}
176
+ # ResetForm and SubmitForm flag bit: act on every field except the named ones
177
+ INCLUDE_EXCLUDE = 1 << 0
178
+
168
179
  # Field flag bits
169
180
  READ_ONLY = 1 << 0
170
181
  REQUIRED = 1 << 1
171
182
  MULTILINE = 1 << 12
183
+ RADIO = 1 << 15
184
+ PUSHBUTTON = 1 << 16
172
185
  COMB = 1 << 24
173
186
 
174
187
  # annotation flag bits
175
188
  HIDDEN = 1 << 1
176
189
 
190
+ # entries read when choosing a PDF version
191
+ Info = "/Info"
192
+ Version = "/Version"
193
+ ToUnicode = "/ToUnicode"
194
+ SMask = "/SMask"
195
+ URI = "/URI"
196
+ CA = "/CA"
197
+ ca = "/ca"
198
+
199
+ # Minimum PDF versions of the features that PyPDFForm can add, from the
200
+ # "(PDF 1.x)" marks of the PDF Reference
201
+ FEATURE_VERSIONS_BY_KEY = {
202
+ # an annotation's title; fields, Hide actions, and threads are 1.1 or later
203
+ T: "1.1",
204
+ FontFile2: "1.1",
205
+ OpenAction: "1.1",
206
+ AcroForm: "1.2",
207
+ ToUnicode: "1.2",
208
+ TU: "1.3",
209
+ SMask: "1.4",
210
+ }
211
+ FEATURE_VERSIONS_BY_SUBTYPE = {
212
+ Widget: "1.2",
213
+ "/Stamp": "1.3",
214
+ "/Highlight": "1.3",
215
+ "/Underline": "1.3",
216
+ "/StrikeOut": "1.3",
217
+ "/Squiggly": "1.4",
218
+ }
219
+ FEATURE_VERSIONS_BY_ACTION = {URI: "1.1", JavaScript: "1.3"}
220
+ FEATURE_VERSIONS_BY_FILTER = {FlateDecode: "1.2"}
221
+ FEATURE_VERSIONS_BY_FIELD_TYPE = {Sig: "1.3"}
222
+ TITLE_VERSION = "1.1" # the title in the document information dictionary
223
+ ALPHA_VERSION = "1.4" # a numeric /CA or /ca, for constant opacity
224
+ COMB_VERSION = "1.5" # also RadiosInUnison, the same bit for radio buttons
225
+ # widget property hooks that write a JavaScript action, whatever the script
226
+ JAVASCRIPT_HOOKS = frozenset(
227
+ {
228
+ "update_field_on_hovered_over_javascript",
229
+ "update_field_on_hovered_off_javascript",
230
+ "update_field_on_mouse_pressed_javascript",
231
+ "update_field_on_mouse_released_javascript",
232
+ "update_field_on_focused_javascript",
233
+ "update_field_on_blurred_javascript",
234
+ }
235
+ )
236
+ # widget property hooks that can add or remove a feature above: comb (1.5),
237
+ # tooltips (/TU), and JavaScript actions; PdfWrapper.version applies them to
238
+ # a copy of the PDF while they are queued
239
+ FEATURE_HOOKS = (
240
+ frozenset({"update_text_field_comb", "update_field_tooltip"}) | JAVASCRIPT_HOOKS
241
+ )
242
+ # the font hook, whose user-facing font names PdfWrapper maps to resource names
243
+ FONT_HOOK = "update_text_field_font"
244
+ # widget property hooks that change the default appearance (/DA), which a
245
+ # field can inherit from its ancestors or the AcroForm; they get the AcroForm
246
+ DEFAULT_APPEARANCE_HOOKS = frozenset(
247
+ {
248
+ FONT_HOOK,
249
+ "update_text_field_font_size",
250
+ "update_text_field_font_color",
251
+ }
252
+ )
253
+ # no feature above needs a newer version, so newer documents are never raised
254
+ NEWEST_FEATURE_VERSION = max(
255
+ [
256
+ *FEATURE_VERSIONS_BY_KEY.values(),
257
+ *FEATURE_VERSIONS_BY_SUBTYPE.values(),
258
+ *FEATURE_VERSIONS_BY_ACTION.values(),
259
+ *FEATURE_VERSIONS_BY_FILTER.values(),
260
+ *FEATURE_VERSIONS_BY_FIELD_TYPE.values(),
261
+ TITLE_VERSION,
262
+ ALPHA_VERSION,
263
+ COMB_VERSION,
264
+ ],
265
+ key=lambda version: tuple(int(part) for part in version.split(".")),
266
+ )
267
+
177
268
  # reportlab acroform func
178
269
  fieldFlags = "fieldFlags"
179
270
  required = "required"
180
271
 
181
- FONT_SIZE_IDENTIFIER = "Tf"
182
- FONT_COLOR_IDENTIFIER = " rg"
183
272
  DEFAULT_FONT = "Helvetica"
184
273
  DEFAULT_FONT_SIZE = 12
185
274
  DEFAULT_FONT_COLOR = (0, 0, 0)
@@ -189,8 +278,6 @@ IMAGE_IMPORT_JAVASCRIPT = "event.target.buttonImportIcon();"
189
278
  COORDINATE_GRID_FONT_SIZE_MARGIN_RATIO = DEFAULT_FONT_SIZE / 100
190
279
  UNIQUE_SUFFIX_LENGTH = 20
191
280
 
192
- SLASH = "/"
193
-
194
281
  # blank page
195
282
  BLANK_PAGE_DEFAULT_WIDTH = 612
196
283
  BLANK_PAGE_DEFAULT_HEIGHT = 792