Brettapps commited on
Commit
3bf5eeb
·
verified ·
1 Parent(s): 9c2b193

Upload folder using huggingface_hub (part 19)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/INSTALLER +1 -0
  2. .venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/METADATA +177 -0
  3. .venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/RECORD +121 -0
  4. .venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/REQUESTED +0 -0
  5. .venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/WHEEL +4 -0
  6. .venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/licenses/LICENSE +29 -0
  7. .venv/lib/python3.13/site-packages/pypdf/_crypt_providers/_base.py +38 -0
  8. .venv/lib/python3.13/site-packages/pypdf/_crypt_providers/_cryptography.py +132 -0
  9. .venv/lib/python3.13/site-packages/pypdf/_crypt_providers/_fallback.py +93 -0
  10. .venv/lib/python3.13/site-packages/pypdf/_crypt_providers/_pycryptodome.py +110 -0
  11. .venv/lib/python3.13/site-packages/pypdf/_doc_common.py +1528 -0
  12. .venv/lib/python3.13/site-packages/pypdf/_encryption.py +1305 -0
  13. .venv/lib/python3.13/site-packages/pypdf/_font.py +799 -0
  14. .venv/lib/python3.13/site-packages/pypdf/_page.py +0 -0
  15. .venv/lib/python3.13/site-packages/pypdf/_page_labels.py +321 -0
  16. .venv/lib/python3.13/site-packages/pypdf/_protocols.py +86 -0
  17. .venv/lib/python3.13/site-packages/pypdf/_reader.py +1604 -0
  18. .venv/lib/python3.13/site-packages/pypdf/_text_extraction/__init__.py +244 -0
  19. .venv/lib/python3.13/site-packages/pypdf/_text_extraction/_layout_mode/__init__.py +16 -0
  20. .venv/lib/python3.13/site-packages/pypdf/_text_extraction/_layout_mode/_fixed_width_page.py +447 -0
  21. .venv/lib/python3.13/site-packages/pypdf/_text_extraction/_layout_mode/_text_state_manager.py +203 -0
  22. .venv/lib/python3.13/site-packages/pypdf/_text_extraction/_layout_mode/_text_state_params.py +161 -0
  23. .venv/lib/python3.13/site-packages/pypdf/_text_extraction/_text_extractor.py +358 -0
  24. .venv/lib/python3.13/site-packages/pypdf/_utils.py +673 -0
  25. .venv/lib/python3.13/site-packages/pypdf/_version.py +1 -0
  26. .venv/lib/python3.13/site-packages/pypdf/_writer.py +0 -0
  27. .venv/lib/python3.13/site-packages/pypdf/actions/__init__.py +17 -0
  28. .venv/lib/python3.13/site-packages/pypdf/actions/_actions.py +187 -0
  29. .venv/lib/python3.13/site-packages/pypdf/annotations/__init__.py +42 -0
  30. .venv/lib/python3.13/site-packages/pypdf/annotations/_base.py +29 -0
  31. .venv/lib/python3.13/site-packages/pypdf/annotations/_markup_annotations.py +351 -0
  32. .venv/lib/python3.13/site-packages/pypdf/annotations/_non_markup_annotations.py +106 -0
  33. .venv/lib/python3.13/site-packages/pypdf/constants.py +817 -0
  34. .venv/lib/python3.13/site-packages/pypdf/errors.py +74 -0
  35. .venv/lib/python3.13/site-packages/pypdf/filters.py +878 -0
  36. .venv/lib/python3.13/site-packages/pypdf/generic/__init__.py +115 -0
  37. .venv/lib/python3.13/site-packages/pypdf/generic/_appearance_stream.py +752 -0
  38. .venv/lib/python3.13/site-packages/pypdf/generic/_base.py +960 -0
  39. .venv/lib/python3.13/site-packages/pypdf/generic/_data_structures.py +1874 -0
  40. .venv/lib/python3.13/site-packages/pypdf/generic/_files.py +418 -0
  41. .venv/lib/python3.13/site-packages/pypdf/generic/_fit.py +174 -0
  42. .venv/lib/python3.13/site-packages/pypdf/generic/_image_inline.py +322 -0
  43. .venv/lib/python3.13/site-packages/pypdf/generic/_image_xobject.py +698 -0
  44. .venv/lib/python3.13/site-packages/pypdf/generic/_link.py +150 -0
  45. .venv/lib/python3.13/site-packages/pypdf/generic/_outline.py +33 -0
  46. .venv/lib/python3.13/site-packages/pypdf/generic/_rectangle.py +136 -0
  47. .venv/lib/python3.13/site-packages/pypdf/generic/_utils.py +215 -0
  48. .venv/lib/python3.13/site-packages/pypdf/generic/_viewerpref.py +164 -0
  49. .venv/lib/python3.13/site-packages/pypdf/pagerange.py +208 -0
  50. .venv/lib/python3.13/site-packages/pypdf/papersizes.py +52 -0
.venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
.venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/METADATA ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: pypdf
3
+ Version: 6.15.0
4
+ Summary: A pure-python PDF library capable of splitting, merging, cropping, and transforming PDF files
5
+ Author-email: Mathieu Fenniak <biziqe@mathieu.fenniak.net>
6
+ Maintainer: stefan6419846
7
+ Maintainer-email: Martin Thoma <info@martin-thoma.de>
8
+ Requires-Python: >=3.9
9
+ Description-Content-Type: text/markdown
10
+ License-Expression: BSD-3-Clause
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Operating System :: OS Independent
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Classifier: Typing :: Typed
24
+ License-File: LICENSE
25
+ Requires-Dist: typing_extensions >= 4.0; python_version < '3.11'
26
+ Requires-Dist: cryptography>3.0 ; extra == "crypto"
27
+ Requires-Dist: PyCryptodome ; extra == "cryptodome"
28
+ Requires-Dist: flit ; extra == "dev"
29
+ Requires-Dist: pip-tools ; extra == "dev"
30
+ Requires-Dist: pre-commit ; extra == "dev"
31
+ Requires-Dist: pytest-cov ; extra == "dev"
32
+ Requires-Dist: pytest-socket ; extra == "dev"
33
+ Requires-Dist: pytest-timeout ; extra == "dev"
34
+ Requires-Dist: pytest-xdist ; extra == "dev"
35
+ Requires-Dist: wheel ; extra == "dev"
36
+ Requires-Dist: myst_parser ; extra == "docs"
37
+ Requires-Dist: sphinx ; extra == "docs"
38
+ Requires-Dist: sphinx_rtd_theme ; extra == "docs"
39
+ Requires-Dist: fonttools ; extra == "fonts"
40
+ Requires-Dist: arabic-reshaper ; extra == "full"
41
+ Requires-Dist: cryptography>3.0 ; extra == "full"
42
+ Requires-Dist: fonttools ; extra == "full"
43
+ Requires-Dist: Pillow>=8.0.0 ; extra == "full"
44
+ Requires-Dist: python-bidi ; extra == "full"
45
+ Requires-Dist: Pillow>=8.0.0 ; extra == "image"
46
+ Requires-Dist: arabic-reshaper ; extra == "rtl-text"
47
+ Requires-Dist: python-bidi ; extra == "rtl-text"
48
+ Project-URL: Bug Reports, https://github.com/py-pdf/pypdf/issues
49
+ Project-URL: Changelog, https://pypdf.readthedocs.io/en/latest/meta/CHANGELOG.html
50
+ Project-URL: Documentation, https://pypdf.readthedocs.io/en/latest/
51
+ Project-URL: Source, https://github.com/py-pdf/pypdf
52
+ Provides-Extra: crypto
53
+ Provides-Extra: cryptodome
54
+ Provides-Extra: dev
55
+ Provides-Extra: docs
56
+ Provides-Extra: fonts
57
+ Provides-Extra: full
58
+ Provides-Extra: image
59
+ Provides-Extra: rtl-text
60
+
61
+ [![PyPI version](https://badge.fury.io/py/pypdf.svg)](https://badge.fury.io/py/pypdf)
62
+ [![Python Support](https://img.shields.io/pypi/pyversions/pypdf.svg)](https://pypi.org/project/pypdf/)
63
+ [![](https://img.shields.io/badge/-documentation-green)](https://pypdf.readthedocs.io/en/stable/)
64
+ [![GitHub last commit](https://img.shields.io/github/last-commit/py-pdf/pypdf)](https://github.com/py-pdf/pypdf)
65
+ [![codecov](https://codecov.io/gh/py-pdf/pypdf/branch/main/graph/badge.svg?token=id42cGNZ5Z)](https://codecov.io/gh/py-pdf/pypdf)
66
+
67
+ # pypdf
68
+
69
+ pypdf is a free and open-source pure-python PDF library capable of splitting,
70
+ [merging](https://pypdf.readthedocs.io/en/stable/user/merging-pdfs.html),
71
+ [cropping, and transforming](https://pypdf.readthedocs.io/en/stable/user/cropping-and-transforming.html)
72
+ the pages of PDF files. It can also add
73
+ custom data, viewing options, and
74
+ [passwords](https://pypdf.readthedocs.io/en/stable/user/encryption-decryption.html)
75
+ to PDF files. pypdf can
76
+ [retrieve text](https://pypdf.readthedocs.io/en/stable/user/extract-text.html)
77
+ and
78
+ [metadata](https://pypdf.readthedocs.io/en/stable/user/metadata.html)
79
+ from PDFs as well.
80
+
81
+ See [pdfly](https://github.com/py-pdf/pdfly) for a CLI application that uses pypdf to interact with PDFs.
82
+
83
+ ## Installation
84
+
85
+ Install pypdf using pip:
86
+
87
+ ```
88
+ pip install pypdf
89
+ ```
90
+
91
+ For using pypdf with AES encryption or decryption, install extra dependencies:
92
+
93
+ ```
94
+ pip install pypdf[crypto]
95
+ ```
96
+
97
+ > **NOTE**: `pypdf` 3.1.0 and above include significant improvements compared to
98
+ > previous versions. Please refer to [the migration
99
+ > guide](https://pypdf.readthedocs.io/en/latest/user/migration-1-to-2.html) for
100
+ > more information.
101
+
102
+ ## Usage
103
+
104
+ ```python
105
+ from pypdf import PdfReader
106
+
107
+ reader = PdfReader("example.pdf")
108
+ number_of_pages = len(reader.pages)
109
+ page = reader.pages[0]
110
+ text = page.extract_text()
111
+ ```
112
+
113
+ pypdf can do a lot more, e.g. splitting, merging, reading and creating annotations, decrypting and encrypting. Check out the
114
+ [documentation](https://pypdf.readthedocs.io/en/stable/) for additional usage
115
+ examples!
116
+
117
+ For questions and answers, visit
118
+ [StackOverflow](https://stackoverflow.com/questions/tagged/pypdf)
119
+ (tagged with [pypdf](https://stackoverflow.com/questions/tagged/pypdf)).
120
+
121
+ ## Contributions
122
+
123
+ Maintaining pypdf is a collaborative effort. You can support the project by
124
+ writing documentation, helping to narrow down issues, and submitting code.
125
+ See the [CONTRIBUTING.md](https://github.com/py-pdf/pypdf/blob/main/CONTRIBUTING.md) file for more information.
126
+
127
+ ### Q&A
128
+
129
+ The experience pypdf users have covers the whole range from beginner to expert. You can contribute to the pypdf community by answering questions
130
+ on [StackOverflow](https://stackoverflow.com/questions/tagged/pypdf),
131
+ helping in [discussions](https://github.com/py-pdf/pypdf/discussions),
132
+ and asking users who report issues for [MCVE](https://stackoverflow.com/help/minimal-reproducible-example)'s (Code + example PDF!).
133
+
134
+
135
+ ### Issues
136
+
137
+ A good bug ticket includes a MCVE - a minimal complete verifiable example.
138
+ For pypdf, this means that you must upload a PDF that causes the bug to occur
139
+ as well as the code you're executing with all of the output. Use
140
+ `print(pypdf.__version__)` to tell us which version you're using.
141
+
142
+ ### Code
143
+
144
+ All code contributions are welcome, but smaller ones have a better chance to
145
+ get included in a timely manner. Adding unit tests for new features or test
146
+ cases for bugs you've fixed help us to ensure that the Pull Request (PR) is fine.
147
+
148
+ pypdf includes a test suite which can be executed with `pytest`:
149
+
150
+ ```bash
151
+ $ pytest
152
+ ===================== test session starts =====================
153
+ platform linux -- Python 3.6.15, pytest-7.0.1, pluggy-1.0.0
154
+ rootdir: /home/moose/GitHub/Martin/pypdf
155
+ plugins: cov-3.0.0
156
+ collected 233 items
157
+
158
+ tests/test_basic_features.py .. [ 0%]
159
+ tests/test_constants.py . [ 1%]
160
+ tests/test_filters.py .................x..... [ 11%]
161
+ tests/test_generic.py ................................. [ 25%]
162
+ ............. [ 30%]
163
+ tests/test_javascript.py .. [ 31%]
164
+ tests/test_merger.py . [ 32%]
165
+ tests/test_page.py ......................... [ 42%]
166
+ tests/test_pagerange.py ................ [ 49%]
167
+ tests/test_papersizes.py .................. [ 57%]
168
+ tests/test_reader.py .................................. [ 72%]
169
+ ............... [ 78%]
170
+ tests/test_utils.py .................... [ 87%]
171
+ tests/test_workflows.py .......... [ 91%]
172
+ tests/test_writer.py ................. [ 98%]
173
+ tests/test_xmp.py ... [100%]
174
+
175
+ ========== 232 passed, 1 xfailed, 1 warning in 4.52s ==========
176
+ ```
177
+
.venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/RECORD ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ pypdf-6.15.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ pypdf-6.15.0.dist-info/METADATA,sha256=0Ez3NVXH7UyS06-fj8J0eKe9qKwJfEZIuoMhyFyIGYs,7450
3
+ pypdf-6.15.0.dist-info/RECORD,,
4
+ pypdf-6.15.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ pypdf-6.15.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
6
+ pypdf-6.15.0.dist-info/licenses/LICENSE,sha256=qXrCMOXzPvEKU2eoUOsB-R8aCwZONHQsd5TSKUVX9SQ,1605
7
+ pypdf/__init__.py,sha256=YS_1ZrQ3jBPHsRgMstqJrAts3lUApj_lMOMK5qiLG5w,1283
8
+ pypdf/__pycache__/__init__.cpython-313.pyc,,
9
+ pypdf/__pycache__/_cmap.cpython-313.pyc,,
10
+ pypdf/__pycache__/_doc_common.cpython-313.pyc,,
11
+ pypdf/__pycache__/_encryption.cpython-313.pyc,,
12
+ pypdf/__pycache__/_font.cpython-313.pyc,,
13
+ pypdf/__pycache__/_page.cpython-313.pyc,,
14
+ pypdf/__pycache__/_page_labels.cpython-313.pyc,,
15
+ pypdf/__pycache__/_protocols.cpython-313.pyc,,
16
+ pypdf/__pycache__/_reader.cpython-313.pyc,,
17
+ pypdf/__pycache__/_utils.cpython-313.pyc,,
18
+ pypdf/__pycache__/_version.cpython-313.pyc,,
19
+ pypdf/__pycache__/_writer.cpython-313.pyc,,
20
+ pypdf/__pycache__/constants.cpython-313.pyc,,
21
+ pypdf/__pycache__/errors.cpython-313.pyc,,
22
+ pypdf/__pycache__/filters.cpython-313.pyc,,
23
+ pypdf/__pycache__/pagerange.cpython-313.pyc,,
24
+ pypdf/__pycache__/papersizes.cpython-313.pyc,,
25
+ pypdf/__pycache__/types.cpython-313.pyc,,
26
+ pypdf/__pycache__/xmp.cpython-313.pyc,,
27
+ pypdf/_cmap.py,sha256=A1k_tJgl8TUzzjrgfgc4bIuLOyz2ZQ1rl_63gVeJSSQ,14653
28
+ pypdf/_codecs/__init__.py,sha256=A11ERAtwtWrpGVOzTSlrC1a3T9HClWLBWRwGe3_Pfu0,1373
29
+ pypdf/_codecs/__pycache__/__init__.cpython-313.pyc,,
30
+ pypdf/_codecs/__pycache__/_codecs.cpython-313.pyc,,
31
+ pypdf/_codecs/__pycache__/adobe_glyphs.cpython-313.pyc,,
32
+ pypdf/_codecs/__pycache__/core_font_metrics.cpython-313.pyc,,
33
+ pypdf/_codecs/__pycache__/pdfdoc.cpython-313.pyc,,
34
+ pypdf/_codecs/__pycache__/std.cpython-313.pyc,,
35
+ pypdf/_codecs/__pycache__/symbol.cpython-313.pyc,,
36
+ pypdf/_codecs/__pycache__/zapfding.cpython-313.pyc,,
37
+ pypdf/_codecs/_codecs.py,sha256=83fId54XE-aRb3mNi_p1olJtZzdUh98HsxWXCOGTtRI,10717
38
+ pypdf/_codecs/adobe_glyphs.py,sha256=aaxORupQQJ7kbLDHbjWigLZ6pg8G9_5eqDKiNJxykj4,577665
39
+ pypdf/_codecs/core_font_metrics.py,sha256=FLPWbTZ4hxeQWXgg1jo5e4qXKCFkKEY5e85U2bLFM6k,114968
40
+ pypdf/_codecs/pdfdoc.py,sha256=xfSvMFYsvxuaSQ0Uu9vZDKaB0Wu85h1uCiB1i9rAcUU,4269
41
+ pypdf/_codecs/std.py,sha256=DyQMuEpAGEpS9uy1jWf4cnj-kqShPOAij5sI7Q1YD8E,2630
42
+ pypdf/_codecs/symbol.py,sha256=CP6VjRcscrm8ymAH90xpdxVaelwi6MSb1Tb1wNDh01k,4642
43
+ pypdf/_codecs/zapfding.py,sha256=45qcY11xbBwtoh6_t0Z_7zNjG7-qI411LRQVXYKPr2U,4655
44
+ pypdf/_crypt_providers/__init__.py,sha256=xUQbFgMQvKMaOOT3RUdW3bS8fZShR8PBOz6resfwWFU,2770
45
+ pypdf/_crypt_providers/__pycache__/__init__.cpython-313.pyc,,
46
+ pypdf/_crypt_providers/__pycache__/_base.cpython-313.pyc,,
47
+ pypdf/_crypt_providers/__pycache__/_cryptography.cpython-313.pyc,,
48
+ pypdf/_crypt_providers/__pycache__/_fallback.cpython-313.pyc,,
49
+ pypdf/_crypt_providers/__pycache__/_pycryptodome.cpython-313.pyc,,
50
+ pypdf/_crypt_providers/_base.py,sha256=NFBXEdhbrg9k01PVfNN_k7lEAYl2BkgXIOi5ofU_-R8,1735
51
+ pypdf/_crypt_providers/_cryptography.py,sha256=fIhNNH2asQqJrw0F7QY61Nl1UeJAEr9RcAo1t0-CgNA,5265
52
+ pypdf/_crypt_providers/_fallback.py,sha256=gXcro_K7q4IYDL5XGVRxoFmXjXXMa6TleDDwxWyCj4E,3382
53
+ pypdf/_crypt_providers/_pycryptodome.py,sha256=xX4Fta8QHHEztE-_YHk-vJtmBU1xKVwB99_ysQ6TnOI,4020
54
+ pypdf/_doc_common.py,sha256=BNPg6w_L4FcuKo6bQstPaRdK4_t_rE13dQz7We8osDw,56383
55
+ pypdf/_encryption.py,sha256=w5ySfgwdn6rOXAbyRGAwJ0IcUHh9uEdTX3gAkOsB4Kc,53649
56
+ pypdf/_font.py,sha256=Lz6afTmfIYJxJth5qlIUs5tZ_7qYU_kLhgmlNJ4SwsQ,35572
57
+ pypdf/_page.py,sha256=bDW_zjKldkjfiny3qh4Rga01-YZip_ebqzJVeXL9P4w,98311
58
+ pypdf/_page_labels.py,sha256=c8iENzeLZNHXtWoAGcbHJQQmu7xQFjR3BVSeSObQ-M0,9929
59
+ pypdf/_protocols.py,sha256=TrrfcqgxqjgjMPntHKXoCsnxz7EfuFGihn-whab3R2Q,2123
60
+ pypdf/_reader.py,sha256=iOjDJfoJk40VHSpBtEvbDA-2Wskb6aMkA7yuMBe-iUo,66477
61
+ pypdf/_text_extraction/__init__.py,sha256=kIx-qGevNfXBGvDjUBEv99PuVtsq2Y7Ke_iwiLBYze0,8672
62
+ pypdf/_text_extraction/__pycache__/__init__.cpython-313.pyc,,
63
+ pypdf/_text_extraction/__pycache__/_text_extractor.cpython-313.pyc,,
64
+ pypdf/_text_extraction/_layout_mode/__init__.py,sha256=RUQIwiUwzneNtcljnVM6jkRaem6pgP7mOD2-MBmtpvw,340
65
+ pypdf/_text_extraction/_layout_mode/__pycache__/__init__.cpython-313.pyc,,
66
+ pypdf/_text_extraction/_layout_mode/__pycache__/_fixed_width_page.cpython-313.pyc,,
67
+ pypdf/_text_extraction/_layout_mode/__pycache__/_text_state_manager.cpython-313.pyc,,
68
+ pypdf/_text_extraction/_layout_mode/__pycache__/_text_state_params.cpython-313.pyc,,
69
+ pypdf/_text_extraction/_layout_mode/_fixed_width_page.py,sha256=KdowE9CUqq78RMZV7ZwUnDk7M-ApLLN1If0p2IMPH7A,17319
70
+ pypdf/_text_extraction/_layout_mode/_text_state_manager.py,sha256=aB_tK4X2aHMTxroyfNrGfFeae5dKni073MDR7aldJ5I,7517
71
+ pypdf/_text_extraction/_layout_mode/_text_state_params.py,sha256=cQZAxv4QHt_m5B_jD9OdNLjMXfluEO_YH6UPPqizqfM,6513
72
+ pypdf/_text_extraction/_text_extractor.py,sha256=RugMYgswXsaecAzbFYn-yWp6xLcTeMMuwsrF54BjlWw,14856
73
+ pypdf/_utils.py,sha256=ime7zpRNyZKm1zqab1KGEO1wOgwMJLr4pmG5ET_vVPQ,22793
74
+ pypdf/_version.py,sha256=8Bbf6hj6ZBEdoH0KJirhsFddWkzMvVBgbbpy7sPV--k,23
75
+ pypdf/_writer.py,sha256=YTu87dgqa33YLGXjRBHgoX5sfHTwluY07b2aIOqEPSg,135145
76
+ pypdf/actions/__init__.py,sha256=2L3YHvYIRrqwl2QEkJkeS2O9a1IesDVu1pbiSFQplRg,391
77
+ pypdf/actions/__pycache__/__init__.cpython-313.pyc,,
78
+ pypdf/actions/__pycache__/_actions.cpython-313.pyc,,
79
+ pypdf/actions/_actions.py,sha256=nDqPLWQdB7EUglcPvx5sfNjmGy6FRxk9U5snlosmS20,6521
80
+ pypdf/annotations/__init__.py,sha256=f2k_-jAn39CCB27KxQ_e93GinnzkAHbUnnSeGJl1jyE,990
81
+ pypdf/annotations/__pycache__/__init__.cpython-313.pyc,,
82
+ pypdf/annotations/__pycache__/_base.cpython-313.pyc,,
83
+ pypdf/annotations/__pycache__/_markup_annotations.cpython-313.pyc,,
84
+ pypdf/annotations/__pycache__/_non_markup_annotations.cpython-313.pyc,,
85
+ pypdf/annotations/_base.py,sha256=YIRTzTdkqj8DUWSTmy0frkfTr4joe5HUGzROUof4oIo,961
86
+ pypdf/annotations/_markup_annotations.py,sha256=sWKhGBCG7X9ojAvEaRMEoJP-fY6FcrlFdOmtefIZBm0,11862
87
+ pypdf/annotations/_non_markup_annotations.py,sha256=WKWYte2OibZG3MH7Bf26oTOpCyyGrkPLYnFdJ1osRrY,3656
88
+ pypdf/constants.py,sha256=4hW9lyieto5PY8vL_W4mxZJeSBB1nhmQmcdyHYZZ8Bs,23676
89
+ pypdf/errors.py,sha256=Bw1W9hxOsDgwqwU6YoQ2l0-JiUyTq6l5QjVCr-W4GFA,1947
90
+ pypdf/filters.py,sha256=gC_yDe0IaQYA00S6gDqB9ewcLXlnyS2qMH1khTd3OOc,32785
91
+ pypdf/generic/__init__.py,sha256=VrqdYftQECePDU2rXVMgEqRaYFR8zOV_fvJgo19x_uw,3468
92
+ pypdf/generic/__pycache__/__init__.cpython-313.pyc,,
93
+ pypdf/generic/__pycache__/_appearance_stream.cpython-313.pyc,,
94
+ pypdf/generic/__pycache__/_base.cpython-313.pyc,,
95
+ pypdf/generic/__pycache__/_data_structures.cpython-313.pyc,,
96
+ pypdf/generic/__pycache__/_files.cpython-313.pyc,,
97
+ pypdf/generic/__pycache__/_fit.cpython-313.pyc,,
98
+ pypdf/generic/__pycache__/_image_inline.cpython-313.pyc,,
99
+ pypdf/generic/__pycache__/_image_xobject.cpython-313.pyc,,
100
+ pypdf/generic/__pycache__/_link.cpython-313.pyc,,
101
+ pypdf/generic/__pycache__/_outline.cpython-313.pyc,,
102
+ pypdf/generic/__pycache__/_rectangle.cpython-313.pyc,,
103
+ pypdf/generic/__pycache__/_utils.cpython-313.pyc,,
104
+ pypdf/generic/__pycache__/_viewerpref.cpython-313.pyc,,
105
+ pypdf/generic/_appearance_stream.py,sha256=jESIYicmk6hACyiOALmhbZY8Fr27HbCKSw-kEgvtZjw,34232
106
+ pypdf/generic/_base.py,sha256=_A8NqHJNt59KyoYdwNzAl65ItUlWzcPcw9aztuoCAI0,33427
107
+ pypdf/generic/_data_structures.py,sha256=TUjLDHbd4HjNtl_wld7cB4ooXw5M64wkQ0ZrEZt99SI,69487
108
+ pypdf/generic/_files.py,sha256=YK2OtD19lP7xgUieOKNyqSxZWrfMezxbx4mHaUlCJEk,16789
109
+ pypdf/generic/_fit.py,sha256=IwhejQjIq751vJjVGaWNe9uJX8HzXQ2XppmtLhI-NOo,5515
110
+ pypdf/generic/_image_inline.py,sha256=pgA1wwIh-bC44kRw5gH9_o38ViiRTzwQ8WY-NBysUd8,13281
111
+ pypdf/generic/_image_xobject.py,sha256=TQFpA6p2lb7uaAAaqMRj1ZUGsTYJRZmT11vCADWuHKI,27041
112
+ pypdf/generic/_link.py,sha256=kINa5ZOipGHxY_YW_fIxF4z0TRNKlww4jRYaGCLTQRY,6207
113
+ pypdf/generic/_outline.py,sha256=PEuST4b-KmAQIDAJ0FhyxN7ANmJjdsWaTdxKo7hiq3g,1094
114
+ pypdf/generic/_rectangle.py,sha256=h6DDP9fgtrMyGG1aouZ51n9XJ0J13dxhhqanJxSBNNU,3924
115
+ pypdf/generic/_utils.py,sha256=n2sDl8uBXYIPHmXj2Fzoz91WOTFNozl0sAaM9wgCT-Q,7514
116
+ pypdf/generic/_viewerpref.py,sha256=y92KHY3iy9FajuBos97E1sPk9unzJG-Uk2VCd7iSYeY,6835
117
+ pypdf/pagerange.py,sha256=8hyGOsEC94aiYeKoqukASrE5FZDtx8XrJQFaD-Lp3C0,7536
118
+ pypdf/papersizes.py,sha256=6Tz5sfNN_3JOUapY83U-lakohnpXYA0hSEQNmOVLFL8,1413
119
+ pypdf/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
120
+ pypdf/types.py,sha256=sJ7wHzk7ER_CJ7kP-s8u9axFnkCXnFpr8nzcj1AxTas,1915
121
+ pypdf/xmp.py,sha256=mBk1XMdkE8oybSbo2A1Kp9kVNCUPuqdO1ATZE4WIIQQ,31655
.venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/REQUESTED ADDED
File without changes
.venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: flit 3.12.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
.venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2006-2008, Mathieu Fenniak
2
+ Some contributions copyright (c) 2007, Ashish Kulkarni <kulkarni.ashish@gmail.com>
3
+ Some contributions copyright (c) 2014, Steve Witham <switham_github@mac-guyver.com>
4
+
5
+ All rights reserved.
6
+
7
+ Redistribution and use in source and binary forms, with or without
8
+ modification, are permitted provided that the following conditions are
9
+ met:
10
+
11
+ * Redistributions of source code must retain the above copyright notice,
12
+ this list of conditions and the following disclaimer.
13
+ * Redistributions in binary form must reproduce the above copyright notice,
14
+ this list of conditions and the following disclaimer in the documentation
15
+ and/or other materials provided with the distribution.
16
+ * The name of the author may not be used to endorse or promote products
17
+ derived from this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
23
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29
+ POSSIBILITY OF SUCH DAMAGE.
.venv/lib/python3.13/site-packages/pypdf/_crypt_providers/_base.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, exiledkingcc
2
+ # All rights reserved.
3
+ #
4
+ # Redistribution and use in source and binary forms, with or without
5
+ # modification, are permitted provided that the following conditions are
6
+ # met:
7
+ #
8
+ # * Redistributions of source code must retain the above copyright notice,
9
+ # this list of conditions and the following disclaimer.
10
+ # * Redistributions in binary form must reproduce the above copyright notice,
11
+ # this list of conditions and the following disclaimer in the documentation
12
+ # and/or other materials provided with the distribution.
13
+ # * The name of the author may not be used to endorse or promote products
14
+ # derived from this software without specific prior written permission.
15
+ #
16
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26
+ # POSSIBILITY OF SUCH DAMAGE.
27
+
28
+
29
+ class CryptBase:
30
+ def encrypt(self, data: bytes) -> bytes: # pragma: no cover
31
+ return data
32
+
33
+ def decrypt(self, data: bytes, *, strict: bool = True) -> bytes: # pragma: no cover
34
+ return data
35
+
36
+
37
+ class CryptIdentity(CryptBase):
38
+ pass
.venv/lib/python3.13/site-packages/pypdf/_crypt_providers/_cryptography.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, exiledkingcc
2
+ # All rights reserved.
3
+ #
4
+ # Redistribution and use in source and binary forms, with or without
5
+ # modification, are permitted provided that the following conditions are
6
+ # met:
7
+ #
8
+ # * Redistributions of source code must retain the above copyright notice,
9
+ # this list of conditions and the following disclaimer.
10
+ # * Redistributions in binary form must reproduce the above copyright notice,
11
+ # this list of conditions and the following disclaimer in the documentation
12
+ # and/or other materials provided with the distribution.
13
+ # * The name of the author may not be used to endorse or promote products
14
+ # derived from this software without specific prior written permission.
15
+ #
16
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26
+ # POSSIBILITY OF SUCH DAMAGE.
27
+
28
+ import secrets
29
+
30
+ from cryptography import __version__
31
+ from cryptography.hazmat.primitives.ciphers.algorithms import AES
32
+ from cryptography.hazmat.primitives.ciphers.base import Cipher
33
+ from cryptography.hazmat.primitives.ciphers.modes import CBC, ECB
34
+ from cryptography.hazmat.primitives.padding import PKCS7
35
+
36
+ from pypdf._crypt_providers._base import CryptBase
37
+ from pypdf._utils import logger_warning
38
+ from pypdf.errors import PdfStreamError
39
+
40
+ try:
41
+ # 43.0.0: https://cryptography.io/en/latest/changelog/#v43-0-0
42
+ from cryptography.hazmat.decrepit.ciphers.algorithms import ARC4
43
+ except ImportError:
44
+ from cryptography.hazmat.primitives.ciphers.algorithms import ARC4
45
+
46
+ crypt_provider = ("cryptography", __version__)
47
+
48
+
49
+ class CryptRC4(CryptBase):
50
+ def __init__(self, key: bytes) -> None:
51
+ self.cipher = Cipher(ARC4(key), mode=None)
52
+
53
+ def encrypt(self, data: bytes) -> bytes:
54
+ encryptor = self.cipher.encryptor()
55
+ return encryptor.update(data) + encryptor.finalize()
56
+
57
+ def decrypt(self, data: bytes, *, strict: bool = True) -> bytes:
58
+ decryptor = self.cipher.decryptor()
59
+ return decryptor.update(data) + decryptor.finalize()
60
+
61
+
62
+ class CryptAES(CryptBase):
63
+ def __init__(self, key: bytes) -> None:
64
+ self.alg = AES(key)
65
+
66
+ def encrypt(self, data: bytes) -> bytes:
67
+ iv = secrets.token_bytes(16)
68
+ padder = PKCS7(128).padder()
69
+ padded_data = padder.update(data) + padder.finalize()
70
+
71
+ cipher = Cipher(self.alg, CBC(iv))
72
+ encryptor = cipher.encryptor()
73
+ return iv + encryptor.update(padded_data) + encryptor.finalize()
74
+
75
+ def decrypt(self, data: bytes, *, strict: bool = True) -> bytes:
76
+ iv = data[:16]
77
+ data = data[16:]
78
+ # for empty encrypted data
79
+ if not data:
80
+ return data
81
+
82
+ if not strict and len(data) % 16 != 0:
83
+ logger_warning("Adding missing padding.", source=__name__)
84
+ padder = PKCS7(128).padder()
85
+ data = padder.update(data) + padder.finalize()
86
+
87
+ cipher = Cipher(self.alg, CBC(iv))
88
+ decryptor = cipher.decryptor()
89
+ try:
90
+ padded_data = decryptor.update(data) + decryptor.finalize()
91
+ except ValueError as exception:
92
+ # Only raised in strict mode. Non-strict mode fixes padding.
93
+ raise PdfStreamError(exception)
94
+
95
+ unpadder = PKCS7(128).unpadder()
96
+ try:
97
+ return unpadder.update(padded_data) + unpadder.finalize()
98
+ except ValueError as exception:
99
+ if strict:
100
+ raise PdfStreamError(exception)
101
+ logger_warning("Ignoring padding error: %(exception)s", source=__name__, exception=exception)
102
+ return padded_data[: -padded_data[-1]]
103
+
104
+
105
+ def rc4_encrypt(key: bytes, data: bytes) -> bytes:
106
+ encryptor = Cipher(ARC4(key), mode=None).encryptor()
107
+ return encryptor.update(data) + encryptor.finalize()
108
+
109
+
110
+ def rc4_decrypt(key: bytes, data: bytes) -> bytes:
111
+ decryptor = Cipher(ARC4(key), mode=None).decryptor()
112
+ return decryptor.update(data) + decryptor.finalize()
113
+
114
+
115
+ def aes_ecb_encrypt(key: bytes, data: bytes) -> bytes:
116
+ encryptor = Cipher(AES(key), mode=ECB()).encryptor()
117
+ return encryptor.update(data) + encryptor.finalize()
118
+
119
+
120
+ def aes_ecb_decrypt(key: bytes, data: bytes) -> bytes:
121
+ decryptor = Cipher(AES(key), mode=ECB()).decryptor()
122
+ return decryptor.update(data) + decryptor.finalize()
123
+
124
+
125
+ def aes_cbc_encrypt(key: bytes, iv: bytes, data: bytes) -> bytes:
126
+ encryptor = Cipher(AES(key), mode=CBC(iv)).encryptor()
127
+ return encryptor.update(data) + encryptor.finalize()
128
+
129
+
130
+ def aes_cbc_decrypt(key: bytes, iv: bytes, data: bytes) -> bytes:
131
+ decryptor = Cipher(AES(key), mode=CBC(iv)).decryptor()
132
+ return decryptor.update(data) + decryptor.finalize()
.venv/lib/python3.13/site-packages/pypdf/_crypt_providers/_fallback.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, exiledkingcc
2
+ # All rights reserved.
3
+ #
4
+ # Redistribution and use in source and binary forms, with or without
5
+ # modification, are permitted provided that the following conditions are
6
+ # met:
7
+ #
8
+ # * Redistributions of source code must retain the above copyright notice,
9
+ # this list of conditions and the following disclaimer.
10
+ # * Redistributions in binary form must reproduce the above copyright notice,
11
+ # this list of conditions and the following disclaimer in the documentation
12
+ # and/or other materials provided with the distribution.
13
+ # * The name of the author may not be used to endorse or promote products
14
+ # derived from this software without specific prior written permission.
15
+ #
16
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26
+ # POSSIBILITY OF SUCH DAMAGE.
27
+
28
+ from pypdf._crypt_providers._base import CryptBase
29
+ from pypdf.errors import DependencyError
30
+
31
+ _DEPENDENCY_ERROR_STR = "cryptography>=3.1 is required for AES algorithm"
32
+
33
+
34
+ crypt_provider = ("local_crypt_fallback", "0.0.0")
35
+
36
+
37
+ class CryptRC4(CryptBase):
38
+ def __init__(self, key: bytes) -> None:
39
+ self.s = bytearray(range(256))
40
+ j = 0
41
+ for i in range(256):
42
+ j = (j + self.s[i] + key[i % len(key)]) % 256
43
+ self.s[i], self.s[j] = self.s[j], self.s[i]
44
+
45
+ def encrypt(self, data: bytes) -> bytes:
46
+ s = bytearray(self.s)
47
+ out = [0 for _ in range(len(data))]
48
+ i, j = 0, 0
49
+ for k in range(len(data)):
50
+ i = (i + 1) % 256
51
+ j = (j + s[i]) % 256
52
+ s[i], s[j] = s[j], s[i]
53
+ x = s[(s[i] + s[j]) % 256]
54
+ out[k] = data[k] ^ x
55
+ return bytes(out)
56
+
57
+ def decrypt(self, data: bytes, *, strict: bool = True) -> bytes:
58
+ return self.encrypt(data)
59
+
60
+
61
+ class CryptAES(CryptBase):
62
+ def __init__(self, key: bytes) -> None:
63
+ pass
64
+
65
+ def encrypt(self, data: bytes) -> bytes:
66
+ raise DependencyError(_DEPENDENCY_ERROR_STR)
67
+
68
+ def decrypt(self, data: bytes, *, strict: bool = True) -> bytes:
69
+ raise DependencyError(_DEPENDENCY_ERROR_STR)
70
+
71
+
72
+ def rc4_encrypt(key: bytes, data: bytes) -> bytes:
73
+ return CryptRC4(key).encrypt(data)
74
+
75
+
76
+ def rc4_decrypt(key: bytes, data: bytes) -> bytes:
77
+ return CryptRC4(key).decrypt(data)
78
+
79
+
80
+ def aes_ecb_encrypt(key: bytes, data: bytes) -> bytes:
81
+ raise DependencyError(_DEPENDENCY_ERROR_STR)
82
+
83
+
84
+ def aes_ecb_decrypt(key: bytes, data: bytes) -> bytes:
85
+ raise DependencyError(_DEPENDENCY_ERROR_STR)
86
+
87
+
88
+ def aes_cbc_encrypt(key: bytes, iv: bytes, data: bytes) -> bytes:
89
+ raise DependencyError(_DEPENDENCY_ERROR_STR)
90
+
91
+
92
+ def aes_cbc_decrypt(key: bytes, iv: bytes, data: bytes) -> bytes:
93
+ raise DependencyError(_DEPENDENCY_ERROR_STR)
.venv/lib/python3.13/site-packages/pypdf/_crypt_providers/_pycryptodome.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, exiledkingcc
2
+ # All rights reserved.
3
+ #
4
+ # Redistribution and use in source and binary forms, with or without
5
+ # modification, are permitted provided that the following conditions are
6
+ # met:
7
+ #
8
+ # * Redistributions of source code must retain the above copyright notice,
9
+ # this list of conditions and the following disclaimer.
10
+ # * Redistributions in binary form must reproduce the above copyright notice,
11
+ # this list of conditions and the following disclaimer in the documentation
12
+ # and/or other materials provided with the distribution.
13
+ # * The name of the author may not be used to endorse or promote products
14
+ # derived from this software without specific prior written permission.
15
+ #
16
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26
+ # POSSIBILITY OF SUCH DAMAGE.
27
+
28
+ import secrets
29
+
30
+ from Crypto import __version__
31
+ from Crypto.Cipher import AES, ARC4
32
+ from Crypto.Util.Padding import pad, unpad
33
+
34
+ from pypdf._crypt_providers._base import CryptBase
35
+ from pypdf._utils import logger_warning
36
+ from pypdf.errors import PdfStreamError
37
+
38
+ crypt_provider = ("pycryptodome", __version__)
39
+
40
+
41
+ class CryptRC4(CryptBase):
42
+ def __init__(self, key: bytes) -> None:
43
+ self.key = key
44
+
45
+ def encrypt(self, data: bytes) -> bytes:
46
+ return ARC4.ARC4Cipher(self.key).encrypt(data)
47
+
48
+ def decrypt(self, data: bytes, *, strict: bool = True) -> bytes:
49
+ return ARC4.ARC4Cipher(self.key).decrypt(data)
50
+
51
+
52
+ class CryptAES(CryptBase):
53
+ def __init__(self, key: bytes) -> None:
54
+ self.key = key
55
+
56
+ def encrypt(self, data: bytes) -> bytes:
57
+ iv = secrets.token_bytes(16)
58
+ padded_data = pad(data, 16)
59
+ aes = AES.new(self.key, AES.MODE_CBC, iv)
60
+ return iv + aes.encrypt(padded_data)
61
+
62
+ def decrypt(self, data: bytes, *, strict: bool = True) -> bytes:
63
+ iv = data[:16]
64
+ data = data[16:]
65
+ # for empty encrypted data
66
+ if not data:
67
+ return data
68
+
69
+ if not strict and len(data) % 16 != 0:
70
+ logger_warning("Adding missing padding.", source=__name__)
71
+ data = pad(data, 16)
72
+
73
+ aes = AES.new(self.key, AES.MODE_CBC, iv)
74
+ try:
75
+ padded_data = aes.decrypt(data)
76
+ except ValueError as exception:
77
+ # Only raised in strict mode. Non-strict mode fixes padding.
78
+ raise PdfStreamError(exception)
79
+
80
+ try:
81
+ return unpad(padded_data, 16)
82
+ except ValueError as exception:
83
+ if strict:
84
+ raise PdfStreamError(exception)
85
+ logger_warning("Ignoring padding error: %(exception)s", source=__name__, exception=exception)
86
+ return padded_data[: -padded_data[-1]]
87
+
88
+
89
+ def rc4_encrypt(key: bytes, data: bytes) -> bytes:
90
+ return ARC4.ARC4Cipher(key).encrypt(data)
91
+
92
+
93
+ def rc4_decrypt(key: bytes, data: bytes) -> bytes:
94
+ return ARC4.ARC4Cipher(key).decrypt(data)
95
+
96
+
97
+ def aes_ecb_encrypt(key: bytes, data: bytes) -> bytes:
98
+ return AES.new(key, AES.MODE_ECB).encrypt(data)
99
+
100
+
101
+ def aes_ecb_decrypt(key: bytes, data: bytes) -> bytes:
102
+ return AES.new(key, AES.MODE_ECB).decrypt(data)
103
+
104
+
105
+ def aes_cbc_encrypt(key: bytes, iv: bytes, data: bytes) -> bytes:
106
+ return AES.new(key, AES.MODE_CBC, iv).encrypt(data)
107
+
108
+
109
+ def aes_cbc_decrypt(key: bytes, iv: bytes, data: bytes) -> bytes:
110
+ return AES.new(key, AES.MODE_CBC, iv).decrypt(data)
.venv/lib/python3.13/site-packages/pypdf/_doc_common.py ADDED
@@ -0,0 +1,1528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2006, Mathieu Fenniak
2
+ # Copyright (c) 2007, Ashish Kulkarni <kulkarni.ashish@gmail.com>
3
+ # Copyright (c) 2024, Pubpub-ZZ
4
+ #
5
+ # All rights reserved.
6
+ #
7
+ # Redistribution and use in source and binary forms, with or without
8
+ # modification, are permitted provided that the following conditions are
9
+ # met:
10
+ #
11
+ # * Redistributions of source code must retain the above copyright notice,
12
+ # this list of conditions and the following disclaimer.
13
+ # * Redistributions in binary form must reproduce the above copyright notice,
14
+ # this list of conditions and the following disclaimer in the documentation
15
+ # and/or other materials provided with the distribution.
16
+ # * The name of the author may not be used to endorse or promote products
17
+ # derived from this software without specific prior written permission.
18
+ #
19
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
23
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29
+ # POSSIBILITY OF SUCH DAMAGE.
30
+
31
+ import struct
32
+ from abc import ABC, abstractmethod
33
+ from collections.abc import Generator, Iterable, Iterator, Mapping
34
+ from datetime import datetime
35
+ from typing import (
36
+ Any,
37
+ NoReturn,
38
+ Optional,
39
+ Union,
40
+ cast,
41
+ )
42
+
43
+ from ._encryption import Encryption
44
+ from ._page import PageObject, _VirtualList
45
+ from ._page_labels import index2label as page_index2page_label
46
+ from ._utils import (
47
+ deprecation_with_replacement,
48
+ logger_warning,
49
+ parse_iso8824_date,
50
+ )
51
+ from .constants import CatalogAttributes as CA
52
+ from .constants import CatalogDictionary as CD
53
+ from .constants import (
54
+ CheckboxRadioButtonAttributes,
55
+ Core,
56
+ GoToActionArguments,
57
+ PagesAttributes,
58
+ UserAccessPermissions,
59
+ )
60
+ from .constants import DocumentInformationAttributes as DI
61
+ from .constants import FieldDictionaryAttributes as FA
62
+ from .constants import PageAttributes as PG
63
+ from .errors import LimitReachedError, PdfReadError, PyPdfError
64
+ from .filters import _decompress_with_limit
65
+ from .generic import (
66
+ ArrayObject,
67
+ BooleanObject,
68
+ ByteStringObject,
69
+ Destination,
70
+ DictionaryObject,
71
+ EncodedStreamObject,
72
+ Field,
73
+ Fit,
74
+ FloatObject,
75
+ IndirectObject,
76
+ NameObject,
77
+ NullObject,
78
+ NumberObject,
79
+ PdfObject,
80
+ TextStringObject,
81
+ TreeObject,
82
+ ViewerPreferences,
83
+ create_string_object,
84
+ is_null_or_none,
85
+ )
86
+ from .generic._files import EmbeddedFile
87
+ from .types import OutlineType, PagemodeType
88
+ from .xmp import XmpInformation
89
+
90
+
91
+ def convert_to_int(d: bytes, size: int) -> Union[int, tuple[Any, ...]]:
92
+ if size > 8:
93
+ raise PdfReadError("Invalid size in convert_to_int")
94
+ d = b"\x00\x00\x00\x00\x00\x00\x00\x00" + d
95
+ d = d[-8:]
96
+ return cast(int, struct.unpack(">Q", d)[0])
97
+
98
+
99
+ class DocumentInformation(DictionaryObject):
100
+ """
101
+ A class representing the basic document metadata provided in a PDF File.
102
+ This class is accessible through
103
+ :py:class:`PdfReader.metadata<pypdf.PdfReader.metadata>`.
104
+
105
+ All text properties of the document metadata have
106
+ *two* properties, e.g. author and author_raw. The non-raw property will
107
+ always return a ``TextStringObject``, making it ideal for a case where the
108
+ metadata is being displayed. The raw property can sometimes return a
109
+ ``ByteStringObject``, if pypdf was unable to decode the string's text
110
+ encoding; this requires additional safety in the caller and therefore is not
111
+ as commonly accessed.
112
+ """
113
+
114
+ def __init__(self) -> None:
115
+ DictionaryObject.__init__(self)
116
+
117
+ def _get_text(self, key: str) -> Optional[str]:
118
+ retval = self.get(key, None)
119
+ if isinstance(retval, TextStringObject):
120
+ return retval
121
+ if isinstance(retval, ByteStringObject):
122
+ return str(retval)
123
+ return None
124
+
125
+ @property
126
+ def title(self) -> Optional[str]:
127
+ """
128
+ Read-only property accessing the document's title.
129
+
130
+ Returns a ``TextStringObject`` or ``None`` if the title is not
131
+ specified.
132
+ """
133
+ return (
134
+ self._get_text(DI.TITLE) or self.get(DI.TITLE).get_object() # type: ignore[union-attr]
135
+ if self.get(DI.TITLE)
136
+ else None
137
+ )
138
+
139
+ @property
140
+ def title_raw(self) -> Optional[str]:
141
+ """The "raw" version of title; can return a ``ByteStringObject``."""
142
+ return self.get(DI.TITLE)
143
+
144
+ @property
145
+ def author(self) -> Optional[str]:
146
+ """
147
+ Read-only property accessing the document's author.
148
+
149
+ Returns a ``TextStringObject`` or ``None`` if the author is not
150
+ specified.
151
+ """
152
+ return self._get_text(DI.AUTHOR)
153
+
154
+ @property
155
+ def author_raw(self) -> Optional[str]:
156
+ """The "raw" version of author; can return a ``ByteStringObject``."""
157
+ return self.get(DI.AUTHOR)
158
+
159
+ @property
160
+ def subject(self) -> Optional[str]:
161
+ """
162
+ Read-only property accessing the document's subject.
163
+
164
+ Returns a ``TextStringObject`` or ``None`` if the subject is not
165
+ specified.
166
+ """
167
+ return self._get_text(DI.SUBJECT)
168
+
169
+ @property
170
+ def subject_raw(self) -> Optional[str]:
171
+ """The "raw" version of subject; can return a ``ByteStringObject``."""
172
+ return self.get(DI.SUBJECT)
173
+
174
+ @property
175
+ def creator(self) -> Optional[str]:
176
+ """
177
+ Read-only property accessing the document's creator.
178
+
179
+ If the document was converted to PDF from another format, this is the
180
+ name of the application (e.g. OpenOffice) that created the original
181
+ document from which it was converted. Returns a ``TextStringObject`` or
182
+ ``None`` if the creator is not specified.
183
+ """
184
+ return self._get_text(DI.CREATOR)
185
+
186
+ @property
187
+ def creator_raw(self) -> Optional[str]:
188
+ """The "raw" version of creator; can return a ``ByteStringObject``."""
189
+ return self.get(DI.CREATOR)
190
+
191
+ @property
192
+ def producer(self) -> Optional[str]:
193
+ """
194
+ Read-only property accessing the document's producer.
195
+
196
+ If the document was converted to PDF from another format, this is the
197
+ name of the application (for example, macOS Quartz) that converted it to
198
+ PDF. Returns a ``TextStringObject`` or ``None`` if the producer is not
199
+ specified.
200
+ """
201
+ return self._get_text(DI.PRODUCER)
202
+
203
+ @property
204
+ def producer_raw(self) -> Optional[str]:
205
+ """The "raw" version of producer; can return a ``ByteStringObject``."""
206
+ return self.get(DI.PRODUCER)
207
+
208
+ @property
209
+ def creation_date(self) -> Optional[datetime]:
210
+ """Read-only property accessing the document's creation date."""
211
+ return parse_iso8824_date(self._get_text(DI.CREATION_DATE))
212
+
213
+ @property
214
+ def creation_date_raw(self) -> Optional[str]:
215
+ """
216
+ The "raw" version of creation date; can return a ``ByteStringObject``.
217
+
218
+ Typically in the format ``D:YYYYMMDDhhmmss[+Z-]hh'mm`` where the suffix
219
+ is the offset from UTC.
220
+ """
221
+ return self.get(DI.CREATION_DATE)
222
+
223
+ @property
224
+ def modification_date(self) -> Optional[datetime]:
225
+ """
226
+ Read-only property accessing the document's modification date.
227
+
228
+ The date and time the document was most recently modified.
229
+ """
230
+ return parse_iso8824_date(self._get_text(DI.MOD_DATE))
231
+
232
+ @property
233
+ def modification_date_raw(self) -> Optional[str]:
234
+ """
235
+ The "raw" version of modification date; can return a
236
+ ``ByteStringObject``.
237
+
238
+ Typically in the format ``D:YYYYMMDDhhmmss[+Z-]hh'mm`` where the suffix
239
+ is the offset from UTC.
240
+ """
241
+ return self.get(DI.MOD_DATE)
242
+
243
+ @property
244
+ def keywords(self) -> Optional[str]:
245
+ """
246
+ Read-only property accessing the document's keywords.
247
+
248
+ Returns a ``TextStringObject`` or ``None`` if keywords are not
249
+ specified.
250
+ """
251
+ return self._get_text(DI.KEYWORDS)
252
+
253
+ @property
254
+ def keywords_raw(self) -> Optional[str]:
255
+ """The "raw" version of keywords; can return a ``ByteStringObject``."""
256
+ return self.get(DI.KEYWORDS)
257
+
258
+
259
+ class PdfDocCommon(ABC):
260
+ """
261
+ Common functions from PdfWriter and PdfReader objects.
262
+
263
+ This root class is strongly abstracted.
264
+ """
265
+
266
+ strict: bool = False # default
267
+
268
+ flattened_pages: Optional[list[PageObject]] = None
269
+
270
+ _encryption: Optional[Encryption] = None
271
+
272
+ _readonly: bool = False
273
+
274
+ @property
275
+ @abstractmethod
276
+ def root_object(self) -> DictionaryObject:
277
+ ... # pragma: no cover
278
+
279
+ @property
280
+ @abstractmethod
281
+ def pdf_header(self) -> str:
282
+ ... # pragma: no cover
283
+
284
+ @abstractmethod
285
+ def get_object(
286
+ self, indirect_reference: Union[int, IndirectObject]
287
+ ) -> Optional[PdfObject]:
288
+ ... # pragma: no cover
289
+
290
+ @abstractmethod
291
+ def _replace_object(self, indirect: IndirectObject, obj: PdfObject) -> PdfObject:
292
+ ... # pragma: no cover
293
+
294
+ @property
295
+ @abstractmethod
296
+ def _info(self) -> Optional[DictionaryObject]:
297
+ ... # pragma: no cover
298
+
299
+ @property
300
+ def metadata(self) -> Optional[DocumentInformation]:
301
+ """
302
+ Retrieve the PDF file's document information dictionary, if it exists.
303
+
304
+ Note that some PDF files use metadata streams instead of document
305
+ information dictionaries, and these metadata streams will not be
306
+ accessed by this function.
307
+ """
308
+ retval = DocumentInformation()
309
+ if self._info is None:
310
+ return None
311
+ retval.update(self._info)
312
+ return retval
313
+
314
+ @property
315
+ @abstractmethod
316
+ def xmp_metadata(self) -> Optional[XmpInformation]:
317
+ ... # pragma: no cover
318
+
319
+ @property
320
+ def viewer_preferences(self) -> Optional[ViewerPreferences]:
321
+ """Returns the existing ViewerPreferences as an overloaded dictionary."""
322
+ o = self.root_object.get(CD.VIEWER_PREFERENCES, None)
323
+ if o is None:
324
+ return None
325
+ o = o.get_object()
326
+ if not isinstance(o, ViewerPreferences):
327
+ o = ViewerPreferences(o)
328
+ if hasattr(o, "indirect_reference") and o.indirect_reference is not None:
329
+ self._replace_object(o.indirect_reference, o)
330
+ else:
331
+ self.root_object[NameObject(CD.VIEWER_PREFERENCES)] = o
332
+ return o
333
+
334
+ def get_num_pages(self) -> int:
335
+ """
336
+ Calculate the number of pages in this PDF file.
337
+
338
+ Returns:
339
+ The number of pages of the parsed PDF file.
340
+
341
+ Raises:
342
+ PdfReadError: If restrictions prevent this action.
343
+
344
+ """
345
+ # Flattened pages will not work on an encrypted PDF;
346
+ # the PDF file's page count is used in this case. Otherwise,
347
+ # the original method (flattened page count) is used.
348
+ if self.is_encrypted:
349
+ return self.root_object["/Pages"]["/Count"] # type: ignore[no-any-return, index]
350
+ if self.flattened_pages is None:
351
+ self._flatten(self._readonly)
352
+ assert self.flattened_pages is not None
353
+ return len(self.flattened_pages)
354
+
355
+ def get_page(self, page_number: int) -> PageObject:
356
+ """
357
+ Retrieve a page by number from this PDF file.
358
+ Most of the time ``.pages[page_number]`` is preferred.
359
+
360
+ Args:
361
+ page_number: The page number to retrieve
362
+ (pages begin at zero)
363
+
364
+ Returns:
365
+ A :class:`PageObject<pypdf._page.PageObject>` instance.
366
+
367
+ """
368
+ if self.flattened_pages is None:
369
+ self._flatten(self._readonly)
370
+ assert self.flattened_pages is not None, "mypy"
371
+ return self.flattened_pages[page_number]
372
+
373
+ def _get_page_in_node(
374
+ self,
375
+ page_number: int,
376
+ ) -> tuple[DictionaryObject, int]:
377
+ """
378
+ Retrieve the node and position within the /Kids containing the page.
379
+ If page_number is greater than the number of pages, it returns the top node, -1.
380
+ """
381
+ top = cast(DictionaryObject, self.root_object["/Pages"])
382
+
383
+ def recursive_call(
384
+ node: DictionaryObject, mi: int
385
+ ) -> tuple[Optional[PdfObject], int]:
386
+ ma = cast(int, node.get("/Count", 1)) # default 1 for /Page types
387
+ if node["/Type"] == "/Page": # type: ignore[comparison-overlap]
388
+ if page_number == mi:
389
+ return node, -1
390
+ return None, mi + 1
391
+ if (page_number - mi) >= ma: # not in nodes below
392
+ if node == top:
393
+ return top, -1
394
+ return None, mi + ma
395
+ for idx, kid in enumerate(cast(ArrayObject, node["/Kids"])):
396
+ kid = cast(DictionaryObject, kid.get_object())
397
+ n, i = recursive_call(kid, mi)
398
+ if n is not None: # page has just been found ...
399
+ if i < 0: # ... just below!
400
+ return node, idx
401
+ # ... at lower levels
402
+ return n, i
403
+ mi = i
404
+ raise PyPdfError("Unexpectedly cannot find the node.")
405
+
406
+ node, idx = recursive_call(top, 0)
407
+ assert isinstance(node, DictionaryObject), "mypy"
408
+ return node, idx
409
+
410
+ @property
411
+ def named_destinations(self) -> dict[str, Destination]:
412
+ """A read-only dictionary which maps names to destinations."""
413
+ return self._get_named_destinations()
414
+
415
+ def get_named_dest_root(self) -> ArrayObject:
416
+ named_dest = ArrayObject()
417
+ if CA.NAMES in self.root_object and isinstance(
418
+ self.root_object[CA.NAMES], DictionaryObject
419
+ ):
420
+ names = cast(DictionaryObject, self.root_object[CA.NAMES])
421
+ if CA.DESTS in names and isinstance(names[CA.DESTS], DictionaryObject):
422
+ # §3.6.3 Name Dictionary (PDF spec 1.7)
423
+ dests = cast(DictionaryObject, names[CA.DESTS])
424
+ dests_ref = dests.indirect_reference
425
+ if CA.NAMES in dests:
426
+ # §7.9.6, entries in a name tree node dictionary
427
+ named_dest = cast(ArrayObject, dests[CA.NAMES])
428
+ else:
429
+ named_dest = ArrayObject()
430
+ dests[NameObject(CA.NAMES)] = named_dest
431
+ elif hasattr(self, "_add_object"):
432
+ dests = DictionaryObject()
433
+ dests_ref = self._add_object(dests)
434
+ names[NameObject(CA.DESTS)] = dests_ref
435
+ dests[NameObject(CA.NAMES)] = named_dest
436
+
437
+ elif hasattr(self, "_add_object"):
438
+ names = DictionaryObject()
439
+ names_ref = self._add_object(names)
440
+ self.root_object[NameObject(CA.NAMES)] = names_ref
441
+ dests = DictionaryObject()
442
+ dests_ref = self._add_object(dests)
443
+ names[NameObject(CA.DESTS)] = dests_ref
444
+ dests[NameObject(CA.NAMES)] = named_dest
445
+
446
+ return named_dest
447
+
448
+ ## common
449
+ def _get_named_destinations(
450
+ self,
451
+ *,
452
+ tree: Union[TreeObject, None] = None,
453
+ retval: Optional[dict[str, Destination]] = None,
454
+ visited: Optional[set[int]] = None,
455
+ ) -> dict[str, Destination]:
456
+ """
457
+ Retrieve the named destinations present in the document.
458
+
459
+ Args:
460
+ tree: The current tree.
461
+ retval: The previously retrieved destinations for nested calls.
462
+ visited: Already known/visited objects.
463
+
464
+ Returns:
465
+ A dictionary which maps names to destinations.
466
+
467
+ """
468
+ if visited is None:
469
+ visited = set()
470
+ if retval is None:
471
+ retval = {}
472
+ catalog = self.root_object
473
+
474
+ # get the name tree
475
+ if CA.DESTS in catalog:
476
+ tree = cast(TreeObject, catalog[CA.DESTS])
477
+ elif CA.NAMES in catalog:
478
+ names = cast(DictionaryObject, catalog[CA.NAMES])
479
+ if CA.DESTS in names:
480
+ tree = cast(TreeObject, names[CA.DESTS])
481
+
482
+ if is_null_or_none(tree):
483
+ return retval
484
+ assert tree is not None, "mypy"
485
+
486
+ tree_id = id(tree)
487
+ if tree_id in visited:
488
+ logger_warning("Detected cycle in destination tree.", source=__name__)
489
+ return retval
490
+ visited.add(tree_id)
491
+
492
+ if PagesAttributes.KIDS in tree:
493
+ # recurse down the tree
494
+ for kid in cast(ArrayObject, tree[PagesAttributes.KIDS]):
495
+ self._get_named_destinations(tree=kid.get_object(), retval=retval, visited=visited)
496
+ # §7.9.6, entries in a name tree node dictionary
497
+ elif CA.NAMES in tree: # /Kids and /Names are exclusives (§7.9.6)
498
+ names = cast(DictionaryObject, tree[CA.NAMES])
499
+ i = 0
500
+ while i < len(names):
501
+ key = names[i].get_object()
502
+ i += 1
503
+ if not isinstance(key, (bytes, str)):
504
+ continue
505
+ try:
506
+ value = names[i].get_object()
507
+ except IndexError:
508
+ break
509
+ i += 1
510
+ if isinstance(value, DictionaryObject):
511
+ if "/D" in value:
512
+ value = value["/D"]
513
+ else:
514
+ continue
515
+ dest = self._build_destination(key, value)
516
+ if dest is not None:
517
+ retval[cast(str, dest["/Title"])] = dest
518
+ # Remain backwards-compatible.
519
+ retval[str(key)] = dest
520
+ else: # case where /Dests is in the document's catalog dictionary (PDF 1.7 specs, §2 about PDF 1.1)
521
+ for k__, v__ in tree.items():
522
+ val = v__.get_object()
523
+ if isinstance(val, DictionaryObject):
524
+ if "/D" in val:
525
+ val = val["/D"].get_object()
526
+ else:
527
+ continue
528
+ dest = self._build_destination(k__, val)
529
+ if dest is not None:
530
+ retval[k__] = dest
531
+ return retval
532
+
533
+ # A select group of relevant field attributes. For the complete list,
534
+ # see §12.3.2 of the PDF 1.7 or PDF 2.0 specification.
535
+
536
+ def get_fields(
537
+ self,
538
+ tree: Optional[TreeObject] = None,
539
+ retval: Optional[dict[Any, Any]] = None,
540
+ fileobj: Optional[Any] = None,
541
+ stack: Optional[list[PdfObject]] = None,
542
+ ) -> Optional[dict[str, Any]]:
543
+ """
544
+ Extract field data if this PDF contains interactive form fields.
545
+
546
+ The *tree*, *retval*, *stack* parameters are for recursive use.
547
+
548
+ Args:
549
+ tree: Current object to parse.
550
+ retval: In-progress list of fields.
551
+ fileobj: A file object (usually a text file) to write
552
+ a report to on all interactive form fields found.
553
+ stack: List of already parsed objects.
554
+
555
+ Returns:
556
+ A dictionary where each key is a field name, and each
557
+ value is a :class:`Field<pypdf.generic.Field>` object. By
558
+ default, the mapping name is used for keys.
559
+ ``None`` if form data could not be located.
560
+
561
+ """
562
+ field_attributes = FA.attributes_dict()
563
+ field_attributes.update(CheckboxRadioButtonAttributes.attributes_dict())
564
+ if retval is None:
565
+ retval = {}
566
+ catalog = self.root_object
567
+ stack = []
568
+ # get the AcroForm tree
569
+ if CD.ACRO_FORM in catalog:
570
+ tree = cast(Optional[TreeObject], catalog[CD.ACRO_FORM])
571
+ else:
572
+ return None
573
+ if tree is None:
574
+ return retval
575
+ assert stack is not None
576
+ if "/Fields" in tree:
577
+ fields = cast(ArrayObject, tree["/Fields"])
578
+ for f in fields:
579
+ field = f.get_object()
580
+ self._build_field(field, retval, fileobj, field_attributes, stack)
581
+ elif any(attr in tree for attr in field_attributes):
582
+ # Tree is a field
583
+ self._build_field(tree, retval, fileobj, field_attributes, stack)
584
+ return retval
585
+
586
+ def _get_qualified_field_name(
587
+ self,
588
+ *,
589
+ parent: DictionaryObject,
590
+ visited: Optional[set[int]] = None
591
+ ) -> str:
592
+ if visited is None:
593
+ visited = set()
594
+ parent_id = id(parent)
595
+ if parent_id in visited:
596
+ raise LimitReachedError("Detected cycle in /Parent hierarchy when retrieving qualified field name.")
597
+ visited.add(parent_id)
598
+
599
+ if "/TM" in parent:
600
+ return cast(str, parent["/TM"])
601
+ if "/Parent" in parent:
602
+ return (
603
+ self._get_qualified_field_name(
604
+ parent=cast(DictionaryObject, parent["/Parent"]),
605
+ visited=visited,
606
+ )
607
+ + "."
608
+ + cast(str, parent.get("/T", ""))
609
+ )
610
+ return cast(str, parent.get("/T", ""))
611
+
612
+ @staticmethod
613
+ def _normal_appearance(appearance: Any) -> DictionaryObject:
614
+ """Return the /N normal-appearance sub-dictionary of an /AP entry."""
615
+ appearance = appearance.get_object()
616
+ if not isinstance(appearance, DictionaryObject):
617
+ raise PdfReadError(f"Expected appearance dictionary, got {appearance!r}")
618
+ normal = appearance.get("/N")
619
+ if normal is not None:
620
+ normal = normal.get_object()
621
+ if not isinstance(normal, DictionaryObject):
622
+ raise PdfReadError(f"Expected /N appearance dictionary, got {normal!r}")
623
+ return normal
624
+
625
+ def _build_field(
626
+ self,
627
+ field: Union[TreeObject, DictionaryObject],
628
+ retval: dict[Any, Any],
629
+ fileobj: Any,
630
+ field_attributes: Any,
631
+ stack: list[PdfObject],
632
+ ) -> None:
633
+ if all(attr not in field for attr in ("/T", "/TM")):
634
+ return
635
+ key = self._get_qualified_field_name(parent=field)
636
+ if fileobj:
637
+ self._write_field(fileobj, field, field_attributes)
638
+ fileobj.write("\n")
639
+ retval[key] = Field(field)
640
+ obj = retval[key].indirect_reference.get_object() # to get the full object
641
+ if obj.get(FA.FT, "") == "/Ch" and obj.get(NameObject(FA.Opt)):
642
+ retval[key][NameObject("/_States_")] = obj[NameObject(FA.Opt)]
643
+ if obj.get(FA.FT, "") == "/Btn" and "/AP" in obj:
644
+ # Checkbox
645
+ normal = self._normal_appearance(obj["/AP"])
646
+ retval[key][NameObject("/_States_")] = ArrayObject(list(normal.keys()))
647
+ if "/Off" not in retval[key]["/_States_"]:
648
+ retval[key][NameObject("/_States_")].append(NameObject("/Off"))
649
+ elif obj.get(FA.FT, "") == "/Btn" and obj.get(FA.Ff, 0) & FA.FfBits.Radio != 0:
650
+ states: list[str] = []
651
+ retval[key][NameObject("/_States_")] = ArrayObject(states)
652
+ for k in obj.get(FA.Kids, {}):
653
+ k = k.get_object()
654
+ if "/AP" not in k:
655
+ raise PdfReadError(f"Button field kid missing /AP: {k!r}")
656
+ normal = self._normal_appearance(k["/AP"])
657
+ for s in list(normal.keys()):
658
+ if s not in states:
659
+ states.append(s)
660
+ retval[key][NameObject("/_States_")] = ArrayObject(states)
661
+ if (
662
+ obj.get(FA.Ff, 0) & FA.FfBits.NoToggleToOff != 0
663
+ and "/Off" in retval[key]["/_States_"]
664
+ ):
665
+ del retval[key]["/_States_"][retval[key]["/_States_"].index("/Off")]
666
+ # at last for order
667
+ self._check_kids(field, retval, fileobj, stack)
668
+
669
+ def _check_kids(
670
+ self,
671
+ tree: Union[TreeObject, DictionaryObject],
672
+ retval: Any,
673
+ fileobj: Any,
674
+ stack: list[PdfObject],
675
+ ) -> None:
676
+ if tree in stack:
677
+ logger_warning(
678
+ "%(field_name)s already parsed",
679
+ source=__name__,
680
+ field_name=self._get_qualified_field_name(parent=tree),
681
+ )
682
+ return
683
+ stack.append(tree)
684
+ if PagesAttributes.KIDS in tree:
685
+ # recurse down the tree
686
+ for kid in tree[PagesAttributes.KIDS]: # type: ignore[attr-defined]
687
+ kid = kid.get_object()
688
+ self.get_fields(kid, retval, fileobj, stack)
689
+
690
+ def _write_field(self, fileobj: Any, field: Any, field_attributes: Any) -> None:
691
+ field_attributes_tuple = FA.attributes()
692
+ field_attributes_tuple = (
693
+ field_attributes_tuple + CheckboxRadioButtonAttributes.attributes()
694
+ )
695
+
696
+ for attr in field_attributes_tuple:
697
+ if attr in (
698
+ FA.Kids,
699
+ FA.AA,
700
+ ):
701
+ continue
702
+ attr_name = field_attributes[attr]
703
+ try:
704
+ if attr == FA.FT:
705
+ # Make the field type value clearer
706
+ types = {
707
+ "/Btn": "Button",
708
+ "/Tx": "Text",
709
+ "/Ch": "Choice",
710
+ "/Sig": "Signature",
711
+ }
712
+ if field[attr] in types:
713
+ fileobj.write(f"{attr_name}: {types[field[attr]]}\n")
714
+ elif attr == FA.Parent:
715
+ # Let's just write the name of the parent
716
+ try:
717
+ name = field[attr][FA.TM]
718
+ except KeyError:
719
+ name = field[attr][FA.T]
720
+ fileobj.write(f"{attr_name}: {name}\n")
721
+ else:
722
+ fileobj.write(f"{attr_name}: {field[attr]}\n")
723
+ except KeyError:
724
+ # Field attribute is N/A or unknown, so don't write anything
725
+ pass
726
+
727
+ def get_form_text_fields(self, full_qualified_name: bool = False) -> dict[str, Any]:
728
+ """
729
+ Retrieve form fields from the document with textual data.
730
+
731
+ Args:
732
+ full_qualified_name: to get full name
733
+
734
+ Returns:
735
+ A dictionary. The key is the name of the form field,
736
+ the value is the content of the field.
737
+
738
+ If the document contains multiple form fields with the same name, the
739
+ second and following will get the suffix .2, .3, ...
740
+
741
+ """
742
+
743
+ def indexed_key(k: str, fields: dict[Any, Any]) -> str:
744
+ if k not in fields:
745
+ return k
746
+ return (
747
+ k
748
+ + "."
749
+ + str(sum(1 for kk in fields if kk.startswith(k + ".")) + 2)
750
+ )
751
+
752
+ # Retrieve document form fields
753
+ form_fields = self.get_fields()
754
+ if form_fields is None:
755
+ return {}
756
+ ff = {}
757
+ for field, value in form_fields.items():
758
+ if value.get("/FT") == "/Tx":
759
+ if full_qualified_name:
760
+ ff[field] = value.get("/V")
761
+ else:
762
+ ff[indexed_key(cast(str, value.get("/T", field)), ff)] = value.get("/V")
763
+ return ff
764
+
765
+ def get_pages_showing_field(
766
+ self, field: Union[Field, PdfObject, IndirectObject]
767
+ ) -> list[PageObject]:
768
+ """
769
+ Provides list of pages where the field is called.
770
+
771
+ Args:
772
+ field: Field Object, PdfObject or IndirectObject referencing a Field
773
+
774
+ Returns:
775
+ List of pages:
776
+ - Empty list:
777
+ The field has no widgets attached
778
+ (either hidden field or ancestor field).
779
+ - Single page list:
780
+ Page where the widget is present
781
+ (most common).
782
+ - Multi-page list:
783
+ Field with multiple kids widgets
784
+ (example: radio buttons, field repeated on multiple pages).
785
+
786
+ """
787
+ try:
788
+ # to cope with all types
789
+ field = cast(DictionaryObject, field.indirect_reference.get_object()) # type: ignore[union-attr]
790
+ except Exception as exc:
791
+ raise ValueError("Field type is invalid") from exc
792
+ if is_null_or_none(field.get_inherited(key="/FT", default=None)):
793
+ raise ValueError("Field is not valid")
794
+ ret = []
795
+ if field.get("/Subtype", "") == "/Widget":
796
+ if "/P" in field:
797
+ ret = [field["/P"].get_object()]
798
+ else:
799
+ ret = [
800
+ p
801
+ for p in self.pages
802
+ if field.indirect_reference in p.get("/Annots", "")
803
+ ]
804
+ else:
805
+ kids = field.get("/Kids", ())
806
+ for k in kids:
807
+ k = k.get_object()
808
+ if (k.get("/Subtype", "") == "/Widget") and ("/T" not in k):
809
+ # Kid that is just a widget, not a field:
810
+ if "/P" in k:
811
+ ret += [k["/P"].get_object()]
812
+ else:
813
+ ret += [
814
+ p
815
+ for p in self.pages
816
+ if k.indirect_reference in p.get("/Annots", "")
817
+ ]
818
+ return [
819
+ x
820
+ if isinstance(x, PageObject)
821
+ else (self.pages[self._get_page_number_by_indirect(x.indirect_reference)]) # type: ignore[index, union-attr]
822
+ for x in ret
823
+ ]
824
+
825
+ @property
826
+ def open_destination(
827
+ self,
828
+ ) -> Union[Destination, TextStringObject, ByteStringObject, None]:
829
+ """
830
+ Property to access the opening destination (``/OpenAction`` entry in
831
+ the PDF catalog). It returns ``None`` if the entry does not exist
832
+ or is not set.
833
+
834
+ Raises:
835
+ Exception: If a destination is invalid.
836
+
837
+ """
838
+ if "/OpenAction" not in self.root_object:
839
+ return None
840
+ oa: Any = self.root_object["/OpenAction"]
841
+ if isinstance(oa, bytes): # pragma: no cover
842
+ oa = oa.decode()
843
+ if isinstance(oa, str):
844
+ return create_string_object(oa)
845
+ if isinstance(oa, ArrayObject):
846
+ try:
847
+ page, typ, *array = oa
848
+ fit = Fit(typ, tuple(array))
849
+ return Destination("OpenAction", page, fit)
850
+ except Exception as exc:
851
+ raise Exception(f"Invalid Destination {oa}: {exc}")
852
+ else:
853
+ return None
854
+
855
+ @open_destination.setter
856
+ def open_destination(self, dest: Union[str, Destination, PageObject, None]) -> None:
857
+ raise NotImplementedError("No setter for open_destination")
858
+
859
+ @property
860
+ def outline(self) -> OutlineType:
861
+ """
862
+ Read-only property for the outline present in the document
863
+ (i.e., a collection of 'outline items' which are also known as
864
+ 'bookmarks').
865
+ """
866
+ return self._get_outline()
867
+
868
+ def _get_outline(
869
+ self,
870
+ node: Optional[DictionaryObject] = None,
871
+ outline: Optional[Any] = None,
872
+ visited: Optional[set[int]] = None,
873
+ ) -> OutlineType:
874
+ if outline is None:
875
+ outline = []
876
+ catalog = self.root_object
877
+
878
+ # get the outline dictionary and named destinations
879
+ if Core.OUTLINES in catalog:
880
+ lines = cast(DictionaryObject, catalog[Core.OUTLINES])
881
+
882
+ if isinstance(lines, NullObject):
883
+ return outline
884
+
885
+ # §12.3.3 Document outline, entries in the outline dictionary
886
+ if not is_null_or_none(lines) and "/First" in lines:
887
+ node = cast(DictionaryObject, lines["/First"])
888
+ self._named_destinations = self._get_named_destinations()
889
+
890
+ if node is None:
891
+ return outline
892
+
893
+ # see if there are any more outline items
894
+ if visited is None:
895
+ visited = set()
896
+ while True:
897
+ node_id = id(node)
898
+ if node_id in visited:
899
+ logger_warning("Detected cycle in outline structure for %(node)s", source=__name__, node=node)
900
+ break
901
+ visited.add(node_id)
902
+
903
+ outline_obj = self._build_outline_item(node)
904
+ if outline_obj:
905
+ outline.append(outline_obj)
906
+
907
+ # check for sub-outline
908
+ if "/First" in node:
909
+ sub_outline: list[Any] = []
910
+ # Pass a copy to allow multiple outer entries to reference the same inner one.
911
+ inner_visited = visited.copy()
912
+ self._get_outline(
913
+ node=cast(DictionaryObject, node["/First"]),
914
+ outline=sub_outline,
915
+ visited=inner_visited,
916
+ )
917
+ if sub_outline:
918
+ outline.append(sub_outline)
919
+
920
+ if "/Next" not in node:
921
+ break
922
+ node = cast(DictionaryObject, node["/Next"])
923
+
924
+ return outline
925
+
926
+ @property
927
+ def threads(self) -> Optional[ArrayObject]:
928
+ """
929
+ Read-only property for the list of threads.
930
+
931
+ See §12.4.3 from the PDF 1.7 or 2.0 specification.
932
+
933
+ It is an array of dictionaries with "/F" (the first bead in the thread)
934
+ and "/I" (a thread information dictionary containing information about
935
+ the thread, such as its title, author, and creation date) properties or
936
+ None if there are no articles.
937
+
938
+ Since PDF 2.0 it can also contain an indirect reference to a metadata
939
+ stream containing information about the thread, such as its title,
940
+ author, and creation date.
941
+ """
942
+ catalog = self.root_object
943
+ if Core.THREADS in catalog:
944
+ return cast("ArrayObject", catalog[Core.THREADS])
945
+ return None
946
+
947
+ @abstractmethod
948
+ def _get_page_number_by_indirect(
949
+ self, indirect_reference: Union[int, NullObject, IndirectObject, None]
950
+ ) -> Optional[int]:
951
+ ... # pragma: no cover
952
+
953
+ def get_page_number(self, page: PageObject) -> Optional[int]:
954
+ """
955
+ Retrieve page number of a given PageObject.
956
+
957
+ Args:
958
+ page: The page to get page number. Should be
959
+ an instance of :class:`PageObject<pypdf._page.PageObject>`
960
+
961
+ Returns:
962
+ The page number or None if page is not found
963
+
964
+ """
965
+ return self._get_page_number_by_indirect(page.indirect_reference)
966
+
967
+ def get_destination_page_number(self, destination: Destination) -> Optional[int]:
968
+ """
969
+ Retrieve page number of a given Destination object.
970
+
971
+ Args:
972
+ destination: The destination to get page number.
973
+
974
+ Returns:
975
+ The page number or None if page is not found
976
+
977
+ """
978
+ return self._get_page_number_by_indirect(destination.page)
979
+
980
+ def _build_destination(
981
+ self,
982
+ title: Union[str, bytes],
983
+ array: Optional[
984
+ list[
985
+ Union[NumberObject, IndirectObject, NullObject, DictionaryObject, None]
986
+ ]
987
+ ],
988
+ ) -> Destination:
989
+ page, typ = None, None
990
+ # handle outline items with missing or invalid destination
991
+ if (
992
+ isinstance(array, (NullObject, str))
993
+ or (isinstance(array, ArrayObject) and len(array) < 2)
994
+ or array is None
995
+ ):
996
+ page = NullObject()
997
+ return Destination(title, page, Fit.fit())
998
+ page, typ, *array = array # type: ignore[assignment]
999
+ try:
1000
+ return Destination(title, page, Fit(fit_type=typ, fit_args=array)) # type: ignore[arg-type]
1001
+ except PdfReadError:
1002
+ logger_warning("Unknown destination: %(title)r %(array)s", source=__name__, title=title, array=array)
1003
+ if self.strict:
1004
+ raise
1005
+ # create a link to first Page
1006
+ tmp = self.pages[0].indirect_reference
1007
+ indirect_reference = NullObject() if tmp is None else tmp
1008
+ return Destination(title, indirect_reference, Fit.fit())
1009
+
1010
+ def _build_outline_item(self, node: DictionaryObject) -> Optional[Destination]:
1011
+ dest, title, outline_item = None, None, None
1012
+
1013
+ # title required for valid outline
1014
+ # §12.3.3, entries in an outline item dictionary
1015
+ try:
1016
+ title = cast("str", node["/Title"])
1017
+ except KeyError:
1018
+ if self.strict:
1019
+ raise PdfReadError(f"Outline Entry Missing /Title attribute: {node!r}")
1020
+ title = ""
1021
+
1022
+ if "/A" in node:
1023
+ # Action, PDF 1.7 and PDF 2.0 §12.6 (only type GoTo supported)
1024
+ action = cast(DictionaryObject, node["/A"])
1025
+ action_type = cast(NameObject, action[GoToActionArguments.S])
1026
+ if action_type == "/GoTo":
1027
+ if GoToActionArguments.D in action:
1028
+ dest = action[GoToActionArguments.D]
1029
+ elif self.strict:
1030
+ raise PdfReadError(f"Outline Action Missing /D attribute: {node!r}")
1031
+ elif "/Dest" in node:
1032
+ # Destination, PDF 1.7 and PDF 2.0 §12.3.2
1033
+ dest = node["/Dest"]
1034
+ # if array was referenced in another object, will be a dict w/ key "/D"
1035
+ if isinstance(dest, DictionaryObject) and "/D" in dest:
1036
+ dest = dest["/D"]
1037
+
1038
+ if isinstance(dest, ArrayObject):
1039
+ outline_item = self._build_destination(title, dest)
1040
+ elif isinstance(dest, str):
1041
+ # named destination, addresses NameObject Issue #193
1042
+ # TODO: Keep named destination instead of replacing it?
1043
+ try:
1044
+ outline_item = self._build_destination(
1045
+ title, self._named_destinations[dest].dest_array
1046
+ )
1047
+ except KeyError:
1048
+ # named destination not found in Name Dict
1049
+ outline_item = self._build_destination(title, None)
1050
+ elif dest is None:
1051
+ # outline item not required to have destination or action
1052
+ # PDFv1.7 Table 153
1053
+ outline_item = self._build_destination(title, dest)
1054
+ else:
1055
+ if self.strict:
1056
+ raise PdfReadError(f"Unexpected destination {dest!r}")
1057
+ logger_warning(
1058
+ "Removed unexpected destination %(dest)r from destination",
1059
+ source=__name__,
1060
+ dest=dest,
1061
+ )
1062
+ outline_item = self._build_destination(title, None)
1063
+
1064
+ # if outline item created, add color, format, and child count if present
1065
+ if outline_item:
1066
+ if "/C" in node:
1067
+ # Color of outline item font in (R, G, B) with values ranging 0.0-1.0
1068
+ color = node["/C"]
1069
+ if isinstance(color, list):
1070
+ outline_item[NameObject("/C")] = ArrayObject(FloatObject(c) for c in color)
1071
+ else:
1072
+ logger_warning(
1073
+ "Ignoring non-array outline color %(color)r",
1074
+ source=__name__,
1075
+ color=color,
1076
+ )
1077
+ if "/F" in node:
1078
+ # specifies style characteristics bold and/or italic
1079
+ # with 1=italic, 2=bold, 3=both
1080
+ outline_item[NameObject("/F")] = node["/F"]
1081
+ if "/Count" in node:
1082
+ # absolute value = num. visible children
1083
+ # with positive = open/unfolded, negative = closed/folded
1084
+ outline_item[NameObject("/Count")] = node["/Count"]
1085
+ # if count is 0 we will consider it as open (to have available is_open)
1086
+ outline_item[NameObject("/%is_open%")] = BooleanObject(
1087
+ node.get("/Count", 0) >= 0
1088
+ )
1089
+ outline_item.node = node
1090
+ try:
1091
+ outline_item.indirect_reference = node.indirect_reference
1092
+ except AttributeError:
1093
+ pass
1094
+ return outline_item
1095
+
1096
+ @property
1097
+ def pages(self) -> list[PageObject]:
1098
+ """
1099
+ Property that emulates a list of :class:`PageObject<pypdf._page.PageObject>`.
1100
+ This property allows to get a page or a range of pages.
1101
+
1102
+ Note:
1103
+ For PdfWriter only: Provides the capability to remove a page/range of
1104
+ page from the list (using the del operator). Remember: Only the page
1105
+ entry is removed, as the objects beneath can be used elsewhere. A
1106
+ solution to completely remove them - if they are not used anywhere - is
1107
+ to write to a buffer/temporary file and then load it into a new
1108
+ PdfWriter.
1109
+
1110
+ """
1111
+ return _VirtualList(self.get_num_pages, self.get_page) # type: ignore[return-value]
1112
+
1113
+ @property
1114
+ def page_labels(self) -> list[str]:
1115
+ """
1116
+ A list of labels for the pages in this document.
1117
+
1118
+ This property is read-only. The labels are in the order that the pages
1119
+ appear in the document.
1120
+ """
1121
+ return [page_index2page_label(self, i) for i in range(len(self.pages))]
1122
+
1123
+ @property
1124
+ def page_layout(self) -> Optional[str]:
1125
+ """
1126
+ Get the page layout currently being used.
1127
+
1128
+ .. list-table:: Valid ``layout`` values
1129
+ :widths: 50 200
1130
+
1131
+ * - /NoLayout
1132
+ - Layout explicitly not specified
1133
+ * - /SinglePage
1134
+ - Show one page at a time
1135
+ * - /OneColumn
1136
+ - Show one column at a time
1137
+ * - /TwoColumnLeft
1138
+ - Show pages in two columns, odd-numbered pages on the left
1139
+ * - /TwoColumnRight
1140
+ - Show pages in two columns, odd-numbered pages on the right
1141
+ * - /TwoPageLeft
1142
+ - Show two pages at a time, odd-numbered pages on the left
1143
+ * - /TwoPageRight
1144
+ - Show two pages at a time, odd-numbered pages on the right
1145
+ """
1146
+ try:
1147
+ return cast(NameObject, self.root_object[CD.PAGE_LAYOUT])
1148
+ except KeyError:
1149
+ return None
1150
+
1151
+ @property
1152
+ def page_mode(self) -> Optional[PagemodeType]:
1153
+ """
1154
+ Get the page mode currently being used.
1155
+
1156
+ .. list-table:: Valid ``mode`` values
1157
+ :widths: 50 200
1158
+
1159
+ * - /UseNone
1160
+ - Do not show outline or thumbnails panels
1161
+ * - /UseOutlines
1162
+ - Show outline (aka bookmarks) panel
1163
+ * - /UseThumbs
1164
+ - Show page thumbnails panel
1165
+ * - /FullScreen
1166
+ - Fullscreen view
1167
+ * - /UseOC
1168
+ - Show Optional Content Group (OCG) panel
1169
+ * - /UseAttachments
1170
+ - Show attachments panel
1171
+ """
1172
+ try:
1173
+ return self.root_object["/PageMode"] # type: ignore[return-value]
1174
+ except KeyError:
1175
+ return None
1176
+
1177
+ def _flatten(
1178
+ self,
1179
+ list_only: bool = False,
1180
+ pages: Union[DictionaryObject, PageObject, None] = None,
1181
+ inherit: Optional[dict[str, Any]] = None,
1182
+ indirect_reference: Optional[IndirectObject] = None,
1183
+ visited: Optional[set[int]] = None,
1184
+ ) -> None:
1185
+ """
1186
+ Process the document pages to ease searching.
1187
+
1188
+ Attributes of a page may inherit from ancestor nodes
1189
+ in the page tree. Flattening means moving
1190
+ any inheritance data into descendant nodes,
1191
+ effectively removing the inheritance dependency.
1192
+
1193
+ Note: It is distinct from another use of "flattening" applied to PDFs.
1194
+ Flattening a PDF also means combining all the contents into one single layer
1195
+ and making the file less editable.
1196
+
1197
+ Args:
1198
+ list_only: Will only list the pages within _flatten_pages.
1199
+ pages:
1200
+ inherit:
1201
+ indirect_reference: Used recursively to flatten the /Pages object.
1202
+ visited: Set of id() values of /Pages nodes already visited during
1203
+ traversal. Detects multi-hop cycles such as A→B→C→A that the
1204
+ single-parent check misses.
1205
+
1206
+ """
1207
+ inheritable_page_attributes = (
1208
+ NameObject(PG.RESOURCES),
1209
+ NameObject(PG.MEDIABOX),
1210
+ NameObject(PG.CROPBOX),
1211
+ NameObject(PG.ROTATE),
1212
+ )
1213
+ if inherit is None:
1214
+ inherit = {}
1215
+ if visited is None:
1216
+ visited = set()
1217
+ if is_null_or_none(pages):
1218
+ # Fix issue 327: set flattened_pages attribute only for
1219
+ # decrypted file
1220
+ catalog = self.root_object
1221
+ pages = catalog.get("/Pages").get_object() # type: ignore[union-attr]
1222
+ if not isinstance(pages, DictionaryObject):
1223
+ raise PdfReadError("Invalid object in /Pages")
1224
+ self.flattened_pages = []
1225
+ assert pages is not None, "mypy"
1226
+
1227
+ if PagesAttributes.TYPE in pages:
1228
+ t = cast(str, pages[PagesAttributes.TYPE])
1229
+ # if the page tree node has no /Type, consider as a page if /Kids is also missing
1230
+ elif PagesAttributes.KIDS not in pages:
1231
+ t = "/Page"
1232
+ else:
1233
+ t = "/Pages"
1234
+
1235
+ if t == "/Pages":
1236
+ for attr in inheritable_page_attributes:
1237
+ if attr in pages:
1238
+ inherit[attr] = pages[attr]
1239
+ pages_reference = getattr(pages, "indirect_reference", object())
1240
+ kids = pages.get(PagesAttributes.KIDS, ArrayObject()).get_object()
1241
+ if isinstance(kids, NullObject):
1242
+ kids = ArrayObject()
1243
+ elif not isinstance(kids, ArrayObject):
1244
+ raise PdfReadError(
1245
+ f"Expected /Kids to be an array, got {type(kids).__name__}."
1246
+ )
1247
+ for page in kids:
1248
+ if getattr(page, "indirect_reference", object()) == pages_reference:
1249
+ raise PdfReadError("Detected cyclic page references.")
1250
+
1251
+ additional_arguments = {}
1252
+ if isinstance(page, IndirectObject):
1253
+ additional_arguments["indirect_reference"] = page
1254
+ obj = page.get_object()
1255
+ if obj:
1256
+ # damaged file may have invalid child in /Pages
1257
+ obj_id = id(obj)
1258
+ if obj_id in visited:
1259
+ raise PdfReadError("Detected cyclic page references.")
1260
+ visited.add(obj_id)
1261
+ self._flatten(list_only, obj, inherit, visited=visited, **additional_arguments)
1262
+ elif t == "/Page":
1263
+ for attr_in, value in inherit.items():
1264
+ # if the page has its own value, it does not inherit the
1265
+ # parent's value
1266
+ if attr_in not in pages:
1267
+ pages[attr_in] = value
1268
+ page_obj = PageObject(self, indirect_reference)
1269
+ if not list_only:
1270
+ page_obj.update(pages)
1271
+
1272
+ # TODO: Could flattened_pages be None at this point?
1273
+ self.flattened_pages.append(page_obj) # type: ignore[union-attr]
1274
+
1275
+ def remove_page(
1276
+ self,
1277
+ page: Union[int, PageObject, IndirectObject],
1278
+ clean: bool = False,
1279
+ ) -> None:
1280
+ """
1281
+ Remove page from pages list.
1282
+
1283
+ Args:
1284
+ page:
1285
+ * :class:`int`: Page number to be removed.
1286
+ * :class:`~pypdf._page.PageObject`: page to be removed. If the page appears many times
1287
+ only the first one will be removed.
1288
+ * :class:`~pypdf.generic.IndirectObject`: Reference to page to be removed.
1289
+
1290
+ clean: replace PageObject with NullObject to prevent annotations
1291
+ or destinations to reference a detached page.
1292
+
1293
+ """
1294
+ if self.flattened_pages is None:
1295
+ self._flatten(self._readonly)
1296
+ assert self.flattened_pages is not None
1297
+ if isinstance(page, IndirectObject):
1298
+ p = page.get_object()
1299
+ if not isinstance(p, PageObject):
1300
+ logger_warning("IndirectObject is not referencing a page", source=__name__)
1301
+ return
1302
+ page = p
1303
+
1304
+ if not isinstance(page, int):
1305
+ try:
1306
+ page = self.flattened_pages.index(page)
1307
+ except ValueError:
1308
+ logger_warning("Cannot find page in pages", source=__name__)
1309
+ return
1310
+ if not (0 <= page < len(self.flattened_pages)):
1311
+ logger_warning("Page number is out of range", source=__name__)
1312
+ return
1313
+
1314
+ ind = self.pages[page].indirect_reference
1315
+ del self.pages[page]
1316
+ if clean and ind is not None:
1317
+ self._replace_object(ind, NullObject())
1318
+
1319
+ def _get_indirect_object(self, num: int, gen: int) -> Optional[PdfObject]:
1320
+ """
1321
+ Used to ease development.
1322
+
1323
+ This is equivalent to generic.IndirectObject(num,gen,self).get_object()
1324
+
1325
+ Args:
1326
+ num: The object number of the indirect object.
1327
+ gen: The generation number of the indirect object.
1328
+
1329
+ Returns:
1330
+ A PdfObject
1331
+
1332
+ """
1333
+ return IndirectObject(num, gen, self).get_object()
1334
+
1335
+ def decode_permissions(
1336
+ self, permissions_code: int
1337
+ ) -> NoReturn: # pragma: no cover
1338
+ """Take the permissions as an integer, return the allowed access."""
1339
+ deprecation_with_replacement(
1340
+ old_name="decode_permissions",
1341
+ new_name="user_access_permissions",
1342
+ removed_in="5.0.0",
1343
+ )
1344
+
1345
+ @property
1346
+ def user_access_permissions(self) -> Optional[UserAccessPermissions]:
1347
+ """
1348
+ Get the user access permissions for encrypted documents.
1349
+ Returns None if not encrypted.
1350
+
1351
+ .. warning::
1352
+
1353
+ For AES-256 encrypted documents (R=5/R=6), the returned
1354
+ permissions are derived from the ``/P`` field, which is
1355
+ only trustworthy if the ``/Perms`` integrity check passed.
1356
+ Check :attr:`are_permissions_valid` to verify.
1357
+ """
1358
+ if self._encryption is None:
1359
+ return None
1360
+ return UserAccessPermissions(self._encryption.P)
1361
+
1362
+ @property
1363
+ def are_permissions_valid(self) -> Optional[bool]:
1364
+ """
1365
+ Whether the ``/Perms`` integrity check passed for this document.
1366
+
1367
+ For AES-256 encrypted documents (R=5/R=6), the ``/Perms`` field
1368
+ is an encrypted copy of the permissions that can be verified
1369
+ independently. Returns ``False`` if this check fails (the ``/P``
1370
+ permissions may have been tampered with).
1371
+
1372
+ Returns ``None`` if the document is not encrypted or has not yet
1373
+ been decrypted via :meth:`decrypt()<pypdf.PdfReader.decrypt>`.
1374
+ Returns ``True`` for non-AES-256 encryption (no ``/Perms`` to check).
1375
+ """
1376
+ if self._encryption is None:
1377
+ return None
1378
+ if not self._encryption.is_decrypted():
1379
+ return None
1380
+ return self._encryption._are_permissions_valid
1381
+
1382
+ @property
1383
+ @abstractmethod
1384
+ def is_encrypted(self) -> bool:
1385
+ """
1386
+ Read-only boolean property showing whether this PDF file is encrypted.
1387
+
1388
+ Note that this property, if true, will remain true even after the
1389
+ :meth:`decrypt()<pypdf.PdfReader.decrypt>` method is called.
1390
+ """
1391
+ ... # pragma: no cover
1392
+
1393
+ @property
1394
+ def xfa(self) -> Optional[dict[str, Any]]:
1395
+ retval: dict[str, Any] = {}
1396
+ catalog = self.root_object
1397
+
1398
+ if "/AcroForm" not in catalog or not catalog["/AcroForm"]:
1399
+ return None
1400
+
1401
+ tree = cast(TreeObject, catalog["/AcroForm"])
1402
+
1403
+ if "/XFA" in tree:
1404
+ fields = cast(ArrayObject, tree["/XFA"])
1405
+ i = iter(fields)
1406
+ for f in i:
1407
+ tag = f
1408
+ f = next(i)
1409
+ if isinstance(f, IndirectObject):
1410
+ field = cast(Optional[EncodedStreamObject], f.get_object())
1411
+ if field:
1412
+ es = _decompress_with_limit(field._data)
1413
+ retval[tag] = es
1414
+ return retval
1415
+
1416
+ @property
1417
+ def attachments(self) -> Mapping[str, list[bytes]]:
1418
+ """Mapping of attachment filenames to their content."""
1419
+ return LazyDict(
1420
+ {
1421
+ name: (self._get_attachment_list, name)
1422
+ for name in self._list_attachments()
1423
+ }
1424
+ )
1425
+
1426
+ @property
1427
+ def attachment_list(self) -> Generator[EmbeddedFile, None, None]:
1428
+ """Iterable of attachment objects."""
1429
+ yield from EmbeddedFile._load(self.root_object)
1430
+
1431
+ def _list_attachments(self) -> list[str]:
1432
+ """
1433
+ Retrieves the list of filenames of file attachments.
1434
+
1435
+ Returns:
1436
+ list of filenames
1437
+
1438
+ """
1439
+ names = []
1440
+ for entry in self.attachment_list:
1441
+ names.append(entry.name)
1442
+ if (name := entry.alternative_name) != entry.name and name:
1443
+ names.append(name)
1444
+ return names
1445
+
1446
+ def _get_attachment_list(self, name: str) -> list[bytes]:
1447
+ out = self._get_attachments(name)[name]
1448
+ if isinstance(out, list):
1449
+ return out
1450
+ return [out]
1451
+
1452
+ def _get_attachments(
1453
+ self, filename: Optional[str] = None
1454
+ ) -> dict[str, Union[bytes, list[bytes]]]:
1455
+ """
1456
+ Retrieves all or selected file attachments of the PDF as a dictionary of file names
1457
+ and the file data as a bytestring.
1458
+
1459
+ Args:
1460
+ filename: If filename is None, then a dictionary of all attachments
1461
+ will be returned, where the key is the filename and the value
1462
+ is the content. Otherwise, a dictionary with just a single key
1463
+ - the filename - and its content will be returned.
1464
+
1465
+ Returns:
1466
+ dictionary of filename -> Union[bytestring or List[ByteString]]
1467
+ If the filename exists multiple times a list of the different versions will be provided.
1468
+
1469
+ """
1470
+ attachments: dict[str, Union[bytes, list[bytes]]] = {}
1471
+ for entry in self.attachment_list:
1472
+ names = set()
1473
+ alternative_name = entry.alternative_name
1474
+ if filename is not None:
1475
+ if filename in {entry.name, alternative_name}:
1476
+ name = entry.name if filename == entry.name else alternative_name
1477
+ names.add(name)
1478
+ else:
1479
+ continue
1480
+ else:
1481
+ names = {entry.name, alternative_name}
1482
+
1483
+ for name in names:
1484
+ if name is None:
1485
+ continue
1486
+ if name in attachments:
1487
+ if not isinstance(attachments[name], list):
1488
+ attachments[name] = [attachments[name]] # type:ignore
1489
+ attachments[name].append(entry.content) # type:ignore
1490
+ else:
1491
+ attachments[name] = entry.content
1492
+ return attachments
1493
+
1494
+ @abstractmethod
1495
+ def _repr_mimebundle_(
1496
+ self,
1497
+ include: Union[Iterable[str], None] = None,
1498
+ exclude: Union[Iterable[str], None] = None,
1499
+ ) -> dict[str, Any]:
1500
+ """
1501
+ Integration into Jupyter Notebooks.
1502
+
1503
+ This method returns a dictionary that maps a mime-type to its
1504
+ representation.
1505
+
1506
+ .. seealso::
1507
+
1508
+ https://ipython.readthedocs.io/en/stable/config/integrating.html
1509
+ """
1510
+ ... # pragma: no cover
1511
+
1512
+
1513
+ class LazyDict(Mapping[Any, Any]):
1514
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
1515
+ self._raw_dict = dict(*args, **kwargs)
1516
+
1517
+ def __getitem__(self, key: str) -> Any:
1518
+ func, arg = self._raw_dict.__getitem__(key)
1519
+ return func(arg)
1520
+
1521
+ def __iter__(self) -> Iterator[Any]:
1522
+ return iter(self._raw_dict)
1523
+
1524
+ def __len__(self) -> int:
1525
+ return len(self._raw_dict)
1526
+
1527
+ def __str__(self) -> str:
1528
+ return f"LazyDict(keys={list(self.keys())})"
.venv/lib/python3.13/site-packages/pypdf/_encryption.py ADDED
@@ -0,0 +1,1305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022, exiledkingcc
2
+ # All rights reserved.
3
+ #
4
+ # Redistribution and use in source and binary forms, with or without
5
+ # modification, are permitted provided that the following conditions are
6
+ # met:
7
+ #
8
+ # * Redistributions of source code must retain the above copyright notice,
9
+ # this list of conditions and the following disclaimer.
10
+ # * Redistributions in binary form must reproduce the above copyright notice,
11
+ # this list of conditions and the following disclaimer in the documentation
12
+ # and/or other materials provided with the distribution.
13
+ # * The name of the author may not be used to endorse or promote products
14
+ # derived from this software without specific prior written permission.
15
+ #
16
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26
+ # POSSIBILITY OF SUCH DAMAGE.
27
+ import hashlib
28
+ import secrets
29
+ import stringprep
30
+ import struct
31
+ import unicodedata
32
+ from enum import Enum, IntEnum
33
+ from typing import Any, Optional, Union, cast
34
+
35
+ from pypdf._crypt_providers import (
36
+ CryptAES,
37
+ CryptBase,
38
+ CryptIdentity,
39
+ CryptRC4,
40
+ aes_cbc_decrypt,
41
+ aes_cbc_encrypt,
42
+ aes_ecb_decrypt,
43
+ aes_ecb_encrypt,
44
+ rc4_decrypt,
45
+ rc4_encrypt,
46
+ )
47
+
48
+ from ._utils import logger_warning
49
+ from .generic import (
50
+ ArrayObject,
51
+ ByteStringObject,
52
+ DictionaryObject,
53
+ NameObject,
54
+ NumberObject,
55
+ PdfObject,
56
+ StreamObject,
57
+ TextStringObject,
58
+ create_string_object,
59
+ )
60
+
61
+
62
+ class CryptFilter:
63
+ def __init__(
64
+ self,
65
+ stm_crypt: CryptBase,
66
+ str_crypt: CryptBase,
67
+ ef_crypt: CryptBase,
68
+ ) -> None:
69
+ self.stm_crypt = stm_crypt
70
+ self.str_crypt = str_crypt
71
+ self.ef_crypt = ef_crypt
72
+
73
+ def encrypt_object(self, obj: PdfObject) -> PdfObject:
74
+ if isinstance(obj, ByteStringObject):
75
+ data = self.str_crypt.encrypt(obj.original_bytes)
76
+ obj = ByteStringObject(data)
77
+ elif isinstance(obj, TextStringObject):
78
+ data = self.str_crypt.encrypt(obj.get_encoded_bytes())
79
+ obj = ByteStringObject(data)
80
+ elif isinstance(obj, StreamObject):
81
+ obj2 = StreamObject()
82
+ obj2.update(obj)
83
+ obj2.set_data(self.stm_crypt.encrypt(obj._data))
84
+ for key, value in obj.items(): # Don't forget the Stream dict.
85
+ obj2[key] = self.encrypt_object(value)
86
+ obj = obj2
87
+ elif isinstance(obj, DictionaryObject):
88
+ obj2 = DictionaryObject() # type: ignore[assignment]
89
+ for key, value in obj.items():
90
+ obj2[key] = self.encrypt_object(value)
91
+ obj = obj2
92
+ elif isinstance(obj, ArrayObject):
93
+ obj = ArrayObject(self.encrypt_object(x) for x in obj)
94
+ return obj
95
+
96
+ def decrypt_object(self, obj: PdfObject, *, strict: bool = True) -> PdfObject:
97
+ if isinstance(obj, (ByteStringObject, TextStringObject)):
98
+ data = self.str_crypt.decrypt(obj.original_bytes, strict=strict)
99
+ obj = create_string_object(data)
100
+ elif isinstance(obj, StreamObject):
101
+ obj._data = self.stm_crypt.decrypt(obj._data, strict=strict)
102
+ for key, value in obj.items(): # Don't forget the Stream dict.
103
+ obj[key] = self.decrypt_object(value, strict=strict)
104
+ elif isinstance(obj, DictionaryObject):
105
+ for key, value in obj.items():
106
+ obj[key] = self.decrypt_object(value, strict=strict)
107
+ elif isinstance(obj, ArrayObject):
108
+ for i in range(len(obj)):
109
+ obj[i] = self.decrypt_object(obj[i], strict=strict)
110
+ return obj
111
+
112
+
113
+ _PADDING = (
114
+ b"\x28\xbf\x4e\x5e\x4e\x75\x8a\x41\x64\x00\x4e\x56\xff\xfa\x01\x08"
115
+ b"\x2e\x2e\x00\xb6\xd0\x68\x3e\x80\x2f\x0c\xa9\xfe\x64\x53\x69\x7a"
116
+ )
117
+
118
+
119
+ def _padding(data: bytes) -> bytes:
120
+ return (data + _PADDING)[:32]
121
+
122
+
123
+ # Module-level constant for SASLprep prohibited character checks (RFC 4013 §2.3)
124
+ _SASLPREP_PROHIBITED_CHECKS = (
125
+ (stringprep.in_table_c12, "non-ASCII space character"),
126
+ (stringprep.in_table_c21, "ASCII control character"),
127
+ (stringprep.in_table_c22, "non-ASCII control character"),
128
+ (stringprep.in_table_c3, "private use character"),
129
+ (stringprep.in_table_c4, "non-character code point"),
130
+ (stringprep.in_table_c5, "surrogate code point"),
131
+ (stringprep.in_table_c6, "inappropriate for plain text"),
132
+ (stringprep.in_table_c7, "inappropriate for canonical representation"),
133
+ (stringprep.in_table_c8, "change display properties/deprecated"),
134
+ (stringprep.in_table_c9, "tagging character"),
135
+ (stringprep.in_table_a1, "unassigned code point"),
136
+ )
137
+
138
+
139
+ class AlgV4:
140
+ @staticmethod
141
+ def compute_key(
142
+ password: bytes,
143
+ rev: int,
144
+ key_size: int,
145
+ o_entry: bytes,
146
+ P: int,
147
+ id1_entry: bytes,
148
+ metadata_encrypted: bool,
149
+ ) -> bytes:
150
+ """
151
+ Algorithm 2: Computing an encryption key.
152
+
153
+ a) Pad or truncate the password string to exactly 32 bytes. If the
154
+ password string is more than 32 bytes long,
155
+ use only its first 32 bytes; if it is less than 32 bytes long, pad it
156
+ by appending the required number of
157
+ additional bytes from the beginning of the following padding string:
158
+ < 28 BF 4E 5E 4E 75 8A 41 64 00 4E 56 FF FA 01 08
159
+ 2E 2E 00 B6 D0 68 3E 80 2F 0C A9 FE 64 53 69 7A >
160
+ That is, if the password string is n bytes long, append
161
+ the first 32 - n bytes of the padding string to the end
162
+ of the password string. If the password string is empty
163
+ (zero-length), meaning there is no user password,
164
+ substitute the entire padding string in its place.
165
+ b) Initialize the MD5 hash function and pass the result of step (a)
166
+ as input to this function.
167
+ c) Pass the value of the encryption dictionary’s O entry to the
168
+ MD5 hash function. ("Algorithm 3: Computing
169
+ the encryption dictionary’s O (owner password) value" shows how the
170
+ O value is computed.)
171
+ d) Convert the integer value of the P entry to a 32-bit unsigned binary
172
+ number and pass these bytes to the
173
+ MD5 hash function, low-order byte first.
174
+ e) Pass the first element of the file’s file identifier array (the value
175
+ of the ID entry in the document’s trailer
176
+ dictionary; see Table 15) to the MD5 hash function.
177
+ f) (Security handlers of revision 4 or greater) If document metadata is
178
+ not being encrypted, pass 4 bytes with
179
+ the value 0xFFFFFFFF to the MD5 hash function.
180
+ g) Finish the hash.
181
+ h) (Security handlers of revision 3 or greater) Do the following
182
+ 50 times: Take the output from the previous
183
+ MD5 hash and pass the first n bytes of the output as input into a new
184
+ MD5 hash, where n is the number of
185
+ bytes of the encryption key as defined by the value of the encryption
186
+ dictionary’s Length entry.
187
+ i) Set the encryption key to the first n bytes of the output from the
188
+ final MD5 hash, where n shall always be 5
189
+ for security handlers of revision 2 but, for security handlers of
190
+ revision 3 or greater, shall depend on the
191
+ value of the encryption dictionary’s Length entry.
192
+
193
+ Args:
194
+ password: The encryption secret as a bytes-string
195
+ rev: The encryption revision (see PDF standard)
196
+ key_size: The size of the key in bytes
197
+ o_entry: The owner entry
198
+ P: A set of flags specifying which operations shall be permitted
199
+ when the document is opened with user access. If bit 2 is set to 1,
200
+ all other bits are ignored and all operations are permitted.
201
+ If bit 2 is set to 0, permission for operations are based on the
202
+ values of the remaining flags defined in Table 24.
203
+ id1_entry:
204
+ metadata_encrypted: A boolean indicating if the metadata is encrypted.
205
+
206
+ Returns:
207
+ The u_hash digest of length key_size
208
+
209
+ """
210
+ a = _padding(password)
211
+ u_hash = hashlib.md5(a)
212
+ u_hash.update(o_entry)
213
+ u_hash.update(struct.pack("<I", P))
214
+ u_hash.update(id1_entry)
215
+ if rev >= 4 and not metadata_encrypted:
216
+ u_hash.update(b"\xff\xff\xff\xff")
217
+ u_hash_digest = u_hash.digest()
218
+ length = key_size // 8
219
+ if rev >= 3:
220
+ for _ in range(50):
221
+ u_hash_digest = hashlib.md5(u_hash_digest[:length]).digest()
222
+ return u_hash_digest[:length]
223
+
224
+ @staticmethod
225
+ def compute_O_value_key(owner_password: bytes, rev: int, key_size: int) -> bytes:
226
+ """
227
+ Algorithm 3: Computing the encryption dictionary’s O (owner password) value.
228
+
229
+ a) Pad or truncate the owner password string as described in step (a)
230
+ of "Algorithm 2: Computing an encryption key".
231
+ If there is no owner password, use the user password instead.
232
+ b) Initialize the MD5 hash function and pass the result of step (a) as
233
+ input to this function.
234
+ c) (Security handlers of revision 3 or greater) Do the following 50 times:
235
+ Take the output from the previous
236
+ MD5 hash and pass it as input into a new MD5 hash.
237
+ d) Create an RC4 encryption key using the first n bytes of the output
238
+ from the final MD5 hash, where n shall
239
+ always be 5 for security handlers of revision 2 but, for security
240
+ handlers of revision 3 or greater, shall
241
+ depend on the value of the encryption dictionary’s Length entry.
242
+ e) Pad or truncate the user password string as described in step (a) of
243
+ "Algorithm 2: Computing an encryption key".
244
+ f) Encrypt the result of step (e), using an RC4 encryption function with
245
+ the encryption key obtained in step (d).
246
+ g) (Security handlers of revision 3 or greater) Do the following 19 times:
247
+ Take the output from the previous
248
+ invocation of the RC4 function and pass it as input to a new
249
+ invocation of the function; use an encryption
250
+ key generated by taking each byte of the encryption key obtained in
251
+ step (d) and performing an XOR
252
+ (exclusive or) operation between that byte and the single-byte value
253
+ of the iteration counter (from 1 to 19).
254
+ h) Store the output from the final invocation of the RC4 function as
255
+ the value of the O entry in the encryption dictionary.
256
+
257
+ Args:
258
+ owner_password:
259
+ rev: The encryption revision (see PDF standard)
260
+ key_size: The size of the key in bytes
261
+
262
+ Returns:
263
+ The RC4 key
264
+
265
+ """
266
+ a = _padding(owner_password)
267
+ o_hash_digest = hashlib.md5(a).digest()
268
+
269
+ if rev >= 3:
270
+ for _ in range(50):
271
+ o_hash_digest = hashlib.md5(o_hash_digest).digest()
272
+
273
+ return o_hash_digest[: key_size // 8]
274
+
275
+ @staticmethod
276
+ def compute_O_value(rc4_key: bytes, user_password: bytes, rev: int) -> bytes:
277
+ """
278
+ See :func:`compute_O_value_key`.
279
+
280
+ Args:
281
+ rc4_key:
282
+ user_password:
283
+ rev: The encryption revision (see PDF standard)
284
+
285
+ Returns:
286
+ The RC4 encrypted
287
+
288
+ """
289
+ a = _padding(user_password)
290
+ rc4_enc = rc4_encrypt(rc4_key, a)
291
+ if rev >= 3:
292
+ for i in range(1, 20):
293
+ key = bytes(x ^ i for x in rc4_key)
294
+ rc4_enc = rc4_encrypt(key, rc4_enc)
295
+ return rc4_enc
296
+
297
+ @staticmethod
298
+ def compute_U_value(key: bytes, rev: int, id1_entry: bytes) -> bytes:
299
+ """
300
+ Algorithm 4: Computing the encryption dictionary’s U (user password) value.
301
+
302
+ (Security handlers of revision 2)
303
+
304
+ a) Create an encryption key based on the user password string, as
305
+ described in "Algorithm 2: Computing an encryption key".
306
+ b) Encrypt the 32-byte padding string shown in step (a) of
307
+ "Algorithm 2: Computing an encryption key", using an RC4 encryption
308
+ function with the encryption key from the preceding step.
309
+ c) Store the result of step (b) as the value of the U entry in the
310
+ encryption dictionary.
311
+
312
+ Args:
313
+ key:
314
+ rev: The encryption revision (see PDF standard)
315
+ id1_entry:
316
+
317
+ Returns:
318
+ The value
319
+
320
+ """
321
+ if rev <= 2:
322
+ return rc4_encrypt(key, _PADDING)
323
+
324
+ """
325
+ Algorithm 5: Computing the encryption dictionary’s U (user password) value.
326
+
327
+ (Security handlers of revision 3 or greater)
328
+
329
+ a) Create an encryption key based on the user password string, as
330
+ described in "Algorithm 2: Computing an encryption key".
331
+ b) Initialize the MD5 hash function and pass the 32-byte padding string
332
+ shown in step (a) of "Algorithm 2:
333
+ Computing an encryption key" as input to this function.
334
+ c) Pass the first element of the file’s file identifier array (the value
335
+ of the ID entry in the document’s trailer
336
+ dictionary; see Table 15) to the hash function and finish the hash.
337
+ d) Encrypt the 16-byte result of the hash, using an RC4 encryption
338
+ function with the encryption key from step (a).
339
+ e) Do the following 19 times: Take the output from the previous
340
+ invocation of the RC4 function and pass it as input to a new
341
+ invocation of the function; use an encryption key generated by
342
+ taking each byte of the original encryption key obtained in
343
+ step (a) and performing an XOR (exclusive or) operation between that
344
+ byte and the single-byte value of the iteration counter (from 1 to 19).
345
+ f) Append 16 bytes of arbitrary padding to the output from the final
346
+ invocation of the RC4 function and store the 32-byte result as the
347
+ value of the U entry in the encryption dictionary.
348
+ """
349
+ u_hash = hashlib.md5(_PADDING)
350
+ u_hash.update(id1_entry)
351
+ rc4_enc = rc4_encrypt(key, u_hash.digest())
352
+ for i in range(1, 20):
353
+ rc4_key = bytes(x ^ i for x in key)
354
+ rc4_enc = rc4_encrypt(rc4_key, rc4_enc)
355
+ return _padding(rc4_enc)
356
+
357
+ @staticmethod
358
+ def verify_user_password(
359
+ user_password: bytes,
360
+ rev: int,
361
+ key_size: int,
362
+ o_entry: bytes,
363
+ u_entry: bytes,
364
+ P: int,
365
+ id1_entry: bytes,
366
+ metadata_encrypted: bool,
367
+ ) -> bytes:
368
+ """
369
+ Algorithm 6: Authenticating the user password.
370
+
371
+ a) Perform all but the last step of "Algorithm 4: Computing the
372
+ encryption dictionary’s U (user password) value (Security handlers of
373
+ revision 2)" or "Algorithm 5: Computing the encryption dictionary’s U
374
+ (user password) value (Security handlers of revision 3 or greater)"
375
+ using the supplied password string.
376
+ b) If the result of step (a) is equal to the value of the encryption
377
+ dictionary’s U entry (comparing on the first 16 bytes in the case of
378
+ security handlers of revision 3 or greater), the password supplied is
379
+ the correct user password. The key obtained in step (a) (that is, in
380
+ the first step of "Algorithm 4: Computing the encryption
381
+ dictionary’s U (user password) value
382
+ (Security handlers of revision 2)" or
383
+ "Algorithm 5: Computing the encryption dictionary’s U (user password)
384
+ value (Security handlers of revision 3 or greater)") shall be used
385
+ to decrypt the document.
386
+
387
+ Args:
388
+ user_password: The user password as a bytes stream
389
+ rev: The encryption revision (see PDF standard)
390
+ key_size: The size of the key in bytes
391
+ o_entry: The owner entry
392
+ u_entry: The user entry
393
+ P: A set of flags specifying which operations shall be permitted
394
+ when the document is opened with user access. If bit 2 is set to 1,
395
+ all other bits are ignored and all operations are permitted.
396
+ If bit 2 is set to 0, permission for operations are based on the
397
+ values of the remaining flags defined in Table 24.
398
+ id1_entry:
399
+ metadata_encrypted: A boolean indicating if the metadata is encrypted.
400
+
401
+ Returns:
402
+ The key
403
+
404
+ """
405
+ key = AlgV4.compute_key(
406
+ user_password, rev, key_size, o_entry, P, id1_entry, metadata_encrypted
407
+ )
408
+ u_value = AlgV4.compute_U_value(key, rev, id1_entry)
409
+ if rev >= 3:
410
+ u_value = u_value[:16]
411
+ u_entry = u_entry[:16]
412
+ if u_value != u_entry:
413
+ key = b""
414
+ return key
415
+
416
+ @staticmethod
417
+ def verify_owner_password(
418
+ owner_password: bytes,
419
+ rev: int,
420
+ key_size: int,
421
+ o_entry: bytes,
422
+ u_entry: bytes,
423
+ P: int,
424
+ id1_entry: bytes,
425
+ metadata_encrypted: bool,
426
+ ) -> bytes:
427
+ """
428
+ Algorithm 7: Authenticating the owner password.
429
+
430
+ a) Compute an encryption key from the supplied password string, as
431
+ described in steps (a) to (d) of
432
+ "Algorithm 3: Computing the encryption dictionary’s O (owner password)
433
+ value".
434
+ b) (Security handlers of revision 2 only) Decrypt the value of the
435
+ encryption dictionary’s O entry, using an RC4
436
+ encryption function with the encryption key computed in step (a).
437
+ (Security handlers of revision 3 or greater) Do the following 20 times:
438
+ Decrypt the value of the encryption dictionary’s O entry (first iteration)
439
+ or the output from the previous iteration (all subsequent iterations),
440
+ using an RC4 encryption function with a different encryption key at
441
+ each iteration. The key shall be generated by taking the original key
442
+ (obtained in step (a)) and performing an XOR (exclusive or) operation
443
+ between each byte of the key and the single-byte value of the
444
+ iteration counter (from 19 to 0).
445
+ c) The result of step (b) purports to be the user password.
446
+ Authenticate this user password using
447
+ "Algorithm 6: Authenticating the user password".
448
+ If it is correct, the password supplied is the correct owner password.
449
+
450
+ Args:
451
+ owner_password:
452
+ rev: The encryption revision (see PDF standard)
453
+ key_size: The size of the key in bytes
454
+ o_entry: The owner entry
455
+ u_entry: The user entry
456
+ P: A set of flags specifying which operations shall be permitted
457
+ when the document is opened with user access. If bit 2 is set to 1,
458
+ all other bits are ignored and all operations are permitted.
459
+ If bit 2 is set to 0, permission for operations are based on the
460
+ values of the remaining flags defined in Table 24.
461
+ id1_entry:
462
+ metadata_encrypted: A boolean indicating if the metadata is encrypted.
463
+
464
+ Returns:
465
+ bytes
466
+
467
+ """
468
+ rc4_key = AlgV4.compute_O_value_key(owner_password, rev, key_size)
469
+
470
+ if rev <= 2:
471
+ user_password = rc4_decrypt(rc4_key, o_entry)
472
+ else:
473
+ user_password = o_entry
474
+ for i in range(19, -1, -1):
475
+ key = bytes(x ^ i for x in rc4_key)
476
+ user_password = rc4_decrypt(key, user_password)
477
+ return AlgV4.verify_user_password(
478
+ user_password,
479
+ rev,
480
+ key_size,
481
+ o_entry,
482
+ u_entry,
483
+ P,
484
+ id1_entry,
485
+ metadata_encrypted,
486
+ )
487
+
488
+
489
+ class AlgV5:
490
+ @staticmethod
491
+ def verify_owner_password(
492
+ R: int, password: bytes, o_value: bytes, oe_value: bytes, u_value: bytes
493
+ ) -> bytes:
494
+ """
495
+ Algorithm 3.2a Computing an encryption key.
496
+
497
+ To understand the algorithm below, it is necessary to treat the O and U
498
+ strings in the Encrypt dictionary as made up of three sections.
499
+ The first 32 bytes are a hash value (explained below). The next 8 bytes
500
+ are called the Validation Salt. The final 8 bytes are called the Key Salt.
501
+
502
+ 1. The password string is generated from Unicode input by processing the
503
+ input string with the SASLprep (IETF RFC 4013) profile of
504
+ stringprep (IETF RFC 3454), and then converting to a UTF-8
505
+ representation.
506
+ 2. Truncate the UTF-8 representation to 127 bytes if it is longer than
507
+ 127 bytes.
508
+ 3. Test the password against the owner key by computing the SHA-256 hash
509
+ of the UTF-8 password concatenated with the 8 bytes of owner
510
+ Validation Salt, concatenated with the 48-byte U string. If the
511
+ 32-byte result matches the first 32 bytes of the O string, this is
512
+ the owner password.
513
+ Compute an intermediate owner key by computing the SHA-256 hash of
514
+ the UTF-8 password concatenated with the 8 bytes of owner Key Salt,
515
+ concatenated with the 48-byte U string. The 32-byte result is the
516
+ key used to decrypt the 32-byte OE string using AES-256 in CBC mode
517
+ with no padding and an initialization vector of zero.
518
+ The 32-byte result is the file encryption key.
519
+ 4. Test the password against the user key by computing the SHA-256 hash
520
+ of the UTF-8 password concatenated with the 8 bytes of user
521
+ Validation Salt. If the 32 byte result matches the first 32 bytes of
522
+ the U string, this is the user password.
523
+ Compute an intermediate user key by computing the SHA-256 hash of the
524
+ UTF-8 password concatenated with the 8 bytes of user Key Salt.
525
+ The 32-byte result is the key used to decrypt the 32-byte
526
+ UE string using AES-256 in CBC mode with no padding and an
527
+ initialization vector of zero. The 32-byte result is the file
528
+ encryption key.
529
+ 5. Decrypt the 16-byte Perms string using AES-256 in ECB mode with an
530
+ initialization vector of zero and the file encryption key as the key.
531
+ Verify that bytes 9-11 of the result are the characters ‘a’, ‘d’, ‘b’.
532
+ Bytes 0-3 of the decrypted Perms entry, treated as a little-endian
533
+ integer, are the user permissions.
534
+ They should match the value in the P key.
535
+
536
+ Args:
537
+ R: A number specifying which revision of the standard security
538
+ handler shall be used to interpret this dictionary
539
+ password: The owner password
540
+ o_value: A 32-byte string, based on both the owner and user passwords,
541
+ that shall be used in computing the encryption key and in
542
+ determining whether a valid owner password was entered
543
+ oe_value:
544
+ u_value: A 32-byte string, based on the user password, that shall be
545
+ used in determining whether to prompt the user for a password and,
546
+ if so, whether a valid user or owner password was entered.
547
+
548
+ Returns:
549
+ The key
550
+
551
+ """
552
+ password = password[:127]
553
+ if (
554
+ AlgV5.calculate_hash(R, password, o_value[32:40], u_value[:48])
555
+ != o_value[:32]
556
+ ):
557
+ return b""
558
+ iv = bytes(0 for _ in range(16))
559
+ tmp_key = AlgV5.calculate_hash(R, password, o_value[40:48], u_value[:48])
560
+ return aes_cbc_decrypt(tmp_key, iv, oe_value)
561
+
562
+ @staticmethod
563
+ def verify_user_password(
564
+ R: int, password: bytes, u_value: bytes, ue_value: bytes
565
+ ) -> bytes:
566
+ """
567
+ See :func:`verify_owner_password`.
568
+
569
+ Args:
570
+ R: A number specifying which revision of the standard security
571
+ handler shall be used to interpret this dictionary
572
+ password: The user password
573
+ u_value: A 32-byte string, based on the user password, that shall be
574
+ used in determining whether to prompt the user for a password
575
+ and, if so, whether a valid user or owner password was entered.
576
+ ue_value:
577
+
578
+ Returns:
579
+ bytes
580
+
581
+ """
582
+ password = password[:127]
583
+ if AlgV5.calculate_hash(R, password, u_value[32:40], b"") != u_value[:32]:
584
+ return b""
585
+ iv = bytes(0 for _ in range(16))
586
+ tmp_key = AlgV5.calculate_hash(R, password, u_value[40:48], b"")
587
+ return aes_cbc_decrypt(tmp_key, iv, ue_value)
588
+
589
+ @staticmethod
590
+ def calculate_hash(R: int, password: bytes, salt: bytes, udata: bytes) -> bytes:
591
+ # https://github.com/qpdf/qpdf/blob/main/libqpdf/QPDF_encryption.cc
592
+ k = hashlib.sha256(password + salt + udata).digest()
593
+ if R < 6:
594
+ return k
595
+ count = 0
596
+ while True:
597
+ count += 1
598
+ k1 = password + k + udata
599
+ e = aes_cbc_encrypt(k[:16], k[16:32], k1 * 64)
600
+ hash_fn = (
601
+ hashlib.sha256,
602
+ hashlib.sha384,
603
+ hashlib.sha512,
604
+ )[sum(e[:16]) % 3]
605
+ k = hash_fn(e).digest()
606
+ if count >= 64 and e[-1] <= count - 32:
607
+ break
608
+ return k[:32]
609
+
610
+ @staticmethod
611
+ def verify_perms(
612
+ key: bytes, perms: bytes, p: int, metadata_encrypted: bool
613
+ ) -> bool:
614
+ """
615
+ See :func:`verify_owner_password` and :func:`compute_perms_value`.
616
+
617
+ Args:
618
+ key: The owner password
619
+ perms:
620
+ p: A set of flags specifying which operations shall be permitted
621
+ when the document is opened with user access.
622
+ If bit 2 is set to 1, all other bits are ignored and all
623
+ operations are permitted.
624
+ If bit 2 is set to 0, permission for operations are based on
625
+ the values of the remaining flags defined in Table 24.
626
+ metadata_encrypted:
627
+
628
+ Returns:
629
+ A boolean
630
+
631
+ """
632
+ b8 = b"T" if metadata_encrypted else b"F"
633
+ p1 = struct.pack("<I", p) + b"\xff\xff\xff\xff" + b8 + b"adb"
634
+ p2 = aes_ecb_decrypt(key, perms)
635
+ return p1 == p2[:12]
636
+
637
+ @staticmethod
638
+ def generate_values(
639
+ R: int,
640
+ user_password: bytes,
641
+ owner_password: bytes,
642
+ key: bytes,
643
+ p: int,
644
+ metadata_encrypted: bool,
645
+ ) -> dict[Any, Any]:
646
+ user_password = user_password[:127]
647
+ owner_password = owner_password[:127]
648
+ u_value, ue_value = AlgV5.compute_U_value(R, user_password, key)
649
+ o_value, oe_value = AlgV5.compute_O_value(R, owner_password, key, u_value)
650
+ perms = AlgV5.compute_Perms_value(key, p, metadata_encrypted)
651
+ return {
652
+ "/U": u_value,
653
+ "/UE": ue_value,
654
+ "/O": o_value,
655
+ "/OE": oe_value,
656
+ "/Perms": perms,
657
+ }
658
+
659
+ @staticmethod
660
+ def compute_U_value(R: int, password: bytes, key: bytes) -> tuple[bytes, bytes]:
661
+ """
662
+ Algorithm 3.8 Computing the encryption dictionary’s U (user password)
663
+ and UE (user encryption key) values.
664
+
665
+ 1. Generate 16 random bytes of data using a strong random number generator.
666
+ The first 8 bytes are the User Validation Salt. The second 8 bytes
667
+ are the User Key Salt. Compute the 32-byte SHA-256 hash of the
668
+ password concatenated with the User Validation Salt. The 48-byte
669
+ string consisting of the 32-byte hash followed by the User
670
+ Validation Salt followed by the User Key Salt is stored as the U key.
671
+ 2. Compute the 32-byte SHA-256 hash of the password concatenated with
672
+ the User Key Salt. Using this hash as the key, encrypt the file
673
+ encryption key using AES-256 in CBC mode with no padding and an
674
+ initialization vector of zero. The resulting 32-byte string is stored
675
+ as the UE key.
676
+
677
+ Args:
678
+ R:
679
+ password:
680
+ key:
681
+
682
+ Returns:
683
+ A tuple (u-value, ue value)
684
+
685
+ """
686
+ random_bytes = secrets.token_bytes(16)
687
+ val_salt = random_bytes[:8]
688
+ key_salt = random_bytes[8:]
689
+ u_value = AlgV5.calculate_hash(R, password, val_salt, b"") + val_salt + key_salt
690
+
691
+ tmp_key = AlgV5.calculate_hash(R, password, key_salt, b"")
692
+ iv = bytes(0 for _ in range(16))
693
+ ue_value = aes_cbc_encrypt(tmp_key, iv, key)
694
+ return u_value, ue_value
695
+
696
+ @staticmethod
697
+ def compute_O_value(
698
+ R: int, password: bytes, key: bytes, u_value: bytes
699
+ ) -> tuple[bytes, bytes]:
700
+ """
701
+ Algorithm 3.9 Computing the encryption dictionary’s O (owner password)
702
+ and OE (owner encryption key) values.
703
+
704
+ 1. Generate 16 random bytes of data using a strong random number
705
+ generator. The first 8 bytes are the Owner Validation Salt. The
706
+ second 8 bytes are the Owner Key Salt. Compute the 32-byte SHA-256
707
+ hash of the password concatenated with the Owner Validation Salt and
708
+ then concatenated with the 48-byte U string as generated in
709
+ Algorithm 3.8. The 48-byte string consisting of the 32-byte hash
710
+ followed by the Owner Validation Salt followed by the Owner Key Salt
711
+ is stored as the O key.
712
+ 2. Compute the 32-byte SHA-256 hash of the password concatenated with
713
+ the Owner Key Salt and then concatenated with the 48-byte U string as
714
+ generated in Algorithm 3.8. Using this hash as the key,
715
+ encrypt the file encryption key using AES-256 in CBC mode with
716
+ no padding and an initialization vector of zero.
717
+ The resulting 32-byte string is stored as the OE key.
718
+
719
+ Args:
720
+ R:
721
+ password:
722
+ key:
723
+ u_value: A 32-byte string, based on the user password, that shall be
724
+ used in determining whether to prompt the user for a password
725
+ and, if so, whether a valid user or owner password was entered.
726
+
727
+ Returns:
728
+ A tuple (O value, OE value)
729
+
730
+ """
731
+ random_bytes = secrets.token_bytes(16)
732
+ val_salt = random_bytes[:8]
733
+ key_salt = random_bytes[8:]
734
+ o_value = (
735
+ AlgV5.calculate_hash(R, password, val_salt, u_value) + val_salt + key_salt
736
+ )
737
+ tmp_key = AlgV5.calculate_hash(R, password, key_salt, u_value[:48])
738
+ iv = bytes(0 for _ in range(16))
739
+ oe_value = aes_cbc_encrypt(tmp_key, iv, key)
740
+ return o_value, oe_value
741
+
742
+ @staticmethod
743
+ def compute_Perms_value(key: bytes, p: int, metadata_encrypted: bool) -> bytes:
744
+ """
745
+ Algorithm 3.10 Computing the encryption dictionary’s Perms
746
+ (permissions) value.
747
+
748
+ 1. Extend the permissions (contents of the P integer) to 64 bits by
749
+ setting the upper 32 bits to all 1’s.
750
+ (This allows for future extension without changing the format.)
751
+ 2. Record the 8 bytes of permission in the bytes 0-7 of the block,
752
+ low order byte first.
753
+ 3. Set byte 8 to the ASCII value ' T ' or ' F ' according to the
754
+ EncryptMetadata Boolean.
755
+ 4. Set bytes 9-11 to the ASCII characters ' a ', ' d ', ' b '.
756
+ 5. Set bytes 12-15 to 4 bytes of random data, which will be ignored.
757
+ 6. Encrypt the 16-byte block using AES-256 in ECB mode with an
758
+ initialization vector of zero, using the file encryption key as the
759
+ key. The result (16 bytes) is stored as the Perms string, and checked
760
+ for validity when the file is opened.
761
+
762
+ Args:
763
+ key:
764
+ p: A set of flags specifying which operations shall be permitted
765
+ when the document is opened with user access. If bit 2 is set to 1,
766
+ all other bits are ignored and all operations are permitted.
767
+ If bit 2 is set to 0, permission for operations are based on the
768
+ values of the remaining flags defined in Table 24.
769
+ metadata_encrypted: A boolean indicating if the metadata is encrypted.
770
+
771
+ Returns:
772
+ The perms value
773
+
774
+ """
775
+ b8 = b"T" if metadata_encrypted else b"F"
776
+ rr = secrets.token_bytes(4)
777
+ data = struct.pack("<I", p) + b"\xff\xff\xff\xff" + b8 + b"adb" + rr
778
+ return aes_ecb_encrypt(key, data)
779
+
780
+
781
+ class PasswordType(IntEnum):
782
+ NOT_DECRYPTED = 0
783
+ USER_PASSWORD = 1
784
+ OWNER_PASSWORD = 2
785
+
786
+
787
+ def _saslprep(password: str) -> str:
788
+ """
789
+ Apply the SASLprep profile (RFC 4013) of stringprep (RFC 3454).
790
+
791
+ This normalizes Unicode passwords for PDF 2.0 (AES-256, revision 5/6)
792
+ encryption as required by the PDF specification.
793
+
794
+ Args:
795
+ password: The Unicode password string to normalize.
796
+
797
+ Returns:
798
+ The SASLprep-normalized string.
799
+
800
+ Raises:
801
+ ValueError: If the password contains prohibited characters
802
+ or fails the bidirectional character check.
803
+
804
+ """
805
+ # Mapping (RFC 4013 §2.1)
806
+ # - Map characters in table B.1 to nothing
807
+ # - Map characters in table C.1.2 (non-ASCII spaces) to U+0020 (SPACE)
808
+ mapped: list[str] = []
809
+ for character in password:
810
+ if stringprep.in_table_b1(character):
811
+ continue # map to nothing
812
+ if stringprep.in_table_c12(character):
813
+ mapped.append(" ") # map to SPACE
814
+ else:
815
+ mapped.append(character)
816
+ password = "".join(mapped)
817
+
818
+ # Normalization (RFC 4013 §2.2) — Unicode NFKC
819
+ password = unicodedata.normalize("NFKC", password)
820
+
821
+ for character in password:
822
+ for check, description in _SASLPREP_PROHIBITED_CHECKS:
823
+ if check(character):
824
+ raise ValueError(
825
+ f"SASLprep: {description} U+{ord(character):04X}"
826
+ )
827
+
828
+ # Bidirectional check (RFC 4013 §2.4, RFC 3454 §6)
829
+ has_r_and_al = False
830
+ has_l = False
831
+ for character in password:
832
+ if stringprep.in_table_d1(character):
833
+ has_r_and_al = True
834
+ if stringprep.in_table_d2(character):
835
+ has_l = True
836
+
837
+ if has_r_and_al:
838
+ if has_l:
839
+ raise ValueError(
840
+ "SASLprep: string with RandALCat characters must not "
841
+ "contain LCat characters"
842
+ )
843
+ if not stringprep.in_table_d1(password[0]) or not stringprep.in_table_d1(
844
+ password[-1]
845
+ ):
846
+ raise ValueError(
847
+ "SASLprep: string with RandALCat characters must start "
848
+ "and end with RandALCat characters"
849
+ )
850
+
851
+ return password
852
+
853
+
854
+ class EncryptAlgorithm(tuple, Enum): # type: ignore # noqa: SLOT001
855
+ # V, R, Length
856
+ RC4_40 = (1, 2, 40)
857
+ RC4_128 = (2, 3, 128)
858
+ AES_128 = (4, 4, 128)
859
+ AES_256_R5 = (5, 5, 256)
860
+ AES_256 = (5, 6, 256)
861
+
862
+
863
+ class EncryptionValues:
864
+ O: bytes # noqa: E741
865
+ U: bytes
866
+ OE: bytes
867
+ UE: bytes
868
+ Perms: bytes
869
+
870
+
871
+ class Encryption:
872
+ """
873
+ Collects and manages parameters for PDF document encryption and decryption.
874
+
875
+ Args:
876
+ V: A code specifying the algorithm to be used in encrypting and
877
+ decrypting the document.
878
+ R: The revision of the standard security handler.
879
+ Length: The length of the encryption key in bits.
880
+ P: A set of flags specifying which operations shall be permitted
881
+ when the document is opened with user access
882
+ entry: The encryption dictionary object.
883
+ EncryptMetadata: Whether to encrypt metadata in the document.
884
+ first_id_entry: The first 16 bytes of the file's original ID.
885
+ StmF: The name of the crypt filter that shall be used by default
886
+ when decrypting streams.
887
+ StrF: The name of the crypt filter that shall be used when decrypting
888
+ all strings in the document.
889
+ EFF: The name of the crypt filter that shall be used when
890
+ encrypting embedded file streams that do not have their own
891
+ crypt filter specifier.
892
+ values: Additional encryption parameters.
893
+
894
+ """
895
+
896
+ def __init__(
897
+ self,
898
+ V: int,
899
+ R: int,
900
+ Length: int,
901
+ P: int,
902
+ entry: DictionaryObject,
903
+ EncryptMetadata: bool,
904
+ first_id_entry: bytes,
905
+ StmF: str,
906
+ StrF: str,
907
+ EFF: str,
908
+ values: Optional[EncryptionValues],
909
+ ) -> None:
910
+ # §7.6.2, entries common to all encryption dictionaries
911
+ # use same name as keys of encryption dictionaries entries
912
+ self.V = V
913
+ self.R = R
914
+ self.Length = Length # key_size
915
+ self.P = (P + 0x100000000) % 0x100000000 # maybe P < 0
916
+ self.EncryptMetadata = EncryptMetadata
917
+ self.id1_entry = first_id_entry
918
+ self.StmF = StmF
919
+ self.StrF = StrF
920
+ self.EFF = EFF
921
+ self.values: EncryptionValues = values or EncryptionValues()
922
+
923
+ self._password_type = PasswordType.NOT_DECRYPTED
924
+ self._key: Optional[bytes] = None
925
+ self._are_permissions_valid: bool = True
926
+
927
+ def is_decrypted(self) -> bool:
928
+ return self._password_type != PasswordType.NOT_DECRYPTED
929
+
930
+ def encrypt_object(self, obj: PdfObject, idnum: int, generation: int) -> PdfObject:
931
+ # skip calculate key
932
+ if not self._is_encryption_object(obj):
933
+ return obj
934
+
935
+ cf = self._make_crypt_filter(idnum, generation)
936
+ return cf.encrypt_object(obj)
937
+
938
+ def decrypt_object(self, obj: PdfObject, idnum: int, generation: int, *, strict: bool = True) -> PdfObject:
939
+ # skip calculate key
940
+ if not self._is_encryption_object(obj):
941
+ return obj
942
+
943
+ cf = self._make_crypt_filter(idnum, generation)
944
+ return cf.decrypt_object(obj, strict=strict)
945
+
946
+ @staticmethod
947
+ def _is_encryption_object(obj: PdfObject) -> bool:
948
+ return isinstance(
949
+ obj,
950
+ (
951
+ ByteStringObject,
952
+ TextStringObject,
953
+ StreamObject,
954
+ ArrayObject,
955
+ DictionaryObject,
956
+ ),
957
+ )
958
+
959
+ def _make_crypt_filter(self, idnum: int, generation: int) -> CryptFilter:
960
+ """
961
+ Algorithm 1: Encryption of data using the RC4 or AES algorithms.
962
+
963
+ a) Obtain the object number and generation number from the object
964
+ identifier of the string or stream to be encrypted
965
+ (see 7.3.10, "Indirect Objects"). If the string is a direct object,
966
+ use the identifier of the indirect object containing it.
967
+ b) For all strings and streams without crypt filter specifier; treating
968
+ the object number and generation number as binary integers, extend
969
+ the original n-byte encryption key to n + 5 bytes by appending the
970
+ low-order 3 bytes of the object number and the low-order 2 bytes of
971
+ the generation number in that order, low-order byte first.
972
+ (n is 5 unless the value of V in the encryption dictionary is greater
973
+ than 1, in which case n is the value of Length divided by 8.)
974
+ If using the AES algorithm, extend the encryption key an additional
975
+ 4 bytes by adding the value “sAlT”, which corresponds to the
976
+ hexadecimal values 0x73, 0x41, 0x6C, 0x54. (This addition is done for
977
+ backward compatibility and is not intended to provide additional
978
+ security.)
979
+ c) Initialize the MD5 hash function and pass the result of step (b) as
980
+ input to this function.
981
+ d) Use the first (n + 5) bytes, up to a maximum of 16, of the output
982
+ from the MD5 hash as the key for the RC4 or AES symmetric key
983
+ algorithms, along with the string or stream data to be encrypted.
984
+ If using the AES algorithm, the Cipher Block Chaining (CBC) mode,
985
+ which requires an initialization vector, is used. The block size
986
+ parameter is set to 16 bytes, and the initialization vector is a
987
+ 16-byte random number that is stored as the first 16 bytes of the
988
+ encrypted stream or string.
989
+
990
+ Algorithm 3.1a: Encryption of data using the AES-256 algorithm.
991
+
992
+ Note: Algorithm 3.1a does not use MD5 key derivation, so AES-256
993
+ encrypted files can be read on FIPS-enabled systems where MD5 is blocked.
994
+
995
+ 1. Use the 32-byte file encryption key for the AES-256 symmetric key
996
+ algorithm, along with the string or stream data to be encrypted.
997
+ Use the AES algorithm in Cipher Block Chaining (CBC) mode, which
998
+ requires an initialization vector. The block size parameter is set to
999
+ 16 bytes, and the initialization vector is a 16-byte random number
1000
+ that is stored as the first 16 bytes of the encrypted stream or string.
1001
+ The output is the encrypted data to be stored in the PDF file.
1002
+ """
1003
+ pack1 = (idnum & 0xFFFFFF).to_bytes(3, "little")
1004
+ pack2 = (generation & 0xFFFF).to_bytes(2, "little")
1005
+
1006
+ assert self._key
1007
+ key = self._key
1008
+
1009
+ # Algorithm 1 (V <= 4): MD5 key derivation. Algorithm 3.1a (V >= 5): key used directly.
1010
+ if self.V <= 4:
1011
+ n = 5 if self.V == 1 else self.Length // 8
1012
+ key_data = key[:n] + pack1 + pack2
1013
+ key_hash = hashlib.md5(key_data)
1014
+ rc4_key = key_hash.digest()[: min(n + 5, 16)]
1015
+
1016
+ # for AES-128
1017
+ key_hash.update(b"sAlT")
1018
+ aes128_key = key_hash.digest()[: min(n + 5, 16)]
1019
+ else:
1020
+ rc4_key = b""
1021
+ aes128_key = b""
1022
+
1023
+ # for AES-256
1024
+ aes256_key = key
1025
+
1026
+ stm_crypt = self._get_crypt(self.StmF, rc4_key, aes128_key, aes256_key)
1027
+ str_crypt = self._get_crypt(self.StrF, rc4_key, aes128_key, aes256_key)
1028
+ ef_crypt = self._get_crypt(self.EFF, rc4_key, aes128_key, aes256_key)
1029
+
1030
+ return CryptFilter(stm_crypt, str_crypt, ef_crypt)
1031
+
1032
+ @staticmethod
1033
+ def _get_crypt(
1034
+ method: str, rc4_key: bytes, aes128_key: bytes, aes256_key: bytes
1035
+ ) -> CryptBase:
1036
+ if method == "/AESV2":
1037
+ return CryptAES(aes128_key)
1038
+ if method == "/AESV3":
1039
+ return CryptAES(aes256_key)
1040
+ if method == "/Identity":
1041
+ return CryptIdentity()
1042
+
1043
+ return CryptRC4(rc4_key)
1044
+
1045
+ def _encode_password(
1046
+ self, password: Union[bytes, str], *, strict: bool = False
1047
+ ) -> bytes:
1048
+ if isinstance(password, str):
1049
+ if self.V >= 5:
1050
+ # PDF 2.0 §7.6.4.3.3: AES-256 (R5/R6) requires SASLprep
1051
+ # normalization followed by UTF-8 encoding.
1052
+ try:
1053
+ password = _saslprep(password)
1054
+ except (ValueError, IndexError) as e:
1055
+ if strict:
1056
+ raise ValueError(
1057
+ f"Password SASLprep normalization failed: {e}"
1058
+ ) from e
1059
+ logger_warning(
1060
+ "SASLprep normalization failed, using plain UTF-8: %(err)s",
1061
+ source=__name__,
1062
+ err=str(e),
1063
+ )
1064
+ pwd = password.encode("utf-8")
1065
+ else:
1066
+ try:
1067
+ pwd = password.encode("latin-1")
1068
+ except Exception:
1069
+ pwd = password.encode("utf-8")
1070
+ else:
1071
+ pwd = password
1072
+ return pwd
1073
+
1074
+ def verify(
1075
+ self, password: Union[bytes, str], *, strict: bool = False
1076
+ ) -> PasswordType:
1077
+ pwd = self._encode_password(password, strict=strict)
1078
+ key, rc = self.verify_v4(pwd) if self.V <= 4 else self.verify_v5(pwd)
1079
+ if rc != PasswordType.NOT_DECRYPTED:
1080
+ self._password_type = rc
1081
+ self._key = key
1082
+ return rc
1083
+
1084
+ def verify_v4(self, password: bytes) -> tuple[bytes, PasswordType]:
1085
+ # verify owner password first
1086
+ key = AlgV4.verify_owner_password(
1087
+ password,
1088
+ self.R,
1089
+ self.Length,
1090
+ self.values.O,
1091
+ self.values.U,
1092
+ self.P,
1093
+ self.id1_entry,
1094
+ self.EncryptMetadata,
1095
+ )
1096
+ if key:
1097
+ return key, PasswordType.OWNER_PASSWORD
1098
+ key = AlgV4.verify_user_password(
1099
+ password,
1100
+ self.R,
1101
+ self.Length,
1102
+ self.values.O,
1103
+ self.values.U,
1104
+ self.P,
1105
+ self.id1_entry,
1106
+ self.EncryptMetadata,
1107
+ )
1108
+ if key:
1109
+ return key, PasswordType.USER_PASSWORD
1110
+ return b"", PasswordType.NOT_DECRYPTED
1111
+
1112
+ def verify_v5(self, password: bytes) -> tuple[bytes, PasswordType]:
1113
+ # verify owner password first
1114
+ key = AlgV5.verify_owner_password(
1115
+ self.R, password, self.values.O, self.values.OE, self.values.U
1116
+ )
1117
+ rc = PasswordType.OWNER_PASSWORD
1118
+ if not key:
1119
+ key = AlgV5.verify_user_password(
1120
+ self.R, password, self.values.U, self.values.UE
1121
+ )
1122
+ rc = PasswordType.USER_PASSWORD
1123
+ if not key:
1124
+ return b"", PasswordType.NOT_DECRYPTED
1125
+
1126
+ # verify Perms
1127
+ self._are_permissions_valid = AlgV5.verify_perms(key, self.values.Perms, self.P, self.EncryptMetadata)
1128
+ if not self._are_permissions_valid:
1129
+ logger_warning("ignore '/Perms' verify failed", source=__name__)
1130
+ return key, rc
1131
+
1132
+ def write_entry(
1133
+ self,
1134
+ user_password: str,
1135
+ owner_password: Optional[str],
1136
+ *,
1137
+ strict: bool = False,
1138
+ ) -> DictionaryObject:
1139
+ user_pwd = self._encode_password(user_password, strict=strict)
1140
+ owner_pwd = (
1141
+ self._encode_password(owner_password, strict=strict)
1142
+ if owner_password
1143
+ else None
1144
+ )
1145
+ if owner_pwd is None:
1146
+ owner_pwd = user_pwd
1147
+
1148
+ if self.V <= 4:
1149
+ self.compute_values_v4(user_pwd, owner_pwd)
1150
+ else:
1151
+ self._key = secrets.token_bytes(self.Length // 8)
1152
+ values = AlgV5.generate_values(
1153
+ self.R, user_pwd, owner_pwd, self._key, self.P, self.EncryptMetadata
1154
+ )
1155
+ self.values.O = values["/O"]
1156
+ self.values.U = values["/U"]
1157
+ self.values.OE = values["/OE"]
1158
+ self.values.UE = values["/UE"]
1159
+ self.values.Perms = values["/Perms"]
1160
+
1161
+ dict_obj = DictionaryObject()
1162
+ dict_obj[NameObject("/V")] = NumberObject(self.V)
1163
+ dict_obj[NameObject("/R")] = NumberObject(self.R)
1164
+ dict_obj[NameObject("/Length")] = NumberObject(self.Length)
1165
+ dict_obj[NameObject("/P")] = NumberObject(self.P)
1166
+ dict_obj[NameObject("/Filter")] = NameObject("/Standard")
1167
+ # ignore /EncryptMetadata
1168
+
1169
+ dict_obj[NameObject("/O")] = ByteStringObject(self.values.O)
1170
+ dict_obj[NameObject("/U")] = ByteStringObject(self.values.U)
1171
+
1172
+ if self.V >= 4:
1173
+ # TODO: allow different method
1174
+ std_cf = DictionaryObject()
1175
+ std_cf[NameObject("/AuthEvent")] = NameObject("/DocOpen")
1176
+ std_cf[NameObject("/CFM")] = NameObject(self.StmF)
1177
+ std_cf[NameObject("/Length")] = NumberObject(self.Length // 8)
1178
+ cf = DictionaryObject()
1179
+ cf[NameObject("/StdCF")] = std_cf
1180
+ dict_obj[NameObject("/CF")] = cf
1181
+ dict_obj[NameObject("/StmF")] = NameObject("/StdCF")
1182
+ dict_obj[NameObject("/StrF")] = NameObject("/StdCF")
1183
+ # ignore EFF
1184
+ # dict_obj[NameObject("/EFF")] = NameObject("/StdCF")
1185
+
1186
+ if self.V >= 5:
1187
+ dict_obj[NameObject("/OE")] = ByteStringObject(self.values.OE)
1188
+ dict_obj[NameObject("/UE")] = ByteStringObject(self.values.UE)
1189
+ dict_obj[NameObject("/Perms")] = ByteStringObject(self.values.Perms)
1190
+ return dict_obj
1191
+
1192
+ def compute_values_v4(self, user_password: bytes, owner_password: bytes) -> None:
1193
+ rc4_key = AlgV4.compute_O_value_key(owner_password, self.R, self.Length)
1194
+ o_value = AlgV4.compute_O_value(rc4_key, user_password, self.R)
1195
+
1196
+ key = AlgV4.compute_key(
1197
+ user_password,
1198
+ self.R,
1199
+ self.Length,
1200
+ o_value,
1201
+ self.P,
1202
+ self.id1_entry,
1203
+ self.EncryptMetadata,
1204
+ )
1205
+ u_value = AlgV4.compute_U_value(key, self.R, self.id1_entry)
1206
+
1207
+ self._key = key
1208
+ self.values.O = o_value
1209
+ self.values.U = u_value
1210
+
1211
+ @staticmethod
1212
+ def read(encryption_entry: DictionaryObject, first_id_entry: bytes) -> "Encryption":
1213
+ if encryption_entry.get("/Filter") != "/Standard":
1214
+ raise NotImplementedError(
1215
+ "only Standard PDF encryption handler is available"
1216
+ )
1217
+ if "/SubFilter" in encryption_entry:
1218
+ raise NotImplementedError("/SubFilter NOT supported")
1219
+
1220
+ stm_filter = "/V2"
1221
+ str_filter = "/V2"
1222
+ ef_filter = "/V2"
1223
+
1224
+ alg_ver = encryption_entry.get("/V", 0)
1225
+ if alg_ver not in (1, 2, 3, 4, 5):
1226
+ raise NotImplementedError(f"Encryption V={alg_ver} NOT supported")
1227
+ if alg_ver >= 4:
1228
+ filters = encryption_entry["/CF"]
1229
+
1230
+ stm_filter = encryption_entry.get("/StmF", "/Identity")
1231
+ str_filter = encryption_entry.get("/StrF", "/Identity")
1232
+ ef_filter = encryption_entry.get("/EFF", stm_filter)
1233
+
1234
+ if stm_filter != "/Identity":
1235
+ stm_filter = filters[stm_filter]["/CFM"] # type: ignore[index]
1236
+ if str_filter != "/Identity":
1237
+ str_filter = filters[str_filter]["/CFM"] # type: ignore[index]
1238
+ if ef_filter != "/Identity":
1239
+ ef_filter = filters[ef_filter]["/CFM"] # type: ignore[index]
1240
+
1241
+ allowed_methods = ("/Identity", "/V2", "/AESV2", "/AESV3")
1242
+ if stm_filter not in allowed_methods:
1243
+ raise NotImplementedError(f"StmF Method {stm_filter} NOT supported!")
1244
+ if str_filter not in allowed_methods:
1245
+ raise NotImplementedError(f"StrF Method {str_filter} NOT supported!")
1246
+ if ef_filter not in allowed_methods:
1247
+ raise NotImplementedError(f"EFF Method {ef_filter} NOT supported!")
1248
+
1249
+ alg_rev = cast(int, encryption_entry["/R"])
1250
+ perm_flags = cast(int, encryption_entry["/P"])
1251
+ key_bits = encryption_entry.get("/Length", 40)
1252
+ if alg_ver == 4 and stm_filter == "/AESV2":
1253
+ cf_dict = cast(DictionaryObject, filters[encryption_entry["/StmF"]]) # type: ignore[index]
1254
+ # CF /Length is in bytes (default 16 for AES-128), convert to bits
1255
+ key_bits = cast(int, cf_dict.get("/Length", 16)) * 8
1256
+ encrypt_metadata = encryption_entry.get("/EncryptMetadata")
1257
+ encrypt_metadata = (
1258
+ encrypt_metadata.value if encrypt_metadata is not None else True
1259
+ )
1260
+ values = EncryptionValues()
1261
+ values.O = cast(ByteStringObject, encryption_entry["/O"]).original_bytes
1262
+ values.U = cast(ByteStringObject, encryption_entry["/U"]).original_bytes
1263
+ values.OE = encryption_entry.get("/OE", ByteStringObject()).original_bytes
1264
+ values.UE = encryption_entry.get("/UE", ByteStringObject()).original_bytes
1265
+ values.Perms = encryption_entry.get("/Perms", ByteStringObject()).original_bytes
1266
+ return Encryption(
1267
+ V=alg_ver,
1268
+ R=alg_rev,
1269
+ Length=key_bits,
1270
+ P=perm_flags,
1271
+ EncryptMetadata=encrypt_metadata,
1272
+ first_id_entry=first_id_entry,
1273
+ values=values,
1274
+ StrF=str_filter,
1275
+ StmF=stm_filter,
1276
+ EFF=ef_filter,
1277
+ entry=encryption_entry, # Dummy entry for the moment; will get removed
1278
+ )
1279
+
1280
+ @staticmethod
1281
+ def make(
1282
+ alg: EncryptAlgorithm, permissions: int, first_id_entry: bytes
1283
+ ) -> "Encryption":
1284
+ alg_ver, alg_rev, key_bits = alg
1285
+
1286
+ stm_filter, str_filter, ef_filter = "/V2", "/V2", "/V2"
1287
+
1288
+ if alg == EncryptAlgorithm.AES_128:
1289
+ stm_filter, str_filter, ef_filter = "/AESV2", "/AESV2", "/AESV2"
1290
+ elif alg in (EncryptAlgorithm.AES_256_R5, EncryptAlgorithm.AES_256):
1291
+ stm_filter, str_filter, ef_filter = "/AESV3", "/AESV3", "/AESV3"
1292
+
1293
+ return Encryption(
1294
+ V=alg_ver,
1295
+ R=alg_rev,
1296
+ Length=key_bits,
1297
+ P=permissions,
1298
+ EncryptMetadata=True,
1299
+ first_id_entry=first_id_entry,
1300
+ values=None,
1301
+ StrF=str_filter,
1302
+ StmF=stm_filter,
1303
+ EFF=ef_filter,
1304
+ entry=DictionaryObject(), # Dummy entry for the moment; will get removed
1305
+ )
.venv/lib/python3.13/site-packages/pypdf/_font.py ADDED
@@ -0,0 +1,799 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import unicodedata
4
+ from collections.abc import Sequence
5
+ from dataclasses import dataclass, field
6
+ from typing import TYPE_CHECKING, Any, ClassVar, cast
7
+
8
+ from pypdf.generic import (
9
+ ArrayObject,
10
+ DictionaryObject,
11
+ FloatObject,
12
+ IndirectObject,
13
+ NameObject,
14
+ NumberObject,
15
+ PdfObject,
16
+ StreamObject,
17
+ TextStringObject,
18
+ )
19
+
20
+ from ._cmap import get_encoding
21
+ from ._codecs.adobe_glyphs import adobe_glyphs
22
+ from ._utils import logger_warning
23
+ from .constants import FontFlags
24
+ from .errors import LimitReachedError, PdfReadError
25
+
26
+ if TYPE_CHECKING:
27
+ from fontTools.ttLib.tables._h_e_a_d import table__h_e_a_d
28
+ from fontTools.ttLib.tables._p_o_s_t import table__p_o_s_t
29
+ from fontTools.ttLib.tables.O_S_2f_2 import table_O_S_2f_2
30
+
31
+ from ._writer import PdfWriter
32
+
33
+ try:
34
+ from io import BytesIO
35
+
36
+ from fontTools.ttLib import TTFont, TTLibError
37
+ HAS_FONTTOOLS = True
38
+ except ImportError:
39
+ HAS_FONTTOOLS = False
40
+
41
+
42
+ # Limits.
43
+ MAX_CID_WIDTH_ENTRY_COUNT = 65_536
44
+ MAX_WIDTH_ENTRY_COUNT = 100_000
45
+
46
+
47
+ # Some constants from truetype font tables that we use:
48
+ HEADER_MACSTYLE_ITALIC = 0x02
49
+ OS2_FSSELECTION_ITALIC = 0x01
50
+ OS2_PANOSE_BFAMILYTYPE_SCRIPT = 3
51
+ OS2_PANOSE_BFAMILYTYPE_DECORATIVE = 4
52
+ OS2_PANOSE_BFAMILYTYPE_PICTORIAL = 5
53
+ OS2_PANOSE_BPROPORTION_MONOSPACED = 9
54
+ OS2_SFAMILYSCLASS_SCRIPTS = 10
55
+ OS2_SFAMILYSCLASS_SYMBOLIC = 12
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class FontDescriptor:
60
+ """
61
+ Represents the FontDescriptor dictionary as defined in the PDF specification.
62
+ This contains both descriptive and metric information.
63
+
64
+ The defaults are derived from the mean values of the 14 core fonts, rounded
65
+ to 100.
66
+ """
67
+
68
+ _DEFAULT_BBOX: ClassVar[tuple[float, float, float, float]] = (-100.0, -200.0, 1000.0, 900.0)
69
+
70
+ name: str = "Unknown"
71
+ family: str = "Unknown"
72
+ weight: str = "Unknown"
73
+
74
+ ascent: float = 700.0
75
+ descent: float = -200.0
76
+ cap_height: float = 600.0
77
+ x_height: float = 500.0
78
+ italic_angle: float = 0.0 # Non-italic
79
+ flags: int = 32 # Non-serif, non-symbolic, not fixed width
80
+ bbox: tuple[float, float, float, float] = _DEFAULT_BBOX
81
+ font_file: StreamObject | None = None
82
+
83
+ def as_font_descriptor_resource(self) -> DictionaryObject:
84
+ font_descriptor_resource = DictionaryObject({
85
+ NameObject("/Type"): NameObject("/FontDescriptor"),
86
+ NameObject("/FontName"): NameObject(f"/{self.name}"),
87
+ NameObject("/Flags"): NumberObject(self.flags),
88
+ NameObject("/FontBBox"): ArrayObject([FloatObject(n) for n in self.bbox]),
89
+ NameObject("/ItalicAngle"): FloatObject(self.italic_angle),
90
+ NameObject("/Ascent"): FloatObject(self.ascent),
91
+ NameObject("/Descent"): FloatObject(self.descent),
92
+ NameObject("/CapHeight"): FloatObject(self.cap_height),
93
+ NameObject("/XHeight"): FloatObject(self.x_height),
94
+ })
95
+
96
+ if self.font_file:
97
+ # Add the stream. For now, we assume a TrueType font (FontFile2)
98
+ font_descriptor_resource[NameObject("/FontFile2")] = self.font_file
99
+
100
+ return font_descriptor_resource
101
+
102
+
103
+ @dataclass(frozen=True)
104
+ class CoreFontMetrics:
105
+ font_descriptor: FontDescriptor
106
+ character_widths: dict[str, int]
107
+
108
+
109
+ @dataclass
110
+ class Font:
111
+ """
112
+ A font object for use during text extraction and for producing
113
+ text appearance streams.
114
+
115
+ Attributes:
116
+ name: Font name, derived from font["/BaseFont"]
117
+ character_map: The font's character map
118
+ encoding: Font encoding
119
+ sub_type: The font type, such as Type1, TrueType, or Type3.
120
+ font_descriptor: Font metrics, including a mapping of characters to widths
121
+ character_widths: A mapping of characters to widths
122
+ space_width: The width of a space, or an approximation
123
+ interpretable: Default True. If False, the font glyphs cannot
124
+ be translated to characters, e.g. Type3 fonts that do not define
125
+ a '/ToUnicode' mapping.
126
+
127
+ """
128
+
129
+ name: str
130
+ encoding: str | dict[int, str]
131
+ character_map: dict[Any, Any] = field(default_factory=dict)
132
+ sub_type: str = "Unknown"
133
+ font_descriptor: FontDescriptor = field(default_factory=FontDescriptor)
134
+ character_widths: dict[str, int] = field(default_factory=lambda: {"default": 500})
135
+ space_width: float | int = 250
136
+ space_char: str = " "
137
+ interpretable: bool = True
138
+
139
+ @staticmethod
140
+ def _collect_tt_t1_character_widths(
141
+ pdf_font_dict: DictionaryObject,
142
+ char_map: dict[Any, Any],
143
+ encoding: str | dict[int, str],
144
+ current_widths: dict[str, int]
145
+ ) -> None:
146
+ """Parses a TrueType or Type1 font's /Widths array from a font dictionary and updates character widths"""
147
+ widths_array = cast(ArrayObject, pdf_font_dict["/Widths"])
148
+ first_char = pdf_font_dict.get("/FirstChar", 0)
149
+ for idx, width in enumerate(widths_array):
150
+ current_widths[chr(idx + first_char)] = int(width)
151
+
152
+ @staticmethod
153
+ def __check_range_length(start: int, end: int) -> None:
154
+ if end < start:
155
+ raise LimitReachedError(
156
+ f"Invalid CID width range: {start}..{end}."
157
+ )
158
+
159
+ count = end - start
160
+ if count > MAX_CID_WIDTH_ENTRY_COUNT:
161
+ raise LimitReachedError(f"CID width range too large: {count} > {MAX_CID_WIDTH_ENTRY_COUNT}.")
162
+
163
+ @staticmethod
164
+ def __check_entry_count(count: int) -> None:
165
+ if count > MAX_WIDTH_ENTRY_COUNT:
166
+ raise LimitReachedError(f"Too many character widths: {count} > {MAX_WIDTH_ENTRY_COUNT}.")
167
+
168
+ @staticmethod
169
+ def _collect_cid_character_widths(d_font: DictionaryObject, current_widths: dict[str, int]) -> None:
170
+ """Parses the /W array from a DescendantFont dictionary and updates character widths."""
171
+ # /W width definitions have two valid formats which can be mixed and matched:
172
+ # (1) A character start index followed by a list of widths, e.g.
173
+ # `45 [500 600 700]` applies widths 500, 600, 700 to characters 45-47.
174
+ # (2) A character start index, a character stop index, and a width, e.g.
175
+ # `45 65 500` applies width 500 to characters 45-65.
176
+ skip_count = 0
177
+ entry_count = 0
178
+ _w = d_font.get("/W", ArrayObject()).get_object()
179
+ _w_length = len(_w)
180
+ for idx, w_entry in enumerate(_w):
181
+ if skip_count:
182
+ skip_count -= 1
183
+ continue
184
+ w_entry = w_entry.get_object()
185
+ if not isinstance(w_entry, (int, float)):
186
+ # We should never get here due to skip_count above. But
187
+ # sometimes we do.
188
+ logger_warning(
189
+ "Expected numeric value for width, got %(w_entry)s. Ignoring it.",
190
+ source=__name__,
191
+ w_entry=w_entry,
192
+ )
193
+ continue
194
+ # check for format (1): `int [int int int int ...]`
195
+ w_next_entry = _w[idx + 1].get_object() if idx + 1 < _w_length else None
196
+ if isinstance(w_next_entry, Sequence):
197
+ start_idx, width_list = int(w_entry), w_next_entry
198
+ stop_idx = start_idx + len(width_list)
199
+ Font.__check_range_length(start_idx, stop_idx)
200
+ entry_count += (stop_idx - start_idx)
201
+ Font.__check_entry_count(entry_count)
202
+ current_widths.update(
203
+ {
204
+ chr(_cidx): _width
205
+ for _cidx, _width in zip(
206
+ range(start_idx, stop_idx, 1),
207
+ width_list,
208
+ )
209
+ }
210
+ )
211
+ skip_count = 1
212
+ # check for format (2): `int int int`
213
+ elif (
214
+ isinstance(w_next_entry, (int, float))
215
+ and idx + 2 < _w_length
216
+ and isinstance(_w[idx + 2].get_object(), (int, float))
217
+ ):
218
+ start_idx, stop_idx, const_width = (
219
+ int(w_entry),
220
+ int(w_next_entry),
221
+ _w[idx + 2].get_object(),
222
+ )
223
+ Font.__check_range_length(start_idx, stop_idx + 1)
224
+ entry_count += (stop_idx - start_idx + 1)
225
+ Font.__check_entry_count(entry_count)
226
+ current_widths.update(
227
+ {
228
+ chr(_cidx): const_width
229
+ for _cidx in range(
230
+ start_idx, stop_idx + 1, 1
231
+ )
232
+ }
233
+ )
234
+ skip_count = 2
235
+ else:
236
+ # This handles the case of out of bounds (reaching the end of the width definitions
237
+ # while expecting more elements).
238
+ logger_warning(
239
+ "Invalid font width definition. Last element: %(w_entry)s.",
240
+ source=__name__,
241
+ w_entry=w_entry,
242
+ )
243
+
244
+ @staticmethod
245
+ def _get_space_char(
246
+ encoding: str | dict[int, str],
247
+ character_map: dict[Any, Any],
248
+ ) -> str:
249
+ space_char = " "
250
+ if isinstance(encoding, dict):
251
+ for char_code, char_str in encoding.items():
252
+ if char_str == space_char:
253
+ return chr(char_code)
254
+
255
+ for glyph_id, char_str in character_map.items():
256
+ if char_str == space_char:
257
+ return str(glyph_id)
258
+
259
+ return space_char
260
+
261
+ @staticmethod
262
+ def _add_default_width(current_widths: dict[str, int], flags: int, space_char: str) -> None:
263
+ if not current_widths:
264
+ current_widths["default"] = 500
265
+ return
266
+
267
+ if space_char in current_widths and current_widths[space_char] != 0:
268
+ # Setting default to once or twice the space width, depending on fixed pitch
269
+ if (flags & FontFlags.FIXED_PITCH) == FontFlags.FIXED_PITCH:
270
+ current_widths["default"] = current_widths[space_char]
271
+ return
272
+
273
+ current_widths["default"] = int(2 * current_widths[space_char])
274
+ return
275
+
276
+ # Use the average width of existing glyph widths
277
+ valid_widths = [w for w in current_widths.values() if w > 0]
278
+ current_widths["default"] = sum(valid_widths) // len(valid_widths) if valid_widths else 500
279
+
280
+ @staticmethod
281
+ def _add_space_width(
282
+ character_widths: dict[str, int],
283
+ flags: int,
284
+ space_char: str
285
+ ) -> int:
286
+ space_width = character_widths.get(space_char, 0)
287
+ if space_width != 0:
288
+ return space_width
289
+
290
+ if (flags & FontFlags.FIXED_PITCH) == FontFlags.FIXED_PITCH:
291
+ return character_widths["default"]
292
+
293
+ return character_widths["default"] // 2
294
+
295
+ @staticmethod
296
+ def _parse_bbox(raw_bbox: Any) -> tuple[float, float, float, float] | None:
297
+ """
298
+ Convert a raw /FontBBox value into four floats.
299
+
300
+ Args:
301
+ raw_bbox: The raw /FontBBox value read from the PDF.
302
+
303
+ Returns:
304
+ The four bounding box values, or ``None`` when the value is not
305
+ a sequence of exactly four numbers, so that a malformed entry
306
+ falls back to the default bounding box rather than raising.
307
+
308
+ """
309
+ try:
310
+ bbox = [float(value) for value in raw_bbox]
311
+ except (TypeError, ValueError):
312
+ return None
313
+ if len(bbox) != 4:
314
+ return None
315
+ return bbox[0], bbox[1], bbox[2], bbox[3]
316
+
317
+ @staticmethod
318
+ def _parse_font_descriptor(font_descriptor_obj: DictionaryObject) -> dict[str, Any]:
319
+ font_descriptor_kwargs: dict[Any, Any] = {}
320
+ for source_key, target_key in [
321
+ ("/FontName", "name"),
322
+ ("/FontFamily", "family"),
323
+ ("/FontWeight", "weight"),
324
+ ("/Ascent", "ascent"),
325
+ ("/Descent", "descent"),
326
+ ("/CapHeight", "cap_height"),
327
+ ("/XHeight", "x_height"),
328
+ ("/ItalicAngle", "italic_angle"),
329
+ ("/Flags", "flags"),
330
+ ("/FontBBox", "bbox")
331
+ ]:
332
+ if source_key in font_descriptor_obj:
333
+ font_descriptor_kwargs[target_key] = font_descriptor_obj[source_key]
334
+ # Handle missing or malformed bbox gracefully - PDFs may have fonts without valid bounding boxes
335
+ if "bbox" in font_descriptor_kwargs:
336
+ bbox = Font._parse_bbox(font_descriptor_kwargs["bbox"])
337
+ if bbox is None:
338
+ del font_descriptor_kwargs["bbox"]
339
+ else:
340
+ font_descriptor_kwargs["bbox"] = bbox
341
+
342
+ # Find the binary stream for this font if there is one
343
+ for source_key in ["/FontFile", "/FontFile2", "/FontFile3"]:
344
+ if source_key in font_descriptor_obj:
345
+ if "font_file" in font_descriptor_kwargs:
346
+ raise PdfReadError(f"More than one /FontFile found in {font_descriptor_obj}")
347
+
348
+ try:
349
+ font_file = font_descriptor_obj[source_key].get_object()
350
+ font_descriptor_kwargs["font_file"] = font_file
351
+ except PdfReadError as e:
352
+ logger_warning(
353
+ "Failed to get %(source_key)r in %(font_descriptor_obj)s: %(error)s",
354
+ source=__name__,
355
+ source_key=source_key,
356
+ font_descriptor_obj=font_descriptor_obj,
357
+ error=e,
358
+ )
359
+ return font_descriptor_kwargs
360
+
361
+ @classmethod
362
+ def from_font_resource(
363
+ cls,
364
+ pdf_font_dict: DictionaryObject,
365
+ ) -> Font:
366
+ from pypdf._codecs.core_font_metrics import CORE_FONT_METRICS # noqa: PLC0415
367
+
368
+ # Can collect base_font, name and encoding directly from font resource
369
+ name = pdf_font_dict.get("/BaseFont", "Unknown").removeprefix("/")
370
+ sub_type = pdf_font_dict.get("/Subtype", "Unknown").removeprefix("/")
371
+ encoding, character_map = get_encoding(pdf_font_dict)
372
+ font_descriptor = None
373
+ character_widths: dict[str, int] = {}
374
+ interpretable = True
375
+
376
+ # Deal with fonts by type; Type1, TrueType and certain Type3
377
+ if pdf_font_dict.get("/Subtype") in ("/Type1", "/MMType1", "/TrueType", "/Type3"):
378
+ # Type3 fonts that do not specify a "/ToUnicode" mapping cannot be
379
+ # reliably converted into character codes unless all named chars
380
+ # in /CharProcs map to a standard adobe glyph. See §9.10.2 of the
381
+ # PDF 1.7 standard.
382
+ if sub_type == "Type3" and "/ToUnicode" not in pdf_font_dict:
383
+ interpretable = all(
384
+ cname in adobe_glyphs
385
+ for cname in pdf_font_dict.get("/CharProcs") or []
386
+ )
387
+ if interpretable: # Save some overhead if font is not interpretable
388
+ if "/Widths" in pdf_font_dict:
389
+ cls._collect_tt_t1_character_widths(
390
+ pdf_font_dict, character_map, encoding, character_widths
391
+ )
392
+
393
+ elif name in CORE_FONT_METRICS:
394
+ font_descriptor = CORE_FONT_METRICS[name].font_descriptor
395
+ if isinstance(encoding, dict):
396
+ for code, character in encoding.items():
397
+ # Look up the width using the glyph name from the encoding
398
+ if character in CORE_FONT_METRICS[name].character_widths:
399
+ character_widths[chr(code)] = CORE_FONT_METRICS[name].character_widths[character]
400
+ else:
401
+ for code in range(256):
402
+ character = chr(code)
403
+ if character in CORE_FONT_METRICS[name].character_widths:
404
+ character_widths[character] = CORE_FONT_METRICS[name].character_widths[character]
405
+ if "/FontDescriptor" in pdf_font_dict:
406
+ font_descriptor_obj = pdf_font_dict.get("/FontDescriptor", DictionaryObject()).get_object()
407
+ if "/MissingWidth" in font_descriptor_obj:
408
+ character_widths["default"] = cast(int, font_descriptor_obj["/MissingWidth"].get_object())
409
+ font_descriptor = FontDescriptor(**cls._parse_font_descriptor(font_descriptor_obj))
410
+ elif "/FontBBox" in pdf_font_dict:
411
+ # For Type3 without Font Descriptor but with FontBBox, see Table 110 in the PDF specification 2.0
412
+ font_descriptor_kwargs: dict[str, Any] = {"name": name}
413
+ bbox = cls._parse_bbox(pdf_font_dict["/FontBBox"])
414
+ if bbox is not None:
415
+ font_descriptor_kwargs["bbox"] = bbox
416
+ font_descriptor = FontDescriptor(**font_descriptor_kwargs)
417
+
418
+ else:
419
+ # Composite font or CID font - CID fonts have a /W array mapping character codes
420
+ # to widths stashed in /DescendantFonts. No need to test for /DescendantFonts though,
421
+ # because all other fonts have already been dealt with.
422
+ d_font: DictionaryObject
423
+ for d_font_idx, d_font in enumerate(
424
+ cast(ArrayObject, pdf_font_dict["/DescendantFonts"])
425
+ ):
426
+ d_font = cast(DictionaryObject, d_font.get_object())
427
+ cast(ArrayObject, pdf_font_dict["/DescendantFonts"])[d_font_idx] = d_font
428
+ cls._collect_cid_character_widths(d_font=d_font, current_widths=character_widths)
429
+ if "/DW" in d_font:
430
+ character_widths["default"] = cast(int, d_font["/DW"].get_object())
431
+ font_descriptor_obj = d_font.get("/FontDescriptor", DictionaryObject()).get_object()
432
+ font_descriptor = FontDescriptor(**cls._parse_font_descriptor(font_descriptor_obj))
433
+
434
+ if not font_descriptor:
435
+ font_descriptor = FontDescriptor(name=name)
436
+
437
+ space_char = cls._get_space_char(encoding, character_map)
438
+ if character_widths.get("default", 0) == 0:
439
+ cls._add_default_width(character_widths, font_descriptor.flags, space_char)
440
+ space_width = cls._add_space_width(character_widths, font_descriptor.flags, space_char)
441
+
442
+ return cls(
443
+ name=name,
444
+ sub_type=sub_type,
445
+ encoding=encoding,
446
+ font_descriptor=font_descriptor,
447
+ character_map=character_map,
448
+ character_widths=character_widths,
449
+ space_width=space_width,
450
+ space_char=space_char,
451
+ interpretable=interpretable
452
+ )
453
+
454
+ @staticmethod
455
+ def _font_flags_from_truetype_font_tables(
456
+ header: table__h_e_a_d,
457
+ postscript: table__p_o_s_t,
458
+ os2: table_O_S_2f_2
459
+ ) -> int:
460
+ # Get the font flags
461
+ if os2:
462
+ panose = os2.panose
463
+ # sFamilyClass is a two-byte field. The high byte describes the family class, whereas the low
464
+ # byte only describes the subclass. We only need the high byte, hence the bit shift below:
465
+ family_class = os2.sFamilyClass >> 8
466
+ flags: int = 0
467
+
468
+ # ITALIC
469
+ if header.macStyle & HEADER_MACSTYLE_ITALIC or (os2 and os2.fsSelection & OS2_FSSELECTION_ITALIC):
470
+ flags |= FontFlags.ITALIC
471
+ if postscript:
472
+ italic_angle = postscript.italicAngle
473
+ if italic_angle != 0.0:
474
+ flags |= FontFlags.ITALIC
475
+
476
+ # FIXED_PITCH
477
+ if (
478
+ (os2 and panose.bProportion == OS2_PANOSE_BPROPORTION_MONOSPACED) or
479
+ (postscript and postscript.isFixedPitch > 0) # Actually 1, but originally (older versions of the TTF
480
+ ): # specification) any non-zero value signified monospace.
481
+ flags |= FontFlags.FIXED_PITCH
482
+
483
+ # SCRIPT
484
+ if os2 and (
485
+ family_class == OS2_SFAMILYSCLASS_SCRIPTS or panose.bFamilyType == OS2_PANOSE_BFAMILYTYPE_SCRIPT
486
+ ):
487
+ flags |= FontFlags.SCRIPT
488
+
489
+ # SERIF
490
+ if os2 and (
491
+ 2 <= panose.bSerifStyle <= 10
492
+ or 1 <= family_class <= 5 or family_class == 7 # 6 is reserved, all 8 and above are not serif
493
+ ):
494
+ flags |= FontFlags.SERIF
495
+
496
+ # SYMBOLIC
497
+ if os2 and (
498
+ family_class == OS2_SFAMILYSCLASS_SYMBOLIC or
499
+ panose.bFamilyType in {OS2_PANOSE_BFAMILYTYPE_DECORATIVE, OS2_PANOSE_BFAMILYTYPE_PICTORIAL}
500
+ ):
501
+ flags |= FontFlags.SYMBOLIC
502
+ else:
503
+ flags |= FontFlags.NONSYMBOLIC
504
+
505
+ return flags
506
+
507
+ @classmethod
508
+ def from_truetype_font_file(cls, font_file: BytesIO) -> Font:
509
+ if not HAS_FONTTOOLS:
510
+ raise ImportError("The 'fontTools' library is required to use 'from_truetype_font_file'")
511
+ with TTFont(font_file) as tt_font_object:
512
+ # See Chapter 6 of the TrueType reference manual for the definition of the head, OS/2 and post tables:
513
+ # https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6head.html
514
+ # https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6OS2.html
515
+ # https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6post.html
516
+ header = tt_font_object["head"]
517
+ horizontal_header = tt_font_object["hhea"]
518
+ metrics = tt_font_object["hmtx"].metrics
519
+
520
+ # Collect additional font tables to derive font information
521
+ postscript = tt_font_object.get("post", None)
522
+ os2 = tt_font_object.get("OS/2", None)
523
+
524
+ # Get the scaling factor to convert font file's units per em to PDF's 1000 units per em
525
+ units_per_em = header.unitsPerEm
526
+ if not units_per_em:
527
+ raise PdfReadError("Font file has an invalid unitsPerEm of 0")
528
+ scale_factor = 1000.0 / units_per_em
529
+
530
+ # Get the font descriptor
531
+ font_descriptor_kwargs: dict[Any, Any] = {}
532
+ names = tt_font_object.get("name", None)
533
+ if names:
534
+ font_descriptor_kwargs["name"] = names.getBestFullName()
535
+ font_descriptor_kwargs["family"] = names.getBestFamilyName()
536
+ font_descriptor_kwargs["weight"] = names.getBestSubFamilyName()
537
+ font_descriptor_kwargs["ascent"] = int(round(horizontal_header.ascent * scale_factor, 0))
538
+ font_descriptor_kwargs["descent"] = int(round(horizontal_header.descent * scale_factor, 0))
539
+ if os2:
540
+ try:
541
+ font_descriptor_kwargs["cap_height"] = int(round(os2.sCapHeight * scale_factor, 0))
542
+ font_descriptor_kwargs["x_height"] = int(round(os2.sxHeight * scale_factor, 0))
543
+ except AttributeError:
544
+ pass
545
+
546
+ font_descriptor_kwargs["flags"] = cls._font_flags_from_truetype_font_tables(header, postscript, os2)
547
+
548
+ font_descriptor_kwargs["bbox"] = (
549
+ round(header.xMin * scale_factor, 0),
550
+ round(header.yMin * scale_factor, 0),
551
+ round(header.xMax * scale_factor, 0),
552
+ round(header.yMax * scale_factor, 0)
553
+ )
554
+
555
+ font_file_data = StreamObject()
556
+ font_file_raw_bytes = font_file.getvalue()
557
+ font_file_data.set_data(font_file_raw_bytes)
558
+ font_file_data.update({NameObject("/Length1"): NumberObject(len(font_file_raw_bytes))})
559
+ font_descriptor_kwargs["font_file"] = font_file_data
560
+
561
+ font_descriptor = FontDescriptor(**font_descriptor_kwargs)
562
+ encoding = "utf_16_be" # Assume unicode
563
+
564
+ character_widths: dict[str, int] = {}
565
+ character_map: dict[str, str] = {}
566
+
567
+ glyph_order = tt_font_object.getGlyphOrder()
568
+ # Note that one glyph can be mapped to multiple unicode code points. However, buildReversedMin()
569
+ # creates a dictionary mapping glyphs to the minimum Unicode codepoint.
570
+ tt_font_cmap_table = tt_font_object.get("cmap")
571
+ if tt_font_cmap_table:
572
+ reverse_cmap = tt_font_cmap_table.buildReversedMin()
573
+ for gid, glyph in enumerate(glyph_order):
574
+ char_code = reverse_cmap.get(glyph)
575
+ if char_code is None:
576
+ continue
577
+ char = chr(char_code)
578
+ gid = tt_font_object.getGlyphID(glyph)
579
+ # The following is to comply with how font_glyph_byte_map works in _appearance_stream.py
580
+ gid_bytes = gid.to_bytes(2, "big")
581
+ gid_key_string = gid_bytes.decode("utf-16-be", "surrogatepass")
582
+ character_map[gid_key_string] = char
583
+ character_widths[gid_key_string] = int(round(metrics[glyph][0] * scale_factor, 0))
584
+ else:
585
+ raise PdfReadError("Font file does not have a cmap table")
586
+
587
+ space_char = cls._get_space_char(encoding, character_map)
588
+ cls._add_default_width(character_widths, font_descriptor_kwargs["flags"], space_char)
589
+ space_width = cls._add_space_width(
590
+ character_widths, font_descriptor_kwargs["flags"], space_char
591
+ )
592
+
593
+ return cls(
594
+ name=font_descriptor.name,
595
+ sub_type="TrueType",
596
+ encoding=encoding,
597
+ font_descriptor=font_descriptor,
598
+ character_map=character_map,
599
+ character_widths=character_widths,
600
+ space_width=space_width,
601
+ space_char=space_char,
602
+ interpretable=True
603
+ )
604
+
605
+ def _get_typographic_maps(self) -> tuple[dict[str, str], dict[str, bytes]]:
606
+ """
607
+ Generates maps to translate input unicode text to bytes in two steps:
608
+ Unicode code point -> raw_character (reverse cmap) -> PDF bytes (encoding cmap).
609
+ """
610
+ reverse_cmap = {}
611
+ encoding_cmap = {}
612
+ if (
613
+ HAS_FONTTOOLS
614
+ and getattr(self.font_descriptor, "font_file", None)
615
+ and isinstance(self.encoding, str)
616
+ ):
617
+ try:
618
+ font_file_data = cast(StreamObject, self.font_descriptor.font_file).get_data()
619
+ with TTFont(BytesIO(font_file_data)) as tt_font_object:
620
+ tt_font_cmap_table = tt_font_object.get("cmap")
621
+ best_cmap = tt_font_cmap_table.getBestCmap()
622
+ for unicode_int, glyph_name in best_cmap.items():
623
+ gid = tt_font_object.getGlyphID(glyph_name)
624
+ gid_bytes = gid.to_bytes(2, "big")
625
+ gid_key_string = gid_bytes.decode("utf-16-be", "surrogatepass")
626
+ unicode_char = chr(unicode_int)
627
+ reverse_cmap[unicode_char] = gid_key_string
628
+ encoding_cmap[gid_key_string] = gid_key_string.encode(self.encoding)
629
+
630
+ return reverse_cmap, encoding_cmap
631
+
632
+ except (AttributeError, TTLibError): # Cmap table is missing or the font is corrupt.
633
+ reverse_cmap.clear()
634
+ encoding_cmap.clear()
635
+
636
+ if isinstance(self.encoding, str):
637
+ for glyph_id, unicode_char in self.character_map.items():
638
+ glyph_id_str = str(glyph_id)
639
+ reverse_cmap[unicode_char] = glyph_id_str
640
+ encoding_cmap[glyph_id_str] = glyph_id_str.encode(self.encoding)
641
+ else:
642
+ for character_code, unicode_char in self.encoding.items():
643
+ character_str = chr(character_code)
644
+ reverse_cmap[unicode_char] = character_str
645
+ encoding_cmap[character_str] = bytes((character_code,))
646
+
647
+ unicode_to_bytes = {
648
+ unicode_char: bytes((character_code,)) for character_code, unicode_char in self.encoding.items()
649
+ }
650
+ for glyph_id, unicode_char in self.character_map.items(): # This code is not covered nor tested
651
+ reverse_cmap[unicode_char] = glyph_id
652
+ encoding_cmap[glyph_id] = unicode_to_bytes.get(unicode_char, bytes((glyph_id,)))
653
+
654
+ return reverse_cmap, encoding_cmap
655
+
656
+ def _create_widths_list_and_unicode_stream(self) -> tuple[list[PdfObject], StreamObject]:
657
+ widths_list = []
658
+ unicode_map = []
659
+ # In the loop, char is the decoded GID string (the reverse unicode hack)
660
+ # and character_map[char] is the actual character.
661
+ # The widths (/W) array can have two formats:
662
+ # [first_cid [w1 w2 w3]] or [first last width]
663
+ # Here we choose the first format and simply provide one array with one width for every cid.
664
+ for gid_str, actual_char in self.character_map.items():
665
+ # Make sure that we do not include characters such as arabic presentation form characters.
666
+ # Note that, in some cases, unicodedata.normalize() might split a ligature, resulting
667
+ # in multiple characters.
668
+ normalized_chars = unicodedata.normalize("NFKC", actual_char)
669
+ uni_points = [ord(char) for char in normalized_chars]
670
+ # Only deal with Basic Multilingual Plane characters.
671
+ # TODO: Add all characters.
672
+ if all(uni_point <= 0xFFFF for uni_point in uni_points):
673
+ cid = ord(gid_str)
674
+ cid_hex = f"{cid:04X}"
675
+ uni_hex = "".join(f"{uni_point:04X}" for uni_point in uni_points)
676
+ unicode_map.append(f"<{cid_hex}> <{uni_hex}>")
677
+
678
+ width = self.character_widths.get(gid_str, self.character_widths["default"])
679
+ widths_list.extend([NumberObject(cid), ArrayObject([NumberObject(width)])])
680
+
681
+ # Create the /ToUnicode CMap Stream
682
+ to_unicode_stream = StreamObject()
683
+ to_unicode_stream.set_data(
684
+ (
685
+ "/CIDInit /ProcSet findresource begin\n"
686
+ "12 dict begin\n"
687
+ "begincmap\n"
688
+ "/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n"
689
+ "/CMapName /Adobe-Identity-UCS def\n"
690
+ "/CMapType 2 def\n"
691
+ "1 begincodespacerange <0000> <FFFF> endcodespacerange\n"
692
+ f"{len(unicode_map)} beginbfchar\n"
693
+ + "\n".join(unicode_map) + "\n"
694
+ "endbfchar\n"
695
+ "endcmap\n"
696
+ "CMapName currentdict /CMap defineresource pop\n"
697
+ "end end"
698
+ ).encode("ascii")
699
+ )
700
+
701
+ return widths_list, to_unicode_stream
702
+
703
+ def as_font_resource(self) -> DictionaryObject:
704
+ # If we have an embedded Truetype font, we assume that we need to produce a Type 2 CID font resource.
705
+ if self.font_descriptor.font_file and self.sub_type == "TrueType":
706
+ # Begin with creating the widths array (part of the descendant font) and the unicode cmap (part
707
+ # of the Type 0 font object).
708
+ widths_list, to_unicode_stream = self._create_widths_list_and_unicode_stream()
709
+
710
+ # Create the descendant font object
711
+ cid_font = DictionaryObject({
712
+ NameObject("/Type"): NameObject("/Font"),
713
+ NameObject("/Subtype"): NameObject("/CIDFontType2"),
714
+ NameObject("/BaseFont"): NameObject(f"/{self.name}"),
715
+ NameObject("/CIDSystemInfo"): DictionaryObject({
716
+ NameObject("/Registry"): TextStringObject("Adobe"),
717
+ NameObject("/Ordering"): TextStringObject("Identity"),
718
+ NameObject("/Supplement"): NumberObject(0)
719
+ }),
720
+ NameObject("/FontDescriptor"): self.font_descriptor.as_font_descriptor_resource(),
721
+ NameObject("/W"): ArrayObject(widths_list),
722
+ NameObject("/DW"): NumberObject(self.character_widths["default"]),
723
+ NameObject("/CIDToGIDMap"): NameObject("/Identity")
724
+ })
725
+
726
+ # Create the Type 0 font object
727
+ return DictionaryObject({
728
+ NameObject("/Type"): NameObject("/Font"),
729
+ NameObject("/Subtype"): NameObject("/Type0"),
730
+ NameObject("/BaseFont"): NameObject(f"/{self.name}"),
731
+ NameObject("/Encoding"): NameObject("/Identity-H"),
732
+ NameObject("/DescendantFonts"): ArrayObject([cid_font]),
733
+ NameObject("/ToUnicode"): to_unicode_stream,
734
+ })
735
+
736
+ # Fallback: Return a font resource for one of the 14 Adobe Core fonts.
737
+ return DictionaryObject({
738
+ NameObject("/Type"): NameObject("/Font"),
739
+ NameObject("/Subtype"): NameObject("/Type1"),
740
+ NameObject("/Name"): NameObject(f"/{self.name}"),
741
+ NameObject("/BaseFont"): NameObject(f"/{self.name}"),
742
+ NameObject("/Encoding"): NameObject("/WinAnsiEncoding")
743
+ })
744
+
745
+ def _add_to_writer(
746
+ self,
747
+ writer: PdfWriter,
748
+ target_resource_dict: DictionaryObject,
749
+ font_resource_name: NameObject
750
+ ) -> IndirectObject:
751
+ """
752
+ Some objects in a font resource need to be indirect objects. This method
753
+ ensures that ToUnicode, FontDescriptor, FontFile, and, ultimately, the font
754
+ resource itself, are registered with the PdfWriter instance as indirect objects.
755
+ """
756
+ font_resource = self.as_font_resource()
757
+ if "/ToUnicode" in font_resource:
758
+ font_resource[NameObject("/ToUnicode")] = writer._add_object(font_resource["/ToUnicode"])
759
+
760
+ if "/DescendantFonts" in font_resource:
761
+ descendant_fonts = cast(ArrayObject, font_resource["/DescendantFonts"])
762
+ font_resource_dict = cast(DictionaryObject, descendant_fonts[0])
763
+ else:
764
+ font_resource_dict = font_resource
765
+
766
+ if "/FontDescriptor" in font_resource_dict:
767
+ font_descriptor_obj = cast(DictionaryObject, font_resource_dict["/FontDescriptor"])
768
+ for key in ["/FontFile", "/FontFile2", "/FontFile3"]:
769
+ if key in font_descriptor_obj:
770
+ font_descriptor_obj[NameObject(key)] = writer._add_object(font_descriptor_obj[key])
771
+ font_resource_dict[NameObject("/FontDescriptor")] = writer._add_object(
772
+ font_resource_dict["/FontDescriptor"]
773
+ )
774
+ font_resource_ref = writer._add_object(font_resource)
775
+ target_resource_dict[font_resource_name] = font_resource_ref
776
+ return font_resource_ref
777
+
778
+ def get_text_width(self, text: str = "") -> float:
779
+ """Sum of character widths specified in PDF font for the supplied text."""
780
+ return sum(
781
+ [self.character_widths.get(char, self.character_widths["default"]) for char in text], 0.0
782
+ )
783
+
784
+ def can_encode(self, text: str) -> bool:
785
+ """Check whether the font is able to encode a text string."""
786
+ try:
787
+ if self.character_map:
788
+ supported_chars = set(self.character_map.values())
789
+ return all(char in supported_chars for char in text)
790
+ if isinstance(self.encoding, str):
791
+ text.encode(self.encoding, "surrogatepass")
792
+ else:
793
+ supported_chars = set(self.encoding.values())
794
+ return all(char in supported_chars for char in text)
795
+
796
+ except UnicodeEncodeError:
797
+ return False
798
+
799
+ return True
.venv/lib/python3.13/site-packages/pypdf/_page.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv/lib/python3.13/site-packages/pypdf/_page_labels.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Page labels are shown by PDF viewers as "the page number".
3
+
4
+ A page has a numeric index, starting at 0. Additionally, the page
5
+ has a label. In the most simple case:
6
+
7
+ label = index + 1
8
+
9
+ However, the title page and the table of contents might have Roman numerals as
10
+ page labels. This makes things more complicated.
11
+
12
+ Example 1
13
+ ---------
14
+
15
+ >>> reader.root_object["/PageLabels"]["/Nums"]
16
+ [0, IndirectObject(18, 0, 139929798197504),
17
+ 8, IndirectObject(19, 0, 139929798197504)]
18
+ >>> reader.get_object(reader.root_object["/PageLabels"]["/Nums"][1])
19
+ {'/S': '/r'}
20
+ >>> reader.get_object(reader.root_object["/PageLabels"]["/Nums"][3])
21
+ {'/S': '/D'}
22
+
23
+ Example 2
24
+ ---------
25
+ The following is a document with pages labeled
26
+ i, ii, iii, iv, 1, 2, 3, A-8, A-9, ...
27
+
28
+ 1 0 obj
29
+ << /Type /Catalog
30
+ /PageLabels << /Nums [
31
+ 0 << /S /r >>
32
+ 4 << /S /D >>
33
+ 7 << /S /D
34
+ /P ( A- )
35
+ /St 8
36
+ >>
37
+ % A number tree containing
38
+ % three page label dictionaries
39
+ ]
40
+ >>
41
+ ...
42
+ >>
43
+ endobj
44
+
45
+
46
+ §12.4.2 PDF Specification 1.7 and 2.0
47
+ =====================================
48
+
49
+ Entries in a page label dictionary
50
+ ----------------------------------
51
+ The /S key:
52
+ D Decimal Arabic numerals
53
+ R Uppercase Roman numerals
54
+ r Lowercase Roman numerals
55
+ A Uppercase letters (A to Z for the first 26 pages,
56
+ AA to ZZ for the next 26, and so on)
57
+ a Lowercase letters (a to z for the first 26 pages,
58
+ aa to zz for the next 26, and so on)
59
+ """
60
+
61
+ from collections.abc import Callable, Iterator
62
+ from typing import Optional, cast
63
+
64
+ from ._protocols import PdfCommonDocProtocol
65
+ from ._utils import logger_warning
66
+ from .generic import (
67
+ ArrayObject,
68
+ DictionaryObject,
69
+ NullObject,
70
+ NumberObject,
71
+ is_null_or_none,
72
+ )
73
+
74
+
75
+ def number2uppercase_roman_numeral(num: int) -> str:
76
+ roman = [
77
+ (1000, "M"),
78
+ (900, "CM"),
79
+ (500, "D"),
80
+ (400, "CD"),
81
+ (100, "C"),
82
+ (90, "XC"),
83
+ (50, "L"),
84
+ (40, "XL"),
85
+ (10, "X"),
86
+ (9, "IX"),
87
+ (5, "V"),
88
+ (4, "IV"),
89
+ (1, "I"),
90
+ ]
91
+
92
+ def roman_num(num: int) -> Iterator[str]:
93
+ for decimal, roman_repr in roman:
94
+ x, _ = divmod(num, decimal)
95
+ yield roman_repr * x
96
+ num -= decimal * x
97
+ if num <= 0:
98
+ break
99
+
100
+ return "".join(list(roman_num(num)))
101
+
102
+
103
+ def number2lowercase_roman_numeral(number: int) -> str:
104
+ return number2uppercase_roman_numeral(number).lower()
105
+
106
+
107
+ def number2uppercase_letter(number: int) -> str:
108
+ if number <= 0:
109
+ raise ValueError("Expecting a positive number")
110
+ alphabet = [chr(i) for i in range(ord("A"), ord("Z") + 1)]
111
+ rep = ""
112
+ while number > 0:
113
+ remainder = number % 26
114
+ if remainder == 0:
115
+ remainder = 26
116
+ rep = alphabet[remainder - 1] + rep
117
+ # update
118
+ number -= remainder
119
+ number = number // 26
120
+ return rep
121
+
122
+
123
+ def number2lowercase_letter(number: int) -> str:
124
+ return number2uppercase_letter(number).lower()
125
+
126
+
127
+ def get_label_from_nums(dictionary_object: DictionaryObject, index: int) -> str:
128
+ # [Nums] shall be an array of the form
129
+ # [ key_1 value_1 key_2 value_2 ... key_n value_n ]
130
+ # where each key_i is an integer and the corresponding
131
+ # value_i shall be the object associated with that key.
132
+ # The keys shall be sorted in numerical order,
133
+ # analogously to the arrangement of keys in a name tree
134
+ # as described in 7.9.6, "Name Trees."
135
+ nums = cast(ArrayObject, dictionary_object["/Nums"])
136
+ nums_length = len(nums)
137
+ i = 0
138
+ value = None
139
+ start_index = 0
140
+ while i < nums_length:
141
+ if i + 1 >= nums_length:
142
+ logger_warning(
143
+ "Ignoring last /Nums key without a value.", source=__name__
144
+ )
145
+ break
146
+ start_index = nums[i]
147
+ value = nums[i + 1].get_object()
148
+ if i + 2 == nums_length:
149
+ break
150
+ if nums[i + 2] > index:
151
+ break
152
+ i += 2
153
+ m: dict[Optional[str], Callable[[int], str]] = {
154
+ None: lambda _: "",
155
+ "/D": str,
156
+ "/R": number2uppercase_roman_numeral,
157
+ "/r": number2lowercase_roman_numeral,
158
+ "/A": number2uppercase_letter,
159
+ "/a": number2lowercase_letter,
160
+ }
161
+ # if /Nums array is not following the specification or if /Nums is empty
162
+ if not isinstance(value, dict):
163
+ return str(index + 1) # Fallback
164
+ start = value.get("/St", 1)
165
+ prefix = cast(str, value.get("/P", ""))
166
+ mapping_function = m.get(value.get("/S"))
167
+ if mapping_function is None:
168
+ # Unknown /S numbering style; fall back to the page position.
169
+ logger_warning(
170
+ "Ignoring unknown page label numbering style %(style)r in /Nums.",
171
+ source=__name__,
172
+ style=value.get("/S"),
173
+ )
174
+ return str(index + 1) # Fallback
175
+ try:
176
+ return prefix + mapping_function(index - start_index + start)
177
+ except (TypeError, ValueError):
178
+ # Malformed /St or /P value; fall back to the page position.
179
+ logger_warning(
180
+ "Ignoring malformed page label entry in /Nums (/St=%(start)r, /P=%(prefix)r).",
181
+ source=__name__,
182
+ start=start,
183
+ prefix=prefix,
184
+ )
185
+ return str(index + 1) # Fallback
186
+
187
+
188
+ def index2label(reader: PdfCommonDocProtocol, index: int) -> str:
189
+ """
190
+ See 7.9.7 "Number Trees".
191
+
192
+ Args:
193
+ reader: The PdfReader
194
+ index: The index of the page
195
+
196
+ Returns:
197
+ The label of the page, e.g. "iv" or "4".
198
+
199
+ """
200
+ root = cast(DictionaryObject, reader.root_object)
201
+ if "/PageLabels" not in root:
202
+ return str(index + 1) # Fallback
203
+ number_tree = cast(DictionaryObject, root["/PageLabels"].get_object())
204
+ if "/Nums" in number_tree:
205
+ return get_label_from_nums(number_tree, index)
206
+ if "/Kids" in number_tree and not isinstance(number_tree["/Kids"], NullObject):
207
+ # number_tree = {'/Kids': [IndirectObject(7333, 0, 140132998195856), ...]}
208
+ # Limit maximum depth.
209
+ level = 0
210
+ while level < 100:
211
+ kids = cast(list[DictionaryObject], number_tree["/Kids"])
212
+ for kid in kids:
213
+ # kid = {'/Limits': [0, 63], '/Nums': [0, {'/P': 'C1'}, ...]}
214
+ limits = kid.get("/Limits", NullObject()).get_object()
215
+ if not isinstance(limits, list) or len(limits) < 2:
216
+ # Skip kids whose /Limits range is missing or malformed.
217
+ logger_warning(
218
+ "Ignoring kid with missing or malformed /Limits in /PageLabels.",
219
+ source=__name__,
220
+ )
221
+ continue
222
+ if limits[0] <= index <= limits[1]:
223
+ if not is_null_or_none(kid.get("/Kids", None)):
224
+ # Recursive definition.
225
+ level += 1
226
+ if level == 100: # pragma: no cover
227
+ raise NotImplementedError(
228
+ "Too deep nesting is not supported."
229
+ )
230
+ number_tree = kid
231
+ # Exit the inner `for` loop and continue at the next level with the
232
+ # next iteration of the `while` loop.
233
+ break
234
+ return get_label_from_nums(kid, index)
235
+ else:
236
+ # When there are no kids, make sure to exit the `while` loop directly
237
+ # and continue with the fallback.
238
+ break
239
+
240
+ logger_warning("Could not reliably determine page label for %(index)d.", source=__name__, index=index)
241
+ return str(index + 1) # Fallback if neither /Nums nor /Kids is in the number_tree
242
+
243
+
244
+ def nums_insert(
245
+ key: NumberObject,
246
+ value: DictionaryObject,
247
+ nums: ArrayObject,
248
+ ) -> None:
249
+ """
250
+ Insert a key, value pair in a Nums array.
251
+
252
+ See 7.9.7 "Number Trees".
253
+
254
+ Args:
255
+ key: number key of the entry
256
+ value: value of the entry
257
+ nums: Nums array to modify
258
+
259
+ """
260
+ if len(nums) % 2 != 0:
261
+ raise ValueError("A nums like array must have an even number of elements")
262
+
263
+ i = len(nums)
264
+ while i != 0 and key <= nums[i - 2]:
265
+ i = i - 2
266
+
267
+ if i < len(nums) and key == nums[i]:
268
+ nums[i + 1] = value
269
+ else:
270
+ nums.insert(i, key)
271
+ nums.insert(i + 1, value)
272
+
273
+
274
+ def nums_clear_range(
275
+ key: NumberObject,
276
+ page_index_to: int,
277
+ nums: ArrayObject,
278
+ ) -> None:
279
+ """
280
+ Remove all entries in a number tree in a range after an entry.
281
+
282
+ See 7.9.7 "Number Trees".
283
+
284
+ Args:
285
+ key: number key of the entry before the range
286
+ page_index_to: The page index of the upper limit of the range
287
+ nums: Nums array to modify
288
+
289
+ """
290
+ if len(nums) % 2 != 0:
291
+ raise ValueError("A nums like array must have an even number of elements")
292
+ if page_index_to < key:
293
+ raise ValueError("page_index_to must be greater or equal than key")
294
+
295
+ i = nums.index(key) + 2
296
+ while i < len(nums) and nums[i] <= page_index_to:
297
+ nums.pop(i)
298
+ nums.pop(i)
299
+
300
+
301
+ def nums_next(
302
+ key: NumberObject,
303
+ nums: ArrayObject,
304
+ ) -> tuple[Optional[NumberObject], Optional[DictionaryObject]]:
305
+ """
306
+ Return the (key, value) pair of the entry after the given one.
307
+
308
+ See 7.9.7 "Number Trees".
309
+
310
+ Args:
311
+ key: number key of the entry
312
+ nums: Nums array
313
+
314
+ """
315
+ if len(nums) % 2 != 0:
316
+ raise ValueError("A nums like array must have an even number of elements")
317
+
318
+ i = nums.index(key) + 2
319
+ if i < len(nums):
320
+ return (nums[i], nums[i + 1])
321
+ return (None, None)
.venv/lib/python3.13/site-packages/pypdf/_protocols.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Helpers for working with PDF types."""
2
+
3
+ from abc import abstractmethod
4
+ from pathlib import Path
5
+ from typing import IO, Any, Optional, Protocol, Union
6
+
7
+ from ._utils import StrByteType, StreamType
8
+
9
+
10
+ class PdfObjectProtocol(Protocol):
11
+ indirect_reference: Any
12
+
13
+ def clone(
14
+ self,
15
+ pdf_dest: Any,
16
+ force_duplicate: bool = False,
17
+ ignore_fields: Union[tuple[str, ...], list[str], None] = (),
18
+ ) -> Any:
19
+ ... # pragma: no cover
20
+
21
+ def _reference_clone(self, clone: Any, pdf_dest: Any) -> Any:
22
+ ... # pragma: no cover
23
+
24
+ def get_object(self) -> Optional["PdfObjectProtocol"]:
25
+ ... # pragma: no cover
26
+
27
+ def hash_value(self) -> bytes:
28
+ ... # pragma: no cover
29
+
30
+ def write_to_stream(
31
+ self, stream: StreamType, encryption_key: Union[str, bytes, None] = None
32
+ ) -> None:
33
+ ... # pragma: no cover
34
+
35
+
36
+ class XmpInformationProtocol(PdfObjectProtocol):
37
+ pass
38
+
39
+
40
+ class PdfCommonDocProtocol(Protocol):
41
+ @property
42
+ def pdf_header(self) -> str:
43
+ ... # pragma: no cover
44
+
45
+ @property
46
+ def pages(self) -> list[Any]:
47
+ ... # pragma: no cover
48
+
49
+ @property
50
+ def root_object(self) -> PdfObjectProtocol:
51
+ ... # pragma: no cover
52
+
53
+ def get_object(self, indirect_reference: Any) -> Optional[PdfObjectProtocol]:
54
+ ... # pragma: no cover
55
+
56
+ @property
57
+ def strict(self) -> bool:
58
+ ... # pragma: no cover
59
+
60
+
61
+ class PdfReaderProtocol(PdfCommonDocProtocol, Protocol):
62
+ @property
63
+ @abstractmethod
64
+ def xref(self) -> dict[int, dict[int, Any]]:
65
+ ... # pragma: no cover
66
+
67
+ @property
68
+ @abstractmethod
69
+ def trailer(self) -> dict[str, Any]:
70
+ ... # pragma: no cover
71
+
72
+
73
+ class PdfWriterProtocol(PdfCommonDocProtocol, Protocol):
74
+ _objects: list[Any]
75
+ _id_translated: dict[int, dict[int, int]]
76
+
77
+ incremental: bool
78
+ _reader: Any # PdfReader
79
+
80
+ @abstractmethod
81
+ def write(self, stream: Union[Path, StrByteType]) -> tuple[bool, IO[Any]]:
82
+ ... # pragma: no cover
83
+
84
+ @abstractmethod
85
+ def _add_object(self, obj: Any) -> Any:
86
+ ... # pragma: no cover
.venv/lib/python3.13/site-packages/pypdf/_reader.py ADDED
@@ -0,0 +1,1604 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2006, Mathieu Fenniak
2
+ # Copyright (c) 2007, Ashish Kulkarni <kulkarni.ashish@gmail.com>
3
+ #
4
+ # All rights reserved.
5
+ #
6
+ # Redistribution and use in source and binary forms, with or without
7
+ # modification, are permitted provided that the following conditions are
8
+ # met:
9
+ #
10
+ # * Redistributions of source code must retain the above copyright notice,
11
+ # this list of conditions and the following disclaimer.
12
+ # * Redistributions in binary form must reproduce the above copyright notice,
13
+ # this list of conditions and the following disclaimer in the documentation
14
+ # and/or other materials provided with the distribution.
15
+ # * The name of the author may not be used to endorse or promote products
16
+ # derived from this software without specific prior written permission.
17
+ #
18
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28
+ # POSSIBILITY OF SUCH DAMAGE.
29
+
30
+ import os
31
+ import re
32
+ import sys
33
+ from collections.abc import Iterable
34
+ from io import BytesIO, UnsupportedOperation
35
+ from pathlib import Path
36
+ from types import TracebackType
37
+ from typing import (
38
+ TYPE_CHECKING,
39
+ Any,
40
+ Callable,
41
+ Optional,
42
+ Union,
43
+ cast,
44
+ )
45
+
46
+ if sys.version_info >= (3, 11):
47
+ from typing import Self
48
+ else:
49
+ from typing_extensions import Self
50
+
51
+ from ._doc_common import PdfDocCommon, convert_to_int
52
+ from ._encryption import Encryption, PasswordType
53
+ from ._utils import (
54
+ WHITESPACES_AS_BYTES,
55
+ StrByteType,
56
+ StreamType,
57
+ logger_warning,
58
+ read_non_whitespace,
59
+ read_previous_line,
60
+ read_until_whitespace,
61
+ skip_over_comment,
62
+ skip_over_whitespace,
63
+ )
64
+ from .constants import TrailerKeys as TK
65
+ from .errors import (
66
+ EmptyFileError,
67
+ FileNotDecryptedError,
68
+ LimitReachedError,
69
+ PdfReadError,
70
+ PdfStreamError,
71
+ WrongPasswordError,
72
+ )
73
+ from .generic import (
74
+ ArrayObject,
75
+ ContentStream,
76
+ DecodedStreamObject,
77
+ Destination,
78
+ DictionaryObject,
79
+ EncodedStreamObject,
80
+ IndirectObject,
81
+ NameObject,
82
+ NullObject,
83
+ NumberObject,
84
+ PdfObject,
85
+ StreamObject,
86
+ TextStringObject,
87
+ TreeObject,
88
+ is_null_or_none,
89
+ read_object,
90
+ )
91
+ from .xmp import XmpInformation
92
+
93
+ if TYPE_CHECKING:
94
+ from ._page import PageObject
95
+
96
+
97
+ class PdfReader(PdfDocCommon):
98
+ """
99
+ Initialize a PdfReader object.
100
+
101
+ This operation can take some time, as the PDF stream's cross-reference
102
+ tables are read into memory.
103
+
104
+ Args:
105
+ stream: A File object or an object that supports the standard read
106
+ and seek methods similar to a File object. Could also be a
107
+ string representing a path to a PDF file.
108
+ strict: Determines whether user should be warned of all
109
+ problems and also causes some correctable problems to be fatal.
110
+ Defaults to ``False``.
111
+ password: Decrypt PDF file at initialization. If the
112
+ password is None, the file will not be decrypted.
113
+ Defaults to ``None``.
114
+ root_object_recovery_limit: The maximum number of objects to query
115
+ for recovering the Root object in non-strict mode. To disable
116
+ this security measure, pass ``None``.
117
+
118
+ """
119
+
120
+ def __init__(
121
+ self,
122
+ stream: Union[StrByteType, Path],
123
+ strict: bool = False,
124
+ password: Union[str, bytes, None] = None,
125
+ *,
126
+ root_object_recovery_limit: Optional[int] = 10_000,
127
+ ) -> None:
128
+ self.strict = strict
129
+ self.flattened_pages: Optional[list[PageObject]] = None
130
+
131
+ #: Storage of parsed PDF objects.
132
+ self.resolved_objects: dict[tuple[Any, Any], Optional[PdfObject]] = {}
133
+
134
+ self._startxref: int = 0
135
+ self.xref_index = 0
136
+ self.xref: dict[int, dict[Any, Any]] = {}
137
+ self.xref_free_entry: dict[int, dict[Any, Any]] = {}
138
+ self.xref_objStm: dict[int, tuple[Any, Any]] = {}
139
+ self.trailer = DictionaryObject()
140
+
141
+ # Security parameters.
142
+ self._root_object_recovery_limit = (
143
+ root_object_recovery_limit if isinstance(root_object_recovery_limit, int) else sys.maxsize
144
+ )
145
+
146
+ # Map page indirect_reference number to page number
147
+ self._page_id2num: Optional[dict[Any, Any]] = None
148
+
149
+ self._validated_root: Optional[DictionaryObject] = None
150
+
151
+ self._initialize_stream(stream)
152
+ self._known_objects: set[tuple[int, int]] = set()
153
+
154
+ self._override_encryption = False
155
+ self._encryption: Optional[Encryption] = None
156
+ if self.is_encrypted:
157
+ self._handle_encryption(password)
158
+ elif password is not None:
159
+ raise PdfReadError("Not an encrypted file")
160
+
161
+ self._named_destinations_cache: Optional[dict[str, Destination]] = None
162
+
163
+ def _initialize_stream(self, stream: Union[StrByteType, Path]) -> None:
164
+ if hasattr(stream, "mode") and "b" not in stream.mode:
165
+ logger_warning(
166
+ "PdfReader stream/file object is not in binary mode. "
167
+ "It may not be read correctly.",
168
+ source=__name__,
169
+ )
170
+ self._stream_opened = False
171
+ if isinstance(stream, (str, Path)):
172
+ with open(stream, "rb") as fh:
173
+ stream = BytesIO(fh.read())
174
+ self._stream_opened = True
175
+ self.read(stream)
176
+ self.stream = stream
177
+
178
+ def _handle_encryption(self, password: Optional[Union[str, bytes]]) -> None:
179
+ self._override_encryption = True
180
+ # Some documents may not have a /ID, use two empty
181
+ # byte strings instead. Solves
182
+ # https://github.com/py-pdf/pypdf/issues/608
183
+ id_entry = self.trailer.get(TK.ID)
184
+ id1_entry = id_entry[0].get_object().original_bytes if id_entry else b""
185
+ encrypt_entry = cast(DictionaryObject, self.trailer[TK.ENCRYPT].get_object())
186
+ self._encryption = Encryption.read(encrypt_entry, id1_entry)
187
+
188
+ # try empty password if no password provided
189
+ pwd = password if password is not None else b""
190
+ if (
191
+ self._encryption.verify(pwd, strict=self.strict) == PasswordType.NOT_DECRYPTED
192
+ and password is not None
193
+ ):
194
+ # raise if password provided
195
+ raise WrongPasswordError("Wrong password")
196
+ self._override_encryption = False
197
+
198
+ def __enter__(self) -> Self:
199
+ return self
200
+
201
+ def __exit__(
202
+ self,
203
+ exc_type: Optional[type[BaseException]],
204
+ exc_val: Optional[BaseException],
205
+ exc_tb: Optional[TracebackType],
206
+ ) -> None:
207
+ self.close()
208
+
209
+ def close(self) -> None:
210
+ """Close the stream if opened in __init__ and clear memory."""
211
+ if self._stream_opened:
212
+ self.stream.close()
213
+ self.flattened_pages = []
214
+ self.resolved_objects = {}
215
+ self.trailer = DictionaryObject()
216
+ self.xref = {}
217
+ self.xref_free_entry = {}
218
+ self.xref_objStm = {}
219
+
220
+ @property
221
+ def root_object(self) -> DictionaryObject:
222
+ """Provide access to "/Root". Standardized with PdfWriter."""
223
+ if self._validated_root:
224
+ return self._validated_root
225
+ root = self.trailer.get(TK.ROOT)
226
+ if is_null_or_none(root):
227
+ logger_warning('Cannot find "/Root" key in trailer', source=__name__)
228
+ elif (
229
+ cast(DictionaryObject, cast(PdfObject, root).get_object()).get("/Type")
230
+ == "/Catalog"
231
+ ):
232
+ self._validated_root = cast(
233
+ DictionaryObject, cast(PdfObject, root).get_object()
234
+ )
235
+ else:
236
+ logger_warning("Invalid Root object in trailer", source=__name__)
237
+ if self._validated_root is None:
238
+ logger_warning('Searching object with "/Catalog" key', source=__name__)
239
+ number_of_objects = cast(int, self.trailer.get("/Size", 0))
240
+ for i in range(number_of_objects):
241
+ if i >= self._root_object_recovery_limit:
242
+ raise LimitReachedError("Maximum Root object recovery limit reached.")
243
+ try:
244
+ obj = self.get_object(i + 1)
245
+ except Exception: # to be sure to capture all errors
246
+ obj = None
247
+ if isinstance(obj, DictionaryObject) and obj.get("/Type") == "/Catalog":
248
+ self._validated_root = obj
249
+ logger_warning(
250
+ "Root found at %(obj_reference)r",
251
+ source=__name__,
252
+ obj_reference=obj.indirect_reference,
253
+ )
254
+ break
255
+ if self._validated_root is None:
256
+ if not is_null_or_none(root) and "/Pages" in cast(DictionaryObject, cast(PdfObject, root).get_object()):
257
+ logger_warning(
258
+ "Possible root found at %(root_ref)r, but missing /Catalog key",
259
+ source=__name__,
260
+ root_ref=cast(PdfObject, root).indirect_reference,
261
+ )
262
+ self._validated_root = cast(
263
+ DictionaryObject, cast(PdfObject, root).get_object()
264
+ )
265
+ else:
266
+ raise PdfReadError("Cannot find Root object in pdf")
267
+ return self._validated_root
268
+
269
+ @property
270
+ def _info(self) -> Optional[DictionaryObject]:
271
+ """
272
+ Provide access to "/Info". Standardized with PdfWriter.
273
+
274
+ Returns:
275
+ /Info Dictionary; None if the entry does not exist
276
+
277
+ """
278
+ info = self.trailer.get(TK.INFO, None)
279
+ if is_null_or_none(info):
280
+ return None
281
+ assert info is not None, "mypy"
282
+ info = info.get_object()
283
+ if not isinstance(info, DictionaryObject):
284
+ raise PdfReadError(
285
+ "Trailer not found or does not point to a document information dictionary"
286
+ )
287
+ return info
288
+
289
+ @property
290
+ def _ID(self) -> Optional[ArrayObject]:
291
+ """
292
+ Provide access to "/ID". Standardized with PdfWriter.
293
+
294
+ Returns:
295
+ /ID array; None if the entry does not exist
296
+
297
+ """
298
+ id = self.trailer.get(TK.ID, None)
299
+ if is_null_or_none(id):
300
+ return None
301
+ assert id is not None, "mypy"
302
+ return cast(ArrayObject, id.get_object())
303
+
304
+ @property
305
+ def pdf_header(self) -> str:
306
+ """
307
+ The first 8 bytes of the file.
308
+
309
+ This is typically something like ``'%PDF-1.6'`` and can be used to
310
+ detect if the file is actually a PDF file and which version it is.
311
+ """
312
+ # TODO: Make this return a bytes object for consistency
313
+ # but that needs a deprecation
314
+ loc = self.stream.tell()
315
+ self.stream.seek(0, 0)
316
+ pdf_file_version = self.stream.read(8).decode("utf-8", "backslashreplace")
317
+ self.stream.seek(loc, 0) # return to where it was
318
+ return pdf_file_version
319
+
320
+ @property
321
+ def xmp_metadata(self) -> Optional[XmpInformation]:
322
+ """XMP (Extensible Metadata Platform) data."""
323
+ try:
324
+ self._override_encryption = True
325
+ return cast(XmpInformation, self.root_object.xmp_metadata)
326
+ finally:
327
+ self._override_encryption = False
328
+
329
+ def _get_page_number_by_indirect(
330
+ self, indirect_reference: Union[int, NullObject, IndirectObject, None]
331
+ ) -> Optional[int]:
332
+ """
333
+ Retrieve the page number from an indirect reference.
334
+
335
+ Args:
336
+ indirect_reference: The indirect reference to locate.
337
+
338
+ Returns:
339
+ Page number or None.
340
+
341
+ """
342
+ if self._page_id2num is None:
343
+ self._page_id2num = {
344
+ x.indirect_reference.idnum: i for i, x in enumerate(self.pages) # type: ignore[union-attr]
345
+ }
346
+
347
+ if is_null_or_none(indirect_reference):
348
+ return None
349
+ assert isinstance(indirect_reference, (int, IndirectObject)), "mypy"
350
+ if isinstance(indirect_reference, int):
351
+ idnum = indirect_reference
352
+ else:
353
+ idnum = indirect_reference.idnum
354
+ assert self._page_id2num is not None, "hint for mypy"
355
+ return self._page_id2num.get(idnum, None)
356
+
357
+ def _get_object_from_stream(
358
+ self, indirect_reference: IndirectObject
359
+ ) -> Union[int, PdfObject, str]:
360
+ # indirect reference to object in object stream
361
+ # read the entire object stream into memory
362
+ stmnum, _idx = self.xref_objStm[indirect_reference.idnum]
363
+ obj_stm: EncodedStreamObject = IndirectObject(stmnum, 0, self).get_object() # type: ignore[assignment]
364
+ # This is an xref to a stream, so its type better be a stream
365
+ assert cast(str, obj_stm["/Type"]) == "/ObjStm"
366
+ # Parse ALL objects in this stream in one pass and cache them.
367
+ # This avoids O(N²) behavior when many objects from the same stream
368
+ # are resolved individually (each call would re-parse the header).
369
+ stream_data = BytesIO(obj_stm.get_data())
370
+ n = int(obj_stm["/N"]) # type: ignore[call-overload]
371
+ first_offset = int(obj_stm["/First"]) # type: ignore[call-overload]
372
+
373
+ # ObjStm header format: "objnum offset objnum offset ..."
374
+ # smallest possible entry: "0 0" = 3 bytes (1 digit + 1 space + 1 digit)
375
+ # using // 4 would reject a valid 3-byte single entry (3 // 4 = 0)
376
+ max_n = stream_data.getbuffer().nbytes // 3
377
+ stream_data.seek(0)
378
+ if n > max_n:
379
+ if self.strict:
380
+ raise LimitReachedError(f"Value /N {n} for object {stmnum} exceeds maximum allowed value {max_n}.")
381
+ logger_warning(
382
+ "Value /N %(n)d for object %(stmnum)d exceeds maximum allowed value %(max_n)d. Limiting to %(max_n)d.",
383
+ source=__name__,
384
+ n=n,
385
+ stmnum=stmnum,
386
+ max_n=max_n,
387
+ )
388
+ n = max_n
389
+
390
+ # Phase 1: Read the index (objnum, offset) pairs from the header.
391
+ obj_index: list[tuple[int, int]] = []
392
+ for _i in range(n):
393
+ read_non_whitespace(stream_data)
394
+ stream_data.seek(-1, 1)
395
+ objnum = NumberObject.read_from_stream(stream_data)
396
+ read_non_whitespace(stream_data)
397
+ stream_data.seek(-1, 1)
398
+ offset = NumberObject.read_from_stream(stream_data)
399
+ read_non_whitespace(stream_data)
400
+ stream_data.seek(-1, 1)
401
+ obj_index.append((int(objnum), int(offset)))
402
+
403
+ # Phase 2: Parse each object and cache it.
404
+ target_obj: Union[int, PdfObject, str] = NullObject()
405
+ found = False
406
+ for i, (obj_num, obj_offset) in enumerate(obj_index):
407
+ # Skip objects already in the cache.
408
+ cached = self.cache_get_indirect_object(0, obj_num)
409
+ if cached is not None:
410
+ if obj_num == indirect_reference.idnum:
411
+ target_obj = cached
412
+ found = True
413
+ continue
414
+
415
+ stream_data.seek(first_offset + obj_offset, 0)
416
+
417
+ # To cope with case where the 'pointer' is on a white space
418
+ read_non_whitespace(stream_data)
419
+ stream_data.seek(-1, 1)
420
+
421
+ try:
422
+ obj = read_object(stream_data, self)
423
+ except PdfStreamError as exc:
424
+ # Stream object cannot be read. Normally, a critical error, but
425
+ # Adobe Reader doesn't complain, so continue (in strict mode?)
426
+ logger_warning(
427
+ "Invalid stream (index %(index)d) within object %(obj_num)d 0: %(exc)s",
428
+ source=__name__,
429
+ index=i,
430
+ obj_num=obj_num,
431
+ exc=exc,
432
+ )
433
+ if self.strict: # pragma: no cover
434
+ raise PdfReadError(
435
+ f"Cannot read object stream: {exc}"
436
+ ) # pragma: no cover
437
+ obj = NullObject() # pragma: no cover
438
+
439
+ # Only cache if this stream is the authoritative source for the object.
440
+ # Incremental updates may override objects originally in the stream;
441
+ # caching those stale versions would shadow the newer xref entry.
442
+ authoritative_stm, _idx = self.xref_objStm.get(obj_num, (None, None))
443
+ if authoritative_stm == stmnum:
444
+ self.cache_indirect_object(0, obj_num, obj) # type: ignore[arg-type]
445
+
446
+ if obj_num == indirect_reference.idnum:
447
+ target_obj = obj
448
+ found = True
449
+
450
+ if not found and self.strict: # pragma: no cover
451
+ raise PdfReadError(
452
+ "This is a fatal error in strict mode."
453
+ ) # pragma: no cover
454
+ return target_obj
455
+
456
+ def get_object(
457
+ self, indirect_reference: Union[int, IndirectObject]
458
+ ) -> Optional[PdfObject]:
459
+ if isinstance(indirect_reference, int):
460
+ indirect_reference = IndirectObject(indirect_reference, 0, self)
461
+ retval = self.cache_get_indirect_object(
462
+ indirect_reference.generation, indirect_reference.idnum
463
+ )
464
+ if retval is not None:
465
+ return retval
466
+ if (
467
+ indirect_reference.generation == 0
468
+ and indirect_reference.idnum in self.xref_objStm
469
+ ):
470
+ retval = self._get_object_from_stream(indirect_reference) # type: ignore
471
+ elif (
472
+ indirect_reference.generation in self.xref
473
+ and indirect_reference.idnum in self.xref[indirect_reference.generation]
474
+ ):
475
+ if self.xref_free_entry.get(indirect_reference.generation, {}).get(
476
+ indirect_reference.idnum, False
477
+ ):
478
+ return NullObject()
479
+ start = self.xref[indirect_reference.generation][indirect_reference.idnum]
480
+ self.stream.seek(start, 0)
481
+ try:
482
+ idnum, generation = self.read_object_header(self.stream)
483
+ if (
484
+ idnum != indirect_reference.idnum
485
+ or generation != indirect_reference.generation
486
+ ):
487
+ raise PdfReadError("Not matching, we parse the file for it")
488
+ except Exception:
489
+ if hasattr(self.stream, "getbuffer"):
490
+ buf = bytes(self.stream.getbuffer())
491
+ else:
492
+ p = self.stream.tell()
493
+ self.stream.seek(0, 0)
494
+ buf = self.stream.read(-1)
495
+ self.stream.seek(p, 0)
496
+ m = re.search(
497
+ rf"\s{indirect_reference.idnum}\s+{indirect_reference.generation}\s+obj".encode(),
498
+ buf,
499
+ )
500
+ if m is not None:
501
+ logger_warning(
502
+ "Object ID %(idnum)d,%(generation)d ref repaired",
503
+ source=__name__,
504
+ idnum=indirect_reference.idnum,
505
+ generation=indirect_reference.generation,
506
+ )
507
+ self.xref[indirect_reference.generation][
508
+ indirect_reference.idnum
509
+ ] = (m.start(0) + 1)
510
+ self.stream.seek(m.start(0) + 1)
511
+ idnum, generation = self.read_object_header(self.stream)
512
+ else:
513
+ idnum = -1
514
+ generation = -1 # exception will be raised below
515
+ if idnum != indirect_reference.idnum and self.xref_index:
516
+ # xref table probably had bad indexes due to not being zero-indexed
517
+ if self.strict:
518
+ raise PdfReadError(
519
+ f"Expected object ID ({indirect_reference.idnum} {indirect_reference.generation}) "
520
+ f"does not match actual ({idnum} {generation}); "
521
+ "xref table not zero-indexed."
522
+ )
523
+ # xref table is corrected in non-strict mode
524
+ elif idnum != indirect_reference.idnum and self.strict:
525
+ # some other problem
526
+ raise PdfReadError(
527
+ f"Expected object ID ({indirect_reference.idnum} {indirect_reference.generation}) "
528
+ f"does not match actual ({idnum} {generation})."
529
+ )
530
+ if self.strict:
531
+ assert generation == indirect_reference.generation
532
+
533
+ current_object = (indirect_reference.idnum, indirect_reference.generation)
534
+ if current_object in self._known_objects:
535
+ raise LimitReachedError(f"Detected loop with self reference for {indirect_reference!r}.")
536
+ self._known_objects.add(current_object)
537
+ retval = read_object(self.stream, self) # type: ignore[assignment]
538
+ self._known_objects.remove(current_object)
539
+
540
+ # override encryption is used for the /Encrypt dictionary
541
+ if not self._override_encryption and self._encryption is not None:
542
+ # if we don't have the encryption key:
543
+ if not self._encryption.is_decrypted():
544
+ raise FileNotDecryptedError("File has not been decrypted")
545
+ # otherwise, decrypt here...
546
+ retval = cast(PdfObject, retval)
547
+ retval = self._encryption.decrypt_object(
548
+ retval, indirect_reference.idnum, indirect_reference.generation,
549
+ strict=self.strict,
550
+ )
551
+ else:
552
+ if hasattr(self.stream, "getbuffer"):
553
+ buf = bytes(self.stream.getbuffer())
554
+ else:
555
+ p = self.stream.tell()
556
+ self.stream.seek(0, 0)
557
+ buf = self.stream.read(-1)
558
+ self.stream.seek(p, 0)
559
+ m = re.search(
560
+ rf"\s{indirect_reference.idnum}\s+{indirect_reference.generation}\s+obj".encode(),
561
+ buf,
562
+ )
563
+ if m is not None:
564
+ logger_warning(
565
+ "Object %(idnum)d %(generation)d found",
566
+ source=__name__,
567
+ idnum=indirect_reference.idnum,
568
+ generation=indirect_reference.generation,
569
+ )
570
+ if indirect_reference.generation not in self.xref:
571
+ self.xref[indirect_reference.generation] = {}
572
+ self.xref[indirect_reference.generation][indirect_reference.idnum] = (
573
+ m.start(0) + 1
574
+ )
575
+ self.stream.seek(m.end(0) + 1)
576
+ skip_over_whitespace(self.stream)
577
+ self.stream.seek(-1, 1)
578
+ retval = read_object(self.stream, self) # type: ignore[assignment]
579
+
580
+ # override encryption is used for the /Encrypt dictionary
581
+ if not self._override_encryption and self._encryption is not None:
582
+ # if we don't have the encryption key:
583
+ if not self._encryption.is_decrypted():
584
+ raise FileNotDecryptedError("File has not been decrypted")
585
+ # otherwise, decrypt here...
586
+ retval = cast(PdfObject, retval)
587
+ retval = self._encryption.decrypt_object(
588
+ retval, indirect_reference.idnum, indirect_reference.generation,
589
+ strict=self.strict,
590
+ )
591
+ else:
592
+ logger_warning(
593
+ "Object %(idnum)d %(generation)d not defined.",
594
+ source=__name__,
595
+ idnum=indirect_reference.idnum,
596
+ generation=indirect_reference.generation,
597
+ )
598
+ if self.strict:
599
+ raise PdfReadError("Could not find object.")
600
+ # For ObjStm objects, _get_object_from_stream already cached
601
+ # the result during batch parsing; skip the redundant cache write
602
+ # to avoid "Overwriting cache" warnings. For non-ObjStm objects
603
+ # (including encrypted ones that need decrypted values cached),
604
+ # always write.
605
+ if not (
606
+ indirect_reference.generation == 0
607
+ and indirect_reference.idnum in self.xref_objStm
608
+ ):
609
+ self.cache_indirect_object(
610
+ indirect_reference.generation, indirect_reference.idnum, retval
611
+ )
612
+ return retval
613
+
614
+ def read_object_header(self, stream: StreamType) -> tuple[int, int]:
615
+ # Should never be necessary to read out whitespace, since the
616
+ # cross-reference table should put us in the right spot to read the
617
+ # object header. In reality some files have stupid cross-reference
618
+ # tables that are off by whitespace bytes.
619
+ skip_over_comment(stream)
620
+ extra = skip_over_whitespace(stream)
621
+ stream.seek(-1, 1)
622
+ idnum = read_until_whitespace(stream)
623
+ extra |= skip_over_whitespace(stream)
624
+ stream.seek(-1, 1)
625
+ generation = read_until_whitespace(stream)
626
+ extra |= skip_over_whitespace(stream)
627
+ stream.seek(-1, 1)
628
+
629
+ # although it's not used, it might still be necessary to read
630
+ _obj = stream.read(3)
631
+
632
+ read_non_whitespace(stream)
633
+ stream.seek(-1, 1)
634
+ if extra and self.strict:
635
+ logger_warning(
636
+ "Superfluous whitespace found in object header %(idnum)r %(generation)r",
637
+ source=__name__,
638
+ idnum=idnum,
639
+ generation=generation,
640
+ )
641
+ return int(idnum), int(generation)
642
+
643
+ def cache_get_indirect_object(
644
+ self, generation: int, idnum: int
645
+ ) -> Optional[PdfObject]:
646
+ try:
647
+ return self.resolved_objects.get((generation, idnum))
648
+ except RecursionError:
649
+ raise PdfReadError("Maximum recursion depth reached.")
650
+
651
+ def cache_indirect_object(
652
+ self, generation: int, idnum: int, obj: Optional[PdfObject]
653
+ ) -> Optional[PdfObject]:
654
+ if (generation, idnum) in self.resolved_objects:
655
+ msg = "Overwriting cache for %(generation)d %(idnum)d"
656
+ values = {"generation": generation, "idnum": idnum}
657
+ if self.strict:
658
+ raise PdfReadError(msg % values)
659
+ logger_warning(msg, source=__name__, **values)
660
+ self.resolved_objects[(generation, idnum)] = obj
661
+ if obj is not None:
662
+ obj.indirect_reference = IndirectObject(idnum, generation, self)
663
+ return obj
664
+
665
+ def _replace_object(self, indirect_reference: IndirectObject, obj: PdfObject) -> PdfObject:
666
+ # function reserved for future development
667
+ if indirect_reference.pdf != self:
668
+ raise ValueError("Cannot update PdfReader with external object")
669
+ if (indirect_reference.generation, indirect_reference.idnum) not in self.resolved_objects:
670
+ raise ValueError("Cannot find referenced object")
671
+ self.resolved_objects[(indirect_reference.generation, indirect_reference.idnum)] = obj
672
+ obj.indirect_reference = indirect_reference
673
+ return obj
674
+
675
+ def read(self, stream: StreamType) -> None:
676
+ """
677
+ Read and process the PDF stream, extracting necessary data.
678
+
679
+ Args:
680
+ stream: The PDF file stream.
681
+
682
+ """
683
+ self._basic_validation(stream)
684
+ self._find_eof_marker(stream)
685
+ startxref = self._find_startxref_pos(stream)
686
+ self._startxref = startxref
687
+
688
+ # check and eventually correct the startxref only if not strict
689
+ xref_issue_nr = self._get_xref_issues(stream, startxref)
690
+ if xref_issue_nr != 0:
691
+ if self.strict and xref_issue_nr:
692
+ raise PdfReadError("Broken xref table")
693
+ logger_warning(
694
+ "incorrect startxref pointer(%(xref_issue_nr)d)",
695
+ source=__name__,
696
+ xref_issue_nr=xref_issue_nr,
697
+ )
698
+
699
+ # read all cross-reference tables and their trailers
700
+ self._read_xref_tables_and_trailers(stream, startxref, xref_issue_nr)
701
+
702
+ # if not zero-indexed, verify that the table is correct; change it if necessary
703
+ if self.xref_index and not self.strict:
704
+ loc = stream.tell()
705
+ for gen, xref_entry in self.xref.items():
706
+ if gen == 65535:
707
+ continue
708
+ xref_k = sorted(
709
+ xref_entry.keys()
710
+ ) # ensure ascending to prevent damage
711
+ for id in xref_k:
712
+ stream.seek(xref_entry[id], 0)
713
+ try:
714
+ pid, _pgen = self.read_object_header(stream)
715
+ except ValueError:
716
+ self._rebuild_xref_table(stream)
717
+ break
718
+ if pid == id - self.xref_index:
719
+ # fixing index item per item is required for revised PDF.
720
+ self.xref[gen][pid] = self.xref[gen][id]
721
+ del self.xref[gen][id]
722
+ # if not, then either it's just plain wrong, or the
723
+ # non-zero-index is actually correct
724
+ stream.seek(loc, 0) # return to where it was
725
+
726
+ # remove wrong objects (not pointing to correct structures) - cf #2326
727
+ if not self.strict:
728
+ loc = stream.tell()
729
+ for gen, xref_entry in self.xref.items():
730
+ if gen == 65535:
731
+ continue
732
+ ids = list(xref_entry.keys())
733
+ for id in ids:
734
+ stream.seek(xref_entry[id], 0)
735
+ try:
736
+ self.read_object_header(stream)
737
+ except ValueError:
738
+ logger_warning(
739
+ "Ignoring wrong pointing object %(id)d %(gen)d (offset %(offset)d)",
740
+ source=__name__,
741
+ id=id,
742
+ gen=gen,
743
+ offset=xref_entry[id],
744
+ )
745
+ del xref_entry[id] # we can delete the id, we are parsing ids
746
+ stream.seek(loc, 0) # return to where it was
747
+
748
+ def _basic_validation(self, stream: StreamType) -> None:
749
+ """Ensure the stream is valid and not empty."""
750
+ stream.seek(0, os.SEEK_SET)
751
+ try:
752
+ header_byte = stream.read(5)
753
+ except UnicodeDecodeError:
754
+ raise UnsupportedOperation("cannot read header")
755
+ if header_byte == b"":
756
+ raise EmptyFileError("Cannot read an empty file")
757
+ if header_byte != b"%PDF-":
758
+ if self.strict:
759
+ raise PdfReadError(
760
+ f"PDF starts with '{header_byte.decode('utf8')}', "
761
+ "but '%PDF-' expected"
762
+ )
763
+ logger_warning("invalid pdf header: %(header_byte)r", source=__name__, header_byte=header_byte)
764
+ stream.seek(0, os.SEEK_END)
765
+
766
+ def _find_eof_marker(self, stream: StreamType) -> None:
767
+ """
768
+ Jump to the %%EOF marker.
769
+
770
+ According to the specs, the %%EOF marker should be at the very end of
771
+ the file. Hence for standard-compliant PDF documents this function will
772
+ read only the last part (DEFAULT_BUFFER_SIZE).
773
+ """
774
+ HEADER_SIZE = 8 # to parse whole file, Header is e.g. '%PDF-1.6'
775
+ line = b""
776
+ first = True
777
+ while not line.startswith(b"%%EOF"):
778
+ if line != b"" and first:
779
+ if any(
780
+ line.strip().endswith(tr) for tr in (b"%%EO", b"%%E", b"%%", b"%")
781
+ ):
782
+ # Consider the file as truncated while
783
+ # having enough confidence to carry on.
784
+ logger_warning("EOF marker seems truncated", source=__name__)
785
+ break
786
+ first = False
787
+ if b"startxref" in line:
788
+ logger_warning(
789
+ "CAUTION: startxref found while searching for %%EOF. "
790
+ "The file might be truncated and some data might not be read.",
791
+ source=__name__,
792
+ )
793
+ if stream.tell() < HEADER_SIZE:
794
+ if self.strict:
795
+ raise PdfReadError("EOF marker not found")
796
+ logger_warning("EOF marker not found", source=__name__)
797
+ line = read_previous_line(stream)
798
+
799
+ def _find_startxref_pos(self, stream: StreamType) -> int:
800
+ """
801
+ Find startxref entry - the location of the xref table.
802
+
803
+ Args:
804
+ stream:
805
+
806
+ Returns:
807
+ The bytes offset
808
+
809
+ """
810
+ line = read_previous_line(stream)
811
+ try:
812
+ startxref = int(line)
813
+ except ValueError:
814
+ # 'startxref' may be on the same line as the location
815
+ if not line.startswith(b"startxref"):
816
+ raise PdfReadError("startxref not found")
817
+ startxref = int(line[9:].strip())
818
+ logger_warning("startxref on same line as offset", source=__name__)
819
+ else:
820
+ line = read_previous_line(stream)
821
+ if not line.startswith(b"startxref"):
822
+ # The 'startxref' keyword expected just above the offset is
823
+ # missing or corrupt (for example a truncated 'tartxref').
824
+ # Some producers append a broken trailing cross-reference
825
+ # pointer while an earlier, intact 'startxref' from a previous
826
+ # revision is still present. Recovering from this violates the
827
+ # standard, so only attempt it in non-strict mode (#3238).
828
+ if self.strict:
829
+ raise PdfReadError("startxref not found")
830
+ startxref = self._find_previous_startxref_pos(stream)
831
+ return startxref
832
+
833
+ # Upper bound on the number of lines _find_previous_startxref_pos scans
834
+ # backwards while recovering a corrupt trailing startxref pointer. Kept
835
+ # fixed and non-configurable so a crafted file cannot trigger an unbounded
836
+ # backwards scan.
837
+ _MAX_STARTXREF_RECOVERY_LINES = 1000
838
+
839
+ @classmethod
840
+ def _find_previous_startxref_pos(cls, stream: StreamType) -> int:
841
+ """
842
+ Recover the most recent intact ``startxref`` pointer by scanning
843
+ backwards from the current position.
844
+
845
+ This is used as a fallback when the ``startxref`` keyword belonging to
846
+ the final ``%%EOF`` is corrupt (#3238). The offset always appears on
847
+ the line directly below the keyword, so the value read immediately
848
+ before encountering ``startxref`` (while moving backwards) is returned.
849
+ At most ``_MAX_STARTXREF_RECOVERY_LINES`` lines are inspected.
850
+
851
+ Args:
852
+ stream: The PDF byte stream, positioned just above the corrupt
853
+ trailing pointer.
854
+
855
+ Returns:
856
+ The bytes offset of the recovered ``startxref``.
857
+
858
+ """
859
+ offset: Optional[int] = None
860
+ for _ in range(cls._MAX_STARTXREF_RECOVERY_LINES):
861
+ if stream.tell() <= 0:
862
+ break
863
+ line = read_previous_line(stream)
864
+ if not line.startswith(b"startxref"):
865
+ try:
866
+ offset = int(line)
867
+ except ValueError:
868
+ offset = None
869
+ continue
870
+ if len(line) > 9:
871
+ # 'startxref' on the same line as the offset
872
+ return int(line[9:].strip())
873
+ if offset is not None:
874
+ logger_warning(
875
+ "found startxref pointing to a previous revision after "
876
+ "a corrupt one",
877
+ source=__name__,
878
+ )
879
+ return offset
880
+ break
881
+ raise PdfReadError("startxref not found")
882
+
883
+ def _load_recovery_cache(self, data: bytes) -> dict[int, tuple[int, int]]:
884
+ cache = {}
885
+ for object_number, generation_number, object_start in self._find_pdf_objects(data):
886
+ if object_number in cache:
887
+ # Always use the first match.
888
+ continue
889
+ cache[object_number] = (object_start, generation_number)
890
+ return cache
891
+
892
+ def _read_standard_xref_table(self, stream: StreamType) -> None:
893
+ # standard cross-reference table
894
+ ref = stream.read(3)
895
+ if ref != b"ref":
896
+ raise PdfReadError("xref table read error")
897
+ read_non_whitespace(stream)
898
+ stream.seek(-1, 1)
899
+ first_time = True # check if the first time looking at the xref table
900
+ recovery_cache: Optional[dict[int, tuple[int, int]]] = None
901
+ while True:
902
+ num = cast(int, read_object(stream, self))
903
+ if first_time and num != 0:
904
+ self.xref_index = num
905
+ if self.strict:
906
+ logger_warning(
907
+ "Xref table not zero-indexed. ID numbers for objects will be corrected.",
908
+ source=__name__,
909
+ )
910
+ # if table not zero indexed, could be due to error from when PDF was created
911
+ # which will lead to mismatched indices later on, only warned and corrected if self.strict==True
912
+ first_time = False
913
+ read_non_whitespace(stream)
914
+ stream.seek(-1, 1)
915
+ size = cast(int, read_object(stream, self))
916
+ if not isinstance(size, int):
917
+ logger_warning(
918
+ "Invalid/Truncated xref table. Rebuilding it.",
919
+ source=__name__,
920
+ )
921
+ self._rebuild_xref_table(stream)
922
+ stream.read()
923
+ return
924
+ read_non_whitespace(stream)
925
+ stream.seek(-1, 1)
926
+ cnt = 0
927
+ while cnt < size:
928
+ line = stream.read(20)
929
+ if not line:
930
+ raise PdfReadError("Unexpected empty line in Xref table.")
931
+
932
+ # It's very clear in section 3.4.3 of the PDF spec
933
+ # that all cross-reference table lines are a fixed
934
+ # 20 bytes (as of PDF 1.7). However, some files have
935
+ # 21-byte entries (or more) due to the use of \r\n
936
+ # (CRLF) EOL's. Detect that case, and adjust the line
937
+ # until it does not begin with a \r (CR) or \n (LF).
938
+ while line[0] in b"\x0D\x0A":
939
+ stream.seek(-20 + 1, 1)
940
+ line = stream.read(20)
941
+
942
+ # On the other hand, some malformed PDF files
943
+ # use a single character EOL without a preceding
944
+ # space. Detect that case, and seek the stream
945
+ # back one character (0-9 means we've bled into
946
+ # the next xref entry, t means we've bled into the
947
+ # text "trailer"):
948
+ if line[-1] in b"0123456789t":
949
+ stream.seek(-1, 1)
950
+
951
+ try:
952
+ offset_b, generation_b = line[:16].split(b" ")
953
+ entry_type_b = line[17:18]
954
+
955
+ offset, generation = int(offset_b), int(generation_b)
956
+ except Exception:
957
+ if hasattr(stream, "getbuffer"):
958
+ buf = bytes(stream.getbuffer())
959
+ else:
960
+ p = stream.tell()
961
+ stream.seek(0, 0)
962
+ buf = stream.read(-1)
963
+ stream.seek(p)
964
+
965
+ if recovery_cache is None:
966
+ recovery_cache = self._load_recovery_cache(buf)
967
+
968
+ if num not in recovery_cache:
969
+ logger_warning(
970
+ "entry %(num)d in Xref table invalid; object not found",
971
+ source=__name__,
972
+ num=num,
973
+ )
974
+ generation = 65535
975
+ offset = -1
976
+ entry_type_b = b"f"
977
+ else:
978
+ logger_warning(
979
+ "entry %(num)d in Xref table invalid but object found",
980
+ source=__name__,
981
+ num=num,
982
+ )
983
+ generation, offset = recovery_cache[num]
984
+ entry_type_b = b"n"
985
+
986
+ if generation not in self.xref:
987
+ self.xref[generation] = {}
988
+ self.xref_free_entry[generation] = {}
989
+ if num in self.xref[generation]:
990
+ # It really seems like we should allow the last
991
+ # xref table in the file to override previous
992
+ # ones. Since we read the file backwards, assume
993
+ # any existing key is already set correctly.
994
+ pass
995
+ else:
996
+ if entry_type_b == b"n":
997
+ self.xref[generation][num] = offset
998
+ try:
999
+ self.xref_free_entry[generation][num] = entry_type_b == b"f"
1000
+ except Exception:
1001
+ pass
1002
+ try:
1003
+ self.xref_free_entry[65535][num] = entry_type_b == b"f"
1004
+ except Exception:
1005
+ pass
1006
+ cnt += 1
1007
+ num += 1
1008
+ read_non_whitespace(stream)
1009
+ stream.seek(-1, 1)
1010
+ # Skip any PDF comments between xref entries and the trailer
1011
+ # keyword. Some PDF producers (e.g. Vectorizer.AI) insert
1012
+ # comments here which are legal per the PDF spec (§7.2.3).
1013
+ while stream.read(1) == b"%":
1014
+ stream.seek(-1, 1)
1015
+ skip_over_comment(stream)
1016
+ read_non_whitespace(stream)
1017
+ stream.seek(-1, 1)
1018
+ stream.seek(-1, 1)
1019
+ trailer_tag = stream.read(7)
1020
+ if trailer_tag != b"trailer":
1021
+ # more xrefs!
1022
+ stream.seek(-7, 1)
1023
+ else:
1024
+ break
1025
+
1026
+ def _read_xref_tables_and_trailers(
1027
+ self, stream: StreamType, startxref: Optional[int], xref_issue_nr: int
1028
+ ) -> None:
1029
+ """Read the cross-reference tables and trailers in the PDF stream."""
1030
+ self.xref = {}
1031
+ self.xref_free_entry = {}
1032
+ self.xref_objStm = {}
1033
+ self.trailer = DictionaryObject()
1034
+ visited_xref_offsets: set[int] = set()
1035
+ while startxref is not None:
1036
+ # Detect circular /Prev references in the xref chain
1037
+ if startxref in visited_xref_offsets:
1038
+ logger_warning(
1039
+ "Circular xref chain detected at offset %(startxref)d, stopping",
1040
+ source=__name__,
1041
+ startxref=startxref,
1042
+ )
1043
+ break
1044
+ visited_xref_offsets.add(startxref)
1045
+ # load the xref table
1046
+ stream.seek(startxref, 0)
1047
+ x = stream.read(1)
1048
+ if x in b"\r\n":
1049
+ x = stream.read(1)
1050
+ if x == b"x":
1051
+ startxref = self._read_xref(stream)
1052
+ elif xref_issue_nr:
1053
+ try:
1054
+ self._rebuild_xref_table(stream)
1055
+ break
1056
+ except Exception:
1057
+ xref_issue_nr = 0
1058
+ elif x.isdigit():
1059
+ try:
1060
+ xrefstream = self._read_pdf15_xref_stream(stream)
1061
+ except Exception as e:
1062
+ if TK.ROOT in self.trailer:
1063
+ logger_warning(
1064
+ "Previous trailer cannot be read: %(args)s",
1065
+ source=__name__,
1066
+ args=e.args,
1067
+ )
1068
+ break
1069
+ raise PdfReadError(f"Trailer cannot be read: {e!s}")
1070
+ self._process_xref_stream(xrefstream)
1071
+ if "/Prev" in xrefstream:
1072
+ startxref = cast(int, xrefstream["/Prev"])
1073
+ else:
1074
+ break
1075
+ else:
1076
+ startxref = self._read_xref_other_error(stream, startxref)
1077
+
1078
+ def _process_xref_stream(self, xrefstream: DictionaryObject) -> None:
1079
+ """Process and handle the xref stream."""
1080
+ trailer_keys = TK.ROOT, TK.ENCRYPT, TK.INFO, TK.ID, TK.SIZE
1081
+ for key in trailer_keys:
1082
+ if key in xrefstream and key not in self.trailer:
1083
+ self.trailer[NameObject(key)] = xrefstream.raw_get(key)
1084
+ if "/XRefStm" in xrefstream:
1085
+ p = self.stream.tell()
1086
+ self.stream.seek(cast(int, xrefstream["/XRefStm"]) + 1, 0)
1087
+ self._read_pdf15_xref_stream(self.stream)
1088
+ self.stream.seek(p, 0)
1089
+
1090
+ def _read_xref(self, stream: StreamType) -> Optional[int]:
1091
+ self._read_standard_xref_table(stream)
1092
+ if stream.read(1) == b"":
1093
+ return None
1094
+ stream.seek(-1, 1)
1095
+ read_non_whitespace(stream)
1096
+ stream.seek(-1, 1)
1097
+ new_trailer = cast(dict[str, Any], read_object(stream, self))
1098
+ for key, value in new_trailer.items():
1099
+ if key not in self.trailer:
1100
+ self.trailer[key] = value
1101
+ if "/XRefStm" in new_trailer:
1102
+ p = stream.tell()
1103
+ stream.seek(cast(int, new_trailer["/XRefStm"]) + 1, 0)
1104
+ try:
1105
+ self._read_pdf15_xref_stream(stream)
1106
+ except Exception:
1107
+ logger_warning(
1108
+ "XRef object at %(xref_stm)d can not be read, some object may be missing",
1109
+ source=__name__,
1110
+ xref_stm=int(new_trailer["/XRefStm"]),
1111
+ )
1112
+ stream.seek(p, 0)
1113
+ if "/Prev" in new_trailer:
1114
+ return cast(int, new_trailer["/Prev"])
1115
+ return None
1116
+
1117
+ def _read_xref_other_error(
1118
+ self, stream: StreamType, startxref: int
1119
+ ) -> Optional[int]:
1120
+ # some PDFs have /Prev=0 in the trailer, instead of no /Prev
1121
+ if startxref == 0:
1122
+ if self.strict:
1123
+ raise PdfReadError(
1124
+ "/Prev=0 in the trailer (try opening with strict=False)"
1125
+ )
1126
+ logger_warning(
1127
+ "/Prev=0 in the trailer - assuming there is no previous xref table",
1128
+ source=__name__,
1129
+ )
1130
+ return None
1131
+ # bad xref character at startxref. Let's see if we can find
1132
+ # the xref table nearby, as we've observed this error with an
1133
+ # off-by-one before.
1134
+ stream.seek(-11, 1)
1135
+ tmp = stream.read(20)
1136
+ xref_loc = tmp.find(b"xref")
1137
+ if xref_loc != -1:
1138
+ startxref -= 10 - xref_loc
1139
+ return startxref
1140
+ # No explicit xref table, try finding a cross-reference stream.
1141
+ stream.seek(startxref, 0)
1142
+ for look in range(25): # value extended to cope with more linearized files
1143
+ if stream.read(1).isdigit():
1144
+ # This is not a standard PDF, consider adding a warning
1145
+ startxref += look
1146
+ return startxref
1147
+ # no xref table found at specified location
1148
+ if "/Root" in self.trailer and not self.strict:
1149
+ # if Root has been already found, just raise warning
1150
+ logger_warning("Invalid parent xref., rebuild xref", source=__name__)
1151
+ try:
1152
+ self._rebuild_xref_table(stream)
1153
+ return None
1154
+ except Exception:
1155
+ raise PdfReadError("Cannot rebuild xref")
1156
+ raise PdfReadError("Could not find xref table at specified location")
1157
+
1158
+ def _sanitize_pdf15_xref_stream_index_pairs(
1159
+ self, index_pairs: list[int], entry_sizes: list[int], xref_stream: ContentStream
1160
+ ) -> list[int]:
1161
+ # `entry_sizes` holds the byte widths for the entries. Summing determines the total number of bytes per entry.
1162
+ # We expect up to 3 values. `min_entry_bytes` will be the smallest plausible size of one xref entry.
1163
+ min_entry_bytes = sum(int(entry_sizes[i]) for i in range(min(len(entry_sizes), 3)))
1164
+ if min_entry_bytes == 0:
1165
+ message = "Cross-reference stream encodes no entry data."
1166
+ if self.strict:
1167
+ raise PdfStreamError(message)
1168
+ logger_warning(message, source=__name__)
1169
+ return []
1170
+
1171
+ # maximum number of entries that could physically fit
1172
+ max_entries = len(xref_stream.get_data()) // min_entry_bytes + 1
1173
+
1174
+ result = []
1175
+ total = 0
1176
+
1177
+ for index, pair_value in enumerate(index_pairs):
1178
+ pair_value_int = int(pair_value)
1179
+
1180
+ # `index_pairs` has the format `[start0, count0, start1, count1, ...]`
1181
+ # Only modify the counts here, but keep the start values.
1182
+ if index % 2 == 1:
1183
+ if total + pair_value_int > max_entries:
1184
+ if self.strict:
1185
+ raise LimitReachedError(
1186
+ f"Total XRef entries {total + pair_value_int} exceed maximum allowed value {max_entries}."
1187
+ )
1188
+ new_v = max(0, max_entries - total)
1189
+ logger_warning(
1190
+ "Clamping XRef count from %(old_count)d to %(new_count)d to fit stream size.",
1191
+ source=__name__,
1192
+ old_count=pair_value_int,
1193
+ new_count=new_v,
1194
+ )
1195
+ pair_value_int = new_v
1196
+
1197
+ total += pair_value_int
1198
+
1199
+ result.append(pair_value_int)
1200
+
1201
+ return result
1202
+
1203
+ def _read_pdf15_xref_stream(
1204
+ self, stream: StreamType
1205
+ ) -> Union[ContentStream, EncodedStreamObject, DecodedStreamObject]:
1206
+ """Read the cross-reference stream for PDF 1.5+."""
1207
+ stream.seek(-1, 1)
1208
+ stream_idnum, stream_generation = self.read_object_header(stream)
1209
+ xref_stream = cast(ContentStream, read_object(stream, self))
1210
+ if cast(str, xref_stream["/Type"]) != "/XRef":
1211
+ raise PdfReadError(f"Unexpected type {xref_stream['/Type']!r}")
1212
+ self.cache_indirect_object(stream_generation, stream_idnum, xref_stream)
1213
+
1214
+ # Index pairs specify the subsections in the dictionary.
1215
+ # If none, create one subsection that spans everything.
1216
+ if "/Size" not in xref_stream:
1217
+ # According to table 17 of the PDF 2.0 specification, this key is required.
1218
+ raise PdfReadError(f"Size missing from XRef stream {xref_stream!r}!")
1219
+ index_pairs = xref_stream.get("/Index", [0, xref_stream["/Size"]])
1220
+
1221
+ entry_sizes = cast(list[int], xref_stream.get("/W"))
1222
+ assert len(entry_sizes) >= 3
1223
+ if self.strict and len(entry_sizes) > 3:
1224
+ raise PdfReadError(f"Too many entry sizes: {entry_sizes}")
1225
+ index_pairs = self._sanitize_pdf15_xref_stream_index_pairs(
1226
+ index_pairs=index_pairs, entry_sizes=entry_sizes, xref_stream=xref_stream
1227
+ )
1228
+
1229
+ stream_data = BytesIO(xref_stream.get_data())
1230
+
1231
+ def get_entry(i: int) -> Union[int, tuple[int, ...]]:
1232
+ # Reads the correct number of bytes for each entry. See the
1233
+ # discussion of the W parameter in PDF spec table 17.
1234
+ if entry_sizes[i] > 0:
1235
+ d = stream_data.read(entry_sizes[i])
1236
+ return convert_to_int(d, entry_sizes[i])
1237
+
1238
+ # PDF Spec Table 17: A value of zero for an element in the
1239
+ # W array indicates...the default value shall be used
1240
+ if i == 0:
1241
+ return 1 # First value defaults to 1
1242
+ return 0
1243
+
1244
+ def used_before(num: int, generation: Union[int, tuple[int, ...]]) -> bool:
1245
+ # We move backwards through the xrefs, don't replace any.
1246
+ return num in self.xref.get(generation, []) or num in self.xref_objStm # type: ignore[arg-type]
1247
+
1248
+ # Iterate through each subsection
1249
+ self._read_xref_subsections(index_pairs, get_entry, used_before)
1250
+ return xref_stream
1251
+
1252
+ @staticmethod
1253
+ def _get_xref_issues(stream: StreamType, startxref: int) -> int:
1254
+ """
1255
+ Return an int which indicates an issue. 0 means there is no issue.
1256
+
1257
+ Args:
1258
+ stream:
1259
+ startxref:
1260
+
1261
+ Returns:
1262
+ 0 means no issue, other values represent specific issues.
1263
+
1264
+ """
1265
+ if startxref == 0:
1266
+ return 4
1267
+
1268
+ stream.seek(startxref - 1, 0) # -1 to check character before
1269
+ line = stream.read(1)
1270
+ if line == b"j":
1271
+ line = stream.read(1)
1272
+ if line not in b"\r\n \t":
1273
+ return 1
1274
+ line = stream.read(4)
1275
+ if line != b"xref":
1276
+ # not a xref so check if it is an XREF object
1277
+ line = b""
1278
+ while line in b"0123456789 \t":
1279
+ line = stream.read(1)
1280
+ if line == b"":
1281
+ return 2
1282
+ line += stream.read(2) # 1 char already read, +2 to check "obj"
1283
+ if line.lower() != b"obj":
1284
+ return 3
1285
+ return 0
1286
+
1287
+ @classmethod
1288
+ def _find_pdf_objects(cls, data: bytes) -> Iterable[tuple[int, int, int]]:
1289
+ index = 0
1290
+ ord_0 = ord("0")
1291
+ ord_9 = ord("9")
1292
+ while True:
1293
+ index = data.find(b" obj", index)
1294
+ if index == -1:
1295
+ return
1296
+
1297
+ index_before_space = index - 1
1298
+
1299
+ # Skip whitespace backwards
1300
+ while index_before_space >= 0 and data[index_before_space] in WHITESPACES_AS_BYTES:
1301
+ index_before_space -= 1
1302
+
1303
+ # Read generation number
1304
+ generation_end = index_before_space + 1
1305
+ while index_before_space >= 0 and ord_0 <= data[index_before_space] <= ord_9:
1306
+ index_before_space -= 1
1307
+ generation_start = index_before_space + 1
1308
+
1309
+ # Skip whitespace
1310
+ while index_before_space >= 0 and data[index_before_space] in WHITESPACES_AS_BYTES:
1311
+ index_before_space -= 1
1312
+
1313
+ # Read object number
1314
+ object_end = index_before_space + 1
1315
+ while index_before_space >= 0 and ord_0 <= data[index_before_space] <= ord_9:
1316
+ index_before_space -= 1
1317
+ object_start = index_before_space + 1
1318
+
1319
+ # Validate
1320
+ if object_start < object_end and generation_start < generation_end:
1321
+ object_number = int(data[object_start:object_end])
1322
+ generation_number = int(data[generation_start:generation_end])
1323
+
1324
+ yield object_number, generation_number, object_start
1325
+
1326
+ index += 4 # len(b" obj")
1327
+
1328
+ @classmethod
1329
+ def _find_pdf_trailers(cls, data: bytes) -> Iterable[int]:
1330
+ index = 0
1331
+ data_length = len(data)
1332
+ while True:
1333
+ index = data.find(b"trailer", index)
1334
+ if index == -1:
1335
+ return
1336
+
1337
+ index_after_trailer = index + 7 # len(b"trailer")
1338
+
1339
+ # Skip whitespace
1340
+ while index_after_trailer < data_length and data[index_after_trailer] in WHITESPACES_AS_BYTES:
1341
+ index_after_trailer += 1
1342
+
1343
+ # Must be dictionary start
1344
+ if index_after_trailer + 1 < data_length and data[index_after_trailer:index_after_trailer+2] == b"<<":
1345
+ yield index_after_trailer # offset of '<<'
1346
+
1347
+ index += 7 # len(b"trailer")
1348
+
1349
+ def _rebuild_xref_table(self, stream: StreamType) -> None:
1350
+ self.xref = {}
1351
+ stream.seek(0, 0)
1352
+ stream_data = stream.read(-1)
1353
+
1354
+ for object_number, generation_number, object_start in self._find_pdf_objects(stream_data):
1355
+ if generation_number not in self.xref:
1356
+ self.xref[generation_number] = {}
1357
+ self.xref[generation_number][object_number] = object_start
1358
+
1359
+ logger_warning("parsing for Object Streams", source=__name__)
1360
+ for generation_number in self.xref:
1361
+ for object_number in self.xref[generation_number]:
1362
+ # get_object in manual
1363
+ stream.seek(self.xref[generation_number][object_number], 0)
1364
+ try:
1365
+ _ = self.read_object_header(stream)
1366
+ obj = cast(StreamObject, read_object(stream, self))
1367
+ if obj.get("/Type", "") != "/ObjStm":
1368
+ continue
1369
+ object_stream = BytesIO(obj.get_data())
1370
+ actual_count = 0
1371
+ while True:
1372
+ current = read_until_whitespace(object_stream)
1373
+ if not current.isdigit():
1374
+ break
1375
+ inner_object_number = int(current)
1376
+ skip_over_whitespace(object_stream)
1377
+ object_stream.seek(-1, 1)
1378
+ current = read_until_whitespace(object_stream)
1379
+ if not current.isdigit(): # pragma: no cover
1380
+ break # pragma: no cover
1381
+ inner_generation_number = int(current)
1382
+ self.xref_objStm[inner_object_number] = (object_number, inner_generation_number)
1383
+ actual_count += 1
1384
+ expected_count = cast(int, obj["/N"])
1385
+ if actual_count != expected_count: # pragma: no cover
1386
+ logger_warning( # pragma: no cover
1387
+ (
1388
+ "found %(actual_count)d objects within "
1389
+ "Object(%(object_number)d,%(generation_number)d) "
1390
+ "whereas %(expected)d expected"
1391
+ ),
1392
+ source=__name__,
1393
+ actual_count=actual_count,
1394
+ object_number=object_number,
1395
+ generation_number=generation_number,
1396
+ expected=expected_count,
1397
+ )
1398
+ except Exception: # could be multiple causes
1399
+ pass
1400
+
1401
+ stream.seek(0, 0)
1402
+ for position in self._find_pdf_trailers(stream_data):
1403
+ stream.seek(position, 0)
1404
+ new_trailer = cast(dict[Any, Any], read_object(stream, self))
1405
+ # Here, we are parsing the file from start to end, the new data have to erase the existing.
1406
+ for key, value in new_trailer.items():
1407
+ self.trailer[key] = value
1408
+
1409
+ def _read_xref_subsections(
1410
+ self,
1411
+ idx_pairs: list[int],
1412
+ get_entry: Callable[[int], Union[int, tuple[int, ...]]],
1413
+ used_before: Callable[[int, Union[int, tuple[int, ...]]], bool],
1414
+ ) -> None:
1415
+ """Read and process the subsections of the xref."""
1416
+ for start, size in self._pairs(idx_pairs):
1417
+ # The subsections must increase
1418
+ for num in range(start, start + size):
1419
+ # The first entry is the type
1420
+ xref_type = get_entry(0)
1421
+ # The rest of the elements depend on the xref_type
1422
+ if xref_type == 0:
1423
+ # linked list of free objects
1424
+ next_free_object = get_entry(1) # noqa: F841
1425
+ next_generation = get_entry(2) # noqa: F841
1426
+ elif xref_type == 1:
1427
+ # objects that are in use but are not compressed
1428
+ byte_offset = get_entry(1)
1429
+ generation = get_entry(2)
1430
+ if generation not in self.xref:
1431
+ self.xref[generation] = {} # type: ignore[index]
1432
+ if not used_before(num, generation):
1433
+ self.xref[generation][num] = byte_offset # type: ignore[index]
1434
+ elif xref_type == 2:
1435
+ # compressed objects
1436
+ objstr_num = get_entry(1)
1437
+ obstr_idx = get_entry(2)
1438
+ generation = 0 # PDF spec table 18, generation is 0
1439
+ if not used_before(num, generation):
1440
+ self.xref_objStm[num] = (objstr_num, obstr_idx)
1441
+ elif self.strict:
1442
+ raise PdfReadError(f"Unknown xref type: {xref_type}")
1443
+
1444
+ def _pairs(self, array: list[int]) -> Iterable[tuple[int, int]]:
1445
+ """Iterate over pairs in the array."""
1446
+ i = 0
1447
+ while i + 1 < len(array):
1448
+ yield array[i], array[i + 1]
1449
+ i += 2
1450
+
1451
+ def decrypt(self, password: Union[str, bytes]) -> PasswordType:
1452
+ """
1453
+ When using an encrypted / secured PDF file with the PDF Standard
1454
+ encryption handler, this function will allow the file to be decrypted.
1455
+ It checks the given password against the document's user password and
1456
+ owner password, and then stores the resulting decryption key if either
1457
+ password is correct.
1458
+
1459
+ It does not matter which password was matched. Both passwords provide
1460
+ the correct decryption key that will allow the document to be used with
1461
+ this library.
1462
+
1463
+ Args:
1464
+ password: The password to match.
1465
+
1466
+ Returns:
1467
+ An indicator if the document was decrypted and whether it was the
1468
+ owner password or the user password.
1469
+
1470
+ """
1471
+ if not self._encryption:
1472
+ raise PdfReadError("Not encrypted file")
1473
+ # TODO: raise Exception for wrong password
1474
+ return self._encryption.verify(password, strict=self.strict)
1475
+
1476
+ @property
1477
+ def is_encrypted(self) -> bool:
1478
+ """
1479
+ Read-only boolean property showing whether this PDF file is encrypted.
1480
+
1481
+ Note that this property, if true, will remain true even after the
1482
+ :meth:`decrypt()<pypdf.PdfReader.decrypt>` method is called.
1483
+ """
1484
+ return TK.ENCRYPT in self.trailer
1485
+
1486
+ def add_form_topname(self, name: str) -> Optional[DictionaryObject]:
1487
+ """
1488
+ Add a top level form that groups all form fields below it.
1489
+
1490
+ Args:
1491
+ name: text string of the "/T" Attribute of the created object
1492
+
1493
+ Returns:
1494
+ The created object. ``None`` means no object was created.
1495
+
1496
+ """
1497
+ catalog = self.root_object
1498
+
1499
+ if "/AcroForm" not in catalog or not isinstance(
1500
+ catalog["/AcroForm"], DictionaryObject
1501
+ ):
1502
+ return None
1503
+ acroform = cast(DictionaryObject, catalog[NameObject("/AcroForm")])
1504
+ if "/Fields" not in acroform:
1505
+ # TODO: No error but this may be extended for XFA Forms
1506
+ return None
1507
+
1508
+ interim = DictionaryObject()
1509
+ interim[NameObject("/T")] = TextStringObject(name)
1510
+ interim[NameObject("/Kids")] = acroform[NameObject("/Fields")]
1511
+ self.cache_indirect_object(
1512
+ 0,
1513
+ max(i for (g, i) in self.resolved_objects if g == 0) + 1,
1514
+ interim,
1515
+ )
1516
+ arr = ArrayObject()
1517
+ arr.append(interim.indirect_reference)
1518
+ acroform[NameObject("/Fields")] = arr
1519
+ for o in cast(ArrayObject, interim["/Kids"]):
1520
+ obj = o.get_object()
1521
+ if "/Parent" in obj:
1522
+ logger_warning(
1523
+ "Top Level Form Field %(obj_ref)s has a non-expected parent",
1524
+ source=__name__,
1525
+ obj_ref=obj.indirect_reference,
1526
+ )
1527
+ obj[NameObject("/Parent")] = interim.indirect_reference
1528
+ return interim
1529
+
1530
+ def rename_form_topname(self, name: str) -> Optional[DictionaryObject]:
1531
+ """
1532
+ Rename top level form field that all form fields below it.
1533
+
1534
+ Args:
1535
+ name: text string of the "/T" field of the created object
1536
+
1537
+ Returns:
1538
+ The modified object. ``None`` means no object was modified.
1539
+
1540
+ """
1541
+ catalog = self.root_object
1542
+
1543
+ if "/AcroForm" not in catalog or not isinstance(
1544
+ catalog["/AcroForm"], DictionaryObject
1545
+ ):
1546
+ return None
1547
+ acroform = cast(DictionaryObject, catalog[NameObject("/AcroForm")])
1548
+ if "/Fields" not in acroform:
1549
+ return None
1550
+
1551
+ interim = cast(
1552
+ DictionaryObject,
1553
+ cast(ArrayObject, acroform[NameObject("/Fields")])[0].get_object(),
1554
+ )
1555
+ interim[NameObject("/T")] = TextStringObject(name)
1556
+ return interim
1557
+
1558
+ def _repr_mimebundle_(
1559
+ self,
1560
+ include: Union[Iterable[str], None] = None,
1561
+ exclude: Union[Iterable[str], None] = None,
1562
+ ) -> dict[str, Any]:
1563
+ """
1564
+ Integration into Jupyter Notebooks.
1565
+
1566
+ This method returns a dictionary that maps a mime-type to its
1567
+ representation.
1568
+
1569
+ .. seealso::
1570
+
1571
+ https://ipython.readthedocs.io/en/stable/config/integrating.html
1572
+ """
1573
+ self.stream.seek(0)
1574
+ pdf_data = self.stream.read()
1575
+ data = {
1576
+ "application/pdf": pdf_data,
1577
+ }
1578
+
1579
+ if include is not None:
1580
+ # Filter representations based on include list
1581
+ data = {k: v for k, v in data.items() if k in include}
1582
+
1583
+ if exclude is not None:
1584
+ # Remove representations based on exclude list
1585
+ data = {k: v for k, v in data.items() if k not in exclude}
1586
+
1587
+ return data
1588
+
1589
+ def _get_named_destinations(
1590
+ self,
1591
+ *,
1592
+ tree: Union[TreeObject, None] = None,
1593
+ retval: Optional[dict[str, Destination]] = None,
1594
+ visited: Optional[set[int]] = None,
1595
+ ) -> dict[str, Destination]:
1596
+ """Override from PdfDocCommon. In the reader we can assume this is
1597
+ static, but not in the writer.
1598
+ """
1599
+ if tree or retval:
1600
+ return super()._get_named_destinations(tree=tree, retval=retval, visited=visited)
1601
+
1602
+ if self._named_destinations_cache is None:
1603
+ self._named_destinations_cache = super()._get_named_destinations()
1604
+ return self._named_destinations_cache
.venv/lib/python3.13/site-packages/pypdf/_text_extraction/__init__.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Code related to text extraction.
3
+
4
+ Some parts are still in _page.py. In doubt, they will stay there.
5
+ """
6
+
7
+ import math
8
+ from typing import Any, Callable, Optional, Union
9
+
10
+ from .._font import Font
11
+ from .._utils import is_char_neutral, is_char_rtl
12
+ from ..generic import DictionaryObject, TextStringObject, encode_pdfdocencoding
13
+
14
+ CUSTOM_RTL_MIN: str = ""
15
+ CUSTOM_RTL_MAX: str = ""
16
+ CUSTOM_RTL_SPECIAL_CHARS: str = ""
17
+ LAYOUT_NEW_BT_GROUP_SPACE_WIDTHS: int = 5
18
+ UNICODE_LOWER_LIMIT = 0
19
+ UNICODE_UPPER_LIMIT = 0x10FFFF
20
+
21
+
22
+ class OrientationNotFoundError(Exception):
23
+ pass
24
+
25
+
26
+ def set_custom_rtl(
27
+ _min: Union[str, int, None] = "",
28
+ _max: Union[str, int, None] = "",
29
+ specials: Union[str, list[int], None] = None,
30
+ ) -> tuple[str, str, str]:
31
+ """
32
+ Change the Right-To-Left and special characters custom parameters.
33
+
34
+ Args:
35
+ _min: The new minimum value for the range of custom characters that
36
+ will be written right to left.
37
+ If set to ``None``, the value will not be changed.
38
+ If set to a valid integer, it will be converted to its corresponding character.
39
+ The default value is "", which sets no additional range to be converted.
40
+ _max: The new maximum value for the range of custom characters that will
41
+ be written right to left.
42
+ If set to ``None``, the value will not be changed.
43
+ If set to a valid integer, it will be converted to its corresponding character.
44
+ The default value is "", which sets no additional range to be converted.
45
+ specials: The new list of special characters to be inserted in the
46
+ current insertion order.
47
+ If set to ``None``, the current value will not be changed.
48
+ If set to a string, it will be converted to a list of ASCII codes.
49
+ The default value is an empty list.
50
+
51
+ Returns:
52
+ A tuple containing the new values for ``CUSTOM_RTL_MIN``,
53
+ ``CUSTOM_RTL_MAX``, and ``CUSTOM_RTL_SPECIAL_CHARS``.
54
+
55
+ """
56
+ global CUSTOM_RTL_MIN, CUSTOM_RTL_MAX, CUSTOM_RTL_SPECIAL_CHARS
57
+ if isinstance(_min, int):
58
+ CUSTOM_RTL_MIN = chr(_min) if UNICODE_LOWER_LIMIT <= _min <= UNICODE_UPPER_LIMIT else ""
59
+ elif isinstance(_min, str):
60
+ CUSTOM_RTL_MIN = _min
61
+ if isinstance(_max, int):
62
+ CUSTOM_RTL_MAX = chr(_max) if UNICODE_LOWER_LIMIT <= _max <= UNICODE_UPPER_LIMIT else ""
63
+ elif isinstance(_max, str):
64
+ CUSTOM_RTL_MAX = _max
65
+ if isinstance(specials, str):
66
+ CUSTOM_RTL_SPECIAL_CHARS = specials
67
+ elif isinstance(specials, list):
68
+ CUSTOM_RTL_SPECIAL_CHARS = "".join(
69
+ chr(char) for char in specials if UNICODE_LOWER_LIMIT <= char <= UNICODE_UPPER_LIMIT
70
+ )
71
+ return CUSTOM_RTL_MIN, CUSTOM_RTL_MAX, CUSTOM_RTL_SPECIAL_CHARS
72
+
73
+
74
+ def mult(m: list[float], n: list[float]) -> list[float]:
75
+ return [
76
+ m[0] * n[0] + m[1] * n[2],
77
+ m[0] * n[1] + m[1] * n[3],
78
+ m[2] * n[0] + m[3] * n[2],
79
+ m[2] * n[1] + m[3] * n[3],
80
+ m[4] * n[0] + m[5] * n[2] + n[4],
81
+ m[4] * n[1] + m[5] * n[3] + n[5],
82
+ ]
83
+
84
+
85
+ def orient(m: list[float]) -> int:
86
+ if m[3] > 1e-6:
87
+ return 0
88
+ if m[3] < -1e-6:
89
+ return 180
90
+ if m[1] > 0:
91
+ return 90
92
+ return 270
93
+
94
+
95
+ def crlf_space_check(
96
+ text: str,
97
+ cmtm_prev: tuple[list[float], list[float]],
98
+ cmtm_matrix: tuple[list[float], list[float]],
99
+ memo_cmtm: tuple[list[float], list[float]],
100
+ font_resource: Optional[DictionaryObject],
101
+ orientations: tuple[int, ...],
102
+ output: str,
103
+ font_size: float,
104
+ visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]],
105
+ str_widths: float,
106
+ spacewidth: float,
107
+ str_height: float,
108
+ ) -> tuple[str, str, list[float], list[float]]:
109
+ cm_prev = cmtm_prev[0]
110
+ tm_prev = cmtm_prev[1]
111
+ cm_matrix = cmtm_matrix[0]
112
+ tm_matrix = cmtm_matrix[1]
113
+ memo_cm = memo_cmtm[0]
114
+ memo_tm = memo_cmtm[1]
115
+
116
+ m_prev = mult(tm_prev, cm_prev)
117
+ m = mult(tm_matrix, cm_matrix)
118
+ orientation = orient(m)
119
+ delta_x = m[4] - m_prev[4]
120
+ delta_y = m[5] - m_prev[5]
121
+ # Table 108 of the 1.7 reference ("Text positioning operators")
122
+ scale_prev_x = math.sqrt(tm_prev[0]**2 + tm_prev[1]**2)
123
+ scale_prev_y = math.sqrt(tm_prev[2]**2 + tm_prev[3]**2)
124
+ scale_y = math.sqrt(tm_matrix[2]**2 + tm_matrix[3]**2)
125
+ cm_prev = m
126
+
127
+ if orientation not in orientations:
128
+ raise OrientationNotFoundError
129
+ if orientation in (0, 180):
130
+ moved_height: float = delta_y
131
+ moved_width: float = delta_x
132
+ elif orientation in (90, 270):
133
+ moved_height = delta_x
134
+ moved_width = delta_y
135
+ try:
136
+ if abs(moved_height) > 0.8 * min(str_height * scale_prev_y, font_size * scale_y):
137
+ if (output + text)[-1] != "\n":
138
+ output += text + "\n"
139
+ if visitor_text is not None:
140
+ visitor_text(
141
+ text + "\n",
142
+ memo_cm,
143
+ memo_tm,
144
+ font_resource,
145
+ font_size,
146
+ )
147
+ text = ""
148
+ elif (
149
+ (moved_width >= (spacewidth + str_widths) * scale_prev_x)
150
+ and (output + text)[-1] != " "
151
+ ):
152
+ text += " "
153
+ except Exception:
154
+ pass
155
+ tm_prev = tm_matrix.copy()
156
+ cm_prev = cm_matrix.copy()
157
+ return text, output, cm_prev, tm_prev
158
+
159
+
160
+ def get_text_operands(
161
+ operands: list[Union[str, TextStringObject]],
162
+ cm_matrix: list[float],
163
+ tm_matrix: list[float],
164
+ font: Font,
165
+ orientations: tuple[int, ...]
166
+ ) -> tuple[str, bool]:
167
+ t: str = ""
168
+ is_str_operands = False
169
+ m = mult(tm_matrix, cm_matrix)
170
+ orientation = orient(m)
171
+ if orientation in orientations and len(operands) > 0:
172
+ if isinstance(operands[0], str):
173
+ t = operands[0]
174
+ is_str_operands = True
175
+ else:
176
+ t = ""
177
+ tt: bytes = (
178
+ encode_pdfdocencoding(operands[0])
179
+ if isinstance(operands[0], str)
180
+ else operands[0]
181
+ )
182
+ if isinstance(font.encoding, str):
183
+ try:
184
+ t = tt.decode(font.encoding, "surrogatepass") # apply str encoding
185
+ except Exception:
186
+ # the data does not match the expectation,
187
+ # we use the alternative ;
188
+ # text extraction may not be good
189
+ t = tt.decode(
190
+ "utf-16-be" if font.encoding == "charmap" else "charmap",
191
+ "surrogatepass",
192
+ ) # apply str encoding
193
+ else: # apply dict encoding
194
+ t = "".join(
195
+ [font.encoding[x] if x in font.encoding else bytes((x,)).decode() for x in tt]
196
+ )
197
+ return (t, is_str_operands)
198
+
199
+
200
+ def get_display_str(
201
+ text: str,
202
+ cm_matrix: list[float],
203
+ tm_matrix: list[float],
204
+ font_resource: Optional[DictionaryObject],
205
+ font: Font,
206
+ text_operands: str,
207
+ font_size: float,
208
+ rtl_dir: bool,
209
+ visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]]
210
+ ) -> tuple[str, bool, float]:
211
+ # "\u0590 - \u08FF \uFB50 - \uFDFF"
212
+ widths: float = 0.0
213
+ for raw_character in text_operands:
214
+ widths += font.space_width if raw_character == font.space_char else font.get_text_width(raw_character)
215
+ x = font.character_map.get(raw_character, raw_character)
216
+ # Test whether x is a sequence of bytes; ex: habibi.pdf
217
+ if len(x) == 1:
218
+ if (
219
+ # Cases where the current inserting order is kept
220
+ is_char_neutral(x, CUSTOM_RTL_SPECIAL_CHARS)
221
+ ):
222
+ text = x + text if rtl_dir else text + x
223
+ elif (
224
+ # Right-to-left characters
225
+ is_char_rtl(x, CUSTOM_RTL_MIN, CUSTOM_RTL_MAX)
226
+ ):
227
+ if not rtl_dir:
228
+ rtl_dir = True
229
+ if visitor_text is not None:
230
+ visitor_text(text, cm_matrix, tm_matrix, font_resource, font_size)
231
+ text = ""
232
+ text = x + text
233
+ else:
234
+ # Left-to-right characters
235
+ if rtl_dir:
236
+ rtl_dir = False
237
+ if visitor_text is not None:
238
+ visitor_text(text, cm_matrix, tm_matrix, font_resource, font_size)
239
+ text = ""
240
+ text = text + x
241
+ else:
242
+ # Treat a sequence of bytes as a neutral character.
243
+ text = x + text if rtl_dir else text + x
244
+ return text, rtl_dir, widths
.venv/lib/python3.13/site-packages/pypdf/_text_extraction/_layout_mode/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Layout mode text extraction extension for pypdf"""
2
+ from ..._font import Font
3
+ from ._fixed_width_page import (
4
+ fixed_char_width,
5
+ fixed_width_page,
6
+ text_show_operations,
7
+ y_coordinate_groups,
8
+ )
9
+
10
+ __all__ = [
11
+ "Font",
12
+ "fixed_char_width",
13
+ "fixed_width_page",
14
+ "text_show_operations",
15
+ "y_coordinate_groups",
16
+ ]
.venv/lib/python3.13/site-packages/pypdf/_text_extraction/_layout_mode/_fixed_width_page.py ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Extract PDF text preserving the layout of the source PDF"""
2
+
3
+ from collections.abc import Iterator
4
+ from itertools import groupby
5
+ from math import ceil
6
+ from pathlib import Path
7
+ from typing import Any, Literal, Optional, TypedDict
8
+
9
+ from ..._font import Font
10
+ from ..._utils import logger_warning
11
+ from .. import LAYOUT_NEW_BT_GROUP_SPACE_WIDTHS
12
+ from ._text_state_manager import TextStateManager
13
+ from ._text_state_params import TextStateParams
14
+
15
+ WHITESPACE_LIMIT = 10_000
16
+ NEWLINE_LIMIT = 1_000
17
+
18
+
19
+ class BTGroup(TypedDict):
20
+ """
21
+ Dict describing a line of text rendered within a BT/ET operator pair.
22
+ If multiple text show operations render text on the same line, the text
23
+ will be combined into a single BTGroup dict.
24
+
25
+ Keys:
26
+ tx: x coordinate of first character in BTGroup
27
+ ty: y coordinate of first character in BTGroup
28
+ font_size: nominal font size
29
+ font_height: effective font height
30
+ text: rendered text
31
+ displaced_tx: x coordinate of last character in BTGroup
32
+ flip_sort: -1 if page is upside down, else 1
33
+ """
34
+
35
+ tx: float
36
+ ty: float
37
+ font_size: float
38
+ font_height: float
39
+ text: str
40
+ displaced_tx: float
41
+ flip_sort: Literal[-1, 1]
42
+
43
+
44
+ def resolve_font(fonts: dict[str, Font], name: str) -> Font:
45
+ """
46
+ Resolve a Tf font name to a layout mode Font.
47
+
48
+ A content stream may select a font name that is not declared in the page
49
+ resources. Fall back to an uninterpretable font so extraction degrades to
50
+ the existing incomplete-output path instead of raising KeyError.
51
+
52
+ Args:
53
+ fonts: font dictionary as returned by PageObject._layout_mode_fonts()
54
+ name: font name supplied by a Tf operator
55
+
56
+ Returns:
57
+ Font: the matching font, or an uninterpretable placeholder font.
58
+
59
+ """
60
+ if name in fonts:
61
+ return fonts[name]
62
+ logger_warning(
63
+ "Font %(name)s is not in the page resources.",
64
+ name=name, source=__name__
65
+ )
66
+ return Font("Unknown", encoding={}, interpretable=False)
67
+
68
+
69
+ def bt_group(tj_op: TextStateParams, rendered_text: str, displaced_tx: float) -> BTGroup:
70
+ """
71
+ BTGroup constructed from a TextStateParams instance, rendered text, and
72
+ displaced tx value.
73
+
74
+ Args:
75
+ tj_op (TextStateParams): TextStateParams instance
76
+ rendered_text (str): rendered text
77
+ displaced_tx (float): x coordinate of last character in BTGroup
78
+
79
+ """
80
+ return BTGroup(
81
+ tx=tj_op.tx,
82
+ ty=tj_op.ty,
83
+ font_size=tj_op.font_size,
84
+ font_height=tj_op.font_height,
85
+ text=rendered_text,
86
+ displaced_tx=displaced_tx,
87
+ flip_sort=-1 if tj_op.flip_vertical else 1,
88
+ )
89
+
90
+
91
+ def recurse_to_target_op(
92
+ ops: Iterator[tuple[list[Any], bytes]],
93
+ text_state_mgr: TextStateManager,
94
+ end_target: Literal[b"Q", b"ET"],
95
+ fonts: dict[str, Font],
96
+ strip_rotated: bool = True,
97
+ ) -> tuple[list[BTGroup], list[TextStateParams]]:
98
+ """
99
+ Recurse operators between BT/ET and/or q/Q operators managing the transform
100
+ stack and capturing text positioning and rendering data.
101
+
102
+ Args:
103
+ ops: iterator of operators in content stream
104
+ text_state_mgr: a TextStateManager instance
105
+ end_target: Either b"Q" (ends b"q" op) or b"ET" (ends b"BT" op)
106
+ fonts: font dictionary as returned by PageObject._layout_mode_fonts()
107
+
108
+ Returns:
109
+ tuple: list of BTGroup dicts + list of TextStateParams dataclass instances.
110
+
111
+ """
112
+ # 1 entry per line of text rendered within each BT/ET operation.
113
+ bt_groups: list[BTGroup] = []
114
+
115
+ # 1 entry per text show operator (Tj/TJ/'/")
116
+ tj_ops: list[TextStateParams] = []
117
+
118
+ if end_target == b"Q":
119
+ # add new q level. cm's added at this level will be popped at next b'Q'
120
+ text_state_mgr.add_q()
121
+
122
+ for operands, op in ops:
123
+ # The loop is broken by the end target, or exits normally when there are no more ops.
124
+ if op == end_target:
125
+ if op == b"Q":
126
+ text_state_mgr.remove_q()
127
+ if op == b"ET":
128
+ if not tj_ops:
129
+ return bt_groups, tj_ops
130
+ _text = ""
131
+ bt_idx = 0 # idx of first tj in this bt group
132
+ last_displaced_tx = tj_ops[bt_idx].displaced_tx
133
+ last_ty = tj_ops[bt_idx].ty
134
+ for _idx, _tj in enumerate(
135
+ tj_ops
136
+ ): # ... build text from new Tj operators
137
+ if strip_rotated and _tj.rotated:
138
+ continue
139
+ if not _tj.font.interpretable: # generates warning
140
+ continue
141
+ # if the y position of the text is greater than the font height, assume
142
+ # the text is on a new line and start a new group
143
+ if abs(_tj.ty - last_ty) > _tj.font_height:
144
+ if _text.strip():
145
+ bt_groups.append(
146
+ bt_group(tj_ops[bt_idx], _text, last_displaced_tx)
147
+ )
148
+ bt_idx = _idx
149
+ _text = ""
150
+
151
+ # if the x position of the text is less than the last x position by
152
+ # more than 5 spaces widths, assume the text order should be flipped
153
+ # and start a new group
154
+ if (
155
+ last_displaced_tx - _tj.tx
156
+ > _tj.space_tx * LAYOUT_NEW_BT_GROUP_SPACE_WIDTHS
157
+ ):
158
+ if _text.strip():
159
+ bt_groups.append(
160
+ bt_group(tj_ops[bt_idx], _text, last_displaced_tx)
161
+ )
162
+ bt_idx = _idx
163
+ last_displaced_tx = _tj.displaced_tx
164
+ _text = ""
165
+
166
+ # calculate excess x translation based on ending tx of previous Tj.
167
+ # multiply by bool (_idx != bt_idx) to ensure spaces aren't double
168
+ # applied to the first tj of a BTGroup in fixed_width_page().
169
+ excess_tx = round(_tj.tx - last_displaced_tx, 3) * (_idx != bt_idx)
170
+ # space_tx could be 0 if either Tz or font_size was 0 for this _tj.
171
+ spaces = int(excess_tx // _tj.space_tx) if _tj.space_tx else 0
172
+ if spaces > WHITESPACE_LIMIT:
173
+ logger_warning(
174
+ "Limiting excessive whitespace from %(actual)d to %(limit)d characters.",
175
+ actual=spaces, limit=WHITESPACE_LIMIT, source=__name__
176
+ )
177
+ spaces = WHITESPACE_LIMIT
178
+ new_text = f'{" " * spaces}{_tj.text}'
179
+
180
+ last_ty = _tj.ty
181
+ _text = f"{_text}{new_text}"
182
+ last_displaced_tx = _tj.displaced_tx
183
+ if _text:
184
+ bt_groups.append(bt_group(tj_ops[bt_idx], _text, last_displaced_tx))
185
+ text_state_mgr.reset_tm()
186
+ break
187
+ if op == b"q":
188
+ bts, tjs = recurse_to_target_op(
189
+ ops, text_state_mgr, b"Q", fonts, strip_rotated
190
+ )
191
+ bt_groups.extend(bts)
192
+ tj_ops.extend(tjs)
193
+ elif op == b"cm":
194
+ text_state_mgr.add_cm(*operands)
195
+ elif op == b"BT":
196
+ bts, tjs = recurse_to_target_op(
197
+ ops, text_state_mgr, b"ET", fonts, strip_rotated
198
+ )
199
+ bt_groups.extend(bts)
200
+ tj_ops.extend(tjs)
201
+ elif op == b"Tj":
202
+ tj_ops.append(text_state_mgr.text_state_params(operands[0]))
203
+ elif op == b"TJ":
204
+ _tj = text_state_mgr.text_state_params()
205
+ for tj_op in operands[0]:
206
+ if isinstance(tj_op, bytes):
207
+ _tj = text_state_mgr.text_state_params(tj_op)
208
+ tj_ops.append(_tj)
209
+ else:
210
+ text_state_mgr.add_trm(_tj.displacement_matrix(td_offset=tj_op))
211
+ elif op == b"'":
212
+ text_state_mgr.reset_trm()
213
+ text_state_mgr.add_tm([0, -text_state_mgr.TL])
214
+ tj_ops.append(text_state_mgr.text_state_params(operands[0]))
215
+ elif op == b'"':
216
+ text_state_mgr.reset_trm()
217
+ text_state_mgr.set_state_param(b"Tw", operands[0])
218
+ text_state_mgr.set_state_param(b"Tc", operands[1])
219
+ text_state_mgr.add_tm([0, -text_state_mgr.TL])
220
+ tj_ops.append(text_state_mgr.text_state_params(operands[2]))
221
+ elif op in (b"Td", b"Tm", b"TD", b"T*"):
222
+ text_state_mgr.reset_trm()
223
+ if op == b"Tm":
224
+ text_state_mgr.reset_tm()
225
+ elif op == b"TD":
226
+ text_state_mgr.set_state_param(b"TL", -operands[1])
227
+ elif op == b"T*":
228
+ operands = [0, -text_state_mgr.TL]
229
+ text_state_mgr.add_tm(operands)
230
+ elif op == b"Tf":
231
+ text_state_mgr.set_font(resolve_font(fonts, operands[0]), operands[1])
232
+ else: # handle Tc, Tw, Tz, TL, and Ts operators
233
+ text_state_mgr.set_state_param(op, operands)
234
+ else:
235
+ logger_warning(
236
+ "Unbalanced target operations, expected %(end_target)r.",
237
+ source=__name__,
238
+ end_target=end_target,
239
+ )
240
+ return bt_groups, tj_ops
241
+
242
+
243
+ def y_coordinate_groups(
244
+ bt_groups: list[BTGroup], debug_path: Optional[Path] = None
245
+ ) -> dict[int, list[BTGroup]]:
246
+ """
247
+ Group text operations by rendered y coordinate, i.e. the line number.
248
+
249
+ Args:
250
+ bt_groups: list of dicts as returned by text_show_operations()
251
+ debug_path (Path, optional): Path to a directory for saving debug output.
252
+
253
+ Returns:
254
+ Dict[int, List[BTGroup]]: dict of lists of text rendered by each BT operator
255
+ keyed by y coordinate
256
+
257
+ """
258
+ ty_groups = {
259
+ ty: sorted(grp, key=lambda x: x["tx"])
260
+ for ty, grp in groupby(
261
+ bt_groups, key=lambda bt_grp: int(bt_grp["ty"] * bt_grp["flip_sort"])
262
+ )
263
+ }
264
+ # combine groups whose y coordinates differ by less than the effective font height
265
+ # (accounts for mixed fonts and other minor oddities)
266
+ last_ty = next(iter(ty_groups))
267
+ last_txs = {int(_t["tx"]) for _t in ty_groups[last_ty] if _t["text"].strip()}
268
+ for ty in list(ty_groups)[1:]:
269
+ fsz = min(ty_groups[_y][0]["font_height"] for _y in (ty, last_ty))
270
+ txs = {int(_t["tx"]) for _t in ty_groups[ty] if _t["text"].strip()}
271
+ # prevent merge if both groups are rendering in the same x position.
272
+ no_text_overlap = not (txs & last_txs)
273
+ offset_less_than_font_height = abs(ty - last_ty) < fsz
274
+ if no_text_overlap and offset_less_than_font_height:
275
+ ty_groups[last_ty] = sorted(
276
+ ty_groups.pop(ty) + ty_groups[last_ty], key=lambda x: x["tx"]
277
+ )
278
+ last_txs |= txs
279
+ else:
280
+ last_ty = ty
281
+ last_txs = txs
282
+ if debug_path: # pragma: no cover
283
+ import json # noqa: PLC0415
284
+
285
+ debug_path.joinpath("bt_groups.json").write_text(
286
+ json.dumps(ty_groups, indent=2, default=str), "utf-8"
287
+ )
288
+ return ty_groups
289
+
290
+
291
+ def text_show_operations(
292
+ ops: Iterator[tuple[list[Any], bytes]],
293
+ fonts: dict[str, Font],
294
+ strip_rotated: bool = True,
295
+ debug_path: Optional[Path] = None,
296
+ ) -> list[BTGroup]:
297
+ """
298
+ Extract text from BT/ET operator pairs.
299
+
300
+ Args:
301
+ ops (Iterator[Tuple[List, bytes]]): iterator of operators in content stream
302
+ fonts (Dict[str, Font]): font dictionary
303
+ strip_rotated: Removes text if rotated w.r.t. to the page. Defaults to True.
304
+ debug_path (Path, optional): Path to a directory for saving debug output.
305
+
306
+ Returns:
307
+ List[BTGroup]: list of dicts of text rendered by each BT operator
308
+
309
+ """
310
+ state_mgr = TextStateManager() # transformation stack manager
311
+ bt_groups: list[BTGroup] = [] # BT operator dict
312
+ tj_ops: list[TextStateParams] = [] # Tj/TJ operator data
313
+ for operands, op in ops:
314
+ if op in (b"BT", b"q"):
315
+ bts, tjs = recurse_to_target_op(
316
+ ops, state_mgr, b"ET" if op == b"BT" else b"Q", fonts, strip_rotated
317
+ )
318
+ bt_groups.extend(bts)
319
+ tj_ops.extend(tjs)
320
+ elif op == b"Tf":
321
+ state_mgr.set_font(resolve_font(fonts, operands[0]), operands[1])
322
+ else: # set Tc, Tw, Tz, TL, and Ts if required. ignores all other ops
323
+ state_mgr.set_state_param(op, operands)
324
+
325
+ if any(tj.rotated for tj in tj_ops):
326
+ if strip_rotated:
327
+ logger_warning(
328
+ "Rotated text discovered. Output will be incomplete.", source=__name__
329
+ )
330
+ else:
331
+ logger_warning(
332
+ "Rotated text discovered. Layout will be degraded.", source=__name__
333
+ )
334
+ if not all(tj.font.interpretable for tj in tj_ops):
335
+ logger_warning(
336
+ "PDF contains an uninterpretable font. Output will be incomplete.", source=__name__
337
+ )
338
+
339
+ # left align the data, i.e. decrement all tx values by min(tx)
340
+ min_x = min((x["tx"] for x in bt_groups), default=0.0)
341
+ bt_groups = [
342
+ dict(ogrp, tx=ogrp["tx"] - min_x, displaced_tx=ogrp["displaced_tx"] - min_x) # type: ignore[misc]
343
+ for ogrp in sorted(
344
+ bt_groups, key=lambda x: (x["ty"] * x["flip_sort"], -x["tx"]), reverse=True
345
+ )
346
+ ]
347
+
348
+ if debug_path: # pragma: no cover
349
+ import json # noqa: PLC0415
350
+
351
+ debug_path.joinpath("bts.json").write_text(
352
+ json.dumps(bt_groups, indent=2, default=str), "utf-8"
353
+ )
354
+ debug_path.joinpath("tjs.json").write_text(
355
+ json.dumps(
356
+ tj_ops, indent=2, default=lambda x: getattr(x, "to_dict", str)(x)
357
+ ),
358
+ "utf-8",
359
+ )
360
+ return bt_groups
361
+
362
+
363
+ def fixed_char_width(bt_groups: list[BTGroup], scale_weight: float = 1.25) -> float:
364
+ """
365
+ Calculate average character width weighted by the length of the rendered
366
+ text in each sample for conversion to fixed-width layout.
367
+
368
+ Args:
369
+ bt_groups (List[BTGroup]): List of dicts of text rendered by each
370
+ BT operator
371
+
372
+ Returns:
373
+ float: fixed character width
374
+
375
+ """
376
+ char_widths = []
377
+ for _bt in bt_groups:
378
+ _len = len(_bt["text"]) * scale_weight
379
+ char_widths.append(((_bt["displaced_tx"] - _bt["tx"]) / _len, _len))
380
+ return sum(_w * _l for _w, _l in char_widths) / sum(_l for _, _l in char_widths)
381
+
382
+
383
+ def fixed_width_page(
384
+ ty_groups: dict[int, list[BTGroup]], char_width: float, space_vertically: bool, font_height_weight: float
385
+ ) -> str:
386
+ """
387
+ Generate page text from text operations grouped by rendered y coordinate.
388
+
389
+ Args:
390
+ ty_groups: dict of text show ops as returned by y_coordinate_groups()
391
+ char_width: fixed character width
392
+ space_vertically: include blank lines inferred from y distance + font height.
393
+ font_height_weight: multiplier for font height when calculating blank lines.
394
+
395
+ Returns:
396
+ str: page text in a fixed width format that closely adheres to the rendered
397
+ layout in the source pdf.
398
+
399
+ """
400
+ lines: list[str] = []
401
+ last_y_coord = 0
402
+ table = str.maketrans(dict.fromkeys(range(14, 32), " "))
403
+ for y_coord, line_data in ty_groups.items():
404
+ if space_vertically and lines:
405
+ fh = line_data[0]["font_height"]
406
+ blank_lines = 0 if fh == 0 else (
407
+ int(abs(y_coord - last_y_coord) / (fh * font_height_weight)) - 1
408
+ )
409
+ if blank_lines > NEWLINE_LIMIT:
410
+ logger_warning(
411
+ "Limiting excessive newlines from %(actual)d to %(limit)d.",
412
+ actual=blank_lines, limit=NEWLINE_LIMIT, source=__name__
413
+ )
414
+ blank_lines = NEWLINE_LIMIT
415
+ lines.extend([""] * blank_lines)
416
+
417
+ line_parts = [] # It uses a list to construct the line, avoiding string concatenation.
418
+ current_len = 0 # Track the size with int instead of len(str) overhead.
419
+ last_disp = 0.0
420
+ for bt_op in line_data:
421
+ tx = bt_op["tx"]
422
+ offset = int(tx // char_width)
423
+ needed_spaces = offset - current_len
424
+ if needed_spaces > 0 and ceil(last_disp) < int(tx):
425
+ if needed_spaces > WHITESPACE_LIMIT:
426
+ logger_warning(
427
+ "Limiting excessive whitespace from %(actual)d to %(limit)d characters.",
428
+ actual=needed_spaces, limit=WHITESPACE_LIMIT, source=__name__
429
+ )
430
+ needed_spaces = WHITESPACE_LIMIT
431
+ padding = " " * needed_spaces
432
+ line_parts.append(padding)
433
+ current_len += needed_spaces
434
+
435
+ raw_text = bt_op["text"]
436
+ text = raw_text.translate(table)
437
+ line_parts.append(text)
438
+ current_len += len(text)
439
+ last_disp = bt_op["displaced_tx"]
440
+
441
+ full_line = "".join(line_parts).rstrip()
442
+ if full_line.strip() or (space_vertically and lines):
443
+ lines.append(full_line)
444
+
445
+ last_y_coord = y_coord
446
+
447
+ return "\n".join(lines)
.venv/lib/python3.13/site-packages/pypdf/_text_extraction/_layout_mode/_text_state_manager.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """manage the PDF transform stack during "layout" mode text extraction"""
2
+
3
+ from collections import ChainMap, Counter
4
+ from collections import ChainMap as ChainMapType
5
+ from collections import Counter as CounterType
6
+ from collections.abc import MutableMapping
7
+ from typing import Any, Union
8
+
9
+ from ..._font import Font
10
+ from ...errors import PdfReadError
11
+ from .. import mult
12
+ from ._text_state_params import TextStateParams
13
+
14
+ TextStateManagerChainMapType = ChainMapType[Union[int, str], Union[float, bool]]
15
+ TextStateManagerDictType = MutableMapping[Union[int, str], Union[float, bool]]
16
+
17
+
18
+ class TextStateManager:
19
+ """
20
+ Tracks the current text state including cm/tm/trm transformation matrices.
21
+
22
+ Attributes:
23
+ transform_stack (ChainMap): ChainMap of cm/tm transformation matrices
24
+ q_queue (Counter[int]): Counter of q operators
25
+ q_depth (List[int]): list of q operator nesting levels
26
+ Tc (float): character spacing
27
+ Tw (float): word spacing
28
+ Tz (int): horizontal scaling
29
+ TL (float): leading
30
+ Ts (float): text rise
31
+ font (Font): font object
32
+ font_size (int | float): font size
33
+
34
+ """
35
+
36
+ def __init__(self) -> None:
37
+ self.transform_stack: TextStateManagerChainMapType = ChainMap(
38
+ self.new_transform()
39
+ )
40
+ self.q_queue: CounterType[int] = Counter()
41
+ self.q_depth = [0]
42
+ self.Tc: float = 0.0
43
+ self.Tw: float = 0.0
44
+ self.Tz: float = 100.0
45
+ self.TL: float = 0.0
46
+ self.Ts: float = 0.0
47
+ self.font_stack: list[tuple[Union[Font, None], Union[int, float]]] = []
48
+ self.font: Union[Font, None] = None
49
+ self.font_size: Union[int, float] = 0
50
+
51
+ def set_state_param(self, op: bytes, value: Union[float, list[Any]]) -> None:
52
+ """
53
+ Set a text state parameter. Supports Tc, Tz, Tw, TL, and Ts operators.
54
+
55
+ Args:
56
+ op: operator read from PDF stream as bytes. No action is taken
57
+ for unsupported operators (see supported operators above).
58
+ value (float | List[Any]): new parameter value. If a list,
59
+ value[0] is used.
60
+
61
+ """
62
+ if op not in [b"Tc", b"Tz", b"Tw", b"TL", b"Ts"]:
63
+ return
64
+ self.__setattr__(op.decode(), value[0] if isinstance(value, list) else value)
65
+
66
+ def set_font(self, font: Font, size: float) -> None:
67
+ """
68
+ Set the current font and font_size.
69
+
70
+ Args:
71
+ font (Font): a layout mode Font
72
+ size (float): font size
73
+
74
+ """
75
+ self.font = font
76
+ self.font_size = size
77
+
78
+ def text_state_params(self, value: Union[bytes, str] = "") -> TextStateParams:
79
+ """
80
+ Create a TextStateParams instance to display a text string. Type[bytes] values
81
+ will be decoded implicitly.
82
+
83
+ Args:
84
+ value (str | bytes): text to associate with the captured state.
85
+
86
+ Raises:
87
+ PdfReadError: if font not set (no Tf operator in incoming pdf content stream)
88
+
89
+ Returns:
90
+ TextStateParams: current text state parameters
91
+
92
+ """
93
+ if not isinstance(self.font, Font):
94
+ raise PdfReadError(
95
+ "font not set: is PDF missing a Tf operator?"
96
+ ) # pragma: no cover
97
+ return TextStateParams(
98
+ value,
99
+ self.font,
100
+ self.font_size,
101
+ self.Tc,
102
+ self.Tw,
103
+ self.Tz,
104
+ self.TL,
105
+ self.Ts,
106
+ self.effective_transform,
107
+ )
108
+
109
+ @staticmethod
110
+ def raw_transform(
111
+ _a: float = 1.0,
112
+ _b: float = 0.0,
113
+ _c: float = 0.0,
114
+ _d: float = 1.0,
115
+ _e: float = 0.0,
116
+ _f: float = 0.0,
117
+ ) -> TextStateManagerDictType:
118
+ """Only a/b/c/d/e/f matrix params"""
119
+ return dict(zip(range(6), map(float, (_a, _b, _c, _d, _e, _f))))
120
+
121
+ @staticmethod
122
+ def new_transform(
123
+ _a: float = 1.0,
124
+ _b: float = 0.0,
125
+ _c: float = 0.0,
126
+ _d: float = 1.0,
127
+ _e: float = 0.0,
128
+ _f: float = 0.0,
129
+ is_text: bool = False,
130
+ is_render: bool = False,
131
+ ) -> TextStateManagerDictType:
132
+ """Standard a/b/c/d/e/f matrix params + 'is_text' and 'is_render' keys"""
133
+ result = TextStateManager.raw_transform(_a, _b, _c, _d, _e, _f)
134
+ result.update({"is_text": is_text, "is_render": is_render})
135
+ return result
136
+
137
+ def reset_tm(self) -> TextStateManagerChainMapType:
138
+ """Clear all transforms from chainmap having is_text==True or is_render==True"""
139
+ while (
140
+ self.transform_stack.maps[0]["is_text"]
141
+ or self.transform_stack.maps[0]["is_render"]
142
+ ):
143
+ self.transform_stack = self.transform_stack.parents
144
+ return self.transform_stack
145
+
146
+ def reset_trm(self) -> TextStateManagerChainMapType:
147
+ """Clear all transforms from chainmap having is_render==True"""
148
+ while self.transform_stack.maps[0]["is_render"]:
149
+ self.transform_stack = self.transform_stack.parents
150
+ return self.transform_stack
151
+
152
+ def remove_q(self) -> TextStateManagerChainMapType:
153
+ """Rewind to stack prior state after closing a 'q' with internal 'cm' ops"""
154
+ self.font, self.font_size = self.font_stack.pop(-1)
155
+ self.transform_stack = self.reset_tm()
156
+ self.transform_stack.maps = self.transform_stack.maps[
157
+ self.q_queue.pop(self.q_depth.pop(), 0) :
158
+ ]
159
+ return self.transform_stack
160
+
161
+ def add_q(self) -> None:
162
+ """Add another level to q_queue"""
163
+ self.font_stack.append((self.font, self.font_size))
164
+ self.q_depth.append(len(self.q_depth))
165
+
166
+ def add_cm(self, *args: Any) -> TextStateManagerChainMapType:
167
+ """Concatenate an additional transform matrix"""
168
+ self.transform_stack = self.reset_tm()
169
+ self.q_queue.update(self.q_depth[-1:])
170
+ self.transform_stack = self.transform_stack.new_child(self.new_transform(*args))
171
+ return self.transform_stack
172
+
173
+ def _complete_matrix(self, operands: list[float]) -> list[float]:
174
+ """Adds a, b, c, and d to an "e/f only" operand set (e.g Td)"""
175
+ if len(operands) == 2: # this is a Td operator or equivalent
176
+ operands = [1.0, 0.0, 0.0, 1.0, *operands]
177
+ return operands
178
+
179
+ def add_tm(self, operands: list[float]) -> TextStateManagerChainMapType:
180
+ """Append a text transform matrix"""
181
+ self.transform_stack = self.transform_stack.new_child(
182
+ self.new_transform( # type: ignore[misc]
183
+ *self._complete_matrix(operands), is_text=True # type: ignore[arg-type]
184
+ )
185
+ )
186
+ return self.transform_stack
187
+
188
+ def add_trm(self, operands: list[float]) -> TextStateManagerChainMapType:
189
+ """Append a text rendering transform matrix"""
190
+ self.transform_stack = self.transform_stack.new_child(
191
+ self.new_transform( # type: ignore[misc]
192
+ *self._complete_matrix(operands), is_text=True, is_render=True # type: ignore[arg-type]
193
+ )
194
+ )
195
+ return self.transform_stack
196
+
197
+ @property
198
+ def effective_transform(self) -> list[float]:
199
+ """Current effective transform accounting for cm, tm, and trm transforms"""
200
+ eff_transform = [*self.transform_stack.maps[0].values()]
201
+ for transform in self.transform_stack.maps[1:]:
202
+ eff_transform = mult(eff_transform, transform) # type: ignore[arg-type] # dict has int keys 0-5
203
+ return eff_transform
.venv/lib/python3.13/site-packages/pypdf/_text_extraction/_layout_mode/_text_state_params.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A dataclass that captures the CTM and Text State for a tj operation"""
2
+
3
+ import math
4
+ from dataclasses import dataclass, field
5
+ from typing import Any, Union
6
+
7
+ from ..._font import Font
8
+ from .. import mult, orient
9
+
10
+
11
+ @dataclass
12
+ class TextStateParams:
13
+ """
14
+ Text state parameters and operator values for a single text value in a
15
+ TJ or Tj PDF operation.
16
+
17
+ Attributes:
18
+ value (bytes | str): the raw text to be rendered.
19
+ font (Font): font object
20
+ font_size (int | float): font size
21
+ Tc (float): character spacing. Defaults to 0.0.
22
+ Tw (float): word spacing. Defaults to 0.0.
23
+ Tz (float): horizontal scaling. Defaults to 100.0.
24
+ TL (float): leading, vertical displacement between text lines. Defaults to 0.0.
25
+ Ts (float): text rise. Used for super/subscripts. Defaults to 0.0.
26
+ transform (List[float]): effective transformation matrix.
27
+ tx (float): x cood of rendered text, i.e. self.transform[4]
28
+ ty (float): y cood of rendered text. May differ from self.transform[5] per self.Ts.
29
+ displaced_tx (float): x coord immediately following rendered text
30
+ space_tx (float): tx for a space character
31
+ font_height (float): effective font height accounting for CTM
32
+ flip_vertical (bool): True if y axis has been inverted (i.e. if self.transform[3] < 0.)
33
+ rotated (bool): True if the text orientation is rotated with respect to the page.
34
+
35
+ """
36
+
37
+ value: Union[bytes, str]
38
+ font: Font
39
+ font_size: Union[int, float]
40
+ Tc: float = 0.0
41
+ Tw: float = 0.0
42
+ Tz: float = 100.0
43
+ TL: float = 0.0
44
+ Ts: float = 0.0
45
+ transform: list[float] = field(
46
+ default_factory=lambda: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
47
+ )
48
+ tx: float = field(default=0.0, init=False)
49
+ ty: float = field(default=0.0, init=False)
50
+ displaced_tx: float = field(default=0.0, init=False)
51
+ space_tx: float = field(default=0.0, init=False)
52
+ font_height: float = field(default=0.0, init=False)
53
+ flip_vertical: bool = field(default=False, init=False)
54
+ rotated: bool = field(default=False, init=False)
55
+ text: str = ""
56
+ _decoded_value: str = ""
57
+
58
+ def __post_init__(self) -> None:
59
+ if isinstance(self.value, bytes):
60
+ try:
61
+ if isinstance(self.font.encoding, str):
62
+ self._decoded_value = self.value.decode(self.font.encoding, "surrogatepass")
63
+ else:
64
+ self._decoded_value = "".join(
65
+ self.font.encoding[x]
66
+ if x in self.font.encoding
67
+ else bytes((x,)).decode()
68
+ for x in self.value
69
+ )
70
+ except UnicodeDecodeError:
71
+ self._decoded_value = self.value.decode("utf-8", "replace")
72
+ self.text = "".join(
73
+ self.font.character_map.get(x, x) for x in self._decoded_value
74
+ )
75
+ else:
76
+ self.text = self.value
77
+
78
+ if orient(self.transform) in (90, 270):
79
+ self.transform = mult(
80
+ [1.0, -self.transform[1], -self.transform[2], 1.0, 0.0, 0.0],
81
+ self.transform,
82
+ )
83
+ self.rotated = True
84
+ # self.transform[0] AND self.transform[3] < 0 indicates true rotation.
85
+ # If only self.transform[3] < 0, the y coords are simply inverted.
86
+ if orient(self.transform) == 180 and self.transform[0] < -1e-6:
87
+ self.transform = mult([-1.0, 0.0, 0.0, -1.0, 0.0, 0.0], self.transform)
88
+ self.rotated = True
89
+ self.displaced_tx = self.displaced_transform()[4]
90
+ self.tx = self.transform[4]
91
+ self.ty = self.render_transform()[5]
92
+ self.space_tx = round(self.word_tx(self.font.space_char), 3)
93
+ if self.space_tx < 1e-6:
94
+ # if the " " char is assigned 0 width (e.g. for fine tuned spacing
95
+ # with TJ int operators a la crazyones.pdf), calculate space_tx as
96
+ # a td_offset of -1 * font.space_width where font.space_width is
97
+ # the space_width calculated in _font.py.
98
+ self.space_tx = round(self.word_tx("", -self.font.space_width), 3)
99
+ self.font_height = self.font_size * math.sqrt(
100
+ self.transform[1] ** 2 + self.transform[3] ** 2
101
+ )
102
+ # flip_vertical handles PDFs generated by Microsoft Word's "publish" command.
103
+ self.flip_vertical = self.transform[3] < -1e-6 # inverts y axis
104
+
105
+ def font_size_matrix(self) -> list[float]:
106
+ """Font size matrix"""
107
+ return [
108
+ self.font_size * (self.Tz / 100.0),
109
+ 0.0,
110
+ 0.0,
111
+ self.font_size,
112
+ 0.0,
113
+ self.Ts,
114
+ ]
115
+
116
+ def displaced_transform(self) -> list[float]:
117
+ """Effective transform matrix after text has been rendered."""
118
+ return mult(self.displacement_matrix(), self.transform)
119
+
120
+ def render_transform(self) -> list[float]:
121
+ """Effective transform matrix accounting for font size, Tz, and Ts."""
122
+ return mult(self.font_size_matrix(), self.transform)
123
+
124
+ def displacement_matrix(
125
+ self, word: Union[bytes, str, None] = None, td_offset: float = 0.0
126
+ ) -> list[float]:
127
+ """
128
+ Text displacement matrix
129
+
130
+ Args:
131
+ word (bytes | str, optional): Defaults to None in which case self.text displacement is
132
+ returned.
133
+ td_offset (float, optional): translation applied by TD operator. Defaults to 0.0.
134
+
135
+ """
136
+ word = word if word is not None else self.value
137
+ return [1.0, 0.0, 0.0, 1.0, self.word_tx(word, td_offset), 0.0]
138
+
139
+ def word_tx(self, word: Union[bytes, str], td_offset: float = 0.0) -> float:
140
+ """Horizontal text displacement for any word according this text state"""
141
+ width: float = 0.0
142
+
143
+ if isinstance(word, bytes):
144
+ word = self._decoded_value
145
+
146
+ for char in word:
147
+ if char == self.font.space_char:
148
+ width += self.font.space_width
149
+ else:
150
+ width += self.font.get_text_width(char)
151
+
152
+ return (
153
+ (self.font_size * ((width - td_offset) / 1000.0))
154
+ + self.Tc
155
+ + word.count(self.font.space_char) * self.Tw
156
+ ) * (self.Tz / 100.0)
157
+
158
+ @staticmethod
159
+ def to_dict(inst: "TextStateParams") -> dict[str, Any]:
160
+ """Dataclass to dict for json.dumps serialization"""
161
+ return {k: getattr(inst, k) for k in inst.__dataclass_fields__ if k != "font"}
.venv/lib/python3.13/site-packages/pypdf/_text_extraction/_text_extractor.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2006, Mathieu Fenniak
2
+ # Copyright (c) 2007, Ashish Kulkarni <kulkarni.ashish@gmail.com>
3
+ #
4
+ # All rights reserved.
5
+ #
6
+ # Redistribution and use in source and binary forms, with or without
7
+ # modification, are permitted provided that the following conditions are
8
+ # met:
9
+ #
10
+ # * Redistributions of source code must retain the above copyright notice,
11
+ # this list of conditions and the following disclaimer.
12
+ # * Redistributions in binary form must reproduce the above copyright notice,
13
+ # this list of conditions and the following disclaimer in the documentation
14
+ # and/or other materials provided with the distribution.
15
+ # * The name of the author may not be used to endorse or promote products
16
+ # derived from this software without specific prior written permission.
17
+ #
18
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28
+ # POSSIBILITY OF SUCH DAMAGE.
29
+
30
+ import math
31
+ from typing import Any, Callable, Optional, Union
32
+
33
+ from .._font import Font, FontDescriptor
34
+ from ..generic import DictionaryObject, TextStringObject
35
+ from . import OrientationNotFoundError, crlf_space_check, get_display_str, get_text_operands, mult
36
+
37
+
38
+ class TextExtraction:
39
+ """
40
+ A class to handle PDF text extraction operations.
41
+
42
+ This class encapsulates all the state and operations needed for extracting
43
+ text from PDF content streams, replacing the nested functions and nonlocal
44
+ variables in the original implementation.
45
+ """
46
+
47
+ def __init__(self) -> None:
48
+ # Text extraction state variables
49
+ self.cm_matrix: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
50
+ self.tm_matrix: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
51
+ self.cm_stack: list[
52
+ tuple[
53
+ list[float],
54
+ Optional[DictionaryObject],
55
+ Font,
56
+ float,
57
+ float,
58
+ float,
59
+ float,
60
+ ]
61
+ ] = []
62
+
63
+ # Store the last modified matrices; can be an intermediate position
64
+ self.cm_prev: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
65
+ self.tm_prev: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
66
+
67
+ # Store the position at the beginning of building the text
68
+ self.memo_cm: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
69
+ self.memo_tm: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
70
+
71
+ self.char_scale = 1.0
72
+ self.space_scale = 1.0
73
+ self._space_width: float = 500.0 # will be set correctly at first Tf
74
+ self._actual_str_size: dict[str, float] = {
75
+ "str_widths": 0.0,
76
+ "str_height": 0.0,
77
+ } # will be set to string length calculation result
78
+ self.TL = 0.0
79
+ self.font_size = 12.0 # init just in case of
80
+
81
+ # Text extraction variables
82
+ self.text: str = ""
83
+ self.output: str = ""
84
+ self.rtl_dir: bool = False # right-to-left
85
+ self.font_resource: Optional[DictionaryObject] = None
86
+ self.font = Font(
87
+ name = "NotInitialized",
88
+ sub_type="Unknown",
89
+ encoding="charmap",
90
+ font_descriptor=FontDescriptor(),
91
+ )
92
+ self.orientations: tuple[int, ...] = (0, 90, 180, 270)
93
+ self.visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]] = None
94
+ self.font_resources: dict[str, DictionaryObject] = {}
95
+ self.fonts: dict[str, Font] = {}
96
+
97
+ self.operation_handlers = {
98
+ b"BT": self._handle_bt,
99
+ b"ET": self._handle_et,
100
+ b"q": self._handle_save_graphics_state,
101
+ b"Q": self._handle_restore_graphics_state,
102
+ b"cm": self._handle_cm,
103
+ b"Tz": self._handle_tz,
104
+ b"Tw": self._handle_tw,
105
+ b"TL": self._handle_tl,
106
+ b"Tf": self._handle_tf,
107
+ b"Td": self._handle_td,
108
+ b"Tm": self._handle_tm,
109
+ b"T*": self._handle_t_star,
110
+ b"Tj": self._handle_tj_operation,
111
+ }
112
+
113
+ def initialize_extraction(
114
+ self,
115
+ orientations: tuple[int, ...] = (0, 90, 180, 270),
116
+ visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]] = None,
117
+ font_resources: Optional[dict[str, DictionaryObject]] = None,
118
+ fonts: Optional[dict[str, Font]] = None
119
+ ) -> None:
120
+ """Initialize the extractor with extraction parameters."""
121
+ self.orientations = orientations
122
+ self.visitor_text = visitor_text
123
+ self.font_resources = font_resources or {}
124
+ self.fonts = fonts or {}
125
+
126
+ # Reset state
127
+ self.text = ""
128
+ self.output = ""
129
+ self.rtl_dir = False
130
+
131
+ def compute_str_widths(self, str_widths: float) -> float:
132
+ return str_widths / 1000
133
+
134
+ def process_operation(self, operator: bytes, operands: list[Any]) -> None:
135
+ if operator in self.operation_handlers:
136
+ handler = self.operation_handlers[operator]
137
+ str_widths = handler(operands)
138
+
139
+ # Post-process operations that affect text positioning
140
+ if operator in {b"Td", b"Tm", b"T*", b"Tj"}:
141
+ self._post_process_text_operation(str_widths or 0.0)
142
+
143
+ def _post_process_text_operation(self, str_widths: float) -> None:
144
+ """Handle common post-processing for text positioning operations."""
145
+ try:
146
+ self.text, self.output, self.cm_prev, self.tm_prev = crlf_space_check(
147
+ self.text,
148
+ (self.cm_prev, self.tm_prev),
149
+ (self.cm_matrix, self.tm_matrix),
150
+ (self.memo_cm, self.memo_tm),
151
+ self.font_resource,
152
+ self.orientations,
153
+ self.output,
154
+ self.font_size,
155
+ self.visitor_text,
156
+ str_widths,
157
+ self.compute_str_widths(self.font_size * self._space_width),
158
+ self._actual_str_size["str_height"],
159
+ )
160
+ if self.text == "":
161
+ self.memo_cm = self.cm_matrix.copy()
162
+ self.memo_tm = self.tm_matrix.copy()
163
+ except OrientationNotFoundError:
164
+ pass
165
+
166
+ def _handle_tj(
167
+ self,
168
+ text: str,
169
+ operands: list[Union[str, TextStringObject]],
170
+ cm_matrix: list[float],
171
+ tm_matrix: list[float],
172
+ font_resource: Optional[DictionaryObject],
173
+ font: Font,
174
+ orientations: tuple[int, ...],
175
+ font_size: float,
176
+ rtl_dir: bool,
177
+ visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]],
178
+ actual_str_size: dict[str, float],
179
+ ) -> tuple[str, bool, dict[str, float]]:
180
+ text_operands, is_str_operands = get_text_operands(
181
+ operands, cm_matrix, tm_matrix, font, orientations
182
+ )
183
+ if is_str_operands:
184
+ text += text_operands
185
+ font_widths = sum(
186
+ [font.space_width if x == font.space_char else font.get_text_width(x) for x in text_operands]
187
+ )
188
+ else:
189
+ text, rtl_dir, font_widths = get_display_str(
190
+ text,
191
+ cm_matrix,
192
+ tm_matrix, # text matrix
193
+ font_resource,
194
+ font,
195
+ text_operands,
196
+ font_size,
197
+ rtl_dir,
198
+ visitor_text,
199
+ )
200
+ actual_str_size["str_widths"] += font_widths * font_size
201
+ actual_str_size["str_height"] = font_size
202
+ return text, rtl_dir, actual_str_size
203
+
204
+ def _flush_text(self) -> None:
205
+ """Flush accumulated text to output and call visitor if present."""
206
+ self.output += self.text
207
+ if self.visitor_text is not None:
208
+ self.visitor_text(self.text, self.memo_cm, self.memo_tm, self.font_resource, self.font_size)
209
+ self.text = ""
210
+ self.memo_cm = self.cm_matrix.copy()
211
+ self.memo_tm = self.tm_matrix.copy()
212
+
213
+ # Operation handlers
214
+
215
+ def _handle_bt(self, operands: list[Any]) -> None:
216
+ """Handle BT (Begin Text) operation - Table 5.4 page 405."""
217
+ self.tm_matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
218
+ self._flush_text()
219
+
220
+ def _handle_et(self, operands: list[Any]) -> None:
221
+ """Handle ET (End Text) operation - Table 5.4 page 405."""
222
+ self._flush_text()
223
+
224
+ def _handle_save_graphics_state(self, operands: list[Any]) -> None:
225
+ """Handle q (Save graphics state) operation - Table 4.7 page 219."""
226
+ self.cm_stack.append(
227
+ (
228
+ self.cm_matrix,
229
+ self.font_resource,
230
+ self.font,
231
+ self.font_size,
232
+ self.char_scale,
233
+ self.space_scale,
234
+ self.TL,
235
+ )
236
+ )
237
+
238
+ def _handle_restore_graphics_state(self, operands: list[Any]) -> None:
239
+ """Handle Q (Restore graphics state) operation - Table 4.7 page 219."""
240
+ try:
241
+ (
242
+ self.cm_matrix,
243
+ self.font_resource,
244
+ self.font,
245
+ self.font_size,
246
+ self.char_scale,
247
+ self.space_scale,
248
+ self.TL,
249
+ ) = self.cm_stack.pop()
250
+ except Exception:
251
+ self.cm_matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
252
+
253
+ def _handle_cm(self, operands: list[Any]) -> None:
254
+ """Handle cm (Modify current matrix) operation - Table 4.7 page 219."""
255
+ self.output += self.text
256
+ if self.visitor_text is not None:
257
+ self.visitor_text(self.text, self.memo_cm, self.memo_tm, self.font_resource, self.font_size)
258
+ self.text = ""
259
+ try:
260
+ self.cm_matrix = mult([float(operand) for operand in operands[:6]], self.cm_matrix)
261
+ except Exception:
262
+ self.cm_matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
263
+ self.memo_cm = self.cm_matrix.copy()
264
+ self.memo_tm = self.tm_matrix.copy()
265
+
266
+ def _handle_tz(self, operands: list[Any]) -> None:
267
+ """Handle Tz (Set horizontal text scaling) operation - Table 5.2 page 398."""
268
+ self.char_scale = float(operands[0]) / 100 if operands else 1.0
269
+
270
+ def _handle_tw(self, operands: list[Any]) -> None:
271
+ """Handle Tw (Set word spacing) operation - Table 5.2 page 398."""
272
+ self.space_scale = 1.0 + float(operands[0] if operands else 0.0)
273
+
274
+ def _handle_tl(self, operands: list[Any]) -> None:
275
+ """Handle TL (Set Text Leading) operation - Table 5.2 page 398."""
276
+ scale_x = math.sqrt(self.tm_matrix[0] ** 2 + self.tm_matrix[2] ** 2)
277
+ self.TL = float(operands[0] if operands else 0.0) * self.font_size * scale_x
278
+
279
+ def _handle_tf(self, operands: list[Any]) -> None:
280
+ """Handle Tf (Set font size) operation - Table 5.2 page 398."""
281
+ if self.text != "":
282
+ self.output += self.text # .translate(cmap)
283
+ if self.visitor_text is not None:
284
+ self.visitor_text(self.text, self.memo_cm, self.memo_tm, self.font_resource, self.font_size)
285
+ self.text = ""
286
+ self.memo_cm = self.cm_matrix.copy()
287
+ self.memo_tm = self.tm_matrix.copy()
288
+ try:
289
+ self.font_resource = self.font_resources[operands[0]]
290
+ self.font = self.fonts[operands[0]]
291
+ except (KeyError, IndexError): # font not found / operand missing
292
+ self.font_resource = None
293
+ font_descriptor = FontDescriptor()
294
+ self.font = Font(
295
+ "Unknown",
296
+ space_width=250,
297
+ encoding=dict.fromkeys(range(256), "�"),
298
+ font_descriptor=font_descriptor,
299
+ character_map={},
300
+ )
301
+
302
+ self._space_width = self.font.space_width / 2 # Actually the width of _half_ a space...
303
+ try:
304
+ self.font_size = float(operands[1])
305
+ except Exception:
306
+ pass # keep previous size
307
+
308
+ def _handle_td(self, operands: list[Any]) -> float:
309
+ """Handle Td (Move text position) operation - Table 5.5 page 406."""
310
+ # A special case is a translating only tm:
311
+ # tm = [1, 0, 0, 1, e, f]
312
+ # i.e. tm[4] += tx, tm[5] += ty.
313
+ tx = float(operands[0]) if len(operands) > 0 else 0.0
314
+ ty = float(operands[1]) if len(operands) > 1 else 0.0
315
+ self.tm_matrix[4] += tx * self.tm_matrix[0] + ty * self.tm_matrix[2]
316
+ self.tm_matrix[5] += tx * self.tm_matrix[1] + ty * self.tm_matrix[3]
317
+ str_widths = self.compute_str_widths(self._actual_str_size["str_widths"])
318
+ self._actual_str_size["str_widths"] = 0.0
319
+ return str_widths
320
+
321
+ def _handle_tm(self, operands: list[Any]) -> float:
322
+ """Handle Tm (Set text matrix) operation - Table 5.5 page 406."""
323
+ try:
324
+ tm_matrix = [float(operand) for operand in operands[:6]]
325
+ except (TypeError, ValueError):
326
+ tm_matrix = []
327
+ # Fall back to the identity matrix when Tm carries the wrong number of
328
+ # operands, mirroring _handle_cm, so the text matrix stays a six-element
329
+ # list and later positioning operators do not read past its end.
330
+ self.tm_matrix = tm_matrix if len(tm_matrix) == 6 else [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
331
+ str_widths = self.compute_str_widths(self._actual_str_size["str_widths"])
332
+ self._actual_str_size["str_widths"] = 0.0
333
+ return str_widths
334
+
335
+ def _handle_t_star(self, operands: list[Any]) -> float:
336
+ """Handle T* (Move to next line) operation - Table 5.5 page 406."""
337
+ self.tm_matrix[4] -= self.TL * self.tm_matrix[2]
338
+ self.tm_matrix[5] -= self.TL * self.tm_matrix[3]
339
+ str_widths = self.compute_str_widths(self._actual_str_size["str_widths"])
340
+ self._actual_str_size["str_widths"] = 0.0
341
+ return str_widths
342
+
343
+ def _handle_tj_operation(self, operands: list[Any]) -> float:
344
+ """Handle Tj (Show text) operation - Table 5.5 page 406."""
345
+ self.text, self.rtl_dir, self._actual_str_size = self._handle_tj(
346
+ self.text,
347
+ operands,
348
+ self.cm_matrix,
349
+ self.tm_matrix,
350
+ self.font_resource,
351
+ self.font,
352
+ self.orientations,
353
+ self.font_size,
354
+ self.rtl_dir,
355
+ self.visitor_text,
356
+ self._actual_str_size,
357
+ )
358
+ return 0.0 # str_widths will be handled in post-processing
.venv/lib/python3.13/site-packages/pypdf/_utils.py ADDED
@@ -0,0 +1,673 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2006, Mathieu Fenniak
2
+ # All rights reserved.
3
+ #
4
+ # Redistribution and use in source and binary forms, with or without
5
+ # modification, are permitted provided that the following conditions are
6
+ # met:
7
+ #
8
+ # * Redistributions of source code must retain the above copyright notice,
9
+ # this list of conditions and the following disclaimer.
10
+ # * Redistributions in binary form must reproduce the above copyright notice,
11
+ # this list of conditions and the following disclaimer in the documentation
12
+ # and/or other materials provided with the distribution.
13
+ # * The name of the author may not be used to endorse or promote products
14
+ # derived from this software without specific prior written permission.
15
+ #
16
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26
+ # POSSIBILITY OF SUCH DAMAGE.
27
+
28
+ """Utility functions for PDF library."""
29
+ __author__ = "Mathieu Fenniak"
30
+ __author_email__ = "biziqe@mathieu.fenniak.net"
31
+
32
+ import functools
33
+ import logging
34
+ import re
35
+ import sys
36
+ import warnings
37
+ from dataclasses import dataclass
38
+ from datetime import datetime, timezone
39
+ from io import DEFAULT_BUFFER_SIZE
40
+ from os import SEEK_CUR
41
+ from re import Pattern
42
+ from typing import (
43
+ IO,
44
+ Any,
45
+ NoReturn,
46
+ Optional,
47
+ Union,
48
+ )
49
+
50
+ if sys.version_info[:2] >= (3, 10):
51
+ # Python 3.10+: https://www.python.org/dev/peps/pep-0484/
52
+ from typing import TypeAlias
53
+ else:
54
+ from typing_extensions import TypeAlias
55
+
56
+ if sys.version_info >= (3, 11):
57
+ from typing import Self
58
+ else:
59
+ from typing_extensions import Self
60
+
61
+ from .errors import (
62
+ STREAM_TRUNCATED_PREMATURELY,
63
+ DeprecationError,
64
+ LimitReachedError,
65
+ PdfStreamError,
66
+ )
67
+
68
+ TransformationMatrixType: TypeAlias = tuple[
69
+ tuple[float, float, float], tuple[float, float, float], tuple[float, float, float]
70
+ ]
71
+ CompressedTransformationMatrix: TypeAlias = tuple[
72
+ float, float, float, float, float, float
73
+ ]
74
+
75
+ StreamType = IO[Any]
76
+ BinaryStreamType = IO[bytes]
77
+ StrByteType = Union[str, StreamType]
78
+
79
+
80
+ def parse_iso8824_date(text: Optional[str]) -> Optional[datetime]:
81
+ orgtext = text
82
+ if not text:
83
+ return None
84
+ if text[0].isdigit():
85
+ text = "D:" + text
86
+ if text.endswith(("Z", "z")):
87
+ text += "0000"
88
+ text = text.replace("z", "+").replace("Z", "+").replace("'", "")
89
+ i = max(text.find("+"), text.find("-"))
90
+ if i > 0 and i != len(text) - 5:
91
+ text += "00"
92
+ for f in (
93
+ "D:%Y",
94
+ "D:%Y%m",
95
+ "D:%Y%m%d",
96
+ "D:%Y%m%d%H",
97
+ "D:%Y%m%d%H%M",
98
+ "D:%Y%m%d%H%M%S",
99
+ "D:%Y%m%d%H%M%S%z",
100
+ ):
101
+ try:
102
+ d = datetime.strptime(text, f) # noqa: DTZ007
103
+ except ValueError:
104
+ continue
105
+ else:
106
+ if text.endswith("+0000"):
107
+ d = d.replace(tzinfo=timezone.utc)
108
+ return d
109
+ raise ValueError(f"Can not convert date: {orgtext}")
110
+
111
+
112
+ def format_iso8824_date(dt: datetime) -> str:
113
+ """
114
+ Convert a datetime object to PDF date string format.
115
+
116
+ Converts datetime to the PDF date format D:YYYYMMDDHHmmSSOHH'mm
117
+ as specified in the PDF Reference.
118
+
119
+ Args:
120
+ dt: A datetime object to convert.
121
+
122
+ Returns:
123
+ A date string in PDF format.
124
+ """
125
+ date_str = dt.strftime("D:%Y%m%d%H%M%S")
126
+ if dt.tzinfo is not None:
127
+ offset = dt.utcoffset()
128
+ assert offset is not None
129
+ total_seconds = int(offset.total_seconds())
130
+ hours, remainder = divmod(abs(total_seconds), 3600)
131
+ minutes = remainder // 60
132
+ sign = "+" if total_seconds >= 0 else "-"
133
+ date_str += f"{sign}{hours:02d}'{minutes:02d}'"
134
+ return date_str
135
+
136
+
137
+ def _get_max_pdf_version_header(header1: str, header2: str) -> str:
138
+ versions = (
139
+ "%PDF-1.3",
140
+ "%PDF-1.4",
141
+ "%PDF-1.5",
142
+ "%PDF-1.6",
143
+ "%PDF-1.7",
144
+ "%PDF-2.0",
145
+ )
146
+ pdf_header_indices = []
147
+ if header1 in versions:
148
+ pdf_header_indices.append(versions.index(header1))
149
+ if header2 in versions:
150
+ pdf_header_indices.append(versions.index(header2))
151
+ if len(pdf_header_indices) == 0:
152
+ raise ValueError(f"Neither {header1!r} nor {header2!r} are proper headers")
153
+ return versions[max(pdf_header_indices)]
154
+
155
+
156
+ WHITESPACES = (b"\x00", b"\t", b"\n", b"\f", b"\r", b" ")
157
+ WHITESPACES_AS_BYTES = b"".join(WHITESPACES)
158
+ WHITESPACES_AS_REGEXP = b"[" + WHITESPACES_AS_BYTES + b"]"
159
+
160
+
161
+ def read_until_whitespace(stream: StreamType, max_bytes: Optional[int] = None) -> bytes:
162
+ """
163
+ Read non-whitespace characters and return them.
164
+
165
+ Stops upon encountering whitespace or when max_bytes is reached.
166
+
167
+ Args:
168
+ stream: The data stream from which was read.
169
+ max_bytes: The maximum number of bytes returned; by default unlimited.
170
+
171
+ Returns:
172
+ The data which was read.
173
+
174
+ """
175
+ txt = bytearray()
176
+ while True:
177
+ tok = stream.read(1)
178
+ if tok.isspace() or not tok:
179
+ break
180
+ txt += tok
181
+ if len(txt) == max_bytes:
182
+ break
183
+ return bytes(txt)
184
+
185
+
186
+ def read_non_whitespace(stream: BinaryStreamType) -> bytes:
187
+ """
188
+ Find and read the next non-whitespace character (ignores whitespace).
189
+
190
+ Args:
191
+ stream: The data stream from which was read.
192
+
193
+ Returns:
194
+ The data which was read.
195
+
196
+ """
197
+ tok = stream.read(1)
198
+ while tok in WHITESPACES:
199
+ tok = stream.read(1)
200
+ return tok
201
+
202
+
203
+ def skip_over_whitespace(stream: StreamType) -> bool:
204
+ """
205
+ Similar to read_non_whitespace, but return a boolean if at least one
206
+ whitespace character was read.
207
+
208
+ Args:
209
+ stream: The data stream from which was read.
210
+
211
+ Returns:
212
+ True if one or more whitespace was skipped, otherwise return False.
213
+
214
+ """
215
+ tok = stream.read(1)
216
+ cnt = 0
217
+ while tok in WHITESPACES:
218
+ cnt += 1
219
+ tok = stream.read(1)
220
+ return cnt > 0
221
+
222
+
223
+ def check_if_whitespace_only(value: bytes) -> bool:
224
+ """
225
+ Check if the given value consists of whitespace characters only.
226
+
227
+ Args:
228
+ value: The bytes to check.
229
+
230
+ Returns:
231
+ True if the value only has whitespace characters, otherwise return False.
232
+
233
+ """
234
+ return all(b in WHITESPACES_AS_BYTES for b in value)
235
+
236
+
237
+ NEUTRAL_CHARACTER_RANGES = (
238
+ ("\x00", "\x2F"), # ASCII control codes, space, and early punctuation (!"#$%)
239
+ ("\x3A", "\x40"), # ASCII operators and punctuation between digits & A (:;<=>?@)
240
+ ("\u2000", "\u206F"), # General punctuation
241
+ ("\u20A0", "\u21FF"), # Currency symbols, diacritical marks, letter-like symbols, number forms, arrows
242
+ )
243
+
244
+
245
+ def is_char_neutral(char: str, custom_special_characters: str = "") -> bool:
246
+ """Check if a character is part of neutral character ranges"""
247
+ if any(start <= char <= end for start, end in NEUTRAL_CHARACTER_RANGES):
248
+ return True
249
+
250
+ return bool(custom_special_characters and char in custom_special_characters)
251
+
252
+
253
+ RTL_CHARACTER_RANGES = (
254
+ ("\u0590", "\u08FF"), # Hebrew, Arabic, Syriac, Thaana, N'Ko, etc.
255
+ ("\uFB1D", "\uFDFF"), # Hebrew & Arabic Presentation Forms-A
256
+ ("\uFE70", "\uFEFF"), # Arabic Presentation Forms-B
257
+ )
258
+
259
+
260
+ def is_char_rtl(char: str, custom_rtl_min: str = "", custom_rtl_max: str = "") -> bool:
261
+ """Check if a character is part of RTL character ranges"""
262
+ if any(start <= char <= end for start, end in RTL_CHARACTER_RANGES):
263
+ return True
264
+
265
+ return bool(custom_rtl_min and custom_rtl_max and (custom_rtl_min <= char <= custom_rtl_max))
266
+
267
+
268
+ def skip_over_comment(stream: StreamType) -> None:
269
+ tok = stream.read(1)
270
+ stream.seek(-1, 1)
271
+ if tok == b"%":
272
+ while tok not in (b"\n", b"\r"):
273
+ tok = stream.read(1)
274
+ if tok == b"":
275
+ raise PdfStreamError("File ended unexpectedly.")
276
+
277
+
278
+ def read_until_regex(*, stream: StreamType, regex: Pattern[bytes], length: int = sys.maxsize) -> bytes:
279
+ """
280
+ Read until the regular expression pattern matched (ignore the match).
281
+ Treats EOF on the underlying stream as the end of the token to be matched.
282
+
283
+ Args:
284
+ stream: The stream to read from.
285
+ regex: The pattern to search for.
286
+ length: The (approximated) maximum number of bytes to read before raising an exception.
287
+
288
+ Returns:
289
+ The read bytes.
290
+
291
+ """
292
+ parts: list[bytes] = []
293
+ total_length = 0
294
+ tail = b""
295
+ chunk_size = 16
296
+ while True:
297
+ token = stream.read(chunk_size)
298
+ if not token:
299
+ return b"".join(parts)
300
+ token_length = len(token)
301
+ if (current_length := total_length + token_length) >= length:
302
+ raise LimitReachedError(
303
+ f"Read stream length of {current_length} exceeds maximum allowed length of {length}."
304
+ )
305
+
306
+ # Search overlap of previous tail + new chunk to catch
307
+ # multi-byte regex matches spanning chunk boundaries.
308
+ current_buffer = tail + token
309
+ search_match = regex.search(current_buffer)
310
+ parts.append(token)
311
+ if search_match is not None:
312
+ overlap = len(tail)
313
+ actual_start = total_length - overlap + search_match.start()
314
+ stream.seek(actual_start - total_length - token_length, 1)
315
+ return b"".join(parts)[:actual_start]
316
+ total_length += token_length
317
+
318
+ # Fixed overlap: 16 bytes is sufficient for the short
319
+ # delimiter patterns used in PDF parsing.
320
+ tail = token[-16:]
321
+ if chunk_size < 8192:
322
+ chunk_size <<= 1
323
+
324
+
325
+ def read_block_backwards(stream: BinaryStreamType, to_read: int) -> bytes:
326
+ """
327
+ Given a stream at position X, read a block of size to_read ending at position X.
328
+
329
+ This changes the stream's position to the beginning of where the block was
330
+ read.
331
+
332
+ Args:
333
+ stream:
334
+ to_read:
335
+
336
+ Returns:
337
+ The data which was read.
338
+
339
+ """
340
+ if stream.tell() < to_read:
341
+ raise PdfStreamError("Could not read malformed PDF file")
342
+ # Seek to the start of the block we want to read.
343
+ stream.seek(-to_read, SEEK_CUR)
344
+ read = stream.read(to_read)
345
+ # Seek to the start of the block we read after reading it.
346
+ stream.seek(-to_read, SEEK_CUR)
347
+ return read
348
+
349
+
350
+ def read_previous_line(stream: StreamType) -> bytes:
351
+ """
352
+ Given a byte stream with current position X, return the previous line.
353
+
354
+ All characters between the first CR/LF byte found before X
355
+ (or, the start of the file, if no such byte is found) and position X
356
+ After this call, the stream will be positioned one byte after the
357
+ first non-CRLF character found beyond the first CR/LF byte before X,
358
+ or, if no such byte is found, at the beginning of the stream.
359
+
360
+ Args:
361
+ stream: StreamType:
362
+
363
+ Returns:
364
+ The data which was read.
365
+
366
+ """
367
+ line_content = []
368
+ found_crlf = False
369
+ if stream.tell() == 0:
370
+ raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY)
371
+ while True:
372
+ to_read = min(DEFAULT_BUFFER_SIZE, stream.tell())
373
+ if to_read == 0:
374
+ break
375
+ # Read the block. After this, our stream will be one
376
+ # beyond the initial position.
377
+ block = read_block_backwards(stream, to_read)
378
+ idx = len(block) - 1
379
+ if not found_crlf:
380
+ # We haven't found our first CR/LF yet.
381
+ # Read off characters until we hit one.
382
+ while idx >= 0 and block[idx] not in b"\r\n":
383
+ idx -= 1
384
+ if idx >= 0:
385
+ found_crlf = True
386
+ if found_crlf:
387
+ # We found our first CR/LF already (on this block or
388
+ # a previous one).
389
+ # Our combined line is the remainder of the block
390
+ # plus any previously read blocks.
391
+ line_content.append(block[idx + 1 :])
392
+ # Continue to read off any more CRLF characters.
393
+ while idx >= 0 and block[idx] in b"\r\n":
394
+ idx -= 1
395
+ else:
396
+ # Didn't find CR/LF yet - add this block to our
397
+ # previously read blocks and continue.
398
+ line_content.append(block)
399
+ if idx >= 0:
400
+ # We found the next non-CRLF character.
401
+ # Set the stream position correctly, then break
402
+ stream.seek(idx + 1, SEEK_CUR)
403
+ break
404
+ # Join all the blocks in the line (which are in reverse order)
405
+ return b"".join(line_content[::-1])
406
+
407
+
408
+ def matrix_multiply(
409
+ a: TransformationMatrixType, b: TransformationMatrixType
410
+ ) -> TransformationMatrixType:
411
+ return tuple( # type: ignore[return-value]
412
+ tuple(sum(float(i) * float(j) for i, j in zip(row, col)) for col in zip(*b))
413
+ for row in a
414
+ )
415
+
416
+
417
+ def mark_location(stream: StreamType) -> None:
418
+ """Create text file showing current location in context."""
419
+ # Mainly for debugging
420
+ radius = 5000
421
+ stream.seek(-radius, 1)
422
+ with open("pypdf_pdfLocation.txt", "wb") as output_fh:
423
+ output_fh.write(stream.read(radius))
424
+ output_fh.write(b"HERE")
425
+ output_fh.write(stream.read(radius))
426
+ stream.seek(-radius, 1)
427
+
428
+
429
+ def deprecate(msg: str, stacklevel: int = 3) -> None:
430
+ warnings.warn(msg, DeprecationWarning, stacklevel=stacklevel)
431
+
432
+
433
+ def deprecation(msg: str) -> NoReturn:
434
+ raise DeprecationError(msg)
435
+
436
+
437
+ def deprecate_with_replacement(old_name: str, new_name: str, removed_in: str) -> None:
438
+ """Issue a warning that a feature will be removed, but has a replacement."""
439
+ deprecate(
440
+ f"{old_name} is deprecated and will be removed in pypdf {removed_in}. Use {new_name} instead.",
441
+ 4,
442
+ )
443
+
444
+
445
+ def deprecation_with_replacement(old_name: str, new_name: str, removed_in: str) -> NoReturn:
446
+ """Raise an exception that a feature was already removed, but has a replacement."""
447
+ deprecation(
448
+ f"{old_name} is deprecated and was removed in pypdf {removed_in}. Use {new_name} instead."
449
+ )
450
+
451
+
452
+ def deprecate_no_replacement(name: str, removed_in: str) -> None:
453
+ """Issue a warning that a feature will be removed without replacement."""
454
+ deprecate(f"{name} is deprecated and will be removed in pypdf {removed_in}.", 4)
455
+
456
+
457
+ def deprecation_no_replacement(name: str, removed_in: str) -> NoReturn:
458
+ """Raise an exception that a feature was already removed without replacement."""
459
+ deprecation(f"{name} is deprecated and was removed in pypdf {removed_in}.")
460
+
461
+
462
+ def logger_error(message: str, *, source: str, **values: Any) -> None:
463
+ """
464
+ Use this instead of logger.error directly.
465
+
466
+ That allows people to overwrite it more easily.
467
+
468
+ See the docs on when to use which:
469
+ https://pypdf.readthedocs.io/en/latest/user/suppress-warnings.html
470
+ """
471
+ if values:
472
+ logging.getLogger(source).error(message, values)
473
+ else:
474
+ logging.getLogger(source).error(message)
475
+
476
+
477
+ def logger_warning(message: str, *, source: str, **values: Any) -> None:
478
+ """
479
+ Use this instead of logger.warning directly.
480
+
481
+ That allows people to overwrite it more easily.
482
+
483
+ ## Exception, warnings.warn, logger_warning
484
+ - Exceptions should be used if the user should write code that deals with
485
+ an error case, e.g. the PDF being completely broken.
486
+ - warnings.warn should be used if the user needs to fix their code, e.g.
487
+ DeprecationWarnings
488
+ - logger_warning should be used if the user needs to know that an issue was
489
+ handled by pypdf, e.g. a non-compliant PDF being read in a way that
490
+ pypdf could apply a robustness fix to still read it. This applies mainly
491
+ to strict=False mode.
492
+ """
493
+ if values:
494
+ logging.getLogger(source).warning(message, values)
495
+ else:
496
+ # Keep parity with logger_error and support plain warning messages.
497
+ # Passing an empty dict to logging is not equivalent to passing no args:
498
+ # plain messages would fail while being formatted.
499
+ logging.getLogger(source).warning(message)
500
+
501
+
502
+ def rename_kwargs(
503
+ func_name: str, kwargs: dict[str, Any], aliases: dict[str, str], fail: bool = False
504
+ ) -> None:
505
+ """
506
+ Helper function to deprecate arguments.
507
+
508
+ Args:
509
+ func_name: Name of the function to be deprecated
510
+ kwargs:
511
+ aliases:
512
+ fail:
513
+
514
+ """
515
+ for old_term, new_term in aliases.items():
516
+ if old_term in kwargs:
517
+ if fail:
518
+ raise DeprecationError(
519
+ f"{old_term} is deprecated as an argument. Use {new_term} instead"
520
+ )
521
+ if new_term in kwargs:
522
+ raise TypeError(
523
+ f"{func_name} received both {old_term} and {new_term} as "
524
+ f"an argument. {old_term} is deprecated. "
525
+ f"Use {new_term} instead."
526
+ )
527
+ kwargs[new_term] = kwargs.pop(old_term)
528
+ warnings.warn(
529
+ message=(
530
+ f"{old_term} is deprecated as an argument. Use {new_term} instead"
531
+ ),
532
+ category=DeprecationWarning,
533
+ stacklevel=3,
534
+ )
535
+
536
+
537
+ def _human_readable_bytes(bytes: int) -> str:
538
+ if bytes < 10**3:
539
+ return f"{bytes} Byte"
540
+ if bytes < 10**6:
541
+ return f"{bytes / 10**3:.1f} kB"
542
+ if bytes < 10**9:
543
+ return f"{bytes / 10**6:.1f} MB"
544
+ return f"{bytes / 10**9:.1f} GB"
545
+
546
+
547
+ # The following class has been copied from Django:
548
+ # https://github.com/django/django/blob/adae619426b6f50046b3daaa744db52989c9d6db/django/utils/functional.py#L51-L65
549
+ # It received some modifications to comply with our own coding standards.
550
+ #
551
+ # Original license:
552
+ #
553
+ # ---------------------------------------------------------------------------------
554
+ # Copyright (c) Django Software Foundation and individual contributors.
555
+ # All rights reserved.
556
+ #
557
+ # Redistribution and use in source and binary forms, with or without modification,
558
+ # are permitted provided that the following conditions are met:
559
+ #
560
+ # 1. Redistributions of source code must retain the above copyright notice,
561
+ # this list of conditions and the following disclaimer.
562
+ #
563
+ # 2. Redistributions in binary form must reproduce the above copyright
564
+ # notice, this list of conditions and the following disclaimer in the
565
+ # documentation and/or other materials provided with the distribution.
566
+ #
567
+ # 3. Neither the name of Django nor the names of its contributors may be used
568
+ # to endorse or promote products derived from this software without
569
+ # specific prior written permission.
570
+ #
571
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
572
+ # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
573
+ # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
574
+ # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
575
+ # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
576
+ # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
577
+ # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
578
+ # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
579
+ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
580
+ # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
581
+ # ---------------------------------------------------------------------------------
582
+ class classproperty: # noqa: N801
583
+ """
584
+ Decorator that converts a method with a single cls argument into a property
585
+ that can be accessed directly from the class.
586
+ """
587
+
588
+ def __init__(self, method=None) -> None: # type: ignore # noqa: ANN001
589
+ self.fget = method
590
+
591
+ def __get__(self, instance, cls=None) -> Any: # type: ignore # noqa: ANN001
592
+ return self.fget(cls)
593
+
594
+ def getter(self, method) -> Self: # type: ignore # noqa: ANN001
595
+ self.fget = method
596
+ return self
597
+
598
+
599
+ @dataclass
600
+ class File:
601
+ from .generic import IndirectObject # noqa: PLC0415
602
+
603
+ name: str = ""
604
+ """
605
+ Filename as identified within the PDF file.
606
+ """
607
+ data: bytes = b""
608
+ """
609
+ Data as bytes.
610
+ """
611
+ indirect_reference: Optional[IndirectObject] = None
612
+ """
613
+ Reference to the object storing the stream.
614
+ """
615
+
616
+ def __str__(self) -> str:
617
+ return f"{self.__class__.__name__}(name={self.name}, data: {_human_readable_bytes(len(self.data))})"
618
+
619
+ def __repr__(self) -> str:
620
+ return self.__str__()[:-1] + f", hash: {hash(self.data)})"
621
+
622
+
623
+ @functools.total_ordering
624
+ class Version:
625
+ COMPONENT_PATTERN = re.compile(r"^(\d+)(.*)$")
626
+
627
+ def __init__(self, version_str: str) -> None:
628
+ self.version_str = version_str
629
+ self.components = self._parse_version(version_str)
630
+
631
+ def _parse_version(self, version_str: str) -> list[tuple[int, str]]:
632
+ components = version_str.split(".")
633
+ parsed_components = []
634
+ for component in components:
635
+ match = Version.COMPONENT_PATTERN.match(component)
636
+ if not match:
637
+ parsed_components.append((0, component))
638
+ continue
639
+ integer_prefix = match.group(1)
640
+ suffix = match.group(2)
641
+ if integer_prefix is None:
642
+ integer_prefix = 0
643
+ parsed_components.append((int(integer_prefix), suffix))
644
+ return parsed_components
645
+
646
+ def __eq__(self, other: object) -> bool:
647
+ if not isinstance(other, Version):
648
+ return False
649
+ return self.components == other.components
650
+
651
+ def __hash__(self) -> int:
652
+ # Convert to tuple as lists cannot be hashed.
653
+ return hash((self.__class__, tuple(self.components)))
654
+
655
+ def __lt__(self, other: Any) -> bool:
656
+ if not isinstance(other, Version):
657
+ raise ValueError(f"Version cannot be compared against {type(other)}")
658
+
659
+ for self_component, other_component in zip(self.components, other.components):
660
+ self_value, self_suffix = self_component
661
+ other_value, other_suffix = other_component
662
+
663
+ if self_value < other_value:
664
+ return True
665
+ if self_value > other_value:
666
+ return False
667
+
668
+ if self_suffix < other_suffix:
669
+ return True
670
+ if self_suffix > other_suffix:
671
+ return False
672
+
673
+ return len(self.components) < len(other.components)
.venv/lib/python3.13/site-packages/pypdf/_version.py ADDED
@@ -0,0 +1 @@
 
 
1
+ __version__ = "6.15.0"
.venv/lib/python3.13/site-packages/pypdf/_writer.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv/lib/python3.13/site-packages/pypdf/actions/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ PDF includes a wide variety of standard action types, whose characteristics and
3
+ behaviour are defined by an action dictionary. These are defined in this
4
+ submodule.
5
+
6
+ Trigger events are the other component of actions, and are specific to their
7
+ associated object.
8
+ """
9
+
10
+
11
+ from ._actions import Action, JavaScript, PageTrigger
12
+
13
+ __all__ = [
14
+ "Action",
15
+ "JavaScript",
16
+ "PageTrigger",
17
+ ]
.venv/lib/python3.13/site-packages/pypdf/actions/_actions.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Action types"""
2
+ import sys
3
+ from abc import ABC
4
+ from enum import Enum, unique
5
+ from typing import (
6
+ TYPE_CHECKING,
7
+ cast,
8
+ )
9
+
10
+ from .._utils import logger_warning
11
+ from ..errors import ParseError
12
+ from ..generic import (
13
+ ArrayObject,
14
+ DictionaryObject,
15
+ NameObject,
16
+ NullObject,
17
+ TextStringObject,
18
+ is_null_or_none,
19
+ )
20
+
21
+ if sys.version_info >= (3, 11):
22
+ from enum import StrEnum
23
+ else:
24
+ class StrEnum(str, Enum):
25
+ def __str__(self) -> str:
26
+ return str(self.value)
27
+
28
+ if TYPE_CHECKING:
29
+ from .._page import PageObject
30
+
31
+
32
+ @unique
33
+ class PageTrigger(StrEnum):
34
+ """Trigger event entries in a page object's additional-actions dictionary."""
35
+ OPEN = "open"
36
+ """Trigger an action when the page is opened."""
37
+ CLOSE = "close"
38
+ """Trigger an action when the page is closed."""
39
+
40
+ @property
41
+ def _name_object(self) -> NameObject:
42
+ """Returns the corresponding NameObject for the trigger."""
43
+ mapping = {
44
+ PageTrigger.OPEN: NameObject("/O"),
45
+ PageTrigger.CLOSE: NameObject("/C"),
46
+ }
47
+ return mapping[self]
48
+
49
+
50
+ class Action(DictionaryObject, ABC):
51
+ """An action dictionary defines the characteristics and behaviour of an action."""
52
+ def __init__(self) -> None:
53
+ super().__init__()
54
+ self[NameObject("/Type")] = NameObject("/Action")
55
+ # The next action or sequence of actions that shall be performed after the action
56
+ # represented by this dictionary. The value is either a single action dictionary
57
+ # or an array of action dictionaries that shall be performed in order.
58
+ self[NameObject("/Next")] = NullObject() # Optional
59
+
60
+ @classmethod
61
+ def _create_new(cls, page: "PageObject", trigger: PageTrigger, action: "Action") -> None:
62
+ """
63
+ Create a new action and add it to the page.
64
+
65
+ Args:
66
+ page: The page to add the action to.
67
+ trigger: An open or close trigger.
68
+ action: The action to be done.
69
+ """
70
+ trigger_name = trigger._name_object
71
+
72
+ if "/AA" not in page:
73
+ # Additional actions key not present
74
+ page[NameObject("/AA")] = DictionaryObject(
75
+ {trigger_name: action}
76
+ )
77
+ return
78
+
79
+ if isinstance(page["/AA"], NullObject):
80
+ page[NameObject("/AA")] = DictionaryObject()
81
+
82
+ if not isinstance(page["/AA"].get_object(), DictionaryObject):
83
+ current_type = type(page["/AA"]).__name__
84
+ if page.pdf is not None and getattr(page.pdf, "strict", False):
85
+ raise ParseError(
86
+ f"The type in a page object's additional-actions key must be a DictionaryObject: "
87
+ f"received type {current_type}."
88
+ )
89
+ logger_warning(
90
+ "The type in a page object's additional-actions key must be a DictionaryObject: "
91
+ "received type %(type)s.",
92
+ source=__name__,
93
+ type=current_type
94
+ )
95
+ return
96
+
97
+ additional_actions = cast(DictionaryObject, page["/AA"])
98
+
99
+ if is_null_or_none(additional_actions.get(trigger_name)):
100
+ additional_actions.update({trigger_name: action})
101
+ return
102
+
103
+ # The action dictionary's Next entry allows sequences of actions to be
104
+ # chained together. For example, the effect of clicking a link
105
+ # annotation with the mouse can be to play a sound, jump to a new
106
+ # page, and start up a movie. Note that the Next entry is not
107
+ # restricted to a single action but can contain an array of actions,
108
+ # each of which in turn can have a Next entry of its own.
109
+ # §12.6.2 Action dictionaries ISO 32000-2:2020
110
+ head = current = additional_actions.get(trigger_name)
111
+ if not isinstance(head, DictionaryObject):
112
+ raise ParseError(
113
+ f"The type in a page object's additional-actions key must be a DictionaryObject: "
114
+ f"received type {type(head).__name__}."
115
+ )
116
+ current = cast(DictionaryObject, current)
117
+
118
+ visited = set()
119
+ while True:
120
+ next_node = current.get("/Next", None)
121
+
122
+ if is_null_or_none(next_node):
123
+ break
124
+
125
+ if not isinstance(next_node, (ArrayObject, DictionaryObject)):
126
+ raise TypeError(
127
+ f"An action dictionary’s Next entry must be an Action dictionary "
128
+ f"or an array of Action dictionaries: received type {type(next_node).__name__}."
129
+ )
130
+
131
+ id_next = id(next_node)
132
+ if id_next in visited:
133
+ logger_warning("Detected cycle in the action tree for %(current)s", source=__name__, current=current)
134
+ break
135
+ visited.add(id_next)
136
+
137
+ if isinstance(next_node, ArrayObject):
138
+ current = next_node[-1]
139
+ else:
140
+ current = next_node
141
+
142
+ if not is_null_or_none(next_node := current.get("/Next")) and id(next_node) in visited:
143
+ logger_warning("Detected cycle in the action tree for %(current)s", source=__name__, current=current)
144
+
145
+ current[NameObject("/Next")] = action
146
+ additional_actions.update({trigger_name: head})
147
+
148
+ @classmethod
149
+ def _delete(cls, page: "PageObject", trigger: PageTrigger) -> None:
150
+ """
151
+ Delete an action from the page.
152
+
153
+ Args:
154
+ page: The page to delete the action.
155
+ trigger: An open or close trigger.
156
+ """
157
+ if "/AA" not in page:
158
+ return
159
+
160
+ trigger_name = trigger._name_object
161
+
162
+ additional_actions = cast(DictionaryObject, page["/AA"])
163
+
164
+ if trigger_name not in additional_actions:
165
+ return
166
+
167
+ del additional_actions[trigger_name]
168
+
169
+ if not additional_actions:
170
+ del page["/AA"]
171
+
172
+
173
+ class JavaScript(Action):
174
+ """
175
+ Upon invocation of an ECMAScript action, a PDF processor shall execute a
176
+ script that is written in the ECMAScript programming language. ECMAScript
177
+ extensions described in ISO/DIS 21757-1 shall also be allowed.
178
+
179
+ Args:
180
+ java_script: A text string containing the ECMAScript script to be executed.
181
+ """
182
+
183
+ def __init__(self, java_script: str) -> None:
184
+ """Initialize JavaScript with a string."""
185
+ super().__init__()
186
+ self[NameObject("/S")] = NameObject("/JavaScript")
187
+ self[NameObject("/JS")] = TextStringObject(java_script)
.venv/lib/python3.13/site-packages/pypdf/annotations/__init__.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ PDF specifies several annotation types which pypdf makes available here.
3
+
4
+ The names of the annotations and their attributes do not reflect the names in
5
+ the specification in all cases. For example, the PDF standard defines a
6
+ 'Square' annotation that does not actually need to be square. For this reason,
7
+ pypdf calls it 'Rectangle'.
8
+
9
+ At their core, all annotation types are DictionaryObjects. That means if pypdf
10
+ does not implement a feature, users can easily extend the given functionality.
11
+ """
12
+
13
+
14
+ from ._base import NO_FLAGS, AnnotationDictionary
15
+ from ._markup_annotations import (
16
+ Ellipse,
17
+ FreeText,
18
+ Highlight,
19
+ Line,
20
+ MarkupAnnotation,
21
+ Polygon,
22
+ PolyLine,
23
+ Rectangle,
24
+ Text,
25
+ )
26
+ from ._non_markup_annotations import Link, Popup
27
+
28
+ __all__ = [
29
+ "NO_FLAGS",
30
+ "AnnotationDictionary",
31
+ "Ellipse",
32
+ "FreeText",
33
+ "Highlight",
34
+ "Line",
35
+ "Link",
36
+ "MarkupAnnotation",
37
+ "PolyLine",
38
+ "Polygon",
39
+ "Popup",
40
+ "Rectangle",
41
+ "Text",
42
+ ]
.venv/lib/python3.13/site-packages/pypdf/annotations/_base.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC
2
+
3
+ from ..constants import AnnotationFlag
4
+ from ..generic import NameObject, NumberObject
5
+ from ..generic._data_structures import DictionaryObject
6
+
7
+
8
+ class AnnotationDictionary(DictionaryObject, ABC):
9
+ def __init__(self) -> None:
10
+ super().__init__()
11
+
12
+ from ..generic._base import NameObject # noqa: PLC0415
13
+
14
+ # /Rect should not be added here as Polygon and PolyLine can automatically set it
15
+ self[NameObject("/Type")] = NameObject("/Annot")
16
+ # The flags were NOT added to the constructor on purpose:
17
+ # We expect that most users don't want to change the default.
18
+ # If they do, they can use the property. The default is 0.
19
+
20
+ @property
21
+ def flags(self) -> AnnotationFlag:
22
+ return AnnotationFlag(self.get(NameObject("/F"), 0))
23
+
24
+ @flags.setter
25
+ def flags(self, value: AnnotationFlag) -> None:
26
+ self[NameObject("/F")] = NumberObject(value)
27
+
28
+
29
+ NO_FLAGS = AnnotationFlag(0)
.venv/lib/python3.13/site-packages/pypdf/annotations/_markup_annotations.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import uuid
3
+ from abc import ABC
4
+ from typing import Any, Literal, Optional, Union
5
+
6
+ from ..constants import AnnotationFlag
7
+ from ..generic import ArrayObject, DictionaryObject
8
+ from ..generic._base import (
9
+ BooleanObject,
10
+ FloatObject,
11
+ IndirectObject,
12
+ NameObject,
13
+ NumberObject,
14
+ TextStringObject,
15
+ )
16
+ from ..generic._rectangle import RectangleObject
17
+ from ..generic._utils import hex_to_rgb
18
+ from ._base import NO_FLAGS, AnnotationDictionary
19
+
20
+ if sys.version_info[:2] >= (3, 10):
21
+ from typing import TypeAlias
22
+ else:
23
+ # PEP 613 introduced typing.TypeAlias with Python 3.10
24
+ # For older Python versions, the backport typing_extensions is necessary:
25
+ from typing_extensions import TypeAlias
26
+
27
+
28
+ Vertex: TypeAlias = tuple[float, float]
29
+
30
+
31
+ def _get_bounding_rectangle(vertices: list[Vertex]) -> RectangleObject:
32
+ x_min, y_min = vertices[0][0], vertices[0][1]
33
+ x_max, y_max = vertices[0][0], vertices[0][1]
34
+ for x, y in vertices:
35
+ x_min = min(x_min, x)
36
+ y_min = min(y_min, y)
37
+ x_max = max(x_max, x)
38
+ y_max = max(y_max, y)
39
+ return RectangleObject((x_min, y_min, x_max, y_max))
40
+
41
+
42
+ class MarkupAnnotation(AnnotationDictionary, ABC):
43
+ """
44
+ Base class for all markup annotations.
45
+
46
+ Args:
47
+ title_bar: Text to be displayed in the title bar of the annotation;
48
+ by convention this is the name of the author
49
+ in_reply_to: The annotation that this annotation is "in reply to"
50
+ (PDF 1.5). Can be either an annotation (previously added using
51
+ :meth:`~pypdf.PdfWriter.add_annotation`) or a reference to the
52
+ target annotation.
53
+ reply_type: The relationship between this annotation and the one
54
+ specified by ``in_reply_to``. Either ``"R"`` (a reply, default)
55
+ or ``"Group"`` (grouped with the parent annotation). Raises
56
+ ``ValueError`` if a non-default value is provided without
57
+ ``in_reply_to``.
58
+ annotation_name: A text string uniquely identifying this annotation
59
+ among all annotations on its page. Automatically generated when
60
+ ``in_reply_to`` is set and no name is provided. Raises
61
+ ``ValueError`` if provided without ``in_reply_to``.
62
+
63
+ """
64
+
65
+ def __init__(
66
+ self,
67
+ *,
68
+ title_bar: Optional[str] = None,
69
+ in_reply_to: Optional[Union[DictionaryObject, IndirectObject]] = None,
70
+ reply_type: Literal["R", "Group"] = "R",
71
+ annotation_name: Optional[str] = None,
72
+ ) -> None:
73
+ if title_bar is not None:
74
+ self[NameObject("/T")] = TextStringObject(title_bar)
75
+ if annotation_name is not None and in_reply_to is None:
76
+ raise ValueError(
77
+ "annotation_name is only supported when in_reply_to is set"
78
+ )
79
+ if reply_type != "R" and in_reply_to is None:
80
+ raise ValueError(
81
+ "reply_type is only meaningful when in_reply_to is set"
82
+ )
83
+ if in_reply_to is not None:
84
+ if isinstance(in_reply_to, IndirectObject):
85
+ ref: IndirectObject = in_reply_to
86
+ else:
87
+ indirect_ref = getattr(in_reply_to, "indirect_reference", None)
88
+ if not isinstance(indirect_ref, IndirectObject):
89
+ raise ValueError(
90
+ "in_reply_to must be a registered annotation "
91
+ "(added via writer.add_annotation() first)"
92
+ )
93
+ ref = indirect_ref
94
+ self[NameObject("/IRT")] = ref
95
+ self[NameObject("/RT")] = NameObject(f"/{reply_type}")
96
+ if annotation_name is None:
97
+ annotation_name = str(uuid.uuid4())
98
+ self[NameObject("/NM")] = TextStringObject(annotation_name)
99
+
100
+
101
+ class Text(MarkupAnnotation):
102
+ """
103
+ A text annotation.
104
+
105
+ Args:
106
+ rect: array of four integers ``[xLL, yLL, xUR, yUR]``
107
+ specifying the clickable rectangular area
108
+ text: The text that is added to the document
109
+ open:
110
+ flags:
111
+
112
+ """
113
+
114
+ def __init__(
115
+ self,
116
+ *,
117
+ rect: Union[RectangleObject, tuple[float, float, float, float]],
118
+ text: str,
119
+ open: bool = False,
120
+ flags: int = NO_FLAGS,
121
+ **kwargs: Any,
122
+ ) -> None:
123
+ super().__init__(**kwargs)
124
+ self[NameObject("/Subtype")] = NameObject("/Text")
125
+ self[NameObject("/Rect")] = RectangleObject(rect)
126
+ self[NameObject("/Contents")] = TextStringObject(text)
127
+ self[NameObject("/Open")] = BooleanObject(open)
128
+ self[NameObject("/Flags")] = NumberObject(flags)
129
+
130
+
131
+ class FreeText(MarkupAnnotation):
132
+ """A FreeText annotation"""
133
+
134
+ def __init__(
135
+ self,
136
+ *,
137
+ text: str,
138
+ rect: Union[RectangleObject, tuple[float, float, float, float]],
139
+ font: str = "Helvetica",
140
+ bold: bool = False,
141
+ italic: bool = False,
142
+ font_size: str = "14pt",
143
+ font_color: str = "000000",
144
+ border_color: Optional[str] = "000000",
145
+ background_color: Optional[str] = "ffffff",
146
+ **kwargs: Any,
147
+ ) -> None:
148
+ super().__init__(**kwargs)
149
+ self[NameObject("/Subtype")] = NameObject("/FreeText")
150
+ self[NameObject("/Rect")] = RectangleObject(rect)
151
+
152
+ # Table 225 of the 1.7 reference ("CSS2 style attributes used in rich text strings")
153
+ font_str = "font: "
154
+ if italic:
155
+ font_str = f"{font_str}italic "
156
+ else:
157
+ font_str = f"{font_str}normal "
158
+ if bold:
159
+ font_str = f"{font_str}bold "
160
+ else:
161
+ font_str = f"{font_str}normal "
162
+ font_str = f"{font_str}{font_size} {font}"
163
+ font_str = f"{font_str};text-align:left;color:#{font_color}"
164
+
165
+ default_appearance_string = ""
166
+ if border_color:
167
+ for st in hex_to_rgb(border_color):
168
+ default_appearance_string = f"{default_appearance_string}{st} "
169
+ default_appearance_string = f"{default_appearance_string}rg"
170
+
171
+ self.update(
172
+ {
173
+ NameObject("/Subtype"): NameObject("/FreeText"),
174
+ NameObject("/Rect"): RectangleObject(rect),
175
+ NameObject("/Contents"): TextStringObject(text),
176
+ # font size color
177
+ NameObject("/DS"): TextStringObject(font_str),
178
+ NameObject("/DA"): TextStringObject(default_appearance_string),
179
+ }
180
+ )
181
+ if border_color is None:
182
+ # Border Style
183
+ self[NameObject("/BS")] = DictionaryObject(
184
+ {
185
+ # width of 0 means no border
186
+ NameObject("/W"): NumberObject(0)
187
+ }
188
+ )
189
+ if background_color is not None:
190
+ self[NameObject("/C")] = ArrayObject(
191
+ [FloatObject(n) for n in hex_to_rgb(background_color)]
192
+ )
193
+
194
+
195
+ class Line(MarkupAnnotation):
196
+ def __init__(
197
+ self,
198
+ p1: Vertex,
199
+ p2: Vertex,
200
+ rect: Union[RectangleObject, tuple[float, float, float, float]],
201
+ text: str = "",
202
+ **kwargs: Any,
203
+ ) -> None:
204
+ super().__init__(**kwargs)
205
+ self.update(
206
+ {
207
+ NameObject("/Subtype"): NameObject("/Line"),
208
+ NameObject("/Rect"): RectangleObject(rect),
209
+ NameObject("/L"): ArrayObject(
210
+ [
211
+ FloatObject(p1[0]),
212
+ FloatObject(p1[1]),
213
+ FloatObject(p2[0]),
214
+ FloatObject(p2[1]),
215
+ ]
216
+ ),
217
+ NameObject("/LE"): ArrayObject(
218
+ [
219
+ NameObject("/None"),
220
+ NameObject("/None"),
221
+ ]
222
+ ),
223
+ NameObject("/IC"): ArrayObject(
224
+ [
225
+ FloatObject(0.5),
226
+ FloatObject(0.5),
227
+ FloatObject(0.5),
228
+ ]
229
+ ),
230
+ NameObject("/Contents"): TextStringObject(text),
231
+ }
232
+ )
233
+
234
+
235
+ class PolyLine(MarkupAnnotation):
236
+ def __init__(
237
+ self,
238
+ vertices: list[Vertex],
239
+ **kwargs: Any,
240
+ ) -> None:
241
+ super().__init__(**kwargs)
242
+ if len(vertices) == 0:
243
+ raise ValueError("A polyline needs at least 1 vertex with two coordinates")
244
+ coord_list = []
245
+ for x, y in vertices:
246
+ coord_list.append(NumberObject(x))
247
+ coord_list.append(NumberObject(y))
248
+ self.update(
249
+ {
250
+ NameObject("/Subtype"): NameObject("/PolyLine"),
251
+ NameObject("/Vertices"): ArrayObject(coord_list),
252
+ NameObject("/Rect"): RectangleObject(_get_bounding_rectangle(vertices)),
253
+ }
254
+ )
255
+
256
+
257
+ class Rectangle(MarkupAnnotation):
258
+ def __init__(
259
+ self,
260
+ rect: Union[RectangleObject, tuple[float, float, float, float]],
261
+ *,
262
+ interior_color: Optional[str] = None,
263
+ **kwargs: Any,
264
+ ) -> None:
265
+ super().__init__(**kwargs)
266
+ self.update(
267
+ {
268
+ NameObject("/Type"): NameObject("/Annot"),
269
+ NameObject("/Subtype"): NameObject("/Square"),
270
+ NameObject("/Rect"): RectangleObject(rect),
271
+ }
272
+ )
273
+
274
+ if interior_color:
275
+ self[NameObject("/IC")] = ArrayObject(
276
+ [FloatObject(n) for n in hex_to_rgb(interior_color)]
277
+ )
278
+
279
+
280
+ class Highlight(MarkupAnnotation):
281
+ def __init__(
282
+ self,
283
+ *,
284
+ rect: Union[RectangleObject, tuple[float, float, float, float]],
285
+ quad_points: ArrayObject,
286
+ highlight_color: str = "ff0000",
287
+ printing: bool = False,
288
+ **kwargs: Any,
289
+ ) -> None:
290
+ super().__init__(**kwargs)
291
+ self.update(
292
+ {
293
+ NameObject("/Subtype"): NameObject("/Highlight"),
294
+ NameObject("/Rect"): RectangleObject(rect),
295
+ NameObject("/QuadPoints"): quad_points,
296
+ NameObject("/C"): ArrayObject(
297
+ [FloatObject(n) for n in hex_to_rgb(highlight_color)]
298
+ ),
299
+ }
300
+ )
301
+ if printing:
302
+ self.flags = AnnotationFlag.PRINT
303
+
304
+
305
+ class Ellipse(MarkupAnnotation):
306
+ def __init__(
307
+ self,
308
+ rect: Union[RectangleObject, tuple[float, float, float, float]],
309
+ *,
310
+ interior_color: Optional[str] = None,
311
+ **kwargs: Any,
312
+ ) -> None:
313
+ super().__init__(**kwargs)
314
+
315
+ self.update(
316
+ {
317
+ NameObject("/Type"): NameObject("/Annot"),
318
+ NameObject("/Subtype"): NameObject("/Circle"),
319
+ NameObject("/Rect"): RectangleObject(rect),
320
+ }
321
+ )
322
+
323
+ if interior_color:
324
+ self[NameObject("/IC")] = ArrayObject(
325
+ [FloatObject(n) for n in hex_to_rgb(interior_color)]
326
+ )
327
+
328
+
329
+ class Polygon(MarkupAnnotation):
330
+ def __init__(
331
+ self,
332
+ vertices: list[tuple[float, float]],
333
+ **kwargs: Any,
334
+ ) -> None:
335
+ super().__init__(**kwargs)
336
+ if len(vertices) == 0:
337
+ raise ValueError("A polygon needs at least 1 vertex with two coordinates")
338
+
339
+ coord_list = []
340
+ for x, y in vertices:
341
+ coord_list.append(NumberObject(x))
342
+ coord_list.append(NumberObject(y))
343
+ self.update(
344
+ {
345
+ NameObject("/Type"): NameObject("/Annot"),
346
+ NameObject("/Subtype"): NameObject("/Polygon"),
347
+ NameObject("/Vertices"): ArrayObject(coord_list),
348
+ NameObject("/IT"): NameObject("/PolygonCloud"),
349
+ NameObject("/Rect"): RectangleObject(_get_bounding_rectangle(vertices)),
350
+ }
351
+ )
.venv/lib/python3.13/site-packages/pypdf/annotations/_non_markup_annotations.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TYPE_CHECKING, Any, Optional, Union
2
+
3
+ from ..generic._base import (
4
+ BooleanObject,
5
+ NameObject,
6
+ NumberObject,
7
+ TextStringObject,
8
+ )
9
+ from ..generic._data_structures import ArrayObject, DictionaryObject
10
+ from ..generic._fit import DEFAULT_FIT, Fit
11
+ from ..generic._rectangle import RectangleObject
12
+ from ._base import AnnotationDictionary
13
+
14
+
15
+ class Link(AnnotationDictionary):
16
+ def __init__(
17
+ self,
18
+ *,
19
+ rect: Union[RectangleObject, tuple[float, float, float, float]],
20
+ border: Optional[ArrayObject] = None,
21
+ url: Optional[str] = None,
22
+ target_page_index: Optional[int] = None,
23
+ fit: Fit = DEFAULT_FIT,
24
+ **kwargs: Any,
25
+ ) -> None:
26
+ super().__init__(**kwargs)
27
+ if TYPE_CHECKING:
28
+ from ..types import BorderArrayType # noqa: PLC0415
29
+
30
+ is_external = url is not None
31
+ is_internal = target_page_index is not None
32
+ if not is_external and not is_internal:
33
+ raise ValueError(
34
+ "Either 'url' or 'target_page_index' have to be provided. Both were None."
35
+ )
36
+ if is_external and is_internal:
37
+ raise ValueError(
38
+ "Either 'url' or 'target_page_index' have to be provided. "
39
+ f"{url=}, {target_page_index=}"
40
+ )
41
+
42
+ border_arr: BorderArrayType
43
+ if border is not None:
44
+ border_arr = [NumberObject(n) for n in border[:3]]
45
+ if len(border) == 4:
46
+ dash_pattern = ArrayObject([NumberObject(n) for n in border[3]])
47
+ border_arr.append(dash_pattern)
48
+ else:
49
+ border_arr = [NumberObject(0)] * 3
50
+
51
+ self.update(
52
+ {
53
+ NameObject("/Type"): NameObject("/Annot"),
54
+ NameObject("/Subtype"): NameObject("/Link"),
55
+ NameObject("/Rect"): RectangleObject(rect),
56
+ NameObject("/Border"): ArrayObject(border_arr),
57
+ }
58
+ )
59
+ if is_external:
60
+ self[NameObject("/A")] = DictionaryObject(
61
+ {
62
+ NameObject("/S"): NameObject("/URI"),
63
+ NameObject("/Type"): NameObject("/Action"),
64
+ NameObject("/URI"): TextStringObject(url),
65
+ }
66
+ )
67
+ if is_internal:
68
+ # This needs to be updated later!
69
+ dest_deferred = DictionaryObject(
70
+ {
71
+ "target_page_index": NumberObject(target_page_index),
72
+ "fit": NameObject(fit.fit_type),
73
+ "fit_args": fit.fit_args,
74
+ }
75
+ )
76
+ self[NameObject("/Dest")] = dest_deferred
77
+
78
+
79
+ class Popup(AnnotationDictionary):
80
+ def __init__(
81
+ self,
82
+ *,
83
+ rect: Union[RectangleObject, tuple[float, float, float, float]],
84
+ parent: Optional[DictionaryObject] = None,
85
+ open: bool = False,
86
+ **kwargs: Any,
87
+ ) -> None:
88
+ super().__init__(**kwargs)
89
+ self.update(
90
+ {
91
+ NameObject("/Subtype"): NameObject("/Popup"),
92
+ NameObject("/Rect"): RectangleObject(rect),
93
+ NameObject("/Open"): BooleanObject(open),
94
+ }
95
+ )
96
+ if parent:
97
+ # This needs to be an indirect object
98
+ try:
99
+ self[NameObject("/Parent")] = parent.indirect_reference
100
+ except AttributeError:
101
+ from .._utils import logger_warning # noqa: PLC0415
102
+
103
+ logger_warning(
104
+ "Unregistered Parent object : No Parent field set",
105
+ source=__name__,
106
+ )
.venv/lib/python3.13/site-packages/pypdf/constants.py ADDED
@@ -0,0 +1,817 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Various constants, enums, and flags to aid readability."""
2
+
3
+ import sys
4
+ from enum import Enum, IntFlag, auto, unique
5
+
6
+ if sys.version_info >= (3, 11):
7
+ from enum import StrEnum
8
+ else:
9
+ class StrEnum(str, Enum):
10
+ def __str__(self) -> str:
11
+ return str(self.value)
12
+
13
+
14
+ class Core:
15
+ """Keywords that don't quite belong anywhere else."""
16
+
17
+ OUTLINES = "/Outlines"
18
+ THREADS = "/Threads"
19
+ PAGE = "/Page"
20
+ PAGES = "/Pages"
21
+ CATALOG = "/Catalog"
22
+
23
+
24
+ class TrailerKeys:
25
+ SIZE = "/Size"
26
+ PREV = "/Prev"
27
+ ROOT = "/Root"
28
+ ENCRYPT = "/Encrypt"
29
+ INFO = "/Info"
30
+ ID = "/ID"
31
+
32
+
33
+ class CatalogAttributes:
34
+ NAMES = "/Names"
35
+ DESTS = "/Dests"
36
+
37
+
38
+ class EncryptionDictAttributes:
39
+ """
40
+ Additional encryption dictionary entries for the standard security handler.
41
+
42
+ Table 3.19, Page 122.
43
+ Table 21 of the 2.0 manual.
44
+ """
45
+
46
+ R = "/R" # number, required; revision of the standard security handler
47
+ O = "/O" # 32-byte string, required # noqa: E741
48
+ U = "/U" # 32-byte string, required
49
+ P = "/P" # integer flag, required; permitted operations
50
+ ENCRYPT_METADATA = "/EncryptMetadata" # boolean flag, optional
51
+
52
+
53
+ class UserAccessPermissions(IntFlag):
54
+ """
55
+ Table 3.20 User access permissions.
56
+ Table 22 of the 2.0 manual.
57
+ """
58
+
59
+ R1 = 1
60
+ R2 = 2
61
+ PRINT = 4
62
+ MODIFY = 8
63
+ EXTRACT = 16
64
+ ADD_OR_MODIFY = 32
65
+ R7 = 64
66
+ R8 = 128
67
+ FILL_FORM_FIELDS = 256
68
+ EXTRACT_TEXT_AND_GRAPHICS = 512
69
+ ASSEMBLE_DOC = 1024
70
+ PRINT_TO_REPRESENTATION = 2048
71
+ R13 = 2**12
72
+ R14 = 2**13
73
+ R15 = 2**14
74
+ R16 = 2**15
75
+ R17 = 2**16
76
+ R18 = 2**17
77
+ R19 = 2**18
78
+ R20 = 2**19
79
+ R21 = 2**20
80
+ R22 = 2**21
81
+ R23 = 2**22
82
+ R24 = 2**23
83
+ R25 = 2**24
84
+ R26 = 2**25
85
+ R27 = 2**26
86
+ R28 = 2**27
87
+ R29 = 2**28
88
+ R30 = 2**29
89
+ R31 = 2**30
90
+ R32 = 2**31
91
+
92
+ @classmethod
93
+ def _is_reserved(cls, name: str) -> bool:
94
+ """Check if the given name corresponds to a reserved flag entry."""
95
+ return name.startswith("R") and name[1:].isdigit()
96
+
97
+ @classmethod
98
+ def _is_active(cls, name: str) -> bool:
99
+ """Check if the given reserved name defaults to 1 = active."""
100
+ return name not in {"R1", "R2"}
101
+
102
+ def to_dict(self) -> dict[str, bool]:
103
+ """Convert the given flag value to a corresponding verbose name mapping."""
104
+ result: dict[str, bool] = {}
105
+ for name, flag in UserAccessPermissions.__members__.items():
106
+ if UserAccessPermissions._is_reserved(name):
107
+ continue
108
+ result[name.lower()] = (self & flag) == flag
109
+ return result
110
+
111
+ @classmethod
112
+ def from_dict(cls, value: dict[str, bool]) -> "UserAccessPermissions":
113
+ """Convert the verbose name mapping to the corresponding flag value."""
114
+ value_copy = value.copy()
115
+ result = cls(0)
116
+ for name, flag in cls.__members__.items():
117
+ if cls._is_reserved(name):
118
+ # Reserved names have a required value. Use it.
119
+ if cls._is_active(name):
120
+ result |= flag
121
+ continue
122
+ is_active = value_copy.pop(name.lower(), False)
123
+ if is_active:
124
+ result |= flag
125
+ if value_copy:
126
+ raise ValueError(f"Unknown dictionary keys: {value_copy!r}")
127
+ return result
128
+
129
+ @classmethod
130
+ def all(cls) -> "UserAccessPermissions":
131
+ return cls((2**32 - 1) - cls.R1 - cls.R2)
132
+
133
+
134
+ class Resources:
135
+ """
136
+ Table 3.30 Entries in a resource dictionary.
137
+ Table 34 in the 2.0 reference.
138
+ """
139
+
140
+ EXT_G_STATE = "/ExtGState" # dictionary, optional
141
+ COLOR_SPACE = "/ColorSpace" # dictionary, optional
142
+ PATTERN = "/Pattern" # dictionary, optional
143
+ SHADING = "/Shading" # dictionary, optional
144
+ XOBJECT = "/XObject" # dictionary, optional
145
+ FONT = "/Font" # dictionary, optional
146
+ PROC_SET = "/ProcSet" # array, optional
147
+ PROPERTIES = "/Properties" # dictionary, optional
148
+
149
+
150
+ class PagesAttributes:
151
+ """§7.7.3.2 of the 1.7 and 2.0 reference."""
152
+
153
+ TYPE = "/Type" # name, required; must be /Pages
154
+ PARENT = "/Parent" # dictionary, required; indirect reference to pages object
155
+ KIDS = "/Kids" # array, required; List of indirect references
156
+ COUNT = "/Count"
157
+ # integer, required; the number of leaf nodes (page objects)
158
+ # that are descendants of this node within the page tree
159
+
160
+
161
+ class PageAttributes:
162
+ """§7.7.3.3 of the 1.7 and 2.0 reference."""
163
+
164
+ TYPE = "/Type" # name, required; must be /Page
165
+ PARENT = "/Parent" # dictionary, required; a pages object
166
+ LAST_MODIFIED = (
167
+ "/LastModified" # date, optional; date and time of last modification
168
+ )
169
+ RESOURCES = "/Resources" # dictionary, required if there are any
170
+ MEDIABOX = "/MediaBox" # rectangle, required; rectangle specifying page size
171
+ CROPBOX = "/CropBox" # rectangle, optional
172
+ BLEEDBOX = "/BleedBox" # rectangle, optional
173
+ TRIMBOX = "/TrimBox" # rectangle, optional
174
+ ARTBOX = "/ArtBox" # rectangle, optional
175
+ BOX_COLOR_INFO = "/BoxColorInfo" # dictionary, optional
176
+ CONTENTS = "/Contents" # stream or array, optional
177
+ ROTATE = "/Rotate" # integer, optional; page rotation in degrees
178
+ GROUP = "/Group" # dictionary, optional; page group
179
+ THUMB = "/Thumb" # stream, optional; indirect reference to image of the page
180
+ B = "/B" # array, optional
181
+ DUR = "/Dur" # number, optional
182
+ TRANS = "/Trans" # dictionary, optional
183
+ ANNOTS = "/Annots" # array, optional; an array of annotations
184
+ AA = "/AA" # dictionary, optional
185
+ METADATA = "/Metadata" # stream, optional
186
+ PIECE_INFO = "/PieceInfo" # dictionary, optional
187
+ STRUCT_PARENTS = "/StructParents" # integer, optional
188
+ ID = "/ID" # byte string, optional
189
+ PZ = "/PZ" # number, optional
190
+ SEPARATION_INFO = "/SeparationInfo" # dictionary, optional
191
+ TABS = "/Tabs" # name, optional
192
+ TEMPLATE_INSTANTIATED = "/TemplateInstantiated" # name, optional
193
+ PRES_STEPS = "/PresSteps" # dictionary, optional
194
+ USER_UNIT = "/UserUnit" # number, optional
195
+ VP = "/VP" # dictionary, optional
196
+ AF = "/AF" # array of dictionaries, optional
197
+ OUTPUT_INTENTS = "/OutputIntents" # array, optional
198
+ D_PART = "/DPart" # dictionary, required, if this page is within the range of a DPart, not permitted otherwise
199
+
200
+
201
+ class FileSpecificationDictionaryEntries:
202
+ """Table 3.41 Entries in a file specification dictionary."""
203
+
204
+ Type = "/Type"
205
+ FS = "/FS" # The name of the file system to be used to interpret this file specification
206
+ F = "/F" # A file specification string of the form described in §3.10.1
207
+ UF = "/UF" # A Unicode string of the file as described in §3.10.1
208
+ DOS = "/DOS"
209
+ Mac = "/Mac"
210
+ Unix = "/Unix"
211
+ ID = "/ID"
212
+ V = "/V"
213
+ EF = "/EF" # dictionary, containing a subset of the keys F, UF, DOS, Mac, and Unix
214
+ RF = "/RF" # dictionary, containing arrays of /EmbeddedFile
215
+ DESC = "/Desc" # description of the file
216
+ Cl = "/Cl"
217
+
218
+
219
+ class StreamAttributes:
220
+ """
221
+ Table 4.2.
222
+ Table 5 in the 2.0 reference.
223
+ """
224
+
225
+ LENGTH = "/Length" # integer, required
226
+ FILTER = "/Filter" # name or array of names, optional
227
+ DECODE_PARMS = "/DecodeParms" # variable, optional; /DecodeParams is wrong
228
+
229
+
230
+ @unique
231
+ class FilterTypes(StrEnum):
232
+ """§7.4 of the 1.7 and 2.0 references."""
233
+
234
+ ASCII_HEX_DECODE = "/ASCIIHexDecode" # abbreviation: AHx
235
+ ASCII_85_DECODE = "/ASCII85Decode" # abbreviation: A85
236
+ LZW_DECODE = "/LZWDecode" # abbreviation: LZW
237
+ FLATE_DECODE = "/FlateDecode" # abbreviation: Fl
238
+ RUN_LENGTH_DECODE = "/RunLengthDecode" # abbreviation: RL
239
+ CCITT_FAX_DECODE = "/CCITTFaxDecode" # abbreviation: CCF
240
+ DCT_DECODE = "/DCTDecode" # abbreviation: DCT
241
+ JPX_DECODE = "/JPXDecode"
242
+ JBIG2_DECODE = "/JBIG2Decode"
243
+
244
+
245
+ class FilterTypeAbbreviations:
246
+ """§8.9.7 of the 1.7 and 2.0 references."""
247
+
248
+ AHx = "/AHx"
249
+ A85 = "/A85"
250
+ LZW = "/LZW"
251
+ FL = "/Fl"
252
+ RL = "/RL"
253
+ CCF = "/CCF"
254
+ DCT = "/DCT"
255
+
256
+
257
+ class LzwFilterParameters:
258
+ """
259
+ Table 4.4.
260
+ Table 8 in the 2.0 reference.
261
+ """
262
+
263
+ PREDICTOR = "/Predictor" # integer
264
+ COLORS = "/Colors" # integer
265
+ BITS_PER_COMPONENT = "/BitsPerComponent" # integer
266
+ COLUMNS = "/Columns" # integer
267
+ EARLY_CHANGE = "/EarlyChange" # integer
268
+
269
+
270
+ class CcittFaxDecodeParameters:
271
+ """
272
+ Table 4.5.
273
+ Table 11 in the 2.0 reference.
274
+ """
275
+
276
+ K = "/K" # integer
277
+ END_OF_LINE = "/EndOfLine" # boolean
278
+ ENCODED_BYTE_ALIGN = "/EncodedByteAlign" # boolean
279
+ COLUMNS = "/Columns" # integer
280
+ ROWS = "/Rows" # integer
281
+ END_OF_BLOCK = "/EndOfBlock" # boolean
282
+ BLACK_IS_1 = "/BlackIs1" # boolean
283
+ DAMAGED_ROWS_BEFORE_ERROR = "/DamagedRowsBeforeError" # integer
284
+
285
+
286
+ class ImageAttributes:
287
+ """§11.6.5 of the 1.7 and 2.0 references."""
288
+
289
+ TYPE = "/Type" # name, required; must be /XObject
290
+ SUBTYPE = "/Subtype" # name, required; must be /Image
291
+ NAME = "/Name" # name, required
292
+ WIDTH = "/Width" # integer, required
293
+ HEIGHT = "/Height" # integer, required
294
+ BITS_PER_COMPONENT = "/BitsPerComponent" # integer, required
295
+ COLOR_SPACE = "/ColorSpace" # name, required
296
+ DECODE = "/Decode" # array, optional
297
+ INTENT = "/Intent" # string, optional
298
+ INTERPOLATE = "/Interpolate" # boolean, optional
299
+ IMAGE_MASK = "/ImageMask" # boolean, optional
300
+ MASK = "/Mask" # 1-bit image mask stream
301
+ S_MASK = "/SMask" # dictionary or name, optional
302
+
303
+
304
+ class ColorSpaces:
305
+ DEVICE_RGB = "/DeviceRGB"
306
+ DEVICE_CMYK = "/DeviceCMYK"
307
+ DEVICE_GRAY = "/DeviceGray"
308
+
309
+
310
+ class TypArguments:
311
+ """Table 8.2 of the PDF 1.7 reference."""
312
+
313
+ LEFT = "/Left"
314
+ RIGHT = "/Right"
315
+ BOTTOM = "/Bottom"
316
+ TOP = "/Top"
317
+
318
+
319
+ class TypFitArguments:
320
+ """Table 8.2 of the PDF 1.7 reference."""
321
+
322
+ XYZ = "/XYZ"
323
+ FIT = "/Fit"
324
+ FIT_H = "/FitH"
325
+ FIT_V = "/FitV"
326
+ FIT_R = "/FitR"
327
+ FIT_B = "/FitB"
328
+ FIT_BH = "/FitBH"
329
+ FIT_BV = "/FitBV"
330
+
331
+
332
+ class GoToActionArguments:
333
+ S = "/S" # name, required: type of action
334
+ D = "/D" # name, byte string, or array, required: destination to jump to
335
+ SD = "/SD" # array, optional: structure destination to jump to
336
+
337
+
338
+ class AnnotationDictionaryAttributes:
339
+ """Table 8.15 Entries common to all annotation dictionaries."""
340
+
341
+ Type = "/Type"
342
+ Subtype = "/Subtype"
343
+ Rect = "/Rect"
344
+ Contents = "/Contents"
345
+ P = "/P"
346
+ NM = "/NM"
347
+ M = "/M"
348
+ F = "/F"
349
+ AP = "/AP"
350
+ AS = "/AS"
351
+ DA = "/DA"
352
+ Border = "/Border"
353
+ C = "/C"
354
+ StructParent = "/StructParent"
355
+ OC = "/OC"
356
+
357
+
358
+ class InteractiveFormDictEntries:
359
+ Fields = "/Fields"
360
+ NeedAppearances = "/NeedAppearances"
361
+ SigFlags = "/SigFlags"
362
+ CO = "/CO"
363
+ DR = "/DR"
364
+ DA = "/DA"
365
+ Q = "/Q"
366
+ XFA = "/XFA"
367
+
368
+
369
+ class FieldDictionaryAttributes:
370
+ """
371
+ Entries common to all field dictionaries (Table 8.69 PDF 1.7 reference)
372
+ (*very partially documented here*).
373
+
374
+ FFBits provides the constants used for `/Ff` from Table 8.70/8.75/8.77/8.79
375
+ """
376
+
377
+ FT = "/FT" # name, required for terminal fields
378
+ Parent = "/Parent" # dictionary, required for children
379
+ Kids = "/Kids" # array, sometimes required
380
+ T = "/T" # text string, optional
381
+ TU = "/TU" # text string, optional
382
+ TM = "/TM" # text string, optional
383
+ Ff = "/Ff" # integer, optional
384
+ V = "/V" # text string or array, optional
385
+ DV = "/DV" # text string, optional
386
+ AA = "/AA" # dictionary, optional
387
+ Opt = "/Opt" # array, optional
388
+
389
+ class FfBits(IntFlag):
390
+ """
391
+ Ease building /Ff flags
392
+ Some entries may be specific to:
393
+
394
+ * Text (Tx) (Table 8.75 PDF 1.7 reference)
395
+ * Buttons (Btn) (Table 8.77 PDF 1.7 reference)
396
+ * Choice (Ch) (Table 8.79 PDF 1.7 reference)
397
+ """
398
+
399
+ ReadOnly = 1 << 0
400
+ """common to Tx/Btn/Ch in Table 8.70"""
401
+ Required = 1 << 1
402
+ """common to Tx/Btn/Ch in Table 8.70"""
403
+ NoExport = 1 << 2
404
+ """common to Tx/Btn/Ch in Table 8.70"""
405
+
406
+ Multiline = 1 << 12
407
+ """Tx"""
408
+ Password = 1 << 13
409
+ """Tx"""
410
+
411
+ NoToggleToOff = 1 << 14
412
+ """Btn"""
413
+ Radio = 1 << 15
414
+ """Btn"""
415
+ Pushbutton = 1 << 16
416
+ """Btn"""
417
+
418
+ Combo = 1 << 17
419
+ """Ch"""
420
+ Edit = 1 << 18
421
+ """Ch"""
422
+ Sort = 1 << 19
423
+ """Ch"""
424
+
425
+ FileSelect = 1 << 20
426
+ """Tx"""
427
+
428
+ MultiSelect = 1 << 21
429
+ """Tx"""
430
+
431
+ DoNotSpellCheck = 1 << 22
432
+ """Tx/Ch"""
433
+ DoNotScroll = 1 << 23
434
+ """Tx"""
435
+ Comb = 1 << 24
436
+ """Tx"""
437
+
438
+ RadiosInUnison = 1 << 25
439
+ """Btn"""
440
+
441
+ RichText = 1 << 25
442
+ """Tx"""
443
+
444
+ CommitOnSelChange = 1 << 26
445
+ """Ch"""
446
+
447
+ @classmethod
448
+ def attributes(cls) -> tuple[str, ...]:
449
+ """
450
+ Get a tuple of all the attributes present in a Field Dictionary.
451
+
452
+ This method returns a tuple of all the attribute constants defined in
453
+ the FieldDictionaryAttributes class. These attributes correspond to the
454
+ entries that are common to all field dictionaries as specified in the
455
+ PDF 1.7 reference.
456
+
457
+ Returns:
458
+ A tuple containing all the attribute constants.
459
+
460
+ """
461
+ return (
462
+ cls.TM,
463
+ cls.T,
464
+ cls.FT,
465
+ cls.Parent,
466
+ cls.TU,
467
+ cls.Ff,
468
+ cls.V,
469
+ cls.DV,
470
+ cls.Kids,
471
+ cls.AA,
472
+ )
473
+
474
+ @classmethod
475
+ def attributes_dict(cls) -> dict[str, str]:
476
+ """
477
+ Get a dictionary of attribute keys and their human-readable names.
478
+
479
+ This method returns a dictionary where the keys are the attribute
480
+ constants defined in the FieldDictionaryAttributes class and the values
481
+ are their corresponding human-readable names. These attributes
482
+ correspond to the entries that are common to all field dictionaries as
483
+ specified in the PDF 1.7 reference.
484
+
485
+ Returns:
486
+ A dictionary containing attribute keys and their names.
487
+
488
+ """
489
+ return {
490
+ cls.FT: "Field Type",
491
+ cls.Parent: "Parent",
492
+ cls.T: "Field Name",
493
+ cls.TU: "Alternate Field Name",
494
+ cls.TM: "Mapping Name",
495
+ cls.Ff: "Field Flags",
496
+ cls.V: "Value",
497
+ cls.DV: "Default Value",
498
+ }
499
+
500
+
501
+ class CheckboxRadioButtonAttributes:
502
+ """Table 8.76 Field flags common to all field types."""
503
+
504
+ Opt = "/Opt" # Options, Optional
505
+
506
+ @classmethod
507
+ def attributes(cls) -> tuple[str, ...]:
508
+ """
509
+ Get a tuple of all the attributes present in a Field Dictionary.
510
+
511
+ This method returns a tuple of all the attribute constants defined in
512
+ the CheckboxRadioButtonAttributes class. These attributes correspond to
513
+ the entries that are common to all field dictionaries as specified in
514
+ the PDF 1.7 reference.
515
+
516
+ Returns:
517
+ A tuple containing all the attribute constants.
518
+
519
+ """
520
+ return (cls.Opt,)
521
+
522
+ @classmethod
523
+ def attributes_dict(cls) -> dict[str, str]:
524
+ """
525
+ Get a dictionary of attribute keys and their human-readable names.
526
+
527
+ This method returns a dictionary where the keys are the attribute
528
+ constants defined in the CheckboxRadioButtonAttributes class and the
529
+ values are their corresponding human-readable names. These attributes
530
+ correspond to the entries that are common to all field dictionaries as
531
+ specified in the PDF 1.7 reference.
532
+
533
+ Returns:
534
+ A dictionary containing attribute keys and their names.
535
+
536
+ """
537
+ return {
538
+ cls.Opt: "Options",
539
+ }
540
+
541
+
542
+ class FieldFlag(IntFlag):
543
+ """Table 8.70 Field flags common to all field types."""
544
+
545
+ READ_ONLY = 1
546
+ REQUIRED = 2
547
+ NO_EXPORT = 4
548
+
549
+
550
+ class DocumentInformationAttributes:
551
+ """Table 10.2 Entries in the document information dictionary."""
552
+
553
+ TITLE = "/Title" # text string, optional
554
+ AUTHOR = "/Author" # text string, optional
555
+ SUBJECT = "/Subject" # text string, optional
556
+ KEYWORDS = "/Keywords" # text string, optional
557
+ CREATOR = "/Creator" # text string, optional
558
+ PRODUCER = "/Producer" # text string, optional
559
+ CREATION_DATE = "/CreationDate" # date, optional
560
+ MOD_DATE = "/ModDate" # date, optional
561
+ TRAPPED = "/Trapped" # name, optional
562
+
563
+
564
+ class PageLayouts:
565
+ """
566
+ Page 84, PDF 1.4 reference.
567
+ Page 115, PDF 2.0 reference.
568
+ """
569
+
570
+ SINGLE_PAGE = "/SinglePage"
571
+ ONE_COLUMN = "/OneColumn"
572
+ TWO_COLUMN_LEFT = "/TwoColumnLeft"
573
+ TWO_COLUMN_RIGHT = "/TwoColumnRight"
574
+ TWO_PAGE_LEFT = "/TwoPageLeft" # (PDF 1.5)
575
+ TWO_PAGE_RIGHT = "/TwoPageRight" # (PDF 1.5)
576
+
577
+
578
+ class GraphicsStateParameters:
579
+ """Table 58 – Entries in a Graphics State Parameter Dictionary"""
580
+
581
+ TYPE = "/Type" # name, optional
582
+ LW = "/LW" # number, optional
583
+ LC = "/LC" # integer, optional
584
+ LJ = "/LJ" # integer, optional
585
+ ML = "/ML" # number, optional
586
+ D = "/D" # array, optional
587
+ RI = "/RI" # name, optional
588
+ OP = "/OP"
589
+ op = "/op"
590
+ OPM = "/OPM"
591
+ FONT = "/Font" # array, optional
592
+ BG = "/BG"
593
+ BG2 = "/BG2"
594
+ UCR = "/UCR"
595
+ UCR2 = "/UCR2"
596
+ TR = "/TR"
597
+ TR2 = "/TR2"
598
+ HT = "/HT"
599
+ FL = "/FL"
600
+ SM = "/SM"
601
+ SA = "/SA"
602
+ BM = "/BM"
603
+ S_MASK = "/SMask" # dictionary or name, optional
604
+ CA = "/CA"
605
+ ca = "/ca"
606
+ AIS = "/AIS"
607
+ TK = "/TK"
608
+
609
+
610
+ class CatalogDictionary:
611
+ """§7.7.2 of the 1.7 and 2.0 references."""
612
+
613
+ TYPE = "/Type" # name, required; must be /Catalog
614
+ VERSION = "/Version" # name
615
+ EXTENSIONS = "/Extensions" # dictionary, optional; ISO 32000-1
616
+ PAGES = "/Pages" # dictionary, required
617
+ PAGE_LABELS = "/PageLabels" # number tree, optional
618
+ NAMES = "/Names" # dictionary, optional
619
+ DESTS = "/Dests" # dictionary, optional
620
+ VIEWER_PREFERENCES = "/ViewerPreferences" # dictionary, optional
621
+ PAGE_LAYOUT = "/PageLayout" # name, optional
622
+ PAGE_MODE = "/PageMode" # name, optional
623
+ OUTLINES = "/Outlines" # dictionary, optional
624
+ THREADS = "/Threads" # array, optional
625
+ OPEN_ACTION = "/OpenAction" # array or dictionary or name, optional
626
+ AA = "/AA" # dictionary, optional
627
+ URI = "/URI" # dictionary, optional
628
+ ACRO_FORM = "/AcroForm" # dictionary, optional
629
+ METADATA = "/Metadata" # stream, optional
630
+ STRUCT_TREE_ROOT = "/StructTreeRoot" # dictionary, optional
631
+ MARK_INFO = "/MarkInfo" # dictionary, optional
632
+ LANG = "/Lang" # text string, optional
633
+ SPIDER_INFO = "/SpiderInfo" # dictionary, optional
634
+ OUTPUT_INTENTS = "/OutputIntents" # array, optional
635
+ PIECE_INFO = "/PieceInfo" # dictionary, optional
636
+ OC_PROPERTIES = "/OCProperties" # dictionary, optional
637
+ PERMS = "/Perms" # dictionary, optional
638
+ LEGAL = "/Legal" # dictionary, optional
639
+ REQUIREMENTS = "/Requirements" # array, optional
640
+ COLLECTION = "/Collection" # dictionary, optional
641
+ NEEDS_RENDERING = "/NeedsRendering" # boolean, optional
642
+ DSS = "/DSS" # dictionary, optional
643
+ AF = "/AF" # array of dictionaries, optional
644
+ D_PART_ROOT = "/DPartRoot" # dictionary, optional
645
+
646
+
647
+ class OutlineFontFlag(IntFlag):
648
+ """A class used as an enumerable flag for formatting an outline font."""
649
+
650
+ italic = 1
651
+ bold = 2
652
+
653
+
654
+ class PageLabelStyle:
655
+ """
656
+ Table 8.10 in the 1.7 reference.
657
+ Table 161 in the 2.0 reference.
658
+ """
659
+
660
+ DECIMAL = "/D" # Decimal Arabic numerals
661
+ UPPERCASE_ROMAN = "/R" # Uppercase Roman numerals
662
+ LOWERCASE_ROMAN = "/r" # Lowercase Roman numerals
663
+ UPPERCASE_LETTER = "/A" # Uppercase letters
664
+ LOWERCASE_LETTER = "/a" # Lowercase letters
665
+
666
+
667
+ class AnnotationFlag(IntFlag):
668
+ """See §12.5.3 "Annotation Flags"."""
669
+
670
+ INVISIBLE = 1
671
+ HIDDEN = 2
672
+ PRINT = 4
673
+ NO_ZOOM = 8
674
+ NO_ROTATE = 16
675
+ NO_VIEW = 32
676
+ READ_ONLY = 64
677
+ LOCKED = 128
678
+ TOGGLE_NO_VIEW = 256
679
+ LOCKED_CONTENTS = 512
680
+
681
+
682
+ PDF_KEYS = (
683
+ AnnotationDictionaryAttributes,
684
+ CatalogAttributes,
685
+ CatalogDictionary,
686
+ CcittFaxDecodeParameters,
687
+ CheckboxRadioButtonAttributes,
688
+ ColorSpaces,
689
+ Core,
690
+ DocumentInformationAttributes,
691
+ EncryptionDictAttributes,
692
+ FieldDictionaryAttributes,
693
+ FileSpecificationDictionaryEntries,
694
+ FilterTypeAbbreviations,
695
+ FilterTypes,
696
+ GoToActionArguments,
697
+ GraphicsStateParameters,
698
+ ImageAttributes,
699
+ InteractiveFormDictEntries,
700
+ LzwFilterParameters,
701
+ PageAttributes,
702
+ PageLayouts,
703
+ PagesAttributes,
704
+ Resources,
705
+ StreamAttributes,
706
+ TrailerKeys,
707
+ TypArguments,
708
+ TypFitArguments,
709
+ )
710
+
711
+
712
+ class ImageType(IntFlag):
713
+ NONE = 0
714
+ XOBJECT_IMAGES = auto()
715
+ INLINE_IMAGES = auto()
716
+ DRAWING_IMAGES = auto()
717
+ ALL = XOBJECT_IMAGES | INLINE_IMAGES | DRAWING_IMAGES
718
+ IMAGES = ALL # for consistency with ObjectDeletionFlag
719
+
720
+
721
+ _INLINE_IMAGE_VALUE_MAPPING = {
722
+ "/G": "/DeviceGray",
723
+ "/RGB": "/DeviceRGB",
724
+ "/CMYK": "/DeviceCMYK",
725
+ "/I": "/Indexed",
726
+ "/AHx": "/ASCIIHexDecode",
727
+ "/A85": "/ASCII85Decode",
728
+ "/LZW": "/LZWDecode",
729
+ "/Fl": "/FlateDecode",
730
+ "/RL": "/RunLengthDecode",
731
+ "/CCF": "/CCITTFaxDecode",
732
+ "/DCT": "/DCTDecode",
733
+ "/DeviceGray": "/DeviceGray",
734
+ "/DeviceRGB": "/DeviceRGB",
735
+ "/DeviceCMYK": "/DeviceCMYK",
736
+ "/Indexed": "/Indexed",
737
+ "/ASCIIHexDecode": "/ASCIIHexDecode",
738
+ "/ASCII85Decode": "/ASCII85Decode",
739
+ "/LZWDecode": "/LZWDecode",
740
+ "/FlateDecode": "/FlateDecode",
741
+ "/RunLengthDecode": "/RunLengthDecode",
742
+ "/CCITTFaxDecode": "/CCITTFaxDecode",
743
+ "/DCTDecode": "/DCTDecode",
744
+ "/RelativeColorimetric": "/RelativeColorimetric",
745
+ }
746
+
747
+ _INLINE_IMAGE_KEY_MAPPING = {
748
+ "/BPC": "/BitsPerComponent",
749
+ "/CS": "/ColorSpace",
750
+ "/D": "/Decode",
751
+ "/DP": "/DecodeParms",
752
+ "/F": "/Filter",
753
+ "/H": "/Height",
754
+ "/W": "/Width",
755
+ "/I": "/Interpolate",
756
+ "/Intent": "/Intent",
757
+ "/IM": "/ImageMask",
758
+ "/BitsPerComponent": "/BitsPerComponent",
759
+ "/ColorSpace": "/ColorSpace",
760
+ "/Decode": "/Decode",
761
+ "/DecodeParms": "/DecodeParms",
762
+ "/Filter": "/Filter",
763
+ "/Height": "/Height",
764
+ "/Width": "/Width",
765
+ "/Interpolate": "/Interpolate",
766
+ "/ImageMask": "/ImageMask",
767
+ }
768
+
769
+
770
+ class AFRelationship:
771
+ """
772
+ Associated file relationship types, defining the relationship between
773
+ the PDF component and the associated file.
774
+
775
+ Defined in table 43 of the PDF 2.0 reference.
776
+ """
777
+
778
+ SOURCE = "/Source" # Original content source
779
+ DATA = "/Data" # Base data for visual presentation
780
+ ALTERNATIVE = "/Alternative" # Alternative content representation
781
+ SUPPLEMENT = "/Supplement" # Supplemental representation of original source/data
782
+ ENCRYPTED_PAYLOAD = "/EncryptedPayload" # Encrypted payload document
783
+ FORM_DATA = "/FormData" # Data associated with AcroForm of this PDF
784
+ SCHEMA = "/Schema" # Schema definition for associated object
785
+ UNSPECIFIED = "/Unspecified" # Not known or cannot be described with values
786
+
787
+
788
+ class BorderStyles:
789
+ """
790
+ A class defining border styles used in PDF documents.
791
+
792
+ Defined in table 168 of the PDF 2.0 reference.
793
+ """
794
+
795
+ BEVELED = "/B"
796
+ DASHED = "/D"
797
+ INSET = "/I"
798
+ SOLID = "/S"
799
+ UNDERLINED = "/U"
800
+
801
+
802
+ class FontFlags(IntFlag):
803
+ """
804
+ A class defining font flags in PDF document font descriptor resources.
805
+
806
+ Defined in table 121 of the PDF 2.0 reference.
807
+ """
808
+
809
+ FIXED_PITCH = 1 << 0
810
+ SERIF = 1 << 1
811
+ SYMBOLIC = 1 << 2
812
+ SCRIPT = 1 << 3
813
+ NONSYMBOLIC = 1 << 5
814
+ ITALIC = 1 << 6
815
+ ALL_CAP = 1 << 16
816
+ SMALL_CAP = 1 << 17
817
+ FORCE_BOLD = 1 << 18
.venv/lib/python3.13/site-packages/pypdf/errors.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ All errors/exceptions pypdf raises and all of the warnings it uses.
3
+
4
+ Please note that broken PDF files might cause other Exceptions.
5
+ """
6
+
7
+
8
+ class DeprecationError(Exception):
9
+ """Raised when a deprecated feature is used."""
10
+
11
+
12
+ class DependencyError(Exception):
13
+ """
14
+ Raised when a required dependency (a library or module that pypdf depends on)
15
+ is not available or cannot be imported.
16
+ """
17
+
18
+
19
+ class PyPdfError(Exception):
20
+ """Base class for all exceptions raised by pypdf."""
21
+
22
+
23
+ class PdfReadError(PyPdfError):
24
+ """Raised when there is an issue reading a PDF file."""
25
+
26
+
27
+ class PageSizeNotDefinedError(PyPdfError):
28
+ """Raised when the page size of a PDF document is not defined."""
29
+
30
+
31
+ class PdfReadWarning(UserWarning):
32
+ """Issued when there is a potential issue reading a PDF file, but it can still be read."""
33
+
34
+
35
+ class PdfStreamError(PdfReadError):
36
+ """Raised when there is an issue reading the stream of data in a PDF file."""
37
+
38
+
39
+ class ParseError(PyPdfError):
40
+ """
41
+ Raised when there is an issue parsing (analyzing and understanding the
42
+ structure and meaning of) a PDF file.
43
+ """
44
+
45
+
46
+ class FileNotDecryptedError(PdfReadError):
47
+ """
48
+ Raised when a PDF file that has been encrypted
49
+ (meaning it requires a password to be accessed) has not been successfully
50
+ decrypted.
51
+ """
52
+
53
+
54
+ class WrongPasswordError(FileNotDecryptedError):
55
+ """Raised when the wrong password is used to try to decrypt an encrypted PDF file."""
56
+
57
+
58
+ class EmptyFileError(PdfReadError):
59
+ """Raised when a PDF file is empty or has no content."""
60
+
61
+
62
+ class EmptyImageDataError(PyPdfError):
63
+ """Raised when trying to process an image that has no data."""
64
+
65
+
66
+ STREAM_TRUNCATED_PREMATURELY = "Stream has ended unexpectedly"
67
+
68
+
69
+ class LimitReachedError(PyPdfError):
70
+ """Raised when a limit is reached."""
71
+
72
+
73
+ class XmpDocumentError(PyPdfError, RuntimeError):
74
+ """Raised when the XMP XML document context is invalid or missing."""
.venv/lib/python3.13/site-packages/pypdf/filters.py ADDED
@@ -0,0 +1,878 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2006, Mathieu Fenniak
2
+ # All rights reserved.
3
+ #
4
+ # Redistribution and use in source and binary forms, with or without
5
+ # modification, are permitted provided that the following conditions are
6
+ # met:
7
+ #
8
+ # * Redistributions of source code must retain the above copyright notice,
9
+ # this list of conditions and the following disclaimer.
10
+ # * Redistributions in binary form must reproduce the above copyright notice,
11
+ # this list of conditions and the following disclaimer in the documentation
12
+ # and/or other materials provided with the distribution.
13
+ # * The name of the author may not be used to endorse or promote products
14
+ # derived from this software without specific prior written permission.
15
+ #
16
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26
+ # POSSIBILITY OF SUCH DAMAGE.
27
+
28
+
29
+ """
30
+ Implementation of stream filters; §7.4 Filters of the PDF 2.0 specification.
31
+
32
+ §8.9.7 Inline images of the PDF 2.0 specification has abbreviations that can be
33
+ used for the names of filters in an inline image object.
34
+ """
35
+ __author__ = "Mathieu Fenniak"
36
+ __author_email__ = "biziqe@mathieu.fenniak.net"
37
+
38
+ import binascii
39
+ import math
40
+ import os
41
+ import shutil
42
+ import struct
43
+ import subprocess
44
+ import zlib
45
+ from base64 import a85decode
46
+ from dataclasses import dataclass
47
+ from pathlib import Path
48
+ from tempfile import TemporaryDirectory
49
+ from typing import Any, NoReturn, Optional, Union, cast
50
+
51
+ from ._codecs._codecs import LzwCodec as _LzwCodec
52
+ from ._utils import (
53
+ WHITESPACES_AS_BYTES,
54
+ deprecate,
55
+ deprecation_with_replacement,
56
+ logger_warning,
57
+ )
58
+ from .constants import CcittFaxDecodeParameters as CCITT
59
+ from .constants import FilterTypeAbbreviations as FTA
60
+ from .constants import FilterTypes as FT
61
+ from .constants import ImageAttributes, StreamAttributes
62
+ from .constants import LzwFilterParameters as LZW
63
+ from .errors import DependencyError, LimitReachedError, PdfReadError, PdfStreamError
64
+ from .generic import (
65
+ ArrayObject,
66
+ DictionaryObject,
67
+ IndirectObject,
68
+ NullObject,
69
+ NumberObject,
70
+ PdfObject,
71
+ StreamObject,
72
+ is_null_or_none,
73
+ )
74
+
75
+ MAX_DECLARED_STREAM_LENGTH = 75_000_000
76
+ MAX_ARRAY_BASED_STREAM_OUTPUT_LENGTH = 75_000_000
77
+
78
+ JBIG2_MAX_OUTPUT_LENGTH = 75_000_000
79
+ LZW_MAX_OUTPUT_LENGTH = 75_000_000
80
+ RUN_LENGTH_MAX_OUTPUT_LENGTH = 75_000_000
81
+ ZLIB_MAX_OUTPUT_LENGTH = 75_000_000
82
+ ZLIB_MAX_RECOVERY_INPUT_LENGTH = 5_000_000
83
+ FLATE_MAX_COLUMNS = 250_000
84
+ FLATE_MAX_ROW_LENGTH = 4_000_000
85
+ FLATE_MAX_BUFFER_SIZE = 75_000_000 # TODO: This should be IMAGE_MAX_BUFFER_SIZE.
86
+
87
+ # Reuse cached 1-byte values in the fallback loop to avoid per-byte allocations.
88
+ _SINGLE_BYTES = tuple(bytes((i,)) for i in range(256))
89
+
90
+
91
+ def _decompress_with_limit(data: bytes) -> bytes:
92
+ decompressor = zlib.decompressobj()
93
+ result = decompressor.decompress(data, max_length=ZLIB_MAX_OUTPUT_LENGTH)
94
+ if decompressor.unconsumed_tail:
95
+ raise LimitReachedError(
96
+ f"Limit reached while decompressing. {len(decompressor.unconsumed_tail)} bytes remaining."
97
+ )
98
+ return result
99
+
100
+
101
+ def decompress(data: bytes) -> bytes:
102
+ """
103
+ Decompress the given data using zlib.
104
+
105
+ Attempts to decompress the input data using zlib.
106
+ If the decompression fails due to a zlib error, it falls back
107
+ to using a decompression object with a larger window size.
108
+
109
+ Please note that the output length is limited to avoid memory
110
+ issues. If you need to process larger content streams, consider
111
+ adapting ``pypdf.filters.ZLIB_MAX_OUTPUT_LENGTH``. In case you
112
+ are only dealing with trusted inputs and/or want to disable these
113
+ limits, set the value to `0`.
114
+
115
+ Args:
116
+ data: The input data to be decompressed.
117
+
118
+ Returns:
119
+ The decompressed data.
120
+
121
+ """
122
+ try:
123
+ return _decompress_with_limit(data)
124
+ except zlib.error:
125
+ # First quick approach: There are known issues with faulty added bytes to the
126
+ # tail of the encoded stream from early Adobe Distiller or Pitstop versions
127
+ # with CR char as the default line separator (assumed by reverse engineering)
128
+ # that breaks the decoding process in the end.
129
+ #
130
+ # Try first to cut off some of the tail byte by byte, but limited to not
131
+ # iterate through too many loops and kill the performance for large streams,
132
+ # to then allow the final fallback to run. Added this intermediate attempt,
133
+ # because starting from the head of the stream byte by byte kills completely
134
+ # the performance for large streams (e.g., 6 MB) with the tail-byte-issue
135
+ # and takes ages. This solution is really fast:
136
+ max_tail_cut_off_bytes: int = 8
137
+ for i in range(1, min(max_tail_cut_off_bytes + 1, len(data))):
138
+ try:
139
+ return _decompress_with_limit(data[:-i])
140
+ except zlib.error:
141
+ pass
142
+
143
+ # If still failing, then try with increased window size.
144
+ decompressor = zlib.decompressobj(zlib.MAX_WBITS | 32)
145
+ result_str = b""
146
+ remaining_limit = ZLIB_MAX_OUTPUT_LENGTH
147
+ data_length = len(data)
148
+ known_errors = set()
149
+ for index in range(data_length):
150
+ chunk = _SINGLE_BYTES[data[index]]
151
+ try:
152
+ decompressed = decompressor.decompress(chunk, max_length=remaining_limit)
153
+ result_str += decompressed
154
+ remaining_limit -= len(decompressed)
155
+ if remaining_limit <= 0:
156
+ raise LimitReachedError(
157
+ f"Limit reached while decompressing. {data_length - index} bytes remaining."
158
+ )
159
+ except zlib.error as error:
160
+ if index > ZLIB_MAX_RECOVERY_INPUT_LENGTH:
161
+ raise LimitReachedError(
162
+ f"Recovery limit reached while decompressing. {data_length - index} bytes remaining."
163
+ )
164
+ error_str = str(error)
165
+ if error_str in known_errors:
166
+ continue
167
+ logger_warning(error_str, source=__name__)
168
+ known_errors.add(error_str)
169
+ return result_str
170
+
171
+
172
+ class FlateDecode:
173
+ @staticmethod
174
+ def decode(
175
+ data: bytes,
176
+ decode_parms: Optional[Union[DictionaryObject, IndirectObject]] = None,
177
+ **kwargs: Any,
178
+ ) -> bytes:
179
+ """
180
+ Decode data which is flate-encoded.
181
+
182
+ Args:
183
+ data: Flate-encoded data.
184
+ decode_parms: Additional decoding parameters.
185
+
186
+ Returns:
187
+ The flate-decoded data.
188
+
189
+ Raises:
190
+ PdfReadError: Unsupported parameters have been found.
191
+
192
+ """
193
+ str_data = decompress(data)
194
+
195
+ processed_parms: Optional[PdfObject] = decode_parms
196
+ if isinstance(decode_parms, IndirectObject) and processed_parms is not None:
197
+ processed_parms = processed_parms.get_object()
198
+ if isinstance(processed_parms, dict):
199
+ parameters = processed_parms
200
+ else:
201
+ if not is_null_or_none(processed_parms):
202
+ logger_warning(
203
+ "Detected invalid /DecodeParms, results might be incorrect: %(value)s (type %(type_name)s)",
204
+ source=__name__, value=decode_parms, type_name=decode_parms.__class__.__name__,
205
+ )
206
+ parameters = DictionaryObject()
207
+
208
+ predictor = parameters.get("/Predictor", 1)
209
+
210
+ # predictor 1 == no predictor
211
+ if predictor != 1:
212
+ columns, colors, bits_per_component = FlateDecode._get_parameters(parameters)
213
+
214
+ # PNG predictor can vary by row and so is the lead byte on each row
215
+ row_length = (
216
+ math.ceil(columns * colors * bits_per_component / 8) + 1
217
+ ) # number of bytes
218
+ if row_length > FLATE_MAX_ROW_LENGTH:
219
+ raise LimitReachedError(
220
+ f"Row length of {row_length} exceeds defined limit of {FLATE_MAX_ROW_LENGTH}."
221
+ )
222
+
223
+ # TIFF prediction:
224
+ if predictor == 2:
225
+ row_length -= 1 # remove the predictor byte
226
+ bpp = row_length // columns
227
+ str_data_mut = bytearray(str_data)
228
+ for i in range(len(str_data_mut)):
229
+ if i % row_length >= bpp:
230
+ str_data_mut[i] = (str_data_mut[i] + str_data_mut[i - bpp]) % 256
231
+ str_data = bytes(str_data_mut)
232
+ # PNG prediction:
233
+ elif 10 <= predictor <= 15:
234
+ str_data = FlateDecode._decode_png_prediction(
235
+ str_data, columns, row_length
236
+ )
237
+ else:
238
+ raise PdfReadError(f"Unsupported flatedecode predictor {predictor!r}")
239
+ return str_data
240
+
241
+ @staticmethod
242
+ def _get_parameters(parameters: DictionaryObject) -> tuple[int, int, int]:
243
+ # For details, see table 8 of ISO 32000-2:2020.
244
+ def get(key: str, default: int) -> int:
245
+ _value = parameters.get(key, NumberObject(default)).get_object()
246
+ if not isinstance(_value, int) or _value < 1:
247
+ raise PdfReadError(f"Expected positive number for {key}, got {_value}!")
248
+ return _value
249
+
250
+ columns = get(key=LZW.COLUMNS, default=1)
251
+ if columns > FLATE_MAX_COLUMNS:
252
+ raise LimitReachedError(f"Number of columns {columns} exceeds defined limit of {FLATE_MAX_COLUMNS}.")
253
+
254
+ colors = get(key=LZW.COLORS, default=1)
255
+ if colors > 16:
256
+ raise LimitReachedError(
257
+ f"Color value {colors} exceeds limit of 16. "
258
+ f"Please open an issue if this limits valid use cases."
259
+ )
260
+
261
+ bits_per_component = get(key=LZW.BITS_PER_COMPONENT, default=8)
262
+ if bits_per_component > 16:
263
+ raise PdfReadError(f"More than 16 bits per component are not allowed: {bits_per_component}")
264
+
265
+ return columns, colors, bits_per_component
266
+
267
+ @staticmethod
268
+ def _decode_png_prediction(data: bytes, columns: int, row_length: int) -> bytes:
269
+ # PNG prediction can vary from row to row
270
+ if (remainder := len(data) % row_length) != 0:
271
+ logger_warning("Image data is not rectangular. Adding padding.", source=__name__)
272
+ data += b"\x00" * (row_length - remainder)
273
+ assert len(data) % row_length == 0
274
+ output = bytearray()
275
+ previous_row_data = bytes(row_length)
276
+ bpp = (row_length - 1) // columns # recomputed locally to not change params
277
+ for row in range(0, len(data), row_length):
278
+ row_data = bytearray(data[row : row + row_length])
279
+ filter_byte = row_data[0]
280
+
281
+ if filter_byte == 0:
282
+ # PNG None Predictor
283
+ pass
284
+ elif filter_byte == 1:
285
+ # PNG Sub Predictor
286
+ for i in range(bpp + 1, row_length):
287
+ row_data[i] = (row_data[i] + row_data[i - bpp]) % 256
288
+ elif filter_byte == 2:
289
+ # PNG Up Predictor
290
+ for i in range(1, row_length):
291
+ row_data[i] = (row_data[i] + previous_row_data[i]) % 256
292
+ elif filter_byte == 3:
293
+ # PNG Average Predictor
294
+ for i in range(1, bpp + 1):
295
+ floor = previous_row_data[i] // 2
296
+ row_data[i] = (row_data[i] + floor) % 256
297
+ for i in range(bpp + 1, row_length):
298
+ left = row_data[i - bpp]
299
+ floor = (left + previous_row_data[i]) // 2
300
+ row_data[i] = (row_data[i] + floor) % 256
301
+ elif filter_byte == 4:
302
+ # PNG Paeth Predictor
303
+ for i in range(1, bpp + 1):
304
+ row_data[i] = (row_data[i] + previous_row_data[i]) % 256
305
+ for i in range(bpp + 1, row_length):
306
+ left = row_data[i - bpp]
307
+ up = previous_row_data[i]
308
+ up_left = previous_row_data[i - bpp]
309
+
310
+ p = left + up - up_left
311
+ dist_left = abs(p - left)
312
+ dist_up = abs(p - up)
313
+ dist_up_left = abs(p - up_left)
314
+
315
+ if dist_left <= dist_up and dist_left <= dist_up_left:
316
+ paeth = left
317
+ elif dist_up <= dist_up_left:
318
+ paeth = up
319
+ else:
320
+ paeth = up_left
321
+
322
+ row_data[i] = (row_data[i] + paeth) % 256
323
+ else:
324
+ raise PdfReadError(
325
+ f"Unsupported PNG filter {filter_byte!r}"
326
+ ) # pragma: no cover
327
+ previous_row_data = bytes(row_data)
328
+ output += row_data[1:]
329
+ return bytes(output)
330
+
331
+ @staticmethod
332
+ def encode(data: bytes, level: int = -1) -> bytes:
333
+ """
334
+ Compress the input data using zlib.
335
+
336
+ Args:
337
+ data: The data to be compressed.
338
+ level: See https://docs.python.org/3/library/zlib.html#zlib.compress
339
+
340
+ Returns:
341
+ The compressed data.
342
+
343
+ """
344
+ return zlib.compress(data, level)
345
+
346
+
347
+ class ASCIIHexDecode:
348
+ """
349
+ The ASCIIHexDecode filter decodes data that has been encoded in ASCII
350
+ hexadecimal form into a base-7 ASCII format.
351
+ """
352
+
353
+ @staticmethod
354
+ def decode(
355
+ data: Union[str, bytes],
356
+ decode_parms: Optional[DictionaryObject] = None,
357
+ **kwargs: Any,
358
+ ) -> bytes:
359
+ """
360
+ Decode an ASCII-Hex encoded data stream.
361
+
362
+ Args:
363
+ data: a str sequence of hexadecimal-encoded values to be
364
+ converted into a base-7 ASCII string
365
+ decode_parms: this filter does not use parameters.
366
+
367
+ Returns:
368
+ A string conversion in base-7 ASCII, where each of its values
369
+ v is such that 0 <= ord(v) <= 127.
370
+
371
+ Raises:
372
+ PdfStreamError:
373
+
374
+ """
375
+ if isinstance(data, str):
376
+ data = data.encode()
377
+
378
+ # Stop at EOD
379
+ eod = data.find(b">")
380
+ if eod == -1:
381
+ logger_warning(
382
+ "missing EOD in ASCIIHexDecode, check if output is OK",
383
+ source=__name__,
384
+ )
385
+ hex_data = data
386
+ else:
387
+ hex_data = data[:eod]
388
+
389
+ # Remove whitespace
390
+ hex_data = b"".join(hex_data.split())
391
+
392
+ # Pad if odd length
393
+ if len(hex_data) % 2 == 1:
394
+ hex_data += b"0"
395
+
396
+ # The spec permits only 0-9, A-F, a-f and whitespace inside the stream.
397
+ # Stray bytes used to surface as an uncaught binascii.Error; turn them
398
+ # into a proper PdfStreamError instead.
399
+ try:
400
+ return binascii.unhexlify(hex_data)
401
+ except binascii.Error as error:
402
+ raise PdfStreamError(f"Invalid hexadecimal character in ASCIIHexDecode stream: {error}")
403
+
404
+
405
+ class RunLengthDecode:
406
+ """
407
+ The RunLengthDecode filter decodes data that has been encoded in a
408
+ simple byte-oriented format based on run length.
409
+ The encoded data is a sequence of runs, where each run consists of
410
+ a length byte followed by 1 to 128 bytes of data. If the length byte is
411
+ in the range 0 to 127,
412
+ the following length + 1 (1 to 128) bytes are copied literally during
413
+ decompression.
414
+ If length is in the range 129 to 255, the following single byte is to be
415
+ copied 257 − length (2 to 128) times during decompression. A length value
416
+ of 128 denotes EOD.
417
+ """
418
+
419
+ @staticmethod
420
+ def decode(
421
+ data: bytes,
422
+ decode_parms: Optional[DictionaryObject] = None,
423
+ **kwargs: Any,
424
+ ) -> bytes:
425
+ """
426
+ Decode a run length encoded data stream.
427
+
428
+ Args:
429
+ data: a bytes sequence of length/data
430
+ decode_parms: this filter does not use parameters.
431
+
432
+ Returns:
433
+ A bytes decompressed sequence.
434
+
435
+ Raises:
436
+ PdfStreamError:
437
+
438
+ """
439
+ lst = []
440
+ index = 0
441
+ data_length = len(data)
442
+ total_length = 0
443
+ while True:
444
+ if index >= data_length:
445
+ logger_warning(
446
+ "missing EOD in RunLengthDecode, check if output is OK", source=__name__
447
+ )
448
+ break # Reached end of string without an EOD
449
+ length = data[index]
450
+ index += 1
451
+ if length == 128:
452
+ if index < data_length:
453
+ # We should first check, if we have an inner stream from a multi-encoded
454
+ # stream with a faulty trailing newline that we can decode properly.
455
+ # We will just ignore the last byte and raise a warning ...
456
+ if (index == data_length - 1) and (data[index : index + 1] == b"\n"):
457
+ logger_warning(
458
+ "Found trailing newline in stream data, check if output is OK", source=__name__
459
+ )
460
+ break
461
+ # Raising an exception here breaks all image extraction for this file, which might
462
+ # not be desirable. For this reason, indicate that the output is most likely wrong,
463
+ # as processing stopped after the first EOD marker. See issue #3517.
464
+ logger_warning(
465
+ "Early EOD in RunLengthDecode, check if output is OK", source=__name__
466
+ )
467
+ break
468
+ if length < 128:
469
+ length += 1
470
+ lst.append(data[index : (index + length)])
471
+ index += length
472
+ else: # >128
473
+ if index >= data_length:
474
+ logger_warning(
475
+ "Missing EOD in RunLengthDecode, check if output is OK", source=__name__
476
+ )
477
+ break # Reached end of string without the replicated byte
478
+ length = 257 - length
479
+ lst.append(bytes((data[index],)) * length)
480
+ index += 1
481
+ total_length += length
482
+ if total_length > RUN_LENGTH_MAX_OUTPUT_LENGTH:
483
+ raise LimitReachedError("Limit reached while decompressing.")
484
+ return b"".join(lst)
485
+
486
+
487
+ class LZWDecode:
488
+ class Decoder:
489
+ STOP = 257
490
+ CLEARDICT = 256
491
+
492
+ def __init__(self, data: bytes) -> None:
493
+ self.data = data
494
+
495
+ def decode(self) -> bytes:
496
+ return _LzwCodec(max_output_length=LZW_MAX_OUTPUT_LENGTH).decode(self.data)
497
+
498
+ @staticmethod
499
+ def decode(
500
+ data: bytes,
501
+ decode_parms: Optional[DictionaryObject] = None,
502
+ **kwargs: Any,
503
+ ) -> bytes:
504
+ """
505
+ Decode an LZW encoded data stream.
506
+
507
+ Args:
508
+ data: ``bytes`` or ``str`` text to decode.
509
+ decode_parms: a dictionary of parameter values.
510
+
511
+ Returns:
512
+ decoded data.
513
+
514
+ """
515
+ # decode_parms is unused here
516
+ return LZWDecode.Decoder(data).decode()
517
+
518
+
519
+ class ASCII85Decode:
520
+ """Decodes string ASCII85-encoded data into a byte format."""
521
+
522
+ @staticmethod
523
+ def decode(
524
+ data: Union[str, bytes],
525
+ decode_parms: Optional[DictionaryObject] = None,
526
+ **kwargs: Any,
527
+ ) -> bytes:
528
+ """
529
+ Decode an Ascii85 encoded data stream.
530
+
531
+ Args:
532
+ data: ``bytes`` or ``str`` text to decode.
533
+ decode_parms: this filter does not use parameters.
534
+
535
+ Returns:
536
+ decoded data.
537
+
538
+ """
539
+ if isinstance(data, str):
540
+ data = data.encode()
541
+ data = data.strip(WHITESPACES_AS_BYTES)
542
+ if len(data) > 2 and data.endswith(b">"):
543
+ data = data[:-1].rstrip(WHITESPACES_AS_BYTES) + data[-1:]
544
+ try:
545
+ return a85decode(data, adobe=True, ignorechars=WHITESPACES_AS_BYTES)
546
+ except ValueError as error:
547
+ if error.args[0] == "Ascii85 encoded byte sequences must end with b'~>'":
548
+ logger_warning("Ignoring missing Ascii85 end marker.", source=__name__)
549
+ return a85decode(data, adobe=False, ignorechars=WHITESPACES_AS_BYTES)
550
+ raise
551
+
552
+
553
+ class DCTDecode:
554
+ @staticmethod
555
+ def decode(
556
+ data: bytes,
557
+ decode_parms: Optional[DictionaryObject] = None,
558
+ **kwargs: Any,
559
+ ) -> bytes:
560
+ """
561
+ Decompresses data encoded using a DCT (discrete cosine transform)
562
+ technique based on the JPEG standard (IS0/IEC 10918),
563
+ reproducing image sample data that approximates the original data.
564
+
565
+ Args:
566
+ data: text to decode.
567
+ decode_parms: this filter does not use parameters.
568
+
569
+ Returns:
570
+ decoded data.
571
+
572
+ """
573
+ return data
574
+
575
+
576
+ class JPXDecode:
577
+ @staticmethod
578
+ def decode(
579
+ data: bytes,
580
+ decode_parms: Optional[DictionaryObject] = None,
581
+ **kwargs: Any,
582
+ ) -> bytes:
583
+ """
584
+ Decompresses data encoded using the wavelet-based JPEG 2000 standard,
585
+ reproducing the original image data.
586
+
587
+ Args:
588
+ data: text to decode.
589
+ decode_parms: this filter does not use parameters.
590
+
591
+ Returns:
592
+ decoded data.
593
+
594
+ """
595
+ return data
596
+
597
+
598
+ @dataclass
599
+ class CCITTParameters:
600
+ """§7.4.6, optional parameters for the CCITTFaxDecode filter."""
601
+
602
+ K: int = 0
603
+ columns: int = 1728
604
+ rows: int = 0
605
+ EndOfLine: Union[bool, None] = False
606
+ EncodedByteAlign: Union[bool, None] = False
607
+ EndOfBlock: Union[bool, None] = True
608
+ BlackIs1: bool = False
609
+ DamagedRowsBeforeError: Union[int, None] = 0
610
+
611
+ @property
612
+ def group(self) -> int:
613
+ if self.K < 0:
614
+ # Pure two-dimensional encoding (Group 4)
615
+ CCITTgroup = 4
616
+ else:
617
+ # K == 0: Pure one-dimensional encoding (Group 3, 1-D)
618
+ # K > 0: Mixed one- and two-dimensional encoding (Group 3, 2-D)
619
+ CCITTgroup = 3
620
+ return CCITTgroup
621
+
622
+
623
+ def __create_old_class_instance(
624
+ K: int = 0,
625
+ columns: int = 0,
626
+ rows: int = 0
627
+ ) -> NoReturn:
628
+ deprecation_with_replacement("CCITParameters", "CCITTParameters", "6.0.0")
629
+
630
+
631
+ # Create an alias for the old class name
632
+ CCITParameters = __create_old_class_instance
633
+
634
+
635
+ class CCITTFaxDecode:
636
+ """
637
+ §7.4.6, CCITTFaxDecode filter (ISO 32000).
638
+
639
+ Either Group 3 or Group 4 CCITT facsimile (fax) encoding.
640
+ CCITT encoding is bit-oriented, not byte-oriented.
641
+
642
+ §7.4.6, optional parameters for the CCITTFaxDecode filter.
643
+ """
644
+
645
+ @staticmethod
646
+ def _get_parameters(
647
+ parameters: Union[ArrayObject, DictionaryObject, IndirectObject, None],
648
+ rows: Union[int, IndirectObject],
649
+ ) -> CCITTParameters:
650
+ ccitt_parameters = CCITTParameters(rows=int(rows))
651
+ if parameters:
652
+ parameters_unwrapped = cast(
653
+ Union[ArrayObject, DictionaryObject], parameters.get_object()
654
+ )
655
+ if isinstance(parameters_unwrapped, ArrayObject):
656
+ for decode_parm in parameters_unwrapped:
657
+ if CCITT.K in decode_parm:
658
+ ccitt_parameters.K = decode_parm[CCITT.K].get_object()
659
+ if CCITT.COLUMNS in decode_parm:
660
+ ccitt_parameters.columns = decode_parm[CCITT.COLUMNS].get_object()
661
+ if CCITT.BLACK_IS_1 in decode_parm:
662
+ ccitt_parameters.BlackIs1 = decode_parm[CCITT.BLACK_IS_1].get_object().value
663
+ else:
664
+ if CCITT.K in parameters_unwrapped:
665
+ ccitt_parameters.K = parameters_unwrapped[CCITT.K].get_object() # type: ignore[assignment]
666
+ if CCITT.COLUMNS in parameters_unwrapped:
667
+ ccitt_parameters.columns = parameters_unwrapped[CCITT.COLUMNS].get_object() # type: ignore[assignment]
668
+ if CCITT.BLACK_IS_1 in parameters_unwrapped:
669
+ ccitt_parameters.BlackIs1 = parameters_unwrapped[CCITT.BLACK_IS_1].get_object().value # type: ignore[union-attr]
670
+ return ccitt_parameters
671
+
672
+ @staticmethod
673
+ def decode(
674
+ data: bytes,
675
+ decode_parms: Optional[DictionaryObject] = None,
676
+ height: int = 0,
677
+ **kwargs: Any,
678
+ ) -> bytes:
679
+ params = CCITTFaxDecode._get_parameters(decode_parms, height)
680
+
681
+ img_size = len(data)
682
+ # TIFF SHORT and LONG fields are unsigned (TIFF 6.0, §2); pack them with
683
+ # unsigned codes so dimensions with the high bit set do not overflow.
684
+ tiff_header_struct = "<2sHLH" + "HHLL" * 8 + "H"
685
+ tiff_header = struct.pack(
686
+ tiff_header_struct,
687
+ b"II", # Byte order indication: Little endian
688
+ 42, # Version number (always 42)
689
+ 8, # Offset to the first image file directory (IFD)
690
+ 8, # Number of tags in IFD
691
+ 256, # ImageWidth, LONG, 1, width
692
+ 4,
693
+ 1,
694
+ params.columns,
695
+ 257, # ImageLength, LONG, 1, length
696
+ 4,
697
+ 1,
698
+ params.rows,
699
+ 258, # BitsPerSample, SHORT, 1, 1
700
+ 3,
701
+ 1,
702
+ 1,
703
+ 259, # Compression, SHORT, 1, compression Type
704
+ 3,
705
+ 1,
706
+ params.group,
707
+ 262, # Thresholding, SHORT, 1, 0 = BlackIs1
708
+ 3,
709
+ 1,
710
+ int(params.BlackIs1),
711
+ 273, # StripOffsets, LONG, 1, length of header
712
+ 4,
713
+ 1,
714
+ struct.calcsize(
715
+ tiff_header_struct
716
+ ),
717
+ 278, # RowsPerStrip, LONG, 1, length
718
+ 4,
719
+ 1,
720
+ params.rows,
721
+ 279, # StripByteCounts, LONG, 1, size of image
722
+ 4,
723
+ 1,
724
+ img_size,
725
+ 0, # last IFD
726
+ )
727
+
728
+ return tiff_header + data
729
+
730
+
731
+ JBIG2DEC_BINARY = shutil.which("jbig2dec")
732
+
733
+
734
+ class JBIG2Decode:
735
+ @staticmethod
736
+ def decode(
737
+ data: bytes,
738
+ decode_parms: Optional[DictionaryObject] = None,
739
+ **kwargs: Any,
740
+ ) -> bytes:
741
+ if JBIG2DEC_BINARY is None:
742
+ raise DependencyError("jbig2dec binary is not available.")
743
+
744
+ with TemporaryDirectory() as tempdir:
745
+ directory = Path(tempdir)
746
+ paths: list[Path] = []
747
+
748
+ if decode_parms and "/JBIG2Globals" in decode_parms:
749
+ jbig2_globals = decode_parms["/JBIG2Globals"]
750
+ if not is_null_or_none(jbig2_globals) and not is_null_or_none(pointer := jbig2_globals.get_object()):
751
+ assert pointer is not None, "mypy"
752
+ if isinstance(pointer, StreamObject):
753
+ path = directory.joinpath("globals.jbig2")
754
+ path.write_bytes(pointer.get_data())
755
+ paths.append(path)
756
+
757
+ path = directory.joinpath("image.jbig2")
758
+ path.write_bytes(data)
759
+ paths.append(path)
760
+
761
+ environment = os.environ.copy()
762
+ environment["LC_ALL"] = "C"
763
+ result = subprocess.run( # noqa: S603
764
+ [
765
+ JBIG2DEC_BINARY,
766
+ "--embedded",
767
+ "--format", "png",
768
+ "--output", "-",
769
+ "-M", str(JBIG2_MAX_OUTPUT_LENGTH),
770
+ *paths
771
+ ],
772
+ capture_output=True,
773
+ env=environment,
774
+ )
775
+ if b"unrecognized option '--embedded'" in result.stderr or b"unrecognized option '-M'" in result.stderr:
776
+ raise DependencyError("jbig2dec>=0.19 is required.")
777
+ if b"FATAL ERROR failed to allocate image data buffer" in result.stderr:
778
+ raise LimitReachedError(
779
+ f"Memory limit reached while reading JBIG2 data:\n{result.stderr.decode('utf-8')}"
780
+ )
781
+ if result.stderr:
782
+ for line in result.stderr.decode("utf-8").splitlines():
783
+ logger_warning(line, source=__name__)
784
+ if result.returncode != 0:
785
+ raise PdfStreamError(f"Unable to decode JBIG2 data. Exit code: {result.returncode}")
786
+ return result.stdout
787
+
788
+ @staticmethod
789
+ def _is_binary_compatible() -> bool:
790
+ if not JBIG2DEC_BINARY: # pragma: no cover
791
+ return False
792
+ result = subprocess.run( # noqa: S603
793
+ [JBIG2DEC_BINARY, "--version"],
794
+ capture_output=True,
795
+ text=True,
796
+ )
797
+ version = result.stdout.split(" ", maxsplit=1)[1]
798
+
799
+ from ._utils import Version # noqa: PLC0415
800
+ return Version(version) >= Version("0.19")
801
+
802
+
803
+ def _deprecate_inline_image_filters(filter_name: str, old_name: str, new_name: str) -> None:
804
+ if filter_name != old_name:
805
+ return
806
+ deprecate(
807
+ f"The filter name {old_name} is deprecated and will be removed in pypdf 7.0.0. Use {new_name} instead.",
808
+ 4,
809
+ )
810
+
811
+
812
+ def decode_stream_data(stream: StreamObject) -> bytes:
813
+ """
814
+ Decode the stream data based on the specified filters.
815
+
816
+ This function decodes the stream data using the filters provided in the
817
+ stream.
818
+
819
+ Args:
820
+ stream: The input stream object containing the data and filters.
821
+
822
+ Returns:
823
+ The decoded stream data.
824
+
825
+ Raises:
826
+ NotImplementedError: If an unsupported filter type is encountered.
827
+
828
+ """
829
+ filters = stream.get(StreamAttributes.FILTER, ())
830
+ if isinstance(filters, IndirectObject):
831
+ filters = cast(ArrayObject, filters.get_object())
832
+ if not isinstance(filters, ArrayObject):
833
+ # We have a single filter instance
834
+ filters = (filters,)
835
+ decode_parms = stream.get(StreamAttributes.DECODE_PARMS, ({},) * len(filters))
836
+ if not isinstance(decode_parms, (list, tuple)):
837
+ decode_parms = (decode_parms,)
838
+ data: bytes = stream._data
839
+ # If there is no data to decode, we should not try to decode it.
840
+ if not data:
841
+ return data
842
+ for filter_name, params in zip(filters, decode_parms):
843
+ if isinstance(params, NullObject):
844
+ params = {}
845
+ if filter_name in (FT.ASCII_HEX_DECODE, FTA.AHx):
846
+ _deprecate_inline_image_filters(filter_name=filter_name, old_name=FTA.AHx, new_name=FT.ASCII_HEX_DECODE)
847
+ data = ASCIIHexDecode.decode(data)
848
+ elif filter_name in (FT.ASCII_85_DECODE, FTA.A85):
849
+ _deprecate_inline_image_filters(filter_name=filter_name, old_name=FTA.A85, new_name=FT.ASCII_85_DECODE)
850
+ data = ASCII85Decode.decode(data)
851
+ elif filter_name in (FT.LZW_DECODE, FTA.LZW):
852
+ _deprecate_inline_image_filters(filter_name=filter_name, old_name=FTA.LZW, new_name=FT.LZW_DECODE)
853
+ data = LZWDecode.decode(data, params)
854
+ elif filter_name in (FT.FLATE_DECODE, FTA.FL):
855
+ _deprecate_inline_image_filters(filter_name=filter_name, old_name=FTA.FL, new_name=FT.FLATE_DECODE)
856
+ data = FlateDecode.decode(data, params)
857
+ elif filter_name in (FT.RUN_LENGTH_DECODE, FTA.RL):
858
+ _deprecate_inline_image_filters(filter_name=filter_name, old_name=FTA.RL, new_name=FT.RUN_LENGTH_DECODE)
859
+ data = RunLengthDecode.decode(data)
860
+ elif filter_name in (FT.CCITT_FAX_DECODE, FTA.CCF):
861
+ _deprecate_inline_image_filters(filter_name=filter_name, old_name=FTA.CCF, new_name=FT.CCITT_FAX_DECODE)
862
+ height = stream.get(ImageAttributes.HEIGHT, ())
863
+ data = CCITTFaxDecode.decode(data, params, height)
864
+ elif filter_name in (FT.DCT_DECODE, FTA.DCT):
865
+ _deprecate_inline_image_filters(filter_name=filter_name, old_name=FTA.DCT, new_name=FT.DCT_DECODE)
866
+ data = DCTDecode.decode(data)
867
+ elif filter_name == FT.JPX_DECODE:
868
+ data = JPXDecode.decode(data)
869
+ elif filter_name == FT.JBIG2_DECODE:
870
+ data = JBIG2Decode.decode(data, params)
871
+ elif filter_name == "/Crypt":
872
+ if "/Name" in params or "/Type" in params:
873
+ raise NotImplementedError(
874
+ "/Crypt filter with /Name or /Type not supported yet"
875
+ )
876
+ else:
877
+ raise NotImplementedError(f"Unsupported filter {filter_name}")
878
+ return data
.venv/lib/python3.13/site-packages/pypdf/generic/__init__.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2006, Mathieu Fenniak
2
+ # All rights reserved.
3
+ #
4
+ # Redistribution and use in source and binary forms, with or without
5
+ # modification, are permitted provided that the following conditions are
6
+ # met:
7
+ #
8
+ # * Redistributions of source code must retain the above copyright notice,
9
+ # this list of conditions and the following disclaimer.
10
+ # * Redistributions in binary form must reproduce the above copyright notice,
11
+ # this list of conditions and the following disclaimer in the documentation
12
+ # and/or other materials provided with the distribution.
13
+ # * The name of the author may not be used to endorse or promote products
14
+ # derived from this software without specific prior written permission.
15
+ #
16
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26
+ # POSSIBILITY OF SUCH DAMAGE.
27
+
28
+ """Implementation of generic PDF objects (dictionary, number, string, ...)."""
29
+ __author__ = "Mathieu Fenniak"
30
+ __author_email__ = "biziqe@mathieu.fenniak.net"
31
+
32
+ from ..constants import OutlineFontFlag
33
+ from ._base import (
34
+ BooleanObject,
35
+ ByteStringObject,
36
+ FloatObject,
37
+ IndirectObject,
38
+ NameObject,
39
+ NullObject,
40
+ NumberObject,
41
+ PdfObject,
42
+ TextStringObject,
43
+ encode_pdfdocencoding,
44
+ is_null_or_none,
45
+ )
46
+ from ._data_structures import (
47
+ ArrayObject,
48
+ ContentStream,
49
+ DecodedStreamObject,
50
+ Destination,
51
+ DictionaryObject,
52
+ EncodedStreamObject,
53
+ Field,
54
+ StreamObject,
55
+ TreeObject,
56
+ read_object,
57
+ )
58
+ from ._files import EmbeddedFile
59
+ from ._fit import Fit
60
+ from ._link import DirectReferenceLink, NamedReferenceLink, ReferenceLink, extract_links
61
+ from ._outline import OutlineItem
62
+ from ._rectangle import RectangleObject
63
+ from ._utils import (
64
+ create_string_object,
65
+ decode_pdfdocencoding,
66
+ hex_to_rgb,
67
+ read_hex_string_from_stream,
68
+ read_string_from_stream,
69
+ )
70
+ from ._viewerpref import ViewerPreferences
71
+
72
+ PAGE_FIT = Fit.fit()
73
+
74
+
75
+ __all__ = [
76
+ "PAGE_FIT",
77
+ "ArrayObject",
78
+ "BooleanObject",
79
+ "ByteStringObject",
80
+ "ContentStream",
81
+ "DecodedStreamObject",
82
+ "Destination",
83
+ "DictionaryObject",
84
+ "DirectReferenceLink",
85
+ "EmbeddedFile",
86
+ "EncodedStreamObject",
87
+ "Field",
88
+ "Fit",
89
+ "FloatObject",
90
+ "IndirectObject",
91
+ "NameObject",
92
+ "NamedReferenceLink",
93
+ "NullObject",
94
+ "NumberObject",
95
+ "OutlineFontFlag",
96
+ "OutlineItem",
97
+ "PdfObject",
98
+ "RectangleObject",
99
+ "ReferenceLink",
100
+ "StreamObject",
101
+ "TextStringObject",
102
+ "TreeObject",
103
+ "ViewerPreferences",
104
+ # Utility functions
105
+ "create_string_object",
106
+ "decode_pdfdocencoding",
107
+ "encode_pdfdocencoding",
108
+ "extract_links",
109
+ "hex_to_rgb",
110
+ "is_null_or_none",
111
+ "read_hex_string_from_stream",
112
+ # Data structures core functions
113
+ "read_object",
114
+ "read_string_from_stream",
115
+ ]
.venv/lib/python3.13/site-packages/pypdf/generic/_appearance_stream.py ADDED
@@ -0,0 +1,752 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from dataclasses import dataclass
5
+ from enum import IntEnum
6
+ from io import BytesIO
7
+ from operator import attrgetter
8
+ from typing import TYPE_CHECKING, Any, NamedTuple, cast
9
+
10
+ from .._codecs import fill_from_encoding
11
+ from .._codecs.core_font_metrics import CORE_FONT_METRICS
12
+ from .._font import Font
13
+ from .._utils import is_char_rtl, logger_warning
14
+ from ..constants import AnnotationDictionaryAttributes, BorderStyles, FieldDictionaryAttributes, PageAttributes
15
+ from ..errors import PdfReadError
16
+ from ..generic import (
17
+ DecodedStreamObject,
18
+ DictionaryObject,
19
+ IndirectObject,
20
+ NameObject,
21
+ NumberObject,
22
+ RectangleObject,
23
+ )
24
+ from ..generic._base import ByteStringObject, TextStringObject
25
+
26
+ if TYPE_CHECKING:
27
+ from pypdf._writer import PdfWriter
28
+
29
+ from .._page import PageObject
30
+
31
+ try:
32
+ import arabic_reshaper
33
+ from bidi.algorithm import get_display
34
+ HAS_RTL_SUPPORT = True
35
+ except ImportError:
36
+ HAS_RTL_SUPPORT = False
37
+
38
+ DEFAULT_FONT_SIZE_IN_MULTILINE = 12
39
+
40
+ # "The glyph widths shall be measured in units in which 1000 units correspond to 1 unit in text space"
41
+ # (Table 111, PDF Specification 2.0)
42
+ TEXT_SPACE_TO_GLYPH_SPACE_FACTOR = 1000
43
+
44
+
45
+ @dataclass
46
+ class BaseStreamConfig:
47
+ """A container representing the basic layout of an appearance stream."""
48
+ rectangle: RectangleObject | tuple[float, float, float, float] = (0.0, 0.0, 0.0, 0.0)
49
+ border_width: int = 1 # The width of the border in points
50
+ border_style: str = BorderStyles.SOLID
51
+
52
+
53
+ class BaseStreamAppearance(DecodedStreamObject):
54
+ """A class representing the very base of an appearance stream, that is, a rectangle and a border."""
55
+
56
+ def __init__(self, layout: BaseStreamConfig | None) -> None:
57
+ """
58
+ Takes the appearance stream layout as an argument.
59
+
60
+ Args:
61
+ layout: The basic layout parameters.
62
+ """
63
+ super().__init__()
64
+ self._layout = layout or BaseStreamConfig()
65
+ self[NameObject("/Type")] = NameObject("/XObject")
66
+ self[NameObject("/Subtype")] = NameObject("/Form")
67
+ self[NameObject("/BBox")] = RectangleObject(self._layout.rectangle)
68
+
69
+
70
+ class TextAlignment(IntEnum):
71
+ """Defines the alignment options for text within a form field's appearance stream."""
72
+
73
+ LEFT = 0
74
+ CENTER = 1
75
+ RIGHT = 2
76
+
77
+
78
+ class WidthWordGlyphs(NamedTuple):
79
+ """A tuple of the unscaled width of a word (unencoded text) and the font-encoded glyphs that represent it."""
80
+
81
+ width: float
82
+ word: str
83
+ glyphs: str
84
+
85
+
86
+ class TextStreamAppearance(BaseStreamAppearance):
87
+ """
88
+ A class representing the appearance stream for a text-based form field.
89
+
90
+ This class generates the content stream (the `ap_stream_data`) that dictates
91
+ how text is rendered within a form field's bounding box. It handles properties
92
+ like font, font size, color, multiline text, and text selection highlighting.
93
+ """
94
+
95
+ def _scale_text(
96
+ self,
97
+ font: Font,
98
+ font_size: float,
99
+ leading_factor: float,
100
+ field_width: float,
101
+ field_height: float,
102
+ paragraphs: list[list[WidthWordGlyphs]],
103
+ min_font_size: float,
104
+ font_size_step: float = 0.2
105
+ ) -> tuple[list[WidthWordGlyphs], float]:
106
+ """
107
+ Takes a piece of text and scales it to field_width or field_height, given font_name
108
+ and font_size. Wraps text where necessary.
109
+
110
+ Args:
111
+ font: The font to be used.
112
+ font_size: The font size in points.
113
+ leading_factor: The line distance.
114
+ field_width: The width of the field in which to fit the text.
115
+ field_height: The height of the field in which to fit the text.
116
+ paragraphs: The list of text paragraphs to fit with the field, where each paragraph is a list
117
+ of tuples of unscaled width, unencoded text, and glyphs (font-encoded text).
118
+ min_font_size: The minimum font size at which to scale the text.
119
+ font_size_step: The amount by which to decrement font size per step while scaling.
120
+
121
+ Returns:
122
+ The text in the form of list of tuples, each tuple containing the length of a line
123
+ and its contents, and the font_size for these lines and lengths.
124
+ """
125
+ wrapped_lines = []
126
+ current_line_words: list[WidthWordGlyphs] = []
127
+ current_line_width: float = 0
128
+ space_width = font.space_width * font_size / TEXT_SPACE_TO_GLYPH_SPACE_FACTOR
129
+ for paragraph in paragraphs:
130
+ for i, width_word_glyphs in enumerate(paragraph):
131
+ word_width = width_word_glyphs.width * font_size
132
+ test_width = current_line_width + word_width + (space_width if i else 0)
133
+ if test_width > field_width and current_line_words:
134
+ wrapped_lines.append(
135
+ WidthWordGlyphs(
136
+ width=current_line_width,
137
+ word=" ".join(map(attrgetter("word"), current_line_words)),
138
+ glyphs=font.space_char.join(map(attrgetter("glyphs"), current_line_words))
139
+ )
140
+ )
141
+ current_line_words = [width_word_glyphs]
142
+ current_line_width = word_width
143
+ elif not current_line_words and word_width > field_width:
144
+ wrapped_lines.append(
145
+ WidthWordGlyphs(
146
+ width=word_width,
147
+ word=width_word_glyphs.word,
148
+ glyphs=width_word_glyphs.glyphs
149
+ )
150
+ )
151
+ current_line_words = []
152
+ current_line_width = 0
153
+ else:
154
+ if current_line_words:
155
+ current_line_width += space_width
156
+ current_line_words.append(width_word_glyphs)
157
+ current_line_width += word_width
158
+ if current_line_words:
159
+ wrapped_lines.append(WidthWordGlyphs(
160
+ width=current_line_width,
161
+ word=" ".join(map(attrgetter("word"), current_line_words)),
162
+ glyphs=font.space_char.join(map(attrgetter("glyphs"), current_line_words))
163
+ ))
164
+ current_line_words = []
165
+ current_line_width = 0
166
+ # Estimate total height.
167
+ estimated_total_height = font_size + (len(wrapped_lines) - 1) * leading_factor * font_size
168
+ if estimated_total_height > field_height:
169
+ # Text overflows height; Retry with smaller font size.
170
+ new_font_size = font_size - font_size_step
171
+ if new_font_size >= min_font_size:
172
+ return self._scale_text(
173
+ font,
174
+ new_font_size,
175
+ leading_factor,
176
+ field_width,
177
+ field_height,
178
+ paragraphs,
179
+ min_font_size,
180
+ font_size_step
181
+ )
182
+ return wrapped_lines, round(font_size, 1)
183
+
184
+ def _generate_appearance_stream_data(
185
+ self,
186
+ text: str,
187
+ selection: list[str] | None ,
188
+ font: Font,
189
+ font_name: str = "/Helv",
190
+ font_size: float = 0.0,
191
+ font_color: str = "0 g",
192
+ is_multiline: bool = False,
193
+ alignment: TextAlignment = TextAlignment.LEFT,
194
+ is_comb: bool = False,
195
+ max_length: int | None = None
196
+ ) -> bytes:
197
+ """
198
+ Generates the raw bytes of the PDF appearance stream for a text field.
199
+
200
+ This private method assembles the PDF content stream operators to draw
201
+ the provided text within the specified rectangle. It handles text positioning,
202
+ font application, color, and special formatting like selected text.
203
+
204
+ Args:
205
+ text: The text to be rendered in the form field.
206
+ selection: An optional list of strings that should be highlighted as selected.
207
+ font: The font to use.
208
+ font_name: The name of the font resource to use (e.g., "/Helv").
209
+ font_size: The font size. If 0, it is automatically calculated
210
+ based on whether the field is multiline or not.
211
+ font_color: The color to apply to the font, represented as a PDF
212
+ graphics state string (e.g., "0 g" for black).
213
+ is_multiline: A boolean indicating if the text field is multiline.
214
+ alignment: Text alignment, can be TextAlignment.LEFT, .RIGHT, or .CENTER.
215
+ is_comb: Boolean that designates fixed-length fields, where every character
216
+ fills one "cell", such as in a postcode.
217
+ max_length: Used if is_comb is set. The maximum number of characters for a fixed-
218
+ length field.
219
+
220
+ Returns:
221
+ A byte string containing the PDF content stream data.
222
+
223
+ """
224
+ rectangle = self._layout.rectangle
225
+ if isinstance(rectangle, tuple):
226
+ rectangle = RectangleObject(rectangle)
227
+ leading_factor = (
228
+ (font.font_descriptor.bbox[3] - font.font_descriptor.bbox[1]) / TEXT_SPACE_TO_GLYPH_SPACE_FACTOR
229
+ )
230
+
231
+ # Set margins based on border width and style, but never less than 1 point
232
+ factor = 2 if self._layout.border_style in {"/B", "/I"} else 1
233
+ margin = max(self._layout.border_width * factor, 1)
234
+ field_height = rectangle.height - 2 * margin
235
+ field_width = rectangle.width - 4 * margin
236
+
237
+ reverse_cmap, encoding_cmap = font._get_typographic_maps()
238
+
239
+ def _unicode_to_glyph_id(text: str, reverse_cmap: dict[str, str]) -> str:
240
+ if HAS_RTL_SUPPORT:
241
+ # Use arabic-reshaper and python-bidi to rearrange and shape text for the PDF engine
242
+ reshaped_text = arabic_reshaper.reshape(text)
243
+ visual_text = get_display(reshaped_text, base_dir="L")
244
+ return "".join(reverse_cmap.get(char, char) for char in visual_text)
245
+
246
+ return "".join(reverse_cmap.get(char, char) for char in text)
247
+
248
+
249
+ def _glyph_id_to_bytes(glyphs: str, encoding_cmap: dict[str, bytes]) -> list[bytes]:
250
+ return [encoding_cmap.get(
251
+ glyph_id, bytes((ord(glyph_id),)) if ord(glyph_id) < 256 else b"?"
252
+ ) for glyph_id in glyphs]
253
+
254
+ # If font_size is 0, apply the logic for multiline or large-as-possible font
255
+ if font_size == 0:
256
+ min_font_size = 4.0 # The minimum font size
257
+ if selection: # Don't wrap text when dealing with a /Ch field, in order to prevent problems
258
+ is_multiline = False # with matching "selection" with "line" later on.
259
+ if is_multiline:
260
+ font_size = DEFAULT_FONT_SIZE_IN_MULTILINE
261
+ # We create a list of paragraphs, here each paragraph is a list of tuples, where each WidthWordGlyphs
262
+ # tuple signifies an unscaled word width, the word itself, and the glyphs that encode it.
263
+ paragraphs: list[list[WidthWordGlyphs]] = []
264
+ for line in text.splitlines():
265
+ if not line.strip():
266
+ paragraphs.append([WidthWordGlyphs(width=0.0, word="", glyphs="")])
267
+ continue
268
+ line_by_widths_words_glyphs: list[WidthWordGlyphs] = []
269
+ words = line.split(" ")
270
+ for word in words:
271
+ glyph_word = _unicode_to_glyph_id(word, reverse_cmap)
272
+ line_by_widths_words_glyphs.append(
273
+ WidthWordGlyphs(
274
+ width=font.get_text_width(word) / TEXT_SPACE_TO_GLYPH_SPACE_FACTOR,
275
+ word=word,
276
+ glyphs=glyph_word
277
+ )
278
+ )
279
+ paragraphs.append(line_by_widths_words_glyphs)
280
+ lines, font_size = self._scale_text(
281
+ font,
282
+ font_size,
283
+ leading_factor,
284
+ field_width,
285
+ field_height,
286
+ paragraphs,
287
+ min_font_size
288
+ )
289
+ else:
290
+ max_vertical_size = field_height / leading_factor
291
+ glyphs = _unicode_to_glyph_id(text, reverse_cmap)
292
+ text_width_unscaled = font.get_text_width(glyphs) / TEXT_SPACE_TO_GLYPH_SPACE_FACTOR
293
+ max_horizontal_size = field_width / (text_width_unscaled or 1)
294
+ font_size = round(max(min(max_vertical_size, max_horizontal_size), min_font_size), 1)
295
+ lines = [WidthWordGlyphs(width=text_width_unscaled * font_size, word=text, glyphs=glyphs)]
296
+ elif is_comb:
297
+ if max_length and len(text) > max_length:
298
+ logger_warning(
299
+ (
300
+ "Length of text %(text)s exceeds maximum length (%(max_length)d) "
301
+ "of field, input truncated."
302
+ ),
303
+ source=__name__,
304
+ text=text,
305
+ max_length=max_length,
306
+ )
307
+ # We act as if each character is one line, because we draw it separately later on
308
+ lines = []
309
+ for index, char in enumerate(text):
310
+ if index < (max_length or len(text)):
311
+ glyphs = _unicode_to_glyph_id(char, reverse_cmap)
312
+ lines.append(
313
+ WidthWordGlyphs(
314
+ width=font.get_text_width(glyphs) * font_size / TEXT_SPACE_TO_GLYPH_SPACE_FACTOR,
315
+ word=char,
316
+ glyphs=glyphs
317
+ )
318
+ )
319
+ else:
320
+ lines = []
321
+ for line in text.splitlines():
322
+ glyphs = _unicode_to_glyph_id(line, reverse_cmap)
323
+ lines.append(
324
+ WidthWordGlyphs(
325
+ width=font.get_text_width(glyphs) * font_size / TEXT_SPACE_TO_GLYPH_SPACE_FACTOR,
326
+ word=line,
327
+ glyphs=glyphs
328
+ )
329
+ )
330
+
331
+ # Set the vertical offset
332
+ if is_multiline:
333
+ y_offset = (
334
+ rectangle.height + margin - font.font_descriptor.bbox[3] * font_size / TEXT_SPACE_TO_GLYPH_SPACE_FACTOR
335
+ )
336
+ else:
337
+ y_offset = margin + (
338
+ (field_height - font.font_descriptor.ascent * font_size / TEXT_SPACE_TO_GLYPH_SPACE_FACTOR) / 2
339
+ )
340
+ default_appearance = f"{font_name} {font_size} Tf {font_color}"
341
+
342
+ ap_stream = (
343
+ f"q\n/Tx BMC \nq\n{2 * margin} {margin} {field_width} {field_height} "
344
+ f"re\nW\nBT\n{default_appearance}\n"
345
+ ).encode()
346
+ current_x_pos: float = 0 # Initial virtual position within the text object.
347
+
348
+ for line_number, (line_width, original_text, line) in enumerate(lines):
349
+ if selection and line in _unicode_to_glyph_id("".join(selection), reverse_cmap):
350
+ # Might be improved, but cannot find how to get fill working => replaced with lined box
351
+ ap_stream += (
352
+ f"1 {y_offset - (line_number * font_size * leading_factor) - 1} "
353
+ f"{rectangle.width - 2} {font_size + 2} re\n"
354
+ f"0.5 0.5 0.5 rg s\n{default_appearance}\n"
355
+ ).encode()
356
+
357
+ # Calculate the desired absolute starting X for the current line
358
+ desired_abs_x_start: float = 0
359
+ if is_comb and max_length:
360
+ # Calculate the width of a cell for one character
361
+ cell_width = rectangle.width / max_length
362
+ # Space from the left edge of the cell to the character's baseline start
363
+ # line_width here is the *actual* character width in points for the single character 'line'
364
+ centering_offset_in_cell = (cell_width - line_width) / 2
365
+ # Absolute start X = (Cell Index, i.e., line_number * Cell Width) + Centering Offset
366
+ desired_abs_x_start = (line_number * cell_width) + centering_offset_in_cell
367
+ elif alignment == TextAlignment.RIGHT:
368
+ desired_abs_x_start = rectangle.width - margin * 2 - line_width
369
+ elif alignment == TextAlignment.CENTER:
370
+ desired_abs_x_start = (rectangle.width - line_width) / 2
371
+ else: # Left aligned; default
372
+ desired_abs_x_start = margin * 2
373
+ # Calculate x_rel_offset: how much to move from the current_x_pos
374
+ # to reach the desired_abs_x_start.
375
+ x_rel_offset = desired_abs_x_start - current_x_pos
376
+
377
+ # Y-offset:
378
+ y_rel_offset: float = 0
379
+ if line_number == 0:
380
+ y_rel_offset = y_offset # Initial vertical position
381
+ elif is_comb:
382
+ y_rel_offset = 0.0 # DO NOT move vertically for subsequent characters
383
+ else:
384
+ y_rel_offset = - font_size * leading_factor # Move down by line height
385
+
386
+ # Td is a relative translation (Tx and Ty).
387
+ # It updates the current text position.
388
+ ap_stream += f"{x_rel_offset} {y_rel_offset} Td\n".encode()
389
+ # Update current_x_pos based on the Td operation for the next iteration.
390
+ # This is the X position where the *current line* will start.
391
+ current_x_pos = desired_abs_x_start
392
+
393
+ is_rtl = any(is_char_rtl(char) for char in line)
394
+
395
+ encoded_line = _glyph_id_to_bytes(line, encoding_cmap)
396
+ if is_rtl:
397
+ # Encode input text as UTF-16BE with a BOM, so that the input text is returned
398
+ # in the right direction when copying text from the resulting PDF
399
+ bom_text = b"\xfe\xff" + original_text.encode("utf-16-be")
400
+ hex_original_text = bom_text.hex().upper()
401
+ ap_stream += f"/Span << /ActualText <{hex_original_text}> >> BDC\n".encode()
402
+ if any(len(c) >= 2 for c in encoded_line):
403
+ ap_stream += b"<" + (b"".join(encoded_line)).hex().encode() + b"> Tj\n"
404
+ else:
405
+ ap_stream += b"(" + b"".join(encoded_line) + b") Tj\n"
406
+ if is_rtl:
407
+ ap_stream += b"EMC\n"
408
+ ap_stream += b"ET\nQ\nEMC\nQ\n"
409
+
410
+ return ap_stream
411
+
412
+ def __init__(
413
+ self,
414
+ layout: BaseStreamConfig | None = None,
415
+ text: str = "",
416
+ selection: list[str] | None = None,
417
+ font: Font | None = None,
418
+ font_resource: DictionaryObject | IndirectObject | None = None,
419
+ font_name: str = "/Helv",
420
+ font_size: float = 0.0,
421
+ font_color: str = "0 g",
422
+ is_multiline: bool = False,
423
+ alignment: TextAlignment = TextAlignment.LEFT,
424
+ is_comb: bool = False,
425
+ max_length: int | None = None
426
+ ) -> None:
427
+ """
428
+ Initializes a TextStreamAppearance object.
429
+
430
+ This constructor creates a new PDF stream object configured as an XObject
431
+ of subtype Form. It uses the `_appearance_stream_data` method to generate
432
+ the content for the stream.
433
+
434
+ Args:
435
+ layout: The basic layout parameters.
436
+ text: The text to be rendered in the form field.
437
+ selection: An optional list of strings that should be highlighted as selected.
438
+ font: A Font object. Falls back to Type 1 Helvetica if not given.
439
+ font_resource: An optional variable that represents a PDF font dictionary. Falls back
440
+ to Type 1 Helvetica if not given.
441
+ font_name: The name of the font resource, e.g., "/Helv".
442
+ font_size: The font size. If 0, it's auto-calculated.
443
+ font_color: The font color string.
444
+ is_multiline: A boolean indicating if the text field is multiline.
445
+ alignment: Text alignment, can be TextAlignment.LEFT, .RIGHT, or .CENTER.
446
+ is_comb: Boolean that designates fixed-length fields, where every character
447
+ fills one "cell", such as in a postcode.
448
+ max_length: Used if is_comb is set. The maximum number of characters for a fixed-
449
+ length field.
450
+
451
+ """
452
+ super().__init__(layout)
453
+
454
+ if not font or not font_resource:
455
+ font_name = "/Helv"
456
+ core_font_metrics = CORE_FONT_METRICS["Helvetica"]
457
+ win_ansi_encoding_list = fill_from_encoding("cp1252") # WinAnsiEncoding
458
+ font = Font(
459
+ name="Helvetica",
460
+ character_map={},
461
+ encoding=dict(zip(range(256), win_ansi_encoding_list)),
462
+ sub_type="Type1",
463
+ font_descriptor=core_font_metrics.font_descriptor,
464
+ character_widths={
465
+ chr(code): core_font_metrics.character_widths[value] for code, value in enumerate(
466
+ win_ansi_encoding_list
467
+ ) if value in core_font_metrics.character_widths
468
+ },
469
+ )
470
+ font.character_widths["default"] = core_font_metrics.character_widths["default"]
471
+ font_resource = font.as_font_resource()
472
+
473
+ ap_stream_data = self._generate_appearance_stream_data(
474
+ text,
475
+ selection,
476
+ font,
477
+ font_name=font_name,
478
+ font_size=font_size,
479
+ font_color=font_color,
480
+ is_multiline=is_multiline,
481
+ alignment=alignment,
482
+ is_comb=is_comb,
483
+ max_length=max_length
484
+ )
485
+
486
+ self.set_data(ByteStringObject(ap_stream_data))
487
+ self[NameObject("/Length")] = NumberObject(len(ap_stream_data))
488
+ # Update Resources with font information
489
+ self[NameObject("/Resources")] = DictionaryObject({
490
+ NameObject("/Font"): DictionaryObject({
491
+ NameObject(font_name): getattr(font_resource, "indirect_reference", font_resource)
492
+ })
493
+ })
494
+
495
+ @staticmethod
496
+ def _find_annotation_font_resource(
497
+ font_name: str,
498
+ annotation: DictionaryObject,
499
+ acro_form: DictionaryObject,
500
+ text: str
501
+ ) -> tuple[str, Font]:
502
+ # Try to find a resource dictionary for the font by examining the annotation and, if that fails,
503
+ # the AcroForm resources dictionary
504
+ acro_form_resources: Any = cast(
505
+ DictionaryObject,
506
+ annotation.get_inherited(
507
+ "/DR",
508
+ acro_form.get("/DR", DictionaryObject()),
509
+ ),
510
+ )
511
+ acro_form_font_resources = acro_form_resources.get("/Font", DictionaryObject())
512
+ font_resource = acro_form_font_resources.get(font_name, None)
513
+ if font_resource:
514
+ font = Font.from_font_resource(font_resource)
515
+ else:
516
+ # Normally, we should have found a font resource by now. However, when a user has provided a specific
517
+ # font name, we may not have found the associated font resource among the AcroForm resources. Also, in
518
+ # case of the 14 Adobe Core fonts, we may be expected to construct a font resource ourselves.
519
+ if font_name.removeprefix("/") not in CORE_FONT_METRICS:
520
+ # Default to Helvetica if we haven't found a font resource and cannot construct one ourselves.
521
+ logger_warning(
522
+ "Font dictionary for %(font_name)s not found; defaulting to Helvetica.",
523
+ source=__name__,
524
+ font_name=font_name,
525
+ )
526
+ font_name = "/Helvetica"
527
+ core_font_metrics = CORE_FONT_METRICS[font_name.removeprefix("/")]
528
+ font = Font(
529
+ name=font_name.removeprefix("/"),
530
+ character_map={},
531
+ encoding=dict(zip(range(256), fill_from_encoding("cp1252"))), # WinAnsiEncoding
532
+ sub_type="Type1",
533
+ font_descriptor=core_font_metrics.font_descriptor,
534
+ character_widths=core_font_metrics.character_widths
535
+ )
536
+
537
+ # If we have found a font resource, it still might not be able to encode the text value we received.
538
+ encodable = font.can_encode(text)
539
+
540
+ if not encodable:
541
+ # If we have a font file, we can try to produce a new font resource with an encoding
542
+ # that does include the necessary characters.
543
+ if font.font_descriptor.font_file and font.sub_type == "TrueType":
544
+ try:
545
+ font = font.from_truetype_font_file(BytesIO(font.font_descriptor.font_file.get_data()))
546
+ font_name = "/PYPDF1" # This means we most probably do not clash with an existing font name
547
+ encodable = font.can_encode(text)
548
+ except (ImportError, PdfReadError) as e:
549
+ logger_warning("Unable to use embedded font for encoding: %(e)s", source=__name__, e=e)
550
+
551
+ if not encodable:
552
+ logger_warning(
553
+ (
554
+ "Text string '%(text)s' contains characters not supported by font encoding. "
555
+ "This may result in text corruption. "
556
+ "Consider calling writer.update_page_form_field_values with auto_regenerate=True."
557
+ ),
558
+ source=__name__,
559
+ text=text,
560
+ )
561
+
562
+ return font_name, font
563
+
564
+ @staticmethod
565
+ def _sync_appearance_stream_font_resources(
566
+ writer: PdfWriter,
567
+ font_name: str,
568
+ font: Font,
569
+ target_resource_dict: DictionaryObject,
570
+ page: PageObject | None = None
571
+ ) -> IndirectObject:
572
+ """
573
+ Unified helper to sync fonts from an AP stream to a target resource dictionary (e.g., AcroForm /DR).
574
+ Will sync to page resources as well when page is added to the arguments.
575
+ """
576
+ target_fonts = target_resource_dict.setdefault(NameObject("/Font"), DictionaryObject()).get_object()
577
+ if font_name not in target_fonts:
578
+ font_resource_reference = font._add_to_writer(
579
+ writer,
580
+ target_fonts,
581
+ NameObject(font_name)
582
+ )
583
+ else:
584
+ font_resource_reference = target_fonts[font_name]
585
+
586
+ if page:
587
+ page_fonts_resource = cast(DictionaryObject, page[PageAttributes.RESOURCES]).setdefault(
588
+ NameObject("/Font"), DictionaryObject()
589
+ ).get_object()
590
+ if font_name not in page_fonts_resource:
591
+ page_fonts_resource[NameObject(font_name)] = getattr(
592
+ font_resource_reference, "indirect_reference", font_resource_reference
593
+ )
594
+
595
+ return font_resource_reference
596
+
597
+ @classmethod
598
+ def from_text_annotation(
599
+ cls,
600
+ writer: PdfWriter,
601
+ page: PageObject,
602
+ flatten: bool,
603
+ acro_form: DictionaryObject, # _root_object[CatalogDictionary.ACRO_FORM])
604
+ field: DictionaryObject,
605
+ annotation: DictionaryObject,
606
+ user_font_name: str = "",
607
+ user_font_size: float = -1,
608
+ ) -> TextStreamAppearance:
609
+ """
610
+ Creates a TextStreamAppearance object from a text field annotation.
611
+
612
+ This class method is a factory for creating a `TextStreamAppearance`
613
+ instance by extracting all necessary information (bounding box, font,
614
+ text content, etc.) from the PDF field and annotation dictionaries.
615
+ It respects inheritance for properties like default appearance (`/DA`).
616
+
617
+ Args:
618
+ writer: The PdfWriter instance that we are creating text stream appearances for.
619
+ page: The page that we are processing annotations for.
620
+ flatten: Whether we flatten text annotations or not. If true, add new font resource
621
+ to the page font resources. Otherwise, add them to the AcroForm resources.
622
+ acro_form: The root AcroForm dictionary from the PDF catalog.
623
+ field: The field dictionary object.
624
+ annotation: The widget annotation dictionary object associated with the field.
625
+ user_font_name: An optional user-provided font name to override the
626
+ default. Defaults to an empty string.
627
+ user_font_size: An optional user-provided font size to override the
628
+ default. A value of -1 indicates no override.
629
+
630
+ Returns:
631
+ A new `TextStreamAppearance` instance configured for the given field.
632
+
633
+ """
634
+ # Calculate rectangle dimensions
635
+ _rectangle = cast(RectangleObject, annotation[AnnotationDictionaryAttributes.Rect])
636
+ rectangle = RectangleObject((0, 0, abs(_rectangle[2] - _rectangle[0]), abs(_rectangle[3] - _rectangle[1])))
637
+
638
+ # Get default appearance dictionary from annotation
639
+ default_appearance = annotation.get_inherited(
640
+ AnnotationDictionaryAttributes.DA,
641
+ acro_form.get(AnnotationDictionaryAttributes.DA, None),
642
+ )
643
+ if not default_appearance:
644
+ # Create a default appearance if none was found in the annotation
645
+ default_appearance = TextStringObject("/Helv 0 Tf 0 g")
646
+ else:
647
+ default_appearance = default_appearance.get_object()
648
+
649
+ # Retrieve field text and selected values
650
+ field_flags = field.get(FieldDictionaryAttributes.Ff, 0)
651
+ if (
652
+ field.get(FieldDictionaryAttributes.FT, "/Tx") == "/Ch" and
653
+ field_flags & FieldDictionaryAttributes.FfBits.Combo == 0
654
+ ):
655
+ text = "\n".join(annotation.get_inherited(FieldDictionaryAttributes.Opt, []))
656
+ selection = field.get("/V", [])
657
+ if not isinstance(selection, list):
658
+ selection = [selection]
659
+ else: # /Tx
660
+ text = field.get("/V", "")
661
+ selection = []
662
+
663
+ # Escape parentheses (PDF 1.7 reference, table 3.2, Literal Strings)
664
+ text = text.replace("\\", "\\\\").replace("(", r"\(").replace(")", r"\)")
665
+
666
+ # Derive font name, size and color from the default appearance. Also set
667
+ # user-provided font name and font size in the default appearance, if given.
668
+ # For a font name, this presumes that we can find an associated font resource
669
+ # dictionary. Uses the variable font_properties as an intermediate.
670
+ # As per the PDF spec:
671
+ # "At a minimum, the string [that is, default_appearance] shall include a Tf (text
672
+ # font) operator along with its two operands, font and size" (Section 12.7.4.3
673
+ # "Variable text" of the PDF 2.0 specification).
674
+ font_properties = [prop for prop in re.split(r"\s", default_appearance) if prop]
675
+ da_font_name = font_properties.pop(font_properties.index("Tf") - 2)
676
+ font_size = float(font_properties.pop(font_properties.index("Tf") - 1))
677
+ font_properties.remove("Tf")
678
+ font_color = " ".join(font_properties)
679
+ # Determine the font name to use, prioritizing the user's input
680
+ if user_font_name:
681
+ font_name = user_font_name
682
+ else:
683
+ font_name = da_font_name
684
+ # Determine the font size to use, prioritizing the user's input
685
+ if user_font_size > 0:
686
+ font_size = user_font_size
687
+
688
+ font_name, font = cls._find_annotation_font_resource(font_name, annotation, acro_form, text)
689
+
690
+ # Change the /DA information if we changed the font name
691
+ if font_name != da_font_name:
692
+ annotation[NameObject("/DA")] = TextStringObject(default_appearance.replace(da_font_name, font_name))
693
+
694
+ # Synchronise font resources
695
+ font_resource_reference = cls._sync_appearance_stream_font_resources(
696
+ writer,
697
+ font_name,
698
+ font,
699
+ acro_form.setdefault(NameObject("/DR"), DictionaryObject()),
700
+ page if flatten else None,
701
+ )
702
+
703
+ # Retrieve formatting information
704
+ is_comb = False
705
+ max_length = None
706
+ if field_flags & FieldDictionaryAttributes.FfBits.Comb:
707
+ is_comb = True
708
+ max_length = annotation.get("/MaxLen")
709
+ is_multiline = False
710
+ if field_flags & FieldDictionaryAttributes.FfBits.Multiline:
711
+ is_multiline = True
712
+ alignment = field.get("/Q", TextAlignment.LEFT)
713
+ border_width = 1
714
+ border_style = BorderStyles.SOLID
715
+ if "/BS" in field:
716
+ border_width = cast(DictionaryObject, field["/BS"]).get("/W", border_width)
717
+ border_style = cast(DictionaryObject, field["/BS"]).get("/S", border_style)
718
+
719
+ # Create the TextStreamAppearance instance
720
+ layout = BaseStreamConfig(rectangle=rectangle, border_width=border_width, border_style=border_style)
721
+ new_appearance_stream = cls(
722
+ layout,
723
+ text,
724
+ selection,
725
+ font,
726
+ font_resource_reference,
727
+ font_name=font_name,
728
+ font_size=font_size,
729
+ font_color=font_color,
730
+ is_multiline=is_multiline,
731
+ alignment=alignment,
732
+ is_comb=is_comb,
733
+ max_length=max_length
734
+ )
735
+
736
+ if AnnotationDictionaryAttributes.AP in annotation:
737
+ for key, value in (
738
+ cast(DictionaryObject, annotation[AnnotationDictionaryAttributes.AP]).get("/N", {}).items()
739
+ ):
740
+ if key in {"/BBox", "/Length", "/Subtype", "/Type", "/Filter"}:
741
+ continue
742
+ # Don't overwrite font resources added by TextAppearanceStream.__init__
743
+ if key == "/Resources":
744
+ if "/Font" not in value:
745
+ value.get_object()[NameObject("/Font")] = DictionaryObject()
746
+ value["/Font"].get_object()[NameObject(font_name)] = getattr(
747
+ font_resource_reference, "indirect_reference", font_resource_reference
748
+ )
749
+ else:
750
+ new_appearance_stream[key] = value
751
+
752
+ return new_appearance_stream
.venv/lib/python3.13/site-packages/pypdf/generic/_base.py ADDED
@@ -0,0 +1,960 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2006, Mathieu Fenniak
2
+ # All rights reserved.
3
+ #
4
+ # Redistribution and use in source and binary forms, with or without
5
+ # modification, are permitted provided that the following conditions are
6
+ # met:
7
+ #
8
+ # * Redistributions of source code must retain the above copyright notice,
9
+ # this list of conditions and the following disclaimer.
10
+ # * Redistributions in binary form must reproduce the above copyright notice,
11
+ # this list of conditions and the following disclaimer in the documentation
12
+ # and/or other materials provided with the distribution.
13
+ # * The name of the author may not be used to endorse or promote products
14
+ # derived from this software without specific prior written permission.
15
+ #
16
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26
+ # POSSIBILITY OF SUCH DAMAGE.
27
+ import binascii
28
+ import codecs
29
+ import hashlib
30
+ import re
31
+ import sys
32
+ from collections.abc import Sequence
33
+ from math import log10
34
+ from struct import iter_unpack
35
+ from typing import Any, Callable, ClassVar, Optional, Union, cast
36
+
37
+ if sys.version_info[:2] >= (3, 10):
38
+ from typing import TypeGuard
39
+ else:
40
+ from typing_extensions import TypeGuard # PEP 647
41
+
42
+ if sys.version_info >= (3, 11):
43
+ from typing import Self
44
+ else:
45
+ from typing_extensions import Self
46
+
47
+ from .._codecs import _pdfdoc_encoding_rev
48
+ from .._protocols import PdfObjectProtocol, PdfWriterProtocol
49
+ from .._utils import (
50
+ StreamType,
51
+ classproperty,
52
+ deprecation_no_replacement,
53
+ deprecation_with_replacement,
54
+ logger_warning,
55
+ read_non_whitespace,
56
+ read_until_regex,
57
+ )
58
+ from ..errors import STREAM_TRUNCATED_PREMATURELY, PdfReadError, PdfStreamError
59
+
60
+ __author__ = "Mathieu Fenniak"
61
+ __author_email__ = "biziqe@mathieu.fenniak.net"
62
+
63
+
64
+ class PdfObject(PdfObjectProtocol):
65
+ # function for calculating a hash value
66
+ hash_func: Callable[..., "hashlib._Hash"] = hashlib.sha1
67
+ indirect_reference: Optional["IndirectObject"]
68
+
69
+ def hash_bin(self) -> int:
70
+ """
71
+ Used to detect modified object.
72
+
73
+ Returns:
74
+ Hash considering type and value.
75
+
76
+ """
77
+ raise NotImplementedError(
78
+ f"{self.__class__.__name__} does not implement .hash_bin() so far"
79
+ )
80
+
81
+ def hash_value_data(self) -> bytes:
82
+ return f"{self}".encode()
83
+
84
+ def hash_value(self) -> bytes:
85
+ return (
86
+ f"{self.__class__.__name__}:"
87
+ f"{self.hash_func(self.hash_value_data()).hexdigest()}"
88
+ ).encode()
89
+
90
+ def replicate(
91
+ self,
92
+ pdf_dest: PdfWriterProtocol,
93
+ ) -> "PdfObject":
94
+ """
95
+ Clone object into pdf_dest (PdfWriterProtocol which is an interface for PdfWriter)
96
+ without ensuring links. This is used in clone_document_from_root with incremental = True.
97
+
98
+ Args:
99
+ pdf_dest: Target to clone to.
100
+
101
+ Returns:
102
+ The cloned PdfObject
103
+
104
+ """
105
+ return self.clone(pdf_dest)
106
+
107
+ def clone(
108
+ self,
109
+ pdf_dest: PdfWriterProtocol,
110
+ force_duplicate: bool = False,
111
+ ignore_fields: Optional[Sequence[Union[str, int]]] = (),
112
+ ) -> "PdfObject":
113
+ """
114
+ Clone object into pdf_dest (PdfWriterProtocol which is an interface for PdfWriter).
115
+
116
+ By default, this method will call ``_reference_clone`` (see ``_reference``).
117
+
118
+
119
+ Args:
120
+ pdf_dest: Target to clone to.
121
+ force_duplicate: By default, if the object has already been cloned and referenced,
122
+ the copy will be returned; when ``True``, a new copy will be created.
123
+ (Default value = ``False``)
124
+ ignore_fields: List/tuple of field names (for dictionaries) that will be ignored
125
+ during cloning (applies to children duplication as well). If fields are to be
126
+ considered for a limited number of levels, you have to add it as integer, for
127
+ example ``[1,"/B","/TOTO"]`` means that ``"/B"`` will be ignored at the first
128
+ level only but ``"/TOTO"`` on all levels.
129
+
130
+ Returns:
131
+ The cloned PdfObject
132
+
133
+ """
134
+ raise NotImplementedError(
135
+ f"{self.__class__.__name__} does not implement .clone so far"
136
+ )
137
+
138
+ def _reference_clone(
139
+ self, clone: "PdfObject", pdf_dest: PdfWriterProtocol, force_duplicate: bool = False
140
+ ) -> "PdfObject":
141
+ """
142
+ Reference the object within the _objects of pdf_dest only if
143
+ indirect_reference attribute exists (which means the objects was
144
+ already identified in xref/xobjstm) if object has been already
145
+ referenced do nothing.
146
+
147
+ Args:
148
+ clone:
149
+ pdf_dest:
150
+
151
+ Returns:
152
+ The clone
153
+
154
+ """
155
+ try:
156
+ if (
157
+ not force_duplicate
158
+ and clone.indirect_reference is not None
159
+ and clone.indirect_reference.pdf == pdf_dest
160
+ ):
161
+ return clone
162
+ except Exception:
163
+ pass
164
+ # if hasattr(clone, "indirect_reference"):
165
+ try:
166
+ ind = self.indirect_reference
167
+ except AttributeError:
168
+ return clone
169
+ if (
170
+ pdf_dest.incremental
171
+ and ind is not None
172
+ and ind.pdf == pdf_dest._reader
173
+ and ind.idnum <= len(pdf_dest._objects)
174
+ ):
175
+ i = ind.idnum
176
+ else:
177
+ i = len(pdf_dest._objects) + 1
178
+ if ind is not None:
179
+ if id(ind.pdf) not in pdf_dest._id_translated:
180
+ pdf_dest._id_translated[id(ind.pdf)] = {}
181
+ pdf_dest._id_translated[id(ind.pdf)]["PreventGC"] = ind.pdf # type: ignore[index]
182
+ if (
183
+ not force_duplicate
184
+ and ind.idnum in pdf_dest._id_translated[id(ind.pdf)]
185
+ ):
186
+ obj = pdf_dest.get_object(
187
+ pdf_dest._id_translated[id(ind.pdf)][ind.idnum]
188
+ )
189
+ assert isinstance(obj, PdfObject), "mypy"
190
+ return obj
191
+ pdf_dest._id_translated[id(ind.pdf)][ind.idnum] = i
192
+ try:
193
+ pdf_dest._objects[i - 1] = clone
194
+ except IndexError:
195
+ pdf_dest._objects.append(clone)
196
+ i = len(pdf_dest._objects)
197
+ clone.indirect_reference = IndirectObject(i, 0, pdf_dest)
198
+ return clone
199
+
200
+ def get_object(self) -> Optional["PdfObject"]:
201
+ """Resolve indirect references."""
202
+ return self
203
+
204
+ def write_to_stream(
205
+ self, stream: StreamType, encryption_key: Union[str, bytes, None] = None
206
+ ) -> None:
207
+ raise NotImplementedError
208
+
209
+
210
+ class NullObject(PdfObject):
211
+ def clone(
212
+ self,
213
+ pdf_dest: PdfWriterProtocol,
214
+ force_duplicate: bool = False,
215
+ ignore_fields: Optional[Sequence[Union[str, int]]] = (),
216
+ ) -> "NullObject":
217
+ """Clone object into pdf_dest."""
218
+ return cast(
219
+ "NullObject", self._reference_clone(NullObject(), pdf_dest, force_duplicate)
220
+ )
221
+
222
+ def hash_bin(self) -> int:
223
+ """
224
+ Used to detect modified object.
225
+
226
+ Returns:
227
+ Hash considering type and value.
228
+
229
+ """
230
+ return hash((self.__class__,))
231
+
232
+ def write_to_stream(
233
+ self, stream: StreamType, encryption_key: Union[str, bytes, None] = None
234
+ ) -> None:
235
+ if encryption_key is not None: # deprecated
236
+ deprecation_no_replacement(
237
+ "the encryption_key parameter of write_to_stream", "5.0.0"
238
+ )
239
+ stream.write(b"null")
240
+
241
+ @staticmethod
242
+ def read_from_stream(stream: StreamType) -> "NullObject":
243
+ nulltxt = stream.read(4)
244
+ if nulltxt != b"null":
245
+ raise PdfReadError("Could not read Null object")
246
+ return NullObject()
247
+
248
+ def __repr__(self) -> str:
249
+ return "NullObject"
250
+
251
+ def __eq__(self, other: object) -> bool:
252
+ return isinstance(other, NullObject)
253
+
254
+ def __hash__(self) -> int:
255
+ return self.hash_bin()
256
+
257
+
258
+ class BooleanObject(PdfObject):
259
+ value: bool
260
+
261
+ def __init__(self, value: Any) -> None:
262
+ self.value = value
263
+
264
+ def clone(
265
+ self,
266
+ pdf_dest: PdfWriterProtocol,
267
+ force_duplicate: bool = False,
268
+ ignore_fields: Optional[Sequence[Union[str, int]]] = (),
269
+ ) -> "BooleanObject":
270
+ """Clone object into pdf_dest."""
271
+ return cast(
272
+ "BooleanObject",
273
+ self._reference_clone(BooleanObject(self.value), pdf_dest, force_duplicate),
274
+ )
275
+
276
+ def hash_bin(self) -> int:
277
+ """
278
+ Used to detect modified object.
279
+
280
+ Returns:
281
+ Hash considering type and value.
282
+
283
+ """
284
+ return hash((self.__class__, self.value))
285
+
286
+ def __eq__(self, o: object, /) -> bool:
287
+ if isinstance(o, BooleanObject):
288
+ return self.value == o.value
289
+ if isinstance(o, bool):
290
+ return self.value == o
291
+ return False
292
+
293
+ def __hash__(self) -> int:
294
+ return self.hash_bin()
295
+
296
+ def __repr__(self) -> str:
297
+ return "True" if self.value else "False"
298
+
299
+ def write_to_stream(
300
+ self, stream: StreamType, encryption_key: Union[str, bytes, None] = None
301
+ ) -> None:
302
+ if encryption_key is not None: # deprecated
303
+ deprecation_no_replacement(
304
+ "the encryption_key parameter of write_to_stream", "5.0.0"
305
+ )
306
+ if self.value:
307
+ stream.write(b"true")
308
+ else:
309
+ stream.write(b"false")
310
+
311
+ @staticmethod
312
+ def read_from_stream(stream: StreamType) -> "BooleanObject":
313
+ word = stream.read(4)
314
+ if word == b"true":
315
+ return BooleanObject(True)
316
+ if word == b"fals":
317
+ stream.read(1)
318
+ return BooleanObject(False)
319
+ raise PdfReadError("Could not read Boolean object")
320
+
321
+
322
+ class IndirectObject(PdfObject):
323
+ def __init__(self, idnum: int, generation: int, pdf: Any) -> None: # PdfReader
324
+ self.idnum = idnum
325
+ self.generation = generation
326
+ self.pdf = pdf
327
+
328
+ def __hash__(self) -> int:
329
+ return hash((self.idnum, self.generation, id(self.pdf)))
330
+
331
+ def hash_bin(self) -> int:
332
+ """
333
+ Used to detect modified object.
334
+
335
+ Returns:
336
+ Hash considering type and value.
337
+
338
+ """
339
+ return hash((self.__class__, self.idnum, self.generation, id(self.pdf)))
340
+
341
+ def replicate(
342
+ self,
343
+ pdf_dest: PdfWriterProtocol,
344
+ ) -> "PdfObject":
345
+ return IndirectObject(self.idnum, self.generation, pdf_dest)
346
+
347
+ def clone(
348
+ self,
349
+ pdf_dest: PdfWriterProtocol,
350
+ force_duplicate: bool = False,
351
+ ignore_fields: Optional[Sequence[Union[str, int]]] = (),
352
+ ) -> "IndirectObject":
353
+ """Clone object into pdf_dest."""
354
+ if self.pdf == pdf_dest and not force_duplicate:
355
+ # Already duplicated and no extra duplication required
356
+ return self
357
+ if id(self.pdf) not in pdf_dest._id_translated:
358
+ pdf_dest._id_translated[id(self.pdf)] = {}
359
+ pdf_dest._id_translated[id(self.pdf)]["PreventGC"] = self.pdf # type: ignore[index]
360
+
361
+ if self.idnum in pdf_dest._id_translated[id(self.pdf)]:
362
+ dup = pdf_dest.get_object(pdf_dest._id_translated[id(self.pdf)][self.idnum])
363
+ if force_duplicate:
364
+ assert dup is not None
365
+ assert dup.indirect_reference is not None
366
+ idref = dup.indirect_reference
367
+ return IndirectObject(idref.idnum, idref.generation, idref.pdf)
368
+ else:
369
+ obj = self.get_object()
370
+ # case observed : a pointed object can not be found
371
+ if obj is None:
372
+ # this normally
373
+ obj = NullObject()
374
+ assert isinstance(self, (IndirectObject,))
375
+ obj.indirect_reference = self
376
+ dup = pdf_dest._add_object(
377
+ obj.clone(pdf_dest, force_duplicate, ignore_fields)
378
+ )
379
+ assert isinstance(dup, PdfObject), "mypy"
380
+ assert dup.indirect_reference is not None, "mypy"
381
+ return dup.indirect_reference
382
+
383
+ @property
384
+ def indirect_reference(self) -> "IndirectObject": # type: ignore[override]
385
+ return self
386
+
387
+ def get_object(self) -> Optional["PdfObject"]:
388
+ obj: Optional[PdfObject] = self.pdf.get_object(self)
389
+ return obj
390
+
391
+ def __deepcopy__(self, memo: Any) -> "IndirectObject":
392
+ return IndirectObject(self.idnum, self.generation, self.pdf)
393
+
394
+ def _get_object_with_check(self) -> Optional["PdfObject"]:
395
+ o = self.get_object()
396
+ # the check is done here to not slow down get_object()
397
+ if isinstance(o, IndirectObject):
398
+ raise PdfStreamError(
399
+ f"{self.__repr__()} references an IndirectObject {o.__repr__()}"
400
+ )
401
+ return o
402
+
403
+ def __getattr__(self, name: str) -> Any:
404
+ # Attribute not found in object: look in pointed object
405
+ try:
406
+ return getattr(self._get_object_with_check(), name)
407
+ except AttributeError:
408
+ raise AttributeError(
409
+ f"No attribute {name} found in IndirectObject or pointed object"
410
+ )
411
+
412
+ def __getitem__(self, key: Any) -> Any:
413
+ # items should be extracted from pointed Object
414
+ return self._get_object_with_check()[key] # type: ignore[index]
415
+
416
+ def __contains__(self, key: Any) -> bool:
417
+ return key in self._get_object_with_check() # type: ignore[operator]
418
+
419
+ def __iter__(self) -> Any:
420
+ return self._get_object_with_check().__iter__() # type: ignore[union-attr]
421
+
422
+ def __float__(self) -> str:
423
+ # in this case we are looking for the pointed data
424
+ return self.get_object().__float__() # type: ignore[union-attr, no-any-return]
425
+
426
+ def __int__(self) -> int:
427
+ # in this case we are looking for the pointed data
428
+ return self.get_object().__int__() # type: ignore[union-attr, no-any-return]
429
+
430
+ def __str__(self) -> str:
431
+ # in this case we are looking for the pointed data
432
+ return self.get_object().__str__()
433
+
434
+ def __repr__(self) -> str:
435
+ return f"IndirectObject({self.idnum!r}, {self.generation!r}, {id(self.pdf)})"
436
+
437
+ def __eq__(self, other: object) -> bool:
438
+ return (
439
+ other is not None
440
+ and isinstance(other, IndirectObject)
441
+ and self.idnum == other.idnum
442
+ and self.generation == other.generation
443
+ and self.pdf is other.pdf
444
+ )
445
+
446
+ def __ne__(self, other: object) -> bool:
447
+ return not self.__eq__(other)
448
+
449
+ def write_to_stream(
450
+ self, stream: StreamType, encryption_key: Union[str, bytes, None] = None
451
+ ) -> None:
452
+ if encryption_key is not None: # deprecated
453
+ deprecation_no_replacement(
454
+ "the encryption_key parameter of write_to_stream", "5.0.0"
455
+ )
456
+ stream.write(f"{self.idnum} {self.generation} R".encode())
457
+
458
+ @staticmethod
459
+ def read_from_stream(stream: StreamType, pdf: Any) -> "IndirectObject": # PdfReader
460
+ idnum = b""
461
+ while True:
462
+ tok = stream.read(1)
463
+ if not tok:
464
+ raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY)
465
+ if tok.isspace():
466
+ break
467
+ idnum += tok
468
+ generation = b""
469
+ while True:
470
+ tok = stream.read(1)
471
+ if not tok:
472
+ raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY)
473
+ if tok.isspace():
474
+ if not generation:
475
+ continue
476
+ break
477
+ generation += tok
478
+ r = read_non_whitespace(stream)
479
+ if r != b"R":
480
+ raise PdfReadError(
481
+ f"Error reading indirect object reference at byte {hex(stream.tell())}"
482
+ )
483
+ return IndirectObject(int(idnum), int(generation), pdf)
484
+
485
+
486
+ FLOAT_WRITE_PRECISION = 8 # shall be min 5 digits max, allow user adj
487
+
488
+
489
+ class FloatObject(float, PdfObject):
490
+ def __new__(
491
+ cls, value: Any = "0.0", context: Optional[Any] = None
492
+ ) -> Self:
493
+ try:
494
+ value = float(value)
495
+ return float.__new__(cls, value)
496
+ except Exception as e:
497
+ # If this isn't a valid decimal (happens in malformed PDFs)
498
+ # fallback to 0
499
+ logger_warning(
500
+ "%(error)s : FloatObject (%(value)s) invalid; use 0.0 instead",
501
+ source=__name__,
502
+ error=e,
503
+ value=value,
504
+ )
505
+ return float.__new__(cls, 0.0)
506
+
507
+ def clone(
508
+ self,
509
+ pdf_dest: Any,
510
+ force_duplicate: bool = False,
511
+ ignore_fields: Optional[Sequence[Union[str, int]]] = (),
512
+ ) -> "FloatObject":
513
+ """Clone object into pdf_dest."""
514
+ return cast(
515
+ "FloatObject",
516
+ self._reference_clone(FloatObject(self), pdf_dest, force_duplicate),
517
+ )
518
+
519
+ def hash_bin(self) -> int:
520
+ """
521
+ Used to detect modified object.
522
+
523
+ Returns:
524
+ Hash considering type and value.
525
+
526
+ """
527
+ return hash((self.__class__, self.as_numeric))
528
+
529
+ def myrepr(self) -> str:
530
+ if self == 0: # type: ignore[comparison-overlap]
531
+ return "0.0"
532
+ nb = FLOAT_WRITE_PRECISION - int(log10(abs(self)))
533
+ return f"{self:.{max(1, nb)}f}".rstrip("0").rstrip(".")
534
+
535
+ def __repr__(self) -> str:
536
+ return self.myrepr() # repr(float(self))
537
+
538
+ def as_numeric(self) -> float:
539
+ return float(self)
540
+
541
+ def write_to_stream(
542
+ self, stream: StreamType, encryption_key: Union[str, bytes, None] = None
543
+ ) -> None:
544
+ if encryption_key is not None: # deprecated
545
+ deprecation_no_replacement(
546
+ "the encryption_key parameter of write_to_stream", "5.0.0"
547
+ )
548
+ stream.write(self.myrepr().encode("utf8"))
549
+
550
+
551
+ class NumberObject(int, PdfObject):
552
+ NumberPattern = re.compile(b"[^+-.0-9]")
553
+ _LENGTH_LIMIT = 64
554
+
555
+ def __new__(cls, value: Any) -> Self:
556
+ try:
557
+ return int.__new__(cls, int(value))
558
+ except ValueError:
559
+ logger_warning("NumberObject(%(value)s) invalid; use 0 instead", source=__name__, value=value)
560
+ return int.__new__(cls, 0)
561
+
562
+ def clone(
563
+ self,
564
+ pdf_dest: Any,
565
+ force_duplicate: bool = False,
566
+ ignore_fields: Optional[Sequence[Union[str, int]]] = (),
567
+ ) -> "NumberObject":
568
+ """Clone object into pdf_dest."""
569
+ return cast(
570
+ "NumberObject",
571
+ self._reference_clone(NumberObject(self), pdf_dest, force_duplicate),
572
+ )
573
+
574
+ def hash_bin(self) -> int:
575
+ """
576
+ Used to detect modified object.
577
+
578
+ Returns:
579
+ Hash considering type and value.
580
+
581
+ """
582
+ return hash((self.__class__, self.as_numeric()))
583
+
584
+ def as_numeric(self) -> int:
585
+ return int(repr(self).encode("utf8"))
586
+
587
+ def write_to_stream(
588
+ self, stream: StreamType, encryption_key: Union[str, bytes, None] = None
589
+ ) -> None:
590
+ if encryption_key is not None: # deprecated
591
+ deprecation_no_replacement(
592
+ "the encryption_key parameter of write_to_stream", "5.0.0"
593
+ )
594
+ stream.write(repr(self).encode("utf8"))
595
+
596
+ @staticmethod
597
+ def read_from_stream(stream: StreamType) -> Union["NumberObject", "FloatObject"]:
598
+ num = read_until_regex(stream=stream, regex=NumberObject.NumberPattern, length=NumberObject._LENGTH_LIMIT)
599
+ if b"." in num:
600
+ return FloatObject(num)
601
+ return NumberObject(num)
602
+
603
+
604
+ class ByteStringObject(bytes, PdfObject):
605
+ """
606
+ Represents a string object where the text encoding could not be determined.
607
+
608
+ This occurs quite often, as the PDF spec doesn't provide an alternate way to
609
+ represent strings -- for example, the encryption data stored in files (like
610
+ /O) is clearly not text, but is still stored in a "String" object.
611
+ """
612
+
613
+ def clone(
614
+ self,
615
+ pdf_dest: Any,
616
+ force_duplicate: bool = False,
617
+ ignore_fields: Optional[Sequence[Union[str, int]]] = (),
618
+ ) -> "ByteStringObject":
619
+ """Clone object into pdf_dest."""
620
+ return cast(
621
+ "ByteStringObject",
622
+ self._reference_clone(
623
+ ByteStringObject(bytes(self)), pdf_dest, force_duplicate
624
+ ),
625
+ )
626
+
627
+ def hash_bin(self) -> int:
628
+ """
629
+ Used to detect modified object.
630
+
631
+ Returns:
632
+ Hash considering type and value.
633
+
634
+ """
635
+ return hash((self.__class__, bytes(self)))
636
+
637
+ @property
638
+ def original_bytes(self) -> bytes:
639
+ """For compatibility with TextStringObject.original_bytes."""
640
+ return self
641
+
642
+ def write_to_stream(
643
+ self, stream: StreamType, encryption_key: Union[str, bytes, None] = None
644
+ ) -> None:
645
+ if encryption_key is not None: # deprecated
646
+ deprecation_no_replacement(
647
+ "the encryption_key parameter of write_to_stream", "5.0.0"
648
+ )
649
+ stream.write(b"<")
650
+ stream.write(binascii.hexlify(self))
651
+ stream.write(b">")
652
+
653
+ def __str__(self) -> str:
654
+ charset_to_try = ["utf-16", *list(NameObject.CHARSETS)]
655
+ for enc in charset_to_try:
656
+ try:
657
+ return self.decode(enc)
658
+ except UnicodeDecodeError:
659
+ pass
660
+ raise PdfReadError("Cannot decode ByteStringObject.")
661
+
662
+
663
+ class TextStringObject(str, PdfObject): # noqa: SLOT000
664
+ """
665
+ A string object that has been decoded into a real unicode string.
666
+
667
+ If read from a PDF document, this string appeared to match the
668
+ PDFDocEncoding, or contained a UTF-16BE BOM mark to cause UTF-16 decoding
669
+ to occur.
670
+ """
671
+
672
+ autodetect_pdfdocencoding: bool
673
+ autodetect_utf16: bool
674
+ utf16_bom: bytes
675
+ _original_bytes: Optional[bytes] = None
676
+
677
+ def __new__(cls, value: Any) -> Self:
678
+ original_bytes = None
679
+ if isinstance(value, bytes):
680
+ original_bytes = value
681
+ value = value.decode("charmap")
682
+ text_string_object = str.__new__(cls, value)
683
+ text_string_object._original_bytes = original_bytes
684
+ text_string_object.autodetect_utf16 = False
685
+ text_string_object.autodetect_pdfdocencoding = False
686
+ text_string_object.utf16_bom = b""
687
+ if original_bytes is not None and original_bytes[:2] in {codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE}:
688
+ # The value of `original_bytes` is only set for inputs being `bytes`.
689
+ # If this is UTF-16 data according to the BOM (first two characters),
690
+ # perform special handling. All other cases should not need any special conversion
691
+ # due to already being a string.
692
+ try:
693
+ text_string_object = str.__new__(cls, original_bytes.decode("utf-16"))
694
+ except UnicodeDecodeError as exception:
695
+ logger_warning(
696
+ "%(exception)s; initial string: %(initial_string)r",
697
+ source=__name__,
698
+ exception=exception,
699
+ initial_string=exception.object,
700
+ )
701
+ text_string_object = str.__new__(cls, exception.object[: exception.start].decode("utf-16"))
702
+ text_string_object._original_bytes = original_bytes
703
+ text_string_object.autodetect_utf16 = True
704
+ text_string_object.utf16_bom = original_bytes[:2]
705
+ else:
706
+ try:
707
+ encode_pdfdocencoding(text_string_object)
708
+ text_string_object.autodetect_pdfdocencoding = True
709
+ except UnicodeEncodeError:
710
+ text_string_object.autodetect_utf16 = True
711
+ text_string_object.utf16_bom = codecs.BOM_UTF16_BE
712
+ return text_string_object
713
+
714
+ def clone(
715
+ self,
716
+ pdf_dest: Any,
717
+ force_duplicate: bool = False,
718
+ ignore_fields: Optional[Sequence[Union[str, int]]] = (),
719
+ ) -> "TextStringObject":
720
+ """Clone object into pdf_dest."""
721
+ obj = TextStringObject(self)
722
+ obj._original_bytes = self._original_bytes
723
+ obj.autodetect_pdfdocencoding = self.autodetect_pdfdocencoding
724
+ obj.autodetect_utf16 = self.autodetect_utf16
725
+ obj.utf16_bom = self.utf16_bom
726
+ return cast(
727
+ "TextStringObject", self._reference_clone(obj, pdf_dest, force_duplicate)
728
+ )
729
+
730
+ def hash_bin(self) -> int:
731
+ """
732
+ Used to detect modified object.
733
+
734
+ Returns:
735
+ Hash considering type and value.
736
+
737
+ """
738
+ return hash((self.__class__, self.original_bytes))
739
+
740
+ @property
741
+ def original_bytes(self) -> bytes:
742
+ """
743
+ It is occasionally possible that a text string object gets created where
744
+ a byte string object was expected due to the autodetection mechanism --
745
+ if that occurs, this "original_bytes" property can be used to
746
+ back-calculate what the original encoded bytes were.
747
+ """
748
+ if self._original_bytes is not None:
749
+ return self._original_bytes
750
+ return self.get_original_bytes()
751
+
752
+ def get_original_bytes(self) -> bytes:
753
+ # We're a text string object, but the library is trying to get our raw
754
+ # bytes. This can happen if we auto-detected this string as text, but
755
+ # we were wrong. It's pretty common. Return the original bytes that
756
+ # would have been used to create this object, based upon the autodetect
757
+ # method.
758
+ if self.autodetect_utf16:
759
+ if self.utf16_bom == codecs.BOM_UTF16_LE:
760
+ return codecs.BOM_UTF16_LE + self.encode("utf-16le")
761
+ if self.utf16_bom == codecs.BOM_UTF16_BE:
762
+ return codecs.BOM_UTF16_BE + self.encode("utf-16be")
763
+ return self.encode("utf-16be")
764
+ if self.autodetect_pdfdocencoding:
765
+ return encode_pdfdocencoding(self)
766
+ raise Exception("no information about original bytes") # pragma: no cover
767
+
768
+ def get_encoded_bytes(self) -> bytes:
769
+ # Try to write the string out as a PDFDocEncoding encoded string. It's
770
+ # nicer to look at in the PDF file. Sadly, we take a performance hit
771
+ # here for trying...
772
+ try:
773
+ if self._original_bytes is not None:
774
+ return self._original_bytes
775
+ if self.autodetect_utf16:
776
+ raise UnicodeEncodeError("", "forced", -1, -1, "")
777
+ bytearr = encode_pdfdocencoding(self)
778
+ except UnicodeEncodeError:
779
+ if self.utf16_bom == codecs.BOM_UTF16_LE:
780
+ bytearr = codecs.BOM_UTF16_LE + self.encode("utf-16le")
781
+ elif self.utf16_bom == codecs.BOM_UTF16_BE:
782
+ bytearr = codecs.BOM_UTF16_BE + self.encode("utf-16be")
783
+ else:
784
+ bytearr = self.encode("utf-16be")
785
+ return bytearr
786
+
787
+ def write_to_stream(
788
+ self, stream: StreamType, encryption_key: Union[str, bytes, None] = None
789
+ ) -> None:
790
+ if encryption_key is not None: # deprecated
791
+ deprecation_no_replacement(
792
+ "the encryption_key parameter of write_to_stream", "5.0.0"
793
+ )
794
+ bytearr = self.get_encoded_bytes()
795
+ stream.write(b"(")
796
+ for c_ in iter_unpack("c", bytearr):
797
+ c = cast(bytes, c_[0])
798
+ if not c.isalnum() and c != b" ":
799
+ # This:
800
+ # stream.write(rf"\{c:0>3o}".encode())
801
+ # gives
802
+ # https://github.com/davidhalter/parso/issues/207
803
+ stream.write(b"\\%03o" % ord(c))
804
+ else:
805
+ stream.write(c)
806
+ stream.write(b")")
807
+
808
+
809
+ class NameObject(str, PdfObject): # noqa: SLOT000
810
+ delimiter_pattern = re.compile(rb"\s+|[\(\)<>\[\]{}/%]")
811
+ prefix = b"/"
812
+ renumber_table: ClassVar[dict[str, bytes]] = {
813
+ **{chr(i): f"#{i:02X}".encode() for i in b"#()<>[]{}/%"},
814
+ **{chr(i): f"#{i:02X}".encode() for i in range(33)},
815
+ }
816
+ _LENGTH_LIMIT = 4096
817
+
818
+ def clone(
819
+ self,
820
+ pdf_dest: Any,
821
+ force_duplicate: bool = False,
822
+ ignore_fields: Optional[Sequence[Union[str, int]]] = (),
823
+ ) -> "NameObject":
824
+ """Clone object into pdf_dest."""
825
+ return cast(
826
+ "NameObject",
827
+ self._reference_clone(NameObject(self), pdf_dest, force_duplicate),
828
+ )
829
+
830
+ def hash_bin(self) -> int:
831
+ """
832
+ Used to detect modified object.
833
+
834
+ Returns:
835
+ Hash considering type and value.
836
+
837
+ """
838
+ return hash((self.__class__, self))
839
+
840
+ def write_to_stream(
841
+ self, stream: StreamType, encryption_key: Union[str, bytes, None] = None
842
+ ) -> None:
843
+ if encryption_key is not None: # deprecated
844
+ deprecation_no_replacement(
845
+ "the encryption_key parameter of write_to_stream", "5.0.0"
846
+ )
847
+ stream.write(self.renumber())
848
+
849
+ def renumber(self) -> bytes:
850
+ out = self[0].encode("utf-8")
851
+ if out != b"/":
852
+ deprecation_no_replacement(
853
+ f"Incorrect first char in NameObject, should start with '/': ({self})",
854
+ "5.0.0",
855
+ )
856
+ parts = [out]
857
+ for c in self[1:]:
858
+ if c > "~":
859
+ parts.extend(f"#{x:02X}".encode() for x in c.encode("utf-8"))
860
+ else:
861
+ try:
862
+ parts.append(self.renumber_table[c])
863
+ except KeyError:
864
+ parts.append(c.encode("utf-8"))
865
+ return b"".join(parts)
866
+
867
+ def _sanitize(self) -> "NameObject":
868
+ """
869
+ Sanitize the NameObject's name to be a valid PDF name part
870
+ (alphanumeric, underscore, hyphen). The _sanitize method replaces
871
+ spaces and any non-alphanumeric/non-underscore/non-hyphen with
872
+ underscores.
873
+
874
+ Returns:
875
+ NameObject with sanitized name.
876
+ """
877
+ name = str(self).removeprefix("/")
878
+ name = re.sub(r" ", "_", name)
879
+ name = re.sub(r"[^a-zA-Z0-9_-]", "_", name)
880
+ return NameObject("/" + name)
881
+
882
+ @classproperty
883
+ def surfix(cls) -> bytes: # noqa: N805
884
+ deprecation_with_replacement("surfix", "prefix", "5.0.0")
885
+ return b"/"
886
+
887
+ @staticmethod
888
+ def unnumber(sin: bytes) -> bytes:
889
+ result = bytearray()
890
+ i = 0
891
+ while i < len(sin):
892
+ if sin[i:i + 1] == b"#":
893
+ try:
894
+ result.append(int(sin[i + 1 : i + 3], 16))
895
+ i += 3
896
+ continue
897
+ except (ValueError, IndexError):
898
+ # if the 2 characters after # can not be converted to hex
899
+ # we change nothing and carry on
900
+ pass
901
+ result.append(sin[i])
902
+ i += 1
903
+ return bytes(result)
904
+
905
+ CHARSETS = ("utf-8", "gbk", "latin1")
906
+
907
+ @staticmethod
908
+ def read_from_stream(stream: StreamType, pdf: Any) -> "NameObject": # PdfReader
909
+ name = stream.read(1)
910
+ if name != NameObject.prefix:
911
+ raise PdfReadError("Name read error")
912
+ name += read_until_regex(stream=stream, regex=NameObject.delimiter_pattern, length=NameObject._LENGTH_LIMIT)
913
+ try:
914
+ # Name objects should represent irregular characters
915
+ # with a '#' followed by the symbol's hex number
916
+ name = NameObject.unnumber(name)
917
+ for enc in NameObject.CHARSETS:
918
+ try:
919
+ ret = name.decode(enc)
920
+ return NameObject(ret)
921
+ except Exception:
922
+ pass
923
+ raise UnicodeDecodeError("", name, 0, 0, "Code Not Found")
924
+ except (UnicodeEncodeError, UnicodeDecodeError) as e:
925
+ if not pdf.strict:
926
+ logger_warning(
927
+ "Illegal character in NameObject (%(name)r), you may need to adjust NameObject.CHARSETS",
928
+ source=__name__,
929
+ name=name,
930
+ )
931
+ return NameObject(name.decode("charmap"))
932
+ raise PdfReadError(
933
+ f"Illegal character in NameObject ({name!r}). "
934
+ "You may need to adjust NameObject.CHARSETS.",
935
+ ) from e
936
+
937
+
938
+ def encode_pdfdocencoding(unicode_string: str) -> bytes:
939
+ try:
940
+ return bytes([_pdfdoc_encoding_rev[k] for k in unicode_string])
941
+ except KeyError:
942
+ raise UnicodeEncodeError(
943
+ "pdfdocencoding",
944
+ unicode_string,
945
+ -1,
946
+ -1,
947
+ "does not exist in translation table",
948
+ )
949
+
950
+
951
+ def is_null_or_none(x: Any) -> TypeGuard[Union[NullObject, IndirectObject, None]]:
952
+ """
953
+ Returns:
954
+ True if x is None or NullObject.
955
+
956
+ """
957
+ return x is None or (
958
+ isinstance(x, PdfObject)
959
+ and (x.get_object() is None or isinstance(x.get_object(), NullObject))
960
+ )
.venv/lib/python3.13/site-packages/pypdf/generic/_data_structures.py ADDED
@@ -0,0 +1,1874 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2006, Mathieu Fenniak
2
+ # All rights reserved.
3
+ #
4
+ # Redistribution and use in source and binary forms, with or without
5
+ # modification, are permitted provided that the following conditions are
6
+ # met:
7
+ #
8
+ # * Redistributions of source code must retain the above copyright notice,
9
+ # this list of conditions and the following disclaimer.
10
+ # * Redistributions in binary form must reproduce the above copyright notice,
11
+ # this list of conditions and the following disclaimer in the documentation
12
+ # and/or other materials provided with the distribution.
13
+ # * The name of the author may not be used to endorse or promote products
14
+ # derived from this software without specific prior written permission.
15
+ #
16
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26
+ # POSSIBILITY OF SUCH DAMAGE.
27
+
28
+
29
+ __author__ = "Mathieu Fenniak"
30
+ __author_email__ = "biziqe@mathieu.fenniak.net"
31
+
32
+ import logging
33
+ import os
34
+ import re
35
+ import sys
36
+ from collections.abc import Iterable, Sequence
37
+ from io import BytesIO
38
+ from math import ceil
39
+ from typing import (
40
+ Any,
41
+ Callable,
42
+ Optional,
43
+ Union,
44
+ cast,
45
+ )
46
+
47
+ from .._protocols import PdfReaderProtocol, PdfWriterProtocol, XmpInformationProtocol
48
+ from .._utils import (
49
+ WHITESPACES,
50
+ BinaryStreamType,
51
+ StreamType,
52
+ deprecation_no_replacement,
53
+ logger_warning,
54
+ read_non_whitespace,
55
+ read_until_regex,
56
+ read_until_whitespace,
57
+ skip_over_comment,
58
+ )
59
+ from ..constants import (
60
+ CheckboxRadioButtonAttributes,
61
+ FieldDictionaryAttributes,
62
+ OutlineFontFlag,
63
+ StreamAttributes,
64
+ )
65
+ from ..constants import FilterTypes as FT
66
+ from ..constants import TypArguments as TA
67
+ from ..constants import TypFitArguments as TF
68
+ from ..errors import STREAM_TRUNCATED_PREMATURELY, LimitReachedError, PdfReadError, PdfStreamError
69
+ from ._base import (
70
+ BooleanObject,
71
+ ByteStringObject,
72
+ FloatObject,
73
+ IndirectObject,
74
+ NameObject,
75
+ NullObject,
76
+ NumberObject,
77
+ PdfObject,
78
+ TextStringObject,
79
+ is_null_or_none,
80
+ )
81
+ from ._fit import Fit
82
+ from ._image_inline import (
83
+ extract_inline__ascii85_decode,
84
+ extract_inline__ascii_hex_decode,
85
+ extract_inline__dct_decode,
86
+ extract_inline__run_length_decode,
87
+ extract_inline_default,
88
+ )
89
+ from ._utils import read_hex_string_from_stream, read_string_from_stream
90
+
91
+ if sys.version_info >= (3, 11):
92
+ from typing import Self
93
+ else:
94
+ from typing_extensions import Self
95
+
96
+ logger = logging.getLogger(__name__)
97
+
98
+ IndirectPattern = re.compile(rb"[+-]?(\d+)\s+(\d+)\s+R[^a-zA-Z]")
99
+
100
+
101
+ class ArrayObject(list[Any], PdfObject):
102
+ def replicate(
103
+ self,
104
+ pdf_dest: PdfWriterProtocol,
105
+ ) -> "ArrayObject":
106
+ arr = cast(
107
+ "ArrayObject",
108
+ self._reference_clone(ArrayObject(), pdf_dest, False),
109
+ )
110
+ for data in self:
111
+ if hasattr(data, "replicate"):
112
+ arr.append(data.replicate(pdf_dest))
113
+ else:
114
+ arr.append(data)
115
+ return arr
116
+
117
+ def clone(
118
+ self,
119
+ pdf_dest: PdfWriterProtocol,
120
+ force_duplicate: bool = False,
121
+ ignore_fields: Optional[Sequence[Union[str, int]]] = (),
122
+ ) -> "ArrayObject":
123
+ """Clone object into pdf_dest."""
124
+ try:
125
+ if self.indirect_reference.pdf == pdf_dest and not force_duplicate: # type: ignore[union-attr]
126
+ return self
127
+ except Exception:
128
+ pass
129
+ arr = cast(
130
+ "ArrayObject",
131
+ self._reference_clone(ArrayObject(), pdf_dest, force_duplicate=True),
132
+ )
133
+ for data in self:
134
+ if isinstance(data, StreamObject):
135
+ dup = data._reference_clone(
136
+ data.clone(pdf_dest, force_duplicate, ignore_fields),
137
+ pdf_dest,
138
+ force_duplicate,
139
+ )
140
+ arr.append(dup.indirect_reference)
141
+ elif isinstance(data, IndirectObject) and isinstance(resolved := data.get_object(), StreamObject):
142
+ dup = data._reference_clone(
143
+ resolved.clone(pdf_dest, force_duplicate=True, ignore_fields=ignore_fields),
144
+ pdf_dest,
145
+ force_duplicate,
146
+ )
147
+ arr.append(dup.indirect_reference)
148
+ elif hasattr(data, "clone"):
149
+ arr.append(data.clone(pdf_dest, force_duplicate, ignore_fields))
150
+ else:
151
+ arr.append(data)
152
+ return arr
153
+
154
+ def hash_bin(self) -> int:
155
+ """
156
+ Used to detect modified object.
157
+
158
+ Returns:
159
+ Hash considering type and value.
160
+
161
+ """
162
+ return hash((self.__class__, tuple(x.hash_bin() for x in self)))
163
+
164
+ def items(self) -> Iterable[Any]:
165
+ """Emulate DictionaryObject.items for a list (index, object)."""
166
+ return enumerate(self)
167
+
168
+ def _to_lst(self, lst: Any) -> list[Any]:
169
+ # Convert to list, internal
170
+ result: list[Any]
171
+ if isinstance(lst, (list, tuple, set)):
172
+ result = list(lst)
173
+ elif isinstance(lst, PdfObject):
174
+ result = [lst]
175
+ elif isinstance(lst, str):
176
+ if lst[0] == "/":
177
+ result = [NameObject(lst)]
178
+ else:
179
+ result = [TextStringObject(lst)]
180
+ elif isinstance(lst, bytes):
181
+ result = [ByteStringObject(lst)]
182
+ else: # for numbers,...
183
+ result = [lst]
184
+ return result
185
+
186
+ def __add__(self, lst: Any) -> "ArrayObject":
187
+ """
188
+ Allow extension by adding list or add one element only
189
+
190
+ Args:
191
+ lst: any list, tuples are extended the list.
192
+ other types(numbers,...) will be appended.
193
+ if str is passed it will be converted into TextStringObject
194
+ or NameObject (if starting with "/")
195
+ if bytes is passed it will be converted into ByteStringObject
196
+
197
+ Returns:
198
+ ArrayObject with all elements
199
+
200
+ """
201
+ temp = ArrayObject(self)
202
+ temp.extend(self._to_lst(lst))
203
+ return temp
204
+
205
+ def __iadd__(self, lst: Any) -> Self:
206
+ """
207
+ Allow extension by adding list or add one element only
208
+
209
+ Args:
210
+ lst: any list, tuples are extended the list.
211
+ other types(numbers,...) will be appended.
212
+ if str is passed it will be converted into TextStringObject
213
+ or NameObject (if starting with "/")
214
+ if bytes is passed it will be converted into ByteStringObject
215
+
216
+ """
217
+ self.extend(self._to_lst(lst))
218
+ return self
219
+
220
+ def __isub__(self, lst: Any) -> Self:
221
+ """Allow to remove items"""
222
+ for x in self._to_lst(lst):
223
+ try:
224
+ index = self.index(x)
225
+ del self[index]
226
+ except ValueError:
227
+ pass
228
+ return self
229
+
230
+ def write_to_stream(
231
+ self, stream: StreamType, encryption_key: Union[str, bytes, None] = None
232
+ ) -> None:
233
+ if encryption_key is not None: # deprecated
234
+ deprecation_no_replacement(
235
+ "the encryption_key parameter of write_to_stream", "5.0.0"
236
+ )
237
+ stream.write(b"[")
238
+ for data in self:
239
+ stream.write(b" ")
240
+ data.write_to_stream(stream)
241
+ stream.write(b" ]")
242
+
243
+ @staticmethod
244
+ def read_from_stream(
245
+ stream: StreamType,
246
+ pdf: Optional[PdfReaderProtocol],
247
+ forced_encoding: Union[str, list[str], dict[int, str], None] = None,
248
+ ) -> "ArrayObject":
249
+ arr = ArrayObject()
250
+ tmp = stream.read(1)
251
+ if tmp != b"[":
252
+ raise PdfReadError("Could not read array")
253
+ while True:
254
+ # skip leading whitespace
255
+ tok = stream.read(1)
256
+ while tok.isspace():
257
+ tok = stream.read(1)
258
+ if tok == b"":
259
+ break
260
+ if tok == b"%":
261
+ stream.seek(-1, 1)
262
+ skip_over_comment(stream)
263
+ continue
264
+ stream.seek(-1, 1)
265
+ # check for array ending
266
+ peek_ahead = stream.read(1)
267
+ if peek_ahead == b"]":
268
+ break
269
+ stream.seek(-1, 1)
270
+ # read and append object
271
+ arr.append(read_object(stream, pdf, forced_encoding))
272
+ return arr
273
+
274
+
275
+ class DictionaryObject(dict[Any, Any], PdfObject):
276
+ def replicate(
277
+ self,
278
+ pdf_dest: PdfWriterProtocol,
279
+ ) -> "DictionaryObject":
280
+ d__ = cast(
281
+ "DictionaryObject",
282
+ self._reference_clone(self.__class__(), pdf_dest, False),
283
+ )
284
+ for k, v in self.items():
285
+ d__[k.replicate(pdf_dest)] = (
286
+ v.replicate(pdf_dest) if hasattr(v, "replicate") else v
287
+ )
288
+ return d__
289
+
290
+ def clone(
291
+ self,
292
+ pdf_dest: PdfWriterProtocol,
293
+ force_duplicate: bool = False,
294
+ ignore_fields: Optional[Sequence[Union[str, int]]] = (),
295
+ ) -> "DictionaryObject":
296
+ """Clone object into pdf_dest."""
297
+ try:
298
+ if self.indirect_reference.pdf == pdf_dest and not force_duplicate: # type: ignore[union-attr]
299
+ return self
300
+ except Exception:
301
+ pass
302
+
303
+ visited: set[tuple[int, int]] = set() # (idnum, generation)
304
+ d__ = cast(
305
+ "DictionaryObject",
306
+ self._reference_clone(self.__class__(), pdf_dest, force_duplicate),
307
+ )
308
+ if ignore_fields is None:
309
+ ignore_fields = []
310
+ if len(d__.keys()) == 0:
311
+ d__._clone(self, pdf_dest, force_duplicate, ignore_fields, visited)
312
+ return d__
313
+
314
+ def _clone(
315
+ self,
316
+ src: "DictionaryObject",
317
+ pdf_dest: PdfWriterProtocol,
318
+ force_duplicate: bool,
319
+ ignore_fields: Optional[Sequence[Union[str, int]]],
320
+ visited: set[tuple[int, int]], # (idnum, generation)
321
+ ) -> None:
322
+ """
323
+ Update the object from src.
324
+
325
+ Args:
326
+ src: "DictionaryObject":
327
+ pdf_dest:
328
+ force_duplicate:
329
+ ignore_fields:
330
+
331
+ """
332
+ # First we remove the ignore_fields
333
+ # that are for a limited number of levels
334
+ assert ignore_fields is not None
335
+ ignore_fields = list(ignore_fields)
336
+ x = 0
337
+ while x < len(ignore_fields):
338
+ if isinstance(ignore_fields[x], int):
339
+ if cast(int, ignore_fields[x]) <= 0:
340
+ del ignore_fields[x]
341
+ del ignore_fields[x]
342
+ continue
343
+ ignore_fields[x] -= 1 # type:ignore
344
+ x += 1
345
+ # Check if this is a chain list, we need to loop to prevent recur
346
+ if any(
347
+ field not in ignore_fields
348
+ and field in src
349
+ and isinstance(src.raw_get(field), IndirectObject)
350
+ and isinstance(src[field], DictionaryObject)
351
+ and (
352
+ src.get("/Type", None) is None
353
+ or cast(DictionaryObject, src[field]).get("/Type", None) is None
354
+ or src.get("/Type", None)
355
+ == cast(DictionaryObject, src[field]).get("/Type", None)
356
+ )
357
+ for field in ["/Next", "/Prev", "/N", "/V"]
358
+ ):
359
+ ignore_fields = list(ignore_fields)
360
+ for lst in (("/Next", "/Prev"), ("/N", "/V")):
361
+ for k in lst:
362
+ objs = []
363
+ if (
364
+ k in src
365
+ and k not in self
366
+ and isinstance(src.raw_get(k), IndirectObject)
367
+ and isinstance(src[k], DictionaryObject)
368
+ # If need to go further the idea is to check
369
+ # that the types are the same
370
+ and (
371
+ src.get("/Type", None) is None
372
+ or cast(DictionaryObject, src[k]).get("/Type", None) is None
373
+ or src.get("/Type", None)
374
+ == cast(DictionaryObject, src[k]).get("/Type", None)
375
+ )
376
+ ):
377
+ cur_obj: Optional[DictionaryObject] = cast(
378
+ "DictionaryObject", src[k]
379
+ )
380
+ prev_obj: Optional[DictionaryObject] = self
381
+ while cur_obj is not None:
382
+ clon = cast(
383
+ "DictionaryObject",
384
+ cur_obj._reference_clone(
385
+ cur_obj.__class__(), pdf_dest, force_duplicate
386
+ ),
387
+ )
388
+ # Check to see if we've previously processed our item
389
+ if clon.indirect_reference is not None:
390
+ idnum = clon.indirect_reference.idnum
391
+ generation = clon.indirect_reference.generation
392
+ if (idnum, generation) in visited:
393
+ cur_obj = None
394
+ break
395
+ visited.add((idnum, generation))
396
+ objs.append((cur_obj, clon))
397
+ assert prev_obj is not None
398
+ prev_obj[NameObject(k)] = clon.indirect_reference
399
+ prev_obj = clon
400
+ try:
401
+ if cur_obj == src:
402
+ cur_obj = None
403
+ else:
404
+ cur_obj = cast("DictionaryObject", cur_obj[k])
405
+ except Exception:
406
+ cur_obj = None
407
+ for s, c in objs:
408
+ c._clone(
409
+ s, pdf_dest, force_duplicate, ignore_fields, visited
410
+ )
411
+
412
+ for k, v in src.items():
413
+ if k not in ignore_fields:
414
+ if isinstance(v, StreamObject):
415
+ if not hasattr(v, "indirect_reference"):
416
+ v.indirect_reference = None
417
+ vv = v.clone(pdf_dest, force_duplicate, ignore_fields)
418
+ assert vv.indirect_reference is not None
419
+ self[k.clone(pdf_dest)] = vv.indirect_reference
420
+ elif k not in self:
421
+ self[NameObject(k)] = (
422
+ v.clone(pdf_dest, force_duplicate, ignore_fields)
423
+ if hasattr(v, "clone")
424
+ else v
425
+ )
426
+
427
+ def hash_bin(self) -> int:
428
+ """
429
+ Used to detect modified object.
430
+
431
+ Returns:
432
+ Hash considering type and value.
433
+
434
+ """
435
+ return hash(
436
+ (self.__class__, tuple(((k, v.hash_bin()) for k, v in self.items())))
437
+ )
438
+
439
+ def raw_get(self, key: Any) -> Any:
440
+ return dict.__getitem__(self, key)
441
+
442
+ def get_inherited(self, key: str, default: Any = None) -> Any:
443
+ """
444
+ Returns the value of a key or from the parent if not found.
445
+ If not found returns default.
446
+
447
+ Args:
448
+ key: string identifying the field to return
449
+
450
+ default: default value to return
451
+
452
+ Returns:
453
+ Current key or inherited one, otherwise default value.
454
+
455
+ """
456
+ current = self
457
+ visited: set[int] = set()
458
+
459
+ while True:
460
+ # Detect cyclic parent references
461
+ obj_id = id(current)
462
+ if obj_id in visited:
463
+ raise LimitReachedError(f"Detected cycle in /Parent hierarchy when retrieving value for key {key!r}.")
464
+ visited.add(obj_id)
465
+
466
+ if key in current:
467
+ return current[key]
468
+
469
+ if "/Parent" not in current:
470
+ return default
471
+
472
+ # Walk upward
473
+ current = cast(
474
+ "DictionaryObject",
475
+ current["/Parent"].get_object(),
476
+ )
477
+
478
+ def __setitem__(self, key: Any, value: Any) -> Any:
479
+ if not isinstance(key, PdfObject):
480
+ raise ValueError("Key must be a PdfObject")
481
+ if not isinstance(value, PdfObject):
482
+ raise ValueError("Value must be a PdfObject")
483
+ return dict.__setitem__(self, key, value)
484
+
485
+ def setdefault(self, key: Any, value: Optional[Any] = None) -> Any:
486
+ if not isinstance(key, PdfObject):
487
+ raise ValueError("Key must be a PdfObject")
488
+ if not isinstance(value, PdfObject):
489
+ raise ValueError("Value must be a PdfObject")
490
+ return dict.setdefault(self, key, value)
491
+
492
+ def __getitem__(self, key: Any) -> PdfObject:
493
+ return cast(PdfObject, dict.__getitem__(self, key).get_object())
494
+
495
+ @property
496
+ def xmp_metadata(self) -> Optional[XmpInformationProtocol]:
497
+ """
498
+ Retrieve XMP (Extensible Metadata Platform) data relevant to this
499
+ object, if available.
500
+
501
+ See Table 347 — Additional entries in a metadata stream dictionary.
502
+
503
+ Returns:
504
+ Returns a :class:`~pypdf.xmp.XmpInformation` instance
505
+ that can be used to access XMP metadata from the document. Can also
506
+ return None if no metadata was found on the document root.
507
+
508
+ """
509
+ from ..xmp import XmpInformation # noqa: PLC0415
510
+
511
+ metadata = self.get("/Metadata", None)
512
+ if is_null_or_none(metadata):
513
+ return None
514
+ assert metadata is not None, "mypy"
515
+ metadata = metadata.get_object()
516
+ return XmpInformation(metadata)
517
+
518
+ def write_to_stream(
519
+ self, stream: StreamType, encryption_key: Union[str, bytes, None] = None
520
+ ) -> None:
521
+ if encryption_key is not None: # deprecated
522
+ deprecation_no_replacement(
523
+ "the encryption_key parameter of write_to_stream", "5.0.0"
524
+ )
525
+ stream.write(b"<<\n")
526
+ for key, value in self.items():
527
+ if len(key) > 2 and key[1] == "%" and key[-1] == "%":
528
+ continue
529
+ key.write_to_stream(stream, encryption_key)
530
+ stream.write(b" ")
531
+ value.write_to_stream(stream)
532
+ stream.write(b"\n")
533
+ stream.write(b">>")
534
+
535
+ @classmethod
536
+ def _get_next_object_position(
537
+ cls, position_before: int, position_end: int, generations: list[int], pdf: PdfReaderProtocol
538
+ ) -> int:
539
+ out = position_end
540
+ for generation in generations:
541
+ for x in pdf.xref[generation].values():
542
+ if position_before < x <= position_end:
543
+ out = min(out, x)
544
+ return out
545
+
546
+ @classmethod
547
+ def _read_unsized_from_stream(
548
+ cls, *, stream: BinaryStreamType, pdf: PdfReaderProtocol, length: int,
549
+ ) -> bytes:
550
+ current_position = stream.tell()
551
+
552
+ # Determine stream size.
553
+ try:
554
+ stream.seek(0, os.SEEK_END)
555
+ stream_length = stream.tell()
556
+ finally:
557
+ stream.seek(current_position)
558
+
559
+ object_position = cls._get_next_object_position(
560
+ position_before=current_position, position_end=stream_length, generations=list(pdf.xref), pdf=pdf
561
+ )
562
+
563
+ bytes_to_read = object_position - current_position
564
+ if bytes_to_read >= length:
565
+ raise LimitReachedError(f"Requested length of {bytes_to_read} exceeds maximum allowed length.")
566
+
567
+ # Read until the next object position.
568
+ read_value = stream.read(bytes_to_read)
569
+ endstream_position = read_value.find(b"endstream")
570
+ if endstream_position < 0:
571
+ raise PdfReadError(
572
+ f"Unable to find 'endstream' marker for obj starting at {current_position}."
573
+ )
574
+ # 9 = len(b"endstream")
575
+ stream.seek(current_position + endstream_position + 9)
576
+ return read_value[: endstream_position - 1]
577
+
578
+ @staticmethod
579
+ def read_from_stream(
580
+ stream: StreamType,
581
+ pdf: Optional[PdfReaderProtocol],
582
+ forced_encoding: Union[str, list[str], dict[int, str], None] = None,
583
+ ) -> "DictionaryObject":
584
+ tmp = stream.read(2)
585
+ if tmp != b"<<":
586
+ raise PdfReadError(
587
+ f"Dictionary read error at byte {hex(stream.tell())}: "
588
+ "stream must begin with '<<'"
589
+ )
590
+ data: dict[Any, Any] = {}
591
+ while True:
592
+ tok = read_non_whitespace(stream)
593
+ if tok == b"\x00":
594
+ continue
595
+ if tok == b"%":
596
+ stream.seek(-1, 1)
597
+ skip_over_comment(stream)
598
+ continue
599
+ if not tok:
600
+ raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY)
601
+
602
+ if tok == b">":
603
+ stream.read(1)
604
+ break
605
+ stream.seek(-1, 1)
606
+ try:
607
+ try:
608
+ key = read_object(stream, pdf)
609
+ if isinstance(key, NullObject):
610
+ break
611
+ if not isinstance(key, NameObject):
612
+ raise PdfReadError(
613
+ f"Expecting a NameObject for key but found {key!r}"
614
+ )
615
+ except PdfReadError as exc:
616
+ if pdf is not None and pdf.strict:
617
+ raise
618
+ logger_warning("%(exception)r", source=__name__, exception=exc)
619
+ continue
620
+ tok = read_non_whitespace(stream)
621
+ stream.seek(-1, 1)
622
+ value = read_object(stream, pdf, forced_encoding)
623
+ except (RecursionError, LimitReachedError) as exc:
624
+ raise PdfReadError(exc.__repr__())
625
+ except Exception as exc:
626
+ if pdf is not None and pdf.strict:
627
+ raise PdfReadError(exc.__repr__())
628
+ logger_warning("%(exception)r", source=__name__, exception=exc)
629
+ retval = DictionaryObject()
630
+ retval.update(data)
631
+ return retval # return partial data
632
+
633
+ if not data.get(key):
634
+ data[key] = value
635
+ else:
636
+ # multiple definitions of key not permitted
637
+ msg = (
638
+ "Multiple definitions in dictionary at byte "
639
+ "%(position)s for key %(key)s"
640
+ )
641
+ values = {"position": hex(stream.tell()), "key": key}
642
+ if pdf is not None and pdf.strict:
643
+ raise PdfReadError(msg % values)
644
+ logger_warning(msg, source=__name__, **values)
645
+
646
+ pos = stream.tell()
647
+ s = read_non_whitespace(stream)
648
+ if s == b"s" and stream.read(5) == b"tream":
649
+ eol = stream.read(1)
650
+ # Occasional PDF file output has spaces after 'stream' keyword but before EOL.
651
+ # patch provided by Danial Sandler
652
+ while eol == b" ":
653
+ eol = stream.read(1)
654
+ if eol not in (b"\n", b"\r"):
655
+ raise PdfStreamError("Stream data must be followed by a newline")
656
+ if eol == b"\r" and stream.read(1) != b"\n":
657
+ stream.seek(-1, 1)
658
+ # this is a stream object, not a dictionary
659
+ if StreamAttributes.LENGTH not in data:
660
+ if pdf is not None and pdf.strict:
661
+ raise PdfStreamError("Stream length not defined")
662
+ logger_warning(
663
+ "Stream length not defined @pos=%(position)d",
664
+ source=__name__,
665
+ position=stream.tell(),
666
+ )
667
+ data[NameObject(StreamAttributes.LENGTH)] = NumberObject(-1)
668
+ length = data[StreamAttributes.LENGTH]
669
+ if isinstance(length, IndirectObject):
670
+ t = stream.tell()
671
+ assert pdf is not None, "mypy"
672
+ length = pdf.get_object(length)
673
+ stream.seek(t, 0)
674
+ if length is None: # if the PDF is damaged
675
+ length = -1
676
+ pstart = stream.tell()
677
+
678
+ from ..filters import MAX_DECLARED_STREAM_LENGTH # noqa: PLC0415
679
+ if length >= 0:
680
+ if length > MAX_DECLARED_STREAM_LENGTH:
681
+ raise LimitReachedError(f"Declared stream length of {length} exceeds maximum allowed length.")
682
+
683
+ data["__streamdata__"] = stream.read(length)
684
+ else:
685
+ data["__streamdata__"] = read_until_regex(
686
+ stream=stream, regex=re.compile(b"endstream"), length=MAX_DECLARED_STREAM_LENGTH,
687
+ )
688
+ e = read_non_whitespace(stream)
689
+ ndstream = stream.read(8)
690
+ if (e + ndstream) != b"endstream":
691
+ # the odd PDF file has a length that is too long, so
692
+ # we need to read backwards to find the "endstream" ending.
693
+ # ReportLab (unknown version) generates files with this bug,
694
+ # and Python users into PDF files tend to be our audience.
695
+ # we need to do this to correct the streamdata and chop off
696
+ # an extra character.
697
+ pos = stream.tell()
698
+ stream.seek(-10, 1)
699
+ end = stream.read(9)
700
+ if end == b"endstream":
701
+ # we found it by looking back one character further.
702
+ data["__streamdata__"] = data["__streamdata__"][:-1]
703
+ elif pdf is not None and not pdf.strict:
704
+ stream.seek(pstart, 0)
705
+ data["__streamdata__"] = DictionaryObject._read_unsized_from_stream(
706
+ stream=stream, pdf=pdf, length=MAX_DECLARED_STREAM_LENGTH
707
+ )
708
+ pos = stream.tell()
709
+ else:
710
+ stream.seek(pos, 0)
711
+ raise PdfReadError(
712
+ "Unable to find 'endstream' marker after stream at byte "
713
+ f"{hex(stream.tell())} (nd='{ndstream!r}', end='{end!r}')."
714
+ )
715
+ else:
716
+ stream.seek(pos, 0)
717
+ if "__streamdata__" in data:
718
+ return StreamObject.initialize_from_dictionary(data)
719
+ retval = DictionaryObject()
720
+ retval.update(data)
721
+ return retval
722
+
723
+
724
+ class TreeObject(DictionaryObject):
725
+ def __init__(self, dct: Optional[DictionaryObject] = None) -> None:
726
+ DictionaryObject.__init__(self)
727
+ if dct:
728
+ self.update(dct)
729
+
730
+ def has_children(self) -> bool:
731
+ return "/First" in self
732
+
733
+ def __iter__(self) -> Any:
734
+ return self.children()
735
+
736
+ def children(self) -> Iterable[Any]:
737
+ if not self.has_children():
738
+ return
739
+
740
+ child_ref = self[NameObject("/First")]
741
+ last = self[NameObject("/Last")]
742
+ child = child_ref.get_object()
743
+ visited: set[int] = set()
744
+ while True:
745
+ child_id = id(child)
746
+ if child_id in visited:
747
+ logger_warning("Detected cycle in outline structure for %(child)s", source=__name__, child=child)
748
+ return
749
+ visited.add(child_id)
750
+
751
+ yield child
752
+
753
+ if child == last:
754
+ return
755
+ child_ref = child.get(NameObject("/Next")) # type: ignore[union-attr]
756
+ if is_null_or_none(child_ref):
757
+ return
758
+ child = child_ref.get_object()
759
+
760
+ def add_child(self, child: Any, pdf: PdfWriterProtocol) -> None:
761
+ self.insert_child(child, None, pdf)
762
+
763
+ def inc_parent_counter_default(
764
+ self, parent: Union[IndirectObject, "TreeObject", None], n: int
765
+ ) -> None:
766
+ if is_null_or_none(parent):
767
+ return
768
+ assert parent is not None, "mypy"
769
+ parent = cast("TreeObject", parent.get_object())
770
+ if "/Count" in parent:
771
+ parent[NameObject("/Count")] = NumberObject(
772
+ max(0, cast(int, parent[NameObject("/Count")]) + n)
773
+ )
774
+ self.inc_parent_counter_default(parent.get("/Parent", None), n)
775
+
776
+ def inc_parent_counter_outline(
777
+ self, parent: Union[IndirectObject, "TreeObject", None], n: int
778
+ ) -> None:
779
+ if is_null_or_none(parent):
780
+ return
781
+ assert parent is not None, "mypy"
782
+ parent = cast("TreeObject", parent.get_object())
783
+ # BooleanObject requires comparison with == not is
784
+ opn = parent.get("/%is_open%", True) == True # noqa: E712
785
+ c = cast(int, parent.get("/Count", 0))
786
+ if c < 0:
787
+ c = abs(c)
788
+ parent[NameObject("/Count")] = NumberObject((c + n) * (1 if opn else -1))
789
+ if not opn:
790
+ return
791
+ self.inc_parent_counter_outline(parent.get("/Parent", None), n)
792
+
793
+ def insert_child(
794
+ self,
795
+ child: Any,
796
+ before: Any,
797
+ pdf: PdfWriterProtocol,
798
+ inc_parent_counter: Optional[Callable[..., Any]] = None,
799
+ ) -> IndirectObject:
800
+ if inc_parent_counter is None:
801
+ inc_parent_counter = self.inc_parent_counter_default
802
+ child_obj = child.get_object()
803
+ assert child.indirect_reference is not None, "mypy"
804
+ child_reference: IndirectObject = child.indirect_reference
805
+
806
+ prev: Optional[DictionaryObject]
807
+ if "/First" not in self: # no child yet
808
+ self[NameObject("/First")] = child_reference
809
+ self[NameObject("/Count")] = NumberObject(0)
810
+ self[NameObject("/Last")] = child_reference
811
+ child_obj[NameObject("/Parent")] = self.indirect_reference
812
+ inc_parent_counter(self, child_obj.get("/Count", 1))
813
+ if "/Next" in child_obj:
814
+ del child_obj["/Next"]
815
+ if "/Prev" in child_obj:
816
+ del child_obj["/Prev"]
817
+ return child_reference
818
+ prev = cast("DictionaryObject", self["/Last"])
819
+
820
+ while prev.indirect_reference != before:
821
+ if "/Next" in prev:
822
+ prev = cast("TreeObject", prev["/Next"])
823
+ else: # append at the end
824
+ prev[NameObject("/Next")] = cast("TreeObject", child_reference)
825
+ child_obj[NameObject("/Prev")] = prev.indirect_reference
826
+ child_obj[NameObject("/Parent")] = self.indirect_reference
827
+ if "/Next" in child_obj:
828
+ del child_obj["/Next"]
829
+ self[NameObject("/Last")] = child_reference
830
+ inc_parent_counter(self, child_obj.get("/Count", 1))
831
+ return child_reference
832
+ try: # insert as first or in the middle
833
+ assert isinstance(prev["/Prev"], DictionaryObject)
834
+ prev["/Prev"][NameObject("/Next")] = child_reference
835
+ child_obj[NameObject("/Prev")] = prev["/Prev"]
836
+ except Exception: # it means we are inserting in first position
837
+ child_obj.pop("/Next", None)
838
+ child_obj[NameObject("/Next")] = prev
839
+ prev[NameObject("/Prev")] = child_reference
840
+ child_obj[NameObject("/Parent")] = self.indirect_reference
841
+ inc_parent_counter(self, child_obj.get("/Count", 1))
842
+ return child_reference
843
+
844
+ def _remove_node_from_tree(
845
+ self, prev: Any, prev_ref: Any, cur: Any, last: Any
846
+ ) -> None:
847
+ """
848
+ Adjust the pointers of the linked list and tree node count.
849
+
850
+ Args:
851
+ prev:
852
+ prev_ref:
853
+ cur:
854
+ last:
855
+
856
+ """
857
+ next_ref = cur.get(NameObject("/Next"), None)
858
+ if prev is None:
859
+ if next_ref:
860
+ # Removing first tree node
861
+ next_obj = next_ref.get_object()
862
+ del next_obj[NameObject("/Prev")]
863
+ self[NameObject("/First")] = next_ref
864
+ self[NameObject("/Count")] = NumberObject(
865
+ self[NameObject("/Count")] - 1 # type: ignore[operator]
866
+ )
867
+
868
+ else:
869
+ # Removing only tree node
870
+ self[NameObject("/Count")] = NumberObject(0)
871
+ del self[NameObject("/First")]
872
+ if NameObject("/Last") in self:
873
+ del self[NameObject("/Last")]
874
+ else:
875
+ if next_ref:
876
+ # Removing middle tree node
877
+ next_obj = next_ref.get_object()
878
+ next_obj[NameObject("/Prev")] = prev_ref
879
+ prev[NameObject("/Next")] = next_ref
880
+ else:
881
+ # Removing last tree node
882
+ assert cur == last
883
+ del prev[NameObject("/Next")]
884
+ self[NameObject("/Last")] = prev_ref
885
+ self[NameObject("/Count")] = NumberObject(self[NameObject("/Count")] - 1) # type: ignore[operator]
886
+
887
+ def remove_child(self, child: Any) -> None:
888
+ child_obj = child.get_object()
889
+ child = child_obj.indirect_reference
890
+
891
+ if NameObject("/Parent") not in child_obj:
892
+ raise ValueError("Removed child does not appear to be a tree item")
893
+ if child_obj[NameObject("/Parent")] != self:
894
+ raise ValueError("Removed child is not a member of this tree")
895
+
896
+ found = False
897
+ prev_ref = None
898
+ prev = None
899
+ cur_ref: Optional[Any] = self[NameObject("/First")]
900
+ cur: Optional[dict[str, Any]] = cur_ref.get_object() # type: ignore[union-attr]
901
+ last_ref = self[NameObject("/Last")]
902
+ last = last_ref.get_object()
903
+ while cur is not None:
904
+ if cur == child_obj:
905
+ self._remove_node_from_tree(prev, prev_ref, cur, last)
906
+ found = True
907
+ break
908
+
909
+ # Go to the next node
910
+ prev_ref = cur_ref
911
+ prev = cur
912
+ if NameObject("/Next") in cur:
913
+ cur_ref = cur[NameObject("/Next")]
914
+ cur = cur_ref.get_object()
915
+ else:
916
+ cur_ref = None
917
+ cur = None
918
+
919
+ if not found:
920
+ raise ValueError("Removal couldn't find item in tree")
921
+
922
+ _reset_node_tree_relationship(child_obj)
923
+
924
+ def remove_from_tree(self) -> None:
925
+ """Remove the object from the tree it is in."""
926
+ if NameObject("/Parent") not in self:
927
+ raise ValueError("Removed child does not appear to be a tree item")
928
+ cast("TreeObject", self["/Parent"]).remove_child(self)
929
+
930
+ def empty_tree(self) -> None:
931
+ for child in self:
932
+ child_obj = child.get_object()
933
+ _reset_node_tree_relationship(child_obj)
934
+
935
+ if NameObject("/Count") in self:
936
+ del self[NameObject("/Count")]
937
+ if NameObject("/First") in self:
938
+ del self[NameObject("/First")]
939
+ if NameObject("/Last") in self:
940
+ del self[NameObject("/Last")]
941
+
942
+
943
+ def _reset_node_tree_relationship(child_obj: Any) -> None:
944
+ """
945
+ Call this after a node has been removed from a tree.
946
+
947
+ This resets the nodes attributes in respect to that tree.
948
+
949
+ Args:
950
+ child_obj:
951
+
952
+ """
953
+ del child_obj[NameObject("/Parent")]
954
+ if NameObject("/Next") in child_obj:
955
+ del child_obj[NameObject("/Next")]
956
+ if NameObject("/Prev") in child_obj:
957
+ del child_obj[NameObject("/Prev")]
958
+
959
+
960
+ class StreamObject(DictionaryObject):
961
+ def __init__(self) -> None:
962
+ self._data: bytes = b""
963
+ self.decoded_self: Optional[DecodedStreamObject] = None
964
+
965
+ def replicate(
966
+ self,
967
+ pdf_dest: PdfWriterProtocol,
968
+ ) -> "StreamObject":
969
+ d__ = cast(
970
+ "StreamObject",
971
+ self._reference_clone(self.__class__(), pdf_dest, False),
972
+ )
973
+ d__._data = self._data
974
+ try:
975
+ decoded_self = self.decoded_self
976
+ if decoded_self is None:
977
+ self.decoded_self = None
978
+ else:
979
+ self.decoded_self = cast(
980
+ "DecodedStreamObject", decoded_self.replicate(pdf_dest)
981
+ )
982
+ except Exception:
983
+ pass
984
+ for k, v in self.items():
985
+ d__[k.replicate(pdf_dest)] = (
986
+ v.replicate(pdf_dest) if hasattr(v, "replicate") else v
987
+ )
988
+ return d__
989
+
990
+ def _clone(
991
+ self,
992
+ src: DictionaryObject,
993
+ pdf_dest: PdfWriterProtocol,
994
+ force_duplicate: bool,
995
+ ignore_fields: Optional[Sequence[Union[str, int]]],
996
+ visited: set[tuple[int, int]],
997
+ ) -> None:
998
+ """
999
+ Update the object from src.
1000
+
1001
+ Args:
1002
+ src:
1003
+ pdf_dest:
1004
+ force_duplicate:
1005
+ ignore_fields:
1006
+
1007
+ """
1008
+ self._data = cast("StreamObject", src)._data
1009
+ try:
1010
+ decoded_self = cast("StreamObject", src).decoded_self
1011
+ if decoded_self is None:
1012
+ self.decoded_self = None
1013
+ else:
1014
+ self.decoded_self = cast(
1015
+ "DecodedStreamObject",
1016
+ decoded_self.clone(pdf_dest, force_duplicate, ignore_fields),
1017
+ )
1018
+ except Exception:
1019
+ pass
1020
+ super()._clone(src, pdf_dest, force_duplicate, ignore_fields, visited)
1021
+
1022
+ def hash_bin(self) -> int:
1023
+ """
1024
+ Used to detect modified object.
1025
+
1026
+ Returns:
1027
+ Hash considering type and value.
1028
+
1029
+ """
1030
+ # Use _data to prevent errors on non-decoded streams.
1031
+ return hash((super().hash_bin(), self._data))
1032
+
1033
+ def get_data(self) -> bytes:
1034
+ return self._data
1035
+
1036
+ def set_data(self, data: bytes) -> None:
1037
+ self._data = data
1038
+
1039
+ def hash_value_data(self) -> bytes:
1040
+ data = super().hash_value_data()
1041
+ data += self.get_data()
1042
+ return data
1043
+
1044
+ def write_to_stream(
1045
+ self, stream: StreamType, encryption_key: Union[str, bytes, None] = None
1046
+ ) -> None:
1047
+ if encryption_key is not None: # deprecated
1048
+ deprecation_no_replacement(
1049
+ "the encryption_key parameter of write_to_stream", "5.0.0"
1050
+ )
1051
+ self[NameObject(StreamAttributes.LENGTH)] = NumberObject(len(self._data))
1052
+ DictionaryObject.write_to_stream(self, stream)
1053
+ del self[StreamAttributes.LENGTH]
1054
+ stream.write(b"\nstream\n")
1055
+ stream.write(self._data)
1056
+ stream.write(b"\nendstream")
1057
+
1058
+ @staticmethod
1059
+ def initialize_from_dictionary(
1060
+ data: dict[str, Any]
1061
+ ) -> Union["EncodedStreamObject", "DecodedStreamObject"]:
1062
+ retval: Union[EncodedStreamObject, DecodedStreamObject]
1063
+ if StreamAttributes.FILTER in data:
1064
+ retval = EncodedStreamObject()
1065
+ else:
1066
+ retval = DecodedStreamObject()
1067
+ retval._data = data["__streamdata__"]
1068
+ del data["__streamdata__"]
1069
+ if StreamAttributes.LENGTH in data:
1070
+ del data[StreamAttributes.LENGTH]
1071
+ retval.update(data)
1072
+ return retval
1073
+
1074
+ def flate_encode(self, level: int = -1) -> "EncodedStreamObject":
1075
+ from ..filters import FlateDecode # noqa: PLC0415
1076
+
1077
+ if StreamAttributes.FILTER in self:
1078
+ f = self[StreamAttributes.FILTER]
1079
+ if isinstance(f, ArrayObject):
1080
+ f = ArrayObject([NameObject(FT.FLATE_DECODE), *f])
1081
+ try:
1082
+ params = ArrayObject(
1083
+ [NullObject(), *self.get(StreamAttributes.DECODE_PARMS, ArrayObject())]
1084
+ )
1085
+ except TypeError:
1086
+ # case of error where the * operator is not working (not an array
1087
+ params = ArrayObject(
1088
+ [NullObject(), self.get(StreamAttributes.DECODE_PARMS, ArrayObject())]
1089
+ )
1090
+ else:
1091
+ f = ArrayObject([NameObject(FT.FLATE_DECODE), f])
1092
+ params = ArrayObject(
1093
+ [NullObject(), self.get(StreamAttributes.DECODE_PARMS, NullObject())]
1094
+ )
1095
+ else:
1096
+ f = NameObject(FT.FLATE_DECODE)
1097
+ params = None
1098
+ retval = EncodedStreamObject()
1099
+ retval.update(self)
1100
+ retval[NameObject(StreamAttributes.FILTER)] = f
1101
+ if params is not None:
1102
+ retval[NameObject(StreamAttributes.DECODE_PARMS)] = params
1103
+ retval._data = FlateDecode.encode(self._data, level)
1104
+ return retval
1105
+
1106
+ def decode_as_image(self, pillow_parameters: Union[dict[str, Any], None] = None) -> Any:
1107
+ """
1108
+ Try to decode the stream object as an image
1109
+
1110
+ Args:
1111
+ pillow_parameters: parameters provided to Pillow Image.save() method,
1112
+ cf. <https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.save>
1113
+
1114
+ Returns:
1115
+ a PIL image if proper decoding has been found
1116
+ Raises:
1117
+ Exception: Errors during decoding will be reported.
1118
+ It is recommended to catch exceptions to prevent
1119
+ stops in your program.
1120
+
1121
+ """
1122
+ from ._image_xobject import _xobj_to_image # noqa: PLC0415
1123
+
1124
+ if self.get("/Subtype", "") != "/Image":
1125
+ try:
1126
+ logger_warning( # pragma: no cover
1127
+ "%(indirect_reference)s does not seem to be an Image",
1128
+ source=__name__,
1129
+ indirect_reference=self.indirect_reference,
1130
+ )
1131
+ except AttributeError:
1132
+ logger_warning( # pragma: no cover
1133
+ "%(obj)r object does not seem to be an Image",
1134
+ source=__name__,
1135
+ obj=self,
1136
+ )
1137
+ extension, _, img = _xobj_to_image(self, pillow_parameters)
1138
+ if extension is None:
1139
+ return None # pragma: no cover
1140
+ return img
1141
+
1142
+
1143
+ class DecodedStreamObject(StreamObject):
1144
+ pass
1145
+
1146
+
1147
+ class EncodedStreamObject(StreamObject):
1148
+ def __init__(self) -> None:
1149
+ self.decoded_self: Optional[DecodedStreamObject] = None
1150
+
1151
+ # This overrides the parent method
1152
+ def get_data(self) -> bytes:
1153
+ from ..filters import decode_stream_data # noqa: PLC0415
1154
+
1155
+ if self.decoded_self is not None:
1156
+ # Cached version of decoded object
1157
+ return self.decoded_self.get_data()
1158
+
1159
+ # Create decoded object
1160
+ decoded = DecodedStreamObject()
1161
+ decoded.set_data(decode_stream_data(self))
1162
+ for key, value in self.items():
1163
+ if key not in (StreamAttributes.LENGTH, StreamAttributes.FILTER, StreamAttributes.DECODE_PARMS):
1164
+ decoded[key] = value
1165
+ self.decoded_self = decoded
1166
+ return decoded.get_data()
1167
+
1168
+ # This overrides the parent method:
1169
+ def set_data(self, data: bytes) -> None:
1170
+ from ..filters import FlateDecode # noqa: PLC0415
1171
+
1172
+ if self.get(StreamAttributes.FILTER, "") in (FT.FLATE_DECODE, [FT.FLATE_DECODE]):
1173
+ if not isinstance(data, bytes):
1174
+ raise TypeError("Data must be bytes")
1175
+ if self.decoded_self is None:
1176
+ self.get_data() # to create self.decoded_self
1177
+ assert self.decoded_self is not None, "mypy"
1178
+ self.decoded_self.set_data(data)
1179
+ super().set_data(FlateDecode.encode(data))
1180
+ else:
1181
+ raise PdfReadError(
1182
+ "Streams encoded with a filter different from FlateDecode are not supported"
1183
+ )
1184
+
1185
+
1186
+ CONTENT_STREAM_ARRAY_MAX_LENGTH = 10_000
1187
+
1188
+
1189
+ class ContentStream(DecodedStreamObject):
1190
+ """
1191
+ In order to be fast, this data structure can contain either:
1192
+
1193
+ * raw data in ._data
1194
+ * parsed stream operations in ._operations.
1195
+
1196
+ At any time, ContentStream object can either have both of those fields defined,
1197
+ or one field defined and the other set to None.
1198
+
1199
+ These fields are "rebuilt" lazily, when accessed:
1200
+
1201
+ * when .get_data() is called, if ._data is None, it is rebuilt from ._operations.
1202
+ * when .operations is called, if ._operations is None, it is rebuilt from ._data.
1203
+
1204
+ Conversely, these fields can be invalidated:
1205
+
1206
+ * when .set_data() is called, ._operations is set to None.
1207
+ * when .operations is set, ._data is set to None.
1208
+ """
1209
+ _OPERATOR_LENGTH_LIMIT = 128
1210
+
1211
+ def __init__(
1212
+ self,
1213
+ stream: Any,
1214
+ pdf: Any,
1215
+ forced_encoding: Union[str, list[str], dict[int, str], None] = None,
1216
+ ) -> None:
1217
+ self.pdf = pdf
1218
+ self._operations: list[tuple[Any, bytes]] = []
1219
+
1220
+ # stream may be a StreamObject or an ArrayObject containing
1221
+ # StreamObjects to be concatenated together.
1222
+ if stream is None:
1223
+ super().set_data(b"")
1224
+ else:
1225
+ stream = stream.get_object()
1226
+ if isinstance(stream, ArrayObject):
1227
+ from pypdf.filters import MAX_ARRAY_BASED_STREAM_OUTPUT_LENGTH # noqa: PLC0415
1228
+
1229
+ if (stream_length := len(stream)) > CONTENT_STREAM_ARRAY_MAX_LENGTH:
1230
+ raise LimitReachedError(
1231
+ f"Array-based stream has {stream_length} > {CONTENT_STREAM_ARRAY_MAX_LENGTH} elements."
1232
+ )
1233
+ data = bytearray()
1234
+ length = 0
1235
+ for s in stream:
1236
+ s_resolved = s.get_object()
1237
+ if isinstance(s_resolved, NullObject):
1238
+ continue
1239
+ if not isinstance(s_resolved, StreamObject):
1240
+ # No need to emit an exception here for now - the PDF structure
1241
+ # seems to already be broken beforehand in these cases.
1242
+ logger_warning(
1243
+ "Expected StreamObject, got %(type_name)s instead. Data might be wrong.",
1244
+ source=__name__,
1245
+ type_name=type(s_resolved).__name__,
1246
+ )
1247
+ else:
1248
+ new_data = s_resolved.get_data()
1249
+ length += len(new_data)
1250
+ if length > MAX_ARRAY_BASED_STREAM_OUTPUT_LENGTH:
1251
+ raise LimitReachedError(
1252
+ f"Array-based stream has at least {length} > "
1253
+ f"{MAX_ARRAY_BASED_STREAM_OUTPUT_LENGTH} output bytes."
1254
+ )
1255
+ data += new_data
1256
+ if len(data) == 0 or data[-1:] != b"\n":
1257
+ # There should be no direct need to check for a change of one byte.
1258
+ length += 1
1259
+ data += b"\n"
1260
+ super().set_data(bytes(data))
1261
+ else:
1262
+ stream_data = stream.get_data()
1263
+ assert stream_data is not None
1264
+ super().set_data(stream_data)
1265
+ self.forced_encoding = forced_encoding
1266
+
1267
+ def replicate(
1268
+ self,
1269
+ pdf_dest: PdfWriterProtocol,
1270
+ ) -> "ContentStream":
1271
+ d__ = cast(
1272
+ "ContentStream",
1273
+ self._reference_clone(self.__class__(None, None), pdf_dest, False),
1274
+ )
1275
+ d__._data = self._data
1276
+ try:
1277
+ decoded_self = self.decoded_self
1278
+ if decoded_self is None:
1279
+ self.decoded_self = None
1280
+ else:
1281
+ self.decoded_self = cast(
1282
+ "DecodedStreamObject", decoded_self.replicate(pdf_dest)
1283
+ )
1284
+ except Exception:
1285
+ pass
1286
+ for k, v in self.items():
1287
+ d__[k.replicate(pdf_dest)] = (
1288
+ v.replicate(pdf_dest) if hasattr(v, "replicate") else v
1289
+ )
1290
+ return d__
1291
+ d__.set_data(self._data)
1292
+ d__.pdf = pdf_dest
1293
+ d__._operations = list(self._operations)
1294
+ d__.forced_encoding = self.forced_encoding
1295
+ return d__
1296
+
1297
+ def clone(
1298
+ self,
1299
+ pdf_dest: Any,
1300
+ force_duplicate: bool = False,
1301
+ ignore_fields: Optional[Sequence[Union[str, int]]] = (),
1302
+ ) -> "ContentStream":
1303
+ """
1304
+ Clone object into pdf_dest.
1305
+
1306
+ Args:
1307
+ pdf_dest:
1308
+ force_duplicate:
1309
+ ignore_fields:
1310
+
1311
+ Returns:
1312
+ The cloned ContentStream
1313
+
1314
+ """
1315
+ try:
1316
+ if self.indirect_reference.pdf == pdf_dest and not force_duplicate: # type: ignore[union-attr]
1317
+ return self
1318
+ except Exception:
1319
+ pass
1320
+
1321
+ visited: set[tuple[int, int]] = set()
1322
+ d__ = cast(
1323
+ "ContentStream",
1324
+ self._reference_clone(
1325
+ self.__class__(None, None), pdf_dest, force_duplicate
1326
+ ),
1327
+ )
1328
+ if ignore_fields is None:
1329
+ ignore_fields = []
1330
+ d__._clone(self, pdf_dest, force_duplicate, ignore_fields, visited)
1331
+ return d__
1332
+
1333
+ def _clone(
1334
+ self,
1335
+ src: DictionaryObject,
1336
+ pdf_dest: PdfWriterProtocol,
1337
+ force_duplicate: bool,
1338
+ ignore_fields: Optional[Sequence[Union[str, int]]],
1339
+ visited: set[tuple[int, int]],
1340
+ ) -> None:
1341
+ """
1342
+ Update the object from src.
1343
+
1344
+ Args:
1345
+ src:
1346
+ pdf_dest:
1347
+ force_duplicate:
1348
+ ignore_fields:
1349
+
1350
+ """
1351
+ src_cs = cast("ContentStream", src)
1352
+ super().set_data(src_cs._data)
1353
+ self.pdf = pdf_dest
1354
+ self._operations = list(src_cs._operations)
1355
+ self.forced_encoding = src_cs.forced_encoding
1356
+ # no need to call DictionaryObjection or anything
1357
+ # like super(DictionaryObject,self)._clone(src, pdf_dest, force_duplicate, ignore_fields, visited)
1358
+
1359
+ def _parse_content_stream(self, stream: StreamType) -> None:
1360
+ # 7.8.2 Content Streams
1361
+ stream.seek(0, 0)
1362
+ operands: list[Union[int, str, PdfObject]] = []
1363
+ while True:
1364
+ peek = read_non_whitespace(stream)
1365
+ if peek in (b"", 0):
1366
+ break
1367
+ stream.seek(-1, 1)
1368
+ if peek.isalpha() or peek in (b"'", b'"'):
1369
+ operator = read_until_regex(
1370
+ stream=stream, regex=NameObject.delimiter_pattern, length=self._OPERATOR_LENGTH_LIMIT
1371
+ )
1372
+ if operator == b"BI":
1373
+ # begin inline image - a completely different parsing
1374
+ # mechanism is required, of course... thanks buddy...
1375
+ assert operands == []
1376
+ ii = self._read_inline_image(stream)
1377
+ self._operations.append((ii, b"INLINE IMAGE"))
1378
+ else:
1379
+ self._operations.append((operands, operator))
1380
+ operands = []
1381
+ elif peek == b"%":
1382
+ # If we encounter a comment in the content stream, we have to
1383
+ # handle it here. Typically, read_object will handle
1384
+ # encountering a comment -- but read_object assumes that
1385
+ # following the comment must be the object we're trying to
1386
+ # read. In this case, it could be an operator instead.
1387
+ while peek not in (b"\r", b"\n", b""):
1388
+ peek = stream.read(1)
1389
+ else:
1390
+ operands.append(read_object(stream, None, self.forced_encoding))
1391
+
1392
+ def _read_inline_image(self, stream: StreamType) -> dict[str, Any]:
1393
+ # begin reading just after the "BI" - begin image
1394
+ # first read the dictionary of settings.
1395
+ settings = DictionaryObject()
1396
+ while True:
1397
+ tok = read_non_whitespace(stream)
1398
+ if not tok:
1399
+ raise PdfReadError("Unexpected end of stream.")
1400
+ stream.seek(-1, 1)
1401
+ if tok == b"I":
1402
+ # "ID" - begin of image data
1403
+ break
1404
+ key = read_object(stream, self.pdf)
1405
+ tok = read_non_whitespace(stream)
1406
+ stream.seek(-1, 1)
1407
+ value = read_object(stream, self.pdf)
1408
+ settings[key] = value
1409
+ # left at beginning of ID
1410
+ tmp = stream.read(3)
1411
+ assert tmp[:2] == b"ID"
1412
+ filtr = settings.get("/F", settings.get("/Filter", "not set"))
1413
+ savpos = stream.tell()
1414
+ if isinstance(filtr, list):
1415
+ filtr = filtr[0] if filtr else "not set" # used forencoding
1416
+ if not isinstance(filtr, str):
1417
+ # A valid filter is a name or an array of names; anything else
1418
+ # cannot match the abbreviations below, so treat it as unfiltered.
1419
+ filtr = "not set"
1420
+ if "AHx" in filtr or "ASCIIHexDecode" in filtr:
1421
+ data = extract_inline__ascii_hex_decode(stream)
1422
+ elif "A85" in filtr or "ASCII85Decode" in filtr:
1423
+ data = extract_inline__ascii85_decode(stream)
1424
+ elif "RL" in filtr or "RunLengthDecode" in filtr:
1425
+ data = extract_inline__run_length_decode(stream)
1426
+ elif "DCT" in filtr or "DCTDecode" in filtr:
1427
+ data = extract_inline__dct_decode(stream)
1428
+ elif filtr == "not set":
1429
+ cs = settings.get("/CS", "")
1430
+ if isinstance(cs, list):
1431
+ cs = cs[0] if cs else ""
1432
+ if not isinstance(cs, str):
1433
+ cs = ""
1434
+ if "RGB" in cs:
1435
+ lcs: float = 3
1436
+ elif "CMYK" in cs:
1437
+ lcs = 4
1438
+ else:
1439
+ bits = settings.get(
1440
+ "/BPC",
1441
+ 8 if cs in {"/I", "/G", "/Indexed", "/DeviceGray"} else -1,
1442
+ )
1443
+ if isinstance(bits, (int, float)) and bits > 0:
1444
+ lcs = bits / 8.0
1445
+ else:
1446
+ data = extract_inline_default(stream)
1447
+ lcs = -1
1448
+ width = settings.get("/W")
1449
+ height = settings.get("/H")
1450
+ if lcs > 0 and isinstance(width, int) and isinstance(height, int):
1451
+ data = stream.read(ceil(width * lcs) * height)
1452
+ elif lcs > 0:
1453
+ # Without usable dimensions the raw sample length is unknown;
1454
+ # fall back to scanning for the `EI` marker.
1455
+ data = extract_inline_default(stream)
1456
+ # Move to the `EI` if possible.
1457
+ ei = read_non_whitespace(stream)
1458
+ stream.seek(-1, 1)
1459
+ else:
1460
+ data = extract_inline_default(stream)
1461
+
1462
+ ei = stream.read(3)
1463
+ # An `EI` at the very end of the stream yields only two bytes; rewinding
1464
+ # unconditionally would step back into the marker (#3468).
1465
+ if len(ei) == 3:
1466
+ stream.seek(-1, 1)
1467
+ ei_trailing = ei[2:3]
1468
+ if ei[:2] != b"EI" or (ei_trailing != b"" and ei_trailing not in WHITESPACES):
1469
+ # Deal with wrong/missing `EI` tags. Example: Wrong dimensions specified above.
1470
+ stream.seek(savpos, 0)
1471
+ data = extract_inline_default(stream)
1472
+ ei = stream.read(3)
1473
+ if len(ei) == 3:
1474
+ stream.seek(-1, 1)
1475
+ ei_trailing = ei[2:3]
1476
+ if ei[:2] != b"EI" or (
1477
+ ei_trailing != b"" and ei_trailing not in WHITESPACES
1478
+ ): # pragma: no cover
1479
+ # Check the same condition again. This should never fail as
1480
+ # edge cases are covered by `extract_inline_default` above,
1481
+ # but check this ot make sure that we are behind the `EI` afterwards.
1482
+ raise PdfStreamError(
1483
+ f"Could not extract inline image, even using fallback. Expected 'EI', got {ei!r}"
1484
+ )
1485
+ return {"settings": settings, "data": data}
1486
+
1487
+ # This overrides the parent method
1488
+ def get_data(self) -> bytes:
1489
+ if not self._data:
1490
+ new_data = BytesIO()
1491
+ for operands, operator in self._operations:
1492
+ if operator == b"INLINE IMAGE":
1493
+ new_data.write(b"BI")
1494
+ dict_text = BytesIO()
1495
+ operands["settings"].write_to_stream(dict_text)
1496
+ new_data.write(dict_text.getvalue()[2:-2])
1497
+ new_data.write(b"ID ")
1498
+ new_data.write(operands["data"])
1499
+ new_data.write(b"EI")
1500
+ else:
1501
+ for op in operands:
1502
+ op.write_to_stream(new_data)
1503
+ new_data.write(b" ")
1504
+ new_data.write(operator)
1505
+ new_data.write(b"\n")
1506
+ self._data = new_data.getvalue()
1507
+ return self._data
1508
+
1509
+ # This overrides the parent method
1510
+ def set_data(self, data: bytes) -> None:
1511
+ super().set_data(data)
1512
+ self._operations = []
1513
+
1514
+ @property
1515
+ def operations(self) -> list[tuple[Any, bytes]]:
1516
+ if not self._operations and self._data:
1517
+ self._parse_content_stream(BytesIO(self._data))
1518
+ self._data = b""
1519
+ return self._operations
1520
+
1521
+ @operations.setter
1522
+ def operations(self, operations: list[tuple[Any, bytes]]) -> None:
1523
+ self._operations = operations
1524
+ self._data = b""
1525
+
1526
+ def isolate_graphics_state(self) -> None:
1527
+ if self._operations:
1528
+ self._operations.insert(0, ([], b"q"))
1529
+ self._operations.append(([], b"Q"))
1530
+ elif self._data:
1531
+ self._data = b"q\n" + self._data + b"\nQ\n"
1532
+
1533
+ # This overrides the parent method
1534
+ def write_to_stream(
1535
+ self, stream: StreamType, encryption_key: Union[str, bytes, None] = None
1536
+ ) -> None:
1537
+ if not self._data and self._operations:
1538
+ self.get_data() # this ensures ._data is rebuilt
1539
+ super().write_to_stream(stream, encryption_key)
1540
+
1541
+
1542
+ def read_object(
1543
+ stream: StreamType,
1544
+ pdf: Optional[PdfReaderProtocol],
1545
+ forced_encoding: Union[str, list[str], dict[int, str], None] = None,
1546
+ ) -> Union[PdfObject, int, str, ContentStream]:
1547
+ tok = stream.read(1)
1548
+ stream.seek(-1, 1) # reset to start
1549
+ if tok == b"/":
1550
+ return NameObject.read_from_stream(stream, pdf)
1551
+ if tok == b"<":
1552
+ # hexadecimal string OR dictionary
1553
+ peek = stream.read(2)
1554
+ stream.seek(-2, 1) # reset to start
1555
+ if peek == b"<<":
1556
+ return DictionaryObject.read_from_stream(stream, pdf, forced_encoding)
1557
+ return read_hex_string_from_stream(stream, forced_encoding)
1558
+ if tok == b"[":
1559
+ return ArrayObject.read_from_stream(stream, pdf, forced_encoding)
1560
+ if tok in (b"t", b"f"):
1561
+ return BooleanObject.read_from_stream(stream)
1562
+ if tok == b"(":
1563
+ return read_string_from_stream(stream, forced_encoding)
1564
+ if tok == b"e" and stream.read(6) == b"endobj":
1565
+ return NullObject()
1566
+ if tok == b"n":
1567
+ return NullObject.read_from_stream(stream)
1568
+ if tok == b"%":
1569
+ # comment
1570
+ skip_over_comment(stream)
1571
+ tok = read_non_whitespace(stream)
1572
+ stream.seek(-1, 1)
1573
+ return read_object(stream, pdf, forced_encoding)
1574
+ if tok in b"0123456789+-.":
1575
+ # number object OR indirect reference
1576
+ peek = stream.read(20)
1577
+ stream.seek(-len(peek), 1) # reset to start
1578
+ if IndirectPattern.match(peek) is not None:
1579
+ assert pdf is not None, "mypy"
1580
+ return IndirectObject.read_from_stream(stream, pdf)
1581
+ return NumberObject.read_from_stream(stream)
1582
+ pos = stream.tell()
1583
+ stream.seek(-20, 1)
1584
+ stream_extract = stream.read(80)
1585
+ stream.seek(pos)
1586
+ read_until_whitespace(stream)
1587
+ raise PdfReadError(
1588
+ f"Invalid Elementary Object starting with {tok!r} @{pos}: {stream_extract!r}"
1589
+ )
1590
+
1591
+
1592
+ class Field(TreeObject):
1593
+ """
1594
+ A class representing a field dictionary.
1595
+
1596
+ This class is accessed through
1597
+ :meth:`get_fields()<pypdf.PdfReader.get_fields>`
1598
+ """
1599
+
1600
+ def __init__(self, data: DictionaryObject) -> None:
1601
+ DictionaryObject.__init__(self)
1602
+ field_attributes = (
1603
+ FieldDictionaryAttributes.attributes()
1604
+ + CheckboxRadioButtonAttributes.attributes()
1605
+ )
1606
+ self.indirect_reference = data.indirect_reference
1607
+ for attr in field_attributes:
1608
+ try:
1609
+ self[NameObject(attr)] = data[attr]
1610
+ except KeyError:
1611
+ pass
1612
+ if isinstance(self.get("/V"), EncodedStreamObject):
1613
+ d = cast(EncodedStreamObject, self[NameObject("/V")]).get_data()
1614
+ if isinstance(d, bytes):
1615
+ d_str = d.decode()
1616
+ elif d is None:
1617
+ d_str = ""
1618
+ else:
1619
+ raise Exception("Should never happen")
1620
+ self[NameObject("/V")] = TextStringObject(d_str)
1621
+
1622
+ # TABLE 8.69 Entries common to all field dictionaries
1623
+ @property
1624
+ def field_type(self) -> Optional[NameObject]:
1625
+ """Read-only property accessing the type of this field."""
1626
+ return self.get(FieldDictionaryAttributes.FT)
1627
+
1628
+ @property
1629
+ def parent(self) -> Optional[DictionaryObject]:
1630
+ """Read-only property accessing the parent of this field."""
1631
+ return self.get(FieldDictionaryAttributes.Parent)
1632
+
1633
+ @property
1634
+ def kids(self) -> Optional["ArrayObject"]:
1635
+ """Read-only property accessing the kids of this field."""
1636
+ return self.get(FieldDictionaryAttributes.Kids)
1637
+
1638
+ @property
1639
+ def name(self) -> Optional[str]:
1640
+ """Read-only property accessing the name of this field."""
1641
+ return self.get(FieldDictionaryAttributes.T)
1642
+
1643
+ @property
1644
+ def alternate_name(self) -> Optional[str]:
1645
+ """Read-only property accessing the alternate name of this field."""
1646
+ return self.get(FieldDictionaryAttributes.TU)
1647
+
1648
+ @property
1649
+ def mapping_name(self) -> Optional[str]:
1650
+ """
1651
+ Read-only property accessing the mapping name of this field.
1652
+
1653
+ This name is used by pypdf as a key in the dictionary returned by
1654
+ :meth:`get_fields()<pypdf.PdfReader.get_fields>`
1655
+ """
1656
+ return self.get(FieldDictionaryAttributes.TM)
1657
+
1658
+ @property
1659
+ def flags(self) -> Optional[int]:
1660
+ """
1661
+ Read-only property accessing the field flags, specifying various
1662
+ characteristics of the field (see Table 8.70 of the PDF 1.7 reference).
1663
+ """
1664
+ return self.get(FieldDictionaryAttributes.Ff)
1665
+
1666
+ @property
1667
+ def value(self) -> Optional[Any]:
1668
+ """
1669
+ Read-only property accessing the value of this field.
1670
+
1671
+ Format varies based on field type.
1672
+ """
1673
+ return self.get(FieldDictionaryAttributes.V)
1674
+
1675
+ @property
1676
+ def default_value(self) -> Optional[Any]:
1677
+ """Read-only property accessing the default value of this field."""
1678
+ return self.get(FieldDictionaryAttributes.DV)
1679
+
1680
+ @property
1681
+ def additional_actions(self) -> Optional[DictionaryObject]:
1682
+ """
1683
+ Read-only property accessing the additional actions dictionary.
1684
+
1685
+ This dictionary defines the field's behavior in response to trigger
1686
+ events. See Section 8.5.2 of the PDF 1.7 reference.
1687
+ """
1688
+ return self.get(FieldDictionaryAttributes.AA)
1689
+
1690
+
1691
+ class Destination(TreeObject):
1692
+ """
1693
+ A class representing a destination within a PDF file.
1694
+
1695
+ See section 12.3.2 of the PDF 2.0 reference.
1696
+
1697
+ Args:
1698
+ title: Title of this destination.
1699
+ page: Reference to the page of this destination. Should
1700
+ be an instance of :class:`IndirectObject<pypdf.generic.IndirectObject>`.
1701
+ fit: How the destination is displayed.
1702
+
1703
+ Raises:
1704
+ PdfReadError: If destination type is invalid.
1705
+
1706
+ """
1707
+
1708
+ node: Optional[
1709
+ DictionaryObject
1710
+ ] = None # node provide access to the original Object
1711
+
1712
+ def __init__(
1713
+ self,
1714
+ title: Union[str, bytes],
1715
+ page: Union[NumberObject, IndirectObject, NullObject, DictionaryObject],
1716
+ fit: Fit,
1717
+ ) -> None:
1718
+ self._filtered_children: list[Any] = [] # used in PdfWriter
1719
+
1720
+ typ = fit.fit_type
1721
+ args = fit.fit_args
1722
+
1723
+ DictionaryObject.__init__(self)
1724
+ self[NameObject("/Title")] = TextStringObject(title)
1725
+ self[NameObject("/Page")] = page
1726
+ self[NameObject("/Type")] = typ
1727
+
1728
+ # from table 8.2 of the PDF 1.7 reference.
1729
+ if typ == "/XYZ":
1730
+ if len(args) < 1: # left is missing : should never occur
1731
+ args.append(NumberObject(0.0))
1732
+ if len(args) < 2: # top is missing
1733
+ args.append(NumberObject(0.0))
1734
+ if len(args) < 3: # zoom is missing
1735
+ args.append(NumberObject(0.0))
1736
+ # surplus arguments are ignored rather than failing the unpacking
1737
+ (
1738
+ self[NameObject(TA.LEFT)],
1739
+ self[NameObject(TA.TOP)],
1740
+ self[NameObject("/Zoom")],
1741
+ ) = args[:3]
1742
+ elif len(args) == 0:
1743
+ pass
1744
+ elif typ == TF.FIT_R:
1745
+ if len(args) == 4: # a wrong number of arguments degrades to null
1746
+ (
1747
+ self[NameObject(TA.LEFT)],
1748
+ self[NameObject(TA.BOTTOM)],
1749
+ self[NameObject(TA.RIGHT)],
1750
+ self[NameObject(TA.TOP)],
1751
+ ) = args
1752
+ else:
1753
+ (
1754
+ self[NameObject(TA.LEFT)],
1755
+ self[NameObject(TA.BOTTOM)],
1756
+ self[NameObject(TA.RIGHT)],
1757
+ self[NameObject(TA.TOP)],
1758
+ ) = (NullObject(), NullObject(), NullObject(), NullObject())
1759
+ elif typ in [TF.FIT_H, TF.FIT_BH]:
1760
+ try: # Prefer to be more robust not only to null parameters
1761
+ (self[NameObject(TA.TOP)],) = args
1762
+ except Exception:
1763
+ (self[NameObject(TA.TOP)],) = (NullObject(),)
1764
+ elif typ in [TF.FIT_V, TF.FIT_BV]:
1765
+ try: # Prefer to be more robust not only to null parameters
1766
+ (self[NameObject(TA.LEFT)],) = args
1767
+ except Exception:
1768
+ (self[NameObject(TA.LEFT)],) = (NullObject(),)
1769
+ elif typ in [TF.FIT, TF.FIT_B]:
1770
+ pass
1771
+ else:
1772
+ raise PdfReadError(f"Unknown Destination Type: {typ!r}")
1773
+
1774
+ @property
1775
+ def dest_array(self) -> "ArrayObject":
1776
+ return ArrayObject(
1777
+ [self.raw_get("/Page"), self["/Type"]]
1778
+ + [
1779
+ self[x]
1780
+ for x in ["/Left", "/Bottom", "/Right", "/Top", "/Zoom"]
1781
+ if x in self
1782
+ ]
1783
+ )
1784
+
1785
+ def write_to_stream(
1786
+ self, stream: StreamType, encryption_key: Union[str, bytes, None] = None
1787
+ ) -> None:
1788
+ if encryption_key is not None: # deprecated
1789
+ deprecation_no_replacement(
1790
+ "the encryption_key parameter of write_to_stream", "5.0.0"
1791
+ )
1792
+ stream.write(b"<<\n")
1793
+ key = NameObject("/D")
1794
+ key.write_to_stream(stream)
1795
+ stream.write(b" ")
1796
+ value = self.dest_array
1797
+ value.write_to_stream(stream)
1798
+
1799
+ key = NameObject("/S")
1800
+ key.write_to_stream(stream)
1801
+ stream.write(b" ")
1802
+ value_s = NameObject("/GoTo")
1803
+ value_s.write_to_stream(stream)
1804
+
1805
+ stream.write(b"\n")
1806
+ stream.write(b">>")
1807
+
1808
+ @property
1809
+ def title(self) -> Optional[str]:
1810
+ """Read-only property accessing the destination title."""
1811
+ return self.get("/Title")
1812
+
1813
+ @property
1814
+ def page(self) -> Optional[IndirectObject]:
1815
+ """Read-only property accessing the IndirectObject of the destination page."""
1816
+ return self.get("/Page")
1817
+
1818
+ @property
1819
+ def typ(self) -> Optional[str]:
1820
+ """Read-only property accessing the destination type."""
1821
+ return self.get("/Type")
1822
+
1823
+ @property
1824
+ def zoom(self) -> Optional[int]:
1825
+ """Read-only property accessing the zoom factor."""
1826
+ return self.get("/Zoom", None)
1827
+
1828
+ @property
1829
+ def left(self) -> Optional[FloatObject]:
1830
+ """Read-only property accessing the left horizontal coordinate."""
1831
+ return self.get("/Left", None)
1832
+
1833
+ @property
1834
+ def right(self) -> Optional[FloatObject]:
1835
+ """Read-only property accessing the right horizontal coordinate."""
1836
+ return self.get("/Right", None)
1837
+
1838
+ @property
1839
+ def top(self) -> Optional[FloatObject]:
1840
+ """Read-only property accessing the top vertical coordinate."""
1841
+ return self.get("/Top", None)
1842
+
1843
+ @property
1844
+ def bottom(self) -> Optional[FloatObject]:
1845
+ """Read-only property accessing the bottom vertical coordinate."""
1846
+ return self.get("/Bottom", None)
1847
+
1848
+ @property
1849
+ def color(self) -> Optional["ArrayObject"]:
1850
+ """Read-only property accessing the color in (R, G, B) with values 0.0-1.0."""
1851
+ return cast(
1852
+ "ArrayObject",
1853
+ self.get("/C", ArrayObject([FloatObject(0), FloatObject(0), FloatObject(0)])),
1854
+ )
1855
+
1856
+ @property
1857
+ def font_format(self) -> Optional[OutlineFontFlag]:
1858
+ """
1859
+ Read-only property accessing the font type.
1860
+
1861
+ 1=italic, 2=bold, 3=both
1862
+ """
1863
+ return OutlineFontFlag(self.get("/F", 0))
1864
+
1865
+ @property
1866
+ def outline_count(self) -> Optional[int]:
1867
+ """
1868
+ Read-only property accessing the outline count.
1869
+
1870
+ positive = expanded
1871
+ negative = collapsed
1872
+ absolute value = number of visible descendants at all levels
1873
+ """
1874
+ return self.get("/Count", None)
.venv/lib/python3.13/site-packages/pypdf/generic/_files.py ADDED
@@ -0,0 +1,418 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import bisect
4
+ from functools import cached_property
5
+ from typing import TYPE_CHECKING, cast
6
+
7
+ from pypdf._utils import format_iso8824_date, parse_iso8824_date
8
+ from pypdf.constants import CatalogAttributes as CA
9
+ from pypdf.constants import FileSpecificationDictionaryEntries
10
+ from pypdf.constants import PageAttributes as PG
11
+ from pypdf.errors import PdfReadError, PyPdfError
12
+ from pypdf.generic import (
13
+ ArrayObject,
14
+ ByteStringObject,
15
+ DecodedStreamObject,
16
+ DictionaryObject,
17
+ NameObject,
18
+ NullObject,
19
+ NumberObject,
20
+ StreamObject,
21
+ TextStringObject,
22
+ is_null_or_none,
23
+ )
24
+
25
+ if TYPE_CHECKING:
26
+ import datetime
27
+ from collections.abc import Generator
28
+
29
+ from pypdf._writer import PdfWriter
30
+
31
+
32
+ class EmbeddedFile:
33
+ """
34
+ Container holding the information on an embedded file.
35
+
36
+ Attributes are evaluated lazily if possible.
37
+
38
+ Further information on embedded files can be found in section 7.11 of the PDF 2.0 specification.
39
+ """
40
+ def __init__(self, name: str, pdf_object: DictionaryObject, parent: ArrayObject | None = None) -> None:
41
+ """
42
+ Args:
43
+ name: The (primary) name as provided in the name tree.
44
+ pdf_object: The corresponding PDF object to allow retrieving further data.
45
+ parent: The parent list.
46
+ """
47
+ self._name = name
48
+ self.pdf_object = pdf_object
49
+ self._parent = parent
50
+
51
+ @property
52
+ def name(self) -> str:
53
+ """
54
+ The (primary) name of the embedded file as provided in the name tree.
55
+
56
+ .. warning::
57
+
58
+ This value can contain arbitrary characters. Please make sure to sanitize it before
59
+ using it to write the file content to the disk for example.
60
+ """
61
+ return self._name
62
+
63
+ @classmethod
64
+ def _create_new(cls, writer: PdfWriter, name: str, content: str | bytes) -> EmbeddedFile:
65
+ """
66
+ Create a new embedded file and add it to the PdfWriter.
67
+
68
+ Args:
69
+ writer: The PdfWriter instance to add the embedded file to.
70
+ name: The filename to display.
71
+ content: The data in the file.
72
+
73
+ Returns:
74
+ EmbeddedFile instance for the newly created embedded file.
75
+ """
76
+ # Convert string content to bytes if needed
77
+ if isinstance(content, str):
78
+ content = content.encode("latin-1")
79
+
80
+ # Create the file entry (the actual embedded file stream)
81
+ file_entry = DecodedStreamObject()
82
+ file_entry.set_data(content)
83
+ file_entry.update({NameObject(PG.TYPE): NameObject("/EmbeddedFile")})
84
+
85
+ # Create the /EF entry
86
+ ef_entry = DictionaryObject()
87
+ ef_entry.update({NameObject("/F"): writer._add_object(file_entry)})
88
+
89
+ # Create the filespec dictionary
90
+ from pypdf.generic import create_string_object # noqa: PLC0415
91
+ filespec = DictionaryObject()
92
+ filespec_reference = writer._add_object(filespec)
93
+ name_object = cast(TextStringObject, create_string_object(name))
94
+ filespec.update(
95
+ {
96
+ NameObject(PG.TYPE): NameObject("/Filespec"),
97
+ NameObject(FileSpecificationDictionaryEntries.F): name_object,
98
+ NameObject(FileSpecificationDictionaryEntries.EF): ef_entry,
99
+ }
100
+ )
101
+
102
+ # Add the name and filespec to the names array.
103
+ # We use the inverse order for insertion, as this allows us to re-use the
104
+ # same index.
105
+ names_array = cls._get_names_array(writer)
106
+ insertion_index = cls._get_insertion_index(names_array, name_object)
107
+ names_array.insert(insertion_index, filespec_reference)
108
+ names_array.insert(insertion_index, name_object)
109
+
110
+ # Return an EmbeddedFile instance
111
+ return cls(name=name, pdf_object=filespec, parent=names_array)
112
+
113
+ @classmethod
114
+ def _get_names_array(cls, writer: PdfWriter) -> ArrayObject:
115
+ """Get the names array for embedded files, possibly creating and flattening it."""
116
+ if CA.NAMES not in writer.root_object:
117
+ # Add the /Names entry to the catalog.
118
+ writer.root_object[NameObject(CA.NAMES)] = writer._add_object(DictionaryObject())
119
+
120
+ names_dict = cast(DictionaryObject, writer.root_object[CA.NAMES])
121
+ if "/EmbeddedFiles" not in names_dict:
122
+ # We do not yet have an entry for embedded files. Create and return it.
123
+ names = ArrayObject()
124
+ embedded_files_names_dictionary = DictionaryObject(
125
+ {NameObject(CA.NAMES): names}
126
+ )
127
+ names_dict[NameObject("/EmbeddedFiles")] = writer._add_object(embedded_files_names_dictionary)
128
+ return names
129
+
130
+ # We have an existing embedded files entry.
131
+ embedded_files_names_tree = cast(DictionaryObject, names_dict["/EmbeddedFiles"])
132
+ if "/Names" in embedded_files_names_tree:
133
+ # Simple case: We already have a flat list.
134
+ return cast(ArrayObject, embedded_files_names_tree[NameObject(CA.NAMES)])
135
+ if "/Kids" not in embedded_files_names_tree:
136
+ # Invalid case: This is no name tree.
137
+ raise PdfReadError("Got neither Names nor Kids in embedded files tree.")
138
+
139
+ # Complex case: Convert a /Kids-based name tree to a /Names-based one.
140
+ # /Name-based ones are much easier to handle and allow us to simplify the
141
+ # actual insertion logic by only having to consider one case.
142
+ names = ArrayObject()
143
+ kids = cast(ArrayObject, embedded_files_names_tree["/Kids"].get_object())
144
+ embedded_files_names_dictionary = DictionaryObject(
145
+ {NameObject(CA.NAMES): names}
146
+ )
147
+ names_dict[NameObject("/EmbeddedFiles")] = writer._add_object(embedded_files_names_dictionary)
148
+ for kid in kids:
149
+ # Write the flattened file entries. As we do not change the actual files,
150
+ # this should not have any impact on references to them.
151
+ # There might be further (nested) kids here.
152
+ # Wait for an example before evaluating an implementation.
153
+ for name in kid.get_object().get("/Names", []):
154
+ names.append(name)
155
+ return names
156
+
157
+ @classmethod
158
+ def _get_insertion_index(cls, names_array: ArrayObject, name: str) -> int:
159
+ keys = [names_array[i].encode("utf-8") for i in range(0, len(names_array), 2)]
160
+ name_bytes = name.encode("utf-8")
161
+
162
+ start = bisect.bisect_left(keys, name_bytes)
163
+ end = bisect.bisect_right(keys, name_bytes)
164
+
165
+ if start != end:
166
+ return end * 2
167
+ if start == 0:
168
+ return 0
169
+ if start == (key_count := len(keys)):
170
+ return key_count * 2
171
+ return end * 2
172
+
173
+ @property
174
+ def alternative_name(self) -> str | None:
175
+ """
176
+ Retrieve the alternative name (as per the file specification dictionary).
177
+
178
+ .. warning::
179
+
180
+ This value can contain arbitrary characters. Please make sure to sanitize it before
181
+ using it to write the file content to the disk for example.
182
+ """
183
+ for key in [FileSpecificationDictionaryEntries.UF, FileSpecificationDictionaryEntries.F]:
184
+ # PDF 2.0 reference, table 43:
185
+ # > A PDF reader shall use the value of the UF key, when present, instead of the F key.
186
+ if key in self.pdf_object:
187
+ value = self.pdf_object[key].get_object()
188
+ if not is_null_or_none(value):
189
+ return cast(str, value)
190
+ return None
191
+
192
+ @alternative_name.setter
193
+ def alternative_name(self, value: TextStringObject | None) -> None:
194
+ """Set the alternative name (as per the file specification dictionary)."""
195
+ if value is None:
196
+ if FileSpecificationDictionaryEntries.UF in self.pdf_object:
197
+ self.pdf_object[NameObject(FileSpecificationDictionaryEntries.UF)] = NullObject()
198
+ if FileSpecificationDictionaryEntries.F in self.pdf_object:
199
+ self.pdf_object[NameObject(FileSpecificationDictionaryEntries.F)] = NullObject()
200
+ else:
201
+ self.pdf_object[NameObject(FileSpecificationDictionaryEntries.UF)] = value
202
+ self.pdf_object[NameObject(FileSpecificationDictionaryEntries.F)] = value
203
+
204
+ @property
205
+ def description(self) -> str | None:
206
+ """Retrieve the description."""
207
+ value = self.pdf_object.get(FileSpecificationDictionaryEntries.DESC)
208
+ if is_null_or_none(value):
209
+ return None
210
+ return value
211
+
212
+ @description.setter
213
+ def description(self, value: TextStringObject | None) -> None:
214
+ """Set the description."""
215
+ if value is None:
216
+ self.pdf_object[NameObject(FileSpecificationDictionaryEntries.DESC)] = NullObject()
217
+ else:
218
+ self.pdf_object[NameObject(FileSpecificationDictionaryEntries.DESC)] = value
219
+
220
+ @property
221
+ def associated_file_relationship(self) -> str:
222
+ """Retrieve the relationship of the referring document to this embedded file."""
223
+ return cast(
224
+ NameObject,
225
+ self.pdf_object.get("/AFRelationship", NameObject("/Unspecified")),
226
+ )
227
+
228
+ @associated_file_relationship.setter
229
+ def associated_file_relationship(self, value: NameObject) -> None:
230
+ """Set the relationship of the referring document to this embedded file."""
231
+ self.pdf_object[NameObject("/AFRelationship")] = value
232
+
233
+ @property
234
+ def _embedded_file(self) -> StreamObject:
235
+ """Retrieve the actual embedded file stream."""
236
+ if "/EF" not in self.pdf_object:
237
+ raise PdfReadError(f"/EF entry not found: {self.pdf_object}")
238
+ ef = cast(DictionaryObject, self.pdf_object["/EF"])
239
+ for key in [FileSpecificationDictionaryEntries.UF, FileSpecificationDictionaryEntries.F]:
240
+ if key in ef:
241
+ return cast(StreamObject, ef[key].get_object())
242
+ raise PdfReadError(f"No /(U)F key found in file dictionary: {ef}")
243
+
244
+ @property
245
+ def _params(self) -> DictionaryObject:
246
+ """Retrieve the file-specific parameters."""
247
+ return cast(DictionaryObject, self._embedded_file.get("/Params", DictionaryObject()).get_object())
248
+
249
+ @cached_property
250
+ def _ensure_params(self) -> DictionaryObject:
251
+ """Ensure the /Params dictionary exists and return it."""
252
+ embedded_file = self._embedded_file
253
+ if "/Params" not in embedded_file:
254
+ embedded_file[NameObject("/Params")] = DictionaryObject()
255
+ return cast(DictionaryObject, embedded_file["/Params"])
256
+
257
+ @property
258
+ def subtype(self) -> str | None:
259
+ """Retrieve the subtype. This is a MIME media type, prefixed by a slash."""
260
+ value = self._embedded_file.get("/Subtype")
261
+ if is_null_or_none(value):
262
+ return None
263
+ return value
264
+
265
+ @subtype.setter
266
+ def subtype(self, value: NameObject | None) -> None:
267
+ """Set the subtype. This should be a MIME media type, prefixed by a slash."""
268
+ embedded_file = self._embedded_file
269
+ if value is None:
270
+ embedded_file[NameObject("/Subtype")] = NullObject()
271
+ else:
272
+ embedded_file[NameObject("/Subtype")] = value
273
+
274
+ @property
275
+ def content(self) -> bytes:
276
+ """Retrieve the actual file content."""
277
+ return self._embedded_file.get_data()
278
+
279
+ @content.setter
280
+ def content(self, value: str | bytes) -> None:
281
+ """Set the file content."""
282
+ if isinstance(value, str):
283
+ value = value.encode("latin-1")
284
+ self._embedded_file.set_data(value)
285
+
286
+ @property
287
+ def size(self) -> int | None:
288
+ """Retrieve the size of the uncompressed file in bytes."""
289
+ value = self._params.get("/Size")
290
+ if is_null_or_none(value):
291
+ return None
292
+ return value
293
+
294
+ @size.setter
295
+ def size(self, value: NumberObject | None) -> None:
296
+ """Set the size of the uncompressed file in bytes."""
297
+ params = self._ensure_params
298
+ if value is None:
299
+ params[NameObject("/Size")] = NullObject()
300
+ else:
301
+ params[NameObject("/Size")] = value
302
+
303
+ @property
304
+ def creation_date(self) -> datetime.datetime | None:
305
+ """Retrieve the file creation datetime."""
306
+ return parse_iso8824_date(self._params.get("/CreationDate"))
307
+
308
+ @creation_date.setter
309
+ def creation_date(self, value: datetime.datetime | None) -> None:
310
+ """Set the file creation datetime."""
311
+ params = self._ensure_params
312
+ if value is None:
313
+ params[NameObject("/CreationDate")] = NullObject()
314
+ else:
315
+ date_str = format_iso8824_date(value)
316
+ params[NameObject("/CreationDate")] = TextStringObject(date_str)
317
+
318
+ @property
319
+ def modification_date(self) -> datetime.datetime | None:
320
+ """Retrieve the datetime of the last file modification."""
321
+ return parse_iso8824_date(self._params.get("/ModDate"))
322
+
323
+ @modification_date.setter
324
+ def modification_date(self, value: datetime.datetime | None) -> None:
325
+ """Set the datetime of the last file modification."""
326
+ params = self._ensure_params
327
+ if value is None:
328
+ params[NameObject("/ModDate")] = NullObject()
329
+ else:
330
+ date_str = format_iso8824_date(value)
331
+ params[NameObject("/ModDate")] = TextStringObject(date_str)
332
+
333
+ @property
334
+ def checksum(self) -> bytes | None:
335
+ """Retrieve the MD5 checksum of the (uncompressed) file."""
336
+ value = self._params.get("/CheckSum")
337
+ if is_null_or_none(value):
338
+ return None
339
+ return value
340
+
341
+ @checksum.setter
342
+ def checksum(self, value: ByteStringObject | None) -> None:
343
+ """Set the MD5 checksum of the (uncompressed) file."""
344
+ params = self._ensure_params
345
+ if value is None:
346
+ params[NameObject("/CheckSum")] = NullObject()
347
+ else:
348
+ params[NameObject("/CheckSum")] = value
349
+
350
+ def delete(self) -> None:
351
+ """Delete the file from the document."""
352
+ if not self._parent:
353
+ raise PyPdfError("Parent required to delete file from document.")
354
+ if self.pdf_object in self._parent:
355
+ index = self._parent.index(self.pdf_object)
356
+ elif (
357
+ (indirect_reference := getattr(self.pdf_object, "indirect_reference", None)) is not None
358
+ and indirect_reference in self._parent
359
+ ):
360
+ index = self._parent.index(indirect_reference)
361
+ else:
362
+ raise PyPdfError("File not found in parent object.")
363
+ self._parent.pop(index) # Reference.
364
+ self._parent.pop(index - 1) # Name.
365
+ self.pdf_object = DictionaryObject() # Invalidate.
366
+
367
+ def __repr__(self) -> str:
368
+ return f"<{self.__class__.__name__} name={self.name!r}>"
369
+
370
+ @classmethod
371
+ def _load_from_names(cls, names: ArrayObject) -> Generator[EmbeddedFile]:
372
+ """
373
+ Convert the given name tree into class instances.
374
+
375
+ Args:
376
+ names: The name tree to load the data from.
377
+
378
+ Returns:
379
+ Iterable of class instances for the files found.
380
+ """
381
+ # This is a name tree of the format [name_1, reference_1, name_2, reference_2, ...]
382
+ for i, name in enumerate(names):
383
+ if not isinstance(name, str):
384
+ # Skip plain strings and retrieve them as `direct_name` by index.
385
+ file_dictionary = name.get_object()
386
+ direct_name = names[i - 1].get_object()
387
+ yield EmbeddedFile(name=direct_name, pdf_object=file_dictionary, parent=names)
388
+
389
+ @classmethod
390
+ def _load(cls, catalog: DictionaryObject) -> Generator[EmbeddedFile]:
391
+ """
392
+ Load the embedded files for the given document catalog.
393
+
394
+ This method and its signature are considered internal API and thus not exposed publicly for now.
395
+
396
+ Args:
397
+ catalog: The document catalog to load from.
398
+
399
+ Returns:
400
+ Iterable of class instances for the files found.
401
+ """
402
+ try:
403
+ container = cast(
404
+ DictionaryObject,
405
+ cast(DictionaryObject, catalog["/Names"])["/EmbeddedFiles"],
406
+ )
407
+ except KeyError:
408
+ return
409
+
410
+ if "/Kids" in container:
411
+ for kid in cast(ArrayObject, container["/Kids"].get_object()):
412
+ # There might be further (nested) kids here.
413
+ # Wait for an example before evaluating an implementation.
414
+ kid = kid.get_object()
415
+ if "/Names" in kid:
416
+ yield from cls._load_from_names(cast(ArrayObject, kid["/Names"]))
417
+ if "/Names" in container:
418
+ yield from cls._load_from_names(cast(ArrayObject, container["/Names"]))
.venv/lib/python3.13/site-packages/pypdf/generic/_fit.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Optional, Union
2
+
3
+ from ._base import is_null_or_none
4
+
5
+
6
+ class Fit:
7
+ def __init__(
8
+ self, fit_type: str, fit_args: tuple[Union[float, Any, None], ...] = ()
9
+ ) -> None:
10
+ from ._base import FloatObject, NameObject, NullObject, NumberObject # noqa: PLC0415
11
+
12
+ self.fit_type = NameObject(fit_type)
13
+ self.fit_args: list[Union[NullObject, FloatObject, NumberObject]] = [
14
+ NullObject() if is_null_or_none(a) else FloatObject(a) for a in fit_args
15
+ ]
16
+
17
+ @classmethod
18
+ def xyz(
19
+ cls,
20
+ left: Optional[float] = None,
21
+ top: Optional[float] = None,
22
+ zoom: Optional[float] = None,
23
+ ) -> "Fit":
24
+ """
25
+ Display the page designated by page, with the coordinates (left, top)
26
+ positioned at the upper-left corner of the window and the contents
27
+ of the page magnified by the factor zoom.
28
+
29
+ A null value for any of the parameters left, top, or zoom specifies
30
+ that the current value of that parameter is to be retained unchanged.
31
+
32
+ A zoom value of 0 has the same meaning as a null value.
33
+
34
+ Args:
35
+ left:
36
+ top:
37
+ zoom:
38
+
39
+ Returns:
40
+ The created fit object.
41
+
42
+ """
43
+ return Fit(fit_type="/XYZ", fit_args=(left, top, zoom))
44
+
45
+ @classmethod
46
+ def fit(cls) -> "Fit":
47
+ """
48
+ Display the page designated by page, with its contents magnified just
49
+ enough to fit the entire page within the window both horizontally and
50
+ vertically.
51
+
52
+ If the required horizontal and vertical magnification factors are
53
+ different, use the smaller of the two, centering the page within the
54
+ window in the other dimension.
55
+ """
56
+ return Fit(fit_type="/Fit")
57
+
58
+ @classmethod
59
+ def fit_horizontally(cls, top: Optional[float] = None) -> "Fit":
60
+ """
61
+ Display the page designated by page, with the vertical coordinate top
62
+ positioned at the top edge of the window and the contents of the page
63
+ magnified just enough to fit the entire width of the page within the
64
+ window.
65
+
66
+ A null value for ``top`` specifies that the current value of that
67
+ parameter is to be retained unchanged.
68
+
69
+ Args:
70
+ top:
71
+
72
+ Returns:
73
+ The created fit object.
74
+
75
+ """
76
+ return Fit(fit_type="/FitH", fit_args=(top,))
77
+
78
+ @classmethod
79
+ def fit_vertically(cls, left: Optional[float] = None) -> "Fit":
80
+ return Fit(fit_type="/FitV", fit_args=(left,))
81
+
82
+ @classmethod
83
+ def fit_rectangle(
84
+ cls,
85
+ left: Optional[float] = None,
86
+ bottom: Optional[float] = None,
87
+ right: Optional[float] = None,
88
+ top: Optional[float] = None,
89
+ ) -> "Fit":
90
+ """
91
+ Display the page designated by page, with its contents magnified
92
+ just enough to fit the rectangle specified by the coordinates
93
+ left, bottom, right, and top entirely within the window
94
+ both horizontally and vertically.
95
+
96
+ If the required horizontal and vertical magnification factors are
97
+ different, use the smaller of the two, centering the rectangle within
98
+ the window in the other dimension.
99
+
100
+ A null value for any of the parameters may result in unpredictable
101
+ behavior.
102
+
103
+ Args:
104
+ left:
105
+ bottom:
106
+ right:
107
+ top:
108
+
109
+ Returns:
110
+ The created fit object.
111
+
112
+ """
113
+ return Fit(fit_type="/FitR", fit_args=(left, bottom, right, top))
114
+
115
+ @classmethod
116
+ def fit_box(cls) -> "Fit":
117
+ """
118
+ Display the page designated by page, with its contents magnified just
119
+ enough to fit its bounding box entirely within the window both
120
+ horizontally and vertically.
121
+
122
+ If the required horizontal and vertical magnification factors are
123
+ different, use the smaller of the two, centering the bounding box
124
+ within the window in the other dimension.
125
+ """
126
+ return Fit(fit_type="/FitB")
127
+
128
+ @classmethod
129
+ def fit_box_horizontally(cls, top: Optional[float] = None) -> "Fit":
130
+ """
131
+ Display the page designated by page, with the vertical coordinate top
132
+ positioned at the top edge of the window and the contents of the page
133
+ magnified just enough to fit the entire width of its bounding box
134
+ within the window.
135
+
136
+ A null value for top specifies that the current value of that parameter
137
+ is to be retained unchanged.
138
+
139
+ Args:
140
+ top:
141
+
142
+ Returns:
143
+ The created fit object.
144
+
145
+ """
146
+ return Fit(fit_type="/FitBH", fit_args=(top,))
147
+
148
+ @classmethod
149
+ def fit_box_vertically(cls, left: Optional[float] = None) -> "Fit":
150
+ """
151
+ Display the page designated by page, with the horizontal coordinate
152
+ left positioned at the left edge of the window and the contents of the
153
+ page magnified just enough to fit the entire height of its bounding box
154
+ within the window.
155
+
156
+ A null value for left specifies that the current value of that
157
+ parameter is to be retained unchanged.
158
+
159
+ Args:
160
+ left:
161
+
162
+ Returns:
163
+ The created fit object.
164
+
165
+ """
166
+ return Fit(fit_type="/FitBV", fit_args=(left,))
167
+
168
+ def __str__(self) -> str:
169
+ if not self.fit_args:
170
+ return f"Fit({self.fit_type})"
171
+ return f"Fit({self.fit_type}, {self.fit_args})"
172
+
173
+
174
+ DEFAULT_FIT = Fit.fit()
.venv/lib/python3.13/site-packages/pypdf/generic/_image_inline.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024, pypdf contributors
2
+ # All rights reserved.
3
+ #
4
+ # Redistribution and use in source and binary forms, with or without
5
+ # modification, are permitted provided that the following conditions are
6
+ # met:
7
+ #
8
+ # * Redistributions of source code must retain the above copyright notice,
9
+ # this list of conditions and the following disclaimer.
10
+ # * Redistributions in binary form must reproduce the above copyright notice,
11
+ # this list of conditions and the following disclaimer in the documentation
12
+ # and/or other materials provided with the distribution.
13
+ # * The name of the author may not be used to endorse or promote products
14
+ # derived from this software without specific prior written permission.
15
+ #
16
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26
+ # POSSIBILITY OF SUCH DAMAGE.
27
+
28
+ import logging
29
+ from io import BytesIO
30
+ from typing import IO
31
+
32
+ from .._utils import (
33
+ WHITESPACES,
34
+ WHITESPACES_AS_BYTES,
35
+ BinaryStreamType,
36
+ StreamType,
37
+ logger_warning,
38
+ read_non_whitespace,
39
+ )
40
+ from ..errors import PdfReadError
41
+
42
+ logger = logging.getLogger(__name__)
43
+
44
+ # An inline image should be used only for small images (4096 bytes or less),
45
+ # but allow twice this for cases where this has been exceeded.
46
+ BUFFER_SIZE = 8192
47
+
48
+
49
+ def _check_end_image_marker(stream: StreamType) -> bool:
50
+ ei_tok = read_non_whitespace(stream)
51
+ ei_tok += stream.read(2)
52
+ stream.seek(-3, 1)
53
+ return ei_tok[:2] == b"EI" and (ei_tok[2:3] == b"" or ei_tok[2:3] in WHITESPACES)
54
+
55
+
56
+ def extract_inline__ascii_hex_decode(stream: StreamType) -> bytes:
57
+ """
58
+ Extract HexEncoded stream from inline image.
59
+ The stream will be moved onto the EI.
60
+ """
61
+ data_out = bytearray()
62
+ # Read data until delimiter > and EI as backup.
63
+ while True:
64
+ data_buffered = read_non_whitespace(stream) + (read_bytes := stream.read(BUFFER_SIZE))
65
+ if not data_buffered or not read_bytes:
66
+ raise PdfReadError("Unexpected end of stream.")
67
+ pos_tok = data_buffered.find(b">")
68
+ if pos_tok >= 0: # found >
69
+ data_out += data_buffered[: pos_tok + 1]
70
+ stream.seek(-len(data_buffered) + pos_tok + 1, 1)
71
+ break
72
+ pos_ei = data_buffered.find(b"EI")
73
+ if pos_ei >= 0: # found EI
74
+ stream.seek(-len(data_buffered) + pos_ei - 1, 1)
75
+ c = stream.read(1)
76
+ while c in WHITESPACES:
77
+ stream.seek(-2, 1)
78
+ c = stream.read(1)
79
+ pos_ei -= 1
80
+ data_out += data_buffered[:pos_ei]
81
+ break
82
+ if len(data_buffered) == 2:
83
+ data_out += data_buffered
84
+ raise PdfReadError("Unexpected end of stream.")
85
+ # Neither > nor EI found
86
+ data_out += data_buffered[:-2]
87
+ stream.seek(-2, 1)
88
+
89
+ if not _check_end_image_marker(stream):
90
+ raise PdfReadError("EI stream not found.")
91
+ return bytes(data_out)
92
+
93
+
94
+ def extract_inline__ascii85_decode(stream: StreamType) -> bytes:
95
+ """
96
+ Extract A85 stream from inline image.
97
+ The stream will be moved onto the EI.
98
+ """
99
+ data_out = bytearray()
100
+ # Read data until delimiter ~>
101
+ while True:
102
+ data_buffered = read_non_whitespace(stream) + (read_bytes := stream.read(BUFFER_SIZE))
103
+ if not data_buffered or not read_bytes:
104
+ raise PdfReadError("Unexpected end of stream.")
105
+ pos_tok = data_buffered.find(b"~>")
106
+ if pos_tok >= 0: # found!
107
+ data_out += data_buffered[: pos_tok + 2]
108
+ stream.seek(-len(data_buffered) + pos_tok + 2, 1)
109
+ break
110
+ if len(data_buffered) == 2: # end of buffer
111
+ data_out += data_buffered
112
+ raise PdfReadError("Unexpected end of stream.")
113
+ data_out += data_buffered[
114
+ :-2
115
+ ] # back by one char in case of in the middle of ~>
116
+ stream.seek(-2, 1)
117
+
118
+ if not _check_end_image_marker(stream):
119
+ raise PdfReadError("EI stream not found.")
120
+ return bytes(data_out)
121
+
122
+
123
+ def extract_inline__run_length_decode(stream: StreamType) -> bytes:
124
+ """
125
+ Extract RL (RunLengthDecode) stream from inline image.
126
+ The stream will be moved onto the EI.
127
+ """
128
+ data_out = bytearray()
129
+ # Read data until delimiter 128
130
+ while True:
131
+ data_buffered = stream.read(BUFFER_SIZE)
132
+ if not data_buffered:
133
+ raise PdfReadError("Unexpected end of stream.")
134
+ pos_tok = data_buffered.find(b"\x80")
135
+ if pos_tok >= 0: # found
136
+ # Ideally, we could just use plain run-length decoding here, where 80_16 = 128_10
137
+ # marks the EOD. But there apparently are cases like in issue #3517, where we have
138
+ # an inline image with up to 51 EOD markers. In these cases, be resilient here and
139
+ # use the default `EI` marker detection instead. Please note that this fallback
140
+ # still omits special `EI` handling within the stream, but for now assume that having
141
+ # both of these cases occur at the same time is very unlikely (and the image stream
142
+ # is broken anyway).
143
+ # For now, do not skip over more than one whitespace character.
144
+ after_token = data_buffered[pos_tok + 1 : pos_tok + 4]
145
+ if after_token.startswith(b"EI") or after_token.endswith(b"EI"):
146
+ data_out += data_buffered[: pos_tok + 1]
147
+ stream.seek(-len(data_buffered) + pos_tok + 1, 1)
148
+ else:
149
+ logger_warning("Early EOD in RunLengthDecode of inline image, using fallback.", source=__name__)
150
+ ei_marker = data_buffered.find(b"EI")
151
+ if ei_marker > 0:
152
+ data_out += data_buffered[: ei_marker]
153
+ stream.seek(-len(data_buffered) + ei_marker - 1, 1)
154
+ break
155
+ data_out += data_buffered
156
+
157
+ if not _check_end_image_marker(stream):
158
+ raise PdfReadError("EI stream not found.")
159
+ return bytes(data_out)
160
+
161
+
162
+ def extract_inline__dct_decode(stream: BinaryStreamType) -> bytes:
163
+ """
164
+ Extract DCT (JPEG) stream from inline image.
165
+ The stream will be moved onto the EI.
166
+ """
167
+ def read(length: int) -> bytes:
168
+ # If 0 bytes are returned, and *size* was not 0, this indicates end of file.
169
+ # If the object is in non-blocking mode and no bytes are available, `None` is returned.
170
+ _result = stream.read(length)
171
+ if _result is None or len(_result) != length:
172
+ raise PdfReadError("Unexpected end of stream.")
173
+ return _result
174
+
175
+ data_out = bytearray()
176
+ # Read Blocks of data (ID/Size/data) up to ID=FF/D9
177
+ # https://www.digicamsoft.com/itu/itu-t81-36.html
178
+ not_first = False
179
+ while True:
180
+ c = read(1)
181
+ if not_first or (c == b"\xff"):
182
+ data_out += c
183
+ if c != b"\xff":
184
+ continue
185
+ not_first = True
186
+ c = read(1)
187
+ data_out += c
188
+ if c == b"\xff":
189
+ stream.seek(-1, 1) # pragma: no cover
190
+ elif c == b"\x00": # stuffing
191
+ pass
192
+ elif c == b"\xd9": # end
193
+ break
194
+ elif c in (
195
+ b"\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc9\xca\xcb\xcc\xcd\xce\xcf"
196
+ b"\xda\xdb\xdc\xdd\xde\xdf"
197
+ b"\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xfe"
198
+ ):
199
+ c = read(2)
200
+ data_out += c
201
+ sz = c[0] * 256 + c[1]
202
+ data_out += read(sz - 2)
203
+
204
+ if not _check_end_image_marker(stream):
205
+ raise PdfReadError("EI stream not found.")
206
+ return bytes(data_out)
207
+
208
+
209
+ def extract_inline_default(stream: StreamType) -> bytes:
210
+ """Legacy method, used by default"""
211
+ stream_out = BytesIO()
212
+ # Read the inline image, while checking for EI (End Image) operator.
213
+ while True:
214
+ data_buffered = stream.read(BUFFER_SIZE)
215
+ if not data_buffered:
216
+ raise PdfReadError("Unexpected end of stream.")
217
+ pos_ei = data_buffered.find(
218
+ b"E"
219
+ ) # We can not look straight for "EI" because it may not have been loaded in the buffer
220
+
221
+ if pos_ei == -1:
222
+ stream_out.write(data_buffered)
223
+ else:
224
+ # Write out everything including E (the one from EI to be removed)
225
+ stream_out.write(data_buffered[0 : pos_ei + 1])
226
+ sav_pos_ei = stream_out.tell() - 1
227
+ # Seek back in the stream to read the E next
228
+ stream.seek(pos_ei + 1 - len(data_buffered), 1)
229
+ saved_pos = stream.tell()
230
+ # Check for End Image
231
+ tok2 = stream.read(1) # I of "EI"
232
+ if tok2 != b"I":
233
+ stream.seek(saved_pos, 0)
234
+ continue
235
+ tok3 = stream.read(1) # possible space after "EI"
236
+ if tok3 == b"":
237
+ # The `EI` marker is at the very end of the stream. There can be
238
+ # no trailing binary data, so this is unambiguously the end of the
239
+ # inline image (#3468).
240
+ stream.seek(saved_pos - 1, 0)
241
+ stream_out.truncate(sav_pos_ei)
242
+ break
243
+ if tok3 not in WHITESPACES:
244
+ stream.seek(saved_pos, 0)
245
+ continue
246
+ while tok3 in WHITESPACES:
247
+ tok3 = stream.read(1)
248
+ if data_buffered[pos_ei - 1 : pos_ei] not in WHITESPACES and tok3 not in {
249
+ b"Q",
250
+ b"E",
251
+ }: # for Q or EMC
252
+ stream.seek(saved_pos, 0)
253
+ continue
254
+ if is_followed_by_binary_data(stream):
255
+ # Inline image contains `EI ` sequence usually marking the end of it, but
256
+ # is followed by binary data which does not make sense for the actual end.
257
+ stream.seek(saved_pos, 0)
258
+ continue
259
+ # Data contains [\s]EI[\s](Q|EMC): 4 chars are sufficient
260
+ # remove E(I) wrongly inserted earlier
261
+ stream.seek(saved_pos - 1, 0)
262
+ stream_out.truncate(sav_pos_ei)
263
+ break
264
+
265
+ return stream_out.getvalue()
266
+
267
+
268
+ def is_followed_by_binary_data(stream: IO[bytes], length: int = 10) -> bool:
269
+ """
270
+ Check if the next bytes of the stream look like binary image data or regular page content.
271
+
272
+ This is just some heuristics due to the PDF specification being too imprecise about
273
+ inline images containing the `EI` marker which would end an image. Starting with PDF 2.0,
274
+ we finally get a mandatory length field, but with (proper) PDF 2.0 support being very limited
275
+ everywhere, we should not expect to be able to remove such hacks in the near future - especially
276
+ considering legacy documents as well.
277
+
278
+ The actual implementation draws some inspiration from
279
+ https://github.com/itext/itext-java/blob/9.1.0/kernel/src/main/java/com/itextpdf/kernel/pdf/canvas/parser/util/InlineImageParsingUtils.java
280
+ """
281
+ position = stream.tell()
282
+ data = stream.read(length)
283
+ stream.seek(position)
284
+ if not data:
285
+ return False
286
+ operator_start = None
287
+ operator_end = None
288
+
289
+ for index, byte in enumerate(data):
290
+ if byte < 32 and byte not in WHITESPACES_AS_BYTES:
291
+ # This covers all characters not being displayable directly, although omitting whitespace
292
+ # to allow for operator detection.
293
+ return True
294
+ is_whitespace = byte in WHITESPACES_AS_BYTES
295
+ if operator_start is None and not is_whitespace:
296
+ # Interpret all other non-whitespace characters as the start of an operation.
297
+ operator_start = index
298
+ if operator_start is not None and is_whitespace:
299
+ # A whitespace stops an operation.
300
+ # Assume that having an inline image with tons of whitespace is rather unlikely.
301
+ operator_end = index
302
+ break
303
+
304
+ if operator_start is None:
305
+ # Inline images should not have tons of whitespaces, which would lead to no operator start.
306
+ return False
307
+ if operator_end is None:
308
+ # We probably are inside an operation.
309
+ operator_end = length
310
+ operator_length = operator_end - operator_start
311
+ operator = data[operator_start:operator_end]
312
+ if operator.startswith(b"/") and operator_length > 1:
313
+ # Name object.
314
+ return False
315
+ if operator.replace(b".", b"").isdigit():
316
+ # Graphics operator, for example a move. A number (integer or float).
317
+ return False
318
+ if operator_length > 3: # noqa: SIM103
319
+ # Usually, the operators inside a content stream should not have more than three characters,
320
+ # especially after an inline image.
321
+ return True
322
+ return False
.venv/lib/python3.13/site-packages/pypdf/generic/_image_xobject.py ADDED
@@ -0,0 +1,698 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions to convert an image XObject to an image"""
2
+
3
+ import sys
4
+ from io import BytesIO
5
+ from typing import Any, Literal, Optional, Union, cast
6
+
7
+ from .._utils import check_if_whitespace_only, logger_warning
8
+ from ..constants import ColorSpaces, ImageAttributes, StreamAttributes
9
+ from ..constants import FilterTypes as FT
10
+ from ..errors import EmptyImageDataError, LimitReachedError, PdfReadError
11
+ from ..generic import (
12
+ ArrayObject,
13
+ DecodedStreamObject,
14
+ EncodedStreamObject,
15
+ NullObject,
16
+ TextStringObject,
17
+ is_null_or_none,
18
+ )
19
+
20
+ if sys.version_info[:2] >= (3, 10):
21
+ from typing import TypeAlias
22
+ else:
23
+ from typing_extensions import TypeAlias
24
+
25
+
26
+ try:
27
+ from PIL import Image, UnidentifiedImageError
28
+ except ImportError:
29
+ raise ImportError(
30
+ "pillow is required to do image extraction. "
31
+ "It can be installed via 'pip install pypdf[image]'"
32
+ )
33
+
34
+ mode_str_type: TypeAlias = Literal[
35
+ "", "1", "RGB", "2bits", "4bits", "P", "L", "RGBA", "CMYK"
36
+ ]
37
+
38
+ MAX_IMAGE_MODE_NESTING_DEPTH: int = 10
39
+
40
+
41
+ def _get_image_mode(
42
+ color_space: Union[str, list[Any], Any],
43
+ color_components: int,
44
+ prev_mode: mode_str_type,
45
+ depth: int = 0,
46
+ ) -> tuple[mode_str_type, bool]:
47
+ """
48
+ Returns:
49
+ Image mode, not taking into account mask (transparency).
50
+ ColorInversion is required (like for some DeviceCMYK).
51
+
52
+ """
53
+ if depth > MAX_IMAGE_MODE_NESTING_DEPTH:
54
+ raise PdfReadError(
55
+ "Color spaces nested too deeply. If required, consider increasing MAX_IMAGE_MODE_NESTING_DEPTH."
56
+ )
57
+ if is_null_or_none(color_space):
58
+ return "", False
59
+ color_space_str: str = ""
60
+ if isinstance(color_space, str):
61
+ color_space_str = color_space
62
+ elif not isinstance(color_space, list):
63
+ raise PdfReadError(
64
+ "Cannot interpret color space", color_space
65
+ ) # pragma: no cover
66
+ elif not color_space:
67
+ return "", False
68
+ elif color_space[0].startswith("/Cal"): # /CalRGB or /CalGray
69
+ color_space_str = "/Device" + color_space[0][4:]
70
+ elif color_space[0] == "/ICCBased":
71
+ icc_profile = color_space[1].get_object()
72
+ color_components = cast(int, icc_profile["/N"])
73
+ color_space_str = icc_profile.get("/Alternate", "")
74
+ elif color_space[0] == "/Indexed":
75
+ color_space_str = color_space[1].get_object()
76
+ mode, invert_color = _get_image_mode(
77
+ color_space_str, color_components, prev_mode, depth + 1
78
+ )
79
+ if mode in ("RGB", "CMYK"):
80
+ mode = "P"
81
+ return mode, invert_color
82
+ elif color_space[0] == "/Separation":
83
+ color_space_str = color_space[2].get_object()
84
+ mode, invert_color = _get_image_mode(
85
+ color_space_str, color_components, prev_mode, depth + 1
86
+ )
87
+ return mode, True
88
+ elif color_space[0] == "/DeviceN":
89
+ original_color_space = color_space
90
+ color_components = len(color_space[1])
91
+ color_space_str = color_space[2].get_object()
92
+ if color_space_str == "/DeviceCMYK" and color_components == 1:
93
+ if original_color_space[1][0] != "/Black":
94
+ logger_warning(
95
+ "Color %(color)s converted to Gray. Please share PDF with pypdf dev team",
96
+ source=__name__,
97
+ color=original_color_space[1][0],
98
+ )
99
+ return "L", True
100
+ mode, invert_color = _get_image_mode(
101
+ color_space_str, color_components, prev_mode, depth + 1
102
+ )
103
+ return mode, invert_color
104
+
105
+ mode_map: dict[str, mode_str_type] = {
106
+ "1bit": "1", # must be zeroth position: color_components may index the values
107
+ "/DeviceGray": "L", # must be first position: color_components may index the values
108
+ "palette": "P", # must be second position: color_components may index the values
109
+ "/DeviceRGB": "RGB", # must be third position: color_components may index the values
110
+ "/DeviceCMYK": "CMYK", # must be fourth position: color_components may index the values
111
+ "2bit": "2bits",
112
+ "4bit": "4bits",
113
+ }
114
+
115
+ mode_values = list(mode_map.values())
116
+ mode = (
117
+ mode_map.get(color_space_str)
118
+ or (
119
+ mode_values[color_components]
120
+ if 0 <= color_components < len(mode_values)
121
+ else None
122
+ )
123
+ or prev_mode
124
+ )
125
+
126
+ return mode, mode == "CMYK"
127
+
128
+
129
+ def bits2byte(
130
+ data: bytes,
131
+ size: tuple[int, int],
132
+ bits: int,
133
+ colors: int = 1,
134
+ scale: bool = False,
135
+ ) -> bytes:
136
+ from pypdf.filters import FLATE_MAX_BUFFER_SIZE # noqa: PLC0415
137
+
138
+ # Number of samples per row = pixels per row * components per pixel.
139
+ samples_per_row = size[0] * colors
140
+ buffer_size = samples_per_row * size[1]
141
+ if buffer_size > FLATE_MAX_BUFFER_SIZE:
142
+ raise LimitReachedError(f"Requested buffer size {buffer_size} exceeds limit of {FLATE_MAX_BUFFER_SIZE}.")
143
+
144
+ byte_buffer = bytearray(buffer_size)
145
+ mask = (1 << bits) - 1
146
+ # Scale a b-bit sample up to the full 0-255 range (e.g. 4-bit 15 -> 255)
147
+ # when the output is consumed directly as color (RGB) rather than as a
148
+ # palette index.
149
+ factor = 255 // mask if scale and mask else 1
150
+
151
+ required = size[1] * ((samples_per_row * bits + 7) // 8)
152
+ if (length := len(data)) < required:
153
+ logger_warning("Image data is not rectangular. Adding padding.", source=__name__)
154
+ data += b"\x00" * (required - length)
155
+
156
+ data_index = 0
157
+ bit = 8 - bits
158
+ for y in range(size[1]):
159
+ if bit != 8 - bits:
160
+ data_index += 1
161
+ bit = 8 - bits
162
+ for x in range(samples_per_row):
163
+ byte_buffer[x + y * samples_per_row] = (
164
+ ((data[data_index] >> bit) & mask) * factor
165
+ )
166
+ bit -= bits
167
+ if bit < 0:
168
+ data_index += 1
169
+ bit = 8 - bits
170
+ return bytes(byte_buffer)
171
+
172
+
173
+ def _expand_low_bit_samples(
174
+ mode: mode_str_type,
175
+ size: tuple[int, int],
176
+ data: bytes,
177
+ color_space: Union[str, ArrayObject],
178
+ ) -> tuple[mode_str_type, bytes]:
179
+ """
180
+ Expand 2- or 4-bit-per-component samples to one byte per component.
181
+
182
+ Pillow has no mode for sub-byte samples, so the packed data has to be
183
+ unpacked before an image can be built from it. For a single-component
184
+ color space the samples are palette/grayscale indices ("P"). For a
185
+ multi-component space such as /DeviceRGB they are interleaved color
186
+ components, so they are also scaled to the full 0-255 range and become
187
+ an "RGB" image.
188
+
189
+ Returns the resulting mode and data, unchanged when the mode is not a
190
+ low-bit one.
191
+ """
192
+ if mode not in ("2bits", "4bits"):
193
+ return mode, data
194
+ bits = int(mode[0])
195
+ if color_space == "/DeviceRGB":
196
+ return "RGB", bits2byte(data, size, bits, colors=3, scale=True)
197
+ return "P", bits2byte(data, size, bits)
198
+
199
+
200
+ def _image_from_bytes(
201
+ mode: str, size: tuple[int, int], data: bytes
202
+ ) -> Image.Image:
203
+ pixel_count = size[0] * size[1]
204
+ bytes_per_pixel = len(mode)
205
+ required_byte_count = pixel_count * bytes_per_pixel
206
+
207
+ from pypdf.filters import FLATE_MAX_BUFFER_SIZE # noqa: PLC0415
208
+ if required_byte_count > FLATE_MAX_BUFFER_SIZE:
209
+ raise LimitReachedError(
210
+ f"Requested image buffer size {required_byte_count} exceeds limit {FLATE_MAX_BUFFER_SIZE}."
211
+ )
212
+
213
+ try:
214
+ img = Image.frombytes(mode, size, data)
215
+ except ValueError as exc:
216
+ data_length = len(data)
217
+ if data_length == 0:
218
+ raise EmptyImageDataError(
219
+ "Data is 0 bytes, cannot process an image from empty data."
220
+ ) from exc
221
+ if data_length % pixel_count != 0:
222
+ raise
223
+ k = required_byte_count / data_length
224
+ data = b"".join(bytes((x,) * int(k)) for x in data)
225
+ img = Image.frombytes(mode, size, data)
226
+ return img
227
+
228
+
229
+ def __handle_flate__indexed(color_space: ArrayObject) -> tuple[Any, Any, Any, Any]:
230
+ count = len(color_space)
231
+ if count == 4:
232
+ color_space, base, hival, lookup = (value.get_object() for value in color_space)
233
+ return color_space, base, hival, lookup
234
+
235
+ # Deal with strange AutoDesk files where `base` and `hival` look like this:
236
+ # /DeviceRGB\x00255
237
+ element1 = color_space[1]
238
+ element1 = element1 if isinstance(element1, str) else element1.get_object()
239
+ if count == 3 and "\x00" in element1:
240
+ color_space, lookup = color_space[0].get_object(), color_space[2].get_object()
241
+ base, hival = element1.split("\x00")
242
+ hival = int(hival)
243
+ return color_space, base, hival, lookup
244
+ raise PdfReadError(f"Expected color space with 4 values, got {count}: {color_space}")
245
+
246
+
247
+ def _handle_flate(
248
+ size: tuple[int, int],
249
+ data: bytes,
250
+ mode: mode_str_type,
251
+ color_space: Union[str, ArrayObject],
252
+ colors: int,
253
+ obj_as_text: str,
254
+ ) -> tuple[Image.Image, str, str, bool]:
255
+ """
256
+ Process image encoded using the zlib/deflate compression method, corresponds to the FlateDecode filter
257
+ Returns img, image_format, extension, color inversion
258
+ """
259
+ base: Any
260
+ hival: Any
261
+ lookup: Any
262
+ if isinstance(color_space, ArrayObject) and color_space[0] == "/Indexed":
263
+ color_space, base, hival, lookup = __handle_flate__indexed(color_space)
264
+ mode, data = _expand_low_bit_samples(mode, size, data, color_space)
265
+ img = _image_from_bytes(mode, size, data)
266
+ if color_space == "/Indexed":
267
+ if isinstance(lookup, (EncodedStreamObject, DecodedStreamObject)):
268
+ lookup = lookup.get_data()
269
+ if isinstance(lookup, TextStringObject):
270
+ lookup = lookup.original_bytes
271
+ if isinstance(lookup, str):
272
+ lookup = lookup.encode()
273
+ try:
274
+ nb, conv, mode = { # type: ignore[assignment]
275
+ "1": (0, "", ""),
276
+ "L": (1, "P", "L"),
277
+ "P": (0, "", ""),
278
+ "RGB": (3, "P", "RGB"),
279
+ "CMYK": (4, "P", "CMYK"),
280
+ }[_get_image_mode(base, 0, "")[0]]
281
+ except KeyError: # pragma: no cover
282
+ logger_warning(
283
+ "Base %(base)s not coded. Please share PDF with pypdf dev team",
284
+ source=__name__,
285
+ base=base,
286
+ )
287
+ lookup = None
288
+ else:
289
+ if img.mode == "1" and nb == 0:
290
+ # A two-color lookup needs at least one byte per color, but the
291
+ # base color space resolves to a 1-bit or palette image.
292
+ logger_warning(
293
+ "Cannot apply lookup for base %(base)s to image with mode 1. "
294
+ "Please share PDF with pypdf dev team",
295
+ source=__name__,
296
+ base=base,
297
+ )
298
+ elif img.mode == "1":
299
+ # Two values ("high" and "low").
300
+ expected_count = 2 * nb
301
+ actual_count = len(lookup)
302
+ if actual_count != expected_count:
303
+ if actual_count < expected_count:
304
+ logger_warning(
305
+ "Not enough lookup values: Expected %(expected_count)d, got %(actual_count)d.",
306
+ source=__name__,
307
+ expected_count=expected_count,
308
+ actual_count=actual_count,
309
+ )
310
+ lookup += bytes([0] * (expected_count - actual_count))
311
+ elif not check_if_whitespace_only(lookup[expected_count:]):
312
+ logger_warning(
313
+ "Too many lookup values: Expected %(expected_count)d, got %(actual_count)d.",
314
+ source=__name__,
315
+ expected_count=expected_count,
316
+ actual_count=actual_count,
317
+ )
318
+ lookup = lookup[:expected_count]
319
+ colors_arr = [lookup[:nb], lookup[nb:]]
320
+ source = img.convert("L")
321
+ bands = [
322
+ source.point(
323
+ [low_value] * 128 + [high_value] * 128
324
+ )
325
+ for low_value, high_value in zip(colors_arr[0], colors_arr[1])
326
+ ]
327
+ img = bands[0] if nb == 1 else Image.merge(mode, bands)
328
+ else:
329
+ img = img.convert(conv)
330
+ if len(lookup) != (hival + 1) * nb:
331
+ logger_warning("Invalid Lookup Table in %(obj_as_text)s", source=__name__, obj_as_text=obj_as_text)
332
+ lookup = None
333
+ elif mode == "L":
334
+ # gray lookup does not work: it is converted to a similar RGB lookup
335
+ lookup = b"".join([bytes([b, b, b]) for b in lookup])
336
+ mode = "RGB"
337
+ # TODO: https://github.com/py-pdf/pypdf/pull/2039
338
+ # this is a work around until PIL is able to process CMYK images
339
+ elif mode == "CMYK":
340
+ _rgb = []
341
+ for _c, _m, _y, _k in (
342
+ lookup[n : n + 4] for n in range(0, 4 * (len(lookup) // 4), 4)
343
+ ):
344
+ _r = int(255 * (1 - _c / 255) * (1 - _k / 255))
345
+ _g = int(255 * (1 - _m / 255) * (1 - _k / 255))
346
+ _b = int(255 * (1 - _y / 255) * (1 - _k / 255))
347
+ _rgb.append(bytes((_r, _g, _b)))
348
+ lookup = b"".join(_rgb)
349
+ mode = "RGB"
350
+ if lookup is not None:
351
+ img.putpalette(lookup, rawmode=mode)
352
+ img = img.convert("L" if base == ColorSpaces.DEVICE_GRAY else "RGB")
353
+ elif not is_null_or_none(color_space) and color_space[0] == "/ICCBased":
354
+ # Exclude pure black-and-white images.
355
+ # TODO: The remaining code still does not look correct. Shouldn't the proper way be
356
+ # to use the original image and apply the ICC transformation on it?
357
+ # For now, this just loads the original image with a different color space.
358
+ if mode != "1":
359
+ # Table 65 - Additional Entries Specific to an ICC Profile Stream Dictionary
360
+ mode2 = _get_image_mode(color_space, colors, mode)[0]
361
+ if mode != mode2:
362
+ img = Image.frombytes(mode, size, data) # reloaded as mode may have changed
363
+ if mode == "CMYK":
364
+ image_format = "TIFF"
365
+ extension = ".tif"
366
+ else:
367
+ image_format = "PNG"
368
+ extension = ".png" # mime_type: "image/png"
369
+ return img, image_format, extension, False
370
+
371
+
372
+ def _handle_jpx(
373
+ size: tuple[int, int],
374
+ data: bytes,
375
+ mode: mode_str_type,
376
+ color_space: str,
377
+ colors: int,
378
+ ) -> tuple[Image.Image, str, str, bool]:
379
+ """
380
+ Process image encoded as JPX/JPEG2000
381
+ Returns img, image_format, extension, inversion
382
+ """
383
+ img1: Image.Image = Image.open(BytesIO(data), formats=("JPEG2000",))
384
+ mode, invert_color = _get_image_mode(color_space, colors, mode)
385
+ if mode == "":
386
+ mode = cast(mode_str_type, img1.mode)
387
+ invert_color = mode == "CMYK"
388
+ if img1.mode == "RGBA" and mode == "RGB":
389
+ mode = "RGBA"
390
+ # we need to convert to the good mode
391
+ if img1.mode == mode or {img1.mode, mode} == {"L", "P"}: # compare (unordered) sets
392
+ # L and P are indexed modes which should not be changed.
393
+ img = img1
394
+ elif {img1.mode, mode} == {"RGBA", "CMYK"}:
395
+ # RGBA / CMYK are 4bytes encoding where
396
+ # the encoding should be corrected
397
+ img = Image.frombytes(mode, img1.size, img1.tobytes())
398
+ else: # pragma: no cover
399
+ img = img1.convert(mode)
400
+ # CMYK conversion
401
+ # https://stackverflow.com/questions/38855022/
402
+ if img.mode == "CMYK" and color_space == "/ICCBased":
403
+ img = img.convert("RGB")
404
+ return img, "JPEG2000", ".jp2", invert_color
405
+
406
+
407
+ def _apply_decode(
408
+ img: Image.Image,
409
+ x_object: dict[str, Any],
410
+ lfilters: FT,
411
+ color_space: Union[str, list[Any], Any],
412
+ invert_color: bool,
413
+ ) -> Image.Image:
414
+ # CMYK image and other color spaces without decode
415
+ # requires reverting scale (cf p243,2§ last sentence)
416
+ if ImageAttributes.DECODE in x_object:
417
+ decode = x_object[ImageAttributes.DECODE]
418
+ # if invert_color and lfilters == FT.DCT_DECODE:
419
+ # decode = list(reversed(decode))
420
+ elif img.mode == "CMYK" and lfilters == FT.JPX_DECODE:
421
+ decode = [1.0, 0.0] if not invert_color else [0.0, 1.0]
422
+ decode = decode * len(img.getbands())
423
+ elif (img.mode == "CMYK" and lfilters == FT.DCT_DECODE) or (invert_color and img.mode == "L"):
424
+ decode = [1.0, 0.0] * len(img.getbands())
425
+ else:
426
+ decode = None
427
+
428
+ if (
429
+ isinstance(color_space, ArrayObject)
430
+ and color_space[0].get_object() == "/Indexed"
431
+ ):
432
+ decode = None # decode is meaningless if Indexed
433
+ if (
434
+ isinstance(color_space, ArrayObject)
435
+ and color_space[0].get_object() == "/Separation"
436
+ ):
437
+ decode = [1.0, 0.0] * len(img.getbands())
438
+ if decode is not None and (
439
+ not isinstance(decode, list) or len(decode) % 2 != 0
440
+ ):
441
+ # /Decode is read straight from the image dictionary and must hold an
442
+ # even number of values (a [min max] pair per component). A malformed
443
+ # array would otherwise read past its end at decode[i + 1]; drop it and
444
+ # render the image without the remap.
445
+ logger_warning(
446
+ "Ignoring malformed /Decode array %(decode)s; expected an even number of values.",
447
+ source=__name__,
448
+ decode=decode,
449
+ )
450
+ decode = None
451
+ if decode is not None and not all(decode[i] == i % 2 for i in range(len(decode))):
452
+ lut: list[int] = []
453
+ for i in range(0, len(decode), 2):
454
+ dmin = decode[i]
455
+ dmax = decode[i + 1]
456
+ lut.extend(
457
+ round(255.0 * (j / 255.0 * (dmax - dmin) + dmin)) for j in range(256)
458
+ )
459
+ img = img.point(lut)
460
+ return img
461
+
462
+
463
+ def _get_mode_and_invert_color(
464
+ x_object: dict[str, Any], colors: int, color_space: Union[str, list[Any], Any]
465
+ ) -> tuple[mode_str_type, bool]:
466
+ if (
467
+ ImageAttributes.COLOR_SPACE in x_object
468
+ and x_object[ImageAttributes.COLOR_SPACE] == ColorSpaces.DEVICE_RGB
469
+ ):
470
+ # https://pillow.readthedocs.io/en/stable/handbook/concepts.html#modes
471
+ mode: mode_str_type = "RGB"
472
+ if x_object.get("/BitsPerComponent", 8) < 8:
473
+ mode, invert_color = _get_image_mode(
474
+ f"{x_object.get('/BitsPerComponent', 8)}bit", 0, ""
475
+ )
476
+ else:
477
+ mode, invert_color = _get_image_mode(
478
+ color_space,
479
+ 2
480
+ if (
481
+ colors == 1
482
+ and (
483
+ not is_null_or_none(color_space)
484
+ and "Gray" not in color_space
485
+ )
486
+ )
487
+ else colors,
488
+ "",
489
+ )
490
+ return mode, invert_color
491
+
492
+
493
+ def _xobj_to_image(
494
+ x_object: dict[str, Any],
495
+ pillow_parameters: Union[dict[str, Any], None] = None,
496
+ visited: Optional[set[int]] = None,
497
+ ) -> tuple[Optional[str], bytes, Any]:
498
+ """
499
+ Users need to have the pillow package installed.
500
+
501
+ It's unclear if pypdf will keep this function here, hence it's private.
502
+ It might get removed at any point.
503
+
504
+ Args:
505
+ x_object:
506
+ pillow_parameters: parameters provided to Pillow Image.save() method,
507
+ cf. <https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.save>
508
+ visited: Set of id() values of XObjects already being converted higher
509
+ up the /SMask chain, used to detect cyclic soft masks.
510
+
511
+ Returns:
512
+ Tuple[file extension, bytes, PIL.Image.Image]
513
+
514
+ """
515
+ if visited is None:
516
+ visited = set()
517
+ visited.add(id(x_object))
518
+
519
+ def _apply_alpha(
520
+ img: Image.Image,
521
+ x_object: dict[str, Any],
522
+ obj_as_text: str,
523
+ image_format: str,
524
+ extension: str,
525
+ ) -> tuple[Image.Image, str, str]:
526
+ if ImageAttributes.S_MASK in x_object: # add alpha channel
527
+ s_mask = x_object[ImageAttributes.S_MASK]
528
+ if id(s_mask) in visited:
529
+ # A soft mask that refers back to an image already being
530
+ # converted would recurse until the interpreter runs out of
531
+ # stack. Such a chain cannot describe a real alpha channel, so
532
+ # drop the mask and keep the image we have.
533
+ logger_warning(
534
+ "Ignoring cyclic /SMask reference in %(obj_as_text)s",
535
+ source=__name__,
536
+ obj_as_text=obj_as_text,
537
+ )
538
+ return img, extension, image_format
539
+ alpha = _xobj_to_image(s_mask, visited=visited)[2]
540
+ if img.size != alpha.size:
541
+ logger_warning(
542
+ "image and mask size not matching: %(obj_as_text)s",
543
+ source=__name__,
544
+ obj_as_text=obj_as_text,
545
+ )
546
+ else:
547
+ # TODO: implement mask
548
+ if alpha.mode != "L":
549
+ alpha = alpha.convert("L")
550
+ if img.mode == "P":
551
+ img = img.convert("RGB")
552
+ elif img.mode == "1":
553
+ img = img.convert("L")
554
+ img.putalpha(alpha)
555
+ if "JPEG" in image_format:
556
+ image_format = "JPEG2000"
557
+ extension = ".jp2"
558
+ else:
559
+ image_format = "PNG"
560
+ extension = ".png"
561
+ return img, extension, image_format
562
+
563
+ # For error reporting
564
+ obj_as_text = (
565
+ x_object.indirect_reference.__repr__()
566
+ if x_object is None # pragma: no cover
567
+ else x_object.__repr__()
568
+ )
569
+
570
+ # Get size and data
571
+ size = (cast(int, x_object[ImageAttributes.WIDTH]), cast(int, x_object[ImageAttributes.HEIGHT]))
572
+ data = x_object.get_data() # type: ignore[attr-defined]
573
+ if isinstance(data, str): # pragma: no cover
574
+ data = data.encode()
575
+ if len(data) % (size[0] * size[1]) == 1 and data[-1] == 0x0A: # i.e. '\n'
576
+ data = data[:-1]
577
+
578
+ # Get color properties
579
+ colors = x_object.get("/Colors", 1)
580
+ color_space: Any = x_object.get("/ColorSpace", NullObject()).get_object()
581
+ if isinstance(color_space, list) and len(color_space) == 1:
582
+ color_space = color_space[0].get_object()
583
+
584
+ mode, invert_color = _get_mode_and_invert_color(x_object, colors, color_space)
585
+
586
+ # Get filters
587
+ filters = x_object.get(StreamAttributes.FILTER, NullObject()).get_object()
588
+ lfilters = filters[-1] if isinstance(filters, list) else filters
589
+ decode_parms = x_object.get(StreamAttributes.DECODE_PARMS)
590
+ if decode_parms and isinstance(decode_parms, (tuple, list)):
591
+ decode_parms = decode_parms[0]
592
+ else:
593
+ decode_parms = {}
594
+ if not isinstance(decode_parms, dict):
595
+ decode_parms = {}
596
+
597
+ extension = None
598
+ if lfilters in (FT.FLATE_DECODE, FT.RUN_LENGTH_DECODE):
599
+ img, image_format, extension, _ = _handle_flate(
600
+ size,
601
+ data,
602
+ mode,
603
+ color_space,
604
+ colors,
605
+ obj_as_text,
606
+ )
607
+ elif lfilters in (FT.LZW_DECODE, FT.ASCII_85_DECODE):
608
+ # I'm not sure if the following logic is correct.
609
+ # There might not be any relationship between the filters and the
610
+ # extension
611
+ if lfilters == FT.LZW_DECODE:
612
+ image_format = "TIFF"
613
+ extension = ".tiff" # mime_type = "image/tiff"
614
+ else:
615
+ image_format = "PNG"
616
+ extension = ".png" # mime_type = "image/png"
617
+ try:
618
+ img = Image.open(BytesIO(data), formats=("TIFF", "PNG"))
619
+ except UnidentifiedImageError:
620
+ fallback_mode, fallback_data = _expand_low_bit_samples(
621
+ mode, size, data, color_space
622
+ )
623
+ img = _image_from_bytes(fallback_mode, size, fallback_data)
624
+ elif lfilters == FT.DCT_DECODE:
625
+ img, image_format, extension = Image.open(BytesIO(data)), "JPEG", ".jpg"
626
+ # invert_color kept unchanged
627
+ elif lfilters == FT.JPX_DECODE:
628
+ img, image_format, extension, invert_color = _handle_jpx(
629
+ size, data, mode, color_space, colors
630
+ )
631
+ elif lfilters == FT.CCITT_FAX_DECODE:
632
+ img, image_format, extension, invert_color = (
633
+ Image.open(BytesIO(data), formats=("TIFF",)),
634
+ "TIFF",
635
+ ".tiff",
636
+ False,
637
+ )
638
+ elif lfilters == FT.JBIG2_DECODE:
639
+ img, image_format, extension, invert_color = (
640
+ Image.open(BytesIO(data), formats=("PNG", "PPM")),
641
+ "PNG",
642
+ ".png",
643
+ False,
644
+ )
645
+ elif mode == "CMYK":
646
+ img, image_format, extension, invert_color = (
647
+ _image_from_bytes(mode, size, data),
648
+ "TIFF",
649
+ ".tif",
650
+ False,
651
+ )
652
+ elif mode == "":
653
+ raise PdfReadError(f"ColorSpace field not found in {x_object}")
654
+ else:
655
+ # Images without a filter (for example inline images) reach Pillow
656
+ # directly, so low-bit samples have to be expanded here as well.
657
+ mode, data = _expand_low_bit_samples(mode, size, data, color_space)
658
+ img, image_format, extension, invert_color = (
659
+ _image_from_bytes(mode, size, data),
660
+ "PNG",
661
+ ".png",
662
+ False,
663
+ )
664
+
665
+ img = _apply_decode(img, x_object, lfilters, color_space, invert_color)
666
+ img, extension, image_format = _apply_alpha(
667
+ img, x_object, obj_as_text, image_format, extension
668
+ )
669
+
670
+ if pillow_parameters is None:
671
+ pillow_parameters = {}
672
+ # Preserve JPEG image quality - see issue #3515.
673
+ if image_format == "JPEG":
674
+ # This prevents: Cannot use 'keep' when original image is not a JPEG:
675
+ # "JPEG" is the value of PIL.JpegImagePlugin.JpegImageFile.format
676
+ img.format = "JPEG"
677
+ if "quality" not in pillow_parameters:
678
+ pillow_parameters["quality"] = "keep"
679
+
680
+ # Save image to bytes
681
+ img_byte_arr = BytesIO()
682
+ try:
683
+ img.save(img_byte_arr, format=image_format, **pillow_parameters)
684
+ except OSError: # pragma: no cover # covered with pillow 10.3
685
+ # in case of we convert to RGBA and then to PNG
686
+ img1 = img.convert("RGBA")
687
+ image_format = "PNG"
688
+ extension = ".png"
689
+ img_byte_arr = BytesIO()
690
+ img1.save(img_byte_arr, format=image_format)
691
+ data = img_byte_arr.getvalue()
692
+
693
+ try: # temporary try/except until other fixes of images
694
+ img = Image.open(BytesIO(data))
695
+ except Exception as exception:
696
+ logger_warning("Failed loading image: %(exception)s", source=__name__, exception=exception)
697
+ img = None # type: ignore[assignment,unused-ignore] # TODO: Remove unused-ignore on Python 3.10
698
+ return extension, data, img
.venv/lib/python3.13/site-packages/pypdf/generic/_link.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # All rights reserved.
2
+ #
3
+ # Redistribution and use in source and binary forms, with or without
4
+ # modification, are permitted provided that the following conditions are
5
+ # met:
6
+ #
7
+ # * Redistributions of source code must retain the above copyright notice,
8
+ # this list of conditions and the following disclaimer.
9
+ # * Redistributions in binary form must reproduce the above copyright notice,
10
+ # this list of conditions and the following disclaimer in the documentation
11
+ # and/or other materials provided with the distribution.
12
+ # * The name of the author may not be used to endorse or promote products
13
+ # derived from this software without specific prior written permission.
14
+ #
15
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25
+ # POSSIBILITY OF SUCH DAMAGE.
26
+
27
+
28
+ # This module contains code used by _writer.py to track links in pages
29
+ # being added to the writer until the links can be resolved.
30
+
31
+ from typing import TYPE_CHECKING, Optional, Union, cast
32
+
33
+ from .._utils import logger_warning
34
+ from . import ArrayObject, DictionaryObject, IndirectObject, PdfObject, TextStringObject, is_null_or_none
35
+
36
+ if TYPE_CHECKING:
37
+ from .._page import PageObject
38
+ from .._reader import PdfReader
39
+ from .._writer import PdfWriter
40
+
41
+
42
+ class NamedReferenceLink:
43
+ """Named reference link being preserved until we can resolve it correctly."""
44
+
45
+ def __init__(self, reference: TextStringObject, source_pdf: "PdfReader") -> None:
46
+ """reference: TextStringObject with named reference"""
47
+ self._reference = reference
48
+ self._source_pdf = source_pdf
49
+
50
+ def find_referenced_page(self) -> Union[IndirectObject, None]:
51
+ destination = self._source_pdf.named_destinations.get(str(self._reference))
52
+ return destination.page if destination else None
53
+
54
+ def patch_reference(self, target_pdf: "PdfWriter", new_page: IndirectObject) -> None:
55
+ """target_pdf: PdfWriter which the new link went into"""
56
+ # point named destination in new PDF to the new page
57
+ if str(self._reference) not in target_pdf.named_destinations:
58
+ target_pdf.add_named_destination(str(self._reference), new_page.page_number)
59
+
60
+
61
+ class DirectReferenceLink:
62
+ """Direct reference link being preserved until we can resolve it correctly."""
63
+
64
+ def __init__(self, reference: ArrayObject) -> None:
65
+ """reference: an ArrayObject whose first element is the Page indirect object"""
66
+ self._reference = reference
67
+
68
+ def find_referenced_page(self) -> Union[IndirectObject, None]:
69
+ if not self._reference:
70
+ return None
71
+ return cast(IndirectObject, self._reference[0])
72
+
73
+ def patch_reference(self, target_pdf: "PdfWriter", new_page: IndirectObject) -> None:
74
+ """target_pdf: PdfWriter which the new link went into"""
75
+ self._reference[0] = new_page
76
+
77
+
78
+ ReferenceLink = Union[NamedReferenceLink, DirectReferenceLink]
79
+
80
+
81
+ def extract_links(new_page: "PageObject", old_page: "PageObject") -> list[tuple[ReferenceLink, ReferenceLink]]:
82
+ """Extracts links from two pages on the assumption that the two pages are
83
+ the same. Produces one list of (new link, old link) tuples.
84
+
85
+ Non-link annotations are ignored before pairing to avoid dropping valid
86
+ links when one page includes additional non-link annotation entries.
87
+ """
88
+ new_annotations = new_page.get("/Annots", ArrayObject()).get_object()
89
+ old_annotations = old_page.get("/Annots", ArrayObject()).get_object()
90
+ if is_null_or_none(new_annotations):
91
+ new_annotations = ArrayObject()
92
+ if is_null_or_none(old_annotations):
93
+ old_annotations = ArrayObject()
94
+ if not isinstance(new_annotations, ArrayObject) or not isinstance(old_annotations, ArrayObject):
95
+ logger_warning(
96
+ "Expected annotation arrays: %(old_annotations)s %(new_annotations)s. Ignoring annotations.",
97
+ source=__name__,
98
+ old_annotations=old_annotations,
99
+ new_annotations=new_annotations,
100
+ )
101
+ return []
102
+ new_links = [
103
+ link
104
+ for annotation in new_annotations
105
+ if (link := _build_link(annotation, new_page)) is not None
106
+ ]
107
+ old_links = [
108
+ link
109
+ for annotation in old_annotations
110
+ if (link := _build_link(annotation, old_page)) is not None
111
+ ]
112
+
113
+ if len(new_links) != len(old_links):
114
+ logger_warning(
115
+ "Annotation sizes differ: %(old_count)d vs. %(new_count)d",
116
+ source=__name__,
117
+ old_count=len(old_links),
118
+ new_count=len(new_links),
119
+ )
120
+
121
+ return list(zip(new_links, old_links))
122
+
123
+
124
+ def _build_link(indirect_object: IndirectObject, page: "PageObject") -> Optional[ReferenceLink]:
125
+ src = cast("PdfReader", page.pdf)
126
+ link = cast(DictionaryObject, indirect_object.get_object())
127
+ if (not isinstance(link, DictionaryObject)) or link.get("/Subtype") != "/Link":
128
+ return None
129
+
130
+ if "/A" in link:
131
+ action = cast(DictionaryObject, link["/A"])
132
+ if action.get("/S") != "/GoTo":
133
+ return None
134
+
135
+ if "/D" not in action:
136
+ return None
137
+ return _create_link(action["/D"], src)
138
+
139
+ if "/Dest" in link:
140
+ return _create_link(link["/Dest"], src)
141
+
142
+ return None # Nothing to do here
143
+
144
+
145
+ def _create_link(reference: PdfObject, source_pdf: "PdfReader") -> Optional[ReferenceLink]:
146
+ if isinstance(reference, TextStringObject):
147
+ return NamedReferenceLink(reference, source_pdf)
148
+ if isinstance(reference, ArrayObject):
149
+ return DirectReferenceLink(reference)
150
+ return None
.venv/lib/python3.13/site-packages/pypdf/generic/_outline.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union
2
+
3
+ from .._utils import StreamType, deprecation_no_replacement
4
+ from ._base import NameObject
5
+ from ._data_structures import Destination
6
+
7
+
8
+ class OutlineItem(Destination):
9
+ def write_to_stream(
10
+ self, stream: StreamType, encryption_key: Union[str, bytes, None] = None
11
+ ) -> None:
12
+ if encryption_key is not None: # deprecated
13
+ deprecation_no_replacement(
14
+ "the encryption_key parameter of write_to_stream", "5.0.0"
15
+ )
16
+ stream.write(b"<<\n")
17
+ for key in [
18
+ NameObject(x)
19
+ for x in ["/Title", "/Parent", "/First", "/Last", "/Next", "/Prev"]
20
+ if x in self
21
+ ]:
22
+ key.write_to_stream(stream)
23
+ stream.write(b" ")
24
+ value = self.raw_get(key)
25
+ value.write_to_stream(stream)
26
+ stream.write(b"\n")
27
+ key = NameObject("/Dest")
28
+ key.write_to_stream(stream)
29
+ stream.write(b" ")
30
+ value = self.dest_array
31
+ value.write_to_stream(stream)
32
+ stream.write(b"\n")
33
+ stream.write(b">>")
.venv/lib/python3.13/site-packages/pypdf/generic/_rectangle.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Union
2
+
3
+ from ._base import FloatObject, NumberObject
4
+ from ._data_structures import ArrayObject
5
+
6
+
7
+ class RectangleObject(ArrayObject):
8
+ """
9
+ This class is used to represent *page boxes* in pypdf.
10
+
11
+ These boxes include:
12
+
13
+ * :attr:`artbox <pypdf._page.PageObject.artbox>`
14
+ * :attr:`bleedbox <pypdf._page.PageObject.bleedbox>`
15
+ * :attr:`cropbox <pypdf._page.PageObject.cropbox>`
16
+ * :attr:`mediabox <pypdf._page.PageObject.mediabox>`
17
+ * :attr:`trimbox <pypdf._page.PageObject.trimbox>`
18
+ """
19
+
20
+ def __init__(
21
+ self, arr: Union["RectangleObject", tuple[float, float, float, float]]
22
+ ) -> None:
23
+ # must have four points
24
+ assert len(arr) == 4
25
+ # automatically convert arr[x] into NumberObject(arr[x]) if necessary
26
+ ArrayObject.__init__(self, [self._ensure_is_number(x) for x in arr])
27
+
28
+ def _ensure_is_number(self, value: Any) -> Union[FloatObject, NumberObject]:
29
+ if not isinstance(value, (FloatObject, NumberObject)):
30
+ return FloatObject(value)
31
+ return value
32
+
33
+ def scale(self, sx: float, sy: float) -> "RectangleObject":
34
+ return RectangleObject(
35
+ (
36
+ float(self.left) * sx,
37
+ float(self.bottom) * sy,
38
+ float(self.right) * sx,
39
+ float(self.top) * sy,
40
+ )
41
+ )
42
+
43
+ def __repr__(self) -> str:
44
+ return f"RectangleObject({list(self)!r})"
45
+
46
+ @property
47
+ def left(self) -> FloatObject:
48
+ value: FloatObject = self[0]
49
+ return value
50
+
51
+ @left.setter
52
+ def left(self, f: float) -> None:
53
+ self[0] = FloatObject(f)
54
+
55
+ @property
56
+ def bottom(self) -> FloatObject:
57
+ value: FloatObject = self[1]
58
+ return value
59
+
60
+ @bottom.setter
61
+ def bottom(self, f: float) -> None:
62
+ self[1] = FloatObject(f)
63
+
64
+ @property
65
+ def right(self) -> FloatObject:
66
+ value: FloatObject = self[2]
67
+ return value
68
+
69
+ @right.setter
70
+ def right(self, f: float) -> None:
71
+ self[2] = FloatObject(f)
72
+
73
+ @property
74
+ def top(self) -> FloatObject:
75
+ value: FloatObject = self[3]
76
+ return value
77
+
78
+ @top.setter
79
+ def top(self, f: float) -> None:
80
+ self[3] = FloatObject(f)
81
+
82
+ @property
83
+ def lower_left(self) -> tuple[float, float]:
84
+ """
85
+ Property to read and modify the lower left coordinate of this box
86
+ in (x,y) form.
87
+ """
88
+ return self.left, self.bottom
89
+
90
+ @lower_left.setter
91
+ def lower_left(self, value: tuple[float, float]) -> None:
92
+ self[0], self[1] = (self._ensure_is_number(x) for x in value)
93
+
94
+ @property
95
+ def lower_right(self) -> tuple[float, float]:
96
+ """
97
+ Property to read and modify the lower right coordinate of this box
98
+ in (x,y) form.
99
+ """
100
+ return self.right, self.bottom
101
+
102
+ @lower_right.setter
103
+ def lower_right(self, value: tuple[float, float]) -> None:
104
+ self[2], self[1] = (self._ensure_is_number(x) for x in value)
105
+
106
+ @property
107
+ def upper_left(self) -> tuple[float, float]:
108
+ """
109
+ Property to read and modify the upper left coordinate of this box
110
+ in (x,y) form.
111
+ """
112
+ return self.left, self.top
113
+
114
+ @upper_left.setter
115
+ def upper_left(self, value: tuple[float, float]) -> None:
116
+ self[0], self[3] = (self._ensure_is_number(x) for x in value)
117
+
118
+ @property
119
+ def upper_right(self) -> tuple[float, float]:
120
+ """
121
+ Property to read and modify the upper right coordinate of this box
122
+ in (x,y) form.
123
+ """
124
+ return self.right, self.top
125
+
126
+ @upper_right.setter
127
+ def upper_right(self, value: tuple[float, float]) -> None:
128
+ self[2], self[3] = (self._ensure_is_number(x) for x in value)
129
+
130
+ @property
131
+ def width(self) -> float:
132
+ return self.right - self.left
133
+
134
+ @property
135
+ def height(self) -> float:
136
+ return self.top - self.bottom
.venv/lib/python3.13/site-packages/pypdf/generic/_utils.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import codecs
2
+ from typing import Union
3
+
4
+ from .._codecs import _pdfdoc_encoding
5
+ from .._utils import StreamType, logger_warning, read_non_whitespace
6
+ from ..errors import STREAM_TRUNCATED_PREMATURELY, PdfStreamError
7
+ from ._base import ByteStringObject, TextStringObject
8
+
9
+
10
+ def hex_to_rgb(value: str) -> tuple[float, float, float]:
11
+ return tuple(int(value.lstrip("#")[i : i + 2], 16) / 255.0 for i in (0, 2, 4)) # type: ignore[return-value]
12
+
13
+
14
+ def read_hex_string_from_stream(
15
+ stream: StreamType,
16
+ forced_encoding: Union[str, list[str], dict[int, str], None] = None,
17
+ ) -> Union["TextStringObject", "ByteStringObject"]:
18
+ stream.read(1)
19
+ arr = []
20
+ x = b""
21
+ while True:
22
+ tok = read_non_whitespace(stream)
23
+ if not tok:
24
+ raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY)
25
+ if tok == b">":
26
+ break
27
+ if tok not in b"0123456789abcdefABCDEF":
28
+ raise PdfStreamError(
29
+ f"Invalid hexadecimal character {tok!r} in hex string"
30
+ )
31
+ x += tok
32
+ if len(x) == 2:
33
+ arr.append(int(x, base=16))
34
+ x = b""
35
+ if len(x) == 1:
36
+ x += b"0"
37
+ if x != b"":
38
+ arr.append(int(x, base=16))
39
+ return create_string_object(bytes(arr), forced_encoding)
40
+
41
+
42
+ __ESCAPE_DICT__ = {
43
+ b"n": ord(b"\n"),
44
+ b"r": ord(b"\r"),
45
+ b"t": ord(b"\t"),
46
+ b"b": ord(b"\b"),
47
+ b"f": ord(b"\f"),
48
+ b"(": ord(b"("),
49
+ b")": ord(b")"),
50
+ b"/": ord(b"/"),
51
+ b"\\": ord(b"\\"),
52
+ b" ": ord(b" "),
53
+ b"%": ord(b"%"),
54
+ b"<": ord(b"<"),
55
+ b">": ord(b">"),
56
+ b"[": ord(b"["),
57
+ b"]": ord(b"]"),
58
+ b"#": ord(b"#"),
59
+ b"_": ord(b"_"),
60
+ b"&": ord(b"&"),
61
+ b"$": ord(b"$"),
62
+ }
63
+ __BACKSLASH_CODE__ = 92
64
+
65
+
66
+ def read_string_from_stream(
67
+ stream: StreamType,
68
+ forced_encoding: Union[str, list[str], dict[int, str], None] = None,
69
+ ) -> Union["TextStringObject", "ByteStringObject"]:
70
+ tok = stream.read(1)
71
+ parens = 1
72
+ txt = []
73
+ while True:
74
+ tok = stream.read(1)
75
+ if not tok:
76
+ raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY)
77
+ if tok == b"(":
78
+ parens += 1
79
+ elif tok == b")":
80
+ parens -= 1
81
+ if parens == 0:
82
+ break
83
+ elif tok == b"\\":
84
+ tok = stream.read(1)
85
+ try:
86
+ txt.append(__ESCAPE_DICT__[tok])
87
+ continue
88
+ except KeyError:
89
+ if b"0" <= tok <= b"7":
90
+ # "The number ddd may consist of one, two, or three
91
+ # octal digits; high-order overflow shall be ignored.
92
+ # Three octal digits shall be used, with leading zeros
93
+ # as needed, if the next character of the string is also
94
+ # a digit." (PDF reference 7.3.4.2, p 16)
95
+ sav = stream.tell() - 1
96
+ for _ in range(2):
97
+ ntok = stream.read(1)
98
+ if b"0" <= ntok <= b"7":
99
+ tok += ntok
100
+ else:
101
+ stream.seek(-1, 1) # ntok has to be analyzed
102
+ break
103
+ i = int(tok, base=8)
104
+ if i > 255:
105
+ txt.append(__BACKSLASH_CODE__)
106
+ stream.seek(sav)
107
+ else:
108
+ txt.append(i)
109
+ continue
110
+ if tok in b"\n\r":
111
+ # This case is hit when a backslash followed by a line
112
+ # break occurs. If it's a multi-char EOL, consume the
113
+ # second character:
114
+ tok = stream.read(1)
115
+ if tok not in b"\n\r":
116
+ stream.seek(-1, 1)
117
+ # Then don't add anything to the actual string, since this
118
+ # line break was escaped:
119
+ continue
120
+ logger_warning(
121
+ "Unexpected escaped string: %(token)s",
122
+ source=__name__,
123
+ token=tok.decode("utf-8", "ignore"),
124
+ )
125
+ txt.append(__BACKSLASH_CODE__)
126
+ txt.append(ord(tok))
127
+ return create_string_object(bytes(txt), forced_encoding)
128
+
129
+
130
+ def create_string_object(
131
+ string: Union[str, bytes],
132
+ forced_encoding: Union[str, list[str], dict[int, str], None] = None,
133
+ ) -> Union[TextStringObject, ByteStringObject]:
134
+ """
135
+ Create a ByteStringObject or a TextStringObject from a string to represent the string.
136
+
137
+ Args:
138
+ string: The data being used
139
+ forced_encoding: Typically None, or an encoding string
140
+
141
+ Returns:
142
+ A ByteStringObject
143
+
144
+ Raises:
145
+ TypeError: If string is not of type str or bytes.
146
+
147
+ """
148
+ if isinstance(string, str):
149
+ return TextStringObject(string)
150
+ if isinstance(string, bytes):
151
+ if isinstance(forced_encoding, (list, dict)):
152
+ out = ""
153
+ for x in string:
154
+ try:
155
+ out += forced_encoding[x]
156
+ except Exception:
157
+ out += bytes((x,)).decode("charmap")
158
+ obj = TextStringObject(out)
159
+ obj._original_bytes = string
160
+ return obj
161
+ if isinstance(forced_encoding, str):
162
+ if forced_encoding == "bytes":
163
+ return ByteStringObject(string)
164
+ obj = TextStringObject(string.decode(forced_encoding))
165
+ obj._original_bytes = string
166
+ return obj
167
+ try:
168
+ if string.startswith((codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE)):
169
+ retval = TextStringObject(string.decode("utf-16"))
170
+ retval._original_bytes = string
171
+ retval.autodetect_utf16 = True
172
+ retval.utf16_bom = string[:2]
173
+ return retval
174
+ if string.startswith(b"\x00"):
175
+ retval = TextStringObject(string.decode("utf-16be"))
176
+ retval._original_bytes = string
177
+ retval.autodetect_utf16 = True
178
+ retval.utf16_bom = codecs.BOM_UTF16_BE
179
+ return retval
180
+ if string[1:2] == b"\x00":
181
+ retval = TextStringObject(string.decode("utf-16le"))
182
+ retval._original_bytes = string
183
+ retval.autodetect_utf16 = True
184
+ retval.utf16_bom = codecs.BOM_UTF16_LE
185
+ return retval
186
+
187
+ # This is probably a big performance hit here, but we need
188
+ # to convert string objects into the text/unicode-aware
189
+ # version if possible... and the only way to check if that's
190
+ # possible is to try.
191
+ # Some strings are strings, some are just byte arrays.
192
+ retval = TextStringObject(decode_pdfdocencoding(string))
193
+ retval._original_bytes = string
194
+ retval.autodetect_pdfdocencoding = True
195
+ return retval
196
+ except UnicodeDecodeError:
197
+ return ByteStringObject(string)
198
+ else:
199
+ raise TypeError("create_string_object should have str or unicode arg")
200
+
201
+
202
+ def decode_pdfdocencoding(byte_array: bytes) -> str:
203
+ retval = ""
204
+ for b in byte_array:
205
+ c = _pdfdoc_encoding[b]
206
+ if c == "\u0000":
207
+ raise UnicodeDecodeError(
208
+ "pdfdocencoding",
209
+ bytearray(b),
210
+ -1,
211
+ -1,
212
+ "does not exist in translation table",
213
+ )
214
+ retval += c
215
+ return retval
.venv/lib/python3.13/site-packages/pypdf/generic/_viewerpref.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, Pubpub-ZZ
2
+ #
3
+ # All rights reserved.
4
+ #
5
+ # Redistribution and use in source and binary forms, with or without
6
+ # modification, are permitted provided that the following conditions are
7
+ # met:
8
+ #
9
+ # * Redistributions of source code must retain the above copyright notice,
10
+ # this list of conditions and the following disclaimer.
11
+ # * Redistributions in binary form must reproduce the above copyright notice,
12
+ # this list of conditions and the following disclaimer in the documentation
13
+ # and/or other materials provided with the distribution.
14
+ # * The name of the author may not be used to endorse or promote products
15
+ # derived from this software without specific prior written permission.
16
+ #
17
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
+ # POSSIBILITY OF SUCH DAMAGE.
28
+
29
+ from typing import (
30
+ Any,
31
+ Optional,
32
+ cast,
33
+ )
34
+
35
+ from ._base import BooleanObject, NameObject, NumberObject, is_null_or_none
36
+ from ._data_structures import ArrayObject, DictionaryObject
37
+
38
+ f_obj = BooleanObject(False)
39
+
40
+
41
+ class ViewerPreferences(DictionaryObject):
42
+ def __init__(self, obj: Optional[DictionaryObject] = None) -> None:
43
+ super().__init__(self)
44
+ if not is_null_or_none(obj):
45
+ self.update(obj.items()) # type: ignore[union-attr]
46
+ try:
47
+ self.indirect_reference = obj.indirect_reference # type: ignore[union-attr]
48
+ except AttributeError:
49
+ pass
50
+
51
+ def _get_bool(self, key: str, default: Optional[BooleanObject]) -> Optional[BooleanObject]:
52
+ return self.get(key, default)
53
+
54
+ def _set_bool(self, key: str, v: bool) -> None:
55
+ self[NameObject(key)] = BooleanObject(v is True)
56
+
57
+ def _get_name(self, key: str, default: Optional[NameObject]) -> Optional[NameObject]:
58
+ return self.get(key, default)
59
+
60
+ def _set_name(self, key: str, lst: list[str], v: NameObject) -> None:
61
+ if v[0] != "/":
62
+ raise ValueError(f"{v} does not start with '/'")
63
+ if lst != [] and v not in lst:
64
+ raise ValueError(f"{v} is an unacceptable value")
65
+ self[NameObject(key)] = NameObject(v)
66
+
67
+ def _get_arr(self, key: str, default: Optional[list[Any]]) -> Optional[ArrayObject]:
68
+ return self.get(key, None if default is None else ArrayObject(default))
69
+
70
+ def _set_arr(self, key: str, v: Optional[ArrayObject]) -> None:
71
+ if v is None:
72
+ try:
73
+ del self[NameObject(key)]
74
+ except KeyError:
75
+ pass
76
+ return
77
+ if not isinstance(v, ArrayObject):
78
+ raise ValueError("ArrayObject is expected")
79
+ self[NameObject(key)] = v
80
+
81
+ def _get_int(self, key: str, default: Optional[NumberObject]) -> Optional[NumberObject]:
82
+ return self.get(key, default)
83
+
84
+ def _set_int(self, key: str, v: int) -> None:
85
+ self[NameObject(key)] = NumberObject(v)
86
+
87
+ @property
88
+ def PRINT_SCALING(self) -> NameObject:
89
+ return NameObject("/PrintScaling")
90
+
91
+ def __new__(cls: Any, value: Any = None) -> "ViewerPreferences": # noqa: PYI034
92
+ def _add_prop_bool(key: str, default: Optional[BooleanObject]) -> property:
93
+ return property(
94
+ lambda self: self._get_bool(key, default),
95
+ lambda self, v: self._set_bool(key, v),
96
+ None,
97
+ f"""
98
+ Returns/Modify the status of {key}, Returns {default} if not defined
99
+ """,
100
+ )
101
+
102
+ def _add_prop_name(
103
+ key: str, lst: list[str], default: Optional[NameObject]
104
+ ) -> property:
105
+ return property(
106
+ lambda self: self._get_name(key, default),
107
+ lambda self, v: self._set_name(key, lst, v),
108
+ None,
109
+ f"""
110
+ Returns/Modify the status of {key}, Returns {default} if not defined.
111
+ Acceptable values: {lst}
112
+ """,
113
+ )
114
+
115
+ def _add_prop_arr(key: str, default: Optional[ArrayObject]) -> property:
116
+ return property(
117
+ lambda self: self._get_arr(key, default),
118
+ lambda self, v: self._set_arr(key, v),
119
+ None,
120
+ f"""
121
+ Returns/Modify the status of {key}, Returns {default} if not defined
122
+ """,
123
+ )
124
+
125
+ def _add_prop_int(key: str, default: Optional[int]) -> property:
126
+ return property(
127
+ lambda self: self._get_int(key, default),
128
+ lambda self, v: self._set_int(key, v),
129
+ None,
130
+ f"""
131
+ Returns/Modify the status of {key}, Returns {default} if not defined
132
+ """,
133
+ )
134
+
135
+ cls.hide_toolbar = _add_prop_bool("/HideToolbar", f_obj)
136
+ cls.hide_menubar = _add_prop_bool("/HideMenubar", f_obj)
137
+ cls.hide_windowui = _add_prop_bool("/HideWindowUI", f_obj)
138
+ cls.fit_window = _add_prop_bool("/FitWindow", f_obj)
139
+ cls.center_window = _add_prop_bool("/CenterWindow", f_obj)
140
+ cls.display_doctitle = _add_prop_bool("/DisplayDocTitle", f_obj)
141
+
142
+ cls.non_fullscreen_pagemode = _add_prop_name(
143
+ "/NonFullScreenPageMode",
144
+ ["/UseNone", "/UseOutlines", "/UseThumbs", "/UseOC"],
145
+ NameObject("/UseNone"),
146
+ )
147
+ cls.direction = _add_prop_name(
148
+ "/Direction", ["/L2R", "/R2L"], NameObject("/L2R")
149
+ )
150
+ cls.view_area = _add_prop_name("/ViewArea", [], None)
151
+ cls.view_clip = _add_prop_name("/ViewClip", [], None)
152
+ cls.print_area = _add_prop_name("/PrintArea", [], None)
153
+ cls.print_clip = _add_prop_name("/PrintClip", [], None)
154
+ cls.print_scaling = _add_prop_name("/PrintScaling", [], None)
155
+ cls.duplex = _add_prop_name(
156
+ "/Duplex", ["/Simplex", "/DuplexFlipShortEdge", "/DuplexFlipLongEdge"], None
157
+ )
158
+ cls.pick_tray_by_pdfsize = _add_prop_bool("/PickTrayByPDFSize", None)
159
+ cls.print_pagerange = _add_prop_arr("/PrintPageRange", None)
160
+ cls.num_copies = _add_prop_int("/NumCopies", None)
161
+
162
+ cls.enforce = _add_prop_arr("/Enforce", ArrayObject())
163
+
164
+ return cast("ViewerPreferences", DictionaryObject.__new__(cls))
.venv/lib/python3.13/site-packages/pypdf/pagerange.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Representation and utils for ranges of PDF file pages.
3
+
4
+ Copyright (c) 2014, Steve Witham <switham_github@mac-guyver.com>.
5
+ All rights reserved. This software is available under a BSD license;
6
+ see https://github.com/py-pdf/pypdf/blob/main/LICENSE
7
+ """
8
+
9
+ import re
10
+ from typing import Any, Optional, Union
11
+
12
+ from .errors import ParseError
13
+
14
+ _INT_RE = r"(0|-?[1-9]\d*)" # A decimal int, don't allow "-0".
15
+ PAGE_RANGE_RE = f"^({_INT_RE}|({_INT_RE}?(:{_INT_RE}?(:{_INT_RE}?)?)))$"
16
+ # groups: 12 34 5 6 7 8
17
+
18
+
19
+ class PageRange:
20
+ """
21
+ A slice-like representation of a range of page indices.
22
+
23
+ For example, page numbers, only starting at zero.
24
+
25
+ The syntax is like what you would put between brackets [ ].
26
+ The slice is one of the few Python types that can't be subclassed,
27
+ but this class converts to and from slices, and allows similar use.
28
+
29
+ - PageRange(str) parses a string representing a page range.
30
+ - PageRange(slice) directly "imports" a slice.
31
+ - to_slice() gives the equivalent slice.
32
+ - str() and repr() allow printing.
33
+ - indices(n) is like slice.indices(n).
34
+ """
35
+
36
+ def __init__(self, arg: Union[slice, "PageRange", str]) -> None:
37
+ """
38
+ Initialize with either a slice -- giving the equivalent page range,
39
+ or a PageRange object -- making a copy,
40
+ or a string like
41
+ "int", "[int]:[int]" or "[int]:[int]:[int]",
42
+ where the brackets indicate optional ints.
43
+ Remember, page indices start with zero.
44
+ Page range expression examples:
45
+
46
+ : all pages. -1 last page.
47
+ 22 just the 23rd page. :-1 all but the last page.
48
+ 0:3 the first three pages. -2 second-to-last page.
49
+ :3 the first three pages. -2: last two pages.
50
+ 5: from the sixth page onward. -3:-1 third & second to last.
51
+ The third, "stride" or "step" number is also recognized.
52
+ ::2 0 2 4 ... to the end. 3:0:-1 3 2 1 but not 0.
53
+ 1:10:2 1 3 5 7 9 2::-1 2 1 0.
54
+ ::-1 all pages in reverse order.
55
+ Note the difference between this notation and arguments to slice():
56
+ slice(3) means the first three pages;
57
+ PageRange("3") means the range of only the fourth page.
58
+ However PageRange(slice(3)) means the first three pages.
59
+ """
60
+ if isinstance(arg, slice):
61
+ self._slice = arg
62
+ return
63
+
64
+ if isinstance(arg, PageRange):
65
+ self._slice = arg.to_slice()
66
+ return
67
+
68
+ m = isinstance(arg, str) and re.match(PAGE_RANGE_RE, arg)
69
+ if not m:
70
+ raise ParseError(arg)
71
+ if m.group(2):
72
+ # Special case: just an int means a range of one page.
73
+ start = int(m.group(2))
74
+ stop = start + 1 if start != -1 else None
75
+ self._slice = slice(start, stop)
76
+ else:
77
+ self._slice = slice(*[int(g) if g else None for g in m.group(4, 6, 8)])
78
+
79
+ @staticmethod
80
+ def valid(input: Any) -> bool:
81
+ """
82
+ True if input is a valid initializer for a PageRange.
83
+
84
+ Args:
85
+ input: A possible PageRange string or a PageRange object.
86
+
87
+ Returns:
88
+ True, if the ``input`` is a valid PageRange.
89
+
90
+ """
91
+ return isinstance(input, (slice, PageRange)) or (
92
+ isinstance(input, str) and bool(re.match(PAGE_RANGE_RE, input))
93
+ )
94
+
95
+ def to_slice(self) -> slice:
96
+ """Return the slice equivalent of this page range."""
97
+ return self._slice
98
+
99
+ def __str__(self) -> str:
100
+ """A string like "1:2:3"."""
101
+ s = self._slice
102
+ indices: Union[tuple[int, int], tuple[int, int, int]]
103
+ if s.step is None:
104
+ if s.start is not None and s.stop == s.start + 1:
105
+ return str(s.start)
106
+
107
+ indices = s.start, s.stop
108
+ else:
109
+ indices = s.start, s.stop, s.step
110
+ return ":".join("" if i is None else str(i) for i in indices)
111
+
112
+ def __repr__(self) -> str:
113
+ """A string like "PageRange('1:2:3')"."""
114
+ return "PageRange(" + repr(str(self)) + ")"
115
+
116
+ def indices(self, n: int) -> tuple[int, int, int]:
117
+ """
118
+ Assuming a sequence of length n, calculate the start and stop indices,
119
+ and the stride length of the PageRange.
120
+
121
+ See help(slice.indices).
122
+
123
+ Args:
124
+ n: the length of the list of pages to choose from.
125
+
126
+ Returns:
127
+ Arguments for range().
128
+
129
+ """
130
+ return self._slice.indices(n)
131
+
132
+ def __eq__(self, other: object) -> bool:
133
+ if not isinstance(other, PageRange):
134
+ return False
135
+ return self._slice == other._slice
136
+
137
+ def __hash__(self) -> int:
138
+ return hash((self.__class__, (self._slice.start, self._slice.stop, self._slice.step)))
139
+
140
+ def __add__(self, other: "PageRange") -> "PageRange":
141
+ if not isinstance(other, PageRange):
142
+ raise TypeError(f"Can't add PageRange and {type(other)}")
143
+ if self._slice.step is not None or other._slice.step is not None:
144
+ raise ValueError("Can't add PageRange with stride")
145
+ a = self._slice.start, self._slice.stop
146
+ b = other._slice.start, other._slice.stop
147
+
148
+ # None start means "beginning" (-inf for ordering); None stop means "end" (+inf).
149
+ def _start_key(v: Optional[int]) -> float:
150
+ return float("-inf") if v is None else v
151
+
152
+ def _stop_key(v: Optional[int]) -> float:
153
+ return float("inf") if v is None else v
154
+
155
+ if _start_key(a[0]) > _start_key(b[0]):
156
+ a, b = b, a
157
+
158
+ # Now `a` has the smaller (or equal) start.
159
+ if _start_key(b[0]) > _stop_key(a[1]):
160
+ # There is a gap between a and b.
161
+ raise ValueError("Can't add PageRanges with gap")
162
+ stop = b[1] if _stop_key(b[1]) > _stop_key(a[1]) else a[1]
163
+ return PageRange(slice(a[0], stop))
164
+
165
+
166
+ PAGE_RANGE_ALL = PageRange(":") # The range of all pages.
167
+
168
+
169
+ def parse_filename_page_ranges(
170
+ args: list[Union[str, PageRange, None]]
171
+ ) -> list[tuple[str, PageRange]]:
172
+ """
173
+ Given a list of filenames and page ranges, return a list of (filename, page_range) pairs.
174
+
175
+ Args:
176
+ args: A list where the first element is a filename. The other elements are
177
+ filenames, page-range expressions, slice objects, or PageRange objects.
178
+ A filename not followed by a page range indicates all pages of the file.
179
+
180
+ Returns:
181
+ A list of (filename, page_range) pairs.
182
+
183
+ """
184
+ pairs: list[tuple[str, PageRange]] = []
185
+ pdf_filename: Union[str, None] = None
186
+ did_page_range = False
187
+ for arg in [*args, None]:
188
+ if PageRange.valid(arg):
189
+ if not pdf_filename:
190
+ raise ValueError(
191
+ "The first argument must be a filename, not a page range."
192
+ )
193
+
194
+ assert arg is not None
195
+ pairs.append((pdf_filename, PageRange(arg)))
196
+ did_page_range = True
197
+ else:
198
+ # New filename or end of list - use the complete previous file?
199
+ if pdf_filename and not did_page_range:
200
+ pairs.append((pdf_filename, PAGE_RANGE_ALL))
201
+
202
+ assert not isinstance(arg, PageRange), arg
203
+ pdf_filename = arg
204
+ did_page_range = False
205
+ return pairs
206
+
207
+
208
+ PageRangeSpec = Union[str, PageRange, tuple[int, int], tuple[int, int, int], list[int]]
.venv/lib/python3.13/site-packages/pypdf/papersizes.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Helper to get paper sizes."""
2
+
3
+ from typing import NamedTuple
4
+
5
+
6
+ class Dimensions(NamedTuple):
7
+ width: int
8
+ height: int
9
+
10
+
11
+ class PaperSize:
12
+ """(width, height) of the paper in portrait mode in pixels at 72 ppi."""
13
+
14
+ # Notes of how to calculate it:
15
+ # 1. Get the size of the paper in millimeters
16
+ # 2. Convert it to inches (25.4 millimeters is equal to 1 inch)
17
+ # 3. Convert it to pixels at 72dpi (1 inch is equal to 72 pixels)
18
+
19
+ # All Din-A paper sizes follow this pattern:
20
+ # 2 x A(n - 1) = A(n)
21
+ # So the height of the next bigger one is the width of the smaller one
22
+ # The ratio is always approximately 1:2**0.5
23
+ # Additionally, A0 is defined to have an area of 1 m**2
24
+ # https://en.wikipedia.org/wiki/ISO_216
25
+ # Be aware of rounding issues!
26
+ A0 = Dimensions(2384, 3370) # 841mm x 1189mm
27
+ A1 = Dimensions(1684, 2384)
28
+ A2 = Dimensions(1191, 1684)
29
+ A3 = Dimensions(842, 1191)
30
+ A4 = Dimensions(
31
+ 595, 842
32
+ ) # Printer paper, documents - this is by far the most common
33
+ A5 = Dimensions(420, 595) # Paperback books
34
+ A6 = Dimensions(298, 420) # Postcards
35
+ A7 = Dimensions(210, 298)
36
+ A8 = Dimensions(147, 210)
37
+
38
+ # Envelopes
39
+ C4 = Dimensions(649, 918)
40
+
41
+
42
+ _din_a = (
43
+ PaperSize.A0,
44
+ PaperSize.A1,
45
+ PaperSize.A2,
46
+ PaperSize.A3,
47
+ PaperSize.A4,
48
+ PaperSize.A5,
49
+ PaperSize.A6,
50
+ PaperSize.A7,
51
+ PaperSize.A8,
52
+ )