diff --git a/.venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/INSTALLER b/.venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/METADATA b/.venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..5ccdb23335ce1e17a6f7dbf53725338e4098dfdd --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/METADATA @@ -0,0 +1,177 @@ +Metadata-Version: 2.4 +Name: pypdf +Version: 6.15.0 +Summary: A pure-python PDF library capable of splitting, merging, cropping, and transforming PDF files +Author-email: Mathieu Fenniak +Maintainer: stefan6419846 +Maintainer-email: Martin Thoma +Requires-Python: >=3.9 +Description-Content-Type: text/markdown +License-Expression: BSD-3-Clause +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Operating System :: OS Independent +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Typing :: Typed +License-File: LICENSE +Requires-Dist: typing_extensions >= 4.0; python_version < '3.11' +Requires-Dist: cryptography>3.0 ; extra == "crypto" +Requires-Dist: PyCryptodome ; extra == "cryptodome" +Requires-Dist: flit ; extra == "dev" +Requires-Dist: pip-tools ; extra == "dev" +Requires-Dist: pre-commit ; extra == "dev" +Requires-Dist: pytest-cov ; extra == "dev" +Requires-Dist: pytest-socket ; extra == "dev" +Requires-Dist: pytest-timeout ; extra == "dev" +Requires-Dist: pytest-xdist ; extra == "dev" +Requires-Dist: wheel ; extra == "dev" +Requires-Dist: myst_parser ; extra == "docs" +Requires-Dist: sphinx ; extra == "docs" +Requires-Dist: sphinx_rtd_theme ; extra == "docs" +Requires-Dist: fonttools ; extra == "fonts" +Requires-Dist: arabic-reshaper ; extra == "full" +Requires-Dist: cryptography>3.0 ; extra == "full" +Requires-Dist: fonttools ; extra == "full" +Requires-Dist: Pillow>=8.0.0 ; extra == "full" +Requires-Dist: python-bidi ; extra == "full" +Requires-Dist: Pillow>=8.0.0 ; extra == "image" +Requires-Dist: arabic-reshaper ; extra == "rtl-text" +Requires-Dist: python-bidi ; extra == "rtl-text" +Project-URL: Bug Reports, https://github.com/py-pdf/pypdf/issues +Project-URL: Changelog, https://pypdf.readthedocs.io/en/latest/meta/CHANGELOG.html +Project-URL: Documentation, https://pypdf.readthedocs.io/en/latest/ +Project-URL: Source, https://github.com/py-pdf/pypdf +Provides-Extra: crypto +Provides-Extra: cryptodome +Provides-Extra: dev +Provides-Extra: docs +Provides-Extra: fonts +Provides-Extra: full +Provides-Extra: image +Provides-Extra: rtl-text + +[![PyPI version](https://badge.fury.io/py/pypdf.svg)](https://badge.fury.io/py/pypdf) +[![Python Support](https://img.shields.io/pypi/pyversions/pypdf.svg)](https://pypi.org/project/pypdf/) +[![](https://img.shields.io/badge/-documentation-green)](https://pypdf.readthedocs.io/en/stable/) +[![GitHub last commit](https://img.shields.io/github/last-commit/py-pdf/pypdf)](https://github.com/py-pdf/pypdf) +[![codecov](https://codecov.io/gh/py-pdf/pypdf/branch/main/graph/badge.svg?token=id42cGNZ5Z)](https://codecov.io/gh/py-pdf/pypdf) + +# pypdf + +pypdf is a free and open-source pure-python PDF library capable of splitting, +[merging](https://pypdf.readthedocs.io/en/stable/user/merging-pdfs.html), +[cropping, and transforming](https://pypdf.readthedocs.io/en/stable/user/cropping-and-transforming.html) +the pages of PDF files. It can also add +custom data, viewing options, and +[passwords](https://pypdf.readthedocs.io/en/stable/user/encryption-decryption.html) +to PDF files. pypdf can +[retrieve text](https://pypdf.readthedocs.io/en/stable/user/extract-text.html) +and +[metadata](https://pypdf.readthedocs.io/en/stable/user/metadata.html) +from PDFs as well. + +See [pdfly](https://github.com/py-pdf/pdfly) for a CLI application that uses pypdf to interact with PDFs. + +## Installation + +Install pypdf using pip: + +``` +pip install pypdf +``` + +For using pypdf with AES encryption or decryption, install extra dependencies: + +``` +pip install pypdf[crypto] +``` + +> **NOTE**: `pypdf` 3.1.0 and above include significant improvements compared to +> previous versions. Please refer to [the migration +> guide](https://pypdf.readthedocs.io/en/latest/user/migration-1-to-2.html) for +> more information. + +## Usage + +```python +from pypdf import PdfReader + +reader = PdfReader("example.pdf") +number_of_pages = len(reader.pages) +page = reader.pages[0] +text = page.extract_text() +``` + +pypdf can do a lot more, e.g. splitting, merging, reading and creating annotations, decrypting and encrypting. Check out the +[documentation](https://pypdf.readthedocs.io/en/stable/) for additional usage +examples! + +For questions and answers, visit +[StackOverflow](https://stackoverflow.com/questions/tagged/pypdf) +(tagged with [pypdf](https://stackoverflow.com/questions/tagged/pypdf)). + +## Contributions + +Maintaining pypdf is a collaborative effort. You can support the project by +writing documentation, helping to narrow down issues, and submitting code. +See the [CONTRIBUTING.md](https://github.com/py-pdf/pypdf/blob/main/CONTRIBUTING.md) file for more information. + +### Q&A + +The experience pypdf users have covers the whole range from beginner to expert. You can contribute to the pypdf community by answering questions +on [StackOverflow](https://stackoverflow.com/questions/tagged/pypdf), +helping in [discussions](https://github.com/py-pdf/pypdf/discussions), +and asking users who report issues for [MCVE](https://stackoverflow.com/help/minimal-reproducible-example)'s (Code + example PDF!). + + +### Issues + +A good bug ticket includes a MCVE - a minimal complete verifiable example. +For pypdf, this means that you must upload a PDF that causes the bug to occur +as well as the code you're executing with all of the output. Use +`print(pypdf.__version__)` to tell us which version you're using. + +### Code + +All code contributions are welcome, but smaller ones have a better chance to +get included in a timely manner. Adding unit tests for new features or test +cases for bugs you've fixed help us to ensure that the Pull Request (PR) is fine. + +pypdf includes a test suite which can be executed with `pytest`: + +```bash +$ pytest +===================== test session starts ===================== +platform linux -- Python 3.6.15, pytest-7.0.1, pluggy-1.0.0 +rootdir: /home/moose/GitHub/Martin/pypdf +plugins: cov-3.0.0 +collected 233 items + +tests/test_basic_features.py .. [ 0%] +tests/test_constants.py . [ 1%] +tests/test_filters.py .................x..... [ 11%] +tests/test_generic.py ................................. [ 25%] +............. [ 30%] +tests/test_javascript.py .. [ 31%] +tests/test_merger.py . [ 32%] +tests/test_page.py ......................... [ 42%] +tests/test_pagerange.py ................ [ 49%] +tests/test_papersizes.py .................. [ 57%] +tests/test_reader.py .................................. [ 72%] +............... [ 78%] +tests/test_utils.py .................... [ 87%] +tests/test_workflows.py .......... [ 91%] +tests/test_writer.py ................. [ 98%] +tests/test_xmp.py ... [100%] + +========== 232 passed, 1 xfailed, 1 warning in 4.52s ========== +``` + diff --git a/.venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/RECORD b/.venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..48cdb4f27a7b97831b9c5a8063f8f08c5848836f --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/RECORD @@ -0,0 +1,121 @@ +pypdf-6.15.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pypdf-6.15.0.dist-info/METADATA,sha256=0Ez3NVXH7UyS06-fj8J0eKe9qKwJfEZIuoMhyFyIGYs,7450 +pypdf-6.15.0.dist-info/RECORD,, +pypdf-6.15.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pypdf-6.15.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +pypdf-6.15.0.dist-info/licenses/LICENSE,sha256=qXrCMOXzPvEKU2eoUOsB-R8aCwZONHQsd5TSKUVX9SQ,1605 +pypdf/__init__.py,sha256=YS_1ZrQ3jBPHsRgMstqJrAts3lUApj_lMOMK5qiLG5w,1283 +pypdf/__pycache__/__init__.cpython-313.pyc,, +pypdf/__pycache__/_cmap.cpython-313.pyc,, +pypdf/__pycache__/_doc_common.cpython-313.pyc,, +pypdf/__pycache__/_encryption.cpython-313.pyc,, +pypdf/__pycache__/_font.cpython-313.pyc,, +pypdf/__pycache__/_page.cpython-313.pyc,, +pypdf/__pycache__/_page_labels.cpython-313.pyc,, +pypdf/__pycache__/_protocols.cpython-313.pyc,, +pypdf/__pycache__/_reader.cpython-313.pyc,, +pypdf/__pycache__/_utils.cpython-313.pyc,, +pypdf/__pycache__/_version.cpython-313.pyc,, +pypdf/__pycache__/_writer.cpython-313.pyc,, +pypdf/__pycache__/constants.cpython-313.pyc,, +pypdf/__pycache__/errors.cpython-313.pyc,, +pypdf/__pycache__/filters.cpython-313.pyc,, +pypdf/__pycache__/pagerange.cpython-313.pyc,, +pypdf/__pycache__/papersizes.cpython-313.pyc,, +pypdf/__pycache__/types.cpython-313.pyc,, +pypdf/__pycache__/xmp.cpython-313.pyc,, +pypdf/_cmap.py,sha256=A1k_tJgl8TUzzjrgfgc4bIuLOyz2ZQ1rl_63gVeJSSQ,14653 +pypdf/_codecs/__init__.py,sha256=A11ERAtwtWrpGVOzTSlrC1a3T9HClWLBWRwGe3_Pfu0,1373 +pypdf/_codecs/__pycache__/__init__.cpython-313.pyc,, +pypdf/_codecs/__pycache__/_codecs.cpython-313.pyc,, +pypdf/_codecs/__pycache__/adobe_glyphs.cpython-313.pyc,, +pypdf/_codecs/__pycache__/core_font_metrics.cpython-313.pyc,, +pypdf/_codecs/__pycache__/pdfdoc.cpython-313.pyc,, +pypdf/_codecs/__pycache__/std.cpython-313.pyc,, +pypdf/_codecs/__pycache__/symbol.cpython-313.pyc,, +pypdf/_codecs/__pycache__/zapfding.cpython-313.pyc,, +pypdf/_codecs/_codecs.py,sha256=83fId54XE-aRb3mNi_p1olJtZzdUh98HsxWXCOGTtRI,10717 +pypdf/_codecs/adobe_glyphs.py,sha256=aaxORupQQJ7kbLDHbjWigLZ6pg8G9_5eqDKiNJxykj4,577665 +pypdf/_codecs/core_font_metrics.py,sha256=FLPWbTZ4hxeQWXgg1jo5e4qXKCFkKEY5e85U2bLFM6k,114968 +pypdf/_codecs/pdfdoc.py,sha256=xfSvMFYsvxuaSQ0Uu9vZDKaB0Wu85h1uCiB1i9rAcUU,4269 +pypdf/_codecs/std.py,sha256=DyQMuEpAGEpS9uy1jWf4cnj-kqShPOAij5sI7Q1YD8E,2630 +pypdf/_codecs/symbol.py,sha256=CP6VjRcscrm8ymAH90xpdxVaelwi6MSb1Tb1wNDh01k,4642 +pypdf/_codecs/zapfding.py,sha256=45qcY11xbBwtoh6_t0Z_7zNjG7-qI411LRQVXYKPr2U,4655 +pypdf/_crypt_providers/__init__.py,sha256=xUQbFgMQvKMaOOT3RUdW3bS8fZShR8PBOz6resfwWFU,2770 +pypdf/_crypt_providers/__pycache__/__init__.cpython-313.pyc,, +pypdf/_crypt_providers/__pycache__/_base.cpython-313.pyc,, +pypdf/_crypt_providers/__pycache__/_cryptography.cpython-313.pyc,, +pypdf/_crypt_providers/__pycache__/_fallback.cpython-313.pyc,, +pypdf/_crypt_providers/__pycache__/_pycryptodome.cpython-313.pyc,, +pypdf/_crypt_providers/_base.py,sha256=NFBXEdhbrg9k01PVfNN_k7lEAYl2BkgXIOi5ofU_-R8,1735 +pypdf/_crypt_providers/_cryptography.py,sha256=fIhNNH2asQqJrw0F7QY61Nl1UeJAEr9RcAo1t0-CgNA,5265 +pypdf/_crypt_providers/_fallback.py,sha256=gXcro_K7q4IYDL5XGVRxoFmXjXXMa6TleDDwxWyCj4E,3382 +pypdf/_crypt_providers/_pycryptodome.py,sha256=xX4Fta8QHHEztE-_YHk-vJtmBU1xKVwB99_ysQ6TnOI,4020 +pypdf/_doc_common.py,sha256=BNPg6w_L4FcuKo6bQstPaRdK4_t_rE13dQz7We8osDw,56383 +pypdf/_encryption.py,sha256=w5ySfgwdn6rOXAbyRGAwJ0IcUHh9uEdTX3gAkOsB4Kc,53649 +pypdf/_font.py,sha256=Lz6afTmfIYJxJth5qlIUs5tZ_7qYU_kLhgmlNJ4SwsQ,35572 +pypdf/_page.py,sha256=bDW_zjKldkjfiny3qh4Rga01-YZip_ebqzJVeXL9P4w,98311 +pypdf/_page_labels.py,sha256=c8iENzeLZNHXtWoAGcbHJQQmu7xQFjR3BVSeSObQ-M0,9929 +pypdf/_protocols.py,sha256=TrrfcqgxqjgjMPntHKXoCsnxz7EfuFGihn-whab3R2Q,2123 +pypdf/_reader.py,sha256=iOjDJfoJk40VHSpBtEvbDA-2Wskb6aMkA7yuMBe-iUo,66477 +pypdf/_text_extraction/__init__.py,sha256=kIx-qGevNfXBGvDjUBEv99PuVtsq2Y7Ke_iwiLBYze0,8672 +pypdf/_text_extraction/__pycache__/__init__.cpython-313.pyc,, +pypdf/_text_extraction/__pycache__/_text_extractor.cpython-313.pyc,, +pypdf/_text_extraction/_layout_mode/__init__.py,sha256=RUQIwiUwzneNtcljnVM6jkRaem6pgP7mOD2-MBmtpvw,340 +pypdf/_text_extraction/_layout_mode/__pycache__/__init__.cpython-313.pyc,, +pypdf/_text_extraction/_layout_mode/__pycache__/_fixed_width_page.cpython-313.pyc,, +pypdf/_text_extraction/_layout_mode/__pycache__/_text_state_manager.cpython-313.pyc,, +pypdf/_text_extraction/_layout_mode/__pycache__/_text_state_params.cpython-313.pyc,, +pypdf/_text_extraction/_layout_mode/_fixed_width_page.py,sha256=KdowE9CUqq78RMZV7ZwUnDk7M-ApLLN1If0p2IMPH7A,17319 +pypdf/_text_extraction/_layout_mode/_text_state_manager.py,sha256=aB_tK4X2aHMTxroyfNrGfFeae5dKni073MDR7aldJ5I,7517 +pypdf/_text_extraction/_layout_mode/_text_state_params.py,sha256=cQZAxv4QHt_m5B_jD9OdNLjMXfluEO_YH6UPPqizqfM,6513 +pypdf/_text_extraction/_text_extractor.py,sha256=RugMYgswXsaecAzbFYn-yWp6xLcTeMMuwsrF54BjlWw,14856 +pypdf/_utils.py,sha256=ime7zpRNyZKm1zqab1KGEO1wOgwMJLr4pmG5ET_vVPQ,22793 +pypdf/_version.py,sha256=8Bbf6hj6ZBEdoH0KJirhsFddWkzMvVBgbbpy7sPV--k,23 +pypdf/_writer.py,sha256=YTu87dgqa33YLGXjRBHgoX5sfHTwluY07b2aIOqEPSg,135145 +pypdf/actions/__init__.py,sha256=2L3YHvYIRrqwl2QEkJkeS2O9a1IesDVu1pbiSFQplRg,391 +pypdf/actions/__pycache__/__init__.cpython-313.pyc,, +pypdf/actions/__pycache__/_actions.cpython-313.pyc,, +pypdf/actions/_actions.py,sha256=nDqPLWQdB7EUglcPvx5sfNjmGy6FRxk9U5snlosmS20,6521 +pypdf/annotations/__init__.py,sha256=f2k_-jAn39CCB27KxQ_e93GinnzkAHbUnnSeGJl1jyE,990 +pypdf/annotations/__pycache__/__init__.cpython-313.pyc,, +pypdf/annotations/__pycache__/_base.cpython-313.pyc,, +pypdf/annotations/__pycache__/_markup_annotations.cpython-313.pyc,, +pypdf/annotations/__pycache__/_non_markup_annotations.cpython-313.pyc,, +pypdf/annotations/_base.py,sha256=YIRTzTdkqj8DUWSTmy0frkfTr4joe5HUGzROUof4oIo,961 +pypdf/annotations/_markup_annotations.py,sha256=sWKhGBCG7X9ojAvEaRMEoJP-fY6FcrlFdOmtefIZBm0,11862 +pypdf/annotations/_non_markup_annotations.py,sha256=WKWYte2OibZG3MH7Bf26oTOpCyyGrkPLYnFdJ1osRrY,3656 +pypdf/constants.py,sha256=4hW9lyieto5PY8vL_W4mxZJeSBB1nhmQmcdyHYZZ8Bs,23676 +pypdf/errors.py,sha256=Bw1W9hxOsDgwqwU6YoQ2l0-JiUyTq6l5QjVCr-W4GFA,1947 +pypdf/filters.py,sha256=gC_yDe0IaQYA00S6gDqB9ewcLXlnyS2qMH1khTd3OOc,32785 +pypdf/generic/__init__.py,sha256=VrqdYftQECePDU2rXVMgEqRaYFR8zOV_fvJgo19x_uw,3468 +pypdf/generic/__pycache__/__init__.cpython-313.pyc,, +pypdf/generic/__pycache__/_appearance_stream.cpython-313.pyc,, +pypdf/generic/__pycache__/_base.cpython-313.pyc,, +pypdf/generic/__pycache__/_data_structures.cpython-313.pyc,, +pypdf/generic/__pycache__/_files.cpython-313.pyc,, +pypdf/generic/__pycache__/_fit.cpython-313.pyc,, +pypdf/generic/__pycache__/_image_inline.cpython-313.pyc,, +pypdf/generic/__pycache__/_image_xobject.cpython-313.pyc,, +pypdf/generic/__pycache__/_link.cpython-313.pyc,, +pypdf/generic/__pycache__/_outline.cpython-313.pyc,, +pypdf/generic/__pycache__/_rectangle.cpython-313.pyc,, +pypdf/generic/__pycache__/_utils.cpython-313.pyc,, +pypdf/generic/__pycache__/_viewerpref.cpython-313.pyc,, +pypdf/generic/_appearance_stream.py,sha256=jESIYicmk6hACyiOALmhbZY8Fr27HbCKSw-kEgvtZjw,34232 +pypdf/generic/_base.py,sha256=_A8NqHJNt59KyoYdwNzAl65ItUlWzcPcw9aztuoCAI0,33427 +pypdf/generic/_data_structures.py,sha256=TUjLDHbd4HjNtl_wld7cB4ooXw5M64wkQ0ZrEZt99SI,69487 +pypdf/generic/_files.py,sha256=YK2OtD19lP7xgUieOKNyqSxZWrfMezxbx4mHaUlCJEk,16789 +pypdf/generic/_fit.py,sha256=IwhejQjIq751vJjVGaWNe9uJX8HzXQ2XppmtLhI-NOo,5515 +pypdf/generic/_image_inline.py,sha256=pgA1wwIh-bC44kRw5gH9_o38ViiRTzwQ8WY-NBysUd8,13281 +pypdf/generic/_image_xobject.py,sha256=TQFpA6p2lb7uaAAaqMRj1ZUGsTYJRZmT11vCADWuHKI,27041 +pypdf/generic/_link.py,sha256=kINa5ZOipGHxY_YW_fIxF4z0TRNKlww4jRYaGCLTQRY,6207 +pypdf/generic/_outline.py,sha256=PEuST4b-KmAQIDAJ0FhyxN7ANmJjdsWaTdxKo7hiq3g,1094 +pypdf/generic/_rectangle.py,sha256=h6DDP9fgtrMyGG1aouZ51n9XJ0J13dxhhqanJxSBNNU,3924 +pypdf/generic/_utils.py,sha256=n2sDl8uBXYIPHmXj2Fzoz91WOTFNozl0sAaM9wgCT-Q,7514 +pypdf/generic/_viewerpref.py,sha256=y92KHY3iy9FajuBos97E1sPk9unzJG-Uk2VCd7iSYeY,6835 +pypdf/pagerange.py,sha256=8hyGOsEC94aiYeKoqukASrE5FZDtx8XrJQFaD-Lp3C0,7536 +pypdf/papersizes.py,sha256=6Tz5sfNN_3JOUapY83U-lakohnpXYA0hSEQNmOVLFL8,1413 +pypdf/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pypdf/types.py,sha256=sJ7wHzk7ER_CJ7kP-s8u9axFnkCXnFpr8nzcj1AxTas,1915 +pypdf/xmp.py,sha256=mBk1XMdkE8oybSbo2A1Kp9kVNCUPuqdO1ATZE4WIIQQ,31655 diff --git a/.venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/REQUESTED b/.venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/WHEEL b/.venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.12.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/.venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/licenses/LICENSE b/.venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ab327d0312875458ba74983867f1b2622b6de39d --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf-6.15.0.dist-info/licenses/LICENSE @@ -0,0 +1,29 @@ +Copyright (c) 2006-2008, Mathieu Fenniak +Some contributions copyright (c) 2007, Ashish Kulkarni +Some contributions copyright (c) 2014, Steve Witham + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright notice, +this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. +* The name of the author may not be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.13/site-packages/pypdf/_crypt_providers/_base.py b/.venv/lib/python3.13/site-packages/pypdf/_crypt_providers/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..d66dd4c2667723da4be677945388da7d1f07901f --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/_crypt_providers/_base.py @@ -0,0 +1,38 @@ +# Copyright (c) 2023, exiledkingcc +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * The name of the author may not be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + + +class CryptBase: + def encrypt(self, data: bytes) -> bytes: # pragma: no cover + return data + + def decrypt(self, data: bytes, *, strict: bool = True) -> bytes: # pragma: no cover + return data + + +class CryptIdentity(CryptBase): + pass diff --git a/.venv/lib/python3.13/site-packages/pypdf/_crypt_providers/_cryptography.py b/.venv/lib/python3.13/site-packages/pypdf/_crypt_providers/_cryptography.py new file mode 100644 index 0000000000000000000000000000000000000000..5605e5e532c156677619b3ba544bfee0cadd2060 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/_crypt_providers/_cryptography.py @@ -0,0 +1,132 @@ +# Copyright (c) 2023, exiledkingcc +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * The name of the author may not be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +import secrets + +from cryptography import __version__ +from cryptography.hazmat.primitives.ciphers.algorithms import AES +from cryptography.hazmat.primitives.ciphers.base import Cipher +from cryptography.hazmat.primitives.ciphers.modes import CBC, ECB +from cryptography.hazmat.primitives.padding import PKCS7 + +from pypdf._crypt_providers._base import CryptBase +from pypdf._utils import logger_warning +from pypdf.errors import PdfStreamError + +try: + # 43.0.0: https://cryptography.io/en/latest/changelog/#v43-0-0 + from cryptography.hazmat.decrepit.ciphers.algorithms import ARC4 +except ImportError: + from cryptography.hazmat.primitives.ciphers.algorithms import ARC4 + +crypt_provider = ("cryptography", __version__) + + +class CryptRC4(CryptBase): + def __init__(self, key: bytes) -> None: + self.cipher = Cipher(ARC4(key), mode=None) + + def encrypt(self, data: bytes) -> bytes: + encryptor = self.cipher.encryptor() + return encryptor.update(data) + encryptor.finalize() + + def decrypt(self, data: bytes, *, strict: bool = True) -> bytes: + decryptor = self.cipher.decryptor() + return decryptor.update(data) + decryptor.finalize() + + +class CryptAES(CryptBase): + def __init__(self, key: bytes) -> None: + self.alg = AES(key) + + def encrypt(self, data: bytes) -> bytes: + iv = secrets.token_bytes(16) + padder = PKCS7(128).padder() + padded_data = padder.update(data) + padder.finalize() + + cipher = Cipher(self.alg, CBC(iv)) + encryptor = cipher.encryptor() + return iv + encryptor.update(padded_data) + encryptor.finalize() + + def decrypt(self, data: bytes, *, strict: bool = True) -> bytes: + iv = data[:16] + data = data[16:] + # for empty encrypted data + if not data: + return data + + if not strict and len(data) % 16 != 0: + logger_warning("Adding missing padding.", source=__name__) + padder = PKCS7(128).padder() + data = padder.update(data) + padder.finalize() + + cipher = Cipher(self.alg, CBC(iv)) + decryptor = cipher.decryptor() + try: + padded_data = decryptor.update(data) + decryptor.finalize() + except ValueError as exception: + # Only raised in strict mode. Non-strict mode fixes padding. + raise PdfStreamError(exception) + + unpadder = PKCS7(128).unpadder() + try: + return unpadder.update(padded_data) + unpadder.finalize() + except ValueError as exception: + if strict: + raise PdfStreamError(exception) + logger_warning("Ignoring padding error: %(exception)s", source=__name__, exception=exception) + return padded_data[: -padded_data[-1]] + + +def rc4_encrypt(key: bytes, data: bytes) -> bytes: + encryptor = Cipher(ARC4(key), mode=None).encryptor() + return encryptor.update(data) + encryptor.finalize() + + +def rc4_decrypt(key: bytes, data: bytes) -> bytes: + decryptor = Cipher(ARC4(key), mode=None).decryptor() + return decryptor.update(data) + decryptor.finalize() + + +def aes_ecb_encrypt(key: bytes, data: bytes) -> bytes: + encryptor = Cipher(AES(key), mode=ECB()).encryptor() + return encryptor.update(data) + encryptor.finalize() + + +def aes_ecb_decrypt(key: bytes, data: bytes) -> bytes: + decryptor = Cipher(AES(key), mode=ECB()).decryptor() + return decryptor.update(data) + decryptor.finalize() + + +def aes_cbc_encrypt(key: bytes, iv: bytes, data: bytes) -> bytes: + encryptor = Cipher(AES(key), mode=CBC(iv)).encryptor() + return encryptor.update(data) + encryptor.finalize() + + +def aes_cbc_decrypt(key: bytes, iv: bytes, data: bytes) -> bytes: + decryptor = Cipher(AES(key), mode=CBC(iv)).decryptor() + return decryptor.update(data) + decryptor.finalize() diff --git a/.venv/lib/python3.13/site-packages/pypdf/_crypt_providers/_fallback.py b/.venv/lib/python3.13/site-packages/pypdf/_crypt_providers/_fallback.py new file mode 100644 index 0000000000000000000000000000000000000000..2b7d3275fd6c0fce04de8df7a316087350a02373 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/_crypt_providers/_fallback.py @@ -0,0 +1,93 @@ +# Copyright (c) 2023, exiledkingcc +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * The name of the author may not be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +from pypdf._crypt_providers._base import CryptBase +from pypdf.errors import DependencyError + +_DEPENDENCY_ERROR_STR = "cryptography>=3.1 is required for AES algorithm" + + +crypt_provider = ("local_crypt_fallback", "0.0.0") + + +class CryptRC4(CryptBase): + def __init__(self, key: bytes) -> None: + self.s = bytearray(range(256)) + j = 0 + for i in range(256): + j = (j + self.s[i] + key[i % len(key)]) % 256 + self.s[i], self.s[j] = self.s[j], self.s[i] + + def encrypt(self, data: bytes) -> bytes: + s = bytearray(self.s) + out = [0 for _ in range(len(data))] + i, j = 0, 0 + for k in range(len(data)): + i = (i + 1) % 256 + j = (j + s[i]) % 256 + s[i], s[j] = s[j], s[i] + x = s[(s[i] + s[j]) % 256] + out[k] = data[k] ^ x + return bytes(out) + + def decrypt(self, data: bytes, *, strict: bool = True) -> bytes: + return self.encrypt(data) + + +class CryptAES(CryptBase): + def __init__(self, key: bytes) -> None: + pass + + def encrypt(self, data: bytes) -> bytes: + raise DependencyError(_DEPENDENCY_ERROR_STR) + + def decrypt(self, data: bytes, *, strict: bool = True) -> bytes: + raise DependencyError(_DEPENDENCY_ERROR_STR) + + +def rc4_encrypt(key: bytes, data: bytes) -> bytes: + return CryptRC4(key).encrypt(data) + + +def rc4_decrypt(key: bytes, data: bytes) -> bytes: + return CryptRC4(key).decrypt(data) + + +def aes_ecb_encrypt(key: bytes, data: bytes) -> bytes: + raise DependencyError(_DEPENDENCY_ERROR_STR) + + +def aes_ecb_decrypt(key: bytes, data: bytes) -> bytes: + raise DependencyError(_DEPENDENCY_ERROR_STR) + + +def aes_cbc_encrypt(key: bytes, iv: bytes, data: bytes) -> bytes: + raise DependencyError(_DEPENDENCY_ERROR_STR) + + +def aes_cbc_decrypt(key: bytes, iv: bytes, data: bytes) -> bytes: + raise DependencyError(_DEPENDENCY_ERROR_STR) diff --git a/.venv/lib/python3.13/site-packages/pypdf/_crypt_providers/_pycryptodome.py b/.venv/lib/python3.13/site-packages/pypdf/_crypt_providers/_pycryptodome.py new file mode 100644 index 0000000000000000000000000000000000000000..b5efba216bbf831f67c3eb3e790a472c074ba0bb --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/_crypt_providers/_pycryptodome.py @@ -0,0 +1,110 @@ +# Copyright (c) 2023, exiledkingcc +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * The name of the author may not be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +import secrets + +from Crypto import __version__ +from Crypto.Cipher import AES, ARC4 +from Crypto.Util.Padding import pad, unpad + +from pypdf._crypt_providers._base import CryptBase +from pypdf._utils import logger_warning +from pypdf.errors import PdfStreamError + +crypt_provider = ("pycryptodome", __version__) + + +class CryptRC4(CryptBase): + def __init__(self, key: bytes) -> None: + self.key = key + + def encrypt(self, data: bytes) -> bytes: + return ARC4.ARC4Cipher(self.key).encrypt(data) + + def decrypt(self, data: bytes, *, strict: bool = True) -> bytes: + return ARC4.ARC4Cipher(self.key).decrypt(data) + + +class CryptAES(CryptBase): + def __init__(self, key: bytes) -> None: + self.key = key + + def encrypt(self, data: bytes) -> bytes: + iv = secrets.token_bytes(16) + padded_data = pad(data, 16) + aes = AES.new(self.key, AES.MODE_CBC, iv) + return iv + aes.encrypt(padded_data) + + def decrypt(self, data: bytes, *, strict: bool = True) -> bytes: + iv = data[:16] + data = data[16:] + # for empty encrypted data + if not data: + return data + + if not strict and len(data) % 16 != 0: + logger_warning("Adding missing padding.", source=__name__) + data = pad(data, 16) + + aes = AES.new(self.key, AES.MODE_CBC, iv) + try: + padded_data = aes.decrypt(data) + except ValueError as exception: + # Only raised in strict mode. Non-strict mode fixes padding. + raise PdfStreamError(exception) + + try: + return unpad(padded_data, 16) + except ValueError as exception: + if strict: + raise PdfStreamError(exception) + logger_warning("Ignoring padding error: %(exception)s", source=__name__, exception=exception) + return padded_data[: -padded_data[-1]] + + +def rc4_encrypt(key: bytes, data: bytes) -> bytes: + return ARC4.ARC4Cipher(key).encrypt(data) + + +def rc4_decrypt(key: bytes, data: bytes) -> bytes: + return ARC4.ARC4Cipher(key).decrypt(data) + + +def aes_ecb_encrypt(key: bytes, data: bytes) -> bytes: + return AES.new(key, AES.MODE_ECB).encrypt(data) + + +def aes_ecb_decrypt(key: bytes, data: bytes) -> bytes: + return AES.new(key, AES.MODE_ECB).decrypt(data) + + +def aes_cbc_encrypt(key: bytes, iv: bytes, data: bytes) -> bytes: + return AES.new(key, AES.MODE_CBC, iv).encrypt(data) + + +def aes_cbc_decrypt(key: bytes, iv: bytes, data: bytes) -> bytes: + return AES.new(key, AES.MODE_CBC, iv).decrypt(data) diff --git a/.venv/lib/python3.13/site-packages/pypdf/_doc_common.py b/.venv/lib/python3.13/site-packages/pypdf/_doc_common.py new file mode 100644 index 0000000000000000000000000000000000000000..016472fc64a5fd6118453467e895ae0adf5012dd --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/_doc_common.py @@ -0,0 +1,1528 @@ +# Copyright (c) 2006, Mathieu Fenniak +# Copyright (c) 2007, Ashish Kulkarni +# Copyright (c) 2024, Pubpub-ZZ +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * The name of the author may not be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +import struct +from abc import ABC, abstractmethod +from collections.abc import Generator, Iterable, Iterator, Mapping +from datetime import datetime +from typing import ( + Any, + NoReturn, + Optional, + Union, + cast, +) + +from ._encryption import Encryption +from ._page import PageObject, _VirtualList +from ._page_labels import index2label as page_index2page_label +from ._utils import ( + deprecation_with_replacement, + logger_warning, + parse_iso8824_date, +) +from .constants import CatalogAttributes as CA +from .constants import CatalogDictionary as CD +from .constants import ( + CheckboxRadioButtonAttributes, + Core, + GoToActionArguments, + PagesAttributes, + UserAccessPermissions, +) +from .constants import DocumentInformationAttributes as DI +from .constants import FieldDictionaryAttributes as FA +from .constants import PageAttributes as PG +from .errors import LimitReachedError, PdfReadError, PyPdfError +from .filters import _decompress_with_limit +from .generic import ( + ArrayObject, + BooleanObject, + ByteStringObject, + Destination, + DictionaryObject, + EncodedStreamObject, + Field, + Fit, + FloatObject, + IndirectObject, + NameObject, + NullObject, + NumberObject, + PdfObject, + TextStringObject, + TreeObject, + ViewerPreferences, + create_string_object, + is_null_or_none, +) +from .generic._files import EmbeddedFile +from .types import OutlineType, PagemodeType +from .xmp import XmpInformation + + +def convert_to_int(d: bytes, size: int) -> Union[int, tuple[Any, ...]]: + if size > 8: + raise PdfReadError("Invalid size in convert_to_int") + d = b"\x00\x00\x00\x00\x00\x00\x00\x00" + d + d = d[-8:] + return cast(int, struct.unpack(">Q", d)[0]) + + +class DocumentInformation(DictionaryObject): + """ + A class representing the basic document metadata provided in a PDF File. + This class is accessible through + :py:class:`PdfReader.metadata`. + + All text properties of the document metadata have + *two* properties, e.g. author and author_raw. The non-raw property will + always return a ``TextStringObject``, making it ideal for a case where the + metadata is being displayed. The raw property can sometimes return a + ``ByteStringObject``, if pypdf was unable to decode the string's text + encoding; this requires additional safety in the caller and therefore is not + as commonly accessed. + """ + + def __init__(self) -> None: + DictionaryObject.__init__(self) + + def _get_text(self, key: str) -> Optional[str]: + retval = self.get(key, None) + if isinstance(retval, TextStringObject): + return retval + if isinstance(retval, ByteStringObject): + return str(retval) + return None + + @property + def title(self) -> Optional[str]: + """ + Read-only property accessing the document's title. + + Returns a ``TextStringObject`` or ``None`` if the title is not + specified. + """ + return ( + self._get_text(DI.TITLE) or self.get(DI.TITLE).get_object() # type: ignore[union-attr] + if self.get(DI.TITLE) + else None + ) + + @property + def title_raw(self) -> Optional[str]: + """The "raw" version of title; can return a ``ByteStringObject``.""" + return self.get(DI.TITLE) + + @property + def author(self) -> Optional[str]: + """ + Read-only property accessing the document's author. + + Returns a ``TextStringObject`` or ``None`` if the author is not + specified. + """ + return self._get_text(DI.AUTHOR) + + @property + def author_raw(self) -> Optional[str]: + """The "raw" version of author; can return a ``ByteStringObject``.""" + return self.get(DI.AUTHOR) + + @property + def subject(self) -> Optional[str]: + """ + Read-only property accessing the document's subject. + + Returns a ``TextStringObject`` or ``None`` if the subject is not + specified. + """ + return self._get_text(DI.SUBJECT) + + @property + def subject_raw(self) -> Optional[str]: + """The "raw" version of subject; can return a ``ByteStringObject``.""" + return self.get(DI.SUBJECT) + + @property + def creator(self) -> Optional[str]: + """ + Read-only property accessing the document's creator. + + If the document was converted to PDF from another format, this is the + name of the application (e.g. OpenOffice) that created the original + document from which it was converted. Returns a ``TextStringObject`` or + ``None`` if the creator is not specified. + """ + return self._get_text(DI.CREATOR) + + @property + def creator_raw(self) -> Optional[str]: + """The "raw" version of creator; can return a ``ByteStringObject``.""" + return self.get(DI.CREATOR) + + @property + def producer(self) -> Optional[str]: + """ + Read-only property accessing the document's producer. + + If the document was converted to PDF from another format, this is the + name of the application (for example, macOS Quartz) that converted it to + PDF. Returns a ``TextStringObject`` or ``None`` if the producer is not + specified. + """ + return self._get_text(DI.PRODUCER) + + @property + def producer_raw(self) -> Optional[str]: + """The "raw" version of producer; can return a ``ByteStringObject``.""" + return self.get(DI.PRODUCER) + + @property + def creation_date(self) -> Optional[datetime]: + """Read-only property accessing the document's creation date.""" + return parse_iso8824_date(self._get_text(DI.CREATION_DATE)) + + @property + def creation_date_raw(self) -> Optional[str]: + """ + The "raw" version of creation date; can return a ``ByteStringObject``. + + Typically in the format ``D:YYYYMMDDhhmmss[+Z-]hh'mm`` where the suffix + is the offset from UTC. + """ + return self.get(DI.CREATION_DATE) + + @property + def modification_date(self) -> Optional[datetime]: + """ + Read-only property accessing the document's modification date. + + The date and time the document was most recently modified. + """ + return parse_iso8824_date(self._get_text(DI.MOD_DATE)) + + @property + def modification_date_raw(self) -> Optional[str]: + """ + The "raw" version of modification date; can return a + ``ByteStringObject``. + + Typically in the format ``D:YYYYMMDDhhmmss[+Z-]hh'mm`` where the suffix + is the offset from UTC. + """ + return self.get(DI.MOD_DATE) + + @property + def keywords(self) -> Optional[str]: + """ + Read-only property accessing the document's keywords. + + Returns a ``TextStringObject`` or ``None`` if keywords are not + specified. + """ + return self._get_text(DI.KEYWORDS) + + @property + def keywords_raw(self) -> Optional[str]: + """The "raw" version of keywords; can return a ``ByteStringObject``.""" + return self.get(DI.KEYWORDS) + + +class PdfDocCommon(ABC): + """ + Common functions from PdfWriter and PdfReader objects. + + This root class is strongly abstracted. + """ + + strict: bool = False # default + + flattened_pages: Optional[list[PageObject]] = None + + _encryption: Optional[Encryption] = None + + _readonly: bool = False + + @property + @abstractmethod + def root_object(self) -> DictionaryObject: + ... # pragma: no cover + + @property + @abstractmethod + def pdf_header(self) -> str: + ... # pragma: no cover + + @abstractmethod + def get_object( + self, indirect_reference: Union[int, IndirectObject] + ) -> Optional[PdfObject]: + ... # pragma: no cover + + @abstractmethod + def _replace_object(self, indirect: IndirectObject, obj: PdfObject) -> PdfObject: + ... # pragma: no cover + + @property + @abstractmethod + def _info(self) -> Optional[DictionaryObject]: + ... # pragma: no cover + + @property + def metadata(self) -> Optional[DocumentInformation]: + """ + Retrieve the PDF file's document information dictionary, if it exists. + + Note that some PDF files use metadata streams instead of document + information dictionaries, and these metadata streams will not be + accessed by this function. + """ + retval = DocumentInformation() + if self._info is None: + return None + retval.update(self._info) + return retval + + @property + @abstractmethod + def xmp_metadata(self) -> Optional[XmpInformation]: + ... # pragma: no cover + + @property + def viewer_preferences(self) -> Optional[ViewerPreferences]: + """Returns the existing ViewerPreferences as an overloaded dictionary.""" + o = self.root_object.get(CD.VIEWER_PREFERENCES, None) + if o is None: + return None + o = o.get_object() + if not isinstance(o, ViewerPreferences): + o = ViewerPreferences(o) + if hasattr(o, "indirect_reference") and o.indirect_reference is not None: + self._replace_object(o.indirect_reference, o) + else: + self.root_object[NameObject(CD.VIEWER_PREFERENCES)] = o + return o + + def get_num_pages(self) -> int: + """ + Calculate the number of pages in this PDF file. + + Returns: + The number of pages of the parsed PDF file. + + Raises: + PdfReadError: If restrictions prevent this action. + + """ + # Flattened pages will not work on an encrypted PDF; + # the PDF file's page count is used in this case. Otherwise, + # the original method (flattened page count) is used. + if self.is_encrypted: + return self.root_object["/Pages"]["/Count"] # type: ignore[no-any-return, index] + if self.flattened_pages is None: + self._flatten(self._readonly) + assert self.flattened_pages is not None + return len(self.flattened_pages) + + def get_page(self, page_number: int) -> PageObject: + """ + Retrieve a page by number from this PDF file. + Most of the time ``.pages[page_number]`` is preferred. + + Args: + page_number: The page number to retrieve + (pages begin at zero) + + Returns: + A :class:`PageObject` instance. + + """ + if self.flattened_pages is None: + self._flatten(self._readonly) + assert self.flattened_pages is not None, "mypy" + return self.flattened_pages[page_number] + + def _get_page_in_node( + self, + page_number: int, + ) -> tuple[DictionaryObject, int]: + """ + Retrieve the node and position within the /Kids containing the page. + If page_number is greater than the number of pages, it returns the top node, -1. + """ + top = cast(DictionaryObject, self.root_object["/Pages"]) + + def recursive_call( + node: DictionaryObject, mi: int + ) -> tuple[Optional[PdfObject], int]: + ma = cast(int, node.get("/Count", 1)) # default 1 for /Page types + if node["/Type"] == "/Page": # type: ignore[comparison-overlap] + if page_number == mi: + return node, -1 + return None, mi + 1 + if (page_number - mi) >= ma: # not in nodes below + if node == top: + return top, -1 + return None, mi + ma + for idx, kid in enumerate(cast(ArrayObject, node["/Kids"])): + kid = cast(DictionaryObject, kid.get_object()) + n, i = recursive_call(kid, mi) + if n is not None: # page has just been found ... + if i < 0: # ... just below! + return node, idx + # ... at lower levels + return n, i + mi = i + raise PyPdfError("Unexpectedly cannot find the node.") + + node, idx = recursive_call(top, 0) + assert isinstance(node, DictionaryObject), "mypy" + return node, idx + + @property + def named_destinations(self) -> dict[str, Destination]: + """A read-only dictionary which maps names to destinations.""" + return self._get_named_destinations() + + def get_named_dest_root(self) -> ArrayObject: + named_dest = ArrayObject() + if CA.NAMES in self.root_object and isinstance( + self.root_object[CA.NAMES], DictionaryObject + ): + names = cast(DictionaryObject, self.root_object[CA.NAMES]) + if CA.DESTS in names and isinstance(names[CA.DESTS], DictionaryObject): + # §3.6.3 Name Dictionary (PDF spec 1.7) + dests = cast(DictionaryObject, names[CA.DESTS]) + dests_ref = dests.indirect_reference + if CA.NAMES in dests: + # §7.9.6, entries in a name tree node dictionary + named_dest = cast(ArrayObject, dests[CA.NAMES]) + else: + named_dest = ArrayObject() + dests[NameObject(CA.NAMES)] = named_dest + elif hasattr(self, "_add_object"): + dests = DictionaryObject() + dests_ref = self._add_object(dests) + names[NameObject(CA.DESTS)] = dests_ref + dests[NameObject(CA.NAMES)] = named_dest + + elif hasattr(self, "_add_object"): + names = DictionaryObject() + names_ref = self._add_object(names) + self.root_object[NameObject(CA.NAMES)] = names_ref + dests = DictionaryObject() + dests_ref = self._add_object(dests) + names[NameObject(CA.DESTS)] = dests_ref + dests[NameObject(CA.NAMES)] = named_dest + + return named_dest + + ## common + def _get_named_destinations( + self, + *, + tree: Union[TreeObject, None] = None, + retval: Optional[dict[str, Destination]] = None, + visited: Optional[set[int]] = None, + ) -> dict[str, Destination]: + """ + Retrieve the named destinations present in the document. + + Args: + tree: The current tree. + retval: The previously retrieved destinations for nested calls. + visited: Already known/visited objects. + + Returns: + A dictionary which maps names to destinations. + + """ + if visited is None: + visited = set() + if retval is None: + retval = {} + catalog = self.root_object + + # get the name tree + if CA.DESTS in catalog: + tree = cast(TreeObject, catalog[CA.DESTS]) + elif CA.NAMES in catalog: + names = cast(DictionaryObject, catalog[CA.NAMES]) + if CA.DESTS in names: + tree = cast(TreeObject, names[CA.DESTS]) + + if is_null_or_none(tree): + return retval + assert tree is not None, "mypy" + + tree_id = id(tree) + if tree_id in visited: + logger_warning("Detected cycle in destination tree.", source=__name__) + return retval + visited.add(tree_id) + + if PagesAttributes.KIDS in tree: + # recurse down the tree + for kid in cast(ArrayObject, tree[PagesAttributes.KIDS]): + self._get_named_destinations(tree=kid.get_object(), retval=retval, visited=visited) + # §7.9.6, entries in a name tree node dictionary + elif CA.NAMES in tree: # /Kids and /Names are exclusives (§7.9.6) + names = cast(DictionaryObject, tree[CA.NAMES]) + i = 0 + while i < len(names): + key = names[i].get_object() + i += 1 + if not isinstance(key, (bytes, str)): + continue + try: + value = names[i].get_object() + except IndexError: + break + i += 1 + if isinstance(value, DictionaryObject): + if "/D" in value: + value = value["/D"] + else: + continue + dest = self._build_destination(key, value) + if dest is not None: + retval[cast(str, dest["/Title"])] = dest + # Remain backwards-compatible. + retval[str(key)] = dest + else: # case where /Dests is in the document's catalog dictionary (PDF 1.7 specs, §2 about PDF 1.1) + for k__, v__ in tree.items(): + val = v__.get_object() + if isinstance(val, DictionaryObject): + if "/D" in val: + val = val["/D"].get_object() + else: + continue + dest = self._build_destination(k__, val) + if dest is not None: + retval[k__] = dest + return retval + + # A select group of relevant field attributes. For the complete list, + # see §12.3.2 of the PDF 1.7 or PDF 2.0 specification. + + def get_fields( + self, + tree: Optional[TreeObject] = None, + retval: Optional[dict[Any, Any]] = None, + fileobj: Optional[Any] = None, + stack: Optional[list[PdfObject]] = None, + ) -> Optional[dict[str, Any]]: + """ + Extract field data if this PDF contains interactive form fields. + + The *tree*, *retval*, *stack* parameters are for recursive use. + + Args: + tree: Current object to parse. + retval: In-progress list of fields. + fileobj: A file object (usually a text file) to write + a report to on all interactive form fields found. + stack: List of already parsed objects. + + Returns: + A dictionary where each key is a field name, and each + value is a :class:`Field` object. By + default, the mapping name is used for keys. + ``None`` if form data could not be located. + + """ + field_attributes = FA.attributes_dict() + field_attributes.update(CheckboxRadioButtonAttributes.attributes_dict()) + if retval is None: + retval = {} + catalog = self.root_object + stack = [] + # get the AcroForm tree + if CD.ACRO_FORM in catalog: + tree = cast(Optional[TreeObject], catalog[CD.ACRO_FORM]) + else: + return None + if tree is None: + return retval + assert stack is not None + if "/Fields" in tree: + fields = cast(ArrayObject, tree["/Fields"]) + for f in fields: + field = f.get_object() + self._build_field(field, retval, fileobj, field_attributes, stack) + elif any(attr in tree for attr in field_attributes): + # Tree is a field + self._build_field(tree, retval, fileobj, field_attributes, stack) + return retval + + def _get_qualified_field_name( + self, + *, + parent: DictionaryObject, + visited: Optional[set[int]] = None + ) -> str: + if visited is None: + visited = set() + parent_id = id(parent) + if parent_id in visited: + raise LimitReachedError("Detected cycle in /Parent hierarchy when retrieving qualified field name.") + visited.add(parent_id) + + if "/TM" in parent: + return cast(str, parent["/TM"]) + if "/Parent" in parent: + return ( + self._get_qualified_field_name( + parent=cast(DictionaryObject, parent["/Parent"]), + visited=visited, + ) + + "." + + cast(str, parent.get("/T", "")) + ) + return cast(str, parent.get("/T", "")) + + @staticmethod + def _normal_appearance(appearance: Any) -> DictionaryObject: + """Return the /N normal-appearance sub-dictionary of an /AP entry.""" + appearance = appearance.get_object() + if not isinstance(appearance, DictionaryObject): + raise PdfReadError(f"Expected appearance dictionary, got {appearance!r}") + normal = appearance.get("/N") + if normal is not None: + normal = normal.get_object() + if not isinstance(normal, DictionaryObject): + raise PdfReadError(f"Expected /N appearance dictionary, got {normal!r}") + return normal + + def _build_field( + self, + field: Union[TreeObject, DictionaryObject], + retval: dict[Any, Any], + fileobj: Any, + field_attributes: Any, + stack: list[PdfObject], + ) -> None: + if all(attr not in field for attr in ("/T", "/TM")): + return + key = self._get_qualified_field_name(parent=field) + if fileobj: + self._write_field(fileobj, field, field_attributes) + fileobj.write("\n") + retval[key] = Field(field) + obj = retval[key].indirect_reference.get_object() # to get the full object + if obj.get(FA.FT, "") == "/Ch" and obj.get(NameObject(FA.Opt)): + retval[key][NameObject("/_States_")] = obj[NameObject(FA.Opt)] + if obj.get(FA.FT, "") == "/Btn" and "/AP" in obj: + # Checkbox + normal = self._normal_appearance(obj["/AP"]) + retval[key][NameObject("/_States_")] = ArrayObject(list(normal.keys())) + if "/Off" not in retval[key]["/_States_"]: + retval[key][NameObject("/_States_")].append(NameObject("/Off")) + elif obj.get(FA.FT, "") == "/Btn" and obj.get(FA.Ff, 0) & FA.FfBits.Radio != 0: + states: list[str] = [] + retval[key][NameObject("/_States_")] = ArrayObject(states) + for k in obj.get(FA.Kids, {}): + k = k.get_object() + if "/AP" not in k: + raise PdfReadError(f"Button field kid missing /AP: {k!r}") + normal = self._normal_appearance(k["/AP"]) + for s in list(normal.keys()): + if s not in states: + states.append(s) + retval[key][NameObject("/_States_")] = ArrayObject(states) + if ( + obj.get(FA.Ff, 0) & FA.FfBits.NoToggleToOff != 0 + and "/Off" in retval[key]["/_States_"] + ): + del retval[key]["/_States_"][retval[key]["/_States_"].index("/Off")] + # at last for order + self._check_kids(field, retval, fileobj, stack) + + def _check_kids( + self, + tree: Union[TreeObject, DictionaryObject], + retval: Any, + fileobj: Any, + stack: list[PdfObject], + ) -> None: + if tree in stack: + logger_warning( + "%(field_name)s already parsed", + source=__name__, + field_name=self._get_qualified_field_name(parent=tree), + ) + return + stack.append(tree) + if PagesAttributes.KIDS in tree: + # recurse down the tree + for kid in tree[PagesAttributes.KIDS]: # type: ignore[attr-defined] + kid = kid.get_object() + self.get_fields(kid, retval, fileobj, stack) + + def _write_field(self, fileobj: Any, field: Any, field_attributes: Any) -> None: + field_attributes_tuple = FA.attributes() + field_attributes_tuple = ( + field_attributes_tuple + CheckboxRadioButtonAttributes.attributes() + ) + + for attr in field_attributes_tuple: + if attr in ( + FA.Kids, + FA.AA, + ): + continue + attr_name = field_attributes[attr] + try: + if attr == FA.FT: + # Make the field type value clearer + types = { + "/Btn": "Button", + "/Tx": "Text", + "/Ch": "Choice", + "/Sig": "Signature", + } + if field[attr] in types: + fileobj.write(f"{attr_name}: {types[field[attr]]}\n") + elif attr == FA.Parent: + # Let's just write the name of the parent + try: + name = field[attr][FA.TM] + except KeyError: + name = field[attr][FA.T] + fileobj.write(f"{attr_name}: {name}\n") + else: + fileobj.write(f"{attr_name}: {field[attr]}\n") + except KeyError: + # Field attribute is N/A or unknown, so don't write anything + pass + + def get_form_text_fields(self, full_qualified_name: bool = False) -> dict[str, Any]: + """ + Retrieve form fields from the document with textual data. + + Args: + full_qualified_name: to get full name + + Returns: + A dictionary. The key is the name of the form field, + the value is the content of the field. + + If the document contains multiple form fields with the same name, the + second and following will get the suffix .2, .3, ... + + """ + + def indexed_key(k: str, fields: dict[Any, Any]) -> str: + if k not in fields: + return k + return ( + k + + "." + + str(sum(1 for kk in fields if kk.startswith(k + ".")) + 2) + ) + + # Retrieve document form fields + form_fields = self.get_fields() + if form_fields is None: + return {} + ff = {} + for field, value in form_fields.items(): + if value.get("/FT") == "/Tx": + if full_qualified_name: + ff[field] = value.get("/V") + else: + ff[indexed_key(cast(str, value.get("/T", field)), ff)] = value.get("/V") + return ff + + def get_pages_showing_field( + self, field: Union[Field, PdfObject, IndirectObject] + ) -> list[PageObject]: + """ + Provides list of pages where the field is called. + + Args: + field: Field Object, PdfObject or IndirectObject referencing a Field + + Returns: + List of pages: + - Empty list: + The field has no widgets attached + (either hidden field or ancestor field). + - Single page list: + Page where the widget is present + (most common). + - Multi-page list: + Field with multiple kids widgets + (example: radio buttons, field repeated on multiple pages). + + """ + try: + # to cope with all types + field = cast(DictionaryObject, field.indirect_reference.get_object()) # type: ignore[union-attr] + except Exception as exc: + raise ValueError("Field type is invalid") from exc + if is_null_or_none(field.get_inherited(key="/FT", default=None)): + raise ValueError("Field is not valid") + ret = [] + if field.get("/Subtype", "") == "/Widget": + if "/P" in field: + ret = [field["/P"].get_object()] + else: + ret = [ + p + for p in self.pages + if field.indirect_reference in p.get("/Annots", "") + ] + else: + kids = field.get("/Kids", ()) + for k in kids: + k = k.get_object() + if (k.get("/Subtype", "") == "/Widget") and ("/T" not in k): + # Kid that is just a widget, not a field: + if "/P" in k: + ret += [k["/P"].get_object()] + else: + ret += [ + p + for p in self.pages + if k.indirect_reference in p.get("/Annots", "") + ] + return [ + x + if isinstance(x, PageObject) + else (self.pages[self._get_page_number_by_indirect(x.indirect_reference)]) # type: ignore[index, union-attr] + for x in ret + ] + + @property + def open_destination( + self, + ) -> Union[Destination, TextStringObject, ByteStringObject, None]: + """ + Property to access the opening destination (``/OpenAction`` entry in + the PDF catalog). It returns ``None`` if the entry does not exist + or is not set. + + Raises: + Exception: If a destination is invalid. + + """ + if "/OpenAction" not in self.root_object: + return None + oa: Any = self.root_object["/OpenAction"] + if isinstance(oa, bytes): # pragma: no cover + oa = oa.decode() + if isinstance(oa, str): + return create_string_object(oa) + if isinstance(oa, ArrayObject): + try: + page, typ, *array = oa + fit = Fit(typ, tuple(array)) + return Destination("OpenAction", page, fit) + except Exception as exc: + raise Exception(f"Invalid Destination {oa}: {exc}") + else: + return None + + @open_destination.setter + def open_destination(self, dest: Union[str, Destination, PageObject, None]) -> None: + raise NotImplementedError("No setter for open_destination") + + @property + def outline(self) -> OutlineType: + """ + Read-only property for the outline present in the document + (i.e., a collection of 'outline items' which are also known as + 'bookmarks'). + """ + return self._get_outline() + + def _get_outline( + self, + node: Optional[DictionaryObject] = None, + outline: Optional[Any] = None, + visited: Optional[set[int]] = None, + ) -> OutlineType: + if outline is None: + outline = [] + catalog = self.root_object + + # get the outline dictionary and named destinations + if Core.OUTLINES in catalog: + lines = cast(DictionaryObject, catalog[Core.OUTLINES]) + + if isinstance(lines, NullObject): + return outline + + # §12.3.3 Document outline, entries in the outline dictionary + if not is_null_or_none(lines) and "/First" in lines: + node = cast(DictionaryObject, lines["/First"]) + self._named_destinations = self._get_named_destinations() + + if node is None: + return outline + + # see if there are any more outline items + if visited is None: + visited = set() + while True: + node_id = id(node) + if node_id in visited: + logger_warning("Detected cycle in outline structure for %(node)s", source=__name__, node=node) + break + visited.add(node_id) + + outline_obj = self._build_outline_item(node) + if outline_obj: + outline.append(outline_obj) + + # check for sub-outline + if "/First" in node: + sub_outline: list[Any] = [] + # Pass a copy to allow multiple outer entries to reference the same inner one. + inner_visited = visited.copy() + self._get_outline( + node=cast(DictionaryObject, node["/First"]), + outline=sub_outline, + visited=inner_visited, + ) + if sub_outline: + outline.append(sub_outline) + + if "/Next" not in node: + break + node = cast(DictionaryObject, node["/Next"]) + + return outline + + @property + def threads(self) -> Optional[ArrayObject]: + """ + Read-only property for the list of threads. + + See §12.4.3 from the PDF 1.7 or 2.0 specification. + + It is an array of dictionaries with "/F" (the first bead in the thread) + and "/I" (a thread information dictionary containing information about + the thread, such as its title, author, and creation date) properties or + None if there are no articles. + + Since PDF 2.0 it can also contain an indirect reference to a metadata + stream containing information about the thread, such as its title, + author, and creation date. + """ + catalog = self.root_object + if Core.THREADS in catalog: + return cast("ArrayObject", catalog[Core.THREADS]) + return None + + @abstractmethod + def _get_page_number_by_indirect( + self, indirect_reference: Union[int, NullObject, IndirectObject, None] + ) -> Optional[int]: + ... # pragma: no cover + + def get_page_number(self, page: PageObject) -> Optional[int]: + """ + Retrieve page number of a given PageObject. + + Args: + page: The page to get page number. Should be + an instance of :class:`PageObject` + + Returns: + The page number or None if page is not found + + """ + return self._get_page_number_by_indirect(page.indirect_reference) + + def get_destination_page_number(self, destination: Destination) -> Optional[int]: + """ + Retrieve page number of a given Destination object. + + Args: + destination: The destination to get page number. + + Returns: + The page number or None if page is not found + + """ + return self._get_page_number_by_indirect(destination.page) + + def _build_destination( + self, + title: Union[str, bytes], + array: Optional[ + list[ + Union[NumberObject, IndirectObject, NullObject, DictionaryObject, None] + ] + ], + ) -> Destination: + page, typ = None, None + # handle outline items with missing or invalid destination + if ( + isinstance(array, (NullObject, str)) + or (isinstance(array, ArrayObject) and len(array) < 2) + or array is None + ): + page = NullObject() + return Destination(title, page, Fit.fit()) + page, typ, *array = array # type: ignore[assignment] + try: + return Destination(title, page, Fit(fit_type=typ, fit_args=array)) # type: ignore[arg-type] + except PdfReadError: + logger_warning("Unknown destination: %(title)r %(array)s", source=__name__, title=title, array=array) + if self.strict: + raise + # create a link to first Page + tmp = self.pages[0].indirect_reference + indirect_reference = NullObject() if tmp is None else tmp + return Destination(title, indirect_reference, Fit.fit()) + + def _build_outline_item(self, node: DictionaryObject) -> Optional[Destination]: + dest, title, outline_item = None, None, None + + # title required for valid outline + # §12.3.3, entries in an outline item dictionary + try: + title = cast("str", node["/Title"]) + except KeyError: + if self.strict: + raise PdfReadError(f"Outline Entry Missing /Title attribute: {node!r}") + title = "" + + if "/A" in node: + # Action, PDF 1.7 and PDF 2.0 §12.6 (only type GoTo supported) + action = cast(DictionaryObject, node["/A"]) + action_type = cast(NameObject, action[GoToActionArguments.S]) + if action_type == "/GoTo": + if GoToActionArguments.D in action: + dest = action[GoToActionArguments.D] + elif self.strict: + raise PdfReadError(f"Outline Action Missing /D attribute: {node!r}") + elif "/Dest" in node: + # Destination, PDF 1.7 and PDF 2.0 §12.3.2 + dest = node["/Dest"] + # if array was referenced in another object, will be a dict w/ key "/D" + if isinstance(dest, DictionaryObject) and "/D" in dest: + dest = dest["/D"] + + if isinstance(dest, ArrayObject): + outline_item = self._build_destination(title, dest) + elif isinstance(dest, str): + # named destination, addresses NameObject Issue #193 + # TODO: Keep named destination instead of replacing it? + try: + outline_item = self._build_destination( + title, self._named_destinations[dest].dest_array + ) + except KeyError: + # named destination not found in Name Dict + outline_item = self._build_destination(title, None) + elif dest is None: + # outline item not required to have destination or action + # PDFv1.7 Table 153 + outline_item = self._build_destination(title, dest) + else: + if self.strict: + raise PdfReadError(f"Unexpected destination {dest!r}") + logger_warning( + "Removed unexpected destination %(dest)r from destination", + source=__name__, + dest=dest, + ) + outline_item = self._build_destination(title, None) + + # if outline item created, add color, format, and child count if present + if outline_item: + if "/C" in node: + # Color of outline item font in (R, G, B) with values ranging 0.0-1.0 + color = node["/C"] + if isinstance(color, list): + outline_item[NameObject("/C")] = ArrayObject(FloatObject(c) for c in color) + else: + logger_warning( + "Ignoring non-array outline color %(color)r", + source=__name__, + color=color, + ) + if "/F" in node: + # specifies style characteristics bold and/or italic + # with 1=italic, 2=bold, 3=both + outline_item[NameObject("/F")] = node["/F"] + if "/Count" in node: + # absolute value = num. visible children + # with positive = open/unfolded, negative = closed/folded + outline_item[NameObject("/Count")] = node["/Count"] + # if count is 0 we will consider it as open (to have available is_open) + outline_item[NameObject("/%is_open%")] = BooleanObject( + node.get("/Count", 0) >= 0 + ) + outline_item.node = node + try: + outline_item.indirect_reference = node.indirect_reference + except AttributeError: + pass + return outline_item + + @property + def pages(self) -> list[PageObject]: + """ + Property that emulates a list of :class:`PageObject`. + This property allows to get a page or a range of pages. + + Note: + For PdfWriter only: Provides the capability to remove a page/range of + page from the list (using the del operator). Remember: Only the page + entry is removed, as the objects beneath can be used elsewhere. A + solution to completely remove them - if they are not used anywhere - is + to write to a buffer/temporary file and then load it into a new + PdfWriter. + + """ + return _VirtualList(self.get_num_pages, self.get_page) # type: ignore[return-value] + + @property + def page_labels(self) -> list[str]: + """ + A list of labels for the pages in this document. + + This property is read-only. The labels are in the order that the pages + appear in the document. + """ + return [page_index2page_label(self, i) for i in range(len(self.pages))] + + @property + def page_layout(self) -> Optional[str]: + """ + Get the page layout currently being used. + + .. list-table:: Valid ``layout`` values + :widths: 50 200 + + * - /NoLayout + - Layout explicitly not specified + * - /SinglePage + - Show one page at a time + * - /OneColumn + - Show one column at a time + * - /TwoColumnLeft + - Show pages in two columns, odd-numbered pages on the left + * - /TwoColumnRight + - Show pages in two columns, odd-numbered pages on the right + * - /TwoPageLeft + - Show two pages at a time, odd-numbered pages on the left + * - /TwoPageRight + - Show two pages at a time, odd-numbered pages on the right + """ + try: + return cast(NameObject, self.root_object[CD.PAGE_LAYOUT]) + except KeyError: + return None + + @property + def page_mode(self) -> Optional[PagemodeType]: + """ + Get the page mode currently being used. + + .. list-table:: Valid ``mode`` values + :widths: 50 200 + + * - /UseNone + - Do not show outline or thumbnails panels + * - /UseOutlines + - Show outline (aka bookmarks) panel + * - /UseThumbs + - Show page thumbnails panel + * - /FullScreen + - Fullscreen view + * - /UseOC + - Show Optional Content Group (OCG) panel + * - /UseAttachments + - Show attachments panel + """ + try: + return self.root_object["/PageMode"] # type: ignore[return-value] + except KeyError: + return None + + def _flatten( + self, + list_only: bool = False, + pages: Union[DictionaryObject, PageObject, None] = None, + inherit: Optional[dict[str, Any]] = None, + indirect_reference: Optional[IndirectObject] = None, + visited: Optional[set[int]] = None, + ) -> None: + """ + Process the document pages to ease searching. + + Attributes of a page may inherit from ancestor nodes + in the page tree. Flattening means moving + any inheritance data into descendant nodes, + effectively removing the inheritance dependency. + + Note: It is distinct from another use of "flattening" applied to PDFs. + Flattening a PDF also means combining all the contents into one single layer + and making the file less editable. + + Args: + list_only: Will only list the pages within _flatten_pages. + pages: + inherit: + indirect_reference: Used recursively to flatten the /Pages object. + visited: Set of id() values of /Pages nodes already visited during + traversal. Detects multi-hop cycles such as A→B→C→A that the + single-parent check misses. + + """ + inheritable_page_attributes = ( + NameObject(PG.RESOURCES), + NameObject(PG.MEDIABOX), + NameObject(PG.CROPBOX), + NameObject(PG.ROTATE), + ) + if inherit is None: + inherit = {} + if visited is None: + visited = set() + if is_null_or_none(pages): + # Fix issue 327: set flattened_pages attribute only for + # decrypted file + catalog = self.root_object + pages = catalog.get("/Pages").get_object() # type: ignore[union-attr] + if not isinstance(pages, DictionaryObject): + raise PdfReadError("Invalid object in /Pages") + self.flattened_pages = [] + assert pages is not None, "mypy" + + if PagesAttributes.TYPE in pages: + t = cast(str, pages[PagesAttributes.TYPE]) + # if the page tree node has no /Type, consider as a page if /Kids is also missing + elif PagesAttributes.KIDS not in pages: + t = "/Page" + else: + t = "/Pages" + + if t == "/Pages": + for attr in inheritable_page_attributes: + if attr in pages: + inherit[attr] = pages[attr] + pages_reference = getattr(pages, "indirect_reference", object()) + kids = pages.get(PagesAttributes.KIDS, ArrayObject()).get_object() + if isinstance(kids, NullObject): + kids = ArrayObject() + elif not isinstance(kids, ArrayObject): + raise PdfReadError( + f"Expected /Kids to be an array, got {type(kids).__name__}." + ) + for page in kids: + if getattr(page, "indirect_reference", object()) == pages_reference: + raise PdfReadError("Detected cyclic page references.") + + additional_arguments = {} + if isinstance(page, IndirectObject): + additional_arguments["indirect_reference"] = page + obj = page.get_object() + if obj: + # damaged file may have invalid child in /Pages + obj_id = id(obj) + if obj_id in visited: + raise PdfReadError("Detected cyclic page references.") + visited.add(obj_id) + self._flatten(list_only, obj, inherit, visited=visited, **additional_arguments) + elif t == "/Page": + for attr_in, value in inherit.items(): + # if the page has its own value, it does not inherit the + # parent's value + if attr_in not in pages: + pages[attr_in] = value + page_obj = PageObject(self, indirect_reference) + if not list_only: + page_obj.update(pages) + + # TODO: Could flattened_pages be None at this point? + self.flattened_pages.append(page_obj) # type: ignore[union-attr] + + def remove_page( + self, + page: Union[int, PageObject, IndirectObject], + clean: bool = False, + ) -> None: + """ + Remove page from pages list. + + Args: + page: + * :class:`int`: Page number to be removed. + * :class:`~pypdf._page.PageObject`: page to be removed. If the page appears many times + only the first one will be removed. + * :class:`~pypdf.generic.IndirectObject`: Reference to page to be removed. + + clean: replace PageObject with NullObject to prevent annotations + or destinations to reference a detached page. + + """ + if self.flattened_pages is None: + self._flatten(self._readonly) + assert self.flattened_pages is not None + if isinstance(page, IndirectObject): + p = page.get_object() + if not isinstance(p, PageObject): + logger_warning("IndirectObject is not referencing a page", source=__name__) + return + page = p + + if not isinstance(page, int): + try: + page = self.flattened_pages.index(page) + except ValueError: + logger_warning("Cannot find page in pages", source=__name__) + return + if not (0 <= page < len(self.flattened_pages)): + logger_warning("Page number is out of range", source=__name__) + return + + ind = self.pages[page].indirect_reference + del self.pages[page] + if clean and ind is not None: + self._replace_object(ind, NullObject()) + + def _get_indirect_object(self, num: int, gen: int) -> Optional[PdfObject]: + """ + Used to ease development. + + This is equivalent to generic.IndirectObject(num,gen,self).get_object() + + Args: + num: The object number of the indirect object. + gen: The generation number of the indirect object. + + Returns: + A PdfObject + + """ + return IndirectObject(num, gen, self).get_object() + + def decode_permissions( + self, permissions_code: int + ) -> NoReturn: # pragma: no cover + """Take the permissions as an integer, return the allowed access.""" + deprecation_with_replacement( + old_name="decode_permissions", + new_name="user_access_permissions", + removed_in="5.0.0", + ) + + @property + def user_access_permissions(self) -> Optional[UserAccessPermissions]: + """ + Get the user access permissions for encrypted documents. + Returns None if not encrypted. + + .. warning:: + + For AES-256 encrypted documents (R=5/R=6), the returned + permissions are derived from the ``/P`` field, which is + only trustworthy if the ``/Perms`` integrity check passed. + Check :attr:`are_permissions_valid` to verify. + """ + if self._encryption is None: + return None + return UserAccessPermissions(self._encryption.P) + + @property + def are_permissions_valid(self) -> Optional[bool]: + """ + Whether the ``/Perms`` integrity check passed for this document. + + For AES-256 encrypted documents (R=5/R=6), the ``/Perms`` field + is an encrypted copy of the permissions that can be verified + independently. Returns ``False`` if this check fails (the ``/P`` + permissions may have been tampered with). + + Returns ``None`` if the document is not encrypted or has not yet + been decrypted via :meth:`decrypt()`. + Returns ``True`` for non-AES-256 encryption (no ``/Perms`` to check). + """ + if self._encryption is None: + return None + if not self._encryption.is_decrypted(): + return None + return self._encryption._are_permissions_valid + + @property + @abstractmethod + def is_encrypted(self) -> bool: + """ + Read-only boolean property showing whether this PDF file is encrypted. + + Note that this property, if true, will remain true even after the + :meth:`decrypt()` method is called. + """ + ... # pragma: no cover + + @property + def xfa(self) -> Optional[dict[str, Any]]: + retval: dict[str, Any] = {} + catalog = self.root_object + + if "/AcroForm" not in catalog or not catalog["/AcroForm"]: + return None + + tree = cast(TreeObject, catalog["/AcroForm"]) + + if "/XFA" in tree: + fields = cast(ArrayObject, tree["/XFA"]) + i = iter(fields) + for f in i: + tag = f + f = next(i) + if isinstance(f, IndirectObject): + field = cast(Optional[EncodedStreamObject], f.get_object()) + if field: + es = _decompress_with_limit(field._data) + retval[tag] = es + return retval + + @property + def attachments(self) -> Mapping[str, list[bytes]]: + """Mapping of attachment filenames to their content.""" + return LazyDict( + { + name: (self._get_attachment_list, name) + for name in self._list_attachments() + } + ) + + @property + def attachment_list(self) -> Generator[EmbeddedFile, None, None]: + """Iterable of attachment objects.""" + yield from EmbeddedFile._load(self.root_object) + + def _list_attachments(self) -> list[str]: + """ + Retrieves the list of filenames of file attachments. + + Returns: + list of filenames + + """ + names = [] + for entry in self.attachment_list: + names.append(entry.name) + if (name := entry.alternative_name) != entry.name and name: + names.append(name) + return names + + def _get_attachment_list(self, name: str) -> list[bytes]: + out = self._get_attachments(name)[name] + if isinstance(out, list): + return out + return [out] + + def _get_attachments( + self, filename: Optional[str] = None + ) -> dict[str, Union[bytes, list[bytes]]]: + """ + Retrieves all or selected file attachments of the PDF as a dictionary of file names + and the file data as a bytestring. + + Args: + filename: If filename is None, then a dictionary of all attachments + will be returned, where the key is the filename and the value + is the content. Otherwise, a dictionary with just a single key + - the filename - and its content will be returned. + + Returns: + dictionary of filename -> Union[bytestring or List[ByteString]] + If the filename exists multiple times a list of the different versions will be provided. + + """ + attachments: dict[str, Union[bytes, list[bytes]]] = {} + for entry in self.attachment_list: + names = set() + alternative_name = entry.alternative_name + if filename is not None: + if filename in {entry.name, alternative_name}: + name = entry.name if filename == entry.name else alternative_name + names.add(name) + else: + continue + else: + names = {entry.name, alternative_name} + + for name in names: + if name is None: + continue + if name in attachments: + if not isinstance(attachments[name], list): + attachments[name] = [attachments[name]] # type:ignore + attachments[name].append(entry.content) # type:ignore + else: + attachments[name] = entry.content + return attachments + + @abstractmethod + def _repr_mimebundle_( + self, + include: Union[Iterable[str], None] = None, + exclude: Union[Iterable[str], None] = None, + ) -> dict[str, Any]: + """ + Integration into Jupyter Notebooks. + + This method returns a dictionary that maps a mime-type to its + representation. + + .. seealso:: + + https://ipython.readthedocs.io/en/stable/config/integrating.html + """ + ... # pragma: no cover + + +class LazyDict(Mapping[Any, Any]): + def __init__(self, *args: Any, **kwargs: Any) -> None: + self._raw_dict = dict(*args, **kwargs) + + def __getitem__(self, key: str) -> Any: + func, arg = self._raw_dict.__getitem__(key) + return func(arg) + + def __iter__(self) -> Iterator[Any]: + return iter(self._raw_dict) + + def __len__(self) -> int: + return len(self._raw_dict) + + def __str__(self) -> str: + return f"LazyDict(keys={list(self.keys())})" diff --git a/.venv/lib/python3.13/site-packages/pypdf/_encryption.py b/.venv/lib/python3.13/site-packages/pypdf/_encryption.py new file mode 100644 index 0000000000000000000000000000000000000000..08a71b3079e6ba53b1edf02c5f579d7131b0fe5d --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/_encryption.py @@ -0,0 +1,1305 @@ +# Copyright (c) 2022, exiledkingcc +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * The name of the author may not be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +import hashlib +import secrets +import stringprep +import struct +import unicodedata +from enum import Enum, IntEnum +from typing import Any, Optional, Union, cast + +from pypdf._crypt_providers import ( + CryptAES, + CryptBase, + CryptIdentity, + CryptRC4, + aes_cbc_decrypt, + aes_cbc_encrypt, + aes_ecb_decrypt, + aes_ecb_encrypt, + rc4_decrypt, + rc4_encrypt, +) + +from ._utils import logger_warning +from .generic import ( + ArrayObject, + ByteStringObject, + DictionaryObject, + NameObject, + NumberObject, + PdfObject, + StreamObject, + TextStringObject, + create_string_object, +) + + +class CryptFilter: + def __init__( + self, + stm_crypt: CryptBase, + str_crypt: CryptBase, + ef_crypt: CryptBase, + ) -> None: + self.stm_crypt = stm_crypt + self.str_crypt = str_crypt + self.ef_crypt = ef_crypt + + def encrypt_object(self, obj: PdfObject) -> PdfObject: + if isinstance(obj, ByteStringObject): + data = self.str_crypt.encrypt(obj.original_bytes) + obj = ByteStringObject(data) + elif isinstance(obj, TextStringObject): + data = self.str_crypt.encrypt(obj.get_encoded_bytes()) + obj = ByteStringObject(data) + elif isinstance(obj, StreamObject): + obj2 = StreamObject() + obj2.update(obj) + obj2.set_data(self.stm_crypt.encrypt(obj._data)) + for key, value in obj.items(): # Don't forget the Stream dict. + obj2[key] = self.encrypt_object(value) + obj = obj2 + elif isinstance(obj, DictionaryObject): + obj2 = DictionaryObject() # type: ignore[assignment] + for key, value in obj.items(): + obj2[key] = self.encrypt_object(value) + obj = obj2 + elif isinstance(obj, ArrayObject): + obj = ArrayObject(self.encrypt_object(x) for x in obj) + return obj + + def decrypt_object(self, obj: PdfObject, *, strict: bool = True) -> PdfObject: + if isinstance(obj, (ByteStringObject, TextStringObject)): + data = self.str_crypt.decrypt(obj.original_bytes, strict=strict) + obj = create_string_object(data) + elif isinstance(obj, StreamObject): + obj._data = self.stm_crypt.decrypt(obj._data, strict=strict) + for key, value in obj.items(): # Don't forget the Stream dict. + obj[key] = self.decrypt_object(value, strict=strict) + elif isinstance(obj, DictionaryObject): + for key, value in obj.items(): + obj[key] = self.decrypt_object(value, strict=strict) + elif isinstance(obj, ArrayObject): + for i in range(len(obj)): + obj[i] = self.decrypt_object(obj[i], strict=strict) + return obj + + +_PADDING = ( + b"\x28\xbf\x4e\x5e\x4e\x75\x8a\x41\x64\x00\x4e\x56\xff\xfa\x01\x08" + b"\x2e\x2e\x00\xb6\xd0\x68\x3e\x80\x2f\x0c\xa9\xfe\x64\x53\x69\x7a" +) + + +def _padding(data: bytes) -> bytes: + return (data + _PADDING)[:32] + + +# Module-level constant for SASLprep prohibited character checks (RFC 4013 §2.3) +_SASLPREP_PROHIBITED_CHECKS = ( + (stringprep.in_table_c12, "non-ASCII space character"), + (stringprep.in_table_c21, "ASCII control character"), + (stringprep.in_table_c22, "non-ASCII control character"), + (stringprep.in_table_c3, "private use character"), + (stringprep.in_table_c4, "non-character code point"), + (stringprep.in_table_c5, "surrogate code point"), + (stringprep.in_table_c6, "inappropriate for plain text"), + (stringprep.in_table_c7, "inappropriate for canonical representation"), + (stringprep.in_table_c8, "change display properties/deprecated"), + (stringprep.in_table_c9, "tagging character"), + (stringprep.in_table_a1, "unassigned code point"), +) + + +class AlgV4: + @staticmethod + def compute_key( + password: bytes, + rev: int, + key_size: int, + o_entry: bytes, + P: int, + id1_entry: bytes, + metadata_encrypted: bool, + ) -> bytes: + """ + Algorithm 2: Computing an encryption key. + + a) Pad or truncate the password string to exactly 32 bytes. If the + password string is more than 32 bytes long, + use only its first 32 bytes; if it is less than 32 bytes long, pad it + by appending the required number of + additional bytes from the beginning of the following padding string: + < 28 BF 4E 5E 4E 75 8A 41 64 00 4E 56 FF FA 01 08 + 2E 2E 00 B6 D0 68 3E 80 2F 0C A9 FE 64 53 69 7A > + That is, if the password string is n bytes long, append + the first 32 - n bytes of the padding string to the end + of the password string. If the password string is empty + (zero-length), meaning there is no user password, + substitute the entire padding string in its place. + b) Initialize the MD5 hash function and pass the result of step (a) + as input to this function. + c) Pass the value of the encryption dictionary’s O entry to the + MD5 hash function. ("Algorithm 3: Computing + the encryption dictionary’s O (owner password) value" shows how the + O value is computed.) + d) Convert the integer value of the P entry to a 32-bit unsigned binary + number and pass these bytes to the + MD5 hash function, low-order byte first. + e) Pass the first element of the file’s file identifier array (the value + of the ID entry in the document’s trailer + dictionary; see Table 15) to the MD5 hash function. + f) (Security handlers of revision 4 or greater) If document metadata is + not being encrypted, pass 4 bytes with + the value 0xFFFFFFFF to the MD5 hash function. + g) Finish the hash. + h) (Security handlers of revision 3 or greater) Do the following + 50 times: Take the output from the previous + MD5 hash and pass the first n bytes of the output as input into a new + MD5 hash, where n is the number of + bytes of the encryption key as defined by the value of the encryption + dictionary’s Length entry. + i) Set the encryption key to the first n bytes of the output from the + final MD5 hash, where n shall always be 5 + for security handlers of revision 2 but, for security handlers of + revision 3 or greater, shall depend on the + value of the encryption dictionary’s Length entry. + + Args: + password: The encryption secret as a bytes-string + rev: The encryption revision (see PDF standard) + key_size: The size of the key in bytes + o_entry: The owner entry + P: A set of flags specifying which operations shall be permitted + when the document is opened with user access. If bit 2 is set to 1, + all other bits are ignored and all operations are permitted. + If bit 2 is set to 0, permission for operations are based on the + values of the remaining flags defined in Table 24. + id1_entry: + metadata_encrypted: A boolean indicating if the metadata is encrypted. + + Returns: + The u_hash digest of length key_size + + """ + a = _padding(password) + u_hash = hashlib.md5(a) + u_hash.update(o_entry) + u_hash.update(struct.pack("= 4 and not metadata_encrypted: + u_hash.update(b"\xff\xff\xff\xff") + u_hash_digest = u_hash.digest() + length = key_size // 8 + if rev >= 3: + for _ in range(50): + u_hash_digest = hashlib.md5(u_hash_digest[:length]).digest() + return u_hash_digest[:length] + + @staticmethod + def compute_O_value_key(owner_password: bytes, rev: int, key_size: int) -> bytes: + """ + Algorithm 3: Computing the encryption dictionary’s O (owner password) value. + + a) Pad or truncate the owner password string as described in step (a) + of "Algorithm 2: Computing an encryption key". + If there is no owner password, use the user password instead. + b) Initialize the MD5 hash function and pass the result of step (a) as + input to this function. + c) (Security handlers of revision 3 or greater) Do the following 50 times: + Take the output from the previous + MD5 hash and pass it as input into a new MD5 hash. + d) Create an RC4 encryption key using the first n bytes of the output + from the final MD5 hash, where n shall + always be 5 for security handlers of revision 2 but, for security + handlers of revision 3 or greater, shall + depend on the value of the encryption dictionary’s Length entry. + e) Pad or truncate the user password string as described in step (a) of + "Algorithm 2: Computing an encryption key". + f) Encrypt the result of step (e), using an RC4 encryption function with + the encryption key obtained in step (d). + g) (Security handlers of revision 3 or greater) Do the following 19 times: + Take the output from the previous + invocation of the RC4 function and pass it as input to a new + invocation of the function; use an encryption + key generated by taking each byte of the encryption key obtained in + step (d) and performing an XOR + (exclusive or) operation between that byte and the single-byte value + of the iteration counter (from 1 to 19). + h) Store the output from the final invocation of the RC4 function as + the value of the O entry in the encryption dictionary. + + Args: + owner_password: + rev: The encryption revision (see PDF standard) + key_size: The size of the key in bytes + + Returns: + The RC4 key + + """ + a = _padding(owner_password) + o_hash_digest = hashlib.md5(a).digest() + + if rev >= 3: + for _ in range(50): + o_hash_digest = hashlib.md5(o_hash_digest).digest() + + return o_hash_digest[: key_size // 8] + + @staticmethod + def compute_O_value(rc4_key: bytes, user_password: bytes, rev: int) -> bytes: + """ + See :func:`compute_O_value_key`. + + Args: + rc4_key: + user_password: + rev: The encryption revision (see PDF standard) + + Returns: + The RC4 encrypted + + """ + a = _padding(user_password) + rc4_enc = rc4_encrypt(rc4_key, a) + if rev >= 3: + for i in range(1, 20): + key = bytes(x ^ i for x in rc4_key) + rc4_enc = rc4_encrypt(key, rc4_enc) + return rc4_enc + + @staticmethod + def compute_U_value(key: bytes, rev: int, id1_entry: bytes) -> bytes: + """ + Algorithm 4: Computing the encryption dictionary’s U (user password) value. + + (Security handlers of revision 2) + + a) Create an encryption key based on the user password string, as + described in "Algorithm 2: Computing an encryption key". + b) Encrypt the 32-byte padding string shown in step (a) of + "Algorithm 2: Computing an encryption key", using an RC4 encryption + function with the encryption key from the preceding step. + c) Store the result of step (b) as the value of the U entry in the + encryption dictionary. + + Args: + key: + rev: The encryption revision (see PDF standard) + id1_entry: + + Returns: + The value + + """ + if rev <= 2: + return rc4_encrypt(key, _PADDING) + + """ + Algorithm 5: Computing the encryption dictionary’s U (user password) value. + + (Security handlers of revision 3 or greater) + + a) Create an encryption key based on the user password string, as + described in "Algorithm 2: Computing an encryption key". + b) Initialize the MD5 hash function and pass the 32-byte padding string + shown in step (a) of "Algorithm 2: + Computing an encryption key" as input to this function. + c) Pass the first element of the file’s file identifier array (the value + of the ID entry in the document’s trailer + dictionary; see Table 15) to the hash function and finish the hash. + d) Encrypt the 16-byte result of the hash, using an RC4 encryption + function with the encryption key from step (a). + e) Do the following 19 times: Take the output from the previous + invocation of the RC4 function and pass it as input to a new + invocation of the function; use an encryption key generated by + taking each byte of the original encryption key obtained in + step (a) and performing an XOR (exclusive or) operation between that + byte and the single-byte value of the iteration counter (from 1 to 19). + f) Append 16 bytes of arbitrary padding to the output from the final + invocation of the RC4 function and store the 32-byte result as the + value of the U entry in the encryption dictionary. + """ + u_hash = hashlib.md5(_PADDING) + u_hash.update(id1_entry) + rc4_enc = rc4_encrypt(key, u_hash.digest()) + for i in range(1, 20): + rc4_key = bytes(x ^ i for x in key) + rc4_enc = rc4_encrypt(rc4_key, rc4_enc) + return _padding(rc4_enc) + + @staticmethod + def verify_user_password( + user_password: bytes, + rev: int, + key_size: int, + o_entry: bytes, + u_entry: bytes, + P: int, + id1_entry: bytes, + metadata_encrypted: bool, + ) -> bytes: + """ + Algorithm 6: Authenticating the user password. + + a) Perform all but the last step of "Algorithm 4: Computing the + encryption dictionary’s U (user password) value (Security handlers of + revision 2)" or "Algorithm 5: Computing the encryption dictionary’s U + (user password) value (Security handlers of revision 3 or greater)" + using the supplied password string. + b) If the result of step (a) is equal to the value of the encryption + dictionary’s U entry (comparing on the first 16 bytes in the case of + security handlers of revision 3 or greater), the password supplied is + the correct user password. The key obtained in step (a) (that is, in + the first step of "Algorithm 4: Computing the encryption + dictionary’s U (user password) value + (Security handlers of revision 2)" or + "Algorithm 5: Computing the encryption dictionary’s U (user password) + value (Security handlers of revision 3 or greater)") shall be used + to decrypt the document. + + Args: + user_password: The user password as a bytes stream + rev: The encryption revision (see PDF standard) + key_size: The size of the key in bytes + o_entry: The owner entry + u_entry: The user entry + P: A set of flags specifying which operations shall be permitted + when the document is opened with user access. If bit 2 is set to 1, + all other bits are ignored and all operations are permitted. + If bit 2 is set to 0, permission for operations are based on the + values of the remaining flags defined in Table 24. + id1_entry: + metadata_encrypted: A boolean indicating if the metadata is encrypted. + + Returns: + The key + + """ + key = AlgV4.compute_key( + user_password, rev, key_size, o_entry, P, id1_entry, metadata_encrypted + ) + u_value = AlgV4.compute_U_value(key, rev, id1_entry) + if rev >= 3: + u_value = u_value[:16] + u_entry = u_entry[:16] + if u_value != u_entry: + key = b"" + return key + + @staticmethod + def verify_owner_password( + owner_password: bytes, + rev: int, + key_size: int, + o_entry: bytes, + u_entry: bytes, + P: int, + id1_entry: bytes, + metadata_encrypted: bool, + ) -> bytes: + """ + Algorithm 7: Authenticating the owner password. + + a) Compute an encryption key from the supplied password string, as + described in steps (a) to (d) of + "Algorithm 3: Computing the encryption dictionary’s O (owner password) + value". + b) (Security handlers of revision 2 only) Decrypt the value of the + encryption dictionary’s O entry, using an RC4 + encryption function with the encryption key computed in step (a). + (Security handlers of revision 3 or greater) Do the following 20 times: + Decrypt the value of the encryption dictionary’s O entry (first iteration) + or the output from the previous iteration (all subsequent iterations), + using an RC4 encryption function with a different encryption key at + each iteration. The key shall be generated by taking the original key + (obtained in step (a)) and performing an XOR (exclusive or) operation + between each byte of the key and the single-byte value of the + iteration counter (from 19 to 0). + c) The result of step (b) purports to be the user password. + Authenticate this user password using + "Algorithm 6: Authenticating the user password". + If it is correct, the password supplied is the correct owner password. + + Args: + owner_password: + rev: The encryption revision (see PDF standard) + key_size: The size of the key in bytes + o_entry: The owner entry + u_entry: The user entry + P: A set of flags specifying which operations shall be permitted + when the document is opened with user access. If bit 2 is set to 1, + all other bits are ignored and all operations are permitted. + If bit 2 is set to 0, permission for operations are based on the + values of the remaining flags defined in Table 24. + id1_entry: + metadata_encrypted: A boolean indicating if the metadata is encrypted. + + Returns: + bytes + + """ + rc4_key = AlgV4.compute_O_value_key(owner_password, rev, key_size) + + if rev <= 2: + user_password = rc4_decrypt(rc4_key, o_entry) + else: + user_password = o_entry + for i in range(19, -1, -1): + key = bytes(x ^ i for x in rc4_key) + user_password = rc4_decrypt(key, user_password) + return AlgV4.verify_user_password( + user_password, + rev, + key_size, + o_entry, + u_entry, + P, + id1_entry, + metadata_encrypted, + ) + + +class AlgV5: + @staticmethod + def verify_owner_password( + R: int, password: bytes, o_value: bytes, oe_value: bytes, u_value: bytes + ) -> bytes: + """ + Algorithm 3.2a Computing an encryption key. + + To understand the algorithm below, it is necessary to treat the O and U + strings in the Encrypt dictionary as made up of three sections. + The first 32 bytes are a hash value (explained below). The next 8 bytes + are called the Validation Salt. The final 8 bytes are called the Key Salt. + + 1. The password string is generated from Unicode input by processing the + input string with the SASLprep (IETF RFC 4013) profile of + stringprep (IETF RFC 3454), and then converting to a UTF-8 + representation. + 2. Truncate the UTF-8 representation to 127 bytes if it is longer than + 127 bytes. + 3. Test the password against the owner key by computing the SHA-256 hash + of the UTF-8 password concatenated with the 8 bytes of owner + Validation Salt, concatenated with the 48-byte U string. If the + 32-byte result matches the first 32 bytes of the O string, this is + the owner password. + Compute an intermediate owner key by computing the SHA-256 hash of + the UTF-8 password concatenated with the 8 bytes of owner Key Salt, + concatenated with the 48-byte U string. The 32-byte result is the + key used to decrypt the 32-byte OE string using AES-256 in CBC mode + with no padding and an initialization vector of zero. + The 32-byte result is the file encryption key. + 4. Test the password against the user key by computing the SHA-256 hash + of the UTF-8 password concatenated with the 8 bytes of user + Validation Salt. If the 32 byte result matches the first 32 bytes of + the U string, this is the user password. + Compute an intermediate user key by computing the SHA-256 hash of the + UTF-8 password concatenated with the 8 bytes of user Key Salt. + The 32-byte result is the key used to decrypt the 32-byte + UE string using AES-256 in CBC mode with no padding and an + initialization vector of zero. The 32-byte result is the file + encryption key. + 5. Decrypt the 16-byte Perms string using AES-256 in ECB mode with an + initialization vector of zero and the file encryption key as the key. + Verify that bytes 9-11 of the result are the characters ‘a’, ‘d’, ‘b’. + Bytes 0-3 of the decrypted Perms entry, treated as a little-endian + integer, are the user permissions. + They should match the value in the P key. + + Args: + R: A number specifying which revision of the standard security + handler shall be used to interpret this dictionary + password: The owner password + o_value: A 32-byte string, based on both the owner and user passwords, + that shall be used in computing the encryption key and in + determining whether a valid owner password was entered + oe_value: + u_value: A 32-byte string, based on the user password, that shall be + used in determining whether to prompt the user for a password and, + if so, whether a valid user or owner password was entered. + + Returns: + The key + + """ + password = password[:127] + if ( + AlgV5.calculate_hash(R, password, o_value[32:40], u_value[:48]) + != o_value[:32] + ): + return b"" + iv = bytes(0 for _ in range(16)) + tmp_key = AlgV5.calculate_hash(R, password, o_value[40:48], u_value[:48]) + return aes_cbc_decrypt(tmp_key, iv, oe_value) + + @staticmethod + def verify_user_password( + R: int, password: bytes, u_value: bytes, ue_value: bytes + ) -> bytes: + """ + See :func:`verify_owner_password`. + + Args: + R: A number specifying which revision of the standard security + handler shall be used to interpret this dictionary + password: The user password + u_value: A 32-byte string, based on the user password, that shall be + used in determining whether to prompt the user for a password + and, if so, whether a valid user or owner password was entered. + ue_value: + + Returns: + bytes + + """ + password = password[:127] + if AlgV5.calculate_hash(R, password, u_value[32:40], b"") != u_value[:32]: + return b"" + iv = bytes(0 for _ in range(16)) + tmp_key = AlgV5.calculate_hash(R, password, u_value[40:48], b"") + return aes_cbc_decrypt(tmp_key, iv, ue_value) + + @staticmethod + def calculate_hash(R: int, password: bytes, salt: bytes, udata: bytes) -> bytes: + # https://github.com/qpdf/qpdf/blob/main/libqpdf/QPDF_encryption.cc + k = hashlib.sha256(password + salt + udata).digest() + if R < 6: + return k + count = 0 + while True: + count += 1 + k1 = password + k + udata + e = aes_cbc_encrypt(k[:16], k[16:32], k1 * 64) + hash_fn = ( + hashlib.sha256, + hashlib.sha384, + hashlib.sha512, + )[sum(e[:16]) % 3] + k = hash_fn(e).digest() + if count >= 64 and e[-1] <= count - 32: + break + return k[:32] + + @staticmethod + def verify_perms( + key: bytes, perms: bytes, p: int, metadata_encrypted: bool + ) -> bool: + """ + See :func:`verify_owner_password` and :func:`compute_perms_value`. + + Args: + key: The owner password + perms: + p: A set of flags specifying which operations shall be permitted + when the document is opened with user access. + If bit 2 is set to 1, all other bits are ignored and all + operations are permitted. + If bit 2 is set to 0, permission for operations are based on + the values of the remaining flags defined in Table 24. + metadata_encrypted: + + Returns: + A boolean + + """ + b8 = b"T" if metadata_encrypted else b"F" + p1 = struct.pack(" dict[Any, Any]: + user_password = user_password[:127] + owner_password = owner_password[:127] + u_value, ue_value = AlgV5.compute_U_value(R, user_password, key) + o_value, oe_value = AlgV5.compute_O_value(R, owner_password, key, u_value) + perms = AlgV5.compute_Perms_value(key, p, metadata_encrypted) + return { + "/U": u_value, + "/UE": ue_value, + "/O": o_value, + "/OE": oe_value, + "/Perms": perms, + } + + @staticmethod + def compute_U_value(R: int, password: bytes, key: bytes) -> tuple[bytes, bytes]: + """ + Algorithm 3.8 Computing the encryption dictionary’s U (user password) + and UE (user encryption key) values. + + 1. Generate 16 random bytes of data using a strong random number generator. + The first 8 bytes are the User Validation Salt. The second 8 bytes + are the User Key Salt. Compute the 32-byte SHA-256 hash of the + password concatenated with the User Validation Salt. The 48-byte + string consisting of the 32-byte hash followed by the User + Validation Salt followed by the User Key Salt is stored as the U key. + 2. Compute the 32-byte SHA-256 hash of the password concatenated with + the User Key Salt. Using this hash as the key, encrypt the file + encryption key using AES-256 in CBC mode with no padding and an + initialization vector of zero. The resulting 32-byte string is stored + as the UE key. + + Args: + R: + password: + key: + + Returns: + A tuple (u-value, ue value) + + """ + random_bytes = secrets.token_bytes(16) + val_salt = random_bytes[:8] + key_salt = random_bytes[8:] + u_value = AlgV5.calculate_hash(R, password, val_salt, b"") + val_salt + key_salt + + tmp_key = AlgV5.calculate_hash(R, password, key_salt, b"") + iv = bytes(0 for _ in range(16)) + ue_value = aes_cbc_encrypt(tmp_key, iv, key) + return u_value, ue_value + + @staticmethod + def compute_O_value( + R: int, password: bytes, key: bytes, u_value: bytes + ) -> tuple[bytes, bytes]: + """ + Algorithm 3.9 Computing the encryption dictionary’s O (owner password) + and OE (owner encryption key) values. + + 1. Generate 16 random bytes of data using a strong random number + generator. The first 8 bytes are the Owner Validation Salt. The + second 8 bytes are the Owner Key Salt. Compute the 32-byte SHA-256 + hash of the password concatenated with the Owner Validation Salt and + then concatenated with the 48-byte U string as generated in + Algorithm 3.8. The 48-byte string consisting of the 32-byte hash + followed by the Owner Validation Salt followed by the Owner Key Salt + is stored as the O key. + 2. Compute the 32-byte SHA-256 hash of the password concatenated with + the Owner Key Salt and then concatenated with the 48-byte U string as + generated in Algorithm 3.8. Using this hash as the key, + encrypt the file encryption key using AES-256 in CBC mode with + no padding and an initialization vector of zero. + The resulting 32-byte string is stored as the OE key. + + Args: + R: + password: + key: + u_value: A 32-byte string, based on the user password, that shall be + used in determining whether to prompt the user for a password + and, if so, whether a valid user or owner password was entered. + + Returns: + A tuple (O value, OE value) + + """ + random_bytes = secrets.token_bytes(16) + val_salt = random_bytes[:8] + key_salt = random_bytes[8:] + o_value = ( + AlgV5.calculate_hash(R, password, val_salt, u_value) + val_salt + key_salt + ) + tmp_key = AlgV5.calculate_hash(R, password, key_salt, u_value[:48]) + iv = bytes(0 for _ in range(16)) + oe_value = aes_cbc_encrypt(tmp_key, iv, key) + return o_value, oe_value + + @staticmethod + def compute_Perms_value(key: bytes, p: int, metadata_encrypted: bool) -> bytes: + """ + Algorithm 3.10 Computing the encryption dictionary’s Perms + (permissions) value. + + 1. Extend the permissions (contents of the P integer) to 64 bits by + setting the upper 32 bits to all 1’s. + (This allows for future extension without changing the format.) + 2. Record the 8 bytes of permission in the bytes 0-7 of the block, + low order byte first. + 3. Set byte 8 to the ASCII value ' T ' or ' F ' according to the + EncryptMetadata Boolean. + 4. Set bytes 9-11 to the ASCII characters ' a ', ' d ', ' b '. + 5. Set bytes 12-15 to 4 bytes of random data, which will be ignored. + 6. Encrypt the 16-byte block using AES-256 in ECB mode with an + initialization vector of zero, using the file encryption key as the + key. The result (16 bytes) is stored as the Perms string, and checked + for validity when the file is opened. + + Args: + key: + p: A set of flags specifying which operations shall be permitted + when the document is opened with user access. If bit 2 is set to 1, + all other bits are ignored and all operations are permitted. + If bit 2 is set to 0, permission for operations are based on the + values of the remaining flags defined in Table 24. + metadata_encrypted: A boolean indicating if the metadata is encrypted. + + Returns: + The perms value + + """ + b8 = b"T" if metadata_encrypted else b"F" + rr = secrets.token_bytes(4) + data = struct.pack(" str: + """ + Apply the SASLprep profile (RFC 4013) of stringprep (RFC 3454). + + This normalizes Unicode passwords for PDF 2.0 (AES-256, revision 5/6) + encryption as required by the PDF specification. + + Args: + password: The Unicode password string to normalize. + + Returns: + The SASLprep-normalized string. + + Raises: + ValueError: If the password contains prohibited characters + or fails the bidirectional character check. + + """ + # Mapping (RFC 4013 §2.1) + # - Map characters in table B.1 to nothing + # - Map characters in table C.1.2 (non-ASCII spaces) to U+0020 (SPACE) + mapped: list[str] = [] + for character in password: + if stringprep.in_table_b1(character): + continue # map to nothing + if stringprep.in_table_c12(character): + mapped.append(" ") # map to SPACE + else: + mapped.append(character) + password = "".join(mapped) + + # Normalization (RFC 4013 §2.2) — Unicode NFKC + password = unicodedata.normalize("NFKC", password) + + for character in password: + for check, description in _SASLPREP_PROHIBITED_CHECKS: + if check(character): + raise ValueError( + f"SASLprep: {description} U+{ord(character):04X}" + ) + + # Bidirectional check (RFC 4013 §2.4, RFC 3454 §6) + has_r_and_al = False + has_l = False + for character in password: + if stringprep.in_table_d1(character): + has_r_and_al = True + if stringprep.in_table_d2(character): + has_l = True + + if has_r_and_al: + if has_l: + raise ValueError( + "SASLprep: string with RandALCat characters must not " + "contain LCat characters" + ) + if not stringprep.in_table_d1(password[0]) or not stringprep.in_table_d1( + password[-1] + ): + raise ValueError( + "SASLprep: string with RandALCat characters must start " + "and end with RandALCat characters" + ) + + return password + + +class EncryptAlgorithm(tuple, Enum): # type: ignore # noqa: SLOT001 + # V, R, Length + RC4_40 = (1, 2, 40) + RC4_128 = (2, 3, 128) + AES_128 = (4, 4, 128) + AES_256_R5 = (5, 5, 256) + AES_256 = (5, 6, 256) + + +class EncryptionValues: + O: bytes # noqa: E741 + U: bytes + OE: bytes + UE: bytes + Perms: bytes + + +class Encryption: + """ + Collects and manages parameters for PDF document encryption and decryption. + + Args: + V: A code specifying the algorithm to be used in encrypting and + decrypting the document. + R: The revision of the standard security handler. + Length: The length of the encryption key in bits. + P: A set of flags specifying which operations shall be permitted + when the document is opened with user access + entry: The encryption dictionary object. + EncryptMetadata: Whether to encrypt metadata in the document. + first_id_entry: The first 16 bytes of the file's original ID. + StmF: The name of the crypt filter that shall be used by default + when decrypting streams. + StrF: The name of the crypt filter that shall be used when decrypting + all strings in the document. + EFF: The name of the crypt filter that shall be used when + encrypting embedded file streams that do not have their own + crypt filter specifier. + values: Additional encryption parameters. + + """ + + def __init__( + self, + V: int, + R: int, + Length: int, + P: int, + entry: DictionaryObject, + EncryptMetadata: bool, + first_id_entry: bytes, + StmF: str, + StrF: str, + EFF: str, + values: Optional[EncryptionValues], + ) -> None: + # §7.6.2, entries common to all encryption dictionaries + # use same name as keys of encryption dictionaries entries + self.V = V + self.R = R + self.Length = Length # key_size + self.P = (P + 0x100000000) % 0x100000000 # maybe P < 0 + self.EncryptMetadata = EncryptMetadata + self.id1_entry = first_id_entry + self.StmF = StmF + self.StrF = StrF + self.EFF = EFF + self.values: EncryptionValues = values or EncryptionValues() + + self._password_type = PasswordType.NOT_DECRYPTED + self._key: Optional[bytes] = None + self._are_permissions_valid: bool = True + + def is_decrypted(self) -> bool: + return self._password_type != PasswordType.NOT_DECRYPTED + + def encrypt_object(self, obj: PdfObject, idnum: int, generation: int) -> PdfObject: + # skip calculate key + if not self._is_encryption_object(obj): + return obj + + cf = self._make_crypt_filter(idnum, generation) + return cf.encrypt_object(obj) + + def decrypt_object(self, obj: PdfObject, idnum: int, generation: int, *, strict: bool = True) -> PdfObject: + # skip calculate key + if not self._is_encryption_object(obj): + return obj + + cf = self._make_crypt_filter(idnum, generation) + return cf.decrypt_object(obj, strict=strict) + + @staticmethod + def _is_encryption_object(obj: PdfObject) -> bool: + return isinstance( + obj, + ( + ByteStringObject, + TextStringObject, + StreamObject, + ArrayObject, + DictionaryObject, + ), + ) + + def _make_crypt_filter(self, idnum: int, generation: int) -> CryptFilter: + """ + Algorithm 1: Encryption of data using the RC4 or AES algorithms. + + a) Obtain the object number and generation number from the object + identifier of the string or stream to be encrypted + (see 7.3.10, "Indirect Objects"). If the string is a direct object, + use the identifier of the indirect object containing it. + b) For all strings and streams without crypt filter specifier; treating + the object number and generation number as binary integers, extend + the original n-byte encryption key to n + 5 bytes by appending the + low-order 3 bytes of the object number and the low-order 2 bytes of + the generation number in that order, low-order byte first. + (n is 5 unless the value of V in the encryption dictionary is greater + than 1, in which case n is the value of Length divided by 8.) + If using the AES algorithm, extend the encryption key an additional + 4 bytes by adding the value “sAlT”, which corresponds to the + hexadecimal values 0x73, 0x41, 0x6C, 0x54. (This addition is done for + backward compatibility and is not intended to provide additional + security.) + c) Initialize the MD5 hash function and pass the result of step (b) as + input to this function. + d) Use the first (n + 5) bytes, up to a maximum of 16, of the output + from the MD5 hash as the key for the RC4 or AES symmetric key + algorithms, along with the string or stream data to be encrypted. + If using the AES algorithm, the Cipher Block Chaining (CBC) mode, + which requires an initialization vector, is used. The block size + parameter is set to 16 bytes, and the initialization vector is a + 16-byte random number that is stored as the first 16 bytes of the + encrypted stream or string. + + Algorithm 3.1a: Encryption of data using the AES-256 algorithm. + + Note: Algorithm 3.1a does not use MD5 key derivation, so AES-256 + encrypted files can be read on FIPS-enabled systems where MD5 is blocked. + + 1. Use the 32-byte file encryption key for the AES-256 symmetric key + algorithm, along with the string or stream data to be encrypted. + Use the AES algorithm in Cipher Block Chaining (CBC) mode, which + requires an initialization vector. The block size parameter is set to + 16 bytes, and the initialization vector is a 16-byte random number + that is stored as the first 16 bytes of the encrypted stream or string. + The output is the encrypted data to be stored in the PDF file. + """ + pack1 = (idnum & 0xFFFFFF).to_bytes(3, "little") + pack2 = (generation & 0xFFFF).to_bytes(2, "little") + + assert self._key + key = self._key + + # Algorithm 1 (V <= 4): MD5 key derivation. Algorithm 3.1a (V >= 5): key used directly. + if self.V <= 4: + n = 5 if self.V == 1 else self.Length // 8 + key_data = key[:n] + pack1 + pack2 + key_hash = hashlib.md5(key_data) + rc4_key = key_hash.digest()[: min(n + 5, 16)] + + # for AES-128 + key_hash.update(b"sAlT") + aes128_key = key_hash.digest()[: min(n + 5, 16)] + else: + rc4_key = b"" + aes128_key = b"" + + # for AES-256 + aes256_key = key + + stm_crypt = self._get_crypt(self.StmF, rc4_key, aes128_key, aes256_key) + str_crypt = self._get_crypt(self.StrF, rc4_key, aes128_key, aes256_key) + ef_crypt = self._get_crypt(self.EFF, rc4_key, aes128_key, aes256_key) + + return CryptFilter(stm_crypt, str_crypt, ef_crypt) + + @staticmethod + def _get_crypt( + method: str, rc4_key: bytes, aes128_key: bytes, aes256_key: bytes + ) -> CryptBase: + if method == "/AESV2": + return CryptAES(aes128_key) + if method == "/AESV3": + return CryptAES(aes256_key) + if method == "/Identity": + return CryptIdentity() + + return CryptRC4(rc4_key) + + def _encode_password( + self, password: Union[bytes, str], *, strict: bool = False + ) -> bytes: + if isinstance(password, str): + if self.V >= 5: + # PDF 2.0 §7.6.4.3.3: AES-256 (R5/R6) requires SASLprep + # normalization followed by UTF-8 encoding. + try: + password = _saslprep(password) + except (ValueError, IndexError) as e: + if strict: + raise ValueError( + f"Password SASLprep normalization failed: {e}" + ) from e + logger_warning( + "SASLprep normalization failed, using plain UTF-8: %(err)s", + source=__name__, + err=str(e), + ) + pwd = password.encode("utf-8") + else: + try: + pwd = password.encode("latin-1") + except Exception: + pwd = password.encode("utf-8") + else: + pwd = password + return pwd + + def verify( + self, password: Union[bytes, str], *, strict: bool = False + ) -> PasswordType: + pwd = self._encode_password(password, strict=strict) + key, rc = self.verify_v4(pwd) if self.V <= 4 else self.verify_v5(pwd) + if rc != PasswordType.NOT_DECRYPTED: + self._password_type = rc + self._key = key + return rc + + def verify_v4(self, password: bytes) -> tuple[bytes, PasswordType]: + # verify owner password first + key = AlgV4.verify_owner_password( + password, + self.R, + self.Length, + self.values.O, + self.values.U, + self.P, + self.id1_entry, + self.EncryptMetadata, + ) + if key: + return key, PasswordType.OWNER_PASSWORD + key = AlgV4.verify_user_password( + password, + self.R, + self.Length, + self.values.O, + self.values.U, + self.P, + self.id1_entry, + self.EncryptMetadata, + ) + if key: + return key, PasswordType.USER_PASSWORD + return b"", PasswordType.NOT_DECRYPTED + + def verify_v5(self, password: bytes) -> tuple[bytes, PasswordType]: + # verify owner password first + key = AlgV5.verify_owner_password( + self.R, password, self.values.O, self.values.OE, self.values.U + ) + rc = PasswordType.OWNER_PASSWORD + if not key: + key = AlgV5.verify_user_password( + self.R, password, self.values.U, self.values.UE + ) + rc = PasswordType.USER_PASSWORD + if not key: + return b"", PasswordType.NOT_DECRYPTED + + # verify Perms + self._are_permissions_valid = AlgV5.verify_perms(key, self.values.Perms, self.P, self.EncryptMetadata) + if not self._are_permissions_valid: + logger_warning("ignore '/Perms' verify failed", source=__name__) + return key, rc + + def write_entry( + self, + user_password: str, + owner_password: Optional[str], + *, + strict: bool = False, + ) -> DictionaryObject: + user_pwd = self._encode_password(user_password, strict=strict) + owner_pwd = ( + self._encode_password(owner_password, strict=strict) + if owner_password + else None + ) + if owner_pwd is None: + owner_pwd = user_pwd + + if self.V <= 4: + self.compute_values_v4(user_pwd, owner_pwd) + else: + self._key = secrets.token_bytes(self.Length // 8) + values = AlgV5.generate_values( + self.R, user_pwd, owner_pwd, self._key, self.P, self.EncryptMetadata + ) + self.values.O = values["/O"] + self.values.U = values["/U"] + self.values.OE = values["/OE"] + self.values.UE = values["/UE"] + self.values.Perms = values["/Perms"] + + dict_obj = DictionaryObject() + dict_obj[NameObject("/V")] = NumberObject(self.V) + dict_obj[NameObject("/R")] = NumberObject(self.R) + dict_obj[NameObject("/Length")] = NumberObject(self.Length) + dict_obj[NameObject("/P")] = NumberObject(self.P) + dict_obj[NameObject("/Filter")] = NameObject("/Standard") + # ignore /EncryptMetadata + + dict_obj[NameObject("/O")] = ByteStringObject(self.values.O) + dict_obj[NameObject("/U")] = ByteStringObject(self.values.U) + + if self.V >= 4: + # TODO: allow different method + std_cf = DictionaryObject() + std_cf[NameObject("/AuthEvent")] = NameObject("/DocOpen") + std_cf[NameObject("/CFM")] = NameObject(self.StmF) + std_cf[NameObject("/Length")] = NumberObject(self.Length // 8) + cf = DictionaryObject() + cf[NameObject("/StdCF")] = std_cf + dict_obj[NameObject("/CF")] = cf + dict_obj[NameObject("/StmF")] = NameObject("/StdCF") + dict_obj[NameObject("/StrF")] = NameObject("/StdCF") + # ignore EFF + # dict_obj[NameObject("/EFF")] = NameObject("/StdCF") + + if self.V >= 5: + dict_obj[NameObject("/OE")] = ByteStringObject(self.values.OE) + dict_obj[NameObject("/UE")] = ByteStringObject(self.values.UE) + dict_obj[NameObject("/Perms")] = ByteStringObject(self.values.Perms) + return dict_obj + + def compute_values_v4(self, user_password: bytes, owner_password: bytes) -> None: + rc4_key = AlgV4.compute_O_value_key(owner_password, self.R, self.Length) + o_value = AlgV4.compute_O_value(rc4_key, user_password, self.R) + + key = AlgV4.compute_key( + user_password, + self.R, + self.Length, + o_value, + self.P, + self.id1_entry, + self.EncryptMetadata, + ) + u_value = AlgV4.compute_U_value(key, self.R, self.id1_entry) + + self._key = key + self.values.O = o_value + self.values.U = u_value + + @staticmethod + def read(encryption_entry: DictionaryObject, first_id_entry: bytes) -> "Encryption": + if encryption_entry.get("/Filter") != "/Standard": + raise NotImplementedError( + "only Standard PDF encryption handler is available" + ) + if "/SubFilter" in encryption_entry: + raise NotImplementedError("/SubFilter NOT supported") + + stm_filter = "/V2" + str_filter = "/V2" + ef_filter = "/V2" + + alg_ver = encryption_entry.get("/V", 0) + if alg_ver not in (1, 2, 3, 4, 5): + raise NotImplementedError(f"Encryption V={alg_ver} NOT supported") + if alg_ver >= 4: + filters = encryption_entry["/CF"] + + stm_filter = encryption_entry.get("/StmF", "/Identity") + str_filter = encryption_entry.get("/StrF", "/Identity") + ef_filter = encryption_entry.get("/EFF", stm_filter) + + if stm_filter != "/Identity": + stm_filter = filters[stm_filter]["/CFM"] # type: ignore[index] + if str_filter != "/Identity": + str_filter = filters[str_filter]["/CFM"] # type: ignore[index] + if ef_filter != "/Identity": + ef_filter = filters[ef_filter]["/CFM"] # type: ignore[index] + + allowed_methods = ("/Identity", "/V2", "/AESV2", "/AESV3") + if stm_filter not in allowed_methods: + raise NotImplementedError(f"StmF Method {stm_filter} NOT supported!") + if str_filter not in allowed_methods: + raise NotImplementedError(f"StrF Method {str_filter} NOT supported!") + if ef_filter not in allowed_methods: + raise NotImplementedError(f"EFF Method {ef_filter} NOT supported!") + + alg_rev = cast(int, encryption_entry["/R"]) + perm_flags = cast(int, encryption_entry["/P"]) + key_bits = encryption_entry.get("/Length", 40) + if alg_ver == 4 and stm_filter == "/AESV2": + cf_dict = cast(DictionaryObject, filters[encryption_entry["/StmF"]]) # type: ignore[index] + # CF /Length is in bytes (default 16 for AES-128), convert to bits + key_bits = cast(int, cf_dict.get("/Length", 16)) * 8 + encrypt_metadata = encryption_entry.get("/EncryptMetadata") + encrypt_metadata = ( + encrypt_metadata.value if encrypt_metadata is not None else True + ) + values = EncryptionValues() + values.O = cast(ByteStringObject, encryption_entry["/O"]).original_bytes + values.U = cast(ByteStringObject, encryption_entry["/U"]).original_bytes + values.OE = encryption_entry.get("/OE", ByteStringObject()).original_bytes + values.UE = encryption_entry.get("/UE", ByteStringObject()).original_bytes + values.Perms = encryption_entry.get("/Perms", ByteStringObject()).original_bytes + return Encryption( + V=alg_ver, + R=alg_rev, + Length=key_bits, + P=perm_flags, + EncryptMetadata=encrypt_metadata, + first_id_entry=first_id_entry, + values=values, + StrF=str_filter, + StmF=stm_filter, + EFF=ef_filter, + entry=encryption_entry, # Dummy entry for the moment; will get removed + ) + + @staticmethod + def make( + alg: EncryptAlgorithm, permissions: int, first_id_entry: bytes + ) -> "Encryption": + alg_ver, alg_rev, key_bits = alg + + stm_filter, str_filter, ef_filter = "/V2", "/V2", "/V2" + + if alg == EncryptAlgorithm.AES_128: + stm_filter, str_filter, ef_filter = "/AESV2", "/AESV2", "/AESV2" + elif alg in (EncryptAlgorithm.AES_256_R5, EncryptAlgorithm.AES_256): + stm_filter, str_filter, ef_filter = "/AESV3", "/AESV3", "/AESV3" + + return Encryption( + V=alg_ver, + R=alg_rev, + Length=key_bits, + P=permissions, + EncryptMetadata=True, + first_id_entry=first_id_entry, + values=None, + StrF=str_filter, + StmF=stm_filter, + EFF=ef_filter, + entry=DictionaryObject(), # Dummy entry for the moment; will get removed + ) diff --git a/.venv/lib/python3.13/site-packages/pypdf/_font.py b/.venv/lib/python3.13/site-packages/pypdf/_font.py new file mode 100644 index 0000000000000000000000000000000000000000..10c8b1a8f93db5f037fd8a6ab73db34628ed5300 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/_font.py @@ -0,0 +1,799 @@ +from __future__ import annotations + +import unicodedata +from collections.abc import Sequence +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, ClassVar, cast + +from pypdf.generic import ( + ArrayObject, + DictionaryObject, + FloatObject, + IndirectObject, + NameObject, + NumberObject, + PdfObject, + StreamObject, + TextStringObject, +) + +from ._cmap import get_encoding +from ._codecs.adobe_glyphs import adobe_glyphs +from ._utils import logger_warning +from .constants import FontFlags +from .errors import LimitReachedError, PdfReadError + +if TYPE_CHECKING: + from fontTools.ttLib.tables._h_e_a_d import table__h_e_a_d + from fontTools.ttLib.tables._p_o_s_t import table__p_o_s_t + from fontTools.ttLib.tables.O_S_2f_2 import table_O_S_2f_2 + + from ._writer import PdfWriter + +try: + from io import BytesIO + + from fontTools.ttLib import TTFont, TTLibError + HAS_FONTTOOLS = True +except ImportError: + HAS_FONTTOOLS = False + + +# Limits. +MAX_CID_WIDTH_ENTRY_COUNT = 65_536 +MAX_WIDTH_ENTRY_COUNT = 100_000 + + +# Some constants from truetype font tables that we use: +HEADER_MACSTYLE_ITALIC = 0x02 +OS2_FSSELECTION_ITALIC = 0x01 +OS2_PANOSE_BFAMILYTYPE_SCRIPT = 3 +OS2_PANOSE_BFAMILYTYPE_DECORATIVE = 4 +OS2_PANOSE_BFAMILYTYPE_PICTORIAL = 5 +OS2_PANOSE_BPROPORTION_MONOSPACED = 9 +OS2_SFAMILYSCLASS_SCRIPTS = 10 +OS2_SFAMILYSCLASS_SYMBOLIC = 12 + + +@dataclass(frozen=True) +class FontDescriptor: + """ + Represents the FontDescriptor dictionary as defined in the PDF specification. + This contains both descriptive and metric information. + + The defaults are derived from the mean values of the 14 core fonts, rounded + to 100. + """ + + _DEFAULT_BBOX: ClassVar[tuple[float, float, float, float]] = (-100.0, -200.0, 1000.0, 900.0) + + name: str = "Unknown" + family: str = "Unknown" + weight: str = "Unknown" + + ascent: float = 700.0 + descent: float = -200.0 + cap_height: float = 600.0 + x_height: float = 500.0 + italic_angle: float = 0.0 # Non-italic + flags: int = 32 # Non-serif, non-symbolic, not fixed width + bbox: tuple[float, float, float, float] = _DEFAULT_BBOX + font_file: StreamObject | None = None + + def as_font_descriptor_resource(self) -> DictionaryObject: + font_descriptor_resource = DictionaryObject({ + NameObject("/Type"): NameObject("/FontDescriptor"), + NameObject("/FontName"): NameObject(f"/{self.name}"), + NameObject("/Flags"): NumberObject(self.flags), + NameObject("/FontBBox"): ArrayObject([FloatObject(n) for n in self.bbox]), + NameObject("/ItalicAngle"): FloatObject(self.italic_angle), + NameObject("/Ascent"): FloatObject(self.ascent), + NameObject("/Descent"): FloatObject(self.descent), + NameObject("/CapHeight"): FloatObject(self.cap_height), + NameObject("/XHeight"): FloatObject(self.x_height), + }) + + if self.font_file: + # Add the stream. For now, we assume a TrueType font (FontFile2) + font_descriptor_resource[NameObject("/FontFile2")] = self.font_file + + return font_descriptor_resource + + +@dataclass(frozen=True) +class CoreFontMetrics: + font_descriptor: FontDescriptor + character_widths: dict[str, int] + + +@dataclass +class Font: + """ + A font object for use during text extraction and for producing + text appearance streams. + + Attributes: + name: Font name, derived from font["/BaseFont"] + character_map: The font's character map + encoding: Font encoding + sub_type: The font type, such as Type1, TrueType, or Type3. + font_descriptor: Font metrics, including a mapping of characters to widths + character_widths: A mapping of characters to widths + space_width: The width of a space, or an approximation + interpretable: Default True. If False, the font glyphs cannot + be translated to characters, e.g. Type3 fonts that do not define + a '/ToUnicode' mapping. + + """ + + name: str + encoding: str | dict[int, str] + character_map: dict[Any, Any] = field(default_factory=dict) + sub_type: str = "Unknown" + font_descriptor: FontDescriptor = field(default_factory=FontDescriptor) + character_widths: dict[str, int] = field(default_factory=lambda: {"default": 500}) + space_width: float | int = 250 + space_char: str = " " + interpretable: bool = True + + @staticmethod + def _collect_tt_t1_character_widths( + pdf_font_dict: DictionaryObject, + char_map: dict[Any, Any], + encoding: str | dict[int, str], + current_widths: dict[str, int] + ) -> None: + """Parses a TrueType or Type1 font's /Widths array from a font dictionary and updates character widths""" + widths_array = cast(ArrayObject, pdf_font_dict["/Widths"]) + first_char = pdf_font_dict.get("/FirstChar", 0) + for idx, width in enumerate(widths_array): + current_widths[chr(idx + first_char)] = int(width) + + @staticmethod + def __check_range_length(start: int, end: int) -> None: + if end < start: + raise LimitReachedError( + f"Invalid CID width range: {start}..{end}." + ) + + count = end - start + if count > MAX_CID_WIDTH_ENTRY_COUNT: + raise LimitReachedError(f"CID width range too large: {count} > {MAX_CID_WIDTH_ENTRY_COUNT}.") + + @staticmethod + def __check_entry_count(count: int) -> None: + if count > MAX_WIDTH_ENTRY_COUNT: + raise LimitReachedError(f"Too many character widths: {count} > {MAX_WIDTH_ENTRY_COUNT}.") + + @staticmethod + def _collect_cid_character_widths(d_font: DictionaryObject, current_widths: dict[str, int]) -> None: + """Parses the /W array from a DescendantFont dictionary and updates character widths.""" + # /W width definitions have two valid formats which can be mixed and matched: + # (1) A character start index followed by a list of widths, e.g. + # `45 [500 600 700]` applies widths 500, 600, 700 to characters 45-47. + # (2) A character start index, a character stop index, and a width, e.g. + # `45 65 500` applies width 500 to characters 45-65. + skip_count = 0 + entry_count = 0 + _w = d_font.get("/W", ArrayObject()).get_object() + _w_length = len(_w) + for idx, w_entry in enumerate(_w): + if skip_count: + skip_count -= 1 + continue + w_entry = w_entry.get_object() + if not isinstance(w_entry, (int, float)): + # We should never get here due to skip_count above. But + # sometimes we do. + logger_warning( + "Expected numeric value for width, got %(w_entry)s. Ignoring it.", + source=__name__, + w_entry=w_entry, + ) + continue + # check for format (1): `int [int int int int ...]` + w_next_entry = _w[idx + 1].get_object() if idx + 1 < _w_length else None + if isinstance(w_next_entry, Sequence): + start_idx, width_list = int(w_entry), w_next_entry + stop_idx = start_idx + len(width_list) + Font.__check_range_length(start_idx, stop_idx) + entry_count += (stop_idx - start_idx) + Font.__check_entry_count(entry_count) + current_widths.update( + { + chr(_cidx): _width + for _cidx, _width in zip( + range(start_idx, stop_idx, 1), + width_list, + ) + } + ) + skip_count = 1 + # check for format (2): `int int int` + elif ( + isinstance(w_next_entry, (int, float)) + and idx + 2 < _w_length + and isinstance(_w[idx + 2].get_object(), (int, float)) + ): + start_idx, stop_idx, const_width = ( + int(w_entry), + int(w_next_entry), + _w[idx + 2].get_object(), + ) + Font.__check_range_length(start_idx, stop_idx + 1) + entry_count += (stop_idx - start_idx + 1) + Font.__check_entry_count(entry_count) + current_widths.update( + { + chr(_cidx): const_width + for _cidx in range( + start_idx, stop_idx + 1, 1 + ) + } + ) + skip_count = 2 + else: + # This handles the case of out of bounds (reaching the end of the width definitions + # while expecting more elements). + logger_warning( + "Invalid font width definition. Last element: %(w_entry)s.", + source=__name__, + w_entry=w_entry, + ) + + @staticmethod + def _get_space_char( + encoding: str | dict[int, str], + character_map: dict[Any, Any], + ) -> str: + space_char = " " + if isinstance(encoding, dict): + for char_code, char_str in encoding.items(): + if char_str == space_char: + return chr(char_code) + + for glyph_id, char_str in character_map.items(): + if char_str == space_char: + return str(glyph_id) + + return space_char + + @staticmethod + def _add_default_width(current_widths: dict[str, int], flags: int, space_char: str) -> None: + if not current_widths: + current_widths["default"] = 500 + return + + if space_char in current_widths and current_widths[space_char] != 0: + # Setting default to once or twice the space width, depending on fixed pitch + if (flags & FontFlags.FIXED_PITCH) == FontFlags.FIXED_PITCH: + current_widths["default"] = current_widths[space_char] + return + + current_widths["default"] = int(2 * current_widths[space_char]) + return + + # Use the average width of existing glyph widths + valid_widths = [w for w in current_widths.values() if w > 0] + current_widths["default"] = sum(valid_widths) // len(valid_widths) if valid_widths else 500 + + @staticmethod + def _add_space_width( + character_widths: dict[str, int], + flags: int, + space_char: str + ) -> int: + space_width = character_widths.get(space_char, 0) + if space_width != 0: + return space_width + + if (flags & FontFlags.FIXED_PITCH) == FontFlags.FIXED_PITCH: + return character_widths["default"] + + return character_widths["default"] // 2 + + @staticmethod + def _parse_bbox(raw_bbox: Any) -> tuple[float, float, float, float] | None: + """ + Convert a raw /FontBBox value into four floats. + + Args: + raw_bbox: The raw /FontBBox value read from the PDF. + + Returns: + The four bounding box values, or ``None`` when the value is not + a sequence of exactly four numbers, so that a malformed entry + falls back to the default bounding box rather than raising. + + """ + try: + bbox = [float(value) for value in raw_bbox] + except (TypeError, ValueError): + return None + if len(bbox) != 4: + return None + return bbox[0], bbox[1], bbox[2], bbox[3] + + @staticmethod + def _parse_font_descriptor(font_descriptor_obj: DictionaryObject) -> dict[str, Any]: + font_descriptor_kwargs: dict[Any, Any] = {} + for source_key, target_key in [ + ("/FontName", "name"), + ("/FontFamily", "family"), + ("/FontWeight", "weight"), + ("/Ascent", "ascent"), + ("/Descent", "descent"), + ("/CapHeight", "cap_height"), + ("/XHeight", "x_height"), + ("/ItalicAngle", "italic_angle"), + ("/Flags", "flags"), + ("/FontBBox", "bbox") + ]: + if source_key in font_descriptor_obj: + font_descriptor_kwargs[target_key] = font_descriptor_obj[source_key] + # Handle missing or malformed bbox gracefully - PDFs may have fonts without valid bounding boxes + if "bbox" in font_descriptor_kwargs: + bbox = Font._parse_bbox(font_descriptor_kwargs["bbox"]) + if bbox is None: + del font_descriptor_kwargs["bbox"] + else: + font_descriptor_kwargs["bbox"] = bbox + + # Find the binary stream for this font if there is one + for source_key in ["/FontFile", "/FontFile2", "/FontFile3"]: + if source_key in font_descriptor_obj: + if "font_file" in font_descriptor_kwargs: + raise PdfReadError(f"More than one /FontFile found in {font_descriptor_obj}") + + try: + font_file = font_descriptor_obj[source_key].get_object() + font_descriptor_kwargs["font_file"] = font_file + except PdfReadError as e: + logger_warning( + "Failed to get %(source_key)r in %(font_descriptor_obj)s: %(error)s", + source=__name__, + source_key=source_key, + font_descriptor_obj=font_descriptor_obj, + error=e, + ) + return font_descriptor_kwargs + + @classmethod + def from_font_resource( + cls, + pdf_font_dict: DictionaryObject, + ) -> Font: + from pypdf._codecs.core_font_metrics import CORE_FONT_METRICS # noqa: PLC0415 + + # Can collect base_font, name and encoding directly from font resource + name = pdf_font_dict.get("/BaseFont", "Unknown").removeprefix("/") + sub_type = pdf_font_dict.get("/Subtype", "Unknown").removeprefix("/") + encoding, character_map = get_encoding(pdf_font_dict) + font_descriptor = None + character_widths: dict[str, int] = {} + interpretable = True + + # Deal with fonts by type; Type1, TrueType and certain Type3 + if pdf_font_dict.get("/Subtype") in ("/Type1", "/MMType1", "/TrueType", "/Type3"): + # Type3 fonts that do not specify a "/ToUnicode" mapping cannot be + # reliably converted into character codes unless all named chars + # in /CharProcs map to a standard adobe glyph. See §9.10.2 of the + # PDF 1.7 standard. + if sub_type == "Type3" and "/ToUnicode" not in pdf_font_dict: + interpretable = all( + cname in adobe_glyphs + for cname in pdf_font_dict.get("/CharProcs") or [] + ) + if interpretable: # Save some overhead if font is not interpretable + if "/Widths" in pdf_font_dict: + cls._collect_tt_t1_character_widths( + pdf_font_dict, character_map, encoding, character_widths + ) + + elif name in CORE_FONT_METRICS: + font_descriptor = CORE_FONT_METRICS[name].font_descriptor + if isinstance(encoding, dict): + for code, character in encoding.items(): + # Look up the width using the glyph name from the encoding + if character in CORE_FONT_METRICS[name].character_widths: + character_widths[chr(code)] = CORE_FONT_METRICS[name].character_widths[character] + else: + for code in range(256): + character = chr(code) + if character in CORE_FONT_METRICS[name].character_widths: + character_widths[character] = CORE_FONT_METRICS[name].character_widths[character] + if "/FontDescriptor" in pdf_font_dict: + font_descriptor_obj = pdf_font_dict.get("/FontDescriptor", DictionaryObject()).get_object() + if "/MissingWidth" in font_descriptor_obj: + character_widths["default"] = cast(int, font_descriptor_obj["/MissingWidth"].get_object()) + font_descriptor = FontDescriptor(**cls._parse_font_descriptor(font_descriptor_obj)) + elif "/FontBBox" in pdf_font_dict: + # For Type3 without Font Descriptor but with FontBBox, see Table 110 in the PDF specification 2.0 + font_descriptor_kwargs: dict[str, Any] = {"name": name} + bbox = cls._parse_bbox(pdf_font_dict["/FontBBox"]) + if bbox is not None: + font_descriptor_kwargs["bbox"] = bbox + font_descriptor = FontDescriptor(**font_descriptor_kwargs) + + else: + # Composite font or CID font - CID fonts have a /W array mapping character codes + # to widths stashed in /DescendantFonts. No need to test for /DescendantFonts though, + # because all other fonts have already been dealt with. + d_font: DictionaryObject + for d_font_idx, d_font in enumerate( + cast(ArrayObject, pdf_font_dict["/DescendantFonts"]) + ): + d_font = cast(DictionaryObject, d_font.get_object()) + cast(ArrayObject, pdf_font_dict["/DescendantFonts"])[d_font_idx] = d_font + cls._collect_cid_character_widths(d_font=d_font, current_widths=character_widths) + if "/DW" in d_font: + character_widths["default"] = cast(int, d_font["/DW"].get_object()) + font_descriptor_obj = d_font.get("/FontDescriptor", DictionaryObject()).get_object() + font_descriptor = FontDescriptor(**cls._parse_font_descriptor(font_descriptor_obj)) + + if not font_descriptor: + font_descriptor = FontDescriptor(name=name) + + space_char = cls._get_space_char(encoding, character_map) + if character_widths.get("default", 0) == 0: + cls._add_default_width(character_widths, font_descriptor.flags, space_char) + space_width = cls._add_space_width(character_widths, font_descriptor.flags, space_char) + + return cls( + name=name, + sub_type=sub_type, + encoding=encoding, + font_descriptor=font_descriptor, + character_map=character_map, + character_widths=character_widths, + space_width=space_width, + space_char=space_char, + interpretable=interpretable + ) + + @staticmethod + def _font_flags_from_truetype_font_tables( + header: table__h_e_a_d, + postscript: table__p_o_s_t, + os2: table_O_S_2f_2 + ) -> int: + # Get the font flags + if os2: + panose = os2.panose + # sFamilyClass is a two-byte field. The high byte describes the family class, whereas the low + # byte only describes the subclass. We only need the high byte, hence the bit shift below: + family_class = os2.sFamilyClass >> 8 + flags: int = 0 + + # ITALIC + if header.macStyle & HEADER_MACSTYLE_ITALIC or (os2 and os2.fsSelection & OS2_FSSELECTION_ITALIC): + flags |= FontFlags.ITALIC + if postscript: + italic_angle = postscript.italicAngle + if italic_angle != 0.0: + flags |= FontFlags.ITALIC + + # FIXED_PITCH + if ( + (os2 and panose.bProportion == OS2_PANOSE_BPROPORTION_MONOSPACED) or + (postscript and postscript.isFixedPitch > 0) # Actually 1, but originally (older versions of the TTF + ): # specification) any non-zero value signified monospace. + flags |= FontFlags.FIXED_PITCH + + # SCRIPT + if os2 and ( + family_class == OS2_SFAMILYSCLASS_SCRIPTS or panose.bFamilyType == OS2_PANOSE_BFAMILYTYPE_SCRIPT + ): + flags |= FontFlags.SCRIPT + + # SERIF + if os2 and ( + 2 <= panose.bSerifStyle <= 10 + or 1 <= family_class <= 5 or family_class == 7 # 6 is reserved, all 8 and above are not serif + ): + flags |= FontFlags.SERIF + + # SYMBOLIC + if os2 and ( + family_class == OS2_SFAMILYSCLASS_SYMBOLIC or + panose.bFamilyType in {OS2_PANOSE_BFAMILYTYPE_DECORATIVE, OS2_PANOSE_BFAMILYTYPE_PICTORIAL} + ): + flags |= FontFlags.SYMBOLIC + else: + flags |= FontFlags.NONSYMBOLIC + + return flags + + @classmethod + def from_truetype_font_file(cls, font_file: BytesIO) -> Font: + if not HAS_FONTTOOLS: + raise ImportError("The 'fontTools' library is required to use 'from_truetype_font_file'") + with TTFont(font_file) as tt_font_object: + # See Chapter 6 of the TrueType reference manual for the definition of the head, OS/2 and post tables: + # https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6head.html + # https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6OS2.html + # https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6post.html + header = tt_font_object["head"] + horizontal_header = tt_font_object["hhea"] + metrics = tt_font_object["hmtx"].metrics + + # Collect additional font tables to derive font information + postscript = tt_font_object.get("post", None) + os2 = tt_font_object.get("OS/2", None) + + # Get the scaling factor to convert font file's units per em to PDF's 1000 units per em + units_per_em = header.unitsPerEm + if not units_per_em: + raise PdfReadError("Font file has an invalid unitsPerEm of 0") + scale_factor = 1000.0 / units_per_em + + # Get the font descriptor + font_descriptor_kwargs: dict[Any, Any] = {} + names = tt_font_object.get("name", None) + if names: + font_descriptor_kwargs["name"] = names.getBestFullName() + font_descriptor_kwargs["family"] = names.getBestFamilyName() + font_descriptor_kwargs["weight"] = names.getBestSubFamilyName() + font_descriptor_kwargs["ascent"] = int(round(horizontal_header.ascent * scale_factor, 0)) + font_descriptor_kwargs["descent"] = int(round(horizontal_header.descent * scale_factor, 0)) + if os2: + try: + font_descriptor_kwargs["cap_height"] = int(round(os2.sCapHeight * scale_factor, 0)) + font_descriptor_kwargs["x_height"] = int(round(os2.sxHeight * scale_factor, 0)) + except AttributeError: + pass + + font_descriptor_kwargs["flags"] = cls._font_flags_from_truetype_font_tables(header, postscript, os2) + + font_descriptor_kwargs["bbox"] = ( + round(header.xMin * scale_factor, 0), + round(header.yMin * scale_factor, 0), + round(header.xMax * scale_factor, 0), + round(header.yMax * scale_factor, 0) + ) + + font_file_data = StreamObject() + font_file_raw_bytes = font_file.getvalue() + font_file_data.set_data(font_file_raw_bytes) + font_file_data.update({NameObject("/Length1"): NumberObject(len(font_file_raw_bytes))}) + font_descriptor_kwargs["font_file"] = font_file_data + + font_descriptor = FontDescriptor(**font_descriptor_kwargs) + encoding = "utf_16_be" # Assume unicode + + character_widths: dict[str, int] = {} + character_map: dict[str, str] = {} + + glyph_order = tt_font_object.getGlyphOrder() + # Note that one glyph can be mapped to multiple unicode code points. However, buildReversedMin() + # creates a dictionary mapping glyphs to the minimum Unicode codepoint. + tt_font_cmap_table = tt_font_object.get("cmap") + if tt_font_cmap_table: + reverse_cmap = tt_font_cmap_table.buildReversedMin() + for gid, glyph in enumerate(glyph_order): + char_code = reverse_cmap.get(glyph) + if char_code is None: + continue + char = chr(char_code) + gid = tt_font_object.getGlyphID(glyph) + # The following is to comply with how font_glyph_byte_map works in _appearance_stream.py + gid_bytes = gid.to_bytes(2, "big") + gid_key_string = gid_bytes.decode("utf-16-be", "surrogatepass") + character_map[gid_key_string] = char + character_widths[gid_key_string] = int(round(metrics[glyph][0] * scale_factor, 0)) + else: + raise PdfReadError("Font file does not have a cmap table") + + space_char = cls._get_space_char(encoding, character_map) + cls._add_default_width(character_widths, font_descriptor_kwargs["flags"], space_char) + space_width = cls._add_space_width( + character_widths, font_descriptor_kwargs["flags"], space_char + ) + + return cls( + name=font_descriptor.name, + sub_type="TrueType", + encoding=encoding, + font_descriptor=font_descriptor, + character_map=character_map, + character_widths=character_widths, + space_width=space_width, + space_char=space_char, + interpretable=True + ) + + def _get_typographic_maps(self) -> tuple[dict[str, str], dict[str, bytes]]: + """ + Generates maps to translate input unicode text to bytes in two steps: + Unicode code point -> raw_character (reverse cmap) -> PDF bytes (encoding cmap). + """ + reverse_cmap = {} + encoding_cmap = {} + if ( + HAS_FONTTOOLS + and getattr(self.font_descriptor, "font_file", None) + and isinstance(self.encoding, str) + ): + try: + font_file_data = cast(StreamObject, self.font_descriptor.font_file).get_data() + with TTFont(BytesIO(font_file_data)) as tt_font_object: + tt_font_cmap_table = tt_font_object.get("cmap") + best_cmap = tt_font_cmap_table.getBestCmap() + for unicode_int, glyph_name in best_cmap.items(): + gid = tt_font_object.getGlyphID(glyph_name) + gid_bytes = gid.to_bytes(2, "big") + gid_key_string = gid_bytes.decode("utf-16-be", "surrogatepass") + unicode_char = chr(unicode_int) + reverse_cmap[unicode_char] = gid_key_string + encoding_cmap[gid_key_string] = gid_key_string.encode(self.encoding) + + return reverse_cmap, encoding_cmap + + except (AttributeError, TTLibError): # Cmap table is missing or the font is corrupt. + reverse_cmap.clear() + encoding_cmap.clear() + + if isinstance(self.encoding, str): + for glyph_id, unicode_char in self.character_map.items(): + glyph_id_str = str(glyph_id) + reverse_cmap[unicode_char] = glyph_id_str + encoding_cmap[glyph_id_str] = glyph_id_str.encode(self.encoding) + else: + for character_code, unicode_char in self.encoding.items(): + character_str = chr(character_code) + reverse_cmap[unicode_char] = character_str + encoding_cmap[character_str] = bytes((character_code,)) + + unicode_to_bytes = { + unicode_char: bytes((character_code,)) for character_code, unicode_char in self.encoding.items() + } + for glyph_id, unicode_char in self.character_map.items(): # This code is not covered nor tested + reverse_cmap[unicode_char] = glyph_id + encoding_cmap[glyph_id] = unicode_to_bytes.get(unicode_char, bytes((glyph_id,))) + + return reverse_cmap, encoding_cmap + + def _create_widths_list_and_unicode_stream(self) -> tuple[list[PdfObject], StreamObject]: + widths_list = [] + unicode_map = [] + # In the loop, char is the decoded GID string (the reverse unicode hack) + # and character_map[char] is the actual character. + # The widths (/W) array can have two formats: + # [first_cid [w1 w2 w3]] or [first last width] + # Here we choose the first format and simply provide one array with one width for every cid. + for gid_str, actual_char in self.character_map.items(): + # Make sure that we do not include characters such as arabic presentation form characters. + # Note that, in some cases, unicodedata.normalize() might split a ligature, resulting + # in multiple characters. + normalized_chars = unicodedata.normalize("NFKC", actual_char) + uni_points = [ord(char) for char in normalized_chars] + # Only deal with Basic Multilingual Plane characters. + # TODO: Add all characters. + if all(uni_point <= 0xFFFF for uni_point in uni_points): + cid = ord(gid_str) + cid_hex = f"{cid:04X}" + uni_hex = "".join(f"{uni_point:04X}" for uni_point in uni_points) + unicode_map.append(f"<{cid_hex}> <{uni_hex}>") + + width = self.character_widths.get(gid_str, self.character_widths["default"]) + widths_list.extend([NumberObject(cid), ArrayObject([NumberObject(width)])]) + + # Create the /ToUnicode CMap Stream + to_unicode_stream = StreamObject() + to_unicode_stream.set_data( + ( + "/CIDInit /ProcSet findresource begin\n" + "12 dict begin\n" + "begincmap\n" + "/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n" + "/CMapName /Adobe-Identity-UCS def\n" + "/CMapType 2 def\n" + "1 begincodespacerange <0000> endcodespacerange\n" + f"{len(unicode_map)} beginbfchar\n" + + "\n".join(unicode_map) + "\n" + "endbfchar\n" + "endcmap\n" + "CMapName currentdict /CMap defineresource pop\n" + "end end" + ).encode("ascii") + ) + + return widths_list, to_unicode_stream + + def as_font_resource(self) -> DictionaryObject: + # If we have an embedded Truetype font, we assume that we need to produce a Type 2 CID font resource. + if self.font_descriptor.font_file and self.sub_type == "TrueType": + # Begin with creating the widths array (part of the descendant font) and the unicode cmap (part + # of the Type 0 font object). + widths_list, to_unicode_stream = self._create_widths_list_and_unicode_stream() + + # Create the descendant font object + cid_font = DictionaryObject({ + NameObject("/Type"): NameObject("/Font"), + NameObject("/Subtype"): NameObject("/CIDFontType2"), + NameObject("/BaseFont"): NameObject(f"/{self.name}"), + NameObject("/CIDSystemInfo"): DictionaryObject({ + NameObject("/Registry"): TextStringObject("Adobe"), + NameObject("/Ordering"): TextStringObject("Identity"), + NameObject("/Supplement"): NumberObject(0) + }), + NameObject("/FontDescriptor"): self.font_descriptor.as_font_descriptor_resource(), + NameObject("/W"): ArrayObject(widths_list), + NameObject("/DW"): NumberObject(self.character_widths["default"]), + NameObject("/CIDToGIDMap"): NameObject("/Identity") + }) + + # Create the Type 0 font object + return DictionaryObject({ + NameObject("/Type"): NameObject("/Font"), + NameObject("/Subtype"): NameObject("/Type0"), + NameObject("/BaseFont"): NameObject(f"/{self.name}"), + NameObject("/Encoding"): NameObject("/Identity-H"), + NameObject("/DescendantFonts"): ArrayObject([cid_font]), + NameObject("/ToUnicode"): to_unicode_stream, + }) + + # Fallback: Return a font resource for one of the 14 Adobe Core fonts. + return DictionaryObject({ + NameObject("/Type"): NameObject("/Font"), + NameObject("/Subtype"): NameObject("/Type1"), + NameObject("/Name"): NameObject(f"/{self.name}"), + NameObject("/BaseFont"): NameObject(f"/{self.name}"), + NameObject("/Encoding"): NameObject("/WinAnsiEncoding") + }) + + def _add_to_writer( + self, + writer: PdfWriter, + target_resource_dict: DictionaryObject, + font_resource_name: NameObject + ) -> IndirectObject: + """ + Some objects in a font resource need to be indirect objects. This method + ensures that ToUnicode, FontDescriptor, FontFile, and, ultimately, the font + resource itself, are registered with the PdfWriter instance as indirect objects. + """ + font_resource = self.as_font_resource() + if "/ToUnicode" in font_resource: + font_resource[NameObject("/ToUnicode")] = writer._add_object(font_resource["/ToUnicode"]) + + if "/DescendantFonts" in font_resource: + descendant_fonts = cast(ArrayObject, font_resource["/DescendantFonts"]) + font_resource_dict = cast(DictionaryObject, descendant_fonts[0]) + else: + font_resource_dict = font_resource + + if "/FontDescriptor" in font_resource_dict: + font_descriptor_obj = cast(DictionaryObject, font_resource_dict["/FontDescriptor"]) + for key in ["/FontFile", "/FontFile2", "/FontFile3"]: + if key in font_descriptor_obj: + font_descriptor_obj[NameObject(key)] = writer._add_object(font_descriptor_obj[key]) + font_resource_dict[NameObject("/FontDescriptor")] = writer._add_object( + font_resource_dict["/FontDescriptor"] + ) + font_resource_ref = writer._add_object(font_resource) + target_resource_dict[font_resource_name] = font_resource_ref + return font_resource_ref + + def get_text_width(self, text: str = "") -> float: + """Sum of character widths specified in PDF font for the supplied text.""" + return sum( + [self.character_widths.get(char, self.character_widths["default"]) for char in text], 0.0 + ) + + def can_encode(self, text: str) -> bool: + """Check whether the font is able to encode a text string.""" + try: + if self.character_map: + supported_chars = set(self.character_map.values()) + return all(char in supported_chars for char in text) + if isinstance(self.encoding, str): + text.encode(self.encoding, "surrogatepass") + else: + supported_chars = set(self.encoding.values()) + return all(char in supported_chars for char in text) + + except UnicodeEncodeError: + return False + + return True diff --git a/.venv/lib/python3.13/site-packages/pypdf/_page.py b/.venv/lib/python3.13/site-packages/pypdf/_page.py new file mode 100644 index 0000000000000000000000000000000000000000..0969e6d82daa07cf2cea6954b4e870223b00f51a --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/_page.py @@ -0,0 +1,2544 @@ +# Copyright (c) 2006, Mathieu Fenniak +# Copyright (c) 2007, Ashish Kulkarni +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * The name of the author may not be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +import math +from collections.abc import Iterable, Iterator, Sequence +from copy import deepcopy +from dataclasses import asdict, dataclass +from decimal import Decimal +from io import BytesIO +from pathlib import Path +from typing import ( + Any, + Callable, + Literal, + Optional, + Union, + cast, + overload, +) + +from ._font import Font +from ._protocols import PdfCommonDocProtocol +from ._text_extraction import ( + _layout_mode, +) +from ._text_extraction._text_extractor import TextExtraction +from ._utils import ( + CompressedTransformationMatrix, + TransformationMatrixType, + _human_readable_bytes, + deprecate, + deprecate_no_replacement, + deprecate_with_replacement, + logger_warning, + matrix_multiply, +) +from .actions import Action, PageTrigger +from .constants import ( + _INLINE_IMAGE_KEY_MAPPING, + _INLINE_IMAGE_VALUE_MAPPING, + AnnotationDictionaryAttributes, + ImageAttributes, +) +from .constants import PageAttributes as PG +from .constants import Resources as RES +from .errors import PageSizeNotDefinedError, PdfReadError +from .generic import ( + ArrayObject, + ContentStream, + DictionaryObject, + EncodedStreamObject, + FloatObject, + IndirectObject, + NameObject, + NullObject, + NumberObject, + PdfObject, + RectangleObject, + StreamObject, + is_null_or_none, +) + +try: + from PIL.Image import Image + + pil_not_imported = False +except ImportError: + Image = object # type: ignore[assignment,misc,unused-ignore] # TODO: Remove unused-ignore on Python 3.10 + pil_not_imported = True # error will be raised only when using images + +MERGE_CROP_BOX = "cropbox" # pypdf <= 3.4.0 used "trimbox" + + +def _get_rectangle(self: Any, name: str, defaults: Iterable[str]) -> RectangleObject: + retval: Union[RectangleObject, ArrayObject, IndirectObject, None] = self.get(name) + if isinstance(retval, RectangleObject): + return retval + if is_null_or_none(retval): + for d in defaults: + retval = self.get(d) + if retval is not None: + break + if isinstance(retval, IndirectObject): + retval = self.pdf.get_object(retval) + if isinstance(retval, ArrayObject) and (length := len(retval)) != 4: + if length > 4: + # Keep backwards-compatibility with files previously written in a + # broken way by pypdf, which carried more than four values. + logger_warning( + "Expected four values, got %(length)d: %(retval)s", + source=__name__, + length=length, + retval=retval, + ) + retval = RectangleObject(tuple(retval[:4])) + else: + raise ValueError( + f"Expected four values for {name}, got {length}: {retval}" + ) + else: + retval = RectangleObject(retval) # type: ignore[arg-type] + _set_rectangle(self, name, retval) + return retval + + +def _set_rectangle(self: Any, name: str, value: Union[RectangleObject, float]) -> None: + self[NameObject(name)] = value + + +def _delete_rectangle(self: Any, name: str) -> None: + del self[name] + + +def _create_rectangle_accessor(name: str, fallback: Iterable[str]) -> property: + return property( + lambda self: _get_rectangle(self, name, fallback), + lambda self, value: _set_rectangle(self, name, value), + lambda self: _delete_rectangle(self, name), + ) + + +class Transformation: + """ + Represent a 2D transformation. + + The transformation between two coordinate systems is represented by a 3-by-3 + transformation matrix with the following form:: + + a b 0 + c d 0 + e f 1 + + Because a transformation matrix has only six elements that can be changed, + it is usually specified in PDF as the six-element array [ a b c d e f ]. + + Coordinate transformations are expressed as matrix multiplications:: + + a b 0 + [ x′ y′ 1 ] = [ x y 1 ] × c d 0 + e f 1 + + + Example: + >>> from pypdf import PdfWriter, Transformation + >>> page = PdfWriter().add_blank_page(800, 600) + >>> op = Transformation().scale(sx=2, sy=3).translate(tx=10, ty=20) + >>> page.add_transformation(op) + + """ + + def __init__(self, ctm: CompressedTransformationMatrix = (1, 0, 0, 1, 0, 0)) -> None: + self.ctm = ctm + + @property + def matrix(self) -> TransformationMatrixType: + """ + Return the transformation matrix as a tuple of tuples in the form: + + ((a, b, 0), (c, d, 0), (e, f, 1)) + """ + return ( + (self.ctm[0], self.ctm[1], 0), + (self.ctm[2], self.ctm[3], 0), + (self.ctm[4], self.ctm[5], 1), + ) + + @staticmethod + def compress(matrix: TransformationMatrixType) -> CompressedTransformationMatrix: + """ + Compresses the transformation matrix into a tuple of (a, b, c, d, e, f). + + Args: + matrix: The transformation matrix as a tuple of tuples. + + Returns: + A tuple representing the transformation matrix as (a, b, c, d, e, f) + + """ + return ( + matrix[0][0], + matrix[0][1], + matrix[1][0], + matrix[1][1], + matrix[2][0], + matrix[2][1], + ) + + def _to_cm(self) -> str: + # Returns the cm operation string for the given transformation matrix + return ( + f"{self.ctm[0]:.4f} {self.ctm[1]:.4f} {self.ctm[2]:.4f} " + f"{self.ctm[3]:.4f} {self.ctm[4]:.4f} {self.ctm[5]:.4f} cm" + ) + + def transform(self, m: "Transformation") -> "Transformation": + """ + Apply one transformation to another. + + Args: + m: a Transformation to apply. + + Returns: + A new ``Transformation`` instance + + Example: + >>> from pypdf import PdfWriter, Transformation + >>> height, width = 40, 50 + >>> page = PdfWriter().add_blank_page(800, 600) + >>> op = Transformation((1, 0, 0, -1, 0, height)) # vertical mirror + >>> op = Transformation().transform(Transformation((-1, 0, 0, 1, width, 0))) # horizontal mirror + >>> page.add_transformation(op) + + """ + ctm = Transformation.compress(matrix_multiply(self.matrix, m.matrix)) + return Transformation(ctm) + + def translate(self, tx: float = 0, ty: float = 0) -> "Transformation": + """ + Translate the contents of a page. + + Args: + tx: The translation along the x-axis. + ty: The translation along the y-axis. + + Returns: + A new ``Transformation`` instance + + """ + m = self.ctm + return Transformation(ctm=(m[0], m[1], m[2], m[3], m[4] + tx, m[5] + ty)) + + def scale( + self, sx: Optional[float] = None, sy: Optional[float] = None + ) -> "Transformation": + """ + Scale the contents of a page towards the origin of the coordinate system. + + Typically, that is the lower-left corner of the page. That can be + changed by translating the contents / the page boxes. + + Args: + sx: The scale factor along the x-axis. + sy: The scale factor along the y-axis. + + Returns: + A new Transformation instance with the scaled matrix. + + """ + if sx is None and sy is None: + raise ValueError("Either sx or sy must be specified") + if sx is None: + sx = sy + if sy is None: + sy = sx + assert sx is not None + assert sy is not None + op: TransformationMatrixType = ((sx, 0, 0), (0, sy, 0), (0, 0, 1)) + ctm = Transformation.compress(matrix_multiply(self.matrix, op)) + return Transformation(ctm) + + def rotate(self, rotation: float) -> "Transformation": + """ + Rotate the contents of a page. + + Args: + rotation: The angle of rotation in degrees. + + Returns: + A new ``Transformation`` instance with the rotated matrix. + + """ + rotation = math.radians(rotation) + op: TransformationMatrixType = ( + (math.cos(rotation), math.sin(rotation), 0), + (-math.sin(rotation), math.cos(rotation), 0), + (0, 0, 1), + ) + ctm = Transformation.compress(matrix_multiply(self.matrix, op)) + return Transformation(ctm) + + def __repr__(self) -> str: + return f"Transformation(ctm={self.ctm})" + + @overload + def apply_on(self, pt: list[float], as_object: bool = False) -> list[float]: + ... + + @overload + def apply_on( + self, pt: tuple[float, float], as_object: bool = False + ) -> tuple[float, float]: + ... + + def apply_on( + self, + pt: Union[tuple[float, float], list[float]], + as_object: bool = False, + ) -> Union[tuple[float, float], list[float]]: + """ + Apply the transformation matrix on the given point. + + Args: + pt: A tuple or list representing the point in the form (x, y). + as_object: If True, return items as FloatObject, otherwise as plain floats. + + Returns: + A tuple or list representing the transformed point in the form (x', y') + + """ + typ = FloatObject if as_object else float + pt1 = ( + typ(float(pt[0]) * self.ctm[0] + float(pt[1]) * self.ctm[2] + self.ctm[4]), + typ(float(pt[0]) * self.ctm[1] + float(pt[1]) * self.ctm[3] + self.ctm[5]), + ) + return list(pt1) if isinstance(pt, list) else pt1 + + +@dataclass +class ImageFile: + """ + Image within the PDF file. *This object is not designed to be built.* + + This object should not be modified except using :func:`ImageFile.replace` to replace the image with a new one. + """ + + name: str = "" + """ + Filename as identified within the PDF file. + + .. warning:: + + This value can contain arbitrary characters. Please make sure to sanitize it before + using it to write the file content to the disk for example. + """ + + data: bytes = b"" + """ + Data as bytes. + """ + + image: Optional[Image] = None + """ + Data as PIL image. + """ + + indirect_reference: Optional[IndirectObject] = None + """ + Reference to the object storing the stream. + """ + + is_inline: bool = False + """ + True if this is an inline image (~0~, ~1~, etc.). + """ + + is_displayed: bool = False + """ + True if this image is displayed in the page content stream. + """ + + def replace(self, new_image: Image, **kwargs: Any) -> None: + """ + Replace the image with a new PIL image. + + Args: + new_image (PIL.Image.Image): The new PIL image to replace the existing image. + **kwargs: Additional keyword arguments to pass to `Image.save()`. + + Raises: + TypeError: If the image is inline or in a PdfReader. + TypeError: If the image does not belong to a PdfWriter. + TypeError: If `new_image` is not a PIL Image. + + Note: + This method replaces the existing image with a new image. + It is not allowed for inline images or images within a PdfReader. + The `kwargs` parameter allows passing additional parameters + to `Image.save()`, such as quality. + + """ + if pil_not_imported: + raise ImportError( + "pillow is required to do image extraction. " + "It can be installed via 'pip install pypdf[image]'" + ) + + from ._reader import PdfReader # noqa: PLC0415 + from .generic import DictionaryObject, PdfObject # noqa: PLC0415 + from .generic._image_xobject import _xobj_to_image # noqa: PLC0415 + + if self.indirect_reference is None: + raise TypeError("Cannot update an inline image.") + if not hasattr(self.indirect_reference.pdf, "_id_translated"): + raise TypeError("Cannot update an image not belonging to a PdfWriter.") + if not isinstance(new_image, Image): + raise TypeError("new_image shall be a PIL Image") + b = BytesIO() + new_image.save(b, "PDF", **kwargs) + reader = PdfReader(b) + page_image = reader.pages[0].images[0] + assert page_image.indirect_reference is not None + self.indirect_reference.pdf._objects[self.indirect_reference.idnum - 1] = ( + page_image.indirect_reference.get_object() + ) + cast( + PdfObject, self.indirect_reference.get_object() + ).indirect_reference = self.indirect_reference + # change the object attributes + extension, byte_stream, img = _xobj_to_image( + cast(DictionaryObject, self.indirect_reference.get_object()), + pillow_parameters=kwargs, + ) + assert extension is not None + self.name = self.name[: self.name.rfind(".")] + extension + self.data = byte_stream + self.image = img + + def __str__(self) -> str: + return f"{self.__class__.__name__}(name={self.name}, data: {_human_readable_bytes(len(self.data))})" + + def __repr__(self) -> str: + return self.__str__()[:-1] + f", hash: {hash(self.data)})" + + +class VirtualListImages(Sequence[ImageFile]): + """ + Provides access to images referenced within a page. + Only one copy will be returned if the usage is used on the same page multiple times. + See :func:`PageObject.images` for more details. + """ + + def __init__( + self, + ids_function: Callable[[], list[Union[str, list[str]]]], + get_function: Callable[[Union[str, list[str], tuple[str]]], ImageFile], + ) -> None: + self.ids_function = ids_function + self.get_function = get_function + self.current = -1 + + def __len__(self) -> int: + return len(self.ids_function()) + + def keys(self) -> list[Union[str, list[str]]]: + return self.ids_function() + + def items(self) -> list[tuple[Union[str, list[str]], ImageFile]]: + return [(x, self[x]) for x in self.ids_function()] + + @overload + def __getitem__(self, index: Union[int, str, list[str]]) -> ImageFile: + ... + + @overload + def __getitem__(self, index: slice) -> Sequence[ImageFile]: + ... + + def __getitem__( + self, index: Union[int, slice, str, list[str], tuple[str]] + ) -> Union[ImageFile, Sequence[ImageFile]]: + lst = self.ids_function() + if isinstance(index, slice): + indices = range(*index.indices(len(self))) + lst = [lst[x] for x in indices] + cls = type(self) + return cls((lambda: lst), self.get_function) + if isinstance(index, (str, list, tuple)): + return self.get_function(index) + if not isinstance(index, int): + raise TypeError("Invalid sequence indices type") + len_self = len(lst) + if index < 0: + # support negative indexes + index += len_self + if not (0 <= index < len_self): + raise IndexError("Sequence index out of range") + return self.get_function(lst[index]) + + def __iter__(self) -> Iterator[ImageFile]: + for i in range(len(self)): + yield self[i] + + def __str__(self) -> str: + p = [f"Image_{i}={n}" for i, n in enumerate(self.ids_function())] + return f"[{', '.join(p)}]" + + +class PageObject(DictionaryObject): + """ + PageObject represents a single page within a PDF file. + + Typically these objects will be created by accessing the + :attr:`pages` property of the + :class:`PdfReader` class, but it is + also possible to create an empty page with the + :meth:`create_blank_page()` static method. + + Args: + pdf: PDF file the page belongs to. + indirect_reference: Stores the original indirect reference to + this object in its source PDF + + """ + + original_page: "PageObject" # very local use in writer when appending + + def __init__( + self, + pdf: Optional[PdfCommonDocProtocol] = None, + indirect_reference: Optional[IndirectObject] = None, + ) -> None: + DictionaryObject.__init__(self) + self.pdf = pdf + self._content_stream_images: Optional[dict[str, Optional[ImageFile]]] = None + self.indirect_reference = indirect_reference + if not is_null_or_none(indirect_reference): + assert indirect_reference is not None, "mypy" + self.update(cast(DictionaryObject, indirect_reference.get_object())) + + def hash_bin(self) -> int: + """ + Used to detect modified object. + + Note: this function is overloaded to return the same results + as a DictionaryObject. + + Returns: + Hash considering type and value. + + """ + return hash( + (DictionaryObject, tuple(((k, v.hash_bin()) for k, v in self.items()))) + ) + + def hash_value_data(self) -> bytes: + data = super().hash_value_data() + data += f"{id(self)}".encode() + return data + + @property + def user_unit(self) -> float: + """ + A read-only positive number giving the size of user space units. + + It is in multiples of 1/72 inch. Hence a value of 1 means a user + space unit is 1/72 inch, and a value of 3 means that a user + space unit is 3/72 inch. + """ + return cast(float, self.get(PG.USER_UNIT, 1)) + + @staticmethod + def create_blank_page( + pdf: Optional[PdfCommonDocProtocol] = None, + width: Union[float, Decimal, None] = None, + height: Union[float, Decimal, None] = None, + ) -> "PageObject": + """ + Return a new blank page. + + If ``width`` or ``height`` is ``None``, try to get the page size + from the last page of *pdf*. + + Args: + pdf: PDF file the page is within. + width: The width of the new page expressed in default user + space units. + height: The height of the new page expressed in default user + space units. + + Returns: + The new blank page + + Raises: + PageSizeNotDefinedError: if ``pdf`` is ``None`` or contains + no page + + """ + page = PageObject(pdf) + + # Creates a new page (cf PDF Reference §7.7.3.3) + page.__setitem__(NameObject(PG.TYPE), NameObject("/Page")) + page.__setitem__(NameObject(PG.PARENT), NullObject()) + page.__setitem__(NameObject(PG.RESOURCES), DictionaryObject()) + if width is None or height is None: + if pdf is not None and len(pdf.pages) > 0: + lastpage = pdf.pages[len(pdf.pages) - 1] + width = lastpage.mediabox.width + height = lastpage.mediabox.height + else: + raise PageSizeNotDefinedError + page.__setitem__( + NameObject(PG.MEDIABOX), RectangleObject((0, 0, width, height)) # type: ignore[arg-type] + ) + + return page + + def _get_ids_image( + self, + obj: Optional[DictionaryObject] = None, + ancest: Optional[list[str]] = None, + call_stack: Optional[list[Any]] = None, + ) -> list[Union[str, list[str]]]: + if call_stack is None: + call_stack = [] + _i = getattr(obj, "indirect_reference", None) + if _i in call_stack: + return [] + call_stack.append(_i) + if self._content_stream_images is None: + self._content_stream_images = self._parse_images_from_content_stream() + if obj is None: + obj = self + if ancest is None: + ancest = [] + lst: list[Union[str, list[str]]] = [] + if ( + PG.RESOURCES not in obj or + is_null_or_none(resources := obj[PG.RESOURCES]) or + RES.XOBJECT not in cast(DictionaryObject, resources) + ): + # Forms without XObject resources have no images inside them + if len(ancest) > 0: + return [] + # for inline images, cache dict entries are not None + return [image_name for image_name, image_value in self._content_stream_images.items() if image_value] + + x_object = resources[RES.XOBJECT].get_object() # type: ignore + + # Iterate through all XObject resources + for o in x_object: + # Skip non-stream objects (only process StreamObject) + if not isinstance(x_object[o], StreamObject): + continue + if x_object[o][ImageAttributes.SUBTYPE] == "/Image": + # If it's an image, add it to lst for further processing + lst.append(o if len(ancest) == 0 else [*ancest, o]) + else: + # If it's a form, recursively search for images inside it + # Forms may contain images that are Do-referenced in their content stream + lst.extend(self._get_ids_image(x_object[o], [*ancest, o], call_stack)) + + # Removes duplicates and preserves order + deduplicated = lst.copy() + + # Add inline images from _content_stream_images + for object_name, object_value in self._content_stream_images.items(): + # inline images have cache populated + if object_name not in deduplicated and object_value: + deduplicated.append(object_name) + + return deduplicated + + def _get_image( + self, + id: Union[str, list[str], tuple[str]], + obj: Optional[DictionaryObject] = None, + ) -> ImageFile: + if obj is None: + obj = cast(DictionaryObject, self) + if isinstance(id, tuple): + id = list(id) + if isinstance(id, list) and len(id) == 1: + id = id[0] + xobjs: Optional[DictionaryObject] = None + try: + xobjs = cast( + DictionaryObject, cast(DictionaryObject, obj[PG.RESOURCES])[RES.XOBJECT] + ) + except KeyError as exc: + if not (id[0] == "~" and id[-1] == "~"): + raise KeyError( + f"Cannot access image object {id} without XObject resources" + ) from exc + if isinstance(id, str): + if id[0] == "~" and id[-1] == "~": + if self._content_stream_images is None: + self._content_stream_images = self._parse_images_from_content_stream() + if id not in self._content_stream_images: + raise KeyError(f"Image {id} not found") + image_file = self._content_stream_images[id] + assert image_file is not None + return image_file + + # Do-referenced image name (non-inline string keys like /Im0) + assert xobjs is not None + if id not in xobjs: + raise KeyError(f"Image {id} not found") + xobj = cast(DictionaryObject, xobjs[id]) + if xobj.get(ImageAttributes.SUBTYPE, "") != "/Image": + raise KeyError(f"XObject {id} is not an image") + + # Check if displayed (in content stream) + is_displayed = self._content_stream_images is not None and id in self._content_stream_images + + from .generic._image_xobject import _xobj_to_image # noqa: PLC0415 + extension, byte_stream, img = _xobj_to_image(xobj) + return ImageFile( + name=f"{id[1:]}{extension}", + data=byte_stream, + image=img, + indirect_reference=xobj.indirect_reference, + is_inline=False, + is_displayed=is_displayed, + ) + # in a subobject + assert xobjs is not None + ids = id[1:] + return self._get_image(ids, cast(DictionaryObject, xobjs[id[0]])) + + @property + def images(self) -> VirtualListImages: + """ + Read-only property emulating a list of images on a page. + + Get a list of all images on the page. The key can be: + - A string (for the top object) + - A tuple (for images within XObject forms) + - An integer + + Examples: + * `reader.pages[0].images[0]` # return first image + * `reader.pages[0].images['/I0']` # return image '/I0' + * `reader.pages[0].images['/TP1','/Image1']` # return image '/Image1' within '/TP1' XObject form + * `for img in reader.pages[0].images:` # loops through all objects + + Example usage: + + >>> from pypdf import PdfWriter + >>> writer = PdfWriter() + >>> page = writer.add_blank_page(800, 600) + >>> images = page.images + + """ + return VirtualListImages(self._get_ids_image, self._get_image) + + @property + def inline_images(self) -> Optional[dict[str, ImageFile]]: + """ + Return only inline images from the page. + + .. deprecated:: + Use :attr:`images` and filter by :attr:`ImageFile.is_inline` instead. + This property will be removed in pypdf 7.0. + + Examples: + >>> from pypdf import PdfWriter + >>> writer = PdfWriter() + >>> page = writer.add_blank_page(800,600) + >>> for image_name, image_file in page.images.items(): + ... if image_file.is_inline: + ... print(f"{image_name} is inline") + """ + deprecate_with_replacement( + "PageObject.inline_images", + "PageObject.images", + "7.0.0", + ) + if self._content_stream_images is None: + return None + return { + image_name: image_file + for image_name, image_file in self._content_stream_images.items() + if image_file and image_file.is_inline # for inline images, image_file is populated + } + + @inline_images.setter + def inline_images(self, value: Optional[dict[str, ImageFile]]) -> None: + deprecate_no_replacement( + "PageObject.inline_images", + "7.0.0", + ) + if value is None: + self._content_stream_images = None + else: + assert self._content_stream_images is not None, "Can't edit inline_images before accessing images" + self._content_stream_images.update(value) + + def _translate_value_inline_image(self, k: str, v: PdfObject) -> PdfObject: + """Translate values used in inline image""" + try: + v = NameObject(_INLINE_IMAGE_VALUE_MAPPING[cast(str, v)]) + except (TypeError, KeyError): + if isinstance(v, NameObject): + # It is a custom name, thus we have to look in resources. + # The only applicable case is for ColorSpace. + try: + res = cast(DictionaryObject, self["/Resources"])["/ColorSpace"] + v = cast(DictionaryObject, res)[v] + except KeyError: # for res and v + raise PdfReadError(f"Cannot find resource entry {v} for {k}") + return v + + def _parse_images_from_content_stream(self) -> dict[str, Optional[ImageFile]]: + """Load images from content stream. Includes both inline images and Do-referenced images. + + This method scans the page content stream and extracts: + + 1. **Inline images** (~0~, ~1~...): Embedded directly in content stream via BI/EI operators + - is_inline=True, is_displayed=True, indirect_reference=None + + 2. **Do-referenced objects** (/Im0, /Im1..., /Form1...): Referenced via "Do" operator + - is_inline=False, is_displayed=True, indirect_reference= + + 3. **Pure XObject images** (/I0, /Image1...): Defined in Resources only (not in content stream) + - is_inline=False, is_displayed=False, indirect_reference= + + Returns: + Dictionary mapping names to ImageFile instances (inline) or None (Do-referenced). + """ + content = self.get_contents() + if is_null_or_none(content): + return {} + imgs_data = [] + do_image_names: list[bytes] = [] + assert content is not None, "mypy" + for param, ope in content.operations: + if ope == b"INLINE IMAGE": + imgs_data.append( + {"settings": param["settings"], "__streamdata__": param["data"]} + ) + elif ope == b"Do" and param: + do_image_names.append(param[0]) # First operand is the XObject name + elif ope in (b"BI", b"EI", b"ID"): # pragma: no cover + raise PdfReadError( + f"{ope!r} operator met whereas not expected, " + "please share use case with pypdf dev team" + ) + + files: dict[str, Optional[ImageFile]] = {} + # Process Do-referenced objects first (images + forms, no subtype check) + files = dict.fromkeys(list(map(str, do_image_names)), None) + + # Then process inline images + for num, ii in enumerate(imgs_data): + init = { + "__streamdata__": ii["__streamdata__"], + "/Length": len(ii["__streamdata__"]), + } + for k, v in ii["settings"].items(): + if k in {"/Length", "/L"}: # no length is expected + continue + if isinstance(v, list): + v = ArrayObject( + [self._translate_value_inline_image(k, x) for x in v] + ) + else: + v = self._translate_value_inline_image(k, v) + if k in _INLINE_IMAGE_KEY_MAPPING: + k = NameObject(_INLINE_IMAGE_KEY_MAPPING[k]) + else: + logger_warning( + "Unknown inline image key %(key)s, keeping it as-is.", + source=__name__, + key=k, + ) + k = NameObject(k) + if k not in init: + init[k] = v + ii["object"] = EncodedStreamObject.initialize_from_dictionary(init) + from .generic._image_xobject import _xobj_to_image # noqa: PLC0415 + extension, byte_stream, img = _xobj_to_image(ii["object"]) + files[f"~{num}~"] = ImageFile( + name=f"~{num}~{extension}", + data=byte_stream, + image=img, + indirect_reference=None, + is_inline=True, + is_displayed=True, + ) + + return files + + @property + def rotation(self) -> int: + """ + The visual rotation of the page. + + This number has to be a multiple of 90 degrees: 0, 90, 180, or 270 are + valid values. This property does not affect ``/Contents``. + """ + rotate_obj = self.get(PG.ROTATE, 0) + return rotate_obj if isinstance(rotate_obj, int) else rotate_obj.get_object() + + @rotation.setter + def rotation(self, r: float) -> None: + self[NameObject(PG.ROTATE)] = NumberObject((((int(r) + 45) // 90) * 90) % 360) + + def transfer_rotation_to_content(self) -> None: + """ + Apply the rotation of the page to the content and the media/crop/... + boxes. + + It is recommended to apply this function before page merging. + """ + r = -self.rotation # rotation to apply is in the otherway + self.rotation = 0 + mb = RectangleObject(self.mediabox) + trsf = ( + Transformation() + .translate( + -float(mb.left + mb.width / 2), -float(mb.bottom + mb.height / 2) + ) + .rotate(r) + ) + pt1 = trsf.apply_on(mb.lower_left) + pt2 = trsf.apply_on(mb.upper_right) + trsf = trsf.translate(-min(pt1[0], pt2[0]), -min(pt1[1], pt2[1])) + self.add_transformation(trsf, False) + for b in ["/MediaBox", "/CropBox", "/BleedBox", "/TrimBox", "/ArtBox"]: + if b in self: + rr = RectangleObject(self[b]) # type: ignore[arg-type] + pt1 = trsf.apply_on(rr.lower_left) + pt2 = trsf.apply_on(rr.upper_right) + self[NameObject(b)] = RectangleObject( + ( + min(pt1[0], pt2[0]), + min(pt1[1], pt2[1]), + max(pt1[0], pt2[0]), + max(pt1[1], pt2[1]), + ) + ) + + def rotate(self, angle: int) -> "PageObject": + """ + Rotate a page clockwise by increments of 90 degrees. + + Args: + angle: Angle to rotate the page. Must be an increment of 90 deg. + + Returns: + The rotated PageObject + + """ + if angle % 90 != 0: + raise ValueError("Rotation angle must be a multiple of 90") + self[NameObject(PG.ROTATE)] = NumberObject(self.rotation + angle) + return self + + def _merge_resources( + self, + res1: DictionaryObject, + res2: DictionaryObject, + resource: Any, + new_res1: bool = True, + ) -> tuple[dict[str, Any], dict[str, Any]]: + try: + assert isinstance(self.indirect_reference, IndirectObject) + pdf = self.indirect_reference.pdf + is_pdf_writer = hasattr( + pdf, "_add_object" + ) # expect isinstance(pdf, PdfWriter) + except (AssertionError, AttributeError): + pdf = None + is_pdf_writer = False + + def compute_unique_key(base_key: str) -> tuple[str, bool]: + """ + Find a key that either doesn't already exist or has the same value + (indicated by the bool) + + Args: + base_key: An index is added to this to get the computed key + + Returns: + A tuple (computed key, bool) where the boolean indicates + if there is a resource of the given computed_key with the same + value. + + """ + value = page2res.raw_get(base_key) + # TODO: a possible improvement for writer, the indirect_reference + # cannot be found because translated + + # try the current key first (e.g. "foo"), but otherwise iterate + # through "foo-0", "foo-1", etc. new_res can contain only finitely + # many keys, thus this'll eventually end, even if it's been crafted + # to be maximally annoying. + computed_key = base_key + idx = 0 + while computed_key in new_res: + if new_res.raw_get(computed_key) == value: + # there's already a resource of this name, with the exact + # same value + return computed_key, True + computed_key = f"{base_key}-{idx}" + idx += 1 + return computed_key, False + + if new_res1: + new_res = DictionaryObject() + new_res.update(res1.get(resource, DictionaryObject()).get_object()) + else: + new_res = cast(DictionaryObject, res1[resource]) + page2res = cast( + DictionaryObject, res2.get(resource, DictionaryObject()).get_object() + ) + rename_res = {} + for key in page2res: + unique_key, same_value = compute_unique_key(key) + newname = NameObject(unique_key) + if key != unique_key: + # we have to use a different name for this + rename_res[key] = newname + + if not same_value: + if is_pdf_writer: + new_res[newname] = page2res.raw_get(key).clone(pdf) + try: + new_res[newname] = new_res[newname].indirect_reference + except AttributeError: + pass + else: + new_res[newname] = page2res.raw_get(key) + lst = sorted(new_res.items()) + new_res.clear() + for el in lst: + new_res[el[0]] = el[1] + return new_res, rename_res + + @staticmethod + def _content_stream_rename( + stream: ContentStream, + rename: dict[Any, Any], + pdf: Optional[PdfCommonDocProtocol], + ) -> ContentStream: + if not rename: + return stream + stream = ContentStream(stream, pdf) + for operands, _operator in stream.operations: + if isinstance(operands, list): + for i, op in enumerate(operands): + if isinstance(op, NameObject): + operands[i] = rename.get(op, op) + elif isinstance(operands, dict): + for i, op in operands.items(): + if isinstance(op, NameObject): + operands[i] = rename.get(op, op) + else: + raise KeyError(f"Type of operands is {type(operands)}") + return stream + + @staticmethod + def _add_transformation_matrix( + contents: Any, + pdf: Optional[PdfCommonDocProtocol], + ctm: CompressedTransformationMatrix, + ) -> ContentStream: + """Add transformation matrix at the beginning of the given contents stream.""" + content_stream = ContentStream(contents, pdf) + content_stream.operations.insert( + 0, + ( + [FloatObject(x) for x in ctm], + b"cm", + ), + ) + return content_stream + + def _get_contents_as_bytes(self) -> Optional[bytes]: + """ + Return the page contents as bytes. + + Returns: + The ``/Contents`` object as bytes, or ``None`` if it doesn't exist. + + """ + if PG.CONTENTS in self: + obj = self[PG.CONTENTS].get_object() + if isinstance(obj, list): + return b"".join(x.get_object().get_data() for x in obj) + return cast(EncodedStreamObject, obj).get_data() + return None + + def get_contents(self) -> Optional[ContentStream]: + """ + Access the page contents. + + Returns: + The ``/Contents`` object, or ``None`` if it does not exist. + ``/Contents`` is optional, as described in §7.7.3.3 of the PDF Reference. + + """ + if PG.CONTENTS in self: + try: + pdf = cast(IndirectObject, self.indirect_reference).pdf + except AttributeError: + pdf = None + obj = self[PG.CONTENTS] + if is_null_or_none(obj): + return None + resolved_object = obj.get_object() + return ContentStream(resolved_object, pdf) + return None + + def replace_contents( + self, content: Union[ContentStream, EncodedStreamObject, ArrayObject, None] + ) -> None: + """ + Replace the page contents with the new content and nullify old objects + Args: + content: new content; if None delete the content field. + """ + if not hasattr(self, "indirect_reference") or self.indirect_reference is None: + # the page is not attached : the content is directly attached. + self[NameObject(PG.CONTENTS)] = content + return + + from pypdf._writer import PdfWriter # noqa: PLC0415 + if not isinstance(self.indirect_reference.pdf, PdfWriter): + deprecate( + "Calling `PageObject.replace_contents()` for pages not assigned to a writer is deprecated " + "and will be removed in pypdf 7.0.0. Attach the page to the writer first or use " + "`PdfWriter(clone_from=...)` directly. The existing approach has proved being unreliable." + ) + + writer = self.indirect_reference.pdf + if isinstance(self.get(PG.CONTENTS, None), ArrayObject): + content_array = cast(ArrayObject, self[PG.CONTENTS]) + for reference in content_array: + try: + writer._replace_object(indirect_reference=reference.indirect_reference, obj=NullObject()) + except ValueError: + # Occurs when called on PdfReader. + pass + + if isinstance(content, ArrayObject): + content = ArrayObject(writer._add_object(obj) for obj in content) + + if is_null_or_none(content): + if PG.CONTENTS not in self: + return + assert self[PG.CONTENTS].indirect_reference is not None + writer._replace_object(indirect_reference=self[PG.CONTENTS].indirect_reference, obj=NullObject()) + del self[PG.CONTENTS] + elif not hasattr(self.get(PG.CONTENTS, None), "indirect_reference"): + try: + self[NameObject(PG.CONTENTS)] = writer._add_object(content) + except AttributeError: + # applies at least for page not in writer + # as a backup solution, we put content as an object although not in accordance with pdf ref + # this will be fixed with the _add_object + self[NameObject(PG.CONTENTS)] = content + else: + assert content is not None, "mypy" + content.indirect_reference = self[ + PG.CONTENTS + ].indirect_reference # TODO: in the future may require generation management + try: + writer._replace_object(indirect_reference=content.indirect_reference, obj=content) + except AttributeError: + # applies at least for page not in writer + # as a backup solution, we put content as an object although not in accordance with pdf ref + # this will be fixed with the _add_object + self[NameObject(PG.CONTENTS)] = content + # forces recalculation of images + self._content_stream_images = None + + def merge_page( + self, page2: "PageObject", expand: bool = False, over: bool = True + ) -> None: + """ + Merge the content streams of two pages into one. + + Resource references (e.g. fonts) are maintained from both pages. + The mediabox, cropbox, etc of this page are not altered. + The parameter page's content stream will + be added to the end of this page's content stream, + meaning that it will be drawn after, or "on top" of this page. + + Args: + page2: The page to be merged into this one. Should be + an instance of :class:`PageObject`. + over: set the page2 content over page1 if True (default) else under + expand: If True, the current page dimensions will be + expanded to accommodate the dimensions of the page to be merged. + + """ + self._merge_page(page2, over=over, expand=expand) + + def _merge_page( + self, + page2: "PageObject", + page2_transformation: Optional[Callable[[Any], ContentStream]] = None, + ctm: Optional[CompressedTransformationMatrix] = None, + over: bool = True, + expand: bool = False, + ) -> None: + # First we work on merging the resource dictionaries. This allows us + # to find out what symbols in the content streams we might need to + # rename. + try: + assert isinstance(self.indirect_reference, IndirectObject) + if hasattr(self.indirect_reference.pdf, "_add_object"): # to detect PdfWriter + return self._merge_page_writer( + page2, page2_transformation, ctm, over, expand + ) + except (AssertionError, AttributeError): + pass + + new_resources = DictionaryObject() + rename: dict[str, Any] = {} + original_resources = cast(DictionaryObject, self.get(PG.RESOURCES, DictionaryObject()).get_object()) + page2_resources = cast(DictionaryObject, page2.get(PG.RESOURCES, DictionaryObject()).get_object()) + new_annots = ArrayObject() + + for page in (self, page2): + if PG.ANNOTS in page: + annots = page[PG.ANNOTS] + if isinstance(annots, ArrayObject): + new_annots.extend(annots) + self[NameObject(PG.ANNOTS)] = new_annots + + for res in ( + RES.EXT_G_STATE, + RES.COLOR_SPACE, + RES.PATTERN, + RES.SHADING, + RES.XOBJECT, + RES.FONT, + RES.PROPERTIES, + ): + new, new_resource_name = self._merge_resources( + original_resources, page2_resources, res + ) + if new: + new_resources[NameObject(res)] = new + rename.update(new_resource_name) + + # Combine /ProcSet sets, making sure there is a consistent order + new_resources[NameObject(RES.PROC_SET)] = ArrayObject( + sorted( + set( + original_resources.get(RES.PROC_SET, ArrayObject()).get_object() + ).union( + set(page2_resources.get(RES.PROC_SET, ArrayObject()).get_object()) + ) + ) + ) + + new_content_array = ArrayObject() + original_content = self.get_contents() + if original_content is not None: + original_content.isolate_graphics_state() + new_content_array.append(original_content) + + page2_content = page2.get_contents() + if page2_content is not None: + rect = getattr(page2, MERGE_CROP_BOX) + page2_content.operations.insert( + 0, + ( + map( + FloatObject, + [ + rect.left, + rect.bottom, + rect.width, + rect.height, + ], + ), + b"re", + ), + ) + page2_content.operations.insert(1, ([], b"W")) + page2_content.operations.insert(2, ([], b"n")) + if page2_transformation is not None: + page2_content = page2_transformation(page2_content) + page2_content = PageObject._content_stream_rename( + page2_content, rename, self.pdf + ) + page2_content.isolate_graphics_state() + if over: + new_content_array.append(page2_content) + else: + new_content_array.insert(0, page2_content) + + # if expanding the page to fit a new page, calculate the new media box size + if expand: + self._expand_mediabox(page2, ctm) + + self.replace_contents(ContentStream(new_content_array, self.pdf)) + self[NameObject(PG.RESOURCES)] = new_resources + + return None + + def _merge_page_writer( + self, + page2: "PageObject", + page2transformation: Optional[Callable[[Any], ContentStream]] = None, + ctm: Optional[CompressedTransformationMatrix] = None, + over: bool = True, + expand: bool = False, + ) -> None: + # First we work on merging the resource dictionaries. This allows us + # to find which symbols in the content streams we might need to + # rename. + assert isinstance(self.indirect_reference, IndirectObject) + pdf = self.indirect_reference.pdf + + if PG.RESOURCES not in self: + self[NameObject(PG.RESOURCES)] = DictionaryObject() + original_resources = cast(DictionaryObject, self[PG.RESOURCES].get_object()) + if PG.RESOURCES not in page2: + page2resources = DictionaryObject() + else: + page2resources = cast(DictionaryObject, page2[PG.RESOURCES].get_object()) + + rename = {} + for res in ( + RES.EXT_G_STATE, + RES.COLOR_SPACE, + RES.PATTERN, + RES.SHADING, + RES.XOBJECT, + RES.FONT, + RES.PROPERTIES, + ): + if res in page2resources: + if res not in original_resources: + original_resources[NameObject(res)] = DictionaryObject() + _, newrename = self._merge_resources( + original_resources, page2resources, res, False + ) + rename.update(newrename) + # Combine /ProcSet sets + if RES.PROC_SET in page2resources: + if RES.PROC_SET not in original_resources: + original_resources[NameObject(RES.PROC_SET)] = ArrayObject() + arr = cast(ArrayObject, original_resources[RES.PROC_SET]) + for x in cast(ArrayObject, page2resources[RES.PROC_SET]): + if x not in arr: + arr.append(x) + arr.sort() + + if not is_null_or_none(page2.get(PG.ANNOTS, None)): + if PG.ANNOTS not in self: + self[NameObject(PG.ANNOTS)] = ArrayObject() + annots = cast(ArrayObject, self[PG.ANNOTS].get_object()) + if ctm is None: + trsf = Transformation() + else: + trsf = Transformation(ctm) + # Ensure we are working on a copy of the list. Otherwise, if both pages + # are the same object, we might run into an infinite loop. + for a in cast(ArrayObject, deepcopy(page2[PG.ANNOTS])): + a = a.get_object() + aa = a.clone( + pdf, + ignore_fields=("/P", "/StructParent", "/Parent"), + force_duplicate=True, + ) + r = cast(ArrayObject, a["/Rect"]) + pt1 = trsf.apply_on((r[0], r[1]), True) + pt2 = trsf.apply_on((r[2], r[3]), True) + aa[NameObject("/Rect")] = ArrayObject( + ( + min(pt1[0], pt2[0]), + min(pt1[1], pt2[1]), + max(pt1[0], pt2[0]), + max(pt1[1], pt2[1]), + ) + ) + if "/QuadPoints" in a: + q = cast(ArrayObject, a["/QuadPoints"]) + aa[NameObject("/QuadPoints")] = ArrayObject( + trsf.apply_on((q[0], q[1]), True) + + trsf.apply_on((q[2], q[3]), True) + + trsf.apply_on((q[4], q[5]), True) + + trsf.apply_on((q[6], q[7]), True) + ) + try: + aa["/Popup"][NameObject("/Parent")] = aa.indirect_reference + except KeyError: + pass + try: + aa[NameObject("/P")] = self.indirect_reference + annots.append(aa.indirect_reference) + except AttributeError: + pass + + new_content_array = ArrayObject() + original_content = self.get_contents() + if original_content is not None: + original_content.isolate_graphics_state() + new_content_array.append(original_content) + + page2content = page2.get_contents() + if page2content is not None: + rect = getattr(page2, MERGE_CROP_BOX) + page2content.operations.insert( + 0, + ( + map( + FloatObject, + [ + rect.left, + rect.bottom, + rect.width, + rect.height, + ], + ), + b"re", + ), + ) + page2content.operations.insert(1, ([], b"W")) + page2content.operations.insert(2, ([], b"n")) + if page2transformation is not None: + page2content = page2transformation(page2content) + page2content = PageObject._content_stream_rename( + page2content, rename, self.pdf + ) + page2content.isolate_graphics_state() + if over: + new_content_array.append(page2content) + else: + new_content_array.insert(0, page2content) + + # if expanding the page to fit a new page, calculate the new media box size + if expand: + self._expand_mediabox(page2, ctm) + + self.replace_contents(new_content_array) + + def _expand_mediabox( + self, page2: "PageObject", ctm: Optional[CompressedTransformationMatrix] + ) -> None: + corners1 = ( + self.mediabox.left.as_numeric(), + self.mediabox.bottom.as_numeric(), + self.mediabox.right.as_numeric(), + self.mediabox.top.as_numeric(), + ) + corners2 = ( + page2.mediabox.left.as_numeric(), + page2.mediabox.bottom.as_numeric(), + page2.mediabox.left.as_numeric(), + page2.mediabox.top.as_numeric(), + page2.mediabox.right.as_numeric(), + page2.mediabox.top.as_numeric(), + page2.mediabox.right.as_numeric(), + page2.mediabox.bottom.as_numeric(), + ) + if ctm is not None: + ctm = tuple(float(x) for x in ctm) # type: ignore[assignment] + new_x = tuple( + ctm[0] * corners2[i] + ctm[2] * corners2[i + 1] + ctm[4] + for i in range(0, 8, 2) + ) + new_y = tuple( + ctm[1] * corners2[i] + ctm[3] * corners2[i + 1] + ctm[5] + for i in range(0, 8, 2) + ) + else: + new_x = corners2[0:8:2] + new_y = corners2[1:8:2] + lowerleft = (min(new_x), min(new_y)) + upperright = (max(new_x), max(new_y)) + lowerleft = (min(corners1[0], lowerleft[0]), min(corners1[1], lowerleft[1])) + upperright = ( + max(corners1[2], upperright[0]), + max(corners1[3], upperright[1]), + ) + + self.mediabox.lower_left = lowerleft + self.mediabox.upper_right = upperright + + def merge_transformed_page( + self, + page2: "PageObject", + ctm: Union[CompressedTransformationMatrix, Transformation], + over: bool = True, + expand: bool = False, + ) -> None: + """ + Similar to :meth:`~pypdf._page.PageObject.merge_page`, but a transformation + matrix is applied to the merged stream. + + Args: + page2: The page to be merged into this one. + ctm: a 6-element tuple containing the operands of the + transformation matrix + over: set the page2 content over page1 if True (default) else under + expand: Whether the page should be expanded to fit the dimensions + of the page to be merged. + + """ + if isinstance(ctm, Transformation): + ctm = ctm.ctm + self._merge_page( + page2, + lambda page2_content: PageObject._add_transformation_matrix( + page2_content, page2.pdf, ctm + ), + ctm, + over, + expand, + ) + + def merge_scaled_page( + self, page2: "PageObject", scale: float, over: bool = True, expand: bool = False + ) -> None: + """ + Similar to :meth:`~pypdf._page.PageObject.merge_page`, but the stream to be merged + is scaled by applying a transformation matrix. + + Args: + page2: The page to be merged into this one. + scale: The scaling factor + over: set the page2 content over page1 if True (default) else under + expand: Whether the page should be expanded to fit the + dimensions of the page to be merged. + + """ + op = Transformation().scale(scale, scale) + self.merge_transformed_page(page2, op, over, expand) + + def merge_rotated_page( + self, + page2: "PageObject", + rotation: float, + over: bool = True, + expand: bool = False, + ) -> None: + """ + Similar to :meth:`~pypdf._page.PageObject.merge_page`, but the stream to be merged + is rotated by applying a transformation matrix. + + Args: + page2: The page to be merged into this one. + rotation: The angle of the rotation, in degrees + over: set the page2 content over page1 if True (default) else under + expand: Whether the page should be expanded to fit the + dimensions of the page to be merged. + + """ + op = Transformation().rotate(rotation) + self.merge_transformed_page(page2, op, over, expand) + + def merge_translated_page( + self, + page2: "PageObject", + tx: float, + ty: float, + over: bool = True, + expand: bool = False, + ) -> None: + """ + Similar to :meth:`~pypdf._page.PageObject.merge_page`, but the stream to be + merged is translated by applying a transformation matrix. + + Args: + page2: the page to be merged into this one. + tx: The translation on X axis + ty: The translation on Y axis + over: set the page2 content over page1 if True (default) else under + expand: Whether the page should be expanded to fit the + dimensions of the page to be merged. + + """ + op = Transformation().translate(tx, ty) + self.merge_transformed_page(page2, op, over, expand) + + def add_transformation( + self, + ctm: Union[Transformation, CompressedTransformationMatrix], + expand: bool = False, + ) -> None: + """ + Apply a transformation matrix to the page. + + Args: + ctm: A 6-element tuple containing the operands of the + transformation matrix. Alternatively, a + :py:class:`Transformation` + object can be passed. + + See :doc:`/user/cropping-and-transforming`. + + """ + if isinstance(ctm, Transformation): + ctm = ctm.ctm + content = self.get_contents() + if content is not None: + content = PageObject._add_transformation_matrix(content, self.pdf, ctm) + content.isolate_graphics_state() + self.replace_contents(content) + # if expanding the page to fit a new page, calculate the new media box size + if expand: + corners = [ + self.mediabox.left.as_numeric(), + self.mediabox.bottom.as_numeric(), + self.mediabox.left.as_numeric(), + self.mediabox.top.as_numeric(), + self.mediabox.right.as_numeric(), + self.mediabox.top.as_numeric(), + self.mediabox.right.as_numeric(), + self.mediabox.bottom.as_numeric(), + ] + + ctm = tuple(float(x) for x in ctm) # type: ignore[assignment] + new_x = [ + ctm[0] * corners[i] + ctm[2] * corners[i + 1] + ctm[4] + for i in range(0, 8, 2) + ] + new_y = [ + ctm[1] * corners[i] + ctm[3] * corners[i + 1] + ctm[5] + for i in range(0, 8, 2) + ] + + self.mediabox.lower_left = (min(new_x), min(new_y)) + self.mediabox.upper_right = (max(new_x), max(new_y)) + + def scale(self, sx: float, sy: float) -> None: + """ + Scale a page by the given factors by applying a transformation matrix + to its content and updating the page size. + + This updates the various page boundaries (bleedbox, trimbox, etc.) + and the contents of the page. + + Args: + sx: The scaling factor on horizontal axis. + sy: The scaling factor on vertical axis. + + """ + self.add_transformation((sx, 0, 0, sy, 0, 0)) + self.bleedbox = self.bleedbox.scale(sx, sy) + self.trimbox = self.trimbox.scale(sx, sy) + self.artbox = self.artbox.scale(sx, sy) + self.cropbox = self.cropbox.scale(sx, sy) + self.mediabox = self.mediabox.scale(sx, sy) + + if PG.ANNOTS in self: + annotations = self[PG.ANNOTS] + if isinstance(annotations, ArrayObject): + for annotation in annotations: + annotation_obj = annotation.get_object() + if AnnotationDictionaryAttributes.Rect in annotation_obj: + rectangle = annotation_obj[AnnotationDictionaryAttributes.Rect] + if isinstance(rectangle, ArrayObject): + rectangle[0] = FloatObject(float(rectangle[0]) * sx) + rectangle[1] = FloatObject(float(rectangle[1]) * sy) + rectangle[2] = FloatObject(float(rectangle[2]) * sx) + rectangle[3] = FloatObject(float(rectangle[3]) * sy) + + if PG.VP in self: + viewport = self[PG.VP] + if isinstance(viewport, ArrayObject): + bbox = viewport[0]["/BBox"] + else: + bbox = viewport["/BBox"] # type: ignore[index] + scaled_bbox = RectangleObject( + ( + float(bbox[0]) * sx, + float(bbox[1]) * sy, + float(bbox[2]) * sx, + float(bbox[3]) * sy, + ) + ) + if isinstance(viewport, ArrayObject): + self[NameObject(PG.VP)][NumberObject(0)][ # type: ignore[index] + NameObject("/BBox") + ] = scaled_bbox + else: + self[NameObject(PG.VP)][NameObject("/BBox")] = scaled_bbox # type: ignore[index] + + def scale_by(self, factor: float) -> None: + """ + Scale a page by the given factor by applying a transformation matrix to + its content and updating the page size. + + Args: + factor: The scaling factor (for both X and Y axis). + + """ + self.scale(factor, factor) + + def scale_to(self, width: float, height: float) -> None: + """ + Scale a page to the specified dimensions by applying a transformation + matrix to its content and updating the page size. + + Args: + width: The new width. + height: The new height. + + """ + sx = width / float(self.mediabox.width) + sy = height / float(self.mediabox.height) + self.scale(sx, sy) + + def compress_content_streams(self, level: int = -1) -> None: + """ + Compress the size of this page by joining all content streams and + applying a FlateDecode filter. + + However, it is possible that this function will perform no action if + content stream compression becomes "automatic". + """ + content = self.get_contents() + if content is not None: + content_obj = content.flate_encode(level) + try: + content.indirect_reference.pdf._objects[ # type: ignore[union-attr] + content.indirect_reference.idnum - 1 # type: ignore[union-attr] + ] = content_obj + except AttributeError: + if self.indirect_reference is not None and hasattr( + self.indirect_reference.pdf, "_add_object" + ): + self.replace_contents(content_obj) + else: + raise ValueError("Page must be part of a PdfWriter") + + @property + def page_number(self) -> Optional[int]: + """ + Read-only property which returns the page number within the PDF file. + + Returns: + Page number; None if the page is not attached to a PDF. + + """ + if self.indirect_reference is None: + return None + try: + lst = self.indirect_reference.pdf.pages + return int(lst.index(self)) + except ValueError: + return None + + def _debug_for_extract(self) -> str: # pragma: no cover + out = "" + for ope, op in ContentStream( + self["/Contents"].get_object(), self.pdf, "bytes" + ).operations: + if op == b"TJ": + s = [x for x in ope[0] if isinstance(x, str)] + else: + s = [] + out += op.decode("utf-8") + " " + "".join(s) + ope.__repr__() + "\n" + out += "\n=============================\n" + try: + for fo in self[PG.RESOURCES]["/Font"]: # type:ignore + out += fo + "\n" + out += self[PG.RESOURCES]["/Font"][fo].__repr__() + "\n" # type:ignore + try: + enc_repr = self[PG.RESOURCES]["/Font"][fo][ # type:ignore + "/Encoding" + ].__repr__() + out += enc_repr + "\n" + except Exception: + pass + try: + out += ( + self[PG.RESOURCES]["/Font"][fo][ # type:ignore + "/ToUnicode" + ] + .get_data() + .decode() + + "\n" + ) + except Exception: + pass + + except KeyError: + out += "No Font\n" + return out + + def _extract_text( + self, + obj: DictionaryObject, + pdf: Any, + orientations: tuple[int, ...] = (0, 90, 180, 270), + space_width: float = 200.0, + content_key: Optional[str] = PG.CONTENTS, + visitor_operand_before: Optional[Callable[[Any, Any, Any, Any], None]] = None, + visitor_operand_after: Optional[Callable[[Any, Any, Any, Any], None]] = None, + visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]] = None, + *, + known_ids: Optional[set[int]] = None, + ) -> str: + """ + See extract_text for most arguments. + + Args: + content_key: indicate the default key where to extract data + None = the object; this allows reusing the function on an XObject + default = "/Content" + + """ + if known_ids is None: + known_ids = set() + + extractor = TextExtraction() + font_resources: dict[str, DictionaryObject] = {} + fonts: dict[str, Font] = {} + + resources_dict = cast( + Optional[DictionaryObject], + obj.get_inherited(key=PG.RESOURCES, default=DictionaryObject()) + ) + if is_null_or_none(resources_dict) or not resources_dict: + # No resources means no text is possible (no font); we consider the + # file as not damaged, no need to check for TJ or Tj + return "" + + if ( + "/Font" in resources_dict + and (font_resources_dict := cast(DictionaryObject, resources_dict["/Font"])) + ): + for font_resource in font_resources_dict: + try: + font_resource_object = cast(DictionaryObject, font_resources_dict[font_resource].get_object()) + font_resources[font_resource] = font_resource_object + fonts[font_resource] = Font.from_font_resource(font_resource_object) + # Override space width, if applicable + if fonts[font_resource].character_widths.get(fonts[font_resource].space_char, 0) == 0: + fonts[font_resource].space_width = space_width + except (AttributeError, TypeError): + pass + + try: + content = ( + obj[content_key].get_object() if isinstance(content_key, str) else obj + ) + if not isinstance(content, ContentStream): + content = ContentStream(content, pdf, "bytes") + except (AttributeError, KeyError): # no content can be extracted (certainly empty page) + return "" + # We check all strings are TextStringObjects. ByteStringObjects + # are strings where the byte->string encoding was unknown, so adding + # them to the text here would be gibberish. + + # Initialize the extractor with the necessary parameters + extractor.initialize_extraction(orientations, visitor_text, font_resources, fonts) + + for operands, operator in content.operations: + if visitor_operand_before is not None: + visitor_operand_before(operator, operands, extractor.cm_matrix, extractor.tm_matrix) + # Multiple operators are handled here + if operator == b"'": + extractor.process_operation(b"T*", []) + extractor.process_operation(b"Tj", operands) + elif operator == b'"' and len(operands) >= 3: + extractor.process_operation(b"Tw", [operands[0]]) + extractor.process_operation(b"Tc", [operands[1]]) + extractor.process_operation(b"T*", []) + extractor.process_operation(b"Tj", operands[2:]) + elif operator == b"TJ": + # The space width may be smaller than the font width, so the width should be 95%. + _confirm_space_width = extractor._space_width * 0.95 + if operands: + for op in operands[0]: + if isinstance(op, (str, bytes)): + extractor.process_operation(b"Tj", [op]) + if isinstance(op, (int, float, NumberObject, FloatObject)) and ( + abs(float(op)) >= _confirm_space_width + and extractor.text + and extractor.text[-1] != " " + ): + extractor.process_operation(b"Tj", [" "]) + elif operator == b"TD" and len(operands) >= 2: + extractor.process_operation(b"TL", [-operands[1]]) + extractor.process_operation(b"Td", operands) + elif operator == b"Do": + extractor.output += extractor.text + if visitor_text is not None: + visitor_text( + extractor.text, + extractor.memo_cm, + extractor.memo_tm, + extractor.font_resource, + extractor.font_size, + ) + try: + if extractor.output[-1] != "\n": + extractor.output += "\n" + if visitor_text is not None: + visitor_text( + "\n", + extractor.memo_cm, + extractor.memo_tm, + extractor.font_resource, + extractor.font_size, + ) + except IndexError: + pass + try: + xobj = cast(DictionaryObject, resources_dict["/XObject"]) + xform = cast(EncodedStreamObject, xobj[operands[0]]) + if xform["/Subtype"] != NameObject("/Image"): + xform_id = id(xform) + if xform_id in known_ids: + logger_warning( + "Detected cyclic form XObject reference, skipping %(operand)s.", + source=__name__, + operand=operands[0] + ) + text = "" + else: + known_ids.add(xform_id) + try: + text = self.extract_xform_text( + xform, + orientations, + space_width, + visitor_operand_before, + visitor_operand_after, + visitor_text, + known_ids=known_ids, + ) + finally: + known_ids.discard(xform_id) + extractor.output += text + if visitor_text is not None: + visitor_text( + text, + extractor.memo_cm, + extractor.memo_tm, + extractor.font_resource, + extractor.font_size, + ) + except Exception as exception: + logger_warning( + "Impossible to decode XFormObject %(operand)s: %(exception)s", + source=__name__, + operand=operands[0], + exception=exception, + ) + finally: + extractor.text = "" + extractor.memo_cm = extractor.cm_matrix.copy() + extractor.memo_tm = extractor.tm_matrix.copy() + else: + extractor.process_operation(operator, operands) + if visitor_operand_after is not None: + visitor_operand_after(operator, operands, extractor.cm_matrix, extractor.tm_matrix) + extractor.output += extractor.text # just in case + if extractor.text != "" and visitor_text is not None: + visitor_text( + extractor.text, + extractor.memo_cm, + extractor.memo_tm, + extractor.font_resource, + extractor.font_size, + ) + return extractor.output + + def _layout_mode_fonts(self) -> dict[str, Font]: + """ + Get fonts formatted for "layout" mode text extraction. + + Returns: + Dict[str, Font]: dictionary of Font instances keyed by font name + + """ + # Font retrieval logic adapted from pypdf.PageObject._extract_text() + obj: Any = self + fonts: dict[str, Font] = {} + visited: set[int] = set() + while True: + obj_id = id(obj) + if obj_id in visited: + logger_warning("Detected cycle in /Parent hierarchy when retrieving fonts.", source=__name__) + break + visited.add(obj_id) + + resources_dict: Any = obj.get(PG.RESOURCES, {}) + if "/Font" in resources_dict and self.pdf is not None: + for font_name in resources_dict["/Font"]: + fonts[font_name] = Font.from_font_resource(resources_dict["/Font"][font_name]) + + if "/Parent" not in obj: + break + obj = obj["/Parent"].get_object() + + return fonts + + def _layout_mode_text( + self, + space_vertically: bool = True, + scale_weight: float = 1.25, + strip_rotated: bool = True, + debug_path: Optional[Path] = None, + font_height_weight: float = 1, + ) -> str: + """ + Get text preserving fidelity to source PDF text layout. + + Args: + space_vertically: include blank lines inferred from y distance + font + height. Defaults to True. + scale_weight: multiplier for string length when calculating weighted + average character width. Defaults to 1.25. + strip_rotated: Removes text that is rotated w.r.t. to the page from + layout mode output. Defaults to True. + debug_path (Path | None): if supplied, must target a directory. + creates the following files with debug information for layout mode + functions if supplied: + - fonts.json: output of self._layout_mode_fonts + - tjs.json: individual text render ops with corresponding transform matrices + - bts.json: text render ops left justified and grouped by BT/ET operators + - bt_groups.json: BT/ET operations grouped by rendered y-coord (aka lines) + Defaults to None. + font_height_weight: multiplier for font height when calculating + blank lines. Defaults to 1. + + Returns: + str: multiline string containing page text in a fixed width format that + closely adheres to the rendered layout in the source pdf. + + """ + fonts = self._layout_mode_fonts() + if debug_path: # pragma: no cover + import json # noqa: PLC0415 + + debug_path.joinpath("fonts.json").write_text( + json.dumps(fonts, indent=2, default=asdict), + "utf-8" + ) + + ops = iter( + ContentStream(self["/Contents"].get_object(), self.pdf, "bytes").operations + ) + bt_groups = _layout_mode.text_show_operations( + ops, fonts, strip_rotated, debug_path + ) + + if not bt_groups: + return "" + + ty_groups = _layout_mode.y_coordinate_groups(bt_groups, debug_path) + + char_width = _layout_mode.fixed_char_width(bt_groups, scale_weight) + + return _layout_mode.fixed_width_page(ty_groups, char_width, space_vertically, font_height_weight) + + def extract_text( + self, + *args: Any, + orientations: Union[int, tuple[int, ...]] = (0, 90, 180, 270), + space_width: float = 200.0, + visitor_operand_before: Optional[Callable[[Any, Any, Any, Any], None]] = None, + visitor_operand_after: Optional[Callable[[Any, Any, Any, Any], None]] = None, + visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]] = None, + extraction_mode: Literal["plain", "layout"] = "plain", + **kwargs: Any, + ) -> str: + """ + Locate all text drawing commands, in the order they are provided in the + content stream, and extract the text. + + This works well for some PDF files, but poorly for others, depending on + the generator used. This will be refined in the future. + + Do not rely on the order of text coming out of this function, as it + will change if this function is made more sophisticated. + + Arabic and Hebrew are extracted in the correct order. + If required a custom RTL range of characters can be defined; + see function set_custom_rtl. + + Additionally you can provide visitor methods to get informed on all + operations and all text objects. + For example in some PDF files this can be useful to parse tables. + + Args: + orientations: list of orientations extract_text will look for + default = (0, 90, 180, 270) + note: currently only 0 (up),90 (turned left), 180 (upside down), + 270 (turned right) + Silently ignored in "layout" mode. + space_width: force default space width + if not extracted from font (default: 200) + Silently ignored in "layout" mode. + visitor_operand_before: function to be called before processing an operation. + It has four arguments: operator, operand-arguments, + current transformation matrix and text matrix. + Ignored with a warning in "layout" mode. + visitor_operand_after: function to be called after processing an operation. + It has four arguments: operator, operand-arguments, + current transformation matrix and text matrix. + Ignored with a warning in "layout" mode. + visitor_text: function to be called when extracting some text at some position. + It has five arguments: text, current transformation matrix, + text matrix, font-dictionary and font-size. + The font-dictionary may be None in case of unknown fonts. + If not None it may e.g. contain key "/BaseFont" with value "/Arial,Bold". + Ignored with a warning in "layout" mode. + extraction_mode (Literal["plain", "layout"]): "plain" for legacy functionality, + "layout" for experimental layout mode functionality. + NOTE: orientations, space_width, and visitor_* parameters are NOT respected + in "layout" mode. + + kwargs: + layout_mode_space_vertically (bool): include blank lines inferred from + y distance + font height. Defaults to True. + layout_mode_scale_weight (float): multiplier for string length when calculating + weighted average character width. Defaults to 1.25. + layout_mode_strip_rotated (bool): layout mode does not support rotated text. + Set to False to include rotated text anyway. If rotated text is discovered, + layout will be degraded and a warning will result. Defaults to True. + layout_mode_debug_path (Path | None): if supplied, must target a directory. + creates the following files with debug information for layout mode + functions if supplied: + + - fonts.json: output of self._layout_mode_fonts + - tjs.json: individual text render ops with corresponding transform matrices + - bts.json: text render ops left justified and grouped by BT/ET operators + - bt_groups.json: BT/ET operations grouped by rendered y-coord (aka lines) + layout_mode_font_height_weight (float): multiplier for font height when calculating + blank lines. Defaults to 1. + + Returns: + The extracted text + + """ + if extraction_mode not in ["plain", "layout"]: + raise ValueError(f"Invalid text extraction mode '{extraction_mode}'") + if extraction_mode == "layout": + for visitor in ( + "visitor_operand_before", + "visitor_operand_after", + "visitor_text", + ): + if locals()[visitor]: + logger_warning( + "Argument %(visitor)s is ignored in layout mode", + source=__name__, + visitor=visitor, + ) + return self._layout_mode_text( + space_vertically=kwargs.get("layout_mode_space_vertically", True), + scale_weight=kwargs.get("layout_mode_scale_weight", 1.25), + strip_rotated=kwargs.get("layout_mode_strip_rotated", True), + debug_path=kwargs.get("layout_mode_debug_path"), + font_height_weight=kwargs.get("layout_mode_font_height_weight", 1) + ) + if len(args) >= 1: + if isinstance(args[0], str): + if len(args) >= 3: + if isinstance(args[2], (tuple, int)): + orientations = args[2] + else: + raise TypeError(f"Invalid positional parameter {args[2]}") + if len(args) >= 4: + if isinstance(args[3], (float, int)): + space_width = args[3] + else: + raise TypeError(f"Invalid positional parameter {args[3]}") + elif isinstance(args[0], (tuple, int)): + orientations = args[0] + if len(args) >= 2: + if isinstance(args[1], (float, int)): + space_width = args[1] + else: + raise TypeError(f"Invalid positional parameter {args[1]}") + else: + raise TypeError(f"Invalid positional parameter {args[0]}") + + if isinstance(orientations, int): + orientations = (orientations,) + + return self._extract_text( + self, + self.pdf, + orientations, + space_width, + PG.CONTENTS, + visitor_operand_before, + visitor_operand_after, + visitor_text, + ) + + def extract_xform_text( + self, + xform: EncodedStreamObject, + orientations: tuple[int, ...] = (0, 90, 270, 360), + space_width: float = 200.0, + visitor_operand_before: Optional[Callable[[Any, Any, Any, Any], None]] = None, + visitor_operand_after: Optional[Callable[[Any, Any, Any, Any], None]] = None, + visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]] = None, + *, + known_ids: Optional[set[int]] = None, + ) -> str: + """ + Extract text from an XObject. + + Args: + xform: + orientations: + space_width: force default space width (if not extracted from font (default 200) + visitor_operand_before: + visitor_operand_after: + visitor_text: + + Returns: + The extracted text + + """ + return self._extract_text( + xform, + self.pdf, + orientations, + space_width, + None, + visitor_operand_before, + visitor_operand_after, + visitor_text, + known_ids=known_ids, + ) + + def _get_fonts(self) -> tuple[set[str], set[str]]: + """ + Get the names of embedded fonts and unembedded fonts. + + Returns: + A tuple (set of embedded fonts, set of unembedded fonts) + + """ + obj = self.get_object() + assert isinstance(obj, DictionaryObject) + fonts: set[str] = set() + embedded: set[str] = set() + fonts, embedded = _get_fonts_walk(obj, fonts, embedded) + unembedded = fonts - embedded + return embedded, unembedded + + mediabox = _create_rectangle_accessor(PG.MEDIABOX, ()) + """A :class:`RectangleObject`, expressed in + default user space units, defining the boundaries of the physical medium on + which the page is intended to be displayed or printed.""" + + cropbox = _create_rectangle_accessor("/CropBox", (PG.MEDIABOX,)) + """ + A :class:`RectangleObject`, expressed in + default user space units, defining the visible region of default user + space. + + When the page is displayed or printed, its contents are to be clipped + (cropped) to this rectangle and then imposed on the output medium in some + implementation-defined manner. Default value: same as + :attr:`mediabox`. + """ + + bleedbox = _create_rectangle_accessor("/BleedBox", ("/CropBox", PG.MEDIABOX)) + """A :class:`RectangleObject`, expressed in + default user space units, defining the region to which the contents of the + page should be clipped when output in a production environment.""" + + trimbox = _create_rectangle_accessor("/TrimBox", ("/CropBox", PG.MEDIABOX)) + """A :class:`RectangleObject`, expressed in + default user space units, defining the intended dimensions of the finished + page after trimming.""" + + artbox = _create_rectangle_accessor("/ArtBox", ("/CropBox", PG.MEDIABOX)) + """A :class:`RectangleObject`, expressed in + default user space units, defining the extent of the page's meaningful + content as intended by the page's creator.""" + + @property + def annotations(self) -> Optional[ArrayObject]: + if "/Annots" not in self: + return None + return cast(ArrayObject, self["/Annots"]) + + @annotations.setter + def annotations(self, value: Optional[ArrayObject]) -> None: + """ + Set the annotations array of the page. + + Typically you do not want to set this value, but append to it. + If you append to it, remember to add the object first to the writer + and only add the indirect object. + """ + if value is None: + if "/Annots" not in self: + return + del self[NameObject("/Annots")] + else: + self[NameObject("/Annots")] = value + + def add_action(self, trigger: PageTrigger, action: Action) -> None: + """ + Add an action which will launch on the given trigger event of this page. + + Args: + trigger: The action trigger to use. + action: The action to be done. + + Example: + >>> from pypdf import PdfWriter + >>> from pypdf.actions import JavaScript, PageTrigger + >>> writer = PdfWriter() + >>> page = writer.add_blank_page(595, 842) + >>> # Display the page number when the page is opened + >>> page.add_action(PageTrigger("open"), JavaScript("app.alert('This is page ' + this.pageNum);")) + >>> # Display the page number when the page is closed + >>> page.add_action(PageTrigger("close"), JavaScript("app.alert('This is page ' + this.pageNum);")) + """ + return Action._create_new(self, trigger, action) + + def delete_action(self, trigger: PageTrigger) -> None: + """ + Delete all actions associated with an open or close trigger event of this page. + + Args: + trigger: An open or close trigger. + + Example: + >>> from pypdf import PdfWriter + >>> from pypdf.actions import JavaScript, PageTrigger + >>> writer = PdfWriter() + >>> page = writer.add_blank_page(595, 842) + >>> page.add_action(PageTrigger("open"), JavaScript("app.alert('This is page ' + this.pageNum);")) + >>> page.add_action(PageTrigger("close"), JavaScript("app.alert('This is page ' + this.pageNum);")) + >>> # Delete all actions triggered by a page open + >>> page.delete_action(PageTrigger("open")) + >>> # Delete all actions triggered by a page close + >>> page.delete_action(PageTrigger("close")) + """ + return Action._delete(self, trigger) + + +class _VirtualList(Sequence[PageObject]): + def __init__( + self, + length_function: Callable[[], int], + get_function: Callable[[int], PageObject], + ) -> None: + self.length_function = length_function + self.get_function = get_function + self.current = -1 + + def __len__(self) -> int: + return self.length_function() + + @overload + def __getitem__(self, index: int) -> PageObject: + ... + + @overload + def __getitem__(self, index: slice) -> Sequence[PageObject]: + ... + + def __getitem__( + self, index: Union[int, slice] + ) -> Union[PageObject, Sequence[PageObject]]: + if isinstance(index, slice): + indices = range(*index.indices(len(self))) + cls = type(self) + return cls(indices.__len__, lambda idx: self[indices[idx]]) + if not isinstance(index, int): + raise TypeError("Sequence indices must be integers") + len_self = len(self) + if index < 0: + # support negative indexes + index += len_self + if not (0 <= index < len_self): + raise IndexError("Sequence index out of range") + return self.get_function(index) + + def __delitem__(self, index: Union[int, slice]) -> None: + if isinstance(index, slice): + r = list(range(*index.indices(len(self)))) + # pages have to be deleted from last to first + r.sort() + r.reverse() + for p in r: + del self[p] # recursive call + return + if not isinstance(index, int): + raise TypeError("Index must be integers") + len_self = len(self) + if index < 0: + # support negative indexes + index += len_self + if not (0 <= index < len_self): + raise IndexError("Index out of range") + ind = self[index].indirect_reference + assert ind is not None + parent: Optional[PdfObject] = cast(DictionaryObject, ind.get_object()).get( + "/Parent", None + ) + first = True + while parent is not None: + parent = cast(DictionaryObject, parent.get_object()) + try: + i = cast(ArrayObject, parent["/Kids"]).index(ind) + del cast(ArrayObject, parent["/Kids"])[i] + first = False + try: + assert ind is not None + del ind.pdf.flattened_pages[index] # case of page in a Reader + except Exception: # pragma: no cover + pass + if "/Count" in parent: + parent[NameObject("/Count")] = NumberObject( + cast(int, parent["/Count"]) - 1 + ) + if len(cast(ArrayObject, parent["/Kids"])) == 0: + # No more objects in this part of this subtree + ind = parent.indirect_reference + parent = parent.get("/Parent", None) + except ValueError: # from index + if first: + raise PdfReadError(f"Page not found in page tree: {ind}") + break + + def __iter__(self) -> Iterator[PageObject]: + for i in range(len(self)): + yield self[i] + + def __str__(self) -> str: + p = [f"PageObject({i})" for i in range(self.length_function())] + return f"[{', '.join(p)}]" + + +def _get_fonts_walk( + obj: DictionaryObject, + fnt: set[str], + emb: set[str], +) -> tuple[set[str], set[str]]: + """ + Get the set of all fonts and all embedded fonts. + + Args: + obj: Page resources dictionary + fnt: font + emb: embedded fonts + + Returns: + A tuple (fnt, emb) + + If there is a key called 'BaseFont', that is a font that is used in the document. + If there is a key called 'FontName' and another key in the same dictionary object + that is called 'FontFilex' (where x is null, 2, or 3), then that fontname is + embedded. + + We create and add to two sets, fnt = fonts used and emb = fonts embedded. + + """ + fontkeys = ("/FontFile", "/FontFile2", "/FontFile3") + + def process_font(f: DictionaryObject) -> None: + nonlocal fnt, emb + f = cast(DictionaryObject, f.get_object()) # to be sure + if "/BaseFont" in f: + fnt.add(cast(str, f["/BaseFont"])) + + if ( + ("/CharProcs" in f) + or ( + "/FontDescriptor" in f + and any( + x in cast(DictionaryObject, f["/FontDescriptor"]) for x in fontkeys + ) + ) + or ( + "/DescendantFonts" in f + and "/FontDescriptor" + in cast( + DictionaryObject, + cast(ArrayObject, f["/DescendantFonts"])[0].get_object(), + ) + and any( + x + in cast( + DictionaryObject, + cast( + DictionaryObject, + cast(ArrayObject, f["/DescendantFonts"])[0].get_object(), + )["/FontDescriptor"], + ) + for x in fontkeys + ) + ) + ): + # the list comprehension ensures there is FontFile + try: + emb.add(cast(str, f["/BaseFont"])) + except KeyError: + emb.add("(" + cast(str, f["/Subtype"]) + ")") + + if "/DR" in obj and "/Font" in cast(DictionaryObject, obj["/DR"]): + for f in cast(DictionaryObject, cast(DictionaryObject, obj["/DR"])["/Font"]): + process_font(f) + if "/Resources" in obj: + if "/Font" in cast(DictionaryObject, obj["/Resources"]): + for f in cast( + DictionaryObject, cast(DictionaryObject, obj["/Resources"])["/Font"] + ).values(): + process_font(f) + if "/XObject" in cast(DictionaryObject, obj["/Resources"]): + for x in cast( + DictionaryObject, cast(DictionaryObject, obj["/Resources"])["/XObject"] + ).values(): + _get_fonts_walk(cast(DictionaryObject, x.get_object()), fnt, emb) + if "/Annots" in obj: + for a in cast(ArrayObject, obj["/Annots"]): + _get_fonts_walk(cast(DictionaryObject, a.get_object()), fnt, emb) + if "/AP" in obj: + if ( + cast(DictionaryObject, cast(DictionaryObject, obj["/AP"])["/N"]).get( + "/Type" + ) + == "/XObject" + ): + _get_fonts_walk( + cast(DictionaryObject, cast(DictionaryObject, obj["/AP"])["/N"]), + fnt, + emb, + ) + else: + for a in cast(DictionaryObject, cast(DictionaryObject, obj["/AP"])["/N"]): + _get_fonts_walk(cast(DictionaryObject, a), fnt, emb) + return fnt, emb # return the sets for each page diff --git a/.venv/lib/python3.13/site-packages/pypdf/_page_labels.py b/.venv/lib/python3.13/site-packages/pypdf/_page_labels.py new file mode 100644 index 0000000000000000000000000000000000000000..5da2ba10d8854074e422769981337328aa26a894 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/_page_labels.py @@ -0,0 +1,321 @@ +""" +Page labels are shown by PDF viewers as "the page number". + +A page has a numeric index, starting at 0. Additionally, the page +has a label. In the most simple case: + + label = index + 1 + +However, the title page and the table of contents might have Roman numerals as +page labels. This makes things more complicated. + +Example 1 +--------- + +>>> reader.root_object["/PageLabels"]["/Nums"] +[0, IndirectObject(18, 0, 139929798197504), + 8, IndirectObject(19, 0, 139929798197504)] +>>> reader.get_object(reader.root_object["/PageLabels"]["/Nums"][1]) +{'/S': '/r'} +>>> reader.get_object(reader.root_object["/PageLabels"]["/Nums"][3]) +{'/S': '/D'} + +Example 2 +--------- +The following is a document with pages labeled +i, ii, iii, iv, 1, 2, 3, A-8, A-9, ... + +1 0 obj + << /Type /Catalog + /PageLabels << /Nums [ + 0 << /S /r >> + 4 << /S /D >> + 7 << /S /D + /P ( A- ) + /St 8 + >> + % A number tree containing + % three page label dictionaries + ] + >> + ... + >> +endobj + + +§12.4.2 PDF Specification 1.7 and 2.0 +===================================== + +Entries in a page label dictionary +---------------------------------- +The /S key: +D Decimal Arabic numerals +R Uppercase Roman numerals +r Lowercase Roman numerals +A Uppercase letters (A to Z for the first 26 pages, + AA to ZZ for the next 26, and so on) +a Lowercase letters (a to z for the first 26 pages, + aa to zz for the next 26, and so on) +""" + +from collections.abc import Callable, Iterator +from typing import Optional, cast + +from ._protocols import PdfCommonDocProtocol +from ._utils import logger_warning +from .generic import ( + ArrayObject, + DictionaryObject, + NullObject, + NumberObject, + is_null_or_none, +) + + +def number2uppercase_roman_numeral(num: int) -> str: + roman = [ + (1000, "M"), + (900, "CM"), + (500, "D"), + (400, "CD"), + (100, "C"), + (90, "XC"), + (50, "L"), + (40, "XL"), + (10, "X"), + (9, "IX"), + (5, "V"), + (4, "IV"), + (1, "I"), + ] + + def roman_num(num: int) -> Iterator[str]: + for decimal, roman_repr in roman: + x, _ = divmod(num, decimal) + yield roman_repr * x + num -= decimal * x + if num <= 0: + break + + return "".join(list(roman_num(num))) + + +def number2lowercase_roman_numeral(number: int) -> str: + return number2uppercase_roman_numeral(number).lower() + + +def number2uppercase_letter(number: int) -> str: + if number <= 0: + raise ValueError("Expecting a positive number") + alphabet = [chr(i) for i in range(ord("A"), ord("Z") + 1)] + rep = "" + while number > 0: + remainder = number % 26 + if remainder == 0: + remainder = 26 + rep = alphabet[remainder - 1] + rep + # update + number -= remainder + number = number // 26 + return rep + + +def number2lowercase_letter(number: int) -> str: + return number2uppercase_letter(number).lower() + + +def get_label_from_nums(dictionary_object: DictionaryObject, index: int) -> str: + # [Nums] shall be an array of the form + # [ key_1 value_1 key_2 value_2 ... key_n value_n ] + # where each key_i is an integer and the corresponding + # value_i shall be the object associated with that key. + # The keys shall be sorted in numerical order, + # analogously to the arrangement of keys in a name tree + # as described in 7.9.6, "Name Trees." + nums = cast(ArrayObject, dictionary_object["/Nums"]) + nums_length = len(nums) + i = 0 + value = None + start_index = 0 + while i < nums_length: + if i + 1 >= nums_length: + logger_warning( + "Ignoring last /Nums key without a value.", source=__name__ + ) + break + start_index = nums[i] + value = nums[i + 1].get_object() + if i + 2 == nums_length: + break + if nums[i + 2] > index: + break + i += 2 + m: dict[Optional[str], Callable[[int], str]] = { + None: lambda _: "", + "/D": str, + "/R": number2uppercase_roman_numeral, + "/r": number2lowercase_roman_numeral, + "/A": number2uppercase_letter, + "/a": number2lowercase_letter, + } + # if /Nums array is not following the specification or if /Nums is empty + if not isinstance(value, dict): + return str(index + 1) # Fallback + start = value.get("/St", 1) + prefix = cast(str, value.get("/P", "")) + mapping_function = m.get(value.get("/S")) + if mapping_function is None: + # Unknown /S numbering style; fall back to the page position. + logger_warning( + "Ignoring unknown page label numbering style %(style)r in /Nums.", + source=__name__, + style=value.get("/S"), + ) + return str(index + 1) # Fallback + try: + return prefix + mapping_function(index - start_index + start) + except (TypeError, ValueError): + # Malformed /St or /P value; fall back to the page position. + logger_warning( + "Ignoring malformed page label entry in /Nums (/St=%(start)r, /P=%(prefix)r).", + source=__name__, + start=start, + prefix=prefix, + ) + return str(index + 1) # Fallback + + +def index2label(reader: PdfCommonDocProtocol, index: int) -> str: + """ + See 7.9.7 "Number Trees". + + Args: + reader: The PdfReader + index: The index of the page + + Returns: + The label of the page, e.g. "iv" or "4". + + """ + root = cast(DictionaryObject, reader.root_object) + if "/PageLabels" not in root: + return str(index + 1) # Fallback + number_tree = cast(DictionaryObject, root["/PageLabels"].get_object()) + if "/Nums" in number_tree: + return get_label_from_nums(number_tree, index) + if "/Kids" in number_tree and not isinstance(number_tree["/Kids"], NullObject): + # number_tree = {'/Kids': [IndirectObject(7333, 0, 140132998195856), ...]} + # Limit maximum depth. + level = 0 + while level < 100: + kids = cast(list[DictionaryObject], number_tree["/Kids"]) + for kid in kids: + # kid = {'/Limits': [0, 63], '/Nums': [0, {'/P': 'C1'}, ...]} + limits = kid.get("/Limits", NullObject()).get_object() + if not isinstance(limits, list) or len(limits) < 2: + # Skip kids whose /Limits range is missing or malformed. + logger_warning( + "Ignoring kid with missing or malformed /Limits in /PageLabels.", + source=__name__, + ) + continue + if limits[0] <= index <= limits[1]: + if not is_null_or_none(kid.get("/Kids", None)): + # Recursive definition. + level += 1 + if level == 100: # pragma: no cover + raise NotImplementedError( + "Too deep nesting is not supported." + ) + number_tree = kid + # Exit the inner `for` loop and continue at the next level with the + # next iteration of the `while` loop. + break + return get_label_from_nums(kid, index) + else: + # When there are no kids, make sure to exit the `while` loop directly + # and continue with the fallback. + break + + logger_warning("Could not reliably determine page label for %(index)d.", source=__name__, index=index) + return str(index + 1) # Fallback if neither /Nums nor /Kids is in the number_tree + + +def nums_insert( + key: NumberObject, + value: DictionaryObject, + nums: ArrayObject, +) -> None: + """ + Insert a key, value pair in a Nums array. + + See 7.9.7 "Number Trees". + + Args: + key: number key of the entry + value: value of the entry + nums: Nums array to modify + + """ + if len(nums) % 2 != 0: + raise ValueError("A nums like array must have an even number of elements") + + i = len(nums) + while i != 0 and key <= nums[i - 2]: + i = i - 2 + + if i < len(nums) and key == nums[i]: + nums[i + 1] = value + else: + nums.insert(i, key) + nums.insert(i + 1, value) + + +def nums_clear_range( + key: NumberObject, + page_index_to: int, + nums: ArrayObject, +) -> None: + """ + Remove all entries in a number tree in a range after an entry. + + See 7.9.7 "Number Trees". + + Args: + key: number key of the entry before the range + page_index_to: The page index of the upper limit of the range + nums: Nums array to modify + + """ + if len(nums) % 2 != 0: + raise ValueError("A nums like array must have an even number of elements") + if page_index_to < key: + raise ValueError("page_index_to must be greater or equal than key") + + i = nums.index(key) + 2 + while i < len(nums) and nums[i] <= page_index_to: + nums.pop(i) + nums.pop(i) + + +def nums_next( + key: NumberObject, + nums: ArrayObject, +) -> tuple[Optional[NumberObject], Optional[DictionaryObject]]: + """ + Return the (key, value) pair of the entry after the given one. + + See 7.9.7 "Number Trees". + + Args: + key: number key of the entry + nums: Nums array + + """ + if len(nums) % 2 != 0: + raise ValueError("A nums like array must have an even number of elements") + + i = nums.index(key) + 2 + if i < len(nums): + return (nums[i], nums[i + 1]) + return (None, None) diff --git a/.venv/lib/python3.13/site-packages/pypdf/_protocols.py b/.venv/lib/python3.13/site-packages/pypdf/_protocols.py new file mode 100644 index 0000000000000000000000000000000000000000..93dd11fd565a256964aa080bfb0d622607ef5b54 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/_protocols.py @@ -0,0 +1,86 @@ +"""Helpers for working with PDF types.""" + +from abc import abstractmethod +from pathlib import Path +from typing import IO, Any, Optional, Protocol, Union + +from ._utils import StrByteType, StreamType + + +class PdfObjectProtocol(Protocol): + indirect_reference: Any + + def clone( + self, + pdf_dest: Any, + force_duplicate: bool = False, + ignore_fields: Union[tuple[str, ...], list[str], None] = (), + ) -> Any: + ... # pragma: no cover + + def _reference_clone(self, clone: Any, pdf_dest: Any) -> Any: + ... # pragma: no cover + + def get_object(self) -> Optional["PdfObjectProtocol"]: + ... # pragma: no cover + + def hash_value(self) -> bytes: + ... # pragma: no cover + + def write_to_stream( + self, stream: StreamType, encryption_key: Union[str, bytes, None] = None + ) -> None: + ... # pragma: no cover + + +class XmpInformationProtocol(PdfObjectProtocol): + pass + + +class PdfCommonDocProtocol(Protocol): + @property + def pdf_header(self) -> str: + ... # pragma: no cover + + @property + def pages(self) -> list[Any]: + ... # pragma: no cover + + @property + def root_object(self) -> PdfObjectProtocol: + ... # pragma: no cover + + def get_object(self, indirect_reference: Any) -> Optional[PdfObjectProtocol]: + ... # pragma: no cover + + @property + def strict(self) -> bool: + ... # pragma: no cover + + +class PdfReaderProtocol(PdfCommonDocProtocol, Protocol): + @property + @abstractmethod + def xref(self) -> dict[int, dict[int, Any]]: + ... # pragma: no cover + + @property + @abstractmethod + def trailer(self) -> dict[str, Any]: + ... # pragma: no cover + + +class PdfWriterProtocol(PdfCommonDocProtocol, Protocol): + _objects: list[Any] + _id_translated: dict[int, dict[int, int]] + + incremental: bool + _reader: Any # PdfReader + + @abstractmethod + def write(self, stream: Union[Path, StrByteType]) -> tuple[bool, IO[Any]]: + ... # pragma: no cover + + @abstractmethod + def _add_object(self, obj: Any) -> Any: + ... # pragma: no cover diff --git a/.venv/lib/python3.13/site-packages/pypdf/_reader.py b/.venv/lib/python3.13/site-packages/pypdf/_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..ba99beb4e862ae47966b205ade8b2248684dd105 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/_reader.py @@ -0,0 +1,1604 @@ +# Copyright (c) 2006, Mathieu Fenniak +# Copyright (c) 2007, Ashish Kulkarni +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * The name of the author may not be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +import os +import re +import sys +from collections.abc import Iterable +from io import BytesIO, UnsupportedOperation +from pathlib import Path +from types import TracebackType +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Optional, + Union, + cast, +) + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +from ._doc_common import PdfDocCommon, convert_to_int +from ._encryption import Encryption, PasswordType +from ._utils import ( + WHITESPACES_AS_BYTES, + StrByteType, + StreamType, + logger_warning, + read_non_whitespace, + read_previous_line, + read_until_whitespace, + skip_over_comment, + skip_over_whitespace, +) +from .constants import TrailerKeys as TK +from .errors import ( + EmptyFileError, + FileNotDecryptedError, + LimitReachedError, + PdfReadError, + PdfStreamError, + WrongPasswordError, +) +from .generic import ( + ArrayObject, + ContentStream, + DecodedStreamObject, + Destination, + DictionaryObject, + EncodedStreamObject, + IndirectObject, + NameObject, + NullObject, + NumberObject, + PdfObject, + StreamObject, + TextStringObject, + TreeObject, + is_null_or_none, + read_object, +) +from .xmp import XmpInformation + +if TYPE_CHECKING: + from ._page import PageObject + + +class PdfReader(PdfDocCommon): + """ + Initialize a PdfReader object. + + This operation can take some time, as the PDF stream's cross-reference + tables are read into memory. + + Args: + stream: A File object or an object that supports the standard read + and seek methods similar to a File object. Could also be a + string representing a path to a PDF file. + strict: Determines whether user should be warned of all + problems and also causes some correctable problems to be fatal. + Defaults to ``False``. + password: Decrypt PDF file at initialization. If the + password is None, the file will not be decrypted. + Defaults to ``None``. + root_object_recovery_limit: The maximum number of objects to query + for recovering the Root object in non-strict mode. To disable + this security measure, pass ``None``. + + """ + + def __init__( + self, + stream: Union[StrByteType, Path], + strict: bool = False, + password: Union[str, bytes, None] = None, + *, + root_object_recovery_limit: Optional[int] = 10_000, + ) -> None: + self.strict = strict + self.flattened_pages: Optional[list[PageObject]] = None + + #: Storage of parsed PDF objects. + self.resolved_objects: dict[tuple[Any, Any], Optional[PdfObject]] = {} + + self._startxref: int = 0 + self.xref_index = 0 + self.xref: dict[int, dict[Any, Any]] = {} + self.xref_free_entry: dict[int, dict[Any, Any]] = {} + self.xref_objStm: dict[int, tuple[Any, Any]] = {} + self.trailer = DictionaryObject() + + # Security parameters. + self._root_object_recovery_limit = ( + root_object_recovery_limit if isinstance(root_object_recovery_limit, int) else sys.maxsize + ) + + # Map page indirect_reference number to page number + self._page_id2num: Optional[dict[Any, Any]] = None + + self._validated_root: Optional[DictionaryObject] = None + + self._initialize_stream(stream) + self._known_objects: set[tuple[int, int]] = set() + + self._override_encryption = False + self._encryption: Optional[Encryption] = None + if self.is_encrypted: + self._handle_encryption(password) + elif password is not None: + raise PdfReadError("Not an encrypted file") + + self._named_destinations_cache: Optional[dict[str, Destination]] = None + + def _initialize_stream(self, stream: Union[StrByteType, Path]) -> None: + if hasattr(stream, "mode") and "b" not in stream.mode: + logger_warning( + "PdfReader stream/file object is not in binary mode. " + "It may not be read correctly.", + source=__name__, + ) + self._stream_opened = False + if isinstance(stream, (str, Path)): + with open(stream, "rb") as fh: + stream = BytesIO(fh.read()) + self._stream_opened = True + self.read(stream) + self.stream = stream + + def _handle_encryption(self, password: Optional[Union[str, bytes]]) -> None: + self._override_encryption = True + # Some documents may not have a /ID, use two empty + # byte strings instead. Solves + # https://github.com/py-pdf/pypdf/issues/608 + id_entry = self.trailer.get(TK.ID) + id1_entry = id_entry[0].get_object().original_bytes if id_entry else b"" + encrypt_entry = cast(DictionaryObject, self.trailer[TK.ENCRYPT].get_object()) + self._encryption = Encryption.read(encrypt_entry, id1_entry) + + # try empty password if no password provided + pwd = password if password is not None else b"" + if ( + self._encryption.verify(pwd, strict=self.strict) == PasswordType.NOT_DECRYPTED + and password is not None + ): + # raise if password provided + raise WrongPasswordError("Wrong password") + self._override_encryption = False + + def __enter__(self) -> Self: + return self + + def __exit__( + self, + exc_type: Optional[type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + self.close() + + def close(self) -> None: + """Close the stream if opened in __init__ and clear memory.""" + if self._stream_opened: + self.stream.close() + self.flattened_pages = [] + self.resolved_objects = {} + self.trailer = DictionaryObject() + self.xref = {} + self.xref_free_entry = {} + self.xref_objStm = {} + + @property + def root_object(self) -> DictionaryObject: + """Provide access to "/Root". Standardized with PdfWriter.""" + if self._validated_root: + return self._validated_root + root = self.trailer.get(TK.ROOT) + if is_null_or_none(root): + logger_warning('Cannot find "/Root" key in trailer', source=__name__) + elif ( + cast(DictionaryObject, cast(PdfObject, root).get_object()).get("/Type") + == "/Catalog" + ): + self._validated_root = cast( + DictionaryObject, cast(PdfObject, root).get_object() + ) + else: + logger_warning("Invalid Root object in trailer", source=__name__) + if self._validated_root is None: + logger_warning('Searching object with "/Catalog" key', source=__name__) + number_of_objects = cast(int, self.trailer.get("/Size", 0)) + for i in range(number_of_objects): + if i >= self._root_object_recovery_limit: + raise LimitReachedError("Maximum Root object recovery limit reached.") + try: + obj = self.get_object(i + 1) + except Exception: # to be sure to capture all errors + obj = None + if isinstance(obj, DictionaryObject) and obj.get("/Type") == "/Catalog": + self._validated_root = obj + logger_warning( + "Root found at %(obj_reference)r", + source=__name__, + obj_reference=obj.indirect_reference, + ) + break + if self._validated_root is None: + if not is_null_or_none(root) and "/Pages" in cast(DictionaryObject, cast(PdfObject, root).get_object()): + logger_warning( + "Possible root found at %(root_ref)r, but missing /Catalog key", + source=__name__, + root_ref=cast(PdfObject, root).indirect_reference, + ) + self._validated_root = cast( + DictionaryObject, cast(PdfObject, root).get_object() + ) + else: + raise PdfReadError("Cannot find Root object in pdf") + return self._validated_root + + @property + def _info(self) -> Optional[DictionaryObject]: + """ + Provide access to "/Info". Standardized with PdfWriter. + + Returns: + /Info Dictionary; None if the entry does not exist + + """ + info = self.trailer.get(TK.INFO, None) + if is_null_or_none(info): + return None + assert info is not None, "mypy" + info = info.get_object() + if not isinstance(info, DictionaryObject): + raise PdfReadError( + "Trailer not found or does not point to a document information dictionary" + ) + return info + + @property + def _ID(self) -> Optional[ArrayObject]: + """ + Provide access to "/ID". Standardized with PdfWriter. + + Returns: + /ID array; None if the entry does not exist + + """ + id = self.trailer.get(TK.ID, None) + if is_null_or_none(id): + return None + assert id is not None, "mypy" + return cast(ArrayObject, id.get_object()) + + @property + def pdf_header(self) -> str: + """ + The first 8 bytes of the file. + + This is typically something like ``'%PDF-1.6'`` and can be used to + detect if the file is actually a PDF file and which version it is. + """ + # TODO: Make this return a bytes object for consistency + # but that needs a deprecation + loc = self.stream.tell() + self.stream.seek(0, 0) + pdf_file_version = self.stream.read(8).decode("utf-8", "backslashreplace") + self.stream.seek(loc, 0) # return to where it was + return pdf_file_version + + @property + def xmp_metadata(self) -> Optional[XmpInformation]: + """XMP (Extensible Metadata Platform) data.""" + try: + self._override_encryption = True + return cast(XmpInformation, self.root_object.xmp_metadata) + finally: + self._override_encryption = False + + def _get_page_number_by_indirect( + self, indirect_reference: Union[int, NullObject, IndirectObject, None] + ) -> Optional[int]: + """ + Retrieve the page number from an indirect reference. + + Args: + indirect_reference: The indirect reference to locate. + + Returns: + Page number or None. + + """ + if self._page_id2num is None: + self._page_id2num = { + x.indirect_reference.idnum: i for i, x in enumerate(self.pages) # type: ignore[union-attr] + } + + if is_null_or_none(indirect_reference): + return None + assert isinstance(indirect_reference, (int, IndirectObject)), "mypy" + if isinstance(indirect_reference, int): + idnum = indirect_reference + else: + idnum = indirect_reference.idnum + assert self._page_id2num is not None, "hint for mypy" + return self._page_id2num.get(idnum, None) + + def _get_object_from_stream( + self, indirect_reference: IndirectObject + ) -> Union[int, PdfObject, str]: + # indirect reference to object in object stream + # read the entire object stream into memory + stmnum, _idx = self.xref_objStm[indirect_reference.idnum] + obj_stm: EncodedStreamObject = IndirectObject(stmnum, 0, self).get_object() # type: ignore[assignment] + # This is an xref to a stream, so its type better be a stream + assert cast(str, obj_stm["/Type"]) == "/ObjStm" + # Parse ALL objects in this stream in one pass and cache them. + # This avoids O(N²) behavior when many objects from the same stream + # are resolved individually (each call would re-parse the header). + stream_data = BytesIO(obj_stm.get_data()) + n = int(obj_stm["/N"]) # type: ignore[call-overload] + first_offset = int(obj_stm["/First"]) # type: ignore[call-overload] + + # ObjStm header format: "objnum offset objnum offset ..." + # smallest possible entry: "0 0" = 3 bytes (1 digit + 1 space + 1 digit) + # using // 4 would reject a valid 3-byte single entry (3 // 4 = 0) + max_n = stream_data.getbuffer().nbytes // 3 + stream_data.seek(0) + if n > max_n: + if self.strict: + raise LimitReachedError(f"Value /N {n} for object {stmnum} exceeds maximum allowed value {max_n}.") + logger_warning( + "Value /N %(n)d for object %(stmnum)d exceeds maximum allowed value %(max_n)d. Limiting to %(max_n)d.", + source=__name__, + n=n, + stmnum=stmnum, + max_n=max_n, + ) + n = max_n + + # Phase 1: Read the index (objnum, offset) pairs from the header. + obj_index: list[tuple[int, int]] = [] + for _i in range(n): + read_non_whitespace(stream_data) + stream_data.seek(-1, 1) + objnum = NumberObject.read_from_stream(stream_data) + read_non_whitespace(stream_data) + stream_data.seek(-1, 1) + offset = NumberObject.read_from_stream(stream_data) + read_non_whitespace(stream_data) + stream_data.seek(-1, 1) + obj_index.append((int(objnum), int(offset))) + + # Phase 2: Parse each object and cache it. + target_obj: Union[int, PdfObject, str] = NullObject() + found = False + for i, (obj_num, obj_offset) in enumerate(obj_index): + # Skip objects already in the cache. + cached = self.cache_get_indirect_object(0, obj_num) + if cached is not None: + if obj_num == indirect_reference.idnum: + target_obj = cached + found = True + continue + + stream_data.seek(first_offset + obj_offset, 0) + + # To cope with case where the 'pointer' is on a white space + read_non_whitespace(stream_data) + stream_data.seek(-1, 1) + + try: + obj = read_object(stream_data, self) + except PdfStreamError as exc: + # Stream object cannot be read. Normally, a critical error, but + # Adobe Reader doesn't complain, so continue (in strict mode?) + logger_warning( + "Invalid stream (index %(index)d) within object %(obj_num)d 0: %(exc)s", + source=__name__, + index=i, + obj_num=obj_num, + exc=exc, + ) + if self.strict: # pragma: no cover + raise PdfReadError( + f"Cannot read object stream: {exc}" + ) # pragma: no cover + obj = NullObject() # pragma: no cover + + # Only cache if this stream is the authoritative source for the object. + # Incremental updates may override objects originally in the stream; + # caching those stale versions would shadow the newer xref entry. + authoritative_stm, _idx = self.xref_objStm.get(obj_num, (None, None)) + if authoritative_stm == stmnum: + self.cache_indirect_object(0, obj_num, obj) # type: ignore[arg-type] + + if obj_num == indirect_reference.idnum: + target_obj = obj + found = True + + if not found and self.strict: # pragma: no cover + raise PdfReadError( + "This is a fatal error in strict mode." + ) # pragma: no cover + return target_obj + + def get_object( + self, indirect_reference: Union[int, IndirectObject] + ) -> Optional[PdfObject]: + if isinstance(indirect_reference, int): + indirect_reference = IndirectObject(indirect_reference, 0, self) + retval = self.cache_get_indirect_object( + indirect_reference.generation, indirect_reference.idnum + ) + if retval is not None: + return retval + if ( + indirect_reference.generation == 0 + and indirect_reference.idnum in self.xref_objStm + ): + retval = self._get_object_from_stream(indirect_reference) # type: ignore + elif ( + indirect_reference.generation in self.xref + and indirect_reference.idnum in self.xref[indirect_reference.generation] + ): + if self.xref_free_entry.get(indirect_reference.generation, {}).get( + indirect_reference.idnum, False + ): + return NullObject() + start = self.xref[indirect_reference.generation][indirect_reference.idnum] + self.stream.seek(start, 0) + try: + idnum, generation = self.read_object_header(self.stream) + if ( + idnum != indirect_reference.idnum + or generation != indirect_reference.generation + ): + raise PdfReadError("Not matching, we parse the file for it") + except Exception: + if hasattr(self.stream, "getbuffer"): + buf = bytes(self.stream.getbuffer()) + else: + p = self.stream.tell() + self.stream.seek(0, 0) + buf = self.stream.read(-1) + self.stream.seek(p, 0) + m = re.search( + rf"\s{indirect_reference.idnum}\s+{indirect_reference.generation}\s+obj".encode(), + buf, + ) + if m is not None: + logger_warning( + "Object ID %(idnum)d,%(generation)d ref repaired", + source=__name__, + idnum=indirect_reference.idnum, + generation=indirect_reference.generation, + ) + self.xref[indirect_reference.generation][ + indirect_reference.idnum + ] = (m.start(0) + 1) + self.stream.seek(m.start(0) + 1) + idnum, generation = self.read_object_header(self.stream) + else: + idnum = -1 + generation = -1 # exception will be raised below + if idnum != indirect_reference.idnum and self.xref_index: + # xref table probably had bad indexes due to not being zero-indexed + if self.strict: + raise PdfReadError( + f"Expected object ID ({indirect_reference.idnum} {indirect_reference.generation}) " + f"does not match actual ({idnum} {generation}); " + "xref table not zero-indexed." + ) + # xref table is corrected in non-strict mode + elif idnum != indirect_reference.idnum and self.strict: + # some other problem + raise PdfReadError( + f"Expected object ID ({indirect_reference.idnum} {indirect_reference.generation}) " + f"does not match actual ({idnum} {generation})." + ) + if self.strict: + assert generation == indirect_reference.generation + + current_object = (indirect_reference.idnum, indirect_reference.generation) + if current_object in self._known_objects: + raise LimitReachedError(f"Detected loop with self reference for {indirect_reference!r}.") + self._known_objects.add(current_object) + retval = read_object(self.stream, self) # type: ignore[assignment] + self._known_objects.remove(current_object) + + # override encryption is used for the /Encrypt dictionary + if not self._override_encryption and self._encryption is not None: + # if we don't have the encryption key: + if not self._encryption.is_decrypted(): + raise FileNotDecryptedError("File has not been decrypted") + # otherwise, decrypt here... + retval = cast(PdfObject, retval) + retval = self._encryption.decrypt_object( + retval, indirect_reference.idnum, indirect_reference.generation, + strict=self.strict, + ) + else: + if hasattr(self.stream, "getbuffer"): + buf = bytes(self.stream.getbuffer()) + else: + p = self.stream.tell() + self.stream.seek(0, 0) + buf = self.stream.read(-1) + self.stream.seek(p, 0) + m = re.search( + rf"\s{indirect_reference.idnum}\s+{indirect_reference.generation}\s+obj".encode(), + buf, + ) + if m is not None: + logger_warning( + "Object %(idnum)d %(generation)d found", + source=__name__, + idnum=indirect_reference.idnum, + generation=indirect_reference.generation, + ) + if indirect_reference.generation not in self.xref: + self.xref[indirect_reference.generation] = {} + self.xref[indirect_reference.generation][indirect_reference.idnum] = ( + m.start(0) + 1 + ) + self.stream.seek(m.end(0) + 1) + skip_over_whitespace(self.stream) + self.stream.seek(-1, 1) + retval = read_object(self.stream, self) # type: ignore[assignment] + + # override encryption is used for the /Encrypt dictionary + if not self._override_encryption and self._encryption is not None: + # if we don't have the encryption key: + if not self._encryption.is_decrypted(): + raise FileNotDecryptedError("File has not been decrypted") + # otherwise, decrypt here... + retval = cast(PdfObject, retval) + retval = self._encryption.decrypt_object( + retval, indirect_reference.idnum, indirect_reference.generation, + strict=self.strict, + ) + else: + logger_warning( + "Object %(idnum)d %(generation)d not defined.", + source=__name__, + idnum=indirect_reference.idnum, + generation=indirect_reference.generation, + ) + if self.strict: + raise PdfReadError("Could not find object.") + # For ObjStm objects, _get_object_from_stream already cached + # the result during batch parsing; skip the redundant cache write + # to avoid "Overwriting cache" warnings. For non-ObjStm objects + # (including encrypted ones that need decrypted values cached), + # always write. + if not ( + indirect_reference.generation == 0 + and indirect_reference.idnum in self.xref_objStm + ): + self.cache_indirect_object( + indirect_reference.generation, indirect_reference.idnum, retval + ) + return retval + + def read_object_header(self, stream: StreamType) -> tuple[int, int]: + # Should never be necessary to read out whitespace, since the + # cross-reference table should put us in the right spot to read the + # object header. In reality some files have stupid cross-reference + # tables that are off by whitespace bytes. + skip_over_comment(stream) + extra = skip_over_whitespace(stream) + stream.seek(-1, 1) + idnum = read_until_whitespace(stream) + extra |= skip_over_whitespace(stream) + stream.seek(-1, 1) + generation = read_until_whitespace(stream) + extra |= skip_over_whitespace(stream) + stream.seek(-1, 1) + + # although it's not used, it might still be necessary to read + _obj = stream.read(3) + + read_non_whitespace(stream) + stream.seek(-1, 1) + if extra and self.strict: + logger_warning( + "Superfluous whitespace found in object header %(idnum)r %(generation)r", + source=__name__, + idnum=idnum, + generation=generation, + ) + return int(idnum), int(generation) + + def cache_get_indirect_object( + self, generation: int, idnum: int + ) -> Optional[PdfObject]: + try: + return self.resolved_objects.get((generation, idnum)) + except RecursionError: + raise PdfReadError("Maximum recursion depth reached.") + + def cache_indirect_object( + self, generation: int, idnum: int, obj: Optional[PdfObject] + ) -> Optional[PdfObject]: + if (generation, idnum) in self.resolved_objects: + msg = "Overwriting cache for %(generation)d %(idnum)d" + values = {"generation": generation, "idnum": idnum} + if self.strict: + raise PdfReadError(msg % values) + logger_warning(msg, source=__name__, **values) + self.resolved_objects[(generation, idnum)] = obj + if obj is not None: + obj.indirect_reference = IndirectObject(idnum, generation, self) + return obj + + def _replace_object(self, indirect_reference: IndirectObject, obj: PdfObject) -> PdfObject: + # function reserved for future development + if indirect_reference.pdf != self: + raise ValueError("Cannot update PdfReader with external object") + if (indirect_reference.generation, indirect_reference.idnum) not in self.resolved_objects: + raise ValueError("Cannot find referenced object") + self.resolved_objects[(indirect_reference.generation, indirect_reference.idnum)] = obj + obj.indirect_reference = indirect_reference + return obj + + def read(self, stream: StreamType) -> None: + """ + Read and process the PDF stream, extracting necessary data. + + Args: + stream: The PDF file stream. + + """ + self._basic_validation(stream) + self._find_eof_marker(stream) + startxref = self._find_startxref_pos(stream) + self._startxref = startxref + + # check and eventually correct the startxref only if not strict + xref_issue_nr = self._get_xref_issues(stream, startxref) + if xref_issue_nr != 0: + if self.strict and xref_issue_nr: + raise PdfReadError("Broken xref table") + logger_warning( + "incorrect startxref pointer(%(xref_issue_nr)d)", + source=__name__, + xref_issue_nr=xref_issue_nr, + ) + + # read all cross-reference tables and their trailers + self._read_xref_tables_and_trailers(stream, startxref, xref_issue_nr) + + # if not zero-indexed, verify that the table is correct; change it if necessary + if self.xref_index and not self.strict: + loc = stream.tell() + for gen, xref_entry in self.xref.items(): + if gen == 65535: + continue + xref_k = sorted( + xref_entry.keys() + ) # ensure ascending to prevent damage + for id in xref_k: + stream.seek(xref_entry[id], 0) + try: + pid, _pgen = self.read_object_header(stream) + except ValueError: + self._rebuild_xref_table(stream) + break + if pid == id - self.xref_index: + # fixing index item per item is required for revised PDF. + self.xref[gen][pid] = self.xref[gen][id] + del self.xref[gen][id] + # if not, then either it's just plain wrong, or the + # non-zero-index is actually correct + stream.seek(loc, 0) # return to where it was + + # remove wrong objects (not pointing to correct structures) - cf #2326 + if not self.strict: + loc = stream.tell() + for gen, xref_entry in self.xref.items(): + if gen == 65535: + continue + ids = list(xref_entry.keys()) + for id in ids: + stream.seek(xref_entry[id], 0) + try: + self.read_object_header(stream) + except ValueError: + logger_warning( + "Ignoring wrong pointing object %(id)d %(gen)d (offset %(offset)d)", + source=__name__, + id=id, + gen=gen, + offset=xref_entry[id], + ) + del xref_entry[id] # we can delete the id, we are parsing ids + stream.seek(loc, 0) # return to where it was + + def _basic_validation(self, stream: StreamType) -> None: + """Ensure the stream is valid and not empty.""" + stream.seek(0, os.SEEK_SET) + try: + header_byte = stream.read(5) + except UnicodeDecodeError: + raise UnsupportedOperation("cannot read header") + if header_byte == b"": + raise EmptyFileError("Cannot read an empty file") + if header_byte != b"%PDF-": + if self.strict: + raise PdfReadError( + f"PDF starts with '{header_byte.decode('utf8')}', " + "but '%PDF-' expected" + ) + logger_warning("invalid pdf header: %(header_byte)r", source=__name__, header_byte=header_byte) + stream.seek(0, os.SEEK_END) + + def _find_eof_marker(self, stream: StreamType) -> None: + """ + Jump to the %%EOF marker. + + According to the specs, the %%EOF marker should be at the very end of + the file. Hence for standard-compliant PDF documents this function will + read only the last part (DEFAULT_BUFFER_SIZE). + """ + HEADER_SIZE = 8 # to parse whole file, Header is e.g. '%PDF-1.6' + line = b"" + first = True + while not line.startswith(b"%%EOF"): + if line != b"" and first: + if any( + line.strip().endswith(tr) for tr in (b"%%EO", b"%%E", b"%%", b"%") + ): + # Consider the file as truncated while + # having enough confidence to carry on. + logger_warning("EOF marker seems truncated", source=__name__) + break + first = False + if b"startxref" in line: + logger_warning( + "CAUTION: startxref found while searching for %%EOF. " + "The file might be truncated and some data might not be read.", + source=__name__, + ) + if stream.tell() < HEADER_SIZE: + if self.strict: + raise PdfReadError("EOF marker not found") + logger_warning("EOF marker not found", source=__name__) + line = read_previous_line(stream) + + def _find_startxref_pos(self, stream: StreamType) -> int: + """ + Find startxref entry - the location of the xref table. + + Args: + stream: + + Returns: + The bytes offset + + """ + line = read_previous_line(stream) + try: + startxref = int(line) + except ValueError: + # 'startxref' may be on the same line as the location + if not line.startswith(b"startxref"): + raise PdfReadError("startxref not found") + startxref = int(line[9:].strip()) + logger_warning("startxref on same line as offset", source=__name__) + else: + line = read_previous_line(stream) + if not line.startswith(b"startxref"): + # The 'startxref' keyword expected just above the offset is + # missing or corrupt (for example a truncated 'tartxref'). + # Some producers append a broken trailing cross-reference + # pointer while an earlier, intact 'startxref' from a previous + # revision is still present. Recovering from this violates the + # standard, so only attempt it in non-strict mode (#3238). + if self.strict: + raise PdfReadError("startxref not found") + startxref = self._find_previous_startxref_pos(stream) + return startxref + + # Upper bound on the number of lines _find_previous_startxref_pos scans + # backwards while recovering a corrupt trailing startxref pointer. Kept + # fixed and non-configurable so a crafted file cannot trigger an unbounded + # backwards scan. + _MAX_STARTXREF_RECOVERY_LINES = 1000 + + @classmethod + def _find_previous_startxref_pos(cls, stream: StreamType) -> int: + """ + Recover the most recent intact ``startxref`` pointer by scanning + backwards from the current position. + + This is used as a fallback when the ``startxref`` keyword belonging to + the final ``%%EOF`` is corrupt (#3238). The offset always appears on + the line directly below the keyword, so the value read immediately + before encountering ``startxref`` (while moving backwards) is returned. + At most ``_MAX_STARTXREF_RECOVERY_LINES`` lines are inspected. + + Args: + stream: The PDF byte stream, positioned just above the corrupt + trailing pointer. + + Returns: + The bytes offset of the recovered ``startxref``. + + """ + offset: Optional[int] = None + for _ in range(cls._MAX_STARTXREF_RECOVERY_LINES): + if stream.tell() <= 0: + break + line = read_previous_line(stream) + if not line.startswith(b"startxref"): + try: + offset = int(line) + except ValueError: + offset = None + continue + if len(line) > 9: + # 'startxref' on the same line as the offset + return int(line[9:].strip()) + if offset is not None: + logger_warning( + "found startxref pointing to a previous revision after " + "a corrupt one", + source=__name__, + ) + return offset + break + raise PdfReadError("startxref not found") + + def _load_recovery_cache(self, data: bytes) -> dict[int, tuple[int, int]]: + cache = {} + for object_number, generation_number, object_start in self._find_pdf_objects(data): + if object_number in cache: + # Always use the first match. + continue + cache[object_number] = (object_start, generation_number) + return cache + + def _read_standard_xref_table(self, stream: StreamType) -> None: + # standard cross-reference table + ref = stream.read(3) + if ref != b"ref": + raise PdfReadError("xref table read error") + read_non_whitespace(stream) + stream.seek(-1, 1) + first_time = True # check if the first time looking at the xref table + recovery_cache: Optional[dict[int, tuple[int, int]]] = None + while True: + num = cast(int, read_object(stream, self)) + if first_time and num != 0: + self.xref_index = num + if self.strict: + logger_warning( + "Xref table not zero-indexed. ID numbers for objects will be corrected.", + source=__name__, + ) + # if table not zero indexed, could be due to error from when PDF was created + # which will lead to mismatched indices later on, only warned and corrected if self.strict==True + first_time = False + read_non_whitespace(stream) + stream.seek(-1, 1) + size = cast(int, read_object(stream, self)) + if not isinstance(size, int): + logger_warning( + "Invalid/Truncated xref table. Rebuilding it.", + source=__name__, + ) + self._rebuild_xref_table(stream) + stream.read() + return + read_non_whitespace(stream) + stream.seek(-1, 1) + cnt = 0 + while cnt < size: + line = stream.read(20) + if not line: + raise PdfReadError("Unexpected empty line in Xref table.") + + # It's very clear in section 3.4.3 of the PDF spec + # that all cross-reference table lines are a fixed + # 20 bytes (as of PDF 1.7). However, some files have + # 21-byte entries (or more) due to the use of \r\n + # (CRLF) EOL's. Detect that case, and adjust the line + # until it does not begin with a \r (CR) or \n (LF). + while line[0] in b"\x0D\x0A": + stream.seek(-20 + 1, 1) + line = stream.read(20) + + # On the other hand, some malformed PDF files + # use a single character EOL without a preceding + # space. Detect that case, and seek the stream + # back one character (0-9 means we've bled into + # the next xref entry, t means we've bled into the + # text "trailer"): + if line[-1] in b"0123456789t": + stream.seek(-1, 1) + + try: + offset_b, generation_b = line[:16].split(b" ") + entry_type_b = line[17:18] + + offset, generation = int(offset_b), int(generation_b) + except Exception: + if hasattr(stream, "getbuffer"): + buf = bytes(stream.getbuffer()) + else: + p = stream.tell() + stream.seek(0, 0) + buf = stream.read(-1) + stream.seek(p) + + if recovery_cache is None: + recovery_cache = self._load_recovery_cache(buf) + + if num not in recovery_cache: + logger_warning( + "entry %(num)d in Xref table invalid; object not found", + source=__name__, + num=num, + ) + generation = 65535 + offset = -1 + entry_type_b = b"f" + else: + logger_warning( + "entry %(num)d in Xref table invalid but object found", + source=__name__, + num=num, + ) + generation, offset = recovery_cache[num] + entry_type_b = b"n" + + if generation not in self.xref: + self.xref[generation] = {} + self.xref_free_entry[generation] = {} + if num in self.xref[generation]: + # It really seems like we should allow the last + # xref table in the file to override previous + # ones. Since we read the file backwards, assume + # any existing key is already set correctly. + pass + else: + if entry_type_b == b"n": + self.xref[generation][num] = offset + try: + self.xref_free_entry[generation][num] = entry_type_b == b"f" + except Exception: + pass + try: + self.xref_free_entry[65535][num] = entry_type_b == b"f" + except Exception: + pass + cnt += 1 + num += 1 + read_non_whitespace(stream) + stream.seek(-1, 1) + # Skip any PDF comments between xref entries and the trailer + # keyword. Some PDF producers (e.g. Vectorizer.AI) insert + # comments here which are legal per the PDF spec (§7.2.3). + while stream.read(1) == b"%": + stream.seek(-1, 1) + skip_over_comment(stream) + read_non_whitespace(stream) + stream.seek(-1, 1) + stream.seek(-1, 1) + trailer_tag = stream.read(7) + if trailer_tag != b"trailer": + # more xrefs! + stream.seek(-7, 1) + else: + break + + def _read_xref_tables_and_trailers( + self, stream: StreamType, startxref: Optional[int], xref_issue_nr: int + ) -> None: + """Read the cross-reference tables and trailers in the PDF stream.""" + self.xref = {} + self.xref_free_entry = {} + self.xref_objStm = {} + self.trailer = DictionaryObject() + visited_xref_offsets: set[int] = set() + while startxref is not None: + # Detect circular /Prev references in the xref chain + if startxref in visited_xref_offsets: + logger_warning( + "Circular xref chain detected at offset %(startxref)d, stopping", + source=__name__, + startxref=startxref, + ) + break + visited_xref_offsets.add(startxref) + # load the xref table + stream.seek(startxref, 0) + x = stream.read(1) + if x in b"\r\n": + x = stream.read(1) + if x == b"x": + startxref = self._read_xref(stream) + elif xref_issue_nr: + try: + self._rebuild_xref_table(stream) + break + except Exception: + xref_issue_nr = 0 + elif x.isdigit(): + try: + xrefstream = self._read_pdf15_xref_stream(stream) + except Exception as e: + if TK.ROOT in self.trailer: + logger_warning( + "Previous trailer cannot be read: %(args)s", + source=__name__, + args=e.args, + ) + break + raise PdfReadError(f"Trailer cannot be read: {e!s}") + self._process_xref_stream(xrefstream) + if "/Prev" in xrefstream: + startxref = cast(int, xrefstream["/Prev"]) + else: + break + else: + startxref = self._read_xref_other_error(stream, startxref) + + def _process_xref_stream(self, xrefstream: DictionaryObject) -> None: + """Process and handle the xref stream.""" + trailer_keys = TK.ROOT, TK.ENCRYPT, TK.INFO, TK.ID, TK.SIZE + for key in trailer_keys: + if key in xrefstream and key not in self.trailer: + self.trailer[NameObject(key)] = xrefstream.raw_get(key) + if "/XRefStm" in xrefstream: + p = self.stream.tell() + self.stream.seek(cast(int, xrefstream["/XRefStm"]) + 1, 0) + self._read_pdf15_xref_stream(self.stream) + self.stream.seek(p, 0) + + def _read_xref(self, stream: StreamType) -> Optional[int]: + self._read_standard_xref_table(stream) + if stream.read(1) == b"": + return None + stream.seek(-1, 1) + read_non_whitespace(stream) + stream.seek(-1, 1) + new_trailer = cast(dict[str, Any], read_object(stream, self)) + for key, value in new_trailer.items(): + if key not in self.trailer: + self.trailer[key] = value + if "/XRefStm" in new_trailer: + p = stream.tell() + stream.seek(cast(int, new_trailer["/XRefStm"]) + 1, 0) + try: + self._read_pdf15_xref_stream(stream) + except Exception: + logger_warning( + "XRef object at %(xref_stm)d can not be read, some object may be missing", + source=__name__, + xref_stm=int(new_trailer["/XRefStm"]), + ) + stream.seek(p, 0) + if "/Prev" in new_trailer: + return cast(int, new_trailer["/Prev"]) + return None + + def _read_xref_other_error( + self, stream: StreamType, startxref: int + ) -> Optional[int]: + # some PDFs have /Prev=0 in the trailer, instead of no /Prev + if startxref == 0: + if self.strict: + raise PdfReadError( + "/Prev=0 in the trailer (try opening with strict=False)" + ) + logger_warning( + "/Prev=0 in the trailer - assuming there is no previous xref table", + source=__name__, + ) + return None + # bad xref character at startxref. Let's see if we can find + # the xref table nearby, as we've observed this error with an + # off-by-one before. + stream.seek(-11, 1) + tmp = stream.read(20) + xref_loc = tmp.find(b"xref") + if xref_loc != -1: + startxref -= 10 - xref_loc + return startxref + # No explicit xref table, try finding a cross-reference stream. + stream.seek(startxref, 0) + for look in range(25): # value extended to cope with more linearized files + if stream.read(1).isdigit(): + # This is not a standard PDF, consider adding a warning + startxref += look + return startxref + # no xref table found at specified location + if "/Root" in self.trailer and not self.strict: + # if Root has been already found, just raise warning + logger_warning("Invalid parent xref., rebuild xref", source=__name__) + try: + self._rebuild_xref_table(stream) + return None + except Exception: + raise PdfReadError("Cannot rebuild xref") + raise PdfReadError("Could not find xref table at specified location") + + def _sanitize_pdf15_xref_stream_index_pairs( + self, index_pairs: list[int], entry_sizes: list[int], xref_stream: ContentStream + ) -> list[int]: + # `entry_sizes` holds the byte widths for the entries. Summing determines the total number of bytes per entry. + # We expect up to 3 values. `min_entry_bytes` will be the smallest plausible size of one xref entry. + min_entry_bytes = sum(int(entry_sizes[i]) for i in range(min(len(entry_sizes), 3))) + if min_entry_bytes == 0: + message = "Cross-reference stream encodes no entry data." + if self.strict: + raise PdfStreamError(message) + logger_warning(message, source=__name__) + return [] + + # maximum number of entries that could physically fit + max_entries = len(xref_stream.get_data()) // min_entry_bytes + 1 + + result = [] + total = 0 + + for index, pair_value in enumerate(index_pairs): + pair_value_int = int(pair_value) + + # `index_pairs` has the format `[start0, count0, start1, count1, ...]` + # Only modify the counts here, but keep the start values. + if index % 2 == 1: + if total + pair_value_int > max_entries: + if self.strict: + raise LimitReachedError( + f"Total XRef entries {total + pair_value_int} exceed maximum allowed value {max_entries}." + ) + new_v = max(0, max_entries - total) + logger_warning( + "Clamping XRef count from %(old_count)d to %(new_count)d to fit stream size.", + source=__name__, + old_count=pair_value_int, + new_count=new_v, + ) + pair_value_int = new_v + + total += pair_value_int + + result.append(pair_value_int) + + return result + + def _read_pdf15_xref_stream( + self, stream: StreamType + ) -> Union[ContentStream, EncodedStreamObject, DecodedStreamObject]: + """Read the cross-reference stream for PDF 1.5+.""" + stream.seek(-1, 1) + stream_idnum, stream_generation = self.read_object_header(stream) + xref_stream = cast(ContentStream, read_object(stream, self)) + if cast(str, xref_stream["/Type"]) != "/XRef": + raise PdfReadError(f"Unexpected type {xref_stream['/Type']!r}") + self.cache_indirect_object(stream_generation, stream_idnum, xref_stream) + + # Index pairs specify the subsections in the dictionary. + # If none, create one subsection that spans everything. + if "/Size" not in xref_stream: + # According to table 17 of the PDF 2.0 specification, this key is required. + raise PdfReadError(f"Size missing from XRef stream {xref_stream!r}!") + index_pairs = xref_stream.get("/Index", [0, xref_stream["/Size"]]) + + entry_sizes = cast(list[int], xref_stream.get("/W")) + assert len(entry_sizes) >= 3 + if self.strict and len(entry_sizes) > 3: + raise PdfReadError(f"Too many entry sizes: {entry_sizes}") + index_pairs = self._sanitize_pdf15_xref_stream_index_pairs( + index_pairs=index_pairs, entry_sizes=entry_sizes, xref_stream=xref_stream + ) + + stream_data = BytesIO(xref_stream.get_data()) + + def get_entry(i: int) -> Union[int, tuple[int, ...]]: + # Reads the correct number of bytes for each entry. See the + # discussion of the W parameter in PDF spec table 17. + if entry_sizes[i] > 0: + d = stream_data.read(entry_sizes[i]) + return convert_to_int(d, entry_sizes[i]) + + # PDF Spec Table 17: A value of zero for an element in the + # W array indicates...the default value shall be used + if i == 0: + return 1 # First value defaults to 1 + return 0 + + def used_before(num: int, generation: Union[int, tuple[int, ...]]) -> bool: + # We move backwards through the xrefs, don't replace any. + return num in self.xref.get(generation, []) or num in self.xref_objStm # type: ignore[arg-type] + + # Iterate through each subsection + self._read_xref_subsections(index_pairs, get_entry, used_before) + return xref_stream + + @staticmethod + def _get_xref_issues(stream: StreamType, startxref: int) -> int: + """ + Return an int which indicates an issue. 0 means there is no issue. + + Args: + stream: + startxref: + + Returns: + 0 means no issue, other values represent specific issues. + + """ + if startxref == 0: + return 4 + + stream.seek(startxref - 1, 0) # -1 to check character before + line = stream.read(1) + if line == b"j": + line = stream.read(1) + if line not in b"\r\n \t": + return 1 + line = stream.read(4) + if line != b"xref": + # not a xref so check if it is an XREF object + line = b"" + while line in b"0123456789 \t": + line = stream.read(1) + if line == b"": + return 2 + line += stream.read(2) # 1 char already read, +2 to check "obj" + if line.lower() != b"obj": + return 3 + return 0 + + @classmethod + def _find_pdf_objects(cls, data: bytes) -> Iterable[tuple[int, int, int]]: + index = 0 + ord_0 = ord("0") + ord_9 = ord("9") + while True: + index = data.find(b" obj", index) + if index == -1: + return + + index_before_space = index - 1 + + # Skip whitespace backwards + while index_before_space >= 0 and data[index_before_space] in WHITESPACES_AS_BYTES: + index_before_space -= 1 + + # Read generation number + generation_end = index_before_space + 1 + while index_before_space >= 0 and ord_0 <= data[index_before_space] <= ord_9: + index_before_space -= 1 + generation_start = index_before_space + 1 + + # Skip whitespace + while index_before_space >= 0 and data[index_before_space] in WHITESPACES_AS_BYTES: + index_before_space -= 1 + + # Read object number + object_end = index_before_space + 1 + while index_before_space >= 0 and ord_0 <= data[index_before_space] <= ord_9: + index_before_space -= 1 + object_start = index_before_space + 1 + + # Validate + if object_start < object_end and generation_start < generation_end: + object_number = int(data[object_start:object_end]) + generation_number = int(data[generation_start:generation_end]) + + yield object_number, generation_number, object_start + + index += 4 # len(b" obj") + + @classmethod + def _find_pdf_trailers(cls, data: bytes) -> Iterable[int]: + index = 0 + data_length = len(data) + while True: + index = data.find(b"trailer", index) + if index == -1: + return + + index_after_trailer = index + 7 # len(b"trailer") + + # Skip whitespace + while index_after_trailer < data_length and data[index_after_trailer] in WHITESPACES_AS_BYTES: + index_after_trailer += 1 + + # Must be dictionary start + if index_after_trailer + 1 < data_length and data[index_after_trailer:index_after_trailer+2] == b"<<": + yield index_after_trailer # offset of '<<' + + index += 7 # len(b"trailer") + + def _rebuild_xref_table(self, stream: StreamType) -> None: + self.xref = {} + stream.seek(0, 0) + stream_data = stream.read(-1) + + for object_number, generation_number, object_start in self._find_pdf_objects(stream_data): + if generation_number not in self.xref: + self.xref[generation_number] = {} + self.xref[generation_number][object_number] = object_start + + logger_warning("parsing for Object Streams", source=__name__) + for generation_number in self.xref: + for object_number in self.xref[generation_number]: + # get_object in manual + stream.seek(self.xref[generation_number][object_number], 0) + try: + _ = self.read_object_header(stream) + obj = cast(StreamObject, read_object(stream, self)) + if obj.get("/Type", "") != "/ObjStm": + continue + object_stream = BytesIO(obj.get_data()) + actual_count = 0 + while True: + current = read_until_whitespace(object_stream) + if not current.isdigit(): + break + inner_object_number = int(current) + skip_over_whitespace(object_stream) + object_stream.seek(-1, 1) + current = read_until_whitespace(object_stream) + if not current.isdigit(): # pragma: no cover + break # pragma: no cover + inner_generation_number = int(current) + self.xref_objStm[inner_object_number] = (object_number, inner_generation_number) + actual_count += 1 + expected_count = cast(int, obj["/N"]) + if actual_count != expected_count: # pragma: no cover + logger_warning( # pragma: no cover + ( + "found %(actual_count)d objects within " + "Object(%(object_number)d,%(generation_number)d) " + "whereas %(expected)d expected" + ), + source=__name__, + actual_count=actual_count, + object_number=object_number, + generation_number=generation_number, + expected=expected_count, + ) + except Exception: # could be multiple causes + pass + + stream.seek(0, 0) + for position in self._find_pdf_trailers(stream_data): + stream.seek(position, 0) + new_trailer = cast(dict[Any, Any], read_object(stream, self)) + # Here, we are parsing the file from start to end, the new data have to erase the existing. + for key, value in new_trailer.items(): + self.trailer[key] = value + + def _read_xref_subsections( + self, + idx_pairs: list[int], + get_entry: Callable[[int], Union[int, tuple[int, ...]]], + used_before: Callable[[int, Union[int, tuple[int, ...]]], bool], + ) -> None: + """Read and process the subsections of the xref.""" + for start, size in self._pairs(idx_pairs): + # The subsections must increase + for num in range(start, start + size): + # The first entry is the type + xref_type = get_entry(0) + # The rest of the elements depend on the xref_type + if xref_type == 0: + # linked list of free objects + next_free_object = get_entry(1) # noqa: F841 + next_generation = get_entry(2) # noqa: F841 + elif xref_type == 1: + # objects that are in use but are not compressed + byte_offset = get_entry(1) + generation = get_entry(2) + if generation not in self.xref: + self.xref[generation] = {} # type: ignore[index] + if not used_before(num, generation): + self.xref[generation][num] = byte_offset # type: ignore[index] + elif xref_type == 2: + # compressed objects + objstr_num = get_entry(1) + obstr_idx = get_entry(2) + generation = 0 # PDF spec table 18, generation is 0 + if not used_before(num, generation): + self.xref_objStm[num] = (objstr_num, obstr_idx) + elif self.strict: + raise PdfReadError(f"Unknown xref type: {xref_type}") + + def _pairs(self, array: list[int]) -> Iterable[tuple[int, int]]: + """Iterate over pairs in the array.""" + i = 0 + while i + 1 < len(array): + yield array[i], array[i + 1] + i += 2 + + def decrypt(self, password: Union[str, bytes]) -> PasswordType: + """ + When using an encrypted / secured PDF file with the PDF Standard + encryption handler, this function will allow the file to be decrypted. + It checks the given password against the document's user password and + owner password, and then stores the resulting decryption key if either + password is correct. + + It does not matter which password was matched. Both passwords provide + the correct decryption key that will allow the document to be used with + this library. + + Args: + password: The password to match. + + Returns: + An indicator if the document was decrypted and whether it was the + owner password or the user password. + + """ + if not self._encryption: + raise PdfReadError("Not encrypted file") + # TODO: raise Exception for wrong password + return self._encryption.verify(password, strict=self.strict) + + @property + def is_encrypted(self) -> bool: + """ + Read-only boolean property showing whether this PDF file is encrypted. + + Note that this property, if true, will remain true even after the + :meth:`decrypt()` method is called. + """ + return TK.ENCRYPT in self.trailer + + def add_form_topname(self, name: str) -> Optional[DictionaryObject]: + """ + Add a top level form that groups all form fields below it. + + Args: + name: text string of the "/T" Attribute of the created object + + Returns: + The created object. ``None`` means no object was created. + + """ + catalog = self.root_object + + if "/AcroForm" not in catalog or not isinstance( + catalog["/AcroForm"], DictionaryObject + ): + return None + acroform = cast(DictionaryObject, catalog[NameObject("/AcroForm")]) + if "/Fields" not in acroform: + # TODO: No error but this may be extended for XFA Forms + return None + + interim = DictionaryObject() + interim[NameObject("/T")] = TextStringObject(name) + interim[NameObject("/Kids")] = acroform[NameObject("/Fields")] + self.cache_indirect_object( + 0, + max(i for (g, i) in self.resolved_objects if g == 0) + 1, + interim, + ) + arr = ArrayObject() + arr.append(interim.indirect_reference) + acroform[NameObject("/Fields")] = arr + for o in cast(ArrayObject, interim["/Kids"]): + obj = o.get_object() + if "/Parent" in obj: + logger_warning( + "Top Level Form Field %(obj_ref)s has a non-expected parent", + source=__name__, + obj_ref=obj.indirect_reference, + ) + obj[NameObject("/Parent")] = interim.indirect_reference + return interim + + def rename_form_topname(self, name: str) -> Optional[DictionaryObject]: + """ + Rename top level form field that all form fields below it. + + Args: + name: text string of the "/T" field of the created object + + Returns: + The modified object. ``None`` means no object was modified. + + """ + catalog = self.root_object + + if "/AcroForm" not in catalog or not isinstance( + catalog["/AcroForm"], DictionaryObject + ): + return None + acroform = cast(DictionaryObject, catalog[NameObject("/AcroForm")]) + if "/Fields" not in acroform: + return None + + interim = cast( + DictionaryObject, + cast(ArrayObject, acroform[NameObject("/Fields")])[0].get_object(), + ) + interim[NameObject("/T")] = TextStringObject(name) + return interim + + def _repr_mimebundle_( + self, + include: Union[Iterable[str], None] = None, + exclude: Union[Iterable[str], None] = None, + ) -> dict[str, Any]: + """ + Integration into Jupyter Notebooks. + + This method returns a dictionary that maps a mime-type to its + representation. + + .. seealso:: + + https://ipython.readthedocs.io/en/stable/config/integrating.html + """ + self.stream.seek(0) + pdf_data = self.stream.read() + data = { + "application/pdf": pdf_data, + } + + if include is not None: + # Filter representations based on include list + data = {k: v for k, v in data.items() if k in include} + + if exclude is not None: + # Remove representations based on exclude list + data = {k: v for k, v in data.items() if k not in exclude} + + return data + + def _get_named_destinations( + self, + *, + tree: Union[TreeObject, None] = None, + retval: Optional[dict[str, Destination]] = None, + visited: Optional[set[int]] = None, + ) -> dict[str, Destination]: + """Override from PdfDocCommon. In the reader we can assume this is + static, but not in the writer. + """ + if tree or retval: + return super()._get_named_destinations(tree=tree, retval=retval, visited=visited) + + if self._named_destinations_cache is None: + self._named_destinations_cache = super()._get_named_destinations() + return self._named_destinations_cache diff --git a/.venv/lib/python3.13/site-packages/pypdf/_text_extraction/__init__.py b/.venv/lib/python3.13/site-packages/pypdf/_text_extraction/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a45480a6176dc419f14d4b27e11fb29789b986c0 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/_text_extraction/__init__.py @@ -0,0 +1,244 @@ +""" +Code related to text extraction. + +Some parts are still in _page.py. In doubt, they will stay there. +""" + +import math +from typing import Any, Callable, Optional, Union + +from .._font import Font +from .._utils import is_char_neutral, is_char_rtl +from ..generic import DictionaryObject, TextStringObject, encode_pdfdocencoding + +CUSTOM_RTL_MIN: str = "" +CUSTOM_RTL_MAX: str = "" +CUSTOM_RTL_SPECIAL_CHARS: str = "" +LAYOUT_NEW_BT_GROUP_SPACE_WIDTHS: int = 5 +UNICODE_LOWER_LIMIT = 0 +UNICODE_UPPER_LIMIT = 0x10FFFF + + +class OrientationNotFoundError(Exception): + pass + + +def set_custom_rtl( + _min: Union[str, int, None] = "", + _max: Union[str, int, None] = "", + specials: Union[str, list[int], None] = None, +) -> tuple[str, str, str]: + """ + Change the Right-To-Left and special characters custom parameters. + + Args: + _min: The new minimum value for the range of custom characters that + will be written right to left. + If set to ``None``, the value will not be changed. + If set to a valid integer, it will be converted to its corresponding character. + The default value is "", which sets no additional range to be converted. + _max: The new maximum value for the range of custom characters that will + be written right to left. + If set to ``None``, the value will not be changed. + If set to a valid integer, it will be converted to its corresponding character. + The default value is "", which sets no additional range to be converted. + specials: The new list of special characters to be inserted in the + current insertion order. + If set to ``None``, the current value will not be changed. + If set to a string, it will be converted to a list of ASCII codes. + The default value is an empty list. + + Returns: + A tuple containing the new values for ``CUSTOM_RTL_MIN``, + ``CUSTOM_RTL_MAX``, and ``CUSTOM_RTL_SPECIAL_CHARS``. + + """ + global CUSTOM_RTL_MIN, CUSTOM_RTL_MAX, CUSTOM_RTL_SPECIAL_CHARS + if isinstance(_min, int): + CUSTOM_RTL_MIN = chr(_min) if UNICODE_LOWER_LIMIT <= _min <= UNICODE_UPPER_LIMIT else "" + elif isinstance(_min, str): + CUSTOM_RTL_MIN = _min + if isinstance(_max, int): + CUSTOM_RTL_MAX = chr(_max) if UNICODE_LOWER_LIMIT <= _max <= UNICODE_UPPER_LIMIT else "" + elif isinstance(_max, str): + CUSTOM_RTL_MAX = _max + if isinstance(specials, str): + CUSTOM_RTL_SPECIAL_CHARS = specials + elif isinstance(specials, list): + CUSTOM_RTL_SPECIAL_CHARS = "".join( + chr(char) for char in specials if UNICODE_LOWER_LIMIT <= char <= UNICODE_UPPER_LIMIT + ) + return CUSTOM_RTL_MIN, CUSTOM_RTL_MAX, CUSTOM_RTL_SPECIAL_CHARS + + +def mult(m: list[float], n: list[float]) -> list[float]: + return [ + m[0] * n[0] + m[1] * n[2], + m[0] * n[1] + m[1] * n[3], + m[2] * n[0] + m[3] * n[2], + m[2] * n[1] + m[3] * n[3], + m[4] * n[0] + m[5] * n[2] + n[4], + m[4] * n[1] + m[5] * n[3] + n[5], + ] + + +def orient(m: list[float]) -> int: + if m[3] > 1e-6: + return 0 + if m[3] < -1e-6: + return 180 + if m[1] > 0: + return 90 + return 270 + + +def crlf_space_check( + text: str, + cmtm_prev: tuple[list[float], list[float]], + cmtm_matrix: tuple[list[float], list[float]], + memo_cmtm: tuple[list[float], list[float]], + font_resource: Optional[DictionaryObject], + orientations: tuple[int, ...], + output: str, + font_size: float, + visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]], + str_widths: float, + spacewidth: float, + str_height: float, +) -> tuple[str, str, list[float], list[float]]: + cm_prev = cmtm_prev[0] + tm_prev = cmtm_prev[1] + cm_matrix = cmtm_matrix[0] + tm_matrix = cmtm_matrix[1] + memo_cm = memo_cmtm[0] + memo_tm = memo_cmtm[1] + + m_prev = mult(tm_prev, cm_prev) + m = mult(tm_matrix, cm_matrix) + orientation = orient(m) + delta_x = m[4] - m_prev[4] + delta_y = m[5] - m_prev[5] + # Table 108 of the 1.7 reference ("Text positioning operators") + scale_prev_x = math.sqrt(tm_prev[0]**2 + tm_prev[1]**2) + scale_prev_y = math.sqrt(tm_prev[2]**2 + tm_prev[3]**2) + scale_y = math.sqrt(tm_matrix[2]**2 + tm_matrix[3]**2) + cm_prev = m + + if orientation not in orientations: + raise OrientationNotFoundError + if orientation in (0, 180): + moved_height: float = delta_y + moved_width: float = delta_x + elif orientation in (90, 270): + moved_height = delta_x + moved_width = delta_y + try: + if abs(moved_height) > 0.8 * min(str_height * scale_prev_y, font_size * scale_y): + if (output + text)[-1] != "\n": + output += text + "\n" + if visitor_text is not None: + visitor_text( + text + "\n", + memo_cm, + memo_tm, + font_resource, + font_size, + ) + text = "" + elif ( + (moved_width >= (spacewidth + str_widths) * scale_prev_x) + and (output + text)[-1] != " " + ): + text += " " + except Exception: + pass + tm_prev = tm_matrix.copy() + cm_prev = cm_matrix.copy() + return text, output, cm_prev, tm_prev + + +def get_text_operands( + operands: list[Union[str, TextStringObject]], + cm_matrix: list[float], + tm_matrix: list[float], + font: Font, + orientations: tuple[int, ...] +) -> tuple[str, bool]: + t: str = "" + is_str_operands = False + m = mult(tm_matrix, cm_matrix) + orientation = orient(m) + if orientation in orientations and len(operands) > 0: + if isinstance(operands[0], str): + t = operands[0] + is_str_operands = True + else: + t = "" + tt: bytes = ( + encode_pdfdocencoding(operands[0]) + if isinstance(operands[0], str) + else operands[0] + ) + if isinstance(font.encoding, str): + try: + t = tt.decode(font.encoding, "surrogatepass") # apply str encoding + except Exception: + # the data does not match the expectation, + # we use the alternative ; + # text extraction may not be good + t = tt.decode( + "utf-16-be" if font.encoding == "charmap" else "charmap", + "surrogatepass", + ) # apply str encoding + else: # apply dict encoding + t = "".join( + [font.encoding[x] if x in font.encoding else bytes((x,)).decode() for x in tt] + ) + return (t, is_str_operands) + + +def get_display_str( + text: str, + cm_matrix: list[float], + tm_matrix: list[float], + font_resource: Optional[DictionaryObject], + font: Font, + text_operands: str, + font_size: float, + rtl_dir: bool, + visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]] +) -> tuple[str, bool, float]: + # "\u0590 - \u08FF \uFB50 - \uFDFF" + widths: float = 0.0 + for raw_character in text_operands: + widths += font.space_width if raw_character == font.space_char else font.get_text_width(raw_character) + x = font.character_map.get(raw_character, raw_character) + # Test whether x is a sequence of bytes; ex: habibi.pdf + if len(x) == 1: + if ( + # Cases where the current inserting order is kept + is_char_neutral(x, CUSTOM_RTL_SPECIAL_CHARS) + ): + text = x + text if rtl_dir else text + x + elif ( + # Right-to-left characters + is_char_rtl(x, CUSTOM_RTL_MIN, CUSTOM_RTL_MAX) + ): + if not rtl_dir: + rtl_dir = True + if visitor_text is not None: + visitor_text(text, cm_matrix, tm_matrix, font_resource, font_size) + text = "" + text = x + text + else: + # Left-to-right characters + if rtl_dir: + rtl_dir = False + if visitor_text is not None: + visitor_text(text, cm_matrix, tm_matrix, font_resource, font_size) + text = "" + text = text + x + else: + # Treat a sequence of bytes as a neutral character. + text = x + text if rtl_dir else text + x + return text, rtl_dir, widths diff --git a/.venv/lib/python3.13/site-packages/pypdf/_text_extraction/_layout_mode/__init__.py b/.venv/lib/python3.13/site-packages/pypdf/_text_extraction/_layout_mode/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d3151600e9bc1029a6d85c2bc9e53e9e36fd07df --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/_text_extraction/_layout_mode/__init__.py @@ -0,0 +1,16 @@ +"""Layout mode text extraction extension for pypdf""" +from ..._font import Font +from ._fixed_width_page import ( + fixed_char_width, + fixed_width_page, + text_show_operations, + y_coordinate_groups, +) + +__all__ = [ + "Font", + "fixed_char_width", + "fixed_width_page", + "text_show_operations", + "y_coordinate_groups", +] diff --git a/.venv/lib/python3.13/site-packages/pypdf/_text_extraction/_layout_mode/_fixed_width_page.py b/.venv/lib/python3.13/site-packages/pypdf/_text_extraction/_layout_mode/_fixed_width_page.py new file mode 100644 index 0000000000000000000000000000000000000000..6505f4bb6dcd0f654f51cdd4b86ad11e75f8a93d --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/_text_extraction/_layout_mode/_fixed_width_page.py @@ -0,0 +1,447 @@ +"""Extract PDF text preserving the layout of the source PDF""" + +from collections.abc import Iterator +from itertools import groupby +from math import ceil +from pathlib import Path +from typing import Any, Literal, Optional, TypedDict + +from ..._font import Font +from ..._utils import logger_warning +from .. import LAYOUT_NEW_BT_GROUP_SPACE_WIDTHS +from ._text_state_manager import TextStateManager +from ._text_state_params import TextStateParams + +WHITESPACE_LIMIT = 10_000 +NEWLINE_LIMIT = 1_000 + + +class BTGroup(TypedDict): + """ + Dict describing a line of text rendered within a BT/ET operator pair. + If multiple text show operations render text on the same line, the text + will be combined into a single BTGroup dict. + + Keys: + tx: x coordinate of first character in BTGroup + ty: y coordinate of first character in BTGroup + font_size: nominal font size + font_height: effective font height + text: rendered text + displaced_tx: x coordinate of last character in BTGroup + flip_sort: -1 if page is upside down, else 1 + """ + + tx: float + ty: float + font_size: float + font_height: float + text: str + displaced_tx: float + flip_sort: Literal[-1, 1] + + +def resolve_font(fonts: dict[str, Font], name: str) -> Font: + """ + Resolve a Tf font name to a layout mode Font. + + A content stream may select a font name that is not declared in the page + resources. Fall back to an uninterpretable font so extraction degrades to + the existing incomplete-output path instead of raising KeyError. + + Args: + fonts: font dictionary as returned by PageObject._layout_mode_fonts() + name: font name supplied by a Tf operator + + Returns: + Font: the matching font, or an uninterpretable placeholder font. + + """ + if name in fonts: + return fonts[name] + logger_warning( + "Font %(name)s is not in the page resources.", + name=name, source=__name__ + ) + return Font("Unknown", encoding={}, interpretable=False) + + +def bt_group(tj_op: TextStateParams, rendered_text: str, displaced_tx: float) -> BTGroup: + """ + BTGroup constructed from a TextStateParams instance, rendered text, and + displaced tx value. + + Args: + tj_op (TextStateParams): TextStateParams instance + rendered_text (str): rendered text + displaced_tx (float): x coordinate of last character in BTGroup + + """ + return BTGroup( + tx=tj_op.tx, + ty=tj_op.ty, + font_size=tj_op.font_size, + font_height=tj_op.font_height, + text=rendered_text, + displaced_tx=displaced_tx, + flip_sort=-1 if tj_op.flip_vertical else 1, + ) + + +def recurse_to_target_op( + ops: Iterator[tuple[list[Any], bytes]], + text_state_mgr: TextStateManager, + end_target: Literal[b"Q", b"ET"], + fonts: dict[str, Font], + strip_rotated: bool = True, +) -> tuple[list[BTGroup], list[TextStateParams]]: + """ + Recurse operators between BT/ET and/or q/Q operators managing the transform + stack and capturing text positioning and rendering data. + + Args: + ops: iterator of operators in content stream + text_state_mgr: a TextStateManager instance + end_target: Either b"Q" (ends b"q" op) or b"ET" (ends b"BT" op) + fonts: font dictionary as returned by PageObject._layout_mode_fonts() + + Returns: + tuple: list of BTGroup dicts + list of TextStateParams dataclass instances. + + """ + # 1 entry per line of text rendered within each BT/ET operation. + bt_groups: list[BTGroup] = [] + + # 1 entry per text show operator (Tj/TJ/'/") + tj_ops: list[TextStateParams] = [] + + if end_target == b"Q": + # add new q level. cm's added at this level will be popped at next b'Q' + text_state_mgr.add_q() + + for operands, op in ops: + # The loop is broken by the end target, or exits normally when there are no more ops. + if op == end_target: + if op == b"Q": + text_state_mgr.remove_q() + if op == b"ET": + if not tj_ops: + return bt_groups, tj_ops + _text = "" + bt_idx = 0 # idx of first tj in this bt group + last_displaced_tx = tj_ops[bt_idx].displaced_tx + last_ty = tj_ops[bt_idx].ty + for _idx, _tj in enumerate( + tj_ops + ): # ... build text from new Tj operators + if strip_rotated and _tj.rotated: + continue + if not _tj.font.interpretable: # generates warning + continue + # if the y position of the text is greater than the font height, assume + # the text is on a new line and start a new group + if abs(_tj.ty - last_ty) > _tj.font_height: + if _text.strip(): + bt_groups.append( + bt_group(tj_ops[bt_idx], _text, last_displaced_tx) + ) + bt_idx = _idx + _text = "" + + # if the x position of the text is less than the last x position by + # more than 5 spaces widths, assume the text order should be flipped + # and start a new group + if ( + last_displaced_tx - _tj.tx + > _tj.space_tx * LAYOUT_NEW_BT_GROUP_SPACE_WIDTHS + ): + if _text.strip(): + bt_groups.append( + bt_group(tj_ops[bt_idx], _text, last_displaced_tx) + ) + bt_idx = _idx + last_displaced_tx = _tj.displaced_tx + _text = "" + + # calculate excess x translation based on ending tx of previous Tj. + # multiply by bool (_idx != bt_idx) to ensure spaces aren't double + # applied to the first tj of a BTGroup in fixed_width_page(). + excess_tx = round(_tj.tx - last_displaced_tx, 3) * (_idx != bt_idx) + # space_tx could be 0 if either Tz or font_size was 0 for this _tj. + spaces = int(excess_tx // _tj.space_tx) if _tj.space_tx else 0 + if spaces > WHITESPACE_LIMIT: + logger_warning( + "Limiting excessive whitespace from %(actual)d to %(limit)d characters.", + actual=spaces, limit=WHITESPACE_LIMIT, source=__name__ + ) + spaces = WHITESPACE_LIMIT + new_text = f'{" " * spaces}{_tj.text}' + + last_ty = _tj.ty + _text = f"{_text}{new_text}" + last_displaced_tx = _tj.displaced_tx + if _text: + bt_groups.append(bt_group(tj_ops[bt_idx], _text, last_displaced_tx)) + text_state_mgr.reset_tm() + break + if op == b"q": + bts, tjs = recurse_to_target_op( + ops, text_state_mgr, b"Q", fonts, strip_rotated + ) + bt_groups.extend(bts) + tj_ops.extend(tjs) + elif op == b"cm": + text_state_mgr.add_cm(*operands) + elif op == b"BT": + bts, tjs = recurse_to_target_op( + ops, text_state_mgr, b"ET", fonts, strip_rotated + ) + bt_groups.extend(bts) + tj_ops.extend(tjs) + elif op == b"Tj": + tj_ops.append(text_state_mgr.text_state_params(operands[0])) + elif op == b"TJ": + _tj = text_state_mgr.text_state_params() + for tj_op in operands[0]: + if isinstance(tj_op, bytes): + _tj = text_state_mgr.text_state_params(tj_op) + tj_ops.append(_tj) + else: + text_state_mgr.add_trm(_tj.displacement_matrix(td_offset=tj_op)) + elif op == b"'": + text_state_mgr.reset_trm() + text_state_mgr.add_tm([0, -text_state_mgr.TL]) + tj_ops.append(text_state_mgr.text_state_params(operands[0])) + elif op == b'"': + text_state_mgr.reset_trm() + text_state_mgr.set_state_param(b"Tw", operands[0]) + text_state_mgr.set_state_param(b"Tc", operands[1]) + text_state_mgr.add_tm([0, -text_state_mgr.TL]) + tj_ops.append(text_state_mgr.text_state_params(operands[2])) + elif op in (b"Td", b"Tm", b"TD", b"T*"): + text_state_mgr.reset_trm() + if op == b"Tm": + text_state_mgr.reset_tm() + elif op == b"TD": + text_state_mgr.set_state_param(b"TL", -operands[1]) + elif op == b"T*": + operands = [0, -text_state_mgr.TL] + text_state_mgr.add_tm(operands) + elif op == b"Tf": + text_state_mgr.set_font(resolve_font(fonts, operands[0]), operands[1]) + else: # handle Tc, Tw, Tz, TL, and Ts operators + text_state_mgr.set_state_param(op, operands) + else: + logger_warning( + "Unbalanced target operations, expected %(end_target)r.", + source=__name__, + end_target=end_target, + ) + return bt_groups, tj_ops + + +def y_coordinate_groups( + bt_groups: list[BTGroup], debug_path: Optional[Path] = None +) -> dict[int, list[BTGroup]]: + """ + Group text operations by rendered y coordinate, i.e. the line number. + + Args: + bt_groups: list of dicts as returned by text_show_operations() + debug_path (Path, optional): Path to a directory for saving debug output. + + Returns: + Dict[int, List[BTGroup]]: dict of lists of text rendered by each BT operator + keyed by y coordinate + + """ + ty_groups = { + ty: sorted(grp, key=lambda x: x["tx"]) + for ty, grp in groupby( + bt_groups, key=lambda bt_grp: int(bt_grp["ty"] * bt_grp["flip_sort"]) + ) + } + # combine groups whose y coordinates differ by less than the effective font height + # (accounts for mixed fonts and other minor oddities) + last_ty = next(iter(ty_groups)) + last_txs = {int(_t["tx"]) for _t in ty_groups[last_ty] if _t["text"].strip()} + for ty in list(ty_groups)[1:]: + fsz = min(ty_groups[_y][0]["font_height"] for _y in (ty, last_ty)) + txs = {int(_t["tx"]) for _t in ty_groups[ty] if _t["text"].strip()} + # prevent merge if both groups are rendering in the same x position. + no_text_overlap = not (txs & last_txs) + offset_less_than_font_height = abs(ty - last_ty) < fsz + if no_text_overlap and offset_less_than_font_height: + ty_groups[last_ty] = sorted( + ty_groups.pop(ty) + ty_groups[last_ty], key=lambda x: x["tx"] + ) + last_txs |= txs + else: + last_ty = ty + last_txs = txs + if debug_path: # pragma: no cover + import json # noqa: PLC0415 + + debug_path.joinpath("bt_groups.json").write_text( + json.dumps(ty_groups, indent=2, default=str), "utf-8" + ) + return ty_groups + + +def text_show_operations( + ops: Iterator[tuple[list[Any], bytes]], + fonts: dict[str, Font], + strip_rotated: bool = True, + debug_path: Optional[Path] = None, +) -> list[BTGroup]: + """ + Extract text from BT/ET operator pairs. + + Args: + ops (Iterator[Tuple[List, bytes]]): iterator of operators in content stream + fonts (Dict[str, Font]): font dictionary + strip_rotated: Removes text if rotated w.r.t. to the page. Defaults to True. + debug_path (Path, optional): Path to a directory for saving debug output. + + Returns: + List[BTGroup]: list of dicts of text rendered by each BT operator + + """ + state_mgr = TextStateManager() # transformation stack manager + bt_groups: list[BTGroup] = [] # BT operator dict + tj_ops: list[TextStateParams] = [] # Tj/TJ operator data + for operands, op in ops: + if op in (b"BT", b"q"): + bts, tjs = recurse_to_target_op( + ops, state_mgr, b"ET" if op == b"BT" else b"Q", fonts, strip_rotated + ) + bt_groups.extend(bts) + tj_ops.extend(tjs) + elif op == b"Tf": + state_mgr.set_font(resolve_font(fonts, operands[0]), operands[1]) + else: # set Tc, Tw, Tz, TL, and Ts if required. ignores all other ops + state_mgr.set_state_param(op, operands) + + if any(tj.rotated for tj in tj_ops): + if strip_rotated: + logger_warning( + "Rotated text discovered. Output will be incomplete.", source=__name__ + ) + else: + logger_warning( + "Rotated text discovered. Layout will be degraded.", source=__name__ + ) + if not all(tj.font.interpretable for tj in tj_ops): + logger_warning( + "PDF contains an uninterpretable font. Output will be incomplete.", source=__name__ + ) + + # left align the data, i.e. decrement all tx values by min(tx) + min_x = min((x["tx"] for x in bt_groups), default=0.0) + bt_groups = [ + dict(ogrp, tx=ogrp["tx"] - min_x, displaced_tx=ogrp["displaced_tx"] - min_x) # type: ignore[misc] + for ogrp in sorted( + bt_groups, key=lambda x: (x["ty"] * x["flip_sort"], -x["tx"]), reverse=True + ) + ] + + if debug_path: # pragma: no cover + import json # noqa: PLC0415 + + debug_path.joinpath("bts.json").write_text( + json.dumps(bt_groups, indent=2, default=str), "utf-8" + ) + debug_path.joinpath("tjs.json").write_text( + json.dumps( + tj_ops, indent=2, default=lambda x: getattr(x, "to_dict", str)(x) + ), + "utf-8", + ) + return bt_groups + + +def fixed_char_width(bt_groups: list[BTGroup], scale_weight: float = 1.25) -> float: + """ + Calculate average character width weighted by the length of the rendered + text in each sample for conversion to fixed-width layout. + + Args: + bt_groups (List[BTGroup]): List of dicts of text rendered by each + BT operator + + Returns: + float: fixed character width + + """ + char_widths = [] + for _bt in bt_groups: + _len = len(_bt["text"]) * scale_weight + char_widths.append(((_bt["displaced_tx"] - _bt["tx"]) / _len, _len)) + return sum(_w * _l for _w, _l in char_widths) / sum(_l for _, _l in char_widths) + + +def fixed_width_page( + ty_groups: dict[int, list[BTGroup]], char_width: float, space_vertically: bool, font_height_weight: float +) -> str: + """ + Generate page text from text operations grouped by rendered y coordinate. + + Args: + ty_groups: dict of text show ops as returned by y_coordinate_groups() + char_width: fixed character width + space_vertically: include blank lines inferred from y distance + font height. + font_height_weight: multiplier for font height when calculating blank lines. + + Returns: + str: page text in a fixed width format that closely adheres to the rendered + layout in the source pdf. + + """ + lines: list[str] = [] + last_y_coord = 0 + table = str.maketrans(dict.fromkeys(range(14, 32), " ")) + for y_coord, line_data in ty_groups.items(): + if space_vertically and lines: + fh = line_data[0]["font_height"] + blank_lines = 0 if fh == 0 else ( + int(abs(y_coord - last_y_coord) / (fh * font_height_weight)) - 1 + ) + if blank_lines > NEWLINE_LIMIT: + logger_warning( + "Limiting excessive newlines from %(actual)d to %(limit)d.", + actual=blank_lines, limit=NEWLINE_LIMIT, source=__name__ + ) + blank_lines = NEWLINE_LIMIT + lines.extend([""] * blank_lines) + + line_parts = [] # It uses a list to construct the line, avoiding string concatenation. + current_len = 0 # Track the size with int instead of len(str) overhead. + last_disp = 0.0 + for bt_op in line_data: + tx = bt_op["tx"] + offset = int(tx // char_width) + needed_spaces = offset - current_len + if needed_spaces > 0 and ceil(last_disp) < int(tx): + if needed_spaces > WHITESPACE_LIMIT: + logger_warning( + "Limiting excessive whitespace from %(actual)d to %(limit)d characters.", + actual=needed_spaces, limit=WHITESPACE_LIMIT, source=__name__ + ) + needed_spaces = WHITESPACE_LIMIT + padding = " " * needed_spaces + line_parts.append(padding) + current_len += needed_spaces + + raw_text = bt_op["text"] + text = raw_text.translate(table) + line_parts.append(text) + current_len += len(text) + last_disp = bt_op["displaced_tx"] + + full_line = "".join(line_parts).rstrip() + if full_line.strip() or (space_vertically and lines): + lines.append(full_line) + + last_y_coord = y_coord + + return "\n".join(lines) diff --git a/.venv/lib/python3.13/site-packages/pypdf/_text_extraction/_layout_mode/_text_state_manager.py b/.venv/lib/python3.13/site-packages/pypdf/_text_extraction/_layout_mode/_text_state_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..ed8ffc34ed946dc287188d8808d1d42e6f27af1a --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/_text_extraction/_layout_mode/_text_state_manager.py @@ -0,0 +1,203 @@ +"""manage the PDF transform stack during "layout" mode text extraction""" + +from collections import ChainMap, Counter +from collections import ChainMap as ChainMapType +from collections import Counter as CounterType +from collections.abc import MutableMapping +from typing import Any, Union + +from ..._font import Font +from ...errors import PdfReadError +from .. import mult +from ._text_state_params import TextStateParams + +TextStateManagerChainMapType = ChainMapType[Union[int, str], Union[float, bool]] +TextStateManagerDictType = MutableMapping[Union[int, str], Union[float, bool]] + + +class TextStateManager: + """ + Tracks the current text state including cm/tm/trm transformation matrices. + + Attributes: + transform_stack (ChainMap): ChainMap of cm/tm transformation matrices + q_queue (Counter[int]): Counter of q operators + q_depth (List[int]): list of q operator nesting levels + Tc (float): character spacing + Tw (float): word spacing + Tz (int): horizontal scaling + TL (float): leading + Ts (float): text rise + font (Font): font object + font_size (int | float): font size + + """ + + def __init__(self) -> None: + self.transform_stack: TextStateManagerChainMapType = ChainMap( + self.new_transform() + ) + self.q_queue: CounterType[int] = Counter() + self.q_depth = [0] + self.Tc: float = 0.0 + self.Tw: float = 0.0 + self.Tz: float = 100.0 + self.TL: float = 0.0 + self.Ts: float = 0.0 + self.font_stack: list[tuple[Union[Font, None], Union[int, float]]] = [] + self.font: Union[Font, None] = None + self.font_size: Union[int, float] = 0 + + def set_state_param(self, op: bytes, value: Union[float, list[Any]]) -> None: + """ + Set a text state parameter. Supports Tc, Tz, Tw, TL, and Ts operators. + + Args: + op: operator read from PDF stream as bytes. No action is taken + for unsupported operators (see supported operators above). + value (float | List[Any]): new parameter value. If a list, + value[0] is used. + + """ + if op not in [b"Tc", b"Tz", b"Tw", b"TL", b"Ts"]: + return + self.__setattr__(op.decode(), value[0] if isinstance(value, list) else value) + + def set_font(self, font: Font, size: float) -> None: + """ + Set the current font and font_size. + + Args: + font (Font): a layout mode Font + size (float): font size + + """ + self.font = font + self.font_size = size + + def text_state_params(self, value: Union[bytes, str] = "") -> TextStateParams: + """ + Create a TextStateParams instance to display a text string. Type[bytes] values + will be decoded implicitly. + + Args: + value (str | bytes): text to associate with the captured state. + + Raises: + PdfReadError: if font not set (no Tf operator in incoming pdf content stream) + + Returns: + TextStateParams: current text state parameters + + """ + if not isinstance(self.font, Font): + raise PdfReadError( + "font not set: is PDF missing a Tf operator?" + ) # pragma: no cover + return TextStateParams( + value, + self.font, + self.font_size, + self.Tc, + self.Tw, + self.Tz, + self.TL, + self.Ts, + self.effective_transform, + ) + + @staticmethod + def raw_transform( + _a: float = 1.0, + _b: float = 0.0, + _c: float = 0.0, + _d: float = 1.0, + _e: float = 0.0, + _f: float = 0.0, + ) -> TextStateManagerDictType: + """Only a/b/c/d/e/f matrix params""" + return dict(zip(range(6), map(float, (_a, _b, _c, _d, _e, _f)))) + + @staticmethod + def new_transform( + _a: float = 1.0, + _b: float = 0.0, + _c: float = 0.0, + _d: float = 1.0, + _e: float = 0.0, + _f: float = 0.0, + is_text: bool = False, + is_render: bool = False, + ) -> TextStateManagerDictType: + """Standard a/b/c/d/e/f matrix params + 'is_text' and 'is_render' keys""" + result = TextStateManager.raw_transform(_a, _b, _c, _d, _e, _f) + result.update({"is_text": is_text, "is_render": is_render}) + return result + + def reset_tm(self) -> TextStateManagerChainMapType: + """Clear all transforms from chainmap having is_text==True or is_render==True""" + while ( + self.transform_stack.maps[0]["is_text"] + or self.transform_stack.maps[0]["is_render"] + ): + self.transform_stack = self.transform_stack.parents + return self.transform_stack + + def reset_trm(self) -> TextStateManagerChainMapType: + """Clear all transforms from chainmap having is_render==True""" + while self.transform_stack.maps[0]["is_render"]: + self.transform_stack = self.transform_stack.parents + return self.transform_stack + + def remove_q(self) -> TextStateManagerChainMapType: + """Rewind to stack prior state after closing a 'q' with internal 'cm' ops""" + self.font, self.font_size = self.font_stack.pop(-1) + self.transform_stack = self.reset_tm() + self.transform_stack.maps = self.transform_stack.maps[ + self.q_queue.pop(self.q_depth.pop(), 0) : + ] + return self.transform_stack + + def add_q(self) -> None: + """Add another level to q_queue""" + self.font_stack.append((self.font, self.font_size)) + self.q_depth.append(len(self.q_depth)) + + def add_cm(self, *args: Any) -> TextStateManagerChainMapType: + """Concatenate an additional transform matrix""" + self.transform_stack = self.reset_tm() + self.q_queue.update(self.q_depth[-1:]) + self.transform_stack = self.transform_stack.new_child(self.new_transform(*args)) + return self.transform_stack + + def _complete_matrix(self, operands: list[float]) -> list[float]: + """Adds a, b, c, and d to an "e/f only" operand set (e.g Td)""" + if len(operands) == 2: # this is a Td operator or equivalent + operands = [1.0, 0.0, 0.0, 1.0, *operands] + return operands + + def add_tm(self, operands: list[float]) -> TextStateManagerChainMapType: + """Append a text transform matrix""" + self.transform_stack = self.transform_stack.new_child( + self.new_transform( # type: ignore[misc] + *self._complete_matrix(operands), is_text=True # type: ignore[arg-type] + ) + ) + return self.transform_stack + + def add_trm(self, operands: list[float]) -> TextStateManagerChainMapType: + """Append a text rendering transform matrix""" + self.transform_stack = self.transform_stack.new_child( + self.new_transform( # type: ignore[misc] + *self._complete_matrix(operands), is_text=True, is_render=True # type: ignore[arg-type] + ) + ) + return self.transform_stack + + @property + def effective_transform(self) -> list[float]: + """Current effective transform accounting for cm, tm, and trm transforms""" + eff_transform = [*self.transform_stack.maps[0].values()] + for transform in self.transform_stack.maps[1:]: + eff_transform = mult(eff_transform, transform) # type: ignore[arg-type] # dict has int keys 0-5 + return eff_transform diff --git a/.venv/lib/python3.13/site-packages/pypdf/_text_extraction/_layout_mode/_text_state_params.py b/.venv/lib/python3.13/site-packages/pypdf/_text_extraction/_layout_mode/_text_state_params.py new file mode 100644 index 0000000000000000000000000000000000000000..aec547b52e52bc190970c8855ab6011ad96ab22a --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/_text_extraction/_layout_mode/_text_state_params.py @@ -0,0 +1,161 @@ +"""A dataclass that captures the CTM and Text State for a tj operation""" + +import math +from dataclasses import dataclass, field +from typing import Any, Union + +from ..._font import Font +from .. import mult, orient + + +@dataclass +class TextStateParams: + """ + Text state parameters and operator values for a single text value in a + TJ or Tj PDF operation. + + Attributes: + value (bytes | str): the raw text to be rendered. + font (Font): font object + font_size (int | float): font size + Tc (float): character spacing. Defaults to 0.0. + Tw (float): word spacing. Defaults to 0.0. + Tz (float): horizontal scaling. Defaults to 100.0. + TL (float): leading, vertical displacement between text lines. Defaults to 0.0. + Ts (float): text rise. Used for super/subscripts. Defaults to 0.0. + transform (List[float]): effective transformation matrix. + tx (float): x cood of rendered text, i.e. self.transform[4] + ty (float): y cood of rendered text. May differ from self.transform[5] per self.Ts. + displaced_tx (float): x coord immediately following rendered text + space_tx (float): tx for a space character + font_height (float): effective font height accounting for CTM + flip_vertical (bool): True if y axis has been inverted (i.e. if self.transform[3] < 0.) + rotated (bool): True if the text orientation is rotated with respect to the page. + + """ + + value: Union[bytes, str] + font: Font + font_size: Union[int, float] + Tc: float = 0.0 + Tw: float = 0.0 + Tz: float = 100.0 + TL: float = 0.0 + Ts: float = 0.0 + transform: list[float] = field( + default_factory=lambda: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0] + ) + tx: float = field(default=0.0, init=False) + ty: float = field(default=0.0, init=False) + displaced_tx: float = field(default=0.0, init=False) + space_tx: float = field(default=0.0, init=False) + font_height: float = field(default=0.0, init=False) + flip_vertical: bool = field(default=False, init=False) + rotated: bool = field(default=False, init=False) + text: str = "" + _decoded_value: str = "" + + def __post_init__(self) -> None: + if isinstance(self.value, bytes): + try: + if isinstance(self.font.encoding, str): + self._decoded_value = self.value.decode(self.font.encoding, "surrogatepass") + else: + self._decoded_value = "".join( + self.font.encoding[x] + if x in self.font.encoding + else bytes((x,)).decode() + for x in self.value + ) + except UnicodeDecodeError: + self._decoded_value = self.value.decode("utf-8", "replace") + self.text = "".join( + self.font.character_map.get(x, x) for x in self._decoded_value + ) + else: + self.text = self.value + + if orient(self.transform) in (90, 270): + self.transform = mult( + [1.0, -self.transform[1], -self.transform[2], 1.0, 0.0, 0.0], + self.transform, + ) + self.rotated = True + # self.transform[0] AND self.transform[3] < 0 indicates true rotation. + # If only self.transform[3] < 0, the y coords are simply inverted. + if orient(self.transform) == 180 and self.transform[0] < -1e-6: + self.transform = mult([-1.0, 0.0, 0.0, -1.0, 0.0, 0.0], self.transform) + self.rotated = True + self.displaced_tx = self.displaced_transform()[4] + self.tx = self.transform[4] + self.ty = self.render_transform()[5] + self.space_tx = round(self.word_tx(self.font.space_char), 3) + if self.space_tx < 1e-6: + # if the " " char is assigned 0 width (e.g. for fine tuned spacing + # with TJ int operators a la crazyones.pdf), calculate space_tx as + # a td_offset of -1 * font.space_width where font.space_width is + # the space_width calculated in _font.py. + self.space_tx = round(self.word_tx("", -self.font.space_width), 3) + self.font_height = self.font_size * math.sqrt( + self.transform[1] ** 2 + self.transform[3] ** 2 + ) + # flip_vertical handles PDFs generated by Microsoft Word's "publish" command. + self.flip_vertical = self.transform[3] < -1e-6 # inverts y axis + + def font_size_matrix(self) -> list[float]: + """Font size matrix""" + return [ + self.font_size * (self.Tz / 100.0), + 0.0, + 0.0, + self.font_size, + 0.0, + self.Ts, + ] + + def displaced_transform(self) -> list[float]: + """Effective transform matrix after text has been rendered.""" + return mult(self.displacement_matrix(), self.transform) + + def render_transform(self) -> list[float]: + """Effective transform matrix accounting for font size, Tz, and Ts.""" + return mult(self.font_size_matrix(), self.transform) + + def displacement_matrix( + self, word: Union[bytes, str, None] = None, td_offset: float = 0.0 + ) -> list[float]: + """ + Text displacement matrix + + Args: + word (bytes | str, optional): Defaults to None in which case self.text displacement is + returned. + td_offset (float, optional): translation applied by TD operator. Defaults to 0.0. + + """ + word = word if word is not None else self.value + return [1.0, 0.0, 0.0, 1.0, self.word_tx(word, td_offset), 0.0] + + def word_tx(self, word: Union[bytes, str], td_offset: float = 0.0) -> float: + """Horizontal text displacement for any word according this text state""" + width: float = 0.0 + + if isinstance(word, bytes): + word = self._decoded_value + + for char in word: + if char == self.font.space_char: + width += self.font.space_width + else: + width += self.font.get_text_width(char) + + return ( + (self.font_size * ((width - td_offset) / 1000.0)) + + self.Tc + + word.count(self.font.space_char) * self.Tw + ) * (self.Tz / 100.0) + + @staticmethod + def to_dict(inst: "TextStateParams") -> dict[str, Any]: + """Dataclass to dict for json.dumps serialization""" + return {k: getattr(inst, k) for k in inst.__dataclass_fields__ if k != "font"} diff --git a/.venv/lib/python3.13/site-packages/pypdf/_text_extraction/_text_extractor.py b/.venv/lib/python3.13/site-packages/pypdf/_text_extraction/_text_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..16cc781c143c5ec174a9b45a39c43339671c361a --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/_text_extraction/_text_extractor.py @@ -0,0 +1,358 @@ +# Copyright (c) 2006, Mathieu Fenniak +# Copyright (c) 2007, Ashish Kulkarni +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * The name of the author may not be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +import math +from typing import Any, Callable, Optional, Union + +from .._font import Font, FontDescriptor +from ..generic import DictionaryObject, TextStringObject +from . import OrientationNotFoundError, crlf_space_check, get_display_str, get_text_operands, mult + + +class TextExtraction: + """ + A class to handle PDF text extraction operations. + + This class encapsulates all the state and operations needed for extracting + text from PDF content streams, replacing the nested functions and nonlocal + variables in the original implementation. + """ + + def __init__(self) -> None: + # Text extraction state variables + self.cm_matrix: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0] + self.tm_matrix: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0] + self.cm_stack: list[ + tuple[ + list[float], + Optional[DictionaryObject], + Font, + float, + float, + float, + float, + ] + ] = [] + + # Store the last modified matrices; can be an intermediate position + self.cm_prev: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0] + self.tm_prev: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0] + + # Store the position at the beginning of building the text + self.memo_cm: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0] + self.memo_tm: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0] + + self.char_scale = 1.0 + self.space_scale = 1.0 + self._space_width: float = 500.0 # will be set correctly at first Tf + self._actual_str_size: dict[str, float] = { + "str_widths": 0.0, + "str_height": 0.0, + } # will be set to string length calculation result + self.TL = 0.0 + self.font_size = 12.0 # init just in case of + + # Text extraction variables + self.text: str = "" + self.output: str = "" + self.rtl_dir: bool = False # right-to-left + self.font_resource: Optional[DictionaryObject] = None + self.font = Font( + name = "NotInitialized", + sub_type="Unknown", + encoding="charmap", + font_descriptor=FontDescriptor(), + ) + self.orientations: tuple[int, ...] = (0, 90, 180, 270) + self.visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]] = None + self.font_resources: dict[str, DictionaryObject] = {} + self.fonts: dict[str, Font] = {} + + self.operation_handlers = { + b"BT": self._handle_bt, + b"ET": self._handle_et, + b"q": self._handle_save_graphics_state, + b"Q": self._handle_restore_graphics_state, + b"cm": self._handle_cm, + b"Tz": self._handle_tz, + b"Tw": self._handle_tw, + b"TL": self._handle_tl, + b"Tf": self._handle_tf, + b"Td": self._handle_td, + b"Tm": self._handle_tm, + b"T*": self._handle_t_star, + b"Tj": self._handle_tj_operation, + } + + def initialize_extraction( + self, + orientations: tuple[int, ...] = (0, 90, 180, 270), + visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]] = None, + font_resources: Optional[dict[str, DictionaryObject]] = None, + fonts: Optional[dict[str, Font]] = None + ) -> None: + """Initialize the extractor with extraction parameters.""" + self.orientations = orientations + self.visitor_text = visitor_text + self.font_resources = font_resources or {} + self.fonts = fonts or {} + + # Reset state + self.text = "" + self.output = "" + self.rtl_dir = False + + def compute_str_widths(self, str_widths: float) -> float: + return str_widths / 1000 + + def process_operation(self, operator: bytes, operands: list[Any]) -> None: + if operator in self.operation_handlers: + handler = self.operation_handlers[operator] + str_widths = handler(operands) + + # Post-process operations that affect text positioning + if operator in {b"Td", b"Tm", b"T*", b"Tj"}: + self._post_process_text_operation(str_widths or 0.0) + + def _post_process_text_operation(self, str_widths: float) -> None: + """Handle common post-processing for text positioning operations.""" + try: + self.text, self.output, self.cm_prev, self.tm_prev = crlf_space_check( + self.text, + (self.cm_prev, self.tm_prev), + (self.cm_matrix, self.tm_matrix), + (self.memo_cm, self.memo_tm), + self.font_resource, + self.orientations, + self.output, + self.font_size, + self.visitor_text, + str_widths, + self.compute_str_widths(self.font_size * self._space_width), + self._actual_str_size["str_height"], + ) + if self.text == "": + self.memo_cm = self.cm_matrix.copy() + self.memo_tm = self.tm_matrix.copy() + except OrientationNotFoundError: + pass + + def _handle_tj( + self, + text: str, + operands: list[Union[str, TextStringObject]], + cm_matrix: list[float], + tm_matrix: list[float], + font_resource: Optional[DictionaryObject], + font: Font, + orientations: tuple[int, ...], + font_size: float, + rtl_dir: bool, + visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]], + actual_str_size: dict[str, float], + ) -> tuple[str, bool, dict[str, float]]: + text_operands, is_str_operands = get_text_operands( + operands, cm_matrix, tm_matrix, font, orientations + ) + if is_str_operands: + text += text_operands + font_widths = sum( + [font.space_width if x == font.space_char else font.get_text_width(x) for x in text_operands] + ) + else: + text, rtl_dir, font_widths = get_display_str( + text, + cm_matrix, + tm_matrix, # text matrix + font_resource, + font, + text_operands, + font_size, + rtl_dir, + visitor_text, + ) + actual_str_size["str_widths"] += font_widths * font_size + actual_str_size["str_height"] = font_size + return text, rtl_dir, actual_str_size + + def _flush_text(self) -> None: + """Flush accumulated text to output and call visitor if present.""" + self.output += self.text + if self.visitor_text is not None: + self.visitor_text(self.text, self.memo_cm, self.memo_tm, self.font_resource, self.font_size) + self.text = "" + self.memo_cm = self.cm_matrix.copy() + self.memo_tm = self.tm_matrix.copy() + + # Operation handlers + + def _handle_bt(self, operands: list[Any]) -> None: + """Handle BT (Begin Text) operation - Table 5.4 page 405.""" + self.tm_matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0] + self._flush_text() + + def _handle_et(self, operands: list[Any]) -> None: + """Handle ET (End Text) operation - Table 5.4 page 405.""" + self._flush_text() + + def _handle_save_graphics_state(self, operands: list[Any]) -> None: + """Handle q (Save graphics state) operation - Table 4.7 page 219.""" + self.cm_stack.append( + ( + self.cm_matrix, + self.font_resource, + self.font, + self.font_size, + self.char_scale, + self.space_scale, + self.TL, + ) + ) + + def _handle_restore_graphics_state(self, operands: list[Any]) -> None: + """Handle Q (Restore graphics state) operation - Table 4.7 page 219.""" + try: + ( + self.cm_matrix, + self.font_resource, + self.font, + self.font_size, + self.char_scale, + self.space_scale, + self.TL, + ) = self.cm_stack.pop() + except Exception: + self.cm_matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0] + + def _handle_cm(self, operands: list[Any]) -> None: + """Handle cm (Modify current matrix) operation - Table 4.7 page 219.""" + self.output += self.text + if self.visitor_text is not None: + self.visitor_text(self.text, self.memo_cm, self.memo_tm, self.font_resource, self.font_size) + self.text = "" + try: + self.cm_matrix = mult([float(operand) for operand in operands[:6]], self.cm_matrix) + except Exception: + self.cm_matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0] + self.memo_cm = self.cm_matrix.copy() + self.memo_tm = self.tm_matrix.copy() + + def _handle_tz(self, operands: list[Any]) -> None: + """Handle Tz (Set horizontal text scaling) operation - Table 5.2 page 398.""" + self.char_scale = float(operands[0]) / 100 if operands else 1.0 + + def _handle_tw(self, operands: list[Any]) -> None: + """Handle Tw (Set word spacing) operation - Table 5.2 page 398.""" + self.space_scale = 1.0 + float(operands[0] if operands else 0.0) + + def _handle_tl(self, operands: list[Any]) -> None: + """Handle TL (Set Text Leading) operation - Table 5.2 page 398.""" + scale_x = math.sqrt(self.tm_matrix[0] ** 2 + self.tm_matrix[2] ** 2) + self.TL = float(operands[0] if operands else 0.0) * self.font_size * scale_x + + def _handle_tf(self, operands: list[Any]) -> None: + """Handle Tf (Set font size) operation - Table 5.2 page 398.""" + if self.text != "": + self.output += self.text # .translate(cmap) + if self.visitor_text is not None: + self.visitor_text(self.text, self.memo_cm, self.memo_tm, self.font_resource, self.font_size) + self.text = "" + self.memo_cm = self.cm_matrix.copy() + self.memo_tm = self.tm_matrix.copy() + try: + self.font_resource = self.font_resources[operands[0]] + self.font = self.fonts[operands[0]] + except (KeyError, IndexError): # font not found / operand missing + self.font_resource = None + font_descriptor = FontDescriptor() + self.font = Font( + "Unknown", + space_width=250, + encoding=dict.fromkeys(range(256), "�"), + font_descriptor=font_descriptor, + character_map={}, + ) + + self._space_width = self.font.space_width / 2 # Actually the width of _half_ a space... + try: + self.font_size = float(operands[1]) + except Exception: + pass # keep previous size + + def _handle_td(self, operands: list[Any]) -> float: + """Handle Td (Move text position) operation - Table 5.5 page 406.""" + # A special case is a translating only tm: + # tm = [1, 0, 0, 1, e, f] + # i.e. tm[4] += tx, tm[5] += ty. + tx = float(operands[0]) if len(operands) > 0 else 0.0 + ty = float(operands[1]) if len(operands) > 1 else 0.0 + self.tm_matrix[4] += tx * self.tm_matrix[0] + ty * self.tm_matrix[2] + self.tm_matrix[5] += tx * self.tm_matrix[1] + ty * self.tm_matrix[3] + str_widths = self.compute_str_widths(self._actual_str_size["str_widths"]) + self._actual_str_size["str_widths"] = 0.0 + return str_widths + + def _handle_tm(self, operands: list[Any]) -> float: + """Handle Tm (Set text matrix) operation - Table 5.5 page 406.""" + try: + tm_matrix = [float(operand) for operand in operands[:6]] + except (TypeError, ValueError): + tm_matrix = [] + # Fall back to the identity matrix when Tm carries the wrong number of + # operands, mirroring _handle_cm, so the text matrix stays a six-element + # list and later positioning operators do not read past its end. + self.tm_matrix = tm_matrix if len(tm_matrix) == 6 else [1.0, 0.0, 0.0, 1.0, 0.0, 0.0] + str_widths = self.compute_str_widths(self._actual_str_size["str_widths"]) + self._actual_str_size["str_widths"] = 0.0 + return str_widths + + def _handle_t_star(self, operands: list[Any]) -> float: + """Handle T* (Move to next line) operation - Table 5.5 page 406.""" + self.tm_matrix[4] -= self.TL * self.tm_matrix[2] + self.tm_matrix[5] -= self.TL * self.tm_matrix[3] + str_widths = self.compute_str_widths(self._actual_str_size["str_widths"]) + self._actual_str_size["str_widths"] = 0.0 + return str_widths + + def _handle_tj_operation(self, operands: list[Any]) -> float: + """Handle Tj (Show text) operation - Table 5.5 page 406.""" + self.text, self.rtl_dir, self._actual_str_size = self._handle_tj( + self.text, + operands, + self.cm_matrix, + self.tm_matrix, + self.font_resource, + self.font, + self.orientations, + self.font_size, + self.rtl_dir, + self.visitor_text, + self._actual_str_size, + ) + return 0.0 # str_widths will be handled in post-processing diff --git a/.venv/lib/python3.13/site-packages/pypdf/_utils.py b/.venv/lib/python3.13/site-packages/pypdf/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2343a70365c6f799ec5d942b0dc758753a225cda --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/_utils.py @@ -0,0 +1,673 @@ +# Copyright (c) 2006, Mathieu Fenniak +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * The name of the author may not be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +"""Utility functions for PDF library.""" +__author__ = "Mathieu Fenniak" +__author_email__ = "biziqe@mathieu.fenniak.net" + +import functools +import logging +import re +import sys +import warnings +from dataclasses import dataclass +from datetime import datetime, timezone +from io import DEFAULT_BUFFER_SIZE +from os import SEEK_CUR +from re import Pattern +from typing import ( + IO, + Any, + NoReturn, + Optional, + Union, +) + +if sys.version_info[:2] >= (3, 10): + # Python 3.10+: https://www.python.org/dev/peps/pep-0484/ + from typing import TypeAlias +else: + from typing_extensions import TypeAlias + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +from .errors import ( + STREAM_TRUNCATED_PREMATURELY, + DeprecationError, + LimitReachedError, + PdfStreamError, +) + +TransformationMatrixType: TypeAlias = tuple[ + tuple[float, float, float], tuple[float, float, float], tuple[float, float, float] +] +CompressedTransformationMatrix: TypeAlias = tuple[ + float, float, float, float, float, float +] + +StreamType = IO[Any] +BinaryStreamType = IO[bytes] +StrByteType = Union[str, StreamType] + + +def parse_iso8824_date(text: Optional[str]) -> Optional[datetime]: + orgtext = text + if not text: + return None + if text[0].isdigit(): + text = "D:" + text + if text.endswith(("Z", "z")): + text += "0000" + text = text.replace("z", "+").replace("Z", "+").replace("'", "") + i = max(text.find("+"), text.find("-")) + if i > 0 and i != len(text) - 5: + text += "00" + for f in ( + "D:%Y", + "D:%Y%m", + "D:%Y%m%d", + "D:%Y%m%d%H", + "D:%Y%m%d%H%M", + "D:%Y%m%d%H%M%S", + "D:%Y%m%d%H%M%S%z", + ): + try: + d = datetime.strptime(text, f) # noqa: DTZ007 + except ValueError: + continue + else: + if text.endswith("+0000"): + d = d.replace(tzinfo=timezone.utc) + return d + raise ValueError(f"Can not convert date: {orgtext}") + + +def format_iso8824_date(dt: datetime) -> str: + """ + Convert a datetime object to PDF date string format. + + Converts datetime to the PDF date format D:YYYYMMDDHHmmSSOHH'mm + as specified in the PDF Reference. + + Args: + dt: A datetime object to convert. + + Returns: + A date string in PDF format. + """ + date_str = dt.strftime("D:%Y%m%d%H%M%S") + if dt.tzinfo is not None: + offset = dt.utcoffset() + assert offset is not None + total_seconds = int(offset.total_seconds()) + hours, remainder = divmod(abs(total_seconds), 3600) + minutes = remainder // 60 + sign = "+" if total_seconds >= 0 else "-" + date_str += f"{sign}{hours:02d}'{minutes:02d}'" + return date_str + + +def _get_max_pdf_version_header(header1: str, header2: str) -> str: + versions = ( + "%PDF-1.3", + "%PDF-1.4", + "%PDF-1.5", + "%PDF-1.6", + "%PDF-1.7", + "%PDF-2.0", + ) + pdf_header_indices = [] + if header1 in versions: + pdf_header_indices.append(versions.index(header1)) + if header2 in versions: + pdf_header_indices.append(versions.index(header2)) + if len(pdf_header_indices) == 0: + raise ValueError(f"Neither {header1!r} nor {header2!r} are proper headers") + return versions[max(pdf_header_indices)] + + +WHITESPACES = (b"\x00", b"\t", b"\n", b"\f", b"\r", b" ") +WHITESPACES_AS_BYTES = b"".join(WHITESPACES) +WHITESPACES_AS_REGEXP = b"[" + WHITESPACES_AS_BYTES + b"]" + + +def read_until_whitespace(stream: StreamType, max_bytes: Optional[int] = None) -> bytes: + """ + Read non-whitespace characters and return them. + + Stops upon encountering whitespace or when max_bytes is reached. + + Args: + stream: The data stream from which was read. + max_bytes: The maximum number of bytes returned; by default unlimited. + + Returns: + The data which was read. + + """ + txt = bytearray() + while True: + tok = stream.read(1) + if tok.isspace() or not tok: + break + txt += tok + if len(txt) == max_bytes: + break + return bytes(txt) + + +def read_non_whitespace(stream: BinaryStreamType) -> bytes: + """ + Find and read the next non-whitespace character (ignores whitespace). + + Args: + stream: The data stream from which was read. + + Returns: + The data which was read. + + """ + tok = stream.read(1) + while tok in WHITESPACES: + tok = stream.read(1) + return tok + + +def skip_over_whitespace(stream: StreamType) -> bool: + """ + Similar to read_non_whitespace, but return a boolean if at least one + whitespace character was read. + + Args: + stream: The data stream from which was read. + + Returns: + True if one or more whitespace was skipped, otherwise return False. + + """ + tok = stream.read(1) + cnt = 0 + while tok in WHITESPACES: + cnt += 1 + tok = stream.read(1) + return cnt > 0 + + +def check_if_whitespace_only(value: bytes) -> bool: + """ + Check if the given value consists of whitespace characters only. + + Args: + value: The bytes to check. + + Returns: + True if the value only has whitespace characters, otherwise return False. + + """ + return all(b in WHITESPACES_AS_BYTES for b in value) + + +NEUTRAL_CHARACTER_RANGES = ( + ("\x00", "\x2F"), # ASCII control codes, space, and early punctuation (!"#$%) + ("\x3A", "\x40"), # ASCII operators and punctuation between digits & A (:;<=>?@) + ("\u2000", "\u206F"), # General punctuation + ("\u20A0", "\u21FF"), # Currency symbols, diacritical marks, letter-like symbols, number forms, arrows +) + + +def is_char_neutral(char: str, custom_special_characters: str = "") -> bool: + """Check if a character is part of neutral character ranges""" + if any(start <= char <= end for start, end in NEUTRAL_CHARACTER_RANGES): + return True + + return bool(custom_special_characters and char in custom_special_characters) + + +RTL_CHARACTER_RANGES = ( + ("\u0590", "\u08FF"), # Hebrew, Arabic, Syriac, Thaana, N'Ko, etc. + ("\uFB1D", "\uFDFF"), # Hebrew & Arabic Presentation Forms-A + ("\uFE70", "\uFEFF"), # Arabic Presentation Forms-B +) + + +def is_char_rtl(char: str, custom_rtl_min: str = "", custom_rtl_max: str = "") -> bool: + """Check if a character is part of RTL character ranges""" + if any(start <= char <= end for start, end in RTL_CHARACTER_RANGES): + return True + + return bool(custom_rtl_min and custom_rtl_max and (custom_rtl_min <= char <= custom_rtl_max)) + + +def skip_over_comment(stream: StreamType) -> None: + tok = stream.read(1) + stream.seek(-1, 1) + if tok == b"%": + while tok not in (b"\n", b"\r"): + tok = stream.read(1) + if tok == b"": + raise PdfStreamError("File ended unexpectedly.") + + +def read_until_regex(*, stream: StreamType, regex: Pattern[bytes], length: int = sys.maxsize) -> bytes: + """ + Read until the regular expression pattern matched (ignore the match). + Treats EOF on the underlying stream as the end of the token to be matched. + + Args: + stream: The stream to read from. + regex: The pattern to search for. + length: The (approximated) maximum number of bytes to read before raising an exception. + + Returns: + The read bytes. + + """ + parts: list[bytes] = [] + total_length = 0 + tail = b"" + chunk_size = 16 + while True: + token = stream.read(chunk_size) + if not token: + return b"".join(parts) + token_length = len(token) + if (current_length := total_length + token_length) >= length: + raise LimitReachedError( + f"Read stream length of {current_length} exceeds maximum allowed length of {length}." + ) + + # Search overlap of previous tail + new chunk to catch + # multi-byte regex matches spanning chunk boundaries. + current_buffer = tail + token + search_match = regex.search(current_buffer) + parts.append(token) + if search_match is not None: + overlap = len(tail) + actual_start = total_length - overlap + search_match.start() + stream.seek(actual_start - total_length - token_length, 1) + return b"".join(parts)[:actual_start] + total_length += token_length + + # Fixed overlap: 16 bytes is sufficient for the short + # delimiter patterns used in PDF parsing. + tail = token[-16:] + if chunk_size < 8192: + chunk_size <<= 1 + + +def read_block_backwards(stream: BinaryStreamType, to_read: int) -> bytes: + """ + Given a stream at position X, read a block of size to_read ending at position X. + + This changes the stream's position to the beginning of where the block was + read. + + Args: + stream: + to_read: + + Returns: + The data which was read. + + """ + if stream.tell() < to_read: + raise PdfStreamError("Could not read malformed PDF file") + # Seek to the start of the block we want to read. + stream.seek(-to_read, SEEK_CUR) + read = stream.read(to_read) + # Seek to the start of the block we read after reading it. + stream.seek(-to_read, SEEK_CUR) + return read + + +def read_previous_line(stream: StreamType) -> bytes: + """ + Given a byte stream with current position X, return the previous line. + + All characters between the first CR/LF byte found before X + (or, the start of the file, if no such byte is found) and position X + After this call, the stream will be positioned one byte after the + first non-CRLF character found beyond the first CR/LF byte before X, + or, if no such byte is found, at the beginning of the stream. + + Args: + stream: StreamType: + + Returns: + The data which was read. + + """ + line_content = [] + found_crlf = False + if stream.tell() == 0: + raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY) + while True: + to_read = min(DEFAULT_BUFFER_SIZE, stream.tell()) + if to_read == 0: + break + # Read the block. After this, our stream will be one + # beyond the initial position. + block = read_block_backwards(stream, to_read) + idx = len(block) - 1 + if not found_crlf: + # We haven't found our first CR/LF yet. + # Read off characters until we hit one. + while idx >= 0 and block[idx] not in b"\r\n": + idx -= 1 + if idx >= 0: + found_crlf = True + if found_crlf: + # We found our first CR/LF already (on this block or + # a previous one). + # Our combined line is the remainder of the block + # plus any previously read blocks. + line_content.append(block[idx + 1 :]) + # Continue to read off any more CRLF characters. + while idx >= 0 and block[idx] in b"\r\n": + idx -= 1 + else: + # Didn't find CR/LF yet - add this block to our + # previously read blocks and continue. + line_content.append(block) + if idx >= 0: + # We found the next non-CRLF character. + # Set the stream position correctly, then break + stream.seek(idx + 1, SEEK_CUR) + break + # Join all the blocks in the line (which are in reverse order) + return b"".join(line_content[::-1]) + + +def matrix_multiply( + a: TransformationMatrixType, b: TransformationMatrixType +) -> TransformationMatrixType: + return tuple( # type: ignore[return-value] + tuple(sum(float(i) * float(j) for i, j in zip(row, col)) for col in zip(*b)) + for row in a + ) + + +def mark_location(stream: StreamType) -> None: + """Create text file showing current location in context.""" + # Mainly for debugging + radius = 5000 + stream.seek(-radius, 1) + with open("pypdf_pdfLocation.txt", "wb") as output_fh: + output_fh.write(stream.read(radius)) + output_fh.write(b"HERE") + output_fh.write(stream.read(radius)) + stream.seek(-radius, 1) + + +def deprecate(msg: str, stacklevel: int = 3) -> None: + warnings.warn(msg, DeprecationWarning, stacklevel=stacklevel) + + +def deprecation(msg: str) -> NoReturn: + raise DeprecationError(msg) + + +def deprecate_with_replacement(old_name: str, new_name: str, removed_in: str) -> None: + """Issue a warning that a feature will be removed, but has a replacement.""" + deprecate( + f"{old_name} is deprecated and will be removed in pypdf {removed_in}. Use {new_name} instead.", + 4, + ) + + +def deprecation_with_replacement(old_name: str, new_name: str, removed_in: str) -> NoReturn: + """Raise an exception that a feature was already removed, but has a replacement.""" + deprecation( + f"{old_name} is deprecated and was removed in pypdf {removed_in}. Use {new_name} instead." + ) + + +def deprecate_no_replacement(name: str, removed_in: str) -> None: + """Issue a warning that a feature will be removed without replacement.""" + deprecate(f"{name} is deprecated and will be removed in pypdf {removed_in}.", 4) + + +def deprecation_no_replacement(name: str, removed_in: str) -> NoReturn: + """Raise an exception that a feature was already removed without replacement.""" + deprecation(f"{name} is deprecated and was removed in pypdf {removed_in}.") + + +def logger_error(message: str, *, source: str, **values: Any) -> None: + """ + Use this instead of logger.error directly. + + That allows people to overwrite it more easily. + + See the docs on when to use which: + https://pypdf.readthedocs.io/en/latest/user/suppress-warnings.html + """ + if values: + logging.getLogger(source).error(message, values) + else: + logging.getLogger(source).error(message) + + +def logger_warning(message: str, *, source: str, **values: Any) -> None: + """ + Use this instead of logger.warning directly. + + That allows people to overwrite it more easily. + + ## Exception, warnings.warn, logger_warning + - Exceptions should be used if the user should write code that deals with + an error case, e.g. the PDF being completely broken. + - warnings.warn should be used if the user needs to fix their code, e.g. + DeprecationWarnings + - logger_warning should be used if the user needs to know that an issue was + handled by pypdf, e.g. a non-compliant PDF being read in a way that + pypdf could apply a robustness fix to still read it. This applies mainly + to strict=False mode. + """ + if values: + logging.getLogger(source).warning(message, values) + else: + # Keep parity with logger_error and support plain warning messages. + # Passing an empty dict to logging is not equivalent to passing no args: + # plain messages would fail while being formatted. + logging.getLogger(source).warning(message) + + +def rename_kwargs( + func_name: str, kwargs: dict[str, Any], aliases: dict[str, str], fail: bool = False +) -> None: + """ + Helper function to deprecate arguments. + + Args: + func_name: Name of the function to be deprecated + kwargs: + aliases: + fail: + + """ + for old_term, new_term in aliases.items(): + if old_term in kwargs: + if fail: + raise DeprecationError( + f"{old_term} is deprecated as an argument. Use {new_term} instead" + ) + if new_term in kwargs: + raise TypeError( + f"{func_name} received both {old_term} and {new_term} as " + f"an argument. {old_term} is deprecated. " + f"Use {new_term} instead." + ) + kwargs[new_term] = kwargs.pop(old_term) + warnings.warn( + message=( + f"{old_term} is deprecated as an argument. Use {new_term} instead" + ), + category=DeprecationWarning, + stacklevel=3, + ) + + +def _human_readable_bytes(bytes: int) -> str: + if bytes < 10**3: + return f"{bytes} Byte" + if bytes < 10**6: + return f"{bytes / 10**3:.1f} kB" + if bytes < 10**9: + return f"{bytes / 10**6:.1f} MB" + return f"{bytes / 10**9:.1f} GB" + + +# The following class has been copied from Django: +# https://github.com/django/django/blob/adae619426b6f50046b3daaa744db52989c9d6db/django/utils/functional.py#L51-L65 +# It received some modifications to comply with our own coding standards. +# +# Original license: +# +# --------------------------------------------------------------------------------- +# Copyright (c) Django Software Foundation and individual contributors. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# 3. Neither the name of Django nor the names of its contributors may be used +# to endorse or promote products derived from this software without +# specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# --------------------------------------------------------------------------------- +class classproperty: # noqa: N801 + """ + Decorator that converts a method with a single cls argument into a property + that can be accessed directly from the class. + """ + + def __init__(self, method=None) -> None: # type: ignore # noqa: ANN001 + self.fget = method + + def __get__(self, instance, cls=None) -> Any: # type: ignore # noqa: ANN001 + return self.fget(cls) + + def getter(self, method) -> Self: # type: ignore # noqa: ANN001 + self.fget = method + return self + + +@dataclass +class File: + from .generic import IndirectObject # noqa: PLC0415 + + name: str = "" + """ + Filename as identified within the PDF file. + """ + data: bytes = b"" + """ + Data as bytes. + """ + indirect_reference: Optional[IndirectObject] = None + """ + Reference to the object storing the stream. + """ + + def __str__(self) -> str: + return f"{self.__class__.__name__}(name={self.name}, data: {_human_readable_bytes(len(self.data))})" + + def __repr__(self) -> str: + return self.__str__()[:-1] + f", hash: {hash(self.data)})" + + +@functools.total_ordering +class Version: + COMPONENT_PATTERN = re.compile(r"^(\d+)(.*)$") + + def __init__(self, version_str: str) -> None: + self.version_str = version_str + self.components = self._parse_version(version_str) + + def _parse_version(self, version_str: str) -> list[tuple[int, str]]: + components = version_str.split(".") + parsed_components = [] + for component in components: + match = Version.COMPONENT_PATTERN.match(component) + if not match: + parsed_components.append((0, component)) + continue + integer_prefix = match.group(1) + suffix = match.group(2) + if integer_prefix is None: + integer_prefix = 0 + parsed_components.append((int(integer_prefix), suffix)) + return parsed_components + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Version): + return False + return self.components == other.components + + def __hash__(self) -> int: + # Convert to tuple as lists cannot be hashed. + return hash((self.__class__, tuple(self.components))) + + def __lt__(self, other: Any) -> bool: + if not isinstance(other, Version): + raise ValueError(f"Version cannot be compared against {type(other)}") + + for self_component, other_component in zip(self.components, other.components): + self_value, self_suffix = self_component + other_value, other_suffix = other_component + + if self_value < other_value: + return True + if self_value > other_value: + return False + + if self_suffix < other_suffix: + return True + if self_suffix > other_suffix: + return False + + return len(self.components) < len(other.components) diff --git a/.venv/lib/python3.13/site-packages/pypdf/_version.py b/.venv/lib/python3.13/site-packages/pypdf/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..5d281f4e4137bb91ac455440cf15f08cad6e13a0 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/_version.py @@ -0,0 +1 @@ +__version__ = "6.15.0" diff --git a/.venv/lib/python3.13/site-packages/pypdf/_writer.py b/.venv/lib/python3.13/site-packages/pypdf/_writer.py new file mode 100644 index 0000000000000000000000000000000000000000..6bf6cca2312bdbbb48851c8a1f854ac9b0b8b84a --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/_writer.py @@ -0,0 +1,3422 @@ +# Copyright (c) 2006, Mathieu Fenniak +# Copyright (c) 2007, Ashish Kulkarni +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * The name of the author may not be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +import decimal +import enum +import hashlib +import re +import struct +import sys +import uuid +from collections.abc import Iterable, Mapping +from io import BytesIO, FileIO, IOBase +from itertools import compress +from pathlib import Path +from re import Pattern +from types import TracebackType +from typing import ( + IO, + Any, + Callable, + Optional, + Union, + cast, +) + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +from ._doc_common import DocumentInformation, PdfDocCommon +from ._encryption import EncryptAlgorithm, Encryption +from ._page import PageObject, Transformation +from ._page_labels import nums_clear_range, nums_insert, nums_next +from ._reader import PdfReader +from ._utils import ( + StrByteType, + StreamType, + _get_max_pdf_version_header, + deprecate_with_replacement, + deprecation_no_replacement, + logger_warning, +) +from .constants import AnnotationDictionaryAttributes as AA +from .constants import CatalogAttributes as CA +from .constants import ( + CatalogDictionary, + Core, + GoToActionArguments, + ImageType, + InteractiveFormDictEntries, + OutlineFontFlag, + PageLabelStyle, + PagesAttributes, + TypFitArguments, + UserAccessPermissions, +) +from .constants import FieldDictionaryAttributes as FA +from .constants import PageAttributes as PG +from .constants import TrailerKeys as TK +from .errors import LimitReachedError, PdfReadError, PyPdfError +from .generic import ( + PAGE_FIT, + ArrayObject, + BooleanObject, + ByteStringObject, + ContentStream, + Destination, + DictionaryObject, + EmbeddedFile, + Fit, + FloatObject, + IndirectObject, + NameObject, + NullObject, + NumberObject, + PdfObject, + RectangleObject, + ReferenceLink, + StreamObject, + TextStringObject, + TreeObject, + ViewerPreferences, + create_string_object, + extract_links, + hex_to_rgb, + is_null_or_none, +) +from .generic._appearance_stream import TextStreamAppearance +from .pagerange import PageRange, PageRangeSpec +from .types import ( + AnnotationSubtype, + BorderArrayType, + LayoutType, + OutlineItemType, + OutlineType, + PagemodeType, +) +from .xmp import XmpInformation + +ALL_DOCUMENT_PERMISSIONS = UserAccessPermissions.all() + + +class ObjectDeletionFlag(enum.IntFlag): + NONE = 0 + TEXT = enum.auto() + LINKS = enum.auto() + ATTACHMENTS = enum.auto() + OBJECTS_3D = enum.auto() + ALL_ANNOTATIONS = enum.auto() + XOBJECT_IMAGES = enum.auto() + INLINE_IMAGES = enum.auto() + DRAWING_IMAGES = enum.auto() + IMAGES = XOBJECT_IMAGES | INLINE_IMAGES | DRAWING_IMAGES + + +def _rolling_checksum(stream: BytesIO, blocksize: int = 65536) -> str: + hash = hashlib.md5(usedforsecurity=False) + for block in iter(lambda: stream.read(blocksize), b""): + hash.update(block) + return hash.hexdigest() + + +class PdfWriter(PdfDocCommon): + """ + Write a PDF file out, given pages produced by another class or through + cloning a PDF file during initialization. + + Typically data is added from a :class:`PdfReader`. + + Args: + clone_from: identical to fileobj (for compatibility) + + incremental: If true, loads the document and set the PdfWriter in incremental mode. + + When writing incrementally, the original document is written first and new/modified + content is appended. To be used for signed document/forms to keep signature valid. + + full: If true, loads all the objects (always full if incremental = True). + This parameter may allow loading large PDFs. + + strict: If true, pypdf will raise an exception if a PDF does not follow the specification. + If false, pypdf will try to be forgiving and do something reasonable, but it will log + a warning message. It is a best-effort approach. + + keep_initial_header: If true, the PDF header of the cloned document is kept + when using ``clone_from`` in non-incremental mode. + + """ + + def __init__( + self, + fileobj: Union[PdfReader, StrByteType, Path, None] = "", + clone_from: Union[PdfReader, StrByteType, Path, None] = None, + incremental: bool = False, + full: bool = False, + strict: bool = False, + *, + keep_initial_header: bool = False, + incremental_clone_object_count_limit: Optional[int] = 500_000, + incremental_clone_object_id_limit: Optional[int] = 1_000_000, + ) -> None: + self.strict = strict + """ + If true, pypdf will raise an exception if a PDF does not follow the specification. + If false, pypdf will try to be forgiving and do something reasonable, but it will log + a warning message. It is a best-effort approach. + """ + + self.incremental = incremental or full + """ + Returns if the PdfWriter object has been started in incremental mode. + """ + + self._objects: list[Optional[PdfObject]] = [] + """ + The indirect objects in the PDF. + For the incremental case, it will be filled with None + in clone_reader_document_root. + """ + + self._original_hash: list[int] = [] + """ + List of hashes after import; used to identify changes. + """ + + self._idnum_hash: dict[bytes, tuple[IndirectObject, list[IndirectObject]]] = {} + """ + Maps hash values of indirect objects to the list of IndirectObjects. + This is used for compression. + """ + + self._id_translated: dict[int, dict[int, int]] = {} + """List of already translated IDs. + dict[id(pdf)][(idnum, generation)] + """ + + self._info_obj: Optional[PdfObject] + """The PDF files's document information dictionary, + defined by Info in the PDF file's trailer dictionary.""" + + self._ID: Union[ArrayObject, None] = None + """The PDF file identifier, + defined by the ID in the PDF file's trailer dictionary.""" + + self._unresolved_links: list[tuple[ReferenceLink, ReferenceLink]] = [] + "Tracks links in pages added to the writer for resolving later." + self._merged_in_pages: dict[Optional[IndirectObject], Optional[IndirectObject]] = {} + "Tracks pages added to the writer and what page they turned into." + + # Security parameters. + self._incremental_clone_object_count_limit = ( + incremental_clone_object_count_limit + if isinstance(incremental_clone_object_count_limit, int) + else sys.maxsize + ) + self._incremental_clone_object_id_limit = ( + incremental_clone_object_id_limit if isinstance(incremental_clone_object_id_limit, int) else sys.maxsize + ) + + if self.incremental: + if isinstance(fileobj, (str, Path)): + with open(fileobj, "rb") as f: + fileobj = BytesIO(f.read(-1)) + if isinstance(fileobj, BytesIO): + fileobj = PdfReader(fileobj) + if not isinstance(fileobj, PdfReader): + raise PyPdfError("Invalid type for incremental mode") + self._reader = fileobj # prev content is in _reader.stream + self._header = fileobj.pdf_header.encode() + self._readonly = True # TODO: to be analysed + else: + self._header = b"%PDF-1.3" + self._info_obj = self._add_object( + DictionaryObject( + {NameObject("/Producer"): create_string_object("pypdf")} + ) + ) + + def _get_clone_from( + fileobj: Union[PdfReader, str, Path, IO[Any], BytesIO, None], + clone_from: Union[PdfReader, str, Path, IO[Any], BytesIO, None], + ) -> Union[PdfReader, str, Path, IO[Any], BytesIO, None]: + if isinstance(fileobj, (str, Path, IO, BytesIO)) and ( + fileobj == "" or clone_from is not None + ): + return clone_from + cloning = True + if isinstance(fileobj, (str, Path)): + fileobj_path = Path(fileobj) + if not fileobj_path.exists() or fileobj_path.stat().st_size == 0: + cloning = False + elif isinstance(fileobj, (IOBase, BytesIO)): + t = fileobj.tell() + if fileobj.seek(0, 2) == 0: + cloning = False + fileobj.seek(t, 0) + if cloning: + clone_from = fileobj + return clone_from + + clone_from = _get_clone_from(fileobj, clone_from) + # To prevent overwriting + self.temp_fileobj = fileobj + self.fileobj = "" + self._with_as_usage = False + self._cloned = False + # The root of our page tree node + pages = DictionaryObject( + { + NameObject(PagesAttributes.TYPE): NameObject("/Pages"), + NameObject(PagesAttributes.COUNT): NumberObject(0), + NameObject(PagesAttributes.KIDS): ArrayObject(), + } + ) + self.flattened_pages = [] + self._encryption: Optional[Encryption] = None + self._encrypt_entry: Optional[DictionaryObject] = None + + if clone_from is not None: + if not isinstance(clone_from, PdfReader): + clone_from = PdfReader(clone_from) + self.clone_document_from_reader(clone_from) + self._cloned = True + if keep_initial_header and not self.incremental: + self._header = clone_from.pdf_header.encode() + else: + self._pages = self._add_object(pages) + self._root_object = DictionaryObject( + { + NameObject(PagesAttributes.TYPE): NameObject(Core.CATALOG), + NameObject(Core.PAGES): self._pages, + } + ) + self._add_object(self._root_object) + if full and not incremental: + self.incremental = False + if isinstance(self._ID, list): + if isinstance(self._ID[0], TextStringObject): + self._ID[0] = ByteStringObject(self._ID[0].get_original_bytes()) + if isinstance(self._ID[1], TextStringObject): + self._ID[1] = ByteStringObject(self._ID[1].get_original_bytes()) + + # for commonality + @property + def is_encrypted(self) -> bool: + """ + Read-only boolean property showing whether this PDF file is encrypted. + + Note that this property, if true, will remain true even after the + :meth:`decrypt()` method is called. + """ + return False + + @property + def root_object(self) -> DictionaryObject: + """ + Provide direct access to PDF Structure. + + Note: + Recommended only for read access. + + """ + return self._root_object + + @property + def _info(self) -> Optional[DictionaryObject]: + """ + Provide access to "/Info". Standardized with PdfReader. + + Returns: + /Info Dictionary; None if the entry does not exist + + """ + return ( + None + if self._info_obj is None + else cast(DictionaryObject, self._info_obj.get_object()) + ) + + @_info.setter + def _info(self, value: Optional[Union[IndirectObject, DictionaryObject]]) -> None: + if value is None: + try: + self._objects[self._info_obj.indirect_reference.idnum - 1] = None # type: ignore[union-attr] + except (KeyError, AttributeError): + pass + self._info_obj = None + else: + if self._info_obj is None: + self._info_obj = self._add_object(DictionaryObject()) + obj = cast(DictionaryObject, self._info_obj.get_object()) + obj.clear() + obj.update(cast(DictionaryObject, value.get_object())) + + @property + def xmp_metadata(self) -> Optional[XmpInformation]: + """XMP (Extensible Metadata Platform) data.""" + return cast(XmpInformation, self.root_object.xmp_metadata) + + @xmp_metadata.setter + def xmp_metadata(self, value: Union[XmpInformation, bytes, None]) -> None: + """XMP (Extensible Metadata Platform) data.""" + if value is None: + if "/Metadata" in self.root_object: + del self.root_object["/Metadata"] + return + + metadata = self.root_object.get("/Metadata", None) + if not isinstance(metadata, IndirectObject): + if metadata is not None: + del self.root_object["/Metadata"] + metadata_stream = StreamObject() + stream_reference = self._add_object(metadata_stream) + self.root_object[NameObject("/Metadata")] = stream_reference + else: + metadata_stream = cast(StreamObject, metadata.get_object()) + + if isinstance(value, XmpInformation): + bytes_data = value.stream.get_data() + else: + bytes_data = value + metadata_stream.set_data(bytes_data) + + @property + def with_as_usage(self) -> bool: + deprecation_no_replacement("with_as_usage", "5.0") + + @with_as_usage.setter + def with_as_usage(self, value: bool) -> None: + deprecation_no_replacement("with_as_usage", "5.0") + + def __enter__(self) -> Self: + """Store how writer is initialized by 'with'.""" + c: bool = self._cloned + t = self.temp_fileobj + self.__init__() # type: ignore[misc] + self._cloned = c + self._with_as_usage = True + self.fileobj = t # type: ignore[assignment] + return self + + def __exit__( + self, + exc_type: Optional[type[BaseException]], + exc: Optional[BaseException], + traceback: Optional[TracebackType], + ) -> None: + """Write data to the fileobj.""" + if self.fileobj and not self._cloned: + self.write(self.fileobj) + + @property + def pdf_header(self) -> str: + """ + Read/Write property of the PDF header that is written. + + This should be something like ``'%PDF-1.5'``. It is recommended to set + the lowest version that supports all features which are used within the + PDF file. + + Note: `pdf_header` returns a string but accepts bytes or str for writing + """ + return self._header.decode() + + @pdf_header.setter + def pdf_header(self, new_header: Union[str, bytes]) -> None: + if isinstance(new_header, str): + new_header = new_header.encode() + self._header = new_header + + def _add_object(self, obj: PdfObject) -> IndirectObject: + if ( + getattr(obj, "indirect_reference", None) is not None + and obj.indirect_reference.pdf == self # type: ignore[union-attr] + ): + return obj.indirect_reference # type: ignore[return-value] + # check for /Contents in Pages (/Contents in annotations are strings) + if isinstance(obj, DictionaryObject) and isinstance( + obj.get(PG.CONTENTS, None), (ArrayObject, DictionaryObject) + ): + obj[NameObject(PG.CONTENTS)] = self._add_object(obj[PG.CONTENTS]) + self._objects.append(obj) + obj.indirect_reference = IndirectObject(len(self._objects), 0, self) + return obj.indirect_reference + + def get_object( + self, + indirect_reference: Union[int, IndirectObject], + ) -> PdfObject: + if isinstance(indirect_reference, int): + obj = self._objects[indirect_reference - 1] + elif indirect_reference.pdf != self: + raise ValueError("PDF must be self") + else: + obj = self._objects[indirect_reference.idnum - 1] + if obj is None: + raise PdfReadError(f"Object {indirect_reference!r} not found!") + return obj + + def _replace_object( + self, + indirect_reference: Union[int, IndirectObject], + obj: PdfObject, + ) -> PdfObject: + if isinstance(indirect_reference, IndirectObject): + if indirect_reference.pdf != self: + raise ValueError("PDF must be self") + indirect_reference = indirect_reference.idnum + gen = self._objects[indirect_reference - 1].indirect_reference.generation # type: ignore[union-attr] + if ( + getattr(obj, "indirect_reference", None) is not None + and obj.indirect_reference.pdf != self # type: ignore[union-attr] + ): + obj = obj.clone(self) + self._objects[indirect_reference - 1] = obj + obj.indirect_reference = IndirectObject(indirect_reference, gen, self) + + assert isinstance(obj, PdfObject), "mypy" + return obj + + def _add_page( + self, + page: PageObject, + index: int, + excluded_keys: Iterable[str] = (), + ) -> PageObject: + if not isinstance(page, PageObject) or page.get(PagesAttributes.TYPE, None) != Core.PAGE: + raise ValueError("Invalid page object") + assert self.flattened_pages is not None, "mypy" + page_org = page + excluded_keys = list(excluded_keys) + excluded_keys += [PagesAttributes.PARENT, "/StructParents"] + # Acrobat does not accept two indirect references pointing on the same + # page; therefore in order to add multiple copies of the same + # page, we need to create a new dictionary for the page, however the + # objects below (including content) are not duplicated: + try: # delete an already existing page + del self._id_translated[id(page_org.indirect_reference.pdf)][ # type: ignore[union-attr] + page_org.indirect_reference.idnum # type: ignore[union-attr] + ] + except Exception: + pass + + page = cast( + "PageObject", page_org.clone(self, False, excluded_keys).get_object() + ) + if page_org.pdf is not None: + other = page_org.pdf.pdf_header + self.pdf_header = _get_max_pdf_version_header(self.pdf_header, other) + + node, idx = self._get_page_in_node(index) + page[NameObject(PagesAttributes.PARENT)] = node.indirect_reference + + if idx >= 0: + cast(ArrayObject, node[PagesAttributes.KIDS]).insert(idx, page.indirect_reference) + self.flattened_pages.insert(index, page) + else: + cast(ArrayObject, node[PagesAttributes.KIDS]).append(page.indirect_reference) + self.flattened_pages.append(page) + current: Optional[PdfObject] = node + recurse = 0 + while not is_null_or_none(current): + assert current is not None, "mypy" # guarded by is_null_or_none + node_dict = cast(DictionaryObject, current.get_object()) + node_dict[NameObject(PagesAttributes.COUNT)] = NumberObject(cast(int, node_dict[PagesAttributes.COUNT]) + 1) + current = node_dict.get(PagesAttributes.PARENT, None) + recurse += 1 + if recurse > 1000: + raise PyPdfError("Too many recursive calls!") + + if page_org.pdf is not None: + # the page may contain links to other pages, and those other + # pages may or may not already be added. we store the + # information we need, so that we can resolve the references + # later. + self._unresolved_links.extend(extract_links(page, page_org)) + self._merged_in_pages[page_org.indirect_reference] = page.indirect_reference + + return page + + def set_need_appearances_writer(self, state: bool = True) -> None: + """ + Sets the "NeedAppearances" flag in the PDF writer. + + The "NeedAppearances" flag indicates whether the appearance dictionary + for form fields should be automatically generated by the PDF viewer or + if the embedded appearance should be used. + + Args: + state: The actual value of the NeedAppearances flag. + + Returns: + None + + """ + # See §12.7.2 and §7.7.2 for more information: + # https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf + try: + # get the AcroForm tree + if CatalogDictionary.ACRO_FORM not in self._root_object: + self._root_object[ + NameObject(CatalogDictionary.ACRO_FORM) + ] = self._add_object(DictionaryObject()) + + need_appearances = NameObject(InteractiveFormDictEntries.NeedAppearances) + cast(DictionaryObject, self._root_object[CatalogDictionary.ACRO_FORM])[ + need_appearances + ] = BooleanObject(state) + except Exception as exc: # pragma: no cover + logger_warning( + "set_need_appearances_writer(%(state)s) catch : %(exc)s", + source=__name__, + state=state, + exc=exc, + ) + + def create_viewer_preferences(self) -> ViewerPreferences: + o = ViewerPreferences() + self._root_object[ + NameObject(CatalogDictionary.VIEWER_PREFERENCES) + ] = self._add_object(o) + return o + + def add_page( + self, + page: PageObject, + excluded_keys: Iterable[str] = (), + ) -> PageObject: + """ + Add a page to this PDF file. + + Recommended for advanced usage including the adequate excluded_keys. + + The page is usually acquired from a :class:`PdfReader` + instance. + + Args: + page: The page to add to the document. Should be + an instance of :class:`PageObject` + excluded_keys: + + Returns: + The added PageObject. + + """ + assert self.flattened_pages is not None, "mypy" + return self._add_page(page, len(self.flattened_pages), excluded_keys) + + def insert_page( + self, + page: PageObject, + index: int = 0, + excluded_keys: Iterable[str] = (), + ) -> PageObject: + """ + Insert a page in this PDF file. The page is usually acquired from a + :class:`PdfReader` instance. + + Args: + page: The page to add to the document. + index: Position at which the page will be inserted. + excluded_keys: + + Returns: + The added PageObject. + + """ + assert self.flattened_pages is not None, "mypy" + if index < 0: + index += len(self.flattened_pages) + if index < 0: + raise ValueError("Invalid index value") + if index >= len(self.flattened_pages): + return self.add_page(page, excluded_keys) + return self._add_page(page, index, excluded_keys) + + def _get_page_number_by_indirect( + self, indirect_reference: Union[int, NullObject, IndirectObject, None] + ) -> Optional[int]: + """ + Generate _page_id2num. + + Args: + indirect_reference: + + Returns: + The page number or None + + """ + # To provide same function as in PdfReader + if is_null_or_none(indirect_reference): + return None + assert indirect_reference is not None, "mypy" + if isinstance(indirect_reference, int): + indirect_reference = IndirectObject(indirect_reference, 0, self) + obj = indirect_reference.get_object() + if isinstance(obj, PageObject): + return obj.page_number + return None + + def add_blank_page( + self, width: Optional[float] = None, height: Optional[float] = None + ) -> PageObject: + """ + Append a blank page to this PDF file and return it. + + If no page size is specified, use the size of the last page. + + Args: + width: The width of the new page expressed in default user + space units. + height: The height of the new page expressed in default + user space units. + + Returns: + The newly appended page. + + Raises: + PageSizeNotDefinedError: if width and height are not defined + and previous page does not exist. + + """ + page = PageObject.create_blank_page(self, width, height) + return self.add_page(page) + + def insert_blank_page( + self, + width: Optional[Union[float, decimal.Decimal]] = None, + height: Optional[Union[float, decimal.Decimal]] = None, + index: int = 0, + ) -> PageObject: + """ + Insert a blank page to this PDF file and return it. + + If no page size is specified for a dimension, use the size of the last page. + + Args: + width: The width of the new page in default user space units. + height: The height of the new page in default user space units. + index: Position to add the page. + + Returns: + The newly inserted page. + + Raises: + PageSizeNotDefinedError: if width and height are not defined + and previous page does not exist. + IndexError: Index is outside of [-self.get_num_pages(), self.get_num_pages()] + """ + num_pages = self.get_num_pages() + if abs(index) <= num_pages: + # Use the chosen index, but do not exceed the available pages + fixed_index = min(index, num_pages - 1) + mediabox = self.pages[fixed_index].mediabox + if width is None or width <= 0: + width = mediabox.width + if height is None or height <= 0: + height = mediabox.height + else: + raise IndexError(f"Index should be in range [-{num_pages}, {num_pages}]") + + page = PageObject.create_blank_page(self, width, height) + self.insert_page(page, index) + return page + + @property + def open_destination( + self, + ) -> Union[Destination, TextStringObject, ByteStringObject, None]: + return super().open_destination + + @open_destination.setter + def open_destination(self, dest: Union[str, Destination, PageObject, None]) -> None: + if dest is None: + try: + del self._root_object["/OpenAction"] + except KeyError: + pass + elif isinstance(dest, str): + self._root_object[NameObject("/OpenAction")] = TextStringObject(dest) + elif isinstance(dest, Destination): + self._root_object[NameObject("/OpenAction")] = dest.dest_array + elif isinstance(dest, PageObject): + self._root_object[NameObject("/OpenAction")] = Destination( + "Opening", + dest.indirect_reference + if dest.indirect_reference is not None + else NullObject(), + PAGE_FIT, + ).dest_array + + def add_js(self, javascript: str) -> None: + """ + Add JavaScript which will launch upon opening this PDF. + + Args: + javascript: Your JavaScript. + + Example: + This will launch the print window when the PDF is opened. + + >>> from pypdf import PdfWriter + >>> output = PdfWriter() + >>> output.add_js("this.print({bUI:true,bSilent:false,bShrinkToFit:true});") + + """ + # Names / JavaScript preferred to be able to add multiple scripts + if "/Names" not in self._root_object: + self._root_object[NameObject(CA.NAMES)] = DictionaryObject() + names = cast(DictionaryObject, self._root_object[CA.NAMES]) + if "/JavaScript" not in names: + names[NameObject("/JavaScript")] = DictionaryObject( + {NameObject("/Names"): ArrayObject()} + ) + js_list = cast( + ArrayObject, cast(DictionaryObject, names["/JavaScript"])["/Names"] + ) + # We need a name for parameterized JavaScript in the PDF file, + # but it can be anything. + js_list.append(create_string_object(str(uuid.uuid4()))) + + js = DictionaryObject( + { + NameObject(PagesAttributes.TYPE): NameObject("/Action"), + NameObject("/S"): NameObject("/JavaScript"), + NameObject("/JS"): TextStringObject(f"{javascript}"), + } + ) + js_list.append(self._add_object(js)) + + def add_attachment(self, filename: str, data: Union[str, bytes]) -> "EmbeddedFile": + """ + Embed a file inside the PDF. + + Reference: + https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf + Section 7.11.3 + + Args: + filename: The filename to display. + data: The data in the file. + + Returns: + EmbeddedFile instance for the newly created embedded file. + + """ + return EmbeddedFile._create_new(self, filename, data) + + def append_pages_from_reader( + self, + reader: PdfReader, + after_page_append: Optional[Callable[[PageObject], None]] = None, + ) -> None: + """ + Copy pages from reader to writer. Includes an optional callback + parameter which is invoked after pages are appended to the writer. + + ``append`` should be preferred. + + Args: + reader: a PdfReader object from which to copy page + annotations to this writer object. The writer's annots + will then be updated. + after_page_append: + Callback function that is invoked after each page is appended to + the writer. Signature includes a reference to the appended page + (delegates to append_pages_from_reader). The single parameter of + the callback is a reference to the page just appended to the + document. + + """ + reader_num_pages = len(reader.pages) + # Copy pages from reader to writer + for reader_page_number in range(reader_num_pages): + reader_page = reader.pages[reader_page_number] + writer_page = self.add_page(reader_page) + # Trigger callback, pass writer page as parameter + if callable(after_page_append): + after_page_append(writer_page) + + def _merge_content_stream_to_page( + self, + page: PageObject, + new_content_data: bytes, + ) -> None: + """ + Combines existing content stream(s) with new content (as bytes). + + Args: + page: The page to which the new content data will be added. + new_content_data: A binary-encoded new content stream, for + instance the commands to draw an XObject. + """ + # First resolve the existing page content. This always is an IndirectObject: + # PDF Explained by John Whitington + # https://www.oreilly.com/library/view/pdf-explained/9781449321581/ch04.html + if NameObject("/Contents") in page: + existing_content_ref = page[NameObject("/Contents")] + existing_content = existing_content_ref.get_object() + + if isinstance(existing_content, ArrayObject): + # Create a new StreamObject for the new_content_data + new_stream_obj = StreamObject() + new_stream_obj.set_data(new_content_data) + existing_content.append(self._add_object(new_stream_obj)) + page[NameObject("/Contents")] = self._add_object(existing_content) + if isinstance(existing_content, StreamObject): + # Merge new content to existing StreamObject + merged_data = existing_content.get_data() + b"\n" + new_content_data + new_stream = StreamObject() + new_stream.set_data(merged_data) + page[NameObject("/Contents")] = self._add_object(new_stream) + else: + # If no existing content, then we have an empty page. + # Create a new StreamObject in a new /Contents entry. + new_stream = StreamObject() + new_stream.set_data(new_content_data) + page[NameObject("/Contents")] = self._add_object(new_stream) + + def _add_apstream_object( + self, + page: PageObject, + appearance_stream_obj: StreamObject, + object_name: str, + x_offset: float, + y_offset: float, + ) -> None: + """ + Adds an appearance stream to the page content in the form of + an XObject. + + Args: + page: The page to which to add the appearance stream. + appearance_stream_obj: The appearance stream. + object_name: The name of the appearance stream. + x_offset: The horizontal offset for the appearance stream. + y_offset: The vertical offset for the appearance stream. + """ + pg_res = cast(DictionaryObject, page[PG.RESOURCES]) + # Always add the resolved stream object to the writer to get a new IndirectObject. + # This ensures we have a valid IndirectObject managed by *this* writer. + xobject_ref = self._add_object(appearance_stream_obj) + xobject_name = NameObject(f"/Fm_{object_name}")._sanitize() + if "/XObject" not in pg_res: + pg_res[NameObject("/XObject")] = DictionaryObject() + pg_xo_res = cast(DictionaryObject, pg_res["/XObject"]) + if xobject_name not in pg_xo_res: + pg_xo_res[xobject_name] = xobject_ref + else: + logger_warning( + "XObject %(xobject_name)r already added to page resources. This might be an issue.", + source=__name__, + xobject_name=xobject_name, + ) + xobject_cm = Transformation().translate(x_offset, y_offset) + xobject_drawing_commands = f"q\n{xobject_cm._to_cm()}\n{xobject_name} Do\nQ".encode() + self._merge_content_stream_to_page(page, xobject_drawing_commands) + + FFBITS_NUL = FA.FfBits(0) + + def update_page_form_field_values( + self, + page: Union[PageObject, list[PageObject], None], + fields: Mapping[str, Union[str, list[str], tuple[str, str, float]]], + flags: FA.FfBits = FFBITS_NUL, + auto_regenerate: Optional[bool] = True, + flatten: bool = False, + ) -> None: + """ + Update the form field values for a given page from a fields dictionary. + + Copy field texts and values from fields to page. + If the field links to a parent object, add the information to the parent. + + Args: + page: `PageObject` - references **PDF writer's page** where the + annotations and field data will be updated. + `List[Pageobject]` - provides list of pages to be processed. + `None` - all pages. + fields: a Python dictionary of: + + * field names (/T) as keys and text values (/V) as value + * field names (/T) as keys and list of text values (/V) for multiple choice list + * field names (/T) as keys and tuple of: + * text values (/V) + * font id (e.g. /F1, the font id must exist) + * font size (0 for autosize) + + flags: A set of flags from :class:`~pypdf.constants.FieldDictionaryAttributes.FfBits`. + + auto_regenerate: Set/unset the need_appearances flag; + the flag is unchanged if auto_regenerate is None. + + flatten: Whether or not to flatten the annotation. If True, this adds the annotation's + appearance stream to the page contents. Note that this option does not remove the + annotation itself. + + """ + if CatalogDictionary.ACRO_FORM not in self._root_object: + raise PyPdfError("No /AcroForm dictionary in PDF of PdfWriter Object") + acro_form = cast(DictionaryObject, self._root_object[CatalogDictionary.ACRO_FORM]) + if InteractiveFormDictEntries.Fields not in acro_form: + raise PyPdfError("No /Fields dictionary in PDF of PdfWriter Object") + if isinstance(auto_regenerate, bool): + self.set_need_appearances_writer(auto_regenerate) + # Iterate through pages, update field values + if page is None: + page = list(self.pages) + if isinstance(page, list): + for p in page: + if PG.ANNOTS in p: # just to prevent warnings + self.update_page_form_field_values(p, fields, flags, None, flatten=flatten) + return + if PG.ANNOTS not in page: + logger_warning("No fields to update on this page", source=__name__) + return + appearance_stream_obj: Optional[StreamObject] = None + + for annotation in page[PG.ANNOTS]: # type: ignore[attr-defined] + annotation = cast(DictionaryObject, annotation.get_object()) + if annotation.get("/Subtype", "") != "/Widget": + continue + if "/FT" in annotation and "/T" in annotation: + parent_annotation = annotation + else: + parent_annotation = annotation.get( + PG.PARENT, DictionaryObject() + ).get_object() + + for field, value in fields.items(): + rectangle = cast(RectangleObject, annotation[AA.Rect]) + if not ( + self._get_qualified_field_name(parent=parent_annotation) == field + or parent_annotation.get("/T", None) == field + ): + continue + if ( + parent_annotation.get("/FT", None) == "/Ch" + and "/I" in parent_annotation + ): + del parent_annotation["/I"] + if flags: + annotation[NameObject(FA.Ff)] = NumberObject(flags) + # Set the field value + if not (value is None and flatten): # Only change values if given by user and not flattening. + if isinstance(value, list): + lst = ArrayObject(TextStringObject(v) for v in value) + parent_annotation[NameObject(FA.V)] = lst + elif isinstance(value, tuple): + annotation[NameObject(FA.V)] = TextStringObject( + value[0], + ) + else: + parent_annotation[NameObject(FA.V)] = TextStringObject(value) + # Get or create the field's appearance stream object + if parent_annotation.get(FA.FT) == "/Btn": + # Checkbox button (no /FT found in Radio widgets); + # We can find the associated appearance stream object + # within the annotation. + v = NameObject(value) + ap = cast(DictionaryObject, annotation[NameObject(AA.AP)]) + normal_ap = cast(DictionaryObject, ap["/N"]) + if v not in normal_ap: + v = NameObject("/Off") + appearance_stream_obj = normal_ap.get(v) + # Other cases will be updated through the for loop + annotation[NameObject(AA.AS)] = v + annotation[NameObject(FA.V)] = v + elif ( + parent_annotation.get(FA.FT) == "/Tx" + or parent_annotation.get(FA.FT) == "/Ch" + ): + # Textbox; we need to generate the appearance stream object + if isinstance(value, tuple): + appearance_stream_obj = TextStreamAppearance.from_text_annotation( + self, page, flatten, acro_form, parent_annotation, annotation, value[1], value[2] + ) + else: + appearance_stream_obj = TextStreamAppearance.from_text_annotation( + self, page, flatten, acro_form, parent_annotation, annotation + ) + # Add the appearance stream object + if AA.AP not in annotation: + annotation[NameObject(AA.AP)] = DictionaryObject( + {NameObject("/N"): self._add_object(appearance_stream_obj)} + ) + elif "/N" not in (ap:= cast(DictionaryObject, annotation[AA.AP])): + cast(DictionaryObject, annotation[NameObject(AA.AP)])[ + NameObject("/N") + ] = self._add_object(appearance_stream_obj) + else: # [/AP][/N] exists + n = annotation[AA.AP]["/N"].indirect_reference.idnum # type: ignore[index] + self._objects[n - 1] = appearance_stream_obj + appearance_stream_obj.indirect_reference = IndirectObject(n, 0, self) + elif ( + annotation.get(FA.FT) == "/Sig" + ): # deprecated # not implemented yet + logger_warning("Signature forms not implemented yet", source=__name__) + + if appearance_stream_obj and flatten: + self._add_apstream_object(page, appearance_stream_obj, field, rectangle[0], rectangle[1]) + + def reattach_fields( + self, page: Optional[PageObject] = None + ) -> list[DictionaryObject]: + """ + Parse annotations within the page looking for orphan fields and + reattach then into the Fields Structure. + + Args: + page: page to analyze. + If none is provided, all pages will be analyzed. + + Returns: + list of reattached fields. + + """ + lst = [] + if page is None: + for p in self.pages: + lst += self.reattach_fields(p) + return lst + + try: + af = cast(DictionaryObject, self._root_object[CatalogDictionary.ACRO_FORM]) + except KeyError: + af = DictionaryObject() + self._root_object[NameObject(CatalogDictionary.ACRO_FORM)] = af + try: + fields = cast(ArrayObject, af[InteractiveFormDictEntries.Fields]) + except KeyError: + fields = ArrayObject() + af[NameObject(InteractiveFormDictEntries.Fields)] = fields + + if "/Annots" not in page: + return lst + annotations = cast(ArrayObject, page["/Annots"]) + for idx, annotation in enumerate(annotations): + is_indirect = isinstance(annotation, IndirectObject) + annotation = cast(DictionaryObject, annotation.get_object()) + if annotation.get("/Subtype", "") == "/Widget" and "/FT" in annotation: + if ( + "indirect_reference" in annotation.__dict__ + and annotation.indirect_reference in fields + ): + continue + if not is_indirect: + annotations[idx] = self._add_object(annotation) + fields.append(annotation.indirect_reference) + lst.append(annotation) + return lst + + def _collect_incremental_clone_object_ids(self, reader: PdfReader) -> list[int]: + object_ids: set[int] = set() + for xref_entry in reader.xref.values(): + object_ids.update(filter(None, xref_entry)) + object_ids.update(filter(None, reader.xref_objStm)) + + object_count = len(object_ids) + if object_count > self._incremental_clone_object_count_limit: + raise LimitReachedError( + f"Incremental clone object count {object_count} exceeds " + f"maximum allowed count {self._incremental_clone_object_count_limit}." + ) + + max_object_id = max(object_ids, default=0) + if max_object_id > self._incremental_clone_object_id_limit: + raise LimitReachedError( + f"Incremental clone object ID {max_object_id} exceeds " + f"maximum allowed ID {self._incremental_clone_object_id_limit}." + ) + + return sorted(object_ids) + + def clone_reader_document_root(self, reader: PdfReader) -> None: + """ + Copy the reader document root to the writer and all sub-elements, + including pages, threads, outlines,... For partial insertion, ``append`` + should be considered. + + Args: + reader: PdfReader from which the document root should be copied. + + """ + self._info_obj = None + if self.incremental: + object_ids = self._collect_incremental_clone_object_ids(reader) + self._objects = [None] * (object_ids[-1] if object_ids else 0) + for object_id in object_ids: + reader_object = reader.get_object(object_id) + if reader_object is not None: + self._objects[object_id - 1] = reader_object.replicate(self) + else: + self._objects.clear() + self._root_object = reader.root_object.clone(self) + self._pages = self._root_object.raw_get("/Pages") + + trailer_size = cast(int, reader.trailer["/Size"]) + if len(self._objects) > trailer_size: + if self.strict: + raise PdfReadError( + f"Object count {len(self._objects)} exceeds defined trailer size {trailer_size}" + ) + logger_warning( + "Object count %(object_count)d exceeds defined trailer size %(trailer_size)d", + source=__name__, + object_count=len(self._objects), + trailer_size=trailer_size, + ) + + # must be done here before rewriting + if self.incremental: + self._original_hash = [ + (obj.hash_bin() if obj is not None else 0) for obj in self._objects + ] + + try: + self._flatten() + except IndexError: + raise PdfReadError("Got index error while flattening.") + + assert self.flattened_pages is not None + for p in self.flattened_pages: + self._replace_object(cast(IndirectObject, p.indirect_reference).idnum, p) + if not self.incremental: + p[NameObject("/Parent")] = self._pages + if not self.incremental: + cast(DictionaryObject, self._pages.get_object())[ + NameObject("/Kids") + ] = ArrayObject([p.indirect_reference for p in self.flattened_pages]) + + def clone_document_from_reader( + self, + reader: PdfReader, + after_page_append: Optional[Callable[[PageObject], None]] = None, + ) -> None: + """ + Create a copy (clone) of a document from a PDF file reader cloning + section '/Root' and '/Info' and '/ID' of the pdf. + + Args: + reader: PDF file reader instance from which the clone + should be created. + after_page_append: + Callback function that is invoked after each page is appended to + the writer. Signature includes a reference to the appended page + (delegates to append_pages_from_reader). The single parameter of + the callback is a reference to the page just appended to the + document. + + """ + self.clone_reader_document_root(reader) + inf = reader._info + if self.incremental: + if inf is not None: + self._info_obj = cast( + IndirectObject, inf.clone(self).indirect_reference + ) + assert isinstance(self._info, DictionaryObject), "mypy" + self._original_hash[ + self._info_obj.indirect_reference.idnum - 1 + ] = self._info.hash_bin() + elif inf is not None: + self._info_obj = self._add_object( + DictionaryObject(cast(DictionaryObject, inf.get_object())) + ) + # else: _info_obj = None done in clone_reader_document_root() + + try: + self._ID = cast(ArrayObject, reader._ID).clone(self) + except AttributeError: + pass + + if callable(after_page_append): + for page in cast( + ArrayObject, cast(DictionaryObject, self._pages.get_object())["/Kids"] + ): + after_page_append(page.get_object()) + + def _compute_document_identifier(self) -> ByteStringObject: + stream = BytesIO() + self._write_pdf_structure(stream) + stream.seek(0) + return ByteStringObject(_rolling_checksum(stream).encode("utf8")) + + def generate_file_identifiers(self) -> None: + """ + Generate an identifier for the PDF that will be written. + + The only point of this is ensuring uniqueness. Reproducibility is not + required. + When a file is first written, both identifiers shall be set to the same value. + If both identifiers match when a file reference is resolved, it is very + likely that the correct and unchanged file has been found. If only the first + identifier matches, a different version of the correct file has been found. + see §14.4 "File Identifiers". + """ + if self._ID: + id1 = self._ID[0] + id2 = self._compute_document_identifier() + else: + id1 = self._compute_document_identifier() + id2 = id1 + self._ID = ArrayObject((id1, id2)) + + def encrypt( + self, + user_password: str, + owner_password: Optional[str] = None, + use_128bit: bool = True, + permissions_flag: UserAccessPermissions = ALL_DOCUMENT_PERMISSIONS, + *, + algorithm: Optional[str] = None, + ) -> None: + """ + Encrypt this PDF file with the PDF Standard encryption handler. + + Args: + user_password: The password which allows for opening + and reading the PDF file with the restrictions provided. + owner_password: The password which allows for + opening the PDF files without any restrictions. By default, + the owner password is the same as the user password. + use_128bit: flag as to whether to use 128bit + encryption. When false, 40bit encryption will be used. + By default, this flag is on. + permissions_flag: permissions as described in + Table 3.20 of the PDF 1.7 specification. A bit value of 1 means + the permission is granted. + Hence an integer value of -1 will set all flags. + Bit position 3 is for printing, 4 is for modifying content, + 5 and 6 control annotations, 9 for form fields, + 10 for extraction of text and graphics. + algorithm: encrypt algorithm. Values may be one of "RC4-40", "RC4-128", + "AES-128", "AES-256-R5", "AES-256". If it is valid, + `use_128bit` will be ignored. + + """ + if self.incremental: + raise NotImplementedError("Encrypting incremental PDF files is currently not supported.") + + if owner_password is None: + owner_password = user_password + + if algorithm is not None: + try: + alg = getattr(EncryptAlgorithm, algorithm.replace("-", "_")) + except AttributeError: + raise ValueError(f"Algorithm '{algorithm}' NOT supported") + else: + alg = EncryptAlgorithm.RC4_128 + if not use_128bit: + alg = EncryptAlgorithm.RC4_40 + self.generate_file_identifiers() + assert self._ID + self._encryption = Encryption.make(alg, permissions_flag, self._ID[0]) + # in case call `encrypt` again + entry = self._encryption.write_entry(user_password, owner_password, strict=self.strict) + if self._encrypt_entry: + # replace old encrypt_entry + assert self._encrypt_entry.indirect_reference is not None + entry.indirect_reference = self._encrypt_entry.indirect_reference + self._objects[entry.indirect_reference.idnum - 1] = entry + else: + self._add_object(entry) + self._encrypt_entry = entry + + def _resolve_links(self) -> None: + """Patch up links that were added to the document earlier, to + make sure they still point to the same pages. + """ + for (new_link, old_link) in self._unresolved_links: + old_page = old_link.find_referenced_page() + if not old_page: + continue + new_page = self._merged_in_pages.get(old_page) + if new_page is None: + continue + new_link.patch_reference(self, new_page) + + def write_stream(self, stream: StreamType) -> None: + if hasattr(stream, "mode") and "b" not in stream.mode: + logger_warning( + "File <%(stream_name)s> to write to is not in binary mode. " + "It may not be written to correctly.", + source=__name__, + stream_name=stream.name, + ) + self._resolve_links() + + if self.incremental: + self._reader.stream.seek(0) + stream.write(self._reader.stream.read(-1)) + if len(self.list_objects_in_increment()) > 0: + self._write_increment(stream) # writes objs, xref stream and startxref + else: + object_positions, free_objects = self._write_pdf_structure(stream) + xref_location = self._write_xref_table( + stream, object_positions, free_objects + ) + self._write_trailer(stream, xref_location) + + def write(self, stream: Union[Path, StrByteType]) -> tuple[bool, IO[Any]]: + """ + Write the collection of pages added to this object out as a PDF file. + + Args: + stream: An object to write the file to. The object can support + the write method and the tell method, similar to a file object, or + be a file path, just like the fileobj, just named it stream to keep + existing workflow. + + Returns: + A tuple (bool, IO). + + """ + my_file = False + + if stream == "": + raise ValueError(f"Output({stream=}) is empty.") + + if isinstance(stream, (str, Path)): + stream = FileIO(stream, "wb") + my_file = True + + self.write_stream(stream) + + if my_file: + stream.close() + else: + stream.flush() + + return my_file, stream + + def list_objects_in_increment(self) -> list[IndirectObject]: + """ + For analysis or debugging. + Provides the list of new or modified objects that will be written + in the increment. + Deleted objects will not be freed but will become orphans. + + Returns: + List of new or modified IndirectObjects + + """ + original_hash_count = len(self._original_hash) + return [ + cast(IndirectObject, obj).indirect_reference + for i, obj in enumerate(self._objects) + if ( + obj is not None + and ( + i >= original_hash_count + or obj.hash_bin() != self._original_hash[i] + ) + ) + ] + + def _write_increment(self, stream: StreamType) -> None: + object_positions = {} + object_blocks = [] + current_start = -1 + current_stop = -2 + original_hash_count = len(self._original_hash) + for i, obj in enumerate(self._objects): + if obj is not None and ( + i >= original_hash_count + or obj.hash_bin() != self._original_hash[i] + ): + idnum = i + 1 + assert isinstance(obj, PdfObject), "mypy" + # first write new/modified object + object_positions[idnum] = stream.tell() + stream.write(f"{idnum} 0 obj\n".encode()) + """ encryption is not operational + if self._encryption and obj != self._encrypt_entry: + obj = self._encryption.encrypt_object(obj, idnum, 0) + """ + obj.write_to_stream(stream) + stream.write(b"\nendobj\n") + + # prepare xref + if idnum != current_stop: + if current_start > 0: + object_blocks.append( + [current_start, current_stop - current_start] + ) + current_start = idnum + current_stop = idnum + 1 + assert current_start > 0, "for pytest only" + object_blocks.append([current_start, current_stop - current_start]) + # write incremented xref + xref_location = stream.tell() + xr_id = len(self._objects) + 1 + stream.write(f"{xr_id} 0 obj".encode()) + init_data = { + NameObject("/Type"): NameObject("/XRef"), + NameObject("/Size"): NumberObject(xr_id + 1), + NameObject("/Root"): self.root_object.indirect_reference, + NameObject("/Filter"): NameObject("/FlateDecode"), + NameObject("/Index"): ArrayObject( + [NumberObject(_it) for _su in object_blocks for _it in _su] + ), + NameObject("/W"): ArrayObject( + [NumberObject(1), NumberObject(4), NumberObject(1)] + ), + "__streamdata__": b"", + } + if self._info is not None and ( + self._info.indirect_reference.idnum - 1 # type: ignore[union-attr] + >= len(self._original_hash) + or cast(IndirectObject, self._info).hash_bin() # kept for future + != self._original_hash[ + self._info.indirect_reference.idnum - 1 # type: ignore[union-attr] + ] + ): + init_data[NameObject(TK.INFO)] = self._info.indirect_reference + init_data[NameObject(TK.PREV)] = NumberObject(self._reader._startxref) + if self._ID: + init_data[NameObject(TK.ID)] = self._ID + xr = StreamObject.initialize_from_dictionary(init_data) + xr.set_data( + b"".join( + [struct.pack(b">BIB", 1, _pos, 0) for _pos in object_positions.values()] + ) + ) + xr.write_to_stream(stream) + stream.write(f"\nendobj\nstartxref\n{xref_location}\n%%EOF\n".encode()) # eof + + def _write_pdf_structure(self, stream: StreamType) -> tuple[list[int], list[int]]: + object_positions = [] + free_objects = [] + stream.write(self.pdf_header.encode() + b"\n") + stream.write(b"%\xE2\xE3\xCF\xD3\n") + + for idnum, obj in enumerate(self._objects, start=1): + if obj is not None: + object_positions.append(stream.tell()) + stream.write(f"{idnum} 0 obj\n".encode()) + if self._encryption and obj != self._encrypt_entry: + obj = self._encryption.encrypt_object(obj, idnum, 0) + obj.write_to_stream(stream) + stream.write(b"\nendobj\n") + else: + object_positions.append(-1) + free_objects.append(idnum) + free_objects.append(0) # add 0 to loop in accordance with specification + return object_positions, free_objects + + def _write_xref_table( + self, stream: StreamType, object_positions: list[int], free_objects: list[int] + ) -> int: + xref_location = stream.tell() + stream.write(b"xref\n") + stream.write(f"0 {len(self._objects) + 1}\n".encode()) + stream.write(f"{free_objects[0]:0>10} {65535:0>5} f \n".encode()) + free_idx = 1 + for offset in object_positions: + if offset > 0: + stream.write(f"{offset:0>10} {0:0>5} n \n".encode()) + else: + stream.write(f"{free_objects[free_idx]:0>10} {1:0>5} f \n".encode()) + free_idx += 1 + return xref_location + + def _write_trailer(self, stream: StreamType, xref_location: int) -> None: + """ + Write the PDF trailer to the stream. + + To quote the PDF specification: + [The] trailer [gives] the location of the cross-reference table and + of certain special objects within the body of the file. + """ + stream.write(b"trailer\n") + trailer = DictionaryObject( + { + NameObject(TK.SIZE): NumberObject(len(self._objects) + 1), + NameObject(TK.ROOT): self.root_object.indirect_reference, + } + ) + if self._info is not None: + trailer[NameObject(TK.INFO)] = self._info.indirect_reference + if self._ID is not None: + trailer[NameObject(TK.ID)] = self._ID + if self._encrypt_entry: + trailer[NameObject(TK.ENCRYPT)] = self._encrypt_entry.indirect_reference + trailer.write_to_stream(stream) + stream.write(f"\nstartxref\n{xref_location}\n%%EOF\n".encode()) # eof + + @property + def metadata(self) -> Optional[DocumentInformation]: + """ + Retrieve/set the PDF file's document information dictionary, if it exists. + + Args: + value: dict with the entries to be set. if None : remove the /Info entry from the pdf. + + Note that some PDF files use (XMP) metadata streams instead of document + information dictionaries, and these metadata streams will not be + accessed by this function, but by :meth:`~xmp_metadata`. + + """ + return super().metadata + + @metadata.setter + def metadata( + self, + value: Optional[Union[DocumentInformation, DictionaryObject, dict[Any, Any]]], + ) -> None: + if value is None: + self._info = None + else: + if self._info is not None: + self._info.clear() + + self.add_metadata(value) + + def add_metadata(self, infos: dict[str, Any]) -> None: + """ + Add custom metadata to the output. + + Args: + infos: a Python dictionary where each key is a field + and each value is your new metadata. + + """ + args = {} + if isinstance(infos, PdfObject): + infos = cast(DictionaryObject, infos.get_object()) + for key, value in list(infos.items()): + if isinstance(value, PdfObject): + value = value.get_object() + args[NameObject(key)] = create_string_object(str(value)) + if self._info is None: + self._info = DictionaryObject() + self._info.update(args) + + _UNSET = object() + + def compress_identical_objects( + self, + remove_identicals: Any = _UNSET, + remove_orphans: Any = _UNSET, + *, + remove_duplicates: bool = True, + remove_unreferenced: bool = True, + ) -> None: + """ + Parse the PDF file and merge objects that have the same hash. + This will make objects common to multiple pages. + Recommended to be used just before writing output. + + Args: + remove_identicals: Deprecated. + remove_orphans: Deprecated. + remove_duplicates: Remove duplicate objects. + remove_unreferenced: Remove unreferenced objects. + + """ + if remove_identicals != self._UNSET: + deprecate_with_replacement("remove_identicals", "remove_duplicates", "7.0.0") + assert isinstance(remove_identicals, bool) + remove_duplicates = remove_identicals + if remove_orphans != self._UNSET: + deprecate_with_replacement("remove_orphans", "remove_unreferenced", "7.0.0") + assert isinstance(remove_orphans, bool) + remove_unreferenced = remove_orphans + + def replace_in_obj( + obj: PdfObject, crossref: dict[IndirectObject, IndirectObject] + ) -> None: + if isinstance(obj, DictionaryObject): + key_val = obj.items() + elif isinstance(obj, ArrayObject): + key_val = enumerate(obj) # type: ignore[assignment] + else: + return + assert isinstance(obj, (DictionaryObject, ArrayObject)) + for k, v in key_val: + if isinstance(v, IndirectObject): + unreferenced[v.idnum - 1] = False + if v in crossref: + obj[k] = crossref[v] + else: + """The filtering on DictionaryObject and ArrayObject only + will be performed within replace_in_obj""" + replace_in_obj(v, crossref) + + # _idnum_hash: dict[hash] = (1st_ind_obj, [2nd_ind_obj,...]) + self._idnum_hash = {} + unreferenced = [True] * len(self._objects) + # look for similar objects + for idx, obj in enumerate(self._objects): + if is_null_or_none(obj): + continue + assert obj is not None, "mypy" # mypy: TypeGuard of `is_null_or_none` does not help here. + assert isinstance(obj.indirect_reference, IndirectObject) + h = obj.hash_value() + if remove_duplicates and h in self._idnum_hash: + self._idnum_hash[h][1].append(obj.indirect_reference) + self._objects[idx] = None + else: + self._idnum_hash[h] = (obj.indirect_reference, []) + + # generate the dict converting others to 1st + cnv = {v[0]: v[1] for v in self._idnum_hash.values() if len(v[1]) > 0} + cnv_rev: dict[IndirectObject, IndirectObject] = {} + for k, v in cnv.items(): + cnv_rev.update(zip(v, (k,) * len(v))) + + # replace reference to merged objects + for obj in self._objects: + if isinstance(obj, (DictionaryObject, ArrayObject)): + replace_in_obj(obj, cnv_rev) + + if remove_unreferenced: + unreferenced[self.root_object.indirect_reference.idnum - 1] = False # type: ignore[union-attr] + + if not is_null_or_none(self._info): + unreferenced[self._info.indirect_reference.idnum - 1] = False # type: ignore[union-attr] + + try: + unreferenced[self._ID.indirect_reference.idnum - 1] = False # type: ignore[union-attr] + except AttributeError: + pass + + for i in compress(range(len(self._objects)), unreferenced): + self._objects[i] = None + + def get_reference(self, obj: PdfObject) -> IndirectObject: + idnum = self._objects.index(obj) + 1 + ref = IndirectObject(idnum, 0, self) + assert ref.get_object() == obj + return ref + + def get_outline_root(self) -> TreeObject: + if Core.OUTLINES in self._root_object: + # Entries in the catalog dictionary + outline = cast(TreeObject, self._root_object[Core.OUTLINES]) + if not isinstance(outline, TreeObject): + t = TreeObject(outline) + self._replace_object(outline.indirect_reference.idnum, t) + outline = t + idnum = self._objects.index(outline) + 1 + outline_ref = IndirectObject(idnum, 0, self) + assert outline_ref.get_object() == outline + else: + outline = TreeObject() + outline.update({}) + outline_ref = self._add_object(outline) + self._root_object[NameObject(Core.OUTLINES)] = outline_ref + + return outline + + def get_threads_root(self) -> ArrayObject: + """ + The list of threads. + + See §12.4.3 of the PDF 1.7 or PDF 2.0 specification. + + Returns: + An array (possibly empty) of Dictionaries with an ``/F`` key, + and optionally information about the thread in ``/I`` or ``/Metadata`` keys. + + """ + if Core.THREADS in self._root_object: + # Entries in the catalog dictionary + threads = cast(ArrayObject, self._root_object[Core.THREADS]) + else: + threads = ArrayObject() + self._root_object[NameObject(Core.THREADS)] = threads + return threads + + @property + def threads(self) -> ArrayObject: + """ + Read-only property for the list of threads. + + See §12.4.3 of the PDF 1.7 or PDF 2.0 specification. + + Each element is a dictionary with an ``/F`` key, and optionally + information about the thread in ``/I`` or ``/Metadata`` keys. + """ + return self.get_threads_root() + + def add_outline_item_destination( + self, + page_destination: Union[IndirectObject, PageObject, TreeObject], + parent: Union[TreeObject, IndirectObject, None] = None, + before: Union[TreeObject, IndirectObject, None] = None, + is_open: bool = True, + ) -> IndirectObject: + page_destination = cast(PageObject, page_destination.get_object()) + if isinstance(page_destination, PageObject): + return self.add_outline_item_destination( + Destination( + f"page #{page_destination.page_number}", + cast(IndirectObject, page_destination.indirect_reference), + Fit.fit(), + ) + ) + + if parent is None: + parent = self.get_outline_root() + + page_destination[NameObject("/%is_open%")] = BooleanObject(is_open) + parent = cast(TreeObject, parent.get_object()) + page_destination_ref = self._add_object(page_destination) + if before is not None: + before = before.indirect_reference + parent.insert_child( + page_destination_ref, + before, + self, + page_destination.inc_parent_counter_outline + if is_open + else (lambda x, y: 0), # noqa: ARG005 + ) + if "/Count" not in page_destination: + page_destination[NameObject("/Count")] = NumberObject(0) + + return page_destination_ref + + def add_outline_item_dict( + self, + outline_item: OutlineItemType, + parent: Union[TreeObject, IndirectObject, None] = None, + before: Union[TreeObject, IndirectObject, None] = None, + is_open: bool = True, + ) -> IndirectObject: + outline_item_object = TreeObject() + outline_item_object.update(outline_item) + + """code currently unreachable + if "/A" in outline_item: + action = DictionaryObject() + a_dict = cast(DictionaryObject, outline_item["/A"]) + for k, v in list(a_dict.items()): + action[NameObject(str(k))] = v + action_ref = self._add_object(action) + outline_item_object[NameObject("/A")] = action_ref + """ + return self.add_outline_item_destination( + outline_item_object, parent, before, is_open + ) + + def add_outline_item( + self, + title: str, + page_number: Union[PageObject, IndirectObject, int, None], + parent: Union[TreeObject, IndirectObject, None] = None, + before: Union[TreeObject, IndirectObject, None] = None, + color: Optional[Union[tuple[float, float, float], str]] = None, + bold: bool = False, + italic: bool = False, + fit: Fit = PAGE_FIT, + is_open: bool = True, + ) -> IndirectObject: + """ + Add an outline item (commonly referred to as a "Bookmark") to the PDF file. + + Args: + title: Title to use for this outline item. + page_number: Page number this outline item will point to. + parent: A reference to a parent outline item to create nested + outline items. + before: + color: Color of the outline item's font as a red, green, blue tuple + from 0.0 to 1.0 or as a Hex String (#RRGGBB) + bold: Outline item font is bold + italic: Outline item font is italic + fit: The fit of the destination page. + + Returns: + The added outline item as an indirect object. + + """ + page_ref: Union[NullObject, IndirectObject, NumberObject, None] + if isinstance(italic, Fit): # it means that we are on the old params + if fit is not None and page_number is None: + page_number = fit + return self.add_outline_item( + title, page_number, parent, None, before, color, bold, italic, is_open=is_open + ) + if page_number is None: + action_ref = None + else: + if isinstance(page_number, IndirectObject): + page_ref = page_number + elif isinstance(page_number, PageObject): + page_ref = page_number.indirect_reference + elif isinstance(page_number, int): + try: + page_ref = self.pages[page_number].indirect_reference + except IndexError: + page_ref = NumberObject(page_number) + if page_ref is None: + logger_warning( + "can not find reference of page %(page_number)s", + source=__name__, + page_number=page_number, + ) + page_ref = NullObject() + dest = Destination( + NameObject("/" + title + " outline item"), + page_ref, + fit, + ) + + action_ref = self._add_object( + DictionaryObject( + { + NameObject(GoToActionArguments.D): dest.dest_array, + NameObject(GoToActionArguments.S): NameObject("/GoTo"), + } + ) + ) + outline_item = self._add_object( + _create_outline_item(action_ref, title, color, italic, bold) + ) + + if parent is None: + parent = self.get_outline_root() + return self.add_outline_item_destination(outline_item, parent, before, is_open) + + def add_outline(self) -> None: + raise NotImplementedError( + "This method is not yet implemented. Use :meth:`add_outline_item` instead." + ) + + def add_named_destination_array( + self, title: TextStringObject, destination: Union[IndirectObject, ArrayObject] + ) -> None: + named_dest = self.get_named_dest_root() + i = 0 + while i < len(named_dest): + if title < named_dest[i]: + named_dest.insert(i, destination) + named_dest.insert(i, TextStringObject(title)) + return + i += 2 + named_dest.extend([TextStringObject(title), destination]) + return + + def add_named_destination_object( + self, + page_destination: PdfObject, + ) -> IndirectObject: + page_destination_ref = self._add_object(page_destination.dest_array) # type: ignore[attr-defined] + self.add_named_destination_array( + cast("TextStringObject", page_destination["/Title"]), page_destination_ref # type: ignore[index] + ) + + return page_destination_ref + + def add_named_destination( + self, + title: str, + page_number: int, + ) -> IndirectObject: + page_ref = self.get_object(self._pages)[PagesAttributes.KIDS][page_number] # type: ignore[index] + dest = DictionaryObject() + dest.update( + { + NameObject(GoToActionArguments.D): ArrayObject( + [page_ref, NameObject(TypFitArguments.FIT_H), NumberObject(826)] + ), + NameObject(GoToActionArguments.S): NameObject("/GoTo"), + } + ) + + dest_ref = self._add_object(dest) + if not isinstance(title, TextStringObject): + title = TextStringObject(str(title)) + + self.add_named_destination_array(title, dest_ref) + return dest_ref + + def remove_links(self) -> None: + """Remove links and annotations from this output.""" + for page in self.pages: + self.remove_objects_from_page(page, ObjectDeletionFlag.ALL_ANNOTATIONS) + + def remove_annotations( + self, subtypes: Optional[Union[AnnotationSubtype, Iterable[AnnotationSubtype]]] + ) -> None: + """ + Remove annotations by annotation subtype. + + Args: + subtypes: subtype or list of subtypes to be removed. + Examples are: "/Link", "/FileAttachment", "/Sound", + "/Movie", "/Screen", ... + If you want to remove all annotations, use subtypes=None. + + """ + for page in self.pages: + self._remove_annots_from_page(page, subtypes) + + def _remove_annots_from_page( + self, + page: Union[IndirectObject, PageObject, DictionaryObject], + subtypes: Optional[Iterable[str]], + ) -> None: + page = cast(DictionaryObject, page.get_object()) + if PG.ANNOTS in page: + i = 0 + while i < len(cast(ArrayObject, page[PG.ANNOTS])): + an = cast(ArrayObject, page[PG.ANNOTS])[i] + obj = cast(DictionaryObject, an.get_object()) + if subtypes is None or cast(str, obj["/Subtype"]) in subtypes: + if isinstance(an, IndirectObject): + self._objects[an.idnum - 1] = NullObject() # to reduce PDF size + del page[PG.ANNOTS][i] # type:ignore + else: + i += 1 + + def remove_objects_from_page( + self, + page: Union[PageObject, DictionaryObject], + to_delete: Union[ObjectDeletionFlag, Iterable[ObjectDeletionFlag]], + text_filters: Optional[dict[str, Any]] = None + ) -> None: + """ + Remove objects specified by ``to_delete`` from the given page. + + Args: + page: Page object to clean up. + to_delete: Objects to be deleted; can be a ``ObjectDeletionFlag`` + or a list of ObjectDeletionFlag + text_filters: Properties of text to be deleted, if applicable. Optional. + This is a Python dictionary with the following properties: + + * font_ids: List of font resource IDs (such as /F1 or /T1_0) to be deleted. + + """ + if isinstance(to_delete, (list, tuple)): + for to_d in to_delete: + self.remove_objects_from_page(page, to_d) + return None + assert isinstance(to_delete, ObjectDeletionFlag) + + if to_delete & ObjectDeletionFlag.LINKS: + return self._remove_annots_from_page(page, ("/Link",)) + if to_delete & ObjectDeletionFlag.ATTACHMENTS: + return self._remove_annots_from_page( + page, ("/FileAttachment", "/Sound", "/Movie", "/Screen") + ) + if to_delete & ObjectDeletionFlag.OBJECTS_3D: + return self._remove_annots_from_page(page, ("/3D",)) + if to_delete & ObjectDeletionFlag.ALL_ANNOTATIONS: + return self._remove_annots_from_page(page, None) + + jump_operators = [] + if to_delete & ObjectDeletionFlag.DRAWING_IMAGES: + jump_operators = [ + b"w", b"J", b"j", b"M", b"d", b"i", + b"W", b"W*", + b"b", b"b*", b"B", b"B*", b"S", b"s", b"f", b"f*", b"F", b"n", + b"m", b"l", b"c", b"v", b"y", b"h", b"re", + b"sh" + ] + if to_delete & ObjectDeletionFlag.TEXT: + jump_operators = [b"Tj", b"TJ", b"'", b'"'] + + if not isinstance(page, PageObject): + page = PageObject(self, page.indirect_reference) # pragma: no cover + if "/Contents" in page: + content = cast(ContentStream, page.get_contents()) + + images, forms = self._remove_objects_from_page__clean_forms( + elt=page, stack=[], jump_operators=jump_operators, to_delete=to_delete, text_filters=text_filters, + ) + + self._remove_objects_from_page__clean( + content=content, images=images, forms=forms, + jump_operators=jump_operators, to_delete=to_delete, + text_filters=text_filters + ) + page.replace_contents(content) + return [], [] # type: ignore[return-value] + + def _remove_objects_from_page__clean( + self, + content: ContentStream, + images: list[str], + forms: list[str], + jump_operators: list[bytes], + to_delete: ObjectDeletionFlag, + text_filters: Optional[dict[str, Any]] = None, + ) -> None: + font_id = None + font_ids_to_delete = [] + if text_filters and to_delete & ObjectDeletionFlag.TEXT: + font_ids_to_delete = text_filters.get("font_ids", []) + + i = 0 + while i < len(content.operations): + operands, operator = content.operations[i] + if operator == b"Tf": + font_id = operands[0] + if ( + ( + operator == b"INLINE IMAGE" + and (to_delete & ObjectDeletionFlag.INLINE_IMAGES) + ) + or (operator in jump_operators) + or ( + operator == b"Do" + and (to_delete & ObjectDeletionFlag.XOBJECT_IMAGES) + and (operands[0] in images) + ) + ): + if ( + not to_delete & ObjectDeletionFlag.TEXT + or (to_delete & ObjectDeletionFlag.TEXT and not text_filters) + or (to_delete & ObjectDeletionFlag.TEXT and font_id in font_ids_to_delete) + ): + del content.operations[i] + else: + i += 1 + else: + i += 1 + content.get_data() # this ensures ._data is rebuilt from the .operations + + def _remove_objects_from_page__clean_forms( + self, + elt: DictionaryObject, + stack: list[DictionaryObject], + jump_operators: list[bytes], + to_delete: ObjectDeletionFlag, + text_filters: Optional[dict[str, Any]] = None, + ) -> tuple[list[str], list[str]]: + # elt in recursive call is a new ContentStream object, so we have to check the indirect_reference + if (elt in stack) or ( + hasattr(elt, "indirect_reference") and any( + elt.indirect_reference == getattr(x, "indirect_reference", -1) + for x in stack + ) + ): + # to prevent infinite looping + return [], [] # pragma: no cover + try: + d = cast( + dict[Any, Any], + cast(DictionaryObject, elt["/Resources"])["/XObject"], + ) + except KeyError: + d = {} + images = [] + forms = [] + for k, v in d.items(): + o = v.get_object() + try: + content: Any = None + if ( + to_delete & ObjectDeletionFlag.XOBJECT_IMAGES + and o["/Subtype"] == "/Image" + ): + content = NullObject() # to delete the image keeping the entry + images.append(k) + if o["/Subtype"] == "/Form": + forms.append(k) + if isinstance(o, ContentStream): + content = o + else: + content = ContentStream(o, self) + content.update( + { + k1: v1 + for k1, v1 in o.items() + if k1 not in ["/Length", "/Filter", "/DecodeParms"] + } + ) + try: + content.indirect_reference = o.indirect_reference + except AttributeError: # pragma: no cover + pass + stack.append(elt) + + # clean subforms + self._remove_objects_from_page__clean_forms( + elt=content, stack=stack, jump_operators=jump_operators, to_delete=to_delete, + text_filters=text_filters, + ) + if content is not None: + if isinstance(v, IndirectObject): + self._objects[v.idnum - 1] = content + else: + # should only occur in a PDF not respecting PDF spec + # where streams must be indirected. + d[k] = self._add_object(content) # pragma: no cover + except (TypeError, KeyError): + pass + for im in images: + del d[im] # for clean-up + if isinstance(elt, StreamObject): # for /Form + if not isinstance(elt, ContentStream): # pragma: no cover + e = ContentStream(elt, self) + e.update(elt.items()) + elt = e + # clean the content + self._remove_objects_from_page__clean( + content=elt, images=images, forms=forms, jump_operators=jump_operators, + to_delete=to_delete, text_filters=text_filters + ) + return images, forms + + def remove_images( + self, + to_delete: ImageType = ImageType.ALL, + ) -> None: + """ + Remove images from this output. + + Args: + to_delete: The type of images to be deleted + (default = all images types) + + """ + if isinstance(to_delete, bool): + to_delete = ImageType.ALL + + i = ObjectDeletionFlag.NONE + + for image in ("XOBJECT_IMAGES", "INLINE_IMAGES", "DRAWING_IMAGES"): + if to_delete & ImageType[image]: + i |= ObjectDeletionFlag[image] + + for page in self.pages: + self.remove_objects_from_page(page, i) + + def remove_text(self, font_names: Optional[list[str]] = None) -> None: + """ + Remove text from the PDF. + + Args: + font_names: List of font names to remove, such as "Helvetica-Bold". + Optional. If not specified, all text will be removed. + """ + if not font_names: + font_names = [] + + for page in self.pages: + resource_ids_to_remove = [] + + # Content streams reference fonts and other resources with names like "/F1" or "/T1_0" + # Font names need to be converted to resource names/IDs for easier removal + if font_names: + # Recursively loop through page objects to gather font info + def get_font_info( + obj: Any, + font_info: Optional[dict[str, Any]] = None, + key: Optional[str] = None + ) -> dict[str, Any]: + if font_info is None: + font_info = {} + if isinstance(obj, IndirectObject): + obj = obj.get_object() + if isinstance(obj, dict): + if obj.get("/Type") == "/Font": + font_name = obj.get("/BaseFont", "") + # Normalize font names like "/RRXFFV+Palatino-Bold" to "Palatino-Bold" + normalized_font_name = font_name.lstrip("/").split("+")[-1] + if normalized_font_name not in font_info: + font_info[normalized_font_name] = { + "normalized_font_name": normalized_font_name, + "resource_ids": [], + } + if key not in font_info[normalized_font_name]["resource_ids"]: + font_info[normalized_font_name]["resource_ids"].append(key) + for k in obj: + font_info = get_font_info(obj[k], font_info, k) + elif isinstance(obj, (list, ArrayObject)): + for child_obj in obj: + font_info = get_font_info(child_obj, font_info) + return font_info + + # Add relevant resource names for removal + font_info = get_font_info(page.get("/Resources")) + for font_name in font_names: + if font_name in font_info: + resource_ids_to_remove.extend(font_info[font_name]["resource_ids"]) + + text_filters = {} + if font_names: + text_filters["font_ids"] = resource_ids_to_remove + self.remove_objects_from_page(page, ObjectDeletionFlag.TEXT, text_filters=text_filters) + + def add_uri( + self, + page_number: int, + uri: str, + rect: RectangleObject, + border: Optional[ArrayObject] = None, + ) -> None: + """ + Add an URI from a rectangular area to the specified page. + + Args: + page_number: index of the page on which to place the URI action. + uri: URI of resource to link to. + rect: :class:`RectangleObject` or + array of four integers specifying the clickable rectangular area + ``[xLL, yLL, xUR, yUR]``, or string in the form + ``"[ xLL yLL xUR yUR ]"``. + border: if provided, an array describing border-drawing + properties. See the PDF spec for details. No border will be + drawn if this argument is omitted. + + """ + page_link = self.get_object(self._pages)[PagesAttributes.KIDS][page_number] # type: ignore[index] + page_ref = cast(dict[str, Any], self.get_object(page_link)) + + border_arr: BorderArrayType + if border is not None: + border_arr = [NumberObject(n) for n in border[:3]] + if len(border) == 4: + dash_pattern = ArrayObject([NumberObject(n) for n in border[3]]) + border_arr.append(dash_pattern) + else: + border_arr = [NumberObject(2), NumberObject(2), NumberObject(2)] + + if isinstance(rect, str): + rect = NumberObject(rect) + elif isinstance(rect, RectangleObject): + pass + else: + rect = RectangleObject(rect) + + lnk2 = DictionaryObject() + lnk2.update( + { + NameObject("/S"): NameObject("/URI"), + NameObject("/URI"): TextStringObject(uri), + } + ) + lnk = DictionaryObject() + lnk.update( + { + NameObject(AA.Type): NameObject("/Annot"), + NameObject(AA.Subtype): NameObject("/Link"), + NameObject(AA.P): page_link, + NameObject(AA.Rect): rect, + NameObject("/H"): NameObject("/I"), + NameObject(AA.Border): ArrayObject(border_arr), + NameObject("/A"): lnk2, + } + ) + lnk_ref = self._add_object(lnk) + + if PG.ANNOTS in page_ref: + page_ref[PG.ANNOTS].append(lnk_ref) + else: + page_ref[NameObject(PG.ANNOTS)] = ArrayObject([lnk_ref]) + + _valid_layouts = ( + "/NoLayout", + "/SinglePage", + "/OneColumn", + "/TwoColumnLeft", + "/TwoColumnRight", + "/TwoPageLeft", + "/TwoPageRight", + ) + + def _get_page_layout(self) -> Optional[LayoutType]: + try: + return cast(LayoutType, self._root_object["/PageLayout"]) + except KeyError: + return None + + def _set_page_layout(self, layout: Union[NameObject, LayoutType]) -> None: + """ + Set the page layout. + + Args: + layout: The page layout to be used. + + .. list-table:: Valid ``layout`` arguments + :widths: 50 200 + + * - /NoLayout + - Layout explicitly not specified + * - /SinglePage + - Show one page at a time + * - /OneColumn + - Show one column at a time + * - /TwoColumnLeft + - Show pages in two columns, odd-numbered pages on the left + * - /TwoColumnRight + - Show pages in two columns, odd-numbered pages on the right + * - /TwoPageLeft + - Show two pages at a time, odd-numbered pages on the left + * - /TwoPageRight + - Show two pages at a time, odd-numbered pages on the right + + """ + if not isinstance(layout, NameObject): + if layout not in self._valid_layouts: + logger_warning( + "Layout should be one of: %(layouts)s", + source=__name__, + layouts={"", "".join(self._valid_layouts)}, + ) + layout = NameObject(layout) + self._root_object.update({NameObject("/PageLayout"): layout}) + + def set_page_layout(self, layout: LayoutType) -> None: + """ + Set the page layout. + + Args: + layout: The page layout to be used + + .. list-table:: Valid ``layout`` arguments + :widths: 50 200 + + * - /NoLayout + - Layout explicitly not specified + * - /SinglePage + - Show one page at a time + * - /OneColumn + - Show one column at a time + * - /TwoColumnLeft + - Show pages in two columns, odd-numbered pages on the left + * - /TwoColumnRight + - Show pages in two columns, odd-numbered pages on the right + * - /TwoPageLeft + - Show two pages at a time, odd-numbered pages on the left + * - /TwoPageRight + - Show two pages at a time, odd-numbered pages on the right + + """ + self._set_page_layout(layout) + + @property + def page_layout(self) -> Optional[LayoutType]: + """ + Page layout property. + + .. list-table:: Valid ``layout`` values + :widths: 50 200 + + * - /NoLayout + - Layout explicitly not specified + * - /SinglePage + - Show one page at a time + * - /OneColumn + - Show one column at a time + * - /TwoColumnLeft + - Show pages in two columns, odd-numbered pages on the left + * - /TwoColumnRight + - Show pages in two columns, odd-numbered pages on the right + * - /TwoPageLeft + - Show two pages at a time, odd-numbered pages on the left + * - /TwoPageRight + - Show two pages at a time, odd-numbered pages on the right + """ + return self._get_page_layout() + + @page_layout.setter + def page_layout(self, layout: LayoutType) -> None: + self._set_page_layout(layout) + + _valid_modes = ( + "/UseNone", + "/UseOutlines", + "/UseThumbs", + "/FullScreen", + "/UseOC", + "/UseAttachments", + ) + + def _get_page_mode(self) -> Optional[PagemodeType]: + try: + return cast(PagemodeType, self._root_object["/PageMode"]) + except KeyError: + return None + + @property + def page_mode(self) -> Optional[PagemodeType]: + """ + Page mode property. + + .. list-table:: Valid ``mode`` values + :widths: 50 200 + + * - /UseNone + - Do not show outline or thumbnails panels + * - /UseOutlines + - Show outline (aka bookmarks) panel + * - /UseThumbs + - Show page thumbnails panel + * - /FullScreen + - Fullscreen view + * - /UseOC + - Show Optional Content Group (OCG) panel + * - /UseAttachments + - Show attachments panel + """ + return self._get_page_mode() + + @page_mode.setter + def page_mode(self, mode: PagemodeType) -> None: + if isinstance(mode, NameObject): + mode_name: NameObject = mode + else: + if mode not in self._valid_modes: + logger_warning( + "Mode should be one of: %(modes)s", + source=__name__, + modes=", ".join(self._valid_modes), + ) + mode_name = NameObject(mode) + self._root_object.update({NameObject("/PageMode"): mode_name}) + + def add_annotation( + self, + page_number: Union[int, PageObject], + annotation: dict[str, Any], + ) -> DictionaryObject: + """ + Add a single annotation to the page. + The added annotation must be a new annotation. + It cannot be recycled. + + Args: + page_number: PageObject or page index. + annotation: Annotation to be added (created with annotation). + + Returns: + The inserted object. + This can be used for popup creation, for example. + + """ + page = page_number + if isinstance(page, int): + page = self.pages[page] + elif not isinstance(page, PageObject): + raise TypeError("page: invalid type") + + to_add = cast(DictionaryObject, _pdf_objectify(annotation)) + to_add[NameObject("/P")] = page.indirect_reference + + if page.annotations is None: + page[NameObject("/Annots")] = ArrayObject() + assert page.annotations is not None + + # Internal link annotations need the correct object type for the + # destination + if to_add.get("/Subtype") == "/Link" and "/Dest" in to_add: + tmp = cast(dict[Any, Any], to_add[NameObject("/Dest")]) + dest = Destination( + NameObject("/LinkName"), + tmp["target_page_index"], + Fit( + fit_type=tmp["fit"], fit_args=dict(tmp)["fit_args"] + ), # I have no clue why this dict-hack is necessary + ) + to_add[NameObject("/Dest")] = dest.dest_array + + page.annotations.append(self._add_object(to_add)) + + if to_add.get("/Subtype") == "/Popup" and NameObject("/Parent") in to_add: + cast(DictionaryObject, to_add["/Parent"].get_object())[ + NameObject("/Popup") + ] = to_add.indirect_reference + + return to_add + + def clean_page(self, page: Union[PageObject, IndirectObject]) -> PageObject: + """ + Perform some clean up in the page. + Currently: convert NameObject named destination to TextStringObject + (required for names/dests list) + + Args: + page: + + Returns: + The cleaned PageObject + + """ + page = cast("PageObject", page.get_object()) + for a in page.get("/Annots", []): + a_obj = a.get_object() + d = a_obj.get("/Dest", None) + act = a_obj.get("/A", None) + if isinstance(d, NameObject): + a_obj[NameObject("/Dest")] = TextStringObject(d) + elif act is not None: + act = act.get_object() + d = act.get("/D", None) + if isinstance(d, NameObject): + act[NameObject("/D")] = TextStringObject(d) + return page + + def _create_stream( + self, fileobj: Union[Path, StrByteType, PdfReader] + ) -> tuple[IOBase, Optional[Encryption]]: + # If the fileobj parameter is a string, assume it is a path + # and create a file object at that location. If it is a file, + # copy the file's contents into a BytesIO stream object; if + # it is a PdfReader, copy that reader's stream into a + # BytesIO stream. + # If fileobj is none of the above types, it is not modified + encryption_obj = None + stream: IOBase + if isinstance(fileobj, (str, Path)): + with FileIO(fileobj, "rb") as f: + stream = BytesIO(f.read()) + elif isinstance(fileobj, PdfReader): + if fileobj._encryption: + encryption_obj = fileobj._encryption + orig_tell = fileobj.stream.tell() + fileobj.stream.seek(0) + stream = BytesIO(fileobj.stream.read()) + + # reset the stream to its original location + fileobj.stream.seek(orig_tell) + elif hasattr(fileobj, "seek") and hasattr(fileobj, "read"): + fileobj.seek(0) + filecontent = fileobj.read() + stream = BytesIO(filecontent) + else: + raise NotImplementedError( + "Merging requires an object that PdfReader can parse. " + "Typically, that is a Path or a string representing a Path, " + "a file object, or an object implementing .seek and .read. " + "Passing a PdfReader directly works as well." + ) + return stream, encryption_obj + + def append( + self, + fileobj: Union[StrByteType, PdfReader, Path], + outline_item: Union[str, PageRange, tuple[int, int], tuple[int, int, int], list[int], None] = None, + pages: Union[PageRange, tuple[int, int], tuple[int, int, int], list[int], list[PageObject], None] = None, + import_outline: bool = True, + excluded_fields: Optional[Union[list[str], tuple[str, ...]]] = None, + ) -> None: + """ + Identical to the :meth:`merge()` method, but assumes you want to + concatenate all pages onto the end of the file instead of specifying a + position. + + Args: + fileobj: A File Object or an object that supports the standard + read and seek methods similar to a File Object. Could also be a + string representing a path to a PDF file. + outline_item: Optionally, you may specify a string to build an + outline (aka 'bookmark') to identify the beginning of the + included file. + pages: Can be a :class:`PageRange` + or a ``(start, stop[, step])`` tuple + or a list of pages to be processed + to merge only the specified range of pages from the source + document into the output document. + import_outline: You may prevent the source document's + outline (collection of outline items, previously referred to as + 'bookmarks') from being imported by specifying this as ``False``. + excluded_fields: Provide the list of fields/keys to be ignored + if ``/Annots`` is part of the list, the annotation will be ignored + if ``/B`` is part of the list, the articles will be ignored + + """ + if excluded_fields is None: + excluded_fields = () + if isinstance(outline_item, (tuple, list, PageRange)): + if isinstance(pages, bool): + if not isinstance(import_outline, bool): + excluded_fields = import_outline + import_outline = pages + pages = outline_item + self.merge( + None, + fileobj, + None, + pages, + import_outline, + excluded_fields, + ) + else: # if isinstance(outline_item, str): + self.merge( + None, + fileobj, + outline_item, + pages, + import_outline, + excluded_fields, + ) + + def merge( + self, + position: Optional[int], + fileobj: Union[Path, StrByteType, PdfReader], + outline_item: Optional[str] = None, + pages: Optional[Union[PageRangeSpec, list[PageObject]]] = None, + import_outline: bool = True, + excluded_fields: Optional[Union[list[str], tuple[str, ...]]] = (), + ) -> None: + """ + Merge the pages from the given file into the output file at the + specified page number. + + Args: + position: The *page number* to insert this file. File will + be inserted after the given number. + fileobj: A File Object or an object that supports the standard + read and seek methods similar to a File Object. Could also be a + string representing a path to a PDF file. + outline_item: Optionally, you may specify a string to build an outline + (aka 'bookmark') to identify the + beginning of the included file. + pages: can be a :class:`PageRange` + or a ``(start, stop[, step])`` tuple + or a list of pages to be processed + to merge only the specified range of pages from the source + document into the output document. + import_outline: You may prevent the source document's + outline (collection of outline items, previously referred to as + 'bookmarks') from being imported by specifying this as ``False``. + excluded_fields: provide the list of fields/keys to be ignored + if ``/Annots`` is part of the list, the annotation will be ignored + if ``/B`` is part of the list, the articles will be ignored + + Raises: + TypeError: The pages attribute is not configured properly + + """ + if isinstance(fileobj, PdfDocCommon): + reader = fileobj + else: + stream, _encryption_obj = self._create_stream(fileobj) + # Create a new PdfReader instance using the stream + # (either file or BytesIO or StringIO) created above + reader = PdfReader(stream, strict=False) # type: ignore[arg-type] + + if excluded_fields is None: + excluded_fields = () + # Find the range of pages to merge. + if pages is None: + pages = list(range(len(reader.pages))) + elif isinstance(pages, PageRange): + pages = list(range(*pages.indices(len(reader.pages)))) + elif isinstance(pages, list): + pass # keep unchanged + elif isinstance(pages, tuple) and len(pages) <= 3: + pages = list(range(*pages)) + elif not isinstance(pages, tuple): + raise TypeError( + '"pages" must be a tuple of (start, stop[, step]) or a list' + ) + + srcpages = {} + for page in pages: + if isinstance(page, PageObject): + pg = page + else: + pg = reader.pages[page] + assert pg.indirect_reference is not None + if position is None: + # numbers in the exclude list identifies that the exclusion is + # only applicable to 1st level of cloning + srcpages[pg.indirect_reference.idnum] = self.add_page( + pg, [*list(excluded_fields), 1, "/B", 1, "/Annots"] # type: ignore[list-item] + ) + else: + srcpages[pg.indirect_reference.idnum] = self.insert_page( + pg, position, [*list(excluded_fields), 1, "/B", 1, "/Annots"] # type: ignore[list-item] + ) + position += 1 + srcpages[pg.indirect_reference.idnum].original_page = pg + + reader._named_destinations = ( + reader.named_destinations + ) # need for the outline processing below + + arr: Any + + for dest in reader._named_destinations.values(): + self._merge__process_named_dests(dest=dest, reader=reader, srcpages=srcpages) + + outline_item_typ: TreeObject + if outline_item is not None: + outline_item_typ = cast( + "TreeObject", + self.add_outline_item( + TextStringObject(outline_item), + next(iter(srcpages.values())).indirect_reference, + fit=PAGE_FIT, + ).get_object(), + ) + else: + outline_item_typ = self.get_outline_root() + + _ro = reader.root_object + if import_outline and Core.OUTLINES in _ro: + outline = self._get_filtered_outline( + node=_ro.get(Core.OUTLINES, None), pages=srcpages, reader=reader + ) + self._insert_filtered_outline( + outline, outline_item_typ, None + ) # TODO: use before parameter + + if "/Annots" not in excluded_fields: + for pag in srcpages.values(): + lst = self._insert_filtered_annotations( + pag.original_page.get("/Annots", []), pag, srcpages, reader + ) + if len(lst) > 0: + pag[NameObject("/Annots")] = lst + self.clean_page(pag) + + if "/AcroForm" in _ro and not is_null_or_none(_ro["/AcroForm"]): + if "/AcroForm" not in self._root_object: + self._root_object[NameObject("/AcroForm")] = self._add_object( + cast( + DictionaryObject, + reader.root_object["/AcroForm"], + ).clone(self, False, ("/Fields",)) + ) + arr = ArrayObject() + else: + arr = cast( + ArrayObject, + cast(DictionaryObject, self._root_object["/AcroForm"])["/Fields"], + ) + trslat = self._id_translated[id(reader)] + try: + for f in reader.root_object["/AcroForm"]["/Fields"]: # type: ignore[index] + try: + ind = IndirectObject(trslat[f.idnum], 0, self) + if ind not in arr: + arr.append(ind) + except KeyError: + # for trslat[] which mean the field has not be copied + # through the page + pass + except KeyError: # for /Acroform or /Fields are not existing + arr = self._add_object(ArrayObject()) + cast(DictionaryObject, self._root_object["/AcroForm"])[ + NameObject("/Fields") + ] = arr + + if "/B" not in excluded_fields: + self.add_filtered_articles("", srcpages, reader) + + def _merge__process_named_dests(self, dest: Any, reader: PdfDocCommon, srcpages: dict[int, PageObject]) -> None: + arr: Any = dest.dest_array + if "/Names" in self._root_object and dest["/Title"] in cast( + list[Any], + cast( + DictionaryObject, + cast(DictionaryObject, self._root_object["/Names"]).get("/Dests", DictionaryObject()), + ).get("/Names", DictionaryObject()), + ): + # already exists: should not duplicate it + pass + elif dest["/Page"] is None or isinstance(dest["/Page"], NullObject): + pass + elif isinstance(dest["/Page"], int): + # the page reference is a page number normally not a PDF Reference + # page numbers as int are normally accepted only in external goto + try: + p = reader.pages[dest["/Page"]] + except IndexError: + return + assert p.indirect_reference is not None + try: + arr[NumberObject(0)] = NumberObject( + srcpages[p.indirect_reference.idnum].page_number + ) + self.add_named_destination_array(dest["/Title"], arr) + except KeyError: + pass + elif dest["/Page"].indirect_reference.idnum in srcpages: + arr[NumberObject(0)] = srcpages[ + dest["/Page"].indirect_reference.idnum + ].indirect_reference + self.add_named_destination_array(dest["/Title"], arr) + + def _add_articles_thread( + self, + thread: DictionaryObject, + pages: dict[int, PageObject], + reader: PdfReader, + ) -> IndirectObject: + """ + Clone the thread with only the applicable articles. + + Args: + thread: Thread entry from the reader's array of threads + pages: Mapping of object numbers to page objects. + reader: The corresponding reader. + + Returns: + The added thread as an indirect reference + + """ + new_thread = thread.clone( + self, force_duplicate=True, ignore_fields=("/F",) + ) # use of clone to keep link between reader and writer + self.threads.append(new_thread.indirect_reference) + first_article = cast("DictionaryObject", thread["/F"]) + current_article: Optional[DictionaryObject] = first_article + new_article: Optional[DictionaryObject] = None + + visited: set[int] = set() + while current_article is not None: + article_id = id(current_article) + if article_id in visited: + raise LimitReachedError("Detected cyclic article structure.") + visited.add(article_id) + + page = self._get_cloned_page( + cast("PageObject", current_article["/P"]), pages, reader + ) + if page is not None: + if new_article is None: + new_article = cast( + "DictionaryObject", + self._add_object(DictionaryObject()).get_object(), + ) + new_first = new_article + new_thread[NameObject("/F")] = new_article.indirect_reference + else: + new_article2 = cast( + "DictionaryObject", + self._add_object( + DictionaryObject( + {NameObject("/V"): new_article.indirect_reference} + ) + ).get_object(), + ) + new_article[NameObject("/N")] = new_article2.indirect_reference + new_article = new_article2 + new_article[NameObject("/P")] = page + new_article[NameObject("/T")] = new_thread.indirect_reference + new_article[NameObject("/R")] = current_article["/R"] + page_object = cast("PageObject", page.get_object()) + if "/B" not in page_object: + page_object[NameObject("/B")] = ArrayObject() + cast("ArrayObject", page_object["/B"]).append( + new_article.indirect_reference + ) + + current_article = cast("DictionaryObject", current_article["/N"]) + if current_article == first_article: + new_article[NameObject("/N")] = new_first.indirect_reference # type: ignore[index] + new_first[NameObject("/V")] = new_article.indirect_reference # type: ignore[union-attr] + current_article = None + + assert new_thread.indirect_reference is not None + return new_thread.indirect_reference + + def add_filtered_articles( + self, + fltr: Union[ + Pattern[Any], str + ], # thread entry from the reader's array of threads + pages: dict[int, PageObject], + reader: PdfReader, + ) -> None: + """ + Add articles matching the defined criteria. + + Args: + fltr: + pages: + reader: + + """ + if isinstance(fltr, str): + fltr = re.compile(fltr) + elif not isinstance(fltr, Pattern): + fltr = re.compile("") + for p in pages.values(): + pp = p.original_page + for a in pp.get("/B", ()): + a_obj = a.get_object() + if is_null_or_none(a_obj): + continue + thr = a_obj.get("/T") + if thr is None: + continue + thr = thr.get_object() + if thr.indirect_reference.idnum not in self._id_translated[ + id(reader) + ] and fltr.search((thr.get("/I", {})).get("/Title", "")): + self._add_articles_thread(thr, pages, reader) + + def _get_cloned_page( + self, + page: Union[IndirectObject, PageObject, NullObject, None], + pages: dict[int, PageObject], + reader: PdfReader, + ) -> Optional[IndirectObject]: + if isinstance(page, NullObject): + return None + if isinstance(page, DictionaryObject) and page.get("/Type", "") == "/Page": + _i = page.indirect_reference + elif isinstance(page, IndirectObject): + _i = page + try: + return pages[_i.idnum].indirect_reference # type: ignore[union-attr] + except Exception: + return None + + def _insert_filtered_annotations( + self, + annots: Union[IndirectObject, list[DictionaryObject], None], + page: PageObject, + pages: dict[int, PageObject], + reader: PdfReader, + ) -> list[Destination]: + outlist = ArrayObject() + if isinstance(annots, IndirectObject): + annots = cast("list[Any]", annots.get_object()) + if annots is None: + return outlist + if not isinstance(annots, list): + logger_warning( + "Expected list of annotations, got %(annots)s of type %(annots_type)s.", + source=__name__, + annots=annots, + annots_type=annots.__class__.__name__, + ) + return outlist + for an in annots: + ano = cast("DictionaryObject", an.get_object()) + if ( + ano["/Subtype"] != "/Link" # type: ignore[comparison-overlap] + or "/A" not in ano + or cast("DictionaryObject", ano["/A"])["/S"] != "/GoTo" # type: ignore[comparison-overlap] + or "/Dest" in ano + ): + if "/Dest" not in ano: + outlist.append(self._add_object(ano.clone(self))) + else: + d = ano["/Dest"] + if isinstance(d, str): + # it is a named dest + if str(d) in self.get_named_dest_root(): + outlist.append(ano.clone(self).indirect_reference) + else: + if not isinstance(d, ArrayObject) or not d: + continue + p = self._get_cloned_page(d[0], pages, reader) + if p is not None: + anc = ano.clone(self, ignore_fields=("/Dest",)) + anc[NameObject("/Dest")] = ArrayObject([p, *d[1:]]) + outlist.append(self._add_object(anc)) + else: + d = cast("DictionaryObject", ano["/A"]).get("/D", NullObject()) + if is_null_or_none(d): + continue + if isinstance(d, str): + # it is a named dest + if str(d) in self.get_named_dest_root(): + outlist.append(ano.clone(self).indirect_reference) + else: + if not isinstance(d, ArrayObject) or not d: + continue + p = self._get_cloned_page(d[0], pages, reader) + if p is not None: + anc = ano.clone(self, ignore_fields=("/D",)) + cast("DictionaryObject", anc["/A"])[ + NameObject("/D") + ] = ArrayObject([p, *d[1:]]) + outlist.append(self._add_object(anc)) + return outlist + + def _get_filtered_outline( + self, + *, + node: Any, + pages: dict[int, PageObject], + reader: PdfReader, + visited: Optional[set[int]] = None, + ) -> list[Destination]: + """ + Extract outline item entries that are part of the specified page set. + + Returns: + A list of destination objects. + + """ + if visited is None: + visited = set() + new_outline: list[Destination] = [] + if node is None: + return new_outline + node = node.get_object() + if is_null_or_none(node): + node = DictionaryObject() + + if node.get("/Type", "") == "/Outlines" or "/Title" not in node: + node_id = id(node) + if node_id in visited: + logger_warning("Detected cycle in outlines.", source=__name__) + return [] + visited.add(node_id) + + node = node.get("/First", None) + if node is not None: + node = node.get_object() + new_outline += self._get_filtered_outline(node=node, pages=pages, reader=reader, visited=visited) + else: + cloned_page: Union[IndirectObject, NullObject, None] + while True: + node = node.get_object() + node_id = id(node) + if node_id in visited: + logger_warning("Detected cycle in outlines.", source=__name__) + break + visited.add(node_id) + + destination = cast("Destination", reader._build_outline_item(node)) + cloned_page = self._get_cloned_page(cast("PageObject", destination["/Page"]), pages, reader) + if cloned_page is None: + cloned_page = NullObject() + destination[NameObject("/Page")] = cloned_page + if "/First" in node: + destination._filtered_children = self._get_filtered_outline( + node=node["/First"], pages=pages, reader=reader, visited=visited + ) + else: + destination._filtered_children = [] + if ( + not isinstance(cloned_page, NullObject) + or len(destination._filtered_children) > 0 + ): + new_outline.append(destination) + + if "/Next" not in node: + break + node = node["/Next"] + return new_outline + + def _clone_outline(self, dest: Destination) -> TreeObject: + n_ol = TreeObject() + self._add_object(n_ol) + n_ol[NameObject("/Title")] = TextStringObject(dest["/Title"]) + if not isinstance(dest["/Page"], NullObject): + if dest.node is not None and "/A" in dest.node: + n_ol[NameObject("/A")] = dest.node["/A"].clone(self) + else: + n_ol[NameObject("/Dest")] = dest.dest_array + # TODO: /SE + if dest.node is not None: + n_ol[NameObject("/F")] = NumberObject(dest.node.get("/F", 0)) + color = dest.node.get("/C", NullObject()).get_object() + if not isinstance(color, list): + color = [FloatObject(0.0), FloatObject(0.0), FloatObject(0.0)] + n_ol[NameObject("/C")] = ArrayObject(color) + return n_ol + + def _insert_filtered_outline( + self, + outlines: list[Destination], + parent: Union[TreeObject, IndirectObject], + before: Union[TreeObject, IndirectObject, None] = None, + ) -> None: + for dest in outlines: + # TODO: can be improved to keep A and SE entries (ignored for the moment) + # with np=self.add_outline_item_destination(dest,parent,before) + if dest.get("/Type", "") == "/Outlines" or "/Title" not in dest: + np = parent + else: + np = self._clone_outline(dest) + cast(TreeObject, parent.get_object()).insert_child(np, before, self) + self._insert_filtered_outline(dest._filtered_children, np, None) + + def close(self) -> None: + """Implemented for API harmonization.""" + return + + def find_outline_item( + self, + outline_item: dict[str, Any], + root: Optional[OutlineType] = None, + ) -> Optional[list[int]]: + if root is None: + o = self.get_outline_root() + else: + o = cast("TreeObject", root) + + i = 0 + while o is not None: + if ( + o.indirect_reference == outline_item + or o.get("/Title", None) == outline_item + ): + return [i] + if "/First" in o: + res = self.find_outline_item( + outline_item, cast(OutlineType, o["/First"]) + ) + if res: + return ([i] if "/Title" in o else []) + res + if "/Next" in o: + i += 1 + o = cast(TreeObject, o["/Next"]) + else: + return None + raise PyPdfError("This line is theoretically unreachable.") # pragma: no cover + + def reset_translation( + self, reader: Union[PdfReader, IndirectObject, None] = None + ) -> None: + """ + Reset the translation table between reader and the writer object. + + Late cloning will create new independent objects. + + Args: + reader: PdfReader or IndirectObject referencing a PdfReader object. + if set to None or omitted, all tables will be reset. + + """ + if reader is None: + self._id_translated = {} + elif isinstance(reader, PdfReader): + try: + del self._id_translated[id(reader)] + except Exception: + pass + elif isinstance(reader, IndirectObject): + try: + del self._id_translated[id(reader.pdf)] + except Exception: + pass + else: + raise Exception("invalid parameter {reader}") + + def set_page_label( + self, + page_index_from: int, + page_index_to: int, + style: Optional[PageLabelStyle] = None, + prefix: Optional[str] = None, + start: Optional[int] = 0, + ) -> None: + """ + Set a page label to a range of pages. + + Page indexes must be given starting from 0. + Labels must have a style, a prefix or both. + If a range is not assigned any page label, a decimal label starting from 1 is applied. + + Args: + page_index_from: page index of the beginning of the range starting from 0 + page_index_to: page index of the beginning of the range starting from 0 + style: The numbering style to be used for the numeric portion of each page label: + + * ``/D`` Decimal Arabic numerals + * ``/R`` Uppercase Roman numerals + * ``/r`` Lowercase Roman numerals + * ``/A`` Uppercase letters (A to Z for the first 26 pages, + AA to ZZ for the next 26, and so on) + * ``/a`` Lowercase letters (a to z for the first 26 pages, + aa to zz for the next 26, and so on) + + prefix: The label prefix for page labels in this range. + start: The value of the numeric portion for the first page label + in the range. + Subsequent pages are numbered sequentially from this value, + which must be greater than or equal to 1. + Default value: 1. + + """ + if style is None and prefix is None: + raise ValueError("At least one of style and prefix must be given") + if page_index_from < 0: + raise ValueError("page_index_from must be greater or equal than 0") + if page_index_to < page_index_from: + raise ValueError( + "page_index_to must be greater or equal than page_index_from" + ) + if page_index_to >= len(self.pages): + raise ValueError("page_index_to exceeds number of pages") + if start is not None and start != 0 and start < 1: + raise ValueError("If given, start must be greater or equal than one") + + self._set_page_label(page_index_from, page_index_to, style, prefix, start) + + def _set_page_label( + self, + page_index_from: int, + page_index_to: int, + style: Optional[PageLabelStyle] = None, + prefix: Optional[str] = None, + start: Optional[int] = 0, + ) -> None: + """ + Set a page label to a range of pages. + + Page indexes must be given starting from 0. + Labels must have a style, a prefix or both. + If a range is not assigned any page label a decimal label starting from 1 is applied. + + Args: + page_index_from: page index of the beginning of the range starting from 0 + page_index_to: page index of the beginning of the range starting from 0 + style: The numbering style to be used for the numeric portion of each page label: + /D Decimal Arabic numerals + /R Uppercase Roman numerals + /r Lowercase Roman numerals + /A Uppercase letters (A to Z for the first 26 pages, + AA to ZZ for the next 26, and so on) + /a Lowercase letters (a to z for the first 26 pages, + aa to zz for the next 26, and so on) + prefix: The label prefix for page labels in this range. + start: The value of the numeric portion for the first page label + in the range. + Subsequent pages are numbered sequentially from this value, + which must be greater than or equal to 1. Default value: 1. + + """ + default_page_label = DictionaryObject() + default_page_label[NameObject("/S")] = NameObject("/D") + + new_page_label = DictionaryObject() + if style is not None: + new_page_label[NameObject("/S")] = NameObject(style) + if prefix is not None: + new_page_label[NameObject("/P")] = TextStringObject(prefix) + if start != 0: + new_page_label[NameObject("/St")] = NumberObject(start) + + if NameObject(CatalogDictionary.PAGE_LABELS) not in self._root_object: + nums = ArrayObject() + nums_insert(NumberObject(0), default_page_label, nums) + page_labels = TreeObject() + page_labels[NameObject("/Nums")] = nums + self._root_object[NameObject(CatalogDictionary.PAGE_LABELS)] = page_labels + + page_labels = cast( + TreeObject, self._root_object[NameObject(CatalogDictionary.PAGE_LABELS)] + ) + nums = cast(ArrayObject, page_labels[NameObject("/Nums")]) + + nums_insert(NumberObject(page_index_from), new_page_label, nums) + nums_clear_range(NumberObject(page_index_from), page_index_to, nums) + next_label_pos, *_ = nums_next(NumberObject(page_index_from), nums) + if next_label_pos != page_index_to + 1 and page_index_to + 1 < len(self.pages): + nums_insert(NumberObject(page_index_to + 1), default_page_label, nums) + + page_labels[NameObject("/Nums")] = nums + self._root_object[NameObject(CatalogDictionary.PAGE_LABELS)] = page_labels + + def _repr_mimebundle_( + self, + include: Union[Iterable[str], None] = None, + exclude: Union[Iterable[str], None] = None, + ) -> dict[str, Any]: + """ + Integration into Jupyter Notebooks. + + This method returns a dictionary that maps a mime-type to its + representation. + + .. seealso:: + + https://ipython.readthedocs.io/en/stable/config/integrating.html + """ + pdf_data = BytesIO() + self.write(pdf_data) + data = { + "application/pdf": pdf_data, + } + + if include is not None: + # Filter representations based on include list + data = {k: v for k, v in data.items() if k in include} + + if exclude is not None: + # Remove representations based on exclude list + data = {k: v for k, v in data.items() if k not in exclude} + + return data + + +def _pdf_objectify(obj: Union[dict[str, Any], str, float, list[Any]]) -> PdfObject: + if isinstance(obj, PdfObject): + return obj + if isinstance(obj, dict): + to_add = DictionaryObject() + for key, value in obj.items(): + to_add[NameObject(key)] = _pdf_objectify(value) + return to_add + if isinstance(obj, str): + if obj.startswith("/"): + return NameObject(obj) + return TextStringObject(obj) + if isinstance(obj, (float, int)): + return FloatObject(obj) + if isinstance(obj, list): + return ArrayObject(_pdf_objectify(i) for i in obj) + raise NotImplementedError( + f"{type(obj)=} could not be cast to a PdfObject" + ) + + +def _create_outline_item( + action_ref: Union[IndirectObject, None], + title: str, + color: Union[tuple[float, float, float], str, None], + italic: bool, + bold: bool, +) -> TreeObject: + outline_item = TreeObject() + if action_ref is not None: + outline_item[NameObject("/A")] = action_ref + outline_item.update( + { + NameObject("/Title"): create_string_object(title), + } + ) + if color: + if isinstance(color, str): + color = hex_to_rgb(color) + outline_item.update( + {NameObject("/C"): ArrayObject([FloatObject(c) for c in color])} + ) + if italic or bold: + format_flag = 0 + if italic: + format_flag += OutlineFontFlag.italic + if bold: + format_flag += OutlineFontFlag.bold + outline_item.update({NameObject("/F"): NumberObject(format_flag)}) + return outline_item diff --git a/.venv/lib/python3.13/site-packages/pypdf/actions/__init__.py b/.venv/lib/python3.13/site-packages/pypdf/actions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5cb5ce556c204947c4f42fdc90ee367324f3f241 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/actions/__init__.py @@ -0,0 +1,17 @@ +""" +PDF includes a wide variety of standard action types, whose characteristics and +behaviour are defined by an action dictionary. These are defined in this +submodule. + +Trigger events are the other component of actions, and are specific to their +associated object. +""" + + +from ._actions import Action, JavaScript, PageTrigger + +__all__ = [ + "Action", + "JavaScript", + "PageTrigger", +] diff --git a/.venv/lib/python3.13/site-packages/pypdf/actions/_actions.py b/.venv/lib/python3.13/site-packages/pypdf/actions/_actions.py new file mode 100644 index 0000000000000000000000000000000000000000..98b8220b40297ebc85f0458af40077fe78ea107c --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/actions/_actions.py @@ -0,0 +1,187 @@ +"""Action types""" +import sys +from abc import ABC +from enum import Enum, unique +from typing import ( + TYPE_CHECKING, + cast, +) + +from .._utils import logger_warning +from ..errors import ParseError +from ..generic import ( + ArrayObject, + DictionaryObject, + NameObject, + NullObject, + TextStringObject, + is_null_or_none, +) + +if sys.version_info >= (3, 11): + from enum import StrEnum +else: + class StrEnum(str, Enum): + def __str__(self) -> str: + return str(self.value) + +if TYPE_CHECKING: + from .._page import PageObject + + +@unique +class PageTrigger(StrEnum): + """Trigger event entries in a page object's additional-actions dictionary.""" + OPEN = "open" + """Trigger an action when the page is opened.""" + CLOSE = "close" + """Trigger an action when the page is closed.""" + + @property + def _name_object(self) -> NameObject: + """Returns the corresponding NameObject for the trigger.""" + mapping = { + PageTrigger.OPEN: NameObject("/O"), + PageTrigger.CLOSE: NameObject("/C"), + } + return mapping[self] + + +class Action(DictionaryObject, ABC): + """An action dictionary defines the characteristics and behaviour of an action.""" + def __init__(self) -> None: + super().__init__() + self[NameObject("/Type")] = NameObject("/Action") + # The next action or sequence of actions that shall be performed after the action + # represented by this dictionary. The value is either a single action dictionary + # or an array of action dictionaries that shall be performed in order. + self[NameObject("/Next")] = NullObject() # Optional + + @classmethod + def _create_new(cls, page: "PageObject", trigger: PageTrigger, action: "Action") -> None: + """ + Create a new action and add it to the page. + + Args: + page: The page to add the action to. + trigger: An open or close trigger. + action: The action to be done. + """ + trigger_name = trigger._name_object + + if "/AA" not in page: + # Additional actions key not present + page[NameObject("/AA")] = DictionaryObject( + {trigger_name: action} + ) + return + + if isinstance(page["/AA"], NullObject): + page[NameObject("/AA")] = DictionaryObject() + + if not isinstance(page["/AA"].get_object(), DictionaryObject): + current_type = type(page["/AA"]).__name__ + if page.pdf is not None and getattr(page.pdf, "strict", False): + raise ParseError( + f"The type in a page object's additional-actions key must be a DictionaryObject: " + f"received type {current_type}." + ) + logger_warning( + "The type in a page object's additional-actions key must be a DictionaryObject: " + "received type %(type)s.", + source=__name__, + type=current_type + ) + return + + additional_actions = cast(DictionaryObject, page["/AA"]) + + if is_null_or_none(additional_actions.get(trigger_name)): + additional_actions.update({trigger_name: action}) + return + + # The action dictionary's Next entry allows sequences of actions to be + # chained together. For example, the effect of clicking a link + # annotation with the mouse can be to play a sound, jump to a new + # page, and start up a movie. Note that the Next entry is not + # restricted to a single action but can contain an array of actions, + # each of which in turn can have a Next entry of its own. + # §12.6.2 Action dictionaries ISO 32000-2:2020 + head = current = additional_actions.get(trigger_name) + if not isinstance(head, DictionaryObject): + raise ParseError( + f"The type in a page object's additional-actions key must be a DictionaryObject: " + f"received type {type(head).__name__}." + ) + current = cast(DictionaryObject, current) + + visited = set() + while True: + next_node = current.get("/Next", None) + + if is_null_or_none(next_node): + break + + if not isinstance(next_node, (ArrayObject, DictionaryObject)): + raise TypeError( + f"An action dictionary’s Next entry must be an Action dictionary " + f"or an array of Action dictionaries: received type {type(next_node).__name__}." + ) + + id_next = id(next_node) + if id_next in visited: + logger_warning("Detected cycle in the action tree for %(current)s", source=__name__, current=current) + break + visited.add(id_next) + + if isinstance(next_node, ArrayObject): + current = next_node[-1] + else: + current = next_node + + if not is_null_or_none(next_node := current.get("/Next")) and id(next_node) in visited: + logger_warning("Detected cycle in the action tree for %(current)s", source=__name__, current=current) + + current[NameObject("/Next")] = action + additional_actions.update({trigger_name: head}) + + @classmethod + def _delete(cls, page: "PageObject", trigger: PageTrigger) -> None: + """ + Delete an action from the page. + + Args: + page: The page to delete the action. + trigger: An open or close trigger. + """ + if "/AA" not in page: + return + + trigger_name = trigger._name_object + + additional_actions = cast(DictionaryObject, page["/AA"]) + + if trigger_name not in additional_actions: + return + + del additional_actions[trigger_name] + + if not additional_actions: + del page["/AA"] + + +class JavaScript(Action): + """ + Upon invocation of an ECMAScript action, a PDF processor shall execute a + script that is written in the ECMAScript programming language. ECMAScript + extensions described in ISO/DIS 21757-1 shall also be allowed. + + Args: + java_script: A text string containing the ECMAScript script to be executed. + """ + + def __init__(self, java_script: str) -> None: + """Initialize JavaScript with a string.""" + super().__init__() + self[NameObject("/S")] = NameObject("/JavaScript") + self[NameObject("/JS")] = TextStringObject(java_script) diff --git a/.venv/lib/python3.13/site-packages/pypdf/annotations/__init__.py b/.venv/lib/python3.13/site-packages/pypdf/annotations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..44ed1dab5cacdfc7dbc9c07605e164e757a927b5 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/annotations/__init__.py @@ -0,0 +1,42 @@ +""" +PDF specifies several annotation types which pypdf makes available here. + +The names of the annotations and their attributes do not reflect the names in +the specification in all cases. For example, the PDF standard defines a +'Square' annotation that does not actually need to be square. For this reason, +pypdf calls it 'Rectangle'. + +At their core, all annotation types are DictionaryObjects. That means if pypdf +does not implement a feature, users can easily extend the given functionality. +""" + + +from ._base import NO_FLAGS, AnnotationDictionary +from ._markup_annotations import ( + Ellipse, + FreeText, + Highlight, + Line, + MarkupAnnotation, + Polygon, + PolyLine, + Rectangle, + Text, +) +from ._non_markup_annotations import Link, Popup + +__all__ = [ + "NO_FLAGS", + "AnnotationDictionary", + "Ellipse", + "FreeText", + "Highlight", + "Line", + "Link", + "MarkupAnnotation", + "PolyLine", + "Polygon", + "Popup", + "Rectangle", + "Text", +] diff --git a/.venv/lib/python3.13/site-packages/pypdf/annotations/_base.py b/.venv/lib/python3.13/site-packages/pypdf/annotations/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..7731b18682b898a4f5b312d69e07df7df3494100 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/annotations/_base.py @@ -0,0 +1,29 @@ +from abc import ABC + +from ..constants import AnnotationFlag +from ..generic import NameObject, NumberObject +from ..generic._data_structures import DictionaryObject + + +class AnnotationDictionary(DictionaryObject, ABC): + def __init__(self) -> None: + super().__init__() + + from ..generic._base import NameObject # noqa: PLC0415 + + # /Rect should not be added here as Polygon and PolyLine can automatically set it + self[NameObject("/Type")] = NameObject("/Annot") + # The flags were NOT added to the constructor on purpose: + # We expect that most users don't want to change the default. + # If they do, they can use the property. The default is 0. + + @property + def flags(self) -> AnnotationFlag: + return AnnotationFlag(self.get(NameObject("/F"), 0)) + + @flags.setter + def flags(self, value: AnnotationFlag) -> None: + self[NameObject("/F")] = NumberObject(value) + + +NO_FLAGS = AnnotationFlag(0) diff --git a/.venv/lib/python3.13/site-packages/pypdf/annotations/_markup_annotations.py b/.venv/lib/python3.13/site-packages/pypdf/annotations/_markup_annotations.py new file mode 100644 index 0000000000000000000000000000000000000000..25eb0dfc48cc776513d27ca38e0a9a5c42602281 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/annotations/_markup_annotations.py @@ -0,0 +1,351 @@ +import sys +import uuid +from abc import ABC +from typing import Any, Literal, Optional, Union + +from ..constants import AnnotationFlag +from ..generic import ArrayObject, DictionaryObject +from ..generic._base import ( + BooleanObject, + FloatObject, + IndirectObject, + NameObject, + NumberObject, + TextStringObject, +) +from ..generic._rectangle import RectangleObject +from ..generic._utils import hex_to_rgb +from ._base import NO_FLAGS, AnnotationDictionary + +if sys.version_info[:2] >= (3, 10): + from typing import TypeAlias +else: + # PEP 613 introduced typing.TypeAlias with Python 3.10 + # For older Python versions, the backport typing_extensions is necessary: + from typing_extensions import TypeAlias + + +Vertex: TypeAlias = tuple[float, float] + + +def _get_bounding_rectangle(vertices: list[Vertex]) -> RectangleObject: + x_min, y_min = vertices[0][0], vertices[0][1] + x_max, y_max = vertices[0][0], vertices[0][1] + for x, y in vertices: + x_min = min(x_min, x) + y_min = min(y_min, y) + x_max = max(x_max, x) + y_max = max(y_max, y) + return RectangleObject((x_min, y_min, x_max, y_max)) + + +class MarkupAnnotation(AnnotationDictionary, ABC): + """ + Base class for all markup annotations. + + Args: + title_bar: Text to be displayed in the title bar of the annotation; + by convention this is the name of the author + in_reply_to: The annotation that this annotation is "in reply to" + (PDF 1.5). Can be either an annotation (previously added using + :meth:`~pypdf.PdfWriter.add_annotation`) or a reference to the + target annotation. + reply_type: The relationship between this annotation and the one + specified by ``in_reply_to``. Either ``"R"`` (a reply, default) + or ``"Group"`` (grouped with the parent annotation). Raises + ``ValueError`` if a non-default value is provided without + ``in_reply_to``. + annotation_name: A text string uniquely identifying this annotation + among all annotations on its page. Automatically generated when + ``in_reply_to`` is set and no name is provided. Raises + ``ValueError`` if provided without ``in_reply_to``. + + """ + + def __init__( + self, + *, + title_bar: Optional[str] = None, + in_reply_to: Optional[Union[DictionaryObject, IndirectObject]] = None, + reply_type: Literal["R", "Group"] = "R", + annotation_name: Optional[str] = None, + ) -> None: + if title_bar is not None: + self[NameObject("/T")] = TextStringObject(title_bar) + if annotation_name is not None and in_reply_to is None: + raise ValueError( + "annotation_name is only supported when in_reply_to is set" + ) + if reply_type != "R" and in_reply_to is None: + raise ValueError( + "reply_type is only meaningful when in_reply_to is set" + ) + if in_reply_to is not None: + if isinstance(in_reply_to, IndirectObject): + ref: IndirectObject = in_reply_to + else: + indirect_ref = getattr(in_reply_to, "indirect_reference", None) + if not isinstance(indirect_ref, IndirectObject): + raise ValueError( + "in_reply_to must be a registered annotation " + "(added via writer.add_annotation() first)" + ) + ref = indirect_ref + self[NameObject("/IRT")] = ref + self[NameObject("/RT")] = NameObject(f"/{reply_type}") + if annotation_name is None: + annotation_name = str(uuid.uuid4()) + self[NameObject("/NM")] = TextStringObject(annotation_name) + + +class Text(MarkupAnnotation): + """ + A text annotation. + + Args: + rect: array of four integers ``[xLL, yLL, xUR, yUR]`` + specifying the clickable rectangular area + text: The text that is added to the document + open: + flags: + + """ + + def __init__( + self, + *, + rect: Union[RectangleObject, tuple[float, float, float, float]], + text: str, + open: bool = False, + flags: int = NO_FLAGS, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self[NameObject("/Subtype")] = NameObject("/Text") + self[NameObject("/Rect")] = RectangleObject(rect) + self[NameObject("/Contents")] = TextStringObject(text) + self[NameObject("/Open")] = BooleanObject(open) + self[NameObject("/Flags")] = NumberObject(flags) + + +class FreeText(MarkupAnnotation): + """A FreeText annotation""" + + def __init__( + self, + *, + text: str, + rect: Union[RectangleObject, tuple[float, float, float, float]], + font: str = "Helvetica", + bold: bool = False, + italic: bool = False, + font_size: str = "14pt", + font_color: str = "000000", + border_color: Optional[str] = "000000", + background_color: Optional[str] = "ffffff", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self[NameObject("/Subtype")] = NameObject("/FreeText") + self[NameObject("/Rect")] = RectangleObject(rect) + + # Table 225 of the 1.7 reference ("CSS2 style attributes used in rich text strings") + font_str = "font: " + if italic: + font_str = f"{font_str}italic " + else: + font_str = f"{font_str}normal " + if bold: + font_str = f"{font_str}bold " + else: + font_str = f"{font_str}normal " + font_str = f"{font_str}{font_size} {font}" + font_str = f"{font_str};text-align:left;color:#{font_color}" + + default_appearance_string = "" + if border_color: + for st in hex_to_rgb(border_color): + default_appearance_string = f"{default_appearance_string}{st} " + default_appearance_string = f"{default_appearance_string}rg" + + self.update( + { + NameObject("/Subtype"): NameObject("/FreeText"), + NameObject("/Rect"): RectangleObject(rect), + NameObject("/Contents"): TextStringObject(text), + # font size color + NameObject("/DS"): TextStringObject(font_str), + NameObject("/DA"): TextStringObject(default_appearance_string), + } + ) + if border_color is None: + # Border Style + self[NameObject("/BS")] = DictionaryObject( + { + # width of 0 means no border + NameObject("/W"): NumberObject(0) + } + ) + if background_color is not None: + self[NameObject("/C")] = ArrayObject( + [FloatObject(n) for n in hex_to_rgb(background_color)] + ) + + +class Line(MarkupAnnotation): + def __init__( + self, + p1: Vertex, + p2: Vertex, + rect: Union[RectangleObject, tuple[float, float, float, float]], + text: str = "", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.update( + { + NameObject("/Subtype"): NameObject("/Line"), + NameObject("/Rect"): RectangleObject(rect), + NameObject("/L"): ArrayObject( + [ + FloatObject(p1[0]), + FloatObject(p1[1]), + FloatObject(p2[0]), + FloatObject(p2[1]), + ] + ), + NameObject("/LE"): ArrayObject( + [ + NameObject("/None"), + NameObject("/None"), + ] + ), + NameObject("/IC"): ArrayObject( + [ + FloatObject(0.5), + FloatObject(0.5), + FloatObject(0.5), + ] + ), + NameObject("/Contents"): TextStringObject(text), + } + ) + + +class PolyLine(MarkupAnnotation): + def __init__( + self, + vertices: list[Vertex], + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if len(vertices) == 0: + raise ValueError("A polyline needs at least 1 vertex with two coordinates") + coord_list = [] + for x, y in vertices: + coord_list.append(NumberObject(x)) + coord_list.append(NumberObject(y)) + self.update( + { + NameObject("/Subtype"): NameObject("/PolyLine"), + NameObject("/Vertices"): ArrayObject(coord_list), + NameObject("/Rect"): RectangleObject(_get_bounding_rectangle(vertices)), + } + ) + + +class Rectangle(MarkupAnnotation): + def __init__( + self, + rect: Union[RectangleObject, tuple[float, float, float, float]], + *, + interior_color: Optional[str] = None, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.update( + { + NameObject("/Type"): NameObject("/Annot"), + NameObject("/Subtype"): NameObject("/Square"), + NameObject("/Rect"): RectangleObject(rect), + } + ) + + if interior_color: + self[NameObject("/IC")] = ArrayObject( + [FloatObject(n) for n in hex_to_rgb(interior_color)] + ) + + +class Highlight(MarkupAnnotation): + def __init__( + self, + *, + rect: Union[RectangleObject, tuple[float, float, float, float]], + quad_points: ArrayObject, + highlight_color: str = "ff0000", + printing: bool = False, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.update( + { + NameObject("/Subtype"): NameObject("/Highlight"), + NameObject("/Rect"): RectangleObject(rect), + NameObject("/QuadPoints"): quad_points, + NameObject("/C"): ArrayObject( + [FloatObject(n) for n in hex_to_rgb(highlight_color)] + ), + } + ) + if printing: + self.flags = AnnotationFlag.PRINT + + +class Ellipse(MarkupAnnotation): + def __init__( + self, + rect: Union[RectangleObject, tuple[float, float, float, float]], + *, + interior_color: Optional[str] = None, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + + self.update( + { + NameObject("/Type"): NameObject("/Annot"), + NameObject("/Subtype"): NameObject("/Circle"), + NameObject("/Rect"): RectangleObject(rect), + } + ) + + if interior_color: + self[NameObject("/IC")] = ArrayObject( + [FloatObject(n) for n in hex_to_rgb(interior_color)] + ) + + +class Polygon(MarkupAnnotation): + def __init__( + self, + vertices: list[tuple[float, float]], + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if len(vertices) == 0: + raise ValueError("A polygon needs at least 1 vertex with two coordinates") + + coord_list = [] + for x, y in vertices: + coord_list.append(NumberObject(x)) + coord_list.append(NumberObject(y)) + self.update( + { + NameObject("/Type"): NameObject("/Annot"), + NameObject("/Subtype"): NameObject("/Polygon"), + NameObject("/Vertices"): ArrayObject(coord_list), + NameObject("/IT"): NameObject("/PolygonCloud"), + NameObject("/Rect"): RectangleObject(_get_bounding_rectangle(vertices)), + } + ) diff --git a/.venv/lib/python3.13/site-packages/pypdf/annotations/_non_markup_annotations.py b/.venv/lib/python3.13/site-packages/pypdf/annotations/_non_markup_annotations.py new file mode 100644 index 0000000000000000000000000000000000000000..9bc6b3e90943859f546ae9bcabd3d8458d27d5f9 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/annotations/_non_markup_annotations.py @@ -0,0 +1,106 @@ +from typing import TYPE_CHECKING, Any, Optional, Union + +from ..generic._base import ( + BooleanObject, + NameObject, + NumberObject, + TextStringObject, +) +from ..generic._data_structures import ArrayObject, DictionaryObject +from ..generic._fit import DEFAULT_FIT, Fit +from ..generic._rectangle import RectangleObject +from ._base import AnnotationDictionary + + +class Link(AnnotationDictionary): + def __init__( + self, + *, + rect: Union[RectangleObject, tuple[float, float, float, float]], + border: Optional[ArrayObject] = None, + url: Optional[str] = None, + target_page_index: Optional[int] = None, + fit: Fit = DEFAULT_FIT, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if TYPE_CHECKING: + from ..types import BorderArrayType # noqa: PLC0415 + + is_external = url is not None + is_internal = target_page_index is not None + if not is_external and not is_internal: + raise ValueError( + "Either 'url' or 'target_page_index' have to be provided. Both were None." + ) + if is_external and is_internal: + raise ValueError( + "Either 'url' or 'target_page_index' have to be provided. " + f"{url=}, {target_page_index=}" + ) + + border_arr: BorderArrayType + if border is not None: + border_arr = [NumberObject(n) for n in border[:3]] + if len(border) == 4: + dash_pattern = ArrayObject([NumberObject(n) for n in border[3]]) + border_arr.append(dash_pattern) + else: + border_arr = [NumberObject(0)] * 3 + + self.update( + { + NameObject("/Type"): NameObject("/Annot"), + NameObject("/Subtype"): NameObject("/Link"), + NameObject("/Rect"): RectangleObject(rect), + NameObject("/Border"): ArrayObject(border_arr), + } + ) + if is_external: + self[NameObject("/A")] = DictionaryObject( + { + NameObject("/S"): NameObject("/URI"), + NameObject("/Type"): NameObject("/Action"), + NameObject("/URI"): TextStringObject(url), + } + ) + if is_internal: + # This needs to be updated later! + dest_deferred = DictionaryObject( + { + "target_page_index": NumberObject(target_page_index), + "fit": NameObject(fit.fit_type), + "fit_args": fit.fit_args, + } + ) + self[NameObject("/Dest")] = dest_deferred + + +class Popup(AnnotationDictionary): + def __init__( + self, + *, + rect: Union[RectangleObject, tuple[float, float, float, float]], + parent: Optional[DictionaryObject] = None, + open: bool = False, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.update( + { + NameObject("/Subtype"): NameObject("/Popup"), + NameObject("/Rect"): RectangleObject(rect), + NameObject("/Open"): BooleanObject(open), + } + ) + if parent: + # This needs to be an indirect object + try: + self[NameObject("/Parent")] = parent.indirect_reference + except AttributeError: + from .._utils import logger_warning # noqa: PLC0415 + + logger_warning( + "Unregistered Parent object : No Parent field set", + source=__name__, + ) diff --git a/.venv/lib/python3.13/site-packages/pypdf/constants.py b/.venv/lib/python3.13/site-packages/pypdf/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..fc6c1148454508fc28e9cbdaee4bde0b3efd05ce --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/constants.py @@ -0,0 +1,817 @@ +"""Various constants, enums, and flags to aid readability.""" + +import sys +from enum import Enum, IntFlag, auto, unique + +if sys.version_info >= (3, 11): + from enum import StrEnum +else: + class StrEnum(str, Enum): + def __str__(self) -> str: + return str(self.value) + + +class Core: + """Keywords that don't quite belong anywhere else.""" + + OUTLINES = "/Outlines" + THREADS = "/Threads" + PAGE = "/Page" + PAGES = "/Pages" + CATALOG = "/Catalog" + + +class TrailerKeys: + SIZE = "/Size" + PREV = "/Prev" + ROOT = "/Root" + ENCRYPT = "/Encrypt" + INFO = "/Info" + ID = "/ID" + + +class CatalogAttributes: + NAMES = "/Names" + DESTS = "/Dests" + + +class EncryptionDictAttributes: + """ + Additional encryption dictionary entries for the standard security handler. + + Table 3.19, Page 122. + Table 21 of the 2.0 manual. + """ + + R = "/R" # number, required; revision of the standard security handler + O = "/O" # 32-byte string, required # noqa: E741 + U = "/U" # 32-byte string, required + P = "/P" # integer flag, required; permitted operations + ENCRYPT_METADATA = "/EncryptMetadata" # boolean flag, optional + + +class UserAccessPermissions(IntFlag): + """ + Table 3.20 User access permissions. + Table 22 of the 2.0 manual. + """ + + R1 = 1 + R2 = 2 + PRINT = 4 + MODIFY = 8 + EXTRACT = 16 + ADD_OR_MODIFY = 32 + R7 = 64 + R8 = 128 + FILL_FORM_FIELDS = 256 + EXTRACT_TEXT_AND_GRAPHICS = 512 + ASSEMBLE_DOC = 1024 + PRINT_TO_REPRESENTATION = 2048 + R13 = 2**12 + R14 = 2**13 + R15 = 2**14 + R16 = 2**15 + R17 = 2**16 + R18 = 2**17 + R19 = 2**18 + R20 = 2**19 + R21 = 2**20 + R22 = 2**21 + R23 = 2**22 + R24 = 2**23 + R25 = 2**24 + R26 = 2**25 + R27 = 2**26 + R28 = 2**27 + R29 = 2**28 + R30 = 2**29 + R31 = 2**30 + R32 = 2**31 + + @classmethod + def _is_reserved(cls, name: str) -> bool: + """Check if the given name corresponds to a reserved flag entry.""" + return name.startswith("R") and name[1:].isdigit() + + @classmethod + def _is_active(cls, name: str) -> bool: + """Check if the given reserved name defaults to 1 = active.""" + return name not in {"R1", "R2"} + + def to_dict(self) -> dict[str, bool]: + """Convert the given flag value to a corresponding verbose name mapping.""" + result: dict[str, bool] = {} + for name, flag in UserAccessPermissions.__members__.items(): + if UserAccessPermissions._is_reserved(name): + continue + result[name.lower()] = (self & flag) == flag + return result + + @classmethod + def from_dict(cls, value: dict[str, bool]) -> "UserAccessPermissions": + """Convert the verbose name mapping to the corresponding flag value.""" + value_copy = value.copy() + result = cls(0) + for name, flag in cls.__members__.items(): + if cls._is_reserved(name): + # Reserved names have a required value. Use it. + if cls._is_active(name): + result |= flag + continue + is_active = value_copy.pop(name.lower(), False) + if is_active: + result |= flag + if value_copy: + raise ValueError(f"Unknown dictionary keys: {value_copy!r}") + return result + + @classmethod + def all(cls) -> "UserAccessPermissions": + return cls((2**32 - 1) - cls.R1 - cls.R2) + + +class Resources: + """ + Table 3.30 Entries in a resource dictionary. + Table 34 in the 2.0 reference. + """ + + EXT_G_STATE = "/ExtGState" # dictionary, optional + COLOR_SPACE = "/ColorSpace" # dictionary, optional + PATTERN = "/Pattern" # dictionary, optional + SHADING = "/Shading" # dictionary, optional + XOBJECT = "/XObject" # dictionary, optional + FONT = "/Font" # dictionary, optional + PROC_SET = "/ProcSet" # array, optional + PROPERTIES = "/Properties" # dictionary, optional + + +class PagesAttributes: + """§7.7.3.2 of the 1.7 and 2.0 reference.""" + + TYPE = "/Type" # name, required; must be /Pages + PARENT = "/Parent" # dictionary, required; indirect reference to pages object + KIDS = "/Kids" # array, required; List of indirect references + COUNT = "/Count" + # integer, required; the number of leaf nodes (page objects) + # that are descendants of this node within the page tree + + +class PageAttributes: + """§7.7.3.3 of the 1.7 and 2.0 reference.""" + + TYPE = "/Type" # name, required; must be /Page + PARENT = "/Parent" # dictionary, required; a pages object + LAST_MODIFIED = ( + "/LastModified" # date, optional; date and time of last modification + ) + RESOURCES = "/Resources" # dictionary, required if there are any + MEDIABOX = "/MediaBox" # rectangle, required; rectangle specifying page size + CROPBOX = "/CropBox" # rectangle, optional + BLEEDBOX = "/BleedBox" # rectangle, optional + TRIMBOX = "/TrimBox" # rectangle, optional + ARTBOX = "/ArtBox" # rectangle, optional + BOX_COLOR_INFO = "/BoxColorInfo" # dictionary, optional + CONTENTS = "/Contents" # stream or array, optional + ROTATE = "/Rotate" # integer, optional; page rotation in degrees + GROUP = "/Group" # dictionary, optional; page group + THUMB = "/Thumb" # stream, optional; indirect reference to image of the page + B = "/B" # array, optional + DUR = "/Dur" # number, optional + TRANS = "/Trans" # dictionary, optional + ANNOTS = "/Annots" # array, optional; an array of annotations + AA = "/AA" # dictionary, optional + METADATA = "/Metadata" # stream, optional + PIECE_INFO = "/PieceInfo" # dictionary, optional + STRUCT_PARENTS = "/StructParents" # integer, optional + ID = "/ID" # byte string, optional + PZ = "/PZ" # number, optional + SEPARATION_INFO = "/SeparationInfo" # dictionary, optional + TABS = "/Tabs" # name, optional + TEMPLATE_INSTANTIATED = "/TemplateInstantiated" # name, optional + PRES_STEPS = "/PresSteps" # dictionary, optional + USER_UNIT = "/UserUnit" # number, optional + VP = "/VP" # dictionary, optional + AF = "/AF" # array of dictionaries, optional + OUTPUT_INTENTS = "/OutputIntents" # array, optional + D_PART = "/DPart" # dictionary, required, if this page is within the range of a DPart, not permitted otherwise + + +class FileSpecificationDictionaryEntries: + """Table 3.41 Entries in a file specification dictionary.""" + + Type = "/Type" + FS = "/FS" # The name of the file system to be used to interpret this file specification + F = "/F" # A file specification string of the form described in §3.10.1 + UF = "/UF" # A Unicode string of the file as described in §3.10.1 + DOS = "/DOS" + Mac = "/Mac" + Unix = "/Unix" + ID = "/ID" + V = "/V" + EF = "/EF" # dictionary, containing a subset of the keys F, UF, DOS, Mac, and Unix + RF = "/RF" # dictionary, containing arrays of /EmbeddedFile + DESC = "/Desc" # description of the file + Cl = "/Cl" + + +class StreamAttributes: + """ + Table 4.2. + Table 5 in the 2.0 reference. + """ + + LENGTH = "/Length" # integer, required + FILTER = "/Filter" # name or array of names, optional + DECODE_PARMS = "/DecodeParms" # variable, optional; /DecodeParams is wrong + + +@unique +class FilterTypes(StrEnum): + """§7.4 of the 1.7 and 2.0 references.""" + + ASCII_HEX_DECODE = "/ASCIIHexDecode" # abbreviation: AHx + ASCII_85_DECODE = "/ASCII85Decode" # abbreviation: A85 + LZW_DECODE = "/LZWDecode" # abbreviation: LZW + FLATE_DECODE = "/FlateDecode" # abbreviation: Fl + RUN_LENGTH_DECODE = "/RunLengthDecode" # abbreviation: RL + CCITT_FAX_DECODE = "/CCITTFaxDecode" # abbreviation: CCF + DCT_DECODE = "/DCTDecode" # abbreviation: DCT + JPX_DECODE = "/JPXDecode" + JBIG2_DECODE = "/JBIG2Decode" + + +class FilterTypeAbbreviations: + """§8.9.7 of the 1.7 and 2.0 references.""" + + AHx = "/AHx" + A85 = "/A85" + LZW = "/LZW" + FL = "/Fl" + RL = "/RL" + CCF = "/CCF" + DCT = "/DCT" + + +class LzwFilterParameters: + """ + Table 4.4. + Table 8 in the 2.0 reference. + """ + + PREDICTOR = "/Predictor" # integer + COLORS = "/Colors" # integer + BITS_PER_COMPONENT = "/BitsPerComponent" # integer + COLUMNS = "/Columns" # integer + EARLY_CHANGE = "/EarlyChange" # integer + + +class CcittFaxDecodeParameters: + """ + Table 4.5. + Table 11 in the 2.0 reference. + """ + + K = "/K" # integer + END_OF_LINE = "/EndOfLine" # boolean + ENCODED_BYTE_ALIGN = "/EncodedByteAlign" # boolean + COLUMNS = "/Columns" # integer + ROWS = "/Rows" # integer + END_OF_BLOCK = "/EndOfBlock" # boolean + BLACK_IS_1 = "/BlackIs1" # boolean + DAMAGED_ROWS_BEFORE_ERROR = "/DamagedRowsBeforeError" # integer + + +class ImageAttributes: + """§11.6.5 of the 1.7 and 2.0 references.""" + + TYPE = "/Type" # name, required; must be /XObject + SUBTYPE = "/Subtype" # name, required; must be /Image + NAME = "/Name" # name, required + WIDTH = "/Width" # integer, required + HEIGHT = "/Height" # integer, required + BITS_PER_COMPONENT = "/BitsPerComponent" # integer, required + COLOR_SPACE = "/ColorSpace" # name, required + DECODE = "/Decode" # array, optional + INTENT = "/Intent" # string, optional + INTERPOLATE = "/Interpolate" # boolean, optional + IMAGE_MASK = "/ImageMask" # boolean, optional + MASK = "/Mask" # 1-bit image mask stream + S_MASK = "/SMask" # dictionary or name, optional + + +class ColorSpaces: + DEVICE_RGB = "/DeviceRGB" + DEVICE_CMYK = "/DeviceCMYK" + DEVICE_GRAY = "/DeviceGray" + + +class TypArguments: + """Table 8.2 of the PDF 1.7 reference.""" + + LEFT = "/Left" + RIGHT = "/Right" + BOTTOM = "/Bottom" + TOP = "/Top" + + +class TypFitArguments: + """Table 8.2 of the PDF 1.7 reference.""" + + XYZ = "/XYZ" + FIT = "/Fit" + FIT_H = "/FitH" + FIT_V = "/FitV" + FIT_R = "/FitR" + FIT_B = "/FitB" + FIT_BH = "/FitBH" + FIT_BV = "/FitBV" + + +class GoToActionArguments: + S = "/S" # name, required: type of action + D = "/D" # name, byte string, or array, required: destination to jump to + SD = "/SD" # array, optional: structure destination to jump to + + +class AnnotationDictionaryAttributes: + """Table 8.15 Entries common to all annotation dictionaries.""" + + Type = "/Type" + Subtype = "/Subtype" + Rect = "/Rect" + Contents = "/Contents" + P = "/P" + NM = "/NM" + M = "/M" + F = "/F" + AP = "/AP" + AS = "/AS" + DA = "/DA" + Border = "/Border" + C = "/C" + StructParent = "/StructParent" + OC = "/OC" + + +class InteractiveFormDictEntries: + Fields = "/Fields" + NeedAppearances = "/NeedAppearances" + SigFlags = "/SigFlags" + CO = "/CO" + DR = "/DR" + DA = "/DA" + Q = "/Q" + XFA = "/XFA" + + +class FieldDictionaryAttributes: + """ + Entries common to all field dictionaries (Table 8.69 PDF 1.7 reference) + (*very partially documented here*). + + FFBits provides the constants used for `/Ff` from Table 8.70/8.75/8.77/8.79 + """ + + FT = "/FT" # name, required for terminal fields + Parent = "/Parent" # dictionary, required for children + Kids = "/Kids" # array, sometimes required + T = "/T" # text string, optional + TU = "/TU" # text string, optional + TM = "/TM" # text string, optional + Ff = "/Ff" # integer, optional + V = "/V" # text string or array, optional + DV = "/DV" # text string, optional + AA = "/AA" # dictionary, optional + Opt = "/Opt" # array, optional + + class FfBits(IntFlag): + """ + Ease building /Ff flags + Some entries may be specific to: + + * Text (Tx) (Table 8.75 PDF 1.7 reference) + * Buttons (Btn) (Table 8.77 PDF 1.7 reference) + * Choice (Ch) (Table 8.79 PDF 1.7 reference) + """ + + ReadOnly = 1 << 0 + """common to Tx/Btn/Ch in Table 8.70""" + Required = 1 << 1 + """common to Tx/Btn/Ch in Table 8.70""" + NoExport = 1 << 2 + """common to Tx/Btn/Ch in Table 8.70""" + + Multiline = 1 << 12 + """Tx""" + Password = 1 << 13 + """Tx""" + + NoToggleToOff = 1 << 14 + """Btn""" + Radio = 1 << 15 + """Btn""" + Pushbutton = 1 << 16 + """Btn""" + + Combo = 1 << 17 + """Ch""" + Edit = 1 << 18 + """Ch""" + Sort = 1 << 19 + """Ch""" + + FileSelect = 1 << 20 + """Tx""" + + MultiSelect = 1 << 21 + """Tx""" + + DoNotSpellCheck = 1 << 22 + """Tx/Ch""" + DoNotScroll = 1 << 23 + """Tx""" + Comb = 1 << 24 + """Tx""" + + RadiosInUnison = 1 << 25 + """Btn""" + + RichText = 1 << 25 + """Tx""" + + CommitOnSelChange = 1 << 26 + """Ch""" + + @classmethod + def attributes(cls) -> tuple[str, ...]: + """ + Get a tuple of all the attributes present in a Field Dictionary. + + This method returns a tuple of all the attribute constants defined in + the FieldDictionaryAttributes class. These attributes correspond to the + entries that are common to all field dictionaries as specified in the + PDF 1.7 reference. + + Returns: + A tuple containing all the attribute constants. + + """ + return ( + cls.TM, + cls.T, + cls.FT, + cls.Parent, + cls.TU, + cls.Ff, + cls.V, + cls.DV, + cls.Kids, + cls.AA, + ) + + @classmethod + def attributes_dict(cls) -> dict[str, str]: + """ + Get a dictionary of attribute keys and their human-readable names. + + This method returns a dictionary where the keys are the attribute + constants defined in the FieldDictionaryAttributes class and the values + are their corresponding human-readable names. These attributes + correspond to the entries that are common to all field dictionaries as + specified in the PDF 1.7 reference. + + Returns: + A dictionary containing attribute keys and their names. + + """ + return { + cls.FT: "Field Type", + cls.Parent: "Parent", + cls.T: "Field Name", + cls.TU: "Alternate Field Name", + cls.TM: "Mapping Name", + cls.Ff: "Field Flags", + cls.V: "Value", + cls.DV: "Default Value", + } + + +class CheckboxRadioButtonAttributes: + """Table 8.76 Field flags common to all field types.""" + + Opt = "/Opt" # Options, Optional + + @classmethod + def attributes(cls) -> tuple[str, ...]: + """ + Get a tuple of all the attributes present in a Field Dictionary. + + This method returns a tuple of all the attribute constants defined in + the CheckboxRadioButtonAttributes class. These attributes correspond to + the entries that are common to all field dictionaries as specified in + the PDF 1.7 reference. + + Returns: + A tuple containing all the attribute constants. + + """ + return (cls.Opt,) + + @classmethod + def attributes_dict(cls) -> dict[str, str]: + """ + Get a dictionary of attribute keys and their human-readable names. + + This method returns a dictionary where the keys are the attribute + constants defined in the CheckboxRadioButtonAttributes class and the + values are their corresponding human-readable names. These attributes + correspond to the entries that are common to all field dictionaries as + specified in the PDF 1.7 reference. + + Returns: + A dictionary containing attribute keys and their names. + + """ + return { + cls.Opt: "Options", + } + + +class FieldFlag(IntFlag): + """Table 8.70 Field flags common to all field types.""" + + READ_ONLY = 1 + REQUIRED = 2 + NO_EXPORT = 4 + + +class DocumentInformationAttributes: + """Table 10.2 Entries in the document information dictionary.""" + + TITLE = "/Title" # text string, optional + AUTHOR = "/Author" # text string, optional + SUBJECT = "/Subject" # text string, optional + KEYWORDS = "/Keywords" # text string, optional + CREATOR = "/Creator" # text string, optional + PRODUCER = "/Producer" # text string, optional + CREATION_DATE = "/CreationDate" # date, optional + MOD_DATE = "/ModDate" # date, optional + TRAPPED = "/Trapped" # name, optional + + +class PageLayouts: + """ + Page 84, PDF 1.4 reference. + Page 115, PDF 2.0 reference. + """ + + SINGLE_PAGE = "/SinglePage" + ONE_COLUMN = "/OneColumn" + TWO_COLUMN_LEFT = "/TwoColumnLeft" + TWO_COLUMN_RIGHT = "/TwoColumnRight" + TWO_PAGE_LEFT = "/TwoPageLeft" # (PDF 1.5) + TWO_PAGE_RIGHT = "/TwoPageRight" # (PDF 1.5) + + +class GraphicsStateParameters: + """Table 58 – Entries in a Graphics State Parameter Dictionary""" + + TYPE = "/Type" # name, optional + LW = "/LW" # number, optional + LC = "/LC" # integer, optional + LJ = "/LJ" # integer, optional + ML = "/ML" # number, optional + D = "/D" # array, optional + RI = "/RI" # name, optional + OP = "/OP" + op = "/op" + OPM = "/OPM" + FONT = "/Font" # array, optional + BG = "/BG" + BG2 = "/BG2" + UCR = "/UCR" + UCR2 = "/UCR2" + TR = "/TR" + TR2 = "/TR2" + HT = "/HT" + FL = "/FL" + SM = "/SM" + SA = "/SA" + BM = "/BM" + S_MASK = "/SMask" # dictionary or name, optional + CA = "/CA" + ca = "/ca" + AIS = "/AIS" + TK = "/TK" + + +class CatalogDictionary: + """§7.7.2 of the 1.7 and 2.0 references.""" + + TYPE = "/Type" # name, required; must be /Catalog + VERSION = "/Version" # name + EXTENSIONS = "/Extensions" # dictionary, optional; ISO 32000-1 + PAGES = "/Pages" # dictionary, required + PAGE_LABELS = "/PageLabels" # number tree, optional + NAMES = "/Names" # dictionary, optional + DESTS = "/Dests" # dictionary, optional + VIEWER_PREFERENCES = "/ViewerPreferences" # dictionary, optional + PAGE_LAYOUT = "/PageLayout" # name, optional + PAGE_MODE = "/PageMode" # name, optional + OUTLINES = "/Outlines" # dictionary, optional + THREADS = "/Threads" # array, optional + OPEN_ACTION = "/OpenAction" # array or dictionary or name, optional + AA = "/AA" # dictionary, optional + URI = "/URI" # dictionary, optional + ACRO_FORM = "/AcroForm" # dictionary, optional + METADATA = "/Metadata" # stream, optional + STRUCT_TREE_ROOT = "/StructTreeRoot" # dictionary, optional + MARK_INFO = "/MarkInfo" # dictionary, optional + LANG = "/Lang" # text string, optional + SPIDER_INFO = "/SpiderInfo" # dictionary, optional + OUTPUT_INTENTS = "/OutputIntents" # array, optional + PIECE_INFO = "/PieceInfo" # dictionary, optional + OC_PROPERTIES = "/OCProperties" # dictionary, optional + PERMS = "/Perms" # dictionary, optional + LEGAL = "/Legal" # dictionary, optional + REQUIREMENTS = "/Requirements" # array, optional + COLLECTION = "/Collection" # dictionary, optional + NEEDS_RENDERING = "/NeedsRendering" # boolean, optional + DSS = "/DSS" # dictionary, optional + AF = "/AF" # array of dictionaries, optional + D_PART_ROOT = "/DPartRoot" # dictionary, optional + + +class OutlineFontFlag(IntFlag): + """A class used as an enumerable flag for formatting an outline font.""" + + italic = 1 + bold = 2 + + +class PageLabelStyle: + """ + Table 8.10 in the 1.7 reference. + Table 161 in the 2.0 reference. + """ + + DECIMAL = "/D" # Decimal Arabic numerals + UPPERCASE_ROMAN = "/R" # Uppercase Roman numerals + LOWERCASE_ROMAN = "/r" # Lowercase Roman numerals + UPPERCASE_LETTER = "/A" # Uppercase letters + LOWERCASE_LETTER = "/a" # Lowercase letters + + +class AnnotationFlag(IntFlag): + """See §12.5.3 "Annotation Flags".""" + + INVISIBLE = 1 + HIDDEN = 2 + PRINT = 4 + NO_ZOOM = 8 + NO_ROTATE = 16 + NO_VIEW = 32 + READ_ONLY = 64 + LOCKED = 128 + TOGGLE_NO_VIEW = 256 + LOCKED_CONTENTS = 512 + + +PDF_KEYS = ( + AnnotationDictionaryAttributes, + CatalogAttributes, + CatalogDictionary, + CcittFaxDecodeParameters, + CheckboxRadioButtonAttributes, + ColorSpaces, + Core, + DocumentInformationAttributes, + EncryptionDictAttributes, + FieldDictionaryAttributes, + FileSpecificationDictionaryEntries, + FilterTypeAbbreviations, + FilterTypes, + GoToActionArguments, + GraphicsStateParameters, + ImageAttributes, + InteractiveFormDictEntries, + LzwFilterParameters, + PageAttributes, + PageLayouts, + PagesAttributes, + Resources, + StreamAttributes, + TrailerKeys, + TypArguments, + TypFitArguments, +) + + +class ImageType(IntFlag): + NONE = 0 + XOBJECT_IMAGES = auto() + INLINE_IMAGES = auto() + DRAWING_IMAGES = auto() + ALL = XOBJECT_IMAGES | INLINE_IMAGES | DRAWING_IMAGES + IMAGES = ALL # for consistency with ObjectDeletionFlag + + +_INLINE_IMAGE_VALUE_MAPPING = { + "/G": "/DeviceGray", + "/RGB": "/DeviceRGB", + "/CMYK": "/DeviceCMYK", + "/I": "/Indexed", + "/AHx": "/ASCIIHexDecode", + "/A85": "/ASCII85Decode", + "/LZW": "/LZWDecode", + "/Fl": "/FlateDecode", + "/RL": "/RunLengthDecode", + "/CCF": "/CCITTFaxDecode", + "/DCT": "/DCTDecode", + "/DeviceGray": "/DeviceGray", + "/DeviceRGB": "/DeviceRGB", + "/DeviceCMYK": "/DeviceCMYK", + "/Indexed": "/Indexed", + "/ASCIIHexDecode": "/ASCIIHexDecode", + "/ASCII85Decode": "/ASCII85Decode", + "/LZWDecode": "/LZWDecode", + "/FlateDecode": "/FlateDecode", + "/RunLengthDecode": "/RunLengthDecode", + "/CCITTFaxDecode": "/CCITTFaxDecode", + "/DCTDecode": "/DCTDecode", + "/RelativeColorimetric": "/RelativeColorimetric", +} + +_INLINE_IMAGE_KEY_MAPPING = { + "/BPC": "/BitsPerComponent", + "/CS": "/ColorSpace", + "/D": "/Decode", + "/DP": "/DecodeParms", + "/F": "/Filter", + "/H": "/Height", + "/W": "/Width", + "/I": "/Interpolate", + "/Intent": "/Intent", + "/IM": "/ImageMask", + "/BitsPerComponent": "/BitsPerComponent", + "/ColorSpace": "/ColorSpace", + "/Decode": "/Decode", + "/DecodeParms": "/DecodeParms", + "/Filter": "/Filter", + "/Height": "/Height", + "/Width": "/Width", + "/Interpolate": "/Interpolate", + "/ImageMask": "/ImageMask", +} + + +class AFRelationship: + """ + Associated file relationship types, defining the relationship between + the PDF component and the associated file. + + Defined in table 43 of the PDF 2.0 reference. + """ + + SOURCE = "/Source" # Original content source + DATA = "/Data" # Base data for visual presentation + ALTERNATIVE = "/Alternative" # Alternative content representation + SUPPLEMENT = "/Supplement" # Supplemental representation of original source/data + ENCRYPTED_PAYLOAD = "/EncryptedPayload" # Encrypted payload document + FORM_DATA = "/FormData" # Data associated with AcroForm of this PDF + SCHEMA = "/Schema" # Schema definition for associated object + UNSPECIFIED = "/Unspecified" # Not known or cannot be described with values + + +class BorderStyles: + """ + A class defining border styles used in PDF documents. + + Defined in table 168 of the PDF 2.0 reference. + """ + + BEVELED = "/B" + DASHED = "/D" + INSET = "/I" + SOLID = "/S" + UNDERLINED = "/U" + + +class FontFlags(IntFlag): + """ + A class defining font flags in PDF document font descriptor resources. + + Defined in table 121 of the PDF 2.0 reference. + """ + + FIXED_PITCH = 1 << 0 + SERIF = 1 << 1 + SYMBOLIC = 1 << 2 + SCRIPT = 1 << 3 + NONSYMBOLIC = 1 << 5 + ITALIC = 1 << 6 + ALL_CAP = 1 << 16 + SMALL_CAP = 1 << 17 + FORCE_BOLD = 1 << 18 diff --git a/.venv/lib/python3.13/site-packages/pypdf/errors.py b/.venv/lib/python3.13/site-packages/pypdf/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..8fec6e13a279b9de013e41c91890d91873fbf1da --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/errors.py @@ -0,0 +1,74 @@ +""" +All errors/exceptions pypdf raises and all of the warnings it uses. + +Please note that broken PDF files might cause other Exceptions. +""" + + +class DeprecationError(Exception): + """Raised when a deprecated feature is used.""" + + +class DependencyError(Exception): + """ + Raised when a required dependency (a library or module that pypdf depends on) + is not available or cannot be imported. + """ + + +class PyPdfError(Exception): + """Base class for all exceptions raised by pypdf.""" + + +class PdfReadError(PyPdfError): + """Raised when there is an issue reading a PDF file.""" + + +class PageSizeNotDefinedError(PyPdfError): + """Raised when the page size of a PDF document is not defined.""" + + +class PdfReadWarning(UserWarning): + """Issued when there is a potential issue reading a PDF file, but it can still be read.""" + + +class PdfStreamError(PdfReadError): + """Raised when there is an issue reading the stream of data in a PDF file.""" + + +class ParseError(PyPdfError): + """ + Raised when there is an issue parsing (analyzing and understanding the + structure and meaning of) a PDF file. + """ + + +class FileNotDecryptedError(PdfReadError): + """ + Raised when a PDF file that has been encrypted + (meaning it requires a password to be accessed) has not been successfully + decrypted. + """ + + +class WrongPasswordError(FileNotDecryptedError): + """Raised when the wrong password is used to try to decrypt an encrypted PDF file.""" + + +class EmptyFileError(PdfReadError): + """Raised when a PDF file is empty or has no content.""" + + +class EmptyImageDataError(PyPdfError): + """Raised when trying to process an image that has no data.""" + + +STREAM_TRUNCATED_PREMATURELY = "Stream has ended unexpectedly" + + +class LimitReachedError(PyPdfError): + """Raised when a limit is reached.""" + + +class XmpDocumentError(PyPdfError, RuntimeError): + """Raised when the XMP XML document context is invalid or missing.""" diff --git a/.venv/lib/python3.13/site-packages/pypdf/filters.py b/.venv/lib/python3.13/site-packages/pypdf/filters.py new file mode 100644 index 0000000000000000000000000000000000000000..d48d2ecb003cbd8945ac889bbb1299f001e55a23 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/filters.py @@ -0,0 +1,878 @@ +# Copyright (c) 2006, Mathieu Fenniak +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * The name of the author may not be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + + +""" +Implementation of stream filters; §7.4 Filters of the PDF 2.0 specification. + +§8.9.7 Inline images of the PDF 2.0 specification has abbreviations that can be +used for the names of filters in an inline image object. +""" +__author__ = "Mathieu Fenniak" +__author_email__ = "biziqe@mathieu.fenniak.net" + +import binascii +import math +import os +import shutil +import struct +import subprocess +import zlib +from base64 import a85decode +from dataclasses import dataclass +from pathlib import Path +from tempfile import TemporaryDirectory +from typing import Any, NoReturn, Optional, Union, cast + +from ._codecs._codecs import LzwCodec as _LzwCodec +from ._utils import ( + WHITESPACES_AS_BYTES, + deprecate, + deprecation_with_replacement, + logger_warning, +) +from .constants import CcittFaxDecodeParameters as CCITT +from .constants import FilterTypeAbbreviations as FTA +from .constants import FilterTypes as FT +from .constants import ImageAttributes, StreamAttributes +from .constants import LzwFilterParameters as LZW +from .errors import DependencyError, LimitReachedError, PdfReadError, PdfStreamError +from .generic import ( + ArrayObject, + DictionaryObject, + IndirectObject, + NullObject, + NumberObject, + PdfObject, + StreamObject, + is_null_or_none, +) + +MAX_DECLARED_STREAM_LENGTH = 75_000_000 +MAX_ARRAY_BASED_STREAM_OUTPUT_LENGTH = 75_000_000 + +JBIG2_MAX_OUTPUT_LENGTH = 75_000_000 +LZW_MAX_OUTPUT_LENGTH = 75_000_000 +RUN_LENGTH_MAX_OUTPUT_LENGTH = 75_000_000 +ZLIB_MAX_OUTPUT_LENGTH = 75_000_000 +ZLIB_MAX_RECOVERY_INPUT_LENGTH = 5_000_000 +FLATE_MAX_COLUMNS = 250_000 +FLATE_MAX_ROW_LENGTH = 4_000_000 +FLATE_MAX_BUFFER_SIZE = 75_000_000 # TODO: This should be IMAGE_MAX_BUFFER_SIZE. + +# Reuse cached 1-byte values in the fallback loop to avoid per-byte allocations. +_SINGLE_BYTES = tuple(bytes((i,)) for i in range(256)) + + +def _decompress_with_limit(data: bytes) -> bytes: + decompressor = zlib.decompressobj() + result = decompressor.decompress(data, max_length=ZLIB_MAX_OUTPUT_LENGTH) + if decompressor.unconsumed_tail: + raise LimitReachedError( + f"Limit reached while decompressing. {len(decompressor.unconsumed_tail)} bytes remaining." + ) + return result + + +def decompress(data: bytes) -> bytes: + """ + Decompress the given data using zlib. + + Attempts to decompress the input data using zlib. + If the decompression fails due to a zlib error, it falls back + to using a decompression object with a larger window size. + + Please note that the output length is limited to avoid memory + issues. If you need to process larger content streams, consider + adapting ``pypdf.filters.ZLIB_MAX_OUTPUT_LENGTH``. In case you + are only dealing with trusted inputs and/or want to disable these + limits, set the value to `0`. + + Args: + data: The input data to be decompressed. + + Returns: + The decompressed data. + + """ + try: + return _decompress_with_limit(data) + except zlib.error: + # First quick approach: There are known issues with faulty added bytes to the + # tail of the encoded stream from early Adobe Distiller or Pitstop versions + # with CR char as the default line separator (assumed by reverse engineering) + # that breaks the decoding process in the end. + # + # Try first to cut off some of the tail byte by byte, but limited to not + # iterate through too many loops and kill the performance for large streams, + # to then allow the final fallback to run. Added this intermediate attempt, + # because starting from the head of the stream byte by byte kills completely + # the performance for large streams (e.g., 6 MB) with the tail-byte-issue + # and takes ages. This solution is really fast: + max_tail_cut_off_bytes: int = 8 + for i in range(1, min(max_tail_cut_off_bytes + 1, len(data))): + try: + return _decompress_with_limit(data[:-i]) + except zlib.error: + pass + + # If still failing, then try with increased window size. + decompressor = zlib.decompressobj(zlib.MAX_WBITS | 32) + result_str = b"" + remaining_limit = ZLIB_MAX_OUTPUT_LENGTH + data_length = len(data) + known_errors = set() + for index in range(data_length): + chunk = _SINGLE_BYTES[data[index]] + try: + decompressed = decompressor.decompress(chunk, max_length=remaining_limit) + result_str += decompressed + remaining_limit -= len(decompressed) + if remaining_limit <= 0: + raise LimitReachedError( + f"Limit reached while decompressing. {data_length - index} bytes remaining." + ) + except zlib.error as error: + if index > ZLIB_MAX_RECOVERY_INPUT_LENGTH: + raise LimitReachedError( + f"Recovery limit reached while decompressing. {data_length - index} bytes remaining." + ) + error_str = str(error) + if error_str in known_errors: + continue + logger_warning(error_str, source=__name__) + known_errors.add(error_str) + return result_str + + +class FlateDecode: + @staticmethod + def decode( + data: bytes, + decode_parms: Optional[Union[DictionaryObject, IndirectObject]] = None, + **kwargs: Any, + ) -> bytes: + """ + Decode data which is flate-encoded. + + Args: + data: Flate-encoded data. + decode_parms: Additional decoding parameters. + + Returns: + The flate-decoded data. + + Raises: + PdfReadError: Unsupported parameters have been found. + + """ + str_data = decompress(data) + + processed_parms: Optional[PdfObject] = decode_parms + if isinstance(decode_parms, IndirectObject) and processed_parms is not None: + processed_parms = processed_parms.get_object() + if isinstance(processed_parms, dict): + parameters = processed_parms + else: + if not is_null_or_none(processed_parms): + logger_warning( + "Detected invalid /DecodeParms, results might be incorrect: %(value)s (type %(type_name)s)", + source=__name__, value=decode_parms, type_name=decode_parms.__class__.__name__, + ) + parameters = DictionaryObject() + + predictor = parameters.get("/Predictor", 1) + + # predictor 1 == no predictor + if predictor != 1: + columns, colors, bits_per_component = FlateDecode._get_parameters(parameters) + + # PNG predictor can vary by row and so is the lead byte on each row + row_length = ( + math.ceil(columns * colors * bits_per_component / 8) + 1 + ) # number of bytes + if row_length > FLATE_MAX_ROW_LENGTH: + raise LimitReachedError( + f"Row length of {row_length} exceeds defined limit of {FLATE_MAX_ROW_LENGTH}." + ) + + # TIFF prediction: + if predictor == 2: + row_length -= 1 # remove the predictor byte + bpp = row_length // columns + str_data_mut = bytearray(str_data) + for i in range(len(str_data_mut)): + if i % row_length >= bpp: + str_data_mut[i] = (str_data_mut[i] + str_data_mut[i - bpp]) % 256 + str_data = bytes(str_data_mut) + # PNG prediction: + elif 10 <= predictor <= 15: + str_data = FlateDecode._decode_png_prediction( + str_data, columns, row_length + ) + else: + raise PdfReadError(f"Unsupported flatedecode predictor {predictor!r}") + return str_data + + @staticmethod + def _get_parameters(parameters: DictionaryObject) -> tuple[int, int, int]: + # For details, see table 8 of ISO 32000-2:2020. + def get(key: str, default: int) -> int: + _value = parameters.get(key, NumberObject(default)).get_object() + if not isinstance(_value, int) or _value < 1: + raise PdfReadError(f"Expected positive number for {key}, got {_value}!") + return _value + + columns = get(key=LZW.COLUMNS, default=1) + if columns > FLATE_MAX_COLUMNS: + raise LimitReachedError(f"Number of columns {columns} exceeds defined limit of {FLATE_MAX_COLUMNS}.") + + colors = get(key=LZW.COLORS, default=1) + if colors > 16: + raise LimitReachedError( + f"Color value {colors} exceeds limit of 16. " + f"Please open an issue if this limits valid use cases." + ) + + bits_per_component = get(key=LZW.BITS_PER_COMPONENT, default=8) + if bits_per_component > 16: + raise PdfReadError(f"More than 16 bits per component are not allowed: {bits_per_component}") + + return columns, colors, bits_per_component + + @staticmethod + def _decode_png_prediction(data: bytes, columns: int, row_length: int) -> bytes: + # PNG prediction can vary from row to row + if (remainder := len(data) % row_length) != 0: + logger_warning("Image data is not rectangular. Adding padding.", source=__name__) + data += b"\x00" * (row_length - remainder) + assert len(data) % row_length == 0 + output = bytearray() + previous_row_data = bytes(row_length) + bpp = (row_length - 1) // columns # recomputed locally to not change params + for row in range(0, len(data), row_length): + row_data = bytearray(data[row : row + row_length]) + filter_byte = row_data[0] + + if filter_byte == 0: + # PNG None Predictor + pass + elif filter_byte == 1: + # PNG Sub Predictor + for i in range(bpp + 1, row_length): + row_data[i] = (row_data[i] + row_data[i - bpp]) % 256 + elif filter_byte == 2: + # PNG Up Predictor + for i in range(1, row_length): + row_data[i] = (row_data[i] + previous_row_data[i]) % 256 + elif filter_byte == 3: + # PNG Average Predictor + for i in range(1, bpp + 1): + floor = previous_row_data[i] // 2 + row_data[i] = (row_data[i] + floor) % 256 + for i in range(bpp + 1, row_length): + left = row_data[i - bpp] + floor = (left + previous_row_data[i]) // 2 + row_data[i] = (row_data[i] + floor) % 256 + elif filter_byte == 4: + # PNG Paeth Predictor + for i in range(1, bpp + 1): + row_data[i] = (row_data[i] + previous_row_data[i]) % 256 + for i in range(bpp + 1, row_length): + left = row_data[i - bpp] + up = previous_row_data[i] + up_left = previous_row_data[i - bpp] + + p = left + up - up_left + dist_left = abs(p - left) + dist_up = abs(p - up) + dist_up_left = abs(p - up_left) + + if dist_left <= dist_up and dist_left <= dist_up_left: + paeth = left + elif dist_up <= dist_up_left: + paeth = up + else: + paeth = up_left + + row_data[i] = (row_data[i] + paeth) % 256 + else: + raise PdfReadError( + f"Unsupported PNG filter {filter_byte!r}" + ) # pragma: no cover + previous_row_data = bytes(row_data) + output += row_data[1:] + return bytes(output) + + @staticmethod + def encode(data: bytes, level: int = -1) -> bytes: + """ + Compress the input data using zlib. + + Args: + data: The data to be compressed. + level: See https://docs.python.org/3/library/zlib.html#zlib.compress + + Returns: + The compressed data. + + """ + return zlib.compress(data, level) + + +class ASCIIHexDecode: + """ + The ASCIIHexDecode filter decodes data that has been encoded in ASCII + hexadecimal form into a base-7 ASCII format. + """ + + @staticmethod + def decode( + data: Union[str, bytes], + decode_parms: Optional[DictionaryObject] = None, + **kwargs: Any, + ) -> bytes: + """ + Decode an ASCII-Hex encoded data stream. + + Args: + data: a str sequence of hexadecimal-encoded values to be + converted into a base-7 ASCII string + decode_parms: this filter does not use parameters. + + Returns: + A string conversion in base-7 ASCII, where each of its values + v is such that 0 <= ord(v) <= 127. + + Raises: + PdfStreamError: + + """ + if isinstance(data, str): + data = data.encode() + + # Stop at EOD + eod = data.find(b">") + if eod == -1: + logger_warning( + "missing EOD in ASCIIHexDecode, check if output is OK", + source=__name__, + ) + hex_data = data + else: + hex_data = data[:eod] + + # Remove whitespace + hex_data = b"".join(hex_data.split()) + + # Pad if odd length + if len(hex_data) % 2 == 1: + hex_data += b"0" + + # The spec permits only 0-9, A-F, a-f and whitespace inside the stream. + # Stray bytes used to surface as an uncaught binascii.Error; turn them + # into a proper PdfStreamError instead. + try: + return binascii.unhexlify(hex_data) + except binascii.Error as error: + raise PdfStreamError(f"Invalid hexadecimal character in ASCIIHexDecode stream: {error}") + + +class RunLengthDecode: + """ + The RunLengthDecode filter decodes data that has been encoded in a + simple byte-oriented format based on run length. + The encoded data is a sequence of runs, where each run consists of + a length byte followed by 1 to 128 bytes of data. If the length byte is + in the range 0 to 127, + the following length + 1 (1 to 128) bytes are copied literally during + decompression. + If length is in the range 129 to 255, the following single byte is to be + copied 257 − length (2 to 128) times during decompression. A length value + of 128 denotes EOD. + """ + + @staticmethod + def decode( + data: bytes, + decode_parms: Optional[DictionaryObject] = None, + **kwargs: Any, + ) -> bytes: + """ + Decode a run length encoded data stream. + + Args: + data: a bytes sequence of length/data + decode_parms: this filter does not use parameters. + + Returns: + A bytes decompressed sequence. + + Raises: + PdfStreamError: + + """ + lst = [] + index = 0 + data_length = len(data) + total_length = 0 + while True: + if index >= data_length: + logger_warning( + "missing EOD in RunLengthDecode, check if output is OK", source=__name__ + ) + break # Reached end of string without an EOD + length = data[index] + index += 1 + if length == 128: + if index < data_length: + # We should first check, if we have an inner stream from a multi-encoded + # stream with a faulty trailing newline that we can decode properly. + # We will just ignore the last byte and raise a warning ... + if (index == data_length - 1) and (data[index : index + 1] == b"\n"): + logger_warning( + "Found trailing newline in stream data, check if output is OK", source=__name__ + ) + break + # Raising an exception here breaks all image extraction for this file, which might + # not be desirable. For this reason, indicate that the output is most likely wrong, + # as processing stopped after the first EOD marker. See issue #3517. + logger_warning( + "Early EOD in RunLengthDecode, check if output is OK", source=__name__ + ) + break + if length < 128: + length += 1 + lst.append(data[index : (index + length)]) + index += length + else: # >128 + if index >= data_length: + logger_warning( + "Missing EOD in RunLengthDecode, check if output is OK", source=__name__ + ) + break # Reached end of string without the replicated byte + length = 257 - length + lst.append(bytes((data[index],)) * length) + index += 1 + total_length += length + if total_length > RUN_LENGTH_MAX_OUTPUT_LENGTH: + raise LimitReachedError("Limit reached while decompressing.") + return b"".join(lst) + + +class LZWDecode: + class Decoder: + STOP = 257 + CLEARDICT = 256 + + def __init__(self, data: bytes) -> None: + self.data = data + + def decode(self) -> bytes: + return _LzwCodec(max_output_length=LZW_MAX_OUTPUT_LENGTH).decode(self.data) + + @staticmethod + def decode( + data: bytes, + decode_parms: Optional[DictionaryObject] = None, + **kwargs: Any, + ) -> bytes: + """ + Decode an LZW encoded data stream. + + Args: + data: ``bytes`` or ``str`` text to decode. + decode_parms: a dictionary of parameter values. + + Returns: + decoded data. + + """ + # decode_parms is unused here + return LZWDecode.Decoder(data).decode() + + +class ASCII85Decode: + """Decodes string ASCII85-encoded data into a byte format.""" + + @staticmethod + def decode( + data: Union[str, bytes], + decode_parms: Optional[DictionaryObject] = None, + **kwargs: Any, + ) -> bytes: + """ + Decode an Ascii85 encoded data stream. + + Args: + data: ``bytes`` or ``str`` text to decode. + decode_parms: this filter does not use parameters. + + Returns: + decoded data. + + """ + if isinstance(data, str): + data = data.encode() + data = data.strip(WHITESPACES_AS_BYTES) + if len(data) > 2 and data.endswith(b">"): + data = data[:-1].rstrip(WHITESPACES_AS_BYTES) + data[-1:] + try: + return a85decode(data, adobe=True, ignorechars=WHITESPACES_AS_BYTES) + except ValueError as error: + if error.args[0] == "Ascii85 encoded byte sequences must end with b'~>'": + logger_warning("Ignoring missing Ascii85 end marker.", source=__name__) + return a85decode(data, adobe=False, ignorechars=WHITESPACES_AS_BYTES) + raise + + +class DCTDecode: + @staticmethod + def decode( + data: bytes, + decode_parms: Optional[DictionaryObject] = None, + **kwargs: Any, + ) -> bytes: + """ + Decompresses data encoded using a DCT (discrete cosine transform) + technique based on the JPEG standard (IS0/IEC 10918), + reproducing image sample data that approximates the original data. + + Args: + data: text to decode. + decode_parms: this filter does not use parameters. + + Returns: + decoded data. + + """ + return data + + +class JPXDecode: + @staticmethod + def decode( + data: bytes, + decode_parms: Optional[DictionaryObject] = None, + **kwargs: Any, + ) -> bytes: + """ + Decompresses data encoded using the wavelet-based JPEG 2000 standard, + reproducing the original image data. + + Args: + data: text to decode. + decode_parms: this filter does not use parameters. + + Returns: + decoded data. + + """ + return data + + +@dataclass +class CCITTParameters: + """§7.4.6, optional parameters for the CCITTFaxDecode filter.""" + + K: int = 0 + columns: int = 1728 + rows: int = 0 + EndOfLine: Union[bool, None] = False + EncodedByteAlign: Union[bool, None] = False + EndOfBlock: Union[bool, None] = True + BlackIs1: bool = False + DamagedRowsBeforeError: Union[int, None] = 0 + + @property + def group(self) -> int: + if self.K < 0: + # Pure two-dimensional encoding (Group 4) + CCITTgroup = 4 + else: + # K == 0: Pure one-dimensional encoding (Group 3, 1-D) + # K > 0: Mixed one- and two-dimensional encoding (Group 3, 2-D) + CCITTgroup = 3 + return CCITTgroup + + +def __create_old_class_instance( + K: int = 0, + columns: int = 0, + rows: int = 0 +) -> NoReturn: + deprecation_with_replacement("CCITParameters", "CCITTParameters", "6.0.0") + + +# Create an alias for the old class name +CCITParameters = __create_old_class_instance + + +class CCITTFaxDecode: + """ + §7.4.6, CCITTFaxDecode filter (ISO 32000). + + Either Group 3 or Group 4 CCITT facsimile (fax) encoding. + CCITT encoding is bit-oriented, not byte-oriented. + + §7.4.6, optional parameters for the CCITTFaxDecode filter. + """ + + @staticmethod + def _get_parameters( + parameters: Union[ArrayObject, DictionaryObject, IndirectObject, None], + rows: Union[int, IndirectObject], + ) -> CCITTParameters: + ccitt_parameters = CCITTParameters(rows=int(rows)) + if parameters: + parameters_unwrapped = cast( + Union[ArrayObject, DictionaryObject], parameters.get_object() + ) + if isinstance(parameters_unwrapped, ArrayObject): + for decode_parm in parameters_unwrapped: + if CCITT.K in decode_parm: + ccitt_parameters.K = decode_parm[CCITT.K].get_object() + if CCITT.COLUMNS in decode_parm: + ccitt_parameters.columns = decode_parm[CCITT.COLUMNS].get_object() + if CCITT.BLACK_IS_1 in decode_parm: + ccitt_parameters.BlackIs1 = decode_parm[CCITT.BLACK_IS_1].get_object().value + else: + if CCITT.K in parameters_unwrapped: + ccitt_parameters.K = parameters_unwrapped[CCITT.K].get_object() # type: ignore[assignment] + if CCITT.COLUMNS in parameters_unwrapped: + ccitt_parameters.columns = parameters_unwrapped[CCITT.COLUMNS].get_object() # type: ignore[assignment] + if CCITT.BLACK_IS_1 in parameters_unwrapped: + ccitt_parameters.BlackIs1 = parameters_unwrapped[CCITT.BLACK_IS_1].get_object().value # type: ignore[union-attr] + return ccitt_parameters + + @staticmethod + def decode( + data: bytes, + decode_parms: Optional[DictionaryObject] = None, + height: int = 0, + **kwargs: Any, + ) -> bytes: + params = CCITTFaxDecode._get_parameters(decode_parms, height) + + img_size = len(data) + # TIFF SHORT and LONG fields are unsigned (TIFF 6.0, §2); pack them with + # unsigned codes so dimensions with the high bit set do not overflow. + tiff_header_struct = "<2sHLH" + "HHLL" * 8 + "H" + tiff_header = struct.pack( + tiff_header_struct, + b"II", # Byte order indication: Little endian + 42, # Version number (always 42) + 8, # Offset to the first image file directory (IFD) + 8, # Number of tags in IFD + 256, # ImageWidth, LONG, 1, width + 4, + 1, + params.columns, + 257, # ImageLength, LONG, 1, length + 4, + 1, + params.rows, + 258, # BitsPerSample, SHORT, 1, 1 + 3, + 1, + 1, + 259, # Compression, SHORT, 1, compression Type + 3, + 1, + params.group, + 262, # Thresholding, SHORT, 1, 0 = BlackIs1 + 3, + 1, + int(params.BlackIs1), + 273, # StripOffsets, LONG, 1, length of header + 4, + 1, + struct.calcsize( + tiff_header_struct + ), + 278, # RowsPerStrip, LONG, 1, length + 4, + 1, + params.rows, + 279, # StripByteCounts, LONG, 1, size of image + 4, + 1, + img_size, + 0, # last IFD + ) + + return tiff_header + data + + +JBIG2DEC_BINARY = shutil.which("jbig2dec") + + +class JBIG2Decode: + @staticmethod + def decode( + data: bytes, + decode_parms: Optional[DictionaryObject] = None, + **kwargs: Any, + ) -> bytes: + if JBIG2DEC_BINARY is None: + raise DependencyError("jbig2dec binary is not available.") + + with TemporaryDirectory() as tempdir: + directory = Path(tempdir) + paths: list[Path] = [] + + if decode_parms and "/JBIG2Globals" in decode_parms: + jbig2_globals = decode_parms["/JBIG2Globals"] + if not is_null_or_none(jbig2_globals) and not is_null_or_none(pointer := jbig2_globals.get_object()): + assert pointer is not None, "mypy" + if isinstance(pointer, StreamObject): + path = directory.joinpath("globals.jbig2") + path.write_bytes(pointer.get_data()) + paths.append(path) + + path = directory.joinpath("image.jbig2") + path.write_bytes(data) + paths.append(path) + + environment = os.environ.copy() + environment["LC_ALL"] = "C" + result = subprocess.run( # noqa: S603 + [ + JBIG2DEC_BINARY, + "--embedded", + "--format", "png", + "--output", "-", + "-M", str(JBIG2_MAX_OUTPUT_LENGTH), + *paths + ], + capture_output=True, + env=environment, + ) + if b"unrecognized option '--embedded'" in result.stderr or b"unrecognized option '-M'" in result.stderr: + raise DependencyError("jbig2dec>=0.19 is required.") + if b"FATAL ERROR failed to allocate image data buffer" in result.stderr: + raise LimitReachedError( + f"Memory limit reached while reading JBIG2 data:\n{result.stderr.decode('utf-8')}" + ) + if result.stderr: + for line in result.stderr.decode("utf-8").splitlines(): + logger_warning(line, source=__name__) + if result.returncode != 0: + raise PdfStreamError(f"Unable to decode JBIG2 data. Exit code: {result.returncode}") + return result.stdout + + @staticmethod + def _is_binary_compatible() -> bool: + if not JBIG2DEC_BINARY: # pragma: no cover + return False + result = subprocess.run( # noqa: S603 + [JBIG2DEC_BINARY, "--version"], + capture_output=True, + text=True, + ) + version = result.stdout.split(" ", maxsplit=1)[1] + + from ._utils import Version # noqa: PLC0415 + return Version(version) >= Version("0.19") + + +def _deprecate_inline_image_filters(filter_name: str, old_name: str, new_name: str) -> None: + if filter_name != old_name: + return + deprecate( + f"The filter name {old_name} is deprecated and will be removed in pypdf 7.0.0. Use {new_name} instead.", + 4, + ) + + +def decode_stream_data(stream: StreamObject) -> bytes: + """ + Decode the stream data based on the specified filters. + + This function decodes the stream data using the filters provided in the + stream. + + Args: + stream: The input stream object containing the data and filters. + + Returns: + The decoded stream data. + + Raises: + NotImplementedError: If an unsupported filter type is encountered. + + """ + filters = stream.get(StreamAttributes.FILTER, ()) + if isinstance(filters, IndirectObject): + filters = cast(ArrayObject, filters.get_object()) + if not isinstance(filters, ArrayObject): + # We have a single filter instance + filters = (filters,) + decode_parms = stream.get(StreamAttributes.DECODE_PARMS, ({},) * len(filters)) + if not isinstance(decode_parms, (list, tuple)): + decode_parms = (decode_parms,) + data: bytes = stream._data + # If there is no data to decode, we should not try to decode it. + if not data: + return data + for filter_name, params in zip(filters, decode_parms): + if isinstance(params, NullObject): + params = {} + if filter_name in (FT.ASCII_HEX_DECODE, FTA.AHx): + _deprecate_inline_image_filters(filter_name=filter_name, old_name=FTA.AHx, new_name=FT.ASCII_HEX_DECODE) + data = ASCIIHexDecode.decode(data) + elif filter_name in (FT.ASCII_85_DECODE, FTA.A85): + _deprecate_inline_image_filters(filter_name=filter_name, old_name=FTA.A85, new_name=FT.ASCII_85_DECODE) + data = ASCII85Decode.decode(data) + elif filter_name in (FT.LZW_DECODE, FTA.LZW): + _deprecate_inline_image_filters(filter_name=filter_name, old_name=FTA.LZW, new_name=FT.LZW_DECODE) + data = LZWDecode.decode(data, params) + elif filter_name in (FT.FLATE_DECODE, FTA.FL): + _deprecate_inline_image_filters(filter_name=filter_name, old_name=FTA.FL, new_name=FT.FLATE_DECODE) + data = FlateDecode.decode(data, params) + elif filter_name in (FT.RUN_LENGTH_DECODE, FTA.RL): + _deprecate_inline_image_filters(filter_name=filter_name, old_name=FTA.RL, new_name=FT.RUN_LENGTH_DECODE) + data = RunLengthDecode.decode(data) + elif filter_name in (FT.CCITT_FAX_DECODE, FTA.CCF): + _deprecate_inline_image_filters(filter_name=filter_name, old_name=FTA.CCF, new_name=FT.CCITT_FAX_DECODE) + height = stream.get(ImageAttributes.HEIGHT, ()) + data = CCITTFaxDecode.decode(data, params, height) + elif filter_name in (FT.DCT_DECODE, FTA.DCT): + _deprecate_inline_image_filters(filter_name=filter_name, old_name=FTA.DCT, new_name=FT.DCT_DECODE) + data = DCTDecode.decode(data) + elif filter_name == FT.JPX_DECODE: + data = JPXDecode.decode(data) + elif filter_name == FT.JBIG2_DECODE: + data = JBIG2Decode.decode(data, params) + elif filter_name == "/Crypt": + if "/Name" in params or "/Type" in params: + raise NotImplementedError( + "/Crypt filter with /Name or /Type not supported yet" + ) + else: + raise NotImplementedError(f"Unsupported filter {filter_name}") + return data diff --git a/.venv/lib/python3.13/site-packages/pypdf/generic/__init__.py b/.venv/lib/python3.13/site-packages/pypdf/generic/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bde1628fb7a02f9dab04666123c1f3d8bdeeb94b --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/generic/__init__.py @@ -0,0 +1,115 @@ +# Copyright (c) 2006, Mathieu Fenniak +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * The name of the author may not be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +"""Implementation of generic PDF objects (dictionary, number, string, ...).""" +__author__ = "Mathieu Fenniak" +__author_email__ = "biziqe@mathieu.fenniak.net" + +from ..constants import OutlineFontFlag +from ._base import ( + BooleanObject, + ByteStringObject, + FloatObject, + IndirectObject, + NameObject, + NullObject, + NumberObject, + PdfObject, + TextStringObject, + encode_pdfdocencoding, + is_null_or_none, +) +from ._data_structures import ( + ArrayObject, + ContentStream, + DecodedStreamObject, + Destination, + DictionaryObject, + EncodedStreamObject, + Field, + StreamObject, + TreeObject, + read_object, +) +from ._files import EmbeddedFile +from ._fit import Fit +from ._link import DirectReferenceLink, NamedReferenceLink, ReferenceLink, extract_links +from ._outline import OutlineItem +from ._rectangle import RectangleObject +from ._utils import ( + create_string_object, + decode_pdfdocencoding, + hex_to_rgb, + read_hex_string_from_stream, + read_string_from_stream, +) +from ._viewerpref import ViewerPreferences + +PAGE_FIT = Fit.fit() + + +__all__ = [ + "PAGE_FIT", + "ArrayObject", + "BooleanObject", + "ByteStringObject", + "ContentStream", + "DecodedStreamObject", + "Destination", + "DictionaryObject", + "DirectReferenceLink", + "EmbeddedFile", + "EncodedStreamObject", + "Field", + "Fit", + "FloatObject", + "IndirectObject", + "NameObject", + "NamedReferenceLink", + "NullObject", + "NumberObject", + "OutlineFontFlag", + "OutlineItem", + "PdfObject", + "RectangleObject", + "ReferenceLink", + "StreamObject", + "TextStringObject", + "TreeObject", + "ViewerPreferences", + # Utility functions + "create_string_object", + "decode_pdfdocencoding", + "encode_pdfdocencoding", + "extract_links", + "hex_to_rgb", + "is_null_or_none", + "read_hex_string_from_stream", + # Data structures core functions + "read_object", + "read_string_from_stream", +] diff --git a/.venv/lib/python3.13/site-packages/pypdf/generic/_appearance_stream.py b/.venv/lib/python3.13/site-packages/pypdf/generic/_appearance_stream.py new file mode 100644 index 0000000000000000000000000000000000000000..055715c886866945f90adcd006cc25d163913463 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/generic/_appearance_stream.py @@ -0,0 +1,752 @@ +from __future__ import annotations + +import re +from dataclasses import dataclass +from enum import IntEnum +from io import BytesIO +from operator import attrgetter +from typing import TYPE_CHECKING, Any, NamedTuple, cast + +from .._codecs import fill_from_encoding +from .._codecs.core_font_metrics import CORE_FONT_METRICS +from .._font import Font +from .._utils import is_char_rtl, logger_warning +from ..constants import AnnotationDictionaryAttributes, BorderStyles, FieldDictionaryAttributes, PageAttributes +from ..errors import PdfReadError +from ..generic import ( + DecodedStreamObject, + DictionaryObject, + IndirectObject, + NameObject, + NumberObject, + RectangleObject, +) +from ..generic._base import ByteStringObject, TextStringObject + +if TYPE_CHECKING: + from pypdf._writer import PdfWriter + + from .._page import PageObject + +try: + import arabic_reshaper + from bidi.algorithm import get_display + HAS_RTL_SUPPORT = True +except ImportError: + HAS_RTL_SUPPORT = False + +DEFAULT_FONT_SIZE_IN_MULTILINE = 12 + +# "The glyph widths shall be measured in units in which 1000 units correspond to 1 unit in text space" +# (Table 111, PDF Specification 2.0) +TEXT_SPACE_TO_GLYPH_SPACE_FACTOR = 1000 + + +@dataclass +class BaseStreamConfig: + """A container representing the basic layout of an appearance stream.""" + rectangle: RectangleObject | tuple[float, float, float, float] = (0.0, 0.0, 0.0, 0.0) + border_width: int = 1 # The width of the border in points + border_style: str = BorderStyles.SOLID + + +class BaseStreamAppearance(DecodedStreamObject): + """A class representing the very base of an appearance stream, that is, a rectangle and a border.""" + + def __init__(self, layout: BaseStreamConfig | None) -> None: + """ + Takes the appearance stream layout as an argument. + + Args: + layout: The basic layout parameters. + """ + super().__init__() + self._layout = layout or BaseStreamConfig() + self[NameObject("/Type")] = NameObject("/XObject") + self[NameObject("/Subtype")] = NameObject("/Form") + self[NameObject("/BBox")] = RectangleObject(self._layout.rectangle) + + +class TextAlignment(IntEnum): + """Defines the alignment options for text within a form field's appearance stream.""" + + LEFT = 0 + CENTER = 1 + RIGHT = 2 + + +class WidthWordGlyphs(NamedTuple): + """A tuple of the unscaled width of a word (unencoded text) and the font-encoded glyphs that represent it.""" + + width: float + word: str + glyphs: str + + +class TextStreamAppearance(BaseStreamAppearance): + """ + A class representing the appearance stream for a text-based form field. + + This class generates the content stream (the `ap_stream_data`) that dictates + how text is rendered within a form field's bounding box. It handles properties + like font, font size, color, multiline text, and text selection highlighting. + """ + + def _scale_text( + self, + font: Font, + font_size: float, + leading_factor: float, + field_width: float, + field_height: float, + paragraphs: list[list[WidthWordGlyphs]], + min_font_size: float, + font_size_step: float = 0.2 + ) -> tuple[list[WidthWordGlyphs], float]: + """ + Takes a piece of text and scales it to field_width or field_height, given font_name + and font_size. Wraps text where necessary. + + Args: + font: The font to be used. + font_size: The font size in points. + leading_factor: The line distance. + field_width: The width of the field in which to fit the text. + field_height: The height of the field in which to fit the text. + paragraphs: The list of text paragraphs to fit with the field, where each paragraph is a list + of tuples of unscaled width, unencoded text, and glyphs (font-encoded text). + min_font_size: The minimum font size at which to scale the text. + font_size_step: The amount by which to decrement font size per step while scaling. + + Returns: + The text in the form of list of tuples, each tuple containing the length of a line + and its contents, and the font_size for these lines and lengths. + """ + wrapped_lines = [] + current_line_words: list[WidthWordGlyphs] = [] + current_line_width: float = 0 + space_width = font.space_width * font_size / TEXT_SPACE_TO_GLYPH_SPACE_FACTOR + for paragraph in paragraphs: + for i, width_word_glyphs in enumerate(paragraph): + word_width = width_word_glyphs.width * font_size + test_width = current_line_width + word_width + (space_width if i else 0) + if test_width > field_width and current_line_words: + wrapped_lines.append( + WidthWordGlyphs( + width=current_line_width, + word=" ".join(map(attrgetter("word"), current_line_words)), + glyphs=font.space_char.join(map(attrgetter("glyphs"), current_line_words)) + ) + ) + current_line_words = [width_word_glyphs] + current_line_width = word_width + elif not current_line_words and word_width > field_width: + wrapped_lines.append( + WidthWordGlyphs( + width=word_width, + word=width_word_glyphs.word, + glyphs=width_word_glyphs.glyphs + ) + ) + current_line_words = [] + current_line_width = 0 + else: + if current_line_words: + current_line_width += space_width + current_line_words.append(width_word_glyphs) + current_line_width += word_width + if current_line_words: + wrapped_lines.append(WidthWordGlyphs( + width=current_line_width, + word=" ".join(map(attrgetter("word"), current_line_words)), + glyphs=font.space_char.join(map(attrgetter("glyphs"), current_line_words)) + )) + current_line_words = [] + current_line_width = 0 + # Estimate total height. + estimated_total_height = font_size + (len(wrapped_lines) - 1) * leading_factor * font_size + if estimated_total_height > field_height: + # Text overflows height; Retry with smaller font size. + new_font_size = font_size - font_size_step + if new_font_size >= min_font_size: + return self._scale_text( + font, + new_font_size, + leading_factor, + field_width, + field_height, + paragraphs, + min_font_size, + font_size_step + ) + return wrapped_lines, round(font_size, 1) + + def _generate_appearance_stream_data( + self, + text: str, + selection: list[str] | None , + font: Font, + font_name: str = "/Helv", + font_size: float = 0.0, + font_color: str = "0 g", + is_multiline: bool = False, + alignment: TextAlignment = TextAlignment.LEFT, + is_comb: bool = False, + max_length: int | None = None + ) -> bytes: + """ + Generates the raw bytes of the PDF appearance stream for a text field. + + This private method assembles the PDF content stream operators to draw + the provided text within the specified rectangle. It handles text positioning, + font application, color, and special formatting like selected text. + + Args: + text: The text to be rendered in the form field. + selection: An optional list of strings that should be highlighted as selected. + font: The font to use. + font_name: The name of the font resource to use (e.g., "/Helv"). + font_size: The font size. If 0, it is automatically calculated + based on whether the field is multiline or not. + font_color: The color to apply to the font, represented as a PDF + graphics state string (e.g., "0 g" for black). + is_multiline: A boolean indicating if the text field is multiline. + alignment: Text alignment, can be TextAlignment.LEFT, .RIGHT, or .CENTER. + is_comb: Boolean that designates fixed-length fields, where every character + fills one "cell", such as in a postcode. + max_length: Used if is_comb is set. The maximum number of characters for a fixed- + length field. + + Returns: + A byte string containing the PDF content stream data. + + """ + rectangle = self._layout.rectangle + if isinstance(rectangle, tuple): + rectangle = RectangleObject(rectangle) + leading_factor = ( + (font.font_descriptor.bbox[3] - font.font_descriptor.bbox[1]) / TEXT_SPACE_TO_GLYPH_SPACE_FACTOR + ) + + # Set margins based on border width and style, but never less than 1 point + factor = 2 if self._layout.border_style in {"/B", "/I"} else 1 + margin = max(self._layout.border_width * factor, 1) + field_height = rectangle.height - 2 * margin + field_width = rectangle.width - 4 * margin + + reverse_cmap, encoding_cmap = font._get_typographic_maps() + + def _unicode_to_glyph_id(text: str, reverse_cmap: dict[str, str]) -> str: + if HAS_RTL_SUPPORT: + # Use arabic-reshaper and python-bidi to rearrange and shape text for the PDF engine + reshaped_text = arabic_reshaper.reshape(text) + visual_text = get_display(reshaped_text, base_dir="L") + return "".join(reverse_cmap.get(char, char) for char in visual_text) + + return "".join(reverse_cmap.get(char, char) for char in text) + + + def _glyph_id_to_bytes(glyphs: str, encoding_cmap: dict[str, bytes]) -> list[bytes]: + return [encoding_cmap.get( + glyph_id, bytes((ord(glyph_id),)) if ord(glyph_id) < 256 else b"?" + ) for glyph_id in glyphs] + + # If font_size is 0, apply the logic for multiline or large-as-possible font + if font_size == 0: + min_font_size = 4.0 # The minimum font size + if selection: # Don't wrap text when dealing with a /Ch field, in order to prevent problems + is_multiline = False # with matching "selection" with "line" later on. + if is_multiline: + font_size = DEFAULT_FONT_SIZE_IN_MULTILINE + # We create a list of paragraphs, here each paragraph is a list of tuples, where each WidthWordGlyphs + # tuple signifies an unscaled word width, the word itself, and the glyphs that encode it. + paragraphs: list[list[WidthWordGlyphs]] = [] + for line in text.splitlines(): + if not line.strip(): + paragraphs.append([WidthWordGlyphs(width=0.0, word="", glyphs="")]) + continue + line_by_widths_words_glyphs: list[WidthWordGlyphs] = [] + words = line.split(" ") + for word in words: + glyph_word = _unicode_to_glyph_id(word, reverse_cmap) + line_by_widths_words_glyphs.append( + WidthWordGlyphs( + width=font.get_text_width(word) / TEXT_SPACE_TO_GLYPH_SPACE_FACTOR, + word=word, + glyphs=glyph_word + ) + ) + paragraphs.append(line_by_widths_words_glyphs) + lines, font_size = self._scale_text( + font, + font_size, + leading_factor, + field_width, + field_height, + paragraphs, + min_font_size + ) + else: + max_vertical_size = field_height / leading_factor + glyphs = _unicode_to_glyph_id(text, reverse_cmap) + text_width_unscaled = font.get_text_width(glyphs) / TEXT_SPACE_TO_GLYPH_SPACE_FACTOR + max_horizontal_size = field_width / (text_width_unscaled or 1) + font_size = round(max(min(max_vertical_size, max_horizontal_size), min_font_size), 1) + lines = [WidthWordGlyphs(width=text_width_unscaled * font_size, word=text, glyphs=glyphs)] + elif is_comb: + if max_length and len(text) > max_length: + logger_warning( + ( + "Length of text %(text)s exceeds maximum length (%(max_length)d) " + "of field, input truncated." + ), + source=__name__, + text=text, + max_length=max_length, + ) + # We act as if each character is one line, because we draw it separately later on + lines = [] + for index, char in enumerate(text): + if index < (max_length or len(text)): + glyphs = _unicode_to_glyph_id(char, reverse_cmap) + lines.append( + WidthWordGlyphs( + width=font.get_text_width(glyphs) * font_size / TEXT_SPACE_TO_GLYPH_SPACE_FACTOR, + word=char, + glyphs=glyphs + ) + ) + else: + lines = [] + for line in text.splitlines(): + glyphs = _unicode_to_glyph_id(line, reverse_cmap) + lines.append( + WidthWordGlyphs( + width=font.get_text_width(glyphs) * font_size / TEXT_SPACE_TO_GLYPH_SPACE_FACTOR, + word=line, + glyphs=glyphs + ) + ) + + # Set the vertical offset + if is_multiline: + y_offset = ( + rectangle.height + margin - font.font_descriptor.bbox[3] * font_size / TEXT_SPACE_TO_GLYPH_SPACE_FACTOR + ) + else: + y_offset = margin + ( + (field_height - font.font_descriptor.ascent * font_size / TEXT_SPACE_TO_GLYPH_SPACE_FACTOR) / 2 + ) + default_appearance = f"{font_name} {font_size} Tf {font_color}" + + ap_stream = ( + f"q\n/Tx BMC \nq\n{2 * margin} {margin} {field_width} {field_height} " + f"re\nW\nBT\n{default_appearance}\n" + ).encode() + current_x_pos: float = 0 # Initial virtual position within the text object. + + for line_number, (line_width, original_text, line) in enumerate(lines): + if selection and line in _unicode_to_glyph_id("".join(selection), reverse_cmap): + # Might be improved, but cannot find how to get fill working => replaced with lined box + ap_stream += ( + f"1 {y_offset - (line_number * font_size * leading_factor) - 1} " + f"{rectangle.width - 2} {font_size + 2} re\n" + f"0.5 0.5 0.5 rg s\n{default_appearance}\n" + ).encode() + + # Calculate the desired absolute starting X for the current line + desired_abs_x_start: float = 0 + if is_comb and max_length: + # Calculate the width of a cell for one character + cell_width = rectangle.width / max_length + # Space from the left edge of the cell to the character's baseline start + # line_width here is the *actual* character width in points for the single character 'line' + centering_offset_in_cell = (cell_width - line_width) / 2 + # Absolute start X = (Cell Index, i.e., line_number * Cell Width) + Centering Offset + desired_abs_x_start = (line_number * cell_width) + centering_offset_in_cell + elif alignment == TextAlignment.RIGHT: + desired_abs_x_start = rectangle.width - margin * 2 - line_width + elif alignment == TextAlignment.CENTER: + desired_abs_x_start = (rectangle.width - line_width) / 2 + else: # Left aligned; default + desired_abs_x_start = margin * 2 + # Calculate x_rel_offset: how much to move from the current_x_pos + # to reach the desired_abs_x_start. + x_rel_offset = desired_abs_x_start - current_x_pos + + # Y-offset: + y_rel_offset: float = 0 + if line_number == 0: + y_rel_offset = y_offset # Initial vertical position + elif is_comb: + y_rel_offset = 0.0 # DO NOT move vertically for subsequent characters + else: + y_rel_offset = - font_size * leading_factor # Move down by line height + + # Td is a relative translation (Tx and Ty). + # It updates the current text position. + ap_stream += f"{x_rel_offset} {y_rel_offset} Td\n".encode() + # Update current_x_pos based on the Td operation for the next iteration. + # This is the X position where the *current line* will start. + current_x_pos = desired_abs_x_start + + is_rtl = any(is_char_rtl(char) for char in line) + + encoded_line = _glyph_id_to_bytes(line, encoding_cmap) + if is_rtl: + # Encode input text as UTF-16BE with a BOM, so that the input text is returned + # in the right direction when copying text from the resulting PDF + bom_text = b"\xfe\xff" + original_text.encode("utf-16-be") + hex_original_text = bom_text.hex().upper() + ap_stream += f"/Span << /ActualText <{hex_original_text}> >> BDC\n".encode() + if any(len(c) >= 2 for c in encoded_line): + ap_stream += b"<" + (b"".join(encoded_line)).hex().encode() + b"> Tj\n" + else: + ap_stream += b"(" + b"".join(encoded_line) + b") Tj\n" + if is_rtl: + ap_stream += b"EMC\n" + ap_stream += b"ET\nQ\nEMC\nQ\n" + + return ap_stream + + def __init__( + self, + layout: BaseStreamConfig | None = None, + text: str = "", + selection: list[str] | None = None, + font: Font | None = None, + font_resource: DictionaryObject | IndirectObject | None = None, + font_name: str = "/Helv", + font_size: float = 0.0, + font_color: str = "0 g", + is_multiline: bool = False, + alignment: TextAlignment = TextAlignment.LEFT, + is_comb: bool = False, + max_length: int | None = None + ) -> None: + """ + Initializes a TextStreamAppearance object. + + This constructor creates a new PDF stream object configured as an XObject + of subtype Form. It uses the `_appearance_stream_data` method to generate + the content for the stream. + + Args: + layout: The basic layout parameters. + text: The text to be rendered in the form field. + selection: An optional list of strings that should be highlighted as selected. + font: A Font object. Falls back to Type 1 Helvetica if not given. + font_resource: An optional variable that represents a PDF font dictionary. Falls back + to Type 1 Helvetica if not given. + font_name: The name of the font resource, e.g., "/Helv". + font_size: The font size. If 0, it's auto-calculated. + font_color: The font color string. + is_multiline: A boolean indicating if the text field is multiline. + alignment: Text alignment, can be TextAlignment.LEFT, .RIGHT, or .CENTER. + is_comb: Boolean that designates fixed-length fields, where every character + fills one "cell", such as in a postcode. + max_length: Used if is_comb is set. The maximum number of characters for a fixed- + length field. + + """ + super().__init__(layout) + + if not font or not font_resource: + font_name = "/Helv" + core_font_metrics = CORE_FONT_METRICS["Helvetica"] + win_ansi_encoding_list = fill_from_encoding("cp1252") # WinAnsiEncoding + font = Font( + name="Helvetica", + character_map={}, + encoding=dict(zip(range(256), win_ansi_encoding_list)), + sub_type="Type1", + font_descriptor=core_font_metrics.font_descriptor, + character_widths={ + chr(code): core_font_metrics.character_widths[value] for code, value in enumerate( + win_ansi_encoding_list + ) if value in core_font_metrics.character_widths + }, + ) + font.character_widths["default"] = core_font_metrics.character_widths["default"] + font_resource = font.as_font_resource() + + ap_stream_data = self._generate_appearance_stream_data( + text, + selection, + font, + font_name=font_name, + font_size=font_size, + font_color=font_color, + is_multiline=is_multiline, + alignment=alignment, + is_comb=is_comb, + max_length=max_length + ) + + self.set_data(ByteStringObject(ap_stream_data)) + self[NameObject("/Length")] = NumberObject(len(ap_stream_data)) + # Update Resources with font information + self[NameObject("/Resources")] = DictionaryObject({ + NameObject("/Font"): DictionaryObject({ + NameObject(font_name): getattr(font_resource, "indirect_reference", font_resource) + }) + }) + + @staticmethod + def _find_annotation_font_resource( + font_name: str, + annotation: DictionaryObject, + acro_form: DictionaryObject, + text: str + ) -> tuple[str, Font]: + # Try to find a resource dictionary for the font by examining the annotation and, if that fails, + # the AcroForm resources dictionary + acro_form_resources: Any = cast( + DictionaryObject, + annotation.get_inherited( + "/DR", + acro_form.get("/DR", DictionaryObject()), + ), + ) + acro_form_font_resources = acro_form_resources.get("/Font", DictionaryObject()) + font_resource = acro_form_font_resources.get(font_name, None) + if font_resource: + font = Font.from_font_resource(font_resource) + else: + # Normally, we should have found a font resource by now. However, when a user has provided a specific + # font name, we may not have found the associated font resource among the AcroForm resources. Also, in + # case of the 14 Adobe Core fonts, we may be expected to construct a font resource ourselves. + if font_name.removeprefix("/") not in CORE_FONT_METRICS: + # Default to Helvetica if we haven't found a font resource and cannot construct one ourselves. + logger_warning( + "Font dictionary for %(font_name)s not found; defaulting to Helvetica.", + source=__name__, + font_name=font_name, + ) + font_name = "/Helvetica" + core_font_metrics = CORE_FONT_METRICS[font_name.removeprefix("/")] + font = Font( + name=font_name.removeprefix("/"), + character_map={}, + encoding=dict(zip(range(256), fill_from_encoding("cp1252"))), # WinAnsiEncoding + sub_type="Type1", + font_descriptor=core_font_metrics.font_descriptor, + character_widths=core_font_metrics.character_widths + ) + + # If we have found a font resource, it still might not be able to encode the text value we received. + encodable = font.can_encode(text) + + if not encodable: + # If we have a font file, we can try to produce a new font resource with an encoding + # that does include the necessary characters. + if font.font_descriptor.font_file and font.sub_type == "TrueType": + try: + font = font.from_truetype_font_file(BytesIO(font.font_descriptor.font_file.get_data())) + font_name = "/PYPDF1" # This means we most probably do not clash with an existing font name + encodable = font.can_encode(text) + except (ImportError, PdfReadError) as e: + logger_warning("Unable to use embedded font for encoding: %(e)s", source=__name__, e=e) + + if not encodable: + logger_warning( + ( + "Text string '%(text)s' contains characters not supported by font encoding. " + "This may result in text corruption. " + "Consider calling writer.update_page_form_field_values with auto_regenerate=True." + ), + source=__name__, + text=text, + ) + + return font_name, font + + @staticmethod + def _sync_appearance_stream_font_resources( + writer: PdfWriter, + font_name: str, + font: Font, + target_resource_dict: DictionaryObject, + page: PageObject | None = None + ) -> IndirectObject: + """ + Unified helper to sync fonts from an AP stream to a target resource dictionary (e.g., AcroForm /DR). + Will sync to page resources as well when page is added to the arguments. + """ + target_fonts = target_resource_dict.setdefault(NameObject("/Font"), DictionaryObject()).get_object() + if font_name not in target_fonts: + font_resource_reference = font._add_to_writer( + writer, + target_fonts, + NameObject(font_name) + ) + else: + font_resource_reference = target_fonts[font_name] + + if page: + page_fonts_resource = cast(DictionaryObject, page[PageAttributes.RESOURCES]).setdefault( + NameObject("/Font"), DictionaryObject() + ).get_object() + if font_name not in page_fonts_resource: + page_fonts_resource[NameObject(font_name)] = getattr( + font_resource_reference, "indirect_reference", font_resource_reference + ) + + return font_resource_reference + + @classmethod + def from_text_annotation( + cls, + writer: PdfWriter, + page: PageObject, + flatten: bool, + acro_form: DictionaryObject, # _root_object[CatalogDictionary.ACRO_FORM]) + field: DictionaryObject, + annotation: DictionaryObject, + user_font_name: str = "", + user_font_size: float = -1, + ) -> TextStreamAppearance: + """ + Creates a TextStreamAppearance object from a text field annotation. + + This class method is a factory for creating a `TextStreamAppearance` + instance by extracting all necessary information (bounding box, font, + text content, etc.) from the PDF field and annotation dictionaries. + It respects inheritance for properties like default appearance (`/DA`). + + Args: + writer: The PdfWriter instance that we are creating text stream appearances for. + page: The page that we are processing annotations for. + flatten: Whether we flatten text annotations or not. If true, add new font resource + to the page font resources. Otherwise, add them to the AcroForm resources. + acro_form: The root AcroForm dictionary from the PDF catalog. + field: The field dictionary object. + annotation: The widget annotation dictionary object associated with the field. + user_font_name: An optional user-provided font name to override the + default. Defaults to an empty string. + user_font_size: An optional user-provided font size to override the + default. A value of -1 indicates no override. + + Returns: + A new `TextStreamAppearance` instance configured for the given field. + + """ + # Calculate rectangle dimensions + _rectangle = cast(RectangleObject, annotation[AnnotationDictionaryAttributes.Rect]) + rectangle = RectangleObject((0, 0, abs(_rectangle[2] - _rectangle[0]), abs(_rectangle[3] - _rectangle[1]))) + + # Get default appearance dictionary from annotation + default_appearance = annotation.get_inherited( + AnnotationDictionaryAttributes.DA, + acro_form.get(AnnotationDictionaryAttributes.DA, None), + ) + if not default_appearance: + # Create a default appearance if none was found in the annotation + default_appearance = TextStringObject("/Helv 0 Tf 0 g") + else: + default_appearance = default_appearance.get_object() + + # Retrieve field text and selected values + field_flags = field.get(FieldDictionaryAttributes.Ff, 0) + if ( + field.get(FieldDictionaryAttributes.FT, "/Tx") == "/Ch" and + field_flags & FieldDictionaryAttributes.FfBits.Combo == 0 + ): + text = "\n".join(annotation.get_inherited(FieldDictionaryAttributes.Opt, [])) + selection = field.get("/V", []) + if not isinstance(selection, list): + selection = [selection] + else: # /Tx + text = field.get("/V", "") + selection = [] + + # Escape parentheses (PDF 1.7 reference, table 3.2, Literal Strings) + text = text.replace("\\", "\\\\").replace("(", r"\(").replace(")", r"\)") + + # Derive font name, size and color from the default appearance. Also set + # user-provided font name and font size in the default appearance, if given. + # For a font name, this presumes that we can find an associated font resource + # dictionary. Uses the variable font_properties as an intermediate. + # As per the PDF spec: + # "At a minimum, the string [that is, default_appearance] shall include a Tf (text + # font) operator along with its two operands, font and size" (Section 12.7.4.3 + # "Variable text" of the PDF 2.0 specification). + font_properties = [prop for prop in re.split(r"\s", default_appearance) if prop] + da_font_name = font_properties.pop(font_properties.index("Tf") - 2) + font_size = float(font_properties.pop(font_properties.index("Tf") - 1)) + font_properties.remove("Tf") + font_color = " ".join(font_properties) + # Determine the font name to use, prioritizing the user's input + if user_font_name: + font_name = user_font_name + else: + font_name = da_font_name + # Determine the font size to use, prioritizing the user's input + if user_font_size > 0: + font_size = user_font_size + + font_name, font = cls._find_annotation_font_resource(font_name, annotation, acro_form, text) + + # Change the /DA information if we changed the font name + if font_name != da_font_name: + annotation[NameObject("/DA")] = TextStringObject(default_appearance.replace(da_font_name, font_name)) + + # Synchronise font resources + font_resource_reference = cls._sync_appearance_stream_font_resources( + writer, + font_name, + font, + acro_form.setdefault(NameObject("/DR"), DictionaryObject()), + page if flatten else None, + ) + + # Retrieve formatting information + is_comb = False + max_length = None + if field_flags & FieldDictionaryAttributes.FfBits.Comb: + is_comb = True + max_length = annotation.get("/MaxLen") + is_multiline = False + if field_flags & FieldDictionaryAttributes.FfBits.Multiline: + is_multiline = True + alignment = field.get("/Q", TextAlignment.LEFT) + border_width = 1 + border_style = BorderStyles.SOLID + if "/BS" in field: + border_width = cast(DictionaryObject, field["/BS"]).get("/W", border_width) + border_style = cast(DictionaryObject, field["/BS"]).get("/S", border_style) + + # Create the TextStreamAppearance instance + layout = BaseStreamConfig(rectangle=rectangle, border_width=border_width, border_style=border_style) + new_appearance_stream = cls( + layout, + text, + selection, + font, + font_resource_reference, + font_name=font_name, + font_size=font_size, + font_color=font_color, + is_multiline=is_multiline, + alignment=alignment, + is_comb=is_comb, + max_length=max_length + ) + + if AnnotationDictionaryAttributes.AP in annotation: + for key, value in ( + cast(DictionaryObject, annotation[AnnotationDictionaryAttributes.AP]).get("/N", {}).items() + ): + if key in {"/BBox", "/Length", "/Subtype", "/Type", "/Filter"}: + continue + # Don't overwrite font resources added by TextAppearanceStream.__init__ + if key == "/Resources": + if "/Font" not in value: + value.get_object()[NameObject("/Font")] = DictionaryObject() + value["/Font"].get_object()[NameObject(font_name)] = getattr( + font_resource_reference, "indirect_reference", font_resource_reference + ) + else: + new_appearance_stream[key] = value + + return new_appearance_stream diff --git a/.venv/lib/python3.13/site-packages/pypdf/generic/_base.py b/.venv/lib/python3.13/site-packages/pypdf/generic/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..ab2d82295ea2258e8e58bb2e5b98c7dc567db936 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/generic/_base.py @@ -0,0 +1,960 @@ +# Copyright (c) 2006, Mathieu Fenniak +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * The name of the author may not be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +import binascii +import codecs +import hashlib +import re +import sys +from collections.abc import Sequence +from math import log10 +from struct import iter_unpack +from typing import Any, Callable, ClassVar, Optional, Union, cast + +if sys.version_info[:2] >= (3, 10): + from typing import TypeGuard +else: + from typing_extensions import TypeGuard # PEP 647 + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +from .._codecs import _pdfdoc_encoding_rev +from .._protocols import PdfObjectProtocol, PdfWriterProtocol +from .._utils import ( + StreamType, + classproperty, + deprecation_no_replacement, + deprecation_with_replacement, + logger_warning, + read_non_whitespace, + read_until_regex, +) +from ..errors import STREAM_TRUNCATED_PREMATURELY, PdfReadError, PdfStreamError + +__author__ = "Mathieu Fenniak" +__author_email__ = "biziqe@mathieu.fenniak.net" + + +class PdfObject(PdfObjectProtocol): + # function for calculating a hash value + hash_func: Callable[..., "hashlib._Hash"] = hashlib.sha1 + indirect_reference: Optional["IndirectObject"] + + def hash_bin(self) -> int: + """ + Used to detect modified object. + + Returns: + Hash considering type and value. + + """ + raise NotImplementedError( + f"{self.__class__.__name__} does not implement .hash_bin() so far" + ) + + def hash_value_data(self) -> bytes: + return f"{self}".encode() + + def hash_value(self) -> bytes: + return ( + f"{self.__class__.__name__}:" + f"{self.hash_func(self.hash_value_data()).hexdigest()}" + ).encode() + + def replicate( + self, + pdf_dest: PdfWriterProtocol, + ) -> "PdfObject": + """ + Clone object into pdf_dest (PdfWriterProtocol which is an interface for PdfWriter) + without ensuring links. This is used in clone_document_from_root with incremental = True. + + Args: + pdf_dest: Target to clone to. + + Returns: + The cloned PdfObject + + """ + return self.clone(pdf_dest) + + def clone( + self, + pdf_dest: PdfWriterProtocol, + force_duplicate: bool = False, + ignore_fields: Optional[Sequence[Union[str, int]]] = (), + ) -> "PdfObject": + """ + Clone object into pdf_dest (PdfWriterProtocol which is an interface for PdfWriter). + + By default, this method will call ``_reference_clone`` (see ``_reference``). + + + Args: + pdf_dest: Target to clone to. + force_duplicate: By default, if the object has already been cloned and referenced, + the copy will be returned; when ``True``, a new copy will be created. + (Default value = ``False``) + ignore_fields: List/tuple of field names (for dictionaries) that will be ignored + during cloning (applies to children duplication as well). If fields are to be + considered for a limited number of levels, you have to add it as integer, for + example ``[1,"/B","/TOTO"]`` means that ``"/B"`` will be ignored at the first + level only but ``"/TOTO"`` on all levels. + + Returns: + The cloned PdfObject + + """ + raise NotImplementedError( + f"{self.__class__.__name__} does not implement .clone so far" + ) + + def _reference_clone( + self, clone: "PdfObject", pdf_dest: PdfWriterProtocol, force_duplicate: bool = False + ) -> "PdfObject": + """ + Reference the object within the _objects of pdf_dest only if + indirect_reference attribute exists (which means the objects was + already identified in xref/xobjstm) if object has been already + referenced do nothing. + + Args: + clone: + pdf_dest: + + Returns: + The clone + + """ + try: + if ( + not force_duplicate + and clone.indirect_reference is not None + and clone.indirect_reference.pdf == pdf_dest + ): + return clone + except Exception: + pass + # if hasattr(clone, "indirect_reference"): + try: + ind = self.indirect_reference + except AttributeError: + return clone + if ( + pdf_dest.incremental + and ind is not None + and ind.pdf == pdf_dest._reader + and ind.idnum <= len(pdf_dest._objects) + ): + i = ind.idnum + else: + i = len(pdf_dest._objects) + 1 + if ind is not None: + if id(ind.pdf) not in pdf_dest._id_translated: + pdf_dest._id_translated[id(ind.pdf)] = {} + pdf_dest._id_translated[id(ind.pdf)]["PreventGC"] = ind.pdf # type: ignore[index] + if ( + not force_duplicate + and ind.idnum in pdf_dest._id_translated[id(ind.pdf)] + ): + obj = pdf_dest.get_object( + pdf_dest._id_translated[id(ind.pdf)][ind.idnum] + ) + assert isinstance(obj, PdfObject), "mypy" + return obj + pdf_dest._id_translated[id(ind.pdf)][ind.idnum] = i + try: + pdf_dest._objects[i - 1] = clone + except IndexError: + pdf_dest._objects.append(clone) + i = len(pdf_dest._objects) + clone.indirect_reference = IndirectObject(i, 0, pdf_dest) + return clone + + def get_object(self) -> Optional["PdfObject"]: + """Resolve indirect references.""" + return self + + def write_to_stream( + self, stream: StreamType, encryption_key: Union[str, bytes, None] = None + ) -> None: + raise NotImplementedError + + +class NullObject(PdfObject): + def clone( + self, + pdf_dest: PdfWriterProtocol, + force_duplicate: bool = False, + ignore_fields: Optional[Sequence[Union[str, int]]] = (), + ) -> "NullObject": + """Clone object into pdf_dest.""" + return cast( + "NullObject", self._reference_clone(NullObject(), pdf_dest, force_duplicate) + ) + + def hash_bin(self) -> int: + """ + Used to detect modified object. + + Returns: + Hash considering type and value. + + """ + return hash((self.__class__,)) + + def write_to_stream( + self, stream: StreamType, encryption_key: Union[str, bytes, None] = None + ) -> None: + if encryption_key is not None: # deprecated + deprecation_no_replacement( + "the encryption_key parameter of write_to_stream", "5.0.0" + ) + stream.write(b"null") + + @staticmethod + def read_from_stream(stream: StreamType) -> "NullObject": + nulltxt = stream.read(4) + if nulltxt != b"null": + raise PdfReadError("Could not read Null object") + return NullObject() + + def __repr__(self) -> str: + return "NullObject" + + def __eq__(self, other: object) -> bool: + return isinstance(other, NullObject) + + def __hash__(self) -> int: + return self.hash_bin() + + +class BooleanObject(PdfObject): + value: bool + + def __init__(self, value: Any) -> None: + self.value = value + + def clone( + self, + pdf_dest: PdfWriterProtocol, + force_duplicate: bool = False, + ignore_fields: Optional[Sequence[Union[str, int]]] = (), + ) -> "BooleanObject": + """Clone object into pdf_dest.""" + return cast( + "BooleanObject", + self._reference_clone(BooleanObject(self.value), pdf_dest, force_duplicate), + ) + + def hash_bin(self) -> int: + """ + Used to detect modified object. + + Returns: + Hash considering type and value. + + """ + return hash((self.__class__, self.value)) + + def __eq__(self, o: object, /) -> bool: + if isinstance(o, BooleanObject): + return self.value == o.value + if isinstance(o, bool): + return self.value == o + return False + + def __hash__(self) -> int: + return self.hash_bin() + + def __repr__(self) -> str: + return "True" if self.value else "False" + + def write_to_stream( + self, stream: StreamType, encryption_key: Union[str, bytes, None] = None + ) -> None: + if encryption_key is not None: # deprecated + deprecation_no_replacement( + "the encryption_key parameter of write_to_stream", "5.0.0" + ) + if self.value: + stream.write(b"true") + else: + stream.write(b"false") + + @staticmethod + def read_from_stream(stream: StreamType) -> "BooleanObject": + word = stream.read(4) + if word == b"true": + return BooleanObject(True) + if word == b"fals": + stream.read(1) + return BooleanObject(False) + raise PdfReadError("Could not read Boolean object") + + +class IndirectObject(PdfObject): + def __init__(self, idnum: int, generation: int, pdf: Any) -> None: # PdfReader + self.idnum = idnum + self.generation = generation + self.pdf = pdf + + def __hash__(self) -> int: + return hash((self.idnum, self.generation, id(self.pdf))) + + def hash_bin(self) -> int: + """ + Used to detect modified object. + + Returns: + Hash considering type and value. + + """ + return hash((self.__class__, self.idnum, self.generation, id(self.pdf))) + + def replicate( + self, + pdf_dest: PdfWriterProtocol, + ) -> "PdfObject": + return IndirectObject(self.idnum, self.generation, pdf_dest) + + def clone( + self, + pdf_dest: PdfWriterProtocol, + force_duplicate: bool = False, + ignore_fields: Optional[Sequence[Union[str, int]]] = (), + ) -> "IndirectObject": + """Clone object into pdf_dest.""" + if self.pdf == pdf_dest and not force_duplicate: + # Already duplicated and no extra duplication required + return self + if id(self.pdf) not in pdf_dest._id_translated: + pdf_dest._id_translated[id(self.pdf)] = {} + pdf_dest._id_translated[id(self.pdf)]["PreventGC"] = self.pdf # type: ignore[index] + + if self.idnum in pdf_dest._id_translated[id(self.pdf)]: + dup = pdf_dest.get_object(pdf_dest._id_translated[id(self.pdf)][self.idnum]) + if force_duplicate: + assert dup is not None + assert dup.indirect_reference is not None + idref = dup.indirect_reference + return IndirectObject(idref.idnum, idref.generation, idref.pdf) + else: + obj = self.get_object() + # case observed : a pointed object can not be found + if obj is None: + # this normally + obj = NullObject() + assert isinstance(self, (IndirectObject,)) + obj.indirect_reference = self + dup = pdf_dest._add_object( + obj.clone(pdf_dest, force_duplicate, ignore_fields) + ) + assert isinstance(dup, PdfObject), "mypy" + assert dup.indirect_reference is not None, "mypy" + return dup.indirect_reference + + @property + def indirect_reference(self) -> "IndirectObject": # type: ignore[override] + return self + + def get_object(self) -> Optional["PdfObject"]: + obj: Optional[PdfObject] = self.pdf.get_object(self) + return obj + + def __deepcopy__(self, memo: Any) -> "IndirectObject": + return IndirectObject(self.idnum, self.generation, self.pdf) + + def _get_object_with_check(self) -> Optional["PdfObject"]: + o = self.get_object() + # the check is done here to not slow down get_object() + if isinstance(o, IndirectObject): + raise PdfStreamError( + f"{self.__repr__()} references an IndirectObject {o.__repr__()}" + ) + return o + + def __getattr__(self, name: str) -> Any: + # Attribute not found in object: look in pointed object + try: + return getattr(self._get_object_with_check(), name) + except AttributeError: + raise AttributeError( + f"No attribute {name} found in IndirectObject or pointed object" + ) + + def __getitem__(self, key: Any) -> Any: + # items should be extracted from pointed Object + return self._get_object_with_check()[key] # type: ignore[index] + + def __contains__(self, key: Any) -> bool: + return key in self._get_object_with_check() # type: ignore[operator] + + def __iter__(self) -> Any: + return self._get_object_with_check().__iter__() # type: ignore[union-attr] + + def __float__(self) -> str: + # in this case we are looking for the pointed data + return self.get_object().__float__() # type: ignore[union-attr, no-any-return] + + def __int__(self) -> int: + # in this case we are looking for the pointed data + return self.get_object().__int__() # type: ignore[union-attr, no-any-return] + + def __str__(self) -> str: + # in this case we are looking for the pointed data + return self.get_object().__str__() + + def __repr__(self) -> str: + return f"IndirectObject({self.idnum!r}, {self.generation!r}, {id(self.pdf)})" + + def __eq__(self, other: object) -> bool: + return ( + other is not None + and isinstance(other, IndirectObject) + and self.idnum == other.idnum + and self.generation == other.generation + and self.pdf is other.pdf + ) + + def __ne__(self, other: object) -> bool: + return not self.__eq__(other) + + def write_to_stream( + self, stream: StreamType, encryption_key: Union[str, bytes, None] = None + ) -> None: + if encryption_key is not None: # deprecated + deprecation_no_replacement( + "the encryption_key parameter of write_to_stream", "5.0.0" + ) + stream.write(f"{self.idnum} {self.generation} R".encode()) + + @staticmethod + def read_from_stream(stream: StreamType, pdf: Any) -> "IndirectObject": # PdfReader + idnum = b"" + while True: + tok = stream.read(1) + if not tok: + raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY) + if tok.isspace(): + break + idnum += tok + generation = b"" + while True: + tok = stream.read(1) + if not tok: + raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY) + if tok.isspace(): + if not generation: + continue + break + generation += tok + r = read_non_whitespace(stream) + if r != b"R": + raise PdfReadError( + f"Error reading indirect object reference at byte {hex(stream.tell())}" + ) + return IndirectObject(int(idnum), int(generation), pdf) + + +FLOAT_WRITE_PRECISION = 8 # shall be min 5 digits max, allow user adj + + +class FloatObject(float, PdfObject): + def __new__( + cls, value: Any = "0.0", context: Optional[Any] = None + ) -> Self: + try: + value = float(value) + return float.__new__(cls, value) + except Exception as e: + # If this isn't a valid decimal (happens in malformed PDFs) + # fallback to 0 + logger_warning( + "%(error)s : FloatObject (%(value)s) invalid; use 0.0 instead", + source=__name__, + error=e, + value=value, + ) + return float.__new__(cls, 0.0) + + def clone( + self, + pdf_dest: Any, + force_duplicate: bool = False, + ignore_fields: Optional[Sequence[Union[str, int]]] = (), + ) -> "FloatObject": + """Clone object into pdf_dest.""" + return cast( + "FloatObject", + self._reference_clone(FloatObject(self), pdf_dest, force_duplicate), + ) + + def hash_bin(self) -> int: + """ + Used to detect modified object. + + Returns: + Hash considering type and value. + + """ + return hash((self.__class__, self.as_numeric)) + + def myrepr(self) -> str: + if self == 0: # type: ignore[comparison-overlap] + return "0.0" + nb = FLOAT_WRITE_PRECISION - int(log10(abs(self))) + return f"{self:.{max(1, nb)}f}".rstrip("0").rstrip(".") + + def __repr__(self) -> str: + return self.myrepr() # repr(float(self)) + + def as_numeric(self) -> float: + return float(self) + + def write_to_stream( + self, stream: StreamType, encryption_key: Union[str, bytes, None] = None + ) -> None: + if encryption_key is not None: # deprecated + deprecation_no_replacement( + "the encryption_key parameter of write_to_stream", "5.0.0" + ) + stream.write(self.myrepr().encode("utf8")) + + +class NumberObject(int, PdfObject): + NumberPattern = re.compile(b"[^+-.0-9]") + _LENGTH_LIMIT = 64 + + def __new__(cls, value: Any) -> Self: + try: + return int.__new__(cls, int(value)) + except ValueError: + logger_warning("NumberObject(%(value)s) invalid; use 0 instead", source=__name__, value=value) + return int.__new__(cls, 0) + + def clone( + self, + pdf_dest: Any, + force_duplicate: bool = False, + ignore_fields: Optional[Sequence[Union[str, int]]] = (), + ) -> "NumberObject": + """Clone object into pdf_dest.""" + return cast( + "NumberObject", + self._reference_clone(NumberObject(self), pdf_dest, force_duplicate), + ) + + def hash_bin(self) -> int: + """ + Used to detect modified object. + + Returns: + Hash considering type and value. + + """ + return hash((self.__class__, self.as_numeric())) + + def as_numeric(self) -> int: + return int(repr(self).encode("utf8")) + + def write_to_stream( + self, stream: StreamType, encryption_key: Union[str, bytes, None] = None + ) -> None: + if encryption_key is not None: # deprecated + deprecation_no_replacement( + "the encryption_key parameter of write_to_stream", "5.0.0" + ) + stream.write(repr(self).encode("utf8")) + + @staticmethod + def read_from_stream(stream: StreamType) -> Union["NumberObject", "FloatObject"]: + num = read_until_regex(stream=stream, regex=NumberObject.NumberPattern, length=NumberObject._LENGTH_LIMIT) + if b"." in num: + return FloatObject(num) + return NumberObject(num) + + +class ByteStringObject(bytes, PdfObject): + """ + Represents a string object where the text encoding could not be determined. + + This occurs quite often, as the PDF spec doesn't provide an alternate way to + represent strings -- for example, the encryption data stored in files (like + /O) is clearly not text, but is still stored in a "String" object. + """ + + def clone( + self, + pdf_dest: Any, + force_duplicate: bool = False, + ignore_fields: Optional[Sequence[Union[str, int]]] = (), + ) -> "ByteStringObject": + """Clone object into pdf_dest.""" + return cast( + "ByteStringObject", + self._reference_clone( + ByteStringObject(bytes(self)), pdf_dest, force_duplicate + ), + ) + + def hash_bin(self) -> int: + """ + Used to detect modified object. + + Returns: + Hash considering type and value. + + """ + return hash((self.__class__, bytes(self))) + + @property + def original_bytes(self) -> bytes: + """For compatibility with TextStringObject.original_bytes.""" + return self + + def write_to_stream( + self, stream: StreamType, encryption_key: Union[str, bytes, None] = None + ) -> None: + if encryption_key is not None: # deprecated + deprecation_no_replacement( + "the encryption_key parameter of write_to_stream", "5.0.0" + ) + stream.write(b"<") + stream.write(binascii.hexlify(self)) + stream.write(b">") + + def __str__(self) -> str: + charset_to_try = ["utf-16", *list(NameObject.CHARSETS)] + for enc in charset_to_try: + try: + return self.decode(enc) + except UnicodeDecodeError: + pass + raise PdfReadError("Cannot decode ByteStringObject.") + + +class TextStringObject(str, PdfObject): # noqa: SLOT000 + """ + A string object that has been decoded into a real unicode string. + + If read from a PDF document, this string appeared to match the + PDFDocEncoding, or contained a UTF-16BE BOM mark to cause UTF-16 decoding + to occur. + """ + + autodetect_pdfdocencoding: bool + autodetect_utf16: bool + utf16_bom: bytes + _original_bytes: Optional[bytes] = None + + def __new__(cls, value: Any) -> Self: + original_bytes = None + if isinstance(value, bytes): + original_bytes = value + value = value.decode("charmap") + text_string_object = str.__new__(cls, value) + text_string_object._original_bytes = original_bytes + text_string_object.autodetect_utf16 = False + text_string_object.autodetect_pdfdocencoding = False + text_string_object.utf16_bom = b"" + if original_bytes is not None and original_bytes[:2] in {codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE}: + # The value of `original_bytes` is only set for inputs being `bytes`. + # If this is UTF-16 data according to the BOM (first two characters), + # perform special handling. All other cases should not need any special conversion + # due to already being a string. + try: + text_string_object = str.__new__(cls, original_bytes.decode("utf-16")) + except UnicodeDecodeError as exception: + logger_warning( + "%(exception)s; initial string: %(initial_string)r", + source=__name__, + exception=exception, + initial_string=exception.object, + ) + text_string_object = str.__new__(cls, exception.object[: exception.start].decode("utf-16")) + text_string_object._original_bytes = original_bytes + text_string_object.autodetect_utf16 = True + text_string_object.utf16_bom = original_bytes[:2] + else: + try: + encode_pdfdocencoding(text_string_object) + text_string_object.autodetect_pdfdocencoding = True + except UnicodeEncodeError: + text_string_object.autodetect_utf16 = True + text_string_object.utf16_bom = codecs.BOM_UTF16_BE + return text_string_object + + def clone( + self, + pdf_dest: Any, + force_duplicate: bool = False, + ignore_fields: Optional[Sequence[Union[str, int]]] = (), + ) -> "TextStringObject": + """Clone object into pdf_dest.""" + obj = TextStringObject(self) + obj._original_bytes = self._original_bytes + obj.autodetect_pdfdocencoding = self.autodetect_pdfdocencoding + obj.autodetect_utf16 = self.autodetect_utf16 + obj.utf16_bom = self.utf16_bom + return cast( + "TextStringObject", self._reference_clone(obj, pdf_dest, force_duplicate) + ) + + def hash_bin(self) -> int: + """ + Used to detect modified object. + + Returns: + Hash considering type and value. + + """ + return hash((self.__class__, self.original_bytes)) + + @property + def original_bytes(self) -> bytes: + """ + It is occasionally possible that a text string object gets created where + a byte string object was expected due to the autodetection mechanism -- + if that occurs, this "original_bytes" property can be used to + back-calculate what the original encoded bytes were. + """ + if self._original_bytes is not None: + return self._original_bytes + return self.get_original_bytes() + + def get_original_bytes(self) -> bytes: + # We're a text string object, but the library is trying to get our raw + # bytes. This can happen if we auto-detected this string as text, but + # we were wrong. It's pretty common. Return the original bytes that + # would have been used to create this object, based upon the autodetect + # method. + if self.autodetect_utf16: + if self.utf16_bom == codecs.BOM_UTF16_LE: + return codecs.BOM_UTF16_LE + self.encode("utf-16le") + if self.utf16_bom == codecs.BOM_UTF16_BE: + return codecs.BOM_UTF16_BE + self.encode("utf-16be") + return self.encode("utf-16be") + if self.autodetect_pdfdocencoding: + return encode_pdfdocencoding(self) + raise Exception("no information about original bytes") # pragma: no cover + + def get_encoded_bytes(self) -> bytes: + # Try to write the string out as a PDFDocEncoding encoded string. It's + # nicer to look at in the PDF file. Sadly, we take a performance hit + # here for trying... + try: + if self._original_bytes is not None: + return self._original_bytes + if self.autodetect_utf16: + raise UnicodeEncodeError("", "forced", -1, -1, "") + bytearr = encode_pdfdocencoding(self) + except UnicodeEncodeError: + if self.utf16_bom == codecs.BOM_UTF16_LE: + bytearr = codecs.BOM_UTF16_LE + self.encode("utf-16le") + elif self.utf16_bom == codecs.BOM_UTF16_BE: + bytearr = codecs.BOM_UTF16_BE + self.encode("utf-16be") + else: + bytearr = self.encode("utf-16be") + return bytearr + + def write_to_stream( + self, stream: StreamType, encryption_key: Union[str, bytes, None] = None + ) -> None: + if encryption_key is not None: # deprecated + deprecation_no_replacement( + "the encryption_key parameter of write_to_stream", "5.0.0" + ) + bytearr = self.get_encoded_bytes() + stream.write(b"(") + for c_ in iter_unpack("c", bytearr): + c = cast(bytes, c_[0]) + if not c.isalnum() and c != b" ": + # This: + # stream.write(rf"\{c:0>3o}".encode()) + # gives + # https://github.com/davidhalter/parso/issues/207 + stream.write(b"\\%03o" % ord(c)) + else: + stream.write(c) + stream.write(b")") + + +class NameObject(str, PdfObject): # noqa: SLOT000 + delimiter_pattern = re.compile(rb"\s+|[\(\)<>\[\]{}/%]") + prefix = b"/" + renumber_table: ClassVar[dict[str, bytes]] = { + **{chr(i): f"#{i:02X}".encode() for i in b"#()<>[]{}/%"}, + **{chr(i): f"#{i:02X}".encode() for i in range(33)}, + } + _LENGTH_LIMIT = 4096 + + def clone( + self, + pdf_dest: Any, + force_duplicate: bool = False, + ignore_fields: Optional[Sequence[Union[str, int]]] = (), + ) -> "NameObject": + """Clone object into pdf_dest.""" + return cast( + "NameObject", + self._reference_clone(NameObject(self), pdf_dest, force_duplicate), + ) + + def hash_bin(self) -> int: + """ + Used to detect modified object. + + Returns: + Hash considering type and value. + + """ + return hash((self.__class__, self)) + + def write_to_stream( + self, stream: StreamType, encryption_key: Union[str, bytes, None] = None + ) -> None: + if encryption_key is not None: # deprecated + deprecation_no_replacement( + "the encryption_key parameter of write_to_stream", "5.0.0" + ) + stream.write(self.renumber()) + + def renumber(self) -> bytes: + out = self[0].encode("utf-8") + if out != b"/": + deprecation_no_replacement( + f"Incorrect first char in NameObject, should start with '/': ({self})", + "5.0.0", + ) + parts = [out] + for c in self[1:]: + if c > "~": + parts.extend(f"#{x:02X}".encode() for x in c.encode("utf-8")) + else: + try: + parts.append(self.renumber_table[c]) + except KeyError: + parts.append(c.encode("utf-8")) + return b"".join(parts) + + def _sanitize(self) -> "NameObject": + """ + Sanitize the NameObject's name to be a valid PDF name part + (alphanumeric, underscore, hyphen). The _sanitize method replaces + spaces and any non-alphanumeric/non-underscore/non-hyphen with + underscores. + + Returns: + NameObject with sanitized name. + """ + name = str(self).removeprefix("/") + name = re.sub(r" ", "_", name) + name = re.sub(r"[^a-zA-Z0-9_-]", "_", name) + return NameObject("/" + name) + + @classproperty + def surfix(cls) -> bytes: # noqa: N805 + deprecation_with_replacement("surfix", "prefix", "5.0.0") + return b"/" + + @staticmethod + def unnumber(sin: bytes) -> bytes: + result = bytearray() + i = 0 + while i < len(sin): + if sin[i:i + 1] == b"#": + try: + result.append(int(sin[i + 1 : i + 3], 16)) + i += 3 + continue + except (ValueError, IndexError): + # if the 2 characters after # can not be converted to hex + # we change nothing and carry on + pass + result.append(sin[i]) + i += 1 + return bytes(result) + + CHARSETS = ("utf-8", "gbk", "latin1") + + @staticmethod + def read_from_stream(stream: StreamType, pdf: Any) -> "NameObject": # PdfReader + name = stream.read(1) + if name != NameObject.prefix: + raise PdfReadError("Name read error") + name += read_until_regex(stream=stream, regex=NameObject.delimiter_pattern, length=NameObject._LENGTH_LIMIT) + try: + # Name objects should represent irregular characters + # with a '#' followed by the symbol's hex number + name = NameObject.unnumber(name) + for enc in NameObject.CHARSETS: + try: + ret = name.decode(enc) + return NameObject(ret) + except Exception: + pass + raise UnicodeDecodeError("", name, 0, 0, "Code Not Found") + except (UnicodeEncodeError, UnicodeDecodeError) as e: + if not pdf.strict: + logger_warning( + "Illegal character in NameObject (%(name)r), you may need to adjust NameObject.CHARSETS", + source=__name__, + name=name, + ) + return NameObject(name.decode("charmap")) + raise PdfReadError( + f"Illegal character in NameObject ({name!r}). " + "You may need to adjust NameObject.CHARSETS.", + ) from e + + +def encode_pdfdocencoding(unicode_string: str) -> bytes: + try: + return bytes([_pdfdoc_encoding_rev[k] for k in unicode_string]) + except KeyError: + raise UnicodeEncodeError( + "pdfdocencoding", + unicode_string, + -1, + -1, + "does not exist in translation table", + ) + + +def is_null_or_none(x: Any) -> TypeGuard[Union[NullObject, IndirectObject, None]]: + """ + Returns: + True if x is None or NullObject. + + """ + return x is None or ( + isinstance(x, PdfObject) + and (x.get_object() is None or isinstance(x.get_object(), NullObject)) + ) diff --git a/.venv/lib/python3.13/site-packages/pypdf/generic/_data_structures.py b/.venv/lib/python3.13/site-packages/pypdf/generic/_data_structures.py new file mode 100644 index 0000000000000000000000000000000000000000..d703e6641c975ac87eda65ab02c6334be94d3e0a --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/generic/_data_structures.py @@ -0,0 +1,1874 @@ +# Copyright (c) 2006, Mathieu Fenniak +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * The name of the author may not be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + + +__author__ = "Mathieu Fenniak" +__author_email__ = "biziqe@mathieu.fenniak.net" + +import logging +import os +import re +import sys +from collections.abc import Iterable, Sequence +from io import BytesIO +from math import ceil +from typing import ( + Any, + Callable, + Optional, + Union, + cast, +) + +from .._protocols import PdfReaderProtocol, PdfWriterProtocol, XmpInformationProtocol +from .._utils import ( + WHITESPACES, + BinaryStreamType, + StreamType, + deprecation_no_replacement, + logger_warning, + read_non_whitespace, + read_until_regex, + read_until_whitespace, + skip_over_comment, +) +from ..constants import ( + CheckboxRadioButtonAttributes, + FieldDictionaryAttributes, + OutlineFontFlag, + StreamAttributes, +) +from ..constants import FilterTypes as FT +from ..constants import TypArguments as TA +from ..constants import TypFitArguments as TF +from ..errors import STREAM_TRUNCATED_PREMATURELY, LimitReachedError, PdfReadError, PdfStreamError +from ._base import ( + BooleanObject, + ByteStringObject, + FloatObject, + IndirectObject, + NameObject, + NullObject, + NumberObject, + PdfObject, + TextStringObject, + is_null_or_none, +) +from ._fit import Fit +from ._image_inline import ( + extract_inline__ascii85_decode, + extract_inline__ascii_hex_decode, + extract_inline__dct_decode, + extract_inline__run_length_decode, + extract_inline_default, +) +from ._utils import read_hex_string_from_stream, read_string_from_stream + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +logger = logging.getLogger(__name__) + +IndirectPattern = re.compile(rb"[+-]?(\d+)\s+(\d+)\s+R[^a-zA-Z]") + + +class ArrayObject(list[Any], PdfObject): + def replicate( + self, + pdf_dest: PdfWriterProtocol, + ) -> "ArrayObject": + arr = cast( + "ArrayObject", + self._reference_clone(ArrayObject(), pdf_dest, False), + ) + for data in self: + if hasattr(data, "replicate"): + arr.append(data.replicate(pdf_dest)) + else: + arr.append(data) + return arr + + def clone( + self, + pdf_dest: PdfWriterProtocol, + force_duplicate: bool = False, + ignore_fields: Optional[Sequence[Union[str, int]]] = (), + ) -> "ArrayObject": + """Clone object into pdf_dest.""" + try: + if self.indirect_reference.pdf == pdf_dest and not force_duplicate: # type: ignore[union-attr] + return self + except Exception: + pass + arr = cast( + "ArrayObject", + self._reference_clone(ArrayObject(), pdf_dest, force_duplicate=True), + ) + for data in self: + if isinstance(data, StreamObject): + dup = data._reference_clone( + data.clone(pdf_dest, force_duplicate, ignore_fields), + pdf_dest, + force_duplicate, + ) + arr.append(dup.indirect_reference) + elif isinstance(data, IndirectObject) and isinstance(resolved := data.get_object(), StreamObject): + dup = data._reference_clone( + resolved.clone(pdf_dest, force_duplicate=True, ignore_fields=ignore_fields), + pdf_dest, + force_duplicate, + ) + arr.append(dup.indirect_reference) + elif hasattr(data, "clone"): + arr.append(data.clone(pdf_dest, force_duplicate, ignore_fields)) + else: + arr.append(data) + return arr + + def hash_bin(self) -> int: + """ + Used to detect modified object. + + Returns: + Hash considering type and value. + + """ + return hash((self.__class__, tuple(x.hash_bin() for x in self))) + + def items(self) -> Iterable[Any]: + """Emulate DictionaryObject.items for a list (index, object).""" + return enumerate(self) + + def _to_lst(self, lst: Any) -> list[Any]: + # Convert to list, internal + result: list[Any] + if isinstance(lst, (list, tuple, set)): + result = list(lst) + elif isinstance(lst, PdfObject): + result = [lst] + elif isinstance(lst, str): + if lst[0] == "/": + result = [NameObject(lst)] + else: + result = [TextStringObject(lst)] + elif isinstance(lst, bytes): + result = [ByteStringObject(lst)] + else: # for numbers,... + result = [lst] + return result + + def __add__(self, lst: Any) -> "ArrayObject": + """ + Allow extension by adding list or add one element only + + Args: + lst: any list, tuples are extended the list. + other types(numbers,...) will be appended. + if str is passed it will be converted into TextStringObject + or NameObject (if starting with "/") + if bytes is passed it will be converted into ByteStringObject + + Returns: + ArrayObject with all elements + + """ + temp = ArrayObject(self) + temp.extend(self._to_lst(lst)) + return temp + + def __iadd__(self, lst: Any) -> Self: + """ + Allow extension by adding list or add one element only + + Args: + lst: any list, tuples are extended the list. + other types(numbers,...) will be appended. + if str is passed it will be converted into TextStringObject + or NameObject (if starting with "/") + if bytes is passed it will be converted into ByteStringObject + + """ + self.extend(self._to_lst(lst)) + return self + + def __isub__(self, lst: Any) -> Self: + """Allow to remove items""" + for x in self._to_lst(lst): + try: + index = self.index(x) + del self[index] + except ValueError: + pass + return self + + def write_to_stream( + self, stream: StreamType, encryption_key: Union[str, bytes, None] = None + ) -> None: + if encryption_key is not None: # deprecated + deprecation_no_replacement( + "the encryption_key parameter of write_to_stream", "5.0.0" + ) + stream.write(b"[") + for data in self: + stream.write(b" ") + data.write_to_stream(stream) + stream.write(b" ]") + + @staticmethod + def read_from_stream( + stream: StreamType, + pdf: Optional[PdfReaderProtocol], + forced_encoding: Union[str, list[str], dict[int, str], None] = None, + ) -> "ArrayObject": + arr = ArrayObject() + tmp = stream.read(1) + if tmp != b"[": + raise PdfReadError("Could not read array") + while True: + # skip leading whitespace + tok = stream.read(1) + while tok.isspace(): + tok = stream.read(1) + if tok == b"": + break + if tok == b"%": + stream.seek(-1, 1) + skip_over_comment(stream) + continue + stream.seek(-1, 1) + # check for array ending + peek_ahead = stream.read(1) + if peek_ahead == b"]": + break + stream.seek(-1, 1) + # read and append object + arr.append(read_object(stream, pdf, forced_encoding)) + return arr + + +class DictionaryObject(dict[Any, Any], PdfObject): + def replicate( + self, + pdf_dest: PdfWriterProtocol, + ) -> "DictionaryObject": + d__ = cast( + "DictionaryObject", + self._reference_clone(self.__class__(), pdf_dest, False), + ) + for k, v in self.items(): + d__[k.replicate(pdf_dest)] = ( + v.replicate(pdf_dest) if hasattr(v, "replicate") else v + ) + return d__ + + def clone( + self, + pdf_dest: PdfWriterProtocol, + force_duplicate: bool = False, + ignore_fields: Optional[Sequence[Union[str, int]]] = (), + ) -> "DictionaryObject": + """Clone object into pdf_dest.""" + try: + if self.indirect_reference.pdf == pdf_dest and not force_duplicate: # type: ignore[union-attr] + return self + except Exception: + pass + + visited: set[tuple[int, int]] = set() # (idnum, generation) + d__ = cast( + "DictionaryObject", + self._reference_clone(self.__class__(), pdf_dest, force_duplicate), + ) + if ignore_fields is None: + ignore_fields = [] + if len(d__.keys()) == 0: + d__._clone(self, pdf_dest, force_duplicate, ignore_fields, visited) + return d__ + + def _clone( + self, + src: "DictionaryObject", + pdf_dest: PdfWriterProtocol, + force_duplicate: bool, + ignore_fields: Optional[Sequence[Union[str, int]]], + visited: set[tuple[int, int]], # (idnum, generation) + ) -> None: + """ + Update the object from src. + + Args: + src: "DictionaryObject": + pdf_dest: + force_duplicate: + ignore_fields: + + """ + # First we remove the ignore_fields + # that are for a limited number of levels + assert ignore_fields is not None + ignore_fields = list(ignore_fields) + x = 0 + while x < len(ignore_fields): + if isinstance(ignore_fields[x], int): + if cast(int, ignore_fields[x]) <= 0: + del ignore_fields[x] + del ignore_fields[x] + continue + ignore_fields[x] -= 1 # type:ignore + x += 1 + # Check if this is a chain list, we need to loop to prevent recur + if any( + field not in ignore_fields + and field in src + and isinstance(src.raw_get(field), IndirectObject) + and isinstance(src[field], DictionaryObject) + and ( + src.get("/Type", None) is None + or cast(DictionaryObject, src[field]).get("/Type", None) is None + or src.get("/Type", None) + == cast(DictionaryObject, src[field]).get("/Type", None) + ) + for field in ["/Next", "/Prev", "/N", "/V"] + ): + ignore_fields = list(ignore_fields) + for lst in (("/Next", "/Prev"), ("/N", "/V")): + for k in lst: + objs = [] + if ( + k in src + and k not in self + and isinstance(src.raw_get(k), IndirectObject) + and isinstance(src[k], DictionaryObject) + # If need to go further the idea is to check + # that the types are the same + and ( + src.get("/Type", None) is None + or cast(DictionaryObject, src[k]).get("/Type", None) is None + or src.get("/Type", None) + == cast(DictionaryObject, src[k]).get("/Type", None) + ) + ): + cur_obj: Optional[DictionaryObject] = cast( + "DictionaryObject", src[k] + ) + prev_obj: Optional[DictionaryObject] = self + while cur_obj is not None: + clon = cast( + "DictionaryObject", + cur_obj._reference_clone( + cur_obj.__class__(), pdf_dest, force_duplicate + ), + ) + # Check to see if we've previously processed our item + if clon.indirect_reference is not None: + idnum = clon.indirect_reference.idnum + generation = clon.indirect_reference.generation + if (idnum, generation) in visited: + cur_obj = None + break + visited.add((idnum, generation)) + objs.append((cur_obj, clon)) + assert prev_obj is not None + prev_obj[NameObject(k)] = clon.indirect_reference + prev_obj = clon + try: + if cur_obj == src: + cur_obj = None + else: + cur_obj = cast("DictionaryObject", cur_obj[k]) + except Exception: + cur_obj = None + for s, c in objs: + c._clone( + s, pdf_dest, force_duplicate, ignore_fields, visited + ) + + for k, v in src.items(): + if k not in ignore_fields: + if isinstance(v, StreamObject): + if not hasattr(v, "indirect_reference"): + v.indirect_reference = None + vv = v.clone(pdf_dest, force_duplicate, ignore_fields) + assert vv.indirect_reference is not None + self[k.clone(pdf_dest)] = vv.indirect_reference + elif k not in self: + self[NameObject(k)] = ( + v.clone(pdf_dest, force_duplicate, ignore_fields) + if hasattr(v, "clone") + else v + ) + + def hash_bin(self) -> int: + """ + Used to detect modified object. + + Returns: + Hash considering type and value. + + """ + return hash( + (self.__class__, tuple(((k, v.hash_bin()) for k, v in self.items()))) + ) + + def raw_get(self, key: Any) -> Any: + return dict.__getitem__(self, key) + + def get_inherited(self, key: str, default: Any = None) -> Any: + """ + Returns the value of a key or from the parent if not found. + If not found returns default. + + Args: + key: string identifying the field to return + + default: default value to return + + Returns: + Current key or inherited one, otherwise default value. + + """ + current = self + visited: set[int] = set() + + while True: + # Detect cyclic parent references + obj_id = id(current) + if obj_id in visited: + raise LimitReachedError(f"Detected cycle in /Parent hierarchy when retrieving value for key {key!r}.") + visited.add(obj_id) + + if key in current: + return current[key] + + if "/Parent" not in current: + return default + + # Walk upward + current = cast( + "DictionaryObject", + current["/Parent"].get_object(), + ) + + def __setitem__(self, key: Any, value: Any) -> Any: + if not isinstance(key, PdfObject): + raise ValueError("Key must be a PdfObject") + if not isinstance(value, PdfObject): + raise ValueError("Value must be a PdfObject") + return dict.__setitem__(self, key, value) + + def setdefault(self, key: Any, value: Optional[Any] = None) -> Any: + if not isinstance(key, PdfObject): + raise ValueError("Key must be a PdfObject") + if not isinstance(value, PdfObject): + raise ValueError("Value must be a PdfObject") + return dict.setdefault(self, key, value) + + def __getitem__(self, key: Any) -> PdfObject: + return cast(PdfObject, dict.__getitem__(self, key).get_object()) + + @property + def xmp_metadata(self) -> Optional[XmpInformationProtocol]: + """ + Retrieve XMP (Extensible Metadata Platform) data relevant to this + object, if available. + + See Table 347 — Additional entries in a metadata stream dictionary. + + Returns: + Returns a :class:`~pypdf.xmp.XmpInformation` instance + that can be used to access XMP metadata from the document. Can also + return None if no metadata was found on the document root. + + """ + from ..xmp import XmpInformation # noqa: PLC0415 + + metadata = self.get("/Metadata", None) + if is_null_or_none(metadata): + return None + assert metadata is not None, "mypy" + metadata = metadata.get_object() + return XmpInformation(metadata) + + def write_to_stream( + self, stream: StreamType, encryption_key: Union[str, bytes, None] = None + ) -> None: + if encryption_key is not None: # deprecated + deprecation_no_replacement( + "the encryption_key parameter of write_to_stream", "5.0.0" + ) + stream.write(b"<<\n") + for key, value in self.items(): + if len(key) > 2 and key[1] == "%" and key[-1] == "%": + continue + key.write_to_stream(stream, encryption_key) + stream.write(b" ") + value.write_to_stream(stream) + stream.write(b"\n") + stream.write(b">>") + + @classmethod + def _get_next_object_position( + cls, position_before: int, position_end: int, generations: list[int], pdf: PdfReaderProtocol + ) -> int: + out = position_end + for generation in generations: + for x in pdf.xref[generation].values(): + if position_before < x <= position_end: + out = min(out, x) + return out + + @classmethod + def _read_unsized_from_stream( + cls, *, stream: BinaryStreamType, pdf: PdfReaderProtocol, length: int, + ) -> bytes: + current_position = stream.tell() + + # Determine stream size. + try: + stream.seek(0, os.SEEK_END) + stream_length = stream.tell() + finally: + stream.seek(current_position) + + object_position = cls._get_next_object_position( + position_before=current_position, position_end=stream_length, generations=list(pdf.xref), pdf=pdf + ) + + bytes_to_read = object_position - current_position + if bytes_to_read >= length: + raise LimitReachedError(f"Requested length of {bytes_to_read} exceeds maximum allowed length.") + + # Read until the next object position. + read_value = stream.read(bytes_to_read) + endstream_position = read_value.find(b"endstream") + if endstream_position < 0: + raise PdfReadError( + f"Unable to find 'endstream' marker for obj starting at {current_position}." + ) + # 9 = len(b"endstream") + stream.seek(current_position + endstream_position + 9) + return read_value[: endstream_position - 1] + + @staticmethod + def read_from_stream( + stream: StreamType, + pdf: Optional[PdfReaderProtocol], + forced_encoding: Union[str, list[str], dict[int, str], None] = None, + ) -> "DictionaryObject": + tmp = stream.read(2) + if tmp != b"<<": + raise PdfReadError( + f"Dictionary read error at byte {hex(stream.tell())}: " + "stream must begin with '<<'" + ) + data: dict[Any, Any] = {} + while True: + tok = read_non_whitespace(stream) + if tok == b"\x00": + continue + if tok == b"%": + stream.seek(-1, 1) + skip_over_comment(stream) + continue + if not tok: + raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY) + + if tok == b">": + stream.read(1) + break + stream.seek(-1, 1) + try: + try: + key = read_object(stream, pdf) + if isinstance(key, NullObject): + break + if not isinstance(key, NameObject): + raise PdfReadError( + f"Expecting a NameObject for key but found {key!r}" + ) + except PdfReadError as exc: + if pdf is not None and pdf.strict: + raise + logger_warning("%(exception)r", source=__name__, exception=exc) + continue + tok = read_non_whitespace(stream) + stream.seek(-1, 1) + value = read_object(stream, pdf, forced_encoding) + except (RecursionError, LimitReachedError) as exc: + raise PdfReadError(exc.__repr__()) + except Exception as exc: + if pdf is not None and pdf.strict: + raise PdfReadError(exc.__repr__()) + logger_warning("%(exception)r", source=__name__, exception=exc) + retval = DictionaryObject() + retval.update(data) + return retval # return partial data + + if not data.get(key): + data[key] = value + else: + # multiple definitions of key not permitted + msg = ( + "Multiple definitions in dictionary at byte " + "%(position)s for key %(key)s" + ) + values = {"position": hex(stream.tell()), "key": key} + if pdf is not None and pdf.strict: + raise PdfReadError(msg % values) + logger_warning(msg, source=__name__, **values) + + pos = stream.tell() + s = read_non_whitespace(stream) + if s == b"s" and stream.read(5) == b"tream": + eol = stream.read(1) + # Occasional PDF file output has spaces after 'stream' keyword but before EOL. + # patch provided by Danial Sandler + while eol == b" ": + eol = stream.read(1) + if eol not in (b"\n", b"\r"): + raise PdfStreamError("Stream data must be followed by a newline") + if eol == b"\r" and stream.read(1) != b"\n": + stream.seek(-1, 1) + # this is a stream object, not a dictionary + if StreamAttributes.LENGTH not in data: + if pdf is not None and pdf.strict: + raise PdfStreamError("Stream length not defined") + logger_warning( + "Stream length not defined @pos=%(position)d", + source=__name__, + position=stream.tell(), + ) + data[NameObject(StreamAttributes.LENGTH)] = NumberObject(-1) + length = data[StreamAttributes.LENGTH] + if isinstance(length, IndirectObject): + t = stream.tell() + assert pdf is not None, "mypy" + length = pdf.get_object(length) + stream.seek(t, 0) + if length is None: # if the PDF is damaged + length = -1 + pstart = stream.tell() + + from ..filters import MAX_DECLARED_STREAM_LENGTH # noqa: PLC0415 + if length >= 0: + if length > MAX_DECLARED_STREAM_LENGTH: + raise LimitReachedError(f"Declared stream length of {length} exceeds maximum allowed length.") + + data["__streamdata__"] = stream.read(length) + else: + data["__streamdata__"] = read_until_regex( + stream=stream, regex=re.compile(b"endstream"), length=MAX_DECLARED_STREAM_LENGTH, + ) + e = read_non_whitespace(stream) + ndstream = stream.read(8) + if (e + ndstream) != b"endstream": + # the odd PDF file has a length that is too long, so + # we need to read backwards to find the "endstream" ending. + # ReportLab (unknown version) generates files with this bug, + # and Python users into PDF files tend to be our audience. + # we need to do this to correct the streamdata and chop off + # an extra character. + pos = stream.tell() + stream.seek(-10, 1) + end = stream.read(9) + if end == b"endstream": + # we found it by looking back one character further. + data["__streamdata__"] = data["__streamdata__"][:-1] + elif pdf is not None and not pdf.strict: + stream.seek(pstart, 0) + data["__streamdata__"] = DictionaryObject._read_unsized_from_stream( + stream=stream, pdf=pdf, length=MAX_DECLARED_STREAM_LENGTH + ) + pos = stream.tell() + else: + stream.seek(pos, 0) + raise PdfReadError( + "Unable to find 'endstream' marker after stream at byte " + f"{hex(stream.tell())} (nd='{ndstream!r}', end='{end!r}')." + ) + else: + stream.seek(pos, 0) + if "__streamdata__" in data: + return StreamObject.initialize_from_dictionary(data) + retval = DictionaryObject() + retval.update(data) + return retval + + +class TreeObject(DictionaryObject): + def __init__(self, dct: Optional[DictionaryObject] = None) -> None: + DictionaryObject.__init__(self) + if dct: + self.update(dct) + + def has_children(self) -> bool: + return "/First" in self + + def __iter__(self) -> Any: + return self.children() + + def children(self) -> Iterable[Any]: + if not self.has_children(): + return + + child_ref = self[NameObject("/First")] + last = self[NameObject("/Last")] + child = child_ref.get_object() + visited: set[int] = set() + while True: + child_id = id(child) + if child_id in visited: + logger_warning("Detected cycle in outline structure for %(child)s", source=__name__, child=child) + return + visited.add(child_id) + + yield child + + if child == last: + return + child_ref = child.get(NameObject("/Next")) # type: ignore[union-attr] + if is_null_or_none(child_ref): + return + child = child_ref.get_object() + + def add_child(self, child: Any, pdf: PdfWriterProtocol) -> None: + self.insert_child(child, None, pdf) + + def inc_parent_counter_default( + self, parent: Union[IndirectObject, "TreeObject", None], n: int + ) -> None: + if is_null_or_none(parent): + return + assert parent is not None, "mypy" + parent = cast("TreeObject", parent.get_object()) + if "/Count" in parent: + parent[NameObject("/Count")] = NumberObject( + max(0, cast(int, parent[NameObject("/Count")]) + n) + ) + self.inc_parent_counter_default(parent.get("/Parent", None), n) + + def inc_parent_counter_outline( + self, parent: Union[IndirectObject, "TreeObject", None], n: int + ) -> None: + if is_null_or_none(parent): + return + assert parent is not None, "mypy" + parent = cast("TreeObject", parent.get_object()) + # BooleanObject requires comparison with == not is + opn = parent.get("/%is_open%", True) == True # noqa: E712 + c = cast(int, parent.get("/Count", 0)) + if c < 0: + c = abs(c) + parent[NameObject("/Count")] = NumberObject((c + n) * (1 if opn else -1)) + if not opn: + return + self.inc_parent_counter_outline(parent.get("/Parent", None), n) + + def insert_child( + self, + child: Any, + before: Any, + pdf: PdfWriterProtocol, + inc_parent_counter: Optional[Callable[..., Any]] = None, + ) -> IndirectObject: + if inc_parent_counter is None: + inc_parent_counter = self.inc_parent_counter_default + child_obj = child.get_object() + assert child.indirect_reference is not None, "mypy" + child_reference: IndirectObject = child.indirect_reference + + prev: Optional[DictionaryObject] + if "/First" not in self: # no child yet + self[NameObject("/First")] = child_reference + self[NameObject("/Count")] = NumberObject(0) + self[NameObject("/Last")] = child_reference + child_obj[NameObject("/Parent")] = self.indirect_reference + inc_parent_counter(self, child_obj.get("/Count", 1)) + if "/Next" in child_obj: + del child_obj["/Next"] + if "/Prev" in child_obj: + del child_obj["/Prev"] + return child_reference + prev = cast("DictionaryObject", self["/Last"]) + + while prev.indirect_reference != before: + if "/Next" in prev: + prev = cast("TreeObject", prev["/Next"]) + else: # append at the end + prev[NameObject("/Next")] = cast("TreeObject", child_reference) + child_obj[NameObject("/Prev")] = prev.indirect_reference + child_obj[NameObject("/Parent")] = self.indirect_reference + if "/Next" in child_obj: + del child_obj["/Next"] + self[NameObject("/Last")] = child_reference + inc_parent_counter(self, child_obj.get("/Count", 1)) + return child_reference + try: # insert as first or in the middle + assert isinstance(prev["/Prev"], DictionaryObject) + prev["/Prev"][NameObject("/Next")] = child_reference + child_obj[NameObject("/Prev")] = prev["/Prev"] + except Exception: # it means we are inserting in first position + child_obj.pop("/Next", None) + child_obj[NameObject("/Next")] = prev + prev[NameObject("/Prev")] = child_reference + child_obj[NameObject("/Parent")] = self.indirect_reference + inc_parent_counter(self, child_obj.get("/Count", 1)) + return child_reference + + def _remove_node_from_tree( + self, prev: Any, prev_ref: Any, cur: Any, last: Any + ) -> None: + """ + Adjust the pointers of the linked list and tree node count. + + Args: + prev: + prev_ref: + cur: + last: + + """ + next_ref = cur.get(NameObject("/Next"), None) + if prev is None: + if next_ref: + # Removing first tree node + next_obj = next_ref.get_object() + del next_obj[NameObject("/Prev")] + self[NameObject("/First")] = next_ref + self[NameObject("/Count")] = NumberObject( + self[NameObject("/Count")] - 1 # type: ignore[operator] + ) + + else: + # Removing only tree node + self[NameObject("/Count")] = NumberObject(0) + del self[NameObject("/First")] + if NameObject("/Last") in self: + del self[NameObject("/Last")] + else: + if next_ref: + # Removing middle tree node + next_obj = next_ref.get_object() + next_obj[NameObject("/Prev")] = prev_ref + prev[NameObject("/Next")] = next_ref + else: + # Removing last tree node + assert cur == last + del prev[NameObject("/Next")] + self[NameObject("/Last")] = prev_ref + self[NameObject("/Count")] = NumberObject(self[NameObject("/Count")] - 1) # type: ignore[operator] + + def remove_child(self, child: Any) -> None: + child_obj = child.get_object() + child = child_obj.indirect_reference + + if NameObject("/Parent") not in child_obj: + raise ValueError("Removed child does not appear to be a tree item") + if child_obj[NameObject("/Parent")] != self: + raise ValueError("Removed child is not a member of this tree") + + found = False + prev_ref = None + prev = None + cur_ref: Optional[Any] = self[NameObject("/First")] + cur: Optional[dict[str, Any]] = cur_ref.get_object() # type: ignore[union-attr] + last_ref = self[NameObject("/Last")] + last = last_ref.get_object() + while cur is not None: + if cur == child_obj: + self._remove_node_from_tree(prev, prev_ref, cur, last) + found = True + break + + # Go to the next node + prev_ref = cur_ref + prev = cur + if NameObject("/Next") in cur: + cur_ref = cur[NameObject("/Next")] + cur = cur_ref.get_object() + else: + cur_ref = None + cur = None + + if not found: + raise ValueError("Removal couldn't find item in tree") + + _reset_node_tree_relationship(child_obj) + + def remove_from_tree(self) -> None: + """Remove the object from the tree it is in.""" + if NameObject("/Parent") not in self: + raise ValueError("Removed child does not appear to be a tree item") + cast("TreeObject", self["/Parent"]).remove_child(self) + + def empty_tree(self) -> None: + for child in self: + child_obj = child.get_object() + _reset_node_tree_relationship(child_obj) + + if NameObject("/Count") in self: + del self[NameObject("/Count")] + if NameObject("/First") in self: + del self[NameObject("/First")] + if NameObject("/Last") in self: + del self[NameObject("/Last")] + + +def _reset_node_tree_relationship(child_obj: Any) -> None: + """ + Call this after a node has been removed from a tree. + + This resets the nodes attributes in respect to that tree. + + Args: + child_obj: + + """ + del child_obj[NameObject("/Parent")] + if NameObject("/Next") in child_obj: + del child_obj[NameObject("/Next")] + if NameObject("/Prev") in child_obj: + del child_obj[NameObject("/Prev")] + + +class StreamObject(DictionaryObject): + def __init__(self) -> None: + self._data: bytes = b"" + self.decoded_self: Optional[DecodedStreamObject] = None + + def replicate( + self, + pdf_dest: PdfWriterProtocol, + ) -> "StreamObject": + d__ = cast( + "StreamObject", + self._reference_clone(self.__class__(), pdf_dest, False), + ) + d__._data = self._data + try: + decoded_self = self.decoded_self + if decoded_self is None: + self.decoded_self = None + else: + self.decoded_self = cast( + "DecodedStreamObject", decoded_self.replicate(pdf_dest) + ) + except Exception: + pass + for k, v in self.items(): + d__[k.replicate(pdf_dest)] = ( + v.replicate(pdf_dest) if hasattr(v, "replicate") else v + ) + return d__ + + def _clone( + self, + src: DictionaryObject, + pdf_dest: PdfWriterProtocol, + force_duplicate: bool, + ignore_fields: Optional[Sequence[Union[str, int]]], + visited: set[tuple[int, int]], + ) -> None: + """ + Update the object from src. + + Args: + src: + pdf_dest: + force_duplicate: + ignore_fields: + + """ + self._data = cast("StreamObject", src)._data + try: + decoded_self = cast("StreamObject", src).decoded_self + if decoded_self is None: + self.decoded_self = None + else: + self.decoded_self = cast( + "DecodedStreamObject", + decoded_self.clone(pdf_dest, force_duplicate, ignore_fields), + ) + except Exception: + pass + super()._clone(src, pdf_dest, force_duplicate, ignore_fields, visited) + + def hash_bin(self) -> int: + """ + Used to detect modified object. + + Returns: + Hash considering type and value. + + """ + # Use _data to prevent errors on non-decoded streams. + return hash((super().hash_bin(), self._data)) + + def get_data(self) -> bytes: + return self._data + + def set_data(self, data: bytes) -> None: + self._data = data + + def hash_value_data(self) -> bytes: + data = super().hash_value_data() + data += self.get_data() + return data + + def write_to_stream( + self, stream: StreamType, encryption_key: Union[str, bytes, None] = None + ) -> None: + if encryption_key is not None: # deprecated + deprecation_no_replacement( + "the encryption_key parameter of write_to_stream", "5.0.0" + ) + self[NameObject(StreamAttributes.LENGTH)] = NumberObject(len(self._data)) + DictionaryObject.write_to_stream(self, stream) + del self[StreamAttributes.LENGTH] + stream.write(b"\nstream\n") + stream.write(self._data) + stream.write(b"\nendstream") + + @staticmethod + def initialize_from_dictionary( + data: dict[str, Any] + ) -> Union["EncodedStreamObject", "DecodedStreamObject"]: + retval: Union[EncodedStreamObject, DecodedStreamObject] + if StreamAttributes.FILTER in data: + retval = EncodedStreamObject() + else: + retval = DecodedStreamObject() + retval._data = data["__streamdata__"] + del data["__streamdata__"] + if StreamAttributes.LENGTH in data: + del data[StreamAttributes.LENGTH] + retval.update(data) + return retval + + def flate_encode(self, level: int = -1) -> "EncodedStreamObject": + from ..filters import FlateDecode # noqa: PLC0415 + + if StreamAttributes.FILTER in self: + f = self[StreamAttributes.FILTER] + if isinstance(f, ArrayObject): + f = ArrayObject([NameObject(FT.FLATE_DECODE), *f]) + try: + params = ArrayObject( + [NullObject(), *self.get(StreamAttributes.DECODE_PARMS, ArrayObject())] + ) + except TypeError: + # case of error where the * operator is not working (not an array + params = ArrayObject( + [NullObject(), self.get(StreamAttributes.DECODE_PARMS, ArrayObject())] + ) + else: + f = ArrayObject([NameObject(FT.FLATE_DECODE), f]) + params = ArrayObject( + [NullObject(), self.get(StreamAttributes.DECODE_PARMS, NullObject())] + ) + else: + f = NameObject(FT.FLATE_DECODE) + params = None + retval = EncodedStreamObject() + retval.update(self) + retval[NameObject(StreamAttributes.FILTER)] = f + if params is not None: + retval[NameObject(StreamAttributes.DECODE_PARMS)] = params + retval._data = FlateDecode.encode(self._data, level) + return retval + + def decode_as_image(self, pillow_parameters: Union[dict[str, Any], None] = None) -> Any: + """ + Try to decode the stream object as an image + + Args: + pillow_parameters: parameters provided to Pillow Image.save() method, + cf. + + Returns: + a PIL image if proper decoding has been found + Raises: + Exception: Errors during decoding will be reported. + It is recommended to catch exceptions to prevent + stops in your program. + + """ + from ._image_xobject import _xobj_to_image # noqa: PLC0415 + + if self.get("/Subtype", "") != "/Image": + try: + logger_warning( # pragma: no cover + "%(indirect_reference)s does not seem to be an Image", + source=__name__, + indirect_reference=self.indirect_reference, + ) + except AttributeError: + logger_warning( # pragma: no cover + "%(obj)r object does not seem to be an Image", + source=__name__, + obj=self, + ) + extension, _, img = _xobj_to_image(self, pillow_parameters) + if extension is None: + return None # pragma: no cover + return img + + +class DecodedStreamObject(StreamObject): + pass + + +class EncodedStreamObject(StreamObject): + def __init__(self) -> None: + self.decoded_self: Optional[DecodedStreamObject] = None + + # This overrides the parent method + def get_data(self) -> bytes: + from ..filters import decode_stream_data # noqa: PLC0415 + + if self.decoded_self is not None: + # Cached version of decoded object + return self.decoded_self.get_data() + + # Create decoded object + decoded = DecodedStreamObject() + decoded.set_data(decode_stream_data(self)) + for key, value in self.items(): + if key not in (StreamAttributes.LENGTH, StreamAttributes.FILTER, StreamAttributes.DECODE_PARMS): + decoded[key] = value + self.decoded_self = decoded + return decoded.get_data() + + # This overrides the parent method: + def set_data(self, data: bytes) -> None: + from ..filters import FlateDecode # noqa: PLC0415 + + if self.get(StreamAttributes.FILTER, "") in (FT.FLATE_DECODE, [FT.FLATE_DECODE]): + if not isinstance(data, bytes): + raise TypeError("Data must be bytes") + if self.decoded_self is None: + self.get_data() # to create self.decoded_self + assert self.decoded_self is not None, "mypy" + self.decoded_self.set_data(data) + super().set_data(FlateDecode.encode(data)) + else: + raise PdfReadError( + "Streams encoded with a filter different from FlateDecode are not supported" + ) + + +CONTENT_STREAM_ARRAY_MAX_LENGTH = 10_000 + + +class ContentStream(DecodedStreamObject): + """ + In order to be fast, this data structure can contain either: + + * raw data in ._data + * parsed stream operations in ._operations. + + At any time, ContentStream object can either have both of those fields defined, + or one field defined and the other set to None. + + These fields are "rebuilt" lazily, when accessed: + + * when .get_data() is called, if ._data is None, it is rebuilt from ._operations. + * when .operations is called, if ._operations is None, it is rebuilt from ._data. + + Conversely, these fields can be invalidated: + + * when .set_data() is called, ._operations is set to None. + * when .operations is set, ._data is set to None. + """ + _OPERATOR_LENGTH_LIMIT = 128 + + def __init__( + self, + stream: Any, + pdf: Any, + forced_encoding: Union[str, list[str], dict[int, str], None] = None, + ) -> None: + self.pdf = pdf + self._operations: list[tuple[Any, bytes]] = [] + + # stream may be a StreamObject or an ArrayObject containing + # StreamObjects to be concatenated together. + if stream is None: + super().set_data(b"") + else: + stream = stream.get_object() + if isinstance(stream, ArrayObject): + from pypdf.filters import MAX_ARRAY_BASED_STREAM_OUTPUT_LENGTH # noqa: PLC0415 + + if (stream_length := len(stream)) > CONTENT_STREAM_ARRAY_MAX_LENGTH: + raise LimitReachedError( + f"Array-based stream has {stream_length} > {CONTENT_STREAM_ARRAY_MAX_LENGTH} elements." + ) + data = bytearray() + length = 0 + for s in stream: + s_resolved = s.get_object() + if isinstance(s_resolved, NullObject): + continue + if not isinstance(s_resolved, StreamObject): + # No need to emit an exception here for now - the PDF structure + # seems to already be broken beforehand in these cases. + logger_warning( + "Expected StreamObject, got %(type_name)s instead. Data might be wrong.", + source=__name__, + type_name=type(s_resolved).__name__, + ) + else: + new_data = s_resolved.get_data() + length += len(new_data) + if length > MAX_ARRAY_BASED_STREAM_OUTPUT_LENGTH: + raise LimitReachedError( + f"Array-based stream has at least {length} > " + f"{MAX_ARRAY_BASED_STREAM_OUTPUT_LENGTH} output bytes." + ) + data += new_data + if len(data) == 0 or data[-1:] != b"\n": + # There should be no direct need to check for a change of one byte. + length += 1 + data += b"\n" + super().set_data(bytes(data)) + else: + stream_data = stream.get_data() + assert stream_data is not None + super().set_data(stream_data) + self.forced_encoding = forced_encoding + + def replicate( + self, + pdf_dest: PdfWriterProtocol, + ) -> "ContentStream": + d__ = cast( + "ContentStream", + self._reference_clone(self.__class__(None, None), pdf_dest, False), + ) + d__._data = self._data + try: + decoded_self = self.decoded_self + if decoded_self is None: + self.decoded_self = None + else: + self.decoded_self = cast( + "DecodedStreamObject", decoded_self.replicate(pdf_dest) + ) + except Exception: + pass + for k, v in self.items(): + d__[k.replicate(pdf_dest)] = ( + v.replicate(pdf_dest) if hasattr(v, "replicate") else v + ) + return d__ + d__.set_data(self._data) + d__.pdf = pdf_dest + d__._operations = list(self._operations) + d__.forced_encoding = self.forced_encoding + return d__ + + def clone( + self, + pdf_dest: Any, + force_duplicate: bool = False, + ignore_fields: Optional[Sequence[Union[str, int]]] = (), + ) -> "ContentStream": + """ + Clone object into pdf_dest. + + Args: + pdf_dest: + force_duplicate: + ignore_fields: + + Returns: + The cloned ContentStream + + """ + try: + if self.indirect_reference.pdf == pdf_dest and not force_duplicate: # type: ignore[union-attr] + return self + except Exception: + pass + + visited: set[tuple[int, int]] = set() + d__ = cast( + "ContentStream", + self._reference_clone( + self.__class__(None, None), pdf_dest, force_duplicate + ), + ) + if ignore_fields is None: + ignore_fields = [] + d__._clone(self, pdf_dest, force_duplicate, ignore_fields, visited) + return d__ + + def _clone( + self, + src: DictionaryObject, + pdf_dest: PdfWriterProtocol, + force_duplicate: bool, + ignore_fields: Optional[Sequence[Union[str, int]]], + visited: set[tuple[int, int]], + ) -> None: + """ + Update the object from src. + + Args: + src: + pdf_dest: + force_duplicate: + ignore_fields: + + """ + src_cs = cast("ContentStream", src) + super().set_data(src_cs._data) + self.pdf = pdf_dest + self._operations = list(src_cs._operations) + self.forced_encoding = src_cs.forced_encoding + # no need to call DictionaryObjection or anything + # like super(DictionaryObject,self)._clone(src, pdf_dest, force_duplicate, ignore_fields, visited) + + def _parse_content_stream(self, stream: StreamType) -> None: + # 7.8.2 Content Streams + stream.seek(0, 0) + operands: list[Union[int, str, PdfObject]] = [] + while True: + peek = read_non_whitespace(stream) + if peek in (b"", 0): + break + stream.seek(-1, 1) + if peek.isalpha() or peek in (b"'", b'"'): + operator = read_until_regex( + stream=stream, regex=NameObject.delimiter_pattern, length=self._OPERATOR_LENGTH_LIMIT + ) + if operator == b"BI": + # begin inline image - a completely different parsing + # mechanism is required, of course... thanks buddy... + assert operands == [] + ii = self._read_inline_image(stream) + self._operations.append((ii, b"INLINE IMAGE")) + else: + self._operations.append((operands, operator)) + operands = [] + elif peek == b"%": + # If we encounter a comment in the content stream, we have to + # handle it here. Typically, read_object will handle + # encountering a comment -- but read_object assumes that + # following the comment must be the object we're trying to + # read. In this case, it could be an operator instead. + while peek not in (b"\r", b"\n", b""): + peek = stream.read(1) + else: + operands.append(read_object(stream, None, self.forced_encoding)) + + def _read_inline_image(self, stream: StreamType) -> dict[str, Any]: + # begin reading just after the "BI" - begin image + # first read the dictionary of settings. + settings = DictionaryObject() + while True: + tok = read_non_whitespace(stream) + if not tok: + raise PdfReadError("Unexpected end of stream.") + stream.seek(-1, 1) + if tok == b"I": + # "ID" - begin of image data + break + key = read_object(stream, self.pdf) + tok = read_non_whitespace(stream) + stream.seek(-1, 1) + value = read_object(stream, self.pdf) + settings[key] = value + # left at beginning of ID + tmp = stream.read(3) + assert tmp[:2] == b"ID" + filtr = settings.get("/F", settings.get("/Filter", "not set")) + savpos = stream.tell() + if isinstance(filtr, list): + filtr = filtr[0] if filtr else "not set" # used forencoding + if not isinstance(filtr, str): + # A valid filter is a name or an array of names; anything else + # cannot match the abbreviations below, so treat it as unfiltered. + filtr = "not set" + if "AHx" in filtr or "ASCIIHexDecode" in filtr: + data = extract_inline__ascii_hex_decode(stream) + elif "A85" in filtr or "ASCII85Decode" in filtr: + data = extract_inline__ascii85_decode(stream) + elif "RL" in filtr or "RunLengthDecode" in filtr: + data = extract_inline__run_length_decode(stream) + elif "DCT" in filtr or "DCTDecode" in filtr: + data = extract_inline__dct_decode(stream) + elif filtr == "not set": + cs = settings.get("/CS", "") + if isinstance(cs, list): + cs = cs[0] if cs else "" + if not isinstance(cs, str): + cs = "" + if "RGB" in cs: + lcs: float = 3 + elif "CMYK" in cs: + lcs = 4 + else: + bits = settings.get( + "/BPC", + 8 if cs in {"/I", "/G", "/Indexed", "/DeviceGray"} else -1, + ) + if isinstance(bits, (int, float)) and bits > 0: + lcs = bits / 8.0 + else: + data = extract_inline_default(stream) + lcs = -1 + width = settings.get("/W") + height = settings.get("/H") + if lcs > 0 and isinstance(width, int) and isinstance(height, int): + data = stream.read(ceil(width * lcs) * height) + elif lcs > 0: + # Without usable dimensions the raw sample length is unknown; + # fall back to scanning for the `EI` marker. + data = extract_inline_default(stream) + # Move to the `EI` if possible. + ei = read_non_whitespace(stream) + stream.seek(-1, 1) + else: + data = extract_inline_default(stream) + + ei = stream.read(3) + # An `EI` at the very end of the stream yields only two bytes; rewinding + # unconditionally would step back into the marker (#3468). + if len(ei) == 3: + stream.seek(-1, 1) + ei_trailing = ei[2:3] + if ei[:2] != b"EI" or (ei_trailing != b"" and ei_trailing not in WHITESPACES): + # Deal with wrong/missing `EI` tags. Example: Wrong dimensions specified above. + stream.seek(savpos, 0) + data = extract_inline_default(stream) + ei = stream.read(3) + if len(ei) == 3: + stream.seek(-1, 1) + ei_trailing = ei[2:3] + if ei[:2] != b"EI" or ( + ei_trailing != b"" and ei_trailing not in WHITESPACES + ): # pragma: no cover + # Check the same condition again. This should never fail as + # edge cases are covered by `extract_inline_default` above, + # but check this ot make sure that we are behind the `EI` afterwards. + raise PdfStreamError( + f"Could not extract inline image, even using fallback. Expected 'EI', got {ei!r}" + ) + return {"settings": settings, "data": data} + + # This overrides the parent method + def get_data(self) -> bytes: + if not self._data: + new_data = BytesIO() + for operands, operator in self._operations: + if operator == b"INLINE IMAGE": + new_data.write(b"BI") + dict_text = BytesIO() + operands["settings"].write_to_stream(dict_text) + new_data.write(dict_text.getvalue()[2:-2]) + new_data.write(b"ID ") + new_data.write(operands["data"]) + new_data.write(b"EI") + else: + for op in operands: + op.write_to_stream(new_data) + new_data.write(b" ") + new_data.write(operator) + new_data.write(b"\n") + self._data = new_data.getvalue() + return self._data + + # This overrides the parent method + def set_data(self, data: bytes) -> None: + super().set_data(data) + self._operations = [] + + @property + def operations(self) -> list[tuple[Any, bytes]]: + if not self._operations and self._data: + self._parse_content_stream(BytesIO(self._data)) + self._data = b"" + return self._operations + + @operations.setter + def operations(self, operations: list[tuple[Any, bytes]]) -> None: + self._operations = operations + self._data = b"" + + def isolate_graphics_state(self) -> None: + if self._operations: + self._operations.insert(0, ([], b"q")) + self._operations.append(([], b"Q")) + elif self._data: + self._data = b"q\n" + self._data + b"\nQ\n" + + # This overrides the parent method + def write_to_stream( + self, stream: StreamType, encryption_key: Union[str, bytes, None] = None + ) -> None: + if not self._data and self._operations: + self.get_data() # this ensures ._data is rebuilt + super().write_to_stream(stream, encryption_key) + + +def read_object( + stream: StreamType, + pdf: Optional[PdfReaderProtocol], + forced_encoding: Union[str, list[str], dict[int, str], None] = None, +) -> Union[PdfObject, int, str, ContentStream]: + tok = stream.read(1) + stream.seek(-1, 1) # reset to start + if tok == b"/": + return NameObject.read_from_stream(stream, pdf) + if tok == b"<": + # hexadecimal string OR dictionary + peek = stream.read(2) + stream.seek(-2, 1) # reset to start + if peek == b"<<": + return DictionaryObject.read_from_stream(stream, pdf, forced_encoding) + return read_hex_string_from_stream(stream, forced_encoding) + if tok == b"[": + return ArrayObject.read_from_stream(stream, pdf, forced_encoding) + if tok in (b"t", b"f"): + return BooleanObject.read_from_stream(stream) + if tok == b"(": + return read_string_from_stream(stream, forced_encoding) + if tok == b"e" and stream.read(6) == b"endobj": + return NullObject() + if tok == b"n": + return NullObject.read_from_stream(stream) + if tok == b"%": + # comment + skip_over_comment(stream) + tok = read_non_whitespace(stream) + stream.seek(-1, 1) + return read_object(stream, pdf, forced_encoding) + if tok in b"0123456789+-.": + # number object OR indirect reference + peek = stream.read(20) + stream.seek(-len(peek), 1) # reset to start + if IndirectPattern.match(peek) is not None: + assert pdf is not None, "mypy" + return IndirectObject.read_from_stream(stream, pdf) + return NumberObject.read_from_stream(stream) + pos = stream.tell() + stream.seek(-20, 1) + stream_extract = stream.read(80) + stream.seek(pos) + read_until_whitespace(stream) + raise PdfReadError( + f"Invalid Elementary Object starting with {tok!r} @{pos}: {stream_extract!r}" + ) + + +class Field(TreeObject): + """ + A class representing a field dictionary. + + This class is accessed through + :meth:`get_fields()` + """ + + def __init__(self, data: DictionaryObject) -> None: + DictionaryObject.__init__(self) + field_attributes = ( + FieldDictionaryAttributes.attributes() + + CheckboxRadioButtonAttributes.attributes() + ) + self.indirect_reference = data.indirect_reference + for attr in field_attributes: + try: + self[NameObject(attr)] = data[attr] + except KeyError: + pass + if isinstance(self.get("/V"), EncodedStreamObject): + d = cast(EncodedStreamObject, self[NameObject("/V")]).get_data() + if isinstance(d, bytes): + d_str = d.decode() + elif d is None: + d_str = "" + else: + raise Exception("Should never happen") + self[NameObject("/V")] = TextStringObject(d_str) + + # TABLE 8.69 Entries common to all field dictionaries + @property + def field_type(self) -> Optional[NameObject]: + """Read-only property accessing the type of this field.""" + return self.get(FieldDictionaryAttributes.FT) + + @property + def parent(self) -> Optional[DictionaryObject]: + """Read-only property accessing the parent of this field.""" + return self.get(FieldDictionaryAttributes.Parent) + + @property + def kids(self) -> Optional["ArrayObject"]: + """Read-only property accessing the kids of this field.""" + return self.get(FieldDictionaryAttributes.Kids) + + @property + def name(self) -> Optional[str]: + """Read-only property accessing the name of this field.""" + return self.get(FieldDictionaryAttributes.T) + + @property + def alternate_name(self) -> Optional[str]: + """Read-only property accessing the alternate name of this field.""" + return self.get(FieldDictionaryAttributes.TU) + + @property + def mapping_name(self) -> Optional[str]: + """ + Read-only property accessing the mapping name of this field. + + This name is used by pypdf as a key in the dictionary returned by + :meth:`get_fields()` + """ + return self.get(FieldDictionaryAttributes.TM) + + @property + def flags(self) -> Optional[int]: + """ + Read-only property accessing the field flags, specifying various + characteristics of the field (see Table 8.70 of the PDF 1.7 reference). + """ + return self.get(FieldDictionaryAttributes.Ff) + + @property + def value(self) -> Optional[Any]: + """ + Read-only property accessing the value of this field. + + Format varies based on field type. + """ + return self.get(FieldDictionaryAttributes.V) + + @property + def default_value(self) -> Optional[Any]: + """Read-only property accessing the default value of this field.""" + return self.get(FieldDictionaryAttributes.DV) + + @property + def additional_actions(self) -> Optional[DictionaryObject]: + """ + Read-only property accessing the additional actions dictionary. + + This dictionary defines the field's behavior in response to trigger + events. See Section 8.5.2 of the PDF 1.7 reference. + """ + return self.get(FieldDictionaryAttributes.AA) + + +class Destination(TreeObject): + """ + A class representing a destination within a PDF file. + + See section 12.3.2 of the PDF 2.0 reference. + + Args: + title: Title of this destination. + page: Reference to the page of this destination. Should + be an instance of :class:`IndirectObject`. + fit: How the destination is displayed. + + Raises: + PdfReadError: If destination type is invalid. + + """ + + node: Optional[ + DictionaryObject + ] = None # node provide access to the original Object + + def __init__( + self, + title: Union[str, bytes], + page: Union[NumberObject, IndirectObject, NullObject, DictionaryObject], + fit: Fit, + ) -> None: + self._filtered_children: list[Any] = [] # used in PdfWriter + + typ = fit.fit_type + args = fit.fit_args + + DictionaryObject.__init__(self) + self[NameObject("/Title")] = TextStringObject(title) + self[NameObject("/Page")] = page + self[NameObject("/Type")] = typ + + # from table 8.2 of the PDF 1.7 reference. + if typ == "/XYZ": + if len(args) < 1: # left is missing : should never occur + args.append(NumberObject(0.0)) + if len(args) < 2: # top is missing + args.append(NumberObject(0.0)) + if len(args) < 3: # zoom is missing + args.append(NumberObject(0.0)) + # surplus arguments are ignored rather than failing the unpacking + ( + self[NameObject(TA.LEFT)], + self[NameObject(TA.TOP)], + self[NameObject("/Zoom")], + ) = args[:3] + elif len(args) == 0: + pass + elif typ == TF.FIT_R: + if len(args) == 4: # a wrong number of arguments degrades to null + ( + self[NameObject(TA.LEFT)], + self[NameObject(TA.BOTTOM)], + self[NameObject(TA.RIGHT)], + self[NameObject(TA.TOP)], + ) = args + else: + ( + self[NameObject(TA.LEFT)], + self[NameObject(TA.BOTTOM)], + self[NameObject(TA.RIGHT)], + self[NameObject(TA.TOP)], + ) = (NullObject(), NullObject(), NullObject(), NullObject()) + elif typ in [TF.FIT_H, TF.FIT_BH]: + try: # Prefer to be more robust not only to null parameters + (self[NameObject(TA.TOP)],) = args + except Exception: + (self[NameObject(TA.TOP)],) = (NullObject(),) + elif typ in [TF.FIT_V, TF.FIT_BV]: + try: # Prefer to be more robust not only to null parameters + (self[NameObject(TA.LEFT)],) = args + except Exception: + (self[NameObject(TA.LEFT)],) = (NullObject(),) + elif typ in [TF.FIT, TF.FIT_B]: + pass + else: + raise PdfReadError(f"Unknown Destination Type: {typ!r}") + + @property + def dest_array(self) -> "ArrayObject": + return ArrayObject( + [self.raw_get("/Page"), self["/Type"]] + + [ + self[x] + for x in ["/Left", "/Bottom", "/Right", "/Top", "/Zoom"] + if x in self + ] + ) + + def write_to_stream( + self, stream: StreamType, encryption_key: Union[str, bytes, None] = None + ) -> None: + if encryption_key is not None: # deprecated + deprecation_no_replacement( + "the encryption_key parameter of write_to_stream", "5.0.0" + ) + stream.write(b"<<\n") + key = NameObject("/D") + key.write_to_stream(stream) + stream.write(b" ") + value = self.dest_array + value.write_to_stream(stream) + + key = NameObject("/S") + key.write_to_stream(stream) + stream.write(b" ") + value_s = NameObject("/GoTo") + value_s.write_to_stream(stream) + + stream.write(b"\n") + stream.write(b">>") + + @property + def title(self) -> Optional[str]: + """Read-only property accessing the destination title.""" + return self.get("/Title") + + @property + def page(self) -> Optional[IndirectObject]: + """Read-only property accessing the IndirectObject of the destination page.""" + return self.get("/Page") + + @property + def typ(self) -> Optional[str]: + """Read-only property accessing the destination type.""" + return self.get("/Type") + + @property + def zoom(self) -> Optional[int]: + """Read-only property accessing the zoom factor.""" + return self.get("/Zoom", None) + + @property + def left(self) -> Optional[FloatObject]: + """Read-only property accessing the left horizontal coordinate.""" + return self.get("/Left", None) + + @property + def right(self) -> Optional[FloatObject]: + """Read-only property accessing the right horizontal coordinate.""" + return self.get("/Right", None) + + @property + def top(self) -> Optional[FloatObject]: + """Read-only property accessing the top vertical coordinate.""" + return self.get("/Top", None) + + @property + def bottom(self) -> Optional[FloatObject]: + """Read-only property accessing the bottom vertical coordinate.""" + return self.get("/Bottom", None) + + @property + def color(self) -> Optional["ArrayObject"]: + """Read-only property accessing the color in (R, G, B) with values 0.0-1.0.""" + return cast( + "ArrayObject", + self.get("/C", ArrayObject([FloatObject(0), FloatObject(0), FloatObject(0)])), + ) + + @property + def font_format(self) -> Optional[OutlineFontFlag]: + """ + Read-only property accessing the font type. + + 1=italic, 2=bold, 3=both + """ + return OutlineFontFlag(self.get("/F", 0)) + + @property + def outline_count(self) -> Optional[int]: + """ + Read-only property accessing the outline count. + + positive = expanded + negative = collapsed + absolute value = number of visible descendants at all levels + """ + return self.get("/Count", None) diff --git a/.venv/lib/python3.13/site-packages/pypdf/generic/_files.py b/.venv/lib/python3.13/site-packages/pypdf/generic/_files.py new file mode 100644 index 0000000000000000000000000000000000000000..41dd3023d2f5de9eef712c439071607088808b01 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/generic/_files.py @@ -0,0 +1,418 @@ +from __future__ import annotations + +import bisect +from functools import cached_property +from typing import TYPE_CHECKING, cast + +from pypdf._utils import format_iso8824_date, parse_iso8824_date +from pypdf.constants import CatalogAttributes as CA +from pypdf.constants import FileSpecificationDictionaryEntries +from pypdf.constants import PageAttributes as PG +from pypdf.errors import PdfReadError, PyPdfError +from pypdf.generic import ( + ArrayObject, + ByteStringObject, + DecodedStreamObject, + DictionaryObject, + NameObject, + NullObject, + NumberObject, + StreamObject, + TextStringObject, + is_null_or_none, +) + +if TYPE_CHECKING: + import datetime + from collections.abc import Generator + + from pypdf._writer import PdfWriter + + +class EmbeddedFile: + """ + Container holding the information on an embedded file. + + Attributes are evaluated lazily if possible. + + Further information on embedded files can be found in section 7.11 of the PDF 2.0 specification. + """ + def __init__(self, name: str, pdf_object: DictionaryObject, parent: ArrayObject | None = None) -> None: + """ + Args: + name: The (primary) name as provided in the name tree. + pdf_object: The corresponding PDF object to allow retrieving further data. + parent: The parent list. + """ + self._name = name + self.pdf_object = pdf_object + self._parent = parent + + @property + def name(self) -> str: + """ + The (primary) name of the embedded file as provided in the name tree. + + .. warning:: + + This value can contain arbitrary characters. Please make sure to sanitize it before + using it to write the file content to the disk for example. + """ + return self._name + + @classmethod + def _create_new(cls, writer: PdfWriter, name: str, content: str | bytes) -> EmbeddedFile: + """ + Create a new embedded file and add it to the PdfWriter. + + Args: + writer: The PdfWriter instance to add the embedded file to. + name: The filename to display. + content: The data in the file. + + Returns: + EmbeddedFile instance for the newly created embedded file. + """ + # Convert string content to bytes if needed + if isinstance(content, str): + content = content.encode("latin-1") + + # Create the file entry (the actual embedded file stream) + file_entry = DecodedStreamObject() + file_entry.set_data(content) + file_entry.update({NameObject(PG.TYPE): NameObject("/EmbeddedFile")}) + + # Create the /EF entry + ef_entry = DictionaryObject() + ef_entry.update({NameObject("/F"): writer._add_object(file_entry)}) + + # Create the filespec dictionary + from pypdf.generic import create_string_object # noqa: PLC0415 + filespec = DictionaryObject() + filespec_reference = writer._add_object(filespec) + name_object = cast(TextStringObject, create_string_object(name)) + filespec.update( + { + NameObject(PG.TYPE): NameObject("/Filespec"), + NameObject(FileSpecificationDictionaryEntries.F): name_object, + NameObject(FileSpecificationDictionaryEntries.EF): ef_entry, + } + ) + + # Add the name and filespec to the names array. + # We use the inverse order for insertion, as this allows us to re-use the + # same index. + names_array = cls._get_names_array(writer) + insertion_index = cls._get_insertion_index(names_array, name_object) + names_array.insert(insertion_index, filespec_reference) + names_array.insert(insertion_index, name_object) + + # Return an EmbeddedFile instance + return cls(name=name, pdf_object=filespec, parent=names_array) + + @classmethod + def _get_names_array(cls, writer: PdfWriter) -> ArrayObject: + """Get the names array for embedded files, possibly creating and flattening it.""" + if CA.NAMES not in writer.root_object: + # Add the /Names entry to the catalog. + writer.root_object[NameObject(CA.NAMES)] = writer._add_object(DictionaryObject()) + + names_dict = cast(DictionaryObject, writer.root_object[CA.NAMES]) + if "/EmbeddedFiles" not in names_dict: + # We do not yet have an entry for embedded files. Create and return it. + names = ArrayObject() + embedded_files_names_dictionary = DictionaryObject( + {NameObject(CA.NAMES): names} + ) + names_dict[NameObject("/EmbeddedFiles")] = writer._add_object(embedded_files_names_dictionary) + return names + + # We have an existing embedded files entry. + embedded_files_names_tree = cast(DictionaryObject, names_dict["/EmbeddedFiles"]) + if "/Names" in embedded_files_names_tree: + # Simple case: We already have a flat list. + return cast(ArrayObject, embedded_files_names_tree[NameObject(CA.NAMES)]) + if "/Kids" not in embedded_files_names_tree: + # Invalid case: This is no name tree. + raise PdfReadError("Got neither Names nor Kids in embedded files tree.") + + # Complex case: Convert a /Kids-based name tree to a /Names-based one. + # /Name-based ones are much easier to handle and allow us to simplify the + # actual insertion logic by only having to consider one case. + names = ArrayObject() + kids = cast(ArrayObject, embedded_files_names_tree["/Kids"].get_object()) + embedded_files_names_dictionary = DictionaryObject( + {NameObject(CA.NAMES): names} + ) + names_dict[NameObject("/EmbeddedFiles")] = writer._add_object(embedded_files_names_dictionary) + for kid in kids: + # Write the flattened file entries. As we do not change the actual files, + # this should not have any impact on references to them. + # There might be further (nested) kids here. + # Wait for an example before evaluating an implementation. + for name in kid.get_object().get("/Names", []): + names.append(name) + return names + + @classmethod + def _get_insertion_index(cls, names_array: ArrayObject, name: str) -> int: + keys = [names_array[i].encode("utf-8") for i in range(0, len(names_array), 2)] + name_bytes = name.encode("utf-8") + + start = bisect.bisect_left(keys, name_bytes) + end = bisect.bisect_right(keys, name_bytes) + + if start != end: + return end * 2 + if start == 0: + return 0 + if start == (key_count := len(keys)): + return key_count * 2 + return end * 2 + + @property + def alternative_name(self) -> str | None: + """ + Retrieve the alternative name (as per the file specification dictionary). + + .. warning:: + + This value can contain arbitrary characters. Please make sure to sanitize it before + using it to write the file content to the disk for example. + """ + for key in [FileSpecificationDictionaryEntries.UF, FileSpecificationDictionaryEntries.F]: + # PDF 2.0 reference, table 43: + # > A PDF reader shall use the value of the UF key, when present, instead of the F key. + if key in self.pdf_object: + value = self.pdf_object[key].get_object() + if not is_null_or_none(value): + return cast(str, value) + return None + + @alternative_name.setter + def alternative_name(self, value: TextStringObject | None) -> None: + """Set the alternative name (as per the file specification dictionary).""" + if value is None: + if FileSpecificationDictionaryEntries.UF in self.pdf_object: + self.pdf_object[NameObject(FileSpecificationDictionaryEntries.UF)] = NullObject() + if FileSpecificationDictionaryEntries.F in self.pdf_object: + self.pdf_object[NameObject(FileSpecificationDictionaryEntries.F)] = NullObject() + else: + self.pdf_object[NameObject(FileSpecificationDictionaryEntries.UF)] = value + self.pdf_object[NameObject(FileSpecificationDictionaryEntries.F)] = value + + @property + def description(self) -> str | None: + """Retrieve the description.""" + value = self.pdf_object.get(FileSpecificationDictionaryEntries.DESC) + if is_null_or_none(value): + return None + return value + + @description.setter + def description(self, value: TextStringObject | None) -> None: + """Set the description.""" + if value is None: + self.pdf_object[NameObject(FileSpecificationDictionaryEntries.DESC)] = NullObject() + else: + self.pdf_object[NameObject(FileSpecificationDictionaryEntries.DESC)] = value + + @property + def associated_file_relationship(self) -> str: + """Retrieve the relationship of the referring document to this embedded file.""" + return cast( + NameObject, + self.pdf_object.get("/AFRelationship", NameObject("/Unspecified")), + ) + + @associated_file_relationship.setter + def associated_file_relationship(self, value: NameObject) -> None: + """Set the relationship of the referring document to this embedded file.""" + self.pdf_object[NameObject("/AFRelationship")] = value + + @property + def _embedded_file(self) -> StreamObject: + """Retrieve the actual embedded file stream.""" + if "/EF" not in self.pdf_object: + raise PdfReadError(f"/EF entry not found: {self.pdf_object}") + ef = cast(DictionaryObject, self.pdf_object["/EF"]) + for key in [FileSpecificationDictionaryEntries.UF, FileSpecificationDictionaryEntries.F]: + if key in ef: + return cast(StreamObject, ef[key].get_object()) + raise PdfReadError(f"No /(U)F key found in file dictionary: {ef}") + + @property + def _params(self) -> DictionaryObject: + """Retrieve the file-specific parameters.""" + return cast(DictionaryObject, self._embedded_file.get("/Params", DictionaryObject()).get_object()) + + @cached_property + def _ensure_params(self) -> DictionaryObject: + """Ensure the /Params dictionary exists and return it.""" + embedded_file = self._embedded_file + if "/Params" not in embedded_file: + embedded_file[NameObject("/Params")] = DictionaryObject() + return cast(DictionaryObject, embedded_file["/Params"]) + + @property + def subtype(self) -> str | None: + """Retrieve the subtype. This is a MIME media type, prefixed by a slash.""" + value = self._embedded_file.get("/Subtype") + if is_null_or_none(value): + return None + return value + + @subtype.setter + def subtype(self, value: NameObject | None) -> None: + """Set the subtype. This should be a MIME media type, prefixed by a slash.""" + embedded_file = self._embedded_file + if value is None: + embedded_file[NameObject("/Subtype")] = NullObject() + else: + embedded_file[NameObject("/Subtype")] = value + + @property + def content(self) -> bytes: + """Retrieve the actual file content.""" + return self._embedded_file.get_data() + + @content.setter + def content(self, value: str | bytes) -> None: + """Set the file content.""" + if isinstance(value, str): + value = value.encode("latin-1") + self._embedded_file.set_data(value) + + @property + def size(self) -> int | None: + """Retrieve the size of the uncompressed file in bytes.""" + value = self._params.get("/Size") + if is_null_or_none(value): + return None + return value + + @size.setter + def size(self, value: NumberObject | None) -> None: + """Set the size of the uncompressed file in bytes.""" + params = self._ensure_params + if value is None: + params[NameObject("/Size")] = NullObject() + else: + params[NameObject("/Size")] = value + + @property + def creation_date(self) -> datetime.datetime | None: + """Retrieve the file creation datetime.""" + return parse_iso8824_date(self._params.get("/CreationDate")) + + @creation_date.setter + def creation_date(self, value: datetime.datetime | None) -> None: + """Set the file creation datetime.""" + params = self._ensure_params + if value is None: + params[NameObject("/CreationDate")] = NullObject() + else: + date_str = format_iso8824_date(value) + params[NameObject("/CreationDate")] = TextStringObject(date_str) + + @property + def modification_date(self) -> datetime.datetime | None: + """Retrieve the datetime of the last file modification.""" + return parse_iso8824_date(self._params.get("/ModDate")) + + @modification_date.setter + def modification_date(self, value: datetime.datetime | None) -> None: + """Set the datetime of the last file modification.""" + params = self._ensure_params + if value is None: + params[NameObject("/ModDate")] = NullObject() + else: + date_str = format_iso8824_date(value) + params[NameObject("/ModDate")] = TextStringObject(date_str) + + @property + def checksum(self) -> bytes | None: + """Retrieve the MD5 checksum of the (uncompressed) file.""" + value = self._params.get("/CheckSum") + if is_null_or_none(value): + return None + return value + + @checksum.setter + def checksum(self, value: ByteStringObject | None) -> None: + """Set the MD5 checksum of the (uncompressed) file.""" + params = self._ensure_params + if value is None: + params[NameObject("/CheckSum")] = NullObject() + else: + params[NameObject("/CheckSum")] = value + + def delete(self) -> None: + """Delete the file from the document.""" + if not self._parent: + raise PyPdfError("Parent required to delete file from document.") + if self.pdf_object in self._parent: + index = self._parent.index(self.pdf_object) + elif ( + (indirect_reference := getattr(self.pdf_object, "indirect_reference", None)) is not None + and indirect_reference in self._parent + ): + index = self._parent.index(indirect_reference) + else: + raise PyPdfError("File not found in parent object.") + self._parent.pop(index) # Reference. + self._parent.pop(index - 1) # Name. + self.pdf_object = DictionaryObject() # Invalidate. + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} name={self.name!r}>" + + @classmethod + def _load_from_names(cls, names: ArrayObject) -> Generator[EmbeddedFile]: + """ + Convert the given name tree into class instances. + + Args: + names: The name tree to load the data from. + + Returns: + Iterable of class instances for the files found. + """ + # This is a name tree of the format [name_1, reference_1, name_2, reference_2, ...] + for i, name in enumerate(names): + if not isinstance(name, str): + # Skip plain strings and retrieve them as `direct_name` by index. + file_dictionary = name.get_object() + direct_name = names[i - 1].get_object() + yield EmbeddedFile(name=direct_name, pdf_object=file_dictionary, parent=names) + + @classmethod + def _load(cls, catalog: DictionaryObject) -> Generator[EmbeddedFile]: + """ + Load the embedded files for the given document catalog. + + This method and its signature are considered internal API and thus not exposed publicly for now. + + Args: + catalog: The document catalog to load from. + + Returns: + Iterable of class instances for the files found. + """ + try: + container = cast( + DictionaryObject, + cast(DictionaryObject, catalog["/Names"])["/EmbeddedFiles"], + ) + except KeyError: + return + + if "/Kids" in container: + for kid in cast(ArrayObject, container["/Kids"].get_object()): + # There might be further (nested) kids here. + # Wait for an example before evaluating an implementation. + kid = kid.get_object() + if "/Names" in kid: + yield from cls._load_from_names(cast(ArrayObject, kid["/Names"])) + if "/Names" in container: + yield from cls._load_from_names(cast(ArrayObject, container["/Names"])) diff --git a/.venv/lib/python3.13/site-packages/pypdf/generic/_fit.py b/.venv/lib/python3.13/site-packages/pypdf/generic/_fit.py new file mode 100644 index 0000000000000000000000000000000000000000..90d7a35aaa378bfb2954bda726e74da5340de9a0 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/generic/_fit.py @@ -0,0 +1,174 @@ +from typing import Any, Optional, Union + +from ._base import is_null_or_none + + +class Fit: + def __init__( + self, fit_type: str, fit_args: tuple[Union[float, Any, None], ...] = () + ) -> None: + from ._base import FloatObject, NameObject, NullObject, NumberObject # noqa: PLC0415 + + self.fit_type = NameObject(fit_type) + self.fit_args: list[Union[NullObject, FloatObject, NumberObject]] = [ + NullObject() if is_null_or_none(a) else FloatObject(a) for a in fit_args + ] + + @classmethod + def xyz( + cls, + left: Optional[float] = None, + top: Optional[float] = None, + zoom: Optional[float] = None, + ) -> "Fit": + """ + Display the page designated by page, with the coordinates (left, top) + positioned at the upper-left corner of the window and the contents + of the page magnified by the factor zoom. + + A null value for any of the parameters left, top, or zoom specifies + that the current value of that parameter is to be retained unchanged. + + A zoom value of 0 has the same meaning as a null value. + + Args: + left: + top: + zoom: + + Returns: + The created fit object. + + """ + return Fit(fit_type="/XYZ", fit_args=(left, top, zoom)) + + @classmethod + def fit(cls) -> "Fit": + """ + Display the page designated by page, with its contents magnified just + enough to fit the entire page within the window both horizontally and + vertically. + + If the required horizontal and vertical magnification factors are + different, use the smaller of the two, centering the page within the + window in the other dimension. + """ + return Fit(fit_type="/Fit") + + @classmethod + def fit_horizontally(cls, top: Optional[float] = None) -> "Fit": + """ + Display the page designated by page, with the vertical coordinate top + positioned at the top edge of the window and the contents of the page + magnified just enough to fit the entire width of the page within the + window. + + A null value for ``top`` specifies that the current value of that + parameter is to be retained unchanged. + + Args: + top: + + Returns: + The created fit object. + + """ + return Fit(fit_type="/FitH", fit_args=(top,)) + + @classmethod + def fit_vertically(cls, left: Optional[float] = None) -> "Fit": + return Fit(fit_type="/FitV", fit_args=(left,)) + + @classmethod + def fit_rectangle( + cls, + left: Optional[float] = None, + bottom: Optional[float] = None, + right: Optional[float] = None, + top: Optional[float] = None, + ) -> "Fit": + """ + Display the page designated by page, with its contents magnified + just enough to fit the rectangle specified by the coordinates + left, bottom, right, and top entirely within the window + both horizontally and vertically. + + If the required horizontal and vertical magnification factors are + different, use the smaller of the two, centering the rectangle within + the window in the other dimension. + + A null value for any of the parameters may result in unpredictable + behavior. + + Args: + left: + bottom: + right: + top: + + Returns: + The created fit object. + + """ + return Fit(fit_type="/FitR", fit_args=(left, bottom, right, top)) + + @classmethod + def fit_box(cls) -> "Fit": + """ + Display the page designated by page, with its contents magnified just + enough to fit its bounding box entirely within the window both + horizontally and vertically. + + If the required horizontal and vertical magnification factors are + different, use the smaller of the two, centering the bounding box + within the window in the other dimension. + """ + return Fit(fit_type="/FitB") + + @classmethod + def fit_box_horizontally(cls, top: Optional[float] = None) -> "Fit": + """ + Display the page designated by page, with the vertical coordinate top + positioned at the top edge of the window and the contents of the page + magnified just enough to fit the entire width of its bounding box + within the window. + + A null value for top specifies that the current value of that parameter + is to be retained unchanged. + + Args: + top: + + Returns: + The created fit object. + + """ + return Fit(fit_type="/FitBH", fit_args=(top,)) + + @classmethod + def fit_box_vertically(cls, left: Optional[float] = None) -> "Fit": + """ + Display the page designated by page, with the horizontal coordinate + left positioned at the left edge of the window and the contents of the + page magnified just enough to fit the entire height of its bounding box + within the window. + + A null value for left specifies that the current value of that + parameter is to be retained unchanged. + + Args: + left: + + Returns: + The created fit object. + + """ + return Fit(fit_type="/FitBV", fit_args=(left,)) + + def __str__(self) -> str: + if not self.fit_args: + return f"Fit({self.fit_type})" + return f"Fit({self.fit_type}, {self.fit_args})" + + +DEFAULT_FIT = Fit.fit() diff --git a/.venv/lib/python3.13/site-packages/pypdf/generic/_image_inline.py b/.venv/lib/python3.13/site-packages/pypdf/generic/_image_inline.py new file mode 100644 index 0000000000000000000000000000000000000000..f689f177f8ee9e72d3d921db536d2a33b3a5b3e5 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/generic/_image_inline.py @@ -0,0 +1,322 @@ +# Copyright (c) 2024, pypdf contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * The name of the author may not be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +import logging +from io import BytesIO +from typing import IO + +from .._utils import ( + WHITESPACES, + WHITESPACES_AS_BYTES, + BinaryStreamType, + StreamType, + logger_warning, + read_non_whitespace, +) +from ..errors import PdfReadError + +logger = logging.getLogger(__name__) + +# An inline image should be used only for small images (4096 bytes or less), +# but allow twice this for cases where this has been exceeded. +BUFFER_SIZE = 8192 + + +def _check_end_image_marker(stream: StreamType) -> bool: + ei_tok = read_non_whitespace(stream) + ei_tok += stream.read(2) + stream.seek(-3, 1) + return ei_tok[:2] == b"EI" and (ei_tok[2:3] == b"" or ei_tok[2:3] in WHITESPACES) + + +def extract_inline__ascii_hex_decode(stream: StreamType) -> bytes: + """ + Extract HexEncoded stream from inline image. + The stream will be moved onto the EI. + """ + data_out = bytearray() + # Read data until delimiter > and EI as backup. + while True: + data_buffered = read_non_whitespace(stream) + (read_bytes := stream.read(BUFFER_SIZE)) + if not data_buffered or not read_bytes: + raise PdfReadError("Unexpected end of stream.") + pos_tok = data_buffered.find(b">") + if pos_tok >= 0: # found > + data_out += data_buffered[: pos_tok + 1] + stream.seek(-len(data_buffered) + pos_tok + 1, 1) + break + pos_ei = data_buffered.find(b"EI") + if pos_ei >= 0: # found EI + stream.seek(-len(data_buffered) + pos_ei - 1, 1) + c = stream.read(1) + while c in WHITESPACES: + stream.seek(-2, 1) + c = stream.read(1) + pos_ei -= 1 + data_out += data_buffered[:pos_ei] + break + if len(data_buffered) == 2: + data_out += data_buffered + raise PdfReadError("Unexpected end of stream.") + # Neither > nor EI found + data_out += data_buffered[:-2] + stream.seek(-2, 1) + + if not _check_end_image_marker(stream): + raise PdfReadError("EI stream not found.") + return bytes(data_out) + + +def extract_inline__ascii85_decode(stream: StreamType) -> bytes: + """ + Extract A85 stream from inline image. + The stream will be moved onto the EI. + """ + data_out = bytearray() + # Read data until delimiter ~> + while True: + data_buffered = read_non_whitespace(stream) + (read_bytes := stream.read(BUFFER_SIZE)) + if not data_buffered or not read_bytes: + raise PdfReadError("Unexpected end of stream.") + pos_tok = data_buffered.find(b"~>") + if pos_tok >= 0: # found! + data_out += data_buffered[: pos_tok + 2] + stream.seek(-len(data_buffered) + pos_tok + 2, 1) + break + if len(data_buffered) == 2: # end of buffer + data_out += data_buffered + raise PdfReadError("Unexpected end of stream.") + data_out += data_buffered[ + :-2 + ] # back by one char in case of in the middle of ~> + stream.seek(-2, 1) + + if not _check_end_image_marker(stream): + raise PdfReadError("EI stream not found.") + return bytes(data_out) + + +def extract_inline__run_length_decode(stream: StreamType) -> bytes: + """ + Extract RL (RunLengthDecode) stream from inline image. + The stream will be moved onto the EI. + """ + data_out = bytearray() + # Read data until delimiter 128 + while True: + data_buffered = stream.read(BUFFER_SIZE) + if not data_buffered: + raise PdfReadError("Unexpected end of stream.") + pos_tok = data_buffered.find(b"\x80") + if pos_tok >= 0: # found + # Ideally, we could just use plain run-length decoding here, where 80_16 = 128_10 + # marks the EOD. But there apparently are cases like in issue #3517, where we have + # an inline image with up to 51 EOD markers. In these cases, be resilient here and + # use the default `EI` marker detection instead. Please note that this fallback + # still omits special `EI` handling within the stream, but for now assume that having + # both of these cases occur at the same time is very unlikely (and the image stream + # is broken anyway). + # For now, do not skip over more than one whitespace character. + after_token = data_buffered[pos_tok + 1 : pos_tok + 4] + if after_token.startswith(b"EI") or after_token.endswith(b"EI"): + data_out += data_buffered[: pos_tok + 1] + stream.seek(-len(data_buffered) + pos_tok + 1, 1) + else: + logger_warning("Early EOD in RunLengthDecode of inline image, using fallback.", source=__name__) + ei_marker = data_buffered.find(b"EI") + if ei_marker > 0: + data_out += data_buffered[: ei_marker] + stream.seek(-len(data_buffered) + ei_marker - 1, 1) + break + data_out += data_buffered + + if not _check_end_image_marker(stream): + raise PdfReadError("EI stream not found.") + return bytes(data_out) + + +def extract_inline__dct_decode(stream: BinaryStreamType) -> bytes: + """ + Extract DCT (JPEG) stream from inline image. + The stream will be moved onto the EI. + """ + def read(length: int) -> bytes: + # If 0 bytes are returned, and *size* was not 0, this indicates end of file. + # If the object is in non-blocking mode and no bytes are available, `None` is returned. + _result = stream.read(length) + if _result is None or len(_result) != length: + raise PdfReadError("Unexpected end of stream.") + return _result + + data_out = bytearray() + # Read Blocks of data (ID/Size/data) up to ID=FF/D9 + # https://www.digicamsoft.com/itu/itu-t81-36.html + not_first = False + while True: + c = read(1) + if not_first or (c == b"\xff"): + data_out += c + if c != b"\xff": + continue + not_first = True + c = read(1) + data_out += c + if c == b"\xff": + stream.seek(-1, 1) # pragma: no cover + elif c == b"\x00": # stuffing + pass + elif c == b"\xd9": # end + break + elif c in ( + b"\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc9\xca\xcb\xcc\xcd\xce\xcf" + b"\xda\xdb\xdc\xdd\xde\xdf" + b"\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xfe" + ): + c = read(2) + data_out += c + sz = c[0] * 256 + c[1] + data_out += read(sz - 2) + + if not _check_end_image_marker(stream): + raise PdfReadError("EI stream not found.") + return bytes(data_out) + + +def extract_inline_default(stream: StreamType) -> bytes: + """Legacy method, used by default""" + stream_out = BytesIO() + # Read the inline image, while checking for EI (End Image) operator. + while True: + data_buffered = stream.read(BUFFER_SIZE) + if not data_buffered: + raise PdfReadError("Unexpected end of stream.") + pos_ei = data_buffered.find( + b"E" + ) # We can not look straight for "EI" because it may not have been loaded in the buffer + + if pos_ei == -1: + stream_out.write(data_buffered) + else: + # Write out everything including E (the one from EI to be removed) + stream_out.write(data_buffered[0 : pos_ei + 1]) + sav_pos_ei = stream_out.tell() - 1 + # Seek back in the stream to read the E next + stream.seek(pos_ei + 1 - len(data_buffered), 1) + saved_pos = stream.tell() + # Check for End Image + tok2 = stream.read(1) # I of "EI" + if tok2 != b"I": + stream.seek(saved_pos, 0) + continue + tok3 = stream.read(1) # possible space after "EI" + if tok3 == b"": + # The `EI` marker is at the very end of the stream. There can be + # no trailing binary data, so this is unambiguously the end of the + # inline image (#3468). + stream.seek(saved_pos - 1, 0) + stream_out.truncate(sav_pos_ei) + break + if tok3 not in WHITESPACES: + stream.seek(saved_pos, 0) + continue + while tok3 in WHITESPACES: + tok3 = stream.read(1) + if data_buffered[pos_ei - 1 : pos_ei] not in WHITESPACES and tok3 not in { + b"Q", + b"E", + }: # for Q or EMC + stream.seek(saved_pos, 0) + continue + if is_followed_by_binary_data(stream): + # Inline image contains `EI ` sequence usually marking the end of it, but + # is followed by binary data which does not make sense for the actual end. + stream.seek(saved_pos, 0) + continue + # Data contains [\s]EI[\s](Q|EMC): 4 chars are sufficient + # remove E(I) wrongly inserted earlier + stream.seek(saved_pos - 1, 0) + stream_out.truncate(sav_pos_ei) + break + + return stream_out.getvalue() + + +def is_followed_by_binary_data(stream: IO[bytes], length: int = 10) -> bool: + """ + Check if the next bytes of the stream look like binary image data or regular page content. + + This is just some heuristics due to the PDF specification being too imprecise about + inline images containing the `EI` marker which would end an image. Starting with PDF 2.0, + we finally get a mandatory length field, but with (proper) PDF 2.0 support being very limited + everywhere, we should not expect to be able to remove such hacks in the near future - especially + considering legacy documents as well. + + The actual implementation draws some inspiration from + https://github.com/itext/itext-java/blob/9.1.0/kernel/src/main/java/com/itextpdf/kernel/pdf/canvas/parser/util/InlineImageParsingUtils.java + """ + position = stream.tell() + data = stream.read(length) + stream.seek(position) + if not data: + return False + operator_start = None + operator_end = None + + for index, byte in enumerate(data): + if byte < 32 and byte not in WHITESPACES_AS_BYTES: + # This covers all characters not being displayable directly, although omitting whitespace + # to allow for operator detection. + return True + is_whitespace = byte in WHITESPACES_AS_BYTES + if operator_start is None and not is_whitespace: + # Interpret all other non-whitespace characters as the start of an operation. + operator_start = index + if operator_start is not None and is_whitespace: + # A whitespace stops an operation. + # Assume that having an inline image with tons of whitespace is rather unlikely. + operator_end = index + break + + if operator_start is None: + # Inline images should not have tons of whitespaces, which would lead to no operator start. + return False + if operator_end is None: + # We probably are inside an operation. + operator_end = length + operator_length = operator_end - operator_start + operator = data[operator_start:operator_end] + if operator.startswith(b"/") and operator_length > 1: + # Name object. + return False + if operator.replace(b".", b"").isdigit(): + # Graphics operator, for example a move. A number (integer or float). + return False + if operator_length > 3: # noqa: SIM103 + # Usually, the operators inside a content stream should not have more than three characters, + # especially after an inline image. + return True + return False diff --git a/.venv/lib/python3.13/site-packages/pypdf/generic/_image_xobject.py b/.venv/lib/python3.13/site-packages/pypdf/generic/_image_xobject.py new file mode 100644 index 0000000000000000000000000000000000000000..9179cd6628e6a1356f0418806a1a9d84815c91f2 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/generic/_image_xobject.py @@ -0,0 +1,698 @@ +"""Functions to convert an image XObject to an image""" + +import sys +from io import BytesIO +from typing import Any, Literal, Optional, Union, cast + +from .._utils import check_if_whitespace_only, logger_warning +from ..constants import ColorSpaces, ImageAttributes, StreamAttributes +from ..constants import FilterTypes as FT +from ..errors import EmptyImageDataError, LimitReachedError, PdfReadError +from ..generic import ( + ArrayObject, + DecodedStreamObject, + EncodedStreamObject, + NullObject, + TextStringObject, + is_null_or_none, +) + +if sys.version_info[:2] >= (3, 10): + from typing import TypeAlias +else: + from typing_extensions import TypeAlias + + +try: + from PIL import Image, UnidentifiedImageError +except ImportError: + raise ImportError( + "pillow is required to do image extraction. " + "It can be installed via 'pip install pypdf[image]'" + ) + +mode_str_type: TypeAlias = Literal[ + "", "1", "RGB", "2bits", "4bits", "P", "L", "RGBA", "CMYK" +] + +MAX_IMAGE_MODE_NESTING_DEPTH: int = 10 + + +def _get_image_mode( + color_space: Union[str, list[Any], Any], + color_components: int, + prev_mode: mode_str_type, + depth: int = 0, +) -> tuple[mode_str_type, bool]: + """ + Returns: + Image mode, not taking into account mask (transparency). + ColorInversion is required (like for some DeviceCMYK). + + """ + if depth > MAX_IMAGE_MODE_NESTING_DEPTH: + raise PdfReadError( + "Color spaces nested too deeply. If required, consider increasing MAX_IMAGE_MODE_NESTING_DEPTH." + ) + if is_null_or_none(color_space): + return "", False + color_space_str: str = "" + if isinstance(color_space, str): + color_space_str = color_space + elif not isinstance(color_space, list): + raise PdfReadError( + "Cannot interpret color space", color_space + ) # pragma: no cover + elif not color_space: + return "", False + elif color_space[0].startswith("/Cal"): # /CalRGB or /CalGray + color_space_str = "/Device" + color_space[0][4:] + elif color_space[0] == "/ICCBased": + icc_profile = color_space[1].get_object() + color_components = cast(int, icc_profile["/N"]) + color_space_str = icc_profile.get("/Alternate", "") + elif color_space[0] == "/Indexed": + color_space_str = color_space[1].get_object() + mode, invert_color = _get_image_mode( + color_space_str, color_components, prev_mode, depth + 1 + ) + if mode in ("RGB", "CMYK"): + mode = "P" + return mode, invert_color + elif color_space[0] == "/Separation": + color_space_str = color_space[2].get_object() + mode, invert_color = _get_image_mode( + color_space_str, color_components, prev_mode, depth + 1 + ) + return mode, True + elif color_space[0] == "/DeviceN": + original_color_space = color_space + color_components = len(color_space[1]) + color_space_str = color_space[2].get_object() + if color_space_str == "/DeviceCMYK" and color_components == 1: + if original_color_space[1][0] != "/Black": + logger_warning( + "Color %(color)s converted to Gray. Please share PDF with pypdf dev team", + source=__name__, + color=original_color_space[1][0], + ) + return "L", True + mode, invert_color = _get_image_mode( + color_space_str, color_components, prev_mode, depth + 1 + ) + return mode, invert_color + + mode_map: dict[str, mode_str_type] = { + "1bit": "1", # must be zeroth position: color_components may index the values + "/DeviceGray": "L", # must be first position: color_components may index the values + "palette": "P", # must be second position: color_components may index the values + "/DeviceRGB": "RGB", # must be third position: color_components may index the values + "/DeviceCMYK": "CMYK", # must be fourth position: color_components may index the values + "2bit": "2bits", + "4bit": "4bits", + } + + mode_values = list(mode_map.values()) + mode = ( + mode_map.get(color_space_str) + or ( + mode_values[color_components] + if 0 <= color_components < len(mode_values) + else None + ) + or prev_mode + ) + + return mode, mode == "CMYK" + + +def bits2byte( + data: bytes, + size: tuple[int, int], + bits: int, + colors: int = 1, + scale: bool = False, +) -> bytes: + from pypdf.filters import FLATE_MAX_BUFFER_SIZE # noqa: PLC0415 + + # Number of samples per row = pixels per row * components per pixel. + samples_per_row = size[0] * colors + buffer_size = samples_per_row * size[1] + if buffer_size > FLATE_MAX_BUFFER_SIZE: + raise LimitReachedError(f"Requested buffer size {buffer_size} exceeds limit of {FLATE_MAX_BUFFER_SIZE}.") + + byte_buffer = bytearray(buffer_size) + mask = (1 << bits) - 1 + # Scale a b-bit sample up to the full 0-255 range (e.g. 4-bit 15 -> 255) + # when the output is consumed directly as color (RGB) rather than as a + # palette index. + factor = 255 // mask if scale and mask else 1 + + required = size[1] * ((samples_per_row * bits + 7) // 8) + if (length := len(data)) < required: + logger_warning("Image data is not rectangular. Adding padding.", source=__name__) + data += b"\x00" * (required - length) + + data_index = 0 + bit = 8 - bits + for y in range(size[1]): + if bit != 8 - bits: + data_index += 1 + bit = 8 - bits + for x in range(samples_per_row): + byte_buffer[x + y * samples_per_row] = ( + ((data[data_index] >> bit) & mask) * factor + ) + bit -= bits + if bit < 0: + data_index += 1 + bit = 8 - bits + return bytes(byte_buffer) + + +def _expand_low_bit_samples( + mode: mode_str_type, + size: tuple[int, int], + data: bytes, + color_space: Union[str, ArrayObject], +) -> tuple[mode_str_type, bytes]: + """ + Expand 2- or 4-bit-per-component samples to one byte per component. + + Pillow has no mode for sub-byte samples, so the packed data has to be + unpacked before an image can be built from it. For a single-component + color space the samples are palette/grayscale indices ("P"). For a + multi-component space such as /DeviceRGB they are interleaved color + components, so they are also scaled to the full 0-255 range and become + an "RGB" image. + + Returns the resulting mode and data, unchanged when the mode is not a + low-bit one. + """ + if mode not in ("2bits", "4bits"): + return mode, data + bits = int(mode[0]) + if color_space == "/DeviceRGB": + return "RGB", bits2byte(data, size, bits, colors=3, scale=True) + return "P", bits2byte(data, size, bits) + + +def _image_from_bytes( + mode: str, size: tuple[int, int], data: bytes +) -> Image.Image: + pixel_count = size[0] * size[1] + bytes_per_pixel = len(mode) + required_byte_count = pixel_count * bytes_per_pixel + + from pypdf.filters import FLATE_MAX_BUFFER_SIZE # noqa: PLC0415 + if required_byte_count > FLATE_MAX_BUFFER_SIZE: + raise LimitReachedError( + f"Requested image buffer size {required_byte_count} exceeds limit {FLATE_MAX_BUFFER_SIZE}." + ) + + try: + img = Image.frombytes(mode, size, data) + except ValueError as exc: + data_length = len(data) + if data_length == 0: + raise EmptyImageDataError( + "Data is 0 bytes, cannot process an image from empty data." + ) from exc + if data_length % pixel_count != 0: + raise + k = required_byte_count / data_length + data = b"".join(bytes((x,) * int(k)) for x in data) + img = Image.frombytes(mode, size, data) + return img + + +def __handle_flate__indexed(color_space: ArrayObject) -> tuple[Any, Any, Any, Any]: + count = len(color_space) + if count == 4: + color_space, base, hival, lookup = (value.get_object() for value in color_space) + return color_space, base, hival, lookup + + # Deal with strange AutoDesk files where `base` and `hival` look like this: + # /DeviceRGB\x00255 + element1 = color_space[1] + element1 = element1 if isinstance(element1, str) else element1.get_object() + if count == 3 and "\x00" in element1: + color_space, lookup = color_space[0].get_object(), color_space[2].get_object() + base, hival = element1.split("\x00") + hival = int(hival) + return color_space, base, hival, lookup + raise PdfReadError(f"Expected color space with 4 values, got {count}: {color_space}") + + +def _handle_flate( + size: tuple[int, int], + data: bytes, + mode: mode_str_type, + color_space: Union[str, ArrayObject], + colors: int, + obj_as_text: str, +) -> tuple[Image.Image, str, str, bool]: + """ + Process image encoded using the zlib/deflate compression method, corresponds to the FlateDecode filter + Returns img, image_format, extension, color inversion + """ + base: Any + hival: Any + lookup: Any + if isinstance(color_space, ArrayObject) and color_space[0] == "/Indexed": + color_space, base, hival, lookup = __handle_flate__indexed(color_space) + mode, data = _expand_low_bit_samples(mode, size, data, color_space) + img = _image_from_bytes(mode, size, data) + if color_space == "/Indexed": + if isinstance(lookup, (EncodedStreamObject, DecodedStreamObject)): + lookup = lookup.get_data() + if isinstance(lookup, TextStringObject): + lookup = lookup.original_bytes + if isinstance(lookup, str): + lookup = lookup.encode() + try: + nb, conv, mode = { # type: ignore[assignment] + "1": (0, "", ""), + "L": (1, "P", "L"), + "P": (0, "", ""), + "RGB": (3, "P", "RGB"), + "CMYK": (4, "P", "CMYK"), + }[_get_image_mode(base, 0, "")[0]] + except KeyError: # pragma: no cover + logger_warning( + "Base %(base)s not coded. Please share PDF with pypdf dev team", + source=__name__, + base=base, + ) + lookup = None + else: + if img.mode == "1" and nb == 0: + # A two-color lookup needs at least one byte per color, but the + # base color space resolves to a 1-bit or palette image. + logger_warning( + "Cannot apply lookup for base %(base)s to image with mode 1. " + "Please share PDF with pypdf dev team", + source=__name__, + base=base, + ) + elif img.mode == "1": + # Two values ("high" and "low"). + expected_count = 2 * nb + actual_count = len(lookup) + if actual_count != expected_count: + if actual_count < expected_count: + logger_warning( + "Not enough lookup values: Expected %(expected_count)d, got %(actual_count)d.", + source=__name__, + expected_count=expected_count, + actual_count=actual_count, + ) + lookup += bytes([0] * (expected_count - actual_count)) + elif not check_if_whitespace_only(lookup[expected_count:]): + logger_warning( + "Too many lookup values: Expected %(expected_count)d, got %(actual_count)d.", + source=__name__, + expected_count=expected_count, + actual_count=actual_count, + ) + lookup = lookup[:expected_count] + colors_arr = [lookup[:nb], lookup[nb:]] + source = img.convert("L") + bands = [ + source.point( + [low_value] * 128 + [high_value] * 128 + ) + for low_value, high_value in zip(colors_arr[0], colors_arr[1]) + ] + img = bands[0] if nb == 1 else Image.merge(mode, bands) + else: + img = img.convert(conv) + if len(lookup) != (hival + 1) * nb: + logger_warning("Invalid Lookup Table in %(obj_as_text)s", source=__name__, obj_as_text=obj_as_text) + lookup = None + elif mode == "L": + # gray lookup does not work: it is converted to a similar RGB lookup + lookup = b"".join([bytes([b, b, b]) for b in lookup]) + mode = "RGB" + # TODO: https://github.com/py-pdf/pypdf/pull/2039 + # this is a work around until PIL is able to process CMYK images + elif mode == "CMYK": + _rgb = [] + for _c, _m, _y, _k in ( + lookup[n : n + 4] for n in range(0, 4 * (len(lookup) // 4), 4) + ): + _r = int(255 * (1 - _c / 255) * (1 - _k / 255)) + _g = int(255 * (1 - _m / 255) * (1 - _k / 255)) + _b = int(255 * (1 - _y / 255) * (1 - _k / 255)) + _rgb.append(bytes((_r, _g, _b))) + lookup = b"".join(_rgb) + mode = "RGB" + if lookup is not None: + img.putpalette(lookup, rawmode=mode) + img = img.convert("L" if base == ColorSpaces.DEVICE_GRAY else "RGB") + elif not is_null_or_none(color_space) and color_space[0] == "/ICCBased": + # Exclude pure black-and-white images. + # TODO: The remaining code still does not look correct. Shouldn't the proper way be + # to use the original image and apply the ICC transformation on it? + # For now, this just loads the original image with a different color space. + if mode != "1": + # Table 65 - Additional Entries Specific to an ICC Profile Stream Dictionary + mode2 = _get_image_mode(color_space, colors, mode)[0] + if mode != mode2: + img = Image.frombytes(mode, size, data) # reloaded as mode may have changed + if mode == "CMYK": + image_format = "TIFF" + extension = ".tif" + else: + image_format = "PNG" + extension = ".png" # mime_type: "image/png" + return img, image_format, extension, False + + +def _handle_jpx( + size: tuple[int, int], + data: bytes, + mode: mode_str_type, + color_space: str, + colors: int, +) -> tuple[Image.Image, str, str, bool]: + """ + Process image encoded as JPX/JPEG2000 + Returns img, image_format, extension, inversion + """ + img1: Image.Image = Image.open(BytesIO(data), formats=("JPEG2000",)) + mode, invert_color = _get_image_mode(color_space, colors, mode) + if mode == "": + mode = cast(mode_str_type, img1.mode) + invert_color = mode == "CMYK" + if img1.mode == "RGBA" and mode == "RGB": + mode = "RGBA" + # we need to convert to the good mode + if img1.mode == mode or {img1.mode, mode} == {"L", "P"}: # compare (unordered) sets + # L and P are indexed modes which should not be changed. + img = img1 + elif {img1.mode, mode} == {"RGBA", "CMYK"}: + # RGBA / CMYK are 4bytes encoding where + # the encoding should be corrected + img = Image.frombytes(mode, img1.size, img1.tobytes()) + else: # pragma: no cover + img = img1.convert(mode) + # CMYK conversion + # https://stackverflow.com/questions/38855022/ + if img.mode == "CMYK" and color_space == "/ICCBased": + img = img.convert("RGB") + return img, "JPEG2000", ".jp2", invert_color + + +def _apply_decode( + img: Image.Image, + x_object: dict[str, Any], + lfilters: FT, + color_space: Union[str, list[Any], Any], + invert_color: bool, +) -> Image.Image: + # CMYK image and other color spaces without decode + # requires reverting scale (cf p243,2§ last sentence) + if ImageAttributes.DECODE in x_object: + decode = x_object[ImageAttributes.DECODE] + # if invert_color and lfilters == FT.DCT_DECODE: + # decode = list(reversed(decode)) + elif img.mode == "CMYK" and lfilters == FT.JPX_DECODE: + decode = [1.0, 0.0] if not invert_color else [0.0, 1.0] + decode = decode * len(img.getbands()) + elif (img.mode == "CMYK" and lfilters == FT.DCT_DECODE) or (invert_color and img.mode == "L"): + decode = [1.0, 0.0] * len(img.getbands()) + else: + decode = None + + if ( + isinstance(color_space, ArrayObject) + and color_space[0].get_object() == "/Indexed" + ): + decode = None # decode is meaningless if Indexed + if ( + isinstance(color_space, ArrayObject) + and color_space[0].get_object() == "/Separation" + ): + decode = [1.0, 0.0] * len(img.getbands()) + if decode is not None and ( + not isinstance(decode, list) or len(decode) % 2 != 0 + ): + # /Decode is read straight from the image dictionary and must hold an + # even number of values (a [min max] pair per component). A malformed + # array would otherwise read past its end at decode[i + 1]; drop it and + # render the image without the remap. + logger_warning( + "Ignoring malformed /Decode array %(decode)s; expected an even number of values.", + source=__name__, + decode=decode, + ) + decode = None + if decode is not None and not all(decode[i] == i % 2 for i in range(len(decode))): + lut: list[int] = [] + for i in range(0, len(decode), 2): + dmin = decode[i] + dmax = decode[i + 1] + lut.extend( + round(255.0 * (j / 255.0 * (dmax - dmin) + dmin)) for j in range(256) + ) + img = img.point(lut) + return img + + +def _get_mode_and_invert_color( + x_object: dict[str, Any], colors: int, color_space: Union[str, list[Any], Any] +) -> tuple[mode_str_type, bool]: + if ( + ImageAttributes.COLOR_SPACE in x_object + and x_object[ImageAttributes.COLOR_SPACE] == ColorSpaces.DEVICE_RGB + ): + # https://pillow.readthedocs.io/en/stable/handbook/concepts.html#modes + mode: mode_str_type = "RGB" + if x_object.get("/BitsPerComponent", 8) < 8: + mode, invert_color = _get_image_mode( + f"{x_object.get('/BitsPerComponent', 8)}bit", 0, "" + ) + else: + mode, invert_color = _get_image_mode( + color_space, + 2 + if ( + colors == 1 + and ( + not is_null_or_none(color_space) + and "Gray" not in color_space + ) + ) + else colors, + "", + ) + return mode, invert_color + + +def _xobj_to_image( + x_object: dict[str, Any], + pillow_parameters: Union[dict[str, Any], None] = None, + visited: Optional[set[int]] = None, +) -> tuple[Optional[str], bytes, Any]: + """ + Users need to have the pillow package installed. + + It's unclear if pypdf will keep this function here, hence it's private. + It might get removed at any point. + + Args: + x_object: + pillow_parameters: parameters provided to Pillow Image.save() method, + cf. + visited: Set of id() values of XObjects already being converted higher + up the /SMask chain, used to detect cyclic soft masks. + + Returns: + Tuple[file extension, bytes, PIL.Image.Image] + + """ + if visited is None: + visited = set() + visited.add(id(x_object)) + + def _apply_alpha( + img: Image.Image, + x_object: dict[str, Any], + obj_as_text: str, + image_format: str, + extension: str, + ) -> tuple[Image.Image, str, str]: + if ImageAttributes.S_MASK in x_object: # add alpha channel + s_mask = x_object[ImageAttributes.S_MASK] + if id(s_mask) in visited: + # A soft mask that refers back to an image already being + # converted would recurse until the interpreter runs out of + # stack. Such a chain cannot describe a real alpha channel, so + # drop the mask and keep the image we have. + logger_warning( + "Ignoring cyclic /SMask reference in %(obj_as_text)s", + source=__name__, + obj_as_text=obj_as_text, + ) + return img, extension, image_format + alpha = _xobj_to_image(s_mask, visited=visited)[2] + if img.size != alpha.size: + logger_warning( + "image and mask size not matching: %(obj_as_text)s", + source=__name__, + obj_as_text=obj_as_text, + ) + else: + # TODO: implement mask + if alpha.mode != "L": + alpha = alpha.convert("L") + if img.mode == "P": + img = img.convert("RGB") + elif img.mode == "1": + img = img.convert("L") + img.putalpha(alpha) + if "JPEG" in image_format: + image_format = "JPEG2000" + extension = ".jp2" + else: + image_format = "PNG" + extension = ".png" + return img, extension, image_format + + # For error reporting + obj_as_text = ( + x_object.indirect_reference.__repr__() + if x_object is None # pragma: no cover + else x_object.__repr__() + ) + + # Get size and data + size = (cast(int, x_object[ImageAttributes.WIDTH]), cast(int, x_object[ImageAttributes.HEIGHT])) + data = x_object.get_data() # type: ignore[attr-defined] + if isinstance(data, str): # pragma: no cover + data = data.encode() + if len(data) % (size[0] * size[1]) == 1 and data[-1] == 0x0A: # i.e. '\n' + data = data[:-1] + + # Get color properties + colors = x_object.get("/Colors", 1) + color_space: Any = x_object.get("/ColorSpace", NullObject()).get_object() + if isinstance(color_space, list) and len(color_space) == 1: + color_space = color_space[0].get_object() + + mode, invert_color = _get_mode_and_invert_color(x_object, colors, color_space) + + # Get filters + filters = x_object.get(StreamAttributes.FILTER, NullObject()).get_object() + lfilters = filters[-1] if isinstance(filters, list) else filters + decode_parms = x_object.get(StreamAttributes.DECODE_PARMS) + if decode_parms and isinstance(decode_parms, (tuple, list)): + decode_parms = decode_parms[0] + else: + decode_parms = {} + if not isinstance(decode_parms, dict): + decode_parms = {} + + extension = None + if lfilters in (FT.FLATE_DECODE, FT.RUN_LENGTH_DECODE): + img, image_format, extension, _ = _handle_flate( + size, + data, + mode, + color_space, + colors, + obj_as_text, + ) + elif lfilters in (FT.LZW_DECODE, FT.ASCII_85_DECODE): + # I'm not sure if the following logic is correct. + # There might not be any relationship between the filters and the + # extension + if lfilters == FT.LZW_DECODE: + image_format = "TIFF" + extension = ".tiff" # mime_type = "image/tiff" + else: + image_format = "PNG" + extension = ".png" # mime_type = "image/png" + try: + img = Image.open(BytesIO(data), formats=("TIFF", "PNG")) + except UnidentifiedImageError: + fallback_mode, fallback_data = _expand_low_bit_samples( + mode, size, data, color_space + ) + img = _image_from_bytes(fallback_mode, size, fallback_data) + elif lfilters == FT.DCT_DECODE: + img, image_format, extension = Image.open(BytesIO(data)), "JPEG", ".jpg" + # invert_color kept unchanged + elif lfilters == FT.JPX_DECODE: + img, image_format, extension, invert_color = _handle_jpx( + size, data, mode, color_space, colors + ) + elif lfilters == FT.CCITT_FAX_DECODE: + img, image_format, extension, invert_color = ( + Image.open(BytesIO(data), formats=("TIFF",)), + "TIFF", + ".tiff", + False, + ) + elif lfilters == FT.JBIG2_DECODE: + img, image_format, extension, invert_color = ( + Image.open(BytesIO(data), formats=("PNG", "PPM")), + "PNG", + ".png", + False, + ) + elif mode == "CMYK": + img, image_format, extension, invert_color = ( + _image_from_bytes(mode, size, data), + "TIFF", + ".tif", + False, + ) + elif mode == "": + raise PdfReadError(f"ColorSpace field not found in {x_object}") + else: + # Images without a filter (for example inline images) reach Pillow + # directly, so low-bit samples have to be expanded here as well. + mode, data = _expand_low_bit_samples(mode, size, data, color_space) + img, image_format, extension, invert_color = ( + _image_from_bytes(mode, size, data), + "PNG", + ".png", + False, + ) + + img = _apply_decode(img, x_object, lfilters, color_space, invert_color) + img, extension, image_format = _apply_alpha( + img, x_object, obj_as_text, image_format, extension + ) + + if pillow_parameters is None: + pillow_parameters = {} + # Preserve JPEG image quality - see issue #3515. + if image_format == "JPEG": + # This prevents: Cannot use 'keep' when original image is not a JPEG: + # "JPEG" is the value of PIL.JpegImagePlugin.JpegImageFile.format + img.format = "JPEG" + if "quality" not in pillow_parameters: + pillow_parameters["quality"] = "keep" + + # Save image to bytes + img_byte_arr = BytesIO() + try: + img.save(img_byte_arr, format=image_format, **pillow_parameters) + except OSError: # pragma: no cover # covered with pillow 10.3 + # in case of we convert to RGBA and then to PNG + img1 = img.convert("RGBA") + image_format = "PNG" + extension = ".png" + img_byte_arr = BytesIO() + img1.save(img_byte_arr, format=image_format) + data = img_byte_arr.getvalue() + + try: # temporary try/except until other fixes of images + img = Image.open(BytesIO(data)) + except Exception as exception: + logger_warning("Failed loading image: %(exception)s", source=__name__, exception=exception) + img = None # type: ignore[assignment,unused-ignore] # TODO: Remove unused-ignore on Python 3.10 + return extension, data, img diff --git a/.venv/lib/python3.13/site-packages/pypdf/generic/_link.py b/.venv/lib/python3.13/site-packages/pypdf/generic/_link.py new file mode 100644 index 0000000000000000000000000000000000000000..fb1c45a11e09e2a464803b3a2e9264937a99772b --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/generic/_link.py @@ -0,0 +1,150 @@ +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * The name of the author may not be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + + +# This module contains code used by _writer.py to track links in pages +# being added to the writer until the links can be resolved. + +from typing import TYPE_CHECKING, Optional, Union, cast + +from .._utils import logger_warning +from . import ArrayObject, DictionaryObject, IndirectObject, PdfObject, TextStringObject, is_null_or_none + +if TYPE_CHECKING: + from .._page import PageObject + from .._reader import PdfReader + from .._writer import PdfWriter + + +class NamedReferenceLink: + """Named reference link being preserved until we can resolve it correctly.""" + + def __init__(self, reference: TextStringObject, source_pdf: "PdfReader") -> None: + """reference: TextStringObject with named reference""" + self._reference = reference + self._source_pdf = source_pdf + + def find_referenced_page(self) -> Union[IndirectObject, None]: + destination = self._source_pdf.named_destinations.get(str(self._reference)) + return destination.page if destination else None + + def patch_reference(self, target_pdf: "PdfWriter", new_page: IndirectObject) -> None: + """target_pdf: PdfWriter which the new link went into""" + # point named destination in new PDF to the new page + if str(self._reference) not in target_pdf.named_destinations: + target_pdf.add_named_destination(str(self._reference), new_page.page_number) + + +class DirectReferenceLink: + """Direct reference link being preserved until we can resolve it correctly.""" + + def __init__(self, reference: ArrayObject) -> None: + """reference: an ArrayObject whose first element is the Page indirect object""" + self._reference = reference + + def find_referenced_page(self) -> Union[IndirectObject, None]: + if not self._reference: + return None + return cast(IndirectObject, self._reference[0]) + + def patch_reference(self, target_pdf: "PdfWriter", new_page: IndirectObject) -> None: + """target_pdf: PdfWriter which the new link went into""" + self._reference[0] = new_page + + +ReferenceLink = Union[NamedReferenceLink, DirectReferenceLink] + + +def extract_links(new_page: "PageObject", old_page: "PageObject") -> list[tuple[ReferenceLink, ReferenceLink]]: + """Extracts links from two pages on the assumption that the two pages are + the same. Produces one list of (new link, old link) tuples. + + Non-link annotations are ignored before pairing to avoid dropping valid + links when one page includes additional non-link annotation entries. + """ + new_annotations = new_page.get("/Annots", ArrayObject()).get_object() + old_annotations = old_page.get("/Annots", ArrayObject()).get_object() + if is_null_or_none(new_annotations): + new_annotations = ArrayObject() + if is_null_or_none(old_annotations): + old_annotations = ArrayObject() + if not isinstance(new_annotations, ArrayObject) or not isinstance(old_annotations, ArrayObject): + logger_warning( + "Expected annotation arrays: %(old_annotations)s %(new_annotations)s. Ignoring annotations.", + source=__name__, + old_annotations=old_annotations, + new_annotations=new_annotations, + ) + return [] + new_links = [ + link + for annotation in new_annotations + if (link := _build_link(annotation, new_page)) is not None + ] + old_links = [ + link + for annotation in old_annotations + if (link := _build_link(annotation, old_page)) is not None + ] + + if len(new_links) != len(old_links): + logger_warning( + "Annotation sizes differ: %(old_count)d vs. %(new_count)d", + source=__name__, + old_count=len(old_links), + new_count=len(new_links), + ) + + return list(zip(new_links, old_links)) + + +def _build_link(indirect_object: IndirectObject, page: "PageObject") -> Optional[ReferenceLink]: + src = cast("PdfReader", page.pdf) + link = cast(DictionaryObject, indirect_object.get_object()) + if (not isinstance(link, DictionaryObject)) or link.get("/Subtype") != "/Link": + return None + + if "/A" in link: + action = cast(DictionaryObject, link["/A"]) + if action.get("/S") != "/GoTo": + return None + + if "/D" not in action: + return None + return _create_link(action["/D"], src) + + if "/Dest" in link: + return _create_link(link["/Dest"], src) + + return None # Nothing to do here + + +def _create_link(reference: PdfObject, source_pdf: "PdfReader") -> Optional[ReferenceLink]: + if isinstance(reference, TextStringObject): + return NamedReferenceLink(reference, source_pdf) + if isinstance(reference, ArrayObject): + return DirectReferenceLink(reference) + return None diff --git a/.venv/lib/python3.13/site-packages/pypdf/generic/_outline.py b/.venv/lib/python3.13/site-packages/pypdf/generic/_outline.py new file mode 100644 index 0000000000000000000000000000000000000000..c76898b54483ef1de7de8faff0dacdac10e90463 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/generic/_outline.py @@ -0,0 +1,33 @@ +from typing import Union + +from .._utils import StreamType, deprecation_no_replacement +from ._base import NameObject +from ._data_structures import Destination + + +class OutlineItem(Destination): + def write_to_stream( + self, stream: StreamType, encryption_key: Union[str, bytes, None] = None + ) -> None: + if encryption_key is not None: # deprecated + deprecation_no_replacement( + "the encryption_key parameter of write_to_stream", "5.0.0" + ) + stream.write(b"<<\n") + for key in [ + NameObject(x) + for x in ["/Title", "/Parent", "/First", "/Last", "/Next", "/Prev"] + if x in self + ]: + key.write_to_stream(stream) + stream.write(b" ") + value = self.raw_get(key) + value.write_to_stream(stream) + stream.write(b"\n") + key = NameObject("/Dest") + key.write_to_stream(stream) + stream.write(b" ") + value = self.dest_array + value.write_to_stream(stream) + stream.write(b"\n") + stream.write(b">>") diff --git a/.venv/lib/python3.13/site-packages/pypdf/generic/_rectangle.py b/.venv/lib/python3.13/site-packages/pypdf/generic/_rectangle.py new file mode 100644 index 0000000000000000000000000000000000000000..c07d6bb1f42e90e01066055384c5aeea07d27a23 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/generic/_rectangle.py @@ -0,0 +1,136 @@ +from typing import Any, Union + +from ._base import FloatObject, NumberObject +from ._data_structures import ArrayObject + + +class RectangleObject(ArrayObject): + """ + This class is used to represent *page boxes* in pypdf. + + These boxes include: + + * :attr:`artbox ` + * :attr:`bleedbox ` + * :attr:`cropbox ` + * :attr:`mediabox ` + * :attr:`trimbox ` + """ + + def __init__( + self, arr: Union["RectangleObject", tuple[float, float, float, float]] + ) -> None: + # must have four points + assert len(arr) == 4 + # automatically convert arr[x] into NumberObject(arr[x]) if necessary + ArrayObject.__init__(self, [self._ensure_is_number(x) for x in arr]) + + def _ensure_is_number(self, value: Any) -> Union[FloatObject, NumberObject]: + if not isinstance(value, (FloatObject, NumberObject)): + return FloatObject(value) + return value + + def scale(self, sx: float, sy: float) -> "RectangleObject": + return RectangleObject( + ( + float(self.left) * sx, + float(self.bottom) * sy, + float(self.right) * sx, + float(self.top) * sy, + ) + ) + + def __repr__(self) -> str: + return f"RectangleObject({list(self)!r})" + + @property + def left(self) -> FloatObject: + value: FloatObject = self[0] + return value + + @left.setter + def left(self, f: float) -> None: + self[0] = FloatObject(f) + + @property + def bottom(self) -> FloatObject: + value: FloatObject = self[1] + return value + + @bottom.setter + def bottom(self, f: float) -> None: + self[1] = FloatObject(f) + + @property + def right(self) -> FloatObject: + value: FloatObject = self[2] + return value + + @right.setter + def right(self, f: float) -> None: + self[2] = FloatObject(f) + + @property + def top(self) -> FloatObject: + value: FloatObject = self[3] + return value + + @top.setter + def top(self, f: float) -> None: + self[3] = FloatObject(f) + + @property + def lower_left(self) -> tuple[float, float]: + """ + Property to read and modify the lower left coordinate of this box + in (x,y) form. + """ + return self.left, self.bottom + + @lower_left.setter + def lower_left(self, value: tuple[float, float]) -> None: + self[0], self[1] = (self._ensure_is_number(x) for x in value) + + @property + def lower_right(self) -> tuple[float, float]: + """ + Property to read and modify the lower right coordinate of this box + in (x,y) form. + """ + return self.right, self.bottom + + @lower_right.setter + def lower_right(self, value: tuple[float, float]) -> None: + self[2], self[1] = (self._ensure_is_number(x) for x in value) + + @property + def upper_left(self) -> tuple[float, float]: + """ + Property to read and modify the upper left coordinate of this box + in (x,y) form. + """ + return self.left, self.top + + @upper_left.setter + def upper_left(self, value: tuple[float, float]) -> None: + self[0], self[3] = (self._ensure_is_number(x) for x in value) + + @property + def upper_right(self) -> tuple[float, float]: + """ + Property to read and modify the upper right coordinate of this box + in (x,y) form. + """ + return self.right, self.top + + @upper_right.setter + def upper_right(self, value: tuple[float, float]) -> None: + self[2], self[3] = (self._ensure_is_number(x) for x in value) + + @property + def width(self) -> float: + return self.right - self.left + + @property + def height(self) -> float: + return self.top - self.bottom diff --git a/.venv/lib/python3.13/site-packages/pypdf/generic/_utils.py b/.venv/lib/python3.13/site-packages/pypdf/generic/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bcf62f1a49f94960c1a7f8d34e4e5345cb0ba39b --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/generic/_utils.py @@ -0,0 +1,215 @@ +import codecs +from typing import Union + +from .._codecs import _pdfdoc_encoding +from .._utils import StreamType, logger_warning, read_non_whitespace +from ..errors import STREAM_TRUNCATED_PREMATURELY, PdfStreamError +from ._base import ByteStringObject, TextStringObject + + +def hex_to_rgb(value: str) -> tuple[float, float, float]: + return tuple(int(value.lstrip("#")[i : i + 2], 16) / 255.0 for i in (0, 2, 4)) # type: ignore[return-value] + + +def read_hex_string_from_stream( + stream: StreamType, + forced_encoding: Union[str, list[str], dict[int, str], None] = None, +) -> Union["TextStringObject", "ByteStringObject"]: + stream.read(1) + arr = [] + x = b"" + while True: + tok = read_non_whitespace(stream) + if not tok: + raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY) + if tok == b">": + break + if tok not in b"0123456789abcdefABCDEF": + raise PdfStreamError( + f"Invalid hexadecimal character {tok!r} in hex string" + ) + x += tok + if len(x) == 2: + arr.append(int(x, base=16)) + x = b"" + if len(x) == 1: + x += b"0" + if x != b"": + arr.append(int(x, base=16)) + return create_string_object(bytes(arr), forced_encoding) + + +__ESCAPE_DICT__ = { + b"n": ord(b"\n"), + b"r": ord(b"\r"), + b"t": ord(b"\t"), + b"b": ord(b"\b"), + b"f": ord(b"\f"), + b"(": ord(b"("), + b")": ord(b")"), + b"/": ord(b"/"), + b"\\": ord(b"\\"), + b" ": ord(b" "), + b"%": ord(b"%"), + b"<": ord(b"<"), + b">": ord(b">"), + b"[": ord(b"["), + b"]": ord(b"]"), + b"#": ord(b"#"), + b"_": ord(b"_"), + b"&": ord(b"&"), + b"$": ord(b"$"), +} +__BACKSLASH_CODE__ = 92 + + +def read_string_from_stream( + stream: StreamType, + forced_encoding: Union[str, list[str], dict[int, str], None] = None, +) -> Union["TextStringObject", "ByteStringObject"]: + tok = stream.read(1) + parens = 1 + txt = [] + while True: + tok = stream.read(1) + if not tok: + raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY) + if tok == b"(": + parens += 1 + elif tok == b")": + parens -= 1 + if parens == 0: + break + elif tok == b"\\": + tok = stream.read(1) + try: + txt.append(__ESCAPE_DICT__[tok]) + continue + except KeyError: + if b"0" <= tok <= b"7": + # "The number ddd may consist of one, two, or three + # octal digits; high-order overflow shall be ignored. + # Three octal digits shall be used, with leading zeros + # as needed, if the next character of the string is also + # a digit." (PDF reference 7.3.4.2, p 16) + sav = stream.tell() - 1 + for _ in range(2): + ntok = stream.read(1) + if b"0" <= ntok <= b"7": + tok += ntok + else: + stream.seek(-1, 1) # ntok has to be analyzed + break + i = int(tok, base=8) + if i > 255: + txt.append(__BACKSLASH_CODE__) + stream.seek(sav) + else: + txt.append(i) + continue + if tok in b"\n\r": + # This case is hit when a backslash followed by a line + # break occurs. If it's a multi-char EOL, consume the + # second character: + tok = stream.read(1) + if tok not in b"\n\r": + stream.seek(-1, 1) + # Then don't add anything to the actual string, since this + # line break was escaped: + continue + logger_warning( + "Unexpected escaped string: %(token)s", + source=__name__, + token=tok.decode("utf-8", "ignore"), + ) + txt.append(__BACKSLASH_CODE__) + txt.append(ord(tok)) + return create_string_object(bytes(txt), forced_encoding) + + +def create_string_object( + string: Union[str, bytes], + forced_encoding: Union[str, list[str], dict[int, str], None] = None, +) -> Union[TextStringObject, ByteStringObject]: + """ + Create a ByteStringObject or a TextStringObject from a string to represent the string. + + Args: + string: The data being used + forced_encoding: Typically None, or an encoding string + + Returns: + A ByteStringObject + + Raises: + TypeError: If string is not of type str or bytes. + + """ + if isinstance(string, str): + return TextStringObject(string) + if isinstance(string, bytes): + if isinstance(forced_encoding, (list, dict)): + out = "" + for x in string: + try: + out += forced_encoding[x] + except Exception: + out += bytes((x,)).decode("charmap") + obj = TextStringObject(out) + obj._original_bytes = string + return obj + if isinstance(forced_encoding, str): + if forced_encoding == "bytes": + return ByteStringObject(string) + obj = TextStringObject(string.decode(forced_encoding)) + obj._original_bytes = string + return obj + try: + if string.startswith((codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE)): + retval = TextStringObject(string.decode("utf-16")) + retval._original_bytes = string + retval.autodetect_utf16 = True + retval.utf16_bom = string[:2] + return retval + if string.startswith(b"\x00"): + retval = TextStringObject(string.decode("utf-16be")) + retval._original_bytes = string + retval.autodetect_utf16 = True + retval.utf16_bom = codecs.BOM_UTF16_BE + return retval + if string[1:2] == b"\x00": + retval = TextStringObject(string.decode("utf-16le")) + retval._original_bytes = string + retval.autodetect_utf16 = True + retval.utf16_bom = codecs.BOM_UTF16_LE + return retval + + # This is probably a big performance hit here, but we need + # to convert string objects into the text/unicode-aware + # version if possible... and the only way to check if that's + # possible is to try. + # Some strings are strings, some are just byte arrays. + retval = TextStringObject(decode_pdfdocencoding(string)) + retval._original_bytes = string + retval.autodetect_pdfdocencoding = True + return retval + except UnicodeDecodeError: + return ByteStringObject(string) + else: + raise TypeError("create_string_object should have str or unicode arg") + + +def decode_pdfdocencoding(byte_array: bytes) -> str: + retval = "" + for b in byte_array: + c = _pdfdoc_encoding[b] + if c == "\u0000": + raise UnicodeDecodeError( + "pdfdocencoding", + bytearray(b), + -1, + -1, + "does not exist in translation table", + ) + retval += c + return retval diff --git a/.venv/lib/python3.13/site-packages/pypdf/generic/_viewerpref.py b/.venv/lib/python3.13/site-packages/pypdf/generic/_viewerpref.py new file mode 100644 index 0000000000000000000000000000000000000000..faece00718767bb34d92c356ad98f4a9ef8e495f --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/generic/_viewerpref.py @@ -0,0 +1,164 @@ +# Copyright (c) 2023, Pubpub-ZZ +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * The name of the author may not be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +from typing import ( + Any, + Optional, + cast, +) + +from ._base import BooleanObject, NameObject, NumberObject, is_null_or_none +from ._data_structures import ArrayObject, DictionaryObject + +f_obj = BooleanObject(False) + + +class ViewerPreferences(DictionaryObject): + def __init__(self, obj: Optional[DictionaryObject] = None) -> None: + super().__init__(self) + if not is_null_or_none(obj): + self.update(obj.items()) # type: ignore[union-attr] + try: + self.indirect_reference = obj.indirect_reference # type: ignore[union-attr] + except AttributeError: + pass + + def _get_bool(self, key: str, default: Optional[BooleanObject]) -> Optional[BooleanObject]: + return self.get(key, default) + + def _set_bool(self, key: str, v: bool) -> None: + self[NameObject(key)] = BooleanObject(v is True) + + def _get_name(self, key: str, default: Optional[NameObject]) -> Optional[NameObject]: + return self.get(key, default) + + def _set_name(self, key: str, lst: list[str], v: NameObject) -> None: + if v[0] != "/": + raise ValueError(f"{v} does not start with '/'") + if lst != [] and v not in lst: + raise ValueError(f"{v} is an unacceptable value") + self[NameObject(key)] = NameObject(v) + + def _get_arr(self, key: str, default: Optional[list[Any]]) -> Optional[ArrayObject]: + return self.get(key, None if default is None else ArrayObject(default)) + + def _set_arr(self, key: str, v: Optional[ArrayObject]) -> None: + if v is None: + try: + del self[NameObject(key)] + except KeyError: + pass + return + if not isinstance(v, ArrayObject): + raise ValueError("ArrayObject is expected") + self[NameObject(key)] = v + + def _get_int(self, key: str, default: Optional[NumberObject]) -> Optional[NumberObject]: + return self.get(key, default) + + def _set_int(self, key: str, v: int) -> None: + self[NameObject(key)] = NumberObject(v) + + @property + def PRINT_SCALING(self) -> NameObject: + return NameObject("/PrintScaling") + + def __new__(cls: Any, value: Any = None) -> "ViewerPreferences": # noqa: PYI034 + def _add_prop_bool(key: str, default: Optional[BooleanObject]) -> property: + return property( + lambda self: self._get_bool(key, default), + lambda self, v: self._set_bool(key, v), + None, + f""" + Returns/Modify the status of {key}, Returns {default} if not defined + """, + ) + + def _add_prop_name( + key: str, lst: list[str], default: Optional[NameObject] + ) -> property: + return property( + lambda self: self._get_name(key, default), + lambda self, v: self._set_name(key, lst, v), + None, + f""" + Returns/Modify the status of {key}, Returns {default} if not defined. + Acceptable values: {lst} + """, + ) + + def _add_prop_arr(key: str, default: Optional[ArrayObject]) -> property: + return property( + lambda self: self._get_arr(key, default), + lambda self, v: self._set_arr(key, v), + None, + f""" + Returns/Modify the status of {key}, Returns {default} if not defined + """, + ) + + def _add_prop_int(key: str, default: Optional[int]) -> property: + return property( + lambda self: self._get_int(key, default), + lambda self, v: self._set_int(key, v), + None, + f""" + Returns/Modify the status of {key}, Returns {default} if not defined + """, + ) + + cls.hide_toolbar = _add_prop_bool("/HideToolbar", f_obj) + cls.hide_menubar = _add_prop_bool("/HideMenubar", f_obj) + cls.hide_windowui = _add_prop_bool("/HideWindowUI", f_obj) + cls.fit_window = _add_prop_bool("/FitWindow", f_obj) + cls.center_window = _add_prop_bool("/CenterWindow", f_obj) + cls.display_doctitle = _add_prop_bool("/DisplayDocTitle", f_obj) + + cls.non_fullscreen_pagemode = _add_prop_name( + "/NonFullScreenPageMode", + ["/UseNone", "/UseOutlines", "/UseThumbs", "/UseOC"], + NameObject("/UseNone"), + ) + cls.direction = _add_prop_name( + "/Direction", ["/L2R", "/R2L"], NameObject("/L2R") + ) + cls.view_area = _add_prop_name("/ViewArea", [], None) + cls.view_clip = _add_prop_name("/ViewClip", [], None) + cls.print_area = _add_prop_name("/PrintArea", [], None) + cls.print_clip = _add_prop_name("/PrintClip", [], None) + cls.print_scaling = _add_prop_name("/PrintScaling", [], None) + cls.duplex = _add_prop_name( + "/Duplex", ["/Simplex", "/DuplexFlipShortEdge", "/DuplexFlipLongEdge"], None + ) + cls.pick_tray_by_pdfsize = _add_prop_bool("/PickTrayByPDFSize", None) + cls.print_pagerange = _add_prop_arr("/PrintPageRange", None) + cls.num_copies = _add_prop_int("/NumCopies", None) + + cls.enforce = _add_prop_arr("/Enforce", ArrayObject()) + + return cast("ViewerPreferences", DictionaryObject.__new__(cls)) diff --git a/.venv/lib/python3.13/site-packages/pypdf/pagerange.py b/.venv/lib/python3.13/site-packages/pypdf/pagerange.py new file mode 100644 index 0000000000000000000000000000000000000000..2ffe2d43cbadbb7bae495de1e040d3ca434b98c4 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/pagerange.py @@ -0,0 +1,208 @@ +""" +Representation and utils for ranges of PDF file pages. + +Copyright (c) 2014, Steve Witham . +All rights reserved. This software is available under a BSD license; +see https://github.com/py-pdf/pypdf/blob/main/LICENSE +""" + +import re +from typing import Any, Optional, Union + +from .errors import ParseError + +_INT_RE = r"(0|-?[1-9]\d*)" # A decimal int, don't allow "-0". +PAGE_RANGE_RE = f"^({_INT_RE}|({_INT_RE}?(:{_INT_RE}?(:{_INT_RE}?)?)))$" +# groups: 12 34 5 6 7 8 + + +class PageRange: + """ + A slice-like representation of a range of page indices. + + For example, page numbers, only starting at zero. + + The syntax is like what you would put between brackets [ ]. + The slice is one of the few Python types that can't be subclassed, + but this class converts to and from slices, and allows similar use. + + - PageRange(str) parses a string representing a page range. + - PageRange(slice) directly "imports" a slice. + - to_slice() gives the equivalent slice. + - str() and repr() allow printing. + - indices(n) is like slice.indices(n). + """ + + def __init__(self, arg: Union[slice, "PageRange", str]) -> None: + """ + Initialize with either a slice -- giving the equivalent page range, + or a PageRange object -- making a copy, + or a string like + "int", "[int]:[int]" or "[int]:[int]:[int]", + where the brackets indicate optional ints. + Remember, page indices start with zero. + Page range expression examples: + + : all pages. -1 last page. + 22 just the 23rd page. :-1 all but the last page. + 0:3 the first three pages. -2 second-to-last page. + :3 the first three pages. -2: last two pages. + 5: from the sixth page onward. -3:-1 third & second to last. + The third, "stride" or "step" number is also recognized. + ::2 0 2 4 ... to the end. 3:0:-1 3 2 1 but not 0. + 1:10:2 1 3 5 7 9 2::-1 2 1 0. + ::-1 all pages in reverse order. + Note the difference between this notation and arguments to slice(): + slice(3) means the first three pages; + PageRange("3") means the range of only the fourth page. + However PageRange(slice(3)) means the first three pages. + """ + if isinstance(arg, slice): + self._slice = arg + return + + if isinstance(arg, PageRange): + self._slice = arg.to_slice() + return + + m = isinstance(arg, str) and re.match(PAGE_RANGE_RE, arg) + if not m: + raise ParseError(arg) + if m.group(2): + # Special case: just an int means a range of one page. + start = int(m.group(2)) + stop = start + 1 if start != -1 else None + self._slice = slice(start, stop) + else: + self._slice = slice(*[int(g) if g else None for g in m.group(4, 6, 8)]) + + @staticmethod + def valid(input: Any) -> bool: + """ + True if input is a valid initializer for a PageRange. + + Args: + input: A possible PageRange string or a PageRange object. + + Returns: + True, if the ``input`` is a valid PageRange. + + """ + return isinstance(input, (slice, PageRange)) or ( + isinstance(input, str) and bool(re.match(PAGE_RANGE_RE, input)) + ) + + def to_slice(self) -> slice: + """Return the slice equivalent of this page range.""" + return self._slice + + def __str__(self) -> str: + """A string like "1:2:3".""" + s = self._slice + indices: Union[tuple[int, int], tuple[int, int, int]] + if s.step is None: + if s.start is not None and s.stop == s.start + 1: + return str(s.start) + + indices = s.start, s.stop + else: + indices = s.start, s.stop, s.step + return ":".join("" if i is None else str(i) for i in indices) + + def __repr__(self) -> str: + """A string like "PageRange('1:2:3')".""" + return "PageRange(" + repr(str(self)) + ")" + + def indices(self, n: int) -> tuple[int, int, int]: + """ + Assuming a sequence of length n, calculate the start and stop indices, + and the stride length of the PageRange. + + See help(slice.indices). + + Args: + n: the length of the list of pages to choose from. + + Returns: + Arguments for range(). + + """ + return self._slice.indices(n) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, PageRange): + return False + return self._slice == other._slice + + def __hash__(self) -> int: + return hash((self.__class__, (self._slice.start, self._slice.stop, self._slice.step))) + + def __add__(self, other: "PageRange") -> "PageRange": + if not isinstance(other, PageRange): + raise TypeError(f"Can't add PageRange and {type(other)}") + if self._slice.step is not None or other._slice.step is not None: + raise ValueError("Can't add PageRange with stride") + a = self._slice.start, self._slice.stop + b = other._slice.start, other._slice.stop + + # None start means "beginning" (-inf for ordering); None stop means "end" (+inf). + def _start_key(v: Optional[int]) -> float: + return float("-inf") if v is None else v + + def _stop_key(v: Optional[int]) -> float: + return float("inf") if v is None else v + + if _start_key(a[0]) > _start_key(b[0]): + a, b = b, a + + # Now `a` has the smaller (or equal) start. + if _start_key(b[0]) > _stop_key(a[1]): + # There is a gap between a and b. + raise ValueError("Can't add PageRanges with gap") + stop = b[1] if _stop_key(b[1]) > _stop_key(a[1]) else a[1] + return PageRange(slice(a[0], stop)) + + +PAGE_RANGE_ALL = PageRange(":") # The range of all pages. + + +def parse_filename_page_ranges( + args: list[Union[str, PageRange, None]] +) -> list[tuple[str, PageRange]]: + """ + Given a list of filenames and page ranges, return a list of (filename, page_range) pairs. + + Args: + args: A list where the first element is a filename. The other elements are + filenames, page-range expressions, slice objects, or PageRange objects. + A filename not followed by a page range indicates all pages of the file. + + Returns: + A list of (filename, page_range) pairs. + + """ + pairs: list[tuple[str, PageRange]] = [] + pdf_filename: Union[str, None] = None + did_page_range = False + for arg in [*args, None]: + if PageRange.valid(arg): + if not pdf_filename: + raise ValueError( + "The first argument must be a filename, not a page range." + ) + + assert arg is not None + pairs.append((pdf_filename, PageRange(arg))) + did_page_range = True + else: + # New filename or end of list - use the complete previous file? + if pdf_filename and not did_page_range: + pairs.append((pdf_filename, PAGE_RANGE_ALL)) + + assert not isinstance(arg, PageRange), arg + pdf_filename = arg + did_page_range = False + return pairs + + +PageRangeSpec = Union[str, PageRange, tuple[int, int], tuple[int, int, int], list[int]] diff --git a/.venv/lib/python3.13/site-packages/pypdf/papersizes.py b/.venv/lib/python3.13/site-packages/pypdf/papersizes.py new file mode 100644 index 0000000000000000000000000000000000000000..ed09f341f6a27e9805f0b49430bd09d4d24d70a3 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/papersizes.py @@ -0,0 +1,52 @@ +"""Helper to get paper sizes.""" + +from typing import NamedTuple + + +class Dimensions(NamedTuple): + width: int + height: int + + +class PaperSize: + """(width, height) of the paper in portrait mode in pixels at 72 ppi.""" + + # Notes of how to calculate it: + # 1. Get the size of the paper in millimeters + # 2. Convert it to inches (25.4 millimeters is equal to 1 inch) + # 3. Convert it to pixels at 72dpi (1 inch is equal to 72 pixels) + + # All Din-A paper sizes follow this pattern: + # 2 x A(n - 1) = A(n) + # So the height of the next bigger one is the width of the smaller one + # The ratio is always approximately 1:2**0.5 + # Additionally, A0 is defined to have an area of 1 m**2 + # https://en.wikipedia.org/wiki/ISO_216 + # Be aware of rounding issues! + A0 = Dimensions(2384, 3370) # 841mm x 1189mm + A1 = Dimensions(1684, 2384) + A2 = Dimensions(1191, 1684) + A3 = Dimensions(842, 1191) + A4 = Dimensions( + 595, 842 + ) # Printer paper, documents - this is by far the most common + A5 = Dimensions(420, 595) # Paperback books + A6 = Dimensions(298, 420) # Postcards + A7 = Dimensions(210, 298) + A8 = Dimensions(147, 210) + + # Envelopes + C4 = Dimensions(649, 918) + + +_din_a = ( + PaperSize.A0, + PaperSize.A1, + PaperSize.A2, + PaperSize.A3, + PaperSize.A4, + PaperSize.A5, + PaperSize.A6, + PaperSize.A7, + PaperSize.A8, +) diff --git a/.venv/lib/python3.13/site-packages/pypdf/py.typed b/.venv/lib/python3.13/site-packages/pypdf/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.13/site-packages/pypdf/types.py b/.venv/lib/python3.13/site-packages/pypdf/types.py new file mode 100644 index 0000000000000000000000000000000000000000..a1c4e495a5710812ff122f13a4580599c380f8a3 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/types.py @@ -0,0 +1,80 @@ +"""Helpers for working with PDF types.""" + +import sys +from typing import Literal, Union + +if sys.version_info[:2] >= (3, 10): + # Python 3.10+: https://www.python.org/dev/peps/pep-0484 + from typing import TypeAlias +else: + from typing_extensions import TypeAlias + +from .generic._base import NameObject, NullObject, NumberObject +from .generic._data_structures import ArrayObject, Destination +from .generic._outline import OutlineItem + +BorderArrayType: TypeAlias = list[Union[NameObject, NumberObject, ArrayObject]] + +OutlineItemType: TypeAlias = Union[OutlineItem, Destination] + +FitType: TypeAlias = Literal[ + "/XYZ", "/Fit", "/FitH", "/FitV", "/FitR", "/FitB", "/FitBH", "/FitBV" +] +# These go with the FitType, they specify values for the fit +ZoomArgType: TypeAlias = Union[NumberObject, NullObject, float] +ZoomArgsType: TypeAlias = list[ZoomArgType] + +# Recursive types like the following are not yet supported by Sphinx: +# OutlineType = List[Union[Destination, "OutlineType"]] +# Hence use this for the moment: +OutlineType = list[Union[Destination, list[Union[Destination, list[Destination]]]]] + +LayoutType: TypeAlias = Literal[ + "/NoLayout", + "/SinglePage", + "/OneColumn", + "/TwoColumnLeft", + "/TwoColumnRight", + "/TwoPageLeft", + "/TwoPageRight", +] + +PagemodeType: TypeAlias = Literal[ + "/UseNone", + "/UseOutlines", + "/UseThumbs", + "/FullScreen", + "/UseOC", + "/UseAttachments", +] + +AnnotationSubtype: TypeAlias = Literal[ + "/Text", + "/Link", + "/FreeText", + "/Line", + "/Square", + "/Circle", + "/Polygon", + "/PolyLine", + "/Highlight", + "/Underline", + "/Squiggly", + "/StrikeOut", + "/Caret", + "/Stamp", + "/Ink", + "/Popup", + "/FileAttachment", + "/Sound", + "/Movie", + "/Screen", + "/Widget", + "/PrinterMark", + "/TrapNet", + "/Watermark", + "/3D", + "/Redact", + "/Projection", + "/RichMedia", +] diff --git a/.venv/lib/python3.13/site-packages/pypdf/xmp.py b/.venv/lib/python3.13/site-packages/pypdf/xmp.py new file mode 100644 index 0000000000000000000000000000000000000000..cc02d3a49b3fb9811b20e5287c9da08549e49ba9 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pypdf/xmp.py @@ -0,0 +1,803 @@ +""" +Anything related to Extensible Metadata Platform (XMP) metadata. + +https://en.wikipedia.org/wiki/Extensible_Metadata_Platform +""" + +import datetime +import decimal +import re +from collections.abc import Iterator +from string import hexdigits +from typing import ( + Any, + Callable, + Optional, + TypeVar, + Union, + cast, +) +from xml.dom.expatbuilder import ExpatBuilderNS +from xml.dom.minidom import Document +from xml.dom.minidom import Element as XmlElement +from xml.dom.xmlbuilder import Options +from xml.parsers.expat import ExpatError, XMLParserType + +from ._protocols import XmpInformationProtocol +from ._utils import StreamType, deprecate_with_replacement, deprecation_no_replacement +from .errors import LimitReachedError, PdfReadError, XmpDocumentError +from .generic import ContentStream, PdfObject + +XMP_MAX_INPUT_LENGTH = 5_000_000 +XMP_MAX_ELEMENT_COUNT = 100_000 + +RDF_NAMESPACE = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" +DC_NAMESPACE = "http://purl.org/dc/elements/1.1/" +XMP_NAMESPACE = "http://ns.adobe.com/xap/1.0/" +PDF_NAMESPACE = "http://ns.adobe.com/pdf/1.3/" +XMPMM_NAMESPACE = "http://ns.adobe.com/xap/1.0/mm/" + +# What is the PDFX namespace, you might ask? +# It's documented here: https://github.com/adobe/xmp-docs/raw/master/XMPSpecifications/XMPSpecificationPart3.pdf +# This namespace is used to place "custom metadata" +# properties, which are arbitrary metadata properties with no semantic or +# documented meaning. +# +# Elements in the namespace are key/value-style storage, +# where the element name is the key and the content is the value. The keys +# are transformed into valid XML identifiers by substituting an invalid +# identifier character with \u2182 followed by the unicode hex ID of the +# original character. A key like "my car" is therefore "my\u21820020car". +# +# \u2182 is the unicode character \u{ROMAN NUMERAL TEN THOUSAND} +# +# The pdfx namespace should be avoided. +# A custom data schema and sensical XML elements could be used instead, as is +# suggested by Adobe's own documentation on XMP under "Extensibility of +# Schemas". +PDFX_NAMESPACE = "http://ns.adobe.com/pdfx/1.3/" + +# PDF/A +PDFAID_NAMESPACE = "http://www.aiim.org/pdfa/ns/id/" + +# Internal mapping of namespace URI → prefix +_NAMESPACE_PREFIX_MAP = { + DC_NAMESPACE: "dc", + XMP_NAMESPACE: "xmp", + PDF_NAMESPACE: "pdf", + XMPMM_NAMESPACE: "xmpMM", + PDFAID_NAMESPACE: "pdfaid", + PDFX_NAMESPACE: "pdfx", +} + +iso8601 = re.compile( + """ + (?P[0-9]{4}) + (- + (?P[0-9]{2}) + (- + (?P[0-9]+) + (T + (?P[0-9]{2}): + (?P[0-9]{2}) + (:(?P[0-9]{2}(.[0-9]+)?))? + (?PZ|[-+][0-9]{2}:[0-9]{2}) + )? + )? + )? + """, + re.VERBOSE, +) + + +K = TypeVar("K") + +# Minimal XMP template +_MINIMAL_XMP = f""" + + + + + + +""" + + +def _identity(value: K) -> K: + return value + + +def _converter_date(value: str) -> datetime.datetime: + matches = iso8601.match(value) + if matches is None: + raise ValueError(f"Invalid date format: {value}") + year = int(matches.group("year")) + month = int(matches.group("month") or "1") + day = int(matches.group("day") or "1") + hour = int(matches.group("hour") or "0") + minute = int(matches.group("minute") or "0") + second = decimal.Decimal(matches.group("second") or "0") + seconds_dec = second.to_integral(decimal.ROUND_FLOOR) + milliseconds_dec = (second - seconds_dec) * 1_000_000 + + seconds = int(seconds_dec) + milliseconds = int(milliseconds_dec) + + tzd = matches.group("tzd") or "Z" + dt = datetime.datetime(year, month, day, hour, minute, seconds, milliseconds) + if tzd != "Z": + tzd_hours, tzd_minutes = (int(x) for x in tzd.split(":")) + tzd_hours *= -1 + if tzd_hours < 0: + tzd_minutes *= -1 + dt = dt + datetime.timedelta(hours=tzd_hours, minutes=tzd_minutes) + return dt + + +def _format_datetime_utc(value: datetime.datetime) -> str: + """Format a datetime as UTC with trailing 'Z'. + + - If the input is timezone-aware, convert to UTC first. + - If naive, assume UTC. + """ + if value.tzinfo is not None and value.utcoffset() is not None: + value = value.astimezone(datetime.timezone.utc) + + value = value.replace(tzinfo=None) + return value.strftime("%Y-%m-%dT%H:%M:%S.%fZ") + + +def _generic_get( + element: XmlElement, self: "XmpInformation", list_type: str, converter: Callable[[Any], Any] = _identity +) -> Optional[list[str]]: + containers = element.getElementsByTagNameNS(RDF_NAMESPACE, list_type) + retval: list[Any] = [] + if len(containers): + for container in containers: + for item in container.getElementsByTagNameNS(RDF_NAMESPACE, "li"): + value = self._get_text(item) + value = converter(value) + retval.append(value) + return retval + return None + + +class _XmpBuilder(ExpatBuilderNS): + """ + Custom XML parser denying all entity declarations. + + This is a stripped down and typed version inspired by what *defusedxml* does. + + Why do we need this? The default limits of *libexpat* used by Python only block exponential entity expansion, + but not cases like quadratic entity expansion which can still cause quite some memory usage. + """ + + def __init__(self, options: Optional[Options] = None) -> None: + super().__init__(options=options) + self._element_count = 0 + + def custom_entity_declaration_handler( + self, + entity_name: str, + is_parameter_entity: bool, + value: Optional[str], + base: Optional[str], + system_id: str, + public_id: Optional[str], + notation_name: Optional[str], + ) -> None: + raise ExpatError(f"Forbidden entities: {entity_name!r}") + + def start_element_handler(self, name: str, attributes: list[str]) -> None: + self._element_count += 1 + if self._element_count > XMP_MAX_ELEMENT_COUNT: + raise LimitReachedError(f"XMP metadata exceeds limit of {XMP_MAX_ELEMENT_COUNT} elements.") + super().start_element_handler(name=name, attributes=attributes) + + def install(self, parser: XMLParserType) -> None: + super().install(parser) + + parser.EntityDeclHandler = self.custom_entity_declaration_handler + parser.StartElementHandler = self.start_element_handler + + +class XmpInformation(XmpInformationProtocol, PdfObject): + """ + An object that represents Extensible Metadata Platform (XMP) metadata. + Usually accessed by :py:attr:`xmp_metadata()`. + + Raises: + PdfReadError: if XML is invalid + + """ + + def __init__(self, stream: ContentStream) -> None: + self.stream = stream + try: + data = self.stream.get_data() + if (length := len(data)) > XMP_MAX_INPUT_LENGTH: + raise LimitReachedError(f"XMP stream size {length} exceeds limit of {XMP_MAX_INPUT_LENGTH}.") + doc_root: Document = _XmpBuilder().parseString(data) + except (AttributeError, ExpatError) as e: + raise PdfReadError(f"XML in XmpInformation was invalid: {e}") + rdf_roots = doc_root.getElementsByTagNameNS(RDF_NAMESPACE, "RDF") + if not rdf_roots: + raise PdfReadError( + "XML in XmpInformation was invalid: Missing rdf:RDF root element" + ) + self.rdf_root: XmlElement = rdf_roots[0] + self.cache: dict[Any, Any] = {} + + @classmethod + def create(cls) -> "XmpInformation": + """ + Create a new XmpInformation object with minimal structure. + + Returns: + A new XmpInformation instance with empty metadata fields. + """ + stream = ContentStream(None, None) + stream.set_data(_MINIMAL_XMP.encode("utf-8")) + return cls(stream) + + def write_to_stream( + self, stream: StreamType, encryption_key: Union[str, bytes, None] = None + ) -> None: + deprecate_with_replacement( + "XmpInformation.write_to_stream", + "PdfWriter.xmp_metadata", + "6.0.0" + ) + if encryption_key is not None: # deprecated + deprecation_no_replacement( + "the encryption_key parameter of write_to_stream", "5.0.0" + ) + self.stream.write_to_stream(stream) + + def get_element(self, about_uri: str, namespace: str, name: str) -> Iterator[Any]: + for desc in self.rdf_root.getElementsByTagNameNS(RDF_NAMESPACE, "Description"): + if desc.getAttributeNS(RDF_NAMESPACE, "about") == about_uri: + attr = desc.getAttributeNodeNS(namespace, name) + if attr is not None: + yield attr + yield from desc.getElementsByTagNameNS(namespace, name) + + def get_nodes_in_namespace(self, about_uri: str, namespace: str) -> Iterator[Any]: + for desc in self.rdf_root.getElementsByTagNameNS(RDF_NAMESPACE, "Description"): + if desc.getAttributeNS(RDF_NAMESPACE, "about") == about_uri: + for i in range(desc.attributes.length): + attr = desc.attributes.item(i) + if attr and attr.namespaceURI == namespace: + yield attr + for child in desc.childNodes: + if child.namespaceURI == namespace: + yield child + + def _get_text(self, element: XmlElement) -> str: + text = "" + for child in element.childNodes: + if child.nodeType == child.TEXT_NODE: + text += child.data + return text + + def _get_single_value( + self, + namespace: str, + name: str, + converter: Callable[[str], Any] = _identity, + ) -> Optional[Any]: + cached = self.cache.get(namespace, {}).get(name) + if cached: + return cached + value = None + for element in self.get_element("", namespace, name): + if element.nodeType == element.ATTRIBUTE_NODE: + value = element.nodeValue + else: + value = self._get_text(element) + break + if value is not None: + value = converter(value) + ns_cache = self.cache.setdefault(namespace, {}) + ns_cache[name] = value + return value + + def _getter_bag(self, namespace: str, name: str) -> Optional[list[str]]: + cached = self.cache.get(namespace, {}).get(name) + if cached: + return cast(list[str], cached) + retval: list[str] = [] + for element in self.get_element("", namespace, name): + if (bags := _generic_get(element, self, list_type="Bag")) is not None: + retval.extend(bags) + else: + value = self._get_text(element) + retval.append(value) + ns_cache = self.cache.setdefault(namespace, {}) + ns_cache[name] = retval + return retval + + def _get_seq_values( + self, + namespace: str, + name: str, + converter: Callable[[Any], Any] = _identity, + ) -> Optional[list[Any]]: + cached = self.cache.get(namespace, {}).get(name) + if cached: + return cast(list[Any], cached) + retval: list[Any] = [] + for element in self.get_element("", namespace, name): + if (seqs := _generic_get(element, self, list_type="Seq", converter=converter)) is not None: + retval.extend(seqs) + elif (bags := _generic_get(element, self, list_type="Bag")) is not None: + # See issue at https://github.com/py-pdf/pypdf/issues/3324 + # Some applications violate the XMP metadata standard regarding `dc:creator` which should + # be an "ordered array" and thus a sequence, but use an unordered array (bag) instead. + # This seems to stem from the fact that the original Dublin Core specification does indeed + # use bags or direct values, while PDFs are expected to follow the XMP standard and ignore + # the plain Dublin Core variant. For this reason, add a fallback here to deal with such + # issues accordingly. + retval.extend(bags) + else: + value = converter(self._get_text(element)) + retval.append(value) + ns_cache = self.cache.setdefault(namespace, {}) + ns_cache[name] = retval + return retval + + def _get_langalt_values(self, namespace: str, name: str) -> Optional[dict[Any, Any]]: + cached = self.cache.get(namespace, {}).get(name) + if cached: + return cast(dict[Any, Any], cached) + retval: dict[Any, Any] = {} + for element in self.get_element("", namespace, name): + alts = element.getElementsByTagNameNS(RDF_NAMESPACE, "Alt") + if len(alts): + for alt in alts: + for item in alt.getElementsByTagNameNS(RDF_NAMESPACE, "li"): + value = self._get_text(item) + retval[item.getAttribute("xml:lang")] = value + else: + retval["x-default"] = self._get_text(element) + ns_cache = self.cache.setdefault(namespace, {}) + ns_cache[name] = retval + return retval + + @property + def dc_contributor(self) -> Optional[list[str]]: + """Contributors to the resource (other than the authors).""" + return self._getter_bag(DC_NAMESPACE, "contributor") + + @dc_contributor.setter + def dc_contributor(self, values: Optional[list[str]]) -> None: + self._set_bag_values(DC_NAMESPACE, "contributor", values) + + @property + def dc_coverage(self) -> Optional[str]: + """Text describing the extent or scope of the resource.""" + return self._get_single_value(DC_NAMESPACE, "coverage") + + @dc_coverage.setter + def dc_coverage(self, value: Optional[str]) -> None: + self._set_single_value(DC_NAMESPACE, "coverage", value) + + @property + def dc_creator(self) -> Optional[list[str]]: + """A sorted array of names of the authors of the resource, listed in order of precedence.""" + return self._get_seq_values(DC_NAMESPACE, "creator") + + @dc_creator.setter + def dc_creator(self, values: Optional[list[str]]) -> None: + self._set_seq_values(DC_NAMESPACE, "creator", values) + + @property + def dc_date(self) -> Optional[list[datetime.datetime]]: + """A sorted array of dates of significance to the resource. The dates and times are in UTC.""" + return self._get_seq_values(DC_NAMESPACE, "date", _converter_date) + + @dc_date.setter + def dc_date(self, values: Optional[list[Union[str, datetime.datetime]]]) -> None: + if values is None: + self._set_seq_values(DC_NAMESPACE, "date", None) + else: + date_strings = [] + for value in values: + if isinstance(value, datetime.datetime): + date_strings.append(_format_datetime_utc(value)) + else: + date_strings.append(str(value)) + self._set_seq_values(DC_NAMESPACE, "date", date_strings) + + @property + def dc_description(self) -> Optional[dict[str, str]]: + """A language-keyed dictionary of textual descriptions of the content of the resource.""" + return self._get_langalt_values(DC_NAMESPACE, "description") + + @dc_description.setter + def dc_description(self, values: Optional[dict[str, str]]) -> None: + self._set_langalt_values(DC_NAMESPACE, "description", values) + + @property + def dc_format(self) -> Optional[str]: + """The mime-type of the resource.""" + return self._get_single_value(DC_NAMESPACE, "format") + + @dc_format.setter + def dc_format(self, value: Optional[str]) -> None: + self._set_single_value(DC_NAMESPACE, "format", value) + + @property + def dc_identifier(self) -> Optional[str]: + """Unique identifier of the resource.""" + return self._get_single_value(DC_NAMESPACE, "identifier") + + @dc_identifier.setter + def dc_identifier(self, value: Optional[str]) -> None: + self._set_single_value(DC_NAMESPACE, "identifier", value) + + @property + def dc_language(self) -> Optional[list[str]]: + """An unordered array specifying the languages used in the resource.""" + return self._getter_bag(DC_NAMESPACE, "language") + + @dc_language.setter + def dc_language(self, values: Optional[list[str]]) -> None: + self._set_bag_values(DC_NAMESPACE, "language", values) + + @property + def dc_publisher(self) -> Optional[list[str]]: + """An unordered array of publisher names.""" + return self._getter_bag(DC_NAMESPACE, "publisher") + + @dc_publisher.setter + def dc_publisher(self, values: Optional[list[str]]) -> None: + self._set_bag_values(DC_NAMESPACE, "publisher", values) + + @property + def dc_relation(self) -> Optional[list[str]]: + """An unordered array of text descriptions of relationships to other documents.""" + return self._getter_bag(DC_NAMESPACE, "relation") + + @dc_relation.setter + def dc_relation(self, values: Optional[list[str]]) -> None: + self._set_bag_values(DC_NAMESPACE, "relation", values) + + @property + def dc_rights(self) -> Optional[dict[str, str]]: + """A language-keyed dictionary of textual descriptions of the rights the user has to this resource.""" + return self._get_langalt_values(DC_NAMESPACE, "rights") + + @dc_rights.setter + def dc_rights(self, values: Optional[dict[str, str]]) -> None: + self._set_langalt_values(DC_NAMESPACE, "rights", values) + + @property + def dc_source(self) -> Optional[str]: + """Unique identifier of the work from which this resource was derived.""" + return self._get_single_value(DC_NAMESPACE, "source") + + @dc_source.setter + def dc_source(self, value: Optional[str]) -> None: + self._set_single_value(DC_NAMESPACE, "source", value) + + @property + def dc_subject(self) -> Optional[list[str]]: + """An unordered array of descriptive phrases or keywords that specify the topic of the content.""" + return self._getter_bag(DC_NAMESPACE, "subject") + + @dc_subject.setter + def dc_subject(self, values: Optional[list[str]]) -> None: + self._set_bag_values(DC_NAMESPACE, "subject", values) + + @property + def dc_title(self) -> Optional[dict[str, str]]: + """A language-keyed dictionary of the title of the resource.""" + return self._get_langalt_values(DC_NAMESPACE, "title") + + @dc_title.setter + def dc_title(self, values: Optional[dict[str, str]]) -> None: + self._set_langalt_values(DC_NAMESPACE, "title", values) + + @property + def dc_type(self) -> Optional[list[str]]: + """An unordered array of textual descriptions of the document type.""" + return self._getter_bag(DC_NAMESPACE, "type") + + @dc_type.setter + def dc_type(self, values: Optional[list[str]]) -> None: + self._set_bag_values(DC_NAMESPACE, "type", values) + + @property + def pdf_keywords(self) -> Optional[str]: + """An unformatted text string representing document keywords.""" + return self._get_single_value(PDF_NAMESPACE, "Keywords") + + @pdf_keywords.setter + def pdf_keywords(self, value: Optional[str]) -> None: + self._set_single_value(PDF_NAMESPACE, "Keywords", value) + + @property + def pdf_pdfversion(self) -> Optional[str]: + """The PDF file version, for example 1.0 or 1.3.""" + return self._get_single_value(PDF_NAMESPACE, "PDFVersion") + + @pdf_pdfversion.setter + def pdf_pdfversion(self, value: Optional[str]) -> None: + self._set_single_value(PDF_NAMESPACE, "PDFVersion", value) + + @property + def pdf_producer(self) -> Optional[str]: + """The name of the tool that saved the document as a PDF.""" + return self._get_single_value(PDF_NAMESPACE, "Producer") + + @pdf_producer.setter + def pdf_producer(self, value: Optional[str]) -> None: + self._set_single_value(PDF_NAMESPACE, "Producer", value) + + @property + def xmp_create_date(self) -> Optional[datetime.datetime]: + """The date and time the resource was originally created. Returned as a UTC datetime object.""" + return self._get_single_value(XMP_NAMESPACE, "CreateDate", _converter_date) + + @xmp_create_date.setter + def xmp_create_date(self, value: Optional[datetime.datetime]) -> None: + if value: + date_str = _format_datetime_utc(value) + self._set_single_value(XMP_NAMESPACE, "CreateDate", date_str) + else: + self._set_single_value(XMP_NAMESPACE, "CreateDate", None) + + @property + def xmp_modify_date(self) -> Optional[datetime.datetime]: + """The date and time the resource was last modified. Returned as a UTC datetime object.""" + return self._get_single_value(XMP_NAMESPACE, "ModifyDate", _converter_date) + + @xmp_modify_date.setter + def xmp_modify_date(self, value: Optional[datetime.datetime]) -> None: + if value: + date_str = _format_datetime_utc(value) + self._set_single_value(XMP_NAMESPACE, "ModifyDate", date_str) + else: + self._set_single_value(XMP_NAMESPACE, "ModifyDate", None) + + @property + def xmp_metadata_date(self) -> Optional[datetime.datetime]: + """The date and time that any metadata for this resource was last changed. Returned as a UTC datetime object.""" + return self._get_single_value(XMP_NAMESPACE, "MetadataDate", _converter_date) + + @xmp_metadata_date.setter + def xmp_metadata_date(self, value: Optional[datetime.datetime]) -> None: + if value: + date_str = _format_datetime_utc(value) + self._set_single_value(XMP_NAMESPACE, "MetadataDate", date_str) + else: + self._set_single_value(XMP_NAMESPACE, "MetadataDate", None) + + @property + def xmp_creator_tool(self) -> Optional[str]: + """The name of the first known tool used to create the resource.""" + return self._get_single_value(XMP_NAMESPACE, "CreatorTool") + + @xmp_creator_tool.setter + def xmp_creator_tool(self, value: Optional[str]) -> None: + self._set_single_value(XMP_NAMESPACE, "CreatorTool", value) + + @property + def xmpmm_document_id(self) -> Optional[str]: + """The common identifier for all versions and renditions of this resource.""" + return self._get_single_value(XMPMM_NAMESPACE, "DocumentID") + + @xmpmm_document_id.setter + def xmpmm_document_id(self, value: Optional[str]) -> None: + self._set_single_value(XMPMM_NAMESPACE, "DocumentID", value) + + @property + def xmpmm_instance_id(self) -> Optional[str]: + """An identifier for a specific incarnation of a document, updated each time a file is saved.""" + return self._get_single_value(XMPMM_NAMESPACE, "InstanceID") + + @xmpmm_instance_id.setter + def xmpmm_instance_id(self, value: Optional[str]) -> None: + self._set_single_value(XMPMM_NAMESPACE, "InstanceID", value) + + @property + def pdfaid_part(self) -> Optional[str]: + """The part of the PDF/A standard that the document conforms to (e.g., 1, 2, 3).""" + return self._get_single_value(PDFAID_NAMESPACE, "part") + + @pdfaid_part.setter + def pdfaid_part(self, value: Optional[str]) -> None: + self._set_single_value(PDFAID_NAMESPACE, "part", value) + + @property + def pdfaid_conformance(self) -> Optional[str]: + """The conformance level within the PDF/A standard (e.g., 'A', 'B', 'U').""" + return self._get_single_value(PDFAID_NAMESPACE, "conformance") + + @pdfaid_conformance.setter + def pdfaid_conformance(self, value: Optional[str]) -> None: + self._set_single_value(PDFAID_NAMESPACE, "conformance", value) + + @property + def custom_properties(self) -> dict[Any, Any]: + """ + Retrieve custom metadata properties defined in the undocumented pdfx + metadata schema. + + Returns: + A dictionary of key/value items for custom metadata properties. + + """ + if not hasattr(self, "_custom_properties"): + self._custom_properties = {} + for node in self.get_nodes_in_namespace("", PDFX_NAMESPACE): + key = node.localName + start = 0 + while True: + # see documentation about PDFX_NAMESPACE earlier in file + idx = key.find("\u2182", start) + if idx == -1: + break + hex_id = key[idx + 1 : idx + 5] + if len(hex_id) != 4 or not all(c in hexdigits for c in hex_id): + # Not a well-formed escape; leave the marker untouched + # and continue past it instead of crashing. + start = idx + 1 + continue + key = key[:idx] + chr(int(hex_id, base=16)) + key[idx + 5 :] + start = idx + 1 + if node.nodeType == node.ATTRIBUTE_NODE: + value = node.nodeValue + else: + value = self._get_text(node) + self._custom_properties[key] = value + return self._custom_properties + + def _get_or_create_description(self, about_uri: str = "") -> XmlElement: + """Get or create an rdf:Description element with the given about URI.""" + for desc in self.rdf_root.getElementsByTagNameNS(RDF_NAMESPACE, "Description"): + if desc.getAttributeNS(RDF_NAMESPACE, "about") == about_uri: + return desc + + doc = self.rdf_root.ownerDocument + if doc is None: + raise XmpDocumentError("XMP Document is None") + desc = doc.createElementNS(RDF_NAMESPACE, "rdf:Description") + desc.setAttributeNS(RDF_NAMESPACE, "rdf:about", about_uri) + self.rdf_root.appendChild(desc) + return desc + + def _clear_cache_entry(self, namespace: str, name: str) -> None: + """Remove a cached value for a given namespace/name if present.""" + ns_cache = self.cache.get(namespace) + if ns_cache and name in ns_cache: + del ns_cache[name] + + def _set_single_value(self, namespace: str, name: str, value: Optional[str]) -> None: + """Set or remove a single metadata value.""" + self._clear_cache_entry(namespace, name) + desc = self._get_or_create_description() + + existing_elements = list(desc.getElementsByTagNameNS(namespace, name)) + for elem in existing_elements: + desc.removeChild(elem) + + if existing_attr := desc.getAttributeNodeNS(namespace, name): + desc.removeAttributeNode(existing_attr) + + if value is not None: + doc = self.rdf_root.ownerDocument + if doc is None: + raise XmpDocumentError("XMP Document is None") + prefix = self._get_namespace_prefix(namespace) + elem = doc.createElementNS(namespace, f"{prefix}:{name}") + text_node = doc.createTextNode(str(value)) + elem.appendChild(text_node) + desc.appendChild(elem) + + self._update_stream() + + def _set_bag_values(self, namespace: str, name: str, values: Optional[list[str]]) -> None: + """Set or remove bag values (unordered array).""" + self._clear_cache_entry(namespace, name) + desc = self._get_or_create_description() + + existing_elements = list(desc.getElementsByTagNameNS(namespace, name)) + for elem in existing_elements: + desc.removeChild(elem) + + if values: + doc = self.rdf_root.ownerDocument + if doc is None: + raise XmpDocumentError("XMP Document is None") + prefix = self._get_namespace_prefix(namespace) + elem = doc.createElementNS(namespace, f"{prefix}:{name}") + bag = doc.createElementNS(RDF_NAMESPACE, "rdf:Bag") + + for value in values: + li = doc.createElementNS(RDF_NAMESPACE, "rdf:li") + text_node = doc.createTextNode(str(value)) + li.appendChild(text_node) + bag.appendChild(li) + + elem.appendChild(bag) + desc.appendChild(elem) + + self._update_stream() + + def _set_seq_values(self, namespace: str, name: str, values: Optional[list[str]]) -> None: + """Set or remove sequence values (ordered array).""" + self._clear_cache_entry(namespace, name) + desc = self._get_or_create_description() + + existing_elements = list(desc.getElementsByTagNameNS(namespace, name)) + for elem in existing_elements: + desc.removeChild(elem) + + if values: + doc = self.rdf_root.ownerDocument + if doc is None: + raise XmpDocumentError("XMP Document is None") + prefix = self._get_namespace_prefix(namespace) + elem = doc.createElementNS(namespace, f"{prefix}:{name}") + seq = doc.createElementNS(RDF_NAMESPACE, "rdf:Seq") + + for value in values: + li = doc.createElementNS(RDF_NAMESPACE, "rdf:li") + text_node = doc.createTextNode(str(value)) + li.appendChild(text_node) + seq.appendChild(li) + + elem.appendChild(seq) + desc.appendChild(elem) + + self._update_stream() + + def _set_langalt_values(self, namespace: str, name: str, values: Optional[dict[str, str]]) -> None: + """Set or remove language alternative values.""" + self._clear_cache_entry(namespace, name) + desc = self._get_or_create_description() + + existing_elements = list(desc.getElementsByTagNameNS(namespace, name)) + for elem in existing_elements: + desc.removeChild(elem) + + if values: + doc = self.rdf_root.ownerDocument + if doc is None: + raise XmpDocumentError("XMP Document is None") + prefix = self._get_namespace_prefix(namespace) + elem = doc.createElementNS(namespace, f"{prefix}:{name}") + alt = doc.createElementNS(RDF_NAMESPACE, "rdf:Alt") + + for lang, value in values.items(): + li = doc.createElementNS(RDF_NAMESPACE, "rdf:li") + li.setAttribute("xml:lang", lang) + text_node = doc.createTextNode(str(value)) + li.appendChild(text_node) + alt.appendChild(li) + + elem.appendChild(alt) + desc.appendChild(elem) + + self._update_stream() + + def _get_namespace_prefix(self, namespace: str) -> str: + """Get the appropriate namespace prefix for a given namespace URI.""" + return _NAMESPACE_PREFIX_MAP.get(namespace, "unknown") + + def _update_stream(self) -> None: + """Update the stream with the current XML content.""" + doc = self.rdf_root.ownerDocument + if doc is None: + raise XmpDocumentError("XMP Document is None") + + xml_data = doc.toxml(encoding="utf-8") + self.stream.set_data(xml_data) diff --git a/.venv/lib/python3.13/site-packages/python_dateutil-2.9.0.post0.dist-info/INSTALLER b/.venv/lib/python3.13/site-packages/python_dateutil-2.9.0.post0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/python_dateutil-2.9.0.post0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.13/site-packages/python_dateutil-2.9.0.post0.dist-info/LICENSE b/.venv/lib/python3.13/site-packages/python_dateutil-2.9.0.post0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1e65815cf0b3132689485874a93034ede7206bf4 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/python_dateutil-2.9.0.post0.dist-info/LICENSE @@ -0,0 +1,54 @@ +Copyright 2017- Paul Ganssle +Copyright 2017- dateutil contributors (see AUTHORS file) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +The above license applies to all contributions after 2017-12-01, as well as +all contributions that have been re-licensed (see AUTHORS file for the list of +contributors who have re-licensed their code). +-------------------------------------------------------------------------------- +dateutil - Extensions to the standard Python datetime module. + +Copyright (c) 2003-2011 - Gustavo Niemeyer +Copyright (c) 2012-2014 - Tomi Pieviläinen +Copyright (c) 2014-2016 - Yaron de Leeuw +Copyright (c) 2015- - Paul Ganssle +Copyright (c) 2015- - dateutil contributors (see AUTHORS file) + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + * Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +The above BSD License Applies to all code, even that also covered by Apache 2.0. \ No newline at end of file diff --git a/.venv/lib/python3.13/site-packages/python_dateutil-2.9.0.post0.dist-info/METADATA b/.venv/lib/python3.13/site-packages/python_dateutil-2.9.0.post0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..577f2bf2b7749e1b123b8225d610b1b257e430cc --- /dev/null +++ b/.venv/lib/python3.13/site-packages/python_dateutil-2.9.0.post0.dist-info/METADATA @@ -0,0 +1,204 @@ +Metadata-Version: 2.1 +Name: python-dateutil +Version: 2.9.0.post0 +Summary: Extensions to the standard Python datetime module +Home-page: https://github.com/dateutil/dateutil +Author: Gustavo Niemeyer +Author-email: gustavo@niemeyer.net +Maintainer: Paul Ganssle +Maintainer-email: dateutil@python.org +License: Dual License +Project-URL: Documentation, https://dateutil.readthedocs.io/en/stable/ +Project-URL: Source, https://github.com/dateutil/dateutil +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 2 +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.3 +Classifier: Programming Language :: Python :: 3.4 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Topic :: Software Development :: Libraries +Requires-Python: !=3.0.*,!=3.1.*,!=3.2.*,>=2.7 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: six >=1.5 + +dateutil - powerful extensions to datetime +========================================== + +|pypi| |support| |licence| + +|gitter| |readthedocs| + +|travis| |appveyor| |pipelines| |coverage| + +.. |pypi| image:: https://img.shields.io/pypi/v/python-dateutil.svg?style=flat-square + :target: https://pypi.org/project/python-dateutil/ + :alt: pypi version + +.. |support| image:: https://img.shields.io/pypi/pyversions/python-dateutil.svg?style=flat-square + :target: https://pypi.org/project/python-dateutil/ + :alt: supported Python version + +.. |travis| image:: https://img.shields.io/travis/dateutil/dateutil/master.svg?style=flat-square&label=Travis%20Build + :target: https://travis-ci.org/dateutil/dateutil + :alt: travis build status + +.. |appveyor| image:: https://img.shields.io/appveyor/ci/dateutil/dateutil/master.svg?style=flat-square&logo=appveyor + :target: https://ci.appveyor.com/project/dateutil/dateutil + :alt: appveyor build status + +.. |pipelines| image:: https://dev.azure.com/pythondateutilazure/dateutil/_apis/build/status/dateutil.dateutil?branchName=master + :target: https://dev.azure.com/pythondateutilazure/dateutil/_build/latest?definitionId=1&branchName=master + :alt: azure pipelines build status + +.. |coverage| image:: https://codecov.io/gh/dateutil/dateutil/branch/master/graphs/badge.svg?branch=master + :target: https://codecov.io/gh/dateutil/dateutil?branch=master + :alt: Code coverage + +.. |gitter| image:: https://badges.gitter.im/dateutil/dateutil.svg + :alt: Join the chat at https://gitter.im/dateutil/dateutil + :target: https://gitter.im/dateutil/dateutil + +.. |licence| image:: https://img.shields.io/pypi/l/python-dateutil.svg?style=flat-square + :target: https://pypi.org/project/python-dateutil/ + :alt: licence + +.. |readthedocs| image:: https://img.shields.io/readthedocs/dateutil/latest.svg?style=flat-square&label=Read%20the%20Docs + :alt: Read the documentation at https://dateutil.readthedocs.io/en/latest/ + :target: https://dateutil.readthedocs.io/en/latest/ + +The `dateutil` module provides powerful extensions to +the standard `datetime` module, available in Python. + +Installation +============ +`dateutil` can be installed from PyPI using `pip` (note that the package name is +different from the importable name):: + + pip install python-dateutil + +Download +======== +dateutil is available on PyPI +https://pypi.org/project/python-dateutil/ + +The documentation is hosted at: +https://dateutil.readthedocs.io/en/stable/ + +Code +==== +The code and issue tracker are hosted on GitHub: +https://github.com/dateutil/dateutil/ + +Features +======== + +* Computing of relative deltas (next month, next year, + next Monday, last week of month, etc); +* Computing of relative deltas between two given + date and/or datetime objects; +* Computing of dates based on very flexible recurrence rules, + using a superset of the `iCalendar `_ + specification. Parsing of RFC strings is supported as well. +* Generic parsing of dates in almost any string format; +* Timezone (tzinfo) implementations for tzfile(5) format + files (/etc/localtime, /usr/share/zoneinfo, etc), TZ + environment string (in all known formats), iCalendar + format files, given ranges (with help from relative deltas), + local machine timezone, fixed offset timezone, UTC timezone, + and Windows registry-based time zones. +* Internal up-to-date world timezone information based on + Olson's database. +* Computing of Easter Sunday dates for any given year, + using Western, Orthodox or Julian algorithms; +* A comprehensive test suite. + +Quick example +============= +Here's a snapshot, just to give an idea about the power of the +package. For more examples, look at the documentation. + +Suppose you want to know how much time is left, in +years/months/days/etc, before the next easter happening on a +year with a Friday 13th in August, and you want to get today's +date out of the "date" unix system command. Here is the code: + +.. code-block:: python3 + + >>> from dateutil.relativedelta import * + >>> from dateutil.easter import * + >>> from dateutil.rrule import * + >>> from dateutil.parser import * + >>> from datetime import * + >>> now = parse("Sat Oct 11 17:13:46 UTC 2003") + >>> today = now.date() + >>> year = rrule(YEARLY,dtstart=now,bymonth=8,bymonthday=13,byweekday=FR)[0].year + >>> rdelta = relativedelta(easter(year), today) + >>> print("Today is: %s" % today) + Today is: 2003-10-11 + >>> print("Year with next Aug 13th on a Friday is: %s" % year) + Year with next Aug 13th on a Friday is: 2004 + >>> print("How far is the Easter of that year: %s" % rdelta) + How far is the Easter of that year: relativedelta(months=+6) + >>> print("And the Easter of that year is: %s" % (today+rdelta)) + And the Easter of that year is: 2004-04-11 + +Being exactly 6 months ahead was **really** a coincidence :) + +Contributing +============ + +We welcome many types of contributions - bug reports, pull requests (code, infrastructure or documentation fixes). For more information about how to contribute to the project, see the ``CONTRIBUTING.md`` file in the repository. + + +Author +====== +The dateutil module was written by Gustavo Niemeyer +in 2003. + +It is maintained by: + +* Gustavo Niemeyer 2003-2011 +* Tomi Pieviläinen 2012-2014 +* Yaron de Leeuw 2014-2016 +* Paul Ganssle 2015- + +Starting with version 2.4.1 and running until 2.8.2, all source and binary +distributions will be signed by a PGP key that has, at the very least, been +signed by the key which made the previous release. A table of release signing +keys can be found below: + +=========== ============================ +Releases Signing key fingerprint +=========== ============================ +2.4.1-2.8.2 `6B49 ACBA DCF6 BD1C A206 67AB CD54 FCE3 D964 BEFB`_ +=========== ============================ + +New releases *may* have signed tags, but binary and source distributions +uploaded to PyPI will no longer have GPG signatures attached. + +Contact +======= +Our mailing list is available at `dateutil@python.org `_. As it is hosted by the PSF, it is subject to the `PSF code of +conduct `_. + +License +======= + +All contributions after December 1, 2017 released under dual license - either `Apache 2.0 License `_ or the `BSD 3-Clause License `_. Contributions before December 1, 2017 - except those those explicitly relicensed - are released only under the BSD 3-Clause License. + + +.. _6B49 ACBA DCF6 BD1C A206 67AB CD54 FCE3 D964 BEFB: + https://pgp.mit.edu/pks/lookup?op=vindex&search=0xCD54FCE3D964BEFB diff --git a/.venv/lib/python3.13/site-packages/python_dateutil-2.9.0.post0.dist-info/RECORD b/.venv/lib/python3.13/site-packages/python_dateutil-2.9.0.post0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..7b611d11a5b8e085c1511c6ce899c3d2d92b6bc4 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/python_dateutil-2.9.0.post0.dist-info/RECORD @@ -0,0 +1,44 @@ +dateutil/__init__.py,sha256=Mqam67WO9IkTmUFyI66vS6IoSXTp9G388DadH2LCMLY,620 +dateutil/__pycache__/__init__.cpython-313.pyc,, +dateutil/__pycache__/_common.cpython-313.pyc,, +dateutil/__pycache__/_version.cpython-313.pyc,, +dateutil/__pycache__/easter.cpython-313.pyc,, +dateutil/__pycache__/relativedelta.cpython-313.pyc,, +dateutil/__pycache__/rrule.cpython-313.pyc,, +dateutil/__pycache__/tzwin.cpython-313.pyc,, +dateutil/__pycache__/utils.cpython-313.pyc,, +dateutil/_common.py,sha256=77w0yytkrxlYbSn--lDVPUMabUXRR9I3lBv_vQRUqUY,932 +dateutil/_version.py,sha256=BV031OxDDAmy58neUg5yyqLkLaqIw7ibK9As3jiMib0,166 +dateutil/easter.py,sha256=dyBi-lKvimH1u_k6p7Z0JJK72QhqVtVBsqByvpEPKvc,2678 +dateutil/parser/__init__.py,sha256=wWk6GFuxTpjoggCGtgkceJoti4pVjl4_fHQXpNOaSYg,1766 +dateutil/parser/__pycache__/__init__.cpython-313.pyc,, +dateutil/parser/__pycache__/_parser.cpython-313.pyc,, +dateutil/parser/__pycache__/isoparser.cpython-313.pyc,, +dateutil/parser/_parser.py,sha256=7klDdyicksQB_Xgl-3UAmBwzCYor1AIZqklIcT6dH_8,58796 +dateutil/parser/isoparser.py,sha256=8Fy999bnCd1frSdOYuOraWfJTtd5W7qQ51NwNuH_hXM,13233 +dateutil/relativedelta.py,sha256=IY_mglMjoZbYfrvloTY2ce02aiVjPIkiZfqgNTZRfuA,24903 +dateutil/rrule.py,sha256=KJzKlaCd1jEbu4A38ZltslaoAUh9nSbdbOFdjp70Kew,66557 +dateutil/tz/__init__.py,sha256=F-Mz13v6jYseklQf9Te9J6nzcLDmq47gORa61K35_FA,444 +dateutil/tz/__pycache__/__init__.cpython-313.pyc,, +dateutil/tz/__pycache__/_common.cpython-313.pyc,, +dateutil/tz/__pycache__/_factories.cpython-313.pyc,, +dateutil/tz/__pycache__/tz.cpython-313.pyc,, +dateutil/tz/__pycache__/win.cpython-313.pyc,, +dateutil/tz/_common.py,sha256=cgzDTANsOXvEc86cYF77EsliuSab8Puwpsl5-bX3_S4,12977 +dateutil/tz/_factories.py,sha256=unb6XQNXrPMveksTCU-Ag8jmVZs4SojoPUcAHpWnrvU,2569 +dateutil/tz/tz.py,sha256=EUnEdMfeThXiY6l4sh9yBabZ63_POzy01zSsh9thn1o,62855 +dateutil/tz/win.py,sha256=xJszWgSwE1xPx_HJj4ZkepyukC_hNy016WMcXhbRaB8,12935 +dateutil/tzwin.py,sha256=7Ar4vdQCnnM0mKR3MUjbIKsZrBVfHgdwsJZc_mGYRew,59 +dateutil/utils.py,sha256=dKCchEw8eObi0loGTx91unBxm_7UGlU3v_FjFMdqwYM,1965 +dateutil/zoneinfo/__init__.py,sha256=KYg0pthCMjcp5MXSEiBJn3nMjZeNZav7rlJw5-tz1S4,5889 +dateutil/zoneinfo/__pycache__/__init__.cpython-313.pyc,, +dateutil/zoneinfo/__pycache__/rebuild.cpython-313.pyc,, +dateutil/zoneinfo/dateutil-zoneinfo.tar.gz,sha256=0-pS57bpaN4NiE3xKIGTWW-pW4A9tPkqGCeac5gARHU,156400 +dateutil/zoneinfo/rebuild.py,sha256=MiqYzCIHvNbMH-LdRYLv-4T0EIA7hDKt5GLR0IRTLdI,2392 +python_dateutil-2.9.0.post0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +python_dateutil-2.9.0.post0.dist-info/LICENSE,sha256=ugD1Gg2SgjtaHN4n2LW50jIeZ-2NqbwWPv-W1eF-V34,2889 +python_dateutil-2.9.0.post0.dist-info/METADATA,sha256=qdQ22jIr6AgzL5jYgyWZjofLaTpniplp_rTPrXKabpM,8354 +python_dateutil-2.9.0.post0.dist-info/RECORD,, +python_dateutil-2.9.0.post0.dist-info/WHEEL,sha256=-G_t0oGuE7UD0DrSpVZnq1hHMBV9DD2XkS5v7XpmTnk,110 +python_dateutil-2.9.0.post0.dist-info/top_level.txt,sha256=4tjdWkhRZvF7LA_BYe_L9gB2w_p2a-z5y6ArjaRkot8,9 +python_dateutil-2.9.0.post0.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 diff --git a/.venv/lib/python3.13/site-packages/python_dateutil-2.9.0.post0.dist-info/WHEEL b/.venv/lib/python3.13/site-packages/python_dateutil-2.9.0.post0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..4724c45738f6ac125bb3a21787855562e6870440 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/python_dateutil-2.9.0.post0.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.42.0) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/.venv/lib/python3.13/site-packages/python_dateutil-2.9.0.post0.dist-info/top_level.txt b/.venv/lib/python3.13/site-packages/python_dateutil-2.9.0.post0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..66501480ba5b63f98ee9a59c1f99e5e6917da6d9 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/python_dateutil-2.9.0.post0.dist-info/top_level.txt @@ -0,0 +1 @@ +dateutil diff --git a/.venv/lib/python3.13/site-packages/python_dateutil-2.9.0.post0.dist-info/zip-safe b/.venv/lib/python3.13/site-packages/python_dateutil-2.9.0.post0.dist-info/zip-safe new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/.venv/lib/python3.13/site-packages/python_dateutil-2.9.0.post0.dist-info/zip-safe @@ -0,0 +1 @@ + diff --git a/.venv/lib/python3.13/site-packages/pyyaml-6.0.3.dist-info/INSTALLER b/.venv/lib/python3.13/site-packages/pyyaml-6.0.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pyyaml-6.0.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.13/site-packages/pyyaml-6.0.3.dist-info/METADATA b/.venv/lib/python3.13/site-packages/pyyaml-6.0.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..702ee6da5865b50b297705b077ea7d5904fead58 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pyyaml-6.0.3.dist-info/METADATA @@ -0,0 +1,59 @@ +Metadata-Version: 2.4 +Name: PyYAML +Version: 6.0.3 +Summary: YAML parser and emitter for Python +Home-page: https://pyyaml.org/ +Download-URL: https://pypi.org/project/PyYAML/ +Author: Kirill Simonov +Author-email: xi@resolvent.net +License: MIT +Project-URL: Bug Tracker, https://github.com/yaml/pyyaml/issues +Project-URL: CI, https://github.com/yaml/pyyaml/actions +Project-URL: Documentation, https://pyyaml.org/wiki/PyYAMLDocumentation +Project-URL: Mailing lists, http://lists.sourceforge.net/lists/listinfo/yaml-core +Project-URL: Source Code, https://github.com/yaml/pyyaml +Platform: Any +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Cython +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Text Processing :: Markup +Requires-Python: >=3.8 +License-File: LICENSE +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: download-url +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: platform +Dynamic: project-url +Dynamic: requires-python +Dynamic: summary + +YAML is a data serialization format designed for human readability +and interaction with scripting languages. PyYAML is a YAML parser +and emitter for Python. + +PyYAML features a complete YAML 1.1 parser, Unicode support, pickle +support, capable extension API, and sensible error messages. PyYAML +supports standard YAML tags and provides Python-specific tags that +allow to represent an arbitrary Python object. + +PyYAML is applicable for a broad range of tasks from complex +configuration files to object serialization and persistence. diff --git a/.venv/lib/python3.13/site-packages/pyyaml-6.0.3.dist-info/RECORD b/.venv/lib/python3.13/site-packages/pyyaml-6.0.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..77d42b242869584c067a6c3ef67dae9d56dfdbcf --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pyyaml-6.0.3.dist-info/RECORD @@ -0,0 +1,43 @@ +_yaml/__init__.py,sha256=04Ae_5osxahpJHa3XBZUAf4wi6XX32gR8D6X6p64GEA,1402 +_yaml/__pycache__/__init__.cpython-313.pyc,, +pyyaml-6.0.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pyyaml-6.0.3.dist-info/METADATA,sha256=A8O0Fe040J-u3Ek2DpMHabQMWPaFhebeAOLkkWqFjTQ,2351 +pyyaml-6.0.3.dist-info/RECORD,, +pyyaml-6.0.3.dist-info/WHEEL,sha256=2iHh9e2o6T3nHtu_NVT7Cs7pebIqF94rZK8zrQfgoJI,190 +pyyaml-6.0.3.dist-info/licenses/LICENSE,sha256=jTko-dxEkP1jVwfLiOsmvXZBAqcoKVQwfT5RZ6V36KQ,1101 +pyyaml-6.0.3.dist-info/top_level.txt,sha256=rpj0IVMTisAjh_1vG3Ccf9v5jpCQwAz6cD1IVU5ZdhQ,11 +yaml/__init__.py,sha256=sZ38wzPWp139cwc5ARZFByUvJxtB07X32FUQAzoFR6c,12311 +yaml/__pycache__/__init__.cpython-313.pyc,, +yaml/__pycache__/composer.cpython-313.pyc,, +yaml/__pycache__/constructor.cpython-313.pyc,, +yaml/__pycache__/cyaml.cpython-313.pyc,, +yaml/__pycache__/dumper.cpython-313.pyc,, +yaml/__pycache__/emitter.cpython-313.pyc,, +yaml/__pycache__/error.cpython-313.pyc,, +yaml/__pycache__/events.cpython-313.pyc,, +yaml/__pycache__/loader.cpython-313.pyc,, +yaml/__pycache__/nodes.cpython-313.pyc,, +yaml/__pycache__/parser.cpython-313.pyc,, +yaml/__pycache__/reader.cpython-313.pyc,, +yaml/__pycache__/representer.cpython-313.pyc,, +yaml/__pycache__/resolver.cpython-313.pyc,, +yaml/__pycache__/scanner.cpython-313.pyc,, +yaml/__pycache__/serializer.cpython-313.pyc,, +yaml/__pycache__/tokens.cpython-313.pyc,, +yaml/_yaml.cpython-313-x86_64-linux-gnu.so,sha256=P5FgHX2lDz0VIegH8EggvhmMyu3CqJCU1pAxz4ko2K8,2653048 +yaml/composer.py,sha256=_Ko30Wr6eDWUeUpauUGT3Lcg9QPBnOPVlTnIMRGJ9FM,4883 +yaml/constructor.py,sha256=kNgkfaeLUkwQYY_Q6Ff1Tz2XVw_pG1xVE9Ak7z-viLA,28639 +yaml/cyaml.py,sha256=6ZrAG9fAYvdVe2FK_w0hmXoG7ZYsoYUwapG8CiC72H0,3851 +yaml/dumper.py,sha256=PLctZlYwZLp7XmeUdwRuv4nYOZ2UBnDIUy8-lKfLF-o,2837 +yaml/emitter.py,sha256=jghtaU7eFwg31bG0B7RZea_29Adi9CKmXq_QjgQpCkQ,43006 +yaml/error.py,sha256=Ah9z-toHJUbE9j-M8YpxgSRM5CgLCcwVzJgLLRF2Fxo,2533 +yaml/events.py,sha256=50_TksgQiE4up-lKo_V-nBy-tAIxkIPQxY5qDhKCeHw,2445 +yaml/loader.py,sha256=UVa-zIqmkFSCIYq_PgSGm4NSJttHY2Rf_zQ4_b1fHN0,2061 +yaml/nodes.py,sha256=gPKNj8pKCdh2d4gr3gIYINnPOaOxGhJAUiYhGRnPE84,1440 +yaml/parser.py,sha256=ilWp5vvgoHFGzvOZDItFoGjD6D42nhlZrZyjAwa0oJo,25495 +yaml/reader.py,sha256=0dmzirOiDG4Xo41RnuQS7K9rkY3xjHiVasfDMNTqCNw,6794 +yaml/representer.py,sha256=IuWP-cAW9sHKEnS0gCqSa894k1Bg4cgTxaDwIcbRQ-Y,14190 +yaml/resolver.py,sha256=9L-VYfm4mWHxUD1Vg4X7rjDRK_7VZd6b92wzq7Y2IKY,9004 +yaml/scanner.py,sha256=YEM3iLZSaQwXcQRg2l2R4MdT0zGP2F9eHkKGKnHyWQY,51279 +yaml/serializer.py,sha256=ChuFgmhU01hj4xgI8GaKv6vfM2Bujwa9i7d2FAHj7cA,4165 +yaml/tokens.py,sha256=lTQIzSVw8Mg9wv459-TjiOQe6wVziqaRlqX2_89rp54,2573 diff --git a/.venv/lib/python3.13/site-packages/pyyaml-6.0.3.dist-info/WHEEL b/.venv/lib/python3.13/site-packages/pyyaml-6.0.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..539ecdef0c43b82970407bf0d2e868801a0862df --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pyyaml-6.0.3.dist-info/WHEEL @@ -0,0 +1,7 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: false +Tag: cp313-cp313-manylinux_2_17_x86_64 +Tag: cp313-cp313-manylinux2014_x86_64 +Tag: cp313-cp313-manylinux_2_28_x86_64 + diff --git a/.venv/lib/python3.13/site-packages/pyyaml-6.0.3.dist-info/licenses/LICENSE b/.venv/lib/python3.13/site-packages/pyyaml-6.0.3.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2f1b8e15e5627d92f0521605c9870bc8e5505cb4 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pyyaml-6.0.3.dist-info/licenses/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2017-2021 Ingy döt Net +Copyright (c) 2006-2016 Kirill Simonov + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.venv/lib/python3.13/site-packages/pyyaml-6.0.3.dist-info/top_level.txt b/.venv/lib/python3.13/site-packages/pyyaml-6.0.3.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..e6475e911f628412049bc4090d86f23ac403adde --- /dev/null +++ b/.venv/lib/python3.13/site-packages/pyyaml-6.0.3.dist-info/top_level.txt @@ -0,0 +1,2 @@ +_yaml +yaml diff --git a/.venv/lib/python3.13/site-packages/reportlab/__init__.py b/.venv/lib/python3.13/site-packages/reportlab/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..586263f58e09e10b18d09ce37b8cbc5f762b435a --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/__init__.py @@ -0,0 +1,45 @@ +#Copyright ReportLab Europe Ltd. 2000-2026 +#see license.txt for license details +__doc__="""The Reportlab PDF generation library.""" +Version = "5.0.0" +__version__=Version +__date__='20260618' + +import sys, os + +__min_python_version__ = (3,9) +if sys.version_info< __min_python_version__: + raise ImportError("""reportlab requires %s.%s+; other versions are unsupported. +If you want to try with other python versions edit line 10 of reportlab/__init__ +to remove this error.""" % (__min_python_version__)) + +#define these early in reportlab's life +def cmp(a,b): + return -1 if ab else 0) + +def _fake_import(fn,name): + from importlib.util import spec_from_loader, module_from_spec + from importlib.machinery import SourceFileLoader + spec = spec_from_loader(name, SourceFileLoader(name, fn)) + module = module_from_spec(spec) + try: + spec.loader.exec_module(module) + except FileNotFoundError: + raise ImportError('file %s not found' % ascii(fn)) + sys.modules[name] = module + +#try to use dynamic modifications from +#reportlab.local_rl_mods.py +#reportlab_mods.py or ~/.reportlab_mods +try: + import reportlab.local_rl_mods +except ImportError: + pass + +try: + import reportlab_mods #application specific modifications can be anywhere on python path +except ImportError: + try: + _fake_import(os.path.expanduser(os.path.join('~','.reportlab_mods')),'reportlab_mods') + except (ImportError,KeyError,PermissionError): + pass diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/00readme.txt b/.venv/lib/python3.13/site-packages/reportlab/fonts/00readme.txt new file mode 100644 index 0000000000000000000000000000000000000000..08d545a8666ee2f1943071171b258c6a2ac886c6 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/fonts/00readme.txt @@ -0,0 +1,8 @@ +This directory is a convenient place to put +fonts where Reportlab will find them. If running +in a server environment, this is a good place to +put Type 1 fonts needed by your application. If +in a desktop environment, you might prefer to add +your font directories to the T1SearchPath in +reportlab/rl_config.py instead. + diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/DarkGarden-changelog.txt b/.venv/lib/python3.13/site-packages/reportlab/fonts/DarkGarden-changelog.txt new file mode 100644 index 0000000000000000000000000000000000000000..48b3b52ccdbbd1262e8e728ad06ecfdec5b0f6e9 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/fonts/DarkGarden-changelog.txt @@ -0,0 +1,14 @@ +2004-05-18 Michal Kosmulski + * Version 1.1 + * Changed license to GNU GPL with Font Exception + * Added Zacute character + * Added basic hinting + * Added kerning information +2000 Michal Kosmulski + * Version 1.0 + * Added Polish and German diacritic characters except for Zacute + +1999 Michal Kosmulski + * Version 0.9 + * Includes only the 26 letters of the English alphabet + * Distributed under a freeware license diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/DarkGarden-copying-gpl.txt b/.venv/lib/python3.13/site-packages/reportlab/fonts/DarkGarden-copying-gpl.txt new file mode 100644 index 0000000000000000000000000000000000000000..e77696ae8ddfea61c8da89bcfa4494707d67cad2 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/fonts/DarkGarden-copying-gpl.txt @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 675 Mass Ave, Cambridge, MA 02139, USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) 19yy + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) 19yy name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/DarkGarden-copying.txt b/.venv/lib/python3.13/site-packages/reportlab/fonts/DarkGarden-copying.txt new file mode 100644 index 0000000000000000000000000000000000000000..38cad8932ed392f7a991d60ea8ac6fcfa61af6f2 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/fonts/DarkGarden-copying.txt @@ -0,0 +1,26 @@ +Copyright (C) 1999, 2000, 2004 Michal Kosmulski + + +This font is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This font is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this font; if not, write to the Free Software +Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + +As a special exception, if you create a document which uses +this font, and embed this font or unaltered portions of this font into +the document, this font does not by itself cause the resulting +document to be covered by the GNU General Public License. This +exception does not however invalidate any other reasons why the +document might be covered by the GNU General Public License. If you +modify this font, you may extend this exception to your version of the +font, but you are not obligated to do so. If you do not wish to do so, +delete this exception statement from your version. diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/DarkGarden-readme.txt b/.venv/lib/python3.13/site-packages/reportlab/fonts/DarkGarden-readme.txt new file mode 100644 index 0000000000000000000000000000000000000000..ceeeb1033aebd294045f836ef37d4d0e05b395c4 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/fonts/DarkGarden-readme.txt @@ -0,0 +1,106 @@ +Dark Garden +=========== + + + +GENERAL + +Dark Garden is a decorative outline font of unusual shape. The typeface +is based on author's original hand drawings. The letterform is complex, +with all characters decorated with spikes resembling thorns or flames, +character spacing is very dense. Such a theme makes it a great font for +titles, banners, logos etc. + +As of version 1.1, Dark Garden includes letters of the English alphabet, +Polish and German diacritic characters and some punctuation. Unicode +encoding is used. The font is equipped with hinting information to allow +high quality rendering at small point sizes. Only horizontal and +vertical hints are currently used, future versions might take advantage +of truetype hinting instructions some day. There are also a lot of +kerning pairs defined in the font - they were chosen after looking at a +choice of Polish and English texts and selecting the character pairs +that needed manual kerning. + +The font was created with PfaEdit / FontForge +(http://fontforge.sourceforge.net/) - an opensource font editing tool. +Pfaedit uses its own text-based file format which can then be exported +to truetype, postscript, opentype and many other font formats. This +makes it possible to generate font files for Dark Garden in any of the +many supported formats, so it can be used on almost any platform. So +far, the truetype version has been tested on X11 (Linux) and Windows, +the opentype version worked on Windows but not X11. Truetype should also +work on Mac OS. + + + +INSTALLATION + +Installation is described for the truetype version of the font (which is +what most users will need). + +On Windows: +* Extract .ttf files from the archive into a temporary directory +* In the Control Panel choose Fonts +* From the File menu choose Install New Font +* Browse to the temporary directory you chose +* "Dark Garden" should appear in the font list - click OK (this may + require Administrator privileges) + +On Linux / UNIX (using KDE): +* Extract .ttf files from the archive into a temporary directory +* In the Control Center choose Font Installer in the System + Administration tree +* Click on "Administrator Mode" and enter root's password +* Click on "Add Fonts" icon +* Select the .ttf file extracted from the archive and click OK + +On Linux / UNIX (using commandline) + unzip darkgarden-*.ttf.zip + su + ginstall -o root -m 644 DarkGardenMK.ttf /usr/X11R6/lib/fonts/TTF + fc-cache -f + + + +COPYRIGHT AND LICENSE + +Copyright (C) 1999, 2000, 2004 Michal Kosmulski + + +This font is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This font is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this font; if not, write to the Free Software +Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + +As a special exception, if you create a document which uses +this font, and embed this font or unaltered portions of this font into +the document, this font does not by itself cause the resulting +document to be covered by the GNU General Public License. This +exception does not however invalidate any other reasons why the +document might be covered by the GNU General Public License. If you +modify this font, you may extend this exception to your version of the +font, but you are not obligated to do so. If you do not wish to do so, +delete this exception statement from your version. + +The text of this license can be found in file COPYING.txt in the +distribution archives. The GNU General Public License text can be found +in file COPYING-GPL.txt. + + + +CONTACTING THE AUTHOR + +Send e-mail with questions, bug reports and patches to Michal Kosmulski, +mkosmul@users.sourceforge.net + +The homepage of Dark Garden Font is located at +http://darkgarden.sourceforge.net/. diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/DarkGarden.sfd b/.venv/lib/python3.13/site-packages/reportlab/fonts/DarkGarden.sfd new file mode 100644 index 0000000000000000000000000000000000000000..e290c30f9fafa148f8c5f612856369e3e2954cbe --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/fonts/DarkGarden.sfd @@ -0,0 +1,11067 @@ +SplineFontDB: 1.0 +FontName: DarkGardenMK +FullName: Dark Garden +FamilyName: Dark Garden +Weight: Medium +Copyright: Copyright (C) 1999, 2000, 2004 Michal Kosmulski \n\n\nThis font is free software; you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2 of the License, or\n(at your option) any later version.\n\nThis font is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this font; if not, write to the Free Software\nFoundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\nAs a special exception, if you create a document which uses\nthis font, and embed this font or unaltered portions of this font into\nthe document, this font does not by itself cause the resulting\ndocument to be covered by the GNU General Public License. This\nexception does not however invalidate any other reasons why the\ndocument might be covered by the GNU General Public License. If you\nmodify this font, you may extend this exception to your version of the\nfont, but you are not obligated to do so. If you do not wish to do so,\ndelete this exception statement from your version.\n +Version: 1.1 +ItalicAngle: 0 +UnderlinePosition: -420 +UnderlineWidth: 80 +Ascent: 1638 +Descent: 410 +Order2: 1 +NeedsXUIDChange: 1 +FSType: 0 +PfmFamily: 81 +TTFWeight: 500 +TTFWidth: 5 +Panose: 2 11 6 3 5 6 0 0 2 4 +LineGap: 0 +VLineGap: 0 +OS2TypoAscent: 2311 +OS2TypoDescent: -708 +OS2WinAscent: 2311 +OS2WinDescent: 708 +ScriptLang: 1 + 1 latn 1 dflt +LangName: 1033 "" "" "Regular" "DarkGarden (Michal Kosmulski)" "" "" "" "" "Micha+AUIA Kosmulski" "Micha+AUIA Kosmulski" +Encoding: unicode +UnicodeInterp: none +DisplaySize: -48 +AntiAlias: 1 +FitToEm: 1 +WinInfo: 64 16 4 +TeXData: 1 10485760 0 524288 262144 174762 810240 -1048576 174762 783286 444596 497025 792723 393216 433062 380633 303038 157286 324010 404750 52429 2506097 1059062 262144 +BeginChars: 65538 86 +StartChar: .notdef +Encoding: 0 -1 0 +Width: 2048 +Flags: MW +VStem: 2 1085<0 1821> +Fore +2 0 m 1,0,-1 + 2 1821 l 0,1,-1 + 1087 1821 l 0,2,-1 + 1087 0 l 0,3,-1 + 2 0 l 1,0,-1 +EndSplineSet +EndChar +StartChar: glyph1 +Encoding: 1 -1 1 +Width: 0 +Flags: W +EndChar +StartChar: glyph2 +Encoding: 2 -1 2 +Width: 2048 +Flags: W +EndChar +StartChar: space +Encoding: 32 32 3 +Width: 1024 +Flags: W +EndChar +StartChar: comma +Encoding: 44 44 6 +Width: 267 +Flags: HMW +HStem: -1.6875 173.812<6.75 231.188> +VStem: 120.938 110.25<-133.875 -1.6875> +Fore +40.5 -154.125 m 1,0,1 + 96.75 -106.875 96.75 -106.875 106.875 -77.625 c 0,2,3 + 117 -48.375 117 -48.375 117 -37.125 c 0,4,5 + 123.75 -4.5 123.75 -4.5 91.125 -4.5 c 0,6,7 + 58.5 -4.5 58.5 -4.5 54 -2.25 c 0,8,9 + 4.5 11.25 4.5 11.25 2.25 81 c 0,10,11 + -1.125 133.875 -1.125 133.875 6.75 172.125 c 0,12,13 + 24.75 208.125 24.75 208.125 48.375 208.125 c 0,14,15 + 116.999 208.125 116.999 208.125 158.062 214.875 c 0,16,17 + 179.095 214.82 l 0,18,19 + 205.824 209.75 205.824 209.75 223.875 177.75 c 0,20,-1 + 248.062 129.938 l 0,21,22 + 251.423 123.475 251.423 123.475 251.338 108.103 c 0,23,24 + 251.239 90.0244 251.239 90.0244 246.375 59.625 c 0,25,-1 + 231.188 -1.6875 l 0,26,27 + 219.376 -49.4989 219.376 -49.4989 191.25 -88.875 c 0,28,29 + 164.25 -119.25 164.25 -119.25 120.938 -133.875 c 0,30,31 + 77.625 -148.5 77.625 -148.5 40.5 -154.125 c 1,0,1 +EndSplineSet +EndChar +StartChar: hyphen +Encoding: 45 45 7 +Width: 1252 +Flags: HMW +HStem: 843.75 163.5<206.75 1005.5> +Fore +379.25 809.25 m 1,0,1 + 319.25 789.75 319.25 789.75 266 800.25 c 0,2,3 + 212.75 810.75 212.75 810.75 212.75 866.25 c 0,4,-1 + 261.5 836.25 l 0,5,6 + 310.25 806.25 310.25 806.25 323.75 890.25 c 0,7,8 + 326.75 932.25 326.75 932.25 268.25 938.25 c 0,9,10 + 209.75 944.25 209.75 944.25 155.75 932.25 c 0,11,12 + 122.75 911.25 122.75 911.25 120.5 863.25 c 0,13,14 + 118.25 815.25 118.25 815.25 118.25 807.75 c 0,15,16 + 74.75 891.75 74.75 891.75 111.5 943.5 c 0,17,18 + 148.25 995.25 148.25 995.25 206.75 1007.25 c 0,19,20 + 344.75 1016.25 344.75 1016.25 464 972 c 0,21,22 + 583.25 927.75 583.25 927.75 718.25 927.75 c 0,23,24 + 764.75 932.25 764.75 932.25 821.75 932.25 c 0,25,26 + 878.75 932.25 878.75 932.25 889.25 966.75 c 0,27,28 + 884.75 1011.75 884.75 1011.75 844.25 1002.75 c 0,29,30 + 803.75 993.75 803.75 993.75 782.75 972.75 c 0,31,32 + 794.75 1005.75 794.75 1005.75 812.75 1033.5 c 0,33,34 + 830.75 1061.25 830.75 1061.25 878.75 1062.75 c 0,35,36 + 934.25 1047.75 934.25 1047.75 950.75 1032.75 c 0,37,38 + 967.25 1017.75 967.25 1017.75 982.25 969.75 c 0,39,40 + 982.25 936.75 982.25 936.75 998.75 915 c 0,41,42 + 1015.25 893.25 1015.25 893.25 1082.75 906.75 c 0,43,44 + 1121.75 921.75 1121.75 921.75 1145.75 947.25 c 0,45,46 + 1139.75 927.75 1139.75 927.75 1123.25 897.75 c 0,47,48 + 1106.75 867.75 1106.75 867.75 1079.75 854.25 c 0,49,-1 + 1079.75 854.25 l 0,50,-1 + 1079.75 854.25 l 0,51,52 + 1066.25 840.75 1066.25 840.75 1005.5 843.75 c 0,53,54 + 944.75 846.75 944.75 846.75 929.75 846.75 c 0,55,56 + 872.75 855.75 872.75 855.75 831.5 858 c 0,57,58 + 790.25 860.25 790.25 860.25 736.25 842.25 c 0,59,60 + 668.75 824.25 668.75 824.25 693.5 791.25 c 0,61,62 + 718.25 758.25 718.25 758.25 784.25 815.25 c 0,63,64 + 772.25 789.75 772.25 789.75 747.5 762 c 0,65,66 + 722.75 734.25 722.75 734.25 613.25 755.25 c 0,67,68 + 523.25 777.75 523.25 777.75 497.75 791.25 c 0,69,70 + 472.25 804.75 472.25 804.75 379.25 809.25 c 1,0,1 +EndSplineSet +KernsSLIF: 90 -260 0 0 122 -208 0 0 88 -182 0 0 120 -156 0 0 89 -130 0 0 121 -104 0 0 87 -182 0 0 119 -182 0 0 84 -286 0 0 116 -273 0 0 83 -234 0 0 115 -156 0 0 65 -234 0 0 97 -234 0 0 +EndChar +StartChar: period +Encoding: 46 46 5 +Width: 270 +Flags: HMW +HStem: 57.9375 152.438<9 235.688> +Fore +142.875 2.25 m 0,0,1 + 103.5 -1.125 103.5 -1.125 92.25 14.625 c 0,2,3 + 81 29.25 81 29.25 63 34.875 c 0,4,5 + 6.75 51.75 6.75 51.75 4.5 120.375 c 0,6,7 + 0 172.125 0 172.125 9 210.375 c 0,8,9 + 27 246.375 27 246.375 50.625 246.375 c 0,10,11 + 119.249 246.375 119.249 246.375 160.312 253.125 c 0,12,13 + 181.345 253.07 l 0,14,15 + 208.074 248 208.074 248 226.125 216 c 0,16,-1 + 250.312 168.188 l 0,17,18 + 253.673 161.725 253.673 161.725 253.588 146.353 c 0,19,20 + 253.489 128.274 253.489 128.274 248.625 97.875 c 0,21,22 + 245.249 84.3705 245.249 84.3705 235.688 57.9375 c 0,23,24 + 226.126 31.5004 226.126 31.5004 214.875 24.75 c 0,25,26 + 180 4.5 180 4.5 142.875 2.25 c 0,0,1 +EndSplineSet +EndChar +StartChar: colon +Encoding: 58 58 34 +Width: 384 +Flags: HMW +HStem: 23.625 211.5<86.625 239.062> 678.75 191.25<108.75 288.75> +Fore +108.75 870 m 1,0,1 + 166.125 930.75 166.125 930.75 202.125 909.938 c 0,2,3 + 238.125 889.125 238.125 889.125 295.5 832.875 c 0,4,5 + 325.875 802.5 325.875 802.5 325.312 754.125 c 0,6,7 + 324.75 705.75 324.75 705.75 288.75 678.75 c 0,8,9 + 211.125 621.375 211.125 621.375 189.75 618 c 0,10,11 + 168.375 614.625 168.375 614.625 131.25 636 c 0,12,13 + 80.625 663 80.625 663 75 680.438 c 0,14,15 + 69.375 697.875 69.375 697.875 68.25 731.625 c 0,16,17 + 64.875 775.5 64.875 775.5 67.6875 803.062 c 0,18,19 + 70.5 830.625 70.5 830.625 108.75 870 c 0,20,-1 + 108.75 870 l 1,0,1 +86.625 235.125 m 0,16,17 + 95.625 275.625 95.625 275.625 164.25 279 c 0,18,19 + 232.875 282.375 232.875 282.375 252 271.125 c 0,20,21 + 273.375 257.625 273.375 257.625 289.688 189.562 c 0,22,23 + 301.323 141.017 301.323 141.017 301.225 117.366 c 0,24,25 + 301.185 107.859 301.185 107.859 299.25 102.375 c 0,26,27 + 273.375 34.875 273.375 34.875 239.062 23.625 c 0,28,29 + 204.749 12.375 204.749 12.375 160.875 12.375 c 0,30,31 + 145.124 12.375 145.124 12.375 128.812 39.9375 c 0,32,33 + 112.499 67.5003 112.499 67.5003 95.625 75.375 c 0,34,35 + 68.625 86.625 68.625 86.625 73.125 142.875 c 0,36,37 + 77.625 199.125 77.625 199.125 86.625 235.125 c 0,16,17 +EndSplineSet +EndChar +StartChar: semicolon +Encoding: 59 59 35 +Width: 384 +Flags: HMW +HStem: 45 132.75<91.125 303.75> 738 180<118.875 291> +VStem: 154.125 149.625<-200.25 45> +Fore +118.875 918 m 1,0,1 + 177.375 977.625 177.375 977.625 212.25 957.375 c 0,2,3 + 247.125 937.125 247.125 937.125 305.625 880.875 c 0,4,5 + 366.375 821.25 366.375 821.25 291 738 c 0,6,7 + 238.125 679.5 238.125 679.5 230.25 678.938 c 0,8,9 + 222.375 678.375 222.375 678.375 141.375 682.875 c 0,10,11 + 82.875 686.25 82.875 686.25 81.1875 716.062 c 0,12,13 + 79.5 745.875 79.5 745.875 77.25 779.625 c 0,14,15 + 73.875 823.5 73.875 823.5 77.25 850.5 c 0,16,17 + 80.625 877.5 80.625 877.5 118.875 918 c 0,18,-1 + 118.875 918 l 1,0,1 +91.125 177.75 m 0,15,16 + 100.125 218.251 100.125 218.251 169.312 222.188 c 0,17,18 + 225.136 222.126 l 0,19,20 + 247.88 220.056 247.88 220.056 257.625 213.75 c 0,21,22 + 278.999 200.25 278.999 200.25 293.062 133.312 c 0,23,24 + 307.125 66.375 307.125 66.375 303.75 45 c 0,25,26 + 292.5 -19.125 292.5 -19.125 246.938 -110.25 c 0,27,28 + 202.357 -199.411 202.357 -199.411 154.125 -200.25 c 0,29,30 + 201.375 -173.25 201.375 -173.25 201.375 -86.625 c 0,31,32 + 201.375 0 201.375 0 174.375 6.75 c 0,33,34 + 140.074 9.61226 l 0,35,36 + 138.95 9.59327 138.95 9.59327 137.812 9.5625 c 0,37,38 + 113.206 12.6329 l 0,39,40 + 106.394 14.6566 106.394 14.6566 100.125 18 c 0,41,42 + 73.125 30.375 73.125 30.375 77.625 85.5 c 0,43,44 + 82.125 140.625 82.125 140.625 91.125 177.75 c 0,15,16 +EndSplineSet +EndChar +StartChar: A +Encoding: 65 65 55 +Width: 1447 +Flags: W +Fore +1268 -330 m 1,0,1 + 1304.01 -261.985 1304.01 -261.985 1321 -184 c 0,2,3 + 1324.46 -150.427 l 0,4,5 + 1323.49 -92.1465 1323.49 -92.1465 1272 -43 c 0,6,7 + 1221.01 4.9888 1221.01 4.9888 1171 38 c 0,8,9 + 1121.01 71 1121.01 71 1066 52 c 0,10,11 + 1028.99 38 1028.99 38 1019.5 -17 c 0,12,13 + 1010.01 -72 1010.01 -72 1006 -72 c 0,14,15 + 965 9 965 9 1013.5 102 c 0,16,17 + 1059.21 189.663 1059.21 189.663 1059.17 266.65 c 0,18,19 + 1059.17 271.346 1059.17 271.346 1059 276 c 0,20,21 + 1053 434.993 1053 434.993 1006 491.5 c 0,22,23 + 959.002 547.999 959.002 547.999 895 573 c 0,24,25 + 861.093 585.849 861.093 585.849 831.581 585.768 c 0,26,27 + 778.406 585.622 778.406 585.622 739.5 543.5 c 0,28,29 + 679.002 478.002 679.002 478.002 616 450 c 0,30,31 + 577 432 577 432 533.5 448.5 c 0,32,33 + 490 465 490 465 487 510 c 0,34,35 + 532 492 532 492 543.5 499.5 c 0,36,37 + 555 507 555 507 558 514 c 0,38,39 + 579 558 579 558 530 570 c 0,40,41 + 424 595 424 595 383 514 c 0,42,43 + 347 446 347 446 318.5 347 c 0,44,45 + 290 248 290 248 328 164 c 0,46,47 + 336.295 144.644 336.295 144.644 336.228 116.448 c 0,48,49 + 336.198 103.856 336.198 103.856 334.5 89.5 c 0,50,51 + 328.999 42.9997 328.999 42.9997 283 27 c 0,52,53 + 302 105 302 105 245 98 c 0,54,55 + 188 91 188 91 157 57 c 0,56,57 + 89.0005 -17 89.0005 -17 55 -80 c 0,58,59 + 21 -143 21 -143 33 -233 c 0,60,61 + 7.11917 -206.16 7.11917 -206.16 6.9652 -142.109 c 0,62,63 + 6.95854 -139.339 6.95854 -139.339 7 -136.5 c 0,64,65 + 8 -67.9999 8 -67.9999 27 -36 c 0,66,67 + 60 22 60 22 93.5 73.5 c 0,68,69 + 126.999 124.999 126.999 124.999 128 188 c 0,70,71 + 128 227 128 227 100 243 c 0,72,73 + 89.0676 246.192 l 0,74,75 + 81.8899 245.118 81.8899 245.118 81.7695 231.241 c 0,76,77 + 87 197 l 0,78,79 + 60.9999 218 60.9999 218 60.5 237 c 0,80,81 + 63 272 l 0,82,83 + 105 461 105 461 237.5 625 c 0,84,85 + 370.001 789.001 370.001 789.001 396 894 c 0,86,87 + 431.998 1045.99 431.998 1045.99 450 1180 c 0,88,89 + 458 1246.01 458 1246.01 501 1303.5 c 0,90,91 + 526.01 1336.94 526.01 1336.94 555.08 1337.06 c 0,92,93 + 575.989 1337.15 575.989 1337.15 599 1320 c 0,94,95 + 545 1309.01 545 1309.01 543 1280.5 c 0,96,97 + 541 1252 541 1252 552 1240 c 0,98,99 + 570.499 1217.04 570.499 1217.04 589 1216.86 c 0,100,101 + 599.5 1216.76 599.5 1216.76 610 1224 c 0,102,103 + 666.003 1261.01 666.003 1261.01 702.5 1381 c 0,104,105 + 739 1501 739 1501 737 1567 c 0,106,107 + 734 1633 734 1633 690 1672 c 0,108,109 + 669.348 1690.31 669.348 1690.31 646.491 1690.32 c 0,110,111 + 620.654 1690.35 620.654 1690.35 592 1667 c 0,112,113 + 628 1758.99 628 1758.99 682.5 1745 c 0,114,115 + 737 1731.01 737 1731.01 792.5 1671.5 c 0,116,117 + 848.023 1611.97 848.023 1611.97 896 1539 c 0,118,119 + 944 1465.99 944 1465.99 966 1440 c 0,120,121 + 1000.99 1397.01 1000.99 1397.01 1047 1369 c 0,122,123 + 1092.99 1341 1092.99 1341 1112 1302 c 0,124,125 + 1127.05 1269.26 1127.05 1269.26 1127.11 1243.37 c 0,126,127 + 1127.19 1210.74 1127.19 1210.74 1103.5 1189 c 0,128,129 + 1081.08 1168.42 1081.08 1168.42 1054.61 1168.45 c 0,130,131 + 1030.93 1168.47 1030.93 1168.47 1004 1185 c 0,132,133 + 1024.39 1186.95 l 0,134,135 + 1038.73 1191.67 1038.73 1191.67 1040 1207 c 0,136,137 + 1040 1232 1040 1232 1000.5 1252 c 0,138,139 + 992.466 1256.07 992.466 1256.07 986.066 1256.04 c 0,140,141 + 961 1255.93 961 1255.93 961 1193 c 0,142,143 + 961 1164.99 961 1164.99 974 1131.5 c 0,144,145 + 987 1098.01 987 1098.01 995 1082 c 0,146,147 + 1018.3 1023.02 1018.3 1023.02 1032.59 1022.63 c 0,148,149 + 1036.22 1022.53 1036.22 1022.53 1039.27 1026.22 c 0,150,151 + 1040.7 1027.94 1040.7 1027.94 1042 1030.5 c 0,152,153 + 1057 1060.01 1057 1060.01 1039 1080 c 0,154,155 + 1077.99 1080 1077.99 1080 1091 1030.5 c 0,156,157 + 1104 981.019 1104 981.019 1104 968 c 0,158,159 + 1104 893.057 1104 893.057 1094.5 786.5 c 0,160,161 + 1092.76 724.816 l 0,162,163 + 1095.42 659.144 1095.42 659.144 1119 612 c 0,164,165 + 1129.97 589.052 1129.97 589.052 1171 527.5 c 0,166,167 + 1211.99 466.005 1211.99 466.005 1230 456 c 0,168,169 + 1251.99 443.008 1251.99 443.008 1272.5 399.5 c 0,170,171 + 1278.45 386.871 1278.45 386.871 1278.38 375.043 c 0,172,173 + 1278.2 346.131 1278.2 346.131 1242 322 c 0,174,175 + 1248.76 340.824 1248.76 340.824 1248.69 354.457 c 0,176,177 + 1248.53 387.176 1248.53 387.176 1209 390 c 0,178,179 + 1180.02 387.742 l 0,180,181 + 1171.73 385.453 1171.73 385.453 1169 380 c 0,182,183 + 1166.86 361.224 l 0,184,185 + 1167.14 356.858 1167.14 356.858 1168 352 c 0,186,187 + 1183 234.001 1183 234.001 1270 167 c 0,188,189 + 1357.01 99.9952 1357.01 99.9952 1368 -1 c 0,190,191 + 1372.17 -39.7089 1372.17 -39.7089 1372.1 -75.0335 c 0,192,193 + 1371.98 -132.791 1371.98 -132.791 1360.5 -181.5 c 0,194,195 + 1342.01 -259.987 1342.01 -259.987 1268 -330 c 1,0,1 +701 705 m 0,116,117 + 736.5 753 l 0,118,119 + 755 778 755 778 776 793 c 0,120,121 + 839 831 839 831 860 763 c 0,122,123 + 831.214 778.397 831.214 778.397 813.857 778.333 c 0,124,125 + 805.285 778.302 805.285 778.302 799.5 774.5 c 0,126,127 + 790.855 768.819 790.855 768.819 790.629 758.624 c 0,128,129 + 794.49 742.017 l 0,130,131 + 796.315 737.74 796.315 737.74 799 733 c 0,132,133 + 827 679 827 679 877 735 c 0,134,135 + 927 791 927 791 912 878 c 0,136,137 + 904.001 918.996 904.001 918.996 851 1051 c 0,138,139 + 798 1183 798 1183 759 1150 c 0,140,141 + 734.385 1130 734.385 1130 734.326 1102.31 c 0,142,143 + 734.308 1094 734.308 1094 736.5 1085 c 0,144,145 + 746 1046 746 1046 750 1010 c 0,146,147 + 756 938 756 938 726 869.5 c 0,148,149 + 696 801 696 801 585 843 c 0,150,151 + 616 840 616 840 661 864.5 c 0,152,153 + 706 889 706 889 654 934 c 0,154,155 + 635 949 635 949 610.5 934.5 c 0,156,157 + 585.998 919.998 585.998 919.998 571 901 c 0,158,159 + 531.263 848.664 531.263 848.664 530.978 805.134 c 0,160,161 + 530.881 790.211 530.881 790.211 535.419 776.324 c 0,162,163 + 544.962 747.125 544.962 747.125 575 722.5 c 0,164,165 + 661 652 661 652 701 705 c 0,116,117 +EndSplineSet +KernsSLIF: 67 -52 0 0 99 -130 0 0 77 -104 0 0 109 -78 0 0 104 -130 0 0 72 -104 0 0 45 -169 0 0 115 -286 0 0 83 -247 0 0 121 -299 0 0 89 -257 0 0 116 -299 0 0 84 -299 0 0 118 -65 0 0 119 -230 0 0 86 -50 0 0 87 -193 0 0 +EndChar +StartChar: B +Encoding: 66 66 16 +Width: 1278 +Flags: HMW +HStem: 48 189<429.6 747.3> 726 257<422.4 754.5> 1447 200<399 696> 1549 111<30 212.7> +VStem: 246 153<-28 1647> +Fore +502 218 m 1,0,1 + 561.4 216.556 l 0,2,3 + 622.601 219 622.601 219 691 237 c 0,4,5 + 793.6 264 793.6 264 865.6 297 c 0,6,7 + 926.8 324 926.8 324 994 397 c 0,8,9 + 1036 442.625 1036 442.625 1036.28 481.219 c 0,10,11 + 1036.38 494.855 1036.38 494.855 1031.27 507.613 c 0,12,13 + 1027.71 516.52 1027.71 516.52 1021.6 525 c 0,14,15 + 1007.2 544 1007.2 544 977.2 551.5 c 0,16,17 + 947.2 559 947.2 559 923.2 535 c 0,18,19 + 907.6 519 907.6 519 914.2 492 c 0,20,21 + 920.8 465 920.8 465 962.8 448 c 0,22,23 + 930.4 424 930.4 424 872.8 455.5 c 0,24,25 + 815.2 487 815.2 487 824.8 540 c 0,26,27 + 834.4 599 834.4 599 892 634.5 c 0,28,29 + 949.6 670 949.6 670 930.4 721 c 0,30,31 + 914.8 760 914.8 760 828.4 789 c 0,32,33 + 742 818 742 818 659.2 824 c 0,34,35 + 583.6 829 583.6 829 518.2 821 c 0,36,37 + 452.8 813 452.8 813 422.8 749 c 0,38,39 + 397.6 699 397.6 699 394 644 c 0,40,41 + 392.642 563.434 l 0,42,43 + 393.092 550.121 393.092 550.121 394 537 c 0,44,45 + 394 505 394 505 425.8 479 c 0,46,47 + 441.204 466.405 441.204 466.405 461.255 466.482 c 0,48,49 + 482.596 466.563 482.596 466.563 509.2 481 c 0,50,51 + 563.2 511 563.2 511 547 549.5 c 0,52,53 + 530.8 588 530.8 588 487.6 600 c 0,54,55 + 535.6 628 535.6 628 587.2 607 c 0,56,57 + 641.417 584.409 641.417 584.409 641.743 534.874 c 0,58,59 + 641.778 529.59 641.778 529.59 641.2 524 c 0,60,61 + 635.2 466 635.2 466 600.4 434 c 0,62,63 + 568 404 568 404 494.8 354.5 c 0,64,65 + 421.6 305 421.6 305 432.4 260 c 0,66,67 + 439.6 222.999 439.6 222.999 502 218 c 0,68,-1 + 502 218 l 1,0,1 +407.399 1024 m 1,44,45 + 440.211 988.385 440.211 988.385 494.485 988.133 c 0,46,47 + 515.008 988.038 515.008 988.038 538.6 993 c 0,48,49 + 710.352 1029.12 710.352 1029.12 715 1040 c 0,50,-1 + 855 1160 l 0,51,52 + 892.587 1216.39 892.587 1216.39 895 1340 c 0,53,54 + 891.78 1368.18 l 0,55,56 + 877.492 1424.08 877.492 1424.08 800.199 1467 c 0,57,58 + 718.469 1511.32 718.469 1511.32 663.365 1511.34 c 0,59,60 + 653.779 1511.34 653.779 1511.34 645 1510 c 0,61,62 + 624.821 1506.71 624.821 1506.71 624.832 1481.94 c 0,63,64 + 624.843 1459.52 624.843 1459.52 641.399 1419.5 c 0,65,66 + 656.36 1382.55 656.36 1382.55 656.399 1347.14 c 0,67,68 + 656.445 1304.45 656.445 1304.45 634.8 1264 c 0,69,70 + 577.198 1157.99 577.198 1157.99 480 1165 c 0,71,72 + 542.913 1179.56 542.913 1179.56 543.048 1262.94 c 0,73,74 + 543.052 1265.44 543.052 1265.44 543 1268 c 0,75,76 + 541.199 1356 541.199 1356 471.6 1356 c 0,77,78 + 412.814 1356 412.814 1356 390 1175 c 0,79,80 + 385.232 1137.17 385.232 1137.17 385.253 1108.14 c 0,81,82 + 385.299 1045.82 385.299 1045.82 407.399 1024 c 0,83,-1 + 407.399 1024 l 1,44,45 +329 42.5 m 145,-1,-1 + 217.398 -13.5 l 0,45,46 + 189.653 -11.4947 l 0,47,48 + 152.289 -3.04026 152.289 -3.04026 148.549 38.5 c 0,49,50 + 143.6 93.5001 143.6 93.5001 170.6 138.5 c 0,51,52 + 171.034 92.1899 l 0,53,54 + 175.03 55.9341 175.03 55.9341 193.049 55.9206 c 0,55,56 + 196.817 55.9177 196.817 55.9177 201.199 57.5 c 0,57,58 + 237.199 70.5001 237.199 70.5001 243.049 146 c 0,59,60 + 245.057 225.875 l 0,61,62 + 244.13 266.908 244.13 266.908 239.449 311.5 c 0,63,64 + 230 401.5 230 401.5 212.449 482.5 c 0,65,66 + 194.897 563.5 194.897 563.5 185.898 586.5 c 0,67,68 + 148.1 672.5 148.1 672.5 131 707 c 0,69,70 + 109.776 749.815 109.776 749.815 62.5996 814.5 c 0,71,72 + 25.0875 865.935 25.0875 865.935 25.0878 930.344 c 0,73,74 + 25.0878 938.566 25.0878 938.566 25.6992 947 c 0,75,76 + 31.099 1021.51 31.099 1021.51 84.1992 1062.5 c 0,77,78 + 105.439 1078.95 105.439 1078.95 132.197 1079.03 c 0,79,80 + 142.86 1079.06 142.86 1079.06 154.398 1076.5 c 0,81,82 + 194.898 1067.5 194.898 1067.5 199.398 984.5 c 0,83,84 + 181.495 1010.2 181.495 1010.2 153.067 1010.13 c 0,85,86 + 147.206 1010.11 147.206 1010.11 140.898 1009 c 0,87,88 + 108.919 1003.37 108.919 1003.37 108.71 956.798 c 0,89,90 + 108.678 949.633 108.678 949.633 109.398 941.5 c 0,91,92 + 113.898 888.5 113.898 888.5 153.5 887 c 0,93,94 + 177.527 889.565 l 0,95,96 + 198.558 895.607 198.558 895.607 209.299 915.5 c 0,97,98 + 244.941 978.864 244.941 978.864 244.85 1117 c 0,99,100 + 244.398 1254.51 244.398 1254.51 239 1337.5 c 0,101,102 + 234.5 1398.51 234.5 1398.51 214.699 1474 c 0,103,104 + 197.487 1539.63 197.487 1539.63 136.544 1539.54 c 0,105,106 + 125.889 1539.52 125.889 1539.52 113.898 1537.5 c 0,107,108 + 53.5987 1527.32 53.5987 1527.32 53.5019 1477.59 c 0,109,110 + 53.4845 1468.68 53.4845 1468.68 55.3984 1458.5 c 0,111,112 + 67.9981 1391.51 67.9981 1391.51 95 1387.5 c 0,113,114 + 71.1185 1384.55 l 0,115,116 + 33.5813 1386.31 33.5813 1386.31 9.04883 1432 c 0,117,118 + -9.05229 1465.71 -9.05229 1465.71 -9.0989 1503.43 c 0,119,120 + -9.13456 1532.29 -9.13456 1532.29 1.39844 1563.5 c 0,121,122 + 48.8936 1701.35 48.8936 1701.35 184.1 1674.5 c 0,123,-1 + 277.25 1656 l 0,124,125 + 288.387 1652.52 288.387 1652.52 303.567 1652.53 c 0,126,127 + 337.485 1652.56 337.485 1652.56 391.6 1670 c 0,128,129 + 439.6 1686.01 439.6 1686.01 478.6 1730 c 0,130,131 + 517.645 1774.05 517.645 1774.05 550 1807 c 0,132,133 + 571.608 1830 571.608 1830 616.6 1849.5 c 0,134,135 + 661.6 1869 661.6 1869 701.2 1863 c 0,136,137 + 757.593 1855.01 757.593 1855.01 810.4 1807 c 0,138,139 + 844.491 1776.01 844.491 1776.01 844.565 1732.09 c 0,140,141 + 844.604 1708.46 844.604 1708.46 834.4 1680 c 0,142,143 + 826.002 1712.99 826.002 1712.99 757 1759 c 0,144,145 + 732.891 1775.07 732.891 1775.07 713.659 1775.14 c 0,146,147 + 686.315 1775.24 686.315 1775.24 668.833 1742.98 c 0,148,149 + 664.282 1734.59 664.282 1734.59 660.4 1724 c 0,150,151 + 659.954 1711.82 l 0,152,153 + 668.693 1677.46 668.693 1677.46 782.8 1621.5 c 0,154,155 + 918.4 1555.01 918.4 1555.01 954.4 1515 c 0,156,157 + 1044.4 1411.99 1044.4 1411.99 1061.8 1300 c 0,158,159 + 1069.05 1253.31 1069.05 1253.31 1068.98 1209.14 c 0,160,161 + 1068.86 1141.63 1068.86 1141.63 1051.6 1080 c 0,162,163 + 1043.2 1049.99 1043.2 1049.99 997 1004.5 c 0,164,165 + 964.388 972.382 964.388 972.382 932.075 972.403 c 0,166,167 + 918.612 972.412 918.612 972.412 905.2 978 c 0,168,169 + 938.8 1012.99 938.8 1012.99 905.2 1026 c 0,170,171 + 886.612 1029.18 l 0,172,173 + 869.691 1027.82 869.691 1027.82 865.6 1006 c 0,174,175 + 857.2 961 857.2 961 951.4 850 c 0,176,177 + 1046.91 737.47 1046.91 737.47 1080.4 784 c 0,178,179 + 1098.4 809 1098.4 809 1080.4 844 c 0,180,181 + 1062.4 879 1062.4 879 1025.2 906 c 0,182,183 + 1133.2 903 1133.2 903 1181.2 815.5 c 0,184,185 + 1229.2 728 1229.2 728 1231.6 695 c 0,186,187 + 1235.2 629 1235.2 629 1196.2 526 c 0,188,189 + 1157.2 423 1157.2 423 1157.2 339 c 0,190,191 + 1157.2 237.999 1157.2 237.999 1142.8 158 c 0,192,193 + 1128.4 78.0005 1128.4 78.0005 1085.2 27 c 0,194,195 + 1033.6 -33 1033.6 -33 947.2 -50 c 0,196,197 + 904 -59 904 -59 830.2 -52 c 0,198,199 + 756.4 -45 756.4 -45 725.2 -20 c 0,200,201 + 780.4 -32 780.4 -32 833.2 -4.5 c 0,202,203 + 887.95 24.0156 887.95 24.0156 856 71 c 0,204,205 + 835.6 101 835.6 101 731.2 97 c 0,206,207 + 626.8 92.9999 626.8 92.9999 584.8 90 c 0,208,-1 + 450.4 79.5 l 0,209,210 + 396.73 69.5341 396.73 69.5341 329 42.5 c 145,-1,-1 +EndSplineSet +EndChar +StartChar: C +Encoding: 67 67 9 +Width: 1268 +Flags: W +Fore +47 1225 m 0,0,1 + 49.4717 1250.42 l 0,2,3 + 59.182 1290.3 59.182 1290.3 105 1339.5 c 0,4,5 + 139.698 1376.76 139.698 1376.76 170.189 1376.97 c 0,6,7 + 184.334 1377.07 184.334 1377.07 197.574 1369.19 c 0,8,9 + 205.969 1364.2 205.969 1364.2 214 1356 c 0,10,11 + 161.521 1347.64 161.521 1347.64 161.103 1310.92 c 0,12,13 + 165.255 1287.2 l 0,14,15 + 165.612 1286.11 165.612 1286.11 166 1285 c 0,16,17 + 173.846 1261.46 173.846 1261.46 188.296 1261.14 c 0,18,19 + 201.91 1265.14 l 0,20,21 + 214.659 1272.25 214.659 1272.25 231 1292 c 0,22,23 + 279.011 1350.02 279.011 1350.02 288 1369 c 0,24,25 + 316.999 1432 316.999 1432 325.5 1494 c 0,26,27 + 334.002 1556.01 334.002 1556.01 375 1609 c 0,28,29 + 407.609 1651.5 407.609 1651.5 461 1651.5 c 0,30,31 + 513.998 1651.01 513.998 1651.01 527 1612 c 0,32,33 + 477.134 1610.54 477.134 1610.54 476.205 1594.01 c 0,34,35 + 479.67 1583.33 l 0,36,37 + 480.687 1581.71 480.687 1581.71 482 1580 c 0,38,39 + 503 1550 503 1550 539 1571 c 0,40,41 + 575.016 1592.01 575.016 1592.01 592 1608 c 0,42,43 + 625.211 1639.88 625.211 1639.88 625.553 1659.63 c 0,44,45 + 622.289 1671.21 l 0,46,47 + 620.426 1674.05 620.426 1674.05 617.5 1676.5 c 0,48,49 + 605.555 1686.5 605.555 1686.5 590.873 1686.63 c 0,50,51 + 579.546 1686.73 579.546 1686.73 566.589 1680.95 c 0,52,53 + 561.901 1678.86 561.901 1678.86 557 1676 c 0,54,55 + 561.001 1724.01 561.001 1724.01 599 1730.5 c 0,56,57 + 631.988 1732.53 l 0,58,59 + 649.19 1731.37 649.19 1731.37 663 1725 c 0,60,61 + 774.955 1671.02 774.955 1671.02 848.5 1627 c 0,62,63 + 922.028 1582.99 922.028 1582.99 944 1574 c 0,64,65 + 980.724 1556.52 980.724 1556.52 1013.99 1556.61 c 0,66,67 + 1018.78 1556.62 1018.78 1556.62 1023.5 1557 c 0,68,69 + 1065.63 1556.28 l 0,70,71 + 1085.75 1554.21 1085.75 1554.21 1108 1549 c 0,72,73 + 1133.01 1543 1133.01 1543 1141 1509 c 0,74,75 + 1144.76 1476.5 l 0,76,77 + 1144.64 1459.48 1144.64 1459.48 1140 1443 c 0,78,79 + 1100.54 1480.38 1100.54 1480.38 1075.21 1480.38 c 0,80,81 + 1063.96 1480.38 1063.96 1480.38 1055.5 1473 c 0,82,83 + 1028 1449 1028 1449 1027 1379 c 0,84,85 + 1025.99 1342.76 1025.99 1342.76 1023.5 1308 c 0,86,87 + 1024.8 1274.25 l 0,88,89 + 1027.4 1257.24 1027.4 1257.24 1034 1241 c 0,90,91 + 1056.99 1187 1056.99 1187 1104 1173.5 c 0,92,93 + 1150.99 1160 1150.99 1160 1208 1157 c 0,94,95 + 1193.22 1128.26 1193.22 1128.26 1142.36 1128.18 c 0,96,97 + 1131.28 1128.16 1131.28 1128.16 1118.5 1129.5 c 0,98,99 + 1046.99 1137 1046.99 1137 1024 1155 c 0,100,101 + 960.474 1201.53 960.474 1201.53 960.191 1248.45 c 0,102,103 + 960.158 1253.97 960.158 1253.97 961 1259.5 c 0,104,105 + 961.658 1293.31 l 0,106,107 + 957.59 1340.52 957.59 1340.52 929 1412 c 0,108,109 + 904.002 1471.99 904.002 1471.99 828.5 1485 c 0,110,111 + 753 1498.01 753 1498.01 702 1440 c 0,112,113 + 663 1395 663 1395 633 1335 c 0,114,115 + 603.007 1275.01 603.007 1275.01 567 1229 c 0,116,117 + 553 1211 553 1211 495 1212.5 c 0,118,119 + 442.472 1213.86 442.472 1213.86 441.617 1243.51 c 0,120,121 + 441.528 1246.6 441.528 1246.6 442 1250 c 0,122,123 + 476 1233.01 476 1233.01 508 1254.5 c 0,124,125 + 538.826 1275.21 538.826 1275.21 539 1309 c 0,126,127 + 538.026 1346.98 538.026 1346.98 516 1347.5 c 0,128,129 + 494.008 1347.01 494.008 1347.01 476 1335 c 0,130,131 + 422.998 1299 422.998 1299 400 1269 c 0,132,133 + 376.997 1239 376.997 1239 363 1178 c 0,134,135 + 350.291 1125.16 350.291 1125.16 350.334 1075.45 c 0,136,137 + 350.354 1050.84 350.354 1050.84 353.5 1027 c 0,138,-1 + 373 875 l 0,139,140 + 377 833 377 833 392.5 790.5 c 0,141,142 + 408 748 408 748 402 708 c 0,143,144 + 384 597 384 597 276 601 c 0,145,146 + 297 615 297 615 321 643.5 c 0,147,148 + 345 672 345 672 327 704 c 0,149,150 + 317.431 720.586 317.431 720.586 296.467 720.691 c 0,151,152 + 284.569 720.75 284.569 720.75 269 715.5 c 0,153,154 + 226 701 226 701 222 674 c 0,155,156 + 203.999 574.997 203.999 574.997 203.5 494 c 0,157,158 + 207.196 446.84 l 0,159,160 + 216.755 387.21 216.755 387.21 251 323 c 0,161,162 + 274 279 274 279 310 272.5 c 0,163,164 + 325.021 273.259 l 0,165,166 + 349.347 280.951 349.347 280.951 361 333 c 0,167,168 + 367 358 367 358 360.5 370.5 c 0,169,170 + 354.013 382.975 354.013 382.975 340 408 c 0,171,172 + 364 402 364 402 386 395.5 c 0,173,174 + 408 389 408 389 420 365 c 0,175,176 + 444 317 444 317 448 270 c 0,177,178 + 452.001 223 452.001 223 469 172 c 0,179,180 + 485.999 112 485.999 112 527 100 c 0,181,182 + 549.843 92.7319 549.843 92.7319 568.743 92.6397 c 0,183,184 + 589.209 92.5398 589.209 92.5398 605.053 100.853 c 0,185,186 + 630.948 114.44 630.948 114.44 644.5 150.5 c 0,187,188 + 674 228.999 674 228.999 713 284 c 0,189,190 + 728 306 728 306 758.5 303 c 0,191,192 + 789 300 789 300 807 272 c 0,193,194 + 822.48 247.06 822.48 247.06 822.428 228.037 c 0,195,196 + 822.42 224.94 822.42 224.94 822 222 c 0,197,198 + 806.151 230.453 806.151 230.453 792.255 230.533 c 0,199,200 + 779.849 230.604 779.849 230.604 769 224 c 0,201,202 + 756.895 216.632 756.895 216.632 756.701 206.493 c 0,203,204 + 760.654 193.505 l 0,205,206 + 762.764 189.883 762.764 189.883 766 186 c 0,207,208 + 778.697 169.395 778.697 169.395 794.376 169.248 c 0,209,210 + 804.891 169.149 804.891 169.149 816.746 176.451 c 0,211,212 + 823.411 180.556 823.411 180.556 830.5 187 c 0,213,214 + 869 221.999 869 221.999 872 275 c 0,215,216 + 875 343 875 343 864 401 c 0,217,218 + 853.002 458.994 853.002 458.994 830 527 c 0,219,220 + 819 558 819 558 829.5 632 c 0,221,222 + 840 706 840 706 877 760 c 0,223,224 + 871 705 871 705 863.5 649.5 c 0,225,226 + 856 594 856 594 874 540 c 0,227,228 + 887.006 500.985 887.006 500.985 903 460.5 c 0,229,230 + 919 420 919 420 937 388 c 0,231,232 + 967.999 333.002 967.999 333.002 997 302 c 0,233,234 + 1020.46 276.921 1020.46 276.921 1064.21 276.712 c 0,235,236 + 1074.54 276.663 1074.54 276.663 1086 278 c 0,237,238 + 1110.37 280.089 1110.37 280.089 1110.5 306.429 c 0,239,240 + 1110.55 317.912 1110.55 317.912 1106 334 c 0,241,242 + 1118.66 334.754 l 0,243,244 + 1131.52 331.594 1131.52 331.594 1143 312 c 0,245,246 + 1157.23 287.716 1157.23 287.716 1157.45 273.956 c 0,247,248 + 1157.49 271.279 1157.49 271.279 1157 269 c 0,249,250 + 1148 226.995 1148 226.995 1130.5 212 c 0,251,252 + 1112.99 197 1112.99 197 1075 185 c 0,253,254 + 1046.42 174.52 1046.42 174.52 1011.5 174.5 c 0,255,256 + 978 174.999 978 174.999 951 161 c 0,257,258 + 914 141.001 914 141.001 909.5 67 c 0,259,260 + 905 -6.99995 905 -6.99995 884 -48 c 0,261,262 + 861 -91.0001 861 -91.0001 795 -104 c 0,263,264 + 769 -108.999 769 -108.999 721.5 -100 c 0,265,266 + 674 -91 674 -91 675 -49 c 0,267,268 + 706 -76 706 -76 748 -55 c 0,269,270 + 771 -41 771 -41 760.5 -12 c 0,271,272 + 750 17 750 17 728 23 c 0,273,274 + 701 27 701 27 672 20 c 0,275,276 + 643 12.9999 643 12.9999 618 4 c 0,277,278 + 510.997 -35.0014 510.997 -35.0014 450.5 -65 c 0,279,280 + 390 -95 390 -95 288 -50 c 0,281,282 + 255.001 -35.0002 255.001 -35.0002 248 19 c 0,283,284 + 240.999 73 240.999 73 266 90 c 0,285,286 + 268.764 57.7708 l 0,287,288 + 273.271 37.2823 273.271 37.2823 285 23.5 c 0,289,290 + 305 -3.8147e-06 305 -3.8147e-06 326 18 c 0,291,292 + 351 42 351 42 330 84.5 c 0,293,294 + 309 126.999 309 126.999 270 170 c 0,295,296 + 231.004 212.997 231.004 212.997 189 247 c 0,297,298 + 147 281 147 281 132 287 c 0,299,300 + 90.8733 273.479 90.8733 273.479 90.2146 252.658 c 0,301,302 + 93.6925 239.052 l 0,303,304 + 99.219 228.316 99.219 228.316 113.5 216 c 0,305,306 + 168.001 168.999 168.001 168.999 208 167 c 0,307,308 + 164.966 164.347 l 0,309,310 + 113.852 166.12 113.852 166.12 87.5 195 c 0,311,312 + 51 235.001 51 235.001 27 291 c 0,313,314 + -18 394 -18 394 7 532 c 0,315,316 + 21 601 21 601 58.5 666.5 c 0,317,318 + 96 732 96 732 100 804 c 0,319,320 + 104.001 909 104.001 909 77.5 1014 c 0,321,322 + 50.9998 1119 50.9998 1119 47 1225 c 0,0,1 +EndSplineSet +KernsSLIF: 83 -143 0 0 115 -130 0 0 65 -65 0 0 97 -91 0 0 +EndChar +StartChar: D +Encoding: 68 68 59 +Width: 1497 +Flags: HMW +VStem: 205 177.5<-118.5 1622> +Fore +365 -163 m 1,0,1 + 416.469 -202.888 416.469 -202.888 460.901 -203.041 c 0,2,3 + 485.532 -203.126 485.532 -203.126 508 -191 c 0,4,5 + 571 -156.999 571 -156.999 570 -140 c 0,6,7 + 568.069 -103.299 568.069 -103.299 511.5 -103 c 0,8,9 + 454.994 -104.001 454.994 -104.001 382.5 -118.5 c 0,10,11 + 309.985 -133.004 309.985 -133.004 241 -149.5 c 0,12,13 + 187.813 -162.219 187.813 -162.219 159.581 -162.162 c 0,14,15 + 151.188 -162.146 151.188 -162.146 145 -161 c 0,16,17 + 87.0002 -150.001 87.0002 -150.001 36.5 -93.5 c 0,18,19 + -14 -37 -14 -37 31 65 c 0,20,21 + 32 -35 32 -35 80 -60.5 c 0,22,23 + 106.871 -74.7751 106.871 -74.7751 136.405 -74.7912 c 0,24,25 + 159.629 -74.8038 159.629 -74.8038 184.5 -66 c 0,26,27 + 241 -46.0003 241 -46.0003 287.5 5 c 0,28,29 + 334 56 334 56 334 110 c 0,30,31 + 334 134.001 334 134.001 303 181 c 0,32,33 + 272 227.999 272 227.999 240 223 c 0,34,35 + 200.921 216.053 200.921 216.053 200.681 163.856 c 0,36,37 + 200.645 155.947 200.645 155.947 201.5 147 c 0,38,39 + 207.999 79.0005 207.999 79.0005 242 55 c 0,40,41 + 198 57 198 57 186 69.5 c 0,42,43 + 173.999 82.0008 173.999 82.0008 166 102 c 0,44,45 + 146.175 148.259 146.175 148.259 146.18 200.646 c 0,46,47 + 146.186 259.24 146.186 259.24 171 325.5 c 0,48,49 + 217.997 450.995 217.997 450.995 255 533 c 0,50,51 + 281 592 281 592 288.5 644.5 c 0,52,53 + 296 697 296 697 284 804 c 0,54,55 + 272 905.001 272 905.001 200.5 994 c 0,56,57 + 129.006 1082.99 129.006 1082.99 113 1136 c 0,58,59 + 105.918 1159.37 105.918 1159.37 105.92 1182.3 c 0,60,61 + 105.924 1224.13 105.924 1224.13 129.5 1264.5 c 0,62,63 + 159.568 1315.99 159.568 1315.99 217.121 1316.24 c 0,64,65 + 229.432 1316.29 229.432 1316.29 243 1314 c 0,66,67 + 217.999 1303.01 217.999 1303.01 202.5 1270.5 c 0,68,69 + 197.239 1259.47 197.239 1259.47 197.22 1249.64 c 0,70,71 + 197.184 1230.54 197.184 1230.54 217 1216 c 0,72,73 + 229.554 1206.32 229.554 1206.32 239.508 1206.15 c 0,74,75 + 250.481 1209.35 l 0,76,77 + 269.179 1221.62 269.179 1221.62 275 1281 c 0,78,79 + 280.343 1335.49 280.343 1335.49 280.262 1373.43 c 0,80,81 + 280.192 1406.51 280.192 1406.51 276 1427 c 0,82,83 + 265.002 1483.99 265.002 1483.99 241 1527 c 0,84,85 + 216.996 1570.01 216.996 1570.01 205 1622 c 0,86,87 + 198.585 1647.66 198.585 1647.66 198.623 1675.88 c 0,88,89 + 198.661 1704.84 198.661 1704.84 205.5 1736.5 c 0,90,91 + 218.999 1799 218.999 1799 263 1838 c 0,92,93 + 292.994 1866 292.994 1866 351 1867.5 c 0,94,95 + 385.17 1864.86 l 0,96,97 + 415.91 1858.47 415.91 1858.47 430 1837 c 0,98,99 + 440 1820.01 440 1820.01 448 1802.5 c 0,100,101 + 451.449 1794.95 451.449 1794.95 451.366 1783.78 c 0,102,103 + 451.257 1769.05 451.257 1769.05 445 1748 c 0,104,105 + 439 1775 439 1775 383 1796 c 0,106,107 + 370.726 1800.6 370.726 1800.6 360.326 1800.69 c 0,108,109 + 348.764 1800.79 348.764 1800.79 339.517 1795.3 c 0,110,111 + 319.131 1783.21 319.131 1783.21 310 1744 c 0,112,113 + 296 1690 296 1690 342.5 1657 c 0,114,115 + 389.022 1623.98 389.022 1623.98 438 1601 c 0,116,117 + 481.975 1580.01 481.975 1580.01 619 1544.5 c 0,118,119 + 667.085 1532.04 667.085 1532.04 700.019 1532.08 c 0,120,121 + 760.914 1532.16 760.914 1532.16 770 1575 c 0,122,123 + 774.3 1598.65 774.3 1598.65 774.32 1618.05 c 0,124,125 + 774.385 1679.86 774.385 1679.86 731 1698.5 c 0,126,127 + 703.091 1710.49 703.091 1710.49 679.502 1710.62 c 0,128,129 + 662.09 1710.72 662.09 1710.72 647.03 1704.36 c 0,130,131 + 635 1698 l 0,132,133 + 635 1743 635 1743 670 1758.5 c 0,134,135 + 704.999 1773.99 704.999 1773.99 713 1775 c 0,136,137 + 760 1774.5 l 0,138,139 + 802.004 1770.17 802.004 1770.17 824 1750.5 c 0,140,141 + 857.006 1720.99 857.006 1720.99 872 1694 c 0,142,143 + 896.002 1649 896.002 1649 913.5 1585 c 0,144,145 + 930.999 1521 930.999 1521 973 1494 c 0,146,147 + 1042 1450.01 1042 1450.01 1072 1440 c 0,148,149 + 1102 1429.99 1102 1429.99 1177 1419 c 0,150,151 + 1282.99 1403 1282.99 1403 1308 1317 c 0,152,153 + 1313.32 1295.3 1313.32 1295.3 1313.3 1276.45 c 0,154,155 + 1313.22 1206.7 1313.22 1206.7 1240 1176 c 0,156,157 + 1260.26 1204.06 1260.26 1204.06 1260.48 1235.14 c 0,158,159 + 1260.55 1243.95 1260.55 1243.95 1259 1253 c 0,160,161 + 1252.76 1289.51 1252.76 1289.51 1206.87 1289.54 c 0,162,163 + 1201.23 1289.55 1201.23 1289.55 1195 1289 c 0,164,165 + 1174.85 1287.11 1174.85 1287.11 1174.92 1260.84 c 0,166,167 + 1174.96 1245.39 1174.96 1245.39 1182 1221.5 c 0,168,169 + 1201.02 1156.95 1201.02 1156.95 1214 1130 c 0,170,171 + 1274.01 1003.97 1274.01 1003.97 1353 887 c 0,172,173 + 1432 770.008 1432 770.008 1438 703 c 0,174,175 + 1437.29 667.063 l 0,176,177 + 1429.48 607.261 1429.48 607.261 1377 554 c 0,178,179 + 1359 536 1359 536 1318.5 532.5 c 0,180,181 + 1285.16 533.1 l 0,182,183 + 1266.74 535.756 1266.74 535.756 1253 544 c 0,184,185 + 1292 544 1292 544 1311.5 575 c 0,186,187 + 1320.25 588.918 1320.25 588.918 1320.44 600.216 c 0,188,189 + 1317.5 612.987 l 0,190,191 + 1314.39 618.996 1314.39 618.996 1308 624 c 0,192,193 + 1266 653 1266 653 1237.5 607.5 c 0,194,195 + 1209 562 1209 562 1200 535 c 0,196,197 + 1198.96 531.908 1198.96 531.908 1180 489.5 c 0,198,199 + 1161.01 447.043 1161.01 447.043 1144.5 396.5 c 0,200,201 + 1128 346 1128 346 1123.5 303.5 c 0,202,203 + 1124.19 278.807 l 0,204,205 + 1128.4 260.303 1128.4 260.303 1146 259 c 0,206,207 + 1188 255 1188 255 1203 276 c 0,208,209 + 1218.01 297.013 1218.01 297.013 1232 339 c 0,210,211 + 1252.93 293.919 1252.93 293.919 1253.12 259.927 c 0,212,213 + 1253.22 242.802 1253.22 242.802 1248.05 228.491 c 0,214,215 + 1244.37 218.279 1244.37 218.279 1238 209.5 c 0,216,217 + 1205 164 1205 164 1175 152 c 0,218,219 + 1085 115.002 1085 115.002 1029.5 103.5 c 0,220,221 + 974 91.9999 974 91.9999 930.5 75.5 c 0,222,223 + 887 59 887 59 844.5 22.5 c 0,224,225 + 801.998 -14.0021 801.998 -14.0021 740 -103 c 0,226,227 + 619.211 -271.373 619.211 -271.373 522.285 -271.438 c 0,228,229 + 513.29 -271.444 513.29 -271.444 504.5 -270 c 0,230,231 + 401 -253 401 -253 365 -163 c 1,0,1 +725 192 m 0,122,123 + 749 216 749 216 794.5 272 c 0,124,125 + 840 328 840 328 855 355 c 0,126,127 + 879.999 397.998 879.999 397.998 888.5 438.5 c 0,128,129 + 897 479 897 479 906 529 c 0,130,131 + 922 613 922 613 979 629.5 c 0,132,133 + 1000.57 635.743 1000.57 635.743 1016.41 635.759 c 0,134,135 + 1042.44 635.784 1042.44 635.784 1053 619 c 0,136,137 + 1002 619 1002 619 984 586 c 0,138,139 + 966 553 966 553 977 538 c 0,140,141 + 989.486 518.904 989.486 518.904 1004.74 518.755 c 0,142,143 + 1015.01 518.656 1015.01 518.656 1026.55 527.159 c 0,144,145 + 1044.5 540.4 1044.5 540.4 1065.5 574.5 c 0,146,147 + 1120 663.009 1120 663.009 1126 744 c 0,148,149 + 1130.99 817 1130.99 817 1094.5 950.5 c 0,150,151 + 1066.07 1054.48 1066.07 1054.48 1021.56 1054.42 c 0,152,153 + 1008.93 1054.4 1008.93 1054.4 995 1046 c 0,154,155 + 975.667 1034 975.667 1034 975.667 1018 c 0,156,157 + 975.667 1010 975.667 1010 980.5 1001 c 0,158,159 + 995.002 973.998 995.002 973.998 1038 962 c 0,160,161 + 954 929 954 929 929.5 1003.5 c 0,162,163 + 904.996 1078.02 904.996 1078.02 894 1138 c 0,164,165 + 876.999 1227 876.999 1227 805.5 1282.5 c 0,166,167 + 734 1338 734 1338 651.5 1350 c 0,168,169 + 605.665 1352.79 l 0,170,171 + 548.883 1351.23 548.883 1351.23 498 1324 c 0,172,173 + 427.002 1286.01 427.002 1286.01 412 1188 c 0,174,175 + 405 1146 405 1146 419.5 1117.5 c 0,176,177 + 434 1089 434 1089 470 1098 c 0,178,179 + 485 1101.75 485 1101.75 485.375 1115.63 c 0,180,181 + 484 1126 l 0,182,183 + 477.997 1149.01 477.997 1149.01 454 1166 c 0,184,185 + 479.875 1167.62 l 0,186,187 + 516.252 1164.25 516.252 1164.25 538 1126 c 0,188,189 + 546.998 1108 546.998 1108 553 1077.5 c 0,190,191 + 553.751 1052.78 l 0,192,193 + 551.262 1032.3 551.262 1032.3 539 1009 c 0,194,195 + 458.999 855.998 458.999 855.998 437.5 671.5 c 0,196,197 + 416 487 416 487 428 407 c 0,198,199 + 445 284 445 284 488.5 279.5 c 0,200,201 + 532 275 532 275 539 318 c 0,202,203 + 538.454 335.091 l 0,204,205 + 531.345 359 531.345 359 484 359 c 0,206,207 + 490 374 490 374 509.5 376 c 0,208,209 + 529 378 529 378 541 381 c 0,210,211 + 567.678 382.442 l 0,212,213 + 608.823 378.097 608.823 378.097 618.5 327 c 0,214,215 + 630.999 261.003 630.999 261.003 643 220 c 0,216,217 + 652 181 652 181 678 176.5 c 0,218,219 + 697.181 176.647 l 0,220,221 + 712.042 179.66 712.042 179.66 725 192 c 0,122,123 +EndSplineSet +KernsSLIF: 90 -182 0 0 122 -143 0 0 97 -207 0 0 65 -150 0 0 +EndChar +StartChar: E +Encoding: 69 69 53 +Width: 1257 +Flags: HMW +HStem: 47 32.5<30 142.5> 89 202.5<224.5 921.5> 729 161<354 767> 1357 203<404 858> +VStem: 117.5 176.5<365 1523> +Fore +702 114 m 1,0,1 + 611.006 112.001 611.006 112.001 515.5 93.5 c 0,2,3 + 420 75.0001 420 75.0001 339 36 c 0,4,5 + 268 1.99995 268 1.99995 178.5 -13.5 c 0,6,7 + 88.9995 -29 88.9995 -29 30 47 c 0,8,9 + -15 107 -15 107 15 159.5 c 0,10,11 + 40.0002 203.25 40.0002 203.25 98.3333 203.597 c 0,12,13 + 110 203.667 110 203.667 123 202 c 0,14,-1 + 82.5 186.5 l 0,15,16 + 64.901 179.851 64.901 179.851 64.7384 152.708 c 0,17,18 + 64.6931 145.149 64.6931 145.149 66 136 c 0,19,20 + 75 70 75 70 142.5 79.5 c 0,21,22 + 210 88.9999 210 88.9999 225 162 c 0,23,24 + 229.413 184.556 229.413 184.556 229.378 216.128 c 0,25,26 + 229.341 248.943 229.341 248.943 224.5 291.5 c 0,27,28 + 215.001 375 215.001 375 152 384 c 0,29,30 + 129.001 387 129.001 387 117.5 365 c 0,31,32 + 105.999 343 105.999 343 110 322 c 0,33,34 + 117.001 279 117.001 279 152 244 c 0,35,36 + 84.0005 262 84.0005 262 60 326 c 0,37,38 + 14 446 14 446 47.5 574 c 0,39,40 + 80.9999 702 80.9999 702 102 820 c 0,41,42 + 121.001 932.001 121.001 932.001 124.5 984 c 0,43,44 + 124.02 1053.51 l 0,45,46 + 121.855 1094.37 121.855 1094.37 116 1150 c 0,47,48 + 103.999 1246.01 103.999 1246.01 60.5 1348.5 c 0,49,50 + 17 1450.99 17 1450.99 22 1545 c 0,51,52 + 24 1585.01 24 1585.01 32 1606.5 c 0,53,54 + 40 1627.99 40 1627.99 71 1653 c 0,55,56 + 106.829 1682.31 106.829 1682.31 136.69 1682.29 c 0,57,58 + 180.171 1682.25 180.171 1682.25 211 1620 c 0,59,60 + 188.421 1640.26 188.421 1640.26 166.513 1640.58 c 0,61,62 + 147.914 1637.21 l 0,63,64 + 141.427 1634.75 141.427 1634.75 135 1630.5 c 0,65,66 + 110.758 1614.45 110.758 1614.45 110.555 1588.31 c 0,67,68 + 110.455 1575.46 110.455 1575.46 117 1558 c 0,69,70 + 135.515 1508.3 135.515 1508.3 195 1508 c 0,71,72 + 253.999 1509.01 253.999 1509.01 294 1523 c 0,73,74 + 395.012 1556 395.012 1556 501.5 1639.5 c 0,75,76 + 591.424 1710.01 591.424 1710.01 685.277 1710.28 c 0,77,78 + 702.572 1710.33 702.572 1710.33 720 1708 c 0,79,80 + 764 1702 764 1702 787.5 1661.5 c 0,81,82 + 811 1621 811 1621 787 1582 c 0,83,84 + 776.899 1645.98 776.899 1645.98 721.089 1646.53 c 0,85,86 + 698.5 1644.5 l 0,87,88 + 623.013 1631.18 623.013 1631.18 623 1584 c 0,89,90 + 623 1526.01 623 1526.01 680.99 1525.71 c 0,91,92 + 698 1525.62 698 1525.62 720 1530.5 c 0,93,94 + 817.381 1552.08 817.381 1552.08 858 1560 c 0,95,96 + 911.778 1569.96 911.778 1569.96 983.5 1580 c 0,97,98 + 1036.93 1583.69 l 0,99,100 + 1076.51 1583.35 1076.51 1583.35 1110 1573 c 0,101,102 + 1244.01 1531 1244.01 1531 1255 1399 c 0,103,104 + 1249 1432 1249 1432 1232 1452 c 0,105,106 + 1215.02 1471.98 1215.02 1471.98 1200 1485 c 0,107,108 + 1153.97 1523.47 1153.97 1523.47 1089.78 1523.48 c 0,109,110 + 1060.52 1523.48 1060.52 1523.48 1027.5 1515.5 c 0,111,112 + 921.99 1490 921.99 1490 863 1441 c 0,113,114 + 833.001 1415.01 833.001 1415.01 827.5 1379 c 0,115,116 + 828.033 1360.63 l 0,117,118 + 833.454 1337.82 833.454 1337.82 864 1324 c 0,119,120 + 869.974 1321.01 869.974 1321.01 888.5 1315.5 c 0,121,122 + 900.641 1311.89 900.641 1311.89 918.181 1311.94 c 0,123,124 + 927.351 1311.97 927.351 1311.97 938 1313 c 0,125,126 + 875 1259 875 1259 740 1322 c 0,127,128 + 605 1385 605 1385 514 1385 c 0,129,130 + 441.992 1383.99 441.992 1383.99 404 1357 c 0,131,132 + 378.16 1338.64 378.16 1338.64 378.214 1299.01 c 0,133,134 + 378.239 1280.81 378.239 1280.81 384 1257 c 0,135,136 + 393 1218 393 1218 423.5 1164 c 0,137,138 + 454 1110 454 1110 434 1071 c 0,139,140 + 409 1021.01 409 1021.01 358 1023 c 0,141,142 + 408 1083 408 1083 370 1108.5 c 0,143,144 + 353.553 1119.54 353.553 1119.54 338.791 1119.8 c 0,145,146 + 322.286 1116.51 l 0,147,148 + 312.191 1112.14 312.191 1112.14 303 1102 c 0,149,150 + 273.134 1069.54 273.134 1069.54 273.197 1022.74 c 0,151,152 + 273.231 997.463 273.231 997.463 282 968 c 0,153,154 + 307 884 307 884 385 891 c 0,155,156 + 455 897 455 897 507.5 911 c 0,157,158 + 559.99 924.997 559.99 924.997 623 948 c 0,159,160 + 702 976 702 976 804 940 c 0,161,162 + 906 904 906 904 884 793 c 0,163,164 + 876 837 876 837 846 869.5 c 0,165,166 + 816 902 816 902 767 890 c 0,167,168 + 726.999 879.999 726.999 879.999 705.5 844.5 c 0,169,170 + 684 809 684 809 677 773 c 0,171,172 + 658 674 658 674 626 610.5 c 0,173,174 + 604.458 567.752 604.458 567.752 542.58 567.831 c 0,175,176 + 512.542 567.869 512.542 567.869 473 578 c 0,177,178 + 561 602 561 602 561 645 c 0,179,180 + 561 720 561 720 485.5 729 c 0,181,182 + 447.32 733.551 447.32 733.551 414.125 733.499 c 0,183,184 + 381.68 733.449 381.68 733.449 354 729 c 0,185,186 + 284 717 284 717 283 654 c 0,187,188 + 280 600 280 600 315 596.5 c 0,189,190 + 328.846 598.578 l 0,191,192 + 344.765 606.4 344.765 606.4 344.877 641.401 c 0,193,194 + 344.905 649.899 344.905 649.899 344 660 c 0,195,196 + 392 607 392 607 391 573 c 0,197,198 + 389.999 514.999 389.999 514.999 357.5 484.5 c 0,199,200 + 325 454.001 325 454.001 325 410 c 0,201,202 + 325 332 325 332 369 336.5 c 0,203,204 + 413 341 413 341 471 370 c 0,205,206 + 529.005 399.002 529.005 399.002 585.5 422.5 c 0,207,208 + 606.644 431.295 606.644 431.295 623.377 431.196 c 0,209,210 + 651.356 431.031 651.356 431.031 667 406 c 0,211,212 + 677.588 389.235 677.588 389.235 677.666 368.967 c 0,213,214 + 677.676 366.265 677.676 366.265 677.5 363.5 c 0,215,216 + 676 340 676 340 652 333 c 0,217,218 + 652.989 347.212 l 0,219,220 + 650.646 358.106 650.646 358.106 635.616 358.287 c 0,221,222 + 630.147 358.352 630.147 358.352 623 357 c 0,223,224 + 563 343 563 343 603 291 c 0,225,226 + 630 254 630 254 697.5 254 c 0,227,228 + 765 254 765 254 800 275 c 0,229,230 + 851 305 851 305 888 352 c 0,231,232 + 925 399 925 399 976 426 c 0,233,234 + 993.321 434.66 993.321 434.66 1010.43 434.679 c 0,235,236 + 1046.68 434.717 1046.68 434.717 1082 396 c 0,237,238 + 1134.01 339 1134.01 339 1076 291 c 0,239,240 + 1101.99 369 1101.99 369 1025 361 c 0,241,242 + 967.999 353.999 967.999 353.999 961.5 300.5 c 0,243,244 + 960.341 260.536 l 0,245,246 + 962.497 231.61 962.497 231.61 974 208 c 0,247,248 + 998 157 998 157 1055 116.5 c 0,249,250 + 1112 76 1112 76 1148 34 c 0,251,252 + 1185 -7.99286 1185 -7.99286 1197 -81.5 c 0,253,254 + 1199.64 -120.957 l 0,255,256 + 1197.74 -168.802 1197.74 -168.802 1169 -204 c 0,257,258 + 1173.43 -171.487 1173.43 -171.487 1173.38 -146.126 c 0,259,260 + 1173.32 -120.019 1173.32 -120.019 1168.5 -101.5 c 0,261,262 + 1159.01 -65.0068 1159.01 -65.0068 1111 -17 c 0,263,264 + 1028.99 64.0016 1028.99 64.0016 921.5 89 c 0,265,266 + 814.002 114 814.002 114 702 114 c 1,0,1 +EndSplineSet +KernsSLIF: 83 -130 0 0 115 -130 0 0 +EndChar +StartChar: F +Encoding: 70 70 8 +Width: 1352 +Flags: MW +HStem: 705 181<397 741> 1396 225<414 1092> +VStem: 110 217<38 1678> +Fore +642 839 m 1,0,1 + 644 729 644 729 741 705 c 0,2,3 + 769.434 702.509 l 0,4,5 + 803.088 704.294 803.088 704.294 834.5 729 c 0,6,7 + 879 763 l 0,8,9 + 873 739 873 739 845.5 693 c 0,10,11 + 818 647 818 647 773 627 c 0,12,13 + 719 607 719 607 685.5 614.5 c 0,14,15 + 652 622 652 622 613 634 c 0,16,17 + 562 653 562 653 505.5 704 c 0,18,19 + 466.31 739.375 466.31 739.375 424.956 739.628 c 0,20,21 + 408.667 739.728 408.667 739.728 392.041 734.379 c 0,22,23 + 390.023 733.73 390.023 733.73 388 733 c 0,24,25 + 340 708 340 708 329.5 679.5 c 0,26,27 + 319 651 319 651 312 621 c 0,28,29 + 306 585 306 585 292 478 c 0,30,31 + 278 371 278 371 370 376 c 0,32,33 + 424 427 424 427 347 473 c 0,34,35 + 419 467 419 467 446 407 c 0,36,37 + 446 353 446 353 433.5 330 c 0,38,39 + 420.995 306.989 420.995 306.989 401 265 c 0,40,41 + 375.999 232 375.999 232 362 187.5 c 0,42,-1 + 346 137 l 0,43,44 + 324 87.0005 324 87.0005 327 38 c 0,45,46 + 327 -20 327 -20 350.5 -86.5 c 0,47,48 + 374.001 -153.001 374.001 -153.001 428 -195 c 0,49,50 + 365.001 -195 365.001 -195 323.5 -122.5 c 0,51,52 + 282.002 -50.0044 282.002 -50.0044 266 -3 c 0,53,54 + 256 75 256 75 228.5 101.5 c 0,55,56 + 201.001 128.001 201.001 128.001 170 137 c 0,57,58 + 165.999 137 165.999 137 132.5 129.5 c 0,59,60 + 99.0005 122 99.0005 122 101 62 c 0,61,-1 + 115.5 33.5 l 0,62,63 + 130.001 5 130.001 5 178 -5 c 0,64,65 + 150.278 -14.0397 150.278 -14.0397 128.549 -13.9998 c 0,66,67 + 114.222 -13.9735 114.222 -13.9735 102.5 -10 c 0,68,69 + 72.9999 4.76837e-06 72.9999 4.76837e-06 61 3 c 0,70,71 + 32 18 32 18 20 48.5 c 0,72,73 + 8 78.9999 8 78.9999 8 97 c 0,74,75 + 15.0001 179.999 15.0001 179.999 77 241 c 0,76,77 + 93.9998 251.999 93.9998 251.999 105 282 c 0,78,79 + 115.999 312 115.999 312 123 336 c 0,80,81 + 128.001 354.007 128.001 354.007 140.5 444.5 c 0,82,83 + 149 506.041 149 506.041 148.946 535.905 c 0,84,85 + 148.92 549.96 148.92 549.96 147 557 c 0,86,87 + 146.947 572.694 l 0,88,89 + 142.652 589.782 142.652 589.782 119 603 c 0,90,91 + 78.9999 606 78.9999 606 86.5 552.5 c 0,92,93 + 93.9998 499.001 93.9998 499.001 108 486 c 0,94,95 + 69 486 69 486 44 527 c 0,96,97 + 20 554 20 554 23 583 c 0,98,99 + 26 612 26 612 35 640 c 0,100,101 + 53 689 53 689 86 731.5 c 0,102,103 + 119 774 119 774 143 820 c 0,104,105 + 145.997 843.974 145.997 843.974 152.5 889 c 0,106,107 + 152.986 918.716 l 0,108,109 + 149.654 945.423 149.654 945.423 132 967 c 0,110,111 + 129 973 129 973 83 1040.5 c 0,112,113 + 38 1106.99 38 1106.99 37 1108 c 0,114,115 + 30.0021 1120 30.0021 1120 17 1176 c 0,116,117 + 9.22428 1209.49 9.22428 1209.49 9.31933 1241.2 c 0,118,119 + 9.38319 1262.5 9.38319 1262.5 13 1283 c 0,120,121 + 13 1311.99 13 1311.99 42.5 1349 c 0,122,123 + 70.2188 1383.77 70.2188 1383.77 104.576 1384.1 c 0,124,125 + 106.774 1384.12 106.774 1384.12 109 1384 c 0,126,127 + 82 1339 82 1339 95.5 1289.5 c 0,128,129 + 109 1240 109 1240 161 1252 c 0,130,131 + 176.009 1255 176.009 1255 193.5 1268 c 0,132,133 + 211.001 1281.01 211.001 1281.01 227 1329 c 0,134,135 + 236 1369.99 236 1369.99 233 1411.5 c 0,136,137 + 230.001 1452.99 230.001 1452.99 224 1495 c 0,138,139 + 215 1547.99 215 1547.99 149 1537 c 0,140,141 + 113 1516.15 113 1516.15 113 1499 c 0,142,143 + 114.998 1483 114.998 1483 130 1444 c 0,144,145 + 68.9998 1495 68.9998 1495 66 1559 c 0,146,147 + 66.2889 1594.43 l 0,148,149 + 72.286 1642.5 72.286 1642.5 110 1678 c 0,150,151 + 159.023 1705.71 159.023 1705.71 195.936 1705.91 c 0,152,153 + 210.973 1705.99 210.973 1705.99 224 1701.5 c 0,154,155 + 269 1686.01 269 1686.01 328 1658 c 0,156,-1 + 414 1621 l 0,157,158 + 452.534 1610.88 452.534 1610.88 492.001 1610.98 c 0,159,160 + 534.461 1611.08 534.461 1611.08 578 1623 c 0,161,162 + 662 1645.99 662 1645.99 743 1662 c 0,163,164 + 815 1672.01 815 1672.01 877.5 1668 c 0,165,166 + 940.046 1663.99 940.046 1663.99 1010 1652 c 0,167,168 + 1102.99 1608.01 1102.99 1608.01 1115 1592.5 c 0,169,-1 + 1148 1551 l 0,170,171 + 1128.02 1558.99 1128.02 1558.99 1114 1568.5 c 0,172,173 + 1099.99 1578.01 1099.99 1578.01 1070 1583 c 0,174,175 + 991 1583 991 1583 986 1543.5 c 0,176,177 + 981 1504 981 1504 972 1504 c 0,178,179 + 987.996 1452.01 987.996 1452.01 1008 1434.5 c 0,180,181 + 1027.99 1417 1027.99 1417 1092 1396 c 0,182,183 + 1224 1402 1224 1402 1237.5 1459.5 c 0,184,185 + 1251.02 1517.06 1251.02 1517.06 1288 1628 c 0,186,-1 + 1272.5 1524 l 0,187,188 + 1257.99 1426.99 1257.99 1426.99 1240 1409 c 0,189,190 + 1215.99 1375.99 1215.99 1375.99 1174.5 1356 c 0,191,192 + 1132.97 1335.99 1132.97 1335.99 1112 1334 c 0,193,194 + 1075.74 1331.76 l 0,195,196 + 1068.75 1331.8 1068.75 1331.8 1060.5 1332 c 0,197,198 + 1017.99 1333.01 1017.99 1333.01 1006 1345 c 0,199,200 + 979 1355.01 979 1355.01 957.5 1369 c 0,201,-1 + 913 1398 l 0,202,203 + 764 1482 764 1482 702.5 1477.5 c 0,204,205 + 640.987 1473 640.987 1473 496 1409 c 0,206,207 + 460 1383.99 460 1383.99 473.5 1352 c 0,208,209 + 487.002 1320 487.002 1320 518 1320 c 0,210,211 + 543.105 1321.01 543.105 1321.01 572.5 1325 c 0,212,213 + 602.002 1329.01 602.002 1329.01 626 1383 c 0,214,215 + 623 1369.01 623 1369.01 623.5 1336.5 c 0,216,217 + 620.162 1310.39 l 0,218,219 + 615.024 1291.76 615.024 1291.76 602 1274 c 0,220,221 + 521.986 1225.99 521.986 1225.99 436.5 1203 c 0,222,223 + 351.002 1180.01 351.002 1180.01 333 1058 c 0,224,225 + 329.412 1045.28 329.412 1045.28 329.388 1030.91 c 0,226,227 + 329.34 1001.22 329.34 1001.22 344.5 964.5 c 0,228,229 + 367 910 367 910 397 886 c 0,230,231 + 406.248 868.824 406.248 868.824 439.281 868.668 c 0,232,233 + 456.251 868.588 456.251 868.588 479.5 873 c 0,234,235 + 548 886 548 886 557 934 c 0,236,237 + 560 994 560 994 526 1001.5 c 0,238,239 + 492 1009 492 1009 457 991 c 0,240,241 + 475.004 1027.01 475.004 1027.01 505 1044 c 0,242,243 + 600 1080 600 1080 630 996 c 0,244,245 + 635 961 635 961 637.5 918 c 0,246,-1 + 642 839 l 1,0,1 +EndSplineSet +KernsSLIF: 116 -286 0 0 84 -169 0 0 45 -208 0 0 46 -234 0 0 44 -273 0 0 65 -491 0 0 97 -470 0 0 +EndChar +StartChar: G +Encoding: 71 71 12 +Width: 1278 +Flags: W +Fore +586 -123 m 0,0,1 + 512 -115.001 512 -115.001 398.5 -55.5 c 0,2,3 + 285.001 3.99925 285.001 3.99925 251 54 c 0,4,5 + 140.158 218.532 140.158 218.532 139.923 377.813 c 0,6,7 + 139.886 402.469 139.886 402.469 142.5 427 c 0,8,9 + 162 610 162 610 93 791 c 0,10,11 + 70.9999 847 70.9999 847 40 906.5 c 0,12,13 + 8.99995 966 8.99995 966 12 1002 c 0,14,15 + 17 1065 17 1065 57 1086 c 0,16,17 + 97.0001 1107 97.0001 1107 130 1095 c 0,18,19 + 112.083 1092.92 l 0,20,21 + 89.0771 1084.96 89.0771 1084.96 75.5 1049 c 0,22,23 + 70.7155 1036.33 70.7155 1036.33 70.5795 1026.33 c 0,24,25 + 73.8997 1010.88 l 0,26,27 + 81.7288 995.636 81.7288 995.636 108 991 c 0,28,29 + 192 975 192 975 163.5 1093.5 c 0,30,31 + 135.001 1212 135.001 1212 134 1245 c 0,32,33 + 127.998 1329.02 127.998 1329.02 125 1379.5 c 0,34,35 + 122 1430.01 122 1430.01 161 1516 c 0,36,37 + 180.003 1560 180.003 1560 240 1560 c 0,38,39 + 300.012 1560 300.012 1560 330 1547 c 0,40,41 + 279 1544 279 1544 259.5 1515.5 c 0,42,43 + 250.674 1502.6 250.674 1502.6 250.759 1491.65 c 0,44,45 + 250.863 1478.4 250.863 1478.4 264 1468 c 0,46,47 + 279.59 1455.3 279.59 1455.3 296.138 1455.14 c 0,48,49 + 306.108 1455.04 306.108 1455.04 316.425 1459.5 c 0,50,51 + 348.303 1473.27 348.303 1473.27 383.5 1530.5 c 0,52,53 + 430.286 1606.57 430.286 1606.57 430.388 1650.76 c 0,54,55 + 430.429 1668.43 430.429 1668.43 423 1681 c 0,56,57 + 405 1709.99 405 1709.99 376 1709.5 c 0,58,59 + 347.026 1709.01 347.026 1709.01 320 1698 c 0,60,61 + 293.003 1686 293.003 1686 277.5 1657 c 0,62,63 + 262 1628.01 262 1628.01 244 1600 c 0,64,65 + 242.736 1626.39 l 0,66,67 + 245.946 1664.86 245.946 1664.86 274.5 1724.5 c 0,68,69 + 314 1807 314 1807 381 1810 c 0,70,71 + 436.151 1813.01 436.151 1813.01 515.5 1820 c 0,72,73 + 595.113 1827.01 595.113 1827.01 640 1833 c 0,74,75 + 754 1848 754 1848 911 1809 c 0,76,77 + 1067.95 1770.01 1067.95 1770.01 1167 1743 c 0,78,79 + 1216.13 1728.55 1216.13 1728.55 1216.08 1665.83 c 0,80,81 + 1216.07 1663.45 1216.07 1663.45 1216 1661 c 0,82,83 + 1214.01 1594.01 1214.01 1594.01 1170 1566 c 0,84,85 + 1173.89 1576.83 1173.89 1576.83 1173.84 1587.2 c 0,86,87 + 1173.72 1614.17 1173.72 1614.17 1147 1638 c 0,88,89 + 1131.29 1652.01 1131.29 1652.01 1115.75 1652.32 c 0,90,91 + 1099.92 1649.06 l 0,92,93 + 1086.9 1643.41 1086.9 1643.41 1074 1628 c 0,94,95 + 1061.39 1613.19 1061.39 1613.19 1061.26 1591.32 c 0,96,97 + 1061.16 1575.07 1061.16 1575.07 1067.94 1554.92 c 0,98,99 + 1068.68 1552.73 1068.68 1552.73 1069.5 1550.5 c 0,100,-1 + 1100 1467 l 0,101,102 + 1130.03 1374.92 1130.03 1374.92 1152 1321 c 0,103,104 + 1160.8 1299.4 1160.8 1299.4 1160.8 1271.08 c 0,105,106 + 1160.8 1229.03 1160.8 1229.03 1141 1171 c 0,107,108 + 1119 1108.01 1119 1108.01 1067.5 1054.5 c 0,109,110 + 1016.01 1001 1016.01 1001 901 976 c 0,111,112 + 945.016 1009.01 945.016 1009.01 1008.5 1039.5 c 0,113,114 + 1068.86 1068.49 1068.86 1068.49 1069.13 1152.16 c 0,115,116 + 1069.15 1156.51 1069.15 1156.51 1069 1161 c 0,117,118 + 1066 1201 1066 1201 1016.5 1247.5 c 0,119,120 + 967 1294 967 1294 918 1273 c 0,121,122 + 867.288 1251.94 867.288 1251.94 866.93 1207.55 c 0,123,124 + 867 1203.5 l 0,125,126 + 868.999 1156 868.999 1156 887 1111 c 0,127,128 + 830 1150 830 1150 838.5 1231 c 0,129,130 + 847 1311.99 847 1311.99 876 1343 c 0,131,132 + 889.997 1358 889.997 1358 904 1387 c 0,133,134 + 914.347 1408.43 914.347 1408.43 914.315 1423.31 c 0,135,136 + 914.304 1428.57 914.304 1428.57 913 1433 c 0,137,138 + 901.003 1475.99 901.003 1475.99 839 1511.5 c 0,139,140 + 809.887 1528.17 809.887 1528.17 782.758 1528.19 c 0,141,142 + 752.113 1528.22 752.113 1528.22 724 1507 c 0,143,144 + 697 1486 697 1486 708 1436.5 c 0,145,146 + 718.999 1387 718.999 1387 720 1355 c 0,147,148 + 721 1269.01 721 1269.01 625 1256 c 0,149,150 + 604.735 1257.19 l 0,151,152 + 590.855 1260.5 590.855 1260.5 576 1270.5 c 0,153,154 + 549.997 1288.01 549.997 1288.01 542 1325 c 0,155,156 + 563.197 1315.63 563.197 1315.63 580.749 1315.5 c 0,157,158 + 593.765 1315.4 593.765 1315.4 604.776 1320.38 c 0,159,160 + 609.038 1322.31 609.038 1322.31 613 1325 c 0,161,162 + 641 1344.01 641 1344.01 623 1391 c 0,163,164 + 614 1412 614 1412 563.5 1424 c 0,165,166 + 540.067 1429.57 540.067 1429.57 521.906 1429.54 c 0,167,168 + 500.936 1429.5 500.936 1429.5 487 1422 c 0,169,170 + 421 1386 421 1386 401 1249 c 0,171,172 + 394.695 1205.81 394.695 1205.81 394.751 1169.67 c 0,173,174 + 394.872 1091.19 394.872 1091.19 425 1046 c 0,175,176 + 484.994 954.01 484.994 954.01 527 883 c 0,177,178 + 548.851 846.061 548.851 846.061 548.778 807.498 c 0,179,180 + 548.71 771.939 548.71 771.939 530 735 c 0,181,182 + 518 711 518 711 463 699 c 0,183,184 + 408 687 408 687 387 707 c 0,185,186 + 440 716 440 716 450 752 c 0,187,188 + 465 819 465 819 386 842 c 0,189,190 + 358.249 844.514 l 0,191,192 + 341.329 844.06 341.329 844.06 319 840 c 0,193,194 + 275 832 275 832 254 795 c 0,195,196 + 241.999 773.999 241.999 773.999 241.5 703 c 0,197,198 + 245.037 633.868 l 0,199,200 + 249.259 594.007 249.259 594.007 258.5 551.5 c 0,201,202 + 276 471 276 471 315 401 c 0,203,204 + 354 331 354 331 422 313 c 0,205,206 + 493 294 493 294 551.5 330 c 0,207,208 + 610 366 610 366 663 385 c 0,209,210 + 725.305 407.252 725.305 407.252 765.019 407.222 c 0,211,212 + 796.695 407.198 796.695 407.198 814 393 c 0,213,214 + 835.408 374.111 835.408 374.111 835.407 352.249 c 0,215,216 + 835.407 339.389 835.407 339.389 828 325.5 c 0,217,218 + 808 288 808 288 772 291 c 0,219,220 + 791.412 305.236 791.412 305.236 791.564 318.842 c 0,221,222 + 791.647 326.265 791.647 326.265 786 333.5 c 0,223,224 + 772.461 350.846 772.461 350.846 760 351 c 0,225,226 + 709 337 709 337 715.5 305.5 c 0,227,228 + 722 274 722 274 746 262 c 0,229,230 + 761.411 253.594 761.411 253.594 778.11 253.469 c 0,231,232 + 791.358 253.369 791.358 253.369 805.415 258.481 c 0,233,234 + 824.232 265.322 824.232 265.322 844.5 281.5 c 0,235,236 + 899 325 899 325 918 361 c 0,237,238 + 930 383 930 383 921 437 c 0,239,240 + 912 491 912 491 885 502 c 0,241,242 + 809.779 529.799 809.779 529.799 747.592 529.855 c 0,243,244 + 733.722 529.868 733.722 529.868 720.5 528.5 c 0,245,246 + 648 521 648 521 548 528 c 0,247,248 + 409 537 409 537 353 577 c 0,249,250 + 297 617 297 617 297 668 c 0,251,252 + 297 691 297 691 315.5 722 c 0,253,254 + 334 753 334 753 392 761 c 0,255,256 + 341 742 341 742 334 692.5 c 0,257,258 + 334.029 667.297 l 0,259,260 + 339.17 637.192 339.17 637.192 371 622 c 0,261,262 + 467 573 467 573 574 628 c 0,263,264 + 681 683 681 683 717 734 c 0,265,266 + 757 791 757 791 829 799.5 c 0,267,268 + 880.389 802.174 l 0,269,270 + 911.309 800.99 911.309 800.99 926 791 c 0,271,272 + 944 778 944 778 955 748 c 0,273,274 + 966 718 966 718 942 693 c 0,275,276 + 943 744 943 744 896.5 738.5 c 0,277,278 + 850 733 850 733 849 715 c 0,279,280 + 846 677 846 677 881 642.5 c 0,281,282 + 916 608 916 608 985 612 c 0,283,284 + 1048 615 1048 615 1120 580 c 0,285,286 + 1192 545 1192 545 1198 506 c 0,287,288 + 1198.65 470.761 l 0,289,290 + 1196.72 451.59 1196.72 451.59 1189.5 435 c 0,291,292 + 1176 404.001 1176 404.001 1138 403 c 0,293,294 + 1151.85 417.478 1151.85 417.478 1152.03 429.782 c 0,295,296 + 1152.12 436.49 1152.12 436.49 1147.5 443.5 c 0,297,298 + 1139.48 454.732 1139.48 454.732 1127.95 455.048 c 0,299,300 + 1114 452 l 0,301,302 + 1085.01 439 1085.01 439 1096 405.5 c 0,303,304 + 1107.01 371.953 1107.01 371.953 1113 345 c 0,305,306 + 1134 242.792 1134 242.792 1133.93 166.08 c 0,307,308 + 1133.9 133.199 1133.9 133.199 1130 105 c 0,309,310 + 1116.99 10.9955 1116.99 10.9955 1090 -10 c 0,311,312 + 1051 -40.0026 1051 -40.0026 994.5 -57 c 0,313,314 + 938 -73.9999 938 -73.9999 869 -34 c 0,315,316 + 845.649 -21.9218 845.649 -21.9218 845.639 20.6278 c 0,317,318 + 845.636 30.9221 845.636 30.9221 847 43 c 0,319,320 + 852 15 852 15 888 9 c 0,321,322 + 924 3 924 3 940 59 c 0,323,324 + 949 90.9999 949 90.9999 903.5 101 c 0,325,326 + 858 111.001 858 111.001 798.5 108.5 c 0,327,328 + 739 105.999 739 105.999 685 95.5 c 0,329,330 + 631 85 631 85 624 78 c 0,331,332 + 597 47 597 47 595.5 32 c 0,333,334 + 594 17 594 17 608 -31 c 0,335,336 + 623 -82 623 -82 686 -82 c 0,337,338 + 749 -82 749 -82 791 -47 c 0,339,340 + 761 -124 761 -124 677.5 -123.5 c 0,341,342 + 594 -123.001 594 -123.001 586 -123 c 0,0,1 +EndSplineSet +EndChar +StartChar: H +Encoding: 72 72 10 +Width: 1352 +Flags: HMW +HStem: 699 320<465.5 883.5> +VStem: 115.5 242.5<36.5 1488> 928 212<-51 1523> +Fore +105.5 816.5 m 132,-1,0 + 36 880 36 880 19 967 c 0,1,2 + 14.9504 986.091 14.9504 986.091 15.0006 1004.26 c 0,3,4 + 15.124 1048.91 15.124 1048.91 40 1088 c 0,5,6 + 73.0086 1139.88 73.0086 1139.88 122.035 1140.15 c 0,7,8 + 124.99 1140.17 124.99 1140.17 128 1140 c 0,9,10 + 170 1137 170 1137 170 1095 c 0,11,12 + 156.052 1106.77 156.052 1106.77 143.148 1106.76 c 0,13,14 + 126.45 1106.74 126.45 1106.74 111.5 1087 c 0,15,16 + 97.7055 1068.78 97.7055 1068.78 97.5949 1049.75 c 0,17,18 + 97.496 1032.71 97.496 1032.71 109 1014 c 0,19,20 + 115.998 1001 115.998 1001 160.5 996.5 c 0,21,22 + 178.23 997.922 l 0,23,24 + 206.536 1006.49 206.536 1006.49 212 1058 c 0,25,26 + 222.998 1168.99 222.998 1168.99 239 1270.5 c 0,27,28 + 244.978 1308.42 244.978 1308.42 244.954 1336.5 c 0,29,30 + 244.913 1383.58 244.913 1383.58 228 1403 c 0,31,32 + 220.944 1410.45 220.944 1410.45 209.816 1410.6 c 0,33,34 + 189.949 1406.38 l 0,35,36 + 178.932 1402.1 178.932 1402.1 165.5 1393.5 c 0,37,38 + 142.118 1378.53 142.118 1378.53 141.789 1354.85 c 0,39,40 + 145.468 1333.76 l 0,41,42 + 149.976 1320.42 149.976 1320.42 160 1305 c 0,43,44 + 110.509 1338.17 110.509 1338.17 110.36 1375.64 c 0,45,46 + 110.26 1400.77 110.26 1400.77 132.369 1427.84 c 0,47,48 + 139.897 1437.06 139.897 1437.06 150 1446.5 c 0,49,50 + 233.996 1524.99 233.996 1524.99 267 1597 c 0,51,52 + 299.996 1670 299.996 1670 353.5 1734.5 c 0,53,54 + 407 1799 407 1799 500 1793 c 0,55,56 + 537.011 1779.99 537.011 1779.99 559.5 1762 c 0,57,58 + 582 1744 582 1744 597 1693 c 0,59,60 + 593.998 1713.01 593.998 1713.01 517.5 1749.5 c 0,61,62 + 500.595 1757.56 500.595 1757.56 484.643 1757.69 c 0,63,64 + 472.549 1757.79 472.549 1757.79 461.003 1753.33 c 0,65,66 + 418.855 1737.05 418.855 1737.05 384 1660 c 0,67,68 + 356.523 1601.82 356.523 1601.82 356.476 1525.34 c 0,69,70 + 356.465 1507.19 356.465 1507.19 358 1488 c 0,71,72 + 364 1398 364 1398 429 1310.5 c 0,73,74 + 477.324 1245.45 477.324 1245.45 477.562 1182.33 c 0,75,76 + 477.644 1160.55 477.644 1160.55 472 1139 c 0,77,78 + 464.998 1111.99 464.998 1111.99 417.5 1102.5 c 0,79,80 + 377.156 1097.63 l 0,81,82 + 363.646 1097.77 363.646 1097.77 358 1102 c 0,83,84 + 394 1106.99 394 1106.99 407 1129 c 0,85,86 + 420 1151 420 1151 420 1152 c 0,87,88 + 416.971 1176.71 l 0,89,90 + 409.979 1201.86 409.979 1201.86 387 1224.5 c 0,91,92 + 371.888 1239.39 371.888 1239.39 359.543 1239.36 c 0,93,94 + 344.11 1239.33 344.11 1239.33 333 1216 c 0,95,96 + 320 1189 320 1189 317 1122 c 0,97,98 + 314 1056 314 1056 314 1055 c 0,99,100 + 322.999 994.003 322.999 994.003 347.5 955.5 c 0,101,102 + 371.999 917.001 371.999 917.001 375 916 c 0,103,104 + 399 895 399 895 428 897.5 c 0,105,106 + 457 900 457 900 472 906 c 0,107,108 + 580 955.999 580 955.999 618 1003 c 0,109,110 + 649.772 1042.29 649.772 1042.29 713.695 1042.45 c 0,111,112 + 726.23 1042.48 726.23 1042.48 740 1041 c 0,113,114 + 769.004 1029 769.004 1029 783.5 1008.5 c 0,115,116 + 798 988 798 988 786 934 c 0,117,118 + 772 898 772 898 735 893 c 0,119,120 + 753 911 753 911 744.5 933.5 c 0,121,122 + 736 956 736 956 712 938 c 0,123,124 + 682.31 915.493 682.31 915.493 681.858 898.26 c 0,125,126 + 685.012 887.021 l 0,127,128 + 692.164 875.551 692.164 875.551 715.5 867 c 0,129,130 + 781 843 781 843 823 846 c 0,131,132 + 838 846 838 846 893 863 c 0,133,134 + 948 880 948 880 923 962 c 0,135,136 + 912.999 995.001 912.999 995.001 883.5 1019 c 0,137,138 + 854 1043 854 1043 851 1083 c 0,139,140 + 851.18 1119.3 l 0,141,142 + 855.8 1158.5 855.8 1158.5 881 1183 c 0,143,144 + 899.015 1200.01 899.015 1200.01 940.5 1211 c 0,145,146 + 964.418 1213.55 l 0,147,148 + 991.024 1211.78 991.024 1211.78 1012 1188 c 0,149,150 + 982.048 1185.47 l 0,151,152 + 938.654 1175.69 938.654 1175.69 931 1129 c 0,153,154 + 921 1067.99 921 1067.99 999 1051 c 0,155,156 + 1015.67 1050.34 l 0,157,158 + 1049.51 1057.23 1049.51 1057.23 1060.5 1137 c 0,159,160 + 1071.56 1217.31 1071.56 1217.31 1071.55 1255.32 c 0,161,162 + 1071.54 1263.69 1071.54 1263.69 1071 1270 c 0,163,164 + 1065 1317.02 1065 1317.02 1002.5 1406 c 0,165,166 + 940 1494.99 940 1494.99 928 1523 c 0,167,168 + 913.999 1551.01 913.999 1551.01 901.5 1616 c 0,169,170 + 899.156 1647.62 l 0,171,172 + 901.5 1693.75 901.5 1693.75 939 1732 c 0,173,174 + 965.005 1758 965.005 1758 1000.5 1759.5 c 0,175,176 + 1054.31 1757.68 l 0,177,178 + 1064.53 1756.61 1064.53 1756.61 1075 1755 c 0,179,180 + 1138 1744.99 1138 1744.99 1193 1697 c 0,181,182 + 1183.01 1697 1183.01 1697 1154 1711 c 0,183,184 + 1124.99 1725 1124.99 1725 1102 1725 c 0,185,186 + 1042.01 1725 1042.01 1725 1002 1697.5 c 0,187,188 + 972.596 1677.29 972.596 1677.29 972.372 1645.99 c 0,189,190 + 972.292 1634.72 972.292 1634.72 976 1622 c 0,191,192 + 1011 1494.87 1011 1494.87 1077.42 1494.19 c 0,193,194 + 1083.09 1494.13 1083.09 1494.13 1089 1495 c 0,195,196 + 1164 1505.99 1164 1505.99 1170 1527 c 0,197,198 + 1175.83 1549.08 1175.83 1549.08 1175.85 1567.34 c 0,199,200 + 1175.87 1592.92 1175.87 1592.92 1164.5 1611 c 0,201,202 + 1145.03 1641.96 1145.03 1641.96 1119 1672 c 0,203,204 + 1155 1672 1155 1672 1198.5 1617.5 c 0,205,206 + 1242 1563.01 1242 1563.01 1242 1530 c 0,207,208 + 1242 1458.02 1242 1458.02 1226.5 1372 c 0,209,210 + 1221.92 1346.59 1221.92 1346.59 1222.01 1316.99 c 0,211,212 + 1222.23 1246.41 1222.23 1246.41 1249 1152 c 0,213,214 + 1263.99 1099.03 1263.99 1099.03 1276 1049.5 c 0,215,216 + 1288 1000 1288 1000 1288 951 c 0,217,218 + 1288 925.992 1288 925.992 1263 891 c 0,219,220 + 1237.99 856 1237.99 856 1181 853 c 0,221,222 + 1181 854 1181 854 1215.5 880.5 c 0,223,224 + 1250 907 1250 907 1235 955 c 0,225,226 + 1223 970 1223 970 1200.5 959.5 c 0,227,228 + 1178.01 949.003 1178.01 949.003 1165 925 c 0,229,230 + 1153 903 1153 903 1142.5 844.5 c 0,231,232 + 1134.87 801.972 1134.87 801.972 1134.9 772.936 c 0,233,234 + 1134.91 762.016 1134.91 762.016 1136 753 c 0,235,236 + 1142 687.014 1142 687.014 1166.5 635 c 0,237,238 + 1191 582.981 1191 582.981 1200 539 c 0,239,240 + 1216.99 446 1216.99 446 1204.5 409 c 0,241,242 + 1192.01 372.012 1192.01 372.012 1177 353 c 0,243,244 + 1165 346.001 1165 346.001 1137.5 341 c 0,245,246 + 1115.12 340.89 l 0,247,248 + 1098.65 343.703 1098.65 343.703 1082 355 c 0,249,250 + 1129 359.001 1129 359.001 1142 378 c 0,251,-1 + 1149.5 410.5 l 0,252,253 + 1149.4 425.528 l 0,254,255 + 1143.56 444.551 1143.56 444.551 1105 449 c 0,256,257 + 1090.45 446.644 l 0,258,259 + 1076.15 440.772 1076.15 440.772 1061 421 c 0,260,261 + 1042.72 397.15 1042.72 397.15 1042.76 337.294 c 0,262,263 + 1042.77 321.845 1042.77 321.845 1044 304 c 0,264,265 + 1051.99 195 1051.99 195 1084.5 123 c 0,266,267 + 1117.01 51 1117.01 51 1140 -51 c 0,268,269 + 1152.45 -109.993 1152.45 -109.993 1152.38 -156.242 c 0,270,271 + 1152.21 -266.008 1152.21 -266.008 1081.5 -304 c 0,272,273 + 982.005 -358 982.005 -358 981 -358 c 0,274,275 + 948 -362 948 -362 901.5 -360.5 c 0,276,277 + 855 -359 855 -359 819 -330 c 0,278,279 + 852 -343 852 -343 896.5 -345 c 0,280,281 + 935.359 -343.042 l 0,282,283 + 957.07 -339.654 957.07 -339.654 976 -331 c 0,284,285 + 1035 -300.996 1035 -300.996 1071 -255.5 c 0,286,287 + 1086.62 -235.762 1086.62 -235.762 1086.8 -212.544 c 0,288,289 + 1086.9 -200.455 1086.9 -200.455 1082.82 -187.422 c 0,290,291 + 1076.66 -167.782 1076.66 -167.782 1061 -146 c 0,292,293 + 992 -51.0001 992 -51.0001 903 -31 c 0,294,295 + 814 -11 814 -11 793 6 c 0,296,297 + 732.585 56.9527 732.585 56.9527 732.57 111.614 c 0,298,299 + 732.564 132.048 732.564 132.048 741 153 c 0,300,301 + 770.744 226.878 770.744 226.878 814 227 c 0,302,303 + 846 224 846 224 876 185 c 0,304,305 + 857.344 193.955 857.344 193.955 843.281 194.139 c 0,306,307 + 828.019 191.183 l 0,308,309 + 815.839 185.689 815.839 185.689 809 170 c 0,310,311 + 785 113 785 113 838 98.5 c 0,312,313 + 891 83.9999 891 83.9999 891 106 c 0,314,315 + 903.199 124.977 903.199 124.977 903.227 166.688 c 0,316,317 + 903.239 186.524 903.239 186.524 900.5 211.5 c 0,318,319 + 891.999 289.006 891.999 289.006 886 323 c 0,320,321 + 831 412 831 412 787.5 416.5 c 0,322,323 + 744 421 744 421 716 452 c 0,324,325 + 672 498.001 672 498.001 669 527.5 c 0,326,327 + 666 557 666 557 678 593 c 0,328,329 + 700 659 700 659 766 632 c 0,330,331 + 746 620 746 620 739 595.5 c 0,332,333 + 732 571 732 571 765 574 c 0,334,335 + 798 577 798 577 825 590.5 c 0,336,337 + 852 604 852 604 844 646 c 0,338,339 + 825 745 825 745 684 751.5 c 0,340,341 + 543 758 543 758 498 734 c 0,342,343 + 481.002 713.002 481.002 713.002 465.5 699 c 0,344,345 + 459.145 693.26 459.145 693.26 459.094 675.417 c 0,346,347 + 459.02 649.739 459.02 649.739 472 599 c 0,348,349 + 478 574 478 574 486.5 528.5 c 0,350,351 + 487.651 503.031 l 0,352,353 + 484.37 476.319 484.37 476.319 460 461 c 0,354,355 + 434.294 445.021 434.294 445.021 398.454 444.97 c 0,356,357 + 382.705 444.947 382.705 444.947 365 448 c 0,358,359 + 401 454 401 454 423 491 c 0,360,361 + 445 528 445 528 391 537 c 0,362,363 + 375.319 535.564 l 0,364,365 + 361.023 530.93 361.023 530.93 348 514 c 0,366,367 + 328 488 328 488 328 458 c 0,368,369 + 330.048 395.957 l 0,370,371 + 337.072 324.887 337.072 324.887 366 269.5 c 0,372,373 + 407 191.001 407 191.001 398 127 c 0,374,375 + 391 82 391 82 375.5 71 c 0,376,377 + 360.001 60.0004 360.001 60.0004 328 53 c 0,378,379 + 336 77 336 77 343.5 92.5 c 0,380,381 + 351 107.999 351 107.999 330 127 c 0,382,383 + 321.857 133.786 321.857 133.786 311.873 133.895 c 0,384,385 + 307.143 133.946 307.143 133.946 302 132.5 c 0,386,387 + 286 128 286 128 277 125 c 0,388,389 + 231.23 107.948 231.23 107.948 230.966 58.6818 c 0,390,391 + 230.936 53.0513 230.936 53.0513 231.5 47 c 0,392,393 + 236.927 -11.2137 236.927 -11.2137 258 -28 c 0,394,395 + 281 -45 281 -45 318.5 -59.5 c 0,396,397 + 356 -74.0001 356 -74.0001 443 -45 c 0,398,-1 + 492.5 -13.5 l 0,399,400 + 542 18 542 18 587 123 c 0,401,402 + 552.999 9.99854 552.999 9.99854 486 -60 c 0,403,404 + 463 -82.9999 463 -82.9999 363 -111.5 c 0,405,406 + 333.213 -119.989 333.213 -119.989 304.491 -119.916 c 0,407,408 + 236.788 -119.745 236.788 -119.745 175 -72 c 0,409,410 + 117 -27.0004 117 -27.0004 115.5 36.5 c 0,411,412 + 114 99.9999 114 99.9999 117 118 c 0,413,414 + 121.001 160.001 121.001 160.001 167.5 263 c 0,415,416 + 214 366.001 214 366.001 214 376 c 0,417,418 + 214 397.991 214 397.991 220.5 508.5 c 0,419,420 + 221.507 585.118 l 0,421,422 + 219.117 635.948 219.117 635.948 207 662 c 0,423,424 + 175.001 752.999 175.001 752.999 105.5 816.5 c 132,-1,0 +EndSplineSet +KernsSLIF: 65 -91 0 0 +EndChar +StartChar: I +Encoding: 73 73 51 +Width: 582 +Flags: HMW +VStem: 256 244.5<240.5 1423> +Fore +232 519 m 0,0,1 + 224.001 624.998 224.001 624.998 126 719 c 0,2,3 + 45.602 796.117 45.602 796.117 45.2953 885.347 c 0,4,5 + 45.2282 904.883 45.2282 904.883 49 925 c 0,6,7 + 63.999 1002.99 63.999 1002.99 117.5 1022 c 0,8,9 + 128.072 1025.76 128.072 1025.76 137.726 1025.68 c 0,10,11 + 176.928 1025.39 176.928 1025.39 201 962 c 0,12,-1 + 190 978 l 0,13,14 + 171.382 993.709 171.382 993.709 155.81 994.016 c 0,15,16 + 141.649 990.804 l 0,17,18 + 138.235 989.102 138.235 989.102 135 986.5 c 0,19,20 + 112.001 968 112.001 968 108 936.5 c 0,21,22 + 108.64 911.78 l 0,23,24 + 112 893.601 112 893.601 124 876.5 c 0,25,26 + 143.999 848 143.999 848 199 857 c 0,27,28 + 226 861 226 861 232 911 c 0,29,30 + 235.1 972.442 l 0,31,32 + 234.847 996.834 234.847 996.834 232.5 1023.5 c 0,33,34 + 227 1086 227 1086 213.5 1143 c 0,35,36 + 200 1200 200 1200 189 1218 c 0,37,38 + 124.986 1314.02 124.986 1314.02 83.5 1358 c 0,39,40 + 49.5783 1393.96 49.5783 1393.96 49.397 1447.97 c 0,41,42 + 49.3565 1460.04 49.3565 1460.04 51 1473 c 0,43,44 + 69.0007 1610 69.0007 1610 219 1646 c 0,45,46 + 145.001 1608.01 145.001 1608.01 126 1542.5 c 0,47,48 + 114.33 1502.27 114.33 1502.27 114.355 1474.3 c 0,49,50 + 114.371 1456.73 114.371 1456.73 119 1444 c 0,51,52 + 138.175 1413.96 138.175 1413.96 172.467 1413.74 c 0,53,54 + 187.822 1413.65 187.822 1413.65 206.21 1419.53 c 0,55,56 + 211.002 1421.06 211.002 1421.06 216 1423 c 0,57,58 + 282.992 1448.99 282.992 1448.99 296 1464 c 0,59,60 + 403 1587 403 1587 365 1725 c 0,61,62 + 327 1863 327 1863 152 1908 c 0,63,64 + 259 1908 259 1908 351 1815 c 0,65,66 + 443.001 1722 443.001 1722 455 1619 c 0,67,68 + 461 1534.99 461 1534.99 483.5 1458 c 0,69,70 + 505.993 1381.03 505.993 1381.03 524 1292 c 0,71,72 + 532 1247 532 1247 544 1211 c 0,73,74 + 554.285 1180.14 554.285 1180.14 554.286 1161.04 c 0,75,76 + 554.286 1157.86 554.286 1157.86 554 1155 c 0,77,78 + 546.001 1064 546.001 1064 450 1064 c 0,79,80 + 492.002 1097 492.002 1097 501.5 1152 c 0,81,82 + 501.656 1171.25 l 0,83,84 + 495.027 1204.71 495.027 1204.71 434.075 1205.07 c 0,85,86 + 430.622 1205.09 430.622 1205.09 427 1205 c 0,87,88 + 392 1206.99 392 1206.99 380.5 1160 c 0,89,90 + 369 1113.01 369 1113.01 369 1052.5 c 0,91,92 + 369 992.005 369 992.005 375.5 935.5 c 0,93,94 + 381.993 879.057 381.993 879.057 384 864 c 0,95,96 + 390 795 390 795 443 801 c 0,97,98 + 478.903 805.065 478.903 805.065 479.013 846.3 c 0,99,100 + 479.065 865.936 479.065 865.936 471 894 c 0,101,102 + 463 918 463 918 426 958 c 0,103,104 + 441 949 441 949 456 938.5 c 0,105,106 + 471 928 471 928 496 897 c 0,107,108 + 528.83 854.008 528.83 854.008 528.971 808.268 c 0,109,110 + 529.011 795.491 529.011 795.491 526.5 782.5 c 0,111,112 + 515 723 515 723 485 660 c 0,113,-1 + 425 532.5 l 0,114,115 + 395 468 395 468 400 404 c 0,116,117 + 407.001 308.999 407.001 308.999 460.5 240.5 c 0,118,119 + 514 172 514 172 517 82 c 0,120,121 + 519 10 519 10 455.5 -13 c 0,122,123 + 392 -36 392 -36 331 -34 c 0,124,125 + 409 -20 409 -20 407 52.5 c 0,126,127 + 405 124.999 405 124.999 321 131 c 0,128,129 + 291.816 129.369 l 0,130,131 + 231.611 117.594 231.611 117.594 231.312 32.2265 c 0,132,133 + 231.26 17.4636 231.26 17.4636 233 0.5 c 0,134,135 + 246.999 -135.998 246.999 -135.998 280 -188 c 0,136,137 + 328 -263 328 -263 391 -299.5 c 0,138,139 + 454 -336 454 -336 487 -366 c 0,140,141 + 427.995 -346.998 427.995 -346.998 394 -329.5 c 0,142,143 + 360.005 -312.002 360.005 -312.002 314 -283 c 0,144,145 + 314 -282 314 -282 276.5 -245 c 0,146,147 + 238.998 -207.997 238.998 -207.997 219 -168 c 0,148,149 + 174.999 -79.9963 174.999 -79.9963 161 11 c 0,150,151 + 157.704 57.9995 l 0,152,153 + 158.567 121.5 158.567 121.5 188.158 185 c 0,154,155 + 190.022 189 190.022 189 192 193 c 0,156,157 + 228 266.001 228 266.001 232.5 352.5 c 0,158,159 + 234.331 462.476 l 0,160,161 + 233.742 491.132 233.742 491.132 232 519 c 0,0,1 +EndSplineSet +EndChar +StartChar: J +Encoding: 74 74 63 +Width: 1235 +Flags: MW +HStem: -181.5 278.5<390.5 1080> 1374 216<210.5 730> +VStem: 262 128.5<-181.5 574> 753 279.5<121 1629> +Fore +266 -186 m 0,0,1 + 224.001 -180 224.001 -180 177.5 -136 c 0,2,3 + 131 -92.0005 131 -92.0005 119 -17 c 0,4,5 + 153.477 -76.1043 153.477 -76.1043 181 -84 c 0,6,7 + 209.646 -85.7528 l 0,8,9 + 237.766 -83.402 237.766 -83.402 252.5 -62.5 c 0,10,11 + 274 -32 274 -32 274 11 c 0,12,13 + 274 74.0005 274 74.0005 219 127 c 0,14,15 + 194.8 150.32 194.8 150.32 182.216 150.408 c 0,16,17 + 168.769 150.502 168.769 150.502 168.586 124.068 c 0,18,19 + 168.551 119.018 168.551 119.018 169 113 c 0,20,21 + 171.948 59.931 171.948 59.931 224 55 c 0,22,23 + 206.644 34.5454 206.644 34.5454 187.56 34.4533 c 0,24,25 + 176.342 34.3991 176.342 34.3991 163.5 42 c 0,26,27 + 131.001 61.999 131.001 61.999 121 82 c 0,28,29 + 86.9999 146.001 86.9999 146.001 115 239 c 0,30,31 + 140.998 329.994 140.998 329.994 180.5 414 c 0,32,33 + 219.995 497.991 219.995 497.991 262 574 c 0,34,35 + 319 680 319 680 419 771.5 c 0,36,37 + 519 863 519 863 639 891 c 0,38,39 + 497 834 497 834 403.5 649 c 0,40,41 + 310 464 310 464 340 317 c 0,42,43 + 350 268 350 268 386.5 238 c 0,44,45 + 402.291 225.021 402.291 225.021 417.613 224.77 c 0,46,47 + 434.195 228.284 l 0,48,49 + 445.735 233.41 445.735 233.41 457 246 c 0,50,51 + 481 273 481 273 479.5 310.5 c 0,52,53 + 478 348 478 348 469 369 c 0,54,55 + 455 396 455 396 417 413 c 0,56,57 + 468 425 468 425 503.5 388.5 c 0,58,59 + 538.999 352.002 538.999 352.002 546 319 c 0,60,61 + 550 297 550 297 546 262 c 0,62,63 + 542 227.005 542 227.005 542 215 c 0,64,65 + 541.282 157.714 l 0,66,67 + 543.818 120.228 543.818 120.228 556 105 c 0,68,69 + 576 79.9999 576 79.9999 613 70 c 0,70,71 + 646 60 646 60 689 75.5 c 0,72,73 + 732 90.9999 732 90.9999 753 121 c 0,74,75 + 789 170.999 789 170.999 805.5 237.5 c 0,76,77 + 822 304 822 304 831 368 c 0,78,79 + 833.059 429.818 l 0,80,81 + 833.031 430.907 833.031 430.907 833 432 c 0,82,83 + 832 467 832 467 796 467 c 0,84,85 + 762 467 762 467 761 439.5 c 0,86,87 + 760 412 760 412 769 394 c 0,88,89 + 748 394 748 394 725.5 408.5 c 0,90,91 + 703 423 703 423 702 480 c 0,92,93 + 701 516 701 516 723.5 545 c 0,94,95 + 746 574 746 574 761 607 c 0,96,97 + 801 694 801 694 807.5 724 c 0,98,99 + 811.571 742.789 811.571 742.789 811.523 776.872 c 0,100,101 + 811.495 797.214 811.495 797.214 810 823 c 0,102,103 + 804 898 804 898 711 1003 c 0,104,105 + 664.04 1056.02 664.04 1056.02 663.74 1107 c 0,106,107 + 663.641 1123.83 663.641 1123.83 668.627 1140.44 c 0,108,109 + 678.449 1173.15 678.449 1173.15 708 1205 c 0,110,111 + 723 1221.99 723 1221.99 764.5 1218.5 c 0,112,113 + 806 1215.01 806 1215.01 815 1166 c 0,114,115 + 800.85 1174.76 800.85 1174.76 784.879 1174.89 c 0,116,117 + 777.153 1174.96 777.153 1174.96 769 1173 c 0,118,119 + 744 1167 744 1167 744 1149 c 0,120,121 + 744 1087.99 744 1087.99 782.5 1101 c 0,122,123 + 821.009 1114.01 821.009 1114.01 844 1135 c 0,124,125 + 871 1160.99 871 1160.99 876 1273 c 0,126,127 + 875.964 1349.1 l 0,128,129 + 872.849 1400.52 872.849 1400.52 860 1425 c 0,130,131 + 849.326 1445.59 849.326 1445.59 825.576 1445.54 c 0,132,133 + 818.173 1445.52 818.173 1445.52 809.5 1443.5 c 0,134,135 + 773 1434.99 773 1434.99 772 1417 c 0,136,137 + 768 1373.01 768 1373.01 798 1373.5 c 0,138,139 + 828 1373.99 828 1373.99 840 1384 c 0,140,141 + 838.397 1364.37 l 0,142,143 + 833.435 1347.78 833.435 1347.78 815.5 1338 c 0,144,145 + 793.685 1326.1 793.685 1326.1 779.113 1326.16 c 0,146,147 + 775.31 1326.17 775.31 1326.17 772 1327 c 0,148,149 + 715 1339 715 1339 678.5 1375 c 0,150,151 + 642.016 1410.98 642.016 1410.98 603 1436 c 0,152,153 + 556.039 1464.7 556.039 1464.7 506.748 1464.68 c 0,154,155 + 480.455 1464.68 480.455 1464.68 453.5 1456.5 c 0,156,157 + 375.96 1432.98 375.96 1432.98 334 1415 c 0,158,159 + 280.973 1391.99 280.973 1391.99 210.5 1374 c 0,160,161 + 146.8 1357.74 146.8 1357.74 121.868 1357.8 c 0,162,163 + 119.215 1357.81 119.215 1357.81 117 1358 c 0,164,165 + 18.9988 1365.01 18.9988 1365.01 8 1466.5 c 0,166,167 + -3 1568.01 -3 1568.01 89 1594 c 0,168,169 + 66.0001 1576 66.0001 1576 44 1532.5 c 0,170,171 + 22 1489 22 1489 63 1447 c 0,172,173 + 85.4007 1423 85.4007 1423 118.04 1422.75 c 0,174,175 + 147.044 1426.67 l 0,176,177 + 163.949 1431.1 163.949 1431.1 183 1440.5 c 0,178,179 + 261 1479.01 261 1479.01 285 1517 c 0,180,181 + 327.531 1585.52 327.531 1585.52 327.879 1616.21 c 0,182,183 + 327.973 1624.48 327.973 1624.48 325 1630 c 0,184,185 + 311 1655.99 311 1655.99 281 1648 c 0,186,187 + 273.001 1646.01 273.001 1646.01 270 1629.5 c 0,188,189 + 270.92 1617.45 l 0,190,191 + 274.131 1609.04 274.131 1609.04 285 1603 c 0,192,193 + 268.51 1595.15 268.51 1595.15 254.565 1595 c 0,194,195 + 245.213 1594.91 245.213 1594.91 237.005 1598.27 c 0,196,197 + 226.275 1602.68 226.275 1602.68 217.5 1613 c 0,198,199 + 199.327 1634.38 199.327 1634.38 199.184 1669.47 c 0,200,201 + 199.126 1683.62 199.126 1683.62 202 1700 c 0,202,203 + 208 1739 208 1739 249.5 1751 c 0,204,205 + 291 1763 291 1763 311 1757 c 0,206,207 + 421.988 1725.01 421.988 1725.01 511.5 1660.5 c 0,208,209 + 601 1596 601 1596 730 1590 c 0,210,211 + 805.281 1589.97 l 0,212,213 + 827.921 1590.97 827.921 1590.97 854 1593 c 0,214,215 + 931 1599 931 1599 931 1659 c 0,216,217 + 931 1679.99 931 1679.99 896.5 1697.5 c 0,218,219 + 870.907 1710.49 870.907 1710.49 857.692 1710.53 c 0,220,221 + 853.097 1710.55 853.097 1710.55 850 1709 c 0,222,223 + 822.999 1692.99 822.999 1692.99 822.5 1675.5 c 0,224,225 + 822 1657.99 822 1657.99 824 1632 c 0,226,227 + 797.428 1640.59 797.428 1640.59 797.12 1672.1 c 0,228,229 + 797.034 1680.9 797.034 1680.9 799 1691.5 c 0,230,231 + 808.001 1740 808.001 1740 838 1755 c 0,232,233 + 861.517 1766.1 861.517 1766.1 891.215 1766.11 c 0,234,235 + 906.986 1766.12 906.986 1766.12 924.5 1763 c 0,236,237 + 974.999 1754 974.999 1754 991 1730 c 0,238,239 + 1028 1673.01 1028 1673.01 1032.5 1629 c 0,240,241 + 1036.27 1592.18 1036.27 1592.18 1036.18 1540.01 c 0,242,243 + 1036 1519 l 0,244,-1 + 1022.5 1335.5 l 0,245,246 + 1020.56 1260.23 l 0,247,248 + 1022.51 1199.19 1022.51 1199.19 1038 1165 c 0,249,250 + 1058 1119.98 1058 1119.98 1081.5 1083.5 c 0,251,-1 + 1125 1013 l 0,252,253 + 1149.01 966.986 1149.01 966.986 1163 858 c 0,254,255 + 1166.9 800.919 l 0,256,257 + 1166.23 743.613 1166.23 743.613 1141 731 c 0,258,259 + 1139.08 769.983 l 0,260,261 + 1132.48 813.66 1132.48 813.66 1105.5 848 c 0,262,263 + 1086.38 872.329 1086.38 872.329 1068.62 872.499 c 0,264,265 + 1058.42 872.597 1058.42 872.597 1048.66 864.714 c 0,266,267 + 1041.2 858.688 1041.2 858.688 1034 848 c 0,268,269 + 1013.01 817.011 1013.01 817.011 994 741 c 0,270,271 + 988.449 718.797 988.449 718.797 988.361 701.972 c 0,272,273 + 988.262 683.23 988.262 683.23 994.94 671.159 c 0,274,275 + 1002.79 656.972 1002.79 656.972 1020 652 c 0,276,277 + 1041.52 648.472 l 0,278,279 + 1063.24 649.314 1063.24 649.314 1068.5 673.5 c 0,280,281 + 1076 708 1076 708 1052 744 c 0,282,283 + 1084 744 1084 744 1102 704 c 0,284,285 + 1115.59 674.668 1115.59 674.668 1115.69 641.818 c 0,286,287 + 1115.78 607.006 1115.78 607.006 1100.73 568.244 c 0,288,289 + 1090.27 541.324 1090.27 541.324 1072.5 512.5 c 0,290,291 + 1005 403 1005 403 975 328 c 0,292,293 + 957 285 957 285 952 227.5 c 0,294,295 + 947 169.995 947 169.995 947 128 c 0,296,297 + 947 113 947 113 956.5 94 c 0,298,299 + 966 74.9999 966 74.9999 988 84 c 0,300,301 + 1020.91 98.9589 1020.91 98.9589 1020.81 124.823 c 0,302,303 + 1020.78 133.542 1020.78 133.542 1017 143.5 c 0,304,305 + 1002 183 1002 183 981 201 c 0,306,307 + 993.355 202.547 l 0,308,309 + 1012.86 199.6 1012.86 199.6 1041.5 166.5 c 0,310,311 + 1080 122.005 1080 122.005 1080 97 c 0,312,313 + 1080 56.9999 1080 56.9999 1066.5 -3 c 0,314,315 + 1053 -63 1053 -63 1008 -77 c 0,316,317 + 967 -89 967 -89 923.5 -86 c 0,318,319 + 880 -83 880 -83 838 -86 c 0,320,321 + 754 -96.0001 754 -96.0001 667.5 -104.5 c 0,322,323 + 580.997 -113.001 580.997 -113.001 506 -144 c 0,324,325 + 444 -168 444 -168 390.5 -181.5 c 0,326,327 + 337 -195 337 -195 266 -186 c 0,0,1 +EndSplineSet +EndChar +StartChar: K +Encoding: 75 75 13 +Width: 1310 +Flags: HMW +VStem: 48 294<-13 1634> +Fore +638 316 m 0,0,1 + 591 315 591 315 620 274 c 0,2,3 + 644.538 239.308 644.538 239.308 683.396 238.982 c 0,4,5 + 690.462 238.923 690.462 238.923 698 240 c 0,6,7 + 679.098 223.619 679.098 223.619 649.677 223.513 c 0,8,9 + 632.402 223.451 632.402 223.451 611.5 229 c 0,10,11 + 555.001 244 555.001 244 536 277 c 0,12,13 + 501 334 501 334 480 444 c 0,14,15 + 459 554 459 554 376 588 c 0,16,17 + 361 594 361 594 328.5 585.5 c 0,18,19 + 296.001 577 296.001 577 286 551 c 0,20,21 + 271 514 271 514 294.5 482 c 0,22,-1 + 342 415 l 0,23,24 + 369 370 369 370 374 303 c 0,25,26 + 373.24 263.147 l 0,27,28 + 368.196 223.29 368.196 223.29 345 196 c 0,29,30 + 344 200.001 344 200.001 342 245.5 c 0,31,32 + 340.55 278.486 340.55 278.486 312.624 278.424 c 0,33,34 + 300.363 278.397 300.363 278.397 283 272 c 0,35,36 + 264.001 265 264.001 265 255.5 165.5 c 0,37,38 + 246.999 66.0001 246.999 66.0001 290 66 c 0,39,40 + 329 66 329 66 323.5 89 c 0,41,42 + 318 111.999 318 111.999 304 127 c 0,43,44 + 361 109 361 109 366.5 63 c 0,45,46 + 372 17 372 17 342 -13 c 0,47,48 + 289.002 -63.9983 289.002 -63.9983 222.5 -104 c 0,49,50 + 156 -144.001 156 -144.001 156 -222 c 0,51,52 + 156 -296.001 156 -296.001 230.5 -329.5 c 0,53,54 + 300.803 -361.112 300.803 -361.112 396.485 -361.113 c 0,55,56 + 402.198 -361.113 402.198 -361.113 408 -361 c 0,57,58 + 348.507 -372.092 348.507 -372.092 301.95 -371.999 c 0,59,60 + 209.993 -371.816 209.993 -371.816 168.5 -328 c 0,61,62 + 107.913 -264.02 107.913 -264.02 98 -181 c 0,63,64 + 97.2541 -142.611 l 0,65,66 + 101.102 -94.0729 101.102 -94.0729 129 -44 c 0,67,68 + 167.999 25.9991 167.999 25.9991 169 95 c 0,69,70 + 169 157.001 169 157.001 144 198 c 0,71,72 + 135.64 212.08 135.64 212.08 124.957 213.576 c 0,73,74 + 111.932 211.149 l 0,75,76 + 103.533 207.148 103.533 207.148 94 197 c 0,77,78 + 62.9999 164 62.9999 164 112 113 c 0,79,80 + 73 102.001 73 102.001 47.5 132 c 0,81,82 + 38.9939 142.007 38.9939 142.007 21 180 c 0,83,84 + 4.00904 215.876 4.00904 215.876 35 283.5 c 0,85,86 + 54.7141 326.518 54.7141 326.518 77 381 c 0,87,88 + 109.344 460.071 109.344 460.071 111.5 491.5 c 0,89,90 + 119.119 602.598 119.119 602.598 121 605 c 0,91,92 + 123.409 606.637 123.409 606.637 123.374 613.538 c 0,93,94 + 123.309 626.595 123.309 626.595 114.5 658.5 c 0,95,96 + 93.5096 731.735 93.5096 731.735 48 800 c 0,97,98 + 36 818 36 818 32 867 c 0,99,100 + 28 916 28 916 67 942 c 0,101,102 + 58.6356 921.335 58.6356 921.335 58.6489 907.841 c 0,103,104 + 58.6678 888.725 58.6678 888.725 75.5 884 c 0,105,106 + 106 876 106 876 130 924 c 0,107,108 + 154.741 970.912 154.741 970.912 154.837 1000.58 c 0,109,110 + 154.848 1004.17 154.848 1004.17 154.5 1007.5 c 0,111,112 + 145.981 1070.48 145.981 1070.48 127 1074 c 0,113,114 + 105.667 1074.72 l 0,115,116 + 91.2499 1071.94 91.2499 1071.94 90.8002 1057.34 c 0,117,118 + 90.73 1055.06 90.73 1055.06 91 1052.5 c 0,119,120 + 94 1024 94 1024 106 1012 c 0,121,122 + 73.004 1012 73.004 1012 53.5 1036.5 c 0,123,124 + 34 1060.99 34 1060.99 34 1076 c 0,125,126 + 31 1122.99 31 1122.99 53 1185.5 c 0,127,128 + 75.0055 1248.02 75.0055 1248.02 88 1296 c 0,129,130 + 97.938 1333.68 97.938 1333.68 97.9311 1370.59 c 0,131,132 + 97.9214 1422.82 97.9214 1422.82 78 1473.5 c 0,133,134 + 44 1560.01 44 1560.01 48 1634 c 0,135,136 + 49.9995 1682.99 49.9995 1682.99 79.5 1717 c 0,137,138 + 99.8632 1740.47 99.8632 1740.47 129.045 1740.59 c 0,139,140 + 142.135 1740.65 142.135 1740.65 157 1736 c 0,141,142 + 110.002 1719.01 110.002 1719.01 102 1688.5 c 0,143,144 + 98.2452 1661.63 l 0,145,146 + 98.4527 1649.59 98.4527 1649.59 103 1641 c 0,147,148 + 122.999 1599 122.999 1599 169 1605 c 0,149,150 + 215.001 1611 215.001 1611 229 1641 c 0,151,152 + 244.674 1677.15 244.674 1677.15 244.693 1707.92 c 0,153,154 + 244.732 1773.36 244.732 1773.36 174 1814.5 c 0,155,156 + 69.9617 1875.02 69.9617 1875.02 36 1886 c 0,157,158 + 165.006 1859 165.006 1859 219 1802.5 c 0,159,160 + 273.003 1745.99 273.003 1745.99 287 1698 c 0,161,162 + 298.866 1655.73 298.866 1655.73 298.907 1618.68 c 0,163,164 + 298.921 1605.77 298.921 1605.77 297.5 1593.5 c 0,165,166 + 292.001 1546.01 292.001 1546.01 277 1488 c 0,167,168 + 266.593 1447.11 266.593 1447.11 266.685 1393.79 c 0,169,170 + 266.717 1375.39 266.717 1375.39 268 1355.5 c 0,171,172 + 272.58 1284.5 272.58 1284.5 328.353 1283.58 c 0,173,174 + 333.462 1283.5 333.462 1283.5 339 1284 c 0,175,176 + 402 1290 402 1290 393 1344 c 0,177,178 + 384 1398 384 1398 334 1410 c 0,179,180 + 359.97 1413.09 l 0,181,182 + 381.98 1412.55 381.98 1412.55 406.5 1402 c 0,183,184 + 445.998 1385.01 445.998 1385.01 455 1355 c 0,185,186 + 475 1280 475 1280 435.5 1215.5 c 0,187,188 + 398.21 1154.61 398.21 1154.61 394 1076 c 0,189,190 + 391.08 1021.49 391.08 1021.49 447 1046 c 0,191,192 + 520 1077.99 520 1077.99 595 1205 c 0,193,194 + 622 1250 622 1250 650 1371.5 c 0,195,196 + 677.466 1490.68 677.466 1490.68 718 1522 c 0,197,198 + 740 1538.99 740 1538.99 774.5 1547.5 c 0,199,200 + 799.731 1550.51 l 0,201,202 + 815.211 1549.79 815.211 1549.79 824 1541 c 0,203,204 + 755 1536.01 755 1536.01 755 1490 c 0,205,206 + 755 1458.99 755 1458.99 785 1466 c 0,207,208 + 875 1482.01 875 1482.01 883.5 1543.5 c 0,209,210 + 892.001 1605.01 892.001 1605.01 931 1655 c 0,211,212 + 958 1689.99 958 1689.99 1005.5 1685 c 0,213,214 + 1052.99 1680.01 1052.99 1680.01 1066 1658 c 0,215,216 + 1046.78 1662.27 1046.78 1662.27 1031.01 1662.3 c 0,217,218 + 987.727 1662.39 987.727 1662.39 970.5 1630.5 c 0,219,220 + 961.129 1613.15 961.129 1613.15 961.06 1596.68 c 0,221,222 + 960.961 1572.89 960.961 1572.89 982 1549 c 0,223,224 + 1006.17 1522.41 1006.17 1522.41 1048.2 1522.44 c 0,225,226 + 1058.33 1522.45 1058.33 1522.45 1069.5 1524 c 0,227,228 + 1126.99 1531.99 1126.99 1531.99 1174.5 1568 c 0,229,230 + 1222.01 1604 1222.01 1604 1242 1662.5 c 0,231,232 + 1248.19 1680.62 1248.19 1680.62 1248.15 1699.75 c 0,233,234 + 1248.06 1742.38 1248.06 1742.38 1217 1790 c 0,235,236 + 1275 1744 1275 1744 1278 1669 c 0,237,238 + 1275.94 1627.18 l 0,239,240 + 1268.9 1580.13 1268.9 1580.13 1240 1547 c 0,241,242 + 1216 1519 1216 1519 1155 1484.5 c 0,243,244 + 1093.98 1449.99 1093.98 1449.99 1031 1426 c 0,245,246 + 936.739 1390.05 936.739 1390.05 861 1257 c 0,247,248 + 824.002 1192.01 824.002 1192.01 803.5 1131 c 0,249,250 + 783.002 1070 783.002 1070 718 989 c 0,251,252 + 674.001 934.001 674.001 934.001 603 927 c 0,253,254 + 639 942 639 942 662 975.5 c 0,255,256 + 670.036 987.205 670.036 987.205 670.015 995.797 c 0,257,258 + 669.976 1011.8 669.976 1011.8 642 1017 c 0,259,260 + 621.612 1016.71 l 0,261,262 + 601.663 1012.85 601.663 1012.85 581.5 995 c 0,263,264 + 552.458 969.292 552.458 969.292 545 932 c 0,265,266 + 533 872 533 872 565.5 844.5 c 0,267,268 + 599.679 815.578 599.679 815.578 619 851 c 0,269,270 + 620.942 860.69 l 0,271,272 + 618.273 876.636 618.273 876.636 575 889 c 0,273,274 + 597.521 905.746 597.521 905.746 617.708 905.986 c 0,275,276 + 636.286 902.519 l 0,277,278 + 641.221 900.562 641.221 900.562 646 897.5 c 0,279,280 + 678 877 678 877 687 847 c 0,281,282 + 711 767 711 767 672 722 c 0,283,284 + 634.562 678.803 634.562 678.803 645 604 c 0,285,286 + 657 518 657 518 757.5 474.5 c 0,287,288 + 858 431 858 431 945 402 c 0,289,290 + 1041.01 369.999 1041.01 369.999 1070 311 c 0,291,292 + 1092.11 266.008 1092.11 266.008 1092.13 243.118 c 0,293,294 + 1092.14 235.987 1092.14 235.987 1090 231 c 0,295,296 + 1064.99 311.001 1064.99 311.001 991 328 c 0,297,298 + 956.966 331.206 l 0,299,300 + 912.173 329.667 912.173 329.667 900 291 c 0,301,302 + 897.698 271.598 l 0,303,304 + 900.902 224.978 900.902 224.978 985 168.5 c 0,305,306 + 1087 99.9995 1087 99.9995 1132 65 c 0,307,308 + 1174.01 30.9915 1174.01 30.9915 1210.5 -27.5 c 0,309,310 + 1239.73 -74.3571 1239.73 -74.3571 1239.78 -117.036 c 0,311,312 + 1239.79 -127.648 1239.79 -127.648 1238 -138 c 0,313,314 + 1209.34 -300.784 1209.34 -300.784 1045 -336 c 0,315,316 + 1025 -340.286 1025 -340.286 992.499 -340.235 c 0,317,318 + 979.5 -340.214 979.5 -340.214 964.5 -339.5 c 0,319,320 + 912 -337 912 -337 868 -322 c 0,321,322 + 880.727 -325.182 880.727 -325.182 912.893 -325.124 c 0,323,324 + 931.273 -325.091 931.273 -325.091 956 -324 c 0,325,326 + 1024 -321 1024 -321 1051 -309 c 0,327,328 + 1115 -279.003 1115 -279.003 1154 -208 c 0,329,330 + 1171.45 -176.237 1171.45 -176.237 1171.48 -142.472 c 0,331,332 + 1171.53 -100.763 1171.53 -100.763 1145 -56 c 0,333,334 + 1131.01 -32.0164 1131.01 -32.0164 1093 -0.5 c 0,335,336 + 1055.01 31 1055.01 31 1012 44 c 0,337,338 + 903 75.0001 903 75.0001 906 29 c 0,339,340 + 906 6.00005 906 6.00005 933.5 6 c 0,341,342 + 961 6 961 6 979 -1 c 0,343,344 + 937 -25 937 -25 890.5 -12.5 c 0,345,346 + 844 -4.76837e-06 844 -4.76837e-06 838 15 c 0,347,348 + 822.002 44.9949 822.002 44.9949 806 92 c 0,349,-1 + 782 172 l 0,350,351 + 772.999 202.002 772.999 202.002 725.5 259.5 c 0,352,353 + 679.085 315.686 679.085 315.686 638 316 c 0,0,1 +EndSplineSet +KernsSLIF: 111 -104 0 0 79 -52 0 0 115 -221 0 0 83 -208 0 0 103 -182 0 0 71 -78 0 0 99 -234 0 0 67 -143 0 0 +EndChar +StartChar: L +Encoding: 76 76 65 +Width: 1349 +Flags: MW +HStem: 5.5 212.5<394 867> +VStem: 77 263<33 1557> +Fore +81 187 m 1,0,1 + 95.8849 195.931 95.8849 195.931 113.845 196 c 0,2,3 + 138.115 196.092 138.115 196.092 168 180 c 0,4,5 + 135.47 181.975 l 0,6,7 + 106.046 179.89 106.046 179.89 86.5 162 c 0,8,9 + 56.9999 135 56.9999 135 75 99 c 0,10,11 + 87.3838 72.0972 87.3838 72.0972 106.059 71.9092 c 0,12,13 + 115.619 71.8129 115.619 71.8129 126.827 78.7173 c 0,14,15 + 144.998 89.91 144.998 89.91 167.5 119.5 c 0,16,17 + 205.326 169.241 205.326 169.241 205.362 225.545 c 0,18,19 + 205.386 263.76 205.386 263.76 188 305 c 0,20,21 + 168.819 348.157 168.819 348.157 146.118 348.141 c 0,22,23 + 135.681 348.134 135.681 348.134 124.5 339 c 0,24,25 + 110.569 327.62 110.569 327.62 110.42 313.007 c 0,26,27 + 110.325 303.613 110.325 303.613 115.924 292.882 c 0,28,29 + 123.812 277.767 123.812 277.767 143 260 c 0,30,31 + 66.9999 285 66.9999 285 64 377 c 0,32,33 + 61 446 61 446 93.5 520.5 c 0,34,35 + 125.999 594.997 125.999 594.997 142 665 c 0,36,37 + 158.584 741.182 158.584 741.182 158.516 811.993 c 0,38,39 + 158.453 877.817 158.453 877.817 144 939 c 0,40,41 + 129 1001 129 1001 109 1061 c 0,42,43 + 89.0001 1121 89.0001 1121 83 1190 c 0,44,45 + 85.4002 1207.77 l 0,46,47 + 89.192 1219.98 89.192 1219.98 98.5 1237 c 0,48,49 + 113.063 1263.62 113.063 1263.62 148.738 1263.94 c 0,50,51 + 155.94 1264.01 155.94 1264.01 164 1263 c 0,52,53 + 151.987 1262.88 l 0,54,55 + 137.206 1258.28 137.206 1258.28 125 1231 c 0,56,57 + 121 1222.06 121 1222.06 120.765 1215.44 c 0,58,59 + 123.205 1205.69 l 0,60,61 + 129.228 1196.59 129.228 1196.59 150.025 1196.62 c 0,62,63 + 154.213 1196.62 154.213 1196.62 159 1197 c 0,64,65 + 193.073 1199.62 193.073 1199.62 193.561 1233.92 c 0,66,67 + 193.632 1238.88 193.632 1238.88 193 1244.5 c 0,68,69 + 188.004 1288.98 188.004 1288.98 180 1342 c 0,70,71 + 168.003 1405.99 168.003 1405.99 142.5 1462.5 c 0,72,73 + 116.992 1519.02 116.992 1519.02 96 1579 c 0,74,75 + 90.8969 1591.93 90.8969 1591.93 90.9442 1607.29 c 0,76,77 + 91.0361 1637.08 91.0361 1637.08 110.5 1676 c 0,78,79 + 127.596 1710.19 127.596 1710.19 157.618 1710.13 c 0,80,81 + 179.407 1710.08 179.407 1710.08 208 1692 c 0,82,83 + 184.001 1692 184.001 1692 154.5 1675.5 c 0,84,85 + 133.787 1663.92 133.787 1663.92 133.533 1633.84 c 0,86,87 + 137 1605 l 0,88,89 + 148.796 1548.97 148.796 1548.97 196 1548.5 c 0,90,91 + 242.998 1548.99 242.998 1548.99 264 1609 c 0,92,93 + 272.991 1635.97 272.991 1635.97 273.066 1660.18 c 0,94,95 + 273.164 1691.87 273.164 1691.87 257.991 1718.82 c 0,96,97 + 240.916 1749.16 240.916 1749.16 204.5 1773.5 c 0,98,99 + 111.01 1836 111.01 1836 31 1848 c 0,100,101 + 98.7863 1845.34 l 0,102,103 + 181.869 1836.9 181.869 1836.9 234 1802.5 c 0,104,105 + 306.003 1754.99 306.003 1754.99 324 1710 c 0,106,107 + 354 1632 354 1632 340 1557 c 0,108,109 + 326 1482 326 1482 326 1409 c 0,110,111 + 329.503 1348.47 l 0,112,113 + 338.221 1276.68 338.221 1276.68 368.5 1193.5 c 0,114,115 + 412 1073.99 412 1073.99 345 1027 c 0,116,117 + 355.31 1043.14 355.31 1043.14 355.372 1059.38 c 0,118,119 + 355.448 1079.36 355.448 1079.36 340 1099.5 c 0,120,121 + 328.21 1114.87 328.21 1114.87 316.244 1115.25 c 0,122,123 + 304.078 1111.81 l 0,124,125 + 293.606 1105.55 293.606 1105.55 283 1088 c 0,126,127 + 268.001 1064 268.001 1064 262.5 975 c 0,128,129 + 263.074 928.003 l 0,130,131 + 268.216 880.218 268.216 880.218 295 864 c 0,132,133 + 304.791 858.066 304.791 858.066 312.778 857.81 c 0,134,135 + 323.721 860.607 l 0,136,137 + 334.485 867.085 334.485 867.085 340.5 888.5 c 0,138,139 + 353 933 353 933 317 972 c 0,140,141 + 358 972 358 972 376.5 918 c 0,142,143 + 395 864 395 864 374 823 c 0,144,145 + 363 801 363 801 348.5 704.5 c 0,146,147 + 334.001 608.009 334.001 608.009 330 500 c 0,148,149 + 330.05 399.127 l 0,150,151 + 332.138 349.53 332.138 349.53 338.5 305.5 c 0,152,153 + 350.999 219.001 350.999 219.001 394 218 c 0,154,155 + 419.375 220.375 l 0,156,157 + 455.75 229.75 455.75 229.75 482 274 c 0,158,159 + 514.832 329.345 514.832 329.345 585.501 329.254 c 0,160,161 + 590.168 329.248 590.168 329.248 595 329 c 0,162,163 + 628 326 628 326 647 296.5 c 0,164,165 + 662.048 273.136 662.048 273.136 662.042 247.577 c 0,166,167 + 662.04 240.864 662.04 240.864 661 234 c 0,168,169 + 640 285 640 285 592 281.5 c 0,170,171 + 544 278 544 278 559 218 c 0,172,173 + 562 200 562 200 599 188 c 0,174,175 + 609.533 184.584 609.533 184.584 625.171 184.652 c 0,176,177 + 664.468 184.825 664.468 184.825 736 207 c 0,178,179 + 792.993 224.998 792.993 224.998 906 266 c 0,180,181 + 1019 307 1019 307 1004 187 c 0,182,183 + 985.478 232.409 985.478 232.409 960.708 233.016 c 0,184,185 + 945.201 229.307 l 0,186,187 + 935.283 224.505 935.283 224.505 924.5 213.5 c 0,188,189 + 876 164 876 164 920 146 c 0,190,191 + 1049 93.0005 1049 93.0005 1151 165.5 c 0,192,193 + 1239.19 228.186 1239.19 228.186 1239.17 375.713 c 0,194,195 + 1239.17 398.817 1239.17 398.817 1237 424 c 0,196,197 + 1285 262 1285 262 1235.5 175 c 0,198,199 + 1186 87.9974 1186 87.9974 1087.5 49 c 0,200,201 + 988.995 9.99982 988.995 9.99982 867 5.5 c 0,202,203 + 745 1 745 1 648 5 c 0,204,205 + 588 8 588 8 517 22 c 0,206,207 + 446 36 446 36 341 8 c 0,208,209 + 291.986 -4.7862 291.986 -4.7862 239.44 -4.70537 c 0,210,211 + 218.014 -4.67242 218.014 -4.67242 196 -2.5 c 0,212,213 + 120.001 4.99989 120.001 4.99989 77 33 c 0,214,215 + 44 54 44 54 38 104 c 0,216,217 + 38.6834 129.312 l 0,218,219 + 44.988 162.747 44.988 162.747 81 187 c 1,0,1 +EndSplineSet +KernsSLIF: 116 -417 0 0 84 -417 0 0 89 -234 0 0 121 -234 0 0 105 -130 0 0 73 -143 0 0 45 -221 0 0 83 -234 0 0 119 -273 0 0 87 -286 0 0 +EndChar +StartChar: M +Encoding: 77 77 14 +Width: 1706 +Flags: HMW +VStem: 94 134<-53 110> 103 219.5<176.5 1679> 352.5 105.5<62.5 376> 1204 234<80 1735> 1320.5 117.5<-254 80> +Fore +1191 -391 m 1,0,1 + 1254.99 -348.011 1254.99 -348.011 1320.5 -254 c 0,2,3 + 1378.85 -170.264 1378.85 -170.264 1378.87 -61.11 c 0,4,5 + 1378.87 -47.7462 1378.87 -47.7462 1378 -34 c 0,6,7 + 1375 5.9856 1375 5.9856 1352 60.5 c 0,8,9 + 1329.01 115 1329.01 115 1271 121 c 0,10,11 + 1236.18 118.355 l 0,12,13 + 1233.88 117.956 1233.88 117.956 1231.5 117.5 c 0,14,15 + 1208 113.001 1208 113.001 1202 95 c 0,16,17 + 1190.15 63.5722 1190.15 63.5722 1190.25 38.2553 c 0,18,19 + 1190.33 14.4222 1190.33 14.4222 1201 -4 c 0,20,21 + 1217.66 -32.7714 1217.66 -32.7714 1249.22 -32.8796 c 0,22,23 + 1259.34 -32.9143 1259.34 -32.9143 1271 -30 c 0,24,25 + 1254.04 -59.2158 1254.04 -59.2158 1207.32 -59.1209 c 0,26,27 + 1204.46 -59.1151 1204.46 -59.1151 1201.5 -59 c 0,28,29 + 1150.01 -57 1150.01 -57 1122 -27 c 0,30,31 + 1082.65 11.5429 1082.65 11.5429 1082.64 73.3058 c 0,32,33 + 1082.64 88.4541 1082.64 88.4541 1085 105 c 0,34,35 + 1098.01 201.049 1098.01 201.049 1129 292 c 0,36,37 + 1159.99 382.965 1159.99 382.965 1178 473 c 0,38,39 + 1190.02 533.081 1190.02 533.081 1210 677.5 c 0,40,41 + 1230 822.036 1230 822.036 1230 885 c 0,42,43 + 1230 933.068 1230 933.068 1224.5 1007.5 c 0,44,45 + 1219 1082 1219 1082 1165 1107 c 0,46,47 + 1145.79 1115.87 1145.79 1115.87 1125.63 1115.79 c 0,48,49 + 1091.2 1115.67 1091.2 1115.67 1054 1089.5 c 0,50,51 + 1014.77 1061.9 1014.77 1061.9 1014.45 1027.45 c 0,52,53 + 1018.33 1004.4 l 0,54,55 + 1020.54 997.811 1020.54 997.811 1024 991 c 0,56,57 + 1037.79 964.081 1037.79 964.081 1054.81 963.673 c 0,58,59 + 1068.33 967.252 l 0,60,61 + 1070.88 968.617 1070.88 968.617 1073.5 970.5 c 0,62,63 + 1101.99 990.995 1101.99 990.995 1112 1029 c 0,64,65 + 1134.99 955 1134.99 955 1094 895 c 0,66,67 + 1058 843.999 1058 843.999 976 836 c 0,68,69 + 893.995 828 893.995 828 830 828 c 0,70,71 + 769 828 769 828 740 797.5 c 0,72,73 + 710.999 766.999 710.999 766.999 709 736 c 0,74,75 + 706 698 706 698 723.5 653.5 c 0,76,77 + 741 609 741 609 768 595 c 0,78,79 + 855 548 855 548 890 574 c 0,80,81 + 925.001 600 925.001 600 936 631 c 0,82,83 + 943 595 943 595 916.5 562 c 0,84,85 + 890 529 890 529 869 526 c 0,86,87 + 790 509 790 509 758.5 527 c 0,88,89 + 727 545 727 545 700 574 c 0,90,91 + 640.999 634.001 640.999 634.001 622.5 739 c 0,92,93 + 604 844 604 844 603 915 c 0,94,95 + 601 959 601 959 577.5 1002.5 c 0,96,97 + 554 1046 554 1046 503 1049 c 0,98,99 + 469 1050.01 469 1050.01 470 1014.5 c 0,100,101 + 470.546 995.136 470.546 995.136 486.86 994.963 c 0,102,103 + 496.177 994.864 496.177 994.864 510.639 1001.02 c 0,104,105 + 517.277 1003.85 517.277 1003.85 525 1008 c 0,106,107 + 515 966 515 966 484 963.5 c 0,108,109 + 455.502 964.925 l 0,110,111 + 440.947 967.75 440.947 967.75 428 975 c 0,112,113 + 397.999 990 397.999 990 397.5 1036 c 0,114,115 + 400.858 1097.86 l 0,116,117 + 402.845 1115.12 402.845 1115.12 406 1133 c 0,118,119 + 408.23 1168.25 l 0,120,121 + 406.474 1196.11 406.474 1196.11 391 1209 c 0,122,123 + 377 1220.38 377 1220.38 365.042 1220.31 c 0,124,125 + 336 1220.15 336 1220.15 319 1152.5 c 0,126,127 + 295 1056.99 295 1056.99 295 999 c 0,128,129 + 295 826.001 295 826.001 348 638 c 0,130,131 + 364 575 364 575 402 506.5 c 0,132,133 + 440 438 440 438 458 376 c 0,134,135 + 480.369 294.514 480.369 294.514 480.4 228.983 c 0,136,137 + 480.408 212.486 480.408 212.486 479 197 c 0,138,139 + 467 54.9995 467 54.9995 376 26 c 0,140,141 + 292 -2 292 -2 265 54 c 0,142,143 + 303 41 303 41 352.5 62.5 c 0,144,145 + 399.923 83.0977 399.923 83.0977 400.077 129.854 c 0,146,147 + 400.084 131.902 400.084 131.902 400 134 c 0,148,149 + 396.484 183.929 396.484 183.929 359.587 184.653 c 0,150,151 + 334.74 180.746 l 0,152,153 + 328.882 179.009 328.882 179.009 322.5 176.5 c 0,154,155 + 250.001 148 250.001 148 228 110 c 0,156,157 + 192.001 48.0011 192.001 48.0011 185 -25 c 0,158,159 + 182.436 -88.491 l 0,160,161 + 183.31 -118.758 183.31 -118.758 189 -141 c 0,162,163 + 223.999 -293.999 223.999 -293.999 290 -361 c 0,164,165 + 356 -428 356 -428 425 -482 c 0,166,167 + 285 -455 285 -455 187.5 -325 c 0,168,169 + 93.943 -200.257 93.943 -200.257 93.8425 -64.4657 c 0,170,171 + 93.8382 -58.7428 93.8382 -58.7428 94 -53 c 0,172,173 + 97 43 97 43 146 140 c 0,174,175 + 195.001 237.001 195.001 237.001 209 333 c 0,176,177 + 214.998 371.988 214.998 371.988 227.5 438.5 c 0,178,179 + 230.901 474.219 l 0,180,181 + 230.041 510.432 230.041 510.432 207 523 c 0,182,183 + 191.903 530.839 191.903 530.839 180.346 530.839 c 0,184,185 + 152.097 530.839 152.097 530.839 145 484 c 0,186,187 + 143.091 450.184 l 0,188,189 + 145.56 415.36 145.56 415.36 171 409 c 0,190,191 + 97.0005 409 97.0005 409 90 474 c 0,192,193 + 82.9999 539 82.9999 539 90 588 c 0,194,195 + 96 634 96 634 127 686 c 0,196,197 + 158 738 158 738 164 783 c 0,198,199 + 168.088 814.428 168.088 814.428 167.998 844.615 c 0,200,201 + 167.736 932.573 167.736 932.573 132 1010 c 0,202,203 + 84.004 1113.99 84.004 1113.99 53 1222 c 0,204,205 + 22.9998 1322.01 22.9998 1322.01 20.5 1382 c 0,206,207 + 18 1442 18 1442 70 1544 c 0,208,209 + 89.997 1582.99 89.997 1582.99 126.5 1590 c 0,210,211 + 154.046 1592.08 l 0,212,213 + 168.318 1590.79 168.318 1590.79 175 1583 c 0,214,215 + 124.999 1578.99 124.999 1578.99 114.5 1508.5 c 0,216,217 + 112.6 1474.11 l 0,218,219 + 115.168 1439.36 115.168 1439.36 144 1436 c 0,220,221 + 173.178 1437.94 l 0,222,223 + 208.051 1445.24 208.051 1445.24 224 1477.5 c 0,224,225 + 246 1522 246 1522 252 1575 c 0,226,227 + 256.999 1620 256.999 1620 246 1672.5 c 0,228,229 + 236.506 1717.81 236.506 1717.81 172.622 1718.06 c 0,230,231 + 162.495 1718.09 162.495 1718.09 151 1717 c 0,232,233 + 128.007 1715.01 128.007 1715.01 115.5 1696.5 c 0,234,235 + 103.708 1679.05 103.708 1679.05 103 1679 c 0,236,237 + 105.806 1714.01 l 0,238,239 + 117.15 1769.34 117.15 1769.34 173.5 1784.5 c 0,240,241 + 189.642 1788.84 189.642 1788.84 205.164 1788.8 c 0,242,243 + 259.359 1788.64 259.359 1788.64 306 1735 c 0,244,245 + 363.005 1667.99 363.005 1667.99 396.5 1582.5 c 0,246,247 + 430 1497 430 1497 473 1428 c 0,248,-1 + 530 1343.5 l 0,249,250 + 566.99 1288.67 566.99 1288.67 595.556 1288.37 c 0,251,252 + 605.034 1288.27 605.034 1288.27 613.585 1294.17 c 0,253,254 + 618.977 1297.89 618.977 1297.89 624 1304 c 0,255,256 + 634.821 1316.98 634.821 1316.98 634.87 1331.28 c 0,257,258 + 634.933 1350.01 634.933 1350.01 616.5 1371 c 0,259,260 + 588.485 1402.9 588.485 1402.9 554.892 1402.84 c 0,261,262 + 549.517 1402.83 549.517 1402.83 544 1402 c 0,263,264 + 562.993 1424.95 562.993 1424.95 587.931 1425.04 c 0,265,266 + 594.509 1425.07 594.509 1425.07 601.5 1423.5 c 0,267,268 + 634.987 1416 634.987 1416 653 1405 c 0,269,270 + 689.001 1379.99 689.001 1379.99 694 1326 c 0,271,272 + 695.999 1271.01 695.999 1271.01 723.5 1217.5 c 0,273,274 + 742.767 1180.01 742.767 1180.01 771.12 1180.09 c 0,275,276 + 783.231 1180.12 783.231 1180.12 797 1187 c 0,277,278 + 839.999 1208 839.999 1208 857.5 1263.5 c 0,279,280 + 874.99 1318.97 874.99 1318.97 901 1389 c 0,281,282 + 937 1485 937 1485 1034.5 1600.5 c 0,283,284 + 1131.99 1715.99 1131.99 1715.99 1204 1735 c 0,285,286 + 1299.18 1758.55 1299.18 1758.55 1414.62 1758.51 c 0,287,288 + 1416.82 1758.51 1416.82 1758.51 1419 1758.5 c 0,289,290 + 1536.99 1758.01 1536.99 1758.01 1624 1696 c 0,291,292 + 1668.01 1662.99 1668.01 1662.99 1715 1607 c 0,293,294 + 1762 1551 1762 1551 1762 1486 c 0,295,296 + 1762 1451.98 1762 1451.98 1753.5 1420.5 c 0,297,298 + 1745 1389 1745 1389 1706 1367 c 0,299,300 + 1732.07 1398.62 1732.07 1398.62 1732.14 1440.1 c 0,301,302 + 1732.19 1473.38 1732.19 1473.38 1715.5 1513 c 0,303,304 + 1678 1602 1678 1602 1606 1635 c 0,305,306 + 1531.03 1668.99 1531.03 1668.99 1449.5 1673 c 0,307,308 + 1424.97 1670.67 l 0,309,310 + 1367.02 1655.35 1367.02 1655.35 1362 1544 c 0,311,312 + 1364.34 1517.8 l 0,313,314 + 1372.6 1483.53 1372.6 1483.53 1408 1448.5 c 0,315,316 + 1438.06 1418.76 1438.06 1418.76 1459.46 1418.54 c 0,317,318 + 1468.94 1418.44 1468.94 1418.44 1476.72 1424.14 c 0,319,320 + 1480.01 1426.55 1480.01 1426.55 1483 1430 c 0,321,322 + 1503.71 1453.3 1503.71 1453.3 1503.69 1471.35 c 0,323,324 + 1503.68 1481.2 1503.68 1481.2 1497.5 1489.5 c 0,325,326 + 1480.01 1512.99 1480.01 1512.99 1451 1523 c 0,327,328 + 1462.95 1538.93 1462.95 1538.93 1480.07 1538.84 c 0,329,330 + 1493.05 1538.77 1493.05 1538.77 1509 1529.5 c 0,331,332 + 1545.99 1508.01 1545.99 1508.01 1552 1497 c 0,333,334 + 1562.18 1474.09 1562.18 1474.09 1562.51 1446 c 0,335,336 + 1558.74 1407.05 l 0,337,338 + 1554 1387 l 0,339,340 + 1536 1321.99 1536 1321.99 1500 1278 c 0,341,342 + 1416.04 1176.16 1416.04 1176.16 1416.08 1061.63 c 0,343,344 + 1416.1 1028.84 1416.1 1028.84 1423 995 c 0,345,346 + 1444 887.992 1444 887.992 1476.5 845 c 0,347,348 + 1508.97 802.053 1508.97 802.053 1539 757 c 0,349,350 + 1602.07 662.786 1602.07 662.786 1602.09 561.896 c 0,351,352 + 1602.09 533.218 1602.09 533.218 1597 504 c 0,353,354 + 1589.99 464.981 1589.99 464.981 1573.5 427.5 c 0,355,356 + 1557 389.995 1557 389.995 1514 360 c 0,357,358 + 1503.02 353.01 1503.02 353.01 1475.5 342.5 c 0,359,360 + 1455.47 338.636 l 0,361,362 + 1439.99 338.866 1439.99 338.866 1427 350 c 0,363,364 + 1484 377 1484 377 1494.5 417.5 c 0,365,366 + 1501.7 445.258 1501.7 445.258 1501.61 472.323 c 0,367,368 + 1501.57 484.735 1501.57 484.735 1500 497 c 0,369,370 + 1497 524 1497 524 1451 525.5 c 0,371,372 + 1429 522.813 l 0,373,374 + 1401.07 514.148 1401.07 514.148 1390 478 c 0,375,376 + 1374.99 431.982 1374.99 431.982 1373 369.5 c 0,377,378 + 1371.01 307 1371.01 307 1379 259 c 0,379,380 + 1389.99 190.017 1389.99 190.017 1406.5 154 c 0,381,382 + 1423 118 1423 118 1438 80 c 0,383,384 + 1469.99 -7 1469.99 -7 1453 -101 c 0,385,386 + 1436.99 -185.011 1436.99 -185.011 1383 -266 c 0,387,388 + 1329 -347 1329 -347 1191 -391 c 1,0,1 +EndSplineSet +KernsSLIF: 65 -104 0 0 97 -104 0 0 105 78 0 0 +EndChar +StartChar: N +Encoding: 78 78 49 +Width: 1258 +Flags: MW +VStem: 112 207<77 1354> 762 258<69 1428.5> +Fore +74 -62 m 1,0,1 + 41 43 41 43 64.5 150 c 0,2,3 + 87.9992 256.995 87.9992 256.995 108 359 c 0,4,5 + 138 521 138 521 61 677 c 0,6,7 + -16 833 -16 833 17 954 c 0,8,9 + 20 965 20 965 44 986 c 0,10,11 + 68 1007 68 1007 101 992 c 0,12,13 + 9.00005 947 9.00005 947 77.5 905.5 c 0,14,15 + 146.001 864 146.001 864 146 964 c 0,16,17 + 146 1059 146 1059 129 1160 c 0,18,19 + 112 1261 112 1261 112 1354 c 0,20,21 + 114.761 1469.81 l 0,22,23 + 116.564 1501.21 116.564 1501.21 119.5 1533.5 c 0,24,25 + 128.001 1627 128.001 1627 184 1684 c 0,26,27 + 203.611 1704.22 203.611 1704.22 228.297 1704.54 c 0,28,29 + 251.074 1700.94 l 0,30,31 + 256.195 1699.33 256.195 1699.33 261.5 1697 c 0,32,33 + 307 1677 307 1677 307 1650 c 0,34,35 + 268.794 1682.55 268.794 1682.55 241.845 1682.8 c 0,36,37 + 231.258 1682.9 231.258 1682.9 221.5 1677.5 c 0,38,39 + 189.999 1659 189.999 1659 180.5 1611.5 c 0,40,41 + 176.467 1591.33 176.467 1591.33 176.489 1569.19 c 0,42,43 + 176.519 1539.16 176.519 1539.16 184 1505.5 c 0,44,45 + 196.999 1447.01 196.999 1447.01 233 1413 c 0,46,47 + 295.992 1350.01 295.992 1350.01 386 1314.5 c 0,48,49 + 476.011 1278.99 476.011 1278.99 519 1224 c 0,50,51 + 545.623 1187.93 545.623 1187.93 545.694 1151.12 c 0,52,53 + 545.706 1145.07 545.706 1145.07 545 1139 c 0,54,55 + 540.001 1096 540.001 1096 480 1066 c 0,56,-1 + 502 1105 l 0,57,58 + 514 1126 514 1126 506 1153 c 0,59,60 + 497 1178.99 497 1178.99 477.5 1184.5 c 0,61,62 + 464.262 1184.99 l 0,63,64 + 453.62 1182.33 453.62 1182.33 446 1169 c 0,65,66 + 437.906 1155.92 437.906 1155.92 437.953 1128.31 c 0,67,68 + 437.981 1111.58 437.981 1111.58 441 1089.5 c 0,69,70 + 449 1031 449 1031 469.5 969.5 c 0,71,72 + 490 908 490 908 517.5 862 c 0,73,74 + 541.915 821.159 541.915 821.159 565.149 820.52 c 0,75,76 + 568.084 820.439 568.084 820.439 571 821 c 0,77,78 + 643 833 643 833 617 883.5 c 0,79,80 + 591.001 933.999 591.001 933.999 559 960 c 0,81,82 + 673 931 673 931 681 835.5 c 0,83,84 + 689 740 689 740 689 645 c 0,85,86 + 689 567.999 689 567.999 744 530 c 0,87,88 + 757.572 520.623 757.572 520.623 768.89 520.563 c 0,89,90 + 787.453 520.463 787.453 520.463 799.956 545.418 c 0,91,92 + 810.726 566.914 810.726 566.914 817 607 c 0,93,94 + 826.998 675.985 826.998 675.985 832.5 743.5 c 0,95,96 + 838 811 838 811 819 882 c 0,97,98 + 808 921 808 921 781.5 974.5 c 0,99,100 + 755 1028.01 755 1028.01 755 1075 c 0,101,102 + 755 1120 755 1120 773 1156 c 0,103,104 + 789.176 1188.35 789.176 1188.35 831.992 1188.4 c 0,105,106 + 836.826 1188.41 836.826 1188.41 842 1188 c 0,107,108 + 822 1170 822 1170 807 1140 c 0,109,110 + 792 1110 792 1110 813 1092 c 0,111,112 + 823 1082.67 823 1082.67 831.5 1082.67 c 0,113,114 + 848.499 1082.67 848.499 1082.67 859.5 1120 c 0,115,116 + 876 1175.99 876 1175.99 876 1188 c 0,117,118 + 876 1262 876 1262 839 1314.5 c 0,119,120 + 802 1367 802 1367 794 1439 c 0,121,122 + 794.095 1471.9 l 0,123,124 + 800.447 1521.51 800.447 1521.51 845.5 1560.5 c 0,125,126 + 905 1611.99 905 1611.99 953 1535 c 0,127,128 + 919.238 1535.44 l 0,129,130 + 871.273 1529.7 871.273 1529.7 870.734 1481.68 c 0,131,132 + 870.688 1477.5 870.688 1477.5 871 1473 c 0,133,134 + 876 1401 876 1401 936 1401 c 0,135,136 + 989.994 1401 989.994 1401 1020 1428.5 c 0,137,138 + 1050 1455.99 1050 1455.99 1071 1499 c 0,139,140 + 1093.96 1545.56 1093.96 1545.56 1093.94 1612.45 c 0,141,142 + 1093.93 1650.44 1093.93 1650.44 1086.5 1695 c 0,143,144 + 1065.99 1818.01 1065.99 1818.01 1006 1877 c 0,145,146 + 1102.01 1814 1102.01 1814 1125 1699 c 0,147,148 + 1148 1583.97 1148 1583.97 1148 1560 c 0,149,150 + 1148 1485.01 1148 1485.01 1116 1422.5 c 0,151,152 + 1083.99 1359.96 1083.99 1359.96 1070 1297 c 0,153,154 + 1062.93 1266.38 1062.93 1266.38 1062.96 1238.99 c 0,155,156 + 1062.99 1196.62 1062.99 1196.62 1080 1162 c 0,157,158 + 1107.99 1105.03 1107.99 1105.03 1134 1043 c 0,159,160 + 1168.01 955 1168.01 955 1183.5 886 c 0,161,162 + 1198.99 817 1198.99 817 1083 760 c 0,163,-1 + 1113 802.5 l 0,164,165 + 1130 827.007 1130 827.007 1130 852 c 0,166,167 + 1130 892 1130 892 1104 892 c 0,168,169 + 1077.42 889.157 l 0,170,171 + 1028.81 876.802 1028.81 876.802 1024 811 c 0,172,173 + 1015 687 1015 687 1003 556.5 c 0,174,175 + 991 426 991 426 966 305 c 0,176,177 + 948 222.001 948 222.001 863 62 c 0,178,179 + 778 -98 778 -98 670 -79 c 0,180,181 + 720 -55 720 -55 736.5 -18.5 c 0,182,183 + 753 18 753 18 762 69 c 0,184,185 + 775 138 775 138 725.5 292.5 c 0,186,187 + 676 447 676 447 593 435 c 0,188,189 + 565 431 565 431 569 395 c 0,190,191 + 572.22 366.025 572.22 366.025 596.817 365.553 c 0,192,193 + 610 367 l 0,194,195 + 596.188 350 596.188 350 578.988 349.934 c 0,196,197 + 563.812 349.875 563.812 349.875 546 363 c 0,198,199 + 508 391 508 391 502 411 c 0,200,201 + 467 518.001 467 518.001 461 595 c 0,202,203 + 455 671.999 455 671.999 423 770 c 0,204,205 + 400 839 400 839 373 847 c 0,206,207 + 364.788 846.446 l 0,208,209 + 359.164 842.844 359.164 842.844 359.247 828.26 c 0,210,211 + 359.369 806.668 359.369 806.668 372 761 c 0,212,213 + 381.671 725.158 381.671 725.158 381.633 684.301 c 0,214,215 + 381.604 653.34 381.604 653.34 376 619.5 c 0,216,217 + 363 541 363 541 267 579 c 0,218,219 + 351 576 351 576 313.5 641.5 c 0,220,221 + 276 707 276 707 249 644 c 0,222,223 + 234.53 609.272 234.53 609.272 234.5 559 c 0,224,225 + 234.999 510.002 234.999 510.002 247 479 c 0,226,227 + 294.999 346.002 294.999 346.002 326.5 289.5 c 0,228,229 + 340.656 264.108 340.656 264.108 340.574 218.621 c 0,230,231 + 340.473 162.892 340.473 162.892 319 77 c 0,232,233 + 309 36 309 36 268 13 c 0,234,235 + 227.001 -9.99947 227.001 -9.99947 186 -20 c 0,236,237 + 230.999 2.99969 230.999 2.99969 250 78.5 c 0,238,239 + 253.611 106.897 l 0,240,241 + 252.175 152.133 252.175 152.133 189 152 c 0,242,243 + 144.001 150.001 144.001 150.001 131 95.5 c 0,244,245 + 117.999 41 117.999 41 118 -7 c 0,246,247 + 118 -142 118 -142 217.5 -203.5 c 0,248,249 + 317 -265 317 -265 431 -271 c 0,250,251 + 395.576 -276.239 395.576 -276.239 363.232 -276.188 c 0,252,253 + 265.925 -276.034 265.925 -276.034 196.5 -228 c 0,254,255 + 104 -164 104 -164 74 -62 c 1,0,1 +EndSplineSet +KernsSLIF: 65 -234 0 0 97 -208 0 0 +EndChar +StartChar: O +Encoding: 79 79 47 +Width: 1417 +Flags: HW +Fore +263 27 m 1,0,1 + 233 13.5 233 13.5 202 13.5 c 0,2,3 + 171 13.5 171 13.5 139 27 c 0,4,5 + 22 76.0001 22 76.0001 22 185 c 0,6,7 + 22 261.001 22 261.001 75 455 c 0,8,-1 + 147 721 l 0,9,10 + 153.999 750.993 153.999 750.993 158 796 c 0,11,12 + 156.573 817.294 l 0,13,14 + 149.813 841.812 149.813 841.812 117 844 c 0,15,16 + 89.2061 842.225 l 0,17,18 + 46.2343 832.476 46.2343 832.476 46.0801 776.017 c 0,19,20 + 46.0569 767.536 46.0569 767.536 47 758 c 0,21,22 + 19.3514 778.513 19.3514 778.513 19.1465 836.017 c 0,23,24 + 19.1216 842.987 19.1216 842.987 19.5 850.5 c 0,25,26 + 23 920 23 920 41.5 1005.5 c 0,27,28 + 60 1091 60 1091 83.5 1178 c 0,29,30 + 106.998 1264.99 106.998 1264.99 116 1324 c 0,31,32 + 128.001 1411.01 128.001 1411.01 174 1492.5 c 0,33,34 + 201.989 1542.09 201.989 1542.09 257.37 1542.25 c 0,35,36 + 289.993 1542.35 289.993 1542.35 332.12 1525.3 c 0,37,38 + 336.018 1523.72 336.018 1523.72 340 1522 c 0,39,40 + 232.57 1519.34 232.57 1519.34 231.558 1459.92 c 0,41,42 + 233 1444 l 0,43,44 + 246.622 1371.02 246.622 1371.02 295 1370 c 0,45,46 + 373.997 1370 373.997 1370 454 1495 c 0,47,48 + 502.516 1570.8 502.516 1570.8 502.485 1611.67 c 0,49,50 + 502.465 1638.19 502.465 1638.19 482 1650 c 0,51,52 + 451.482 1667.25 451.482 1667.25 427.613 1667.38 c 0,53,54 + 409.651 1667.48 409.651 1667.48 395.456 1657.88 c 0,55,56 + 385.869 1651.4 385.869 1651.4 378 1640.5 c 0,57,58 + 343 1592.01 343 1592.01 330 1567 c 0,59,60 + 325.922 1585.8 325.922 1585.8 325.899 1602.66 c 0,61,62 + 325.82 1660.2 325.82 1660.2 373 1695 c 0,63,64 + 427.818 1735.44 427.818 1735.44 511.724 1735.5 c 0,65,66 + 521.177 1735.51 521.177 1735.51 531 1735 c 0,67,68 + 630.999 1729 630.999 1729 758 1669 c 0,69,70 + 885.004 1609 885.004 1609 924 1539 c 0,71,-1 + 949.5 1479.5 l 0,72,73 + 970.969 1429.07 970.969 1429.07 999.5 1372.5 c 0,74,75 + 1027.99 1316.02 1027.99 1316.02 1060 1270.5 c 0,76,77 + 1089.79 1228.14 1089.79 1228.14 1118 1228 c 0,78,79 + 1188.94 1234.16 1188.94 1234.16 1189.13 1280.17 c 0,80,81 + 1189.18 1293.83 1189.18 1293.83 1183 1311 c 0,82,83 + 1156 1386.01 1156 1386.01 1090 1388 c 0,84,85 + 1116.63 1392.13 1116.63 1392.13 1138.87 1392.1 c 0,86,87 + 1224.37 1392 1224.37 1392 1245 1330.5 c 0,88,89 + 1260.02 1285.72 1260.02 1285.72 1260.02 1250.8 c 0,90,91 + 1260.03 1225.27 1260.03 1225.27 1252 1205 c 0,92,93 + 1227.01 1143.05 1227.01 1143.05 1162 963 c 0,94,95 + 1114.5 831.456 1114.5 831.456 1114.53 767.21 c 0,96,97 + 1114.54 743.538 1114.54 743.538 1121 729 c 0,98,99 + 1134.99 694 1134.99 694 1190 694.5 c 0,100,101 + 1245 695 1245 695 1257 742 c 0,102,103 + 1261.16 756.544 1261.16 756.544 1261.24 768.805 c 0,104,105 + 1261.34 782.452 1261.34 782.452 1256.4 793.271 c 0,106,107 + 1242.28 824.188 1242.28 824.188 1187 832 c 0,108,109 + 1197.02 844.659 1197.02 844.659 1221.79 844.798 c 0,110,111 + 1239.24 844.897 1239.24 844.897 1264.01 838.779 c 0,112,113 + 1270.74 837.119 1270.74 837.119 1278 835 c 0,114,115 + 1347.81 814.638 1347.81 814.638 1348.05 740.675 c 0,116,117 + 1348.06 738.365 1348.06 738.365 1348 736 c 0,118,119 + 1343.01 576.009 1343.01 576.009 1216.5 460.5 c 0,120,121 + 1090 344.992 1090 344.992 1030 216 c 0,122,123 + 1024.6 204.557 1024.6 204.557 1024.65 193.874 c 0,124,125 + 1024.76 170.939 1024.76 170.939 1050 151.5 c 0,126,127 + 1063.03 141.468 1063.03 141.468 1082.37 141.534 c 0,128,129 + 1117.97 141.656 1117.97 141.656 1175 176 c 0,130,131 + 1155.01 125 1155.01 125 1091 97 c 0,132,133 + 1026.98 68.9955 1026.98 68.9955 952.5 52.5 c 0,134,135 + 878 36 878 36 810.5 25.5 c 0,136,137 + 743 15 743 15 718 1 c 0,138,139 + 658 -32 658 -32 567 -58 c 0,140,141 + 522.468 -70.7233 522.468 -70.7233 476.5 -70.7546 c 0,142,143 + 428.532 -70.7873 428.532 -70.7873 379 -57 c 0,144,145 + 367 -53 367 -53 343.5 -37 c 0,146,147 + 320 -21 320 -21 315 11 c 0,148,149 + 368 -31 368 -31 410 -27 c 0,150,151 + 452 -23 452 -23 473 -1 c 0,152,153 + 497 25 497 25 456 54.5 c 0,154,155 + 415 84.0001 415 84.0001 353.5 106.5 c 0,156,157 + 292 129 292 129 233.5 138 c 0,158,159 + 189.68 141.609 l 0,160,161 + 170.8 140.934 170.8 140.934 166 134 c 0,162,163 + 152.476 114.369 152.476 114.369 152.56 97.6881 c 0,164,165 + 152.668 76.131 152.668 76.131 175.5 59.5 c 0,166,167 + 216 30 216 30 263 27 c 1,0,1 +887 310 m 1,85,86 + 899 334 899 334 890.5 373 c 0,87,88 + 882 412 882 412 832 394 c 0,89,90 + 781 376 781 376 788 333 c 0,91,92 + 795 290 795 290 818 288 c 0,93,94 + 749 286 749 286 745 349 c 0,95,96 + 739 418 739 418 790 450.5 c 0,97,98 + 841 483 841 483 889 534 c 0,99,100 + 904 551 904 551 945 692.5 c 0,101,102 + 986 834 986 834 968 910 c 0,103,104 + 946 999 946 999 872.5 1038 c 0,105,106 + 799 1077 799 1077 799 1186 c 0,107,108 + 799 1200.99 799 1200.99 817 1212.5 c 0,109,110 + 826.229 1218.4 826.229 1218.4 836.25 1218.38 c 0,111,112 + 845.767 1218.36 845.767 1218.36 856 1213 c 0,113,114 + 840.205 1210.37 840.205 1210.37 839.81 1193.49 c 0,115,116 + 839.755 1191.13 839.755 1191.13 840 1188.5 c 0,117,118 + 842 1167.01 842 1167.01 860 1166 c 0,119,120 + 872.806 1168.21 l 0,121,122 + 884.747 1174.44 884.747 1174.44 884.653 1197.6 c 0,123,124 + 884.553 1222.09 884.553 1222.09 871 1265.5 c 0,125,126 + 839 1367.99 839 1367.99 736 1390 c 0,127,128 + 628 1412.99 628 1412.99 550.5 1369 c 0,129,130 + 473 1325.01 473 1325.01 473 1256 c 0,131,132 + 473 1230.99 473 1230.99 505 1214 c 0,133,134 + 525.872 1202.91 525.872 1202.91 548.866 1202.89 c 0,135,136 + 561.131 1202.87 561.131 1202.87 574 1206 c 0,137,138 + 603.86 1213.31 603.86 1213.31 604.012 1235.48 c 0,139,140 + 604.11 1249.69 604.11 1249.69 592 1270 c 0,141,142 + 628.292 1265.05 628.292 1265.05 628.527 1221.67 c 0,143,144 + 628.577 1212.45 628.577 1212.45 627 1201.5 c 0,145,146 + 618.002 1139.01 618.002 1139.01 585 1126 c 0,147,148 + 547.001 1111 547.001 1111 491 1102 c 0,149,150 + 435.018 1093 435.018 1093 388 1073 c 0,151,152 + 356.003 1059.01 356.003 1059.01 331 996 c 0,153,154 + 306 933 306 933 289.5 859 c 0,155,156 + 273 785 273 785 264.5 719 c 0,157,158 + 256 653 256 653 257 632 c 0,159,160 + 260 542 260 542 312.5 522.5 c 0,161,162 + 365 503 365 503 416 449 c 0,163,164 + 443 420 443 420 441 370.5 c 0,165,166 + 439 321 439 321 402 316 c 0,167,168 + 411.192 332.085 411.192 332.085 411.143 345.2 c 0,169,170 + 411.106 354.915 411.106 354.915 406 363 c 0,171,172 + 394 382 394 382 360 373 c 0,173,174 + 322 363 322 363 328.5 317.5 c 0,175,176 + 335 272 335 272 371 252 c 0,177,178 + 468.098 195.621 468.098 195.621 594.015 195.652 c 0,179,180 + 628.902 195.661 628.902 195.661 666 200 c 0,181,182 + 837 220 837 220 887 310 c 1,85,86 +EndSplineSet +KernsSLIF: 121 -78 0 0 89 -91 0 0 97 -156 0 0 65 -156 0 0 120 -156 0 0 88 -156 0 0 87 -234 0 0 116 -286 0 0 84 -365 0 0 +EndChar +StartChar: P +Encoding: 80 80 61 +Width: 1329 +Flags: MW +VStem: 197 325<73 1477> +Fore +518 874 m 0,0,1 + 606 816 606 816 627 886 c 0,2,3 + 650 964 650 964 611 956.5 c 0,4,5 + 572 949 572 949 555 928 c 0,6,7 + 543 943 543 943 554.5 971.5 c 0,8,9 + 566 1000 566 1000 578 1012 c 0,10,11 + 627 1061.01 627 1061.01 677 1025.5 c 0,12,13 + 726.986 990.005 726.986 990.005 783 974 c 0,14,15 + 852 953 852 953 878.5 1050 c 0,16,17 + 905.001 1147.01 905.001 1147.01 910 1231 c 0,18,19 + 908.901 1282.34 l 0,20,21 + 904.241 1331.41 904.241 1331.41 886 1384.5 c 0,22,23 + 857.997 1466 857.997 1466 788 1505 c 0,24,25 + 746.02 1526.99 746.02 1526.99 701 1528 c 0,26,27 + 656 1529.01 656 1529.01 661 1453 c 0,28,29 + 663 1415 663 1415 696.5 1410.5 c 0,30,31 + 726.891 1410.32 l 0,32,33 + 746.742 1412.61 746.742 1412.61 768 1421 c 0,34,35 + 761.001 1388.01 761.001 1388.01 727 1373.5 c 0,36,37 + 705.194 1364.2 705.194 1364.2 689.55 1364.16 c 0,38,39 + 680.813 1364.13 680.813 1364.13 674 1367 c 0,40,41 + 603.995 1394 603.995 1394 569.5 1438.5 c 0,42,43 + 535.012 1482.99 535.012 1482.99 511 1493 c 0,44,45 + 487.022 1501.95 487.022 1501.95 468.037 1502.06 c 0,46,47 + 451.651 1502.15 451.651 1502.15 438.986 1495.66 c 0,48,49 + 425.329 1488.66 425.329 1488.66 416 1474 c 0,50,51 + 393 1439 393 1439 391.5 1350.5 c 0,52,53 + 394.035 1261.13 l 0,54,55 + 397.399 1214.16 397.399 1214.16 405 1165 c 0,56,57 + 419.999 1068 419.999 1068 449.5 984 c 0,58,59 + 479 900 479 900 518 874 c 0,0,1 +235 -68 m 0,36,37 + 233.325 25.6653 l 0,38,39 + 237.033 178.49 237.033 178.49 283 327.5 c 0,40,41 + 319.793 446.772 319.793 446.772 319.734 573.376 c 0,42,43 + 319.697 653.229 319.697 653.229 305 736 c 0,44,45 + 288.001 824.999 288.001 824.999 232 888 c 0,46,47 + 176 951.001 176 951.001 164 1029 c 0,48,49 + 162.356 1058.78 l 0,50,51 + 163.651 1078.43 163.651 1078.43 170.5 1102 c 0,52,53 + 182.999 1145.01 182.999 1145.01 222 1150 c 0,54,55 + 205.412 1107.34 205.412 1107.34 205.203 1079.82 c 0,56,57 + 205.105 1067.02 205.105 1067.02 208.55 1057.49 c 0,58,59 + 216.453 1035.63 216.453 1035.63 243 1031 c 0,60,61 + 265.996 1030.34 l 0,62,63 + 303.391 1035.78 303.391 1035.78 312 1089 c 0,64,65 + 310.993 1137.94 l 0,66,67 + 308.867 1164.38 308.867 1164.38 304 1202 c 0,68,69 + 293.002 1286.99 293.002 1286.99 266 1363.5 c 0,70,71 + 239.003 1439.99 239.003 1439.99 197 1477 c 0,72,73 + 181.88 1490.32 181.88 1490.32 164.686 1490.29 c 0,74,75 + 134.121 1490.24 134.121 1490.24 97 1448 c 0,76,77 + 59.3301 1404.67 59.3301 1404.67 59.3529 1351.6 c 0,78,79 + 59.3544 1348.32 59.3544 1348.32 59.5 1345 c 0,80,81 + 62 1288 62 1288 83 1261 c 0,82,83 + 101 1237 101 1237 109 1222 c 0,84,85 + 117.003 1206.99 117.003 1206.99 141 1199 c 0,86,87 + 78 1208 78 1208 67.5 1221.5 c 0,88,89 + 56.9847 1235.02 56.9847 1235.02 33 1258 c 0,90,91 + 10.9999 1303 10.9999 1303 10 1340 c 0,92,93 + 12.5953 1401.58 l 0,94,95 + 13.6097 1411.57 13.6097 1411.57 15 1422 c 0,96,97 + 27.0018 1502.01 27.0018 1502.01 71 1555 c 0,98,99 + 176 1676.01 176 1676.01 269 1705 c 0,100,101 + 353.428 1731.32 353.428 1731.32 498.8 1731.28 c 0,102,103 + 513.581 1731.28 513.581 1731.28 529 1731 c 0,104,105 + 694.016 1728 694.016 1728 811 1689.5 c 0,106,107 + 928.032 1650.98 928.032 1650.98 1071 1557 c 0,108,109 + 1142.03 1508.98 1142.03 1508.98 1204 1436 c 0,110,111 + 1238.68 1395.16 1238.68 1395.16 1238.63 1344.64 c 0,112,113 + 1238.59 1304.83 1238.59 1304.83 1217 1259 c 0,114,115 + 1201 1225 1201 1225 1177.5 1206 c 0,116,117 + 1154.01 1187.01 1154.01 1187.01 1103 1183 c 0,118,119 + 1122 1215.99 1122 1215.99 1129.5 1250 c 0,120,121 + 1130.62 1272.67 l 0,122,123 + 1127.86 1294.49 1127.86 1294.49 1110 1315 c 0,124,125 + 1098.99 1326.01 1098.99 1326.01 1065.5 1334 c 0,126,127 + 1032.01 1341.99 1032.01 1341.99 1031 1289 c 0,128,129 + 1032.07 1159.01 l 0,130,131 + 1033.01 1135.15 1033.01 1135.15 1034.5 1111.5 c 0,132,133 + 1035.52 1032.62 l 0,134,135 + 1033.73 983.704 1033.73 983.704 1026 934 c 0,136,137 + 1017 876.978 1017 876.978 968 749.5 c 0,138,139 + 919 622 919 622 836 589 c 0,140,141 + 782 568 782 568 699.5 588 c 0,142,143 + 617 608 617 608 596 671 c 0,144,145 + 653 642 653 642 708 645 c 0,146,147 + 773 648 773 648 777 682 c 0,148,149 + 774.961 695.917 l 0,150,151 + 764.158 721.263 764.158 721.263 701 741 c 0,152,153 + 651 756 651 756 596 745.5 c 0,154,155 + 541 735 541 735 509 694 c 0,156,157 + 485.999 663.998 485.999 663.998 466 566 c 0,158,159 + 454.824 511.235 454.824 511.235 454.889 464.59 c 0,160,161 + 454.941 427.764 454.941 427.764 462 396 c 0,162,163 + 481.006 309.979 481.006 309.979 500.5 233 c 0,164,165 + 520.001 155.999 520.001 155.999 522 73 c 0,166,167 + 525 -94 525 -94 450 -233 c 0,168,169 + 423 -283 423 -283 341.5 -349 c 0,170,171 + 260.001 -415 260.001 -415 201 -415 c 0,172,173 + 287 -373 287 -373 379 -249.5 c 0,174,175 + 442.033 -164.885 442.033 -164.885 442.164 -90.362 c 0,176,177 + 442.224 -56.1152 442.224 -56.1152 429 -24 c 0,178,179 + 405 31 405 31 363 27.5 c 0,180,181 + 321 24 321 24 289 -18 c 0,182,183 + 268 -46 268 -46 275.5 -98.5 c 0,184,185 + 283 -151 283 -151 294 -175 c 0,186,187 + 239.001 -134.001 239.001 -134.001 235 -68 c 0,36,37 +EndSplineSet +KernsSLIF: 45 -208 0 0 46 -260 0 0 44 -286 0 0 116 -91 0 0 84 -195 0 0 321 -363 0 0 322 -363 0 0 65 -342 0 0 97 -363 0 0 +EndChar +StartChar: Q +Encoding: 81 81 32 +Width: 1255 +Flags: W +Fore +946 1665 m 1,0,1 + 972.261 1677.88 972.261 1677.88 999.749 1678 c 0,2,3 + 1023.34 1678.1 1023.34 1678.1 1047.83 1668.8 c 0,4,5 + 1052.4 1667.06 1052.4 1667.06 1057 1665 c 0,6,7 + 1162 1612.99 1162 1612.99 1162 1503 c 0,8,9 + 1162 1424.01 1162 1424.01 1114 1225 c 0,10,11 + 1066.03 1026.12 1066.03 1026.12 1050 953 c 0,12,13 + 1042.99 921 1042.99 921 1039.5 875 c 0,14,15 + 1036.01 829 1036.01 829 1077 826 c 0,16,17 + 1100.59 827.702 l 0,18,19 + 1139.62 837.667 1139.62 837.667 1139.65 898.428 c 0,20,21 + 1139.65 906.288 1139.65 906.288 1139 915 c 0,22,23 + 1170.9 877.5 1170.9 877.5 1171.01 822.931 c 0,24,25 + 1171.1 779.997 1171.1 779.997 1151.5 726.5 c 0,26,27 + 1107 605.014 1107 605.014 1107 504 c 0,28,29 + 1107 402.008 1107 402.008 1139 350.5 c 0,30,31 + 1170.99 299 1170.99 299 1163 239 c 0,32,33 + 1152.01 149.012 1152.01 149.012 1110 77.5 c 0,34,35 + 1086.04 36.7115 1086.04 36.7115 1040.93 36.4396 c 0,36,37 + 1024.38 36.3399 1024.38 36.3399 1005 41.6884 c 0,38,39 + 984.575 47.3221 984.575 47.3221 961 59 c 0,40,41 + 1067.99 61 1067.99 61 1055.5 138 c 0,42,43 + 1043.33 212.974 1043.33 212.974 1001 214 c 0,44,45 + 983 214 983 214 942 177.5 c 0,46,47 + 901 141.001 901 141.001 901 95 c 0,48,49 + 899 34 899 34 925 15 c 0,50,51 + 951 -4.00001 951 -4.00001 985 -23 c 0,52,53 + 1018.99 -41.9901 1018.99 -41.9901 1050 -81.5 c 0,54,55 + 1080.99 -120.985 1080.99 -120.985 1091 -223 c 0,56,57 + 1055 -129.996 1055 -129.996 979 -79.5 c 0,58,59 + 903 -29 903 -29 877 -98 c 0,60,61 + 859 -144.999 859 -144.999 956.5 -251 c 0,62,63 + 1054 -357 1054 -357 1183 -365 c 0,64,65 + 1121.24 -362.563 l 0,66,67 + 1028.23 -352.747 1028.23 -352.747 951.5 -305.5 c 0,68,69 + 850 -243 850 -243 782 -175 c 0,70,71 + 723.983 -116.983 723.983 -116.983 724 -55 c 0,72,73 + 725 6.00005 725 6.00005 698 16 c 0,74,75 + 684.054 21.1892 684.054 21.1892 671.37 21.1191 c 0,76,77 + 644.946 20.973 644.946 20.973 624 -2 c 0,78,79 + 593 -36 593 -36 522 -50 c 0,80,81 + 244 -101 244 -101 220 54 c 0,82,83 + 286 0 286 0 337 21 c 0,84,85 + 388 42 388 42 355 114 c 0,86,87 + 351.005 121.989 351.005 121.989 332 173.5 c 0,88,89 + 313 224.999 313 224.999 287 283 c 0,90,91 + 261 341 261 341 232.5 387.5 c 0,92,93 + 204.564 433.08 204.564 433.08 182 433 c 0,94,95 + 99.0005 424 99.0005 424 123 346.5 c 0,96,97 + 147 269 147 269 207 269 c 0,98,99 + 187.571 253.572 187.571 253.572 167.49 253.49 c 0,100,101 + 152.429 253.429 152.429 253.429 137 262 c 0,102,103 + 101 282 101 282 95 291 c 0,104,105 + 42 354 42 354 65 457 c 0,106,107 + 71 489 71 489 93.5 559 c 0,108,-1 + 138.5 705 l 0,109,110 + 160.999 780.995 160.999 780.995 175.5 848.5 c 0,111,112 + 190.001 916 190.001 916 180 944 c 0,113,114 + 166.999 979 166.999 979 117.5 979 c 0,115,116 + 68 979 68 979 58 932 c 0,117,118 + 39 851 39 851 120 839 c 0,119,120 + 102 815 102 815 39.5 836 c 0,121,122 + -23 857 -23 857 -22 937 c 0,123,124 + -17.9997 1101.01 -17.9997 1101.01 94.5 1220 c 0,125,126 + 206.996 1338.99 206.996 1338.99 261 1471 c 0,127,128 + 276 1507 276 1507 241 1522 c 0,129,130 + 206.001 1537 206.001 1537 154 1459 c 0,131,132 + 158.999 1543 158.999 1543 213.5 1582 c 0,133,134 + 268.01 1621.01 268.01 1621.01 335 1638 c 0,135,136 + 402.083 1655.02 402.083 1655.02 462.5 1663 c 0,137,138 + 522.996 1670.99 522.996 1670.99 540 1692 c 0,139,140 + 572 1732.01 572 1732.01 504 1761 c 0,141,142 + 482.218 1770.29 482.218 1770.29 461.258 1770.34 c 0,143,144 + 423.561 1770.44 423.561 1770.44 388.522 1740.68 c 0,145,146 + 382.218 1735.32 382.218 1735.32 376 1729 c 0,147,148 + 382.001 1806.01 382.001 1806.01 465.5 1821.5 c 0,149,150 + 549 1836.99 549 1836.99 587 1820 c 0,151,152 + 656 1787 656 1787 697 1740.5 c 0,153,154 + 738.065 1693.93 738.065 1693.93 756 1672 c 0,155,156 + 819.012 1591.99 819.012 1591.99 912.5 1554 c 0,157,158 + 958.669 1535.24 958.669 1535.24 988.622 1535.25 c 0,159,160 + 1019.33 1535.26 1019.33 1535.26 1033 1555 c 0,161,162 + 1046.31 1574.97 1046.31 1574.97 1046.33 1592.08 c 0,163,164 + 1046.36 1613.54 1046.36 1613.54 1025.5 1630.5 c 0,165,166 + 988 1660.99 988 1660.99 946 1665 c 0,167,-1 + 946 1665 l 1,0,1 +735 1510 m 0,105,106 + 636 1511.01 636 1511.01 529.5 1478.5 c 0,107,108 + 422.998 1445.99 422.998 1445.99 389 1374 c 0,109,110 + 377 1350 377 1350 384.5 1309.5 c 0,111,112 + 389.617 1281.87 389.617 1281.87 412.654 1281.93 c 0,113,114 + 423.383 1281.96 423.383 1281.96 438 1288 c 0,115,116 + 476.322 1303.68 476.322 1303.68 476.716 1339.08 c 0,117,118 + 476.774 1344.32 476.774 1344.32 476 1350 c 0,119,120 + 469.999 1394 469.999 1394 451 1397 c 0,121,122 + 475.763 1394.05 l 0,123,124 + 512.154 1383.46 512.154 1383.46 516 1335 c 0,125,126 + 514.434 1298.61 l 0,127,128 + 507.433 1254.61 507.433 1254.61 474.5 1230 c 0,129,130 + 428.988 1195.99 428.988 1195.99 387 1145 c 0,131,132 + 371.997 1127 371.997 1127 332.5 980.5 c 0,133,134 + 304.311 875.949 304.311 875.949 304.388 806.797 c 0,135,136 + 304.418 779.049 304.418 779.049 309 757 c 0,137,138 + 328.001 664.999 328.001 664.999 402.5 593 c 0,139,140 + 477 521 477 521 477 410 c 0,141,142 + 477 395 477 395 460.5 382.5 c 0,143,144 + 444 370 444 370 426 382 c 0,145,146 + 441 385 441 385 439 407 c 0,147,148 + 437 429 437 429 422 431 c 0,149,150 + 383 434 383 434 376 361.5 c 0,151,152 + 369 289 369 289 435 243 c 0,153,154 + 476 213 476 213 527 201 c 0,155,156 + 578 189 578 189 608 204 c 0,157,158 + 667 229.999 667 229.999 656 285 c 0,159,160 + 645 340 645 340 582 376 c 0,161,162 + 678 371 678 371 691.5 318.5 c 0,163,164 + 705 266 705 266 768 262 c 0,165,166 + 807 259 807 259 826.5 295 c 0,167,168 + 846 331 846 331 846 349 c 0,169,170 + 846 373.999 846 373.999 817 391.5 c 0,171,172 + 797.184 403.458 797.184 403.458 776.433 403.509 c 0,173,174 + 766.817 403.533 766.817 403.533 757 401 c 0,175,176 + 729.121 393.121 729.121 393.121 728.791 370.55 c 0,177,178 + 732.807 350.482 l 0,179,180 + 735.501 343.222 735.501 343.222 740 335 c 0,181,182 + 706.857 339.971 706.857 339.971 706.668 384.761 c 0,183,184 + 706.629 394.028 706.629 394.028 708 405 c 0,185,186 + 716 469 716 469 746 483 c 0,187,188 + 779 498 779 498 846 517.5 c 0,189,190 + 913 537 913 537 937 598 c 0,191,192 + 961 661 961 661 940 875.5 c 0,193,194 + 919 1089.99 919 1089.99 810 1232 c 0,195,196 + 787.5 1260.13 787.5 1260.13 787.412 1305.83 c 0,197,198 + 787.406 1308.88 787.406 1308.88 787.5 1312 c 0,199,200 + 789 1362 789 1362 822 1368 c 0,201,202 + 813.495 1350.99 813.495 1350.99 813.349 1337.68 c 0,203,204 + 813.25 1328.63 813.25 1328.63 818 1319.5 c 0,205,206 + 825.334 1307.17 825.334 1307.17 841.555 1307.06 c 0,207,208 + 849.667 1307 849.667 1307 860 1310 c 0,209,210 + 893 1320.01 893 1320.01 893 1371 c 0,211,212 + 893 1421.99 893 1421.99 869 1450 c 0,213,214 + 845.986 1476.01 845.986 1476.01 805.5 1493 c 0,215,216 + 764.988 1510 764.988 1510 735 1510 c 0,105,106 +EndSplineSet +EndChar +StartChar: R +Encoding: 82 82 57 +Width: 1327 +Flags: MW +VStem: 112 318<-13 1619> +Fore +1128 -43 m 0,0,1 + 1125 20.0058 1125 20.0058 1077.5 71.5 c 0,2,3 + 1029.99 123.002 1029.99 123.002 969 136 c 0,4,5 + 942.51 137.844 l 0,6,7 + 911.739 135.321 911.739 135.321 893.5 108.5 c 0,8,9 + 868 71 868 71 903 37 c 0,10,11 + 933 7 933 7 951 20 c 0,12,13 + 969 33 969 33 987 57 c 0,14,15 + 1005 -25 1005 -25 930 -45 c 0,16,17 + 855 -65 855 -65 813 -4 c 0,18,19 + 780 44 780 44 770.5 108.5 c 0,20,21 + 761 173 761 173 745 227 c 0,22,23 + 716.999 318.002 716.999 318.002 642.5 454 c 0,24,25 + 568 590 568 590 472 611 c 0,26,27 + 436 617 436 617 386 598.5 c 0,28,29 + 337.069 580.396 337.069 580.396 337 505 c 0,30,31 + 337 368 337 368 381 245 c 0,32,33 + 425 122 425 122 416 -26 c 0,34,35 + 411.001 -102.999 411.001 -102.999 341.5 -186 c 0,36,37 + 272 -269.001 272 -269.001 200 -295 c 0,38,39 + 147.999 -313 147.999 -313 102 -320.5 c 0,40,41 + 55.9999 -328 55.9999 -328 -1 -319 c 0,42,43 + 64 -309 64 -309 138 -277 c 0,44,45 + 181.001 -256 181.001 -256 248.5 -196.5 c 0,46,47 + 316.001 -136.999 316.001 -136.999 321 -47 c 0,48,49 + 324 14 324 14 310 68 c 0,50,51 + 296 122 296 122 220 121 c 0,52,53 + 161.371 119.046 161.371 119.046 161 33.5 c 0,54,55 + 162.001 -52.0001 162.001 -52.0001 222 -74 c 0,56,57 + 185.921 -72.0319 l 0,58,59 + 160.223 -67.6052 160.223 -67.6052 146 -54 c 0,60,61 + 122.998 -31.9977 122.998 -31.9977 112 -13 c 0,62,63 + 87.1224 30.6532 87.1224 30.6532 87.0314 92.7034 c 0,64,65 + 86.9318 160.706 86.9318 160.706 116.602 250.804 c 0,66,67 + 117.536 253.642 117.536 253.642 118.5 256.5 c 0,68,69 + 177.998 432.992 177.998 432.992 200 529 c 0,70,71 + 213.298 586.794 213.298 586.794 213.255 619.738 c 0,72,73 + 213.214 651.206 213.214 651.206 201 660 c 0,74,75 + 189.636 668.182 189.636 668.182 179.512 668.306 c 0,76,77 + 171.681 668.402 171.681 668.402 164.591 663.676 c 0,78,79 + 160.683 661.07 160.683 661.07 157 657 c 0,80,81 + 138.001 636.001 138.001 636.001 135.5 602 c 0,82,83 + 136.939 576.347 l 0,84,85 + 140.286 561.572 140.286 561.572 150 553 c 0,86,87 + 81 556 81 556 73.5 615.5 c 0,88,89 + 66 675 66 675 75 710 c 0,90,91 + 88.9999 771 88.9999 771 129 837.5 c 0,92,93 + 168.998 903.996 168.998 903.996 185 966 c 0,94,95 + 209 1063.01 209 1063.01 200 1164 c 0,96,97 + 187.999 1302.01 187.999 1302.01 165.5 1448 c 0,98,99 + 161.539 1473.7 161.539 1473.7 161.56 1498.62 c 0,100,101 + 161.659 1615.3 161.659 1615.3 249 1715 c 0,102,103 + 332.004 1811.01 332.004 1811.01 498.5 1823.5 c 0,104,105 + 542.128 1823.16 l 0,106,107 + 666.124 1810.3 666.124 1810.3 673 1653 c 0,108,109 + 633 1746 633 1746 526 1740 c 0,110,111 + 429.612 1734.6 429.612 1734.6 428.979 1640.74 c 0,112,113 + 428.909 1630.41 428.909 1630.41 430 1619 c 0,114,115 + 433 1582 433 1582 480 1559.5 c 0,116,117 + 527.013 1536.99 527.013 1536.99 583 1530.5 c 0,118,119 + 634.872 1528.19 l 0,120,121 + 661.46 1529.07 661.46 1529.07 685.5 1534.5 c 0,122,123 + 732 1545 732 1545 734 1575 c 0,124,125 + 730.88 1592.46 l 0,126,127 + 720.662 1615.48 720.662 1615.48 677.121 1615.69 c 0,128,129 + 669.123 1615.73 669.123 1615.73 660 1615 c 0,130,131 + 696.965 1635.92 696.965 1635.92 737.127 1635.89 c 0,132,133 + 779.53 1635.87 779.53 1635.87 825.5 1612.5 c 0,134,135 + 914.997 1567.01 914.997 1567.01 949 1468 c 0,136,137 + 974.001 1390 974.001 1390 1011 1367.5 c 0,138,139 + 1047.99 1345.01 1047.99 1345.01 1111 1288 c 0,140,141 + 1137.99 1262.01 1137.99 1262.01 1149.5 1203.5 c 0,142,143 + 1150.82 1178.98 l 0,144,145 + 1146.53 1137.32 1146.53 1137.32 1095 1110 c 0,146,147 + 1121.6 1139.56 1121.6 1139.56 1121.65 1165.79 c 0,148,149 + 1121.68 1183.94 1121.68 1183.94 1109 1200.5 c 0,150,151 + 1088.51 1227.26 1088.51 1227.26 1070.66 1227.17 c 0,152,153 + 1061.48 1227.12 1061.48 1227.12 1053 1220 c 0,154,155 + 1037.03 1206.94 1037.03 1206.94 1036.99 1173.85 c 0,156,157 + 1036.94 1138.57 1036.94 1138.57 1055 1080.5 c 0,158,159 + 1089.99 968 1089.99 968 1064 859 c 0,160,161 + 1038.99 757 1038.99 757 945.5 742.5 c 0,162,163 + 852 728 852 728 813 764 c 0,164,165 + 854.001 765 854.001 765 885 788.5 c 0,166,167 + 916 812 916 812 907 857 c 0,168,169 + 892 927 892 927 809 855.5 c 0,170,171 + 726 784 726 784 738 710 c 0,172,173 + 744 666 744 666 803.5 620 c 0,174,175 + 863 574 863 574 887 593 c 0,176,177 + 897.886 601.165 897.886 601.165 898.107 612.144 c 0,178,179 + 894.131 627.135 l 0,180,181 + 892.791 629.758 892.791 629.758 891 632.5 c 0,182,183 + 875 657 875 657 833 657 c 0,184,185 + 837 687 837 687 889 687 c 0,186,187 + 941 687 941 687 967 659 c 0,188,189 + 1000 620 1000 620 991 539 c 0,190,191 + 982 458 982 458 982 408 c 0,192,193 + 982 300.001 982 300.001 1059 269.5 c 0,194,195 + 1135.99 239.001 1135.99 239.001 1191 158 c 0,196,197 + 1234 94.0096 1234 94.0096 1249 7.5 c 0,198,199 + 1257.42 -41.0666 1257.42 -41.0666 1257.33 -82.5396 c 0,200,201 + 1257.26 -114.933 1257.26 -114.933 1252 -143 c 0,202,203 + 1196.01 -418.993 1196.01 -418.993 985.5 -531 c 0,204,205 + 775.003 -642.999 775.003 -642.999 531 -677 c 0,206,207 + 771.001 -609.999 771.001 -609.999 956.5 -466.5 c 0,208,209 + 1128.86 -333.171 1128.86 -333.171 1128.98 -81.9849 c 0,210,211 + 1128.99 -62.8342 1128.99 -62.8342 1128 -43 c 0,0,1 +596 909 m 0,125,126 + 622 881 622 881 659.5 894.5 c 0,127,128 + 697 908 697 908 739 937 c 0,129,130 + 788 971 788 971 817.5 1042.5 c 0,131,132 + 846.999 1114 846.999 1114 852.5 1183.5 c 0,133,134 + 853.032 1236.31 l 0,135,136 + 850.538 1272.97 850.538 1272.97 839.5 1302.5 c 0,137,138 + 824.154 1343.56 824.154 1343.56 789.89 1343.68 c 0,139,140 + 782.845 1343.71 782.845 1343.71 775 1342 c 0,141,142 + 736 1333 736 1333 732.5 1301.5 c 0,143,144 + 734.396 1286.82 l 0,145,146 + 743.097 1264.03 743.097 1264.03 788 1245 c 0,147,148 + 704 1231.99 704 1231.99 664.5 1276.5 c 0,149,150 + 625.002 1321 625.002 1321 584 1347 c 0,151,152 + 543.637 1371.84 543.637 1371.84 506.754 1372.04 c 0,153,154 + 488.577 1372.14 488.577 1372.14 471.246 1366.26 c 0,155,156 + 455.786 1361.01 455.786 1361.01 441 1351 c 0,157,158 + 376.004 1307.01 376.004 1307.01 346 1215 c 0,159,160 + 331 1171.01 331 1171.01 322 1032 c 0,161,162 + 313 893 313 893 394 878 c 0,163,164 + 420.822 875.578 l 0,165,166 + 464.908 878.309 464.908 878.309 465.305 934.977 c 0,167,168 + 465.342 940.254 465.342 940.254 465 946 c 0,169,170 + 461.845 983.859 461.845 983.859 419.498 984.392 c 0,171,172 + 394 982 l 0,173,174 + 395.633 992.939 l 0,175,176 + 401.858 1006 401.858 1006 429 1016 c 0,177,178 + 449.668 1023.61 449.668 1023.61 464.713 1023.54 c 0,179,180 + 477.334 1023.47 477.334 1023.47 486 1018 c 0,181,182 + 561 967 561 967 552.5 965.5 c 0,183,184 + 544 964 544 964 596 909 c 0,125,126 +EndSplineSet +KernsSLIF: 89 -143 0 0 121 -130 0 0 83 -208 0 0 71 -104 0 0 116 -286 0 0 84 -313 0 0 86 -22 0 0 87 -150 0 0 +EndChar +StartChar: S +Encoding: 83 83 15 +Width: 1364 +Flags: HW +Fore +598 -86 m 0,0,1 + 580 -78.0001 580 -78.0001 553.5 -52 c 0,2,3 + 531.24 -30.1606 531.24 -30.1606 531.206 -9.7312 c 0,4,5 + 531.2 -5.8401 531.2 -5.8401 532 -2 c 0,6,7 + 556.993 -17.9955 556.993 -17.9955 582 -36.5 c 0,8,9 + 594 -45.38 594 -45.38 606 -45.62 c 0,10,11 + 622 -42.1 l 0,12,13 + 627 -39.8 627 -39.8 632 -36 c 0,14,15 + 649.627 -22.339 649.627 -22.339 649.777 -9.26058 c 0,16,17 + 649.872 -0.893791 649.872 -0.893791 642.815 7.23458 c 0,18,19 + 635.87 15.2327 635.87 15.2327 622 23 c 0,20,21 + 572 51 572 51 493 79 c 0,22,-1 + 335.5 134 l 0,23,24 + 256.999 161 256.999 161 240 188 c 0,25,26 + 211.999 230 211.999 230 219 294.5 c 0,27,28 + 226 359 226 359 283 372 c 0,29,30 + 283.268 329.648 l 0,31,32 + 286.957 296.146 286.957 296.146 303 278.5 c 0,33,34 + 328 251 328 251 403 274 c 0,35,36 + 445 286 445 286 436.5 339 c 0,37,38 + 427.999 392.001 427.999 392.001 414 421 c 0,39,40 + 384 481 384 481 302.5 515.5 c 0,41,42 + 221.001 550 221.001 550 157 560 c 0,43,44 + 122.001 565 122.001 565 83.5 557.5 c 0,45,46 + 45 550 45 550 8 542 c 0,47,48 + 79 596 79 596 130.5 595.5 c 0,49,50 + 182.001 595 182.001 595 200 594 c 0,51,52 + 248 591 248 591 326.5 558 c 0,53,54 + 405 525 405 525 438 494 c 0,55,56 + 492.001 441.998 492.001 441.998 546 351 c 0,57,58 + 599.621 260.638 599.621 260.638 666 208 c 0,59,60 + 704 176.999 704 176.999 783 160 c 0,61,62 + 809.78 154.237 809.78 154.237 831.963 154.22 c 0,63,64 + 875.22 154.187 875.22 154.187 901 176 c 0,65,66 + 998 261.999 998 261.999 1013 374.5 c 0,67,68 + 1028 487 1028 487 992 570 c 0,69,70 + 974 612 974 612 893.5 669 c 0,71,72 + 813 726 813 726 754 729 c 0,73,74 + 721.157 727.957 l 0,75,76 + 684 721.514 684 721.514 684 688 c 0,77,78 + 684 637 684 637 705 625.5 c 0,79,-1 + 764 593 l 0,80,81 + 740.845 584.699 740.845 584.699 718.262 584.796 c 0,82,83 + 689.155 584.922 689.155 584.922 661 599 c 0,84,85 + 611 624 611 624 592 672 c 0,86,-1 + 546.5 782 l 0,87,88 + 510 870 510 870 460.5 963 c 0,89,90 + 411.009 1055.98 411.009 1055.98 356.5 1124.5 c 0,91,92 + 311.764 1180.73 311.764 1180.73 272.75 1180.69 c 0,93,94 + 264.239 1180.69 264.239 1180.69 256 1178 c 0,95,96 + 220.5 1166.49 220.5 1166.49 220.442 1108.94 c 0,97,98 + 220.439 1106.51 220.439 1106.51 220.5 1104 c 0,99,100 + 222 1041.99 222 1041.99 256 1034 c 0,101,102 + 231.657 1031.21 l 0,103,104 + 199.094 1032.81 199.094 1032.81 182 1067 c 0,105,106 + 159 1113.01 159 1113.01 159 1134 c 0,107,108 + 159 1199 159 1199 174 1247 c 0,109,110 + 189 1295 189 1295 213 1343 c 0,111,112 + 270.997 1462.99 270.997 1462.99 412.5 1566 c 0,113,114 + 554 1669.01 554 1669.01 611 1704 c 0,115,116 + 689.946 1749.97 689.946 1749.97 763 1779.5 c 0,117,118 + 836 1809.01 836 1809.01 1021 1775 c 0,119,120 + 1123.01 1755.99 1123.01 1755.99 1179 1697 c 0,121,122 + 1235 1638 1235 1638 1241 1590 c 0,123,124 + 1170.01 1684.01 1170.01 1684.01 1043 1644 c 0,125,126 + 1000.99 1630.99 1000.99 1630.99 980 1586.5 c 0,127,128 + 959 1541.99 959 1541.99 963 1495 c 0,129,130 + 972.959 1370.96 972.959 1370.96 1086.21 1370.29 c 0,131,132 + 1098.04 1370.22 1098.04 1370.22 1111 1371.5 c 0,133,134 + 1247.98 1385 1247.98 1385 1338 1414 c 0,135,136 + 1283 1338 1283 1338 1180 1315.5 c 0,137,138 + 1110.41 1300.3 1110.41 1300.3 1067.29 1300.39 c 0,139,140 + 1046.6 1300.43 1046.6 1300.43 1032 1304 c 0,141,142 + 943.012 1323.99 943.012 1323.99 902 1366.5 c 0,143,144 + 861 1408.99 861 1408.99 803 1461 c 0,145,146 + 761.569 1497.43 761.569 1497.43 707.898 1497.38 c 0,147,148 + 686.428 1497.36 686.428 1497.36 663 1491.5 c 0,149,150 + 580.997 1470.99 580.997 1470.99 545 1396 c 0,151,152 + 519 1340 519 1340 509.5 1233.5 c 0,153,154 + 508.766 1185.28 l 0,155,156 + 513.672 1116.51 513.672 1116.51 556 1084 c 0,157,158 + 651.097 1007.76 651.097 1007.76 701.05 1007.84 c 0,159,160 + 709.406 1007.85 709.406 1007.85 716.5 1010 c 0,161,162 + 766 1025 766 1025 839 1016 c 0,163,164 + 880 1010 880 1010 922 975 c 0,165,166 + 964 940 964 940 941 883 c 0,167,168 + 914 952 914 952 883 955.5 c 0,169,170 + 861.719 954.539 l 0,171,172 + 845.625 950.75 845.625 950.75 835 937 c 0,173,174 + 802 895 802 895 901.5 820 c 0,175,176 + 1001 745 1001 745 1040 733 c 0,177,178 + 1057.62 726.748 1057.62 726.748 1077.66 726.795 c 0,179,180 + 1092.88 726.831 1092.88 726.831 1109.5 730.5 c 0,181,182 + 1124.23 733.752 1124.23 733.752 1124.54 745.418 c 0,183,184 + 1120.41 761.043 l 0,185,186 + 1112.25 778.324 1112.25 778.324 1088 805 c 0,187,188 + 1169.99 797.002 1169.99 797.002 1178.5 720 c 0,189,190 + 1187.01 643 1187.01 643 1177 597 c 0,191,192 + 1168 559 1168 559 1154.5 451 c 0,193,194 + 1150.46 418.662 1150.46 418.662 1150.5 389.819 c 0,195,196 + 1150.58 322.343 1150.58 322.343 1173 274 c 0,197,198 + 1198 217.001 1198 217.001 1222.5 204 c 0,199,200 + 1247.01 190.994 1247.01 190.994 1261 104 c 0,201,202 + 1265.01 72.0001 1265.01 72.0001 1243 6.5 c 0,203,204 + 1220.99 -59.0006 1220.99 -59.0006 1146 -68 c 0,205,206 + 1159.01 -44 1159.01 -44 1198.5 14 c 0,207,208 + 1211.67 33.3338 1211.67 33.3338 1211.67 47.4445 c 0,209,210 + 1211.67 75.6671 1211.67 75.6671 1159 83 c 0,211,212 + 1127.99 86 1127.99 86 1099 43 c 0,213,214 + 1067 -5 l 0,215,216 + 1002.99 -102.001 1002.99 -102.001 853 -118.5 c 0,217,218 + 703 -135 703 -135 598 -86 c 0,0,1 +EndSplineSet +KernsSLIF: 69 52 0 0 101 39 0 0 83 -117 0 0 116 -182 0 0 84 -65 0 0 +EndChar +StartChar: T +Encoding: 84 84 83 +Width: 1699 +Flags: MW +HStem: 1371 258<399 1229> +VStem: 705 217.5<139 1333> +Fore +705 139 m 0,0,1 + 725.954 259.212 725.954 259.212 725.928 369.54 c 0,2,3 + 725.906 459.29 725.906 459.29 712 542.5 c 0,4,5 + 681 728 681 728 631 926 c 0,6,7 + 620 965 620 965 632 1042.5 c 0,8,9 + 643.026 1113.72 643.026 1113.72 696.275 1114.42 c 0,10,11 + 700.974 1114.49 700.974 1114.49 706 1114 c 0,12,13 + 697 1114 697 1114 684.5 1091.5 c 0,14,15 + 673.19 1071.14 673.19 1071.14 673 1060 c 0,16,17 + 675.939 1014.92 675.939 1014.92 711.5 1010 c 0,18,19 + 725.288 1011.93 l 0,20,21 + 744.108 1020.83 744.108 1020.83 744.233 1066.63 c 0,22,23 + 744.248 1072.06 744.248 1072.06 744 1078 c 0,24,25 + 743.001 1100.95 743.001 1100.95 742 1158.5 c 0,26,27 + 740.999 1216.01 740.999 1216.01 731.5 1272 c 0,28,29 + 722.001 1327.99 722.001 1327.99 700.5 1366.5 c 0,30,31 + 679 1405.01 679 1405.01 637 1392 c 0,32,33 + 622 1387.01 622 1387.01 530 1380 c 0,34,35 + 438 1372.99 438 1372.99 399 1371 c 0,36,37 + 356.557 1372.66 l 0,38,39 + 304.306 1379.74 304.306 1379.74 259.5 1412 c 0,40,41 + 218.599 1441.45 218.599 1441.45 218.597 1490.6 c 0,42,43 + 218.596 1516.55 218.596 1516.55 230 1548 c 0,44,45 + 230 1463.01 230 1463.01 275 1459 c 0,46,47 + 301.917 1458.98 l 0,48,49 + 336.366 1464.11 336.366 1464.11 336.475 1500.02 c 0,50,51 + 336.498 1507.58 336.498 1507.58 335 1516.5 c 0,52,53 + 324.001 1582 324.001 1582 287 1594 c 0,54,55 + 194 1622 194 1622 138 1627 c 0,56,57 + 106.672 1625.72 l 0,58,59 + 60.8195 1618.5 60.8195 1618.5 2 1581 c 0,60,61 + 24.9947 1632.99 24.9947 1632.99 83 1653.5 c 0,62,63 + 133.741 1671.44 133.741 1671.44 175.312 1671.38 c 0,64,65 + 181.25 1671.37 181.25 1671.37 187 1671 c 0,66,67 + 392.272 1652.98 392.272 1652.98 641 1626.5 c 0,68,69 + 817.488 1607.71 817.488 1607.71 957.858 1607.77 c 0,70,71 + 1015.48 1607.8 1015.48 1607.8 1067 1611 c 0,72,73 + 1160 1615.99 1160 1615.99 1229 1629 c 0,74,75 + 1270.13 1636.75 1270.13 1636.75 1317.67 1636.68 c 0,76,77 + 1349.86 1636.64 1349.86 1636.64 1385 1633 c 0,78,79 + 1485.29 1621 1485.29 1621 1485.65 1571.16 c 0,80,81 + 1485.72 1562.86 1485.72 1562.86 1483 1553.5 c 0,82,83 + 1467.25 1499.22 1467.25 1499.22 1464 1501 c 0,84,85 + 1459.01 1586.99 1459.01 1586.99 1387.5 1573 c 0,86,87 + 1316 1559.01 1316 1559.01 1307 1530 c 0,88,89 + 1302.26 1515.52 1302.26 1515.52 1302.17 1502.75 c 0,90,91 + 1302.07 1489.7 1302.07 1489.7 1306.81 1478.42 c 0,92,93 + 1315.06 1458.77 1315.06 1458.77 1338 1444.5 c 0,94,95 + 1387.01 1414.01 1387.01 1414.01 1450.5 1414.5 c 0,96,97 + 1513.99 1414.99 1513.99 1414.99 1566 1449.5 c 0,98,99 + 1608.59 1477.75 1608.59 1477.75 1608.92 1533.85 c 0,100,101 + 1608.99 1546.24 1608.99 1546.24 1607 1560 c 0,102,103 + 1611.51 1543.45 1611.51 1543.45 1611.5 1523.93 c 0,104,105 + 1611.47 1491.55 1611.47 1491.55 1599 1451 c 0,106,107 + 1579.01 1386.01 1579.01 1386.01 1484 1358 c 0,108,109 + 1393.64 1330.95 1393.64 1330.95 1315.57 1330.98 c 0,110,111 + 1249.36 1331 1249.36 1331 1192 1350.5 c 0,112,113 + 1067.01 1392.99 1067.01 1392.99 968 1394 c 0,114,115 + 923 1394 923 1394 922.5 1333 c 0,116,117 + 925.664 1227.25 l 0,118,119 + 926.274 1218.14 926.274 1218.14 927 1209 c 0,120,121 + 927 1208.01 927 1208.01 936 1130.5 c 0,122,123 + 944.999 1053.01 944.999 1053.01 1029 941 c 0,124,125 + 1068 889 1068 889 1047 764.5 c 0,126,127 + 1026 640 1026 640 928 653 c 0,128,129 + 992.426 653 992.426 653 992.628 741.926 c 0,130,131 + 992.648 751 992.648 751 992 761 c 0,132,133 + 985 869 985 869 935 827 c 0,134,135 + 899 797 899 797 892.5 771.5 c 0,136,137 + 886 746 886 746 891 671 c 0,138,139 + 901.999 494.004 901.999 494.004 941.5 392.5 c 0,140,141 + 975.036 306.325 975.036 306.325 975.054 132.577 c 0,142,143 + 975.057 101.673 975.057 101.673 974 68 c 0,144,145 + 968 -93.9994 968 -93.9994 861 -122 c 0,146,147 + 913.644 -62.4528 913.644 -62.4528 913.78 -24.1307 c 0,148,149 + 913.801 -18.048 913.801 -18.048 912.5 -12.5 c 0,150,151 + 903.001 27.9999 903.001 27.9999 869.5 34.5 c 0,152,153 + 836 41 836 41 801.5 11 c 0,154,155 + 767 -19 767 -19 779 -94 c 0,156,157 + 806 -273 806 -273 858.5 -319.5 c 0,158,159 + 911 -366 911 -366 944 -399 c 0,160,161 + 801 -369 801 -369 740.5 -184 c 0,162,163 + 697.607 -52.8381 697.607 -52.8381 697.69 54.6971 c 0,164,165 + 697.724 98.8389 697.724 98.8389 705 139 c 0,0,1 +EndSplineSet +KernsSLIF: 322 -391 0 0 321 -469 0 0 85 -117 0 0 117 -143 0 0 104 -234 0 0 72 -156 0 0 45 -300 0 0 46 -260 0 0 44 -260 0 0 243 -300 0 0 211 -208 0 0 115 -286 0 0 83 -260 0 0 111 -208 0 0 79 -143 0 0 65 -512 0 0 97 -512 0 0 +EndChar +StartChar: U +Encoding: 85 85 68 +Width: 1411 +Flags: W +Fore +46 241 m 0,0,1 + -23 339 -23 339 50.5 416.5 c 0,2,3 + 124 494 124 494 164 494 c 0,4,5 + 118.001 458.001 118.001 458.001 103.5 368.5 c 0,6,7 + 88.9999 279 88.9999 279 192 310 c 0,8,9 + 222 319 222 319 232 422 c 0,10,11 + 237.34 477.005 237.34 477.005 237.262 527.732 c 0,12,13 + 237.194 571.994 237.194 571.994 233 613 c 0,14,15 + 224 705 224 705 177.5 757 c 0,16,17 + 164.022 772.073 164.022 772.073 155.879 772.61 c 0,18,19 + 149.279 769.765 l 0,20,21 + 143.401 762.964 143.401 762.964 143.449 740.018 c 0,22,23 + 148 688 l 0,24,25 + 64 754 64 754 96 903 c 0,26,27 + 119.323 1011.6 119.323 1011.6 119.273 1144.11 c 0,28,29 + 119.254 1193.4 119.254 1193.4 116 1246 c 0,30,31 + 113.225 1341.01 l 0,32,33 + 115.265 1478.14 115.265 1478.14 156 1561.5 c 0,34,35 + 209.993 1671.99 209.993 1671.99 280 1722.5 c 0,36,37 + 350 1773.01 350 1773.01 410 1781 c 0,38,39 + 469.016 1789 l 0,40,41 + 469 1789 l 0,42,43 + 388 1774 388 1774 314.5 1694.5 c 0,44,45 + 240.996 1615 240.996 1615 209 1527 c 0,46,47 + 191.706 1479.44 191.706 1479.44 191.644 1438.16 c 0,48,49 + 191.592 1403.06 191.592 1403.06 204 1372.5 c 0,50,51 + 226.472 1317.16 226.472 1317.16 314.735 1316.87 c 0,52,53 + 332.531 1316.82 332.531 1316.82 353 1319 c 0,54,55 + 435 1328 435 1328 409.5 1419.5 c 0,56,57 + 386.796 1500.97 386.796 1500.97 317.708 1501.18 c 0,58,59 + 309.205 1501.2 309.205 1501.2 300 1500 c 0,60,61 + 328.11 1504.8 328.11 1504.8 351.378 1504.8 c 0,62,63 + 458.89 1504.76 458.89 1504.76 463 1402 c 0,64,65 + 468 1277.01 468 1277.01 444 1246 c 0,66,67 + 350.001 1126 350.001 1126 344.5 922 c 0,68,69 + 339 718 339 718 348 571 c 0,70,71 + 354 470.999 354 470.999 395.5 365 c 0,72,73 + 437 259 437 259 527 295 c 0,74,75 + 563 309.063 563 309.063 562.93 332.617 c 0,76,77 + 562.875 350.937 562.875 350.937 541 375 c 0,78,79 + 491 430 491 430 466 364 c 0,80,81 + 451 427 451 427 493.5 441.5 c 0,82,83 + 536 456 536 456 560 449 c 0,84,85 + 659 416 659 416 654 337 c 0,86,87 + 649.001 258.004 649.001 258.004 643 233 c 0,88,89 + 640.623 210.278 l 0,90,91 + 643.022 170.739 643.022 170.739 693.5 141 c 0,92,93 + 710.928 130.733 710.928 130.733 732.042 130.759 c 0,94,95 + 789.073 130.83 789.073 130.83 873 206 c 0,96,97 + 891 222.001 891 222.001 931 287.5 c 0,98,99 + 970.999 352.998 970.999 352.998 997.5 431 c 0,100,101 + 1024.01 509 1024.01 509 1017 580 c 0,102,103 + 1009.99 651.002 1009.99 651.002 934 679 c 0,104,105 + 883 697 883 697 885.5 635.5 c 0,106,107 + 888 574 888 574 932 546 c 0,108,109 + 829 595 829 595 823 689 c 0,110,111 + 817 783 817 783 850.5 898.5 c 0,112,113 + 884.003 1014.01 884.003 1014.01 929.5 1137.5 c 0,114,115 + 975 1261 975 1261 975 1369 c 0,116,117 + 975 1384.99 975 1384.99 996.5 1507.5 c 0,118,119 + 1014.74 1611.48 1014.74 1611.48 1106.84 1612.07 c 0,120,121 + 1142 1609 l 0,122,123 + 1114 1609 1114 1609 1084 1578 c 0,124,125 + 1065.83 1559.22 1065.83 1559.22 1065.63 1537.15 c 0,126,127 + 1065.54 1526.11 1065.54 1526.11 1069.93 1514.25 c 0,128,129 + 1071.26 1510.66 1071.26 1510.66 1073 1507 c 0,130,131 + 1097.08 1458.24 1097.08 1458.24 1127.69 1458.04 c 0,132,133 + 1143.25 1457.94 1143.25 1457.94 1160.49 1470.39 c 0,134,135 + 1165.67 1474.13 1165.67 1474.13 1171 1479 c 0,136,137 + 1199.69 1504.1 1199.69 1504.1 1199.8 1560.46 c 0,138,139 + 1199.87 1598.4 1199.87 1598.4 1187 1650.5 c 0,140,141 + 1160.61 1757.3 1160.61 1757.3 1045.79 1757.66 c 0,142,143 + 1021.39 1757.73 1021.39 1757.73 993 1753 c 0,144,145 + 1034.65 1774 1034.65 1774 1074.09 1774.11 c 0,146,147 + 1108.32 1774.21 1108.32 1774.21 1140.89 1758.58 c 0,148,149 + 1178.03 1740.77 1178.03 1740.77 1213 1702.5 c 0,150,151 + 1266.02 1644.49 1266.02 1644.49 1266.13 1556.31 c 0,152,153 + 1266.23 1476.51 1266.23 1476.51 1223 1372 c 0,154,155 + 1187.02 1285.05 1187.02 1285.05 1145.5 1165.5 c 0,156,157 + 1104 1046.01 1104 1046.01 1101 977 c 0,158,159 + 1102.08 933.908 l 0,160,161 + 1108.46 884.297 1108.46 884.297 1140.5 864.5 c 0,162,163 + 1185.01 837 1185.01 837 1224.5 853.5 c 0,164,165 + 1264.01 870.005 1264.01 870.005 1270.5 923 c 0,166,167 + 1269.24 946.944 l 0,168,169 + 1259.55 992.592 1259.55 992.592 1196 1053 c 0,170,171 + 1338.99 1039.01 1338.99 1039.01 1341.5 918 c 0,172,173 + 1338.83 854.387 l 0,174,175 + 1329.25 760.063 1329.25 760.063 1286.5 653 c 0,176,177 + 1229.01 509 1229.01 509 1151.5 384.5 c 0,178,179 + 1073.98 259.972 1073.98 259.972 1059 241 c 0,180,181 + 1020.99 192.985 1020.99 192.985 991 128 c 0,182,183 + 961 63.0001 961 63.0001 1048 81 c 0,184,185 + 1093 90 1093 90 1088.5 126 c 0,186,187 + 1084 161.999 1084 161.999 1069 208 c 0,188,189 + 1143.1 168.331 1143.1 168.331 1143.53 96.7311 c 0,190,191 + 1139.54 60.7425 l 0,192,193 + 1137.87 53.0215 1137.87 53.0215 1135.5 45 c 0,194,195 + 1102.99 -65.0001 1102.99 -65.0001 1012 -66 c 0,196,197 + 578 -72 578 -72 336.5 49.5 c 0,198,199 + 94.9995 171 94.9995 171 46 241 c 0,0,1 +EndSplineSet +KernsSLIF: 116 -78 0 0 84 -65 0 0 88 -130 0 0 +EndChar +StartChar: V +Encoding: 86 86 69 +Width: 1266 +Flags: W +Fore +346 1049 m 1,0,1 + 445 1021 445 1021 449 940.5 c 0,2,3 + 450.299 842.065 l 0,4,5 + 449.624 820.845 449.624 820.845 448 802 c 0,6,7 + 442 735 442 735 432.5 682.5 c 0,8,9 + 431.139 654.738 l 0,10,11 + 434.544 623.651 434.544 623.651 463 608 c 0,12,13 + 498 588 498 588 514.5 635 c 0,14,15 + 531 682 531 682 536 749 c 0,16,17 + 540.231 805.7 540.231 805.7 540.166 859.521 c 0,18,19 + 540.154 869.308 540.154 869.308 540 879 c 0,20,21 + 539 942 539 942 539 954 c 0,22,23 + 539 1034.01 539 1034.01 544.5 1098.5 c 0,24,25 + 550 1163 550 1163 574 1239 c 0,26,27 + 590.997 1292.99 590.997 1292.99 629.5 1337.5 c 0,28,29 + 667.985 1381.99 667.985 1381.99 699 1398 c 0,30,31 + 713.755 1401.18 l 0,32,33 + 723.716 1400.86 723.716 1400.86 734 1394 c 0,34,35 + 752 1382 752 1382 752 1369 c 0,36,37 + 698 1397.99 698 1397.99 700 1322.5 c 0,38,39 + 702 1247 702 1247 733 1247 c 0,40,41 + 765.998 1247 765.998 1247 779.5 1279 c 0,42,43 + 793 1310.99 793 1310.99 793 1337 c 0,44,45 + 793 1433 793 1433 808.5 1505 c 0,46,47 + 823.997 1576.99 823.997 1576.99 850 1667 c 0,48,49 + 857.997 1696.99 857.997 1696.99 884.5 1729.5 c 0,50,51 + 911.003 1762.01 911.003 1762.01 927 1776 c 0,52,53 + 956 1801.01 956 1801.01 1012.5 1800 c 0,54,55 + 1069 1798.99 1069 1798.99 1076 1765 c 0,56,57 + 1057.04 1782.69 1057.04 1782.69 1033.2 1782.91 c 0,58,59 + 1009.58 1779.2 l 0,60,61 + 986.018 1771.95 986.018 1771.95 958.5 1750.5 c 0,62,63 + 915 1716.6 915 1716.6 914.88 1673.88 c 0,64,65 + 914.8 1645.4 914.8 1645.4 934 1613 c 0,66,67 + 951.778 1582.33 951.778 1582.33 978.643 1582.38 c 0,68,69 + 1012.23 1582.44 1012.23 1582.44 1060 1630.5 c 0,70,71 + 1146 1717.01 1146 1717.01 1158 1756 c 0,72,73 + 1179.24 1823.78 1179.24 1823.78 1179.24 1871.65 c 0,74,75 + 1179.24 1929.72 1179.24 1929.72 1148 1958.5 c 0,76,77 + 1091 2011 1091 2011 1074 2028 c 0,78,79 + 1142.02 1994.99 1142.02 1994.99 1174 1955 c 0,80,81 + 1206 1914.99 1206 1914.99 1206 1828 c 0,82,83 + 1206 1746.01 1206 1746.01 1164 1676 c 0,84,85 + 1122 1605.99 1122 1605.99 1076 1552 c 0,86,87 + 964.997 1423 964.997 1423 911 1267.5 c 0,88,89 + 857 1111.99 857 1111.99 854 945 c 0,90,91 + 853 915 853 915 856 832 c 0,92,93 + 859 749 859 749 852.5 655 c 0,94,95 + 846.001 561.005 846.001 561.005 824.5 478 c 0,96,97 + 803 395 803 395 754 365 c 0,98,99 + 793 446 793 446 792.5 514 c 0,100,101 + 792 582 792 582 750 613 c 0,102,103 + 675 665 675 665 637 563 c 0,104,105 + 599 461 599 461 589 409 c 0,106,107 + 571 325 571 325 559 244.5 c 0,108,109 + 547 163.999 547 163.999 642 168 c 0,110,111 + 651 168 651 168 666 188.5 c 0,112,113 + 681 209.001 681 209.001 675 238 c 0,114,115 + 666 281 666 281 604 292 c 0,116,117 + 629.82 313.633 629.82 313.633 653.449 313.839 c 0,118,119 + 663.68 313.928 663.68 313.928 673.5 310 c 0,120,121 + 706.001 296.999 706.001 296.999 724 266 c 0,122,123 + 744.16 227.514 744.16 227.514 744.167 188.094 c 0,124,125 + 744.171 162.987 744.171 162.987 736 137.5 c 0,126,127 + 715 71.9999 715 71.9999 681 52 c 0,128,-1 + 575 -7.5 l 0,129,130 + 530 -32 530 -32 530 -128 c 0,131,132 + 530 -264.001 530 -264.001 624.5 -318.5 c 0,133,134 + 719 -373 719 -373 839 -367 c 0,135,136 + 744 -397 744 -397 654.5 -374.5 c 0,137,138 + 565 -352 565 -352 530 -313 c 0,139,140 + 412 -179.999 412 -179.999 410.5 -4 c 0,141,142 + 409 171.999 409 171.999 320 295 c 0,143,144 + 304 316 304 316 265 333 c 0,145,146 + 226 350 226 350 211 297 c 0,147,148 + 185.001 208.001 185.001 208.001 274 186 c 0,149,150 + 239.736 185.285 l 0,151,152 + 218.405 187.152 218.405 187.152 195 194.5 c 0,153,154 + 152.001 208 152.001 208 124 277 c 0,155,156 + 106.733 319 106.733 319 106.78 364.267 c 0,157,158 + 106.834 416 106.834 416 129.5 472 c 0,159,160 + 172 577.001 172 577.001 172 669 c 0,161,162 + 172 813.002 172 813.002 124.5 942.5 c 0,163,164 + 76.9999 1071.99 76.9999 1071.99 48 1208 c 0,165,166 + 39 1248.01 39 1248.01 22.5 1335.5 c 0,167,168 + 8.49056 1409.79 8.49056 1409.79 8.53863 1491.66 c 0,169,170 + 8.54717 1506.21 8.54717 1506.21 9 1521 c 0,171,172 + 10.9999 1588.01 10.9999 1588.01 45 1680 c 0,173,174 + 79.004 1772.01 79.004 1772.01 133 1780 c 0,175,176 + 110.001 1747 110.001 1747 92.5 1700.5 c 0,177,178 + 78.865 1664.27 78.865 1664.27 78.8889 1635.02 c 0,179,180 + 78.8957 1626.73 78.8957 1626.73 80 1619 c 0,181,182 + 92.9678 1535.64 92.9678 1535.64 186.577 1535.49 c 0,183,184 + 194.034 1535.48 194.034 1535.48 202 1536 c 0,185,186 + 257 1539 257 1539 266 1632.5 c 0,187,188 + 270.261 1713.86 l 0,189,190 + 270.153 1752.18 270.153 1752.18 265 1780 c 0,191,192 + 258 1814.01 258 1814.01 223 1843 c 0,193,194 + 187.993 1872 187.993 1872 152 1878 c 0,195,196 + 193.862 1879.28 l 0,197,198 + 284.127 1872.85 284.127 1872.85 312.5 1779.5 c 0,199,200 + 347 1665.99 347 1665.99 338 1592 c 0,201,202 + 329.999 1541.99 329.999 1541.99 303.5 1446 c 0,203,204 + 277.002 1350.01 277.002 1350.01 267 1293 c 0,205,206 + 263.07 1274.13 263.07 1274.13 263.156 1218.51 c 0,207,208 + 263.179 1203.37 263.179 1203.37 263.5 1185.5 c 0,209,210 + 265 1102.01 265 1102.01 276 1018.5 c 0,211,212 + 286.999 935.003 286.999 935.003 310 881 c 0,213,214 + 333 827 333 827 372 863 c 0,215,216 + 415 902 415 902 399 960.5 c 0,217,218 + 382.999 1019 382.999 1019 346 1049 c 1,0,1 +EndSplineSet +KernsSLIF: 214 -193 0 0 246 -224 0 0 111 -195 0 0 79 -156 0 0 45 -208 0 0 46 -247 0 0 44 -247 0 0 73 -104 0 0 105 -182 0 0 97 -321 0 0 65 -270 0 0 +EndChar +StartChar: W +Encoding: 87 87 11 +Width: 2018 +Flags: HW +Fore +1198 -258 m 0,0,1 + 1141 -241.001 1141 -241.001 1105 -191 c 0,2,3 + 1068.99 -140.988 1068.99 -140.988 1055 -100 c 0,4,5 + 1028 -25 1028 -25 1011.5 75 c 0,6,7 + 995 175 995 175 962 235 c 0,8,9 + 914 318 914 318 882 324 c 0,10,11 + 850 330 850 330 808 271 c 0,12,13 + 777.835 228.58 777.835 228.58 777.883 126.621 c 0,14,15 + 777.885 120.42 777.885 120.42 778 114 c 0,16,17 + 780 1.99995 780 1.99995 814 -37 c 0,18,19 + 839 -67 839 -67 899 -79 c 0,20,21 + 848.175 -107.756 848.175 -107.756 793.772 -107.666 c 0,22,23 + 766.825 -107.622 766.825 -107.622 739 -100.5 c 0,24,25 + 655 -79.0001 655 -79.0001 620 -45 c 0,26,27 + 586 -12 586 -12 561.5 25.5 c 0,28,29 + 537 63 537 63 513 105 c 0,30,31 + 485.998 152.002 485.998 152.002 472.5 171.5 c 0,32,33 + 459 190.999 459 190.999 402 210 c 0,34,35 + 384.54 209.64 l 0,36,37 + 369.5 205 l 0,38,39 + 349.001 197.001 349.001 197.001 345 185 c 0,40,41 + 321 119 321 119 383 104 c 0,42,43 + 344 84.9999 344 84.9999 314 110 c 0,44,45 + 284 135.001 284 135.001 281 163 c 0,46,47 + 273.557 211.38 273.557 211.38 273.604 252.976 c 0,48,49 + 273.646 289.62 273.646 289.62 279.5 321 c 0,50,51 + 292 388 292 388 314 462 c 0,52,53 + 357.094 610.435 357.094 610.435 357.085 756.122 c 0,54,55 + 357.085 762.561 357.085 762.561 357 769 c 0,56,57 + 355 920.999 355 920.999 289 1064 c 0,58,59 + 254.025 1136.95 254.025 1136.95 214 1204 c 0,60,61 + 174 1271 174 1271 171 1359 c 0,62,63 + 171.789 1419.71 l 0,64,65 + 181.716 1538.68 181.716 1538.68 263 1546 c 0,66,67 + 291.179 1544.62 l 0,68,69 + 330 1536.43 330 1536.43 330 1490 c 0,70,71 + 306 1512.01 306 1512.01 271.5 1497.5 c 0,72,73 + 249.617 1488.3 249.617 1488.3 249.661 1455.57 c 0,74,75 + 249.686 1436.7 249.686 1436.7 257 1410 c 0,76,77 + 266.64 1374.41 266.64 1374.41 302.395 1374 c 0,78,79 + 330.5 1378 l 0,80,81 + 391 1394.01 391 1394.01 391 1442 c 0,82,83 + 389.999 1546 389.999 1546 327 1586.5 c 0,84,85 + 264 1627 264 1627 190 1627 c 0,86,87 + 89.9968 1627 89.9968 1627 57 1575 c 0,88,89 + 24 1522.99 24 1522.99 9 1497 c 0,90,91 + 19 1585.99 19 1585.99 67 1623 c 0,92,93 + 114.993 1660 114.993 1660 196 1666 c 0,94,95 + 240.049 1665.23 l 0,96,97 + 302.45 1658.55 302.45 1658.55 356 1619.5 c 0,98,99 + 428 1567 428 1567 456 1513 c 0,100,101 + 534 1360 534 1360 502 1271.5 c 0,102,103 + 470 1183 470 1183 460 1017 c 0,104,105 + 457 966 457 966 456 896.5 c 0,106,107 + 455 827 455 827 489 788 c 0,108,109 + 521 752 521 752 541.5 763.5 c 0,110,111 + 560.877 774.37 560.877 774.37 561 800 c 0,112,113 + 559.001 821.999 559.001 821.999 553.5 841 c 0,114,115 + 548 860 548 860 494 864 c 0,116,117 + 527.206 880.794 527.206 880.794 554.148 880.98 c 0,118,119 + 568.225 881.078 568.225 881.078 580.592 876.641 c 0,120,121 + 606.569 867.323 606.569 867.323 625 838 c 0,122,123 + 648.561 798.453 648.561 798.453 648.756 767.399 c 0,124,125 + 648.793 761.549 648.793 761.549 648 756 c 0,126,127 + 643 721 643 721 637 688 c 0,128,129 + 618 590 618 590 617.5 538 c 0,130,131 + 617 486 617 486 659 456 c 0,132,133 + 686 435 686 435 741 542.5 c 0,134,135 + 796 650 796 650 820 704 c 0,136,137 + 846 761 846 761 873 797.5 c 0,138,139 + 900 834 900 834 984 873 c 0,140,141 + 934 801 934 801 920.5 759 c 0,142,143 + 907 717 907 717 919 639 c 0,144,145 + 925 592.001 925 592.001 942 552.5 c 0,146,147 + 959 513 959 513 999 509 c 0,148,149 + 1027.6 508.97 l 0,150,151 + 1090.09 517.856 1090.09 517.856 1127 608.5 c 0,152,153 + 1172 719 1172 719 1178 779 c 0,154,155 + 1179.01 791 1179.01 791 1199 889 c 0,156,157 + 1218.99 987 1218.99 987 1175 987 c 0,158,159 + 1148 987 1148 987 1139 958.5 c 0,160,161 + 1130 930 1130 930 1151 911 c 0,162,163 + 1104.99 919 1104.99 919 1104.5 966 c 0,164,165 + 1104.01 1013 1104.01 1013 1115 1031 c 0,166,167 + 1151 1088 1151 1088 1203 1129.5 c 0,168,169 + 1255.02 1171.01 1255.02 1171.01 1287 1210 c 0,170,171 + 1335 1270 1335 1270 1348.5 1294 c 0,172,173 + 1362 1318 1362 1318 1383 1381 c 0,174,175 + 1399.89 1431.69 1399.89 1431.69 1439.5 1540 c 0,176,177 + 1478.99 1647.99 1478.99 1647.99 1529 1698 c 0,178,179 + 1572.99 1741.99 1572.99 1741.99 1607 1759.5 c 0,180,181 + 1627.24 1769.92 1627.24 1769.92 1653.15 1769.88 c 0,182,183 + 1670.76 1769.86 1670.76 1769.86 1691 1765 c 0,184,-1 + 1607 1716.5 l 0,185,186 + 1567 1694 1567 1694 1543 1631 c 0,187,188 + 1528.58 1595.35 1528.58 1595.35 1528.56 1547.03 c 0,189,190 + 1528.55 1531.66 1528.55 1531.66 1530 1515 c 0,191,192 + 1536 1446 1536 1446 1594 1440 c 0,193,194 + 1663 1432.01 1663 1432.01 1721.5 1474.5 c 0,195,196 + 1779.99 1516.99 1779.99 1516.99 1808 1580 c 0,197,198 + 1825.98 1621.95 1825.98 1621.95 1847.5 1662.5 c 0,199,200 + 1868.99 1703 1868.99 1703 1864 1805 c 0,201,202 + 1858 1913 1858 1913 1703 1994 c 0,203,204 + 1884.99 1955 1884.99 1955 1910 1785 c 0,205,206 + 1914.52 1754.1 1914.52 1754.1 1914.43 1721.43 c 0,207,208 + 1914.28 1667.39 1914.28 1667.39 1901.5 1608.5 c 0,209,210 + 1881 1514.01 1881 1514.01 1819 1444 c 0,211,212 + 1731 1344 1731 1344 1622 1262 c 0,213,214 + 1579.99 1230 1579.99 1230 1512 1140.5 c 0,215,216 + 1444.01 1050.99 1444.01 1050.99 1491 995 c 0,217,218 + 1503 980 1503 980 1533 987 c 0,219,220 + 1562.99 993.999 1562.99 993.999 1570 1021 c 0,221,222 + 1575.85 1043.49 1575.85 1043.49 1575.93 1057.9 c 0,223,224 + 1576.02 1075.5 1576.02 1075.5 1567.5 1081 c 0,225,-1 + 1530 1106 l 0,226,227 + 1561.81 1109.98 l 0,228,229 + 1606.38 1109.6 1606.38 1109.6 1617 1067.5 c 0,230,231 + 1624.51 1037.74 1624.51 1037.74 1624.54 1010.13 c 0,232,233 + 1624.56 986.259 1624.56 986.259 1619 964 c 0,234,235 + 1601 892 1601 892 1535 861 c 0,236,237 + 1469.01 830.005 1469.01 830.005 1417 786 c 0,238,239 + 1355.99 735 1355.99 735 1307.5 681 c 0,240,241 + 1259 626.993 1259 626.993 1247 548 c 0,242,243 + 1240.43 507.416 1240.43 507.416 1240.43 473.856 c 0,244,245 + 1240.44 420.581 1240.44 420.581 1257 385 c 0,246,-1 + 1322 239 l 0,247,248 + 1349.01 173.984 1349.01 173.984 1357 99.5 c 0,249,250 + 1356.76 63.9884 l 0,251,252 + 1349.8 2.65468 1349.8 2.65468 1299 -72 c 0,253,254 + 1299 -39.0261 1299 -39.0261 1313 33 c 0,255,256 + 1326.99 105 1326.99 105 1259 147 c 0,257,258 + 1243.74 155.902 1243.74 155.902 1229.44 156.01 c 0,259,260 + 1217.62 156.1 1217.62 156.1 1206.45 150.18 c 0,261,262 + 1188.64 140.736 1188.64 140.736 1172.5 116 c 0,263,264 + 1134 57.0082 1134 57.0082 1131 -57 c 0,265,266 + 1133.57 -92.4594 l 0,267,268 + 1139.35 -124.071 1139.35 -124.071 1157.5 -157.5 c 0,269,270 + 1186 -210.003 1186 -210.003 1232 -232 c 0,271,272 + 1277 -253.001 1277 -253.001 1373 -255 c 0,273,274 + 1341.01 -271 1341.01 -271 1289 -270 c 0,275,276 + 1237 -269 1237 -269 1198 -258 c 0,0,1 +EndSplineSet +KernsSLIF: 214 -180 0 0 246 -212 0 0 322 -469 0 0 321 -508 0 0 72 -260 0 0 104 -300 0 0 45 -234 0 0 46 -326 0 0 44 -364 0 0 115 -326 0 0 83 -260 0 0 105 -182 0 0 73 -91 0 0 243 -313 0 0 211 -365 0 0 111 -273 0 0 79 -221 0 0 196 -313 0 0 228 -270 0 0 261 -342 0 0 260 -342 0 0 97 -449 0 0 65 -398 0 0 +EndChar +StartChar: X +Encoding: 88 88 29 +Width: 1415 +Flags: HW +Fore +760 1490 m 0,0,1 + 714 1479.88 714 1479.88 713.706 1446.06 c 0,2,3 + 714 1440 l 0,4,5 + 718 1402.01 718 1402.01 718 1401 c 0,6,7 + 668 1425 668 1425 677 1494 c 0,8,9 + 684.998 1557.99 684.998 1557.99 760 1577 c 0,10,11 + 801.957 1587.98 801.957 1587.98 857.5 1609 c 0,12,13 + 913 1630 913 1630 949 1654 c 0,14,15 + 964.003 1663 964.003 1663 980 1697 c 0,16,17 + 995.999 1731 995.999 1731 1000 1751 c 0,18,19 + 1004.07 1771.56 1004.07 1771.56 1004.04 1788.43 c 0,20,21 + 1003.92 1854.44 1003.92 1854.44 941 1864 c 0,22,23 + 966.36 1866.94 l 0,24,25 + 988.032 1865.85 988.032 1865.85 1004.5 1851 c 0,26,27 + 1030 1828.01 1030 1828.01 1030 1798 c 0,28,29 + 1030 1772.94 1030 1772.94 1023 1683.5 c 0,30,31 + 1021.96 1629.04 l 0,32,33 + 1024.61 1594 1024.61 1594 1039 1594 c 0,34,35 + 1071 1594 1071 1594 1092 1637 c 0,36,37 + 1115.99 1692.98 1115.99 1692.98 1117 1744.5 c 0,38,39 + 1118.01 1796.02 1118.01 1796.02 1140 1845 c 0,40,41 + 1161.01 1890.01 1161.01 1890.01 1202.5 1920.5 c 0,42,43 + 1237.05 1945.88 1237.05 1945.88 1267.77 1945.99 c 0,44,45 + 1273.96 1946.01 1273.96 1946.01 1280 1945 c 0,46,47 + 1246.99 1934 1246.99 1934 1221 1903 c 0,48,49 + 1195 1871.99 1195 1871.99 1195 1851 c 0,50,51 + 1195 1802 1195 1802 1249 1802 c 0,52,53 + 1272 1802 1272 1802 1280.5 1824 c 0,54,55 + 1285.39 1836.65 1285.39 1836.65 1285.48 1847.98 c 0,56,57 + 1285.55 1856.35 1285.55 1856.35 1283 1864 c 0,58,59 + 1322 1859.99 1322 1859.99 1322 1811.5 c 0,60,61 + 1322 1762.99 1322 1762.99 1310 1743 c 0,62,63 + 1292 1713 1292 1713 1253 1672.5 c 0,64,65 + 1213.92 1631.92 1213.92 1631.92 1189 1609 c 0,66,-1 + 1070 1500 l 0,67,68 + 975.004 1414 975.004 1414 945 1346 c 0,69,70 + 928.994 1309.99 928.994 1309.99 891 1189 c 0,71,72 + 874.988 1138.01 874.988 1138.01 874.956 1101.76 c 0,73,74 + 874.912 1051.98 874.912 1051.98 905 1030 c 0,75,76 + 919.654 1018.16 919.654 1018.16 935.262 1018.24 c 0,77,78 + 947.346 1018.3 947.346 1018.3 960 1025.5 c 0,79,80 + 989.007 1042 989.007 1042 1001 1058 c 0,81,82 + 1029.99 1095.99 1029.99 1095.99 999.5 1122.5 c 0,83,84 + 969 1149.01 969 1149.01 947 1151 c 0,85,86 + 966.65 1157.25 966.65 1157.25 984.599 1157.22 c 0,87,88 + 1006.85 1157.19 1006.85 1157.19 1026.5 1147.5 c 0,89,90 + 1062 1130 1062 1130 1068 1110 c 0,91,92 + 1076.18 1081.05 1076.18 1081.05 1076.24 1057.88 c 0,93,94 + 1076.34 1019.14 1076.34 1019.14 1053.71 996.609 c 0,95,96 + 1046.89 989.817 1046.89 989.817 1038 984.5 c 0,97,98 + 981.995 950.994 981.995 950.994 928 898 c 0,99,100 + 874 844 874 844 871.5 803 c 0,101,102 + 869 762 869 762 875 720 c 0,103,104 + 884 659 884 659 935 574.5 c 0,105,106 + 986.02 489.967 986.02 489.967 1051.5 404.5 c 0,107,-1 + 1181 243 l 0,108,-1 + 1280 125 l 0,109,110 + 1306.99 91.0083 1306.99 91.0083 1326 11.5 c 0,111,112 + 1345.01 -68 1345.01 -68 1302 -109 c 0,113,114 + 1315.29 -83.1647 1315.29 -83.1647 1315.22 -54.808 c 0,115,116 + 1315.11 -6.33775 1315.11 -6.33775 1276 49.5 c 0,117,118 + 1214.01 137.998 1214.01 137.998 1155 149 c 0,119,120 + 1125.06 150.232 l 0,121,122 + 1088.17 146.304 1088.17 146.304 1077.5 111 c 0,123,124 + 1070.42 87.5735 1070.42 87.5735 1070.37 67.0018 c 0,125,126 + 1070.32 45.43 1070.32 45.43 1078 27 c 0,127,128 + 1121.01 -73 1121.01 -73 1192 -106.5 c 0,129,130 + 1263 -140 1263 -140 1331 -140.5 c 0,131,132 + 1395.74 -137.331 l 0,133,134 + 1424.13 -134.077 1424.13 -134.077 1448 -127.5 c 0,135,136 + 1479 -118.959 1479 -118.959 1490.39 -119.024 c 0,137,138 + 1497 -119.061 1497 -119.061 1497 -122 c 0,139,140 + 1387.98 -157.22 1387.98 -157.22 1301.63 -157.28 c 0,141,142 + 1233.52 -157.327 1233.52 -157.327 1179.5 -135.5 c 0,143,144 + 1057 -86.0024 1057 -86.0024 1009 38 c 0,145,146 + 980.998 110.003 980.998 110.003 940 229.5 c 0,147,148 + 899 349 899 349 868 352 c 0,149,150 + 804 358 804 358 804 299 c 0,151,152 + 804 263 804 263 821.5 256.5 c 0,153,154 + 833.616 252 833.616 252 844.533 252.053 c 0,155,156 + 849.385 252.077 849.385 252.077 854 253 c 0,157,158 + 835.564 229.6 835.564 229.6 815.619 229.581 c 0,159,160 + 807.436 229.573 807.436 229.573 799 233.5 c 0,161,162 + 770 247.001 770 247.001 758 272 c 0,163,164 + 731.999 325.002 731.999 325.002 727 386 c 0,165,166 + 722 447 722 447 722 518 c 0,167,168 + 722 542 722 542 711 588.5 c 0,169,170 + 700 635 700 635 667 639 c 0,171,172 + 590 648 590 648 536.5 513 c 0,173,174 + 499.347 419.251 499.347 419.251 499.087 386.264 c 0,175,176 + 498.992 374.272 498.992 374.272 506 369 c 0,177,178 + 527 361 527 361 548 384 c 0,179,180 + 572 408 572 408 537 446 c 0,181,182 + 558 446 558 446 574.5 422.5 c 0,183,184 + 591 399 591 399 591 378 c 0,185,186 + 591 338 591 338 558.5 289 c 0,187,188 + 526 240 526 240 485 229 c 0,189,190 + 431 215.001 431 215.001 385 185.5 c 0,191,192 + 339 155.999 339 155.999 327 100 c 0,193,194 + 313.005 37.0199 313.005 37.0199 297.5 -20 c 0,195,196 + 282 -77 282 -77 255 -114 c 0,197,198 + 243 -129 243 -129 201.5 -141 c 0,199,200 + 179.007 -147.504 179.007 -147.504 161.656 -147.545 c 0,201,202 + 146.992 -147.58 146.992 -147.58 136 -143 c 0,203,204 + 195 -134 195 -134 224 -81 c 0,205,206 + 242.001 -46.999 242.001 -46.999 242.5 20 c 0,207,208 + 242.999 87.0001 242.999 87.0001 187 87 c 0,209,210 + 124 87 124 87 90 12.5 c 0,211,212 + 55.9999 -62 55.9999 -62 56 -116 c 0,213,214 + 56 -207.001 56 -207.001 149 -254 c 0,215,216 + 80 -254 80 -254 48.5 -209 c 0,217,218 + 17 -164 17 -164 14 -116 c 0,219,220 + 3 2.00005 3 2.00005 77 106 c 0,221,222 + 112.997 157.997 112.997 157.997 232 284 c 0,223,224 + 351 410 351 410 349 463 c 0,225,226 + 347 495 347 495 306 495 c 0,227,228 + 284.978 495 284.978 495 284.5 472.5 c 0,229,230 + 284.999 450.002 284.999 450.002 293 440 c 0,231,232 + 269 433 269 433 245.5 460 c 0,233,234 + 221.999 487 221.999 487 247 535 c 0,235,236 + 267 574 267 574 325.5 608 c 0,237,238 + 384.003 642.002 384.003 642.002 417 673 c 0,239,240 + 450.002 704.002 450.002 704.002 490.5 765 c 0,241,242 + 531 826 531 826 531 877 c 0,243,244 + 531 910 531 910 503 924 c 0,245,246 + 475 938 475 938 448 938 c 0,247,248 + 379.456 935.397 379.456 935.397 378.665 895.53 c 0,249,250 + 380 882.5 l 0,251,252 + 391 830 391 830 421 830 c 0,253,254 + 369 821 369 821 328 845 c 0,255,256 + 287 869 287 869 287 926 c 0,257,258 + 287 970 287 970 312 1017.5 c 0,259,260 + 337.001 1065.01 337.001 1065.01 347 1104 c 0,261,262 + 355 1140 355 1140 355.5 1190 c 0,263,264 + 356 1239.99 356 1239.99 344 1274 c 0,265,266 + 319.003 1339.99 319.003 1339.99 266 1395 c 0,267,268 + 213 1450.01 213 1450.01 213 1535 c 0,269,270 + 213 1557.99 213 1557.99 237.5 1602.5 c 0,271,272 + 261.997 1647 261.997 1647 302 1647 c 0,273,274 + 263 1609.99 263 1609.99 263 1559 c 0,275,276 + 263 1544.99 263 1544.99 276 1522 c 0,277,278 + 289.003 1499 289.003 1499 310 1499 c 0,279,280 + 374 1499 374 1499 374 1562 c 0,281,282 + 374 1752.53 374 1752.53 219.724 1752.48 c 0,283,284 + 212.053 1752.47 212.053 1752.47 204 1752 c 0,285,286 + 247.833 1765.11 247.833 1765.11 282.611 1765.1 c 0,287,288 + 340.669 1765.08 340.669 1765.08 373.5 1728.5 c 0,289,290 + 426.001 1670 426.001 1670 448 1582 c 0,291,292 + 466 1505.99 466 1505.99 475.5 1424.5 c 0,293,294 + 485.001 1342.99 485.001 1342.99 506 1269 c 0,295,296 + 515.003 1235.99 515.003 1235.99 552 1178.5 c 0,297,298 + 581.04 1133.37 581.04 1133.37 613.156 1132.9 c 0,299,300 + 631 1136 l 0,301,302 + 680.005 1152.01 680.005 1152.01 722.5 1212 c 0,303,304 + 765 1272 765 1272 783 1320 c 0,305,306 + 789 1336.01 789 1336.01 801.5 1419 c 0,307,308 + 803.564 1454.98 l 0,309,310 + 800.907 1490.88 800.907 1490.88 773.555 1491.5 c 0,311,312 + 760 1490 l 0,0,1 +EndSplineSet +KernsSLIF: 45 -208 0 0 +EndChar +StartChar: Y +Encoding: 89 89 17 +Width: 1321 +Flags: MW +VStem: 406 327<-12 893> +Fore +587 -427 m 1,0,1 + 650 -373 650 -373 691.5 -193 c 0,2,3 + 733 -13 733 -13 673 39 c 0,4,5 + 647 61 647 61 574 65.5 c 0,6,7 + 501 70 501 70 520 10 c 0,8,9 + 531 -25 531 -25 563.5 -31 c 0,10,11 + 591.368 -32.2583 l 0,12,13 + 609.425 -30.504 609.425 -30.504 627 -22 c 0,14,15 + 627 -68 627 -68 526 -76 c 0,16,17 + 425 -83.9999 425 -83.9999 406 -12 c 0,18,19 + 398.427 14.7027 398.427 14.7027 398.479 42.0412 c 0,20,21 + 398.558 83.2966 398.558 83.2966 416 126 c 0,22,23 + 445 197.002 445 197.002 469 265 c 0,24,25 + 474.004 280.013 474.004 280.013 489.5 337.5 c 0,26,27 + 505 395.003 505 395.003 515.5 458.5 c 0,28,29 + 525.179 517.032 525.179 517.032 525.086 565.366 c 0,30,31 + 525.078 569.468 525.078 569.468 525 573.5 c 0,32,33 + 524 625.001 524 625.001 496 630 c 0,34,35 + 473.874 629.028 l 0,36,37 + 461.395 626.368 461.395 626.368 448.5 619 c 0,38,39 + 425.042 605.596 425.042 605.596 425 572 c 0,40,41 + 425 548 425 548 473 539 c 0,42,43 + 435 526 435 526 387.5 534.5 c 0,44,45 + 340 543 340 543 324 580 c 0,46,47 + 317.399 594.852 317.399 594.852 317.497 610.957 c 0,48,49 + 317.697 643.648 317.697 643.648 345.5 681.5 c 0,50,51 + 387 738 387 738 398 783 c 0,52,53 + 404.119 810.154 404.119 810.154 404.095 837.382 c 0,54,55 + 404.056 881.345 404.056 881.345 388 925.5 c 0,56,57 + 362 997 362 997 319 1042 c 0,58,59 + 310.857 1049.71 310.857 1049.71 301.979 1049.9 c 0,60,61 + 289.326 1046.54 l 0,62,63 + 283.314 1043.31 283.314 1043.31 277 1037 c 0,64,65 + 263.787 1023.79 263.787 1023.79 263.445 1010.25 c 0,66,67 + 267.068 995.034 l 0,68,69 + 268.318 992.522 268.318 992.522 270 990 c 0,70,71 + 282 972 282 972 290.5 967 c 0,72,73 + 299 962 299 962 341 962 c 0,74,75 + 333.001 943 333.001 943 281.5 940 c 0,76,77 + 245.179 941.292 l 0,78,79 + 219.509 945.159 219.509 945.159 203 958 c 0,80,81 + 158 992 158 992 173 1067 c 0,82,83 + 188 1142 188 1142 188 1190 c 0,84,85 + 188 1298 188 1298 111 1360 c 0,86,87 + 34.0009 1421.99 34.0009 1421.99 19 1521 c 0,88,89 + 14.7895 1547.84 14.7895 1547.84 14.8726 1575.69 c 0,90,91 + 15.1051 1653.65 15.1051 1653.65 49 1739.5 c 0,92,93 + 94.9978 1856 94.9978 1856 234 1913 c 0,94,95 + 139.993 1851.99 139.993 1851.99 89.5 1755 c 0,96,97 + 39 1657.99 39 1657.99 84 1557 c 0,98,99 + 113.309 1491.05 113.309 1491.05 188.767 1490.96 c 0,100,101 + 195.689 1490.95 195.689 1490.95 203 1491.5 c 0,102,103 + 289.995 1497.99 289.995 1497.99 332 1546 c 0,104,105 + 346.769 1562.25 346.769 1562.25 346.875 1578.25 c 0,106,107 + 346.974 1593.24 346.974 1593.24 334.206 1608.02 c 0,108,109 + 332.918 1609.51 332.918 1609.51 331.5 1611 c 0,110,111 + 310.872 1632.64 310.872 1632.64 278.582 1632.79 c 0,112,113 + 263.126 1632.86 263.126 1632.86 245 1628 c 0,114,115 + 281 1653.99 281 1653.99 325.5 1653.5 c 0,116,117 + 369.993 1653.01 369.993 1653.01 392 1635 c 0,118,119 + 421.654 1608.64 421.654 1608.64 421.779 1569.91 c 0,120,121 + 421.843 1549.86 421.843 1549.86 414 1526.5 c 0,122,123 + 391.987 1460.93 391.987 1460.93 391.958 1414.16 c 0,124,125 + 391.957 1412.06 391.957 1412.06 392 1410 c 0,126,127 + 393 1358.01 393 1358.01 402.5 1279 c 0,128,129 + 411.998 1200.01 411.998 1200.01 433.5 1129.5 c 0,130,131 + 455.002 1058.99 455.002 1058.99 490.5 1016.5 c 0,132,133 + 526 974 526 974 580 997 c 0,134,135 + 623.004 1015 623.004 1015 668 1086.5 c 0,136,137 + 713.005 1158.01 713.005 1158.01 722 1192 c 0,138,139 + 722.967 1213.49 l 0,140,141 + 720.821 1232.68 720.821 1232.68 709.5 1259 c 0,142,143 + 697.668 1286.51 697.668 1286.51 678.264 1287.01 c 0,144,145 + 662.531 1283.53 l 0,146,147 + 658.396 1281.73 658.396 1281.73 654 1279 c 0,148,149 + 623 1259.99 623 1259.99 644 1238.5 c 0,150,151 + 665.005 1217 665.005 1217 689 1217 c 0,152,153 + 668.538 1203.36 668.538 1203.36 648.887 1203.12 c 0,154,155 + 628.401 1206.6 l 0,156,157 + 623.929 1208.19 623.929 1208.19 619.5 1210.5 c 0,158,159 + 586 1228.01 586 1228.01 580 1254 c 0,160,161 + 577.345 1283.47 l 0,162,163 + 580.493 1350.79 580.493 1350.79 672.5 1397 c 0,164,165 + 783.992 1452.99 783.992 1452.99 842 1519 c 0,166,167 + 883.993 1565.99 883.993 1565.99 911.5 1631 c 0,168,169 + 939.004 1696.01 939.004 1696.01 975 1747 c 0,170,-1 + 1009 1799 l 0,171,172 + 1034.59 1838.13 1034.59 1838.13 1076.6 1838.19 c 0,173,174 + 1090.41 1838.21 1090.41 1838.21 1106 1834 c 0,175,176 + 1048 1818 1048 1818 1029 1767.5 c 0,177,178 + 1023.79 1753.67 1023.79 1753.67 1023.77 1741.52 c 0,179,180 + 1023.69 1709.34 1023.69 1709.34 1060 1689 c 0,181,182 + 1070.52 1682.59 1070.52 1682.59 1083.77 1682.47 c 0,183,184 + 1107.18 1686.44 l 0,185,186 + 1112.9 1688.29 1112.9 1688.29 1119 1691 c 0,187,188 + 1155.02 1707.01 1155.02 1707.01 1164 1717 c 0,189,190 + 1211.36 1773.83 1211.36 1773.83 1211.75 1816.12 c 0,191,192 + 1208.36 1838.44 l 0,193,194 + 1199.16 1866.33 1199.16 1866.33 1165 1886.5 c 0,195,196 + 1070.99 1942.01 1070.99 1942.01 1047 1951 c 0,197,198 + 1137.99 1935 1137.99 1935 1181 1897 c 0,199,200 + 1223.99 1859.02 1223.99 1859.02 1227 1853 c 0,201,202 + 1246.97 1809.61 1246.97 1809.61 1247.02 1775.71 c 0,203,204 + 1247.05 1760.39 1247.05 1760.39 1243 1747 c 0,205,206 + 1229.99 1703.99 1229.99 1703.99 1186 1636 c 0,207,208 + 1142.01 1570.01 1142.01 1570.01 1043 1495 c 0,209,210 + 944 1420 944 1420 935 1345 c 0,211,212 + 926 1282 926 1282 945.5 1214.5 c 0,213,214 + 965 1147 965 1147 967 1084 c 0,215,216 + 967 1054 967 1054 943.5 963 c 0,217,218 + 920 872 920 872 815 866 c 0,219,220 + 857 879 857 879 883.5 956.5 c 0,221,222 + 889.484 974.001 889.484 974.001 889.681 987.55 c 0,223,224 + 886.68 1005.75 l 0,225,226 + 875.526 1034 875.526 1034 823 1034 c 0,227,228 + 771 1034 771 1034 752 980 c 0,229,230 + 733 926 733 926 733 893 c 0,231,232 + 733 811.001 733 811.001 801 798 c 0,233,234 + 834.18 791.758 834.18 791.758 860.508 791.83 c 0,235,236 + 914.319 791.977 914.319 791.977 939.5 818.5 c 0,237,238 + 960.695 840.826 960.695 840.826 960.646 863.631 c 0,239,240 + 960.608 881.174 960.608 881.174 948 899 c 0,241,242 + 978 896 978 896 989.5 866 c 0,243,244 + 1001 836 1001 836 997 821 c 0,245,246 + 961 701 961 701 866.5 644.5 c 0,247,248 + 772 588 772 588 736 460 c 0,249,250 + 723.002 415.009 723.002 415.009 713 360 c 0,251,252 + 703 305 703 305 703 257 c 0,253,254 + 703 207.999 703 207.999 723.5 154.5 c 0,255,256 + 744.007 100.984 744.007 100.984 763 57 c 0,257,258 + 807 -46.0001 807 -46.0001 731.5 -214 c 0,259,260 + 656 -382 656 -382 587 -427 c 1,0,1 +EndSplineSet +KernsSLIF: 79 -91 0 0 111 -182 0 0 321 -313 0 0 83 -260 0 0 45 -195 0 0 46 -234 0 0 44 -234 0 0 97 -427 0 0 65 -385 0 0 +EndChar +StartChar: Z +Encoding: 90 90 30 +Width: 1724 +Flags: HMW +HStem: 39.5 156<312 1458.5> 1435 135<408 1265> +Fore +237 -220 m 0,0,1 + 177 -220 177 -220 153.5 -186 c 0,2,3 + 130.001 -152.001 130.001 -152.001 126 -106 c 0,4,5 + 124.999 -98.9995 124.999 -98.9995 130.5 -45 c 0,6,7 + 136.001 9.00019 136.001 9.00019 178 20 c 0,8,9 + 160 3.8147e-06 160 3.8147e-06 154 -37 c 0,10,11 + 153.534 -61.664 l 0,12,13 + 156.519 -80.2962 156.519 -80.2962 171 -91 c 0,14,15 + 195.849 -108.749 195.849 -108.749 220.619 -108.763 c 0,16,17 + 258.651 -108.785 258.651 -108.785 296.5 -67 c 0,18,19 + 359 2 359 2 350 74 c 0,20,21 + 341 140 341 140 312 195.5 c 0,22,23 + 284.062 248.969 284.062 248.969 283.967 326.1 c 0,24,25 + 283.963 329.032 283.963 329.032 284 332 c 0,26,27 + 284 367 284 367 308.5 416 c 0,28,29 + 332.999 464.999 332.999 464.999 375 475 c 0,30,31 + 386 478 386 478 412.5 479 c 0,32,33 + 439 480 439 480 445 464 c 0,34,35 + 421 479 421 479 380 457.5 c 0,36,37 + 339 436 339 436 336 411 c 0,38,39 + 333 384 333 384 340 349 c 0,40,41 + 347 314 347 314 386 314 c 0,42,43 + 433 314 433 314 491 438 c 0,44,45 + 549 562 549 562 561 604 c 0,46,47 + 588.999 708.994 588.999 708.994 597.5 802.5 c 0,48,49 + 606.002 896.013 606.002 896.013 622 989 c 0,50,51 + 626.002 1016.01 626.002 1016.01 642 1055.5 c 0,52,53 + 658 1094.99 658 1094.99 679 1114 c 0,54,55 + 732.993 1163 732.993 1163 790 1170.5 c 0,56,57 + 847 1178 847 1178 861 1157 c 0,58,59 + 839.005 1159.27 l 0,60,61 + 804.088 1157.18 804.088 1157.18 761.5 1121 c 0,62,63 + 729.029 1093.41 729.029 1093.41 728.761 1068.8 c 0,64,65 + 728.666 1060.01 728.666 1060.01 732.68 1051.59 c 0,66,67 + 736.981 1042.58 736.981 1042.58 746 1034 c 0,68,69 + 758.751 1021.72 758.751 1021.72 775.514 1021.82 c 0,70,71 + 794.252 1021.93 794.252 1021.93 818 1037.5 c 0,72,73 + 863 1067.01 863 1067.01 878 1087 c 0,74,-1 + 938.5 1169.5 l 0,75,76 + 971.986 1215.98 971.986 1215.98 996 1257 c 0,77,78 + 1019.99 1299.98 1019.99 1299.98 1034.5 1347 c 0,79,80 + 1037.69 1368.81 l 0,81,82 + 1036.86 1402.8 1036.86 1402.8 998 1431 c 0,83,84 + 953.018 1461.99 953.018 1461.99 882 1470.5 c 0,85,86 + 811.043 1479 811.043 1479 758 1479 c 0,87,88 + 637.993 1479 637.993 1479 585 1440.5 c 0,89,-1 + 461 1347 l 0,90,91 + 452 1341 452 1341 431.5 1324.5 c 0,92,93 + 411 1308 411 1308 399 1308 c 0,94,95 + 373 1306.01 373 1306.01 328.5 1318.5 c 0,96,97 + 284 1330.99 284 1330.99 273 1377 c 0,98,99 + 281.997 1358 281.997 1358 348.5 1347.5 c 0,100,101 + 370.966 1347.4 l 0,102,103 + 408.317 1354.47 408.317 1354.47 408.663 1416.16 c 0,104,105 + 408.713 1425.02 408.713 1425.02 408 1435 c 0,106,107 + 402.001 1507.99 402.001 1507.99 309.5 1513.5 c 0,108,109 + 225.463 1515.21 l 0,110,111 + 196.474 1514.14 196.474 1514.14 179 1510 c 0,112,113 + 52.0235 1476.53 52.0235 1476.53 51.5 1402.5 c 0,114,115 + 52 1292 l 0,116,117 + 29.2774 1353.48 29.2774 1353.48 29.1846 1400.28 c 0,118,119 + 29.0851 1450.43 29.0851 1450.43 54.9838 1483.72 c 0,120,121 + 59.1549 1489.08 59.1549 1489.08 64 1494 c 0,122,123 + 126.992 1558 126.992 1558 183 1576 c 0,124,125 + 251.935 1596.94 251.935 1596.94 326.223 1596.94 c 0,126,127 + 337.056 1596.94 337.056 1596.94 348 1596.5 c 0,128,129 + 433.929 1593.01 433.929 1593.01 515 1584 c 0,130,131 + 572 1578 572 1578 630.5 1582.5 c 0,132,133 + 673.739 1585.83 673.739 1585.83 674.092 1615.65 c 0,134,135 + 669.821 1637.75 l 0,136,137 + 669.427 1638.86 669.427 1638.86 669 1640 c 0,138,139 + 656.558 1671.11 656.558 1671.11 625.717 1671.15 c 0,140,141 + 611.944 1671.17 611.944 1671.17 594.5 1665 c 0,142,143 + 538.001 1645.01 538.001 1645.01 534 1629 c 0,144,145 + 532.47 1656.34 l 0,146,147 + 534.846 1679.14 534.846 1679.14 551 1694 c 0,148,149 + 576.009 1717 576.009 1717 597 1723 c 0,150,151 + 636 1732 636 1732 696 1727.5 c 0,152,153 + 755.989 1723 755.989 1723 794 1703 c 0,154,-1 + 917 1635.5 l 0,155,156 + 983.989 1598.01 983.989 1598.01 1039 1585 c 0,157,158 + 1102 1570 1102 1570 1150.5 1568.5 c 0,159,160 + 1260.41 1569.8 l 0,161,162 + 1262.69 1569.9 1262.69 1569.9 1265 1570 c 0,163,164 + 1349.93 1567.33 l 0,165,166 + 1365.77 1566.16 1365.77 1566.16 1382.5 1564.5 c 0,167,168 + 1447.99 1558.01 1447.99 1558.01 1490 1519 c 0,169,170 + 1518.99 1492 1518.99 1492 1521.5 1422.5 c 0,171,172 + 1519.34 1385.52 l 0,173,174 + 1512.2 1343.51 1512.2 1343.51 1483 1320 c 0,175,176 + 1461.18 1301.94 1461.18 1301.94 1419.52 1302 c 0,177,178 + 1405.83 1302.02 1405.83 1302.02 1390 1304 c 0,179,180 + 1421.01 1305.01 1421.01 1305.01 1454.5 1361.5 c 0,181,182 + 1468.24 1384.68 1468.24 1384.68 1468.27 1407.09 c 0,183,184 + 1468.31 1439.33 1468.31 1439.33 1440 1470 c 0,185,186 + 1427.39 1482.61 1427.39 1482.61 1405.3 1482.6 c 0,187,188 + 1387.11 1482.58 1387.11 1482.58 1362.5 1474 c 0,189,190 + 1308 1454.99 1308 1454.99 1290 1435 c 0,191,192 + 1215 1352.01 1215 1352.01 1139.5 1219.5 c 0,193,194 + 1064.02 1087.02 1064.02 1087.02 1018 985 c 0,195,196 + 988.999 918.996 988.999 918.996 972 828 c 0,197,198 + 955 737 955 737 946 665 c 0,199,200 + 935.001 593.002 935.001 593.002 894 557.5 c 0,201,202 + 853 522 853 522 760 561 c 0,203,204 + 793 555 793 555 837.5 579 c 0,205,206 + 882 603 882 603 864 663 c 0,207,208 + 853.377 695.377 853.377 695.377 831.749 695.891 c 0,209,210 + 814.459 692.007 l 0,211,212 + 798.784 685.202 798.784 685.202 779 666.5 c 0,213,214 + 715 606.001 715 606.001 712 568 c 0,215,216 + 706.001 503.007 706.001 503.007 703.5 387 c 0,217,218 + 706.084 344.04 l 0,219,220 + 718.324 266.367 718.324 266.367 787 248 c 0,221,222 + 835.997 235 835.997 235 897.5 226 c 0,223,224 + 959 217 959 217 1018 217 c 0,225,226 + 1110.99 217 1110.99 217 1154 286 c 0,227,228 + 1197.03 355.037 1197.03 355.037 1245 418 c 0,229,230 + 1311.58 504.619 1311.58 504.619 1367.71 504.744 c 0,231,232 + 1398.42 504.812 1398.42 504.812 1426 479 c 0,233,234 + 1498.75 410.917 1498.75 410.917 1499.3 379.363 c 0,235,236 + 1499.34 377.087 1499.34 377.087 1499 375 c 0,237,238 + 1482.01 402 1482.01 402 1418 425.5 c 0,239,240 + 1397.57 433 1397.57 433 1380.61 432.912 c 0,241,242 + 1344.43 432.724 1344.43 432.724 1324 398 c 0,243,244 + 1304 362.992 1304 362.992 1304 298 c 0,245,246 + 1304 260.996 1304 260.996 1348.5 222 c 0,247,248 + 1393.01 183 1393.01 183 1419 174 c 0,249,250 + 1456.01 159 1456.01 159 1509 141 c 0,251,252 + 1562.02 122.991 1562.02 122.991 1598 108 c 0,253,254 + 1669.01 77.9939 1669.01 77.9939 1713 17.5 c 0,255,256 + 1745.17 -26.7446 1745.17 -26.7446 1745.27 -73.9191 c 0,257,258 + 1745.3 -91.2615 1745.3 -91.2615 1741 -109 c 0,259,260 + 1722.99 -65.9799 1722.99 -65.9799 1692 -19.5 c 0,261,262 + 1660.99 27.0011 1660.99 27.0011 1582 35 c 0,263,264 + 1536.43 39.8826 1536.43 39.8826 1483.24 39.7986 c 0,265,266 + 1471.07 39.7794 1471.07 39.7794 1458.5 39.5 c 0,267,268 + 1390.99 37.9999 1390.99 37.9999 1335 24 c 0,269,270 + 1287 10.9999 1287 10.9999 1240.5 -17.5 c 0,271,272 + 1194 -46 1194 -46 1152 -63 c 0,273,274 + 1090.99 -86.0012 1090.99 -86.0012 1044.5 -92.5 c 0,275,276 + 998 -98.9999 998 -98.9999 964 -63 c 0,277,278 + 949 -48 949 -48 951.5 -26 c 0,279,280 + 954 -3.99995 954 -3.99995 962 1 c 0,281,282 + 969.999 -44 969.999 -44 999 -44 c 0,283,284 + 1042.99 -44 1042.99 -44 1050 -2 c 0,285,286 + 1048.42 12.7096 l 0,287,288 + 1038.21 37.5233 1038.21 37.5233 973.184 37.7045 c 0,289,290 + 961.698 37.7366 961.698 37.7366 948.5 37 c 0,291,292 + 841.002 31.0001 841.002 31.0001 828 29 c 0,293,294 + 699 6.99995 699 6.99995 604 -48.5 c 0,295,296 + 509 -104 509 -104 397 -161 c 0,297,-1 + 320 -198 l 0,298,299 + 274.001 -220 274.001 -220 237 -220 c 0,0,1 +EndSplineSet +KernsSLIF: 121 -117 0 0 89 -104 0 0 322 -182 0 0 321 -169 0 0 105 -52 0 0 73 -65 0 0 101 -65 0 0 98 -78 0 0 66 -78 0 0 45 -208 0 0 +EndChar +StartChar: a +Encoding: 97 97 56 +Width: 1254 +Flags: W +Fore +1101 -190 m 1,0,1 + 1130.99 -133.017 1130.99 -133.017 1145.5 -66.5 c 0,2,3 + 1160.01 -5.34058e-05 1160.01 -5.34058e-05 1105 52 c 0,4,5 + 1061.98 94.0183 1061.98 94.0183 1019 122 c 0,6,7 + 976 150.001 976 150.001 929 134 c 0,8,9 + 898.001 122 898.001 122 889.5 75 c 0,10,11 + 881 28 881 28 878 28 c 0,12,13 + 843 97 843 97 885 176 c 0,14,15 + 924.162 249.663 924.162 249.663 924.2 314.63 c 0,16,17 + 924.203 319.338 924.203 319.338 924 324 c 0,18,19 + 918 460 918 460 878 508 c 0,20,21 + 838 556 838 556 784 577 c 0,22,23 + 755.159 588.038 755.159 588.038 730.121 588.046 c 0,24,25 + 684.841 588.061 684.841 588.061 652 552 c 0,26,27 + 601 496 601 496 547 472 c 0,28,29 + 514 457 514 457 477.5 471 c 0,30,31 + 441 485 441 485 438 524 c 0,32,33 + 464.8 513.421 464.8 513.421 477.424 513.287 c 0,34,35 + 482.7 513.232 482.7 513.232 485.5 515 c 0,36,37 + 495 521 495 521 498 527 c 0,38,39 + 515 563 515 563 474 575 c 0,40,41 + 385 595 385 595 349 527 c 0,42,43 + 319 469 319 469 294.5 385 c 0,44,45 + 270 301 270 301 302 230 c 0,46,47 + 308.851 213.559 308.851 213.559 308.896 189.844 c 0,48,49 + 308.917 178.941 308.917 178.941 307.5 166.5 c 0,50,51 + 303 126.999 303 126.999 264 113 c 0,52,53 + 267.965 142.506 l 0,54,55 + 267.628 173.422 267.628 173.422 240.722 174.061 c 0,56,57 + 231.5 173.5 l 0,58,59 + 183 167 183 167 157 138 c 0,60,61 + 98.9995 73.9999 98.9995 73.9999 70 21 c 0,62,63 + 41 -32 41 -32 51 -108 c 0,64,65 + 27 -84 27 -84 28.5 -26.5 c 0,66,67 + 30 31 30 31 46 58 c 0,68,69 + 74.9999 109 74.9999 109 103 152.5 c 0,70,71 + 131.001 196 131.001 196 133 250 c 0,72,73 + 133 283 133 283 109 296.5 c 0,74,75 + 85 310 85 310 97 257 c 0,76,77 + 68.0001 282 68.0001 282 77 321 c 0,78,79 + 111.999 481 111.999 481 225.5 621 c 0,80,81 + 338.999 760.998 338.999 760.998 360 850 c 0,82,83 + 374.002 908.012 374.002 908.012 386 973.5 c 0,84,85 + 398.006 1039.04 398.006 1039.04 406 1093 c 0,86,87 + 412.001 1150.01 412.001 1150.01 448.5 1198.5 c 0,88,89 + 469.7 1226.67 469.7 1226.67 494.444 1226.67 c 0,90,91 + 512.299 1226.67 512.299 1226.67 532 1212 c 0,92,93 + 487 1203 487 1203 485.5 1178.5 c 0,94,95 + 484 1154.01 484 1154.01 493 1144 c 0,96,97 + 508.183 1124.39 508.183 1124.39 523.767 1124.39 c 0,98,99 + 532.816 1124.39 532.816 1124.39 542 1131 c 0,100,101 + 590 1162.99 590 1162.99 620.5 1264.5 c 0,102,103 + 650.032 1362.79 650.032 1362.79 650 1422 c 0,104,105 + 647 1478 647 1478 609.5 1511 c 0,106,107 + 591.999 1526.4 591.999 1526.4 572.867 1526.56 c 0,108,109 + 561.011 1526.65 561.011 1526.65 548.53 1520.9 c 0,110,111 + 537.988 1516.04 537.988 1516.04 527 1507 c 0,112,113 + 557 1585 557 1585 603.5 1573 c 0,114,115 + 650.006 1561 650.006 1561 697.5 1510.5 c 0,116,117 + 745 1459.99 745 1459.99 785.5 1398 c 0,118,119 + 826 1336.01 826 1336.01 844 1314 c 0,120,121 + 873.983 1277.02 873.983 1277.02 913.5 1253.5 c 0,122,123 + 953.003 1229.99 953.003 1229.99 969 1197 c 0,124,125 + 981.772 1169.25 981.772 1169.25 981.839 1147.23 c 0,126,127 + 981.924 1119.24 981.924 1119.24 961.5 1100.5 c 0,128,129 + 942.278 1082.86 942.278 1082.86 919.867 1082.83 c 0,130,131 + 899.721 1082.8 899.721 1082.8 877 1097 c 0,132,133 + 907 1097 907 1097 907 1116 c 0,134,135 + 907 1136.99 907 1136.99 873.5 1154.5 c 0,136,137 + 859.98 1158.04 l 0,138,139 + 840.37 1156.54 840.37 1156.54 840 1104 c 0,140,141 + 840 1080 840 1080 851.5 1052 c 0,142,-1 + 869 1010 l 0,143,144 + 896 941 896 941 908.5 966 c 0,145,146 + 921 991 921 991 906 1008 c 0,147,148 + 939 1008 939 1008 950.5 966 c 0,149,150 + 962 924 962 924 962 913 c 0,151,152 + 962 849 962 849 953.5 758.5 c 0,153,154 + 945 668 945 668 975 611 c 0,155,156 + 984 591 984 591 1019 539 c 0,157,158 + 1053.42 487.858 1053.42 487.858 1069 478 c 0,159,160 + 1087.99 466.009 1087.99 466.009 1105.5 429.5 c 0,161,162 + 1110.37 419.346 1110.37 419.346 1110.48 409.695 c 0,163,164 + 1110.57 401.279 1110.57 401.279 1107.05 393.244 c 0,165,166 + 1100.08 377.377 1100.08 377.377 1079 363 c 0,167,168 + 1084.24 378.447 1084.24 378.447 1084.46 389.787 c 0,169,170 + 1081.44 405.63 l 0,171,172 + 1074.39 420.005 1074.39 420.005 1051 421 c 0,173,174 + 1032.22 419.204 l 0,175,176 + 1015.67 414.069 1015.67 414.069 1015.63 395.11 c 0,177,178 + 1015.62 392.216 1015.62 392.216 1016 389 c 0,179,180 + 1028 288.996 1028 288.996 1102.5 232 c 0,181,182 + 1177 175.004 1177 175.004 1186 88 c 0,183,184 + 1189.26 21.1694 l 0,185,186 + 1188.68 -24.9163 1188.68 -24.9163 1179.5 -64 c 0,187,188 + 1164.01 -129.994 1164.01 -129.994 1101 -190 c 1,0,1 +619 690 m 1,115,116 + 634 708 634 708 649.5 729.5 c 0,117,118 + 665 751 665 751 683 764 c 0,119,120 + 703.141 776.451 703.141 776.451 718.052 776.43 c 0,121,122 + 743.859 776.394 743.859 776.394 754 739 c 0,123,124 + 718 758 718 758 703 748 c 0,125,126 + 695.286 742.857 695.286 742.857 695.242 733.747 c 0,127,128 + 695.2 725.143 695.2 725.143 702 713 c 0,129,130 + 726 668 726 668 768.5 715 c 0,131,132 + 801.516 751.512 801.516 751.512 801.642 804.32 c 0,133,134 + 801.678 819.488 801.678 819.488 799 836 c 0,135,136 + 793 871 793 871 747 983 c 0,137,138 + 710.201 1072.6 710.201 1072.6 681.72 1073.24 c 0,139,140 + 670.911 1070.1 l 0,141,142 + 669.443 1069.18 669.443 1069.18 668 1068 c 0,143,144 + 641 1045.99 641 1045.99 649.5 1012.5 c 0,145,146 + 658 979 658 979 661 948 c 0,147,148 + 660.631 904.308 l 0,149,150 + 656.786 866.042 656.786 866.042 640.5 829 c 0,151,152 + 615 771 615 771 521 807 c 0,153,154 + 548 804 548 804 586 824.5 c 0,155,156 + 624 845 624 845 579 884 c 0,157,158 + 570.784 890.676 570.784 890.676 561.249 890.627 c 0,159,160 + 552.216 890.581 552.216 890.581 542 884.5 c 0,161,162 + 521 872 521 872 509 856 c 0,163,164 + 440 763 440 763 512.5 704 c 0,165,166 + 585 645 585 645 619 690 c 1,115,116 +EndSplineSet +KernsSLIF: 99 -130 0 0 109 -78 0 0 104 -117 0 0 45 -182 0 0 115 -208 0 0 121 -299 0 0 116 -342 0 0 118 -43 0 0 119 -221 0 0 +EndChar +StartChar: b +Encoding: 98 98 18 +Width: 1083 +Flags: HMW +HStem: 40.8 160.65<365.16 635.205> 617.1 218.45<359.04 641.325> 1229.95 170<339.15 591.6> 1316.65 94.35<25.5 180.795> +VStem: 209.1 130.05<-23.8 1399.95> +Fore +426.7 185.3 m 1,0,1 + 482.159 184.3 l 0,2,3 + 531.98 186.879 531.98 186.879 587.35 201.45 c 0,4,5 + 674.56 224.4 674.56 224.4 735.76 252.45 c 0,6,7 + 787.78 275.4 787.78 275.4 844.9 337.45 c 0,8,9 + 880.496 376.117 880.496 376.117 880.837 408.843 c 0,10,11 + 877.226 429.789 l 0,12,13 + 874.124 438.244 874.124 438.244 868.359 446.25 c 0,14,15 + 856.121 462.4 856.121 462.4 830.62 468.775 c 0,16,17 + 805.12 475.15 805.12 475.15 784.721 454.75 c 0,18,19 + 775.451 445.243 775.451 445.243 775.402 431.167 c 0,20,21 + 775.382 425.107 775.382 425.107 777.07 418.2 c 0,22,23 + 782.68 395.25 782.68 395.25 818.38 380.8 c 0,24,25 + 790.84 360.4 790.84 360.4 741.88 387.175 c 0,26,27 + 700.418 409.849 700.418 409.849 699.92 445.63 c 0,28,29 + 699.83 452.101 699.83 452.101 701.08 459 c 0,30,31 + 709.24 509.15 709.24 509.15 758.2 539.325 c 0,32,33 + 807.16 569.5 807.16 569.5 790.84 612.85 c 0,34,35 + 777.58 646 777.58 646 704.141 670.65 c 0,36,37 + 630.699 695.299 630.699 695.299 560.32 700.4 c 0,38,39 + 496.06 704.649 496.06 704.649 440.47 697.85 c 0,40,41 + 384.88 691.051 384.88 691.051 359.38 636.65 c 0,42,43 + 337.96 594.151 337.96 594.151 334.9 547.4 c 0,44,45 + 333.928 474.045 l 0,46,47 + 334.294 465.198 334.294 465.198 334.9 456.45 c 0,48,49 + 334.9 429.25 334.9 429.25 361.93 407.15 c 0,50,51 + 374.852 396.585 374.852 396.585 391.621 396.51 c 0,52,53 + 409.928 396.428 409.928 396.428 432.82 408.85 c 0,54,55 + 467.684 428.219 467.684 428.219 468.122 451.755 c 0,56,57 + 464.95 467.075 l 0,58,59 + 451.18 499.8 451.18 499.8 414.46 510 c 0,60,61 + 437.91 523.68 437.91 523.68 462.372 523.6 c 0,62,63 + 480.469 523.54 480.469 523.54 499.12 515.95 c 0,64,65 + 545.059 496.808 545.059 496.808 545.48 454.907 c 0,66,67 + 545.527 450.291 545.527 450.291 545.021 445.4 c 0,68,69 + 539.919 396.099 539.919 396.099 510.34 368.9 c 0,70,71 + 482.8 343.4 482.8 343.4 420.58 301.325 c 0,72,73 + 358.359 259.25 358.359 259.25 367.54 221 c 0,74,75 + 373.66 189.549 373.66 189.549 426.7 185.3 c 0,76,-1 + 426.7 185.3 l 1,0,1 +346.289 870.4 m 1,44,45 + 374.387 839.903 374.387 839.903 420.997 839.912 c 0,46,47 + 438.15 839.915 438.15 839.915 457.81 844.05 c 0,48,49 + 603.802 874.755 603.802 874.755 607.75 884 c 0,50,-1 + 726.75 986 l 0,51,52 + 758.7 1033.93 758.7 1033.93 760.75 1139 c 0,53,54 + 757.517 1164.82 l 0,55,56 + 744.581 1211.19 744.581 1211.19 680.169 1246.95 c 0,57,58 + 610.978 1284.48 610.978 1284.48 564.236 1284.64 c 0,59,60 + 555.885 1284.66 555.885 1284.66 548.25 1283.5 c 0,61,62 + 515.57 1278.17 515.57 1278.17 545.189 1206.58 c 0,63,64 + 573.239 1137.3 573.239 1137.3 539.58 1074.4 c 0,65,66 + 493.969 990.462 493.969 990.462 419.145 989.885 c 0,67,68 + 413.651 989.843 413.651 989.843 408 990.25 c 0,69,70 + 461.193 1002.56 461.193 1002.56 461.588 1072.75 c 0,71,72 + 461.602 1075.24 461.602 1075.24 461.55 1077.8 c 0,73,74 + 460.02 1152.6 460.02 1152.6 400.859 1152.6 c 0,75,76 + 350.893 1152.6 350.893 1152.6 331.5 998.75 c 0,77,78 + 327.473 940.051 l 0,79,80 + 327.837 888.625 327.837 888.625 346.289 870.4 c 0,81,-1 + 346.289 870.4 l 1,44,45 +279.65 36.125 m 145,-1,-1 + 184.789 -11.4746 l 0,45,46 + 159.502 -9.35944 l 0,47,48 + 129.359 -1.62558 129.359 -1.62558 126.267 32.7246 c 0,49,50 + 126.948 66.7202 l 0,51,52 + 130.7 93.8745 130.7 93.8745 145.01 117.725 c 0,53,54 + 140.419 37.8253 140.419 37.8253 171.02 48.875 c 0,55,56 + 201.62 59.9251 201.62 59.9251 206.592 124.1 c 0,57,58 + 211.563 188.275 211.563 188.275 203.532 264.775 c 0,59,60 + 195.5 341.275 195.5 341.275 180.582 410.125 c 0,61,62 + 165.665 478.973 165.665 478.973 158.014 498.525 c 0,63,64 + 125.887 571.621 125.887 571.621 111.35 600.95 c 0,65,66 + 93.3115 637.34 93.3115 637.34 53.21 692.325 c 0,67,68 + 21.4043 735.935 21.4043 735.935 21.3251 790.518 c 0,69,70 + 21.3148 797.641 21.3148 797.641 21.8447 804.95 c 0,71,72 + 26.4336 868.276 26.4336 868.276 71.5693 903.125 c 0,73,74 + 89.6215 917.105 89.6215 917.105 112.368 917.176 c 0,75,76 + 121.43 917.204 121.43 917.204 131.238 915.025 c 0,77,78 + 165.664 907.375 165.664 907.375 169.488 836.825 c 0,79,80 + 154.453 858.406 154.453 858.406 130.692 858.606 c 0,81,82 + 125.441 858.65 125.441 858.65 119.764 857.65 c 0,83,84 + 88.4003 852.125 88.4003 852.125 92.9883 800.275 c 0,85,86 + 96.8135 755.225 96.8135 755.225 130.475 753.95 c 0,87,88 + 152.528 756.629 l 0,89,90 + 169.195 762.046 169.195 762.046 177.904 778.175 c 0,91,92 + 208.147 831.941 208.147 831.941 208.122 949.45 c 0,93,94 + 207.738 1066.34 207.738 1066.34 203.15 1136.88 c 0,95,96 + 199.325 1188.72 199.325 1188.72 182.494 1252.9 c 0,97,98 + 167.916 1308.49 167.916 1308.49 116.417 1308.61 c 0,99,100 + 107.206 1308.63 107.206 1308.63 96.8135 1306.88 c 0,101,102 + 45.3775 1298.19 45.3775 1298.19 45.4768 1255.64 c 0,103,104 + 45.4942 1248.2 45.4942 1248.2 47.0889 1239.72 c 0,105,106 + 57.7988 1182.79 57.7988 1182.79 80.75 1179.38 c 0,107,108 + 59.2039 1176.94 l 0,109,110 + 28.1379 1179.12 28.1379 1179.12 7.69141 1217.2 c 0,111,112 + -7.80302 1246.06 -7.80302 1246.06 -7.73372 1278.37 c 0,113,114 + -7.68156 1302.69 -7.68156 1302.69 1.18848 1328.97 c 0,115,116 + 34.7996 1426.53 34.7996 1426.53 120.092 1427.05 c 0,117,118 + 156.484 1423.33 l 0,119,-1 + 235.662 1407.6 l 0,120,121 + 259.896 1404.67 l 0,122,123 + 288.348 1405.15 288.348 1405.15 332.859 1419.5 c 0,124,125 + 373.66 1433.1 373.66 1433.1 406.81 1470.5 c 0,126,127 + 440.005 1507.95 440.005 1507.95 467.5 1535.95 c 0,128,129 + 485.874 1555.51 485.874 1555.51 524.109 1572.08 c 0,130,131 + 553.312 1584.73 553.312 1584.73 579.849 1584.75 c 0,132,133 + 588.062 1584.76 588.062 1584.76 596.021 1583.55 c 0,134,135 + 643.954 1576.76 643.954 1576.76 688.84 1535.95 c 0,136,137 + 717.922 1509.51 717.922 1509.51 717.881 1472.01 c 0,138,139 + 717.858 1452.1 717.858 1452.1 709.24 1428 c 0,140,141 + 702.102 1456.04 702.102 1456.04 643.45 1495.15 c 0,142,143 + 623.166 1508.67 623.166 1508.67 606.944 1508.87 c 0,144,145 + 598.781 1508.97 598.781 1508.97 591.647 1505.69 c 0,146,147 + 572.968 1497.11 572.968 1497.11 561.34 1465.4 c 0,148,149 + 550.12 1434.8 550.12 1434.8 665.38 1378.28 c 0,150,151 + 780.658 1321.74 780.658 1321.74 811.24 1287.75 c 0,152,153 + 887.742 1200.19 887.742 1200.19 902.53 1105 c 0,154,155 + 908.699 1065.29 908.699 1065.29 908.628 1027.72 c 0,156,157 + 908.519 970.361 908.519 970.361 893.859 918 c 0,158,159 + 886.72 892.498 886.72 892.498 847.45 853.825 c 0,160,161 + 819.755 826.55 819.755 826.55 792.314 826.543 c 0,162,163 + 780.845 826.539 780.845 826.539 769.42 831.3 c 0,164,165 + 797.979 861.049 797.979 861.049 769.42 872.1 c 0,166,167 + 753.683 874.809 l 0,168,169 + 739.244 873.686 739.244 873.686 735.76 855.1 c 0,170,171 + 728.62 816.85 728.62 816.85 808.69 722.5 c 0,172,173 + 889.862 626.849 889.862 626.849 918.34 666.4 c 0,174,175 + 933.641 687.651 933.641 687.651 918.34 717.4 c 0,176,177 + 903.04 747.15 903.04 747.15 871.42 770.1 c 0,178,179 + 963.221 767.55 963.221 767.55 1004.02 693.175 c 0,180,181 + 1044.82 618.8 1044.82 618.8 1046.86 590.75 c 0,182,183 + 1044.78 549.144 l 0,184,185 + 1038.75 505.432 1038.75 505.432 1016.77 447.1 c 0,186,187 + 983.62 359.55 983.62 359.55 983.62 288.15 c 0,188,189 + 983.62 202.3 983.62 202.3 971.38 134.3 c 0,190,191 + 959.141 66.2997 959.141 66.2997 922.42 22.9502 c 0,192,193 + 878.56 -28.0498 878.56 -28.0498 805.12 -42.5 c 0,194,195 + 768.4 -50.1505 768.4 -50.1505 705.67 -44.2002 c 0,196,197 + 642.94 -38.25 642.94 -38.25 616.42 -17 c 0,198,199 + 647.676 -20.065 l 0,200,201 + 678.398 -19.3574 678.398 -19.3574 708.221 -3.8252 c 0,202,203 + 737.354 11.3484 737.354 11.3484 737.606 32.6744 c 0,204,205 + 737.702 40.8109 737.702 40.8109 733.594 49.8429 c 0,206,207 + 731.27 54.953 731.27 54.953 727.6 60.3496 c 0,208,209 + 710.26 85.8496 710.26 85.8496 621.521 82.4502 c 0,210,211 + 532.781 79.0499 532.781 79.0499 497.08 76.5 c 0,212,-1 + 382.84 67.5752 l 0,213,214 + 337.222 59.1049 337.222 59.1049 279.65 36.125 c 145,-1,-1 +EndSplineSet +EndChar +StartChar: c +Encoding: 99 99 19 +Width: 1171 +Flags: W +Fore +130 1163 m 1,0,1 + 132.395 1186.83 l 0,2,3 + 140.998 1220.08 140.998 1220.08 178.5 1260.5 c 0,4,5 + 207.417 1291.66 207.417 1291.66 233.339 1292.09 c 0,6,7 + 251.453 1288.48 l 0,8,9 + 261.996 1284 261.996 1284 272 1274 c 0,10,11 + 226.25 1267.25 226.25 1267.25 226.063 1236.88 c 0,12,13 + 226 1226.75 226 1226.75 231 1214 c 0,14,15 + 238.091 1193.2 238.091 1193.2 250.769 1193.3 c 0,16,17 + 264.909 1193.4 264.909 1193.4 286 1219.5 c 0,18,19 + 325.995 1268.99 325.995 1268.99 334 1286 c 0,20,21 + 358.997 1338.99 358.997 1338.99 366 1392 c 0,22,23 + 373.001 1445 373.001 1445 409 1490 c 0,24,25 + 436.611 1525.5 436.611 1525.5 481.5 1525.5 c 0,26,27 + 525.998 1525.01 525.998 1525.01 538 1492 c 0,28,29 + 480 1492 480 1492 499 1465 c 0,30,31 + 509.578 1449.72 509.578 1449.72 524.471 1449.64 c 0,32,33 + 534.923 1449.58 534.923 1449.58 547.5 1457 c 0,34,35 + 577.986 1474.99 577.986 1474.99 593 1489 c 0,36,37 + 621.242 1516.57 621.242 1516.57 621.224 1533.29 c 0,38,39 + 621.216 1541.43 621.216 1541.43 614.5 1547 c 0,40,41 + 594 1563.99 594 1563.99 564 1547 c 0,42,43 + 567.001 1588.01 567.001 1588.01 599.5 1593 c 0,44,45 + 630.619 1594.13 l 0,46,47 + 643.508 1592.77 643.508 1592.77 654 1588 c 0,48,49 + 749.093 1541.95 749.093 1541.95 811.5 1505 c 0,50,51 + 874 1467.99 874 1467.99 892 1460 c 0,52,53 + 923.249 1445.25 923.249 1445.25 951.459 1445.18 c 0,54,55 + 955.764 1445.17 955.764 1445.17 960 1445.5 c 0,56,57 + 1000.05 1444.5 l 0,58,59 + 1015.33 1442.75 1015.33 1442.75 1032 1439 c 0,60,61 + 1053.01 1433 1053.01 1433 1059.5 1404.5 c 0,62,63 + 1065.99 1376 1065.99 1376 1058 1349 c 0,64,65 + 1024.88 1380.05 1024.88 1380.05 1003.65 1380.15 c 0,66,67 + 994.125 1380.2 994.125 1380.2 987 1374 c 0,68,69 + 964 1354.01 964 1354.01 963 1294 c 0,70,71 + 961.999 1263.98 961.999 1263.98 959.5 1234 c 0,72,73 + 957 1204 957 1204 969 1177 c 0,74,75 + 988.003 1130 988.003 1130 1028 1119.5 c 0,76,77 + 1068.01 1109 1068.01 1109 1116 1106 c 0,78,79 + 1103.78 1081.57 1103.78 1081.57 1061.37 1081.35 c 0,80,81 + 1051.72 1081.3 1051.72 1081.3 1040.5 1082.5 c 0,82,83 + 980.007 1088.99 980.007 1088.99 961 1104 c 0,84,85 + 906.204 1143.52 906.204 1143.52 905.876 1183.45 c 0,86,87 + 905.839 1187.97 905.839 1187.97 906.5 1192.5 c 0,88,89 + 906.604 1224.3 l 0,90,91 + 902.367 1263.58 902.367 1263.58 879 1322 c 0,92,93 + 857.998 1373.01 857.998 1373.01 794 1384 c 0,94,95 + 762.159 1385.67 l 0,96,97 + 718.588 1382.3 718.588 1382.3 686 1346 c 0,98,99 + 653.006 1308.01 653.006 1308.01 627.5 1257 c 0,100,101 + 602 1206 602 1206 572 1167 c 0,102,103 + 560.987 1152.31 560.987 1152.31 518.784 1152.37 c 0,104,105 + 515.018 1152.38 515.018 1152.38 511 1152.5 c 0,106,107 + 466.355 1153.87 466.355 1153.87 465.708 1179.72 c 0,108,109 + 465.644 1182.24 465.644 1182.24 466 1185 c 0,110,111 + 495 1170 495 1170 522 1188 c 0,112,113 + 547.852 1205.23 547.852 1205.23 548 1235 c 0,114,115 + 547.031 1266.97 547.031 1266.97 528.5 1267 c 0,116,117 + 509.991 1265.99 509.991 1265.99 495 1257 c 0,118,119 + 450.683 1226.47 450.683 1226.47 430 1200.5 c 0,120,121 + 409.998 1175 409.998 1175 398 1123 c 0,122,123 + 387.25 1077.98 387.25 1077.98 387.334 1035.68 c 0,124,125 + 387.375 1015.02 387.375 1015.02 390 995 c 0,126,-1 + 407 865 l 0,127,128 + 410 830 410 830 423.5 794 c 0,129,130 + 437 758 437 758 432 724 c 0,131,132 + 415.795 633.439 415.795 633.439 333.252 632.842 c 0,133,134 + 329.206 632.813 329.206 632.813 325 633 c 0,135,136 + 342 645 342 645 362.5 669 c 0,137,138 + 383 693 383 693 368 720 c 0,139,140 + 355 742 355 742 318.5 730 c 0,141,142 + 282 718 282 718 279 695 c 0,143,144 + 264 611 264 611 263 541.5 c 0,145,146 + 266.367 498.172 l 0,147,148 + 274.626 448.904 274.626 448.904 303 397 c 0,149,150 + 322.999 359.001 322.999 359.001 353.5 353.5 c 0,151,152 + 384 348 384 348 397 405 c 0,153,154 + 399.148 427.344 l 0,155,156 + 398.563 432.875 398.563 432.875 396.5 437 c 0,157,158 + 391 448 391 448 379 469 c 0,159,160 + 399.007 462.998 399.007 462.998 417.5 458 c 0,161,162 + 436 453 436 453 447 433 c 0,163,164 + 468 391 468 391 471 351 c 0,165,166 + 474 311.003 474 311.003 488 268 c 0,167,168 + 504 216 504 216 538 207 c 0,169,170 + 557.5 200.76 557.5 200.76 573.62 200.638 c 0,171,172 + 586.718 200.539 586.718 200.539 597.585 204.479 c 0,173,174 + 624.781 214.339 624.781 214.339 638 249.5 c 0,175,176 + 663 316 663 316 696 364 c 0,177,178 + 709 382 709 382 735 379.5 c 0,179,180 + 761 377 761 377 776 353 c 0,181,182 + 791 329 791 329 788 311 c 0,183,184 + 763 325 763 325 743.5 313 c 0,185,186 + 724 301 724 301 741 281 c 0,187,188 + 751.698 266.413 751.698 266.413 764.877 266.011 c 0,189,190 + 779.807 269.701 l 0,191,192 + 787.321 273.45 787.321 273.45 795.5 281 c 0,193,194 + 828 311 828 311 831 356 c 0,195,196 + 829.957 415.261 l 0,197,198 + 823.929 488.15 823.929 488.15 795 570 c 0,199,200 + 790.425 583.218 790.425 583.218 790.501 606.128 c 0,201,202 + 790.575 628.283 790.575 628.283 795 659.5 c 0,203,204 + 804 723 804 723 835 768 c 0,205,206 + 830.002 721.017 830.002 721.017 824 674 c 0,207,208 + 818 627 818 627 833 581 c 0,209,210 + 844 548 844 548 857.5 513.5 c 0,211,212 + 871 479 871 479 886 452 c 0,213,214 + 913 405 913 405 937.5 378.5 c 0,215,216 + 962 352 962 352 1013 358 c 0,217,218 + 1033.63 360.063 1033.63 360.063 1033.93 381.977 c 0,219,220 + 1030 406 l 0,221,222 + 1046.99 412 1046.99 412 1061.5 387.5 c 0,223,224 + 1073.22 367.704 1073.22 367.704 1073.51 356.063 c 0,225,226 + 1073.58 353.302 1073.58 353.302 1073 351 c 0,227,228 + 1062.99 299 1062.99 299 1004 279 c 0,229,230 + 978 270 978 270 949.5 270.5 c 0,231,232 + 921 271 921 271 898 259 c 0,233,234 + 867 242.001 867 242.001 863.5 178.5 c 0,235,236 + 860 115.001 860 115.001 842 81 c 0,237,238 + 821 43 821 43 766 33 c 0,239,240 + 744 28 744 28 703.5 36 c 0,241,242 + 663 44 663 44 664 80 c 0,243,244 + 691 55 691 55 725 75 c 0,245,246 + 745 85.9999 745 85.9999 736 111.5 c 0,247,248 + 727 137 727 137 708 141 c 0,249,250 + 679.592 141.611 l 0,251,252 + 652.565 138.87 652.565 138.87 616 125 c 0,253,254 + 525 90.9996 525 90.9996 473 65 c 0,255,256 + 421 39 421 39 335 79 c 0,257,258 + 306 91 306 91 300.5 137.5 c 0,259,260 + 300.225 168.721 l 0,261,262 + 303.157 189.438 303.157 189.438 316 198 c 0,263,264 + 316 161.999 316 161.999 332.5 142 c 0,265,266 + 341.348 131.275 341.348 131.275 350.627 130.902 c 0,267,268 + 361.932 134.19 l 0,269,270 + 364.451 135.734 364.451 135.734 367 138 c 0,271,272 + 381.21 150.918 381.21 150.918 381.339 168.895 c 0,273,274 + 381.439 182.643 381.439 182.643 373.303 199.348 c 0,275,276 + 359.136 228.439 359.136 228.439 320 266.5 c 0,277,278 + 229 355 229 355 202 366 c 0,279,280 + 166.426 353.951 166.426 353.951 166.407 335.647 c 0,281,282 + 166.393 322.049 166.393 322.049 186 305 c 0,283,284 + 231.999 265.001 231.999 265.001 267 264 c 0,285,286 + 196.001 254 196.001 254 165 288 c 0,287,288 + 134.001 321.999 134.001 321.999 113 369 c 0,289,290 + 87.6341 423.536 87.6341 423.536 87.6032 491.344 c 0,291,292 + 87.5854 530.464 87.5854 530.464 96 574 c 0,293,294 + 108 633 108 633 140 689 c 0,295,296 + 172 745 172 745 175 806 c 0,297,298 + 178 896 178 896 155.5 984.5 c 0,299,300 + 133 1073 133 1073 130 1163 c 1,0,1 +EndSplineSet +KernsSLIF: 115 -117 0 0 97 -104 0 0 +EndChar +StartChar: d +Encoding: 100 100 60 +Width: 1313 +Flags: MW +VStem: 197 151.5<8.5 1487> +Fore +334 -30 m 1,0,1 + 377.834 -63.5206 377.834 -63.5206 415.436 -63.5899 c 0,2,3 + 436.165 -63.6281 436.165 -63.6281 455 -53.5 c 0,4,5 + 508 -25 508 -25 508 -10 c 0,6,7 + 506 21 506 21 458 20.5 c 0,8,9 + 410 20 410 20 348.5 8.5 c 0,10,11 + 287 -3 287 -3 228 -17.5 c 0,12,13 + 181.952 -28.8171 181.952 -28.8171 157.832 -28.8647 c 0,14,15 + 151.049 -28.8781 151.049 -28.8781 146 -28 c 0,16,17 + 98 -19 98 -19 54.5 29 c 0,18,19 + 11 77 11 77 50 164 c 0,20,21 + 51.0001 77.9999 51.0001 77.9999 91.5 56.5 c 0,22,23 + 132 35 132 35 180 52 c 0,24,25 + 227.999 68.9997 227.999 68.9997 268 112.5 c 0,26,27 + 308 155.999 308 155.999 308 203 c 0,28,29 + 308 222.999 308 222.999 281.5 263 c 0,30,31 + 257.972 298.514 257.972 298.514 234.05 298.555 c 0,32,33 + 231.028 298.561 231.028 298.561 228 298 c 0,34,35 + 193.875 292.75 193.875 292.75 193.82 247.688 c 0,36,37 + 193.812 241.25 193.812 241.25 194.5 234 c 0,38,39 + 200.001 175.999 200.001 175.999 229 156 c 0,40,41 + 191.999 157.001 191.999 157.001 181 168 c 0,42,43 + 170 179 170 179 164 196 c 0,44,45 + 147.605 234.879 147.605 234.879 147.667 279.024 c 0,46,47 + 147.737 329.122 147.737 329.122 169 386 c 0,48,49 + 209.007 493.016 209.007 493.016 240 562 c 0,50,51 + 262.001 612 262.001 612 268.5 657 c 0,52,53 + 270.99 707.825 l 0,54,55 + 270.407 743.335 270.407 743.335 265 792 c 0,56,57 + 254.001 877.999 254.001 877.999 193.5 953.5 c 0,58,59 + 133.003 1028.99 133.003 1028.99 120 1074 c 0,60,61 + 113.455 1094.73 113.455 1094.73 113.455 1114.93 c 0,62,63 + 113.455 1150.28 113.455 1150.28 133.5 1184 c 0,64,65 + 159.451 1227.66 159.451 1227.66 208.138 1227.89 c 0,66,67 + 218.549 1227.94 218.549 1227.94 230 1226 c 0,68,69 + 208.997 1217 208.997 1217 195.5 1189 c 0,70,71 + 190.804 1179.26 190.804 1179.26 190.888 1170.73 c 0,72,73 + 191.044 1154.74 191.044 1154.74 208 1143 c 0,74,75 + 219.174 1134.49 219.174 1134.49 227.907 1134.36 c 0,76,77 + 234.827 1134.26 234.827 1134.26 240.213 1139.43 c 0,78,79 + 253.577 1152.25 253.577 1152.25 257.5 1197.5 c 0,80,81 + 265 1284.01 265 1284.01 258 1322 c 0,82,83 + 248.999 1370.01 248.999 1370.01 228 1406.5 c 0,84,85 + 207.005 1442.99 207.005 1442.99 197 1487 c 0,86,87 + 191.696 1508.7 191.696 1508.7 191.74 1532.38 c 0,88,89 + 191.787 1557.8 191.787 1557.8 198 1585.5 c 0,90,91 + 209.999 1639 209.999 1639 247 1672 c 0,92,93 + 272.994 1695.99 272.994 1695.99 322 1697 c 0,94,95 + 353.127 1694.13 l 0,96,97 + 377.447 1688.33 377.447 1688.33 389 1671 c 0,98,99 + 398 1656 398 1656 404.5 1641 c 0,100,101 + 407.204 1623.97 l 0,102,103 + 406.891 1611.85 406.891 1611.85 402 1595 c 0,104,105 + 396 1617.99 396 1617.99 349 1635.5 c 0,106,107 + 302 1653.01 302 1653.01 287 1592 c 0,108,109 + 275 1545.01 275 1545.01 314.5 1517 c 0,110,111 + 353.959 1489.02 353.959 1489.02 396 1470 c 0,112,113 + 433.024 1451.99 433.024 1451.99 549.5 1421.5 c 0,114,115 + 589.846 1410.94 589.846 1410.94 617.657 1410.87 c 0,116,117 + 657.976 1410.77 657.976 1410.77 671.957 1432.72 c 0,118,119 + 676.18 1439.36 676.18 1439.36 678 1448 c 0,120,121 + 681.935 1486.52 l 0,122,123 + 681.575 1537.19 681.575 1537.19 645 1552.5 c 0,124,125 + 621.099 1562.5 621.099 1562.5 601.002 1562.63 c 0,126,127 + 584.9 1562.73 584.9 1562.73 571.241 1556.48 c 0,128,129 + 567.003 1554.55 567.003 1554.55 563 1552 c 0,130,131 + 563 1590.99 563 1590.99 593 1604 c 0,132,133 + 622.962 1616.99 622.962 1616.99 629 1618 c 0,134,135 + 695 1621 695 1621 723.5 1597 c 0,136,137 + 752 1573 752 1573 765 1549 c 0,138,139 + 785.996 1510.01 785.996 1510.01 800.5 1455.5 c 0,140,141 + 815 1401.01 815 1401.01 851 1379 c 0,142,143 + 908.983 1342.01 908.983 1342.01 934.5 1333 c 0,144,145 + 960 1324 960 1324 1024 1315 c 0,146,147 + 1112.99 1301.99 1112.99 1301.99 1135 1228 c 0,148,149 + 1140.22 1208.71 1140.22 1208.71 1140.13 1192.05 c 0,150,151 + 1139.85 1135.97 1139.85 1135.97 1078 1109 c 0,152,153 + 1094.92 1132.07 1094.92 1132.07 1094.98 1158.11 c 0,154,155 + 1095 1165.92 1095 1165.92 1093.5 1174 c 0,156,157 + 1087.84 1204.5 1087.84 1204.5 1050.65 1204.62 c 0,158,159 + 1045.17 1204.64 1045.17 1204.64 1039 1204 c 0,160,161 + 1022.33 1202.15 1022.33 1202.15 1022.05 1180.66 c 0,162,163 + 1026.65 1151.28 l 0,164,165 + 1027.28 1148.94 1027.28 1148.94 1028 1146.5 c 0,166,167 + 1044.01 1091.99 1044.01 1091.99 1056 1070 c 0,168,169 + 1105.98 963.021 1105.98 963.021 1173.5 863.5 c 0,170,171 + 1241.01 763.992 1241.01 763.992 1246 707 c 0,172,173 + 1244.58 673.304 l 0,174,175 + 1236.64 624.131 1236.64 624.131 1194 580 c 0,176,177 + 1179 565 1179 565 1144.5 562 c 0,178,179 + 1110 559 1110 559 1089 571 c 0,180,181 + 1122 571 1122 571 1138.5 597.5 c 0,182,183 + 1145.85 609.313 1145.85 609.313 1145.96 618.841 c 0,184,185 + 1146.05 627.748 1146.05 627.748 1139.81 634.659 c 0,186,187 + 1137.75 636.938 1137.75 636.938 1135 639 c 0,188,189 + 1121.36 648.356 1121.36 648.356 1109.39 648.29 c 0,190,191 + 1090.64 648.186 1090.64 648.186 1076 625 c 0,192,193 + 1052 587.002 1052 587.002 1043 564 c 0,194,195 + 1041.99 559.967 1041.99 559.967 997 446.5 c 0,196,197 + 974.979 390.957 974.979 390.957 974.75 361.637 c 0,198,199 + 974.65 348.854 974.65 348.854 978.693 341.055 c 0,200,201 + 984.326 330.189 984.326 330.189 998 329 c 0,202,203 + 1023.15 329.34 l 0,204,205 + 1039.03 332.237 1039.03 332.237 1046.5 343 c 0,206,207 + 1059 361.014 1059 361.014 1071 397 c 0,208,209 + 1088.77 358.229 1088.77 358.229 1088.85 329.175 c 0,210,211 + 1088.93 304.269 1088.93 304.269 1076 286.5 c 0,212,213 + 1048 248.001 1048 248.001 1022 238 c 0,214,215 + 869.999 176 869.999 176 814.5 173 c 0,216,217 + 759 170 759 170 652 20 c 0,218,219 + 541 -136 541 -136 452.5 -121 c 0,220,221 + 364 -106 364 -106 334 -30 c 1,0,1 +640 273 m 0,118,119 + 660 292 660 292 698.5 340 c 0,120,121 + 737 388 737 388 751 411 c 0,122,123 + 772 447 772 447 779 481.5 c 0,124,-1 + 794 558 l 0,125,126 + 807 630 807 630 855.5 644 c 0,127,128 + 904 658 904 658 919 635 c 0,129,130 + 875 635 875 635 860 607 c 0,131,132 + 850.854 589.926 850.854 589.926 850.631 578.431 c 0,133,134 + 853.459 566.831 l 0,135,136 + 854 566 l 0,137,138 + 884 522 884 522 929.5 597.5 c 0,139,140 + 975 673 975 673 981 742 c 0,141,142 + 979.57 790.509 l 0,143,144 + 974.2 842.742 974.2 842.742 953.5 917 c 0,145,146 + 929.084 1004.59 929.084 1004.59 891.747 1005.06 c 0,147,148 + 875.211 1001.29 l 0,149,150 + 872.143 999.898 872.143 999.898 869 998 c 0,151,152 + 845 983 845 983 857 959.5 c 0,153,154 + 869 936 869 936 905 927 c 0,155,156 + 883.461 918.384 883.461 918.384 866.562 918.432 c 0,157,158 + 828.539 918.538 828.539 918.538 814 962.5 c 0,159,160 + 793.002 1025.99 793.002 1025.99 784 1077 c 0,161,162 + 769.001 1151.99 769.001 1151.99 708.5 1199.5 c 0,163,164 + 648 1247.01 648 1247.01 578 1256.5 c 0,165,166 + 508 1265.99 508 1265.99 447.5 1234 c 0,167,168 + 387.002 1202.01 387.002 1202.01 374 1119 c 0,169,170 + 372.342 1087.63 l 0,171,172 + 373.653 1071.46 373.653 1071.46 380 1058.5 c 0,173,174 + 392 1034.01 392 1034.01 423 1042 c 0,175,176 + 440 1046.01 440 1046.01 435.5 1066 c 0,177,178 + 430.999 1086 430.999 1086 410 1101 c 0,179,180 + 433.116 1101.63 l 0,181,182 + 462.692 1097.49 462.692 1097.49 481 1066 c 0,183,184 + 489 1051 489 1051 494 1025 c 0,185,186 + 494.287 1001.71 l 0,187,188 + 491.796 985.017 491.796 985.017 482 966 c 0,189,190 + 413.999 836.997 413.999 836.997 395.5 680 c 0,191,192 + 383.413 577.424 383.413 577.424 383.492 512.842 c 0,193,194 + 383.533 478.573 383.533 478.573 387 455 c 0,195,196 + 402 350 402 350 439 346.5 c 0,197,198 + 476 343 476 343 482 379 c 0,199,200 + 486 415 486 415 435 415 c 0,201,202 + 439 427 439 427 456 428.5 c 0,203,204 + 473.001 430 473.001 430 484 433 c 0,205,206 + 538 442 538 442 549 386.5 c 0,207,208 + 560 331 560 331 570 296 c 0,209,210 + 578 263 578 263 600 259 c 0,211,212 + 622 255 622 255 640 273 c 0,118,119 +EndSplineSet +KernsSLIF: 122 -91 0 0 97 -150 0 0 +EndChar +StartChar: e +Encoding: 101 101 54 +Width: 1080 +Flags: HMW +HStem: 142 27<40 136.5> 177.5 172<205.5 798> 722 137<316 666> 1260.15 167.854<365 744> +VStem: 114.5 149.5<412 1397> +Fore +611 199 m 0,0,1 + 532.994 197.999 532.994 197.999 452 182 c 0,2,3 + 370.998 165.999 370.998 165.999 302 133 c 0,4,5 + 242 103 242 103 166 89.5 c 0,6,7 + 89.9995 76 89.9995 76 40 142 c 0,8,9 + 16.5184 172.707 16.5184 172.707 16.6003 201.057 c 0,10,11 + 16.6544 219.793 16.6544 219.793 27 237.5 c 0,12,13 + 49.0431 275.228 49.0431 275.228 99.8393 275.219 c 0,14,15 + 108.956 275.217 108.956 275.217 119 274 c 0,16,-1 + 84 260.5 l 0,17,18 + 68.7059 254.765 68.7059 254.765 68.6159 232.948 c 0,19,20 + 68.5882 226.235 68.5882 226.235 70 218 c 0,21,22 + 77.7819 168.715 77.7819 168.715 121.824 168.025 c 0,23,24 + 136.5 169 l 0,25,26 + 194 177 194 177 206 240 c 0,27,28 + 209.42 259.054 209.42 259.054 209.379 285.629 c 0,29,30 + 209.336 313.444 209.336 313.444 205.5 349.5 c 0,31,32 + 198 420 198 420 144 428 c 0,33,34 + 130.002 426.996 l 0,35,36 + 120.296 423.593 120.296 423.593 114.5 412 c 0,37,38 + 105.001 393 105.001 393 108 376 c 0,39,40 + 114 339 114 339 144 310 c 0,41,42 + 85.9995 325 85.9995 325 65 379 c 0,43,44 + 26 481 26 481 54.5 590 c 0,45,46 + 83.0006 699.003 83.0006 699.003 101 799 c 0,47,48 + 117.001 895 117.001 895 120 939.5 c 0,49,50 + 123 984 123 984 113 1080 c 0,51,52 + 102.999 1161 102.999 1161 66 1248 c 0,53,54 + 32.5449 1326.66 32.5449 1326.66 32.6099 1399.61 c 0,55,56 + 32.6168 1407.34 32.6168 1407.34 33 1415 c 0,57,58 + 35.9995 1475.99 35.9995 1475.99 75 1507 c 0,59,60 + 104.849 1532.01 104.849 1532.01 129.979 1532.28 c 0,61,62 + 149.015 1528.68 l 0,63,64 + 174.29 1518.42 174.29 1518.42 194 1479 c 0,65,66 + 174.301 1496.91 174.301 1496.91 155.139 1496.82 c 0,67,68 + 142.197 1496.77 142.197 1496.77 129.5 1488.5 c 0,69,70 + 98 1467.99 98 1467.99 114 1427 c 0,71,72 + 129.519 1384.33 129.519 1384.33 180 1384 c 0,73,74 + 230.015 1385.01 230.015 1385.01 264 1397 c 0,75,76 + 349.99 1424 349.99 1424 440.5 1495 c 0,77,78 + 517.902 1555.72 517.902 1555.72 599.319 1555.73 c 0,79,80 + 613.102 1555.74 613.102 1555.74 627 1554 c 0,81,82 + 663.003 1548 663.003 1548 683.5 1514 c 0,83,84 + 693.597 1497.25 693.597 1497.25 693.627 1480.75 c 0,85,86 + 693.657 1463.75 693.657 1463.75 683 1447 c 0,87,88 + 675.449 1501.53 675.449 1501.53 628.135 1501.87 c 0,89,90 + 619.051 1501.93 619.051 1501.93 608.5 1500 c 0,91,92 + 543 1488 543 1488 544 1449 c 0,93,94 + 544 1398.96 544 1398.96 594.427 1399.05 c 0,95,96 + 608.5 1399.07 608.5 1399.07 626.5 1403 c 0,97,98 + 708.714 1420.94 708.714 1420.94 744 1428 c 0,99,100 + 789.909 1436.98 789.909 1436.98 850.5 1445.5 c 0,101,102 + 898.275 1448.51 l 0,103,104 + 930.453 1447.79 930.453 1447.79 958 1439 c 0,105,106 + 1070.99 1404.01 1070.99 1404.01 1081 1291 c 0,107,108 + 1073.99 1330 1073.99 1330 1034 1364 c 0,109,110 + 994.899 1396.93 994.899 1396.93 940.501 1397.15 c 0,111,112 + 916.073 1397.25 916.073 1397.25 887.5 1390.5 c 0,113,114 + 798.009 1369.01 798.009 1369.01 749 1327 c 0,115,116 + 721.998 1304.99 721.998 1304.99 717.5 1274 c 0,117,118 + 718.413 1256.86 l 0,119,120 + 723.722 1238.24 723.722 1238.24 749 1227 c 0,121,122 + 777 1215 777 1215 812 1218 c 0,123,124 + 787.164 1197.3 787.164 1197.3 749.528 1197.34 c 0,125,126 + 705.755 1197.38 705.755 1197.38 643.5 1226 c 0,127,128 + 528.99 1279 528.99 1279 452 1279 c 0,129,130 + 393.915 1279 393.915 1279 365 1260.15 c 0,131,132 + 336.453 1241.55 336.453 1241.55 336.306 1204.56 c 0,133,134 + 336.246 1189.34 336.246 1189.34 341 1171 c 0,135,136 + 348.997 1138.01 348.997 1138.01 374.5 1092 c 0,137,138 + 389.671 1064.63 389.671 1064.63 389.799 1041.87 c 0,139,140 + 389.886 1026.37 389.886 1026.37 383 1013 c 0,141,142 + 362.985 972.016 362.985 972.016 319 972 c 0,143,144 + 342.462 1000.49 342.462 1000.49 342.676 1019.78 c 0,145,146 + 342.77 1028.23 342.77 1028.23 338.391 1034.92 c 0,147,148 + 334.882 1040.28 334.882 1040.28 328.5 1044.5 c 0,149,150 + 314.406 1053.82 314.406 1053.82 301.912 1054.03 c 0,151,152 + 287.322 1050.91 l 0,153,154 + 279.271 1047.18 279.271 1047.18 272 1039 c 0,155,156 + 233 997 233 997 254 925.5 c 0,157,158 + 275 854 275 854 342 860 c 0,159,160 + 401 865 401 865 445.5 876.5 c 0,161,162 + 490 888 490 888 544 908 c 0,163,164 + 611 932 611 932 698 901.5 c 0,165,166 + 769.056 876.59 769.056 876.59 769.404 808.654 c 0,167,168 + 769.482 793.41 769.482 793.41 766 776 c 0,169,170 + 758.999 814.001 758.999 814.001 733.5 841.5 c 0,171,172 + 714.8 861.667 714.8 861.667 687.227 861.667 c 0,173,174 + 677.2 861.667 677.2 861.667 666 859 c 0,175,176 + 633 850 633 850 614.5 819.5 c 0,177,178 + 596 789 596 789 590 759 c 0,179,180 + 573 675 573 675 546.5 621 c 0,181,182 + 520 567 520 567 416 594 c 0,183,184 + 492 614 492 614 492 650 c 0,185,186 + 492 714 492 714 427.5 721.5 c 0,187,188 + 363 729 363 729 316 722 c 0,189,190 + 256.001 712 256.001 712 255 658 c 0,191,192 + 252 612 252 612 282 609 c 0,193,194 + 312 606 312 606 307 663 c 0,195,196 + 347 619 347 619 347 589 c 0,197,198 + 345.999 539.999 345.999 539.999 318 514 c 0,199,200 + 290 488 290 488 290 451 c 0,201,202 + 290 385 290 385 327.5 389 c 0,203,204 + 365 393 365 393 414.5 417 c 0,205,206 + 464 441 464 441 512 461 c 0,207,208 + 529.829 468.428 529.829 468.428 544.07 468.407 c 0,209,210 + 568.171 468.371 568.171 468.371 582 447 c 0,211,212 + 611 399 611 399 569 385 c 0,213,214 + 574 412 574 412 544 406 c 0,215,216 + 494 394 494 394 527 349 c 0,217,218 + 550 318 550 318 607 318 c 0,219,220 + 664 318 664 318 694 336 c 0,221,222 + 738 361 738 361 769 401.5 c 0,223,224 + 800 442 800 442 845 464 c 0,225,226 + 890 487 890 487 934 439 c 0,227,228 + 954.533 416.6 954.533 416.6 954.813 395.507 c 0,229,230 + 951.306 377.599 l 0,231,232 + 945.296 362.968 945.296 362.968 929 349 c 0,233,234 + 934.5 365.5 934.5 365.5 934.563 377.5 c 0,235,236 + 934.661 396.45 934.661 396.45 921.2 404.178 c 0,237,238 + 911.841 409.551 911.841 409.551 895.928 409.5 c 0,239,240 + 891.247 409.484 891.247 409.484 886 409 c 0,241,242 + 837.001 403 837.001 403 831.5 357.5 c 0,243,244 + 830.802 321.967 l 0,245,246 + 833.038 298.338 833.038 298.338 843 279 c 0,247,248 + 862.999 236.001 862.999 236.001 911 201.5 c 0,249,250 + 959 167 959 167 990 131 c 0,251,252 + 1021.99 93.9995 1021.99 93.9995 1032 32.5 c 0,253,254 + 1042.01 -29 1042.01 -29 1008 -71 c 0,255,256 + 1011.87 -21.0033 l 0,257,258 + 1011.65 -0.13516 1011.65 -0.13516 1007.5 15 c 0,259,260 + 998.993 46.0079 998.993 46.0079 959 87 c 0,261,262 + 888.999 156.001 888.999 156.001 798 177.5 c 0,263,264 + 706.997 199 706.997 199 611 199 c 0,0,1 +EndSplineSet +KernsSLIF: 115 -78 0 0 +EndChar +StartChar: f +Encoding: 102 102 20 +Width: 1155 +Flags: HMW +HStem: 714 154<374 666> 1301 192<389 965> +VStem: 130 185<147 1541> +Fore +582 828 m 1,0,1 + 584 733 584 733 666 714 c 0,2,3 + 708 705 708 705 746 735 c 0,4,5 + 784 765 784 765 784 764 c 0,6,7 + 778 743 778 743 755 704 c 0,8,9 + 732 665 732 665 694 648 c 0,10,11 + 647 631 647 631 619 637 c 0,12,13 + 591 643 591 643 558 654 c 0,14,15 + 515 670 515 670 466.5 713.5 c 0,16,17 + 418 757 418 757 366 739 c 0,18,19 + 325 717 325 717 316.5 692.5 c 0,20,21 + 308 668 308 668 302 643 c 0,22,23 + 297 613 297 613 285 522 c 0,24,25 + 273 431 273 431 351 435 c 0,26,27 + 369.915 452.305 369.915 452.305 370.366 468.962 c 0,28,29 + 367.282 483.295 l 0,30,31 + 359.337 500.505 359.337 500.505 331 517 c 0,32,33 + 391 513 391 513 416 461 c 0,34,35 + 416 416 416 416 405 396.5 c 0,36,37 + 393.995 376.989 393.995 376.989 377 341 c 0,38,39 + 356 312 356 312 344.5 274.5 c 0,40,41 + 332.999 236.998 332.999 236.998 331 232 c 0,42,43 + 314.682 193.354 314.682 193.354 314.591 158.394 c 0,44,45 + 314.576 152.647 314.576 152.647 315 147 c 0,46,47 + 315 96 315 96 334.5 40.5 c 0,48,49 + 354 -15 354 -15 400 -50 c 0,50,51 + 347 -50 347 -50 312 10.5 c 0,52,53 + 276.998 71.004 276.998 71.004 263 112 c 0,54,55 + 254 179 254 179 231 202 c 0,56,57 + 208.001 224.999 208.001 224.999 181 232 c 0,58,59 + 178.002 232 178.002 232 149.5 225.5 c 0,60,61 + 121.991 219.226 121.991 219.226 122 168 c 0,62,-1 + 135 143.5 l 0,63,64 + 148.001 119 148.001 119 188 110 c 0,65,66 + 149 96.0005 149 96.0005 123.5 105 c 0,67,68 + 98 114 98 114 89 118 c 0,69,70 + 64.9997 130 64.9997 130 54.5 156.5 c 0,71,72 + 44 183.001 44 183.001 44 198 c 0,73,74 + 49 267 49 267 102 320 c 0,75,76 + 117 329 117 329 126 354.5 c 0,77,78 + 135 380 135 380 141 401 c 0,79,80 + 145.001 416 145.001 416 156 493 c 0,81,82 + 166.999 570 166.999 570 162 588 c 0,83,84 + 166.001 613 166.001 613 138 628 c 0,85,86 + 103.999 631 103.999 631 110 585.5 c 0,87,88 + 116 540 116 540 128 528 c 0,89,90 + 95 528 95 528 74 563 c 0,91,92 + 54 587 54 587 56.5 611 c 0,93,94 + 59 635 59 635 66 659 c 0,95,96 + 81 701 81 701 109.5 737 c 0,97,98 + 138.001 773.002 138.001 773.002 158 812 c 0,99,-1 + 166 870.5 l 0,100,101 + 165.864 898.01 l 0,102,103 + 162.564 919.121 162.564 919.121 149 937 c 0,104,105 + 146 943 146 943 107 1000 c 0,106,107 + 69.0001 1055.99 69.0001 1055.99 68 1057 c 0,108,109 + 61.9965 1067.01 61.9965 1067.01 51.5 1114.5 c 0,110,111 + 45.1768 1143.11 45.1768 1143.11 45.2001 1170.08 c 0,112,113 + 45.2154 1187.89 45.2154 1187.89 48 1205 c 0,114,115 + 48 1230 48 1230 73 1261.5 c 0,116,117 + 97.1265 1291.9 97.1265 1291.9 130 1292 c 0,118,119 + 113.751 1265.6 113.751 1265.6 113.775 1238.05 c 0,120,121 + 113.786 1224.91 113.786 1224.91 117.5 1211.5 c 0,122,123 + 126.928 1177.48 126.928 1177.48 158.199 1177.4 c 0,124,125 + 165.072 1177.38 165.072 1177.38 173 1179 c 0,126,127 + 185.001 1181 185.001 1181 200.5 1192.5 c 0,128,129 + 215.999 1204.01 215.999 1204.01 229 1245 c 0,130,131 + 235.158 1271.18 235.158 1271.18 235.095 1298.23 c 0,132,133 + 235.076 1306.33 235.076 1306.33 234.5 1314.5 c 0,134,135 + 231.999 1350.02 231.999 1350.02 228 1386 c 0,136,137 + 221.477 1421.88 221.477 1421.88 182.376 1422.52 c 0,138,139 + 163 1421 l 0,140,141 + 133 1404.12 133 1404.12 132.5 1389 c 0,142,143 + 134.001 1375 134.001 1375 147 1342 c 0,144,145 + 95.9994 1385.01 95.9994 1385.01 93 1440 c 0,146,147 + 93.4391 1473.01 l 0,148,149 + 98.921 1513.54 98.921 1513.54 130 1541 c 0,150,151 + 171.776 1564.77 171.776 1564.77 203.429 1564.68 c 0,152,153 + 215.728 1564.64 215.728 1564.64 226.5 1561 c 0,154,155 + 264.999 1548 264.999 1548 316 1525 c 0,156,-1 + 389 1493 l 0,157,158 + 421.777 1484.32 421.777 1484.32 455.251 1484.36 c 0,159,160 + 491.223 1484.4 491.223 1484.4 528 1494.5 c 0,161,162 + 599.07 1514.02 599.07 1514.02 668 1528 c 0,163,164 + 710.819 1534.32 710.819 1534.32 749.674 1534.23 c 0,165,166 + 766.196 1534.19 766.196 1534.19 782 1533 c 0,167,168 + 835.112 1528.99 835.112 1528.99 895 1519 c 0,169,170 + 974.006 1481.99 974.006 1481.99 984.5 1468.5 c 0,171,-1 + 1013 1433 l 0,172,173 + 995 1439 995 1439 983.5 1448 c 0,174,175 + 972.008 1456.99 972.008 1456.99 946 1461 c 0,176,177 + 879.001 1461 879.001 1461 874.5 1427.5 c 0,178,179 + 869.999 1394 869.999 1394 863 1394 c 0,180,181 + 876.001 1349 876.001 1349 893.5 1334 c 0,182,183 + 911 1319 911 1319 965 1301 c 0,184,185 + 1077 1307 1077 1307 1088.5 1356 c 0,186,187 + 1100.02 1405.08 1100.02 1405.08 1131 1499 c 0,188,189 + 1130.03 1493.23 1130.03 1493.23 1118 1410.5 c 0,190,191 + 1106 1327.99 1106 1327.99 1090 1313 c 0,192,193 + 1070.01 1284.99 1070.01 1284.99 1034.5 1268 c 0,194,195 + 998.966 1250.99 998.966 1250.99 982 1249 c 0,196,197 + 975 1247.01 975 1247.01 938.5 1247.5 c 0,198,199 + 902 1247.99 902 1247.99 892 1258 c 0,200,201 + 868.998 1267 868.998 1267 850.5 1279 c 0,202,-1 + 813 1303 l 0,203,204 + 687 1373.99 687 1373.99 634 1370.5 c 0,205,206 + 581.013 1367.01 581.013 1367.01 458 1313 c 0,207,208 + 436.041 1297.63 436.041 1297.63 436.049 1278.77 c 0,209,210 + 436.052 1271.87 436.052 1271.87 439 1264.5 c 0,211,212 + 450.002 1237 450.002 1237 477 1237 c 0,213,214 + 498 1238.01 498 1238.01 523 1241.5 c 0,215,216 + 547.997 1244.99 547.997 1244.99 569 1290 c 0,217,218 + 566 1278 566 1278 566.5 1251 c 0,219,220 + 563.262 1227.75 l 0,221,222 + 558.754 1212.71 558.754 1212.71 548 1198 c 0,223,224 + 480.001 1158 480.001 1158 407.5 1138 c 0,225,226 + 335.001 1118.01 335.001 1118.01 320 1014 c 0,227,228 + 311 981 311 981 330 935 c 0,229,230 + 349.001 888.999 349.001 888.999 374 868 c 0,231,232 + 386 846 386 846 444 856.5 c 0,233,234 + 502 867 502 867 510 909 c 0,235,236 + 513 960 513 960 484 966.5 c 0,237,238 + 455 973 455 973 425 958 c 0,239,240 + 442 990 442 990 466 1003 c 0,241,242 + 489.104 1011.77 489.104 1011.77 507.76 1011.91 c 0,243,244 + 521.278 1012.01 521.278 1012.01 532.462 1007.57 c 0,245,246 + 558.618 997.189 558.618 997.189 572 962 c 0,247,248 + 576 932 576 932 578 895.5 c 0,249,250 + 579.994 859.099 579.994 859.099 582 828 c 1,0,1 +EndSplineSet +KernsSLIF: 116 -130 0 0 45 -156 0 0 46 -247 0 0 44 -260 0 0 97 -427 0 0 +EndChar +StartChar: g +Encoding: 103 103 21 +Width: 1125 +Flags: HW +Fore +531 22 m 0,0,1 + 468 28 468 28 371.5 79 c 0,2,3 + 275.001 130 275.001 130 247 174 c 0,4,5 + 152.809 313.125 152.809 313.125 152.707 448.145 c 0,6,7 + 152.69 469.373 152.69 469.373 155 490.5 c 0,8,9 + 158.749 561.265 l 0,10,11 + 158.332 681.08 158.332 681.08 112 800 c 0,12,13 + 92.9999 848 92.9999 848 67 898.5 c 0,14,15 + 41 949 41 949 44 979 c 0,16,17 + 48 1033 48 1033 82 1051 c 0,18,19 + 102.837 1062.03 102.837 1062.03 121.423 1062.17 c 0,20,21 + 133.16 1062.26 133.16 1062.26 144 1058 c 0,22,23 + 112.999 1059.99 112.999 1059.99 98 1019 c 0,24,25 + 94.0204 1008.12 94.0204 1008.12 94.0529 999.568 c 0,26,27 + 94.1429 975.877 94.1429 975.877 125 970 c 0,28,29 + 148.219 968.74 l 0,30,31 + 178.448 972.724 178.448 972.724 178.718 1012.41 c 0,32,33 + 174.332 1048.98 l 0,34,35 + 173.496 1052.89 173.496 1052.89 172.5 1057 c 0,36,37 + 148.001 1157.99 148.001 1157.99 147 1186 c 0,38,39 + 142.997 1257.03 142.997 1257.03 140 1300 c 0,40,41 + 142.052 1332.31 l 0,42,43 + 148.094 1367.54 148.094 1367.54 170 1416 c 0,44,45 + 186.001 1453.01 186.001 1453.01 237 1453.5 c 0,46,47 + 288 1453.99 288 1453.99 314 1443 c 0,48,49 + 270 1440 270 1440 253.5 1416 c 0,50,51 + 246.487 1405.8 246.487 1405.8 246.248 1397.05 c 0,52,53 + 249.324 1385.34 l 0,54,55 + 252.262 1380.37 252.262 1380.37 258 1376 c 0,56,57 + 303 1338.01 303 1338.01 359 1428.5 c 0,58,59 + 398.875 1492.94 398.875 1492.94 399.203 1530.76 c 0,60,61 + 399.299 1541.98 399.299 1541.98 395.92 1550.85 c 0,62,63 + 394.69 1554.08 394.69 1554.08 393 1557 c 0,64,65 + 377.944 1581.09 377.944 1581.09 349.102 1581.24 c 0,66,67 + 330.49 1581.34 330.49 1581.34 305 1571 c 0,68,69 + 281.994 1560.99 281.994 1560.99 269 1536 c 0,70,71 + 256.013 1511.02 256.013 1511.02 241 1487 c 0,72,73 + 239.456 1510.96 l 0,74,75 + 242.089 1543.47 242.089 1543.47 266.5 1593 c 0,76,77 + 300.997 1663 300.997 1663 358 1666 c 0,78,79 + 404.325 1669.02 404.325 1669.02 472 1674.5 c 0,80,81 + 540.002 1680.01 540.002 1680.01 578 1685 c 0,82,83 + 636.783 1688.22 l 0,84,85 + 712.691 1687.58 712.691 1687.58 807.5 1664.5 c 0,86,87 + 941 1631.99 941 1631.99 1025 1609 c 0,88,89 + 1068.99 1597 1068.99 1597 1067 1540 c 0,90,91 + 1065.01 1483.01 1065.01 1483.01 1027 1459 c 0,92,93 + 1030.32 1478.67 l 0,94,95 + 1029.52 1500.41 1029.52 1500.41 1008 1519.5 c 0,96,97 + 994.786 1531.22 994.786 1531.22 981.755 1531.41 c 0,98,99 + 966.92 1527.85 l 0,100,101 + 956.905 1522.89 956.905 1522.89 947 1511 c 0,102,103 + 935.923 1498.81 935.923 1498.81 935.889 1480.19 c 0,104,105 + 935.861 1465.19 935.861 1465.19 943 1446 c 0,106,107 + 959 1402.99 959 1402.99 968 1374 c 0,108,109 + 993.985 1296.05 993.985 1296.05 1012.5 1250.5 c 0,110,111 + 1019.83 1232.48 1019.83 1232.48 1019.86 1208.73 c 0,112,113 + 1019.91 1172.52 1019.91 1172.52 1003 1123 c 0,114,115 + 984.998 1068.99 984.998 1068.99 941 1023.5 c 0,116,117 + 897 978 897 978 799 957 c 0,118,119 + 836 986 836 986 890.5 1011.5 c 0,120,121 + 941.81 1035.51 941.81 1035.51 942.154 1105.16 c 0,122,123 + 942.176 1109.49 942.176 1109.49 942 1114 c 0,124,125 + 939.001 1147.99 939.001 1147.99 897 1188 c 0,126,127 + 868.002 1215.62 868.002 1215.62 839 1215.59 c 0,128,129 + 826 1215.57 826 1215.57 813 1210 c 0,130,131 + 770.269 1191.95 770.269 1191.95 769.918 1154.53 c 0,132,133 + 769.899 1152.54 769.899 1152.54 770 1150.5 c 0,134,135 + 772 1110 772 1110 787 1072 c 0,136,137 + 745.147 1100.77 745.147 1100.77 745.109 1156.53 c 0,138,139 + 745.103 1164.73 745.103 1164.73 746 1173.5 c 0,140,141 + 753 1242 753 1242 778 1269 c 0,142,143 + 790 1282.01 790 1282.01 801.5 1306.5 c 0,144,145 + 810.671 1326.03 810.671 1326.03 810.62 1339.53 c 0,146,147 + 810.608 1342.96 810.608 1342.96 810 1346 c 0,148,149 + 797.998 1382.01 797.998 1382.01 746 1412.5 c 0,150,151 + 694 1442.99 694 1442.99 649 1408 c 0,152,153 + 626 1390 626 1390 635 1348 c 0,154,155 + 644 1306 644 1306 645 1279 c 0,156,157 + 642.621 1251.41 l 0,158,159 + 630.999 1203.16 630.999 1203.16 565 1196 c 0,160,161 + 541.843 1195.8 l 0,162,163 + 505.619 1202.1 505.619 1202.1 494 1254 c 0,164,165 + 530 1237.99 530 1237.99 554 1254 c 0,166,167 + 568.571 1263.72 568.571 1263.72 568.767 1282.28 c 0,168,169 + 564.575 1305.54 l 0,170,171 + 563.85 1307.73 563.85 1307.73 563 1310 c 0,172,173 + 556.002 1327.99 556.002 1327.99 512.5 1338 c 0,174,175 + 492.91 1342.51 492.91 1342.51 477.678 1342.55 c 0,176,177 + 459.093 1342.6 459.093 1342.6 447 1336 c 0,178,179 + 390.999 1306 390.999 1306 374 1189.5 c 0,180,181 + 368.629 1152.69 368.629 1152.69 368.648 1121.92 c 0,182,183 + 368.69 1055.3 368.69 1055.3 394 1017 c 0,184,185 + 445 939 445 939 481 878.5 c 0,186,187 + 517 818 517 818 484 752 c 0,188,189 + 474 732 474 732 427 722 c 0,190,191 + 394.04 718.32 l 0,192,193 + 373.463 718.785 373.463 718.785 362 729 c 0,194,195 + 408 737 408 737 416 767 c 0,196,197 + 418.16 790.251 l 0,198,199 + 414.789 827.474 414.789 827.474 362 843 c 0,200,201 + 342 849 342 849 308 846.5 c 0,202,203 + 274.001 844 274.001 844 249 803 c 0,204,205 + 235.692 781.805 235.692 781.805 235.746 730.244 c 0,206,207 + 235.801 677.194 235.801 677.194 250 592 c 0,208,209 + 278 424 278 424 392 394 c 0,210,211 + 452 377 452 377 502 407.5 c 0,212,213 + 552.003 438.002 552.003 438.002 597 455 c 0,214,215 + 692 489 692 489 726 461 c 0,216,217 + 743.193 445.649 743.193 445.649 743.419 427.659 c 0,218,219 + 739.897 410.197 l 0,220,221 + 738.664 407.132 738.664 407.132 737 404 c 0,222,223 + 720 372 720 372 689 374 c 0,224,225 + 706.383 386.233 706.383 386.233 706.771 397.844 c 0,226,227 + 703.446 408.525 l 0,228,229 + 702 410.5 l 0,230,231 + 689.827 425.717 689.827 425.717 679 426 c 0,232,233 + 636 414 636 414 641.5 387.5 c 0,234,235 + 647 361 647 361 668 350 c 0,236,237 + 682.869 341.783 682.869 341.783 698.428 341.834 c 0,238,239 + 722.631 341.913 722.631 341.913 748.5 362 c 0,240,241 + 791.001 395.001 791.001 395.001 814 434 c 0,242,243 + 822.957 450.72 822.957 450.72 823 472.252 c 0,244,245 + 823.029 486.78 823.029 486.78 819 503.5 c 0,246,247 + 809 545 809 545 785 554 c 0,248,249 + 707 584 707 584 645.5 577 c 0,250,251 + 584 570 584 570 500 576 c 0,252,253 + 381.002 583.999 381.002 583.999 333 617.5 c 0,254,255 + 286.238 650.135 286.238 650.135 286 695 c 0,256,257 + 286 715 286 715 301.5 741.5 c 0,258,259 + 316.999 767.999 316.999 767.999 367 775 c 0,260,261 + 324 758 324 758 317.5 716 c 0,262,263 + 311 674 311 674 349 656 c 0,264,265 + 431 614 431 614 521.5 661 c 0,266,267 + 612 708 612 708 643 751 c 0,268,269 + 677 800 677 800 738 807 c 0,270,271 + 784.905 809.042 l 0,272,273 + 808.475 807.683 808.475 807.683 820 800 c 0,274,275 + 834.999 789.001 834.999 789.001 845 763 c 0,276,277 + 848.309 744.846 l 0,278,279 + 847.766 729.405 847.766 729.405 835 716 c 0,280,281 + 835 760 835 760 795.5 755 c 0,282,283 + 756 750 756 750 755 735 c 0,284,285 + 756.786 713.323 l 0,286,287 + 762.156 693.016 762.156 693.016 781.5 674 c 0,288,289 + 811 645 811 645 871 648 c 0,290,291 + 910.248 645.529 l 0,292,293 + 947.216 639.656 947.216 639.656 986.5 620.5 c 0,294,295 + 1047.01 590.994 1047.01 590.994 1052 558 c 0,296,297 + 1062.99 471 1062.99 471 1001 471 c 0,298,299 + 1019 489 1019 489 1008.5 504 c 0,300,301 + 998 519 998 519 980 512 c 0,302,303 + 956 500 956 500 964.5 472.5 c 0,304,305 + 973 445 973 445 979 421 c 0,306,307 + 1007 296 1007 296 995 216.5 c 0,308,309 + 983 137 983 137 959 119 c 0,310,311 + 926 92 926 92 878 77.5 c 0,312,313 + 830 62.9999 830 62.9999 772 97 c 0,314,315 + 752.299 108.492 752.299 108.492 752.139 146.266 c 0,316,317 + 752.105 154.507 752.105 154.507 753 164 c 0,318,319 + 757.001 139.999 757.001 139.999 788 135 c 0,320,321 + 803.325 136.102 l 0,322,323 + 822.734 142.8 822.734 142.8 833 178 c 0,324,325 + 833.161 192.353 l 0,326,327 + 828.613 207.514 828.613 207.514 801.5 213.5 c 0,328,329 + 763 222.001 763 222.001 712 219.5 c 0,330,331 + 660.992 216.999 660.992 216.999 615.5 208.5 c 0,332,333 + 569.999 199.999 569.999 199.999 564 194 c 0,334,335 + 540 166.999 540 166.999 539.5 154 c 0,336,337 + 545.209 121.479 l 0,338,339 + 547.604 112.321 547.604 112.321 551 101 c 0,340,341 + 563 56 563 56 616.5 56.5 c 0,342,343 + 670 57 670 57 706 87 c 0,344,345 + 679 21 679 21 608.5 21 c 0,346,347 + 538 21 538 21 531 22 c 0,0,1 +EndSplineSet +EndChar +StartChar: h +Encoding: 104 104 22 +Width: 1191 +Flags: HMW +HStem: 703 272.5<432 788> +VStem: 135 206<140 1374> 826 179<65 1404> +Fore +127 803.5 m 128,-1,0 + 68.0001 857 68.0001 857 53 931 c 0,1,2 + 49.5493 964.928 l 0,3,4 + 50.165 1001.61 50.165 1001.61 70.5 1034 c 0,5,6 + 98.0227 1077.85 98.0227 1077.85 139.03 1078.18 c 0,7,8 + 141.981 1078.2 141.981 1078.2 145 1078 c 0,9,10 + 181 1075 181 1075 181 1040 c 0,11,12 + 169.272 1049.99 169.272 1049.99 158.394 1049.98 c 0,13,14 + 144.227 1049.97 144.227 1049.97 131.5 1033 c 0,15,16 + 109 1003 109 1003 130 971 c 0,17,18 + 136.001 959.999 136.001 959.999 173.5 956.5 c 0,19,20 + 189.848 958.247 l 0,21,22 + 212.456 966.35 212.456 966.35 217 1008 c 0,23,24 + 225.997 1101.98 225.997 1101.98 239.5 1188.5 c 0,25,26 + 244.674 1221.65 244.674 1221.65 244.634 1246.07 c 0,27,28 + 244.568 1285.35 244.568 1285.35 231 1302 c 0,29,30 + 225.057 1308.34 225.057 1308.34 215.502 1308.4 c 0,31,32 + 200.945 1308.49 200.945 1308.49 178 1294 c 0,33,34 + 157.734 1281.2 157.734 1281.2 157.662 1260.72 c 0,35,36 + 157.6 1242.8 157.6 1242.8 173 1219 c 0,37,38 + 130.636 1246.72 130.636 1246.72 130.124 1278.13 c 0,39,40 + 133.771 1297.81 l 0,41,42 + 141.244 1317.48 141.244 1317.48 164 1338.5 c 0,43,44 + 235.991 1404.99 235.991 1404.99 264 1467 c 0,45,46 + 292.005 1530.01 292.005 1530.01 337.5 1584.5 c 0,47,48 + 378.252 1633.31 378.252 1633.31 445.867 1633.59 c 0,49,50 + 453.751 1633.63 453.751 1633.63 462 1633 c 0,51,52 + 492.977 1622.01 492.977 1622.01 512.5 1606.5 c 0,53,54 + 532 1591.01 532 1591.01 544 1548 c 0,55,56 + 540.999 1565 540.999 1565 476 1596.5 c 0,57,58 + 461.045 1603.75 461.045 1603.75 446.989 1603.66 c 0,59,60 + 399.957 1603.38 399.957 1603.38 363 1521 c 0,61,62 + 335 1458 335 1458 341 1374 c 0,63,64 + 345.999 1298.01 345.999 1298.01 401 1223.5 c 0,65,66 + 456 1148.99 456 1148.99 438 1078 c 0,67,68 + 432 1055.01 432 1055.01 392 1046.5 c 0,69,70 + 356.819 1042.14 l 0,71,72 + 345.962 1042.39 345.962 1042.39 341 1046 c 0,73,74 + 372 1050.01 372 1050.01 383 1068.5 c 0,75,76 + 394 1087 394 1087 394 1089 c 0,77,78 + 391.033 1111.52 l 0,79,80 + 384.862 1131.96 384.862 1131.96 366 1150.5 c 0,81,82 + 337 1179 337 1179 319 1143 c 0,83,84 + 308 1120 308 1120 306 1063 c 0,85,86 + 304 1007.01 304 1007.01 304 1006 c 0,87,88 + 311.001 954.998 311.001 954.998 331.5 922 c 0,89,90 + 352 889 352 889 355 888 c 0,91,92 + 376 870 376 870 401 872 c 0,93,94 + 426 874 426 874 438 880 c 0,95,96 + 530 922 530 922 561.5 962 c 0,97,98 + 593 1002 593 1002 665 995 c 0,99,100 + 690 984 690 984 702.5 966.5 c 0,101,102 + 709.4 956.839 709.4 956.839 709.444 938.8 c 0,103,104 + 709.48 924.16 709.48 924.16 705 904 c 0,105,106 + 693 873 693 873 662 868 c 0,107,108 + 677 883 677 883 670 902.5 c 0,109,110 + 663 922 663 922 642 907 c 0,111,112 + 616.157 887.496 616.157 887.496 616.111 872.628 c 0,113,114 + 616.062 857.004 616.062 857.004 644.5 846.5 c 0,115,116 + 700 826 700 826 736 829 c 0,117,118 + 749 829 749 829 796 843 c 0,119,120 + 828.07 852.553 828.07 852.553 828.48 888.646 c 0,121,122 + 824.428 919.069 l 0,123,124 + 823.356 923.414 823.356 923.414 822 928 c 0,125,126 + 813 955 813 955 788 975.5 c 0,127,128 + 763 996 763 996 760 1030 c 0,129,130 + 761.054 1063.96 l 0,131,132 + 765.883 1095.56 765.883 1095.56 786 1115 c 0,133,134 + 801 1130 801 1130 836 1139 c 0,135,136 + 856.93 1140.92 l 0,137,138 + 879.097 1138.97 879.097 1138.97 897 1119 c 0,139,140 + 870.531 1116.71 l 0,141,142 + 834.782 1108.19 834.782 1108.19 828 1069 c 0,143,144 + 819 1016.99 819 1016.99 886 1003 c 0,145,146 + 901.604 1002.82 l 0,147,148 + 929.362 1010.06 929.362 1010.06 938.5 1076 c 0,149,150 + 947.659 1142.1 947.659 1142.1 947.621 1174.59 c 0,151,152 + 947.611 1182.89 947.611 1182.89 947 1189 c 0,153,154 + 941 1229.01 941 1229.01 888.5 1304.5 c 0,155,156 + 836.007 1379.99 836.007 1379.99 826 1404 c 0,157,158 + 814 1428 814 1428 803.5 1483.5 c 0,159,160 + 801.65 1512.46 l 0,161,162 + 804.299 1550.56 804.299 1550.56 835 1582 c 0,163,164 + 857.909 1604.91 857.909 1604.91 909.781 1604.88 c 0,165,166 + 928.085 1604.87 928.085 1604.87 950 1602 c 0,167,168 + 1004 1593 1004 1593 1051 1552 c 0,169,170 + 1042.01 1552 1042.01 1552 1017 1564 c 0,171,172 + 991.995 1576 991.995 1576 974 1576 c 0,173,174 + 922.993 1576 922.993 1576 888.5 1552.5 c 0,175,176 + 854 1528.99 854 1528.99 866 1488 c 0,177,178 + 895.617 1379.71 895.617 1379.71 952.652 1379.79 c 0,179,180 + 957.237 1379.79 957.237 1379.79 962 1380.5 c 0,181,182 + 1026 1389.99 1026 1389.99 1031 1408 c 0,183,184 + 1035.9 1426.38 1035.9 1426.38 1035.96 1441.59 c 0,185,186 + 1036.05 1463.62 1036.05 1463.62 1026 1479 c 0,187,188 + 1008.99 1505.02 1008.99 1505.02 988 1531 c 0,189,190 + 1019.01 1531 1019.01 1531 1055.5 1484.5 c 0,191,192 + 1092 1437.99 1092 1437.99 1092 1410 c 0,193,194 + 1092 1347.98 1092 1347.98 1079 1275 c 0,195,196 + 1075.15 1253.41 1075.15 1253.41 1075.25 1228.33 c 0,197,198 + 1075.46 1168.59 1075.46 1168.59 1098 1089 c 0,199,-1 + 1121 1002 l 0,200,201 + 1132 959.981 1132 959.981 1132 918 c 0,202,203 + 1132 897.007 1132 897.007 1110.5 867 c 0,204,205 + 1089.01 837 1089.01 837 1041 834 c 0,206,207 + 1041 835.996 1041 835.996 1070 858 c 0,208,209 + 1089.94 873.128 1089.94 873.128 1090.02 897.703 c 0,210,211 + 1090.06 908.876 1090.06 908.876 1086 922 c 0,212,213 + 1080.13 929.035 1080.13 929.035 1071.18 929.025 c 0,214,215 + 1064.86 929.017 1064.86 929.017 1057 925.5 c 0,216,217 + 1037.99 917 1037.99 917 1027 896 c 0,218,219 + 1017 877.014 1017 877.014 1008 827 c 0,220,221 + 999 777 999 777 1002 750 c 0,222,223 + 1008 693 1008 693 1029 649 c 0,224,225 + 1049.99 605.018 1049.99 605.018 1057 568 c 0,226,227 + 1065.62 522.606 1065.62 522.606 1065.65 492.89 c 0,228,229 + 1065.68 470.899 1065.68 470.899 1061 457.5 c 0,230,231 + 1050.01 426 1050.01 426 1037 410 c 0,232,233 + 1026.99 403.997 1026.99 403.997 1003.5 399.5 c 0,234,235 + 980 395 980 395 956 412 c 0,236,237 + 996 414 996 414 1007 431 c 0,238,-1 + 1013.5 458.5 l 0,239,240 + 1019.99 486 1019.99 486 976 492 c 0,241,242 + 958 493 958 493 938 468 c 0,243,244 + 918 443 918 443 924 368 c 0,245,246 + 930 275 930 275 958.5 213.5 c 0,247,248 + 987 152 987 152 1005 65 c 0,249,250 + 1015.71 15.0325 1015.71 15.0325 1015.71 -24.0976 c 0,251,252 + 1015.72 -116.534 1015.72 -116.534 956 -148.5 c 0,253,254 + 871.999 -194 871.999 -194 871 -194 c 0,255,256 + 807.664 -196.104 l 0,257,258 + 805.354 -196.059 805.354 -196.059 803 -196 c 0,259,260 + 762.999 -194.999 762.999 -194.999 733 -171 c 0,261,262 + 769.5 -185 769.5 -185 803 -185 c 0,263,264 + 836.5 -185 836.5 -185 867 -171 c 0,265,266 + 916 -147 916 -147 946.5 -108 c 0,267,268 + 977 -69 977 -69 938 -15 c 0,269,270 + 880 65 880 65 804.5 82 c 0,271,272 + 729 98.9999 729 98.9999 711 115 c 0,273,274 + 659.39 157.887 659.39 157.887 659.297 204.209 c 0,275,276 + 659.263 221.612 659.263 221.612 666.5 239.5 c 0,277,278 + 692.165 302.937 692.165 302.937 729 303 c 0,279,280 + 755 301 755 301 782 267 c 0,281,282 + 765.311 274.586 765.311 274.586 752.937 274.547 c 0,283,284 + 732.689 274.483 732.689 274.483 724 254 c 0,285,286 + 717.578 239.322 717.578 239.322 717.375 227.964 c 0,287,288 + 720.614 212.702 l 0,289,290 + 727.42 199.291 727.42 199.291 748.5 193.5 c 0,291,292 + 777.978 188.543 l 0,293,294 + 794 188.725 794 188.725 794 200 c 0,295,296 + 804.307 216.492 804.307 216.492 804.227 252.578 c 0,297,298 + 804.19 269.008 804.19 269.008 802 289.5 c 0,299,300 + 795 355 795 355 790 384 c 0,301,302 + 743 459 743 459 706 463 c 0,303,304 + 669 467 669 467 646 494 c 0,305,306 + 608 533 608 533 605 558 c 0,307,308 + 605.804 586.508 l 0,309,310 + 607.893 599.607 607.893 599.607 613 614 c 0,311,312 + 633 671 633 671 688 646 c 0,313,314 + 671 636.999 671 636.999 664.5 615.5 c 0,315,316 + 658 594 658 594 687 597 c 0,317,318 + 715 600 715 600 738 611.5 c 0,319,320 + 755.674 620.337 755.674 620.337 755.633 643.64 c 0,321,322 + 755.621 650.663 755.621 650.663 754 659 c 0,323,324 + 738 743 738 743 618 748.5 c 0,325,326 + 536.449 748.89 l 0,327,328 + 483.089 746.152 483.089 746.152 460 734 c 0,329,330 + 445 715 445 715 432 703 c 0,331,332 + 419 691 419 691 438 619 c 0,333,334 + 443 598 443 598 450 559 c 0,335,336 + 450.723 535.595 l 0,337,338 + 447.5 513.776 447.5 513.776 428 501 c 0,339,340 + 405.482 487.63 405.482 487.63 374.545 487.63 c 0,341,342 + 361.519 487.63 361.519 487.63 347 490 c 0,343,344 + 377 495 377 495 395.5 526.5 c 0,345,346 + 414 558 414 558 369 566 c 0,347,348 + 349 569 349 569 332.5 547 c 0,349,350 + 316 525 316 525 316 498 c 0,351,352 + 313 405 313 405 348 338.5 c 0,353,354 + 383 272 383 272 375 218 c 0,355,356 + 369 179 369 179 356 170 c 0,357,358 + 343 161.001 343 161.001 316 154 c 0,359,360 + 321.999 174.997 321.999 174.997 328.5 188 c 0,361,362 + 335 201.001 335 201.001 317 218 c 0,363,364 + 311.667 222.445 311.667 222.445 302.185 222.543 c 0,365,366 + 277.896 218.022 l 0,367,368 + 275.037 217.104 275.037 217.104 272 216 c 0,369,370 + 233.492 201.671 233.492 201.671 233.078 159.275 c 0,371,372 + 233.03 154.328 233.03 154.328 233.5 149 c 0,373,374 + 238 98 238 98 256 85 c 0,375,376 + 275.001 69.9993 275.001 69.9993 307.5 58 c 0,377,378 + 318.436 53.9621 318.436 53.9621 333.958 54.0004 c 0,379,380 + 364.564 54.0758 364.564 54.0758 413 70 c 0,381,-1 + 455 97 l 0,382,383 + 497 124 497 124 536 214 c 0,384,385 + 507.999 117.999 507.999 117.999 450 58 c 0,386,387 + 431 37 431 37 345.5 14 c 0,388,389 + 260 -8.99999 260 -8.99999 185 48 c 0,390,391 + 136.001 84.9993 136.001 84.9993 135 140 c 0,392,393 + 136 210 l 0,394,395 + 139 246.001 139 246.001 179 333 c 0,396,397 + 219 419.999 219 419.999 219 429 c 0,398,399 + 219 448.008 219 448.008 224.5 542 c 0,400,401 + 225.127 611.157 l 0,402,403 + 222.808 651.23 222.808 651.23 213 672 c 0,404,405 + 186 749.999 186 749.999 127 803.5 c 128,-1,0 +EndSplineSet +KernsSLIF: 97 -104 0 0 +EndChar +StartChar: i +Encoding: 105 105 52 +Width: 526 +Flags: HMW +VStem: 191.5 208.5<315 1320> +Fore +205 552 m 0,0,1 + 199 642 199 642 115 721.5 c 0,2,3 + 31 801 31 801 50 897 c 0,4,5 + 62 963 62 963 107.5 979 c 0,6,7 + 126.311 982.037 l 0,8,9 + 158.637 980.476 158.637 980.476 179 928 c 0,10,-1 + 170 941 l 0,11,12 + 150.714 957.786 150.714 957.786 136.276 958.117 c 0,13,14 + 124.188 955.041 l 0,15,16 + 107.697 945.447 107.697 945.447 100 906 c 0,17,18 + 83.9999 824 83.9999 824 177 839 c 0,19,20 + 211.046 843.346 211.046 843.346 211.247 915.645 c 0,21,22 + 211.323 943.154 211.323 943.154 206.5 980.5 c 0,23,24 + 188.999 1116 188.999 1116 169 1146 c 0,25,26 + 113.997 1227 113.997 1227 78.5 1264.5 c 0,27,28 + 43 1302 43 1302 52 1362 c 0,29,30 + 65.9993 1475.99 65.9993 1475.99 194 1510 c 0,31,32 + 131 1477 131 1477 115 1421.5 c 0,33,34 + 105.515 1388.6 105.515 1388.6 105.519 1365.36 c 0,35,36 + 105.521 1349.4 105.521 1349.4 110 1338 c 0,37,38 + 126.105 1312.23 126.105 1312.23 155.28 1312.19 c 0,39,40 + 171.396 1312.17 171.396 1312.17 191.5 1320 c 0,41,42 + 248.008 1342.01 248.008 1342.01 260 1354 c 0,43,44 + 351 1459 351 1459 318.5 1576 c 0,45,46 + 285.999 1693 285.999 1693 138 1732 c 0,47,48 + 229.001 1732 229.001 1732 307.5 1652.5 c 0,49,50 + 386 1573 386 1573 395 1486 c 0,51,52 + 399.999 1414.01 399.999 1414.01 419.5 1348.5 c 0,53,54 + 439.003 1282.98 439.003 1282.98 454 1208 c 0,55,56 + 460.003 1169.99 460.003 1169.99 470.5 1139.5 c 0,57,58 + 480.116 1111.57 480.116 1111.57 480 1092 c 0,59,60 + 472 1015 472 1015 391 1015 c 0,61,62 + 426 1042 426 1042 434 1089 c 0,63,64 + 433.926 1106.55 l 0,65,66 + 427.642 1134.17 427.642 1134.17 377.246 1134.08 c 0,67,68 + 374.678 1134.08 374.678 1134.08 372 1134 c 0,69,70 + 313 1138.99 313 1138.99 322.5 1005 c 0,71,72 + 331.999 871.009 331.999 871.009 335 845 c 0,73,74 + 340 786 340 786 385 790.5 c 0,75,76 + 430 795 430 795 409 870 c 0,77,78 + 403 889 403 889 371 925 c 0,79,80 + 383 918 383 918 396 908.5 c 0,81,82 + 409 899 409 899 430 872 c 0,83,84 + 502 780 502 780 421 671 c 0,85,86 + 340 562 340 562 349 454 c 0,87,88 + 355 373 355 373 400 315 c 0,89,90 + 445 257 445 257 448 179 c 0,91,92 + 450 117.999 450 117.999 396 98 c 0,93,94 + 342 78.0001 342 78.0001 290 81 c 0,95,96 + 354.192 91.6986 354.192 91.6986 354.5 154 c 0,97,98 + 353 216 353 216 282 222 c 0,99,100 + 255.63 220.575 l 0,101,102 + 205.536 210.268 205.536 210.268 205.16 138.129 c 0,103,104 + 205.095 125.728 205.095 125.728 206.5 111.5 c 0,105,106 + 218.001 -5.00005 218.001 -5.00005 247 -50 c 0,107,108 + 286 -113 286 -113 340.5 -144.5 c 0,109,110 + 395.002 -176.002 395.002 -176.002 422 -201 c 0,111,112 + 371.997 -183.999 371.997 -183.999 343 -169.5 c 0,113,114 + 313.991 -154.995 313.991 -154.995 275 -130 c 0,115,116 + 275 -129 275 -129 243 -97.5 c 0,117,118 + 210.998 -65.998 210.998 -65.998 194 -32 c 0,119,120 + 157 40.9986 157 40.9986 145 119 c 0,121,122 + 142.267 162.201 l 0,123,124 + 143.819 218.362 143.819 218.362 172 274 c 0,125,126 + 202.001 337.001 202.001 337.001 205.5 410.5 c 0,127,128 + 206.608 515.08 l 0,129,130 + 206.074 533.739 206.074 533.739 205 552 c 0,0,1 +EndSplineSet +EndChar +StartChar: j +Encoding: 106 106 64 +Width: 1080 +Flags: MW +HStem: -47.5 237.5<360.5 947> 1275.5 183.5<208 649> +VStem: 252 108.5<-47.5 596> 669 237.5<211 1492.5> +Fore +255 -50 m 0,0,1 + 219 -44 219 -44 180 -8 c 0,2,3 + 140.999 28.0006 140.999 28.0006 130 92 c 0,4,5 + 161.001 39 161.001 39 184 36 c 0,6,7 + 226 27 226 27 244 53 c 0,8,9 + 262 78.9999 262 78.9999 262 117 c 0,10,11 + 262 170.001 262 170.001 215.5 215.5 c 0,12,13 + 195.259 235.306 195.259 235.306 184.586 235.69 c 0,14,15 + 177.625 232.939 l 0,16,17 + 172.716 227.713 172.716 227.713 172.683 212.589 c 0,18,19 + 172.675 208.633 172.675 208.633 173 204 c 0,20,21 + 175.94 158.921 175.94 158.921 220 154 c 0,22,23 + 205.32 137.485 205.32 137.485 189.331 137.245 c 0,24,25 + 173.596 140.802 l 0,26,27 + 171.063 141.962 171.063 141.962 168.5 143.5 c 0,28,29 + 141 160 141 160 132 177 c 0,30,31 + 116.083 207.737 116.083 207.737 116.132 244.8 c 0,32,33 + 116.173 275.264 116.173 275.264 127 310 c 0,34,35 + 149.002 388.004 149.002 388.004 183 459.5 c 0,36,37 + 217.001 531 217.001 531 252 596 c 0,38,39 + 300 686 300 686 385 763.5 c 0,40,41 + 470 841 470 841 572 865 c 0,42,43 + 452 817 452 817 372 659 c 0,44,45 + 292 501 292 501 319 377 c 0,46,47 + 327 335 327 335 358 309.5 c 0,48,49 + 389 284 389 284 418 317 c 0,50,51 + 439 340 439 340 437 371.5 c 0,52,53 + 435 403 435 403 428 421 c 0,54,55 + 415 445 415 445 383 459 c 0,56,57 + 427 468 427 468 457 437.5 c 0,58,59 + 487 407 487 407 493 379 c 0,60,61 + 493.982 342.219 l 0,62,63 + 493.618 336.582 493.618 336.582 493 330.5 c 0,64,65 + 490 301 490 301 490 290 c 0,66,67 + 485 218 485 218 501.5 197 c 0,68,69 + 518 176 518 176 550 167 c 0,70,71 + 568.655 161.454 568.655 161.454 585.468 161.5 c 0,72,73 + 635.344 161.638 635.344 161.638 669 211 c 0,74,75 + 699 253 699 253 713.5 309.5 c 0,76,77 + 727.999 365.993 727.999 365.993 735 420 c 0,78,79 + 737.068 472.341 l 0,80,81 + 737.037 473.416 737.037 473.416 737 474.5 c 0,82,83 + 736 504 736 504 706 504 c 0,84,85 + 677 504 677 504 676 481 c 0,86,87 + 678.327 455.139 l 0,88,89 + 680.053 448.527 680.053 448.527 683 443 c 0,90,91 + 665 443 665 443 646 455 c 0,92,93 + 627 466.999 627 466.999 626 516 c 0,94,95 + 625 546 625 546 644 570.5 c 0,96,97 + 662.998 594.996 662.998 594.996 676 623 c 0,98,99 + 709.998 696.995 709.998 696.995 715.5 722.5 c 0,100,101 + 721 748 721 748 717 807 c 0,102,103 + 712 871 712 871 633 960 c 0,104,105 + 593.041 1005.01 593.041 1005.01 592.994 1048.5 c 0,106,107 + 592.948 1090.98 592.948 1090.98 631 1132 c 0,108,109 + 641.561 1144.18 641.561 1144.18 666.649 1144.16 c 0,110,111 + 672.436 1144.16 672.436 1144.16 679 1143.5 c 0,112,113 + 714 1140.01 714 1140.01 722 1098 c 0,114,115 + 704 1108.99 704 1108.99 683 1104 c 0,116,117 + 662 1099.01 662 1099.01 662 1084 c 0,118,119 + 662 1042.15 662 1042.15 683.378 1041.11 c 0,120,121 + 695 1043 l 0,122,123 + 727.992 1053.99 727.992 1053.99 746 1072 c 0,124,125 + 770 1094.01 770 1094.01 774 1189 c 0,126,127 + 773.549 1259.71 l 0,128,129 + 770.677 1299.08 770.677 1299.08 761 1319 c 0,130,131 + 752.033 1336.18 752.033 1336.18 732.184 1336.34 c 0,132,133 + 725.465 1336.4 725.465 1336.4 717.5 1334.5 c 0,134,135 + 686 1327 686 1327 685 1312 c 0,136,137 + 686.41 1290.57 l 0,138,139 + 690.959 1275 690.959 1275 707.5 1275 c 0,140,141 + 733 1275 733 1275 744 1284 c 0,142,143 + 742.032 1266.13 l 0,144,145 + 737.373 1252.41 737.373 1252.41 722.5 1244.5 c 0,146,147 + 704.631 1235 704.631 1235 692.267 1235.03 c 0,148,149 + 688.359 1235.04 688.359 1235.04 685 1236 c 0,150,151 + 637 1246.01 637 1246.01 605.5 1276.5 c 0,152,153 + 573.985 1307.01 573.985 1307.01 541 1328 c 0,154,155 + 501.957 1352.08 501.957 1352.08 460.364 1352.02 c 0,156,157 + 438.049 1351.98 438.049 1351.98 415 1345 c 0,158,159 + 349.045 1325.02 349.045 1325.02 313 1310 c 0,160,161 + 268 1290.99 268 1290.99 208 1275.5 c 0,162,163 + 154.836 1261.77 154.836 1261.77 133.861 1261.77 c 0,164,165 + 131.164 1261.77 131.164 1261.77 129 1262 c 0,166,167 + 44.9994 1268 44.9994 1268 35.5 1354.5 c 0,168,169 + 35.3657 1387.6 l 0,170,171 + 42.3818 1445.56 42.3818 1445.56 105 1463 c 0,172,173 + 85.0001 1448 85.0001 1448 66.5 1410.5 c 0,174,175 + 48 1373 48 1373 83 1337 c 0,176,177 + 101.794 1316.6 101.794 1316.6 129.668 1316.66 c 0,178,179 + 153.708 1316.72 153.708 1316.72 184.5 1332 c 0,180,181 + 250.996 1365 250.996 1365 271 1397 c 0,182,183 + 317 1470.99 317 1470.99 305.5 1493 c 0,184,185 + 296.454 1510.31 296.454 1510.31 278.433 1510.29 c 0,186,187 + 273.547 1510.28 273.547 1510.28 268 1509 c 0,188,189 + 262.002 1507.01 262.002 1507.01 259 1493 c 0,190,191 + 259.794 1481.77 l 0,192,193 + 262.522 1475.09 262.522 1475.09 271 1470 c 0,194,195 + 256.877 1463.14 256.877 1463.14 244.871 1463.2 c 0,196,197 + 227.122 1463.29 227.122 1463.29 214 1478.5 c 0,198,199 + 198.496 1496.47 198.496 1496.47 198.388 1526.11 c 0,200,201 + 198.342 1538.53 198.342 1538.53 201 1553 c 0,202,203 + 207.001 1586.01 207.001 1586.01 242 1595.5 c 0,204,205 + 266.917 1602.26 266.917 1602.26 282.695 1602.19 c 0,206,207 + 289.097 1602.16 289.097 1602.16 294 1601 c 0,208,209 + 387 1574 387 1574 463.5 1518.5 c 0,210,211 + 539.993 1463.01 539.993 1463.01 649 1459 c 0,212,213 + 689 1457.01 689 1457.01 755 1462 c 0,214,215 + 821 1466.99 821 1466.99 821 1518 c 0,216,217 + 821 1536 821 1536 791.5 1551 c 0,218,219 + 770.962 1561.44 770.962 1561.44 759.876 1561.71 c 0,220,221 + 752 1560 l 0,222,223 + 728.999 1546.99 728.999 1546.99 728.5 1532 c 0,224,225 + 730 1495 l 0,226,227 + 707.38 1502.02 707.38 1502.02 706.967 1528.51 c 0,228,229 + 708.5 1545 l 0,230,231 + 716 1585.99 716 1585.99 742 1599 c 0,232,233 + 772 1614 772 1614 815 1606.5 c 0,234,235 + 858 1599 858 1599 872 1578 c 0,236,237 + 903 1528.99 903 1528.99 906.5 1492.5 c 0,238,239 + 910 1456 910 1456 910 1399 c 0,240,-1 + 898.5 1243 l 0,241,242 + 896.911 1175.05 l 0,243,244 + 898.939 1126.57 898.939 1126.57 912 1098 c 0,245,246 + 927.997 1059.01 927.997 1059.01 948.5 1028 c 0,247,248 + 969.009 996.982 969.009 996.982 985 968 c 0,249,250 + 1005.99 929.012 1005.99 929.012 1017.5 836.5 c 0,251,252 + 1020.61 785.11 l 0,253,254 + 1019.37 739.187 1019.37 739.187 999 729 c 0,255,256 + 996.499 765.333 l 0,257,258 + 990.165 800.003 990.165 800.003 968.5 828 c 0,259,260 + 952.652 848.479 952.652 848.479 937.876 848.987 c 0,261,262 + 925.717 845.927 l 0,263,264 + 916.644 840.966 916.644 840.966 908 828 c 0,265,266 + 890 801 890 801 874 737 c 0,267,268 + 869.307 718.227 869.307 718.227 869.26 704.013 c 0,269,270 + 869.16 673.848 869.16 673.848 889.99 664.225 c 0,271,272 + 892.805 662.925 892.805 662.925 896 662 c 0,273,274 + 915.755 658.584 l 0,275,276 + 933.115 659.596 933.115 659.596 937.5 679.5 c 0,277,278 + 938.669 701.65 l 0,279,280 + 936.562 720.529 936.562 720.529 924 740 c 0,281,282 + 950 740 950 740 966 706 c 0,283,284 + 998 636 998 636 940.5 543 c 0,285,286 + 883 450 883 450 858 387 c 0,287,288 + 843 349.999 843 349.999 838.5 301 c 0,289,290 + 834 252 834 252 834 216 c 0,291,292 + 834 203.999 834 203.999 842.5 187 c 0,293,294 + 847.793 176.415 847.793 176.415 856.768 175.91 c 0,295,296 + 869 179 l 0,297,298 + 896.475 191.623 896.475 191.623 896.655 213.346 c 0,299,300 + 896.718 220.876 896.718 220.876 893.5 229.5 c 0,301,302 + 881 262.999 881 262.999 863 279 c 0,303,304 + 874.769 279.858 l 0,305,306 + 891.15 276.301 891.15 276.301 914.5 249 c 0,307,308 + 947 211.001 947 211.001 947 190 c 0,309,310 + 947 156.003 947 156.003 936 104 c 0,311,312 + 925 51.9999 925 51.9999 886 41 c 0,313,314 + 856.875 32.6783 856.875 32.6783 826.709 32.6667 c 0,315,316 + 820.626 32.6643 820.626 32.6643 814.5 33 c 0,317,318 + 778 35 778 35 742 34 c 0,319,320 + 670 25 670 25 596.5 17.5 c 0,321,322 + 523 10 523 10 459 -15 c 0,323,324 + 406.003 -35.9992 406.003 -35.9992 360.5 -47.5 c 0,325,326 + 315 -59 315 -59 255 -50 c 0,0,1 +EndSplineSet +EndChar +StartChar: k +Encoding: 107 107 23 +Width: 1113 +Flags: HMW +VStem: 40.7998 249.9<-11.0498 1388.9> +Fore +542.3 268.6 m 0,0,1 + 502.35 267.749 502.35 267.749 527 232.9 c 0,2,3 + 547.932 203.306 547.932 203.306 581.122 203.133 c 0,4,5 + 587.018 203.102 587.018 203.102 593.3 204 c 0,6,7 + 577.164 190.016 577.164 190.016 552.009 189.986 c 0,8,9 + 537.411 189.968 537.411 189.968 519.775 194.65 c 0,10,11 + 471.751 207.4 471.751 207.4 455.6 235.45 c 0,12,13 + 425.85 283.901 425.85 283.901 408 377.4 c 0,14,15 + 390.15 470.899 390.15 470.899 319.6 499.8 c 0,16,17 + 306.85 504.9 306.85 504.9 279.225 497.675 c 0,18,19 + 251.601 490.45 251.601 490.45 243.1 468.35 c 0,20,21 + 238.176 456.204 238.176 456.204 238.133 444.692 c 0,22,23 + 238.064 426.395 238.064 426.395 250.325 409.7 c 0,24,-1 + 290.7 352.75 l 0,25,26 + 313.651 314.499 313.651 314.499 317.9 257.55 c 0,27,28 + 316.954 221.448 l 0,29,30 + 312.315 189.03 312.315 189.03 293.25 166.6 c 0,31,32 + 292.4 170.001 292.4 170.001 290.7 208.675 c 0,33,34 + 289.493 236.149 289.493 236.149 266.675 236.651 c 0,35,36 + 244.032 232.428 l 0,37,38 + 242.322 231.853 242.322 231.853 240.55 231.2 c 0,39,40 + 224.401 225.25 224.401 225.25 217.175 140.675 c 0,41,42 + 209.949 56.0996 209.949 56.0996 246.5 56.0996 c 0,43,44 + 274.994 56.0996 274.994 56.0996 275.542 70.5434 c 0,45,46 + 275.632 72.904 275.632 72.904 274.975 75.6504 c 0,47,48 + 270.299 95.2002 270.299 95.2002 258.4 107.95 c 0,49,50 + 306.849 92.6506 306.849 92.6506 311.525 53.5498 c 0,51,52 + 316.201 14.4502 316.201 14.4502 290.7 -11.0498 c 0,53,54 + 245.652 -54.3987 245.652 -54.3987 189.125 -88.4004 c 0,55,56 + 132.6 -122.4 132.6 -122.4 132.6 -188.7 c 0,57,58 + 132.6 -251.601 132.6 -251.601 195.925 -280.075 c 0,59,60 + 255.893 -307.04 255.893 -307.04 337.584 -306.945 c 0,61,62 + 342.157 -306.94 342.157 -306.94 346.8 -306.85 c 0,63,64 + 196.35 -334.9 196.35 -334.9 143.225 -278.8 c 0,65,66 + 91.7255 -224.418 91.7255 -224.418 83.2998 -153.85 c 0,67,68 + 82.957 -117.949 l 0,69,70 + 86.8762 -78.2765 86.8762 -78.2765 109.65 -37.4004 c 0,71,72 + 142.799 22.0987 142.799 22.0987 143.65 80.75 c 0,73,74 + 143.65 133.451 143.65 133.451 122.4 168.3 c 0,75,76 + 106.25 195.499 106.25 195.499 79.9004 167.45 c 0,77,78 + 53.5498 139.4 53.5498 139.4 95.2002 96.0498 c 0,79,80 + 62.0497 86.7002 62.0497 86.7002 40.375 112.2 c 0,81,82 + 33.1445 120.707 33.1445 120.707 17.8496 153 c 0,83,84 + 3.40722 183.493 3.40722 183.493 29.75 240.975 c 0,85,86 + 46.5068 277.54 46.5068 277.54 65.4502 323.85 c 0,87,88 + 92.9434 391.062 92.9434 391.062 94.7754 417.775 c 0,89,90 + 101.251 512.209 101.251 512.209 102.85 514.25 c 0,91,92 + 104.836 522.868 l 0,93,94 + 104.373 534.203 104.373 534.203 97.3252 559.725 c 0,95,96 + 79.4824 621.977 79.4824 621.977 40.7998 680 c 0,97,98 + 30.5996 695.3 30.5996 695.3 27.2002 736.95 c 0,99,100 + 23.7999 778.6 23.7999 778.6 56.9502 800.7 c 0,101,102 + 49.8754 783.221 49.8754 783.221 49.8519 771.778 c 0,103,104 + 49.8182 755.43 49.8182 755.43 64.1748 751.4 c 0,105,106 + 90.0996 744.6 90.0996 744.6 110.5 785.4 c 0,107,108 + 131.413 825.057 131.413 825.057 131.609 850.216 c 0,109,110 + 131.634 853.413 131.634 853.413 131.325 856.375 c 0,111,112 + 124.084 909.899 124.084 909.899 107.95 912.9 c 0,113,114 + 74.7999 918.85 74.7999 918.85 77.3496 894.625 c 0,115,116 + 79.9004 870.4 79.9004 870.4 90.0996 860.2 c 0,117,118 + 62.0502 860.2 62.0502 860.2 45.4746 881.025 c 0,119,120 + 28.9003 901.849 28.9003 901.849 28.9004 914.6 c 0,121,122 + 30.6431 951.441 l 0,123,124 + 34.4008 977.421 34.4008 977.421 45.0498 1007.67 c 0,125,126 + 63.75 1060.8 63.75 1060.8 74.7998 1101.6 c 0,127,128 + 95.2003 1178.96 95.2003 1178.96 66.2998 1252.47 c 0,129,130 + 40.3659 1318.45 40.3659 1318.45 40.4422 1375.88 c 0,131,132 + 40.451 1382.45 40.451 1382.45 40.7998 1388.9 c 0,133,134 + 42.4996 1430.54 42.4996 1430.54 67.5752 1459.45 c 0,135,136 + 85.036 1479.58 85.036 1479.58 110.125 1479.5 c 0,137,138 + 121.062 1479.47 121.062 1479.47 133.45 1475.6 c 0,139,140 + 93.4999 1461.15 93.4999 1461.15 86.7002 1435.22 c 0,141,142 + 83.601 1410.01 l 0,143,144 + 84.1391 1401.29 84.1391 1401.29 87.5498 1394.85 c 0,145,146 + 102.429 1363.6 102.429 1363.6 134.236 1363.61 c 0,147,148 + 138.771 1363.61 138.771 1363.61 143.65 1364.25 c 0,149,150 + 182.75 1369.35 182.75 1369.35 194.65 1394.85 c 0,151,152 + 208.059 1425.77 208.059 1425.77 207.989 1452.07 c 0,153,154 + 207.84 1507.45 207.84 1507.45 147.9 1542.33 c 0,155,156 + 59.481 1593.76 59.481 1593.76 30.5996 1603.1 c 0,157,158 + 140.25 1580.15 140.25 1580.15 186.15 1532.12 c 0,159,160 + 232.049 1484.11 232.049 1484.11 243.95 1443.3 c 0,161,162 + 257.551 1394.85 257.551 1394.85 252.875 1354.47 c 0,163,164 + 248.199 1314.1 248.199 1314.1 235.45 1264.8 c 0,165,166 + 226.614 1230.08 226.614 1230.08 226.682 1184.83 c 0,167,168 + 226.706 1169.13 226.706 1169.13 227.8 1152.17 c 0,169,170 + 231.7 1091.72 231.7 1091.72 279.269 1091.04 c 0,171,172 + 283.534 1090.98 283.534 1090.98 288.15 1091.4 c 0,173,174 + 341.7 1096.5 341.7 1096.5 334.05 1142.4 c 0,175,176 + 326.4 1188.3 326.4 1188.3 283.9 1198.5 c 0,177,178 + 308.183 1201.04 l 0,179,180 + 325.909 1200.14 325.909 1200.14 345.525 1191.7 c 0,181,182 + 379.098 1177.26 379.098 1177.26 386.75 1151.75 c 0,183,184 + 392.424 1130.47 392.424 1130.47 392.464 1110.19 c 0,185,186 + 392.543 1069.7 392.543 1069.7 370.175 1033.17 c 0,187,188 + 338.479 981.419 338.479 981.419 334.9 914.6 c 0,189,190 + 332.417 868.263 332.417 868.263 379.95 889.1 c 0,191,192 + 442 916.299 442 916.299 505.75 1024.25 c 0,193,194 + 528.697 1062.5 528.697 1062.5 552.5 1165.78 c 0,195,196 + 575.844 1267.07 575.844 1267.07 610.3 1293.7 c 0,197,198 + 629.01 1308.15 629.01 1308.15 658.325 1315.38 c 0,199,200 + 681.508 1317.82 l 0,201,202 + 693.431 1316.82 693.431 1316.82 700.4 1309.85 c 0,203,204 + 641.75 1305.6 641.75 1305.6 641.75 1266.5 c 0,205,206 + 641.75 1240.15 641.75 1240.15 667.25 1246.1 c 0,207,208 + 743.751 1259.71 743.751 1259.71 750.975 1311.97 c 0,209,210 + 758.202 1364.26 758.202 1364.26 791.35 1406.75 c 0,211,212 + 811.401 1432.74 811.401 1432.74 844.752 1432.78 c 0,213,214 + 849.575 1432.79 849.575 1432.79 854.675 1432.25 c 0,215,216 + 895.049 1428.01 895.049 1428.01 906.1 1409.3 c 0,217,218 + 874.516 1412.94 l 0,219,220 + 839.2 1412.34 839.2 1412.34 824.925 1385.92 c 0,221,222 + 817.061 1371.36 817.061 1371.36 816.904 1357.53 c 0,223,224 + 820.58 1338.22 l 0,225,226 + 824.994 1327.19 824.994 1327.19 834.7 1316.65 c 0,227,228 + 855.055 1294.26 855.055 1294.26 890.312 1294.08 c 0,229,230 + 899.217 1294.03 899.217 1294.03 909.075 1295.4 c 0,231,232 + 957.942 1302.19 957.942 1302.19 998.325 1332.8 c 0,233,234 + 1038.71 1363.41 1038.71 1363.41 1055.7 1413.12 c 0,235,236 + 1060.93 1428.44 1060.93 1428.44 1060.93 1444.6 c 0,237,238 + 1060.92 1480.92 1060.92 1480.92 1034.45 1521.5 c 0,239,240 + 1083.75 1482.4 1083.75 1482.4 1086.3 1418.65 c 0,241,242 + 1084.19 1380.81 l 0,243,244 + 1077.86 1342.3 1077.86 1342.3 1054 1314.95 c 0,245,246 + 1033.61 1291.16 1033.61 1291.16 981.75 1261.83 c 0,247,248 + 929.871 1232.49 929.871 1232.49 876.35 1212.1 c 0,249,250 + 796.23 1181.55 796.23 1181.55 731.85 1068.45 c 0,251,252 + 700.406 1013.22 700.406 1013.22 682.975 961.35 c 0,253,254 + 665.549 909.5 665.549 909.5 610.3 840.65 c 0,255,256 + 572.901 793.901 572.901 793.901 512.55 787.95 c 0,257,258 + 543.15 800.7 543.15 800.7 562.7 829.175 c 0,259,260 + 569.503 839.084 569.503 839.084 569.513 846.368 c 0,261,262 + 569.531 860.017 569.531 860.017 545.7 864.45 c 0,263,264 + 520.2 868.7 520.2 868.7 494.275 845.75 c 0,265,266 + 469.591 823.898 469.591 823.898 463.25 792.2 c 0,267,268 + 460.627 761.739 l 0,269,270 + 462.103 733.539 462.103 733.539 480.675 717.825 c 0,271,272 + 493.756 706.756 493.756 706.756 504.277 706.775 c 0,273,274 + 517.122 706.798 517.122 706.798 526.15 723.35 c 0,275,276 + 527.626 732.428 l 0,277,278 + 524.386 745.468 524.386 745.468 488.75 755.65 c 0,279,280 + 508.168 770.089 508.168 770.089 525.544 770.091 c 0,281,282 + 537.833 770.093 537.833 770.093 549.1 762.875 c 0,283,284 + 576.3 745.449 576.3 745.449 583.95 719.95 c 0,285,286 + 604.35 651.951 604.35 651.951 571.2 613.7 c 0,287,288 + 546.358 585.035 546.358 585.035 546.316 540 c 0,289,290 + 546.304 527.346 546.304 527.346 548.25 513.4 c 0,291,292 + 558.45 440.3 558.45 440.3 643.875 403.325 c 0,293,294 + 729.3 366.35 729.3 366.35 803.25 341.7 c 0,295,296 + 884.85 314.5 884.85 314.5 909.5 264.35 c 0,297,298 + 928.35 226 928.35 226 928.312 206.538 c 0,299,300 + 928.3 200.55 928.3 200.55 926.5 196.35 c 0,301,302 + 905.249 264.351 905.249 264.351 842.35 278.8 c 0,303,304 + 811.077 281.413 l 0,305,306 + 775.025 279.194 775.025 279.194 765 247.35 c 0,307,308 + 763.193 229.147 l 0,309,310 + 767.307 190.197 767.307 190.197 837.25 143.225 c 0,311,312 + 923.95 84.9995 923.95 84.9995 962.2 55.25 c 0,313,314 + 997.9 26.3497 997.9 26.3497 1028.92 -23.375 c 0,315,316 + 1053.67 -63.0368 1053.67 -63.0368 1053.81 -99.1914 c 0,317,318 + 1053.85 -108.358 1053.85 -108.358 1052.3 -117.3 c 0,319,320 + 1027.92 -255.669 1027.92 -255.669 888.25 -285.6 c 0,321,322 + 871.057 -289.284 871.057 -289.284 843.002 -289.198 c 0,323,324 + 832.216 -289.165 832.216 -289.165 819.825 -288.575 c 0,325,326 + 775.198 -286.449 775.198 -286.449 737.8 -273.7 c 0,327,328 + 748.664 -276.416 748.664 -276.416 776.189 -276.355 c 0,329,330 + 791.737 -276.32 791.737 -276.32 812.6 -275.4 c 0,331,332 + 870.4 -272.85 870.4 -272.85 893.35 -262.65 c 0,333,334 + 947.749 -237.15 947.749 -237.15 980.9 -176.8 c 0,335,336 + 1014.05 -116.451 1014.05 -116.451 973.25 -47.5996 c 0,337,338 + 961.351 -27.202 961.351 -27.202 929.05 -0.424805 c 0,339,340 + 896.751 26.3496 896.751 26.3496 860.2 37.4004 c 0,341,342 + 823.078 47.9578 823.078 47.9578 801.239 48.0084 c 0,343,344 + 770.67 48.0793 770.67 48.0793 770.1 24.6504 c 0,345,346 + 770.1 5.09961 770.1 5.09961 793.475 5.09961 c 0,347,348 + 816.85 5.09961 816.85 5.09961 832.15 -0.849609 c 0,349,350 + 796.45 -21.25 796.45 -21.25 756.925 -10.625 c 0,351,352 + 717.4 -4.76837e-06 717.4 -4.76837e-06 712.3 12.75 c 0,353,354 + 698.702 38.2446 698.702 38.2446 685.1 78.2002 c 0,355,-1 + 664.7 146.2 l 0,356,357 + 657.049 171.702 657.049 171.702 616.675 220.575 c 0,358,359 + 577.384 268.136 577.384 268.136 542.3 268.6 c 0,0,1 +EndSplineSet +KernsSLIF: 111 -65 0 0 115 -104 0 0 103 -65 0 0 99 -156 0 0 +EndChar +StartChar: l +Encoding: 108 108 66 +Width: 1076 +Flags: HMW +HStem: 136.5 181.5<307 709> +VStem: 37 223.5<161 1456.5> +Fore +41 292 m 0,0,1 + 70 310 70 310 114 285 c 0,2,3 + 70.0001 294 70.0001 294 45 270.5 c 0,4,5 + 29.3458 255.785 29.3458 255.785 29.375 238.521 c 0,6,7 + 29.3925 228.215 29.3925 228.215 35 217 c 0,8,9 + 45.7595 193.759 45.7595 193.759 61.8905 193.765 c 0,10,11 + 83.2405 193.772 83.2405 193.772 114 234.5 c 0,12,13 + 146.057 276.946 146.057 276.946 146.044 324.502 c 0,14,15 + 146.035 357.054 146.035 357.054 131 392 c 0,16,17 + 107 446 107 446 77 421 c 0,18,19 + 47 396 47 396 93 354 c 0,20,21 + 27 375 27 375 26 453 c 0,22,23 + 27.8452 496.459 l 0,24,25 + 32.9898 535.068 32.9898 535.068 50.5 575.5 c 0,26,27 + 77.9997 638.999 77.9997 638.999 92 698 c 0,28,29 + 119 824 119 824 94 931 c 0,30,31 + 81.9967 983.015 81.9967 983.015 64.5 1034.5 c 0,32,33 + 47.0011 1085.99 47.0011 1085.99 42 1145 c 0,34,35 + 45.7278 1163.7 l 0,36,37 + 48.9752 1172.67 48.9752 1172.67 55 1184.5 c 0,38,39 + 68.9999 1211.99 68.9999 1211.99 111 1207 c 0,40,41 + 100.366 1206.12 l 0,42,43 + 88.4565 1201.3 88.4565 1201.3 78 1179 c 0,44,45 + 74.1633 1163.65 l 0,46,47 + 75.1096 1150.58 75.1096 1150.58 97.0824 1150.55 c 0,48,49 + 101.177 1150.55 101.177 1150.55 106 1151 c 0,50,51 + 134.875 1152.75 134.875 1152.75 135.422 1182.06 c 0,52,53 + 135.5 1186.25 135.5 1186.25 135 1191 c 0,54,55 + 130.996 1229.03 130.996 1229.03 124 1274 c 0,56,57 + 113.999 1328 113.999 1328 92.5 1376 c 0,58,59 + 71.0001 1424 71.0001 1424 53 1475 c 0,60,61 + 49.0488 1485.54 49.0488 1485.54 49.109 1498.02 c 0,62,63 + 49.2317 1523.47 49.2317 1523.47 66 1557 c 0,64,65 + 80.4583 1585.91 80.4583 1585.91 105.952 1586.07 c 0,66,67 + 122.383 1586.17 122.383 1586.17 143.398 1574.32 c 0,68,69 + 146.159 1572.76 146.159 1572.76 149 1571 c 0,70,71 + 128.01 1571 128.01 1571 103 1557 c 0,72,73 + 77.9999 1543.01 77.9999 1543.01 88 1497 c 0,74,75 + 96.8173 1449.97 96.8173 1449.97 137.5 1449.5 c 0,76,77 + 177.998 1449.99 177.998 1449.99 196 1501 c 0,78,79 + 203.796 1524.39 203.796 1524.39 203.751 1545.28 c 0,80,81 + 203.629 1602.11 203.629 1602.11 145.5 1640.5 c 0,82,83 + 66.01 1692.99 66.01 1692.99 -2 1703 c 0,84,85 + 59.4295 1700.45 l 0,86,87 + 127.09 1692.99 127.09 1692.99 170 1664.5 c 0,88,89 + 230.996 1624 230.996 1624 247 1586 c 0,90,91 + 264.567 1541.41 264.567 1541.41 264.558 1497.95 c 0,92,93 + 264.554 1477.09 264.554 1477.09 260.5 1456.5 c 0,94,95 + 248 1393 248 1393 248 1330 c 0,96,97 + 248 1249 248 1249 285 1147 c 0,98,99 + 322 1045 322 1045 265 1006 c 0,100,101 + 284 1036 284 1036 260 1067.5 c 0,102,103 + 249.5 1081.28 249.5 1081.28 239 1081.18 c 0,104,105 + 225.501 1081.06 225.501 1081.06 212 1058 c 0,106,107 + 200.001 1037 200.001 1037 194.5 961.5 c 0,108,109 + 194.818 919.869 l 0,110,111 + 199.301 880.069 199.301 880.069 222 867 c 0,112,113 + 230.364 862.221 230.364 862.221 237.166 862.215 c 0,114,115 + 253.136 862.201 253.136 862.201 260.5 888.5 c 0,116,117 + 271 926 271 926 241 959 c 0,118,119 + 276.001 959 276.001 959 291.5 913 c 0,120,121 + 298.669 891.725 298.669 891.725 298.672 873.017 c 0,122,123 + 298.675 851.275 298.675 851.275 289 833 c 0,124,125 + 280 814 280 814 268 731.5 c 0,126,127 + 255.999 648.995 255.999 648.995 252.5 557.5 c 0,128,129 + 252.749 465.02 l 0,130,131 + 254.6 426.799 254.6 426.799 259.5 392.5 c 0,132,133 + 270 319 270 319 307 318 c 0,134,135 + 352 316 352 316 381.5 366 c 0,136,137 + 411 416 411 416 477 413 c 0,138,139 + 545 407 545 407 533 332 c 0,140,141 + 517.466 372.206 517.466 372.206 481.891 372.75 c 0,142,143 + 478.534 372.802 478.534 372.802 475 372.5 c 0,144,145 + 443.78 369.835 443.78 369.835 443.871 339.628 c 0,146,147 + 443.899 330.165 443.899 330.165 447 318 c 0,148,149 + 450 303 450 303 481 292.5 c 0,150,151 + 503.812 289.566 l 0,152,153 + 536.914 289.914 536.914 289.914 597 309 c 0,154,155 + 646 324 646 324 742 359 c 0,156,157 + 838 394 838 394 825 292 c 0,158,159 + 798 357 798 357 757 314.5 c 0,160,161 + 716 272 716 272 754 257 c 0,162,163 + 800.183 238.107 800.183 238.107 842.224 238.075 c 0,164,165 + 900.317 238.031 900.317 238.031 950.5 274 c 0,166,167 + 1024.75 327.219 1024.75 327.219 1024.95 450.456 c 0,168,169 + 1024.98 470.777 1024.98 470.777 1023 493 c 0,170,171 + 1042.44 425.955 1042.44 425.955 1042.51 374.013 c 0,172,173 + 1042.59 319.048 1042.59 319.048 1021 281 c 0,174,175 + 978.999 206.999 978.999 206.999 896 173.5 c 0,176,177 + 812.998 139.999 812.998 139.999 709 136.5 c 0,178,179 + 566.939 135.419 l 0,180,181 + 543.748 135.952 543.748 135.952 522 137 c 0,182,183 + 471.006 138.999 471.006 138.999 411 151.5 c 0,184,185 + 390.2 155.833 390.2 155.833 365.795 155.78 c 0,186,187 + 319.799 155.68 319.799 155.68 261 140 c 0,188,189 + 219.505 128.553 219.505 128.553 174.425 128.623 c 0,190,191 + 156.496 128.65 156.496 128.65 138 130.5 c 0,192,193 + 73.0009 136.999 73.0009 136.999 37 161 c 0,194,195 + 8.00005 179 8.00005 179 3.5 221.5 c 0,196,197 + -1 263.999 -1 263.999 41 292 c 0,0,1 +EndSplineSet +KernsSLIF: 116 -286 0 0 121 -156 0 0 105 -78 0 0 45 -156 0 0 115 -130 0 0 119 -195 0 0 +EndChar +StartChar: m +Encoding: 109 109 24 +Width: 1471 +Flags: HMW +VStem: 93 114<55 195> 100 187<251 1528> 312.5 89.5<154.5 421> 1036 199<169 1576> 1134.5 100.5<-115 169> +Fore +1025 -231 m 1,0,1 + 1079 -195 1079 -195 1134.5 -115 c 0,2,3 + 1190 -35 1190 -35 1184 71 c 0,4,5 + 1181 106 1181 106 1161.5 152 c 0,6,7 + 1142 198.001 1142 198.001 1093 204 c 0,8,9 + 1079 204 1079 204 1059.5 200.5 c 0,10,11 + 1040 197.001 1040 197.001 1034 182 c 0,12,13 + 1024.39 155.698 1024.39 155.698 1024.37 134.251 c 0,14,15 + 1024.36 113.308 1024.36 113.308 1033.5 97 c 0,16,17 + 1047.33 72.3194 1047.33 72.3194 1073.76 72.2502 c 0,18,19 + 1082.67 72.2269 1082.67 72.2269 1093 75 c 0,20,21 + 1078.76 49.3729 1078.76 49.3729 1038.4 49.4211 c 0,22,23 + 1036.24 49.4237 1036.24 49.4237 1034 49.5 c 0,24,25 + 990 51.0002 990 51.0002 966 77 c 0,26,27 + 933.272 109.728 933.272 109.728 933.041 162.846 c 0,28,29 + 932.982 176.272 932.982 176.272 935 191 c 0,30,31 + 946 272 946 272 972.5 349.5 c 0,32,33 + 999 426.998 999 426.998 1014 503 c 0,34,35 + 1024.01 554 1024.01 554 1041 677 c 0,36,37 + 1058 800.036 1058 800.036 1058 853 c 0,38,39 + 1058 893 1058 893 1053.5 957 c 0,40,41 + 1049 1021 1049 1021 1003 1042 c 0,42,43 + 987.084 1049.23 987.084 1049.23 970.385 1049.21 c 0,44,45 + 940.911 1049.16 940.911 1049.16 909 1026.5 c 0,46,47 + 875.767 1002.9 875.767 1002.9 875.667 973.785 c 0,48,49 + 875.617 959.096 875.617 959.096 884 943 c 0,50,51 + 895.195 919.951 895.195 919.951 909.426 919.67 c 0,52,53 + 921.873 923.425 l 0,54,55 + 923.421 924.349 923.421 924.349 925 925.5 c 0,56,57 + 949 943 949 943 958 976 c 0,58,59 + 977 914 977 914 943 862 c 0,60,61 + 911.999 817.999 911.999 817.999 842.5 811.5 c 0,62,63 + 773 805 773 805 718 805 c 0,64,65 + 667 805 667 805 642 779 c 0,66,67 + 617 753 617 753 615 726 c 0,68,69 + 612 694 612 694 627 656.5 c 0,70,71 + 642 619 642 619 665 607 c 0,72,73 + 739 567 739 567 769 589 c 0,74,75 + 799 611 799 611 808 638 c 0,76,77 + 808.615 615.462 l 0,78,79 + 805.87 596.063 805.87 596.063 791.5 578.5 c 0,80,81 + 769 551 769 551 751 548 c 0,82,83 + 684 533 684 533 658 548.5 c 0,84,85 + 632 564 632 564 608 589 c 0,86,87 + 558 640 558 640 542 729.5 c 0,88,89 + 526.001 818.995 526.001 818.995 525 879 c 0,90,91 + 524 915.999 524 915.999 504 953 c 0,92,93 + 484 990 484 990 441 992 c 0,94,95 + 411 993 411 993 412.5 963.5 c 0,96,97 + 414 934 414 934 459 958 c 0,98,99 + 450 922 450 922 424 920 c 0,100,101 + 398 918 398 918 377 930 c 0,102,103 + 351 942 351 942 350.5 981.5 c 0,104,105 + 350 1020.99 350 1020.99 358 1064 c 0,106,107 + 359.954 1094.75 l 0,108,109 + 358.246 1117.65 358.246 1117.65 345 1129 c 0,110,111 + 333.574 1137.92 333.574 1137.92 323.779 1138.06 c 0,112,113 + 317.203 1138.15 317.203 1138.15 311.363 1134.29 c 0,114,115 + 294.684 1123.27 294.684 1123.27 284 1080 c 0,116,117 + 264 999 264 999 264 950 c 0,118,119 + 264 801.001 264 801.001 308 643 c 0,120,121 + 323 590 323 590 354.5 531.5 c 0,122,123 + 386 473 386 473 402 421 c 0,124,125 + 426 337 426 337 420 268 c 0,126,127 + 409.999 148.999 409.999 148.999 332 123 c 0,128,129 + 307.489 114.489 307.489 114.489 288.773 114.554 c 0,130,131 + 252.511 114.681 252.511 114.681 238 147 c 0,132,133 + 249.812 142.94 249.812 142.94 263.055 142.899 c 0,134,135 + 285.688 142.829 285.688 142.829 312.5 154.5 c 0,136,137 + 352.19 171.777 352.19 171.777 352.198 209.549 c 0,138,139 + 352.198 212.223 352.198 212.223 352 215 c 0,140,141 + 349 275 349 275 287 251 c 0,142,143 + 225 227 225 227 207 195 c 0,144,145 + 176.999 141.999 176.999 141.999 170.5 79.5 c 0,146,147 + 167.94 21.3888 l 0,148,149 + 168.706 -1.8226 168.706 -1.8226 173 -19 c 0,150,151 + 203 -149 203 -149 259.5 -205.5 c 0,152,153 + 315.999 -261.999 315.999 -261.999 374 -308 c 0,154,155 + 254 -285.999 254 -285.999 172 -175.5 c 0,156,157 + 89.9995 -64.9995 89.9995 -64.9995 93 55 c 0,158,159 + 95 136 95 136 136.5 219.5 c 0,160,161 + 178 302.999 178 302.999 190 384 c 0,162,163 + 194.996 416.975 194.996 416.975 206 474 c 0,164,165 + 209 507.333 l 0,166,167 + 207.667 536 207.667 536 189 546 c 0,168,169 + 176.804 551.963 176.804 551.963 167.289 552.233 c 0,170,171 + 153.866 549.07 l 0,172,173 + 139.867 541.011 139.867 541.011 135.5 512.5 c 0,174,175 + 126.999 457 126.999 457 158 448 c 0,176,177 + 95 448 95 448 89 503.5 c 0,178,179 + 83 559 83 559 89 601 c 0,180,181 + 95 640 95 640 120.5 683.5 c 0,182,183 + 146 727 146 727 152 766 c 0,184,185 + 155.588 821.346 l 0,186,187 + 155.088 894.71 155.088 894.71 125.5 959 c 0,188,189 + 84.9961 1047.01 84.9961 1047.01 58 1140 c 0,190,191 + 32.9998 1225.01 32.9998 1225.01 30.5 1276 c 0,192,193 + 28 1327 28 1327 73 1414 c 0,194,195 + 89.0001 1447 89.0001 1447 120.5 1453 c 0,196,197 + 145.355 1454.66 l 0,198,199 + 156.698 1453.36 156.698 1453.36 162 1447 c 0,200,201 + 119.001 1444 119.001 1444 110 1383.5 c 0,202,203 + 101 1323.01 101 1323.01 135 1322 c 0,204,205 + 161.228 1323.78 l 0,206,207 + 189.587 1330.18 189.587 1330.18 203 1357 c 0,208,209 + 222 1394.99 222 1394.99 227 1440 c 0,210,211 + 227.387 1482.88 l 0,212,213 + 225.876 1502 225.876 1502 221.5 1522.5 c 0,214,215 + 213.181 1561.47 213.181 1561.47 157.691 1561.71 c 0,216,217 + 149.82 1561.75 149.82 1561.75 141 1561 c 0,218,219 + 122.004 1558 122.004 1558 111.5 1542.5 c 0,220,221 + 101.718 1528.07 101.718 1528.07 100 1528 c 0,222,223 + 103.126 1559.45 l 0,224,225 + 113.773 1604.2 113.773 1604.2 160.5 1617.5 c 0,226,227 + 174.44 1621.47 174.44 1621.47 187.84 1621.5 c 0,228,229 + 224.431 1621.6 224.431 1621.6 257.003 1592.39 c 0,230,231 + 265.126 1585.11 265.126 1585.11 273 1576 c 0,232,233 + 321.005 1518.99 321.005 1518.99 350 1446 c 0,234,235 + 379 1372.99 379 1372.99 415 1314 c 0,236,-1 + 463 1243 l 0,237,238 + 511 1172.01 511 1172.01 543 1210 c 0,239,240 + 552 1220.72 552 1220.72 552.092 1232.53 c 0,241,242 + 552.188 1244.99 552.188 1244.99 542.38 1258.68 c 0,243,244 + 539.786 1262.3 539.786 1262.3 536.5 1266 c 0,245,246 + 513.03 1292.46 513.03 1292.46 484.812 1292.69 c 0,247,248 + 479.976 1292.73 479.976 1292.73 475 1292 c 0,249,250 + 490.916 1311.9 490.916 1311.9 512.538 1312.16 c 0,251,252 + 518.082 1312.22 518.082 1312.22 524 1311 c 0,253,254 + 553 1305 553 1305 568 1296 c 0,255,256 + 599.001 1273.99 599.001 1273.99 602 1228 c 0,257,258 + 604 1180.99 604 1180.99 627.5 1135.5 c 0,259,260 + 651 1090.01 651 1090.01 690 1110 c 0,261,262 + 726 1128 726 1128 741 1174.5 c 0,263,264 + 756 1221 756 1221 779 1281 c 0,265,266 + 808.994 1362.99 808.994 1362.99 892.5 1461.5 c 0,267,268 + 975.99 1559.99 975.99 1559.99 1036 1576 c 0,269,270 + 1115.38 1596.09 1115.38 1596.09 1210.29 1596.05 c 0,271,272 + 1214.63 1596.04 1214.63 1596.04 1219 1596 c 0,273,274 + 1319.01 1594.99 1319.01 1594.99 1393 1542 c 0,275,276 + 1431.02 1514.98 1431.02 1514.98 1470.5 1467 c 0,277,278 + 1510 1418.99 1510 1418.99 1510 1364 c 0,279,280 + 1510 1333.99 1510 1333.99 1503 1307.5 c 0,281,282 + 1496 1281 1496 1281 1463 1263 c 0,283,284 + 1484.46 1289.96 1484.46 1289.96 1484.42 1324.94 c 0,285,286 + 1484.39 1353.54 1484.39 1353.54 1470 1387.5 c 0,287,288 + 1438.01 1462.99 1438.01 1462.99 1378 1491 c 0,289,290 + 1313.98 1520 1313.98 1520 1244.5 1523 c 0,291,292 + 1222.23 1520.55 l 0,293,294 + 1174.12 1506.48 1174.12 1506.48 1170 1414 c 0,295,296 + 1172.56 1390 l 0,297,298 + 1180.15 1360.99 1180.15 1360.99 1209.5 1332 c 0,299,300 + 1235.32 1306.5 1235.32 1306.5 1253.58 1306.53 c 0,301,302 + 1264.68 1306.55 1264.68 1306.55 1273 1316 c 0,303,304 + 1290.28 1335.2 1290.28 1335.2 1290.36 1350.31 c 0,305,306 + 1290.4 1358.8 1290.4 1358.8 1285 1366 c 0,307,308 + 1269.99 1386 1269.99 1386 1246 1395 c 0,309,310 + 1256 1408.33 1256 1408.33 1270.17 1408.55 c 0,311,312 + 1286.92 1404.85 l 0,313,314 + 1291.08 1403.1 1291.08 1403.1 1295.5 1400.5 c 0,315,316 + 1327 1382 1327 1382 1332 1373 c 0,317,318 + 1340.68 1353.09 1340.68 1353.09 1340.88 1329 c 0,319,320 + 1337.14 1293.77 l 0,321,322 + 1335.62 1286.54 1335.62 1286.54 1333.5 1279 c 0,323,324 + 1318.01 1224.02 1318.01 1224.02 1288 1187 c 0,325,326 + 1193.99 1074.99 1193.99 1074.99 1222 947 c 0,327,328 + 1240 856.01 1240 856.01 1267.5 819 c 0,329,-1 + 1321 744 l 0,330,331 + 1374.27 666.794 1374.27 666.794 1374.49 580.64 c 0,332,333 + 1374.56 555.209 1374.56 555.209 1370 529 c 0,334,335 + 1364 496.019 1364 496.019 1350 464.5 c 0,336,337 + 1336.01 433.005 1336.01 433.005 1300 407 c 0,338,339 + 1291 401 1291 401 1267 392.5 c 0,340,341 + 1248.3 389.491 l 0,342,343 + 1235.95 390.219 1235.95 390.219 1226 399 c 0,344,345 + 1274 422 1274 422 1283 456 c 0,346,347 + 1289.22 479.507 1289.22 479.507 1289.23 503 c 0,348,349 + 1289.24 513.5 1289.24 513.5 1288 524 c 0,350,351 + 1285 547 1285 547 1246 548 c 0,352,353 + 1225.66 544.999 l 0,354,355 + 1203.25 536.886 1203.25 536.886 1194 507 c 0,356,357 + 1182 468 1182 468 1180.5 415 c 0,358,359 + 1182.17 345.543 l 0,360,361 + 1183.28 332.776 1183.28 332.776 1185 321 c 0,362,363 + 1194 262.984 1194 262.984 1208.5 232.5 c 0,364,365 + 1222.98 202.047 1222.98 202.047 1235 169 c 0,366,367 + 1253.25 119.481 1253.25 119.481 1253.23 68.6809 c 0,368,369 + 1253.23 41.5239 1253.23 41.5239 1248 14 c 0,370,371 + 1234.01 -55.9778 1234.01 -55.9778 1188.5 -125 c 0,372,373 + 1143.01 -193.999 1143.01 -193.999 1025 -231 c 1,0,1 +EndSplineSet +KernsSLIF: 97 -91 0 0 105 65 0 0 +EndChar +StartChar: n +Encoding: 110 110 50 +Width: 1072 +Flags: HMW +VStem: 116 176<173 1259> 669 262<167 1382> +Fore +84 54 m 0,0,1 + 67.6022 106.707 67.6022 106.707 67.6669 159.757 c 0,2,3 + 67.7127 197.292 67.7127 197.292 76 235 c 0,4,5 + 95.9999 326 95.9999 326 112 413 c 0,6,7 + 119.449 452.538 119.449 452.538 119.387 491.624 c 0,8,9 + 119.234 588.963 119.234 588.963 72.5 683.5 c 0,10,11 + 6.99995 816 6.99995 816 36 919 c 0,12,13 + 38 928 38 928 58.5 946 c 0,14,15 + 79.0001 964 79.0001 964 107 951 c 0,16,17 + 28 913 28 913 86.5 877.5 c 0,18,19 + 145 842 145 842 145 927 c 0,20,21 + 145 1008.01 145 1008.01 130.5 1094 c 0,22,23 + 115.999 1179.99 115.999 1179.99 116 1259 c 0,24,25 + 116 1331.99 116 1331.99 122.5 1411.5 c 0,26,27 + 128.999 1491 128.999 1491 177 1539 c 0,28,29 + 193.772 1556.4 193.772 1556.4 215.176 1556.62 c 0,30,31 + 236.709 1552.9 l 0,32,33 + 239.815 1551.85 239.815 1551.85 243 1550.5 c 0,34,35 + 282 1534 282 1534 282 1511 c 0,36,37 + 244.773 1542.56 244.773 1542.56 220.07 1543.1 c 0,38,39 + 205.24 1540.12 l 0,40,41 + 181.674 1529.11 181.674 1529.11 174.5 1477.5 c 0,42,43 + 171.376 1428.44 l 0,44,45 + 172.982 1352.49 172.982 1352.49 219 1308 c 0,46,47 + 273.009 1255 273.009 1255 349.5 1225 c 0,48,49 + 425.994 1195 425.994 1195 462 1148 c 0,50,51 + 488.105 1114.38 488.105 1114.38 488.397 1086.39 c 0,52,53 + 485.131 1066.6 l 0,54,55 + 474.466 1036.51 474.466 1036.51 429 1014 c 0,56,-1 + 448 1047 l 0,57,58 + 453.854 1057.54 453.854 1057.54 453.882 1069.79 c 0,59,60 + 453.903 1078.47 453.903 1078.47 451 1088 c 0,61,62 + 444 1110.01 444 1110.01 427 1115 c 0,63,64 + 414.31 1115.26 l 0,65,66 + 405.925 1112.67 405.925 1112.67 400 1102 c 0,67,68 + 392.365 1089.51 392.365 1089.51 392.438 1065.21 c 0,69,70 + 392.576 1019.49 392.576 1019.49 420 932 c 0,71,72 + 462 798 462 798 506 806 c 0,73,74 + 550.453 813.17 550.453 813.17 551.467 837.304 c 0,75,76 + 548.076 853.531 l 0,77,78 + 546.968 856.195 546.968 856.195 545.5 859 c 0,79,80 + 523.001 901.999 523.001 901.999 496 924 c 0,81,82 + 594 900 594 900 600.5 818.5 c 0,83,84 + 607 737 607 737 607 656 c 0,85,86 + 607 591 607 591 653.5 558.5 c 0,87,88 + 665.214 550.313 665.214 550.313 674.992 550.407 c 0,89,90 + 704.03 550.687 704.03 550.687 716 624 c 0,91,92 + 725 682 725 682 729 739.5 c 0,93,94 + 733 797 733 797 717 858 c 0,95,96 + 708 891 708 891 685.5 936.5 c 0,97,98 + 663 982 663 982 663 1022 c 0,99,100 + 663 1060.01 663 1060.01 678 1090.5 c 0,101,102 + 691.45 1117.84 691.45 1117.84 727.403 1118.26 c 0,103,104 + 731.552 1118.31 731.552 1118.31 736 1118 c 0,105,106 + 719.991 1101.99 719.991 1101.99 707 1077 c 0,107,108 + 701.61 1066.63 701.61 1066.63 701.549 1057.82 c 0,109,110 + 701.463 1045.37 701.463 1045.37 712 1036 c 0,111,112 + 737 1012 737 1012 751 1060 c 0,113,114 + 765 1108 765 1108 765 1118 c 0,115,116 + 765 1180.99 765 1180.99 733.5 1225.5 c 0,117,118 + 701.999 1270.01 701.999 1270.01 696 1331 c 0,119,120 + 696.659 1361.08 l 0,121,122 + 702.981 1402.43 702.981 1402.43 740 1435 c 0,123,124 + 759.78 1452.4 759.78 1452.4 778.152 1452.6 c 0,125,126 + 787.631 1452.7 787.631 1452.7 796.735 1448.21 c 0,127,128 + 814.589 1439.42 814.589 1439.42 831 1413 c 0,129,130 + 757 1422 757 1422 761.5 1360.5 c 0,131,132 + 766 1299 766 1299 817 1299 c 0,133,134 + 891.998 1299 891.998 1299 931 1382 c 0,135,136 + 950.863 1422.37 950.863 1422.37 950.815 1479.56 c 0,137,138 + 950.788 1511.64 950.788 1511.64 944.5 1549 c 0,139,140 + 926.997 1653.01 926.997 1653.01 876 1703 c 0,141,142 + 957.002 1649 957.002 1649 977 1552 c 0,143,144 + 997 1454.99 997 1454.99 997 1434 c 0,145,146 + 997 1371 997 1371 969.5 1318 c 0,147,148 + 942.002 1265.01 942.002 1265.01 930 1211 c 0,149,150 + 924.391 1186.32 924.391 1186.32 924.235 1164.02 c 0,151,152 + 927.798 1128.33 l 0,153,154 + 931.489 1111.34 931.489 1111.34 939 1096 c 0,155,156 + 963 1046.99 963 1046.99 985 994 c 0,157,158 + 1013.99 919 1013.99 919 1027 860.5 c 0,159,160 + 1028.01 839.43 l 0,161,162 + 1021.88 793.213 1021.88 793.213 941 754 c 0,163,164 + 953 769 953 769 967.5 790 c 0,165,166 + 982 811 982 811 982 832 c 0,167,168 + 982 866 982 866 959 866 c 0,169,170 + 934.737 863.08 l 0,171,172 + 896.5 851.954 896.5 851.954 892 797 c 0,173,-1 + 873 581 l 0,174,175 + 863 470 863 470 842 367 c 0,176,177 + 827 297.001 827 297.001 755 159.5 c 0,178,179 + 683 21.9999 683 21.9999 591 40 c 0,180,181 + 633 60 633 60 646.5 91.5 c 0,182,183 + 660 123 660 123 669 167 c 0,184,185 + 680 225.001 680 225.001 638 356 c 0,186,187 + 596 487 596 487 525 478 c 0,188,189 + 501 474 501 474 504.5 443.5 c 0,190,191 + 507.29 419.188 507.29 419.188 527.552 418.703 c 0,192,193 + 539 420 l 0,194,195 + 517 393 517 393 485 416.5 c 0,196,197 + 452.999 440.001 452.999 440.001 448 457 c 0,198,199 + 417.999 548.003 417.999 548.003 413 613.5 c 0,200,201 + 408 679 408 679 381 763 c 0,202,203 + 361.001 820.999 361.001 820.999 338 828 c 0,204,205 + 315 835 315 835 338 754 c 0,206,207 + 345.7 724.299 345.7 724.299 345.686 690.97 c 0,208,209 + 345.675 663.7 345.675 663.7 340.5 634 c 0,210,211 + 329 568 329 568 248 600 c 0,212,213 + 320 597 320 597 288 653 c 0,214,215 + 256 709 256 709 232 655 c 0,216,217 + 218.999 625 218.999 625 220 583.5 c 0,218,219 + 221.001 541.997 221.001 541.997 231 515 c 0,220,221 + 272 401 272 401 298.5 353.5 c 0,222,223 + 310.319 332.316 310.319 332.316 310.303 294.126 c 0,224,225 + 310.283 246.685 310.283 246.685 292 173 c 0,226,227 + 283 137.999 283 137.999 248.5 118 c 0,228,229 + 213.999 97.9998 213.999 97.9998 179 90 c 0,230,231 + 216.999 109.999 216.999 109.999 233 174.5 c 0,232,233 + 236.04 199.261 l 0,234,235 + 234.584 237.113 234.584 237.113 182 237 c 0,236,237 + 142.999 235.999 142.999 235.999 132 189.5 c 0,238,239 + 121.001 143 121.001 143 121 101 c 0,240,241 + 121 -12.9997 121 -12.9997 205.5 -65.5 c 0,242,243 + 290 -118 290 -118 387 -123 c 0,244,245 + 331.946 -127.042 l 0,246,247 + 248.215 -126.958 248.215 -126.958 188.5 -85.5 c 0,248,249 + 109.999 -30.9992 109.999 -30.9992 84 54 c 0,0,1 +EndSplineSet +KernsSLIF: 97 -208 0 0 +EndChar +StartChar: o +Encoding: 111 111 48 +Width: 1255 +Flags: W +Fore +273 143 m 1,0,1 + 247 130.5 247 130.5 220.5 130.5 c 0,2,3 + 194 130.5 194 130.5 167 143 c 0,4,5 + 68 183.001 68 183.001 68 276 c 0,6,7 + 68 342 68 342 113 506.5 c 0,8,-1 + 174 733 l 0,9,10 + 180.001 758.004 180.001 758.004 183.5 796 c 0,11,12 + 181.908 815.246 l 0,13,14 + 175.585 834.878 175.585 834.878 148 837 c 0,15,16 + 82 841 82 841 89 763 c 0,17,18 + 37 804 37 804 84.5 974.5 c 0,19,20 + 132.003 1145.01 132.003 1145.01 147 1245 c 0,21,22 + 158 1319 158 1319 197 1388 c 0,23,24 + 220.787 1430.08 220.787 1430.08 268.011 1430.13 c 0,25,26 + 298.212 1430.16 298.212 1430.16 338 1413 c 0,27,28 + 247.27 1410.33 247.27 1410.33 246.344 1359.79 c 0,29,30 + 247.5 1346.5 l 0,31,32 + 258.818 1284.01 258.818 1284.01 300 1284 c 0,33,34 + 367.003 1284 367.003 1284 435.5 1390 c 0,35,36 + 504 1496.01 504 1496.01 459 1522 c 0,37,38 + 433.333 1536.36 433.333 1536.36 413.25 1536.61 c 0,39,40 + 394.256 1533.23 l 0,41,42 + 380.637 1527.76 380.637 1527.76 370.5 1513.5 c 0,43,44 + 340.989 1471.98 340.989 1471.98 330 1451 c 0,45,46 + 326.246 1484.15 l 0,47,48 + 326.881 1531.42 326.881 1531.42 366 1560 c 0,49,50 + 414.154 1595.18 414.154 1595.18 488.874 1595.22 c 0,51,52 + 494.849 1595.22 494.849 1595.22 501 1595 c 0,53,54 + 584.988 1590.01 584.988 1590.01 693.5 1539 c 0,55,56 + 802 1488 802 1488 835 1428 c 0,57,-1 + 899 1286.5 l 0,58,59 + 954.143 1164.13 954.143 1164.13 999 1164 c 0,60,61 + 1059.17 1168.63 1059.17 1168.63 1059.54 1207.77 c 0,62,63 + 1059.63 1218.49 1059.63 1218.49 1054.5 1234 c 0,64,65 + 1032 1297.99 1032 1297.99 975 1299 c 0,66,67 + 1019.99 1302.45 l 0,68,69 + 1090.79 1301.3 1090.79 1301.3 1107.5 1250 c 0,70,71 + 1119.87 1212.01 1119.87 1212.01 1119.83 1182.65 c 0,72,73 + 1119.79 1160.98 1119.79 1160.98 1113 1144 c 0,74,75 + 1092.07 1091.19 1092.07 1091.19 1037 938 c 0,76,77 + 996.721 825.96 996.721 825.96 996.666 771.829 c 0,78,79 + 996.647 752.046 996.647 752.046 1002 740 c 0,80,81 + 1014 710 1014 710 1060.5 710.5 c 0,82,83 + 1107 711 1107 711 1118 750 c 0,84,85 + 1120.72 775.054 l 0,86,87 + 1118.42 818.286 1118.42 818.286 1059 827 c 0,88,89 + 1066.89 837.526 1066.89 837.526 1087.53 837.526 c 0,90,91 + 1106.1 837.526 1106.1 837.526 1135 829 c 0,92,93 + 1196.01 811 1196.01 811 1195 746 c 0,94,95 + 1190.99 608.991 1190.99 608.991 1083.5 510.5 c 0,96,97 + 976.003 412.007 976.003 412.007 925 303 c 0,98,99 + 910 273 910 273 941.5 249 c 0,100,101 + 973 225 973 225 1048 270 c 0,102,103 + 1015 183 1015 183 859 163.5 c 0,104,105 + 703 144 703 144 659 120 c 0,106,107 + 608 91.9995 608 91.9995 531 69.5 c 0,108,109 + 493.463 58.5313 493.463 58.5313 454.499 58.6135 c 0,110,111 + 413.537 58.7 413.537 58.7 371 71 c 0,112,113 + 361 72.9999 361 72.9999 341 87 c 0,114,115 + 321 101 321 101 317 129 c 0,116,117 + 362 91.9995 362 91.9995 398 95 c 0,118,119 + 434 98 434 98 452 118 c 0,120,121 + 459.368 126.105 459.368 126.105 459.271 134.686 c 0,122,123 + 459.105 149.395 459.105 149.395 437 165.5 c 0,124,125 + 402.002 190.999 402.002 190.999 350 210 c 0,126,127 + 298 229.001 298 229.001 248 237 c 0,128,129 + 209.512 240.063 l 0,130,131 + 194.138 239.207 194.138 239.207 190 233 c 0,132,133 + 178.857 216.286 178.857 216.286 178.827 202.327 c 0,134,135 + 178.786 183.714 178.786 183.714 198.5 170 c 0,136,137 + 233 146 233 146 273 143 c 1,0,1 +803 384 m 0,79,80 + 814 403 814 403 806.5 436 c 0,81,82 + 799 469 799 469 757 454 c 0,83,84 + 714 439 714 439 719.5 402.5 c 0,85,86 + 725.001 365.999 725.001 365.999 744 364 c 0,87,88 + 686 364 686 364 682 416 c 0,89,90 + 682.987 446.036 l 0,91,92 + 689.14 481.814 689.14 481.814 720.5 502 c 0,93,94 + 764 530 764 530 805 574 c 0,95,96 + 818 588 818 588 852.5 708 c 0,97,98 + 887 828 887 828 872 893 c 0,99,100 + 852.999 968.001 852.999 968.001 790.5 1001.5 c 0,101,102 + 728 1034.99 728 1034.99 728 1128 c 0,103,104 + 728 1139.99 728 1139.99 743.5 1150 c 0,105,106 + 751.596 1155.23 751.596 1155.23 760.376 1155.26 c 0,107,108 + 768.402 1155.3 768.402 1155.3 777 1151 c 0,109,110 + 764.093 1148.42 764.093 1148.42 763.773 1134.36 c 0,111,112 + 763.721 1132.08 763.721 1132.08 764 1129.5 c 0,113,114 + 766 1111 766 1111 781 1111 c 0,115,116 + 792.638 1113.28 l 0,117,118 + 801.466 1118.77 801.466 1118.77 801.409 1136.92 c 0,119,120 + 801.343 1157.82 801.343 1157.82 789.5 1195.5 c 0,121,122 + 761.999 1283 761.999 1283 675 1301 c 0,123,124 + 582 1320.01 582 1320.01 516.5 1283 c 0,125,126 + 451 1245.99 451 1245.99 451 1187 c 0,127,128 + 451 1166.01 451 1166.01 478.5 1151.5 c 0,129,130 + 496.123 1142.2 496.123 1142.2 515.194 1142.16 c 0,131,132 + 525.87 1142.13 525.87 1142.13 537 1145 c 0,133,134 + 579 1154 579 1154 553 1199 c 0,135,136 + 583.043 1194.13 583.043 1194.13 583.417 1158.6 c 0,137,138 + 582 1140.5 l 0,139,140 + 574 1087.99 574 1087.99 547 1077 c 0,141,142 + 514.021 1064 514.021 1064 466 1056.5 c 0,143,144 + 418.018 1049 418.018 1049 379 1032 c 0,145,146 + 325 1008 325 1008 295.5 850.5 c 0,147,148 + 267.83 702.772 267.83 702.772 267.873 661.932 c 0,149,150 + 267.876 659.233 267.876 659.233 268 657 c 0,151,152 + 270 581 270 581 314.5 564 c 0,153,154 + 359 547 359 547 403 502 c 0,155,156 + 425 477 425 477 423.5 434.5 c 0,157,158 + 422 392 422 392 391 389 c 0,159,160 + 404 412 404 412 394 428 c 0,161,162 + 387.333 438.667 387.333 438.667 372.222 438.667 c 0,163,164 + 364.667 438.667 364.667 438.667 355 436 c 0,165,166 + 323 427 323 427 329 389 c 0,167,168 + 335 350.999 335 350.999 365 334 c 0,169,170 + 446.945 286.393 446.945 286.393 553.56 286.295 c 0,171,172 + 583.554 286.268 583.554 286.268 615.5 290 c 0,173,174 + 760.999 306.999 760.999 306.999 803 384 c 0,79,80 +EndSplineSet +KernsSLIF: 121 -65 0 0 97 -156 0 0 120 -143 0 0 119 -195 0 0 116 -313 0 0 +EndChar +StartChar: p +Encoding: 112 112 62 +Width: 1149 +Flags: MW +VStem: 186 277<161 1354.5> +Fore +459 842 m 0,0,1 + 533 791 533 791 552 852 c 0,2,3 + 571 918 571 918 538 911.5 c 0,4,5 + 505.001 905.001 505.001 905.001 490 888 c 0,6,7 + 484.931 894.589 484.931 894.589 485.001 903.875 c 0,8,9 + 485.068 912.911 485.068 912.911 490 924.5 c 0,10,11 + 500.001 948.002 500.001 948.002 510 959 c 0,12,13 + 552 1001 552 1001 594.5 970.5 c 0,14,15 + 636.999 940.001 636.999 940.001 684 927 c 0,16,17 + 743 909 743 909 765.5 991.5 c 0,18,19 + 788 1074 788 1074 793 1146 c 0,20,21 + 791.31 1194.24 l 0,22,23 + 786.836 1233.11 786.836 1233.11 772.5 1275.5 c 0,24,25 + 748.997 1345 748.997 1345 689 1378 c 0,26,27 + 653.011 1395.99 653.011 1395.99 614.5 1397 c 0,28,29 + 576 1398.01 576 1398.01 580 1334 c 0,30,31 + 582 1300.99 582 1300.99 610.5 1297.5 c 0,32,33 + 640.125 1297.91 l 0,34,35 + 655.135 1300.05 655.135 1300.05 671 1306 c 0,36,37 + 664.999 1278.99 664.999 1278.99 636.5 1266.5 c 0,38,39 + 618.241 1258.49 618.241 1258.49 605.122 1258.49 c 0,40,41 + 597.752 1258.48 597.752 1258.48 592 1261 c 0,42,43 + 532.006 1283.99 532.006 1283.99 502.5 1321.5 c 0,44,45 + 473 1359 473 1359 453 1368 c 0,46,47 + 432.95 1375.16 432.95 1375.16 416.875 1375.14 c 0,48,49 + 388.049 1375.11 388.049 1375.11 372 1352 c 0,50,51 + 352 1322 352 1322 350.5 1246.5 c 0,52,53 + 352.925 1165.25 l 0,54,55 + 355.829 1127.66 355.829 1127.66 362 1088.5 c 0,56,57 + 375.001 1005.99 375.001 1005.99 400 935 c 0,58,59 + 425.001 864 425.001 864 459 842 c 0,0,1 +219 40 m 0,36,37 + 217.856 126.542 l 0,38,39 + 221.958 253.051 221.958 253.051 260 376.5 c 0,40,41 + 291.04 477.228 291.04 477.228 290.964 584.069 c 0,42,43 + 290.915 652.771 290.915 652.771 278 724 c 0,44,45 + 263 800 263 800 215.5 853.5 c 0,46,47 + 168.001 906.999 168.001 906.999 158 973 c 0,48,49 + 157.625 1002.88 l 0,50,51 + 159.2 1017.98 159.2 1017.98 164 1035.5 c 0,52,53 + 174.001 1071.99 174.001 1071.99 208 1076 c 0,54,55 + 194.139 1039.57 194.139 1039.57 193.923 1016.15 c 0,56,57 + 196.953 996.417 l 0,58,59 + 203.629 978.699 203.629 978.699 225 975 c 0,60,61 + 246.691 974.559 l 0,62,63 + 276.931 980 276.931 980 283 1024 c 0,64,65 + 282.228 1068.73 l 0,66,67 + 280.438 1090.45 280.438 1090.45 276.5 1120.5 c 0,68,69 + 266.999 1193.01 266.999 1193.01 244.5 1258 c 0,70,71 + 221.997 1323 221.997 1323 186 1354.5 c 0,72,73 + 173.294 1365.62 173.294 1365.62 158.969 1365.71 c 0,74,75 + 144.032 1365.81 144.032 1365.81 127.335 1353.92 c 0,76,77 + 114.674 1344.91 114.674 1344.91 101 1329 c 0,78,79 + 68.9429 1292.23 68.9429 1292.23 68.889 1247.01 c 0,80,81 + 68.8857 1244.27 68.8857 1244.27 69 1241.5 c 0,82,83 + 70.9999 1193.01 70.9999 1193.01 89 1171 c 0,84,85 + 104.009 1149.99 104.009 1149.99 111 1137 c 0,86,87 + 117.997 1124 117.997 1124 139 1118 c 0,88,89 + 85.8527 1124.89 85.8527 1124.89 76 1137 c 0,90,91 + 66.9851 1149.02 66.9851 1149.02 47 1169 c 0,92,93 + 28 1206.99 28 1206.99 27 1238 c 0,94,95 + 26 1269.01 26 1269.01 32 1307 c 0,96,97 + 42.001 1376.01 42.001 1376.01 79 1420 c 0,98,99 + 169 1523.01 169 1523.01 248 1547.5 c 0,100,101 + 321.281 1570.22 321.281 1570.22 448.769 1570.15 c 0,102,103 + 458.716 1570.14 458.716 1570.14 469 1570 c 0,104,105 + 609.017 1567 609.017 1567 708.5 1534.5 c 0,106,107 + 808 1501.99 808 1501.99 929 1422 c 0,108,109 + 988.991 1381.01 988.991 1381.01 1042 1319 c 0,110,111 + 1071.32 1284.7 1071.32 1284.7 1071.57 1242.43 c 0,112,113 + 1071.66 1225.04 1071.66 1225.04 1066.84 1206.3 c 0,114,115 + 1062.2 1188.27 1062.2 1188.27 1053 1169 c 0,116,117 + 1025 1111.01 1025 1111.01 956 1104 c 0,118,119 + 978.832 1141.7 978.832 1141.7 979.109 1171.22 c 0,120,121 + 975.706 1193.58 l 0,122,123 + 971.477 1206.24 971.477 1206.24 962 1217 c 0,124,125 + 952.994 1226.01 952.994 1226.01 924 1232.5 c 0,126,127 + 895 1238.99 895 1238.99 895 1195 c 0,128,129 + 893 1118.01 893 1118.01 898 1043.5 c 0,130,131 + 898.872 971.375 l 0,132,133 + 897.219 932.389 897.219 932.389 891 893 c 0,134,135 + 883 845 883 845 841.5 736 c 0,136,137 + 800 627 800 627 729 600 c 0,138,139 + 704.81 590.534 704.81 590.534 673.984 590.609 c 0,140,141 + 646.19 590.677 646.19 590.677 613 598.5 c 0,142,143 + 543 615 543 615 526 669 c 0,144,145 + 568.61 646.769 568.61 646.769 613.795 646.846 c 0,146,147 + 617.39 646.853 617.39 646.853 621 647 c 0,148,149 + 675 650 675 650 679 678.5 c 0,150,151 + 676.92 691.447 l 0,152,153 + 667.063 711.922 667.063 711.922 615 728 c 0,154,155 + 572 741 572 741 525.5 732 c 0,156,157 + 479 723 479 723 452 689 c 0,158,159 + 432 663 432 663 414.5 579.5 c 0,160,161 + 397 496 397 496 412 436 c 0,162,163 + 428 362 428 362 444.5 296.5 c 0,164,165 + 461.001 230.997 461.001 230.997 463 161 c 0,166,167 + 464 15.9999 464 15.9999 401 -99 c 0,168,169 + 376.999 -141.002 376.999 -141.002 308.5 -197 c 0,170,171 + 239.999 -253 239.999 -253 190 -253 c 0,172,173 + 262 -218.001 262 -218.001 340.5 -113.5 c 0,174,175 + 419 -8.99995 419 -8.99995 383 78 c 0,176,177 + 363 124.999 363 124.999 327 121.5 c 0,178,179 + 291 118.001 291 118.001 264 82 c 0,180,181 + 251.066 64.7553 251.066 64.7553 251.04 37.4438 c 0,182,183 + 251.029 26.7444 251.029 26.7444 253 14.5 c 0,184,185 + 260 -29 260 -29 269 -50 c 0,186,187 + 220.999 -15.9996 220.999 -15.9996 219 40 c 0,36,37 +EndSplineSet +KernsSLIF: 45 -104 0 0 46 -221 0 0 44 -208 0 0 116 -195 0 0 322 -299 0 0 97 -299 0 0 +EndChar +StartChar: q +Encoding: 113 113 33 +Width: 1161 +Flags: W +Fore +894 1526 m 1,0,1 + 939 1548.01 939 1548.01 988 1526 c 0,2,3 + 1076 1482.01 1076 1482.01 1076 1388 c 0,4,5 + 1076 1319.99 1076 1319.99 1035.5 1151.5 c 0,6,7 + 995.011 983.049 995.011 983.049 982 920 c 0,8,9 + 976 893 976 893 973 854.5 c 0,10,11 + 970 816 970 816 1005 813 c 0,12,13 + 1025.76 814.377 l 0,14,15 + 1058.35 822.828 1058.35 822.828 1058.55 874.124 c 0,16,17 + 1058.58 881.159 1058.58 881.159 1058 889 c 0,18,19 + 1084.77 857.216 1084.77 857.216 1084.79 810.971 c 0,20,21 + 1084.81 774.286 1084.81 774.286 1068 728.5 c 0,22,23 + 1030 624.986 1030 624.986 1030 539 c 0,24,25 + 1030 452 1030 452 1057 408 c 0,26,27 + 1084 364 1084 364 1078 313 c 0,28,29 + 1069 237.011 1069 237.011 1032.5 176 c 0,30,31 + 1011.58 141.039 1011.58 141.039 973.09 140.897 c 0,32,33 + 946.128 140.797 946.128 140.797 910.547 157.778 c 0,34,35 + 908.291 158.855 908.291 158.855 906 160 c 0,36,37 + 997 161.999 997 161.999 986.5 227.5 c 0,38,39 + 976 293 976 293 940 293 c 0,40,41 + 924.998 291.999 924.998 291.999 890 261 c 0,42,43 + 855 229.999 855 229.999 855 191 c 0,44,45 + 854 138.001 854 138.001 876 122 c 0,46,47 + 897.996 106.003 897.996 106.003 926.5 90 c 0,48,49 + 955 73.9999 955 73.9999 981.5 40.5 c 0,50,51 + 1008.01 6.99366 1008.01 6.99366 1016 -79 c 0,52,53 + 985 -1 985 -1 920.5 42 c 0,54,55 + 856 85.0001 856 85.0001 835 26 c 0,56,57 + 820 -13 820 -13 902.5 -103 c 0,58,59 + 985 -193 985 -193 1095 -199 c 0,60,61 + 1038.78 -196.757 l 0,62,63 + 961.445 -188.18 961.445 -188.18 897.5 -149 c 0,64,65 + 811 -96.0005 811 -96.0005 754 -39 c 0,66,67 + 703 10 703 10 704 62.5 c 0,68,69 + 705 115 705 115 683 124 c 0,70,71 + 671.055 128.52 671.055 128.52 660.204 128.453 c 0,72,73 + 637.445 128.315 637.445 128.315 619.5 108 c 0,74,75 + 593 78 593 78 533 67 c 0,76,77 + 296 22 296 22 276 156 c 0,78,79 + 332 109.001 332 109.001 375.5 127.5 c 0,80,81 + 419 145.999 419 145.999 391 207 c 0,82,83 + 384 220.999 384 220.999 333 351 c 0,84,85 + 282 481 282 481 244 478 c 0,86,87 + 190.301 472.63 190.301 472.63 189.566 432.54 c 0,88,89 + 193.349 407.215 l 0,90,91 + 193.662 406.115 193.662 406.115 194 405 c 0,92,93 + 213.999 339 213.999 339 265 339 c 0,94,95 + 248.288 325.169 248.288 325.169 231.244 325.121 c 0,96,97 + 218.712 325.085 218.712 325.085 206 332.5 c 0,98,99 + 175.998 350.001 175.998 350.001 170 357 c 0,100,101 + 138.31 395.028 138.31 395.028 138.359 449.918 c 0,102,103 + 138.38 472.972 138.38 472.972 144 499 c 0,104,105 + 155.998 553.993 155.998 553.993 207.5 709.5 c 0,106,107 + 258.999 865 258.999 865 242 913 c 0,108,109 + 230.225 942.439 230.225 942.439 188.5 942.5 c 0,110,111 + 147 942 147 942 138 903 c 0,112,113 + 135.388 876.036 l 0,114,115 + 137.633 831.849 137.633 831.849 191 824 c 0,116,117 + 176 803 176 803 122 821 c 0,118,119 + 68 839 68 839 69 907 c 0,120,121 + 72.0001 1046.01 72.0001 1046.01 168 1147 c 0,122,123 + 263.993 1247.99 263.993 1247.99 311 1361 c 0,124,125 + 314.463 1377.59 l 0,126,127 + 314.082 1394.93 314.082 1394.93 293.5 1404 c 0,128,129 + 280.413 1405.97 l 0,130,131 + 254.722 1403.08 254.722 1403.08 220 1351 c 0,132,133 + 224.001 1422 224.001 1422 270.5 1455 c 0,134,135 + 316.989 1487.99 316.989 1487.99 374 1502.5 c 0,136,137 + 431 1517.01 431 1517.01 482 1523.5 c 0,138,139 + 532.995 1529.99 532.995 1529.99 548 1548 c 0,140,141 + 556.237 1558.37 556.237 1558.37 556.563 1567.91 c 0,142,143 + 553.491 1580.23 l 0,144,145 + 545.526 1594.7 545.526 1594.7 517 1607 c 0,146,147 + 459 1632.01 459 1632.01 408 1580 c 0,148,149 + 414 1645.99 414 1645.99 485 1659 c 0,150,151 + 518.084 1665.06 518.084 1665.06 542.705 1665.04 c 0,152,153 + 570.911 1665.01 570.911 1665.01 588 1657 c 0,154,155 + 646.008 1630 646.008 1630 681 1590 c 0,156,-1 + 732 1531 l 0,157,158 + 785.011 1462.99 785.011 1462.99 864.5 1431 c 0,159,160 + 902.895 1415.55 902.895 1415.55 928.109 1415.49 c 0,161,162 + 955.109 1415.42 955.109 1415.42 967 1433 c 0,163,164 + 992 1470.01 992 1470.01 960.5 1496 c 0,165,166 + 929 1521.99 929 1521.99 894 1526 c 0,167,-1 + 894 1526 l 1,0,1 +714 1394 m 1,101,102 + 629.017 1394 629.017 1394 539 1366.5 c 0,103,104 + 449 1339.01 449 1339.01 420 1278 c 0,105,106 + 413.818 1265.02 413.818 1265.02 413.751 1247.07 c 0,107,108 + 413.709 1235.98 413.709 1235.98 416 1223 c 0,109,110 + 422 1188.99 422 1188.99 461 1205 c 0,111,112 + 499 1220 499 1220 494 1257.5 c 0,113,114 + 489.001 1295 489.001 1295 472 1298 c 0,115,116 + 494.625 1295.06 l 0,117,118 + 524.25 1285.5 524.25 1285.5 528 1245 c 0,119,120 + 526.001 1211.45 l 0,121,122 + 519.32 1176.2 519.32 1176.2 492.5 1156 c 0,123,124 + 454.022 1127.02 454.022 1127.02 418 1083 c 0,125,126 + 406 1068 406 1068 372 943.5 c 0,127,128 + 347.868 855.136 347.868 855.136 347.917 796.743 c 0,129,130 + 347.937 772.865 347.937 772.865 352 754 c 0,131,132 + 368 676 368 676 431 615 c 0,133,134 + 494 554 494 554 494 459 c 0,135,136 + 494 446.001 494 446.001 480 436 c 0,137,138 + 466 426 466 426 451 435 c 0,139,140 + 462.186 437.581 462.186 437.581 462.266 451.639 c 0,141,142 + 462.279 453.919 462.279 453.919 462 456.5 c 0,143,144 + 460 475 460 475 448 477 c 0,145,146 + 415 479 415 479 409 417.5 c 0,147,148 + 403 356 403 356 459 317 c 0,149,150 + 543 254 543 254 606 284 c 0,151,152 + 656 306 656 306 647 353 c 0,153,154 + 638 400 638 400 584 430 c 0,155,156 + 665 426 665 426 676.5 381 c 0,157,158 + 688 336 688 336 742 333 c 0,159,160 + 775 330 775 330 792 361 c 0,161,162 + 809 392 809 392 809 407 c 0,163,164 + 806 469 806 469 732 451 c 0,165,166 + 693 440 693 440 718 395 c 0,167,168 + 684 401 684 401 691 455 c 0,169,170 + 698 509 698 509 724 521 c 0,171,172 + 752.003 533.001 752.003 533.001 808.5 549.5 c 0,173,174 + 865 566 865 566 886 619 c 0,175,176 + 906 672 906 672 888 854.5 c 0,177,178 + 870 1037 870 1037 777 1157 c 0,179,180 + 757.882 1180.9 757.882 1180.9 758 1225 c 0,181,182 + 759 1268.01 759 1268.01 788 1273 c 0,183,184 + 780.325 1258.24 780.325 1258.24 780.318 1246.44 c 0,185,186 + 780.313 1238.26 780.313 1238.26 784 1231.5 c 0,187,188 + 793 1215 793 1215 820 1224 c 0,189,190 + 848 1233 848 1233 848 1276 c 0,191,192 + 848 1319 848 1319 828 1343 c 0,193,194 + 784 1391 784 1391 714 1394 c 1,101,102 +EndSplineSet +EndChar +StartChar: r +Encoding: 114 114 58 +Width: 1124 +Flags: HMW +VStem: 91 270<64 1451> +Fore +955 37 m 0,0,1 + 952 91 952 91 911.5 135 c 0,2,3 + 870.999 179 870.999 179 819 191 c 0,4,5 + 794.703 192.621 l 0,6,7 + 770.125 190 770.125 190 755 168 c 0,8,9 + 745.623 154.361 745.623 154.361 745.693 141.266 c 0,10,11 + 745.787 123.639 745.787 123.639 763 107 c 0,12,13 + 789 80 789 80 804 91.5 c 0,14,15 + 819 103 819 103 834 124 c 0,16,17 + 849 52 849 52 786 35 c 0,18,19 + 723 18 723 18 687 71 c 0,20,21 + 657.999 113.002 657.999 113.002 650 167.5 c 0,22,23 + 642 221.999 642 221.999 629 268 c 0,24,25 + 605 346 605 346 541.5 461.5 c 0,26,27 + 478 577 478 577 396 594 c 0,28,29 + 366 600 366 600 324 584 c 0,30,31 + 282 568 282 568 282 504 c 0,32,33 + 282 388 282 388 319 283 c 0,34,35 + 356 178 356 178 349 52 c 0,36,37 + 345 -12 345 -12 286 -82.5 c 0,38,39 + 227.001 -152.999 227.001 -152.999 166 -175 c 0,40,41 + 73 -208 73 -208 -6 -196 c 0,42,43 + 48 -188.001 48 -188.001 113 -160 c 0,44,45 + 149.001 -141.999 149.001 -141.999 206.5 -91 c 0,46,47 + 263.999 -40 263.999 -40 268 35 c 0,48,49 + 267.157 86.4993 l 0,50,51 + 264.878 110.469 264.878 110.469 259 133 c 0,52,53 + 247.316 177.79 247.316 177.79 183 178 c 0,54,55 + 132.68 176.027 132.68 176.027 132.5 103 c 0,56,57 + 132.999 30.0002 132.999 30.0002 184 11 c 0,58,59 + 139 9 139 9 119.5 27.5 c 0,60,61 + 100 46 100 46 91 64 c 0,62,63 + 46 143.001 46 143.001 96.5 293 c 0,64,65 + 146.998 442.991 146.998 442.991 166 525 c 0,66,67 + 187 621 187 621 166 636.5 c 0,68,69 + 156.351 643.621 156.351 643.621 147.758 643.671 c 0,70,71 + 137.649 643.73 137.649 643.73 129 634 c 0,72,73 + 113.001 616.001 113.001 616.001 110.5 587 c 0,74,75 + 107.999 558 107.999 558 123 546 c 0,76,77 + 64.9999 548 64.9999 548 58.5 598.5 c 0,78,79 + 52 649 52 649 59 679 c 0,80,81 + 71 730 71 730 105 787 c 0,82,83 + 139.001 844 139.001 844 153 896 c 0,84,85 + 167.911 959.375 167.911 959.375 167.814 1022.19 c 0,86,87 + 167.781 1043.63 167.781 1043.63 166 1065 c 0,88,89 + 155.002 1181.99 155.002 1181.99 136 1306 c 0,90,91 + 132.713 1352.23 l 0,92,93 + 134.048 1449.51 134.048 1449.51 207 1533 c 0,94,95 + 277.995 1615 277.995 1615 419.5 1625.5 c 0,96,97 + 561 1636 561 1636 567 1480 c 0,98,99 + 533 1558 533 1558 442.5 1553.5 c 0,100,101 + 360.829 1549.44 360.829 1549.44 360.191 1469.23 c 0,102,103 + 360.122 1460.56 360.122 1460.56 361 1451 c 0,104,105 + 366 1387.99 366 1387.99 491.5 1375.5 c 0,106,107 + 547.456 1373.25 l 0,108,109 + 617.51 1376 617.51 1376 619 1414 c 0,110,111 + 616.188 1429.37 l 0,112,113 + 607.359 1448.45 607.359 1448.45 570.946 1448.57 c 0,114,115 + 564.416 1448.59 564.416 1448.59 557 1448 c 0,116,117 + 588.229 1465.3 588.229 1465.3 621.879 1465.4 c 0,118,119 + 654.905 1465.5 654.905 1465.5 690.262 1449.03 c 0,120,121 + 693.869 1447.35 693.869 1447.35 697.5 1445.5 c 0,122,123 + 773.003 1406.99 773.003 1406.99 802 1323 c 0,124,125 + 823 1257 823 1257 854.5 1237.5 c 0,126,127 + 886 1218 886 1218 940 1170 c 0,128,129 + 964.001 1147.99 964.001 1147.99 973 1098.5 c 0,130,131 + 982 1049 982 1049 926 1019 c 0,132,133 + 964 1061 964 1061 938 1095.5 c 0,134,135 + 921.406 1117.52 921.406 1117.52 906.846 1118.56 c 0,136,137 + 894.877 1115.67 l 0,138,139 + 892.918 1114.55 892.918 1114.55 891 1113 c 0,140,141 + 877.293 1101.25 877.293 1101.25 877.365 1072.37 c 0,142,143 + 877.441 1042.25 877.441 1042.25 892.5 993.5 c 0,144,145 + 922 898 922 898 900 805 c 0,146,147 + 879 719 879 719 799.5 707 c 0,148,149 + 720 695 720 695 687 725 c 0,150,151 + 721 725 721 725 748 745 c 0,152,153 + 768.483 760.172 768.483 760.172 768.823 785.704 c 0,154,155 + 767 803 l 0,156,157 + 755 863 755 863 684 802.5 c 0,158,159 + 622.198 749.838 622.198 749.838 621.768 695.282 c 0,160,161 + 621.704 687.162 621.704 687.162 623 679 c 0,162,163 + 628 642 628 642 678.5 602.5 c 0,164,165 + 714.169 574.601 714.169 574.601 735.12 574.389 c 0,166,167 + 743.832 574.301 743.832 574.301 750 579 c 0,168,169 + 767 593 767 593 753 613.5 c 0,170,171 + 739 634 739 634 703 634 c 0,172,173 + 706.918 659.463 706.918 659.463 751.5 659.5 c 0,174,175 + 796 659 796 659 817 635 c 0,176,177 + 845 602 845 602 837.5 533 c 0,178,179 + 830 464 830 464 830 422 c 0,180,181 + 830 331.001 830 331.001 895 304.5 c 0,182,183 + 960 278 960 278 1008 210 c 0,184,185 + 1044.01 154.989 1044.01 154.989 1056.5 81 c 0,186,187 + 1063.49 39.6195 1063.49 39.6195 1063.44 4.82321 c 0,188,189 + 1063.41 -22.6343 1063.41 -22.6343 1059 -46 c 0,190,191 + 1012.01 -279.997 1012.01 -279.997 833 -375 c 0,192,193 + 654 -470 654 -470 447 -500 c 0,194,195 + 651 -443 651 -443 809 -321.5 c 0,196,197 + 967 -200 967 -200 955 37 c 0,0,1 +502 848 m 0,122,123 + 524 824 524 824 556 836 c 0,124,125 + 588 848 588 848 624 872 c 0,126,127 + 708 930 708 930 720 1081.5 c 0,128,129 + 721.045 1138.14 l 0,130,131 + 716.188 1217.67 716.188 1217.67 668.868 1217.71 c 0,132,133 + 661.895 1217.72 661.895 1217.72 654 1216 c 0,134,135 + 621 1208.01 621 1208.01 618 1181.5 c 0,136,137 + 619.974 1168.14 l 0,138,139 + 627.885 1149.33 627.885 1149.33 665 1133 c 0,140,141 + 627.903 1130.74 l 0,142,143 + 584.539 1132.87 584.539 1132.87 560.5 1160.5 c 0,144,145 + 527.011 1198.99 527.011 1198.99 492 1220 c 0,146,147 + 456.982 1241.43 456.982 1241.43 425.381 1241.41 c 0,148,149 + 396.515 1241.4 396.515 1241.4 370.5 1223.5 c 0,150,151 + 315.999 1186 315.999 1186 290 1108 c 0,152,153 + 276.999 1070.99 276.999 1070.99 269.5 953 c 0,154,155 + 269.879 905.901 l 0,156,157 + 277.054 832.123 277.054 832.123 330 822 c 0,158,159 + 394 808 394 808 391 879 c 0,160,161 + 387.786 911.935 387.786 911.935 350.375 911.961 c 0,162,163 + 341.213 911.967 341.213 911.967 330 910 c 0,164,165 + 327 927 327 927 359.5 939 c 0,166,167 + 392 951 392 951 409 941 c 0,168,169 + 472 898 472 898 464.5 896.5 c 0,170,171 + 457 895 457 895 502 848 c 0,122,123 +EndSplineSet +KernsSLIF: 121 -156 0 0 115 -182 0 0 103 -104 0 0 116 -339 0 0 118 -43 0 0 119 -150 0 0 +EndChar +StartChar: s +Encoding: 115 115 25 +Width: 1163 +Flags: HW +Fore +509 51 m 0,0,1 + 494 57 494 57 471.5 79 c 0,2,3 + 449 101 449 101 453 122 c 0,4,-1 + 495.5 92.5 l 0,5,6 + 517 77.0001 517 77.0001 538 93 c 0,7,8 + 553.149 104.584 553.149 104.584 553.111 115.871 c 0,9,10 + 553.064 129.916 553.064 129.916 529.5 143.5 c 0,11,12 + 487 167.999 487 167.999 420 191.5 c 0,13,-1 + 286.5 238 l 0,14,15 + 220 261 220 261 205 285 c 0,16,17 + 181 321 181 321 187 375.5 c 0,18,19 + 193 430.001 193 430.001 241 441 c 0,20,21 + 233.001 324 233.001 324 343 358 c 0,22,23 + 379 369 379 369 372 414 c 0,24,25 + 365 459 365 459 353 483 c 0,26,27 + 327 534 327 534 258 563 c 0,28,29 + 188.998 592 188.998 592 134 601 c 0,30,31 + 96.4745 601.959 l 0,32,33 + 84.3876 601.016 84.3876 601.016 72 598.5 c 0,34,-1 + 8 586 l 0,35,36 + 67.4219 631.557 67.4219 631.557 112 631.5 c 0,37,38 + 156 631 156 631 171 630 c 0,39,40 + 212.002 627 212.002 627 278.5 599 c 0,41,42 + 345 571 345 571 373 545 c 0,43,44 + 420.001 499.999 420.001 499.999 465.5 423 c 0,45,46 + 511 346 511 346 567 302 c 0,47,48 + 599 275 599 275 666.5 261 c 0,49,50 + 689 256.333 689 256.333 707.667 256.333 c 0,51,52 + 745 256.333 745 256.333 767 275 c 0,53,54 + 849 347 849 347 861.5 443 c 0,55,56 + 874 539 874 539 844 610 c 0,57,58 + 828.999 645.001 828.999 645.001 760.5 693.5 c 0,59,60 + 692 742 692 742 642 745 c 0,61,62 + 582 748 582 748 582 710 c 0,63,64 + 582 667 582 667 600 657.5 c 0,65,-1 + 650 630 l 0,66,67 + 605 613 605 613 562.5 634.5 c 0,68,69 + 520 656 520 656 504 696 c 0,70,-1 + 465 789.5 l 0,71,72 + 434 864 434 864 392 943.5 c 0,73,74 + 350 1023 350 1023 304 1081.5 c 0,75,76 + 266.656 1128.99 266.656 1128.99 233.93 1129.36 c 0,77,78 + 226.341 1129.45 226.341 1129.45 219 1127 c 0,79,80 + 188.007 1116.35 188.007 1116.35 188 1063.5 c 0,81,82 + 189 1011 189 1011 219 1004 c 0,83,84 + 196.609 1001.73 l 0,85,86 + 170.282 1003.7 170.282 1003.7 155.5 1032 c 0,87,88 + 136 1071 136 1071 136 1089 c 0,89,90 + 136 1144 136 1144 148.5 1184.5 c 0,91,92 + 160.999 1225 160.999 1225 182 1267 c 0,93,94 + 231.001 1368 231.001 1368 351 1456 c 0,95,96 + 471 1544.01 471 1544.01 521 1573 c 0,97,98 + 587 1612 587 1612 649.5 1637.5 c 0,99,100 + 678.818 1649.46 678.818 1649.46 728.714 1649.43 c 0,101,102 + 785.176 1649.39 785.176 1649.39 868 1634 c 0,103,104 + 955.012 1617.99 955.012 1617.99 1003 1567.5 c 0,105,106 + 1051.01 1516.99 1051.01 1516.99 1056 1476 c 0,107,108 + 1013.4 1532.09 1013.4 1532.09 946.088 1532.22 c 0,109,110 + 918.604 1532.28 918.604 1532.28 887 1523 c 0,111,112 + 851 1511 851 1511 833.5 1473.5 c 0,113,114 + 819.161 1442.77 819.161 1442.77 819.256 1410.37 c 0,115,116 + 819.277 1403.23 819.277 1403.23 820 1396 c 0,117,118 + 829 1279 829 1279 945 1291 c 0,119,120 + 1061.01 1303 1061.01 1303 1138 1327 c 0,121,122 + 1091 1261.99 1091 1261.99 1004 1243.5 c 0,123,124 + 945.303 1231.02 945.303 1231.02 908.464 1231.06 c 0,125,126 + 890.69 1231.07 890.69 1231.07 878 1234 c 0,127,128 + 803 1250.01 803 1250.01 768 1286.5 c 0,129,130 + 732.944 1323.05 732.944 1323.05 683 1367 c 0,131,132 + 648.004 1397.71 648.004 1397.71 602.286 1397.82 c 0,133,134 + 584.001 1397.86 584.001 1397.86 564 1393 c 0,135,136 + 494 1376.01 494 1376.01 464 1312 c 0,137,138 + 442.001 1264 442.001 1264 433.5 1173.5 c 0,139,140 + 425 1083.01 425 1083.01 473 1046 c 0,141,142 + 567 971 567 971 609.5 983.5 c 0,143,144 + 635.732 991.215 635.732 991.215 669.393 991.121 c 0,145,146 + 690.268 991.062 690.268 991.062 714 988 c 0,147,148 + 749 983 749 983 784.5 953.5 c 0,149,150 + 820 924 820 924 801 876 c 0,151,152 + 778 934 778 934 751.5 937 c 0,153,154 + 725 940 725 940 710 921 c 0,155,156 + 703.558 912.65 703.558 912.65 703.463 902.677 c 0,157,158 + 703.364 892.286 703.364 892.286 710.156 880.133 c 0,159,160 + 724.167 855.064 724.167 855.064 767.5 822.5 c 0,161,162 + 852 759 852 759 885 749 c 0,163,164 + 912 740 912 740 944.5 746.5 c 0,165,166 + 957.24 749.048 957.24 749.048 957.149 759.202 c 0,167,168 + 957.008 774.952 957.008 774.952 926 809 c 0,169,170 + 995 803 995 803 1002.5 737.5 c 0,171,172 + 1006.09 675.401 l 0,173,174 + 1005.75 651.29 1005.75 651.29 1002 633 c 0,175,176 + 994 600 994 600 982.5 508.5 c 0,177,178 + 971 417 971 417 998 358 c 0,179,180 + 1019 310 1019 310 1040 298.5 c 0,181,182 + 1061 286.999 1061 286.999 1073 214 c 0,183,184 + 1071.38 184.394 l 0,185,186 + 1067.63 161.887 1067.63 161.887 1057 130 c 0,187,188 + 1037.99 72.9995 1037.99 72.9995 975 67 c 0,189,190 + 985.997 86.995 985.997 86.995 1019.5 137 c 0,191,192 + 1030.29 153.102 1030.29 153.102 1030.65 164.951 c 0,193,194 + 1027.91 176.689 l 0,195,196 + 1019.57 191.491 1019.57 191.491 986 196 c 0,197,198 + 959 199 959 199 935 161.5 c 0,199,200 + 911 124 911 124 908 120 c 0,201,202 + 854 37.0001 854 37.0001 726 23 c 0,203,204 + 659.279 19.5269 l 0,205,206 + 573.801 20.4195 573.801 20.4195 509 51 c 0,0,1 +EndSplineSet +KernsSLIF: 99 -52 0 0 115 -104 0 0 116 -78 0 0 +EndChar +StartChar: t +Encoding: 116 116 84 +Width: 1471 +Flags: HMW +HStem: 1266 219.5<365 1069.5> +VStem: 624 185.5<219 1233.5> +Fore +624 219 m 0,0,1 + 642.376 322.018 642.376 322.018 642.302 416.663 c 0,2,3 + 642.244 491.983 642.244 491.983 630.5 562 c 0,4,5 + 604 720 604 720 562 888 c 0,6,7 + 553 921 553 921 563 987 c 0,8,9 + 572.193 1047.67 572.193 1047.67 616.886 1048.34 c 0,10,11 + 620.807 1048.4 620.807 1048.4 625 1048 c 0,12,13 + 616.998 1048 616.998 1048 607 1029 c 0,14,15 + 597 1009.99 597 1009.99 597 1002 c 0,16,17 + 599 963.001 599 963.001 629.5 959 c 0,18,19 + 641.54 960.523 l 0,20,21 + 657.957 968.155 657.957 968.155 658.121 1008.79 c 0,22,23 + 658.137 1012.74 658.137 1012.74 658 1017 c 0,24,25 + 656.003 1055.96 656.003 1055.96 647 1181.5 c 0,26,27 + 639.493 1286.18 639.493 1286.18 588.846 1287.54 c 0,28,29 + 567 1284 l 0,30,31 + 554.021 1280 554.021 1280 476 1274 c 0,32,33 + 397.691 1267.98 397.691 1267.98 365 1266 c 0,34,35 + 299 1263 299 1263 245.5 1300.5 c 0,36,37 + 210.991 1324.69 210.991 1324.69 210.807 1365.73 c 0,38,39 + 210.708 1387.86 210.708 1387.86 221 1416 c 0,40,41 + 221 1344.01 221 1344.01 259 1340 c 0,42,43 + 283.415 1340.61 l 0,44,45 + 310.784 1345.98 310.784 1345.98 311.168 1375.6 c 0,46,47 + 311.254 1382.2 311.254 1382.2 310 1390 c 0,48,49 + 301 1445.99 301 1445.99 269 1456 c 0,50,51 + 189.025 1479.99 189.025 1479.99 142 1484 c 0,52,53 + 113.297 1482.43 l 0,54,55 + 75.4871 1475.66 75.4871 1475.66 27 1445 c 0,56,57 + 46 1488.99 46 1488.99 95.5 1506.5 c 0,58,59 + 137.72 1521.43 137.72 1521.43 172.316 1521.44 c 0,60,61 + 178.271 1521.44 178.271 1521.44 184 1521 c 0,62,63 + 358 1506 358 1506 570 1483.5 c 0,64,65 + 782 1461 782 1461 932 1470 c 0,66,67 + 1011.07 1474.01 1011.07 1474.01 1069.5 1485.5 c 0,68,69 + 1104.15 1492.31 1104.15 1492.31 1144.26 1492.28 c 0,70,71 + 1171.84 1492.26 1171.84 1492.26 1202 1489 c 0,72,73 + 1287.72 1478.71 1287.72 1478.71 1288.21 1436.1 c 0,74,75 + 1286 1421 l 0,76,77 + 1272.84 1374.96 1272.84 1374.96 1270 1376 c 0,78,79 + 1266.61 1438.7 1266.61 1438.7 1221.94 1439.3 c 0,80,81 + 1204.5 1437.5 l 0,82,83 + 1143.01 1425.01 1143.01 1425.01 1136 1401 c 0,84,85 + 1131.97 1388.36 1131.97 1388.36 1131.98 1377.27 c 0,86,87 + 1132.03 1347.14 1132.03 1347.14 1162 1328.5 c 0,88,89 + 1202.99 1303 1202.99 1303 1257 1303 c 0,90,91 + 1311 1303 1311 1303 1355.5 1332.5 c 0,92,93 + 1392.39 1356.95 1392.39 1356.95 1392.51 1405.11 c 0,94,95 + 1392.54 1415.05 1392.54 1415.05 1391 1426 c 0,96,97 + 1394.7 1412.33 1394.7 1412.33 1394.7 1396.19 c 0,98,99 + 1394.72 1368.69 1394.72 1368.69 1384 1334 c 0,100,101 + 1367.01 1279 1367.01 1279 1286 1255 c 0,102,103 + 1209.95 1231.81 1209.95 1231.81 1143.93 1231.74 c 0,104,105 + 1087.56 1231.69 1087.56 1231.69 1038.5 1248.5 c 0,106,107 + 931.985 1285 931.985 1285 848 1285 c 0,108,109 + 810 1285 810 1285 809.5 1233.5 c 0,110,111 + 812.56 1134.13 l 0,112,113 + 812.772 1131.07 812.772 1131.07 813 1128 c 0,114,-1 + 820.5 1062 l 0,115,116 + 828 996 828 996 900 901 c 0,117,118 + 933 856 933 856 915 750 c 0,119,120 + 897 644 897 644 814 656 c 0,121,122 + 874 656 874 656 868 747.5 c 0,123,124 + 862 839 862 839 820 803 c 0,125,126 + 789 777.001 789 777.001 784 755.5 c 0,127,128 + 781.13 743.159 781.13 743.159 781.225 717.148 c 0,129,130 + 781.296 697.84 781.296 697.84 783 671 c 0,131,132 + 792 520.002 792 520.002 825.5 433.5 c 0,133,134 + 859 347 859 347 853 158 c 0,135,136 + 847 17 847 17 757 -3 c 0,137,138 + 808 55 808 55 800 89.5 c 0,139,140 + 792 124 792 124 763.5 129.5 c 0,141,142 + 744.112 129.608 l 0,143,144 + 725.165 126.183 725.165 126.183 706 109 c 0,145,146 + 684.494 89.7188 684.494 89.7188 684.436 50.0908 c 0,147,148 + 684.416 36.2807 684.416 36.2807 687 20 c 0,149,150 + 709.999 -130.999 709.999 -130.999 754.5 -171 c 0,151,-1 + 828 -238 l 0,152,153 + 706 -212 706 -212 654.5 -55.5 c 0,154,155 + 603 101 603 101 624 219 c 0,0,1 +EndSplineSet +KernsSLIF: 322 -326 0 0 117 -117 0 0 104 -169 0 0 45 -221 0 0 46 -260 0 0 44 -260 0 0 243 -208 0 0 115 -208 0 0 111 -182 0 0 97 -448 0 0 +EndChar +StartChar: u +Encoding: 117 117 67 +Width: 1204 +Flags: W +Fore +46 335 m 0,0,1 + -12 419 -12 419 50.5 484.5 c 0,2,3 + 113 550 113 550 146 550 c 0,4,5 + 107 520 107 520 95 443.5 c 0,6,7 + 83 367 83 367 171 394 c 0,8,9 + 196.001 402 196.001 402 204 489 c 0,10,11 + 208.642 539.483 208.642 539.483 208.57 585.923 c 0,12,13 + 208.518 619.519 208.518 619.519 206 651 c 0,14,15 + 198.001 728.999 198.001 728.999 158.5 773 c 0,16,17 + 147.119 785.678 147.119 785.678 140.179 786.152 c 0,18,19 + 134.174 783.358 l 0,20,21 + 129.301 777.2 129.301 777.2 129.337 757.553 c 0,22,23 + 129.368 740.725 129.368 740.725 133 714 c 0,24,25 + 81.8411 754.35 81.8411 754.35 81.5628 831.304 c 0,26,27 + 81.4631 858.861 81.4631 858.861 87.8877 891.11 c 0,28,29 + 88.4213 893.788 88.4213 893.788 89 896.5 c 0,30,31 + 116 1023 116 1023 106 1188 c 0,32,33 + 103.71 1273.97 l 0,34,35 + 106.169 1385.74 106.169 1385.74 140 1454.5 c 0,36,37 + 186.008 1548.01 186.008 1548.01 245 1590.5 c 0,38,39 + 303.999 1632.99 303.999 1632.99 355.5 1640 c 0,40,41 + 405.982 1646.87 405.982 1646.87 406 1647 c 0,42,43 + 337.006 1635 337.006 1635 274.5 1567 c 0,44,45 + 212.006 1499.01 212.006 1499.01 185 1425 c 0,46,47 + 170.414 1385.03 170.414 1385.03 170.42 1350.16 c 0,48,49 + 170.425 1320.48 170.425 1320.48 181 1294.5 c 0,50,51 + 200.164 1247.42 200.164 1247.42 274.889 1247.21 c 0,52,53 + 289.833 1247.17 289.833 1247.17 307 1249 c 0,54,55 + 359.668 1254.35 359.668 1254.35 359.608 1300.76 c 0,56,57 + 359.589 1315.16 359.589 1315.16 354.5 1333.5 c 0,58,59 + 335.326 1402.62 335.326 1402.62 276.773 1402.94 c 0,60,61 + 269.676 1402.97 269.676 1402.97 262 1402 c 0,62,63 + 286.672 1406.42 286.672 1406.42 306.953 1406.43 c 0,64,65 + 396.829 1406.48 396.829 1406.48 400.5 1320 c 0,66,67 + 400.121 1249.19 l 0,68,69 + 396.789 1203.44 396.789 1203.44 384 1187 c 0,70,71 + 304 1085 304 1085 299.5 912.5 c 0,72,73 + 295 740 295 740 303 615 c 0,74,75 + 307.999 531.003 307.999 531.003 343 441 c 0,76,77 + 378 351 378 351 454 381 c 0,78,79 + 508 402 508 402 466 449 c 0,80,81 + 424 496 424 496 403 440 c 0,82,83 + 400.021 467.968 l 0,84,85 + 401.42 496.722 401.42 496.722 426 505.5 c 0,86,87 + 461 518 461 518 482 512 c 0,88,89 + 561.579 485.473 561.579 485.473 561.729 423.945 c 0,90,91 + 561.737 420.526 561.737 420.526 561.5 417 c 0,92,93 + 557 350 557 350 553 329 c 0,94,95 + 551.037 308.068 l 0,96,97 + 553.844 275.341 553.844 275.341 595.5 250.5 c 0,98,99 + 610.331 241.656 610.331 241.656 628.383 241.735 c 0,100,101 + 676.669 241.947 676.669 241.947 748 306 c 0,102,103 + 763 319 763 319 797 375 c 0,104,105 + 830.998 430.995 830.998 430.995 853 497 c 0,106,107 + 875 563 875 563 869.5 623 c 0,108,109 + 863.999 683 863.999 683 800 707 c 0,110,111 + 780.712 710.301 l 0,112,113 + 758.425 708.952 758.425 708.952 758.366 675.576 c 0,114,115 + 758.361 672.891 758.361 672.891 758.5 670 c 0,116,117 + 761 617.999 761 617.999 798 594 c 0,118,119 + 711.001 634.999 711.001 634.999 705.5 715 c 0,120,121 + 700 795 700 795 728.5 892.5 c 0,122,123 + 757 990 757 990 795.5 1095 c 0,124,125 + 834 1200 834 1200 835 1292 c 0,126,127 + 835 1305.01 835 1305.01 852.5 1409 c 0,128,129 + 867.429 1497.72 867.429 1497.72 946.032 1497.66 c 0,130,131 + 959.572 1497.64 959.572 1497.64 975 1495 c 0,132,133 + 951.995 1495 951.995 1495 926.5 1468.5 c 0,134,135 + 911.116 1452.51 911.116 1452.51 910.836 1433.8 c 0,136,137 + 914.401 1414.21 l 0,138,139 + 915.524 1411.14 915.524 1411.14 917 1408 c 0,140,141 + 937.073 1367.26 937.073 1367.26 962.372 1366.61 c 0,142,143 + 978.379 1369.98 l 0,144,145 + 988.798 1374.48 988.798 1374.48 1000 1385 c 0,146,147 + 1024 1406.6 1024 1406.6 1024.06 1454.48 c 0,148,149 + 1024.1 1486.4 1024.1 1486.4 1013.5 1530 c 0,150,151 + 987 1639.01 987 1639.01 850 1617 c 0,152,153 + 950 1666.99 950 1666.99 1035.5 1573.5 c 0,154,155 + 1080.31 1524.5 1080.31 1524.5 1080.48 1450.07 c 0,156,157 + 1080.58 1406.75 1080.58 1406.75 1065.56 1354.82 c 0,158,159 + 1057.15 1325.76 1057.15 1325.76 1044 1294 c 0,160,161 + 1013.95 1220.87 1013.95 1220.87 979 1119.5 c 0,162,163 + 944 1017.99 944 1017.99 941 959 c 0,164,165 + 936 887 936 887 974 864 c 0,166,167 + 997.65 849.686 997.65 849.686 1019.56 849.509 c 0,168,169 + 1031.83 849.41 1031.83 849.41 1045.5 854.5 c 0,170,171 + 1079 868.002 1079 868.002 1085 913 c 0,172,173 + 1091 958 1091 958 1022 1023 c 0,174,175 + 1143.01 1012 1143.01 1012 1145 909 c 0,176,177 + 1142.12 849.83 l 0,178,179 + 1133.28 771.826 1133.28 771.826 1098 684 c 0,180,181 + 1048.99 561.998 1048.99 561.998 984 456.5 c 0,182,183 + 919 351 919 351 906 335 c 0,184,185 + 872.999 294.998 872.999 294.998 847.5 240 c 0,186,187 + 840.928 225.825 840.928 225.825 840.965 216.299 c 0,188,189 + 841.041 196.841 841.041 196.841 868.696 196.786 c 0,190,191 + 880.031 196.763 880.031 196.763 896 200 c 0,192,193 + 930.895 206.264 930.895 206.264 931.366 231.74 c 0,194,195 + 931.421 234.737 931.421 234.737 931 238 c 0,196,197 + 927 269 927 269 913 308 c 0,198,199 + 977.209 274.007 977.209 274.007 977.222 212.054 c 0,200,201 + 977.226 191.993 977.226 191.993 970.5 169 c 0,202,203 + 943.001 75.0001 943.001 75.0001 865 74 c 0,204,205 + 732.561 75.6253 l 0,206,207 + 459.222 87.5019 459.222 87.5019 292.5 172 c 0,208,209 + 88.0008 275.999 88.0008 275.999 46 335 c 0,0,1 +EndSplineSet +KernsSLIF: 116 -78 0 0 120 -104 0 0 +EndChar +StartChar: v +Encoding: 118 118 70 +Width: 1087 +Flags: W +Fore +305 1015 m 1,0,1 + 390 991 390 991 393 922.5 c 0,2,3 + 393.509 829.461 l 0,4,5 + 392.953 816.677 392.953 816.677 392 805 c 0,6,7 + 386 748 386 748 378.5 703.5 c 0,8,9 + 377.807 678.574 l 0,10,11 + 381.441 653.166 381.441 653.166 405 640 c 0,12,13 + 413.621 635.115 413.621 635.115 420.879 634.937 c 0,14,15 + 431.632 637.67 l 0,16,17 + 441.986 643.7 441.986 643.7 448.5 663 c 0,18,19 + 462 703 462 703 466.5 760 c 0,20,21 + 471 817 471 817 470 870.5 c 0,22,23 + 469 923.975 469 923.975 469 934 c 0,24,25 + 469 1002 469 1002 473.5 1056.5 c 0,26,27 + 478.001 1111.01 478.001 1111.01 499 1176 c 0,28,29 + 514.003 1223 514.003 1223 546.5 1260.5 c 0,30,31 + 578.993 1297.99 578.993 1297.99 605 1311 c 0,32,33 + 619 1313.94 l 0,34,35 + 626.997 1313.57 626.997 1313.57 635 1308.5 c 0,36,37 + 650 1299.01 650 1299.01 650 1287 c 0,38,39 + 637.454 1293.55 637.454 1293.55 628.479 1293.58 c 0,40,41 + 606.104 1293.67 606.104 1293.67 605.918 1253.32 c 0,42,43 + 605.905 1250.51 605.905 1250.51 606 1247.5 c 0,44,45 + 608 1184 608 1184 634 1184 c 0,46,47 + 662 1184 662 1184 673.5 1211 c 0,48,49 + 685 1238 685 1238 685 1259 c 0,50,51 + 685 1341.01 685 1341.01 698.5 1403 c 0,52,53 + 712.006 1465.02 712.006 1465.02 734 1540 c 0,54,55 + 740.003 1566.01 740.003 1566.01 763 1593.5 c 0,56,57 + 786.018 1621.02 786.018 1621.02 799 1633 c 0,58,59 + 822.005 1653.13 822.005 1653.13 871 1653 c 0,60,61 + 919 1651.99 919 1651.99 925 1623 c 0,62,63 + 888 1659 888 1659 826 1611 c 0,64,65 + 764 1563 764 1563 805 1494 c 0,66,67 + 819.935 1468.52 819.935 1468.52 842.394 1468.42 c 0,68,69 + 863.65 1468.32 863.65 1468.32 891.649 1490.95 c 0,70,71 + 901.414 1498.84 901.414 1498.84 912 1509.5 c 0,72,73 + 985 1583 985 1583 996 1616 c 0,74,75 + 1013.4 1672.65 1013.4 1672.65 1013.38 1712.89 c 0,76,77 + 1013.36 1762.85 1013.36 1762.85 986.5 1787.5 c 0,78,79 + 937.961 1832.04 937.961 1832.04 924 1847 c 0,80,81 + 981.007 1818.99 981.007 1818.99 1008.5 1784.5 c 0,82,83 + 1036 1749.99 1036 1749.99 1036 1677 c 0,84,85 + 1036 1607.99 1036 1607.99 1000.5 1547.5 c 0,86,87 + 964.989 1486.99 964.989 1486.99 926 1442 c 0,88,89 + 743 1230.01 743 1230.01 737 927 c 0,90,91 + 736 901 736 901 738.5 830.5 c 0,92,93 + 741 760 741 760 735.5 680 c 0,94,95 + 729.999 599.996 729.999 599.996 712 529 c 0,96,97 + 694 458 694 458 652 433 c 0,98,99 + 688.123 508.663 688.123 508.663 688.026 560.736 c 0,100,101 + 687.924 615.337 687.924 615.337 648 644 c 0,102,103 + 585 689 585 689 553 602 c 0,104,105 + 521 515 521 515 512 471 c 0,106,107 + 497 399 497 399 486.5 331 c 0,108,109 + 476 263 476 263 557 266 c 0,110,111 + 564 266 564 266 577 283.5 c 0,112,113 + 586.241 295.94 586.241 295.94 586.386 311.664 c 0,114,115 + 586.446 318.06 586.446 318.06 585 325 c 0,116,117 + 577 361 577 361 524 372 c 0,118,119 + 556 398 556 398 584 387 c 0,120,121 + 612 376 612 376 627 349 c 0,122,123 + 655 295 655 295 637 239.5 c 0,124,125 + 619 184.001 619 184.001 590 168 c 0,126,-1 + 500 116 l 0,127,128 + 462 93.9995 462 93.9995 462 13 c 0,129,130 + 462 -101 462 -101 542 -147.5 c 0,131,132 + 614.087 -189.401 614.087 -189.401 704.039 -189.485 c 0,133,134 + 713.912 -189.494 713.912 -189.494 724 -189 c 0,135,136 + 678.195 -202.572 678.195 -202.572 634.149 -202.553 c 0,137,138 + 600.305 -202.538 600.305 -202.538 567.5 -194.5 c 0,139,140 + 492 -176.001 492 -176.001 462 -143 c 0,141,142 + 361 -30.0001 361 -30.0001 359.5 119.5 c 0,143,144 + 358 269 358 269 283 374 c 0,145,146 + 269 392 269 392 236 406.5 c 0,147,148 + 220.144 410.016 l 0,149,150 + 200.816 409.305 200.816 409.305 190 376 c 0,151,152 + 169 298 169 298 244 282 c 0,153,154 + 211.123 281.752 l 0,155,156 + 195.064 283.447 195.064 283.447 177.5 288.5 c 0,157,158 + 141 299 141 299 117 359 c 0,159,160 + 102.015 394.589 102.015 394.589 101.942 433.139 c 0,161,162 + 101.858 476.911 101.858 476.911 121 524.5 c 0,163,164 + 157 614 157 614 157 692 c 0,165,166 + 157 815 157 815 116.5 925 c 0,167,168 + 75.9978 1035.01 75.9978 1035.01 52 1150 c 0,169,170 + 43.9902 1184.05 43.9902 1184.05 30 1258.5 c 0,171,172 + 16 1333.01 16 1333.01 19 1416 c 0,173,174 + 20.0001 1473.01 20.0001 1473.01 49.5 1551.5 c 0,175,176 + 79.0021 1630 79.0021 1630 124 1636 c 0,177,178 + 104.996 1609 104.996 1609 90 1569 c 0,179,180 + 75 1528.99 75 1528.99 80 1500 c 0,181,182 + 90.1461 1428.98 90.1461 1428.98 169.197 1428.57 c 0,183,184 + 175.854 1428.53 175.854 1428.53 183 1429 c 0,185,186 + 230 1432 230 1432 237.5 1511 c 0,187,188 + 241.099 1585.22 l 0,189,190 + 240.776 1614.29 240.776 1614.29 237 1636 c 0,191,192 + 222 1708 222 1708 140 1720 c 0,193,194 + 248 1733.01 248 1733.01 277.5 1636 c 0,195,196 + 307 1538.99 307 1538.99 298 1477 c 0,197,198 + 292.001 1435.01 292.001 1435.01 269.5 1353 c 0,199,200 + 246.994 1270.97 246.994 1270.97 238 1222 c 0,201,202 + 235.011 1207.06 235.011 1207.06 235.093 1163.63 c 0,203,204 + 235.121 1148.94 235.121 1148.94 235.5 1131 c 0,205,206 + 237 1060.01 237 1060.01 246 988.5 c 0,207,208 + 255 917 255 917 274.5 871.5 c 0,209,210 + 294 826 294 826 327 856 c 0,211,212 + 363 890 363 890 350 940 c 0,213,214 + 337 990 337 990 305 1015 c 1,0,1 +EndSplineSet +KernsSLIF: 246 -172 0 0 111 -143 0 0 45 -182 0 0 46 -182 0 0 44 -208 0 0 105 -104 0 0 97 -257 0 0 +EndChar +StartChar: w +Encoding: 119 119 26 +Width: 1586 +Flags: HW +Fore +1014 -90 m 0,0,1 + 965 -75 965 -75 934.5 -33.5 c 0,2,3 + 904 8 904 8 892 43 c 0,4,5 + 868.999 107.005 868.999 107.005 855 192.5 c 0,6,7 + 841 278 841 278 813 329 c 0,8,9 + 773 399 773 399 745.5 404 c 0,10,11 + 718 409 718 409 682 359 c 0,12,13 + 655 320 655 320 656.5 224.5 c 0,14,15 + 658 129.001 658 129.001 687 96 c 0,16,17 + 710 69 710 69 759 61 c 0,18,19 + 715.03 35.2941 715.03 35.2941 668.313 35.2145 c 0,20,21 + 645.97 35.1765 645.97 35.1765 623 41 c 0,22,23 + 552 59 552 59 522 89 c 0,24,25 + 493 116 493 116 472.5 149 c 0,26,-1 + 431 218 l 0,27,28 + 408 257 408 257 396.5 274 c 0,29,30 + 385 291 385 291 337 307 c 0,31,32 + 328 310 328 310 309.5 303 c 0,33,34 + 291 296 291 296 288 285 c 0,35,36 + 282.97 270.441 282.97 270.441 282.916 258.825 c 0,37,38 + 282.819 238.131 282.819 238.131 298.512 226.777 c 0,39,40 + 307.287 220.428 307.287 220.428 321 217 c 0,41,42 + 306.593 210.22 306.593 210.22 293.802 210.084 c 0,43,44 + 284.612 209.986 284.612 209.986 276.255 213.318 c 0,45,46 + 268.795 216.292 268.795 216.292 262 222 c 0,47,48 + 237 243 237 243 234 267 c 0,49,50 + 227.71 307.884 227.71 307.884 227.739 342.862 c 0,51,52 + 227.766 374.615 227.766 374.615 233 401.5 c 0,53,54 + 243.998 457.993 243.998 457.993 262 521 c 0,55,56 + 301 653 301 653 299 782.5 c 0,57,58 + 297.001 911.997 297.001 911.997 241 1033 c 0,59,60 + 210.985 1095.03 210.985 1095.03 177 1152 c 0,61,62 + 143 1209 143 1209 140 1284 c 0,63,64 + 141.271 1338.67 l 0,65,66 + 151.107 1435.81 151.107 1435.81 219 1443 c 0,67,68 + 276 1447.01 276 1447.01 276 1395 c 0,69,70 + 264.083 1406.32 264.083 1406.32 248.788 1406.46 c 0,71,72 + 238.421 1406.55 238.421 1406.55 226.5 1401.5 c 0,73,74 + 207.837 1393.6 207.837 1393.6 207.785 1366.27 c 0,75,76 + 207.755 1350.41 207.755 1350.41 214 1328 c 0,77,78 + 222.184 1296.75 222.184 1296.75 252.786 1296.23 c 0,79,80 + 276.5 1299.5 l 0,81,82 + 328 1313 328 1313 328 1354 c 0,83,84 + 327 1443 327 1443 273.5 1477 c 0,85,86 + 220.007 1511 220.007 1511 157 1511 c 0,87,88 + 72.0033 1511 72.0033 1511 43.5 1467 c 0,89,90 + 15 1423.01 15 1423.01 3 1401 c 0,91,92 + 17 1534.99 17 1534.99 162 1545 c 0,93,94 + 237 1549.99 237 1549.99 298 1504.5 c 0,95,96 + 358.995 1459.01 358.995 1459.01 383 1414 c 0,97,98 + 429.636 1322.85 429.636 1322.85 429.838 1258.41 c 0,99,100 + 429.922 1231.65 429.922 1231.65 422 1209.5 c 0,101,102 + 395 1134.01 395 1134.01 386 993 c 0,103,104 + 383 950 383 950 382.5 891 c 0,105,106 + 382 832 382 832 411 799 c 0,107,108 + 431.326 774.91 431.326 774.91 446.268 774.622 c 0,109,110 + 451.174 774.528 451.174 774.528 455.5 777 c 0,111,112 + 473 787 473 787 472 808 c 0,113,114 + 470.999 827.004 470.999 827.004 465.5 843.5 c 0,115,116 + 460 860 460 860 415 863 c 0,117,118 + 443.027 877.205 443.027 877.205 466.042 877.26 c 0,119,120 + 502.973 877.348 502.973 877.348 527 841 c 0,121,122 + 551 801 551 801 546.5 771 c 0,123,124 + 542 741 542 741 537 714 c 0,125,126 + 521 630 521 630 520.5 586 c 0,127,128 + 523.692 560.121 l 0,129,130 + 531 533.828 531 533.828 555 516 c 0,131,132 + 578 498 578 498 624.5 589.5 c 0,133,134 + 671 681 671 681 692 727 c 0,135,136 + 714 775 714 775 737 806.5 c 0,137,138 + 759.999 837.999 759.999 837.999 831 871 c 0,139,140 + 789 810 789 810 777.5 774 c 0,141,142 + 766 738 766 738 776 672 c 0,143,144 + 781 632 781 632 795.5 598.5 c 0,145,146 + 810 565 810 565 845 561 c 0,147,148 + 915 552 915 552 953 646 c 0,149,150 + 991 740 991 740 997 791 c 0,151,152 + 998.001 801.003 998.001 801.003 1014.5 884.5 c 0,153,154 + 1019.54 910.001 1019.54 910.001 1019.59 927.713 c 0,155,156 + 1019.69 963 1019.69 963 999.982 967.379 c 0,157,158 + 997.19 968 997.19 968 994 968 c 0,159,160 + 970 968 970 968 962.5 943.5 c 0,161,162 + 955 919 955 919 973 903 c 0,163,164 + 934 909 934 909 934 949.5 c 0,165,166 + 934 990 934 990 943 1005 c 0,167,168 + 972.994 1052.99 972.994 1052.99 1017.5 1088.5 c 0,169,170 + 1062 1124 1062 1124 1089 1157 c 0,171,172 + 1131.02 1208.03 1131.02 1208.03 1142 1228.5 c 0,173,174 + 1153.01 1249.04 1153.01 1249.04 1171 1303 c 0,175,176 + 1184.99 1346.01 1184.99 1346.01 1219 1438 c 0,177,178 + 1253.01 1530.01 1253.01 1530.01 1295 1572 c 0,179,180 + 1354.39 1631.39 1354.39 1631.39 1409.01 1631.59 c 0,181,182 + 1420.61 1631.63 1420.61 1631.63 1432 1629 c 0,183,-1 + 1361.5 1588 l 0,184,185 + 1328 1568.99 1328 1568.99 1307 1515 c 0,186,187 + 1293.8 1483.93 1293.8 1483.93 1293.87 1441.71 c 0,188,189 + 1293.88 1429.57 1293.88 1429.57 1295 1416.5 c 0,190,191 + 1299.99 1358 1299.99 1358 1350 1352 c 0,192,193 + 1408.01 1346 1408.01 1346 1458 1382 c 0,194,195 + 1508 1418.01 1508 1418.01 1532 1472 c 0,196,197 + 1546.97 1507.94 1546.97 1507.94 1565.5 1542 c 0,198,199 + 1580.79 1570.11 1580.79 1570.11 1580.71 1634.4 c 0,200,201 + 1580.7 1647.9 1580.7 1647.9 1580 1663 c 0,202,203 + 1574 1753.99 1574 1753.99 1443 1824 c 0,204,205 + 1597 1790 1597 1790 1619 1646 c 0,206,207 + 1622.07 1590.37 l 0,208,209 + 1621.42 1545.07 1621.42 1545.07 1611 1496 c 0,210,211 + 1594 1416 1594 1416 1542 1356 c 0,212,213 + 1468.98 1272.99 1468.98 1272.99 1374 1201 c 0,214,215 + 1337.98 1173.98 1337.98 1173.98 1280.5 1098 c 0,216,217 + 1246.65 1053.25 1246.65 1053.25 1246.59 1018.22 c 0,218,219 + 1246.55 993.741 1246.55 993.741 1263 974 c 0,220,221 + 1269.62 966.056 1269.62 966.056 1283.03 966 c 0,222,223 + 1289.88 965.972 1289.88 965.972 1298.5 968 c 0,224,225 + 1324 974 1324 974 1330 996 c 0,226,227 + 1334.96 1014.94 1334.96 1014.94 1334.94 1027.17 c 0,228,229 + 1334.91 1042.06 1334.91 1042.06 1327.5 1047 c 0,230,-1 + 1295 1069 l 0,231,232 + 1323.65 1072.59 l 0,233,234 + 1361.04 1071.97 1361.04 1071.97 1370 1036.5 c 0,235,236 + 1376.58 1010.46 1376.58 1010.46 1376.55 986.389 c 0,237,238 + 1376.52 966.529 1376.52 966.529 1372 948 c 0,239,240 + 1355.99 885.999 1355.99 885.999 1300 860 c 0,241,242 + 1243.99 833.995 1243.99 833.995 1199 797 c 0,243,244 + 1148.02 754.015 1148.02 754.015 1106.5 707.5 c 0,245,246 + 1065.01 661.014 1065.01 661.014 1055 595 c 0,247,248 + 1049.56 560.034 1049.56 560.034 1049.63 531.26 c 0,249,250 + 1049.74 485.962 1049.74 485.962 1063.5 456 c 0,251,-1 + 1119 332 l 0,252,253 + 1141.99 276 1141.99 276 1149 213 c 0,254,255 + 1148.59 180.883 l 0,256,257 + 1142.04 129.433 1142.04 129.433 1099 66 c 0,258,259 + 1099 93 1099 93 1111 155.5 c 0,260,261 + 1112.74 183.814 l 0,262,263 + 1109.16 226.59 1109.16 226.59 1065 254 c 0,264,265 + 1024.01 278 1024.01 278 991.5 228 c 0,266,267 + 959 178.001 959 178.001 957 79 c 0,268,269 + 955 38 955 38 979 -6 c 0,270,271 + 1003 -50 1003 -50 1042 -68 c 0,272,273 + 1079.01 -86 1079.01 -86 1162 -88 c 0,274,275 + 1136.9 -100.085 1136.9 -100.085 1097.11 -100.071 c 0,276,277 + 1094.1 -100.07 1094.1 -100.07 1091 -100 c 0,278,279 + 1047 -98.9998 1047 -98.9998 1014 -90 c 0,0,1 +EndSplineSet +KernsSLIF: 246 -42 0 0 322 -300 0 0 104 -104 0 0 45 -117 0 0 46 -195 0 0 44 -208 0 0 115 -91 0 0 105 13 0 0 243 -156 0 0 111 -91 0 0 228 -228 0 0 261 -313 0 0 97 -342 0 0 +EndChar +StartChar: x +Encoding: 120 120 28 +Width: 1239 +Flags: HW +Fore +659 1394 m 0,0,1 + 619.965 1385.64 619.965 1385.64 619.801 1356.11 c 0,2,3 + 619.788 1353.86 619.788 1353.86 620 1351.5 c 0,4,5 + 623 1318.99 623 1318.99 623 1318 c 0,6,7 + 587.525 1334.5 587.525 1334.5 587.443 1378.22 c 0,8,9 + 587.425 1387.5 587.425 1387.5 589 1398 c 0,10,11 + 594 1451.01 594 1451.01 659 1468 c 0,12,13 + 695.043 1477.01 695.043 1477.01 742 1494.5 c 0,14,15 + 789.016 1512.01 789.016 1512.01 820 1533 c 0,16,17 + 832 1542 832 1542 845.5 1570.5 c 0,18,19 + 858.997 1598.99 858.997 1598.99 863 1616 c 0,20,21 + 879 1701.99 879 1701.99 812 1712 c 0,22,23 + 845 1721 845 1721 866.5 1701.5 c 0,24,25 + 888 1682 888 1682 888 1656 c 0,26,27 + 888 1633.99 888 1633.99 882 1558.5 c 0,28,29 + 881.281 1511.03 l 0,30,31 + 883.815 1483 883.815 1483 896 1483 c 0,32,33 + 912.786 1485.53 l 0,34,35 + 929.979 1492.51 929.979 1492.51 941 1518 c 0,36,37 + 960.999 1566 960.999 1566 962 1610 c 0,38,39 + 963.001 1654 963.001 1654 982 1696 c 0,40,41 + 999.999 1735 999.999 1735 1035.5 1760 c 0,42,43 + 1065.03 1780.8 1065.03 1780.8 1090.77 1780.83 c 0,44,45 + 1095.96 1780.84 1095.96 1780.84 1101 1780 c 0,46,47 + 1029 1757.99 1029 1757.99 1029 1701 c 0,48,49 + 1029 1659 1029 1659 1074 1659 c 0,50,51 + 1094 1659 1094 1659 1101 1678 c 0,52,53 + 1105.12 1689.17 1105.12 1689.17 1105.08 1698.97 c 0,54,55 + 1105.06 1705.82 1105.06 1705.82 1103 1712 c 0,56,57 + 1136 1707.99 1136 1707.99 1136 1667 c 0,58,59 + 1136 1625.99 1136 1625.99 1126 1609 c 0,60,61 + 1111 1583.01 1111 1583.01 1078 1549 c 0,62,-1 + 1024 1495 l 0,63,-1 + 922 1402 l 0,64,65 + 840.994 1328.99 840.994 1328.99 816 1271 c 0,66,67 + 801.993 1240.98 801.993 1240.98 770 1138 c 0,68,69 + 756.589 1094.83 756.589 1094.83 756.527 1063.96 c 0,70,71 + 756.441 1021.17 756.441 1021.17 782 1002 c 0,72,73 + 804 985 804 985 828.5 999 c 0,74,75 + 852.987 1012.99 852.987 1012.99 864 1027 c 0,76,77 + 875.229 1041.97 875.229 1041.97 875.513 1054.86 c 0,78,79 + 872.132 1069.17 l 0,80,81 + 868.752 1075.66 868.752 1075.66 862 1081.5 c 0,82,83 + 835.994 1104.01 835.994 1104.01 818 1106 c 0,84,85 + 855 1118 855 1118 885 1103 c 0,86,87 + 914.998 1088 914.998 1088 921 1071 c 0,88,89 + 942 993 942 993 894.5 964.5 c 0,90,91 + 847 936 847 936 802 891 c 0,92,93 + 754.999 845.999 754.999 845.999 753 810.5 c 0,94,95 + 751 775 751 775 757 739 c 0,96,97 + 772 636 772 636 907 471 c 0,98,-1 + 1101 234 l 0,99,100 + 1123.99 205.001 1123.99 205.001 1140 136 c 0,101,102 + 1156.01 67 1156.01 67 1119 34 c 0,103,104 + 1150.99 92.9999 1150.99 92.9999 1098 169 c 0,105,106 + 1045.01 244.998 1045.01 244.998 995 254 c 0,107,108 + 968.167 255.138 l 0,109,110 + 937.522 251.594 937.522 251.594 928.5 222 c 0,111,112 + 922.338 201.789 922.338 201.789 922.373 184.251 c 0,113,114 + 922.408 166.211 922.408 166.211 929 151 c 0,115,116 + 965 65.0001 965 65.0001 1025.5 36.5 c 0,117,118 + 1085.99 8 1085.99 8 1144 7 c 0,119,120 + 1202.59 9.65475 l 0,121,122 + 1224.73 12.2988 1224.73 12.2988 1243.5 17.5 c 0,123,124 + 1271 25.1205 1271 25.1205 1280.28 25.0566 c 0,125,126 + 1285 25.0241 1285 25.0241 1285 23 c 0,127,128 + 1192.24 -6.79408 1192.24 -6.79408 1118.61 -6.88269 c 0,129,130 + 1061.26 -6.95171 1061.26 -6.95171 1015.5 11 c 0,131,132 + 911 52 911 52 870 160 c 0,133,134 + 845.997 221.008 845.997 221.008 811.5 322.5 c 0,135,136 + 777 424 777 424 750 427 c 0,137,138 + 696 431 696 431 696 382 c 0,139,140 + 696 336 696 336 739 342 c 0,141,142 + 717 315 717 315 691.5 326 c 0,143,144 + 666 337 666 337 657 358 c 0,145,146 + 635.001 402.998 635.001 402.998 631 455.5 c 0,147,148 + 627 508 627 508 627 568 c 0,149,150 + 627 589 627 589 617 628 c 0,151,152 + 607 667 607 667 580 671 c 0,153,154 + 514 678 514 678 468.5 563 c 0,155,156 + 436.8 482.877 436.8 482.877 436.894 455.18 c 0,157,158 + 436.935 443.123 436.935 443.123 443 441 c 0,159,160 + 455.538 439.465 l 0,161,162 + 466.861 441.222 466.861 441.222 479 454 c 0,163,164 + 500 475 500 475 469 506 c 0,165,166 + 487 506 487 506 501 486.5 c 0,167,168 + 515 467 515 467 515 449 c 0,169,170 + 515 414 515 414 487.5 372.5 c 0,171,172 + 460.001 331 460.001 331 425 322 c 0,173,174 + 379 310 379 310 340.5 285 c 0,175,176 + 302 260 302 260 291 212 c 0,177,178 + 278.998 157.992 278.998 157.992 266 109 c 0,179,180 + 253 59.9999 253 59.9999 230 30 c 0,181,182 + 219.999 16.9999 219.999 16.9999 184 7 c 0,183,184 + 163.709 1.36363 163.709 1.36363 148.819 1.44562 c 0,185,186 + 137.291 1.50909 137.291 1.50909 129 5 c 0,187,188 + 177.001 11.0001 177.001 11.0001 203 57 c 0,189,190 + 219 85.9999 219 85.9999 219.5 143.5 c 0,191,192 + 216.668 168.843 l 0,193,194 + 207.895 201 207.895 201 172 201 c 0,195,196 + 119 201 119 201 89.5 137 c 0,197,198 + 59.9999 72.9999 59.9999 72.9999 60 28 c 0,199,200 + 60 -48.0001 60 -48.0001 140 -88 c 0,201,202 + 81.0005 -88 81.0005 -88 54 -50 c 0,203,204 + 27 -12 27 -12 24 28 c 0,205,206 + 16 129 16 129 78 217 c 0,207,208 + 109 262 109 262 210 369 c 0,209,210 + 311 476 311 476 309 521 c 0,211,212 + 309 548 309 548 273 548 c 0,213,214 + 255 548 255 548 254.5 529 c 0,215,216 + 254.999 510 254.999 510 262 501 c 0,217,218 + 241 495 241 495 221.5 518.5 c 0,219,220 + 212.134 529.788 212.134 529.788 212.111 544.881 c 0,221,222 + 212.087 561.212 212.087 561.212 223 582 c 0,223,224 + 239.999 615 239.999 615 289 644 c 0,225,226 + 337.997 672.998 337.997 672.998 367 699 c 0,227,228 + 395 726 395 726 429.5 778 c 0,229,230 + 464 830 464 830 464 873 c 0,231,232 + 464 901 464 901 440.5 913 c 0,233,234 + 417 925 417 925 394 925 c 0,235,236 + 327 922 327 922 336 877.5 c 0,237,238 + 345 833 345 833 371 833 c 0,239,240 + 338.017 831.603 l 0,241,242 + 312.765 833.673 312.765 833.673 291.5 846 c 0,243,244 + 257 866 257 866 257 914 c 0,245,246 + 257 952 257 952 278 992 c 0,247,248 + 299.005 1032.01 299.005 1032.01 307 1066 c 0,249,250 + 313.999 1095.99 313.999 1095.99 315 1138.5 c 0,251,252 + 312.455 1183.29 l 0,253,254 + 310.196 1197.83 310.196 1197.83 306 1210 c 0,255,256 + 284 1267 284 1267 239 1313.5 c 0,257,258 + 194 1360 194 1360 194 1432 c 0,259,260 + 194 1451.01 194 1451.01 215 1489 c 0,261,262 + 236 1526.99 236 1526.99 270 1528 c 0,263,264 + 236 1496.01 236 1496.01 236 1452 c 0,265,266 + 236 1440 236 1440 247 1420.5 c 0,267,268 + 257.999 1401 257.999 1401 277 1401 c 0,269,270 + 331 1401 331 1401 331 1456 c 0,271,272 + 331 1616.55 331 1616.55 200.138 1616.46 c 0,273,274 + 193.252 1616.45 193.252 1616.45 186 1616 c 0,275,276 + 285 1646 285 1646 330 1596.5 c 0,277,278 + 375 1547 375 1547 394 1472 c 0,279,280 + 409 1407.01 409 1407.01 417 1338 c 0,281,282 + 425 1269 425 1269 443 1206 c 0,283,284 + 449.999 1179.01 449.999 1179.01 481.5 1130 c 0,285,286 + 506.465 1091.16 506.465 1091.16 534.26 1090.65 c 0,287,288 + 549 1093 l 0,289,290 + 590.995 1106.99 590.995 1106.99 627 1158 c 0,291,292 + 662.996 1208.99 662.996 1208.99 678 1250 c 0,293,294 + 683.003 1263.01 683.003 1263.01 694 1333.5 c 0,295,296 + 695.76 1365.97 l 0,297,298 + 693.084 1394.55 693.084 1394.55 670.648 1395.23 c 0,299,300 + 659 1394 l 0,0,1 +EndSplineSet +KernsSLIF: 45 -208 0 0 +EndChar +StartChar: y +Encoding: 121 121 27 +Width: 1145 +Flags: HMW +VStem: 362 278<103 873> +Fore +516 -249 m 1,0,1 + 569 -202.999 569 -202.999 604.5 -50.5 c 0,2,3 + 640 102 640 102 589 147 c 0,4,5 + 567.001 165.999 567.001 165.999 504.5 170 c 0,6,7 + 477.767 168.457 l 0,8,9 + 455.328 163.118 455.328 163.118 455.365 142.228 c 0,10,11 + 455.38 133.861 455.38 133.861 459 123 c 0,12,13 + 468 92.0002 468 92.0002 495.5 86.5 c 0,14,15 + 519.369 85.4306 l 0,16,17 + 534.421 87.1496 534.421 87.1496 549 95 c 0,18,19 + 549 54.9999 549 54.9999 463 48.5 c 0,20,21 + 377 42 377 42 362 103 c 0,22,23 + 355.586 126.249 355.586 126.249 355.68 149.9 c 0,24,25 + 355.821 185.251 355.821 185.251 370.5 221.5 c 0,26,27 + 395.006 282.015 395.006 282.015 415 340 c 0,28,29 + 424 366 424 366 455 504 c 0,30,31 + 486 642 486 642 438 650 c 0,32,33 + 419 653 419 653 398 640.5 c 0,34,35 + 377 628 377 628 378 601 c 0,36,37 + 378 580.999 378 580.999 418 573 c 0,38,39 + 386 561 386 561 346 568.5 c 0,40,41 + 306 576 306 576 292 607 c 0,42,43 + 286.399 619.52 286.399 619.52 286.497 633.18 c 0,44,45 + 286.697 660.981 286.697 660.981 310.5 693.5 c 0,46,47 + 345.999 741.998 345.999 741.998 355 780 c 0,48,49 + 369 840 369 840 346.5 900.5 c 0,50,51 + 324 961 324 961 288 1000 c 0,52,53 + 272 1015 272 1015 252 995.5 c 0,54,55 + 232.001 976 232.001 976 246 956 c 0,56,57 + 256.001 940.999 256.001 940.999 263 936.5 c 0,58,59 + 270 932 270 932 306 932 c 0,60,61 + 300 916.001 300 916.001 256.5 913.5 c 0,62,63 + 213 911 213 911 189 929 c 0,64,65 + 151.001 958 151.001 958 163.5 1022 c 0,66,67 + 176 1086.01 176 1086.01 176 1126 c 0,68,69 + 176 1218 176 1218 110.5 1270.5 c 0,70,71 + 44.9999 1323 44.9999 1323 33 1407 c 0,72,73 + 18 1494 18 1494 57.5 1593 c 0,74,75 + 96.9998 1692 96.9998 1692 216 1740 c 0,76,77 + 135 1689 135 1689 92 1606.5 c 0,78,79 + 69.4154 1563.17 69.4154 1563.17 69.4513 1518.87 c 0,80,81 + 69.4837 1478.83 69.4837 1478.83 88 1438 c 0,82,83 + 112.858 1381.83 112.858 1381.83 177.572 1381.62 c 0,84,85 + 183.138 1381.6 183.138 1381.6 189 1382 c 0,86,87 + 262.991 1386.99 262.991 1386.99 299 1428 c 0,88,89 + 310.937 1441.84 310.937 1441.84 311.247 1455.12 c 0,90,91 + 308.015 1469.67 l 0,92,93 + 304.702 1476.67 304.702 1476.67 298 1483.5 c 0,94,95 + 280.194 1501.65 280.194 1501.65 252.532 1501.74 c 0,96,97 + 239.809 1501.78 239.809 1501.78 225 1498 c 0,98,99 + 263.544 1524.4 263.544 1524.4 296.233 1524.59 c 0,100,101 + 312.955 1524.69 312.955 1524.69 328.145 1517.93 c 0,102,103 + 339.5 1512.88 339.5 1512.88 350 1504 c 0,104,105 + 374.854 1481.76 374.854 1481.76 375.11 1449.04 c 0,106,107 + 371.339 1421.03 l 0,108,109 + 370.117 1416.35 370.117 1416.35 368.5 1411.5 c 0,110,111 + 349.989 1355.97 349.989 1355.97 349.951 1317.11 c 0,112,113 + 349.949 1315.03 349.949 1315.03 350 1313 c 0,114,115 + 351.001 1224.99 351.001 1224.99 385 1074.5 c 0,116,117 + 411.928 955.304 411.928 955.304 474.61 954.347 c 0,118,119 + 499.5 958.184 l 0,120,121 + 504.651 959.766 504.651 959.766 510 962 c 0,122,123 + 546 977 546 977 584 1038 c 0,124,125 + 622.001 1099.01 622.001 1099.01 630 1128 c 0,126,127 + 631.185 1147.49 l 0,128,129 + 629.345 1163.19 629.345 1163.19 620 1184.5 c 0,130,131 + 609.445 1208.57 609.445 1208.57 592.368 1208.51 c 0,132,133 + 583.553 1208.47 583.553 1208.47 573 1202 c 0,134,135 + 556.8 1191.8 556.8 1191.8 556.8 1181.24 c 0,136,137 + 556.8 1174.2 556.8 1174.2 564 1167 c 0,138,139 + 582 1149 582 1149 603 1149 c 0,140,141 + 571 1128 571 1128 542.5 1143 c 0,142,143 + 514 1158 514 1158 510 1180 c 0,144,145 + 507.91 1207.16 l 0,146,147 + 511.963 1262.94 511.963 1262.94 588.5 1301 c 0,148,149 + 682.991 1347.99 682.991 1347.99 732 1405 c 0,150,151 + 768.009 1445.01 768.009 1445.01 792 1500 c 0,152,153 + 816 1555.01 816 1555.01 846 1599 c 0,154,-1 + 874.5 1643 l 0,155,156 + 903 1686.99 903 1686.99 957 1673 c 0,157,158 + 907.003 1659.01 907.003 1659.01 891.5 1616.5 c 0,159,160 + 887.421 1605.32 887.421 1605.32 887.324 1595.41 c 0,161,162 + 887.226 1585.39 887.226 1585.39 891.206 1576.68 c 0,163,164 + 898.238 1561.29 898.238 1561.29 918 1550 c 0,165,166 + 937 1538 937 1538 967.5 1551.5 c 0,167,168 + 998.009 1565 998.009 1565 1006 1574 c 0,169,170 + 1046.5 1622 1046.5 1622 1046.75 1658 c 0,171,172 + 1046.85 1672.4 1046.85 1672.4 1040.51 1684.88 c 0,173,174 + 1031 1703.6 1031 1703.6 1007 1718 c 0,175,176 + 927.02 1765.99 927.02 1765.99 906 1773 c 0,177,178 + 983.986 1759.01 983.986 1759.01 1020.5 1727 c 0,179,180 + 1057 1695 1057 1695 1060 1689 c 0,181,182 + 1076.31 1652.31 1076.31 1652.31 1076.45 1623.69 c 0,183,184 + 1076.52 1610.2 1076.52 1610.2 1073 1598.5 c 0,185,186 + 1062.01 1562.02 1062.01 1562.02 1024 1505 c 0,187,188 + 987.005 1448.01 987.005 1448.01 903.5 1384 c 0,189,190 + 819.999 1319.99 819.999 1319.99 811 1257 c 0,191,192 + 809.173 1213.58 l 0,193,194 + 810.601 1181.82 810.601 1181.82 820.5 1146.5 c 0,195,196 + 837 1089 837 1089 839 1036 c 0,197,198 + 839 1010 839 1010 819 933 c 0,199,200 + 799 856 799 856 709 850 c 0,201,202 + 745 861 745 861 768 927 c 0,203,204 + 791 993 791 993 716 993 c 0,205,206 + 672 993 672 993 656 947 c 0,207,208 + 640 901.001 640 901.001 640 873 c 0,209,210 + 640 803 640 803 697 793 c 0,211,212 + 726.152 787.237 726.152 787.237 749.1 787.335 c 0,213,214 + 793.848 787.525 793.848 787.525 815 810 c 0,215,216 + 833.353 829.5 833.353 829.5 833.285 849 c 0,217,218 + 833.235 863.5 833.235 863.5 823 878 c 0,219,220 + 848 875 848 875 858 850 c 0,221,222 + 865.632 830.921 865.632 830.921 865.692 818.831 c 0,223,224 + 865.711 815.079 865.711 815.079 865 812 c 0,225,226 + 835 710 835 710 753.5 661.5 c 0,227,228 + 672 613 672 613 642 505 c 0,229,230 + 631 467 631 467 622.5 420.5 c 0,231,232 + 614 374 614 374 614 333 c 0,233,234 + 614 291 614 291 631.5 245 c 0,235,236 + 649.004 198.989 649.004 198.989 665 162 c 0,237,238 + 678.513 129.86 678.513 129.86 678.555 90.5183 c 0,239,240 + 678.626 22.1387 678.626 22.1387 638 -68 c 0,241,242 + 573.999 -210.001 573.999 -210.001 516 -249 c 1,0,1 +EndSplineSet +KernsSLIF: 111 -130 0 0 322 -260 0 0 115 -208 0 0 45 -169 0 0 46 -195 0 0 44 -208 0 0 97 -363 0 0 +EndChar +StartChar: z +Encoding: 122 122 31 +Width: 1565 +Flags: HMW +HStem: 147 132.5<256.5 1230.5> 1333 115<337 1066> +Fore +192 -73 m 0,0,1 + 107 -73 107 -73 98 23 c 0,2,3 + 96.9999 29 96.9999 29 101.5 75 c 0,4,5 + 106 121.001 106 121.001 142 130 c 0,6,7 + 127 112 127 112 121.5 80.5 c 0,8,9 + 121.118 58.5858 l 0,10,11 + 123.865 43.8878 123.865 43.8878 136 36 c 0,12,13 + 157.196 21.0841 157.196 21.0841 178.239 21.0364 c 0,14,15 + 210.804 20.9627 210.804 20.9627 243 56.5 c 0,16,17 + 288.962 107.232 288.962 107.232 289.049 160.597 c 0,18,19 + 289.062 168.768 289.062 168.768 288 177 c 0,20,21 + 281 231.999 281 231.999 256.5 279.5 c 0,22,23 + 233.051 324.964 233.051 324.964 232.961 390.117 c 0,24,25 + 232.957 393.038 232.957 393.038 233 396 c 0,26,27 + 233 426.002 233 426.002 253.5 467 c 0,28,29 + 274 508 274 508 310 517 c 0,30,31 + 319 520 319 520 341.5 521 c 0,32,33 + 358.339 518.81 l 0,34,35 + 366.273 515.636 366.273 515.636 369 508 c 0,36,37 + 349 520 349 520 313.5 502 c 0,38,39 + 278.001 484.001 278.001 484.001 277 463 c 0,40,41 + 274 439 274 439 280 410 c 0,42,43 + 286 381 286 381 319 381 c 0,44,45 + 358 381 358 381 408 486 c 0,46,47 + 458 591 458 591 467 627 c 0,48,49 + 491 716 491 716 498.5 795.5 c 0,50,51 + 506 875 506 875 519 955 c 0,52,53 + 522 977.999 522 977.999 536 1011.5 c 0,54,55 + 550.003 1045 550.003 1045 568 1060 c 0,56,57 + 614.007 1102.01 614.007 1102.01 662.5 1108.5 c 0,58,59 + 695.795 1109.75 l 0,60,61 + 715.86 1107.71 715.86 1107.71 723 1097 c 0,62,63 + 702.171 1098.72 l 0,64,65 + 673.014 1096.04 673.014 1096.04 638 1066.5 c 0,66,67 + 590 1026 590 1026 625 993 c 0,68,69 + 635.364 982.636 635.364 982.636 649.389 982.592 c 0,70,71 + 665.136 982.541 665.136 982.541 685.5 995.5 c 0,72,73 + 723.984 1019.98 723.984 1019.98 737 1037 c 0,74,-1 + 789 1107.5 l 0,75,76 + 816.971 1146.95 816.971 1146.95 837 1182 c 0,77,78 + 858 1218 858 1218 870.5 1258.5 c 0,79,80 + 873.186 1278.82 l 0,81,82 + 871.615 1307.02 871.615 1307.02 839 1330 c 0,83,84 + 801.009 1356.99 801.009 1356.99 740.5 1364 c 0,85,86 + 680.044 1371 680.044 1371 635 1371 c 0,87,88 + 532.993 1371 532.993 1371 488 1338.5 c 0,89,-1 + 383 1259 l 0,90,-1 + 358.5 1239 l 0,91,92 + 340.993 1225 340.993 1225 330 1225 c 0,93,94 + 299.544 1226.95 l 0,95,96 + 286.046 1229.27 286.046 1229.27 269.5 1234 c 0,97,98 + 231.001 1244.99 231.001 1244.99 222 1284 c 0,99,100 + 229.997 1268 229.997 1268 286.5 1259 c 0,101,102 + 306.838 1259.13 l 0,103,104 + 337.526 1265.89 337.526 1265.89 337.576 1317.74 c 0,105,106 + 337.583 1324.94 337.583 1324.94 337 1333 c 0,107,108 + 332 1395.01 332 1395.01 253.5 1400 c 0,109,110 + 178.634 1401.45 l 0,111,112 + 156.61 1400.4 156.61 1400.4 143 1397 c 0,113,114 + 33.0001 1368.01 33.0001 1368.01 34.5 1305.5 c 0,115,116 + 35 1212 l 0,117,118 + 14.6647 1264.87 14.6647 1264.87 14.6483 1304.98 c 0,119,120 + 14.6284 1353.63 14.6284 1353.63 44.5 1383.5 c 0,121,122 + 99.0072 1438 99.0072 1438 147 1453 c 0,123,124 + 205.397 1470.43 205.397 1470.43 268.328 1470.39 c 0,125,126 + 277.615 1470.39 277.615 1470.39 287 1470 c 0,127,128 + 360.084 1467 360.084 1467 429 1460 c 0,129,130 + 489.53 1456.4 l 0,131,132 + 508.127 1456.49 508.127 1456.49 527 1458 c 0,133,134 + 563.734 1460.94 563.734 1460.94 564.304 1486.01 c 0,135,136 + 560.419 1505.87 l 0,137,138 + 560 1507 l 0,139,140 + 549.725 1533.71 549.725 1533.71 523.728 1534.15 c 0,141,142 + 499.826 1530.11 l 0,143,144 + 498.185 1529.59 498.185 1529.59 496.5 1529 c 0,145,146 + 448.004 1512.01 448.004 1512.01 444 1498 c 0,147,148 + 443.297 1522.75 l 0,149,150 + 445.875 1541.5 445.875 1541.5 459 1554 c 0,151,152 + 480.015 1574.01 480.015 1574.01 498 1579 c 0,153,154 + 519.22 1584.14 519.22 1584.14 547.867 1584.12 c 0,155,156 + 563.788 1584.11 563.788 1584.11 582 1582.5 c 0,157,158 + 632.988 1578 632.988 1578 666 1561 c 0,159,-1 + 770 1503.5 l 0,160,161 + 827.016 1471.99 827.016 1471.99 874 1461 c 0,162,163 + 926.975 1448 926.975 1448 969 1446.5 c 0,164,165 + 1061.49 1447.76 l 0,166,167 + 1063.75 1447.88 1063.75 1447.88 1066 1448 c 0,168,169 + 1144.4 1445.44 l 0,170,171 + 1155 1444.6 1155 1444.6 1166 1443.5 c 0,172,173 + 1221.01 1437.99 1221.01 1437.99 1257 1405 c 0,174,175 + 1282.01 1381 1282.01 1381 1284 1322.5 c 0,176,177 + 1281.53 1288.39 l 0,178,179 + 1274.87 1255.1 1274.87 1255.1 1251 1236 c 0,180,181 + 1233.82 1220.31 1233.82 1220.31 1198.24 1220.25 c 0,182,183 + 1186.18 1220.23 1186.18 1220.23 1172 1222 c 0,184,185 + 1199 1223.01 1199 1223.01 1227.5 1271 c 0,186,187 + 1239.27 1290.83 1239.27 1290.83 1239.19 1309.97 c 0,188,189 + 1239.06 1337.18 1239.06 1337.18 1215 1363 c 0,190,191 + 1204.09 1373.91 1204.09 1373.91 1185.45 1373.96 c 0,192,193 + 1169.91 1374 1169.91 1374 1149 1366.5 c 0,194,195 + 1103 1350 1103 1350 1088 1334 c 0,196,197 + 1024.02 1263.03 1024.02 1263.03 959.5 1150.5 c 0,198,199 + 895 1038 895 1038 856 951 c 0,200,201 + 832.001 895.003 832.001 895.003 817.5 818 c 0,202,203 + 803 741.002 803 741.002 795 679 c 0,204,205 + 786 618 786 618 751 587.5 c 0,206,207 + 716 557 716 557 637 590 c 0,208,209 + 659.766 589.972 l 0,210,211 + 678.989 592.981 678.989 592.981 702.5 605.5 c 0,212,213 + 741 626 741 626 725 677 c 0,214,215 + 707 731 707 731 653 680 c 0,216,217 + 599 629 599 629 596 596 c 0,218,219 + 590 541 590 541 588.5 442 c 0,220,221 + 587 343 587 343 660 325 c 0,222,223 + 760 298 760 298 856 298 c 0,224,225 + 936 298 936 298 972 357 c 0,226,227 + 1007.98 415.974 1007.98 415.974 1049 469 c 0,228,229 + 1105.57 542.286 1105.57 542.286 1153.05 542.837 c 0,230,231 + 1173.67 539.5 l 0,232,233 + 1188.84 534.299 1188.84 534.299 1203 521 c 0,234,235 + 1265.25 462.519 1265.25 462.519 1265 433 c 0,236,237 + 1250 456 1250 456 1196 475.5 c 0,238,239 + 1178.91 481.671 1178.91 481.671 1164.73 481.583 c 0,240,241 + 1134.09 481.393 1134.09 481.393 1117 452 c 0,242,243 + 1099 422 1099 422 1099 367 c 0,244,245 + 1099 335.005 1099 335.005 1137 302.5 c 0,246,247 + 1174.99 270 1174.99 270 1197 261 c 0,248,249 + 1228.05 248.984 1228.05 248.984 1273 233 c 0,250,251 + 1317.95 217.016 1317.95 217.016 1349 205 c 0,252,253 + 1409 179.999 1409 179.999 1446.5 127.5 c 0,254,255 + 1474.23 88.6715 1474.23 88.6715 1474.35 48.4816 c 0,256,257 + 1474.39 34.3255 1474.39 34.3255 1471 20 c 0,258,259 + 1456 56 1456 56 1429 96.5 c 0,260,261 + 1402 136.999 1402 136.999 1336 144 c 0,262,263 + 1246.66 147.183 l 0,264,265 + 1238.67 147.142 1238.67 147.142 1230.5 147 c 0,266,267 + 1172.99 145.999 1172.99 145.999 1126 134 c 0,268,269 + 1084 123.001 1084 123.001 1045 98 c 0,270,271 + 1006 72.9999 1006 72.9999 970 59 c 0,272,273 + 918 39 918 39 879 33.5 c 0,274,275 + 840 28 840 28 810 59 c 0,276,277 + 797 71 797 71 799.5 90 c 0,278,279 + 802 109.001 802 109.001 808 115 c 0,280,281 + 816 76 816 76 840 76 c 0,282,283 + 878 76 878 76 883 111 c 0,284,285 + 881.225 124.68 l 0,286,287 + 871.742 145.173 871.742 145.173 818.066 145.18 c 0,288,289 + 808.269 145.181 808.269 145.181 797 144.5 c 0,290,291 + 705.966 138.997 705.966 138.997 695 138 c 0,292,293 + 584.998 118.999 584.998 118.999 504.5 71.5 c 0,294,295 + 424 24 424 24 329 -23 c 0,296,-1 + 262.5 -54 l 0,297,298 + 223.001 -73.0001 223.001 -73.0001 192 -73 c 0,0,1 +EndSplineSet +KernsSLIF: 121 -195 0 0 322 -247 0 0 105 -143 0 0 101 -104 0 0 98 -156 0 0 45 -364 0 0 +EndChar +StartChar: Adieresis +Encoding: 196 196 75 +Width: 1568 +Flags: HW +Fore +128 -308 m 1,0,1 + 33 -174 33 -174 20.5 -51 c 0,2,3 + 8.00005 72 8.00005 72 37.5 184.5 c 0,4,5 + 67 297 67 297 118.5 399.5 c 0,6,7 + 170.001 502.002 170.001 502.002 203 595 c 0,8,9 + 224 654 224 654 227 761.5 c 0,10,11 + 230 869 230 869 240.5 978.5 c 0,12,13 + 251.001 1088.01 251.001 1088.01 282.5 1177 c 0,14,15 + 314.004 1266.01 314.004 1266.01 394 1289 c 0,16,17 + 318 1214 318 1214 362.5 1157 c 0,18,19 + 379.049 1136.49 379.049 1136.49 415 1148 c 0,20,21 + 441.428 1156.46 441.428 1156.46 466 1283 c 0,22,23 + 486 1386.01 486 1386.01 583.5 1530.5 c 0,24,25 + 678.497 1672.92 678.497 1672.92 755.5 1733.5 c 0,26,27 + 805.557 1772.89 805.557 1772.89 859.876 1772.89 c 0,28,29 + 912.441 1772.89 912.441 1772.89 969 1736 c 0,30,31 + 934.103 1737 l 0,32,33 + 864.411 1730.95 864.411 1730.95 851 1653 c 0,34,35 + 847.071 1630.16 847.071 1630.16 847.122 1606.63 c 0,36,37 + 847.278 1534.34 847.278 1534.34 885 1455.5 c 0,38,39 + 932.227 1356.79 932.227 1356.79 966 1356 c 0,40,41 + 1004 1360.01 1004 1360.01 1007 1379.5 c 0,42,43 + 1007.48 1398.72 l 0,44,45 + 1003.15 1423.01 1003.15 1423.01 974 1448 c 0,46,47 + 1089.92 1426.41 1089.92 1426.41 1090.5 1312.5 c 0,48,49 + 1090.4 1270.56 1090.4 1270.56 1109.82 1163.16 c 0,50,51 + 1116.69 1125.17 1116.69 1125.17 1126 1079 c 0,52,53 + 1150 959.018 1150 959.018 1168.5 919.5 c 0,54,55 + 1188.08 877.713 1188.08 877.713 1221 891 c 0,56,57 + 1269.26 910.472 1269.26 910.472 1260 966 c 0,58,59 + 1248 1038 1248 1038 1209 1083 c 0,60,61 + 1296 1030 1296 1030 1320.5 961 c 0,62,63 + 1341.19 902.719 1341.19 902.719 1341.2 841.959 c 0,64,65 + 1341.2 830.773 1341.2 830.773 1340.5 819.5 c 0,66,67 + 1336 746.97 1336 746.97 1320 679 c 0,68,69 + 1309.29 633.487 1309.29 633.487 1309.33 596.017 c 0,70,71 + 1309.36 577.528 1309.36 577.528 1312 561 c 0,72,73 + 1327 457.016 1327 457.016 1374 353 c 0,74,75 + 1420.99 249 1420.99 249 1453.5 137 c 0,76,77 + 1481.72 39.766 1481.72 39.766 1481.67 -66.1854 c 0,78,79 + 1481.66 -82.2438 1481.66 -82.2438 1481 -98.5 c 0,80,81 + 1476.01 -221.982 1476.01 -221.982 1387 -366 c 0,82,83 + 1415.72 -269.572 1415.72 -269.572 1415.68 -151.161 c 0,84,85 + 1415.66 -96.4285 1415.66 -96.4285 1409.5 -37 c 0,86,87 + 1390.4 147.188 1390.4 147.188 1260.35 147.146 c 0,88,89 + 1256.72 147.145 1256.72 147.145 1253 147 c 0,90,91 + 1175.99 144 1175.99 144 1153 79.5 c 0,92,93 + 1130.01 15 1130.01 15 1156 -73 c 0,94,95 + 1040.99 -4 1040.99 -4 1078 170 c 0,96,97 + 1113.08 334.959 1113.08 334.959 1113.1 447.845 c 0,98,99 + 1113.1 454.001 1113.1 454.001 1113 460 c 0,100,101 + 1111.01 586.996 1111.01 586.996 1030 636 c 0,102,103 + 949 685 949 685 856 667 c 0,104,105 + 753.973 646.352 753.973 646.352 720.5 592 c 0,106,107 + 673.661 518 673.661 518 608 518 c 0,108,109 + 554 518 554 518 528 537 c 0,110,111 + 627.133 541.425 627.133 541.425 627.252 603.216 c 0,112,113 + 627.265 610.238 627.265 610.238 626 618 c 0,114,115 + 614.656 687.608 614.656 687.608 539 671 c 0,116,117 + 470.971 656.062 470.971 656.062 437.5 614 c 0,118,119 + 381.001 543.002 381.001 543.002 365 441 c 0,120,121 + 353.351 369.356 353.351 369.356 353.406 284.484 c 0,122,123 + 353.445 223.641 353.445 223.641 359.5 156 c 0,124,125 + 374 -6 374 -6 262 -68 c 0,126,127 + 308.115 30.5945 308.115 30.5945 274 92 c 0,128,129 + 254.66 126.814 254.66 126.814 187.626 127.026 c 0,130,131 + 185.341 127.033 185.341 127.033 183 127 c 0,132,133 + 153.87 123.844 l 0,134,135 + 79.7216 105.672 79.7216 105.672 79 -17 c 0,136,137 + 77.9999 -186.999 77.9999 -186.999 128 -308 c 1,0,1 +564 987 m 0,77,78 + 564 913 564 913 632.5 878.5 c 0,79,80 + 701 844 701 844 782.5 839.5 c 0,81,82 + 871.984 834.559 871.984 834.559 930.5 856 c 0,83,84 + 996 880 996 880 993 914 c 0,85,86 + 987.893 969.548 987.893 969.548 889.5 1045 c 0,87,88 + 832.997 1088.33 832.997 1088.33 832.548 1133.03 c 0,89,90 + 836.254 1156.84 l 0,91,92 + 842.636 1176.79 842.636 1176.79 860 1197 c 0,93,94 + 858.922 1165.93 l 0,95,96 + 861.742 1140.27 861.742 1140.27 880.656 1139.92 c 0,97,98 + 893.5 1142 l 0,99,100 + 919.125 1149.84 919.125 1149.84 919.484 1172.94 c 0,101,102 + 915.537 1194.44 l 0,103,104 + 913.05 1201.75 913.05 1201.75 909 1210 c 0,105,106 + 881.004 1263.99 881.004 1263.99 815 1328 c 0,107,108 + 767.167 1374.39 767.167 1374.39 731.412 1374.55 c 0,109,110 + 717.835 1374.61 717.835 1374.61 706 1368 c 0,111,112 + 658 1341 658 1341 664.5 1294.5 c 0,113,114 + 670.998 1248.01 670.998 1248.01 689 1196 c 0,115,116 + 707.001 1143.99 707.001 1143.99 714.5 1094.5 c 0,117,118 + 722 1045 722 1045 677 1012 c 0,119,120 + 698 1091.99 698 1091.99 617 1078 c 0,121,122 + 564.452 1070.36 564.452 1070.36 563.972 992.397 c 0,123,124 + 563.956 989.741 563.956 989.741 564 987 c 0,77,78 +509 1815 m 1,99,100 + 455 1950 455 1950 538 2068.5 c 0,101,102 + 614.315 2177.46 614.315 2177.46 728.667 2177.78 c 0,103,104 + 738.687 2177.81 738.687 2177.81 749 2177 c 0,105,106 + 618.485 2101.78 618.485 2101.78 618.174 2040.1 c 0,107,108 + 618.142 2033.73 618.142 2033.73 619.5 2027.5 c 0,109,110 + 627.779 1989.54 627.779 1989.54 673.706 1989.54 c 0,111,112 + 708.221 1989.55 708.221 1989.55 764 2011 c 0,113,114 + 745.001 1939.01 745.001 1939.01 646.5 1914 c 0,115,116 + 548 1888.99 548 1888.99 509 1815 c 1,99,100 +1081 1812 m 1,108,109 + 1077.59 1842.42 l 0,110,111 + 1078.03 1909.94 1078.03 1909.94 1140 2017 c 0,112,113 + 1210.35 2138.52 1210.35 2138.52 1316.61 2138.99 c 0,114,115 + 1326.64 2139.04 1326.64 2139.04 1337 2138 c 0,116,117 + 1282.21 2087.85 1282.21 2087.85 1282.18 2034.27 c 0,118,119 + 1282.18 2030.14 1282.18 2030.14 1282.5 2026 c 0,120,121 + 1285.05 1993.14 1285.05 1993.14 1326.92 1993.02 c 0,122,123 + 1358.95 1992.93 1358.95 1992.93 1414 2012 c 0,124,125 + 1358.01 1928 1358.01 1928 1264.5 1910 c 0,126,127 + 1171.01 1892 1171.01 1892 1081 1812 c 1,108,109 +EndSplineSet +EndChar +StartChar: Oacute +Encoding: 211 211 45 +Width: 1442 +Flags: W +Fore +702 -166 m 0,0,1 + 595.001 -155.001 595.001 -155.001 494.5 -66 c 0,2,3 + 394 23 394 23 316.5 126.5 c 0,4,5 + 239 230 239 230 192 315 c 0,6,7 + 145 400.001 145 400.001 145 402 c 0,8,9 + 128.001 450 128.001 450 92.5 525.5 c 0,10,11 + 57.0008 600.998 57.0008 600.998 34 678 c 0,12,13 + 11 755 11 755 16 820.5 c 0,14,15 + 20.9999 885.999 20.9999 885.999 86 914 c 0,16,17 + 120.999 928 120.999 928 151 910 c 0,18,19 + 76 883 76 883 92 806.5 c 0,20,21 + 108.001 730 108.001 730 144 769 c 0,22,23 + 185.999 812.998 185.999 812.998 246 939.5 c 0,24,25 + 281.016 1013.32 281.016 1013.32 281.292 1054.96 c 0,26,27 + 281.388 1069.49 281.388 1069.49 277.259 1080.1 c 0,28,29 + 272.94 1091.19 272.94 1091.19 264 1098 c 0,30,31 + 250.79 1107.15 250.79 1107.15 239.416 1107.23 c 0,32,33 + 226.112 1107.32 226.112 1107.32 215.319 1095.02 c 0,34,35 + 208.425 1087.16 208.425 1087.16 202 1073 c 0,36,37 + 191.968 1050.32 191.968 1050.32 192.019 1029.54 c 0,38,39 + 192.085 1002.68 192.085 1002.68 209 979 c 0,40,41 + 143.612 1022.32 143.612 1022.32 143.36 1067.98 c 0,42,43 + 143.304 1078.18 143.304 1078.18 146.5 1088.5 c 0,44,45 + 164.001 1145.01 164.001 1145.01 222 1193.5 c 0,46,47 + 280.032 1242.02 280.032 1242.02 350 1277 c 0,48,49 + 420.039 1312.01 420.039 1312.01 445 1321 c 0,50,51 + 491 1339 491 1339 595 1370.5 c 0,52,53 + 671.347 1393.62 671.347 1393.62 672.246 1429.41 c 0,54,55 + 668.639 1446.62 l 0,56,57 + 666.47 1451.7 666.47 1451.7 663 1457 c 0,58,59 + 646.528 1481.71 646.528 1481.71 625.907 1481.67 c 0,60,61 + 611.47 1481.65 611.47 1481.65 595 1469.5 c 0,62,63 + 554.997 1439.99 554.997 1439.99 543 1410 c 0,64,65 + 535.72 1416.76 535.72 1416.76 535.606 1430.01 c 0,66,67 + 535.507 1441.42 535.507 1441.42 541.5 1460 c 0,68,69 + 553.997 1497 553.997 1497 564 1506 c 0,70,71 + 632 1564.99 632 1564.99 717.5 1536 c 0,72,73 + 802.989 1507.01 802.989 1507.01 890 1438 c 0,74,75 + 977.001 1369 977.001 1369 1057 1284.5 c 0,76,77 + 1136.96 1200.04 1136.96 1200.04 1194 1148 c 0,78,79 + 1225.01 1119.01 1225.01 1119.01 1236 1169 c 0,80,81 + 1236.66 1189.31 l 0,82,83 + 1230.47 1227.67 1230.47 1227.67 1167 1261 c 0,84,85 + 1307.99 1261 1307.99 1261 1328.5 1135 c 0,86,87 + 1337.08 1082.31 1337.08 1082.31 1336.99 1022.87 c 0,88,89 + 1336.87 940.211 1336.87 940.211 1320 844.5 c 0,90,91 + 1291.02 680.102 1291.02 680.102 1247 520.5 c 0,92,93 + 1213.1 397.602 1213.1 397.602 1213.03 329.64 c 0,94,95 + 1213.01 309.382 1213.01 309.382 1216 294 c 0,96,97 + 1219 276 1219 276 1243 276.5 c 0,98,99 + 1266.99 276.999 1266.99 276.999 1283 295 c 0,100,101 + 1337 358 1337 358 1292 429 c 0,102,103 + 1349 412.001 1349 412.001 1358 350 c 0,104,105 + 1360.83 303.874 l 0,106,107 + 1358.57 224.182 1358.57 224.182 1302.5 174 c 0,108,109 + 1230.99 109.998 1230.99 109.998 1124.5 74.5 c 0,110,111 + 1018 39 1018 39 903.5 23 c 0,112,113 + 789 6.99995 789 6.99995 720 -9 c 0,114,115 + 666 -21 666 -21 709 -76.5 c 0,116,117 + 724.904 -97.0275 724.904 -97.0275 749.016 -96.9665 c 0,118,119 + 790.096 -96.8626 790.096 -96.8626 855 -37 c 0,120,121 + 843 -89.0001 843 -89.0001 797 -129.5 c 0,122,123 + 755.357 -166.164 755.357 -166.164 711.257 -166.359 c 0,124,125 + 706.642 -166.379 706.642 -166.379 702 -166 c 0,0,1 +529 896 m 0,66,67 + 484.999 861 484.999 861 450 857.5 c 0,68,69 + 415 854 415 854 385 860 c 0,70,71 + 514 904 514 904 484 1000 c 0,72,73 + 479.058 1014.83 479.058 1014.83 459.197 1014.73 c 0,74,75 + 454.941 1014.71 454.941 1014.71 450 1014 c 0,76,77 + 421.994 1009.99 421.994 1009.99 409 998 c 0,78,79 + 370.001 960.001 370.001 960.001 332.5 887.5 c 0,80,81 + 295 815 295 815 274 739 c 0,82,83 + 253 663 253 663 256 600 c 0,84,85 + 259 537 259 537 301 521 c 0,86,87 + 406 479 406 479 388.5 555 c 0,88,89 + 371 631 371 631 317 642 c 0,90,91 + 370 663 370 663 417.5 617 c 0,92,93 + 465.001 570.999 465.001 570.999 497 502.5 c 0,94,95 + 529.001 433.997 529.001 433.997 541 365.5 c 0,96,97 + 553 297 553 297 535 273 c 0,98,99 + 534 318.001 534 318.001 504.5 336 c 0,100,101 + 475 354 475 354 448 323 c 0,102,103 + 414.348 283.229 414.348 283.229 414.233 251.128 c 0,104,105 + 414.135 223.66 414.135 223.66 438.591 201.807 c 0,106,107 + 441.609 199.111 441.609 199.111 445 196.5 c 0,108,109 + 508 148.001 508 148.001 617.5 141 c 0,110,111 + 727 133.999 727 133.999 842 174 c 0,112,113 + 957 214 957 214 996 314 c 0,114,115 + 1004.81 337.305 1004.81 337.305 1004.94 355.037 c 0,116,117 + 1005.04 368.522 1005.04 368.522 1000.11 378.784 c 0,118,119 + 988.723 402.504 988.723 402.504 950.5 409 c 0,120,121 + 874 422 874 422 893 308 c 0,122,123 + 855.407 364.132 855.407 364.132 855.207 406.739 c 0,124,125 + 855.109 427.468 855.109 427.468 863.863 444.996 c 0,126,127 + 872.055 461.4 872.055 461.4 888 475 c 0,128,129 + 956.012 533.01 956.012 533.01 1034 609 c 0,130,131 + 1157 729 1157 729 1139 875.5 c 0,132,133 + 1121 1022 1121 1022 995 1139 c 0,134,135 + 911.451 1215.28 911.451 1215.28 853.874 1215.69 c 0,136,137 + 848.054 1215.73 848.054 1215.73 842.5 1215 c 0,138,139 + 782 1207.01 782 1207.01 734 1153.5 c 0,140,141 + 685.991 1099.98 685.991 1099.98 639.5 1023.5 c 0,142,143 + 593 947 593 947 529 896 c 0,66,67 +834 1616 m 1,109,110 + 771.325 1690.07 771.325 1690.07 771.259 1771.76 c 0,111,112 + 771.244 1790.43 771.244 1790.43 774.5 1809.5 c 0,113,114 + 792 1911.99 792 1911.99 860 1982 c 0,115,116 + 927.993 2052 927.993 2052 1025.5 2068.5 c 0,117,118 + 1123 2085 1123 2085 1207 2004 c 0,119,120 + 1142.86 2052.29 1142.86 2052.29 1091.17 2052.27 c 0,121,122 + 1071.15 2052.26 1071.15 2052.26 1053 2045 c 0,123,124 + 988.002 2019 988.002 2019 956.5 1966.5 c 0,125,126 + 925 1914 925 1914 933 1867.5 c 0,127,128 + 938.015 1838.35 938.015 1838.35 963.071 1838.08 c 0,129,130 + 985.38 1842.18 l 0,131,132 + 992.25 1844.45 992.25 1844.45 1000 1848 c 0,133,134 + 1013.12 1852.92 1013.12 1852.92 1013.09 1871.6 c 0,135,136 + 1013.06 1887.07 1013.06 1887.07 1004 1912 c 0,137,138 + 1040.78 1864.25 1040.78 1864.25 1040.82 1834.9 c 0,139,140 + 1040.83 1826.74 1040.83 1826.74 1038 1820 c 0,141,142 + 1025 1789 1025 1789 986 1764 c 0,143,-1 + 900.5 1708 l 0,144,145 + 853.995 1676.99 853.995 1676.99 834 1616 c 1,109,110 +EndSplineSet +KernsSLIF: 84 -286 0 0 87 -182 0 0 +EndChar +StartChar: Odieresis +Encoding: 214 214 79 +Width: 1622 +Flags: HW +Fore +1078 -11 m 0,0,1 + 1064.01 0.998647 1064.01 0.998647 973.5 11.5 c 0,2,3 + 883 22 883 22 778 24 c 0,4,5 + 673 26 673 26 585.5 15 c 0,6,7 + 499.124 4.14128 499.124 4.14128 491 -27 c 0,8,9 + 485 -50 485 -50 507.5 -75 c 0,10,11 + 530 -100 530 -100 615 -130 c 0,12,13 + 563.194 -132.16 l 0,14,15 + 497.059 -129.791 497.059 -129.791 433 -101 c 0,16,17 + 325.829 -52.8336 325.829 -52.8336 300 23 c 0,18,19 + 240.001 203.998 240.001 203.998 222.5 289 c 0,20,21 + 190.738 481.604 190.738 481.604 176 512 c 0,22,23 + 128 611 128 611 44.5 753.5 c 0,24,25 + -39.0001 896 -39.0001 896 43 1037 c 0,26,27 + 37 930 37 930 69 916.5 c 0,28,29 + 101 903 101 903 132 921 c 0,30,31 + 165 941 165 941 227 1097.5 c 0,32,33 + 289.014 1254.03 289.014 1254.03 306 1300 c 0,34,35 + 321.216 1342.27 321.216 1342.27 321.243 1370.28 c 0,36,37 + 321.265 1394.44 321.265 1394.44 310 1408 c 0,38,39 + 289.612 1432.55 289.612 1432.55 262.475 1432.69 c 0,40,41 + 243.542 1432.78 243.542 1432.78 221.325 1421 c 0,42,43 + 198.844 1409.08 198.844 1409.08 173 1385 c 0,44,45 + 183 1455 183 1455 225 1491 c 0,46,47 + 283.465 1538.64 283.465 1538.64 372.5 1543 c 0,48,49 + 411.143 1545.55 411.143 1545.55 546 1607.5 c 0,50,51 + 605.628 1634.94 605.628 1634.94 705 1636 c 0,52,53 + 799.002 1637.01 799.002 1637.01 813 1682 c 0,54,55 + 832 1746.01 832 1746.01 714 1766 c 0,56,57 + 744.427 1778.86 744.427 1778.86 774.49 1778.95 c 0,58,59 + 807.009 1779.05 807.009 1779.05 839.1 1764.21 c 0,60,61 + 846.561 1760.76 846.561 1760.76 854 1756.5 c 0,62,63 + 922.99 1717.01 922.99 1717.01 985.5 1648 c 0,64,65 + 1048.01 1579 1048.01 1579 1101 1501 c 0,66,67 + 1153.99 1423.01 1153.99 1423.01 1193 1376 c 0,68,69 + 1258.99 1295.01 1258.99 1295.01 1395.5 1208.5 c 0,70,71 + 1531.99 1122 1531.99 1122 1545 955 c 0,72,73 + 1493.91 1031.63 1493.91 1031.63 1456.6 1031.78 c 0,74,75 + 1450.09 1031.8 1450.09 1031.8 1444 1029.5 c 0,76,77 + 1403 1014 1403 1014 1395 988 c 0,78,79 + 1368.69 904.7 1368.69 904.7 1368.67 830.234 c 0,80,81 + 1368.66 785.795 1368.66 785.795 1378 744.5 c 0,82,83 + 1413.42 587.936 1413.42 587.936 1437 543.5 c 0,84,85 + 1485.01 452.991 1485.01 452.991 1485.5 381.5 c 0,86,87 + 1487.95 300.016 1487.95 300.016 1436 257 c 0,88,89 + 1444.29 298.88 1444.29 298.88 1444.3 328.871 c 0,90,91 + 1444.31 367.613 1444.31 367.613 1430.5 386.5 c 0,92,93 + 1412.56 411.031 1412.56 411.031 1386.84 411.164 c 0,94,95 + 1377.44 411.213 1377.44 411.213 1367 408 c 0,96,97 + 1341.99 400 1341.99 400 1311.5 301 c 0,98,99 + 1281.05 202.142 1281.05 202.142 1240 93.5 c 0,100,101 + 1189.08 -41.2672 1189.08 -41.2672 1145 -92 c 0,102,103 + 1105.04 -137.992 1105.04 -137.992 1053.71 -137.938 c 0,104,105 + 1036.96 -137.921 1036.96 -137.921 1019 -133 c 0,106,107 + 1091 -116.999 1091 -116.999 1100 -78.5 c 0,108,109 + 1101.97 -55.1353 l 0,110,111 + 1099.91 -29.7823 1099.91 -29.7823 1078 -11 c 0,0,1 +645 195 m 0,62,63 + 762.759 189.131 762.759 189.131 808.5 268.5 c 0,64,65 + 885 399 885 399 996 351 c 0,66,67 + 909.315 332.426 909.315 332.426 948 261 c 0,68,69 + 966.315 227.184 966.315 227.184 1035 231 c 0,70,71 + 1090.8 234.1 1090.8 234.1 1138 328.5 c 0,72,73 + 1210.49 473.474 1210.49 473.474 1218 561.5 c 0,74,75 + 1224.79 641.024 1224.79 641.024 1224.69 711.756 c 0,76,77 + 1224.62 765.961 1224.62 765.961 1220.5 815 c 0,78,79 + 1206.48 958.433 1206.48 958.433 1193 985 c 0,80,81 + 1174.69 1020.77 1174.69 1020.77 1130 1010.5 c 0,82,83 + 1085.67 1001.18 1085.67 1001.18 1085.09 966.896 c 0,84,85 + 1089.04 942.902 l 0,86,87 + 1092.23 932.685 1092.23 932.685 1098 921 c 0,88,89 + 1018.73 960.128 1018.73 960.128 1008 1035 c 0,90,91 + 1008.69 1052 1008.69 1052 1016.5 1197 c 0,92,93 + 1019.84 1268.11 1019.84 1268.11 961 1356 c 0,94,95 + 933.657 1396.84 933.657 1396.84 792 1419 c 0,96,97 + 759.176 1420.36 l 0,98,99 + 704.916 1416.09 704.916 1416.09 658.5 1367.5 c 0,100,101 + 570.656 1275.53 570.656 1275.53 568 1232.5 c 0,102,103 + 553.425 996.171 553.425 996.171 549 981 c 0,104,105 + 515.298 859.438 515.298 859.438 442.5 819 c 0,106,107 + 486.422 946.219 486.422 946.219 363 948.5 c 0,108,109 + 309.74 949.484 309.74 949.484 312 819 c 0,110,111 + 314.316 685.281 314.316 685.281 318 642 c 0,112,113 + 327.896 514.557 327.896 514.557 374 427 c 0,114,115 + 450.349 282.004 450.349 282.004 489 249 c 0,116,117 + 547.345 199.867 547.345 199.867 645 195 c 0,62,63 +290 1856 m 1,94,95 + 294.001 1943.01 294.001 1943.01 364.5 2072.5 c 0,96,97 + 435 2202 435 2202 526 2218 c 0,98,99 + 467.076 2106.95 467.076 2106.95 466.932 2058.68 c 0,100,101 + 466.886 2043.05 466.886 2043.05 473 2034 c 0,102,103 + 497.993 1997.01 497.993 1997.01 583 1993 c 0,104,105 + 571.999 1943 571.999 1943 455 1914.5 c 0,106,107 + 338 1886 338 1886 290 1856 c 1,94,95 +1051 1877 m 1,103,104 + 1063 1958.01 1063 1958.01 1145 2049.5 c 0,105,106 + 1227.01 2141 1227.01 2141 1326 2165 c 0,107,108 + 1259 2099.01 1259 2099.01 1245.5 2036 c 0,109,110 + 1244.66 2015.26 l 0,111,112 + 1251.83 1967.83 1251.83 1967.83 1347 1943 c 0,113,114 + 1311.37 1914.87 1311.37 1914.87 1267.16 1914.68 c 0,115,116 + 1244.88 1914.58 1244.88 1914.58 1220.42 1921.57 c 0,117,118 + 1215.75 1922.91 1215.75 1922.91 1211 1924.5 c 0,119,120 + 1190.26 1931.46 1190.26 1931.46 1169.39 1931.49 c 0,121,122 + 1110.74 1931.58 1110.74 1931.58 1051 1877 c 1,103,104 +EndSplineSet +EndChar +StartChar: Udieresis +Encoding: 220 220 77 +Width: 1564 +Flags: HW +Fore +934.5 -28 m 128,-1,0 + 945 -89.9999 945 -89.9999 1050 -50 c 0,1,2 + 1006.09 -119.363 1006.09 -119.363 934.178 -119.579 c 0,3,4 + 901.082 -119.678 901.082 -119.678 862.054 -105.131 c 0,5,6 + 855.121 -102.547 855.121 -102.547 848 -99.5 c 0,7,8 + 819.129 -87.1482 819.129 -87.1482 609 -54 c 0,9,-1 + 445 -26 l 0,10,11 + 324 -27 324 -27 318 108 c 0,12,13 + 370.439 64.3008 370.439 64.3008 408.5 112 c 0,14,15 + 417.639 123.453 417.639 123.453 417.618 139.02 c 0,16,17 + 417.598 154.083 417.598 154.083 409 173 c 0,18,19 + 389.182 216.601 389.182 216.601 357 252 c 0,20,-1 + 307 307 l 0,21,22 + 283.139 331.714 283.139 331.714 245 311.5 c 0,23,24 + 213.696 295.848 213.696 295.848 213.789 268.858 c 0,25,26 + 213.854 250.152 213.854 250.152 229 226 c 0,27,28 + 164.711 239.834 164.711 239.834 164.281 312.053 c 0,29,30 + 164.189 327.45 164.189 327.45 167 345.5 c 0,31,32 + 171.076 371.671 171.076 371.671 171.038 399.582 c 0,33,34 + 170.963 454.432 170.963 454.432 155 516 c 0,35,36 + 106.307 701.036 106.307 701.036 57.5 767.5 c 0,37,38 + -42 906 -42 906 28 1063 c 0,39,40 + 30.0443 991.442 30.0443 991.442 69.5 991.5 c 0,41,42 + 98.0043 991.542 98.0043 991.542 112 1027 c 0,43,44 + 115.628 1036.19 115.628 1036.19 115.6 1052.67 c 0,45,46 + 115.51 1104.31 115.51 1104.31 79.5 1227.5 c 0,47,48 + 34.0309 1383.05 34.0309 1383.05 33.9195 1433.69 c 0,49,50 + 33.9145 1435.95 33.9145 1435.95 34 1438 c 0,51,52 + 38.9997 1630.99 38.9997 1630.99 161 1782 c 0,53,54 + 121.48 1676.06 121.48 1676.06 121.46 1567.79 c 0,55,56 + 121.453 1531.03 121.453 1531.03 126 1494 c 0,57,58 + 145.116 1338.34 145.116 1338.34 247 1320 c 0,59,60 + 271.932 1319.82 l 0,61,62 + 301.474 1323.99 301.474 1323.99 340 1347.5 c 0,63,64 + 408.002 1389.01 408.002 1389.01 429 1501 c 0,65,66 + 469 1403.01 469 1403.01 434.5 1315 c 0,67,68 + 402.62 1233.68 402.62 1233.68 390 1118 c 0,69,70 + 386.268 1050.09 l 0,71,72 + 386.641 983.869 386.641 983.869 404.5 934 c 0,73,74 + 411.708 913.872 411.708 913.872 411.703 895.446 c 0,75,76 + 411.688 846.128 411.688 846.128 360 809 c 0,77,78 + 372 866 372 866 354 888.5 c 0,79,80 + 328.77 920.038 328.77 920.038 300 866 c 0,81,82 + 291.392 849.833 291.392 849.833 291.384 816.023 c 0,83,84 + 291.375 776.696 291.375 776.696 303 713.5 c 0,85,86 + 322.001 607.499 322.001 607.499 337 567.5 c 0,87,88 + 362.966 495.17 362.966 495.17 399 435 c 0,89,90 + 463.641 335.174 463.641 335.174 520 288 c 0,91,92 + 563.185 268.568 563.185 268.568 581 283.5 c 0,93,94 + 615 312 615 312 572 367 c 0,95,96 + 694.138 356.907 694.138 356.907 709.5 243 c 0,97,98 + 720.458 160.941 720.458 160.941 775.5 166.5 c 0,99,100 + 843.666 172.427 843.666 172.427 885 261 c 0,101,102 + 923.283 343.035 923.283 343.035 944.5 420.5 c 0,103,104 + 975.867 535.024 975.867 535.024 981 573 c 0,105,106 + 996.001 687.004 996.001 687.004 1069 738 c 0,107,108 + 1054.05 699.755 1054.05 699.755 1053.95 673.431 c 0,109,110 + 1053.85 648.277 1053.85 648.277 1067.3 634.007 c 0,111,112 + 1072.24 628.771 1072.24 628.771 1079 625 c 0,113,114 + 1089.88 618.928 1089.88 618.928 1101.28 618.984 c 0,115,116 + 1117.15 619.061 1117.15 619.061 1134 631 c 0,117,118 + 1158.82 648.023 1158.82 648.023 1158.75 739.476 c 0,119,120 + 1158.72 776.982 1158.72 776.982 1154.5 827 c 0,121,122 + 1139.2 1008.54 1139.2 1008.54 1122 1097 c 0,123,124 + 1097.76 1221.73 1097.76 1221.73 1080.5 1273.5 c 0,125,126 + 1063.07 1325.8 1063.07 1325.8 1063.03 1375.37 c 0,127,128 + 1062.97 1455.21 1062.97 1455.21 1108 1528 c 0,129,130 + 1118.73 1412.85 1118.73 1412.85 1175.5 1374.5 c 0,131,132 + 1218.91 1345.17 1218.91 1345.17 1245.11 1344.85 c 0,133,134 + 1260.78 1347.91 l 0,135,136 + 1263.55 1349.19 1263.55 1349.19 1266 1351 c 0,137,138 + 1338.58 1407.54 1338.58 1407.54 1358 1591.5 c 0,139,140 + 1363.39 1642.57 1363.39 1642.57 1363.33 1689.38 c 0,141,142 + 1363.21 1781.42 1363.21 1781.42 1342 1857 c 0,143,144 + 1407.99 1746.01 1407.99 1746.01 1425.5 1582 c 0,145,146 + 1431.64 1524.47 1431.64 1524.47 1431.56 1469.76 c 0,147,148 + 1431.42 1368.54 1431.42 1368.54 1410 1277 c 0,149,150 + 1389.43 1189.71 1389.43 1189.71 1389.41 1113.87 c 0,151,152 + 1389.4 1053.29 1389.4 1053.29 1402.5 1000 c 0,153,154 + 1413.81 954.001 1413.81 954.001 1413.73 916.817 c 0,155,156 + 1413.6 857.002 1413.6 857.002 1384 820 c 0,157,158 + 1382.46 849.538 l 0,159,160 + 1377.56 874.521 1377.56 874.521 1359.5 887 c 0,161,162 + 1353.45 891.18 1353.45 891.18 1347.91 891.101 c 0,163,164 + 1328.26 890.82 1328.26 890.82 1315 837 c 0,165,166 + 1299.92 775.08 1299.92 775.08 1299.92 700.686 c 0,167,168 + 1299.92 636.926 1299.92 636.926 1311 564 c 0,169,170 + 1335 406 1335 406 1272 322 c 0,171,172 + 1272 435 1272 435 1221 426 c 0,173,174 + 1166.23 416.106 1166.23 416.106 1047 219 c 0,175,176 + 926.422 19.6906 926.422 19.6906 934.5 -28 c 128,-1,0 +194 1948 m 1,92,93 + 246.065 1994.11 246.065 1994.11 269.5 2145.5 c 0,94,95 + 287.998 2264.99 287.998 2264.99 402 2296 c 0,96,97 + 332.966 2219.29 332.966 2219.29 333.064 2156.71 c 0,98,99 + 333.094 2137.71 333.094 2137.71 339.5 2120 c 0,100,101 + 358.415 2064.52 358.415 2064.52 387.209 2063.76 c 0,102,103 + 403.103 2067.17 l 0,104,105 + 425.939 2077.12 425.939 2077.12 454 2116 c 0,106,107 + 465.818 2098.7 465.818 2098.7 465.962 2079.71 c 0,108,109 + 466.059 2067.01 466.059 2067.01 460.94 2053.55 c 0,110,111 + 447.15 2017.29 447.15 2017.29 395.5 1975.5 c 0,112,113 + 335.507 1926.96 335.507 1926.96 274.599 1926.96 c 0,114,115 + 234.497 1926.96 234.497 1926.96 194 1948 c 1,92,93 +1193 1962 m 1,101,102 + 1226.99 1976.99 1226.99 1976.99 1252 2032.5 c 0,103,104 + 1276.85 2085.8 1276.85 2085.8 1297 2142.5 c 0,105,106 + 1319.99 2197.98 1319.99 2197.98 1351.5 2236.5 c 0,107,108 + 1374 2264 1374 2264 1409 2264.2 c 0,109,110 + 1423 2264.29 1423 2264.29 1439 2260 c 0,111,112 + 1405.72 2244.42 1405.72 2244.42 1380.5 2194 c 0,113,114 + 1358.7 2150.38 1358.7 2150.38 1358.67 2098.08 c 0,115,116 + 1358.67 2091.61 1358.67 2091.61 1359 2085 c 0,117,118 + 1361.09 2061.73 1361.09 2061.73 1403 2050.5 c 0,119,120 + 1424.24 2049.35 l 0,121,122 + 1450 2052.01 1450 2052.01 1490 2071 c 0,123,124 + 1442.32 1997.88 1442.32 1997.88 1335 1953.5 c 0,125,126 + 1299.06 1938.64 1299.06 1938.64 1267.06 1938.64 c 0,127,128 + 1227.48 1938.63 1227.48 1938.63 1193 1962 c 1,101,102 +EndSplineSet +EndChar +StartChar: germandbls +Encoding: 223 223 85 +Width: 1114 +Flags: HMW +VStem: 55 281<-368 1583> +Fore +118 967 m 0,0,1 + 118 1084.53 118 1084.53 88 1118 c 0,2,3 + 34 1178 34 1178 62 1274 c 0,4,5 + 69.7902 1199.99 69.7902 1199.99 124 1247 c 0,6,7 + 134.791 1256.36 134.791 1256.36 148 1330 c 0,8,9 + 154 1363.45 154 1363.45 154 1436 c 0,10,11 + 154 1497.94 154 1497.94 119 1533 c 0,12,13 + 94.3849 1557.65 94.3849 1557.65 55.2625 1557.79 c 0,14,15 + 32.9829 1557.87 32.9829 1557.87 6 1550 c 0,16,17 + 97.9904 1627.49 97.9904 1627.49 183.416 1627.57 c 0,18,19 + 201.861 1627.59 201.861 1627.59 220 1624 c 0,20,21 + 251.926 1617.67 251.926 1617.67 371 1574 c 0,22,23 + 389.214 1567.32 389.214 1567.32 544 1540 c 0,24,25 + 583.266 1536.42 l 0,26,27 + 621.488 1537.23 621.488 1537.23 632 1560 c 0,28,29 + 637.571 1573 637.571 1573 637.538 1582.98 c 0,30,31 + 637.428 1616 637.428 1616 576 1616 c 0,32,33 + 659.582 1645.07 659.582 1645.07 698 1581.5 c 0,34,35 + 744.865 1503.95 744.865 1503.95 786 1494 c 0,36,37 + 830.007 1483.99 830.007 1483.99 908 1436 c 0,38,39 + 943.792 1413.98 943.792 1413.98 944.051 1385.79 c 0,40,41 + 944.151 1374.93 944.151 1374.93 938.978 1363.16 c 0,42,43 + 938.07 1361.09 938.07 1361.09 937 1359 c 0,44,45 + 927.441 1382.05 927.441 1382.05 909.851 1382.55 c 0,46,47 + 893.461 1378.91 l 0,48,49 + 884.467 1375.02 884.467 1375.02 874 1367 c 0,50,51 + 867.597 1362.09 867.597 1362.09 867.581 1353.42 c 0,52,53 + 867.53 1327.07 867.53 1327.07 926.5 1266 c 0,54,55 + 972.687 1218.16 972.687 1218.16 972.762 1181.23 c 0,56,57 + 972.794 1165.07 972.794 1165.07 964 1151 c 0,58,59 + 968.156 1203.53 968.156 1203.53 920 1172 c 0,60,61 + 891.619 1153.41 891.619 1153.41 880 1096 c 0,62,63 + 873.279 1062.79 873.279 1062.79 873.335 1041.2 c 0,64,65 + 873.41 1011.87 873.41 1011.87 886 1004 c 0,66,67 + 896.666 997.333 896.666 997.333 906.222 997.333 c 0,68,69 + 925.333 997.333 925.333 997.333 940 1024 c 0,70,71 + 955.756 941.28 955.756 941.28 762 870 c 0,72,73 + 695.301 845.461 695.301 845.461 708 774 c 0,74,75 + 719.596 708.712 719.596 708.712 767.426 708.519 c 0,76,77 + 774.784 708.489 774.784 708.489 783 710 c 0,78,79 + 957 742 957 742 951 626 c 0,80,81 + 924.609 688.556 924.609 688.556 882 666 c 0,82,83 + 858.918 653.781 858.918 653.781 909 525 c 0,84,85 + 972.715 358.127 972.715 358.127 993 357 c 0,86,87 + 1035 354 1035 354 1041 411 c 0,88,89 + 1056.22 397.957 1056.22 397.957 1056.4 376.249 c 0,90,91 + 1056.5 364.686 1056.5 364.686 1052.34 350.665 c 0,92,93 + 1042.74 318.359 1042.74 318.359 1010.5 273 c 0,94,95 + 945.852 179.834 945.852 179.834 945.454 148.336 c 0,96,97 + 945.372 141.868 945.372 141.868 948 138 c 0,98,99 + 917.598 92.499 917.598 92.499 840.5 36 c 0,100,101 + 786.888 -3.30363 786.888 -3.30363 794 -41 c 0,102,103 + 804 -93.9999 804 -93.9999 890 -68 c 0,104,105 + 866.618 -120.33 866.618 -120.33 733.273 -120.517 c 0,106,107 + 685.65 -120.584 685.65 -120.584 624 -114 c 0,108,109 + 418 -91.9999 418 -91.9999 394 -45 c 0,110,111 + 625.996 -66.7838 625.996 -66.7838 714 75 c 0,112,113 + 722.786 89.1553 722.786 89.1553 723.001 101.566 c 0,114,115 + 719.591 117.104 l 0,116,117 + 716.737 123.045 716.737 123.045 711.5 128.5 c 0,118,119 + 701.576 138.839 701.576 138.839 689.308 138.97 c 0,120,121 + 680.36 139.067 680.36 139.067 670.166 133.733 c 0,122,123 + 660.629 128.743 660.629 128.743 650 119 c 0,124,125 + 652 165 652 165 701.5 187.5 c 0,126,127 + 780.66 223.482 780.66 223.482 796 242.5 c 0,128,129 + 815.469 266.638 815.469 266.638 819 351 c 0,130,131 + 816.128 388.012 l 0,132,133 + 807.98 434.589 807.98 434.589 777.5 498.5 c 0,134,135 + 759.191 536.891 759.191 536.891 723 585 c 0,136,137 + 680.348 641.698 680.348 641.698 644 645 c 0,138,139 + 628.856 642.918 l 0,140,141 + 618.212 638.877 618.212 638.877 608.5 627.5 c 0,142,143 + 590 608 590 608 613 579 c 0,144,145 + 588.638 580.55 l 0,146,147 + 552.063 589.3 552.063 589.3 534.5 638.5 c 0,148,149 + 513.743 696.65 513.743 696.65 469 735 c 0,150,151 + 474.064 740.88 474.064 740.88 406 801.5 c 0,152,153 + 386.095 819.228 386.095 819.228 385.923 839.472 c 0,154,155 + 385.827 850.808 385.827 850.808 393 865 c 0,156,157 + 399.384 832.1 399.384 832.1 431.868 831.868 c 0,158,159 + 445.55 831.771 445.55 831.771 463.862 837.468 c 0,160,161 + 478.251 841.945 478.251 841.945 495.5 850 c 0,162,163 + 592 896 592 896 607 919 c 0,164,165 + 617.211 934.495 617.211 934.495 618 948.5 c 0,166,167 + 620 984 620 984 578 969 c 0,168,169 + 582.733 1004.49 582.733 1004.49 686.5 1026 c 0,170,171 + 737.466 1036.56 737.466 1036.56 755 1073.5 c 0,172,173 + 768.109 1101.59 768.109 1101.59 768.067 1145.9 c 0,174,175 + 768.064 1148.91 768.064 1148.91 768 1152 c 0,176,177 + 766.896 1205.52 766.896 1205.52 759 1212.5 c 0,178,179 + 725 1242.5 725 1242.5 722 1197.5 c 0,180,181 + 679.373 1223.49 679.373 1223.49 678.841 1259.22 c 0,182,183 + 682.49 1282.11 l 0,184,185 + 684.128 1287.22 684.128 1287.22 686.5 1292.5 c 0,186,187 + 693.835 1309.57 693.835 1309.57 693.858 1326.34 c 0,188,189 + 693.884 1345.87 693.884 1345.87 684 1365 c 0,190,191 + 659.831 1408.89 659.831 1408.89 558 1389 c 0,192,193 + 488.278 1375.38 488.278 1375.38 467 1359 c 0,194,195 + 440.515 1338.04 440.515 1338.04 416.774 1338.07 c 0,196,197 + 397.482 1338.1 397.482 1338.1 380 1352 c 0,198,199 + 415.734 1352 415.734 1352 427 1363 c 0,200,201 + 436.501 1372.28 436.501 1372.28 436.539 1387.56 c 0,202,203 + 436.555 1393.78 436.555 1393.78 435 1401 c 0,204,205 + 428.085 1432.13 428.085 1432.13 417 1435 c 0,206,207 + 398.473 1439.81 398.473 1439.81 384.817 1439.86 c 0,208,209 + 366.071 1439.92 366.071 1439.92 356.5 1431 c 0,210,211 + 277.822 1354.86 277.822 1354.86 302 1306.5 c 0,212,213 + 328.119 1254.26 328.119 1254.26 328.201 1225.13 c 0,214,215 + 328.269 1201.37 328.269 1201.37 311 1193 c 0,216,217 + 311 1216.07 311 1216.07 295.615 1216.67 c 0,218,219 + 285 1215 l 0,220,221 + 255.639 1204.93 255.639 1204.93 255.571 1140.69 c 0,222,223 + 255.562 1132.76 255.562 1132.76 256 1124 c 0,224,225 + 259.68 1050.41 259.68 1050.41 271 1033 c 0,226,227 + 286.562 1010.12 286.562 1010.12 302.5 1009.5 c 0,228,229 + 323.004 1009.7 323.004 1009.7 328 1038 c 0,230,231 + 355 996 355 996 330.5 920.5 c 0,232,233 + 306.001 845.001 306.001 845.001 302 807 c 0,234,235 + 299.425 755.455 l 0,236,237 + 301.69 689.489 301.69 689.489 338 668 c 0,238,239 + 387 639 387 639 360 579 c 0,240,241 + 355.031 622.897 355.031 622.897 321.24 623.294 c 0,242,243 + 315.096 623.366 315.096 623.366 308 622 c 0,244,245 + 271.879 615.048 271.879 615.048 266.5 483.5 c 0,246,247 + 266.151 393.507 l 0,248,249 + 268.939 337.887 268.939 337.887 281 321 c 0,250,251 + 294.707 301.81 294.707 301.81 317 304.5 c 0,252,253 + 343.999 307.999 343.999 307.999 348 349 c 0,254,255 + 378 316 378 316 352.5 227 c 0,256,257 + 323.944 127.336 323.944 127.336 291 51 c 0,258,259 + 272.96 9.19997 272.96 9.19997 272.925 -44.2157 c 0,260,261 + 272.88 -112.2 272.88 -112.2 302 -199 c 0,262,263 + 328 -276.499 328 -276.499 328 -326.999 c 0,264,265 + 328 -376.818 328 -376.818 302 -401 c 0,266,267 + 302.608 -376.581 l 0,268,269 + 298.602 -349.953 298.602 -349.953 272.5 -332.5 c 0,270,271 + 242.027 -312.125 242.027 -312.125 218 -312 c 0,272,273 + 175.052 -314.051 175.052 -314.051 141 -347.5 c 0,274,275 + 121.999 -366 121.999 -366 105 -421 c 0,276,277 + 92 -461 92 -461 89.5 -519 c 0,278,279 + 86.9999 -577 86.9999 -577 94 -622 c 0,280,281 + 74.9999 -568 74.9999 -568 61 -503 c 0,282,283 + 47.9576 -442.447 47.9576 -442.447 55 -368 c 0,284,285 + 62 -294 62 -294 91 -142.5 c 0,286,287 + 119.999 9 119.999 9 81 94 c 0,288,289 + 63.9996 128.001 63.9996 128.001 48 196.5 c 0,290,291 + 41.9721 222.307 41.9721 222.307 42.0474 243.927 c 0,292,293 + 42.1721 279.693 42.1721 279.693 59 304 c 0,294,295 + 56.1273 271.443 56.1273 271.443 79 271 c 0,296,297 + 95.4265 270.777 95.4265 270.777 110 288 c 0,298,299 + 130.215 313.73 130.215 313.73 136 360 c 0,300,301 + 140.9 399.204 140.9 399.204 127 465 c 0,302,303 + 121.971 496.186 121.971 496.186 101 501 c 0,304,305 + 51.9536 514 51.9536 514 58 450 c 0,306,307 + 42.0932 466.57 42.0932 466.57 42.0707 502.115 c 0,308,309 + 42.0269 571.209 42.0269 571.209 102 712 c 0,310,311 + 118.001 749.562 118.001 749.562 118 967 c 0,0,1 +EndSplineSet +KernsSLIF: 116 -195 0 0 84 -313 0 0 +EndChar +StartChar: adieresis +Encoding: 228 228 76 +Width: 1332 +Flags: HW +Fore +108.8 -261.8 m 1,0,1 + 28.0497 -147.901 28.0497 -147.901 17.4248 -43.3496 c 0,2,3 + 6.79985 61.2002 6.79985 61.2002 31.875 156.825 c 0,4,5 + 56.9505 252.451 56.9505 252.451 100.725 339.575 c 0,6,7 + 144.501 426.702 144.501 426.702 172.55 505.75 c 0,8,9 + 190.4 555.899 190.4 555.899 192.95 647.275 c 0,10,11 + 195.5 738.65 195.5 738.65 204.425 831.725 c 0,12,13 + 213.35 924.8 213.35 924.8 240.125 1000.45 c 0,14,15 + 266.904 1076.11 266.904 1076.11 334.9 1095.65 c 0,16,17 + 270.299 1031.9 270.299 1031.9 308.125 983.45 c 0,18,19 + 322.192 966.021 322.192 966.021 352.75 975.8 c 0,20,21 + 375.215 982.988 375.215 982.988 396.1 1090.55 c 0,22,23 + 413.098 1178.1 413.098 1178.1 495.975 1300.92 c 0,24,25 + 576.726 1421.98 576.726 1421.98 642.175 1473.47 c 0,26,27 + 684.84 1507.04 684.84 1507.04 731.145 1506.95 c 0,28,29 + 775.711 1506.86 775.711 1506.86 823.65 1475.6 c 0,30,31 + 791.682 1476.23 l 0,32,33 + 734.526 1470.01 734.526 1470.01 723.35 1405.05 c 0,34,35 + 720.073 1363.06 l 0,36,37 + 720.858 1302.78 720.858 1302.78 752.25 1237.17 c 0,38,39 + 794.078 1149.77 794.078 1149.77 821.1 1152.6 c 0,40,41 + 853.4 1156.01 853.4 1156.01 855.95 1172.58 c 0,42,43 + 856.239 1189.56 l 0,44,45 + 852.29 1209.9 852.29 1209.9 827.9 1230.8 c 0,46,47 + 926.311 1212.47 926.311 1212.47 926.925 1115.62 c 0,48,49 + 926.826 1076.61 926.826 1076.61 946.613 970.938 c 0,50,51 + 951.299 945.912 951.299 945.912 957.1 917.15 c 0,52,53 + 977.5 815.151 977.5 815.151 993.225 781.575 c 0,54,55 + 1005.77 754.812 1005.77 754.812 1024.74 754.627 c 0,56,57 + 1030.95 754.566 1030.95 754.566 1037.85 757.35 c 0,58,59 + 1078.88 773.9 1078.88 773.9 1071 821.1 c 0,60,61 + 1060.8 882.3 1060.8 882.3 1027.65 920.55 c 0,62,63 + 1101.6 875.501 1101.6 875.501 1122.42 816.85 c 0,64,65 + 1139.96 767.482 1139.96 767.482 1140.01 715.971 c 0,66,67 + 1140.02 706.31 1140.02 706.31 1139.42 696.575 c 0,68,69 + 1135.59 634.892 1135.59 634.892 1122 577.15 c 0,70,71 + 1112.87 538.38 1112.87 538.38 1112.93 506.472 c 0,72,73 + 1112.96 490.835 1112.96 490.835 1115.2 476.85 c 0,74,75 + 1127.95 388.465 1127.95 388.465 1167.9 300.05 c 0,76,77 + 1207.87 211.588 1207.87 211.588 1235.47 116.45 c 0,78,79 + 1259.51 33.6266 1259.51 33.6266 1259.42 -56.6199 c 0,80,81 + 1258.85 -83.7246 l 0,82,83 + 1254.61 -188.683 1254.61 -188.683 1178.95 -311.1 c 0,84,85 + 1203.42 -228.959 1203.42 -228.959 1203.33 -128.066 c 0,86,87 + 1203.3 -81.7345 1203.3 -81.7345 1198.08 -31.4502 c 0,88,89 + 1181.92 124.337 1181.92 124.337 1072.39 125.071 c 0,90,91 + 1068.77 125.095 1068.77 125.095 1065.05 124.95 c 0,92,93 + 1000.37 122.43 1000.37 122.43 980.05 67.5752 c 0,94,95 + 960.501 12.75 960.501 12.75 982.6 -62.0498 c 0,96,97 + 884.849 -3.4004 884.849 -3.4004 916.3 144.5 c 0,98,99 + 946.219 285.196 946.219 285.196 946.137 381.283 c 0,100,101 + 946.133 386.201 946.133 386.201 946.05 391 c 0,102,103 + 944.351 498.949 944.351 498.949 875.5 540.6 c 0,104,105 + 806.65 582.25 806.65 582.25 727.6 566.95 c 0,106,107 + 640.877 549.399 640.877 549.399 612.425 503.2 c 0,108,109 + 572.61 440.3 572.61 440.3 516.8 440.3 c 0,110,111 + 470.899 440.3 470.899 440.3 448.8 456.45 c 0,112,113 + 542.639 460.64 542.639 460.64 532.1 525.3 c 0,114,115 + 524.543 571.665 524.543 571.665 483.418 573.028 c 0,116,117 + 458.15 570.35 l 0,118,119 + 400.326 557.651 400.326 557.651 371.875 521.9 c 0,120,121 + 323.851 461.552 323.851 461.552 310.25 374.85 c 0,122,123 + 300.338 313.888 300.338 313.888 300.395 241.659 c 0,124,125 + 300.436 190.01 300.436 190.01 305.575 132.6 c 0,126,127 + 317.9 -5.09955 317.9 -5.09955 222.7 -57.7998 c 0,128,129 + 261.896 26.0049 261.896 26.0049 232.9 78.2002 c 0,130,131 + 216.34 108.009 216.34 108.009 155.55 107.95 c 0,132,133 + 128.74 104.737 l 0,134,135 + 67.7534 88.1114 67.7534 88.1114 67.1504 -14.4502 c 0,136,137 + 66.2997 -158.949 66.2997 -158.949 108.8 -261.8 c 1,0,1 +479.4 838.95 m 0,77,78 + 479.4 776.051 479.4 776.051 537.625 746.725 c 0,79,80 + 595.851 717.4 595.851 717.4 665.125 713.575 c 0,81,82 + 724.336 714 l 0,83,84 + 762.062 717.024 762.062 717.024 790.925 727.6 c 0,85,86 + 843.456 746.848 843.456 746.848 844.05 776.9 c 0,87,88 + 839.707 824.116 839.707 824.116 756.075 888.25 c 0,89,90 + 707.698 925.347 707.698 925.347 707.663 963.627 c 0,91,92 + 707.638 990.253 707.638 990.253 731 1017.45 c 0,93,94 + 730.287 989.406 l 0,95,96 + 733.091 969.257 733.091 969.257 748.499 968.932 c 0,97,98 + 759.475 970.7 l 0,99,100 + 781.225 977.353 781.225 977.353 781.56 996.947 c 0,101,102 + 777.499 1017.28 l 0,103,104 + 775.544 1022.6 775.544 1022.6 772.65 1028.5 c 0,105,106 + 748.854 1074.39 748.854 1074.39 692.75 1128.8 c 0,107,108 + 652.395 1167.94 652.395 1167.94 622.154 1168.36 c 0,109,110 + 604.83 1165.09 l 0,111,112 + 602.425 1164.1 602.425 1164.1 600.1 1162.8 c 0,113,114 + 564.525 1142.79 564.525 1142.79 564.17 1110.18 c 0,115,116 + 564.118 1105.39 564.118 1105.39 564.825 1100.33 c 0,117,118 + 570.349 1060.81 570.349 1060.81 585.65 1016.6 c 0,119,120 + 600.95 972.4 600.95 972.4 607.325 930.325 c 0,121,122 + 613.7 888.25 613.7 888.25 575.45 860.2 c 0,123,124 + 593.3 928.2 593.3 928.2 524.45 916.3 c 0,125,126 + 479.456 909.755 479.456 909.755 479.4 838.95 c 0,77,78 +432.65 1542.75 m 1,99,100 + 414.656 1587.74 414.656 1587.74 414.559 1630.56 c 0,101,102 + 414.46 1674.09 414.46 1674.09 432.846 1715.39 c 0,103,104 + 442.516 1737.11 442.516 1737.11 457.3 1758.22 c 0,105,106 + 522.348 1851.09 522.348 1851.09 619.897 1851.11 c 0,107,108 + 628.156 1851.11 628.156 1851.11 636.65 1850.45 c 0,109,110 + 525.809 1786.57 525.809 1786.57 525.449 1734.18 c 0,111,112 + 525.411 1728.72 525.411 1728.72 526.575 1723.38 c 0,113,114 + 533.582 1691.24 533.582 1691.24 572.317 1691.11 c 0,115,116 + 601.716 1691.01 601.716 1691.01 649.4 1709.35 c 0,117,118 + 633.251 1648.15 633.251 1648.15 549.525 1626.9 c 0,119,120 + 465.8 1605.65 465.8 1605.65 432.65 1542.75 c 1,99,100 +918.85 1540.2 m 1,108,109 + 915.999 1568.74 l 0,110,111 + 917.542 1625.56 917.542 1625.56 969 1714.45 c 0,112,113 + 1028.97 1818.05 1028.97 1818.05 1119.65 1818.14 c 0,114,115 + 1127.92 1818.15 1127.92 1818.15 1136.45 1817.3 c 0,116,117 + 1089.98 1774.77 1089.98 1774.77 1089.85 1729.33 c 0,118,119 + 1089.84 1725.72 1089.84 1725.72 1090.12 1722.1 c 0,120,121 + 1092.3 1693.97 1092.3 1693.97 1128.39 1694.07 c 0,122,123 + 1155.54 1694.14 1155.54 1694.14 1201.9 1710.2 c 0,124,125 + 1154.31 1638.8 1154.31 1638.8 1074.83 1623.5 c 0,126,127 + 995.359 1608.2 995.359 1608.2 918.85 1540.2 c 1,108,109 +EndSplineSet +EndChar +StartChar: oacute +Encoding: 243 243 46 +Width: 1230 +Flags: HW +Fore +601 -2 m 0,0,1 + 510 5.99999 510 5.99999 424.5 82 c 0,2,3 + 338.998 158.003 338.998 158.003 273 246 c 0,4,5 + 207.001 333.999 207.001 333.999 167 406 c 0,6,7 + 127 477.999 127 477.999 127 480 c 0,8,9 + 113.001 520 113.001 520 83 584.5 c 0,10,11 + 53 649 53 649 33.5 714.5 c 0,12,13 + 14 780 14 780 18 835.5 c 0,14,15 + 22 891 22 891 77 915 c 0,16,17 + 106 927 106 927 133 912 c 0,18,19 + 80.6363 893.182 80.6363 893.182 80.1529 846.248 c 0,20,21 + 82.5 824 l 0,22,23 + 96 759 96 759 127 792 c 0,24,25 + 162.002 830.002 162.002 830.002 213.5 937.5 c 0,26,27 + 243.557 1000.24 243.557 1000.24 243.809 1035.56 c 0,28,29 + 243.905 1049 243.905 1049 239.684 1058.47 c 0,30,31 + 235.993 1066.76 235.993 1066.76 229 1072 c 0,32,33 + 217.589 1079.95 217.589 1079.95 207.672 1079.89 c 0,34,35 + 188.912 1079.78 188.912 1079.78 175.5 1051 c 0,36,37 + 166.787 1032.3 166.787 1032.3 166.655 1015.05 c 0,38,39 + 166.556 1002.3 166.556 1002.3 171.139 990.344 c 0,40,41 + 174.951 980.399 174.951 980.399 182 971 c 0,42,43 + 126.43 1007.77 126.43 1007.77 126.29 1046.55 c 0,44,45 + 126.258 1055.23 126.258 1055.23 129 1064 c 0,46,47 + 143.998 1111.99 143.998 1111.99 193.5 1153.5 c 0,48,49 + 242.971 1194.98 242.971 1194.98 302.5 1224.5 c 0,50,51 + 362 1254.01 362 1254.01 383 1262 c 0,52,53 + 421.942 1276.98 421.942 1276.98 510 1303.5 c 0,54,55 + 598 1330.01 598 1330.01 568 1377 c 0,56,57 + 553.93 1398.1 553.93 1398.1 536.426 1398.25 c 0,58,59 + 524.536 1398.34 524.536 1398.34 510 1388 c 0,60,61 + 476 1362.99 476 1362.99 465 1337 c 0,62,63 + 458.647 1342.82 458.647 1342.82 458.741 1354.39 c 0,64,65 + 458.824 1364.68 458.824 1364.68 464 1379.5 c 0,66,67 + 475.002 1411.01 475.002 1411.01 484 1419 c 0,68,69 + 541 1468.99 541 1468.99 614 1444.5 c 0,70,71 + 686.989 1420.01 686.989 1420.01 760.5 1361.5 c 0,72,73 + 834 1303 834 1303 902 1231 c 0,74,75 + 970.031 1158.97 970.031 1158.97 1019 1115 c 0,76,77 + 1028.75 1105.97 1028.75 1105.97 1036.15 1105.75 c 0,78,79 + 1043.94 1108.44 l 0,80,81 + 1051.13 1114.23 1051.13 1114.23 1055 1132.5 c 0,82,83 + 1055.19 1151.12 l 0,84,85 + 1048.84 1183.02 1048.84 1183.02 996 1211 c 0,86,87 + 1116 1211 1116 1211 1133.5 1103.5 c 0,88,89 + 1140.87 1058.24 1140.87 1058.24 1140.79 1007.3 c 0,90,91 + 1140.68 937.275 1140.68 937.275 1126.5 856.5 c 0,92,93 + 1102.01 717.049 1102.01 717.049 1064.5 581.5 c 0,94,95 + 1035.57 476.98 1035.57 476.98 1035.51 419.158 c 0,96,97 + 1035.49 402.028 1035.49 402.028 1038 389 c 0,98,99 + 1039.99 374 1039.99 374 1060.5 374.5 c 0,100,101 + 1080.99 374.999 1080.99 374.999 1094 390 c 0,102,103 + 1119.37 418.072 1119.37 418.072 1119.68 448.764 c 0,104,105 + 1115.99 473.526 l 0,106,107 + 1111.6 487.99 1111.6 487.99 1102 503 c 0,108,109 + 1150 489 1150 489 1159 437 c 0,110,111 + 1161.09 395.311 l 0,112,113 + 1158.04 329.427 1158.04 329.427 1111.5 287.5 c 0,114,115 + 1051.01 233.004 1051.01 233.004 960.5 202.5 c 0,116,117 + 869.996 171.999 869.996 171.999 772.5 158 c 0,118,119 + 675.01 144.002 675.01 144.002 616 130 c 0,120,121 + 570 119.001 570 119.001 607 72.5 c 0,122,123 + 620.616 55.388 620.616 55.388 641.139 55.4071 c 0,124,125 + 676.384 55.44 676.384 55.44 732 106 c 0,126,127 + 721 61 721 61 682 28 c 0,128,129 + 643 -5 643 -5 601 -2 c 0,0,1 +454 901 m 0,66,67 + 416 871 416 871 387 867.5 c 0,68,69 + 358 864 358 864 331 870 c 0,70,71 + 419.739 899.849 419.739 899.849 419.97 958.983 c 0,72,73 + 420.025 973.151 420.025 973.151 415 989 c 0,74,75 + 411.054 1000.84 411.054 1000.84 395.575 1001.15 c 0,76,77 + 391.448 1001.24 391.448 1001.24 386.5 1000.5 c 0,78,79 + 363 997 363 997 352 987 c 0,80,81 + 286 924 286 924 237 767 c 0,82,83 + 217.135 703.352 217.135 703.352 217.157 660.905 c 0,84,85 + 217.189 598.649 217.189 598.649 260 582 c 0,86,87 + 350 546 350 546 334.5 610.5 c 0,88,89 + 319 675 319 675 273 684 c 0,90,91 + 318 702 318 702 358.5 663 c 0,92,93 + 399 624 399 624 426.5 566 c 0,94,95 + 454 508 454 508 464 449.5 c 0,96,97 + 474 391 474 391 459 371 c 0,98,99 + 458 408 458 408 432.5 424 c 0,100,101 + 407 440 407 440 385 413 c 0,102,103 + 356.738 379.691 356.738 379.691 356.366 352.75 c 0,104,105 + 359.552 334.59 l 0,106,107 + 365.495 319.032 365.495 319.032 382.5 306 c 0,108,109 + 436 265 436 265 529 259 c 0,110,111 + 622 253 622 253 720 287 c 0,112,113 + 818 321.001 818 321.001 851 406 c 0,114,115 + 877 475 877 475 812 486.5 c 0,116,117 + 790.15 486.903 l 0,118,119 + 759.741 481.142 759.741 481.142 759.84 434.141 c 0,120,121 + 759.871 419.164 759.871 419.164 763 400 c 0,122,123 + 731.127 447.81 731.127 447.81 730.967 483.991 c 0,124,125 + 730.869 506.399 730.869 506.399 742.934 524.347 c 0,126,127 + 749.283 533.791 749.283 533.791 759 542 c 0,128,129 + 817 591 817 591 883 657 c 0,130,131 + 988 759 988 759 973 883 c 0,132,133 + 958.001 1006.99 958.001 1006.99 850 1107 c 0,134,135 + 778.288 1172.36 778.288 1172.36 729.654 1172.62 c 0,136,137 + 724.708 1172.65 724.708 1172.65 720 1172 c 0,138,139 + 668.989 1164.99 668.989 1164.99 628 1119 c 0,140,141 + 586.987 1072.98 586.987 1072.98 547.5 1008.5 c 0,142,143 + 508 944 508 944 454 901 c 0,66,67 +713 1513 m 1,107,108 + 659.89 1575.91 659.89 1575.91 659.855 1645.51 c 0,109,110 + 659.847 1661.09 659.847 1661.09 662.5 1677 c 0,111,112 + 677 1764 677 1764 735 1823.5 c 0,113,114 + 793 1883.01 793 1883.01 876 1897 c 0,115,116 + 911.02 1899.19 l 0,117,118 + 974.217 1896.21 974.217 1896.21 1030 1842 c 0,119,120 + 976.262 1882.84 976.262 1882.84 932.539 1883.13 c 0,121,122 + 917.33 1883.23 917.33 1883.23 903.333 1878.42 c 0,123,124 + 901.405 1877.76 901.405 1877.76 899.5 1877 c 0,125,126 + 843.996 1854.99 843.996 1854.99 817 1810 c 0,127,128 + 795.751 1774.59 795.751 1774.59 795.56 1742.58 c 0,129,130 + 795.509 1733.91 795.509 1733.91 797 1725.5 c 0,131,132 + 804 1686.01 804 1686.01 854 1709 c 0,133,134 + 864.909 1713.36 864.909 1713.36 865.107 1729.33 c 0,135,136 + 860.634 1755.7 l 0,137,138 + 859.468 1759.69 859.468 1759.69 858 1764 c 0,139,140 + 887.56 1724.58 887.56 1724.58 888.396 1699.82 c 0,141,142 + 886 1685.5 l 0,143,144 + 875.003 1659 875.003 1659 842 1638 c 0,145,-1 + 769.5 1591 l 0,146,147 + 729.999 1565 729.999 1565 713 1513 c 1,107,108 +EndSplineSet +KernsSLIF: 116 -234 0 0 119 -156 0 0 +EndChar +StartChar: odieresis +Encoding: 246 246 80 +Width: 1378 +Flags: HW +Fore +916.3 -9.34961 m 0,0,1 + 904.401 0.849471 904.401 0.849471 827.475 9.77539 c 0,2,3 + 750.552 18.7001 750.552 18.7001 661.3 20.4004 c 0,4,5 + 572.05 22.0996 572.05 22.0996 497.675 12.75 c 0,6,7 + 424.255 3.52052 424.255 3.52052 417.35 -22.9502 c 0,8,9 + 412.25 -42.5 412.25 -42.5 431.375 -63.75 c 0,10,11 + 450.5 -85.0001 450.5 -85.0001 522.75 -110.5 c 0,12,13 + 475.333 -112.195 l 0,14,15 + 420.862 -109.586 420.862 -109.586 368.05 -85.8496 c 0,16,17 + 276.266 -44.5988 276.266 -44.5988 255 19.5498 c 0,18,19 + 204.001 173.398 204.001 173.398 189.125 245.65 c 0,20,21 + 162.128 409.363 162.128 409.363 149.6 435.2 c 0,22,23 + 108.8 519.35 108.8 519.35 37.8252 640.475 c 0,24,25 + -33.1504 761.6 -33.1504 761.6 36.5498 881.45 c 0,26,27 + 36.886 828.045 l 0,28,29 + 40.8577 786.531 40.8577 786.531 58.6504 779.025 c 0,30,31 + 85.8496 767.55 85.8496 767.55 112.2 782.85 c 0,32,33 + 140.25 799.849 140.25 799.849 192.95 932.875 c 0,34,35 + 245.705 1066.04 245.705 1066.04 260.1 1105 c 0,36,37 + 272.902 1140.56 272.902 1140.56 273.054 1164.26 c 0,38,39 + 273.151 1179.36 273.151 1179.36 268.108 1189.64 c 0,40,41 + 266.18 1193.57 266.18 1193.57 263.5 1196.8 c 0,42,43 + 246.17 1217.66 246.17 1217.66 223.104 1217.78 c 0,44,45 + 203.924 1217.88 203.924 1217.88 180.779 1203.64 c 0,46,47 + 164.853 1193.84 164.853 1193.84 147.05 1177.25 c 0,48,49 + 155.55 1236.75 155.55 1236.75 191.25 1267.35 c 0,50,51 + 240.928 1307.83 240.928 1307.83 316.625 1311.55 c 0,52,53 + 349.497 1313.73 349.497 1313.73 464.1 1366.38 c 0,54,55 + 514.772 1389.7 514.772 1389.7 599.25 1390.6 c 0,56,57 + 679.152 1391.46 679.152 1391.46 691.05 1429.7 c 0,58,59 + 707.201 1484.1 707.201 1484.1 606.9 1501.1 c 0,60,61 + 667.25 1526.6 667.25 1526.6 725.9 1493.03 c 0,62,63 + 784.558 1459.44 784.558 1459.44 837.675 1400.8 c 0,64,65 + 890.8 1342.15 890.8 1342.15 935.85 1275.85 c 0,66,67 + 980.915 1209.53 980.915 1209.53 1014.05 1169.6 c 0,68,69 + 1070.16 1100.74 1070.16 1100.74 1186.17 1027.22 c 0,70,71 + 1302.19 953.7 1302.19 953.7 1313.25 811.75 c 0,72,73 + 1269.97 876.665 1269.97 876.665 1238.32 877.009 c 0,74,75 + 1232.68 877.07 1232.68 877.07 1227.4 875.075 c 0,76,77 + 1192.54 861.896 1192.54 861.896 1185.75 839.8 c 0,78,79 + 1163.33 768.803 1163.33 768.803 1163.37 705.357 c 0,80,81 + 1163.39 667.767 1163.39 667.767 1171.3 632.825 c 0,82,83 + 1201.41 499.741 1201.41 499.741 1221.45 461.975 c 0,84,85 + 1262.25 385.05 1262.25 385.05 1262.67 324.275 c 0,86,87 + 1260.17 287.831 l 0,88,89 + 1252.31 244.712 1252.31 244.712 1220.6 218.45 c 0,90,91 + 1236.76 300.05 1236.76 300.05 1215.92 328.525 c 0,92,93 + 1200.89 349.086 1200.89 349.086 1179.42 349.482 c 0,94,95 + 1161.95 346.8 l 0,96,97 + 1140.7 340.002 1140.7 340.002 1114.78 255.85 c 0,98,99 + 1088.84 171.7 1088.84 171.7 1054 79.4746 c 0,100,101 + 1010.71 -35.0859 1010.71 -35.0859 973.25 -78.2002 c 0,102,103 + 939.558 -116.979 939.558 -116.979 896.355 -117.246 c 0,104,105 + 881.793 -117.336 881.793 -117.336 866.15 -113.05 c 0,106,107 + 927.35 -99.4494 927.35 -99.4494 935 -66.7246 c 0,108,109 + 936.469 -44.7745 l 0,110,111 + 934.018 -24.5366 934.018 -24.5366 916.3 -9.34961 c 0,0,1 +548.25 165.75 m 0,62,63 + 648.347 160.761 648.347 160.761 687.225 228.225 c 0,64,65 + 752.25 339.15 752.25 339.15 846.6 298.35 c 0,66,67 + 772.919 282.561 772.919 282.561 805.8 221.85 c 0,68,69 + 821.369 193.105 821.369 193.105 879.75 196.35 c 0,70,71 + 927.179 198.985 927.179 198.985 967.3 279.225 c 0,72,73 + 1028.91 402.453 1028.91 402.453 1035.3 477.275 c 0,74,75 + 1041.05 544.612 1041.05 544.612 1040.99 604.498 c 0,76,77 + 1040.95 650.853 1040.95 650.853 1037.42 692.75 c 0,78,79 + 1025.49 814.679 1025.49 814.679 1014.05 837.25 c 0,80,81 + 998.48 867.665 998.48 867.665 960.5 858.925 c 0,82,83 + 922.666 850.974 922.666 850.974 922.325 821.624 c 0,84,85 + 926.362 799.386 l 0,86,87 + 928.982 791.603 928.982 791.603 933.3 782.85 c 0,88,89 + 865.909 816.107 865.909 816.107 856.8 879.75 c 0,90,91 + 857.365 893.879 857.365 893.879 864.025 1017.45 c 0,92,93 + 866.867 1077.89 866.867 1077.89 816.85 1152.6 c 0,94,95 + 793.608 1187.32 793.608 1187.32 673.2 1206.15 c 0,96,97 + 610.858 1215.9 610.858 1215.9 559.725 1162.38 c 0,98,99 + 485.058 1084.22 485.058 1084.22 482.8 1047.62 c 0,100,101 + 470.41 846.737 470.41 846.737 466.65 833.85 c 0,102,103 + 438.003 730.523 438.003 730.523 376.125 696.15 c 0,104,105 + 413.458 804.286 413.458 804.286 308.55 806.225 c 0,106,107 + 294.277 803.159 l 0,108,109 + 265.044 788.558 265.044 788.558 265.122 704.552 c 0,110,111 + 265.126 700.434 265.126 700.434 265.2 696.15 c 0,112,113 + 267.169 582.489 267.169 582.489 270.3 545.7 c 0,114,115 + 278.711 437.373 278.711 437.373 317.9 362.95 c 0,116,117 + 383.163 239.008 383.163 239.008 415.65 211.65 c 0,118,119 + 465.243 169.889 465.243 169.889 548.25 165.75 c 0,62,63 +246.5 1577.6 m 1,94,95 + 249.901 1651.55 249.901 1651.55 309.825 1761.62 c 0,96,97 + 369.744 1871.69 369.744 1871.69 447.1 1885.3 c 0,98,99 + 396.908 1790.71 396.908 1790.71 396.892 1749.7 c 0,100,101 + 396.887 1736.54 396.887 1736.54 402.05 1728.9 c 0,102,103 + 423.294 1697.46 423.294 1697.46 495.55 1694.05 c 0,104,105 + 486.201 1651.56 486.201 1651.56 386.75 1627.33 c 0,106,107 + 287.314 1603.11 287.314 1603.11 246.5 1577.6 c 1,94,95 +893.35 1595.45 m 1,103,104 + 903.551 1664.31 903.551 1664.31 973.25 1742.08 c 0,105,106 + 1042.95 1819.85 1042.95 1819.85 1127.1 1840.25 c 0,107,108 + 1070.15 1784.15 1070.15 1784.15 1058.67 1730.6 c 0,109,110 + 1047.2 1677.05 1047.2 1677.05 1144.95 1651.55 c 0,111,112 + 1114.52 1627.53 1114.52 1627.53 1076.72 1627.48 c 0,113,114 + 1054.33 1627.45 1054.33 1627.45 1029.35 1635.83 c 0,115,116 + 962.2 1658.34 962.2 1658.34 893.35 1595.45 c 1,103,104 +EndSplineSet +EndChar +StartChar: udieresis +Encoding: 252 252 78 +Width: 1329 +Flags: HW +Fore +794.325 -23.7998 m 128,-1,0 + 803.25 -76.5 803.25 -76.5 892.5 -42.5 c 0,1,2 + 855.06 -101.644 855.06 -101.644 793.666 -101.642 c 0,3,4 + 760.689 -101.641 760.689 -101.641 720.8 -84.5752 c 0,5,6 + 696.261 -74.0762 696.261 -74.0762 517.65 -45.9004 c 0,7,-1 + 378.25 -22.0996 l 0,8,9 + 345.296 -18.8683 l 0,10,11 + 274.509 -2.90244 274.509 -2.90244 270.3 91.7998 c 0,12,13 + 314.873 54.6553 314.873 54.6553 347.225 95.2002 c 0,14,15 + 354.846 104.75 354.846 104.75 354.974 117.666 c 0,16,17 + 355.071 127.561 355.071 127.561 350.77 139.432 c 0,18,19 + 349.425 143.144 349.425 143.144 347.65 147.05 c 0,20,21 + 330.805 184.111 330.805 184.111 303.45 214.2 c 0,22,-1 + 260.95 260.95 l 0,23,24 + 240.668 281.956 240.668 281.956 208.25 264.775 c 0,25,26 + 181.797 251.548 181.797 251.548 181.721 228.796 c 0,27,28 + 181.667 212.801 181.667 212.801 194.65 192.1 c 0,29,30 + 140.102 203.838 140.102 203.838 139.64 265.025 c 0,31,32 + 139.541 278.203 139.541 278.203 141.95 293.675 c 0,33,34 + 145.373 341.637 l 0,35,36 + 145.028 387.385 145.028 387.385 131.75 438.6 c 0,37,38 + 90.3602 595.881 90.3602 595.881 48.875 652.375 c 0,39,40 + -35.7002 770.099 -35.7002 770.099 23.7998 903.55 c 0,41,42 + 25.5382 842.726 25.5382 842.726 59.0752 842.775 c 0,43,44 + 83.3029 842.811 83.3029 842.811 95.2002 872.95 c 0,45,46 + 107.95 905.249 107.95 905.249 67.5752 1043.38 c 0,47,48 + 27.2001 1181.5 27.2001 1181.5 28.9004 1222.3 c 0,49,50 + 33.1501 1386.34 33.1501 1386.34 136.85 1514.7 c 0,51,52 + 91.8515 1394.07 91.8515 1394.07 107.1 1269.9 c 0,53,54 + 123.35 1137.58 123.35 1137.58 209.95 1122 c 0,55,56 + 232.44 1122.04 l 0,57,58 + 257.102 1125.91 257.102 1125.91 289 1145.38 c 0,59,60 + 346.8 1180.65 346.8 1180.65 364.65 1275.85 c 0,61,62 + 398.65 1192.55 398.65 1192.55 369.325 1117.75 c 0,63,64 + 342.227 1048.63 342.227 1048.63 331.5 950.3 c 0,65,66 + 328.38 887.9 l 0,67,68 + 329.279 834.519 329.279 834.519 343.825 793.9 c 0,69,70 + 350.026 776.584 350.026 776.584 349.946 760.75 c 0,71,72 + 349.736 719.066 349.736 719.066 306 687.65 c 0,73,74 + 316.2 736.1 316.2 736.1 300.9 755.225 c 0,75,76 + 279.454 782.031 279.454 782.031 255 736.1 c 0,77,78 + 239.174 706.375 239.174 706.375 257.55 606.475 c 0,79,80 + 273.701 516.374 273.701 516.374 286.45 482.375 c 0,81,82 + 308.524 420.886 308.524 420.886 339.15 369.75 c 0,83,84 + 394.097 284.896 394.097 284.896 442 244.8 c 0,85,86 + 462.424 235.609 462.424 235.609 476.172 235.462 c 0,87,88 + 485.273 235.364 485.273 235.364 493.85 240.975 c 0,89,90 + 506.463 251.547 506.463 251.547 506.61 266.41 c 0,91,92 + 506.707 276.331 506.707 276.331 501.251 288.163 c 0,93,94 + 496.151 299.222 496.151 299.222 486.2 311.95 c 0,95,96 + 590.019 303.37 590.019 303.37 603.075 206.55 c 0,97,98 + 612.388 136.8 612.388 136.8 659.175 141.525 c 0,99,100 + 717.115 146.564 717.115 146.564 752.25 221.85 c 0,101,102 + 784.79 291.579 784.79 291.579 802.825 357.425 c 0,103,104 + 829.489 454.781 829.489 454.781 833.85 487.05 c 0,105,106 + 846.6 583.95 846.6 583.95 908.65 627.3 c 0,107,108 + 879.354 552.334 879.354 552.334 917.15 531.25 c 0,109,110 + 939.276 518.908 939.276 518.908 963.9 536.35 c 0,111,112 + 984.9 550.75 984.9 550.75 984.935 627.832 c 0,113,114 + 984.95 659.95 984.95 659.95 981.325 702.95 c 0,115,116 + 968.318 857.227 968.318 857.227 953.7 932.45 c 0,117,118 + 933.107 1038.42 933.107 1038.42 918.425 1082.47 c 0,119,120 + 903.528 1127.16 903.528 1127.16 903.575 1169.52 c 0,121,122 + 903.651 1237.13 903.651 1237.13 941.8 1298.8 c 0,123,124 + 950.924 1200.93 950.924 1200.93 999.175 1168.33 c 0,125,126 + 1036.52 1143.09 1036.52 1143.09 1058.89 1143.12 c 0,127,128 + 1069.04 1143.14 1069.04 1143.14 1076.1 1148.35 c 0,129,130 + 1137.78 1196.39 1137.78 1196.39 1154.3 1352.78 c 0,131,132 + 1158.92 1396.53 1158.92 1396.53 1158.83 1436.6 c 0,133,134 + 1158.66 1514.46 1158.66 1514.46 1140.7 1578.45 c 0,135,136 + 1196.81 1484.09 1196.81 1484.09 1211.67 1344.7 c 0,137,138 + 1216.91 1295.64 1216.91 1295.64 1216.83 1248.99 c 0,139,140 + 1216.68 1163.11 1216.68 1163.11 1198.5 1085.45 c 0,141,142 + 1180.94 1010.95 1180.94 1010.95 1181 946.244 c 0,143,144 + 1181.05 895.058 1181.05 895.058 1192.12 850 c 0,145,146 + 1217.2 748 1217.2 748 1176.4 697 c 0,147,148 + 1174.77 723.682 l 0,149,150 + 1170.35 743.741 1170.35 743.741 1155.58 753.95 c 0,151,152 + 1132.2 770.1 1132.2 770.1 1117.75 711.45 c 0,153,154 + 1104.92 658.776 1104.92 658.776 1104.93 595.482 c 0,155,156 + 1104.94 541.33 1104.94 541.33 1114.35 479.4 c 0,157,158 + 1120.07 441.729 1120.07 441.729 1119.98 409.006 c 0,159,160 + 1119.73 325.072 1119.73 325.072 1081.2 273.7 c 0,161,162 + 1081.2 362.144 1081.2 362.144 1044.44 362.661 c 0,163,164 + 1041.28 362.706 1041.28 362.706 1037.85 362.1 c 0,165,166 + 991.308 353.69 991.308 353.69 889.95 186.15 c 0,167,168 + 787.459 16.7373 787.459 16.7373 794.325 -23.7998 c 128,-1,0 +164.9 1655.8 m 1,92,93 + 209.152 1694.99 209.152 1694.99 229.075 1823.67 c 0,94,95 + 244.799 1925.24 244.799 1925.24 341.7 1951.6 c 0,96,97 + 283.098 1886.48 283.098 1886.48 283.104 1833.34 c 0,98,99 + 283.106 1817.11 283.106 1817.11 288.575 1802 c 0,100,101 + 304.802 1754.41 304.802 1754.41 329.579 1754.19 c 0,102,103 + 340.419 1754.09 340.419 1754.09 352.896 1763.06 c 0,104,105 + 368.171 1774.03 368.171 1774.03 385.9 1798.6 c 0,106,107 + 420.75 1747.6 420.75 1747.6 336.175 1679.17 c 0,108,109 + 251.6 1610.76 251.6 1610.76 164.9 1655.8 c 1,92,93 +1014.05 1667.7 m 1,101,102 + 1042.95 1680.45 1042.95 1680.45 1064.2 1727.62 c 0,103,104 + 1085.34 1772.94 1085.34 1772.94 1102.45 1821.12 c 0,105,106 + 1121.99 1868.28 1121.99 1868.28 1148.78 1901.03 c 0,107,108 + 1168 1924.51 1168 1924.51 1197.93 1924.57 c 0,109,110 + 1209.71 1924.6 1209.71 1924.6 1223.15 1921 c 0,111,112 + 1194.86 1907.76 1194.86 1907.76 1173.42 1864.9 c 0,113,114 + 1154.85 1827.74 1154.85 1827.74 1154.87 1783.15 c 0,115,116 + 1154.87 1777.75 1154.87 1777.75 1155.15 1772.25 c 0,117,118 + 1156.92 1752.48 1156.92 1752.48 1192.55 1742.92 c 0,119,120 + 1216.35 1736.55 1216.35 1736.55 1266.5 1760.35 c 0,121,122 + 1225.96 1698.19 1225.96 1698.19 1134.75 1660.47 c 0,123,124 + 1104.12 1647.8 1104.12 1647.8 1076.85 1647.84 c 0,125,126 + 1042.83 1647.88 1042.83 1647.88 1014.05 1667.7 c 1,101,102 +EndSplineSet +EndChar +StartChar: Aogonek +Encoding: 260 260 79 +Width: 1433 +Flags: HW +Fore +1029 333 m 0,0,1 + 1023.7 401.322 1023.7 401.322 971 464 c 0,2,3 + 877 590 877 590 812.5 602.5 c 0,4,5 + 744.95 615.59 744.95 615.59 699 592.5 c 0,6,-1 + 607.5 541.5 l 0,7,8 + 546 534 546 534 522 591 c 0,9,10 + 512.517 613.165 512.517 613.165 518.5 646.5 c 0,11,12 + 521.999 665.998 521.999 665.998 539 687 c 0,13,14 + 554.303 602.429 554.303 602.429 598 660.5 c 0,15,16 + 637.977 713.627 637.977 713.627 580 748 c 0,17,18 + 442.531 829.503 442.531 829.503 400.5 697 c 0,19,20 + 371.001 604.004 371.001 604.004 365.5 479 c 0,21,22 + 359.999 353.995 359.999 353.995 330.5 250 c 0,23,24 + 306.258 164.54 306.258 164.54 200.652 164.16 c 0,25,26 + 177.741 164.078 177.741 164.078 151 168 c 0,27,28 + 207 174 207 174 229.5 192 c 0,29,30 + 253.321 209.628 253.321 209.628 253.516 233.935 c 0,31,32 + 253.613 245.962 253.613 245.962 247.925 259.624 c 0,33,34 + 246.616 262.768 246.616 262.768 245 266 c 0,35,36 + 210.517 328.87 210.517 328.87 161 300.5 c 0,37,38 + 113.001 273.001 113.001 273.001 98.5 206.5 c 0,39,40 + 94.6267 188.736 94.6267 188.736 94.7136 170.045 c 0,41,42 + 94.9521 118.764 94.9521 118.764 125 60.5 c 0,43,44 + 165.999 -18.9998 165.999 -18.9998 307 -62 c 0,45,46 + 102 -62 102 -62 35 76.5 c 0,47,48 + 3.95718 140.67 3.95718 140.67 3.82694 205.378 c 0,49,50 + 3.72716 254.951 3.72716 254.951 21.7708 304.839 c 0,51,52 + 31.0079 330.378 31.0079 330.378 45 356 c 0,53,54 + 110.993 472.988 110.993 472.988 207.5 625.5 c 0,55,56 + 332.475 822.999 332.475 822.999 312 1096 c 0,57,58 + 312.923 1135.59 l 0,59,60 + 320.24 1195.69 320.24 1195.69 363.5 1255.5 c 0,61,62 + 399.342 1306.42 399.342 1306.42 444.631 1306.68 c 0,63,64 + 461.621 1306.78 461.621 1306.78 479.94 1299.75 c 0,65,66 + 494.548 1294.14 494.548 1294.14 510 1284 c 0,67,68 + 479.738 1283.76 l 0,69,70 + 447.266 1279 447.266 1279 427 1253.5 c 0,71,72 + 411.213 1233.8 411.213 1233.8 411.267 1214.56 c 0,73,74 + 411.319 1196.07 411.319 1196.07 426 1178 c 0,75,76 + 442.916 1157.08 442.916 1157.08 460.13 1156.77 c 0,77,78 + 475.394 1160.51 l 0,79,80 + 489.351 1167.58 489.351 1167.58 503.5 1188 c 0,81,82 + 542.995 1244.99 542.995 1244.99 580 1337 c 0,83,84 + 617 1428.99 617 1428.99 648.5 1523 c 0,85,86 + 679.997 1617 679.997 1617 703 1644 c 0,87,88 + 769 1722 769 1722 840 1714.5 c 0,89,90 + 911 1707 911 1707 911 1580 c 0,91,92 + 893.378 1613.83 893.378 1613.83 870.288 1613.88 c 0,93,94 + 860.623 1613.9 860.623 1613.9 850 1608 c 0,95,96 + 821.002 1591.01 821.002 1591.01 809 1529 c 0,97,98 + 800.755 1486.41 800.755 1486.41 800.771 1440.51 c 0,99,100 + 800.779 1419.59 800.779 1419.59 802.5 1398 c 0,101,102 + 808.001 1328.99 808.001 1328.99 832 1273 c 0,103,104 + 855.257 1218.74 855.257 1218.74 900 1215 c 0,105,106 + 936 1212 936 1212 927 1249.5 c 0,107,108 + 918 1287 918 1287 891 1320 c 0,109,110 + 949.002 1302 949.002 1302 969 1233.5 c 0,111,112 + 989 1164.99 989 1164.99 993 1080.5 c 0,113,114 + 995.825 937.374 l 0,115,116 + 995.723 924.927 995.723 924.927 995.5 912.5 c 0,117,118 + 994 829 994 829 1010 782 c 0,119,120 + 1023.01 742 1023.01 742 1098.5 638 c 0,121,122 + 1173.99 534 1173.99 534 1242.5 420 c 0,123,124 + 1311 306.016 1311 306.016 1338 208.5 c 0,125,126 + 1344.72 184.225 1344.72 184.225 1344.69 164.443 c 0,127,128 + 1344.59 104.775 1344.59 104.775 1283 86 c 0,129,130 + 1297.93 112.12 1297.93 112.12 1297.96 128.075 c 0,131,132 + 1298 152.964 1298 152.964 1261.79 153.122 c 0,133,134 + 1259 153.134 1259 153.134 1256 153 c 0,135,136 + 1228.22 152.133 1228.22 152.133 1228.3 114.634 c 0,137,138 + 1228.35 90.4386 1228.35 90.4386 1240 51 c 0,139,140 + 1280.48 -87.1799 1280.48 -87.1799 1280.48 -185.313 c 0,141,142 + 1280.48 -249.802 1280.48 -249.802 1263 -297 c 0,143,144 + 1234.55 -373.8 1234.55 -373.8 1191 -416 c 0,145,146 + 1107.92 -495.703 1107.92 -495.703 1027.5 -512.5 c 0,147,148 + 888.41 -542.467 888.41 -542.467 798 -505 c 0,149,150 + 874.226 -508.555 874.226 -508.555 927 -498 c 0,151,152 + 980.597 -487.281 980.597 -487.281 1038 -441 c 0,153,154 + 1076.94 -409.604 1076.94 -409.604 1099.5 -351.5 c 0,155,156 + 1104.33 -339.051 1104.33 -339.051 1104.24 -327.737 c 0,157,158 + 1104 -295.17 1104 -295.17 1063 -272 c 0,159,160 + 1048.68 -263.905 1048.68 -263.905 1035.82 -263.715 c 0,161,162 + 1019.54 -266.886 l 0,163,164 + 1002.14 -274.218 1002.14 -274.218 987 -300 c 0,165,166 + 975 -321 975 -321 984 -386 c 0,167,168 + 945.74 -313.824 945.74 -313.824 963 -263 c 0,169,170 + 981 -209.999 981 -209.999 1021 -191.5 c 0,171,172 + 1131.73 -140.111 1131.73 -140.111 1152 -75 c 0,173,174 + 1177.68 7.50585 1177.68 7.50585 1116 21 c 0,175,176 + 1069.64 31.1432 1069.64 31.1432 1059 18 c 0,177,178 + 1050.41 7.81504 1050.41 7.81504 1050.19 -3.31424 c 0,179,180 + 1053.95 -19.2845 l 0,181,182 + 1060.04 -32.0857 1060.04 -32.0857 1076 -46 c 0,183,184 + 1003.72 -45.1274 1003.72 -45.1274 1016 57 c 0,185,186 + 1031.7 187.605 1031.7 187.605 1031.61 272.387 c 0,187,188 + 1031.58 306.378 1031.58 306.378 1029 333 c 0,0,1 +733 888 m 0,93,94 + 763.873 888.762 l 0,95,96 + 796.902 894.015 796.902 894.015 817.5 919.5 c 0,97,98 + 846.999 955.998 846.999 955.998 852.5 997.5 c 0,99,100 + 853.215 1029.13 l 0,101,102 + 851 1049.91 851 1049.91 841 1065.5 c 0,103,104 + 822.658 1086.53 822.658 1086.53 805.386 1086.66 c 0,105,106 + 795.518 1086.74 795.518 1086.74 786 1080 c 0,107,108 + 767.953 1069.48 767.953 1069.48 767.749 1054.02 c 0,109,110 + 767.651 1046.6 767.651 1046.6 771.657 1038.05 c 0,111,112 + 773.597 1033.91 773.597 1033.91 776.5 1029.5 c 0,113,114 + 789.996 1009 789.996 1009 823 997 c 0,115,116 + 746.568 970.543 746.568 970.543 715 1020 c 0,117,118 + 700.983 1041.96 700.983 1041.96 701.047 1068.4 c 0,119,120 + 701.12 1098.54 701.12 1098.54 719.5 1134.5 c 0,121,122 + 754.648 1203.27 754.648 1203.27 717 1220 c 0,123,124 + 681 1236.01 681 1236.01 640 1190 c 0,125,126 + 598.998 1143.99 598.998 1143.99 585.5 1079.5 c 0,127,128 + 572 1015 572 1015 600.5 956 c 0,129,130 + 629 897 629 897 733 888 c 0,93,94 +EndSplineSet +KernsSLIF: 87 -208 0 0 +EndChar +StartChar: aogonek +Encoding: 261 261 80 +Width: 1218 +Flags: HW +Fore +874.65 283.05 m 0,0,1 + 870.156 341.119 870.156 341.119 825.35 394.4 c 0,2,3 + 745.449 501.501 745.449 501.501 690.625 512.125 c 0,4,5 + 669.512 516.217 669.512 516.217 650.882 516.15 c 0,6,7 + 618.846 516.035 618.846 516.035 594.15 503.625 c 0,8,-1 + 516.375 460.275 l 0,9,10 + 464.1 453.9 464.1 453.9 443.7 502.35 c 0,11,12 + 438.716 514.002 438.716 514.002 438.758 529.284 c 0,13,14 + 438.785 538.714 438.785 538.714 440.725 549.525 c 0,15,16 + 443.699 566.098 443.699 566.098 458.15 583.95 c 0,17,18 + 465.711 542.167 465.711 542.167 481.426 541.346 c 0,19,20 + 492.256 544.975 l 0,21,22 + 499.619 549.888 499.619 549.888 508.3 561.425 c 0,23,24 + 542.28 606.583 542.28 606.583 493 635.8 c 0,25,26 + 448.906 661.942 448.906 661.942 416.364 662.182 c 0,27,28 + 402.973 662.28 402.973 662.28 391.537 657.992 c 0,29,30 + 357.121 645.087 357.121 645.087 340.425 592.45 c 0,31,32 + 315.351 513.404 315.351 513.404 310.675 407.15 c 0,33,34 + 305.999 300.895 305.999 300.895 280.925 212.5 c 0,35,36 + 260.287 139.743 260.287 139.743 170.268 139.535 c 0,37,38 + 150.912 139.491 150.912 139.491 128.35 142.8 c 0,39,40 + 175.95 147.9 175.95 147.9 195.075 163.2 c 0,41,42 + 215.219 178.107 215.219 178.107 215.486 198.634 c 0,43,44 + 211.531 218.694 l 0,45,46 + 210.136 222.328 210.136 222.328 208.25 226.1 c 0,47,48 + 178.939 279.538 178.939 279.538 136.85 255.425 c 0,49,50 + 96.05 232.05 96.05 232.05 83.7246 175.525 c 0,51,52 + 80.5269 142.666 l 0,53,54 + 81.2572 99.8871 81.2572 99.8871 106.25 51.4248 c 0,55,56 + 141.1 -16.1504 141.1 -16.1504 260.95 -52.7002 c 0,57,58 + 86.7002 -52.7002 86.7002 -52.7002 29.75 65.0254 c 0,59,60 + 3.24371 119.818 3.24371 119.818 3.25233 175.071 c 0,61,62 + 3.26224 238.532 3.26224 238.532 38.25 302.6 c 0,63,64 + 94.3515 402.053 94.3515 402.053 176.375 531.675 c 0,65,66 + 267.729 676.043 267.729 676.043 267.65 867.872 c 0,67,68 + 267.637 899.106 267.637 899.106 265.2 931.6 c 0,69,70 + 266.376 968.254 l 0,71,72 + 273.284 1017.82 273.284 1017.82 308.975 1067.17 c 0,73,74 + 339.503 1110.54 339.503 1110.54 378.091 1110.68 c 0,75,76 + 403.982 1110.77 403.982 1110.77 433.5 1091.4 c 0,77,78 + 406.329 1090.97 l 0,79,80 + 379.719 1086.58 379.719 1086.58 362.95 1065.47 c 0,81,82 + 336.635 1032.64 336.635 1032.64 362.1 1001.3 c 0,83,84 + 376.748 983.182 376.748 983.182 391.659 983.246 c 0,85,86 + 409.627 983.323 409.627 983.323 427.975 1009.8 c 0,87,88 + 461.545 1058.24 461.545 1058.24 493 1136.45 c 0,89,90 + 524.45 1214.65 524.45 1214.65 551.225 1294.55 c 0,91,92 + 577.997 1374.45 577.997 1374.45 597.55 1397.4 c 0,93,94 + 648.354 1457.44 648.354 1457.44 702.637 1457.89 c 0,95,96 + 708.3 1457.93 708.3 1457.93 714 1457.33 c 0,97,98 + 774.35 1450.95 774.35 1450.95 774.35 1343 c 0,99,100 + 759.658 1371.21 759.658 1371.21 740.495 1371.79 c 0,101,102 + 725.624 1368.4 l 0,103,104 + 722.5 1366.8 l 0,105,106 + 697.852 1352.36 697.852 1352.36 687.65 1299.65 c 0,107,108 + 680.656 1263.52 680.656 1263.52 680.656 1224.58 c 0,109,110 + 680.655 1206.73 680.655 1206.73 682.125 1188.3 c 0,111,112 + 686.801 1129.64 686.801 1129.64 707.2 1082.05 c 0,113,114 + 726.976 1035.91 726.976 1035.91 765 1032.75 c 0,115,116 + 780.597 1034.61 l 0,117,118 + 789.506 1038.67 789.506 1038.67 789.48 1050.78 c 0,119,120 + 789.469 1055.75 789.469 1055.75 787.95 1062.08 c 0,121,122 + 780.302 1093.95 780.302 1093.95 757.35 1122 c 0,123,124 + 806.651 1106.7 806.651 1106.7 823.65 1048.47 c 0,125,126 + 840.518 990.703 840.518 990.703 844.05 918.425 c 0,127,128 + 847.451 846.6 847.451 846.6 846.175 775.625 c 0,129,130 + 848.559 712.944 l 0,131,132 + 851.634 684.868 851.634 684.868 858.5 664.7 c 0,133,134 + 869.551 630.7 869.551 630.7 933.725 542.3 c 0,135,136 + 997.93 453.859 997.93 453.859 1056.12 357 c 0,137,138 + 1114.35 260.1 1114.35 260.1 1137.3 177.225 c 0,139,140 + 1143.06 156.431 1143.06 156.431 1142.98 139.517 c 0,141,142 + 1142.76 89.0173 1142.76 89.0173 1090.55 73.0996 c 0,143,144 + 1103.06 94.9886 1103.06 94.9886 1103.26 108.48 c 0,145,146 + 1100.22 120.124 l 0,147,148 + 1093.75 129.824 1093.75 129.824 1073.52 130.144 c 0,149,150 + 1070.7 130.189 1070.7 130.189 1067.6 130.05 c 0,151,152 + 1043.98 129.312 1043.98 129.312 1044.05 97.4379 c 0,153,154 + 1044.09 76.8749 1044.09 76.8749 1054 43.3496 c 0,155,156 + 1088.46 -74.2999 1088.46 -74.2999 1088.41 -157.795 c 0,157,158 + 1088.37 -212.434 1088.37 -212.434 1073.55 -252.45 c 0,159,160 + 1049.17 -318.284 1049.17 -318.284 1012.35 -353.6 c 0,161,162 + 941.723 -421.348 941.723 -421.348 873.375 -435.625 c 0,163,164 + 755.148 -461.096 755.148 -461.096 678.3 -429.25 c 0,165,166 + 745.832 -428.787 l 0,167,168 + 768.723 -427.145 768.723 -427.145 787.95 -423.3 c 0,169,170 + 833.506 -414.188 833.506 -414.188 882.3 -374.85 c 0,171,172 + 915.4 -348.164 915.4 -348.164 934.575 -298.775 c 0,173,174 + 950.506 -257.74 950.506 -257.74 903.55 -231.2 c 0,175,176 + 891.257 -224.252 891.257 -224.252 880.236 -224.155 c 0,177,178 + 869.238 -224.059 869.238 -224.059 859.507 -230.783 c 0,179,180 + 848.405 -238.453 848.405 -238.453 838.95 -255 c 0,181,182 + 833.076 -265.28 833.076 -265.28 833.122 -287.966 c 0,183,184 + 833.156 -304.67 833.156 -304.67 836.4 -328.1 c 0,185,186 + 803.878 -266.751 803.878 -266.751 818.55 -223.55 c 0,187,188 + 833.851 -178.499 833.851 -178.499 867.85 -162.775 c 0,189,190 + 961.975 -119.091 961.975 -119.091 979.2 -63.75 c 0,191,192 + 1001.03 6.37995 1001.03 6.37995 948.6 17.8496 c 0,193,194 + 909.195 26.4718 909.195 26.4718 900.15 15.2998 c 0,195,196 + 892.906 6.70984 892.906 6.70984 892.667 -2.67166 c 0,197,198 + 896.39 -17.4706 l 0,199,200 + 901.706 -27.8569 901.706 -27.8569 914.6 -39.0996 c 0,201,202 + 853.165 -38.3584 853.165 -38.3584 863.6 48.4502 c 0,203,204 + 876.96 159.575 876.96 159.575 876.87 231.658 c 0,205,206 + 876.835 260.474 876.835 260.474 874.65 283.05 c 0,0,1 +623.05 754.8 m 0,93,94 + 651.68 755.862 l 0,95,96 + 678.117 760.841 678.117 760.841 694.875 781.575 c 0,97,98 + 719.949 812.598 719.949 812.598 724.625 847.875 c 0,99,100 + 724.988 876.826 l 0,101,102 + 722.85 893.204 722.85 893.204 714.85 905.675 c 0,103,104 + 699.258 923.547 699.258 923.547 684.578 923.664 c 0,105,106 + 676.19 923.731 676.19 923.731 668.1 918 c 0,107,108 + 652.852 909.109 652.852 909.109 652.589 896.07 c 0,109,110 + 656.305 881.517 l 0,111,112 + 657.846 878.384 657.846 878.384 660.025 875.075 c 0,113,114 + 671.5 857.65 671.5 857.65 699.55 847.45 c 0,115,116 + 677.045 839.66 677.045 839.66 659.116 839.612 c 0,117,118 + 625.288 839.523 625.288 839.523 607.75 867 c 0,119,120 + 595.874 885.605 595.874 885.605 595.89 907.989 c 0,121,122 + 595.907 933.67 595.907 933.67 611.575 964.325 c 0,123,124 + 625.829 992.219 625.829 992.219 625.998 1010.04 c 0,125,126 + 626.093 1020.15 626.093 1020.15 621.652 1027.02 c 0,127,128 + 617.518 1033.42 617.518 1033.42 609.45 1037 c 0,129,130 + 592.831 1040.51 l 0,131,132 + 569.558 1040.18 569.558 1040.18 544 1011.5 c 0,133,134 + 509.15 972.399 509.15 972.399 497.675 917.575 c 0,135,136 + 486.2 862.75 486.2 862.75 510.425 812.6 c 0,137,138 + 534.65 762.451 534.65 762.451 623.05 754.8 c 0,93,94 +EndSplineSet +KernsSLIF: 119 -182 0 0 +EndChar +StartChar: Cacute +Encoding: 262 262 81 +Width: 1221 +Flags: W +Fore +769 -106 m 0,0,1 + 471 -10 471 -10 308.5 95.5 c 0,2,3 + 146.001 200.999 146.001 200.999 52 521 c 0,4,5 + -21 771 -21 771 61.5 803 c 0,6,7 + 144 835 144 835 183 814 c 0,8,9 + 100 809 100 809 92 748 c 0,10,11 + 87.9999 724 87.9999 724 107 703.5 c 0,12,13 + 113.742 696.226 113.742 696.226 123.506 696.065 c 0,14,15 + 140.554 700.134 l 0,16,17 + 153.145 705.726 153.145 705.726 169 719 c 0,18,19 + 250.999 787.999 250.999 787.999 313.5 936.5 c 0,20,21 + 345.304 1012.07 345.304 1012.07 345.388 1061.87 c 0,22,23 + 345.468 1109.93 345.468 1109.93 316 1134 c 0,24,25 + 297.495 1147.88 297.495 1147.88 285.093 1147.79 c 0,26,27 + 268.004 1147.66 268.004 1147.66 262.5 1121 c 0,28,29 + 259.612 1088.31 l 0,30,31 + 260.551 1059.54 260.551 1059.54 274 1032 c 0,32,33 + 211.33 1083.77 211.33 1083.77 211.355 1131.42 c 0,34,35 + 211.358 1136.23 211.358 1136.23 212 1141 c 0,36,37 + 219 1193 219 1193 230 1211 c 0,38,39 + 257 1259 257 1259 334 1308.5 c 0,40,-1 + 490.5 1405 l 0,41,42 + 570 1451.99 570 1451.99 629 1495 c 0,43,44 + 680.531 1532.56 680.531 1532.56 680.952 1564.77 c 0,45,46 + 681.013 1569.44 681.013 1569.44 680 1574 c 0,47,48 + 673.091 1599.91 673.091 1599.91 657.729 1600.63 c 0,49,50 + 643.631 1596.94 l 0,51,52 + 637.511 1593.8 637.511 1593.8 630.5 1588 c 0,53,54 + 595.679 1559.21 595.679 1559.21 596 1532 c 0,55,56 + 592.844 1540.68 592.844 1540.68 592.879 1559.48 c 0,57,58 + 592.931 1588.32 592.931 1588.32 600.5 1641 c 0,59,60 + 613 1728 613 1728 715 1686 c 0,61,62 + 978.009 1575 978.009 1575 1049 1418 c 0,63,64 + 1076.75 1356.64 1076.75 1356.64 1076.7 1303.38 c 0,65,66 + 1076.62 1220.35 1076.62 1220.35 1009 1157 c 0,67,68 + 1022 1185.98 1022 1185.98 1029.5 1285.5 c 0,69,70 + 1028.57 1316.85 l 0,71,72 + 1021.6 1358.1 1021.6 1358.1 980.781 1358.56 c 0,73,74 + 950.888 1354.61 l 0,75,76 + 941.948 1352.41 941.948 1352.41 932 1349 c 0,77,78 + 853.592 1320.96 853.592 1320.96 853.408 1261.41 c 0,79,80 + 853.309 1229.29 853.309 1229.29 875.979 1188 c 0,81,82 + 877.205 1185.76 877.205 1185.76 878.5 1183.5 c 0,83,84 + 948 1062 948 1062 1087 1047 c 0,85,86 + 1059.4 1041.56 1059.4 1041.56 1030.84 1041.64 c 0,87,88 + 991.108 1041.74 991.108 1041.74 949.5 1052.5 c 0,89,90 + 878.012 1070.99 878.012 1070.99 860 1091 c 0,91,92 + 812 1144 812 1144 810 1175.5 c 0,93,94 + 808.001 1206.99 808.001 1206.99 786 1292 c 0,95,96 + 763 1376 763 1376 698.5 1364 c 0,97,98 + 633.992 1352 633.992 1352 569 1292.5 c 0,99,100 + 504 1232.99 504 1232.99 460.5 1151.5 c 0,101,102 + 430.805 1095.87 430.805 1095.87 430.701 1053.04 c 0,103,104 + 430.653 1033.14 430.653 1033.14 437 1016 c 0,105,106 + 454 967 454 967 502 988 c 0,107,108 + 538.099 1003.79 538.099 1003.79 538 1030.05 c 0,109,110 + 537.967 1038.71 537.967 1038.71 534 1048.5 c 0,111,112 + 517.997 1088 517.997 1088 478 1100 c 0,113,114 + 498.94 1109.19 498.94 1109.19 516.623 1109.26 c 0,115,116 + 533.557 1109.31 533.557 1109.31 547.5 1101 c 0,117,118 + 575.996 1084.01 575.996 1084.01 588 1063 c 0,119,120 + 600.251 1038.5 600.251 1038.5 600.196 1012.93 c 0,121,122 + 600.043 942.503 600.043 942.503 506.5 864 c 0,123,124 + 379 757 379 757 334 658 c 0,125,126 + 235 442 235 442 332 274 c 0,127,128 + 383.944 184.036 383.944 184.036 477.181 184.115 c 0,129,130 + 558.055 184.183 558.055 184.183 670 252 c 0,131,132 + 682.002 259.002 682.002 259.002 725.5 306.5 c 0,133,134 + 769 354 769 354 819.5 396 c 0,135,136 + 870 438 870 438 915 451 c 0,137,138 + 934.367 452.983 l 0,139,140 + 963.5 449.533 963.5 449.533 975 402 c 0,141,142 + 939 430 939 430 905 404.5 c 0,143,144 + 871 379 871 379 857.5 341.5 c 0,145,146 + 844 304 844 304 861 274 c 0,147,148 + 871.446 255.566 871.446 255.566 900.392 255.633 c 0,149,150 + 918.554 255.675 918.554 255.675 944 263 c 0,151,152 + 1110.72 309.975 1110.72 309.975 1110.72 453.253 c 0,153,154 + 1110.72 465.522 1110.72 465.522 1109.5 478.5 c 0,155,156 + 1094.01 642.999 1094.01 642.999 988 698 c 0,157,158 + 1127.99 642 1127.99 642 1145.5 504 c 0,159,160 + 1163.01 366 1163.01 366 1090 284 c 0,161,162 + 1042 228.999 1042 228.999 932.5 158 c 0,163,164 + 823 87.0005 823 87.0005 852 36 c 0,165,166 + 891 -36 891 -36 945.5 18 c 0,167,168 + 1000.01 72.0056 1000.01 72.0056 1002 120 c 0,169,170 + 1020 14 1020 14 942.5 -61.5 c 0,171,172 + 887.78 -114.807 887.78 -114.807 823.84 -115.023 c 0,173,174 + 797.219 -115.113 797.219 -115.113 769 -106 c 0,0,1 +885 1767 m 1,90,91 + 839 1752 839 1752 797 1798.5 c 0,92,93 + 754.997 1845 754.997 1845 735 1912 c 0,94,95 + 722.259 1954.69 722.259 1954.69 722.302 1997.77 c 0,96,97 + 722.326 2022.32 722.326 2022.32 726.5 2047 c 0,98,99 + 738.001 2115 738.001 2115 798 2142 c 0,100,101 + 765 2105 765 2105 766 2047.5 c 0,102,103 + 766.946 1993.17 766.946 1993.17 807.179 1992.85 c 0,104,105 + 809.523 1992.83 809.523 1992.83 812 1993 c 0,106,107 + 865.773 1996.58 865.773 1996.58 866.085 2049.52 c 0,108,109 + 866.183 2066.19 866.183 2066.19 860.977 2087.76 c 0,110,111 + 859.658 2093.22 859.658 2093.22 858 2099 c 0,112,113 + 888.014 2051.29 888.014 2051.29 888.119 2012.75 c 0,114,115 + 888.15 2001.21 888.15 2001.21 885.5 1990.5 c 0,116,117 + 873.997 1943.99 873.997 1943.99 855.5 1906 c 0,118,119 + 837.001 1868.01 837.001 1868.01 833 1835 c 0,120,121 + 834.75 1818.37 l 0,122,123 + 843.001 1793.25 843.001 1793.25 885 1767 c 1,90,91 +EndSplineSet +EndChar +StartChar: cacute +Encoding: 263 263 82 +Width: 1053 +Flags: W +Fore +667 50 m 0,0,1 + 414.002 130.999 414.002 130.999 276 221.5 c 0,2,3 + 138 312 138 312 58 584 c 0,4,5 + -3.99995 797 -3.99995 797 66 824 c 0,6,7 + 136.001 851 136.001 851 169 833 c 0,8,9 + 98.9995 830 98.9995 830 91 777 c 0,10,11 + 88 756 88 756 104.5 739 c 0,12,13 + 110.314 733.01 110.314 733.01 118.55 732.979 c 0,14,15 + 133.686 732.924 133.686 732.924 157 753 c 0,16,17 + 226 811 226 811 279.5 937 c 0,18,19 + 333 1063 333 1063 282 1105 c 0,20,21 + 245 1133.99 245 1133.99 237 1094.5 c 0,22,23 + 234.565 1064.17 l 0,24,25 + 235.643 1040.93 235.643 1040.93 246 1019 c 0,26,27 + 193.643 1062.33 193.643 1062.33 193.438 1102.81 c 0,28,29 + 193.416 1107.17 193.416 1107.17 194 1111.5 c 0,30,31 + 199.999 1156 199.999 1156 209 1171 c 0,32,33 + 231.999 1211.01 231.999 1211.01 297.5 1253.5 c 0,34,-1 + 430.5 1336 l 0,35,36 + 498 1376.01 498 1376.01 548 1412.5 c 0,37,38 + 591.233 1444.06 591.233 1444.06 591.851 1470.76 c 0,39,40 + 591.947 1474.94 591.947 1474.94 591 1479 c 0,41,42 + 581 1516.99 581 1516.99 549 1491 c 0,43,44 + 519.723 1467.22 519.723 1467.22 520 1444 c 0,45,46 + 517.162 1451.3 517.162 1451.3 517.2 1467.88 c 0,47,48 + 517.257 1492.2 517.257 1492.2 523.5 1536.5 c 0,49,50 + 530.554 1586.55 530.554 1586.55 572.133 1586.73 c 0,51,52 + 592.446 1586.82 592.446 1586.82 621 1575 c 0,53,54 + 843.999 1481 843.999 1481 905 1347 c 0,55,56 + 928.906 1294.49 928.906 1294.49 928.852 1249.04 c 0,57,58 + 928.771 1179.09 928.771 1179.09 871 1125 c 0,59,60 + 882.999 1149 882.999 1149 888.5 1233.5 c 0,61,62 + 886.96 1262.72 l 0,63,64 + 879.922 1295.56 879.922 1295.56 846.301 1295.86 c 0,65,66 + 818.321 1291.76 l 0,67,68 + 812.409 1290.18 812.409 1290.18 806 1288 c 0,69,70 + 739.114 1264.43 739.114 1264.43 738.776 1213.88 c 0,71,72 + 738.677 1198.96 738.677 1198.96 744.373 1181.69 c 0,73,74 + 749.675 1165.61 749.675 1165.61 760 1147.5 c 0,75,76 + 818.997 1044.01 818.997 1044.01 937 1031 c 0,77,78 + 914.022 1026.49 914.022 1026.49 890.21 1026.52 c 0,79,80 + 855.966 1026.56 855.966 1026.56 820 1036 c 0,81,82 + 759 1052.01 759 1052.01 744 1069 c 0,83,84 + 703 1114 703 1114 701.5 1140.5 c 0,85,86 + 700 1167 700 1167 682 1239 c 0,87,88 + 662 1311 662 1311 607 1300.5 c 0,89,90 + 552.008 1290 552.008 1290 497 1240 c 0,91,92 + 442.012 1190.02 442.012 1190.02 405 1120.5 c 0,93,94 + 379.853 1073.27 379.853 1073.27 379.65 1036.89 c 0,95,96 + 379.554 1019.74 379.554 1019.74 385 1005 c 0,97,98 + 394.672 975.982 394.672 975.982 417.234 975.605 c 0,99,100 + 436.705 979.633 l 0,101,102 + 438.331 980.267 438.331 980.267 440 981 c 0,103,104 + 470 994.5 470 994.5 470.188 1017 c 0,105,106 + 470.25 1024.5 470.25 1024.5 467 1033 c 0,107,108 + 454.002 1067 454.002 1067 419 1076 c 0,109,110 + 436.939 1083.69 436.939 1083.69 452.123 1083.76 c 0,111,112 + 466.558 1083.82 466.558 1083.82 478.5 1077 c 0,113,114 + 502.995 1063.01 502.995 1063.01 513 1045 c 0,115,116 + 552 967 552 967 444 876 c 0,117,118 + 336 785 336 785 297 701 c 0,119,120 + 213 518 213 518 295.5 374.5 c 0,121,122 + 339.547 297.884 339.547 297.884 418.515 297.806 c 0,123,124 + 487.451 297.739 487.451 297.739 583 356 c 0,125,126 + 592.998 361.999 592.998 361.999 630 402.5 c 0,127,128 + 667.002 443.001 667.002 443.001 710 478.5 c 0,129,130 + 753 514 753 514 791.5 524.5 c 0,131,132 + 830 535 830 535 842 483 c 0,133,134 + 812 506 812 506 783 484.5 c 0,135,136 + 754.001 463.001 754.001 463.001 742.5 431 c 0,137,138 + 737.254 416.404 737.254 416.404 737.314 403.264 c 0,139,140 + 737.386 387.597 737.386 387.597 745 374 c 0,141,142 + 759 349 759 349 816 365 c 0,143,144 + 969 407 969 407 956 547.5 c 0,145,146 + 943 688 943 688 853 735 c 0,147,148 + 972.001 687 972.001 687 987.5 569.5 c 0,149,150 + 1003 452 1003 452 940 382 c 0,151,152 + 898 336 898 336 806 275.5 c 0,153,154 + 714 215.001 714 215.001 738 172 c 0,155,156 + 771 109 771 109 817 156 c 0,157,158 + 863 202.999 863 202.999 865 244 c 0,159,160 + 880 152.999 880 152.999 814 88 c 0,161,162 + 748 23 748 23 667 50 c 0,0,1 +766 1644 m 1,90,91 + 727 1630.01 727 1630.01 691 1669.5 c 0,92,93 + 655.004 1708.99 655.004 1708.99 638.5 1766.5 c 0,94,95 + 628.026 1803 628.026 1803 628.029 1839.5 c 0,96,97 + 628.031 1860.5 628.031 1860.5 631.5 1881.5 c 0,98,99 + 641.001 1939.01 641.001 1939.01 692 1962 c 0,100,101 + 664.696 1930.8 664.696 1930.8 664.5 1881.5 c 0,102,103 + 664.967 1836.2 664.967 1836.2 699.025 1835.83 c 0,104,105 + 701.429 1835.8 701.429 1835.8 704 1836 c 0,106,107 + 749.303 1838.88 749.303 1838.88 749.618 1883.64 c 0,108,109 + 749.718 1897.74 749.718 1897.74 745.351 1916 c 0,110,111 + 744.304 1920.38 744.304 1920.38 743 1925 c 0,112,113 + 768.109 1884.68 768.109 1884.68 768.324 1852.45 c 0,114,115 + 768.391 1842.33 768.391 1842.33 766 1833 c 0,116,117 + 756.002 1794.01 756.002 1794.01 740.5 1761.5 c 0,118,119 + 725.516 1730.08 725.516 1730.08 721.5 1701.5 c 0,120,121 + 723.355 1686.49 l 0,122,123 + 730.94 1665.91 730.94 1665.91 766 1644 c 1,90,91 +EndSplineSet +EndChar +StartChar: Eogonek +Encoding: 280 280 83 +Width: 1514 +Flags: HMW +HStem: -25.5 188.5<428 1169.5> 701.5 157<313.5 758.5> 1353 218<196 987> +VStem: 82 215<-28 1037> 585 218.5<-320.5 -47> +Fore +500 -334 m 132,-1,0 + 530 -270.001 530 -270.001 573 -221 c 0,1,2 + 616.001 -171.999 616.001 -171.999 637 -132 c 0,3,4 + 658 -91.9995 658 -91.9995 585 -47 c 0,5,6 + 556 -29 556 -29 469.5 -23 c 0,7,8 + 383 -17 383 -17 297 -28 c 0,9,10 + 211 -39 211 -39 155.5 -70.5 c 0,11,12 + 100 -102 100 -102 133 -159 c 0,13,14 + 154 -195.001 154 -195.001 230 -206 c 0,15,16 + 203.189 -212.105 203.189 -212.105 180.923 -212.01 c 0,17,18 + 119.311 -211.745 119.311 -211.745 92.5 -164 c 0,19,20 + 56.0001 -99.0005 56.0001 -99.0005 53 -3.5 c 0,21,22 + 50 92 50 92 65 190 c 0,23,24 + 80 288 80 288 82 330 c 0,25,26 + 83.3538 453.119 l 0,27,28 + 81.2241 552.794 81.2241 552.794 68.5 649 c 0,29,30 + 48 804 48 804 12 960 c 0,31,32 + 0 1020 0 1020 8.5 1078.5 c 0,33,34 + 17 1137 17 1137 83 1158 c 0,35,36 + 45 1137 45 1137 38 1069.5 c 0,37,38 + 38.125 1042.16 l 0,39,40 + 41.0576 1025.78 41.0576 1025.78 52.8586 1025.08 c 0,41,42 + 68.1897 1028.89 l 0,43,44 + 74.4608 1031.83 74.4608 1031.83 82 1037 c 0,45,46 + 149.999 1082 149.999 1082 190.5 1236.5 c 0,47,48 + 206.042 1295.79 206.042 1295.79 206.047 1335.86 c 0,49,50 + 206.056 1400.21 206.056 1400.21 166 1415 c 0,51,52 + 79 1445 79 1445 58 1386.5 c 0,53,54 + 37 1328 37 1328 52 1256 c 0,55,56 + 11.599 1313.04 11.599 1313.04 11.6157 1374.49 c 0,57,58 + 11.6272 1416.47 11.6272 1416.47 30.5 1460.5 c 0,59,60 + 77.0044 1569.01 77.0044 1569.01 196 1571 c 0,61,62 + 295 1572.01 295 1572.01 408.5 1527.5 c 0,63,64 + 462.924 1506.16 462.924 1506.16 512.867 1506.09 c 0,65,66 + 567.073 1506.02 567.073 1506.02 616 1531 c 0,67,68 + 632.022 1539.01 632.022 1539.01 754 1572 c 0,69,70 + 876.019 1605.01 876.019 1605.01 1026.5 1607 c 0,71,72 + 1102.39 1604.14 l 0,73,74 + 1212.74 1594.25 1212.74 1594.25 1317.5 1551 c 0,75,76 + 1458.01 1492.99 1458.01 1492.99 1511 1320 c 0,77,78 + 1461 1392 1461 1392 1429.5 1422.5 c 0,79,80 + 1397.99 1453 1397.99 1453 1350 1474 c 0,81,82 + 1328.96 1482.01 1328.96 1482.01 1257.5 1498.5 c 0,83,84 + 1185.99 1515 1185.99 1515 1115 1513.5 c 0,85,86 + 1043.99 1512 1043.99 1512 999 1478 c 0,87,88 + 973.44 1458.69 973.44 1458.69 973.045 1420.99 c 0,89,90 + 977.026 1386.64 l 0,91,92 + 980.5 1370.93 980.5 1370.93 987 1353 c 0,93,94 + 1002 1309.01 1002 1309.01 1053 1329 c 0,95,96 + 1104 1348.99 1104 1348.99 1119 1395 c 0,97,98 + 1116 1316 1116 1316 1076 1295 c 0,99,100 + 1046.63 1279.59 1046.63 1279.59 1009.73 1279.53 c 0,101,102 + 996.362 1279.51 996.362 1279.51 982 1281.5 c 0,103,104 + 928.02 1289 928.02 1289 872.5 1310.5 c 0,105,106 + 816.976 1332 816.976 1332 783 1338 c 0,107,108 + 724.708 1347.93 724.708 1347.93 671.147 1347.88 c 0,109,110 + 514.287 1347.73 514.287 1347.73 398 1262 c 0,111,112 + 281.569 1176.17 281.569 1176.17 281.56 1027.39 c 0,113,114 + 281.557 976.831 281.557 976.831 295 919 c 0,115,116 + 312.784 837.568 312.784 837.568 406.788 837.613 c 0,117,118 + 413.215 837.616 413.215 837.616 420 838 c 0,119,120 + 526 844 526 844 481 923 c 0,121,122 + 453 971 453 971 418 937 c 0,123,124 + 383 903 383 903 391 882 c 0,125,126 + 387.648 921.385 l 0,127,128 + 389.057 996.13 389.057 996.13 462.658 996.742 c 0,129,130 + 470.653 996.808 470.653 996.808 479.5 996 c 0,131,132 + 589.005 985.999 589.005 985.999 678 958 c 0,133,134 + 716 946 716 946 799.5 969 c 0,135,136 + 845.412 981.646 845.412 981.646 887.847 981.595 c 0,137,138 + 922.589 981.553 922.589 981.553 955 973 c 0,139,140 + 1018.01 954.998 1018.01 954.998 1056 886 c 0,141,142 + 1093.99 817 1093.99 817 1026 698 c 0,143,144 + 1060.99 815 1060.99 815 1008 860.5 c 0,145,146 + 958.847 902.697 958.847 902.697 894.212 902.75 c 0,147,148 + 889.153 902.754 889.153 902.754 884 902.5 c 0,149,150 + 813 899 813 899 758.5 858.5 c 0,151,152 + 704 818 704 818 737 763 c 0,153,154 + 743 753 743 753 781.5 754.5 c 0,155,156 + 820 756 820 756 808 801 c 0,157,158 + 856 777 856 777 837.5 748 c 0,159,160 + 819 719 819 719 798 709 c 0,161,162 + 733.814 680.116 733.814 680.116 661.903 680.2 c 0,163,164 + 644.186 680.221 644.186 680.221 626 682 c 0,165,166 + 534 691 534 691 453 701.5 c 0,167,168 + 372 712 372 712 313.5 701.5 c 0,169,170 + 255 691 255 691 245 615 c 0,171,172 + 236.91 558.37 236.91 558.37 236.919 518.43 c 0,173,174 + 236.932 459.629 236.932 459.629 254.5 437 c 0,175,176 + 284 399 284 399 314 408 c 0,177,178 + 344 417 344 417 349 445.5 c 0,179,180 + 347.674 456.176 l 0,181,182 + 340.847 469.073 340.847 469.073 305.92 469.043 c 0,183,184 + 296.076 469.035 296.076 469.035 284 468 c 0,185,186 + 294.001 486 294.001 486 322 487.5 c 0,187,188 + 350 489 350 489 361 486 c 0,189,190 + 428 463 428 463 423.5 394.5 c 0,191,192 + 419 326.002 419 326.002 411.5 262 c 0,193,194 + 404 197.999 404 197.999 428 163 c 0,195,196 + 452 128.001 452 128.001 577 172 c 0,197,198 + 622.009 187.003 622.009 187.003 761.5 242 c 0,199,200 + 901 297 901 297 925 216 c 0,201,202 + 903.999 228.001 903.999 228.001 882 228.5 c 0,203,204 + 866.839 226.005 l 0,205,206 + 859.566 222.478 859.566 222.478 859 214 c 0,207,208 + 860.873 195.111 l 0,209,210 + 873.894 153.483 873.894 153.483 969.23 153.319 c 0,211,212 + 975.913 153.308 975.913 153.308 983 153.5 c 0,213,214 + 1111.99 156.999 1111.99 156.999 1122 226 c 0,215,216 + 1121.24 242.091 l 0,217,218 + 1117.86 253.528 1117.86 253.528 1104.73 253.833 c 0,219,220 + 1091.5 252 l 0,221,222 + 1056.99 242.999 1056.99 242.999 1043 213 c 0,223,224 + 1059.01 279 1059.01 279 1095.5 286.5 c 0,225,226 + 1131.99 294 1131.99 294 1173.5 277.5 c 0,227,228 + 1214.99 261.005 1214.99 261.005 1255.5 236 c 0,229,230 + 1296 210.999 1296 210.999 1320 212 c 0,231,232 + 1442.73 214.707 1442.73 214.707 1443.3 346.089 c 0,233,234 + 1443.37 360.293 1443.37 360.293 1442 376 c 0,235,236 + 1499 268 1499 268 1409 178 c 0,237,238 + 1319 88 1319 88 1184 43 c 0,239,240 + 1148.59 31.1974 1148.59 31.1974 1148.41 11.023 c 0,241,242 + 1148.31 0.467999 1148.31 0.467999 1157.85 -12.3787 c 0,243,244 + 1162.52 -18.6647 1162.52 -18.6647 1169.5 -25.5 c 0,245,246 + 1187.51 -43.1428 1187.51 -43.1428 1204.22 -43.058 c 0,247,248 + 1232.49 -42.9144 1232.49 -42.9144 1257 8 c 0,249,250 + 1255.01 -59.9961 1255.01 -59.9961 1220 -73.5 c 0,251,252 + 1185.01 -87 1185.01 -87 1139 -76.5 c 0,253,254 + 1092.99 -66 1092.99 -66 1049 -46.5 c 0,255,256 + 1009.26 -28.8871 1009.26 -28.8871 987 -29 c 0,257,258 + 934 -34 934 -34 850.5 -63.5 c 0,259,260 + 767 -93.0001 767 -93.0001 776 -225 c 0,261,262 + 778.351 -264.189 778.351 -264.189 799.132 -264.677 c 0,263,264 + 812 -262 l 0,265,266 + 845 -248.999 845 -248.999 863 -195 c 0,267,268 + 858 -305.999 858 -305.999 803.5 -320.5 c 0,269,270 + 749 -335 749 -335 686.5 -332.5 c 0,271,272 + 636.585 -334.226 l 0,273,274 + 602.996 -338.11 602.996 -338.11 573.5 -349.5 c 0,275,276 + 523 -369 523 -369 526 -491 c 0,277,278 + 470 -398 470 -398 500 -334 c 132,-1,0 +EndSplineSet +EndChar +StartChar: eogonek +Encoding: 281 281 84 +Width: 1305 +Flags: HMW +HStem: 148 160.5<389.5 1019.5> 766 133.5<291.5 670> 1320.5 185<192 865> +VStem: 96 182<145 1051.5> 523 185.5<-102 129.5> +Fore +451 -113 m 132,-1,0 + 476 -58.5001 476 -58.5001 512.5 -17 c 0,1,2 + 549 24.5 549 24.5 566.5 58 c 0,3,4 + 570.294 65.2622 570.294 65.2622 570.398 72.736 c 0,5,6 + 566.895 87.9464 l 0,7,8 + 557.508 108.003 557.508 108.003 523 129.5 c 0,9,10 + 497.999 144.501 497.999 144.501 424.5 149.5 c 0,11,12 + 351 154.499 351 154.499 278 145 c 0,13,14 + 205.003 135.501 205.003 135.501 157.5 109.5 c 0,15,16 + 109.999 83.5001 109.999 83.5001 138 35.5 c 0,17,18 + 156 5.50008 156 5.50008 221 -4.5 c 0,19,20 + 135.001 -23.5 135.001 -23.5 104 31.5 c 0,21,22 + 72.9999 86.5001 72.9999 86.5001 70.5 167.5 c 0,23,24 + 67.9999 248.5 67.9999 248.5 81 331.5 c 0,25,26 + 94.0001 414.5 94.0001 414.5 96 450.5 c 0,27,28 + 102 589.5 102 589.5 84 721.5 c 0,29,30 + 66 853.5 66 853.5 36 985.5 c 0,31,32 + 28.6337 1016.81 28.6337 1016.81 28.6154 1047.74 c 0,33,34 + 28.604 1067.2 28.604 1067.2 31.5 1086.5 c 0,35,36 + 39.0008 1136.5 39.0008 1136.5 96 1154.5 c 0,37,38 + 63 1136.5 63 1136.5 57.5 1079.5 c 0,39,40 + 58.1818 1054.81 l 0,41,42 + 61.2307 1042.02 61.2307 1042.02 71.4697 1041.73 c 0,43,44 + 86.6965 1046.05 l 0,45,46 + 91.0331 1048.23 91.0331 1048.23 96 1051.5 c 0,47,48 + 152.998 1090.5 152.998 1090.5 187 1221.5 c 0,49,50 + 200.06 1271.82 200.06 1271.82 200.136 1305.76 c 0,51,52 + 200.234 1349.58 200.234 1349.58 178.69 1366.1 c 0,53,54 + 173.478 1370.1 173.478 1370.1 167 1372.5 c 0,55,56 + 141.459 1381.35 141.459 1381.35 122.587 1381.45 c 0,57,58 + 103.52 1381.55 103.52 1381.55 91.2603 1372.71 c 0,59,60 + 80.0198 1364.61 80.0198 1364.61 74.5 1349 c 0,61,62 + 64.4434 1320.55 64.4434 1320.55 64.459 1288.31 c 0,63,64 + 64.4706 1264.45 64.4706 1264.45 70 1238.5 c 0,65,66 + 35.4682 1286.73 35.4682 1286.73 35.4975 1338.85 c 0,67,68 + 35.5174 1374.28 35.5174 1374.28 51.5 1411.5 c 0,69,70 + 91.0043 1503.51 91.0043 1503.51 192 1505.5 c 0,71,72 + 276 1505.5 276 1505.5 372.5 1468 c 0,73,74 + 418.698 1450.05 418.698 1450.05 461.118 1450.09 c 0,75,76 + 507.299 1450.13 507.299 1450.13 549 1471.5 c 0,77,78 + 561.963 1478.48 561.963 1478.48 666 1506.5 c 0,79,80 + 769.98 1534.5 769.98 1534.5 898 1536 c 0,81,82 + 968.2 1532.96 l 0,83,84 + 1059.08 1523.94 1059.08 1523.94 1145.5 1488.5 c 0,85,86 + 1265 1439.5 1265 1439.5 1310 1291.5 c 0,87,88 + 1267.99 1352.52 1267.99 1352.52 1241.5 1378.5 c 0,89,90 + 1214.98 1404.51 1214.98 1404.51 1173 1422.5 c 0,91,92 + 1155.08 1429.48 1155.08 1429.48 1094.5 1444 c 0,93,94 + 1039.52 1457.18 1039.52 1457.18 984.499 1457.14 c 0,95,96 + 979.002 1457.14 979.002 1457.14 973.5 1457 c 0,97,98 + 912.999 1455.5 912.999 1455.5 875 1427 c 0,99,100 + 853.056 1410.54 853.056 1410.54 853.121 1377.58 c 0,101,102 + 853.169 1353.46 853.169 1353.46 865 1320.5 c 0,103,104 + 873.107 1295.5 873.107 1295.5 895.597 1295.15 c 0,105,106 + 917.149 1299.25 l 0,107,108 + 918.801 1299.84 918.801 1299.84 920.5 1300.5 c 0,109,110 + 963.998 1317.49 963.998 1317.49 976 1356.5 c 0,111,112 + 972.121 1252.54 972.121 1252.54 904.433 1251.81 c 0,113,114 + 874.102 1255.82 l 0,115,116 + 867.279 1257.54 867.279 1257.54 860 1260 c 0,117,118 + 749.03 1297.49 749.03 1297.49 691 1307.5 c 0,119,120 + 496 1340.5 496 1340.5 363.5 1243 c 0,121,122 + 231 1145.5 231 1145.5 276 950.5 c 0,123,124 + 290.949 882.298 290.949 882.298 370.925 882.18 c 0,125,126 + 376.552 882.171 376.552 882.171 382.5 882.5 c 0,127,128 + 445.726 885.993 445.726 885.993 445.745 920.236 c 0,129,130 + 445.753 935.007 445.753 935.007 434 955.5 c 0,131,132 + 410 994.5 410 994.5 380.5 966.5 c 0,133,134 + 351 938.5 351 938.5 358 920.5 c 0,135,136 + 355.178 956.588 l 0,137,138 + 357.557 1016.96 357.557 1016.96 418.311 1017.63 c 0,139,140 + 425.273 1017.71 425.273 1017.71 433 1017 c 0,141,142 + 526.022 1008.49 526.022 1008.49 602 984.5 c 0,143,144 + 613.184 981.005 613.184 981.005 629.133 981.052 c 0,145,146 + 658.816 981.14 658.816 981.14 705 993.5 c 0,147,148 + 776 1012.51 776 1012.51 837 996.5 c 0,149,150 + 891 981.5 891 981.5 923 923 c 0,151,152 + 955 864.5 955 864.5 898 763.5 c 0,153,154 + 909.411 802.85 909.411 802.85 909.365 832.678 c 0,155,156 + 909.292 878.65 909.292 878.65 882 902 c 0,157,158 + 837 940.5 837 940.5 776.5 937.5 c 0,159,160 + 716 934.5 716 934.5 670 899.5 c 0,161,162 + 624 864.5 624 864.5 652 818.5 c 0,163,164 + 657 809.5 657 809.5 689.5 810.5 c 0,165,166 + 722 811.5 722 811.5 712 850.5 c 0,167,168 + 741.022 836.343 741.022 836.343 741.734 819.93 c 0,169,170 + 738.701 808.047 l 0,171,172 + 738.15 807.027 738.15 807.027 737.5 806 c 0,173,174 + 722 781.499 722 781.499 704 773.5 c 0,175,176 + 649.462 748.636 649.462 748.636 588.167 748.539 c 0,177,178 + 573.039 748.515 573.039 748.515 557.5 750 c 0,179,180 + 479 757.5 479 757.5 410 766.5 c 0,181,182 + 341 775.5 341 775.5 291.5 766 c 0,183,184 + 242 756.5 242 756.5 233 692.5 c 0,185,186 + 226.133 644.427 226.133 644.427 226.201 610.552 c 0,187,188 + 226.301 560.572 226.301 560.572 241.5 541.5 c 0,189,190 + 267 509.5 267 509.5 292.5 517 c 0,191,192 + 318 524.5 318 524.5 322 548.5 c 0,193,194 + 320.371 558.225 l 0,195,196 + 313.925 568.374 313.925 568.374 285.403 568.362 c 0,197,198 + 277.13 568.358 277.13 568.358 267 567.5 c 0,199,200 + 276 582.5 276 582.5 299.5 584.5 c 0,201,202 + 323 586.5 323 586.5 332 583.5 c 0,203,204 + 389 563.5 389 563.5 385.5 505.5 c 0,205,206 + 382.001 447.516 382.001 447.516 375.5 393 c 0,207,208 + 374.494 354.701 l 0,209,210 + 376.885 326.961 376.885 326.961 389.5 308.5 c 0,211,212 + 398.494 295.338 398.494 295.338 423.946 295.265 c 0,213,214 + 456.506 295.172 456.506 295.172 516 316.5 c 0,215,216 + 555 329.5 555 329.5 673.5 376 c 0,217,218 + 792 422.5 792 422.5 812 353.5 c 0,219,220 + 794.002 363.499 794.002 363.499 775 364.5 c 0,221,222 + 762.368 362.683 l 0,223,224 + 756 359.605 756 359.605 756 351.5 c 0,225,226 + 752 297.5 752 297.5 861 300.5 c 0,227,228 + 970 303.5 970 303.5 979 361.5 c 0,229,230 + 983 391.5 983 391.5 953.5 384.5 c 0,231,232 + 924 377.5 924 377.5 912 351.5 c 0,233,234 + 940 462.5 940 462.5 1023 406 c 0,235,236 + 1104.66 350.411 1104.66 350.411 1147 350.5 c 0,237,238 + 1251.4 352.3 1251.4 352.3 1252.12 464.26 c 0,239,240 + 1252.2 476.7 1252.2 476.7 1251 490.5 c 0,241,242 + 1269.94 454.563 1269.94 454.563 1270.06 421.088 c 0,243,244 + 1270.15 393.428 1270.15 393.428 1257.4 367.45 c 0,245,246 + 1245.66 343.511 1245.66 343.511 1223 321 c 0,247,248 + 1146.01 244.502 1146.01 244.502 1032 206.5 c 0,249,250 + 978 188.5 978 188.5 1019.5 148 c 0,251,252 + 1034.82 133.05 1034.82 133.05 1048.98 133.021 c 0,253,254 + 1073.18 132.97 1073.18 132.97 1094 176.5 c 0,255,256 + 1092.56 92.98 1092.56 92.98 1041.35 92.1448 c 0,257,258 + 1015.84 95.942 l 0,259,260 + 1005.59 98.8556 1005.59 98.8556 994 104 c 0,261,262 + 896 147.5 896 147.5 865 144.5 c 0,263,264 + 820 139.501 820 139.501 749 114.5 c 0,265,266 + 684.311 91.7219 684.311 91.7219 684.372 -1.61601 c 0,267,268 + 684.378 -10.7222 684.378 -10.7222 685 -20.5 c 0,269,270 + 688 -62.5 688 -62.5 716 -52 c 0,271,272 + 744 -41.5 744 -41.5 759 4.5 c 0,273,274 + 755 -89.5 755 -89.5 708.5 -102 c 0,275,276 + 662 -114.499 662 -114.499 609 -112.5 c 0,277,278 + 556 -110.501 556 -110.501 513 -127 c 0,279,280 + 472.855 -142.404 472.855 -142.404 472.804 -234.077 c 0,281,282 + 472.801 -240.595 472.801 -240.595 473 -247.5 c 0,283,284 + 442.424 -195.455 442.424 -195.455 442.32 -154.203 c 0,285,286 + 442.264 -132.044 442.264 -132.044 451 -113 c 132,-1,0 +EndSplineSet +EndChar +StartChar: Lslash +Encoding: 321 321 85 +Width: 1737 +Flags: HMW +HStem: 8 320<774 1387> +VStem: 583 159<31.5 1459> +Fore +687 1538 m 1,0,1 + 655 1514 655 1514 655.5 1490 c 0,2,3 + 656 1465.99 656 1465.99 694 1464 c 0,4,5 + 708.349 1466.74 l 0,6,7 + 744.986 1483.48 744.986 1483.48 776 1600 c 0,8,9 + 786.895 1640.93 786.895 1640.93 786.865 1673.36 c 0,10,11 + 786.795 1751.08 786.795 1751.08 724 1780 c 0,12,13 + 790 1796.01 790 1796.01 821 1709.5 c 0,14,15 + 841.964 1651 841.964 1651 841.891 1584.05 c 0,16,17 + 841.856 1551.99 841.856 1551.99 837 1518 c 0,18,19 + 828.998 1467.99 828.998 1467.99 808.5 1382.5 c 0,20,21 + 788 1297 788 1297 775 1212 c 0,22,23 + 762 1126.99 762 1126.99 768 1062 c 0,24,25 + 774 996.999 774 996.999 820 989 c 0,26,27 + 877 977 877 977 952 1030 c 0,28,29 + 1000.71 1064.42 1000.71 1064.42 1001.33 1095.05 c 0,30,31 + 997.749 1112.28 l 0,32,33 + 994.418 1119.76 994.418 1119.76 988 1127 c 0,34,35 + 949 1170.01 949 1170.01 921.5 1131.5 c 0,36,37 + 893.998 1092.99 893.998 1092.99 880 1058 c 0,38,39 + 883 1167.99 883 1167.99 947.5 1188.5 c 0,40,41 + 1011.96 1208.99 1011.96 1208.99 1098.5 1213 c 0,42,43 + 1185.01 1217.01 1185.01 1217.01 1273 1242.5 c 0,44,45 + 1361 1268 1361 1268 1412 1389 c 0,46,47 + 1401.99 1282.99 1401.99 1282.99 1351 1231.5 c 0,48,49 + 1300.01 1180.01 1300.01 1180.01 1239.5 1144.5 c 0,50,51 + 1178.91 1108.94 1178.91 1108.94 1124.5 1070 c 0,52,53 + 1070.01 1031 1070.01 1031 1054 951 c 0,54,55 + 1048 927 1048 927 1070.5 924.5 c 0,56,57 + 1095.88 925.692 l 0,58,59 + 1107.45 927.889 1107.45 927.889 1120 933 c 0,60,61 + 1158 947.001 1158 947.001 1158 999 c 0,62,63 + 1201.99 920 1201.99 920 1156.5 883.5 c 0,64,65 + 1111.01 847.004 1111.01 847.004 1037 831 c 0,66,67 + 963 815 963 815 889.5 808.5 c 0,68,69 + 816 802 816 802 804 783 c 0,70,71 + 744 693 744 693 729 563 c 0,72,73 + 714 433 714 433 774 328 c 0,74,75 + 837 215.001 837 215.001 958 230.5 c 0,76,77 + 1078.99 245.997 1078.99 245.997 1204.5 286 c 0,78,79 + 1330.01 326.002 1330.01 326.002 1433 337 c 0,80,81 + 1465.48 336.915 l 0,82,83 + 1540.7 327.344 1540.7 327.344 1564 225 c 0,84,85 + 1540 267.001 1540 267.001 1489.5 277 c 0,86,87 + 1438.99 287 1438.99 287 1419 266 c 0,88,89 + 1353 195.001 1353 195.001 1416 150.5 c 0,90,91 + 1464.57 116.195 1464.57 116.195 1534.23 116.061 c 0,92,93 + 1554.93 116.022 1554.93 116.022 1577.5 119 c 0,94,95 + 1676 132 1676 132 1764.5 216 c 0,96,97 + 1853 300 1853 300 1838 486 c 0,98,99 + 1857.76 416.141 1857.76 416.141 1857.67 356.651 c 0,100,101 + 1857.47 208.36 1857.47 208.36 1734 124.5 c 0,102,103 + 1562.5 8.01583 1562.5 8.01583 1387 8 c 0,104,105 + 1300.01 8 1300.01 8 1176 51.5 c 0,106,107 + 1051.99 95 1051.99 95 1035 3 c 0,108,109 + 1033.55 -20.8143 l 0,110,111 + 1037.84 -57.1116 1037.84 -57.1116 1089.5 -57.5 c 0,112,113 + 1155.99 -58 1155.99 -58 1196 -13 c 0,114,115 + 1155.11 -117.502 1155.11 -117.502 1089.03 -117.958 c 0,116,117 + 1082.39 -118.004 1082.39 -118.004 1075.5 -117 c 0,118,119 + 1000 -106 1000 -106 914.5 -57.5 c 0,120,121 + 829 -9.00005 829 -9.00005 742 31.5 c 0,122,123 + 655 72 655 72 587 17 c 0,124,125 + 496 -56.0001 496 -56.0001 575 -133 c 0,126,127 + 650.982 -207.057 650.982 -207.057 726.037 -207.112 c 0,128,129 + 729.019 -207.115 729.019 -207.115 732 -207 c 0,130,131 + 685.805 -218.957 685.805 -218.957 649.06 -218.951 c 0,132,133 + 618.756 -218.946 618.756 -218.946 594 -210.5 c 0,134,135 + 541 -192 541 -192 496 -135 c 0,136,137 + 445 -70.0001 445 -70.0001 467 29 c 0,138,139 + 489.002 128.007 489.002 128.007 524.5 231 c 0,140,141 + 560 334 560 334 578.5 424.5 c 0,142,143 + 583.04 446.711 583.04 446.711 582.973 466.241 c 0,144,145 + 582.766 526.289 582.766 526.289 539 561 c 0,146,147 + 488 600 488 600 440 572.5 c 0,148,149 + 392 545 392 545 343 505 c 0,150,151 + 293.999 464.999 293.999 464.999 242 439.5 c 0,152,153 + 222.917 430.142 222.917 430.142 203.161 430.009 c 0,154,155 + 188.511 429.911 188.511 429.911 173.491 434.885 c 0,156,157 + 153.571 441.481 153.571 441.481 133 457 c 0,158,159 + 239.999 453 239.999 453 251.5 513 c 0,160,161 + 254.696 548.121 l 0,162,163 + 253.566 580.482 253.566 580.482 234 596 c 0,164,165 + 171 642 171 642 127.5 606 c 0,166,167 + 84 570 84 570 66.5 503.5 c 0,168,169 + 49 437 49 437 61 365.5 c 0,170,171 + 72.9998 294.001 72.9998 294.001 121 269 c 0,172,173 + 13 315 13 315 16.5 463.5 c 0,174,175 + 20 612 20 612 57 656 c 0,176,177 + 163.999 785 163.999 785 306 763 c 0,178,179 + 337.145 758.175 337.145 758.175 367.568 758.208 c 0,180,181 + 475.854 758.327 475.854 758.327 575 820 c 0,182,183 + 593 830 593 830 581.5 953.5 c 0,184,185 + 570.001 1076.98 570.001 1076.98 566 1215.5 c 0,186,187 + 566.756 1320.01 l 0,188,189 + 570.322 1395.61 570.322 1395.61 583 1459 c 0,190,191 + 599.759 1542.8 599.759 1542.8 656.009 1543.16 c 0,192,193 + 670.24 1543.25 670.24 1543.25 687 1538 c 1,0,1 +EndSplineSet +KernsSLIF: 89 -156 0 0 121 -78 0 0 84 -208 0 0 87 -321 0 0 +EndChar +StartChar: lslash +Encoding: 322 322 86 +Width: 1480 +Flags: HMW +HStem: 128 272<667 1188> +VStem: 505 135<147.5 1361> +Fore +593 1428 m 1,0,1 + 567.318 1408.02 567.318 1408.02 566.5 1387 c 0,2,3 + 567 1366.99 567 1366.99 599 1365 c 0,4,5 + 637 1362 637 1362 668.5 1480.5 c 0,6,7 + 677.632 1514.85 677.632 1514.85 677.729 1542.19 c 0,8,9 + 677.827 1569.77 677.827 1569.77 668.732 1590.2 c 0,10,11 + 655.742 1619.38 655.742 1619.38 624 1634 c 0,12,13 + 647.265 1635.96 l 0,14,15 + 686.64 1632.06 686.64 1632.06 707 1574.5 c 0,16,17 + 724.413 1525.27 724.413 1525.27 724.333 1468.65 c 0,18,19 + 724.294 1440.72 724.294 1440.72 720 1411 c 0,20,21 + 714.001 1369.01 714.001 1369.01 696.5 1296 c 0,22,23 + 678.997 1222.99 678.997 1222.99 668 1151 c 0,24,25 + 660.378 1101.11 660.378 1101.11 660.438 1059.38 c 0,26,27 + 660.465 1040.89 660.465 1040.89 662 1024 c 0,28,29 + 666.999 969.001 666.999 969.001 706 962 c 0,30,31 + 755 952 755 952 818.5 997 c 0,32,33 + 860.317 1026.63 860.317 1026.63 860.285 1052.8 c 0,34,35 + 860.268 1066.36 860.268 1066.36 849 1079 c 0,36,37 + 831.104 1097.95 831.104 1097.95 816.257 1097.92 c 0,38,39 + 802.894 1097.9 802.894 1097.9 792 1082.5 c 0,40,41 + 768.995 1049.99 768.995 1049.99 758 1020 c 0,42,43 + 760 1114.01 760 1114.01 815 1131 c 0,44,45 + 870.001 1147.99 870.001 1147.99 943 1152 c 0,46,47 + 1016 1156.01 1016 1156.01 1091 1177.5 c 0,48,49 + 1165.99 1198.99 1165.99 1198.99 1209 1302 c 0,50,51 + 1200 1211.99 1200 1211.99 1157 1168 c 0,52,53 + 1113.98 1123.99 1113.98 1123.99 1062.5 1094 c 0,54,55 + 1011.02 1064.01 1011.02 1064.01 964.5 1030.5 c 0,56,57 + 918.002 997.006 918.002 997.006 905 929 c 0,58,59 + 904.926 915.649 l 0,60,61 + 907.773 908.182 907.773 908.182 919 907 c 0,62,63 + 938 905 938 905 961 914 c 0,64,65 + 993 926 993 926 993 970 c 0,66,67 + 1011.22 936.52 1011.22 936.52 1011.25 912.127 c 0,68,69 + 1011.29 886.983 1011.29 886.983 992 871.5 c 0,70,71 + 954 841 954 841 891 827.5 c 0,72,73 + 828 814 828 814 765 808.5 c 0,74,75 + 702 803 702 803 692 787 c 0,76,77 + 641 709 641 709 628.5 599 c 0,78,79 + 626.227 545.05 l 0,80,81 + 628.814 466.638 628.814 466.638 667 400 c 0,82,83 + 721 304 721 304 824 317.5 c 0,84,85 + 927 331 927 331 1033.5 364.5 c 0,86,87 + 1140 398.001 1140 398.001 1227 407.5 c 0,88,89 + 1314 417 1314 417 1338 313 c 0,90,91 + 1317 348 1317 348 1275 356.5 c 0,92,93 + 1246.05 359.1 l 0,94,95 + 1226.37 357.983 1226.37 357.983 1216 347 c 0,96,97 + 1160.01 286 1160.01 286 1213 248.5 c 0,98,99 + 1254.39 219.212 1254.39 219.212 1314.7 219.203 c 0,100,101 + 1331.61 219.201 1331.61 219.201 1350 221.5 c 0,102,103 + 1433.99 231.999 1433.99 231.999 1508.5 303.5 c 0,104,105 + 1572.66 365.071 1572.66 365.071 1572.66 491.539 c 0,106,107 + 1572.67 511.925 1572.67 511.925 1571 534 c 0,108,109 + 1629.01 327 1629.01 327 1482.5 227 c 0,110,111 + 1337.49 128.018 1337.49 128.018 1188 128 c 0,112,113 + 1115 128 1115 128 1009.5 164.5 c 0,114,115 + 975.793 176.162 975.793 176.162 951.324 176.135 c 0,116,117 + 899.207 176.079 899.207 176.079 889 123 c 0,118,119 + 879 70.9999 879 70.9999 935.5 70.5 c 0,120,121 + 992 70.0001 992 70.0001 1025 109 c 0,122,123 + 987 11 987 11 923 20.5 c 0,124,125 + 859 30 859 30 786.5 71.5 c 0,126,127 + 714.005 112.997 714.005 112.997 640 147.5 c 0,128,129 + 608.606 162.136 608.606 162.136 580.092 162.104 c 0,130,131 + 541.931 162.061 541.931 162.061 508 135 c 0,132,133 + 430 72 430 72 497.5 7.5 c 0,134,135 + 565 -57 565 -57 632 -55 c 0,136,137 + 559 -74.0001 559 -74.0001 514 -58 c 0,138,139 + 469 -42 469 -42 431 5 c 0,140,141 + 400.295 42.6839 400.295 42.6839 400.27 95.4635 c 0,142,143 + 400.259 118.317 400.259 118.317 406 144 c 0,144,145 + 425.001 229.002 425.001 229.002 455 317 c 0,146,147 + 485 405 485 405 501 482 c 0,148,149 + 504.875 518.125 l 0,150,151 + 504.5 568.75 504.5 568.75 467 598 c 0,152,153 + 424 631 424 631 383 607.5 c 0,154,155 + 341.997 583.997 341.997 583.997 300.5 550 c 0,156,157 + 259.003 516.002 259.003 516.002 215 494 c 0,158,159 + 171.001 472 171.001 472 122 509 c 0,160,161 + 213.001 506 213.001 506 222.5 557 c 0,162,163 + 225.013 589.347 l 0,164,165 + 223.428 614.785 223.428 614.785 208 627 c 0,166,167 + 177.736 648.857 177.736 648.857 152.812 648.885 c 0,168,169 + 133.264 648.906 133.264 648.906 117 635.5 c 0,170,171 + 79.9999 605 79.9999 605 65 548.5 c 0,172,173 + 50 492 50 492 60.5 431.5 c 0,174,175 + 71 371 71 371 112 350 c 0,176,177 + 20 389 20 389 23 515 c 0,178,179 + 26 641 26 641 57 679 c 0,180,181 + 134.265 772.396 134.265 772.396 233.155 772.797 c 0,182,183 + 250.736 772.868 250.736 772.868 269 770 c 0,184,185 + 390 751 390 751 498 818 c 0,186,187 + 513 827 513 827 503.5 931.5 c 0,188,189 + 493.999 1036.03 493.999 1036.03 490.5 1154 c 0,190,191 + 487 1272.01 487 1272.01 505 1361 c 0,192,193 + 519.319 1431.8 519.319 1431.8 566.539 1432.36 c 0,194,195 + 591.921 1428.33 l 0,196,197 + 593 1428 l 1,0,1 +EndSplineSet +KernsSLIF: 121 -104 0 0 116 -208 0 0 119 -385 0 0 +EndChar +StartChar: Nacute +Encoding: 323 323 87 +Width: 1285 +Flags: MW +VStem: 131 270.5<220 1558.5> 626 189<1760.5 1967> 822.5 107<83 1472> +Fore +324 1593 m 0,0,1 + 346.986 1609 346.986 1609 395 1624 c 0,2,3 + 417.177 1627.12 l 0,4,5 + 451.57 1625.67 451.57 1625.67 479 1583 c 0,6,7 + 455.226 1594.71 455.226 1594.71 438.565 1595.02 c 0,8,9 + 422.575 1592.01 l 0,10,11 + 406.252 1584.52 406.252 1584.52 401.5 1558.5 c 0,12,13 + 397.146 1534.66 397.146 1534.66 397.177 1505.92 c 0,14,15 + 397.22 1465.34 397.22 1465.34 406 1415 c 0,16,17 + 421.004 1328.98 421.004 1328.98 446.5 1246 c 0,18,19 + 471.753 1163.81 471.753 1163.81 480 1146 c 0,20,21 + 493 1111.01 493 1111.01 527.5 1101 c 0,22,23 + 547.556 1098.57 l 0,24,25 + 567.655 1100.11 567.655 1100.11 580 1120 c 0,26,27 + 604 1160.01 604 1160.01 572.5 1183 c 0,28,29 + 547.425 1201.3 547.425 1201.3 515.706 1201.24 c 0,30,31 + 507.571 1201.22 507.571 1201.22 499 1200 c 0,32,33 + 536.359 1222.03 536.359 1222.03 565.234 1222.04 c 0,34,35 + 596.638 1222.05 596.638 1222.05 618 1196 c 0,36,37 + 658.999 1146.01 658.999 1146.01 679 1080 c 0,38,39 + 688 1047 688 1047 704 978 c 0,40,41 + 720 909 720 909 741.5 846.5 c 0,42,43 + 763 784 763 784 790 750.5 c 0,44,45 + 817 717 817 717 849 755 c 0,46,47 + 888.427 802.159 888.427 802.159 888.409 889.659 c 0,48,49 + 888.404 915.342 888.404 915.342 885 944.5 c 0,50,51 + 870.005 1072.96 870.005 1072.96 847 1212 c 0,52,53 + 824 1351.01 824 1351.01 822.5 1472 c 0,54,55 + 821 1593.01 821 1593.01 899 1640 c 0,56,57 + 893.009 1624.02 893.009 1624.02 861.5 1558 c 0,58,59 + 852.5 1539.14 852.5 1539.14 852.357 1523.63 c 0,60,61 + 852.259 1512.93 852.259 1512.93 856.378 1503.82 c 0,62,63 + 867.182 1479.93 867.182 1479.93 907 1467 c 0,64,65 + 923.542 1461.31 923.542 1461.31 938.201 1461.19 c 0,66,67 + 960.888 1464.7 l 0,68,69 + 1010.83 1481.53 1010.83 1481.53 1033.5 1579 c 0,70,71 + 1045.45 1630.38 1045.45 1630.38 1045.5 1672.21 c 0,72,73 + 1045.59 1747.62 1045.59 1747.62 1007 1792 c 0,74,75 + 1087.86 1740.37 1087.86 1740.37 1088.52 1642.23 c 0,76,77 + 1088.54 1639.63 1088.54 1639.63 1088.5 1637 c 0,78,79 + 1087 1535.03 1087 1535.03 1067 1436.5 c 0,80,81 + 1046.99 1337.91 1046.99 1337.91 1042 1269.5 c 0,82,83 + 1043.5 1244.33 l 0,84,85 + 1050.72 1214.15 1050.72 1214.15 1086.69 1213.97 c 0,86,87 + 1098.34 1213.91 1098.34 1213.91 1113 1217 c 0,88,89 + 1169.68 1227.56 1169.68 1227.56 1169.6 1287.95 c 0,90,91 + 1169.6 1290.43 1169.6 1290.43 1169.5 1293 c 0,92,93 + 1166.99 1358 1166.99 1358 1116 1404 c 0,94,95 + 1221 1357.99 1221 1357.99 1222.5 1273.5 c 0,96,97 + 1219.36 1222.38 l 0,98,99 + 1210.9 1161.16 1210.9 1161.16 1180 1095.5 c 0,100,101 + 1136 1001.99 1136 1001.99 1076.5 914 c 0,102,103 + 1017 826.012 1017 826.012 1002 774 c 0,104,105 + 982.94 710.755 982.94 710.755 983.02 577.323 c 0,106,107 + 983.032 556.746 983.032 556.746 983.5 534.5 c 0,108,109 + 987 368 987 368 981 279 c 0,110,111 + 973.999 187.997 973.999 187.997 929.5 83 c 0,112,113 + 885 -22 885 -22 805 -81 c 0,114,115 + 844 36 844 36 846 218 c 0,116,117 + 848 400 848 400 728 455 c 0,118,119 + 712.982 458.284 l 0,120,121 + 695.093 457.395 695.093 457.395 685 430 c 0,122,123 + 671 392 671 392 695 371 c 0,124,125 + 715.996 352.003 715.996 352.003 721.5 348 c 0,126,127 + 727 344 727 344 753 335 c 0,128,129 + 678 326 678 326 656.5 358 c 0,130,131 + 634.999 390.001 634.999 390.001 630 442 c 0,132,133 + 610.999 635.01 610.999 635.01 588.5 804 c 0,134,135 + 566 973 566 973 379 1038 c 0,136,137 + 359.306 1041.07 l 0,138,139 + 316.358 1039.59 316.358 1039.59 295 959.5 c 0,140,141 + 269 862 269 862 316 823 c 0,142,143 + 352 793 352 793 387.5 821.5 c 0,144,145 + 423 850 423 850 381 902 c 0,146,147 + 407.792 899.407 l 0,148,149 + 449.736 888.761 449.736 888.761 449.941 835.163 c 0,150,151 + 449.973 826.849 449.973 826.849 449 817.5 c 0,152,153 + 440 731.001 440 731.001 398 617.5 c 0,154,155 + 356 504 356 504 309 395.5 c 0,156,157 + 263.887 291.355 263.887 291.355 264 246 c 0,158,159 + 271.999 70.0008 271.999 70.0008 326.5 23 c 0,160,161 + 380.996 -23.9972 380.996 -23.9972 485 -93 c 0,162,163 + 359 -70.9999 359 -70.9999 260.5 12.5 c 0,164,165 + 162.001 95.9991 162.001 95.9991 131 220 c 0,166,167 + 95 367 95 367 155.5 536 c 0,168,169 + 184.99 618.377 184.99 618.377 185.137 667.728 c 0,170,171 + 185.236 701.109 185.236 701.109 171.911 719.38 c 0,172,173 + 164.52 729.514 164.52 729.514 153 735 c 0,174,175 + 130 745.667 130 745.667 114.167 745.833 c 0,176,177 + 104.718 745.933 104.718 745.933 97.8211 742.293 c 0,178,179 + 81.6048 733.734 81.6048 733.734 79.5 704.5 c 0,180,181 + 75 642 75 642 111 630 c 0,182,183 + 31 635 31 635 21 692 c 0,184,185 + 10.9999 749 10.9999 749 33.5 820.5 c 0,186,187 + 56 892 56 892 91 960 c 0,188,189 + 125.995 1027.99 125.995 1027.99 137 1055 c 0,190,191 + 169.999 1143.99 169.999 1143.99 217.5 1347.5 c 0,192,193 + 264.999 1551 264.999 1551 324 1593 c 0,0,1 +587 1669 m 1,98,99 + 630 1708 630 1708 626 1760.5 c 0,100,101 + 621.997 1813.03 621.997 1813.03 615 1866 c 0,102,103 + 608 1918.99 608 1918.99 621 1965 c 0,104,105 + 634 2011.01 634 2011.01 711 2037 c 0,106,107 + 679.998 2023.99 679.998 2023.99 666.5 1988 c 0,108,109 + 662.585 1968.38 l 0,110,111 + 662.9 1947.8 662.9 1947.8 686 1938 c 0,112,113 + 760 1906.01 760 1906.01 767 2010 c 0,114,115 + 767.449 2068.65 l 0,116,117 + 763.629 2125.31 763.629 2125.31 741 2150 c 0,118,119 + 743.995 2150 743.995 2150 782.5 2104.5 c 0,120,121 + 815.68 2065.29 815.68 2065.29 815.809 1991.54 c 0,122,123 + 815.829 1979.71 815.829 1979.71 815 1967 c 0,124,125 + 798 1712.99 798 1712.99 587 1669 c 1,98,99 +EndSplineSet +EndChar +StartChar: nacute +Encoding: 324 324 88 +Width: 1095 +Flags: MW +VStem: 114 229<334 1471> 534.5 160.5<1643 1818> 701.5 91<216 1398> +Fore +278 1500 m 0,0,1 + 297 1513.99 297 1513.99 338 1527 c 0,2,3 + 358.082 1529.67 l 0,4,5 + 386.604 1527.83 386.604 1527.83 409 1492 c 0,6,7 + 352 1520.01 352 1520.01 343 1471 c 0,8,9 + 339.238 1450.51 339.238 1450.51 339.32 1425.84 c 0,10,11 + 339.434 1391.49 339.434 1391.49 347 1349 c 0,12,13 + 360 1276 360 1276 382 1205.5 c 0,14,15 + 404 1135 404 1135 410 1120 c 0,16,17 + 422 1091.01 422 1091.01 451 1082.5 c 0,18,19 + 469.146 1080.48 l 0,20,21 + 485.113 1082.18 485.113 1082.18 495 1098 c 0,22,23 + 516 1132.01 516 1132.01 489 1152 c 0,24,25 + 468.094 1167.48 468.094 1167.48 442.398 1167.38 c 0,26,27 + 434.903 1167.35 434.903 1167.35 427 1166 c 0,28,29 + 458.365 1184.53 458.365 1184.53 482.731 1184.66 c 0,30,31 + 501.908 1184.76 501.908 1184.76 516.747 1173.46 c 0,32,33 + 522.726 1168.9 522.726 1168.9 528 1162.5 c 0,34,35 + 562.996 1120.01 562.996 1120.01 580 1064 c 0,36,37 + 588 1035.99 588 1035.99 601.5 977 c 0,38,39 + 615 918 615 918 633 865.5 c 0,40,41 + 651 813 651 813 674 784 c 0,42,43 + 697 755 697 755 724 788 c 0,44,45 + 757.888 828.051 757.888 828.051 757.965 901.911 c 0,46,47 + 757.988 923.95 757.988 923.95 755 949 c 0,48,49 + 742 1058 742 1058 722.5 1176.5 c 0,50,51 + 703 1295 703 1295 701.5 1398 c 0,52,53 + 704.502 1442.42 l 0,54,55 + 715.57 1510.06 715.57 1510.06 767 1540 c 0,56,57 + 760.949 1525.89 760.949 1525.89 734.5 1470 c 0,58,59 + 726.928 1454 726.928 1454 726.826 1440.86 c 0,60,61 + 726.731 1428.6 726.731 1428.6 733.137 1418.82 c 0,62,63 + 743.897 1402.4 743.897 1402.4 773 1393 c 0,64,65 + 787.331 1388.1 787.331 1388.1 799.999 1388.12 c 0,66,67 + 857.17 1388.22 857.17 1388.22 880.5 1488.5 c 0,68,69 + 909 1611.01 909 1611.01 858 1670 c 0,70,71 + 926.936 1625.68 926.936 1625.68 927 1538.5 c 0,72,73 + 926 1452 926 1452 909.5 1368 c 0,74,75 + 893 1284 893 1284 888.5 1225.5 c 0,76,77 + 889.952 1203 l 0,78,79 + 896.331 1178.48 896.331 1178.48 926.052 1178.3 c 0,80,81 + 936.173 1178.24 936.173 1178.24 949 1181 c 0,82,83 + 998 1190 998 1190 995.5 1245.5 c 0,84,85 + 993 1301 993 1301 951 1340 c 0,86,87 + 1040.99 1301 1040.99 1301 1042 1229 c 0,88,89 + 1038.7 1182.13 l 0,90,91 + 1031 1131.55 1031 1131.55 1005.5 1077.5 c 0,92,93 + 968 998 968 998 917.5 923 c 0,94,95 + 867.001 848.003 867.001 848.003 854 804 c 0,96,97 + 838.122 749.311 838.122 749.311 838.195 632.77 c 0,98,99 + 838.205 617.187 838.205 617.187 838.5 600.5 c 0,100,101 + 838.195 430.678 l 0,102,103 + 837.386 404.787 837.386 404.787 836 384 c 0,104,105 + 830 306 830 306 792.5 216 c 0,106,107 + 755 126 755 126 687 77 c 0,108,109 + 720 177 720 177 721.5 331.5 c 0,110,111 + 723 486 723 486 621 534 c 0,112,113 + 607.018 536.132 l 0,114,115 + 593.061 533.918 593.061 533.918 584.5 512 c 0,116,117 + 572 480 572 480 593 462 c 0,118,119 + 616 440 616 440 643 431 c 0,120,121 + 579 424 579 424 560.5 450.5 c 0,122,123 + 542 477 542 477 538 522 c 0,124,125 + 521.997 687.025 521.997 687.025 503 830.5 c 0,126,127 + 484 974 484 974 325 1029 c 0,128,129 + 306.614 1031.48 l 0,130,131 + 270.724 1028.86 270.724 1028.86 253 962 c 0,132,133 + 230.999 879 230.999 879 271 846 c 0,134,135 + 302 820 302 820 332 844 c 0,136,137 + 362 868 362 868 326 913 c 0,138,139 + 392 915 392 915 384 841.5 c 0,140,141 + 376 768 376 768 340.5 671.5 c 0,142,143 + 304.992 574.979 304.992 574.979 265 483 c 0,144,145 + 226.89 395.349 226.89 395.349 227 356 c 0,146,147 + 233 206 233 206 280 165 c 0,148,149 + 327.001 124 327.001 124 414 67 c 0,150,151 + 307 85 307 85 223.5 156.5 c 0,152,153 + 139.999 228.001 139.999 228.001 114 334 c 0,154,155 + 82.9999 459 82.9999 459 135 602.5 c 0,156,157 + 160.46 672.76 160.46 672.76 160.509 714.612 c 0,158,159 + 160.561 758.24 160.561 758.24 133 771 c 0,160,161 + 73 798 73 798 69.5 745 c 0,162,163 + 66.0001 692 66.0001 692 97 682 c 0,164,165 + 29 686 29 686 20.5 734.5 c 0,166,167 + 17.9648 771.712 l 0,168,169 + 18.9725 805.202 18.9725 805.202 31 843.5 c 0,170,171 + 50 904 50 904 80 962 c 0,172,173 + 110 1020.01 110 1020.01 119 1043 c 0,174,175 + 146.995 1117.98 146.995 1117.98 187 1291 c 0,176,177 + 227.002 1464 227.002 1464 278 1500 c 0,0,1 +501 1565 m 1,97,98 + 534.679 1595.04 534.679 1595.04 534.802 1635.02 c 0,99,100 + 534.814 1638.96 534.814 1638.96 534.5 1643 c 0,101,102 + 531 1688 531 1688 525.5 1733 c 0,103,104 + 520 1778 520 1778 530.5 1817 c 0,105,106 + 541 1856 541 1856 607 1877 c 0,107,108 + 580.003 1866.01 580.003 1866.01 568.5 1836 c 0,109,110 + 565.261 1819.15 l 0,111,112 + 565.976 1802.29 565.976 1802.29 586 1794 c 0,113,114 + 649 1767 649 1767 654.5 1855.5 c 0,115,116 + 660 1944 660 1944 633 1974 c 0,117,118 + 636 1974 636 1974 668 1935 c 0,119,120 + 700 1896 700 1896 695 1818 c 0,121,122 + 681.056 1601.86 681.056 1601.86 501 1565 c 1,97,98 +EndSplineSet +EndChar +StartChar: Sacute +Encoding: 346 346 89 +Width: 1144 +Flags: HW +Fore +683 -50 m 0,0,1 + 575 -44 575 -44 470.5 -51 c 0,2,3 + 366 -58 366 -58 278.5 -43.5 c 0,4,5 + 191.001 -29 191.001 -29 128.5 23 c 0,6,7 + 65.9999 75 65.9999 75 43 201 c 0,8,9 + 70.0002 133 70.0002 133 142 103 c 0,10,11 + 155.224 97.4898 155.224 97.4898 166.729 97.3099 c 0,12,13 + 184.056 100.442 l 0,14,15 + 220.947 115.345 220.947 115.345 235 201 c 0,16,17 + 236.947 234.883 l 0,18,19 + 233.812 282.336 233.812 282.336 194 307.5 c 0,20,21 + 161.449 328.075 161.449 328.075 120.976 328.092 c 0,22,23 + 95.5509 328.102 95.5509 328.102 67 320 c 0,24,25 + 131.999 431 131.999 431 228 360 c 0,26,27 + 324 289 324 289 360 229 c 0,28,29 + 453 70 453 70 534 100 c 0,30,31 + 615 130 615 130 656.5 224.5 c 0,32,33 + 698 319 698 319 685 417 c 0,34,35 + 674.43 496.682 674.43 496.682 610.31 497.032 c 0,36,37 + 595.57 497.112 595.57 497.112 578 493 c 0,38,39 + 551 486 551 486 551.5 462 c 0,40,41 + 552 438 552 438 573 419 c 0,42,43 + 600 392 600 392 641 423 c 0,44,45 + 608.573 339.022 608.573 339.022 568.541 339.041 c 0,46,47 + 560.427 339.045 560.427 339.045 552 342.5 c 0,48,49 + 502 363.001 502 363.001 456 430 c 0,50,51 + 410 497 410 497 375.5 573 c 0,52,53 + 341 649 341 649 333 658 c 0,54,55 + 198.002 796.998 198.002 796.998 75.5 956.5 c 0,56,57 + 9.56444 1042.35 9.56444 1042.35 9.53848 1139.94 c 0,58,59 + 9.5162 1223.65 9.5162 1223.65 58 1316 c 0,60,61 + 71.9999 1343 71.9999 1343 107 1359.5 c 0,62,63 + 116.032 1363.76 116.032 1363.76 124.532 1363.79 c 0,64,65 + 148.967 1363.87 148.967 1363.87 169 1329 c 0,66,67 + 153.833 1338.39 153.833 1338.39 140.232 1338.32 c 0,68,69 + 116.166 1338.21 116.166 1338.21 97 1308.5 c 0,70,71 + 83.5354 1287.63 83.5354 1287.63 83.5672 1272.7 c 0,72,73 + 83.6063 1254.37 83.6063 1254.37 104 1245 c 0,74,75 + 114.919 1239.84 114.919 1239.84 126.863 1239.92 c 0,76,77 + 175.081 1240.25 175.081 1240.25 240 1326 c 0,78,79 + 321 1432.99 321 1432.99 276 1491 c 0,80,81 + 263.212 1506.89 263.212 1506.89 248.323 1507.16 c 0,82,83 + 233.127 1503.63 l 0,84,85 + 215.806 1495.55 215.806 1495.55 196 1469 c 0,86,87 + 195.152 1498.14 l 0,88,89 + 201.306 1554.44 201.306 1554.44 273 1577 c 0,90,91 + 362 1605.01 362 1605.01 480.5 1604 c 0,92,93 + 599.036 1602.99 599.036 1602.99 711.5 1586.5 c 0,94,95 + 824 1570 824 1570 859 1561 c 0,96,97 + 944.601 1539.42 944.601 1539.42 944.717 1476.2 c 0,98,99 + 944.767 1448.57 944.767 1448.57 928.5 1413 c 0,100,101 + 874.997 1295.99 874.997 1295.99 785 1261 c 0,102,103 + 814.991 1296.99 814.991 1296.99 845 1350 c 0,104,105 + 875 1402.99 875 1402.99 848 1434 c 0,106,107 + 826.995 1457 826.995 1457 788.5 1458.5 c 0,108,109 + 770.041 1455.64 l 0,110,111 + 743.053 1445.86 743.053 1445.86 722 1403 c 0,112,113 + 685.428 1330.43 685.428 1330.43 685.265 1283.65 c 0,114,115 + 685.167 1255.51 685.167 1255.51 698.253 1236.7 c 0,116,117 + 701.476 1232.07 701.476 1232.07 705.5 1228 c 0,118,119 + 751.965 1181.05 751.965 1181.05 842.5 1181 c 0,120,121 + 932.029 1182.01 932.029 1182.01 1028.5 1217.5 c 0,122,123 + 1124.99 1253.01 1124.99 1253.01 1159 1294 c 0,124,125 + 1084 1171 1084 1171 940 1120 c 0,126,127 + 870.72 1095.46 870.72 1095.46 800.75 1095.46 c 0,128,129 + 725.277 1095.46 725.277 1095.46 649 1124 c 0,130,131 + 571.991 1151 571.991 1151 521 1198.5 c 0,132,133 + 470 1246.01 470 1246.01 430.5 1275 c 0,134,135 + 400.256 1297.2 400.256 1297.2 373.833 1297.43 c 0,136,137 + 365.737 1297.49 365.737 1297.49 358 1295.5 c 0,138,139 + 324.998 1286.99 324.998 1286.99 285 1203 c 0,140,141 + 261.211 1152.62 261.211 1152.62 261.165 1096.13 c 0,142,143 + 261.145 1071.88 261.145 1071.88 265.5 1046.5 c 0,144,145 + 280 962 280 962 355 904 c 0,146,147 + 370.918 891.619 370.918 891.619 387.13 891.556 c 0,148,149 + 407.581 891.476 407.581 891.476 428.5 911 c 0,150,151 + 466 946 466 946 411 982 c 0,152,153 + 441.509 992.17 441.509 992.17 466.463 992.083 c 0,154,155 + 495.49 991.981 495.49 991.981 517 978 c 0,156,157 + 556.998 952.002 556.998 952.002 612 865 c 0,158,159 + 631.998 832.002 631.998 832.002 712 740 c 0,160,161 + 792.002 647.997 792.002 647.997 863 543 c 0,162,163 + 934 438 934 438 961 343 c 0,164,165 + 967.496 320.143 967.496 320.143 967.451 300.585 c 0,166,167 + 967.308 238.857 967.308 238.857 902 210 c 0,168,169 + 899.454 252.437 l 0,170,171 + 897.919 262.322 897.919 262.322 895.5 272 c 0,172,173 + 888 302 888 302 851 293 c 0,174,175 + 848 292 848 292 819.5 250 c 0,176,177 + 791 208 791 208 770 161.5 c 0,178,179 + 749 115 749 115 751.5 82 c 0,180,181 + 754 49 754 49 814 66 c 0,182,183 + 838 72 838 72 836.5 92.5 c 0,184,185 + 835 113.001 835 113.001 839 137 c 0,186,187 + 914 60.0001 914 60.0001 819.5 4 c 0,188,189 + 725 -52 725 -52 683 -50 c 0,0,1 +414 1714 m 1,98,99 + 395.009 1728.03 395.009 1728.03 395.108 1801.05 c 0,100,101 + 395.129 1816.46 395.129 1816.46 396 1834.5 c 0,102,103 + 401 1938 401 1938 446.5 2042 c 0,104,105 + 491.999 2145.99 491.999 2145.99 585.5 2208.5 c 0,106,107 + 631.398 2239.18 631.398 2239.18 691.879 2239.14 c 0,108,109 + 754.596 2239.09 754.596 2239.09 833 2206 c 0,110,111 + 746.818 2206.21 l 0,112,113 + 690.669 2203.56 690.669 2203.56 649 2193 c 0,114,115 + 578 2175 578 2175 545 2079 c 0,116,117 + 530.449 2035.69 530.449 2035.69 530.302 2007.15 c 0,118,119 + 530.21 1989.43 530.21 1989.43 535.67 1977.4 c 0,120,121 + 546.801 1952.87 546.801 1952.87 581 1952 c 0,122,123 + 606.959 1954.33 l 0,124,125 + 630.094 1960.29 630.094 1960.29 630.065 1981.19 c 0,126,127 + 630.039 1999.11 630.039 1999.11 613 2028 c 0,128,129 + 669 2013 669 2013 673.5 1945 c 0,130,131 + 672.229 1913.5 l 0,132,133 + 665.109 1871.18 665.109 1871.18 627 1854 c 0,134,135 + 536.013 1812.01 536.013 1812.01 491.5 1808 c 0,136,137 + 446.998 1803.99 446.998 1803.99 414 1714 c 1,98,99 +EndSplineSet +EndChar +StartChar: sacute +Encoding: 347 347 90 +Width: 1004 +Flags: HW +Fore +589 120 m 0,0,1 + 406 130.001 406 130.001 245 125.5 c 0,2,3 + 204.652 128.097 l 0,4,5 + 78.8561 149.094 78.8561 149.094 45 334 c 0,6,7 + 67 277 67 277 128.5 251.5 c 0,8,9 + 190 226 190 226 208 334 c 0,10,11 + 208.984 365.264 l 0,12,13 + 205.085 404.631 205.085 404.631 172.5 425.5 c 0,14,15 + 145.386 442.865 145.386 442.865 111.404 442.967 c 0,16,17 + 89.6139 443.033 89.6139 443.033 65 436 c 0,18,19 + 98.2419 492.813 98.2419 492.813 141.164 493.188 c 0,20,21 + 152.496 493.287 152.496 493.287 164.502 489.453 c 0,22,23 + 182.263 483.78 182.263 483.78 201.5 469.5 c 0,24,25 + 282.999 409 282.999 409 314 358 c 0,26,27 + 393 223 393 223 462 248.5 c 0,28,29 + 531 274 531 274 566 354.5 c 0,30,31 + 601 435 601 435 590 518 c 0,32,33 + 581.055 585.495 581.055 585.495 526.482 585.539 c 0,34,35 + 513.945 585.55 513.945 585.55 499 582 c 0,36,37 + 475 576 475 576 476 556 c 0,38,39 + 477 536 477 536 495 520 c 0,40,41 + 505.707 509.293 505.707 509.293 519.014 509.205 c 0,42,43 + 533.844 509.107 533.844 509.107 553 523 c 0,44,45 + 525.682 451.808 525.682 451.808 491.854 451.542 c 0,46,47 + 484.818 451.487 484.818 451.487 477.5 454.5 c 0,48,49 + 435 472 435 472 396 529 c 0,50,51 + 357 586 357 586 327.5 650.5 c 0,52,53 + 297.998 715.003 297.998 715.003 291 723 c 0,54,55 + 175.998 841.002 175.998 841.002 71 977 c 0,56,57 + 14.885 1049.69 14.885 1049.69 14.7503 1131.79 c 0,58,59 + 14.651 1192.36 14.651 1192.36 45.0218 1258.07 c 0,60,61 + 50.513 1269.95 50.513 1269.95 57 1282 c 0,62,63 + 69.0071 1305.01 69.0071 1305.01 98.5 1319 c 0,64,65 + 114.087 1322.62 l 0,66,67 + 134.507 1322.16 134.507 1322.16 152 1293 c 0,68,69 + 139.415 1300.69 139.415 1300.69 128.112 1300.87 c 0,70,71 + 113.474 1297.69 l 0,72,73 + 101.083 1291.89 101.083 1291.89 90.5 1275.5 c 0,74,75 + 79.2991 1258.15 79.2991 1258.15 78.9994 1245.72 c 0,76,77 + 81.6689 1234.06 l 0,78,79 + 85.7401 1226.63 85.7401 1226.63 96 1222 c 0,80,81 + 105.319 1217.64 105.319 1217.64 115.503 1217.7 c 0,82,83 + 156.677 1217.94 156.677 1217.94 212 1290.5 c 0,84,85 + 256.445 1348.79 256.445 1348.79 256.495 1390.28 c 0,86,87 + 256.523 1413.21 256.523 1413.21 243 1431 c 0,88,89 + 232.294 1444.38 232.294 1444.38 219.834 1444.75 c 0,90,91 + 206.014 1441.43 l 0,92,93 + 191.532 1434.32 191.532 1434.32 175 1412 c 0,94,95 + 174.516 1438.21 l 0,96,97 + 180.593 1484.96 180.593 1484.96 240.5 1504 c 0,98,99 + 314.701 1527.59 314.701 1527.59 417 1527.5 c 0,100,101 + 518 1527.01 518 1527.01 613 1512.5 c 0,102,103 + 708.126 1497.98 708.126 1497.98 738 1491 c 0,104,105 + 810.628 1472.32 810.628 1472.32 811.25 1418.96 c 0,106,107 + 807.364 1391.21 l 0,108,109 + 803.94 1378.58 803.94 1378.58 797.5 1364.5 c 0,110,111 + 751.998 1265 751.998 1265 675 1235 c 0,112,113 + 700.011 1266.02 700.011 1266.02 726 1311 c 0,114,115 + 739.549 1334.45 739.549 1334.45 739.791 1352.74 c 0,116,117 + 736.569 1370.08 l 0,118,119 + 733.894 1376.47 733.894 1376.47 729 1382 c 0,120,121 + 710.995 1402 710.995 1402 678 1403.5 c 0,122,123 + 661.255 1400.79 l 0,124,125 + 638.683 1392.11 638.683 1392.11 621 1356 c 0,126,127 + 567 1248 567 1248 607.5 1207.5 c 0,128,129 + 646.962 1168.04 646.962 1168.04 724 1168 c 0,130,131 + 800.014 1169.01 800.014 1169.01 882 1199 c 0,132,133 + 963.994 1229 963.994 1229 993 1264 c 0,134,135 + 930.004 1159.01 930.004 1159.01 807.5 1116 c 0,136,137 + 685 1072.99 685 1072.99 560 1119 c 0,138,139 + 431.01 1165.99 431.01 1165.99 374.5 1247.5 c 0,140,141 + 354.599 1276.2 354.599 1276.2 333.396 1277.06 c 0,142,143 + 317.756 1273.98 l 0,144,145 + 285.794 1260.26 285.794 1260.26 251 1186 c 0,146,147 + 229.83 1142.95 229.83 1142.95 229.824 1094.68 c 0,148,149 + 229.821 1074.55 229.821 1074.55 233.5 1053.5 c 0,150,151 + 245.999 982 245.999 982 310 932 c 0,152,153 + 340 908 340 908 372 938 c 0,154,155 + 404 968 404 968 357 998 c 0,156,157 + 414 1017.01 414 1017.01 447.5 995 c 0,158,159 + 481.001 972.998 481.001 972.998 528 899 c 0,160,161 + 544.996 871.005 544.996 871.005 613 793 c 0,162,163 + 681.005 714.993 681.005 714.993 741.5 625.5 c 0,164,165 + 802.001 535.997 802.001 535.997 825 455 c 0,166,167 + 830.495 435.646 830.495 435.646 830.51 419.09 c 0,168,169 + 830.557 366.353 830.557 366.353 775 342 c 0,170,171 + 775 369 775 369 769 394.5 c 0,172,173 + 763 420 763 420 731 412 c 0,174,175 + 728 411 728 411 704 376 c 0,176,177 + 680.003 341.004 680.003 341.004 662.5 301.5 c 0,178,179 + 646.815 266.098 646.815 266.098 646.795 239.931 c 0,180,181 + 646.793 236.903 646.793 236.903 647 234 c 0,182,183 + 648.32 215.509 648.32 215.509 671.01 215.335 c 0,184,185 + 682.679 215.245 682.679 215.245 700 220 c 0,186,187 + 719.174 225.478 719.174 225.478 719.5 243 c 0,188,189 + 720.689 277.847 l 0,190,191 + 720.838 278.919 720.838 278.919 721 280 c 0,192,193 + 748.912 251.652 748.912 251.652 749.34 226.442 c 0,194,195 + 745.982 208.436 l 0,196,197 + 737.062 186.118 737.062 186.118 704.5 166.5 c 0,198,199 + 624 118.001 624 118.001 589 120 c 0,0,1 +360 1621 m 1,94,95 + 340 1634.99 340 1634.99 344.5 1723 c 0,96,97 + 349 1811 349 1811 388 1899.5 c 0,98,99 + 427.003 1988.01 427.003 1988.01 506 2041 c 0,100,101 + 544.749 2066.99 544.749 2066.99 596.004 2067.01 c 0,102,103 + 649.255 2067.03 649.255 2067.03 716 2039 c 0,104,105 + 636.712 2038.65 l 0,106,107 + 592.755 2036.02 592.755 2036.02 559.5 2027.5 c 0,108,109 + 499 2012.01 499 2012.01 472 1930 c 0,110,111 + 436 1825 436 1825 502 1823.5 c 0,112,113 + 568 1822 568 1822 529 1888 c 0,114,115 + 577.001 1874.99 577.001 1874.99 580.5 1817 c 0,116,117 + 578.704 1787.04 l 0,118,119 + 571.864 1754.29 571.864 1754.29 541 1740 c 0,120,121 + 462.986 1703.99 462.986 1703.99 425.5 1700.5 c 0,122,123 + 388 1697.01 388 1697.01 360 1621 c 1,94,95 +EndSplineSet +EndChar +StartChar: Zacute +Encoding: 377 377 91 +Width: 1478 +Flags: HMW +HStem: -67.4639 277.536<303.18 1275.14> 1344.32 217.56<298.476 1314.54> 1899.4 128.77<686.556 1148.72> +Fore +1282.79 1570.7 m 0,0,1 + 1372.16 1569.53 1372.16 1569.53 1401.56 1504.26 c 0,2,3 + 1421.76 1459.42 1421.76 1459.42 1421.7 1406.8 c 0,4,5 + 1421.67 1382.84 1421.67 1382.84 1417.44 1357.26 c 0,6,7 + 1403.93 1275.56 1403.93 1275.56 1357.46 1202.62 c 0,8,9 + 1311 1129.7 1311 1129.7 1249.86 1114.42 c 0,10,11 + 1352.93 1230.64 1352.93 1230.64 1352.86 1291.21 c 0,12,13 + 1352.82 1328.08 1352.82 1328.08 1314.54 1344.32 c 0,14,15 + 1293.11 1353.42 1293.11 1353.42 1272.11 1353.51 c 0,16,17 + 1250.07 1353.61 1250.07 1353.61 1228.5 1343.8 c 0,18,19 + 1173.58 1318.83 1173.58 1318.83 1121.68 1229.66 c 0,20,21 + 1084.05 1164.98 1084.05 1164.98 1074.64 1051.5 c 0,22,23 + 1065.23 938.016 1065.23 938.016 1046.41 863.928 c 0,24,25 + 1028.77 800.421 1028.77 800.421 986.436 744.563 c 0,26,27 + 944.1 688.704 944.1 688.704 870.012 734.568 c 0,28,29 + 920.58 743.976 920.58 743.976 926.46 779.256 c 0,30,31 + 932.34 814.536 932.34 814.536 901.764 815.712 c 0,32,33 + 839.436 816.888 839.436 816.888 810.036 749.268 c 0,34,35 + 780.636 681.646 780.636 681.646 759.468 600.504 c 0,36,37 + 738.3 519.36 738.3 519.36 714.78 452.328 c 0,38,39 + 691.26 385.296 691.26 385.296 643.044 390 c 0,40,41 + 681.852 437.04 681.852 437.04 669.504 464.088 c 0,42,43 + 657.156 491.136 657.156 491.136 635.988 486.432 c 0,44,45 + 583.066 473.496 583.066 473.496 536.616 361.188 c 0,46,47 + 490.164 248.88 490.164 248.88 506.628 213.6 c 0,48,49 + 532.5 153.624 532.5 153.624 653.628 151.271 c 0,50,51 + 718.72 153.447 l 0,52,53 + 779.51 159.89 779.51 159.89 790.044 184.2 c 0,54,55 + 805.332 218.304 805.332 218.304 770.052 233.592 c 0,56,57 + 734.771 248.88 734.771 248.88 718.308 224.184 c 0,58,59 + 753.588 322.968 753.588 322.968 848.256 248.88 c 0,60,61 + 942.924 174.792 942.924 174.792 1031.12 157.152 c 0,62,63 + 1075.81 147.744 1075.81 147.744 1142.84 174.792 c 0,64,65 + 1209.88 201.84 1209.88 201.84 1275.14 210.072 c 0,66,67 + 1340.41 218.304 1340.41 218.304 1392.74 178.908 c 0,68,69 + 1445.07 139.512 1445.07 139.512 1460.36 -1.6084 c 0,70,71 + 1422.73 93.6475 1422.73 93.6475 1351.58 86.5918 c 0,72,73 + 1280.44 79.5361 1280.44 79.5361 1203.41 28.9678 c 0,74,75 + 1126.37 -21.611 1126.37 -21.611 1058.76 -84.5156 c 0,76,77 + 991.14 -147.432 991.14 -147.432 961.74 -167.424 c 0,78,79 + 922.932 -190.944 922.932 -190.944 842.964 -180.36 c 0,80,81 + 762.996 -169.776 762.996 -169.776 750.06 -123.912 c 0,82,83 + 769.443 -127.877 769.443 -127.877 787.093 -127.799 c 0,84,85 + 816.561 -127.668 816.561 -127.668 841.2 -116.269 c 0,86,87 + 857.586 -108.687 857.586 -108.687 858.002 -97.3406 c 0,88,89 + 854.262 -84.773 l 0,90,91 + 847.346 -72.9171 847.346 -72.9171 827.676 -58.0557 c 0,92,93 + 767.7 -12.1925 767.7 -12.1925 569.544 -27.4805 c 0,94,95 + 371.388 -42.7687 371.388 -42.7687 303.18 -67.4639 c 0,96,97 + 220.858 -95.6885 220.858 -95.6885 118.548 -67.4639 c 0,98,99 + 16.2354 -39.2402 16.2354 -39.2402 16.2354 38.376 c 0,100,101 + 85.6201 -29.832 85.6201 -29.832 165 -9.25195 c 0,102,103 + 244.38 11.3281 244.38 11.3281 263.196 112.464 c 0,104,105 + 274.956 177.144 274.956 177.144 259.668 261.816 c 0,106,107 + 244.38 346.488 244.38 346.488 244.38 418.224 c 0,108,109 + 244.38 489.96 244.38 489.96 280.836 532.296 c 0,110,111 + 317.292 574.632 317.292 574.632 434.892 554.64 c 0,112,113 + 377.268 542.88 377.268 542.88 370.212 521.712 c 0,114,115 + 364.587 510.863 364.587 510.863 364.316 503.172 c 0,116,117 + 366.552 493.963 l 0,118,119 + 370.814 487.229 370.814 487.229 383.147 485.256 c 0,120,121 + 460.764 467.616 460.764 467.616 557.784 590.508 c 0,122,123 + 654.804 713.4 654.804 713.4 577.188 774.552 c 0,124,125 + 541.908 800.424 541.908 800.424 519.563 766.908 c 0,126,127 + 497.219 733.39 497.219 733.39 486.636 702.816 c 0,128,129 + 459.588 771.022 459.588 771.022 540.144 836.88 c 0,130,131 + 620.7 902.736 620.7 902.736 721.836 973.884 c 0,132,133 + 822.936 1045 822.936 1045 900 1125 c 0,134,135 + 954.038 1181.1 954.038 1181.1 953.961 1245.89 c 0,136,137 + 953.928 1273.45 953.928 1273.45 944.1 1302.58 c 0,138,139 + 936.209 1323.38 936.209 1323.38 914.101 1323.4 c 0,140,141 + 899.961 1323.41 899.961 1323.41 880.008 1314.92 c 0,142,143 + 828.957 1293.22 828.957 1293.22 771.228 1271.41 c 0,144,145 + 713.604 1249.66 713.604 1249.66 668.328 1255.54 c 0,146,147 + 623.052 1261.42 623.052 1261.42 623.052 1349.62 c 0,148,149 + 673.62 1284.94 673.62 1284.94 723.012 1320.22 c 0,150,151 + 739.476 1330.8 739.476 1330.8 740.063 1354.32 c 0,152,153 + 737.416 1374.98 l 0,154,155 + 734.913 1381.67 734.913 1381.67 730.067 1384.9 c 0,156,157 + 667.74 1423.71 667.74 1423.71 607.764 1389.01 c 0,158,159 + 547.788 1354.31 547.788 1354.31 488.988 1308.46 c 0,160,161 + 430.188 1262.59 430.188 1262.59 370.212 1237.9 c 0,162,163 + 310.234 1213.2 310.234 1213.2 249.084 1273.18 c 0,164,165 + 213.804 1304.93 213.804 1304.93 213.804 1361.38 c 0,166,167 + 217.335 1346.08 217.335 1346.08 264.96 1316.1 c 0,168,169 + 297.51 1295.61 297.51 1295.61 325.383 1295.71 c 0,170,171 + 338.304 1295.75 338.304 1295.75 350.22 1300.22 c 0,172,173 + 385.506 1313.17 385.506 1313.17 402.552 1333.74 c 0,174,175 + 414.513 1348.18 414.513 1348.18 414.612 1380.26 c 0,176,177 + 414.655 1393.92 414.655 1393.92 412.548 1410.77 c 0,178,179 + 393.73 1541.3 393.73 1541.3 254.964 1490.15 c 0,180,181 + 116.189 1438.98 116.189 1438.98 72.6836 1360.2 c 0,182,183 + 45.6312 1311.97 45.6312 1311.97 30.3477 1250.83 c 0,184,185 + 28.8703 1292.72 l 0,186,187 + 30.8234 1327.58 30.8234 1327.58 43.2842 1363.14 c 0,188,189 + 63.2687 1420.17 63.2687 1420.17 86.7959 1451.93 c 0,190,191 + 162.06 1557.77 162.06 1557.77 298.476 1561.88 c 0,192,193 + 434.892 1566.01 434.892 1566.01 547.788 1534.25 c 0,194,195 + 615.363 1515.28 615.363 1515.28 705.509 1515.29 c 0,196,197 + 794.181 1515.29 794.181 1515.29 904.704 1533.66 c 0,198,199 + 1127.58 1570.7 1127.58 1570.7 1282.79 1570.7 c 0,0,1 +1148.72 2028.17 m 1,119,120 + 1051.12 1851.78 1051.12 1851.78 857.076 1850.59 c 0,121,122 + 775.932 1849.42 775.932 1849.42 745.944 1796.5 c 0,123,124 + 715.958 1743.58 715.958 1743.58 699.492 1669.49 c 0,125,126 + 655.406 1731.47 655.406 1731.47 655.406 1793.96 c 0,127,128 + 655.405 1846.49 655.405 1846.49 686.556 1899.4 c 0,129,130 + 754.76 2015.22 754.76 2015.22 860.604 2057.57 c 0,131,132 + 898.203 2071.67 898.203 2071.67 939.396 2074.03 c 0,133,134 + 980.556 2076.39 980.556 2076.39 988.788 2050.51 c 0,135,136 + 946.452 2061.1 946.452 2061.1 915.288 2031.7 c 0,137,138 + 884.124 2002.3 884.124 2002.3 911.172 1978.78 c 0,139,140 + 946.337 1945.68 946.337 1945.68 985.142 1945.74 c 0,141,142 + 1012.52 1945.77 1012.52 1945.77 1041.71 1962.31 c 0,143,144 + 1112.3 2002.32 1112.3 2002.32 1148.72 2028.17 c 1,119,120 +EndSplineSet +EndChar +StartChar: zacute +Encoding: 378 378 92 +Width: 1265 +Flags: HMW +HStem: 9 236<259 1085.5> 1209.5 185<255 1119> 1681.5 109.5<585 978> +Fore +1092 1402 m 0,0,1 + 1168 1400.99 1168 1400.99 1193 1345.5 c 0,2,3 + 1210.2 1307.32 1210.2 1307.32 1210.13 1262.5 c 0,4,5 + 1206.5 1220.5 l 0,6,7 + 1194.99 1150.99 1194.99 1150.99 1155.5 1089 c 0,8,9 + 1116.01 1027.01 1116.01 1027.01 1064 1014 c 0,10,11 + 1151.63 1112.81 1151.63 1112.81 1151.58 1164.32 c 0,12,13 + 1151.55 1195.69 1151.55 1195.69 1119 1209.5 c 0,14,15 + 1100.65 1217.29 1100.65 1217.29 1082.66 1217.31 c 0,16,17 + 1016.35 1217.4 1016.35 1217.4 955 1112 c 0,18,19 + 922.999 1056.99 922.999 1056.99 915 960.5 c 0,20,21 + 907 864 907 864 891 801 c 0,22,23 + 876 747 876 747 840 699.5 c 0,24,25 + 804 652 804 652 741 691 c 0,26,27 + 784 699 784 699 789 729 c 0,28,29 + 794 759 794 759 768 760 c 0,30,31 + 743.841 757.016 l 0,32,33 + 708.911 746.994 708.911 746.994 690 703.5 c 0,34,35 + 665 646 665 646 647 577 c 0,36,37 + 629 508 629 508 609 451 c 0,38,39 + 590.312 397.737 590.312 397.737 553.287 397.738 c 0,40,41 + 550.689 397.738 550.689 397.738 548 398 c 0,42,43 + 581 438 581 438 570.5 461 c 0,44,45 + 561.842 479.965 561.842 479.965 548.085 480.573 c 0,46,47 + 542 480 l 0,48,49 + 497 469 497 469 457.5 373.5 c 0,50,51 + 418 278 418 278 432 248 c 0,52,53 + 454.001 196.999 454.001 196.999 557 195 c 0,54,55 + 614.825 197.124 l 0,56,57 + 664.258 202.828 664.258 202.828 673 223 c 0,58,59 + 686 251.999 686 251.999 656 265 c 0,60,61 + 626 278 626 278 612 257 c 0,62,63 + 642 341 642 341 722.5 278 c 0,64,65 + 803 215 803 215 878 200 c 0,66,67 + 916 192.001 916 192.001 973 215 c 0,68,69 + 1030 237.999 1030 237.999 1085.5 245 c 0,70,71 + 1118.85 245.448 l 0,72,73 + 1154.79 241.615 1154.79 241.615 1185.5 218.5 c 0,74,75 + 1229.99 185.009 1229.99 185.009 1243 65 c 0,76,77 + 1213.43 139.87 1213.43 139.87 1159.49 140.41 c 0,78,79 + 1155.08 140.454 1155.08 140.454 1150.5 140 c 0,80,81 + 1090.01 134 1090.01 134 1024.5 91 c 0,82,83 + 959 48 959 48 901.5 -5.5 c 0,84,85 + 844 -59 844 -59 819 -76 c 0,86,87 + 786 -95.9999 786 -95.9999 718 -87 c 0,88,89 + 649.999 -77.9999 649.999 -77.9999 639 -39 c 0,90,91 + 673.033 -42.2686 l 0,92,93 + 696.616 -41.7 696.616 -41.7 716.5 -32.5 c 0,94,95 + 750 -17 750 -17 705 17 c 0,96,97 + 654 56 654 56 485.5 43 c 0,98,99 + 317 30 317 30 259 9 c 0,100,101 + 223.777 -3.07646 223.777 -3.07646 184.25 -2.99951 c 0,102,103 + 145.223 -2.92354 145.223 -2.92354 102 9 c 0,104,105 + 15 33 15 33 15 99 c 0,106,107 + 74 41 74 41 141.5 58.5 c 0,108,109 + 208.999 75.9999 208.999 75.9999 225 162 c 0,110,111 + 229.41 186.252 229.41 186.252 229.347 213.809 c 0,112,113 + 229.268 248.748 229.268 248.748 222 289 c 0,114,115 + 209 360.997 209 360.997 209 422 c 0,116,117 + 209 483.001 209 483.001 240 519 c 0,118,119 + 261.061 543.458 261.061 543.458 313.971 543.453 c 0,120,121 + 338.939 543.45 338.939 543.45 371 538 c 0,122,123 + 322 528 322 528 316 510 c 0,124,125 + 311.032 500.419 311.032 500.419 310.975 493.735 c 0,126,127 + 310.877 482.339 310.877 482.339 327 479 c 0,128,129 + 393 464 393 464 475.5 568.5 c 0,130,131 + 521.099 626.259 521.099 626.259 521.332 667.979 c 0,132,133 + 521.432 685.754 521.432 685.754 513.296 700.618 c 0,134,135 + 505.978 713.987 505.978 713.987 492 725 c 0,136,137 + 462 747 462 747 443 718.5 c 0,138,139 + 424 690 424 690 415 664 c 0,140,141 + 409.149 678.754 409.149 678.754 409.22 693.379 c 0,142,143 + 409.425 736.246 409.425 736.246 460.5 778 c 0,144,145 + 529.009 834.007 529.009 834.007 615 894.5 c 0,146,147 + 700.997 954.997 700.997 954.997 766.5 1023 c 0,148,149 + 812.481 1070.73 812.481 1070.73 812.385 1125.86 c 0,150,151 + 812.344 1149.27 812.344 1149.27 804 1174 c 0,152,153 + 793 1202.99 793 1202.99 749.5 1184.5 c 0,154,155 + 705.784 1165.91 705.784 1165.91 657 1147.5 c 0,156,157 + 618.64 1133.02 618.64 1133.02 586.715 1132.94 c 0,158,159 + 577.86 1132.92 577.86 1132.92 569.5 1134 c 0,160,161 + 531 1138.99 531 1138.99 531 1214 c 0,162,163 + 558.823 1178.41 558.823 1178.41 586.228 1178.41 c 0,164,165 + 601.176 1178.41 601.176 1178.41 616 1189 c 0,166,167 + 630 1198 630 1198 630.5 1218 c 0,168,169 + 627.915 1236.42 l 0,170,171 + 625.807 1241.46 625.807 1241.46 622 1244 c 0,172,173 + 593.97 1261.45 593.97 1261.45 566.502 1261.43 c 0,174,175 + 542.028 1261.4 542.028 1261.4 518 1247.5 c 0,176,177 + 466.973 1217.98 466.973 1217.98 417 1179 c 0,178,179 + 367 1140 367 1140 316 1119 c 0,180,181 + 301.146 1112.88 301.146 1112.88 286.207 1112.88 c 0,182,183 + 249.855 1112.85 249.855 1112.85 213 1149 c 0,184,185 + 183 1176 183 1176 183 1224 c 0,186,187 + 185.999 1211 185.999 1211 226.5 1185.5 c 0,188,189 + 267 1160 267 1160 299 1172 c 0,190,191 + 329 1182.99 329 1182.99 343.5 1200.5 c 0,192,193 + 353.794 1212.93 353.794 1212.93 353.756 1240.72 c 0,194,195 + 353.74 1252.08 353.74 1252.08 352 1266 c 0,196,197 + 340.537 1345.52 340.537 1345.52 276.723 1345.75 c 0,198,199 + 251.463 1345.84 251.463 1345.84 218 1333.5 c 0,200,201 + 99.9967 1290 99.9967 1290 63 1223 c 0,202,203 + 40 1182.01 40 1182.01 27 1130 c 0,204,205 + 25.9714 1169.14 l 0,206,207 + 28.0316 1197.06 28.0316 1197.06 38 1225.5 c 0,208,209 + 55.0032 1274 55.0032 1274 75 1301 c 0,210,211 + 139.004 1391.01 139.004 1391.01 255 1394.5 c 0,212,213 + 335.599 1393.09 l 0,214,215 + 405.421 1388.32 405.421 1388.32 467 1371 c 0,216,217 + 524.66 1354.82 524.66 1354.82 601.628 1354.88 c 0,218,219 + 676.847 1354.93 676.847 1354.93 770.5 1370.5 c 0,220,221 + 960 1402 960 1402 1092 1402 c 0,0,1 +978 1791 m 1,119,120 + 895.003 1641.01 895.003 1641.01 730 1640 c 0,121,122 + 660.997 1638.99 660.997 1638.99 635.5 1594 c 0,123,124 + 610 1549 610 1549 596 1486 c 0,125,126 + 558.765 1538.35 558.765 1538.35 558.513 1591.13 c 0,127,128 + 558.415 1611.74 558.415 1611.74 563.958 1632.42 c 0,129,130 + 570.523 1656.91 570.523 1656.91 585 1681.5 c 0,131,132 + 642.997 1780 642.997 1780 733 1816 c 0,133,134 + 765.015 1828.01 765.015 1828.01 800 1830 c 0,135,136 + 822.603 1828.04 l 0,137,138 + 837.667 1823.62 837.667 1823.62 842 1810 c 0,139,140 + 818.356 1812.17 l 0,141,142 + 796.883 1810.4 796.883 1810.4 779.5 1794 c 0,143,144 + 765.367 1780.66 765.367 1780.66 765.313 1768.75 c 0,145,146 + 765.267 1758.33 765.267 1758.33 776 1749 c 0,147,148 + 805.866 1720.89 805.866 1720.89 838.816 1720.9 c 0,149,150 + 862.136 1720.91 862.136 1720.91 887 1735 c 0,151,152 + 947.068 1769.04 947.068 1769.04 978 1791 c 1,119,120 +EndSplineSet +EndChar +StartChar: Zdotaccent +Encoding: 379 379 93 +Width: 1555 +Flags: HMW +HStem: -105.28 182.83<79.9004 1308.01> 1407.18 141.47<120.32 1356.42> 1778.01 73.79<756.7 935.3> +Fore +899.58 1112.02 m 1,0,1 + 885.839 1123.16 885.839 1123.16 875.473 1123.15 c 0,2,3 + 859.6 1123.14 859.6 1123.14 851.64 1096.98 c 0,4,5 + 838.48 1053.73 838.48 1053.73 837.54 1039.64 c 0,6,7 + 802.76 1085.7 802.76 1085.7 843.18 1152.44 c 0,8,9 + 883.574 1219.13 883.574 1219.13 912.27 1277.46 c 0,10,11 + 926.839 1307.07 926.839 1307.07 926.965 1330.74 c 0,12,13 + 927.063 1349.1 927.063 1349.1 918.475 1363.88 c 0,14,15 + 916.345 1367.54 916.345 1367.54 913.68 1370.99 c 0,16,17 + 886.421 1406.24 886.421 1406.24 716.28 1389.32 c 0,18,19 + 660.522 1383.74 660.522 1383.74 630.27 1370.05 c 0,20,21 + 612.219 1361.74 612.219 1361.74 611.81 1344.53 c 0,22,23 + 615.659 1325.47 l 0,24,25 + 616.892 1322.25 616.892 1322.25 618.52 1318.82 c 0,26,27 + 633.4 1284.81 633.4 1284.81 658.163 1284.45 c 0,28,29 + 675.39 1287.8 l 0,30,31 + 712.521 1301.9 712.521 1301.9 742.6 1332.92 c 0,32,33 + 742.6 1263.36 742.6 1263.36 691.84 1237.04 c 0,34,35 + 641.08 1210.71 641.08 1210.71 574.81 1211.66 c 0,36,37 + 508.505 1212.61 508.505 1212.61 444.62 1231.87 c 0,38,39 + 380.701 1251.15 380.701 1251.15 354.38 1272.76 c 0,40,41 + 279.181 1331.03 279.181 1331.03 195.05 1417.99 c 0,42,43 + 153.956 1460.46 153.956 1460.46 120.822 1460.88 c 0,44,45 + 102.421 1457.64 l 0,46,47 + 78.9938 1448.77 78.9938 1448.77 60.1602 1415.64 c 0,48,49 + 48.9799 1395.91 48.9799 1395.91 48.8423 1384.23 c 0,50,51 + 48.7833 1379.22 48.7833 1379.22 50.7598 1375.69 c 0,52,53 + 57.38 1363.87 57.38 1363.87 71.4404 1342.32 c 0,54,55 + -2.82025 1366.76 -2.82025 1366.76 7.51953 1438.2 c 0,56,57 + 23.5391 1548.56 23.5391 1548.56 110.343 1548.95 c 0,58,59 + 115.22 1548.97 115.22 1548.97 120.32 1548.65 c 0,60,61 + 199.929 1547.52 l 0,62,63 + 257.241 1549.51 257.241 1549.51 315.84 1559.46 c 0,64,65 + 345.926 1565.1 345.926 1565.1 379.29 1598.47 c 0,66,67 + 400.507 1619.69 400.507 1619.69 400.634 1635.02 c 0,68,69 + 400.707 1643.79 400.707 1643.79 393.86 1650.64 c 0,70,71 + 368.48 1673.2 368.48 1673.2 344.98 1664.74 c 0,72,73 + 321.479 1656.28 321.479 1656.28 291.4 1642.18 c 0,74,75 + 331.304 1714.47 331.304 1714.47 372.273 1715.24 c 0,76,77 + 390.844 1711.94 l 0,78,79 + 407.307 1705.8 407.307 1705.8 423.94 1688.24 c 0,80,81 + 491.602 1616.81 491.602 1616.81 547.08 1574.5 c 0,82,83 + 628.867 1510.58 628.867 1510.58 781.14 1499.3 c 0,84,85 + 854.669 1497.47 l 0,86,87 + 948.034 1500.65 948.034 1500.65 988.88 1535.96 c 0,88,89 + 998.844 1545.01 998.844 1545.01 998.771 1553.85 c 0,90,91 + 998.693 1563.36 998.693 1563.36 987 1572.62 c 0,92,93 + 960.068 1591.04 960.068 1591.04 941.426 1591.04 c 0,94,95 + 935.336 1591.04 935.336 1591.04 930.13 1589.07 c 0,96,97 + 908.941 1581.06 908.941 1581.06 880.78 1563.22 c 0,98,99 + 886.421 1611.17 886.421 1611.17 938.12 1632.78 c 0,100,101 + 949.999 1637.46 949.999 1637.46 966.568 1637.38 c 0,102,103 + 993.252 1637.26 993.252 1637.26 1032.12 1624.79 c 0,104,105 + 1095.13 1604.58 1095.13 1604.58 1169.36 1586.72 c 0,106,107 + 1233.67 1571.25 1233.67 1571.25 1298.71 1571.3 c 0,108,109 + 1308.76 1571.3 1308.76 1571.3 1318.82 1571.68 c 0,110,111 + 1394.03 1574.5 1394.03 1574.5 1449.48 1634.66 c 0,112,113 + 1507.75 1698.57 1507.75 1698.57 1441.02 1767.2 c 0,114,115 + 1512.47 1741.82 1512.47 1741.82 1512.93 1690.12 c 0,116,117 + 1509.33 1652.82 l 0,118,119 + 1502.52 1618.66 1502.52 1618.66 1482.85 1582.96 c 0,120,121 + 1452.26 1527.44 1452.26 1527.44 1410.47 1477.68 c 0,122,123 + 1368.67 1427.9 1368.67 1427.9 1356.42 1407.18 c 0,124,125 + 1319.75 1342.31 1319.75 1342.31 1317.88 1291.56 c 0,126,127 + 1316.11 1243.75 1316.11 1243.75 1225.93 1243.47 c 0,128,129 + 1220.37 1243.46 1220.37 1243.46 1214.48 1243.62 c 0,130,131 + 1256.77 1262.41 1256.77 1262.41 1278.87 1299.55 c 0,132,133 + 1287.73 1314.43 1287.73 1314.43 1288.05 1325.17 c 0,134,135 + 1284.94 1337.23 l 0,136,137 + 1280.54 1344.11 1280.54 1344.11 1269.94 1347.96 c 0,138,139 + 1254.4 1352.93 1254.4 1352.93 1239.99 1352.87 c 0,140,141 + 1210.82 1352.75 1210.82 1352.75 1186.28 1331.98 c 0,142,143 + 1149.62 1300.96 1149.62 1300.96 1128 1256.78 c 0,144,145 + 1106.39 1212.61 1106.39 1212.61 1102.62 1171.71 c 0,146,147 + 1103.32 1145.19 l 0,148,149 + 1106.66 1129.34 1106.66 1129.34 1118.6 1127.06 c 0,150,151 + 1149.01 1123.83 l 0,152,153 + 1183.71 1125.42 1183.71 1125.42 1184.4 1159.02 c 0,154,155 + 1181.58 1187.33 l 0,156,157 + 1175.31 1213.23 1175.31 1213.23 1155.26 1229.52 c 0,158,159 + 1207.9 1213.54 1207.9 1213.54 1220.12 1178.76 c 0,160,161 + 1226.02 1159.08 1226.02 1159.08 1226.03 1142.66 c 0,162,163 + 1226.05 1112.03 1226.05 1112.03 1205.55 1092.75 c 0,164,165 + 1174.05 1063.13 1174.05 1063.13 1128 1038.7 c 0,166,167 + 1081.99 1014.29 1081.99 1014.29 1040.58 984.18 c 0,168,169 + 999.219 954.096 999.219 954.096 997.34 898.64 c 0,170,171 + 995.46 844.12 995.46 844.12 1074.42 873.26 c 0,172,173 + 1063.14 833.78 1063.14 833.78 1026.48 814.98 c 0,174,175 + 989.819 796.18 989.819 796.18 960.68 786.78 c 0,176,177 + 862.921 756.701 862.921 756.701 761.4 647.66 c 0,178,179 + 659.881 538.622 659.881 538.622 606.3 418.3 c 0,180,181 + 567.675 331.563 567.675 331.563 567.641 256.305 c 0,182,183 + 567.628 227.167 567.628 227.167 573.4 199.75 c 0,184,185 + 594.081 101.52 594.081 101.52 740.72 94.9404 c 0,186,187 + 764.158 96.9563 l 0,188,189 + 790.657 103.873 790.657 103.873 806.99 132.54 c 0,190,191 + 817.439 150.879 817.439 150.879 817.342 166.896 c 0,192,193 + 817.225 186.181 817.225 186.181 801.82 202.1 c 0,194,195 + 774.56 227.48 774.56 227.48 739.78 213.38 c 0,196,197 + 705 199.28 705 199.28 684.32 175.78 c 0,198,199 + 694.659 249.099 694.659 249.099 734.61 259.91 c 0,200,201 + 749.507 263.941 749.507 263.941 765.712 263.855 c 0,202,203 + 792.962 263.709 792.962 263.709 823.91 251.92 c 0,204,205 + 873.255 233.122 873.255 233.122 923.55 200.22 c 0,206,207 + 973.841 167.32 973.841 167.32 1004.86 155.1 c 0,208,209 + 1213.54 67.6797 1213.54 67.6797 1308.01 77.5498 c 0,210,211 + 1402.48 87.42 1402.48 87.42 1532.2 208.68 c 0,212,213 + 1532.2 110.917 1532.2 110.917 1428.33 42.7695 c 0,214,215 + 1324.45 -25.381 1324.45 -25.381 1247.38 -31.96 c 0,216,217 + 1181.98 -32.991 l 0,218,219 + 1127.84 -30.5965 1127.84 -30.5965 1074.42 -17.3896 c 0,220,221 + 1048.4 -10.9567 1048.4 -10.9567 1024.38 -10.9157 c 0,222,223 + 969.438 -10.8217 969.438 -10.8217 924.96 -44.1797 c 0,224,225 + 895.82 -63.9199 895.82 -63.9199 926.84 -93.0596 c 0,226,227 + 952.966 -116.283 952.966 -116.283 970.127 -116.534 c 0,228,229 + 975.194 -116.609 975.194 -116.609 979.48 -114.68 c 0,230,-1 + 1023.66 -94.9404 l 0,231,232 + 1010.51 -152.28 1010.51 -152.28 970.08 -156.51 c 0,233,234 + 929.659 -160.74 929.659 -160.74 881.25 -141.94 c 0,235,236 + 832.84 -123.14 832.84 -123.14 786.31 -95.4102 c 0,237,238 + 739.78 -67.6797 739.78 -67.6797 714.4 -61.0996 c 0,239,240 + 634.502 -38.5407 634.502 -38.5407 561.65 2.82031 c 0,241,242 + 528.265 21.7742 528.265 21.7742 498.729 21.7766 c 0,243,244 + 463.815 21.7794 463.815 21.7794 434.28 -4.7002 c 0,245,246 + 419.28 -18.2478 419.28 -18.2478 419.225 -32.0451 c 0,247,248 + 419.172 -45.0517 419.172 -45.0517 432.4 -58.2803 c 0,249,250 + 449.496 -77.2754 449.496 -77.2754 469.951 -77.5578 c 0,251,252 + 489.438 -73.8738 l 0,253,254 + 500.884 -69.5507 500.884 -69.5507 513.24 -60.1602 c 0,255,256 + 513.24 -103.401 513.24 -103.401 457.31 -113.74 c 0,257,258 + 401.38 -124.08 401.38 -124.08 364.72 -107.16 c 0,259,260 + 349.68 -99.6393 349.68 -99.6393 302.21 -62.5098 c 0,261,262 + 254.739 -25.3793 254.739 -25.3793 203.98 -2.82031 c 0,263,264 + 153.22 19.7402 153.22 19.7402 114.68 6.11035 c 0,265,266 + 76.1396 -7.51953 76.1396 -7.51953 79.9004 -105.28 c 0,267,268 + 80.8399 -158.86 80.8399 -158.86 137.71 -173.43 c 0,269,270 + 166.776 -180.876 166.776 -180.876 194.982 -180.834 c 0,271,272 + 221.964 -180.794 221.964 -180.794 248.16 -173.9 c 0,273,274 + 210.53 -210.624 210.53 -210.624 164.261 -210.829 c 0,275,276 + 141.869 -210.928 141.869 -210.928 117.454 -202.474 c 0,277,278 + 87.722 -192.179 87.722 -192.179 54.9902 -169.2 c 0,279,280 + -60.1601 -88.3605 -60.1601 -88.3605 20.6797 40.4199 c 0,281,282 + 101.52 169.2 101.52 169.2 232.65 252.39 c 0,283,284 + 363.779 335.579 363.779 335.579 440.86 465.3 c 0,285,286 + 506.658 578.096 506.658 578.096 568.23 757.17 c 0,287,288 + 629.8 936.24 629.8 936.24 731.32 956.92 c 0,289,290 + 715.341 942.82 715.341 942.82 710.17 918.38 c 0,291,292 + 705 893.94 705 893.94 719.1 878.9 c 0,293,294 + 731.321 864.8 731.321 864.8 767.04 894.41 c 0,295,296 + 802.76 924.02 802.76 924.02 837.54 967.73 c 0,297,298 + 872.326 1011.45 872.326 1011.45 893.47 1054.68 c 0,299,300 + 905.768 1079.82 905.768 1079.82 905.83 1095.11 c 0,301,302 + 905.875 1106.12 905.875 1106.12 899.58 1112.02 c 1,0,1 +830.02 1714.56 m 0,157,158 + 744.479 1724.89 744.479 1724.89 756.7 1778.01 c 0,159,160 + 768.919 1831.12 768.919 1831.12 815.92 1867.78 c 0,161,162 + 850.152 1894.18 850.152 1894.18 877.328 1894.33 c 0,163,164 + 894.699 1894.43 894.699 1894.43 909.187 1883.81 c 0,165,166 + 923.688 1873.18 923.688 1873.18 935.3 1851.8 c 0,167,168 + 940.628 1841.7 940.628 1841.7 940.686 1829.77 c 0,169,170 + 940.784 1809.32 940.784 1809.32 925.404 1783.45 c 0,171,172 + 919.676 1773.82 919.676 1773.82 911.8 1763.44 c 0,173,174 + 874.489 1714.25 874.489 1714.25 837.937 1714.03 c 0,175,176 + 833.974 1714.01 833.974 1714.01 830.02 1714.56 c 0,157,158 +EndSplineSet +EndChar +StartChar: zdotaccent +Encoding: 380 380 94 +Width: 1343 +Flags: HMW +HStem: -17.54 156.04<86.6797 1130.55> 1268.38 120.79<120.989 1172.38> 1583.75 62.51<661.489 814.239> +Fore +783.22 1017.4 m 0,0,1 + 772.103 1026.72 772.103 1026.72 763.586 1027.15 c 0,2,3 + 754.464 1024.58 l 0,4,5 + 747.245 1019.63 747.245 1019.63 742.8 1005.18 c 0,6,7 + 731.52 968.522 731.52 968.522 731.52 956.301 c 0,8,9 + 717.44 974.78 717.44 974.78 717.468 996.967 c 0,10,11 + 717.499 1022.18 717.499 1022.18 735.75 1052.18 c 0,12,13 + 770.065 1108.59 770.065 1108.59 794.029 1157.93 c 0,14,15 + 806.23 1183.05 806.23 1183.05 806.254 1203.18 c 0,16,17 + 806.278 1222.59 806.278 1222.59 794.97 1237.36 c 0,18,19 + 779.213 1257.94 779.213 1257.94 706.485 1257.84 c 0,20,21 + 672.904 1257.79 672.904 1257.79 627.18 1253.34 c 0,22,23 + 520.02 1242.06 520.02 1242.06 544.46 1194.12 c 0,24,25 + 557.187 1164.42 557.187 1164.42 578.153 1163.98 c 0,26,27 + 592.869 1166.86 l 0,28,29 + 624.375 1179.09 624.375 1179.09 649.739 1205.4 c 0,30,31 + 649.739 1146.18 649.739 1146.18 606.5 1124.09 c 0,32,33 + 565.004 1102.89 565.004 1102.89 511.821 1102.9 c 0,34,35 + 509.586 1102.9 509.586 1102.9 507.33 1102.94 c 0,36,37 + 451.4 1103.89 451.4 1103.89 396.88 1119.86 c 0,38,39 + 342.376 1135.83 342.376 1135.83 319.8 1154.64 c 0,40,41 + 255.841 1203.55 255.841 1203.55 183.97 1277.78 c 0,42,43 + 148.579 1314.33 148.579 1314.33 120.359 1314.45 c 0,44,45 + 96.4207 1314.55 96.4207 1314.55 77.6431 1288.43 c 0,46,47 + 73.5809 1282.78 73.5809 1282.78 69.7598 1275.9 c 0,48,49 + 55.6592 1252.4 55.6592 1252.4 61.7695 1242.06 c 0,50,-1 + 79.1592 1213.86 l 0,51,52 + 23.9276 1232.27 23.9276 1232.27 23.9089 1277.95 c 0,53,54 + 23.9056 1285.91 23.9056 1285.91 25.5801 1294.7 c 0,55,56 + 39.6797 1394.34 39.6797 1394.34 120.989 1389.17 c 0,57,58 + 193.089 1388.53 l 0,59,60 + 239.478 1390.61 239.478 1390.61 286.899 1399.04 c 0,61,62 + 312.279 1402.81 312.279 1402.81 340.949 1431.47 c 0,63,64 + 359.124 1449.64 359.124 1449.64 359.356 1462.34 c 0,65,66 + 356.047 1472.51 l 0,67,68 + 355.007 1473.89 355.007 1473.89 353.64 1475.18 c 0,69,70 + 337.706 1489.73 337.706 1489.73 322.537 1489.73 c 0,71,72 + 317.125 1489.72 317.125 1489.72 311.81 1487.87 c 0,73,74 + 291.561 1480.81 291.561 1480.81 266.22 1468.6 c 0,75,76 + 300.537 1530.26 300.537 1530.26 335.576 1530.55 c 0,77,78 + 347.721 1530.65 347.721 1530.65 359.953 1523.37 c 0,79,80 + 369.46 1517.72 369.46 1517.72 379.02 1507.61 c 0,81,82 + 436.376 1446.96 436.376 1446.96 484.3 1411.26 c 0,83,84 + 553.867 1357.67 553.867 1357.67 683.109 1347.34 c 0,85,86 + 812.359 1337 812.359 1337 859.359 1378.36 c 0,87,88 + 867.431 1385.58 867.431 1385.58 867.823 1392.61 c 0,89,90 + 864.543 1402.45 l 0,91,92 + 861.995 1405.94 861.995 1405.94 857.479 1409.38 c 0,93,94 + 834.929 1424.89 834.929 1424.89 819.247 1425.07 c 0,95,96 + 814.01 1425.13 814.01 1425.13 809.54 1423.48 c 0,97,98 + 791.682 1416.9 791.682 1416.9 768.18 1400.92 c 0,99,100 + 771.939 1442.27 771.939 1442.27 816.119 1460.14 c 0,101,102 + 826.07 1464.56 826.07 1464.56 840.359 1464.58 c 0,103,104 + 862.506 1464.6 862.506 1464.6 895.08 1454.03 c 0,105,106 + 948.721 1436.62 948.721 1436.62 1012.11 1421.13 c 0,107,108 + 1066.09 1407.93 1066.09 1407.93 1120.42 1408.01 c 0,109,110 + 1129.95 1408.02 1129.95 1408.02 1139.48 1408.44 c 0,111,112 + 1203.41 1411.26 1203.41 1411.26 1250.4 1462.02 c 0,113,114 + 1273.28 1487.06 1273.28 1487.06 1273.56 1512.89 c 0,115,116 + 1269.86 1534.57 l 0,117,118 + 1262.91 1554.47 1262.91 1554.47 1242.88 1574.82 c 0,119,120 + 1303.99 1552.26 1303.99 1552.26 1304.45 1508.55 c 0,121,122 + 1300.89 1474.26 l 0,123,124 + 1294.94 1446.53 1294.94 1446.53 1279.07 1417.37 c 0,125,126 + 1253.26 1369.95 1253.26 1369.95 1217.5 1328.07 c 0,127,128 + 1181.77 1286.22 1181.77 1286.22 1172.38 1268.38 c 0,129,130 + 1140.42 1213.86 1140.42 1213.86 1139.01 1170.62 c 0,131,132 + 1137.7 1130.33 1137.7 1130.33 1062.53 1130.03 c 0,133,134 + 1057.02 1130.01 1057.02 1130.01 1051.12 1130.2 c 0,135,136 + 1087.78 1145.25 1087.78 1145.25 1105.64 1177.2 c 0,137,138 + 1112.71 1189.84 1112.71 1189.84 1113.01 1198.95 c 0,139,140 + 1110.36 1209.59 l 0,141,142 + 1106.73 1215.37 1106.73 1215.37 1098.12 1218.56 c 0,143,144 + 1082.16 1223.88 1082.16 1223.88 1067.74 1223.88 c 0,145,146 + 1010.8 1223.89 1010.8 1223.89 977.8 1141.01 c 0,147,148 + 954.788 1083.22 954.788 1083.22 954.764 1055.55 c 0,149,150 + 954.744 1033.48 954.744 1033.48 969.34 1030.56 c 0,151,152 + 996.981 1028.25 l 0,153,154 + 1025.07 1030.62 1025.07 1030.62 1025.74 1058.29 c 0,155,156 + 1022.83 1084.53 l 0,157,158 + 1017.29 1104.61 1017.29 1104.61 1001.3 1117.04 c 0,159,160 + 1045.49 1104.81 1045.49 1104.81 1055.82 1074.74 c 0,161,162 + 1069.92 1026.8 1069.92 1026.8 1043.13 1001.42 c 0,163,164 + 1016.33 976.035 1016.33 976.035 977.33 955.36 c 0,165,166 + 938.317 934.68 938.317 934.68 903.069 909.301 c 0,167,168 + 867.819 883.919 867.819 883.919 866.88 836.92 c 0,169,170 + 869.21 820.455 l 0,171,172 + 874.76 806.996 874.76 806.996 893.248 806.83 c 0,173,174 + 904.345 806.73 904.345 806.73 920.103 811.419 c 0,175,176 + 925.633 813.065 925.633 813.065 931.739 815.301 c 0,177,178 + 921.4 781.459 921.4 781.459 890.85 765.48 c 0,179,180 + 860.294 749.498 860.294 749.498 834.92 741.98 c 0,181,182 + 752.2 716.601 752.2 716.601 665.72 623.54 c 0,183,184 + 579.239 530.48 579.239 530.48 534.119 428.021 c 0,185,186 + 501.638 354.259 501.638 354.259 501.553 290.485 c 0,187,188 + 501.519 265.672 501.519 265.672 506.39 242.37 c 0,189,190 + 523.779 159.181 523.779 159.181 648.8 153.54 c 0,191,192 + 669.809 155.334 l 0,193,194 + 691.55 161.305 691.55 161.305 705.199 185.03 c 0,195,196 + 714.026 200.372 714.026 200.372 714.019 213.929 c 0,197,198 + 714.011 230.69 714.011 230.69 700.5 244.721 c 0,199,200 + 677 266.341 677 266.341 647.39 254.591 c 0,201,202 + 617.78 242.842 617.78 242.842 599.92 223.101 c 0,203,204 + 612.578 307.278 612.578 307.278 662.312 307.291 c 0,205,206 + 686.442 307.297 686.442 307.297 719.3 287.49 c 0,207,208 + 819.881 226.859 819.881 226.859 873.46 205.24 c 0,209,210 + 1050.18 130.04 1050.18 130.04 1130.55 138.5 c 0,211,212 + 1210.92 146.96 1210.92 146.96 1320.9 250.36 c 0,213,214 + 1320.9 166.696 1320.9 166.696 1232.54 108.42 c 0,215,216 + 1144.17 50.1396 1144.17 50.1396 1078.38 44.5 c 0,217,218 + 1005.06 38.8605 1005.06 38.8605 931.739 57.6602 c 0,219,220 + 858.42 76.46 858.42 76.46 804.84 35.1006 c 0,221,222 + 792.66 26.0785 792.66 26.0785 792.604 15.9739 c 0,223,224 + 792.542 5.02315 792.542 5.02315 806.72 -7.19922 c 0,225,226 + 835.859 -33.5195 835.859 -33.5195 850.899 -26.4697 c 0,227,-1 + 888.5 -9.08008 l 0,228,229 + 866.88 -104.96 866.88 -104.96 768.18 -48.5596 c 0,230,231 + 669.478 7.84116 669.478 7.84116 626.239 20.0605 c 0,232,233 + 557.619 38.8602 557.619 38.8602 496.05 74.5801 c 0,234,235 + 434.479 110.301 434.479 110.301 388.42 68 c 0,236,237 + 375.162 55.7245 375.162 55.7245 375.242 43.7057 c 0,238,239 + 375.315 32.7157 375.315 32.7157 386.54 21.9404 c 0,240,241 + 415.681 -10.96 415.681 -10.96 455.159 21 c 0,242,243 + 455.159 -16.5997 455.159 -16.5997 407.689 -25.5293 c 0,244,245 + 371.209 -28.8155 l 0,246,247 + 347.38 -28.2343 347.38 -28.2343 329.199 -19.4199 c 0,248,249 + 316.039 -13.7793 316.039 -13.7793 275.619 18.1807 c 0,250,251 + 235.197 50.1417 235.197 50.1417 192.43 69.8809 c 0,252,253 + 149.659 89.6201 149.659 89.6201 116.76 77.4004 c 0,254,255 + 83.8595 65.1806 83.8595 65.1806 86.6797 -17.54 c 0,256,257 + 87.6191 -62.6592 87.6191 -62.6592 136.029 -74.8799 c 0,258,259 + 184.439 -87.0996 184.439 -87.0996 229.56 -74.8799 c 0,260,261 + 197.553 -106.429 197.553 -106.429 157.984 -106.507 c 0,262,263 + 116.206 -106.589 116.206 -106.589 66 -71.5898 c 0,264,265 + -31.7607 -3.4394 -31.7607 -3.4394 35.9199 107.48 c 0,266,267 + 104.54 216.521 104.54 216.521 216.399 287.021 c 0,268,269 + 328.261 357.522 328.261 357.522 393.119 468.44 c 0,270,271 + 449.521 564.32 449.521 564.32 501.689 716.601 c 0,272,273 + 553.859 868.881 553.859 868.881 640.34 885.801 c 0,274,275 + 617.12 865.821 617.12 865.821 617.166 847.081 c 0,276,277 + 617.2 833.201 617.2 833.201 630 820 c 0,278,279 + 634.076 815.747 634.076 815.747 640.206 815.804 c 0,280,281 + 666.594 816.047 666.594 816.047 731.05 896.141 c 0,282,283 + 810.479 994.839 810.479 994.839 783.22 1017.4 c 0,0,1 +724 1529.7 m 0,147,148 + 660.063 1537.08 660.063 1537.08 660.1 1572.69 c 0,149,150 + 660.106 1577.92 660.106 1577.92 661.489 1583.75 c 0,151,152 + 672.301 1629.34 672.301 1629.34 712.72 1660.36 c 0,153,154 + 741.575 1683.03 741.575 1683.03 764.646 1683.11 c 0,155,156 + 794.183 1683.21 794.183 1683.21 814.239 1646.26 c 0,157,158 + 828.341 1618.06 828.341 1618.06 793.56 1571.53 c 0,159,160 + 762.282 1529.69 762.282 1529.69 731 1529.27 c 0,161,162 + 727.499 1529.23 727.499 1529.23 724 1529.7 c 0,147,148 +EndSplineSet +EndChar +EndChars +EndSplineFont diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/DarkGardenMK.afm b/.venv/lib/python3.13/site-packages/reportlab/fonts/DarkGardenMK.afm new file mode 100644 index 0000000000000000000000000000000000000000..57ea5f5821219cd3baf7c4872a1d979b75517e2c --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/fonts/DarkGardenMK.afm @@ -0,0 +1,429 @@ +StartFontMetrics 2.0 +Comment Generated by FontForge 20071110 +Comment Creation Date: Wed Sep 10 17:07:49 2008 +FontName DarkGardenMK +FullName Dark Garden +FamilyName Dark Garden +Weight Medium +Notice (Copyright (C) 1999, 2000, 2004 Michal Kosmulski ) +Comment +Comment +Comment This font is free software; you can redistribute it and/or modify +Comment it under the terms of the GNU General Public License as published by +Comment the Free Software Foundation; either version 2 of the License, or +Comment (at your option) any later version. +Comment +Comment This font is distributed in the hope that it will be useful, +Comment but WITHOUT ANY WARRANTY; without even the implied warranty of +Comment MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +Comment GNU General Public License for more details. +Comment +Comment You should have received a copy of the GNU General Public License +Comment along with this font; if not, write to the Free Software +Comment Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +Comment +Comment As a special exception, if you create a document which uses +Comment this font, and embed this font or unaltered portions of this font into +Comment the document, this font does not by itself cause the resulting +Comment document to be covered by the GNU General Public License. This +Comment exception does not however invalidate any other reasons why the +Comment document might be covered by the GNU General Public License. If you +Comment modify this font, you may extend this exception to your version of the +Comment font, but you are not obligated to do so. If you do not wish to do so, +Comment delete this exception statement from your version. +Comment +ItalicAngle 0 +IsFixedPitch false +UnderlinePosition -420 +UnderlineThickness 80 +Version 1.1 +EncodingScheme ISO10646-1 +FontBBox -11 -331 935 1122 +CapHeight 931 +XHeight 869 +Ascender 831 +Descender -123 +StartCharMetrics 86 +C 0 ; WX 1000 ; N .notdef ; B 0 0 531 890 ; +C 1 ; WX 0 ; N glyph1 ; B 0 0 0 0 ; +C 2 ; WX 1000 ; N glyph2 ; B 0 0 0 0 ; +C 32 ; WX 500 ; N space ; B 0 0 0 0 ; +C 44 ; WX 130 ; N comma ; B 0 -76 123 105 ; +C 45 ; WX 611 ; N hyphen ; B 46 364 560 519 ; +C 46 ; WX 131 ; N period ; B 1 0 124 124 ; +C 58 ; WX 187 ; N colon ; B 32 6 159 447 ; +C 59 ; WX 187 ; N semicolon ; B 36 -98 163 470 ; +C 65 ; WX 706 ; N A ; B 3 -162 670 853 ; +C 66 ; WX 624 ; N B ; B -5 -27 602 911 ; +C 67 ; WX 619 ; N C ; B -1 -52 590 846 ; +C 68 ; WX 730 ; N D ; B 4 -133 703 912 ; +C 69 ; WX 613 ; N E ; B 1 -100 613 836 ; +C 70 ; WX 660 ; N F ; B 3 -96 629 833 ; +C 71 ; WX 624 ; N G ; B 5 -61 594 898 ; +C 72 ; WX 660 ; N H ; B 7 -177 629 876 ; +C 73 ; WX 284 ; N I ; B 22 -179 271 932 ; +C 74 ; WX 603 ; N J ; B 3 -93 570 863 ; +C 75 ; WX 639 ; N K ; B 7 -182 625 921 ; +C 76 ; WX 658 ; N L ; B 15 -3 616 903 ; +C 77 ; WX 833 ; N M ; B 9 -236 861 874 ; +C 78 ; WX 614 ; N N ; B 3 -135 579 917 ; +C 79 ; WX 691 ; N O ; B 9 -35 659 848 ; +C 80 ; WX 648 ; N P ; B 4 -203 605 846 ; +C 81 ; WX 612 ; N Q ; B -11 -179 578 894 ; +C 82 ; WX 647 ; N R ; B -1 -331 614 891 ; +C 83 ; WX 666 ; N S ; B 3 -60 654 876 ; +C 84 ; WX 829 ; N T ; B 0 -195 787 817 ; +C 85 ; WX 688 ; N U ; B 6 -33 656 874 ; +C 86 ; WX 618 ; N V ; B 4 -188 589 991 ; +C 87 ; WX 985 ; N W ; B 4 -132 935 974 ; +C 88 ; WX 690 ; N X ; B 6 -125 731 951 ; +C 89 ; WX 645 ; N Y ; B 7 -209 609 953 ; +C 90 ; WX 841 ; N Z ; B 14 -108 853 845 ; +C 97 ; WX 612 ; N a ; B 13 -93 581 769 ; +C 98 ; WX 528 ; N b ; B -4 -23 512 774 ; +C 99 ; WX 571 ; N c ; B 42 15 545 779 ; +C 100 ; WX 641 ; N d ; B 15 -60 609 829 ; +C 101 ; WX 527 ; N e ; B 8 -35 528 760 ; +C 102 ; WX 563 ; N f ; B 21 -25 553 765 ; +C 103 ; WX 549 ; N g ; B 21 10 522 825 ; +C 104 ; WX 581 ; N h ; B 24 -96 553 798 ; +C 105 ; WX 256 ; N i ; B 22 -99 235 846 ; +C 106 ; WX 527 ; N j ; B 17 -27 499 786 ; +C 107 ; WX 543 ; N k ; B 6 -155 531 783 ; +C 108 ; WX 525 ; N l ; B -1 62 510 832 ; +C 109 ; WX 718 ; N m ; B 14 -151 738 792 ; +C 110 ; WX 523 ; N n ; B 13 -63 502 832 ; +C 111 ; WX 612 ; N o ; B 30 28 584 779 ; +C 112 ; WX 561 ; N p ; B 13 -124 524 767 ; +C 113 ; WX 566 ; N q ; B 33 -98 535 814 ; +C 114 ; WX 548 ; N r ; B -3 -245 520 795 ; +C 115 ; WX 567 ; N s ; B 3 9 556 806 ; +C 116 ; WX 718 ; N t ; B 13 -117 682 743 ; +C 117 ; WX 587 ; N u ; B 8 36 560 805 ; +C 118 ; WX 530 ; N v ; B 9 -99 506 902 ; +C 119 ; WX 774 ; N w ; B 1 -49 793 891 ; +C 120 ; WX 604 ; N x ; B 11 -43 628 870 ; +C 121 ; WX 559 ; N y ; B 14 -122 526 866 ; +C 122 ; WX 764 ; N z ; B 7 -36 720 774 ; +C 196 ; WX 765 ; N Adieresis ; B 8 -179 724 1064 ; +C 211 ; WX 704 ; N Oacute ; B 7 -82 665 1012 ; +C 214 ; WX 791 ; N Odieresis ; B 1 -68 755 1084 ; +C 220 ; WX 763 ; N Udieresis ; B -1 -59 728 1122 ; +C 223 ; WX 543 ; N germandbls ; B 2 -304 516 795 ; +C 228 ; WX 650 ; N adieresis ; B 6 -152 615 904 ; +C 243 ; WX 600 ; N oacute ; B 8 -2 567 928 ; +C 246 ; WX 672 ; N odieresis ; B 0 -58 642 921 ; +C 252 ; WX 648 ; N udieresis ; B -1 -50 619 953 ; +C -1 ; WX 699 ; N Aogonek ; B 1 -257 657 838 ; +C -1 ; WX 594 ; N aogonek ; B 1 -219 559 712 ; +C -1 ; WX 596 ; N Cacute ; B 8 -57 561 1046 ; +C -1 ; WX 514 ; N cacute ; B 14 20 484 959 ; +C -1 ; WX 739 ; N Eogonek ; B 2 -240 738 785 ; +C -1 ; WX 637 ; N eogonek ; B 13 -121 640 750 ; +C -1 ; WX 848 ; N Lslash ; B 8 -107 908 871 ; +C -1 ; WX 722 ; N lslash ; B 11 -32 776 799 ; +C -1 ; WX 627 ; N Nacute ; B 8 -46 597 1050 ; +C -1 ; WX 534 ; N nacute ; B 8 32 509 964 ; +C -1 ; WX 558 ; N Sacute ; B 4 -27 566 1094 ; +C -1 ; WX 490 ; N sacute ; B 7 58 485 1010 ; +C -1 ; WX 721 ; N Zacute ; B 7 -90 714 1013 ; +C -1 ; WX 617 ; N zacute ; B 7 -44 607 894 ; +C -1 ; WX 759 ; N Zdotaccent ; B -7 -103 749 925 ; +C -1 ; WX 655 ; N zdotaccent ; B 4 -53 645 822 ; +EndCharMetrics +StartKernData +StartKernPairs 291 +KPX hyphen Z -126 +KPX hyphen z -101 +KPX hyphen X -88 +KPX hyphen x -76 +KPX hyphen Y -63 +KPX hyphen y -50 +KPX hyphen W -88 +KPX hyphen w -88 +KPX hyphen T -139 +KPX hyphen t -133 +KPX hyphen S -114 +KPX hyphen s -76 +KPX hyphen A -114 +KPX hyphen a -114 +KPX A C -25 +KPX A c -63 +KPX A M -50 +KPX A m -38 +KPX A h -63 +KPX A H -50 +KPX A hyphen -82 +KPX A s -139 +KPX A S -120 +KPX A y -145 +KPX A Y -125 +KPX A t -145 +KPX A T -145 +KPX A v -31 +KPX A w -112 +KPX A V -24 +KPX A W -94 +KPX C S -69 +KPX C s -63 +KPX C A -31 +KPX C a -44 +KPX D Z -88 +KPX D z -69 +KPX D a -101 +KPX D A -73 +KPX E S -63 +KPX E s -63 +KPX F t -139 +KPX F T -82 +KPX F hyphen -101 +KPX F period -114 +KPX F comma -133 +KPX F A -239 +KPX F a -229 +KPX H A -44 +KPX K o -50 +KPX K O -25 +KPX K s -107 +KPX K S -101 +KPX K g -88 +KPX K G -38 +KPX K c -114 +KPX K C -69 +KPX L t -203 +KPX L T -203 +KPX L Y -114 +KPX L y -114 +KPX L i -63 +KPX L I -69 +KPX L hyphen -107 +KPX L S -114 +KPX L w -133 +KPX L W -139 +KPX M A -50 +KPX M a -50 +KPX M i 38 +KPX N A -114 +KPX N a -101 +KPX O y -38 +KPX O Y -44 +KPX O a -76 +KPX O A -76 +KPX O x -76 +KPX O X -76 +KPX O W -114 +KPX O t -139 +KPX O T -178 +KPX P hyphen -101 +KPX P period -126 +KPX P comma -139 +KPX P t -44 +KPX P T -95 +KPX P Lslash -177 +KPX P lslash -177 +KPX P A -166 +KPX P a -177 +KPX R Y -69 +KPX R y -63 +KPX R S -101 +KPX R G -50 +KPX R t -139 +KPX R T -152 +KPX R V -10 +KPX R W -73 +KPX S E 25 +KPX S e 19 +KPX S S -57 +KPX S t -88 +KPX S T -31 +KPX T lslash -190 +KPX T Lslash -229 +KPX T U -57 +KPX T u -69 +KPX T h -114 +KPX T H -76 +KPX T hyphen -146 +KPX T period -126 +KPX T comma -126 +KPX T oacute -146 +KPX T Oacute -101 +KPX T s -139 +KPX T S -126 +KPX T o -101 +KPX T O -69 +KPX T A -250 +KPX T a -250 +KPX U t -38 +KPX U T -31 +KPX U X -63 +KPX V Odieresis -94 +KPX V odieresis -109 +KPX V o -95 +KPX V O -76 +KPX V hyphen -101 +KPX V period -120 +KPX V comma -120 +KPX V I -50 +KPX V i -88 +KPX V a -156 +KPX V A -131 +KPX W Odieresis -87 +KPX W odieresis -103 +KPX W lslash -229 +KPX W Lslash -248 +KPX W H -126 +KPX W h -146 +KPX W hyphen -114 +KPX W period -159 +KPX W comma -177 +KPX W s -159 +KPX W S -126 +KPX W i -88 +KPX W I -44 +KPX W oacute -152 +KPX W Oacute -178 +KPX W o -133 +KPX W O -107 +KPX W Adieresis -152 +KPX W adieresis -131 +KPX W aogonek -166 +KPX W Aogonek -166 +KPX W a -219 +KPX W A -194 +KPX X hyphen -101 +KPX Y O -44 +KPX Y o -88 +KPX Y Lslash -152 +KPX Y S -126 +KPX Y hyphen -95 +KPX Y period -114 +KPX Y comma -114 +KPX Y a -208 +KPX Y A -187 +KPX Z y -57 +KPX Z Y -50 +KPX Z lslash -88 +KPX Z Lslash -82 +KPX Z i -25 +KPX Z I -31 +KPX Z e -31 +KPX Z b -38 +KPX Z B -38 +KPX Z hyphen -101 +KPX a c -63 +KPX a m -38 +KPX a h -57 +KPX a hyphen -88 +KPX a s -101 +KPX a y -145 +KPX a t -166 +KPX a v -20 +KPX a w -107 +KPX c s -57 +KPX c a -50 +KPX d z -44 +KPX d a -73 +KPX e s -38 +KPX f t -63 +KPX f hyphen -76 +KPX f period -120 +KPX f comma -126 +KPX f a -208 +KPX h a -50 +KPX k o -31 +KPX k s -50 +KPX k g -31 +KPX k c -76 +KPX l t -139 +KPX l y -76 +KPX l i -38 +KPX l hyphen -76 +KPX l s -63 +KPX l w -95 +KPX m a -44 +KPX m i 31 +KPX n a -101 +KPX o y -31 +KPX o a -76 +KPX o x -69 +KPX o w -95 +KPX o t -152 +KPX p hyphen -50 +KPX p period -107 +KPX p comma -101 +KPX p t -95 +KPX p lslash -145 +KPX p a -145 +KPX r y -76 +KPX r s -88 +KPX r g -50 +KPX r t -165 +KPX r v -20 +KPX r w -73 +KPX s c -25 +KPX s s -50 +KPX s t -38 +KPX t lslash -159 +KPX t u -57 +KPX t h -82 +KPX t hyphen -107 +KPX t period -126 +KPX t comma -126 +KPX t oacute -101 +KPX t s -101 +KPX t o -88 +KPX t a -218 +KPX u t -38 +KPX u x -50 +KPX v odieresis -83 +KPX v o -69 +KPX v hyphen -88 +KPX v period -88 +KPX v comma -101 +KPX v i -50 +KPX v a -125 +KPX w odieresis -20 +KPX w lslash -146 +KPX w h -50 +KPX w hyphen -57 +KPX w period -95 +KPX w comma -101 +KPX w s -44 +KPX w i 6 +KPX w oacute -76 +KPX w o -44 +KPX w adieresis -111 +KPX w aogonek -152 +KPX w a -166 +KPX x hyphen -101 +KPX y o -63 +KPX y lslash -126 +KPX y s -101 +KPX y hyphen -82 +KPX y period -95 +KPX y comma -101 +KPX y a -177 +KPX z y -95 +KPX z lslash -120 +KPX z i -69 +KPX z e -50 +KPX z b -76 +KPX z hyphen -177 +KPX Oacute T -139 +KPX Oacute W -88 +KPX germandbls t -95 +KPX germandbls T -152 +KPX oacute t -114 +KPX oacute w -76 +KPX Aogonek W -101 +KPX aogonek w -88 +KPX Lslash Y -76 +KPX Lslash y -38 +KPX Lslash T -101 +KPX Lslash W -156 +KPX lslash y -50 +KPX lslash t -101 +KPX lslash w -187 +EndKernPairs +EndKernData +EndFontMetrics diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/DarkGardenMK.pfb b/.venv/lib/python3.13/site-packages/reportlab/fonts/DarkGardenMK.pfb new file mode 100644 index 0000000000000000000000000000000000000000..79e9702621e9d1a86237929ef66e2240b2b6576d Binary files /dev/null and b/.venv/lib/python3.13/site-packages/reportlab/fonts/DarkGardenMK.pfb differ diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/Vera.ttf b/.venv/lib/python3.13/site-packages/reportlab/fonts/Vera.ttf new file mode 100644 index 0000000000000000000000000000000000000000..58cd6b5e61eff273e920942e28041f8ddcf1e1b5 Binary files /dev/null and b/.venv/lib/python3.13/site-packages/reportlab/fonts/Vera.ttf differ diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/VeraBI.ttf b/.venv/lib/python3.13/site-packages/reportlab/fonts/VeraBI.ttf new file mode 100644 index 0000000000000000000000000000000000000000..b55eee397ee4c3a502f33a0e6ff708101f59fe9c Binary files /dev/null and b/.venv/lib/python3.13/site-packages/reportlab/fonts/VeraBI.ttf differ diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/VeraBd.ttf b/.venv/lib/python3.13/site-packages/reportlab/fonts/VeraBd.ttf new file mode 100644 index 0000000000000000000000000000000000000000..51d6111d722981a86766cc99c53f1956e5c0a229 Binary files /dev/null and b/.venv/lib/python3.13/site-packages/reportlab/fonts/VeraBd.ttf differ diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/VeraIt.ttf b/.venv/lib/python3.13/site-packages/reportlab/fonts/VeraIt.ttf new file mode 100644 index 0000000000000000000000000000000000000000..cc23c9efd20503a0d8d9c93a4650a68d50006281 Binary files /dev/null and b/.venv/lib/python3.13/site-packages/reportlab/fonts/VeraIt.ttf differ diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/_a______.pfb b/.venv/lib/python3.13/site-packages/reportlab/fonts/_a______.pfb new file mode 100644 index 0000000000000000000000000000000000000000..bd50088978fb6a7644301b45a825de06a8c05bf9 Binary files /dev/null and b/.venv/lib/python3.13/site-packages/reportlab/fonts/_a______.pfb differ diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/_ab_____.pfb b/.venv/lib/python3.13/site-packages/reportlab/fonts/_ab_____.pfb new file mode 100644 index 0000000000000000000000000000000000000000..fb7188f3ede1b0f3c9c5949ec830d998f5a75d09 Binary files /dev/null and b/.venv/lib/python3.13/site-packages/reportlab/fonts/_ab_____.pfb differ diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/_abi____.pfb b/.venv/lib/python3.13/site-packages/reportlab/fonts/_abi____.pfb new file mode 100644 index 0000000000000000000000000000000000000000..1477207ae4ed76ba29d8314dcdea1e0ac360b190 Binary files /dev/null and b/.venv/lib/python3.13/site-packages/reportlab/fonts/_abi____.pfb differ diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/_ai_____.pfb b/.venv/lib/python3.13/site-packages/reportlab/fonts/_ai_____.pfb new file mode 100644 index 0000000000000000000000000000000000000000..5392474a7ed0b69b06208c63242978eb1be56a16 Binary files /dev/null and b/.venv/lib/python3.13/site-packages/reportlab/fonts/_ai_____.pfb differ diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/_eb_____.pfb b/.venv/lib/python3.13/site-packages/reportlab/fonts/_eb_____.pfb new file mode 100644 index 0000000000000000000000000000000000000000..6fbd279a766efd616799818720b98e5f5673fdf3 Binary files /dev/null and b/.venv/lib/python3.13/site-packages/reportlab/fonts/_eb_____.pfb differ diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/_ebi____.pfb b/.venv/lib/python3.13/site-packages/reportlab/fonts/_ebi____.pfb new file mode 100644 index 0000000000000000000000000000000000000000..615eb4cb9128b98ef9f8ff67c821e72df74668f9 Binary files /dev/null and b/.venv/lib/python3.13/site-packages/reportlab/fonts/_ebi____.pfb differ diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/_ei_____.pfb b/.venv/lib/python3.13/site-packages/reportlab/fonts/_ei_____.pfb new file mode 100644 index 0000000000000000000000000000000000000000..af6219dab3a737166e8b2b5556d0fd3a4b775b19 Binary files /dev/null and b/.venv/lib/python3.13/site-packages/reportlab/fonts/_ei_____.pfb differ diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/_er_____.pfb b/.venv/lib/python3.13/site-packages/reportlab/fonts/_er_____.pfb new file mode 100644 index 0000000000000000000000000000000000000000..30d42aa60de39a07350ac91221273dee90676b5d Binary files /dev/null and b/.venv/lib/python3.13/site-packages/reportlab/fonts/_er_____.pfb differ diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/bitstream-vera-license.txt b/.venv/lib/python3.13/site-packages/reportlab/fonts/bitstream-vera-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..e651be1c4fe958e06fd7d7a2e79b3e7c2cb70a8e --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/fonts/bitstream-vera-license.txt @@ -0,0 +1,124 @@ +Bitstream Vera Fonts Copyright + +The fonts have a generous copyright, allowing derivative works (as +long as "Bitstream" or "Vera" are not in the names), and full +redistribution (so long as they are not *sold* by themselves). They +can be be bundled, redistributed and sold with any software. + +The fonts are distributed under the following copyright: + +Copyright +========= + +Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream +Vera is a trademark of Bitstream, Inc. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of the fonts accompanying this license ("Fonts") and associated +documentation files (the "Font Software"), to reproduce and distribute +the Font Software, including without limitation the rights to use, +copy, merge, publish, distribute, and/or sell copies of the Font +Software, and to permit persons to whom the Font Software is furnished +to do so, subject to the following conditions: + +The above copyright and trademark notices and this permission notice +shall be included in all copies of one or more of the Font Software +typefaces. + +The Font Software may be modified, altered, or added to, and in +particular the designs of glyphs or characters in the Fonts may be +modified and additional glyphs or characters may be added to the +Fonts, only if the fonts are renamed to names not containing either +the words "Bitstream" or the word "Vera". + +This License becomes null and void to the extent applicable to Fonts +or Font Software that has been modified and is distributed under the +"Bitstream Vera" names. + +The Font Software may be sold as part of a larger software package but +no copy of one or more of the Font Software typefaces may be sold by +itself. + +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL +BITSTREAM OR THE GNOME FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, +OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT +SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. + +Except as contained in this notice, the names of Gnome, the Gnome +Foundation, and Bitstream Inc., shall not be used in advertising or +otherwise to promote the sale, use or other dealings in this Font +Software without prior written authorization from the Gnome Foundation +or Bitstream Inc., respectively. For further information, contact: +fonts at gnome dot org. + +Copyright FAQ +============= + + 1. I don't understand the resale restriction... What gives? + + Bitstream is giving away these fonts, but wishes to ensure its + competitors can't just drop the fonts as is into a font sale system + and sell them as is. It seems fair that if Bitstream can't make money + from the Bitstream Vera fonts, their competitors should not be able to + do so either. You can sell the fonts as part of any software package, + however. + + 2. I want to package these fonts separately for distribution and + sale as part of a larger software package or system. Can I do so? + + Yes. A RPM or Debian package is a "larger software package" to begin + with, and you aren't selling them independently by themselves. + See 1. above. + + 3. Are derivative works allowed? + Yes! + + 4. Can I change or add to the font(s)? + Yes, but you must change the name(s) of the font(s). + + 5. Under what terms are derivative works allowed? + + You must change the name(s) of the fonts. This is to ensure the + quality of the fonts, both to protect Bitstream and Gnome. We want to + ensure that if an application has opened a font specifically of these + names, it gets what it expects (though of course, using fontconfig, + substitutions could still could have occurred during font + opening). You must include the Bitstream copyright. Additional + copyrights can be added, as per copyright law. Happy Font Hacking! + + 6. If I have improvements for Bitstream Vera, is it possible they might get + adopted in future versions? + + Yes. The contract between the Gnome Foundation and Bitstream has + provisions for working with Bitstream to ensure quality additions to + the Bitstream Vera font family. Please contact us if you have such + additions. Note, that in general, we will want such additions for the + entire family, not just a single font, and that you'll have to keep + both Gnome and Jim Lyles, Vera's designer, happy! To make sense to add + glyphs to the font, they must be stylistically in keeping with Vera's + design. Vera cannot become a "ransom note" font. Jim Lyles will be + providing a document describing the design elements used in Vera, as a + guide and aid for people interested in contributing to Vera. + + 7. I want to sell a software package that uses these fonts: Can I do so? + + Sure. Bundle the fonts with your software and sell your software + with the fonts. That is the intent of the copyright. + + 8. If applications have built the names "Bitstream Vera" into them, + can I override this somehow to use fonts of my choosing? + + This depends on exact details of the software. Most open source + systems and software (e.g., Gnome, KDE, etc.) are now converting to + use fontconfig (see www.fontconfig.org) to handle font configuration, + selection and substitution; it has provisions for overriding font + names and subsituting alternatives. An example is provided by the + supplied local.conf file, which chooses the family Bitstream Vera for + "sans", "serif" and "monospace". Other software (e.g., the XFree86 + core server) has other mechanisms for font substitution. + diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/callig15.afm b/.venv/lib/python3.13/site-packages/reportlab/fonts/callig15.afm new file mode 100644 index 0000000000000000000000000000000000000000..09d37282807dac3c6011a9c7f847f5ff8fc86ae3 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/fonts/callig15.afm @@ -0,0 +1,191 @@ +StartFontMetrics 2.0 +Comment Generated by FontForge 20110222 +Comment Creation Date: Sun Oct 16 04:57:33 2011 +FontName CALLIG15 +FullName CALLIG15 +FamilyName CALLIG15 +Weight Medium +Notice (Copyright 1992 Peter Vanroose, 1999 S. Dachian) +Comment You may freely use, modify and/or distribute this file, as long as this copyright notice is retained +ItalicAngle 0 +IsFixedPitch false +UnderlinePosition -67 +UnderlineThickness 33 +Version 001.000 +EncodingScheme FontSpecific +FontBBox -294 -257 1566 839 +CapHeight 634 +XHeight 226 +Ascender 452 +Descender -221 +StartCharMetrics 168 +C 0 ; WX 143 ; N grave ; B 30 744 113 831 ; +C 1 ; WX 144 ; N acute ; B 30 239 114 319 ; +C 2 ; WX 153 ; N circumflex ; B 164 239 348 319 ; +C 3 ; WX 140 ; N tilde ; B 167 239 306 278 ; +C 4 ; WX 170 ; N dieresis ; B 30 239 139 289 ; +C 6 ; WX 118 ; N ring ; B 195 239 296 335 ; +C 8 ; WX 158 ; N breve ; B 176 249 360 330 ; +C 10 ; WX 59 ; N dotaccent ; B 208 287 253 332 ; +C 14 ; WX 142 ; N guilsinglleft ; B 70 0 195 187 ; +C 15 ; WX 142 ; N guilsinglright ; B 63 0 190 182 ; +C 16 ; WX 165 ; N quotedblleft ; B 400 580 587 664 ; +C 17 ; WX 164 ; N quotedblright ; B 387 580 573 664 ; +C 18 ; WX 170 ; N quotedblbase ; B -17 -46 169 40 ; +C 19 ; WX 230 ; N guillemotleft ; B 69 0 289 187 ; +C 20 ; WX 231 ; N guillemotright ; B 63 0 283 187 ; +C 22 ; WX 1099 ; N emdash ; B 58 90 1187 141 ; +C 28 ; WX 336 ; N fi ; B -187 -231 626 523 ; +C 29 ; WX 394 ; N fl ; B -188 -231 811 523 ; +C 33 ; WX 206 ; N exclam ; B 40 -7 392 341 ; +C 34 ; WX 193 ; N quotedbl ; B 425 557 563 664 ; +C 35 ; WX 188 ; N numbersign ; B 68 -7 241 190 ; +C 36 ; WX 559 ; N dollar ; B 151 -83 759 666 ; +C 37 ; WX 388 ; N percent ; B 132 -7 460 328 ; +C 38 ; WX 379 ; N ampersand ; B -83 -223 473 296 ; +C 39 ; WX 78 ; N quoteright ; B 388 580 485 664 ; +C 40 ; WX 191 ; N parenleft ; B 57 -7 484 459 ; +C 41 ; WX 193 ; N parenright ; B -2 -7 427 457 ; +C 42 ; WX 239 ; N asterisk ; B 373 465 603 665 ; +C 44 ; WX 129 ; N comma ; B 21 -25 119 60 ; +C 45 ; WX 140 ; N hyphen ; B 68 80 192 115 ; +C 46 ; WX 141 ; N period ; B 40 -7 101 55 ; +C 47 ; WX 149 ; N slash ; B 12 -7 350 329 ; +C 48 ; WX 298 ; N zero ; B 82 -7 439 323 ; +C 49 ; WX 244 ; N one ; B 80 0 437 330 ; +C 50 ; WX 318 ; N two ; B 30 -9 398 326 ; +C 51 ; WX 312 ; N three ; B 60 -7 459 340 ; +C 52 ; WX 333 ; N four ; B 84 0 419 334 ; +C 53 ; WX 296 ; N five ; B 58 -6 479 331 ; +C 54 ; WX 279 ; N six ; B 80 -7 446 335 ; +C 55 ; WX 302 ; N seven ; B 89 1 483 331 ; +C 56 ; WX 294 ; N eight ; B 78 -7 438 328 ; +C 57 ; WX 269 ; N nine ; B 36 -7 402 328 ; +C 58 ; WX 142 ; N colon ; B 40 -7 215 175 ; +C 59 ; WX 119 ; N semicolon ; B 0 -25 188 174 ; +C 63 ; WX 274 ; N question ; B 27 -7 415 305 ; +C 65 ; WX 789 ; N A ; B 85 -6 1286 666 ; +C 66 ; WX 884 ; N B ; B 160 -7 1179 674 ; +C 67 ; WX 774 ; N C ; B 323 -7 1124 663 ; +C 68 ; WX 888 ; N D ; B 202 -6 1128 659 ; +C 69 ; WX 723 ; N E ; B 337 -7 1027 703 ; +C 70 ; WX 673 ; N F ; B 72 -6 1242 666 ; +C 71 ; WX 943 ; N G ; B 306 -210 1255 669 ; +C 72 ; WX 795 ; N H ; B 135 -7 1304 660 ; +C 73 ; WX 599 ; N I ; B 71 -7 1102 651 ; +C 74 ; WX 365 ; N J ; B -120 -257 870 651 ; +C 75 ; WX 792 ; N K ; B 85 -7 1339 656 ; +C 76 ; WX 736 ; N L ; B 83 -6 1167 671 ; +C 77 ; WX 799 ; N M ; B 55 -7 1184 669 ; +C 78 ; WX 933 ; N N ; B 75 -6 1474 656 ; +C 79 ; WX 586 ; N O ; B 136 -7 934 668 ; +C 80 ; WX 766 ; N P ; B 132 -7 1110 655 ; +C 81 ; WX 602 ; N Q ; B 135 -9 949 643 ; +C 82 ; WX 866 ; N R ; B 162 -7 1125 668 ; +C 83 ; WX 704 ; N S ; B 122 -7 1126 667 ; +C 84 ; WX 628 ; N T ; B 72 -7 1243 668 ; +C 85 ; WX 765 ; N U ; B 316 -4 1155 654 ; +C 86 ; WX 815 ; N V ; B 353 -7 1363 677 ; +C 87 ; WX 1025 ; N W ; B 355 -10 1566 659 ; +C 88 ; WX 664 ; N X ; B 62 -6 1181 662 ; +C 89 ; WX 692 ; N Y ; B 260 -7 1080 645 ; +C 90 ; WX 679 ; N Z ; B 159 -7 1009 634 ; +C 91 ; WX 590 ; N bracketleft ; B 30 -1 558 464 ; +C 93 ; WX 623 ; N bracketright ; B 30 -1 591 467 ; +C 94 ; WX 373 ; N asciicircum ; B 30 448 342 664 ; +C 95 ; WX 1032 ; N underscore ; B 0 -100 1028 -47 ; +C 96 ; WX 76 ; N quoteleft ; B 400 580 498 664 ; +C 97 ; WX 293 ; N a ; B 45 -5 358 193 ; +C 98 ; WX 291 ; N b ; B 62 -7 615 533 ; +C 99 ; WX 190 ; N c ; B 46 -6 257 195 ; +C 100 ; WX 299 ; N d ; B 42 -7 616 452 ; +C 101 ; WX 195 ; N e ; B 41 -7 261 191 ; +C 102 ; WX 216 ; N f ; B -181 -231 632 523 ; +C 103 ; WX 296 ; N g ; B -145 -229 362 197 ; +C 104 ; WX 352 ; N h ; B 28 -6 636 520 ; +C 105 ; WX 150 ; N i ; B 41 -7 331 332 ; +C 106 ; WX 156 ; N j ; B -294 -228 317 331 ; +C 107 ; WX 315 ; N k ; B 36 0 630 534 ; +C 108 ; WX 189 ; N l ; B 64 -7 608 523 ; +C 109 ; WX 525 ; N m ; B 57 0 589 196 ; +C 110 ; WX 361 ; N n ; B 59 -1 426 193 ; +C 111 ; WX 218 ; N o ; B 41 -7 283 191 ; +C 112 ; WX 332 ; N p ; B -208 -225 397 322 ; +C 113 ; WX 284 ; N q ; B -82 -217 357 193 ; +C 114 ; WX 214 ; N r ; B 63 -7 279 228 ; +C 115 ; WX 165 ; N s ; B 12 -7 227 243 ; +C 116 ; WX 186 ; N t ; B 60 -6 360 335 ; +C 117 ; WX 310 ; N u ; B 41 -7 375 190 ; +C 118 ; WX 305 ; N v ; B 64 -7 373 193 ; +C 119 ; WX 460 ; N w ; B 64 -7 524 202 ; +C 120 ; WX 274 ; N x ; B 30 -7 339 195 ; +C 121 ; WX 351 ; N y ; B -89 -222 415 190 ; +C 122 ; WX 289 ; N z ; B 64 -12 354 192 ; +C 123 ; WX 312 ; N braceleft ; B 40 1 490 464 ; +C 125 ; WX 532 ; N braceright ; B 40 -1 490 461 ; +C 126 ; WX 402 ; N asciitilde ; B 30 192 371 307 ; +C 127 ; WX 140 ; N sfthyphen ; B 68 80 192 115 ; +C 152 ; WX 740 ; N Ydieresis ; B 260 -7 1080 794 ; +C 184 ; WX 358 ; N ydieresis ; B -82 -222 423 299 ; +C 189 ; WX 158 ; N exclamdown ; B -86 -141 266 206 ; +C 190 ; WX 265 ; N questiondown ; B -15 -106 373 206 ; +C 191 ; WX 773 ; N sterling ; B 67 -10 1003 480 ; +C 192 ; WX 787 ; N Agrave ; B 83 -6 1334 826 ; +C 193 ; WX 792 ; N Aacute ; B 88 -6 1340 824 ; +C 194 ; WX 789 ; N Acircumflex ; B 85 -6 1357 824 ; +C 195 ; WX 791 ; N Atilde ; B 86 -6 1318 783 ; +C 196 ; WX 793 ; N Adieresis ; B 88 -6 1319 794 ; +C 197 ; WX 792 ; N Aring ; B 86 -6 1326 839 ; +C 198 ; WX 1226 ; N AE ; B 77 -6 1554 679 ; +C 199 ; WX 780 ; N Ccedilla ; B 314 -115 1131 663 ; +C 200 ; WX 684 ; N Egrave ; B 335 -7 1025 831 ; +C 201 ; WX 685 ; N Eacute ; B 336 -7 1029 824 ; +C 202 ; WX 681 ; N Ecircumflex ; B 334 -7 1084 824 ; +C 203 ; WX 682 ; N Edieresis ; B 335 -7 1025 794 ; +C 204 ; WX 597 ; N Igrave ; B 68 -7 1099 831 ; +C 205 ; WX 598 ; N Iacute ; B 69 -7 1100 824 ; +C 206 ; WX 597 ; N Icircumflex ; B 68 -7 1114 824 ; +C 207 ; WX 597 ; N Idieresis ; B 68 -7 1099 794 ; +C 209 ; WX 1112 ; N Ntilde ; B 73 -6 1472 783 ; +C 210 ; WX 586 ; N Ograve ; B 135 -7 933 831 ; +C 211 ; WX 586 ; N Oacute ; B 136 -7 934 824 ; +C 212 ; WX 586 ; N Ocircumflex ; B 136 -7 937 824 ; +C 213 ; WX 587 ; N Otilde ; B 136 -7 934 783 ; +C 214 ; WX 586 ; N Odieresis ; B 135 -7 933 794 ; +C 215 ; WX 1306 ; N OE ; B 73 -7 1234 704 ; +C 216 ; WX 608 ; N Oslash ; B 132 -7 954 699 ; +C 217 ; WX 764 ; N Ugrave ; B 316 -4 1155 831 ; +C 218 ; WX 765 ; N Uacute ; B 316 -4 1155 824 ; +C 219 ; WX 764 ; N Ucircumflex ; B 316 -4 1155 824 ; +C 220 ; WX 764 ; N Udieresis ; B 316 -4 1155 794 ; +C 224 ; WX 295 ; N agrave ; B 47 -5 360 326 ; +C 225 ; WX 296 ; N aacute ; B 48 -5 362 319 ; +C 226 ; WX 295 ; N acircumflex ; B 47 -5 416 319 ; +C 227 ; WX 295 ; N atilde ; B 47 -5 372 278 ; +C 228 ; WX 295 ; N adieresis ; B 47 -5 360 289 ; +C 229 ; WX 296 ; N aring ; B 45 -5 367 335 ; +C 230 ; WX 357 ; N ae ; B 43 -6 422 193 ; +C 231 ; WX 200 ; N ccedilla ; B -64 -129 265 200 ; +C 232 ; WX 198 ; N egrave ; B 43 -7 263 326 ; +C 233 ; WX 199 ; N eacute ; B 44 -7 280 319 ; +C 234 ; WX 198 ; N ecircumflex ; B 43 -7 333 319 ; +C 235 ; WX 197 ; N edieresis ; B 43 -7 273 289 ; +C 236 ; WX 151 ; N igrave ; B 42 -7 221 326 ; +C 237 ; WX 150 ; N iacute ; B 41 -7 259 319 ; +C 238 ; WX 150 ; N icircumflex ; B 41 -7 318 319 ; +C 239 ; WX 150 ; N idieresis ; B 41 -7 246 289 ; +C 241 ; WX 362 ; N ntilde ; B 58 -1 425 278 ; +C 242 ; WX 220 ; N ograve ; B 43 -7 285 326 ; +C 243 ; WX 220 ; N oacute ; B 43 -7 288 319 ; +C 244 ; WX 220 ; N ocircumflex ; B 43 -7 359 319 ; +C 245 ; WX 220 ; N otilde ; B 43 -7 296 278 ; +C 246 ; WX 220 ; N odieresis ; B 43 -7 292 289 ; +C 247 ; WX 359 ; N oe ; B 41 -7 426 193 ; +C 248 ; WX 219 ; N oslash ; B 35 -24 288 204 ; +C 249 ; WX 309 ; N ugrave ; B 40 -7 374 326 ; +C 250 ; WX 310 ; N uacute ; B 41 -7 375 319 ; +C 251 ; WX 309 ; N ucircumflex ; B 41 -7 406 319 ; +C 252 ; WX 308 ; N udieresis ; B 40 -7 374 289 ; +C 255 ; WX 689 ; N germandbls ; B 27 -106 656 502 ; +EndCharMetrics +EndFontMetrics diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/callig15.pfb b/.venv/lib/python3.13/site-packages/reportlab/fonts/callig15.pfb new file mode 100644 index 0000000000000000000000000000000000000000..a357026a8015b87f5530274f3d0672a3fc5f88bc Binary files /dev/null and b/.venv/lib/python3.13/site-packages/reportlab/fonts/callig15.pfb differ diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/cob_____.pfb b/.venv/lib/python3.13/site-packages/reportlab/fonts/cob_____.pfb new file mode 100644 index 0000000000000000000000000000000000000000..9dbcbd5f23d00200cb6913a719bae54ebed61e2e Binary files /dev/null and b/.venv/lib/python3.13/site-packages/reportlab/fonts/cob_____.pfb differ diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/cobo____.pfb b/.venv/lib/python3.13/site-packages/reportlab/fonts/cobo____.pfb new file mode 100644 index 0000000000000000000000000000000000000000..0ec68171716129896de20b143310571a83bc3297 Binary files /dev/null and b/.venv/lib/python3.13/site-packages/reportlab/fonts/cobo____.pfb differ diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/com_____.pfb b/.venv/lib/python3.13/site-packages/reportlab/fonts/com_____.pfb new file mode 100644 index 0000000000000000000000000000000000000000..f7f8e562187715a7f3aed9d40eeb45473a04ff0e Binary files /dev/null and b/.venv/lib/python3.13/site-packages/reportlab/fonts/com_____.pfb differ diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/coo_____.pfb b/.venv/lib/python3.13/site-packages/reportlab/fonts/coo_____.pfb new file mode 100644 index 0000000000000000000000000000000000000000..eadc9de46961e700d2f1f76a6e6e317dc862e752 Binary files /dev/null and b/.venv/lib/python3.13/site-packages/reportlab/fonts/coo_____.pfb differ diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/hb-test.ttf b/.venv/lib/python3.13/site-packages/reportlab/fonts/hb-test.ttf new file mode 100644 index 0000000000000000000000000000000000000000..5ea92b5625fb58140c8faf93e5dd71520bf7c2c8 Binary files /dev/null and b/.venv/lib/python3.13/site-packages/reportlab/fonts/hb-test.ttf differ diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/sy______.pfb b/.venv/lib/python3.13/site-packages/reportlab/fonts/sy______.pfb new file mode 100644 index 0000000000000000000000000000000000000000..8c0325a450ebfa0c1bf65bdb315f191724e00071 Binary files /dev/null and b/.venv/lib/python3.13/site-packages/reportlab/fonts/sy______.pfb differ diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/zd______.pfb b/.venv/lib/python3.13/site-packages/reportlab/fonts/zd______.pfb new file mode 100644 index 0000000000000000000000000000000000000000..1c1ce0684ba347e48c40981b3715aa03ee5d630d Binary files /dev/null and b/.venv/lib/python3.13/site-packages/reportlab/fonts/zd______.pfb differ diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/zx______.pfb b/.venv/lib/python3.13/site-packages/reportlab/fonts/zx______.pfb new file mode 100644 index 0000000000000000000000000000000000000000..001ed5f2ccc69400179a09e89e0791e94bc645af Binary files /dev/null and b/.venv/lib/python3.13/site-packages/reportlab/fonts/zx______.pfb differ diff --git a/.venv/lib/python3.13/site-packages/reportlab/fonts/zy______.pfb b/.venv/lib/python3.13/site-packages/reportlab/fonts/zy______.pfb new file mode 100644 index 0000000000000000000000000000000000000000..cf7ef6e703d5d0011a6d5204fc5dcf31a58fa750 Binary files /dev/null and b/.venv/lib/python3.13/site-packages/reportlab/fonts/zy______.pfb differ diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/__init__.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2f1af9c678698abecc842b66f4e7a247b6871884 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/__init__.py @@ -0,0 +1,6 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/graphics/__init__.py +__version__='3.3.0' +__doc__='''Framework for reusable object graphics, in PDF or bitmap form''' + diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/__init__.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..69993d3f2749518f86235d21ba3c869631d3fe8b --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/__init__.py @@ -0,0 +1,152 @@ +# +# Copyright (c) 1996-2000 Tyler C. Sarna +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. All advertising materials mentioning features or use of this software +# must display the following acknowledgement: +# This product includes software developed by Tyler C. Sarna. +# 4. Neither the name of the author nor the names of contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS +# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# +__all__ = tuple('''registerWidget getCodes getCodeNames createBarcodeDrawing createBarcodeImageInMemory'''.split()) +__version__ = '0.9' +__doc__='''Popular barcodes available as reusable widgets''' + +_widgets = [] +def registerWidget(widget): + _widgets.append(widget) + +def _reset(): + _widgets[:] = [] + from reportlab.graphics.barcode.widgets import BarcodeI2of5, BarcodeCode128, BarcodeStandard93,\ + BarcodeExtended93, BarcodeStandard39, BarcodeExtended39,\ + BarcodeMSI, BarcodeCodabar, BarcodeCode11, BarcodeFIM,\ + BarcodePOSTNET, BarcodeUSPS_4State, BarcodeCode128Auto, BarcodeECC200DataMatrix + + #newer codes will typically get their own module + from reportlab.graphics.barcode.eanbc import Ean13BarcodeWidget, Ean8BarcodeWidget, UPCA, Ean5BarcodeWidget, ISBNBarcodeWidget + from reportlab.graphics.barcode.qr import QrCodeWidget + for widget in (BarcodeI2of5, + BarcodeCode128, + BarcodeCode128Auto, + BarcodeStandard93, + BarcodeExtended93, + BarcodeStandard39, + BarcodeExtended39, + BarcodeMSI, + BarcodeCodabar, + BarcodeCode11, + BarcodeFIM, + BarcodePOSTNET, + BarcodeUSPS_4State, + Ean13BarcodeWidget, + Ean8BarcodeWidget, + UPCA, + Ean5BarcodeWidget, + ISBNBarcodeWidget, + QrCodeWidget, + BarcodeECC200DataMatrix, + ): + registerWidget(widget) + from reportlab.graphics.barcode import dmtx + if dmtx.pylibdmtx: + registerWidget(dmtx.DataMatrixWidget) + +_reset() +from reportlab.rl_config import register_reset +register_reset(_reset) + +def getCodes(): + """Returns a dict mapping code names to widgets""" + #the module exports a dictionary of names to widgets, to make it easy for + #apps and doc tools to display information about them. + codes = {} + for widget in _widgets: + codeName = widget.codeName + codes[codeName] = widget + + return codes + +def getCodeNames(): + """Returns sorted list of supported bar code names""" + return sorted(getCodes().keys()) + +def createBarcodeDrawing(codeName, **options): + """This creates and returns a drawing with a barcode. + """ + from reportlab.graphics.shapes import Drawing + + codes = getCodes() + bcc = codes[codeName] + width = options.pop('width',None) + height = options.pop('height',None) + isoScale = options.pop('isoScale',0) + kw = {} + for k,v in options.items(): + if k.startswith('_') or k in bcc._attrMap: kw[k] = v + bc = bcc(**kw) + + + #Robin's new ones validate when setting the value property. + #Ty Sarna's old ones do not. We need to test. + if hasattr(bc, 'validate'): + bc.validate() #raise exception if bad value + if not bc.valid: + raise ValueError("Illegal barcode with value '%s' in code '%s'" % (options.get('value',None), codeName)) + + #size it after setting the data + x1, y1, x2, y2 = bc.getBounds() + w = float(x2 - x1) + h = float(y2 - y1) + sx = width not in ('auto',None) + sy = height not in ('auto',None) + if sx or sy: + sx = sx and width/w or 1.0 + sy = sy and height/h or 1.0 + if isoScale: + if sx<1.0 and sy<1.0: + sx = sy = max(sx,sy) + else: + sx = sy = min(sx,sy) + + w *= sx + h *= sy + else: + sx = sy = 1 + + #bc.x = -sx*x1 + #bc.y = -sy*y1 + d = Drawing(width=w,height=h,transform=[sx,0,0,sy,-sx*x1,-sy*y1]) + d.add(bc, "_bc") + return d + +def createBarcodeImageInMemory(codeName,**options): + """This creates and returns barcode as an image in memory. + Takes same arguments as createBarcodeDrawing and also an + optional format keyword which can be anything acceptable + to Drawing.asString eg gif, pdf, tiff, py ...... + """ + format = options.pop('format','png') + d = createBarcodeDrawing(codeName, **options) + return d.asString(format) diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/code128.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/code128.py new file mode 100644 index 0000000000000000000000000000000000000000..c8cf4fc02456043aa0605e820eda48a9ed57d916 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/code128.py @@ -0,0 +1,460 @@ +# +# Copyright (c) 2000 Tyler C. Sarna +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. All advertising materials mentioning features or use of this software +# must display the following acknowledgement: +# This product includes software developed by Tyler C. Sarna. +# 4. Neither the name of the author nor the names of contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS +# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# + +from reportlab.lib.units import inch +from reportlab.lib.utils import asNative +from reportlab.graphics.barcode.common import MultiWidthBarcode +from string import digits + +_patterns = { + 0 : 'BaBbBb', 1 : 'BbBaBb', 2 : 'BbBbBa', + 3 : 'AbAbBc', 4 : 'AbAcBb', 5 : 'AcAbBb', + 6 : 'AbBbAc', 7 : 'AbBcAb', 8 : 'AcBbAb', + 9 : 'BbAbAc', 10 : 'BbAcAb', 11 : 'BcAbAb', + 12 : 'AaBbCb', 13 : 'AbBaCb', 14 : 'AbBbCa', + 15 : 'AaCbBb', 16 : 'AbCaBb', 17 : 'AbCbBa', + 18 : 'BbCbAa', 19 : 'BbAaCb', 20 : 'BbAbCa', + 21 : 'BaCbAb', 22 : 'BbCaAb', 23 : 'CaBaCa', + 24 : 'CaAbBb', 25 : 'CbAaBb', 26 : 'CbAbBa', + 27 : 'CaBbAb', 28 : 'CbBaAb', 29 : 'CbBbAa', + 30 : 'BaBaBc', 31 : 'BaBcBa', 32 : 'BcBaBa', + 33 : 'AaAcBc', 34 : 'AcAaBc', 35 : 'AcAcBa', + 36 : 'AaBcAc', 37 : 'AcBaAc', 38 : 'AcBcAa', + 39 : 'BaAcAc', 40 : 'BcAaAc', 41 : 'BcAcAa', + 42 : 'AaBaCc', 43 : 'AaBcCa', 44 : 'AcBaCa', + 45 : 'AaCaBc', 46 : 'AaCcBa', 47 : 'AcCaBa', + 48 : 'CaCaBa', 49 : 'BaAcCa', 50 : 'BcAaCa', + 51 : 'BaCaAc', 52 : 'BaCcAa', 53 : 'BaCaCa', + 54 : 'CaAaBc', 55 : 'CaAcBa', 56 : 'CcAaBa', + 57 : 'CaBaAc', 58 : 'CaBcAa', 59 : 'CcBaAa', + 60 : 'CaDaAa', 61 : 'BbAdAa', 62 : 'DcAaAa', + 63 : 'AaAbBd', 64 : 'AaAdBb', 65 : 'AbAaBd', + 66 : 'AbAdBa', 67 : 'AdAaBb', 68 : 'AdAbBa', + 69 : 'AaBbAd', 70 : 'AaBdAb', 71 : 'AbBaAd', + 72 : 'AbBdAa', 73 : 'AdBaAb', 74 : 'AdBbAa', + 75 : 'BdAbAa', 76 : 'BbAaAd', 77 : 'DaCaAa', + 78 : 'BdAaAb', 79 : 'AcDaAa', 80 : 'AaAbDb', + 81 : 'AbAaDb', 82 : 'AbAbDa', 83 : 'AaDbAb', + 84 : 'AbDaAb', 85 : 'AbDbAa', 86 : 'DaAbAb', + 87 : 'DbAaAb', 88 : 'DbAbAa', 89 : 'BaBaDa', + 90 : 'BaDaBa', 91 : 'DaBaBa', 92 : 'AaAaDc', + 93 : 'AaAcDa', 94 : 'AcAaDa', 95 : 'AaDaAc', + 96 : 'AaDcAa', 97 : 'DaAaAc', 98 : 'DaAcAa', + 99 : 'AaCaDa', 100 : 'AaDaCa', 101 : 'CaAaDa', + 102 : 'DaAaCa', 103 : 'BaAdAb', 104 : 'BaAbAd', + 105 : 'BaAbCb', 106 : 'BcCaAaB' +} + +starta, startb, startc, stop = 103, 104, 105, 106 + +seta = { + ' ' : 0, '!' : 1, '"' : 2, '#' : 3, + '$' : 4, '%' : 5, '&' : 6, '\'' : 7, + '(' : 8, ')' : 9, '*' : 10, '+' : 11, + ',' : 12, '-' : 13, '.' : 14, '/' : 15, + '0' : 16, '1' : 17, '2' : 18, '3' : 19, + '4' : 20, '5' : 21, '6' : 22, '7' : 23, + '8' : 24, '9' : 25, ':' : 26, ';' : 27, + '<' : 28, '=' : 29, '>' : 30, '?' : 31, + '@' : 32, 'A' : 33, 'B' : 34, 'C' : 35, + 'D' : 36, 'E' : 37, 'F' : 38, 'G' : 39, + 'H' : 40, 'I' : 41, 'J' : 42, 'K' : 43, + 'L' : 44, 'M' : 45, 'N' : 46, 'O' : 47, + 'P' : 48, 'Q' : 49, 'R' : 50, 'S' : 51, + 'T' : 52, 'U' : 53, 'V' : 54, 'W' : 55, + 'X' : 56, 'Y' : 57, 'Z' : 58, '[' : 59, + '\\' : 60, ']' : 61, '^' : 62, '_' : 63, + '\x00' : 64, '\x01' : 65, '\x02' : 66, '\x03' : 67, + '\x04' : 68, '\x05' : 69, '\x06' : 70, '\x07' : 71, + '\x08' : 72, '\x09' : 73, '\x0a' : 74, '\x0b' : 75, + '\x0c' : 76, '\x0d' : 77, '\x0e' : 78, '\x0f' : 79, + '\x10' : 80, '\x11' : 81, '\x12' : 82, '\x13' : 83, + '\x14' : 84, '\x15' : 85, '\x16' : 86, '\x17' : 87, + '\x18' : 88, '\x19' : 89, '\x1a' : 90, '\x1b' : 91, + '\x1c' : 92, '\x1d' : 93, '\x1e' : 94, '\x1f' : 95, + '\xf3' : 96, '\xf2' : 97, 'SHIFT' : 98, 'TO_C' : 99, + 'TO_B' : 100, '\xf4' : 101, '\xf1' : 102 +} + +setb = { + ' ' : 0, '!' : 1, '"' : 2, '#' : 3, + '$' : 4, '%' : 5, '&' : 6, '\'' : 7, + '(' : 8, ')' : 9, '*' : 10, '+' : 11, + ',' : 12, '-' : 13, '.' : 14, '/' : 15, + '0' : 16, '1' : 17, '2' : 18, '3' : 19, + '4' : 20, '5' : 21, '6' : 22, '7' : 23, + '8' : 24, '9' : 25, ':' : 26, ';' : 27, + '<' : 28, '=' : 29, '>' : 30, '?' : 31, + '@' : 32, 'A' : 33, 'B' : 34, 'C' : 35, + 'D' : 36, 'E' : 37, 'F' : 38, 'G' : 39, + 'H' : 40, 'I' : 41, 'J' : 42, 'K' : 43, + 'L' : 44, 'M' : 45, 'N' : 46, 'O' : 47, + 'P' : 48, 'Q' : 49, 'R' : 50, 'S' : 51, + 'T' : 52, 'U' : 53, 'V' : 54, 'W' : 55, + 'X' : 56, 'Y' : 57, 'Z' : 58, '[' : 59, + '\\' : 60, ']' : 61, '^' : 62, '_' : 63, + '`' : 64, 'a' : 65, 'b' : 66, 'c' : 67, + 'd' : 68, 'e' : 69, 'f' : 70, 'g' : 71, + 'h' : 72, 'i' : 73, 'j' : 74, 'k' : 75, + 'l' : 76, 'm' : 77, 'n' : 78, 'o' : 79, + 'p' : 80, 'q' : 81, 'r' : 82, 's' : 83, + 't' : 84, 'u' : 85, 'v' : 86, 'w' : 87, + 'x' : 88, 'y' : 89, 'z' : 90, '{' : 91, + '|' : 92, '}' : 93, '~' : 94, '\x7f' : 95, + '\xf3' : 96, '\xf2' : 97, 'SHIFT' : 98, 'TO_C' : 99, + '\xf4' : 100, 'TO_A' : 101, '\xf1' : 102 +} + +setc = { + '00': 0, '01': 1, '02': 2, '03': 3, '04': 4, + '05': 5, '06': 6, '07': 7, '08': 8, '09': 9, + '10':10, '11':11, '12':12, '13':13, '14':14, + '15':15, '16':16, '17':17, '18':18, '19':19, + '20':20, '21':21, '22':22, '23':23, '24':24, + '25':25, '26':26, '27':27, '28':28, '29':29, + '30':30, '31':31, '32':32, '33':33, '34':34, + '35':35, '36':36, '37':37, '38':38, '39':39, + '40':40, '41':41, '42':42, '43':43, '44':44, + '45':45, '46':46, '47':47, '48':48, '49':49, + '50':50, '51':51, '52':52, '53':53, '54':54, + '55':55, '56':56, '57':57, '58':58, '59':59, + '60':60, '61':61, '62':62, '63':63, '64':64, + '65':65, '66':66, '67':67, '68':68, '69':69, + '70':70, '71':71, '72':72, '73':73, '74':74, + '75':75, '76':76, '77':77, '78':78, '79':79, + '80':80, '81':81, '82':82, '83':83, '84':84, + '85':85, '86':86, '87':87, '88':88, '89':89, + '90':90, '91':91, '92':92, '93':93, '94':94, + '95':95, '96':96, '97':97, '98':98, '99':99, + + 'TO_B' : 100, 'TO_A' : 101, '\xf1' : 102 +} + +setmap = { + 'TO_A' : (seta, setb), + 'TO_B' : (setb, seta), + 'TO_C' : (setc, None), + 'START_A' : (starta, seta, setb), + 'START_B' : (startb, setb, seta), + 'START_C' : (startc, setc, None), +} +cStarts = ('START_B','TO_A','TO_B') +tos = list(setmap.keys()) + +class Code128(MultiWidthBarcode): + """ + Code 128 is a very compact symbology that can encode the entire + 128 character ASCII set, plus 4 special control codes, + (FNC1-FNC4, expressed in the input string as \xf1 to \xf4). + Code 128 can also encode digits at double density (2 per byte) + and has a mandatory checksum. Code 128 is well supported and + commonly used -- for example, by UPS for tracking labels. + + Because of these qualities, Code 128 is probably the best choice + for a linear symbology today (assuming you have a choice). + + Options that may be passed to constructor: + + value (int, or numeric string. required.): + The value to encode. + + barWidth (float, default .0075): + X-Dimension, or width of the smallest element + Minumum is .0075 inch (7.5 mils). + + barHeight (float, see default below): + Height of the symbol. Default is the height of the two + bearer bars (if they exist) plus the greater of .25 inch + or .15 times the symbol's length. + + quiet (bool, default 1): + Wether to include quiet zones in the symbol. + + lquiet (float, see default below): + Quiet zone size to left of code, if quiet is true. + Default is the greater of .25 inch, or 10 barWidth + + rquiet (float, defaults as above): + Quiet zone size to right left of code, if quiet is true. + + Sources of Information on Code 128: + + http://www.semiconductor.agilent.com/barcode/sg/Misc/code_128.html + http://www.adams1.com/pub/russadam/128code.html + http://www.barcodeman.com/c128.html + + Official Spec, "ANSI/AIM BC4-1999, ISS" is available for US$45 from + http://www.aimglobal.org/aimstore/ + """ + barWidth = inch * 0.0075 + lquiet = None + rquiet = None + quiet = 1 + barHeight = None + def __init__(self, value='', **args): + value = str(value) if isinstance(value,int) else asNative(value) + + for k, v in args.items(): + setattr(self, k, v) + + if self.quiet: + if self.lquiet is None: + self.lquiet = max(inch * 0.25, self.barWidth * 10.0) + if self.rquiet is None: + self.rquiet = max(inch * 0.25, self.barWidth * 10.0) + else: + self.lquiet = self.rquiet = 0.0 + + MultiWidthBarcode.__init__(self, value) + + def validate(self): + vval = "" + self.valid = 1 + for c in self.value: + if ord(c) > 127 and c not in '\xf1\xf2\xf3\xf4': + self.valid = 0 + continue + vval = vval + c + self.validated = vval + return vval + + + def _try_TO_C(self, l): + '''Improved version of old _trailingDigitsToC(self, l) inspired by''' + i = 0 + nl = [] + while i < len(l): + startpos = i + rl = [] + savings = -1 # the TO_C costs one character + while i < len(l): + if l[i] in cStarts: + j = i + break + elif l[i] == '\xf1': + rl.append(l[i]) + i += 1 + continue + elif l[i] in digits \ + and l[i+1] in digits: + rl.append(l[i] + l[i+1]) + i += 2 + savings += 1 + continue + else: + if l[i] in digits and l[i+1]=='STOP': + rrl = [] + rsavings = -1 #we need a TO_C + k = i + while k>startpos: + if l[k]=='\xf1': + rrl.append(l[i]) + k -= 1 + elif l[k] in digits and l[k-1] in digits: + rrl.append(l[k-1]+l[k]) + rsavings += 1 + k -= 2 + else: + break + rrl.reverse() + if rsavings>savings+int(savings>=0 and (startpos and nl[-1] in cStarts))-1: + nl += l[startpos] + startpos += 1 + rl = rrl + del rrl + i += 1 + break + ta = not (l[i]=='STOP' or j==i) + xs = savings>=0 and (startpos and nl[-1] in cStarts) + if savings+int(xs) > int(ta): + if xs: + toc = nl[-1][:-1]+'C' + del nl[-1] + else: + toc = 'TO_C' + nl += [toc]+rl + if ta: + nl.append('TO'+l[j][-2:]) + nl.append(l[i]) + else: + nl += l[startpos:i+1] + i += 1 + return nl + + def encode(self): + # First, encode using only B + s = self.validated + l = ['START_B'] + for c in s: + if c not in setb: + l = l + ['TO_A', c, 'TO_B'] + else: + l.append(c) + l.append('STOP') + + l = self._try_TO_C(l) + + # Finally, replace START_X,TO_Y with START_Y + if l[1] in tos: + l[:2] = ['START_' + l[1][-1]] + +# print repr(l) + + # encode into numbers + start, set, shset = setmap[l[0]] + e = [start] + + l = l[1:-1] + while l: + c = l[0] + if c == 'SHIFT': + e = e + [set[c], shset[l[1]]] + l = l[2:] + elif c in tos: + e.append(set[c]) + set, shset = setmap[c] + l = l[1:] + else: + e.append(set[c]) + l = l[1:] + + c = e[0] + for i in range(1, len(e)): + c = c + i * e[i] + self.encoded = e + [c % 103, stop] + return self.encoded + + def decompose(self): + self.decomposed = ''.join([_patterns[c] for c in self.encoded]) + return self.decomposed + + def _humanText(self): + return self.value + +class Code128Auto(Code128): + '''contributed by https://bitbucket.org/kylemacfarlane/ + see https://bitbucket.org/rptlab/reportlab/issues/69/implementations-of-code-128-auto-and-data + ''' + def encode(self): + s = self.validated + + current_set = None + l = [] + value = list(s) + while value: + c = value.pop(0) + if c in digits and value and value[0] in digits: + c += value.pop(0) + + if c in setc: + set_ = 'C' + elif c in setb: + set_ = 'B' + else: + set_ = 'A' + + if current_set != set_: + if current_set: + l.append('TO_' + set_) + else: + l.append('START_' + set_) + current_set = set_ + + l.append(c) + l.append('STOP') + + start, set, shset = setmap[l[0]] + e = [start] + + l = l[1:-1] + while l: + c = l[0] + if c == 'SHIFT': + e = e + [set[c], shset[l[1]]] + l = l[2:] + elif c in tos: + e.append(set[c]) + set, shset = setmap[c] + l = l[1:] + else: + e.append(set[c]) + l = l[1:] + + c = e[0] + for i in range(1, len(e)): + c = c + i * e[i] + self.encoded = e + [c % 103, stop] + return self.encoded + +if __name__=='__main__': + def main(): + from reportlab.graphics.barcode.code128 import Code128 + from reportlab.platypus import Spacer, SimpleDocTemplate + from reportlab.lib.units import inch + from reportlab.lib.styles import getSampleStyleSheet + from reportlab.platypus.paragraph import Paragraph + from reportlab.platypus.flowables import KeepTogether + styles = getSampleStyleSheet() + styleN = styles['Normal'] + styleH = styles['Heading1'] + story = [] + storyAdd = story.append + for s in ( + 'BBBB123456BBB', + 'BBBB12345BBB', + 'BBBB1234BBB', + 'BBBB123BBB', + 'BBBB12BBB', + 'BBBB1BBB', + 'BBBB123456aa', + 'BBBB1234aa', + 'BBBB123aa', + 'BBBB12aa', + 'BBBB1aa', + 'BBBB123456', + 'BBBB12345', + 'BBBB1234', + 'BBBB123', + 'BBBB12', + 'BBBB1', + '\xf11234B', + 'Ba\xf11234B', + 'Ba12', + 'Ba123B', + 'Ba1234B', + 'BBBB1234567', + 'BBBB1234567aa', + ): + storyAdd(KeepTogether([Paragraph('Code 128 %r' % s, styleN),Code128(s)])) + storyAdd(Spacer(inch,inch)) + SimpleDocTemplate('code128-out.pdf').build(story) + main() diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/code39.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/code39.py new file mode 100644 index 0000000000000000000000000000000000000000..65fd99d45a119573293e2b04f138de7998b084f4 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/code39.py @@ -0,0 +1,244 @@ +# +# Copyright (c) 1996-2000 Tyler C. Sarna +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. All advertising materials mentioning features or use of this software +# must display the following acknowledgement: +# This product includes software developed by Tyler C. Sarna. +# 4. Neither the name of the author nor the names of contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS +# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# + +from reportlab.lib.units import inch +from reportlab.lib.utils import asNative +from reportlab.graphics.barcode.common import Barcode +from string import ascii_uppercase, ascii_lowercase, digits as string_digits + +_patterns = { + '0': ("bsbSBsBsb", 0), '1': ("BsbSbsbsB", 1), + '2': ("bsBSbsbsB", 2), '3': ("BsBSbsbsb", 3), + '4': ("bsbSBsbsB", 4), '5': ("BsbSBsbsb", 5), + '6': ("bsBSBsbsb", 6), '7': ("bsbSbsBsB", 7), + '8': ("BsbSbsBsb", 8), '9': ("bsBSbsBsb", 9), + 'A': ("BsbsbSbsB", 10), 'B': ("bsBsbSbsB", 11), + 'C': ("BsBsbSbsb", 12), 'D': ("bsbsBSbsB", 13), + 'E': ("BsbsBSbsb", 14), 'F': ("bsBsBSbsb", 15), + 'G': ("bsbsbSBsB", 16), 'H': ("BsbsbSBsb", 17), + 'I': ("bsBsbSBsb", 18), 'J': ("bsbsBSBsb", 19), + 'K': ("BsbsbsbSB", 20), 'L': ("bsBsbsbSB", 21), + 'M': ("BsBsbsbSb", 22), 'N': ("bsbsBsbSB", 23), + 'O': ("BsbsBsbSb", 24), 'P': ("bsBsBsbSb", 25), + 'Q': ("bsbsbsBSB", 26), 'R': ("BsbsbsBSb", 27), + 'S': ("bsBsbsBSb", 28), 'T': ("bsbsBsBSb", 29), + 'U': ("BSbsbsbsB", 30), 'V': ("bSBsbsbsB", 31), + 'W': ("BSBsbsbsb", 32), 'X': ("bSbsBsbsB", 33), + 'Y': ("BSbsBsbsb", 34), 'Z': ("bSBsBsbsb", 35), + '-': ("bSbsbsBsB", 36), '.': ("BSbsbsBsb", 37), + ' ': ("bSBsbsBsb", 38), '*': ("bSbsBsBsb", None), + '$': ("bSbSbSbsb", 39), '/': ("bSbSbsbSb", 40), + '+': ("bSbsbSbSb", 41), '%': ("bsbSbSbSb", 42) + } + +_stdchrs = string_digits + ascii_uppercase + "-. $/+%" + +_extended = { + '\0': "%U", '\01': "$A", '\02': "$B", '\03': "$C", + '\04': "$D", '\05': "$E", '\06': "$F", '\07': "$G", + '\010': "$H", '\011': "$I", '\012': "$J", '\013': "$K", + '\014': "$L", '\015': "$M", '\016': "$N", '\017': "$O", + '\020': "$P", '\021': "$Q", '\022': "$R", '\023': "$S", + '\024': "$T", '\025': "$U", '\026': "$V", '\027': "$W", + '\030': "$X", '\031': "$Y", '\032': "$Z", '\033': "%A", + '\034': "%B", '\035': "%C", '\036': "%D", '\037': "%E", + '!': "/A", '"': "/B", '#': "/C", '$': "/D", + '%': "/E", '&': "/F", '\'': "/G", '(': "/H", + ')': "/I", '*': "/J", '+': "/K", ',': "/L", + '/': "/O", ':': "/Z", ';': "%F", '<': "%G", + '=': "%H", '>': "%I", '?': "%J", '@': "%V", + '[': "%K", '\\': "%L", ']': "%M", '^': "%N", + '_': "%O", '`': "%W", 'a': "+A", 'b': "+B", + 'c': "+C", 'd': "+D", 'e': "+E", 'f': "+F", + 'g': "+G", 'h': "+H", 'i': "+I", 'j': "+J", + 'k': "+K", 'l': "+L", 'm': "+M", 'n': "+N", + 'o': "+O", 'p': "+P", 'q': "+Q", 'r': "+R", + 's': "+S", 't': "+T", 'u': "+U", 'v': "+V", + 'w': "+W", 'x': "+X", 'y': "+Y", 'z': "+Z", + '{': "%P", '|': "%Q", '}': "%R", '~': "%S", + '\177': "%T" + } + + +_extchrs = _stdchrs + ascii_lowercase + \ + "\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017" + \ + "\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" + \ + "*!'#&\"(),:;<=>?@[\\]^_`{|}~\177" + +def _encode39(value, cksum, stop): + v = sum([_patterns[c][1] for c in value]) % 43 + if cksum: + value += _stdchrs[v] + if stop: value = '*'+value+'*' + return value + +class _Code39Base(Barcode): + barWidth = inch * 0.0075 + lquiet = None + rquiet = None + quiet = 1 + gap = None + barHeight = None + ratio = 2.2 + checksum = 1 + bearers = 0.0 + stop = 1 + def __init__(self, value = "", **args): + value = asNative(value) + for k, v in args.items(): + setattr(self, k, v) + + if self.quiet: + if self.lquiet is None: + self.lquiet = max(inch * 0.25, self.barWidth * 10.0) + self.rquiet = max(inch * 0.25, self.barWidth * 10.0) + else: + self.lquiet = self.rquiet = 0.0 + + Barcode.__init__(self, value) + + def decompose(self): + dval = "" + for c in self.encoded: + dval = dval + _patterns[c][0] + 'i' + self.decomposed = dval[:-1] + return self.decomposed + + def _humanText(self): + return self.stop and self.encoded[1:-1] or self.encoded + +class Standard39(_Code39Base): + """ + Options that may be passed to constructor: + + value (int, or numeric string required.): + The value to encode. + + barWidth (float, default .0075): + X-Dimension, or width of the smallest element + Minumum is .0075 inch (7.5 mils). + + ratio (float, default 2.2): + The ratio of wide elements to narrow elements. + Must be between 2.0 and 3.0 (or 2.2 and 3.0 if the + barWidth is greater than 20 mils (.02 inch)) + + gap (float or None, default None): + width of intercharacter gap. None means "use barWidth". + + barHeight (float, see default below): + Height of the symbol. Default is the height of the two + bearer bars (if they exist) plus the greater of .25 inch + or .15 times the symbol's length. + + checksum (bool, default 1): + Wether to compute and include the check digit + + bearers (float, in units of barWidth. default 0): + Height of bearer bars (horizontal bars along the top and + bottom of the barcode). Default is 0 (no bearers). + + quiet (bool, default 1): + Wether to include quiet zones in the symbol. + + lquiet (float, see default below): + Quiet zone size to left of code, if quiet is true. + Default is the greater of .25 inch, or .15 times the symbol's + length. + + rquiet (float, defaults as above): + Quiet zone size to right left of code, if quiet is true. + + stop (bool, default 1): + Whether to include start/stop symbols. + + Sources of Information on Code 39: + + http://www.semiconductor.agilent.com/barcode/sg/Misc/code_39.html + http://www.adams1.com/pub/russadam/39code.html + http://www.barcodeman.com/c39_1.html + + Official Spec, "ANSI/AIM BC1-1995, USS" is available for US$45 from + http://www.aimglobal.org/aimstore/ + """ + def validate(self): + vval = [].append + self.valid = 1 + for c in self.value: + if c in ascii_lowercase: + c = c.upper() + if c not in _stdchrs: + self.valid = 0 + continue + vval(c) + self.validated = ''.join(vval.__self__) + return self.validated + + def encode(self): + self.encoded = _encode39(self.validated, self.checksum, self.stop) + return self.encoded + +class Extended39(_Code39Base): + """ + Extended Code 39 is a convention for encoding additional characters + not present in stanmdard Code 39 by using pairs of characters to + represent the characters missing in Standard Code 39. + + See Standard39 for arguments. + + Sources of Information on Extended Code 39: + + http://www.semiconductor.agilent.com/barcode/sg/Misc/xcode_39.html + http://www.barcodeman.com/c39_ext.html + """ + def validate(self): + vval = "" + self.valid = 1 + for c in self.value: + if c not in _extchrs: + self.valid = 0 + continue + vval = vval + c + self.validated = vval + return vval + + def encode(self): + self.encoded = "" + for c in self.validated: + if c in _extended: + self.encoded = self.encoded + _extended[c] + elif c in _stdchrs: + self.encoded = self.encoded + c + else: + raise ValueError + self.encoded = _encode39(self.encoded, self.checksum,self.stop) + return self.encoded diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/code93.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/code93.py new file mode 100644 index 0000000000000000000000000000000000000000..e1c95a1756fe2b4d7d504b1ccacc65f279839893 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/code93.py @@ -0,0 +1,234 @@ +# +# Copyright (c) 2000 Tyler C. Sarna +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. All advertising materials mentioning features or use of this software +# must display the following acknowledgement: +# This product includes software developed by Tyler C. Sarna. +# 4. Neither the name of the author nor the names of contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS +# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# + +from reportlab.lib.units import inch +from reportlab.lib.utils import asNative +from reportlab.graphics.barcode.common import MultiWidthBarcode + +_patterns = { + '0' : ('AcAaAb', 0), '1' : ('AaAbAc', 1), '2' : ('AaAcAb', 2), + '3' : ('AaAdAa', 3), '4' : ('AbAaAc', 4), '5' : ('AbAbAb', 5), + '6' : ('AbAcAa', 6), '7' : ('AaAaAd', 7), '8' : ('AcAbAa', 8), + '9' : ('AdAaAa', 9), 'A' : ('BaAaAc', 10), 'B' : ('BaAbAb', 11), + 'C' : ('BaAcAa', 12), 'D' : ('BbAaAb', 13), 'E' : ('BbAbAa', 14), + 'F' : ('BcAaAa', 15), 'G' : ('AaBaAc', 16), 'H' : ('AaBbAb', 17), + 'I' : ('AaBcAa', 18), 'J' : ('AbBaAb', 19), 'K' : ('AcBaAa', 20), + 'L' : ('AaAaBc', 21), 'M' : ('AaAbBb', 22), 'N' : ('AaAcBa', 23), + 'O' : ('AbAaBb', 24), 'P' : ('AcAaBa', 25), 'Q' : ('BaBaAb', 26), + 'R' : ('BaBbAa', 27), 'S' : ('BaAaBb', 28), 'T' : ('BaAbBa', 29), + 'U' : ('BbAaBa', 30), 'V' : ('BbBaAa', 31), 'W' : ('AaBaBb', 32), + 'X' : ('AaBbBa', 33), 'Y' : ('AbBaBa', 34), 'Z' : ('AbCaAa', 35), + '-' : ('AbAaCa', 36), '.' : ('CaAaAb', 37), ' ' : ('CaAbAa', 38), + '$' : ('CbAaAa', 39), '/' : ('AaBaCa', 40), '+' : ('AaCaBa', 41), + '%' : ('BaAaCa', 42), '#' : ('AbAbBa', 43), '!' : ('CaBaAa', 44), + '=' : ('CaAaBa', 45), '&' : ('AbBbAa', 46), + 'start' : ('AaAaDa', -1), 'stop' : ('AaAaDaA', -2) +} + +_charsbyval = {} +for k, v in _patterns.items(): + _charsbyval[v[1]] = k + +_extended = { + '\x00' : '!U', '\x01' : '#A', '\x02' : '#B', '\x03' : '#C', + '\x04' : '#D', '\x05' : '#E', '\x06' : '#F', '\x07' : '#G', + '\x08' : '#H', '\x09' : '#I', '\x0a' : '#J', '\x0b' : '#K', + '\x0c' : '#L', '\x0d' : '#M', '\x0e' : '#N', '\x0f' : '#O', + '\x10' : '#P', '\x11' : '#Q', '\x12' : '#R', '\x13' : '#S', + '\x14' : '#T', '\x15' : '#U', '\x16' : '#V', '\x17' : '#W', + '\x18' : '#X', '\x19' : '#Y', '\x1a' : '#Z', '\x1b' : '!A', + '\x1c' : '!B', '\x1d' : '!C', '\x1e' : '!D', '\x1f' : '!E', + '!' : '=A', '"' : '=B', '#' : '=C', '$' : '=D', + '%' : '=E', '&' : '=F', '\'' : '=G', '(' : '=H', + ')' : '=I', '*' : '=J', '+' : '=K', ',' : '=L', + '/' : '=O', ':' : '=Z', ';' : '!F', '<' : '!G', + '=' : '!H', '>' : '!I', '?' : '!J', '@' : '!V', + '[' : '!K', '\\' : '!L', ']' : '!M', '^' : '!N', + '_' : '!O', '`' : '!W', 'a' : '&A', 'b' : '&B', + 'c' : '&C', 'd' : '&D', 'e' : '&E', 'f' : '&F', + 'g' : '&G', 'h' : '&H', 'i' : '&I', 'j' : '&J', + 'k' : '&K', 'l' : '&L', 'm' : '&M', 'n' : '&N', + 'o' : '&O', 'p' : '&P', 'q' : '&Q', 'r' : '&R', + 's' : '&S', 't' : '&T', 'u' : '&U', 'v' : '&V', + 'w' : '&W', 'x' : '&X', 'y' : '&Y', 'z' : '&Z', + '{' : '!P', '|' : '!Q', '}' : '!R', '~' : '!S', + '\x7f' : '!T' +} + +def _encode93(str): + s = list(str) + s.reverse() + + # compute 'C' checksum + i = 0; v = 1; c = 0 + while i < len(s): + c = c + v * _patterns[s[i]][1] + i = i + 1; v = v + 1 + if v > 20: + v = 1 + s.insert(0, _charsbyval[c % 47]) + + # compute 'K' checksum + i = 0; v = 1; c = 0 + while i < len(s): + c = c + v * _patterns[s[i]][1] + i = i + 1; v = v + 1 + if v > 15: + v = 1 + s.insert(0, _charsbyval[c % 47]) + + s.reverse() + + return ''.join(s) + +class _Code93Base(MultiWidthBarcode): + barWidth = inch * 0.0075 + lquiet = None + rquiet = None + quiet = 1 + barHeight = None + stop = 1 + def __init__(self, value='', **args): + + if type(value) is type(1): + value = asNative(value) + + for (k, v) in args.items(): + setattr(self, k, v) + + if self.quiet: + if self.lquiet is None: + self.lquiet = max(inch * 0.25, self.barWidth * 10.0) + self.rquiet = max(inch * 0.25, self.barWidth * 10.0) + else: + self.lquiet = self.rquiet = 0.0 + + MultiWidthBarcode.__init__(self, value) + + def decompose(self): + dval = self.stop and [_patterns['start'][0]] or [] + dval += [_patterns[c][0] for c in self.encoded] + if self.stop: dval.append(_patterns['stop'][0]) + self.decomposed = ''.join(dval) + return self.decomposed + +class Standard93(_Code93Base): + """ + Code 93 is a Uppercase alphanumeric symbology with some punctuation. + See Extended Code 93 for a variant that can represent the entire + 128 characrter ASCII set. + + Options that may be passed to constructor: + + value (int, or numeric string. required.): + The value to encode. + + barWidth (float, default .0075): + X-Dimension, or width of the smallest element + Minumum is .0075 inch (7.5 mils). + + barHeight (float, see default below): + Height of the symbol. Default is the height of the two + bearer bars (if they exist) plus the greater of .25 inch + or .15 times the symbol's length. + + quiet (bool, default 1): + Wether to include quiet zones in the symbol. + + lquiet (float, see default below): + Quiet zone size to left of code, if quiet is true. + Default is the greater of .25 inch, or 10 barWidth + + rquiet (float, defaults as above): + Quiet zone size to right left of code, if quiet is true. + + stop (bool, default 1): + Whether to include start/stop symbols. + + Sources of Information on Code 93: + + http://www.semiconductor.agilent.com/barcode/sg/Misc/code_93.html + + Official Spec, "NSI/AIM BC5-1995, USS" is available for US$45 from + http://www.aimglobal.org/aimstore/ + """ + def validate(self): + vval = "" + self.valid = 1 + for c in self.value.upper(): + if c not in _patterns: + self.valid = 0 + continue + vval = vval + c + self.validated = vval + return vval + + def encode(self): + self.encoded = _encode93(self.validated) + return self.encoded + + +class Extended93(_Code93Base): + """ + Extended Code 93 is a convention for encoding the entire 128 character + set using pairs of characters to represent the characters missing in + Standard Code 93. It is very much like Extended Code 39 in that way. + + See Standard93 for arguments. + """ + + def validate(self): + vval = [] + self.valid = 1 + a = vval.append + for c in self.value: + if c not in _patterns and c not in _extended: + self.valid = 0 + continue + a(c) + self.validated = ''.join(vval) + return self.validated + + def encode(self): + self.encoded = "" + for c in self.validated: + if c in _patterns: + self.encoded = self.encoded + c + elif c in _extended: + self.encoded = self.encoded + _extended[c] + else: + raise ValueError + self.encoded = _encode93(self.encoded) + return self.encoded + + def _humanText(self): + return self.validated+self.encoded[-2:] diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/common.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/common.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae03a21b2fbeeb2aa66a149e908be596e2c87e --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/common.py @@ -0,0 +1,775 @@ +# +# Copyright (c) 1996-2000 Tyler C. Sarna +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. All advertising materials mentioning features or use of this software +# must display the following acknowledgement: +# This product includes software developed by Tyler C. Sarna. +# 4. Neither the name of the author nor the names of contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS +# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# + +from reportlab.platypus.flowables import Flowable +from reportlab.lib.units import inch +from string import ascii_lowercase, ascii_uppercase, digits as string_digits + +class Barcode(Flowable): + """Abstract Base for barcodes. Includes implementations of + some methods suitable for the more primitive barcode types""" + + fontName = 'Courier' + fontSize = 12 + humanReadable = 0 + + def _humanText(self): + return self.encoded + + def __init__(self, value='',**kwd): + self.value = str(value) + + self._setKeywords(**kwd) + if not hasattr(self, 'gap'): + self.gap = None + + + def _calculate(self): + self.validate() + self.encode() + self.decompose() + self.computeSize() + + def _setKeywords(self,**kwd): + for (k, v) in kwd.items(): + setattr(self, k, v) + + def validate(self): + self.valid = 1 + self.validated = self.value + + def encode(self): + self.encoded = self.validated + + def decompose(self): + self.decomposed = self.encoded + + def computeSize(self, *args): + barWidth = self.barWidth + wx = barWidth * self.ratio + + if self.gap == None: + self.gap = barWidth + + w = 0.0 + + for c in self.decomposed: + if c in 'sb': + w = w + barWidth + elif c in 'SB': + w = w + wx + else: # 'i' + w = w + self.gap + + if self.barHeight is None: + self.barHeight = w * 0.15 + self.barHeight = max(0.25 * inch, self.barHeight) + if self.bearers: + self.barHeight = self.barHeight + self.bearers * 2.0 * barWidth + + if self.quiet: + w += self.lquiet + self.rquiet + + + self._height = self.barHeight + self._width = w + + @property + def width(self): + self._calculate() + return self._width + @width.setter + def width(self,v): + pass + + @property + def height(self): + self._calculate() + return self._height + @height.setter + def height(self,v): + pass + + def draw(self): + self._calculate() + barWidth = self.barWidth + wx = barWidth * self.ratio + + left = self.quiet and self.lquiet or 0 + b = self.bearers * barWidth + bb = b * 0.5 + tb = self.barHeight - (b * 1.5) + + for c in self.decomposed: + if c == 'i': + left = left + self.gap + elif c == 's': + left = left + barWidth + elif c == 'S': + left = left + wx + elif c == 'b': + self.rect(left, bb, barWidth, tb) + left = left + barWidth + elif c == 'B': + self.rect(left, bb, wx, tb) + left = left + wx + + if self.bearers: + if getattr(self,'bearerBox', None): + canv = self.canv + if hasattr(canv,'_Gadd'): + #this is a widget rect takes other arguments + canv.rect(bb, bb, self.width, self.barHeight-b, + strokeWidth=b, strokeColor=self.barFillColor or self.barStrokeColor, fillColor=None) + else: + canv.saveState() + canv.setLineWidth(b) + canv.rect(bb, bb, self.width, self.barHeight-b, stroke=1, fill=0) + canv.restoreState() + else: + w = self._width - (self.lquiet + self.rquiet) + self.rect(self.lquiet, 0, w, b) + self.rect(self.lquiet, self.barHeight - b, w, b) + + self.drawHumanReadable() + + def drawHumanReadable(self): + if self.humanReadable: + #we have text + from reportlab.pdfbase.pdfmetrics import getAscent, stringWidth + s = str(self._humanText()) + fontSize = self.fontSize + fontName = self.fontName + w = stringWidth(s,fontName,fontSize) + width = self._width + if self.quiet: + width -= self.lquiet+self.rquiet + x = self.lquiet + else: + x = 0 + if w>width: fontSize *= width/float(w) + y = 1.07*getAscent(fontName)*fontSize/1000. + self.annotate(x+width/2.,-y,s,fontName,fontSize) + + def rect(self, x, y, w, h): + self.canv.rect(x, y, w, h, stroke=0, fill=1) + + def annotate(self,x,y,text,fontName,fontSize,anchor='middle'): + canv = self.canv + canv.saveState() + canv.setFont(self.fontName,fontSize) + if anchor=='middle': func = 'drawCentredString' + elif anchor=='end': func = 'drawRightString' + else: func = 'drawString' + getattr(canv,func)(x,y,text) + canv.restoreState() + + def _checkVal(self, name, v, allowed): + if v not in allowed: + raise ValueError('%s attribute %s is invalid %r\nnot in allowed %r' % ( + self.__class__.__name__, name, v, allowed)) + return v + +class MultiWidthBarcode(Barcode): + """Base for variable-bar-width codes like Code93 and Code128""" + + def computeSize(self, *args): + barWidth = self.barWidth + oa, oA = ord('a') - 1, ord('A') - 1 + + w = 0.0 + + for c in self.decomposed: + oc = ord(c) + if c in ascii_lowercase: + w = w + barWidth * (oc - oa) + elif c in ascii_uppercase: + w = w + barWidth * (oc - oA) + + if self.barHeight is None: + self.barHeight = w * 0.15 + self.barHeight = max(0.25 * inch, self.barHeight) + + if self.quiet: + w += self.lquiet + self.rquiet + + self._height = self.barHeight + self._width = w + + def draw(self): + self._calculate() + oa, oA = ord('a') - 1, ord('A') - 1 + barWidth = self.barWidth + left = self.quiet and self.lquiet or 0 + + for c in self.decomposed: + oc = ord(c) + if c in ascii_lowercase: + left = left + (oc - oa) * barWidth + elif c in ascii_uppercase: + w = (oc - oA) * barWidth + self.rect(left, 0, w, self.barHeight) + left += w + self.drawHumanReadable() + +class I2of5(Barcode): + """ + Interleaved 2 of 5 is a numeric-only barcode. It encodes an even + number of digits; if an odd number is given, a 0 is prepended. + + Options that may be passed to constructor: + + value (int, or numeric string required.): + The value to encode. + + barWidth (float, default .0075): + X-Dimension, or width of the smallest element + Minumum is .0075 inch (7.5 mils). + + ratio (float, default 2.2): + The ratio of wide elements to narrow elements. + Must be between 2.0 and 3.0 (or 2.2 and 3.0 if the + barWidth is greater than 20 mils (.02 inch)) + + gap (float or None, default None): + width of intercharacter gap. None means "use barWidth". + + barHeight (float, see default below): + Height of the symbol. Default is the height of the two + bearer bars (if they exist) plus the greater of .25 inch + or .15 times the symbol's length. + + checksum (bool, default 1): + Whether to compute and include the check digit + + bearers (float, in units of barWidth. default 3.0): + Height of bearer bars (horizontal bars along the top and + bottom of the barcode). Default is 3 x-dimensions. + Set to zero for no bearer bars. (Bearer bars help detect + misscans, so it is suggested to leave them on). + + bearerBox (bool default False) + if true draw a true rectangle of width bearers around the barcode. + + quiet (bool, default 1): + Whether to include quiet zones in the symbol. + + lquiet (float, see default below): + Quiet zone size to left of code, if quiet is true. + Default is the greater of .25 inch, or .15 times the symbol's + length. + + rquiet (float, defaults as above): + Quiet zone size to right left of code, if quiet is true. + + stop (bool, default 1): + Whether to include start/stop symbols. + + Sources of Information on Interleaved 2 of 5: + + http://www.semiconductor.agilent.com/barcode/sg/Misc/i_25.html + http://www.adams1.com/pub/russadam/i25code.html + + Official Spec, "ANSI/AIM BC2-1995, USS" is available for US$45 from + http://www.aimglobal.org/aimstore/ + """ + + patterns = { + 'start' : 'bsbs', + 'stop' : 'Bsb', + + 'B0' : 'bbBBb', 'S0' : 'ssSSs', + 'B1' : 'BbbbB', 'S1' : 'SsssS', + 'B2' : 'bBbbB', 'S2' : 'sSssS', + 'B3' : 'BBbbb', 'S3' : 'SSsss', + 'B4' : 'bbBbB', 'S4' : 'ssSsS', + 'B5' : 'BbBbb', 'S5' : 'SsSss', + 'B6' : 'bBBbb', 'S6' : 'sSSss', + 'B7' : 'bbbBB', 'S7' : 'sssSS', + 'B8' : 'BbbBb', 'S8' : 'SssSs', + 'B9' : 'bBbBb', 'S9' : 'sSsSs' + } + + barHeight = None + barWidth = inch * 0.0075 + ratio = 2.2 + checksum = 1 + bearers = 3.0 + bearerBox = False + quiet = 1 + lquiet = None + rquiet = None + stop = 1 + + def __init__(self, value='', **args): + + if type(value) == type(1): + value = str(value) + + for k, v in args.items(): + setattr(self, k, v) + + if self.quiet: + if self.lquiet is None: + self.lquiet = min(inch * 0.25, self.barWidth * 10.0) + self.rquiet = min(inch * 0.25, self.barWidth * 10.0) + else: + self.lquiet = self.rquiet = 0.0 + + Barcode.__init__(self, value) + + def validate(self): + vval = "" + self.valid = 1 + for c in self.value.strip(): + if c not in string_digits: + self.valid = 0 + continue + vval = vval + c + self.validated = vval + return vval + + def encode(self): + s = self.validated + cs = self.checksum + c = len(s) + + #ensure len(result)%2 == 0, checksum included + if ((c % 2 == 0) and cs) or ((c % 2 == 1) and not cs): + s = '0' + s + c += 1 + + if cs: + c = 3*sum([int(s[i]) for i in range(0,c,2)])+sum([int(s[i]) for i in range(1,c,2)]) + s += str((10 - c) % 10) + + self.encoded = s + + def decompose(self): + dval = self.stop and [self.patterns['start']] or [] + a = dval.append + + for i in range(0, len(self.encoded), 2): + b = self.patterns['B' + self.encoded[i]] + s = self.patterns['S' + self.encoded[i+1]] + + for i in range(0, len(b)): + a(b[i] + s[i]) + + if self.stop: a(self.patterns['stop']) + self.decomposed = ''.join(dval) + return self.decomposed + +class MSI(Barcode): + """ + MSI is a numeric-only barcode. + + Options that may be passed to constructor: + + value (int, or numeric string required.): + The value to encode. + + barWidth (float, default .0075): + X-Dimension, or width of the smallest element + + ratio (float, default 2.2): + The ratio of wide elements to narrow elements. + + gap (float or None, default None): + width of intercharacter gap. None means "use barWidth". + + barHeight (float, see default below): + Height of the symbol. Default is the height of the two + bearer bars (if they exist) plus the greater of .25 inch + or .15 times the symbol's length. + + checksum (bool, default 1): + Wether to compute and include the check digit + + bearers (float, in units of barWidth. default 0): + Height of bearer bars (horizontal bars along the top and + bottom of the barcode). Default is 0 (no bearers). + + lquiet (float, see default below): + Quiet zone size to left of code, if quiet is true. + Default is the greater of .25 inch, or 10 barWidths. + + rquiet (float, defaults as above): + Quiet zone size to right left of code, if quiet is true. + + stop (bool, default 1): + Whether to include start/stop symbols. + + Sources of Information on MSI Bar Code: + + http://www.semiconductor.agilent.com/barcode/sg/Misc/msi_code.html + http://www.adams1.com/pub/russadam/plessy.html + """ + + patterns = { + 'start' : 'Bs', 'stop' : 'bSb', + + '0' : 'bSbSbSbS', '1' : 'bSbSbSBs', + '2' : 'bSbSBsbS', '3' : 'bSbSBsBs', + '4' : 'bSBsbSbS', '5' : 'bSBsbSBs', + '6' : 'bSBsBsbS', '7' : 'bSBsBsBs', + '8' : 'BsbSbSbS', '9' : 'BsbSbSBs' + } + + stop = 1 + barHeight = None + barWidth = inch * 0.0075 + ratio = 2.2 + checksum = 1 + bearers = 0.0 + quiet = 1 + lquiet = None + rquiet = None + + def __init__(self, value="", **args): + + if type(value) == type(1): + value = str(value) + + for k, v in args.items(): + setattr(self, k, v) + + if self.quiet: + if self.lquiet is None: + self.lquiet = max(inch * 0.25, self.barWidth * 10.0) + self.rquiet = max(inch * 0.25, self.barWidth * 10.0) + else: + self.lquiet = self.rquiet = 0.0 + + Barcode.__init__(self, value) + + def validate(self): + vval = "" + self.valid = 1 + for c in self.value.strip(): + if c not in string_digits: + self.valid = 0 + continue + vval = vval + c + self.validated = vval + return vval + + def encode(self): + s = self.validated + + if self.checksum: + c = '' + for i in range(1, len(s), 2): + c = c + s[i] + d = str(int(c) * 2) + t = 0 + for c in d: + t = t + int(c) + for i in range(0, len(s), 2): + t = t + int(s[i]) + c = 10 - (t % 10) + + s = s + str(c) + + self.encoded = s + + def decompose(self): + dval = self.stop and [self.patterns['start']] or [] + dval += [self.patterns[c] for c in self.encoded] + if self.stop: dval.append(self.patterns['stop']) + self.decomposed = ''.join(dval) + return self.decomposed + +class Codabar(Barcode): + """ + Codabar is a numeric plus some puntuation ("-$:/.+") barcode + with four start/stop characters (A, B, C, and D). + + Options that may be passed to constructor: + + value (string required.): + The value to encode. + + barWidth (float, default .0065): + X-Dimension, or width of the smallest element + minimum is 6.5 mils (.0065 inch) + + ratio (float, default 2.0): + The ratio of wide elements to narrow elements. + + gap (float or None, default None): + width of intercharacter gap. None means "use barWidth". + + barHeight (float, see default below): + Height of the symbol. Default is the height of the two + bearer bars (if they exist) plus the greater of .25 inch + or .15 times the symbol's length. + + checksum (bool, default 0): + Whether to compute and include the check digit + + bearers (float, in units of barWidth. default 0): + Height of bearer bars (horizontal bars along the top and + bottom of the barcode). Default is 0 (no bearers). + + quiet (bool, default 1): + Whether to include quiet zones in the symbol. + + stop (bool, default 1): + Whether to include start/stop symbols. + + lquiet (float, see default below): + Quiet zone size to left of code, if quiet is true. + Default is the greater of .25 inch, or 10 barWidth + + rquiet (float, defaults as above): + Quiet zone size to right left of code, if quiet is true. + + Sources of Information on Codabar + + http://www.semiconductor.agilent.com/barcode/sg/Misc/codabar.html + http://www.barcodeman.com/codabar.html + + Official Spec, "ANSI/AIM BC3-1995, USS" is available for US$45 from + http://www.aimglobal.org/aimstore/ + """ + + patterns = { + '0': 'bsbsbSB', '1': 'bsbsBSb', '2': 'bsbSbsB', + '3': 'BSbsbsb', '4': 'bsBsbSb', '5': 'BsbsbSb', + '6': 'bSbsbsB', '7': 'bSbsBsb', '8': 'bSBsbsb', + '9': 'BsbSbsb', '-': 'bsbSBsb', '$': 'bsBSbsb', + ':': 'BsbsBsB', '/': 'BsBsbsB', '.': 'BsBsBsb', + '+': 'bsBsBsB', 'A': 'bsBSbSb', 'B': 'bSbSbsB', + 'C': 'bsbSbSB', 'D': 'bsbSBSb' + } + + values = { + '0' : 0, '1' : 1, '2' : 2, '3' : 3, '4' : 4, + '5' : 5, '6' : 6, '7' : 7, '8' : 8, '9' : 9, + '-' : 10, '$' : 11, ':' : 12, '/' : 13, '.' : 14, + '+' : 15, 'A' : 16, 'B' : 17, 'C' : 18, 'D' : 19 + } + + chars = string_digits + "-$:/.+" + + stop = 1 + barHeight = None + barWidth = inch * 0.0065 + ratio = 2.0 # XXX ? + checksum = 0 + bearers = 0.0 + quiet = 1 + lquiet = None + rquiet = None + + def __init__(self, value='', **args): + if type(value) == type(1): + value = str(value) + + for k, v in args.items(): + setattr(self, k, v) + + if self.quiet: + if self.lquiet is None: + self.lquiet = min(inch * 0.25, self.barWidth * 10.0) + self.rquiet = min(inch * 0.25, self.barWidth * 10.0) + else: + self.lquiet = self.rquiet = 0.0 + + Barcode.__init__(self, value) + + def validate(self): + vval = "" + self.valid = 1 + s = self.value.strip() + for i in range(0, len(s)): + c = s[i] + if c not in self.chars: + if ((i != 0) and (i != len(s) - 1)) or (c not in 'ABCD'): + self.Valid = 0 + continue + vval = vval + c + + if self.stop: + if vval[0] not in 'ABCD': + vval = 'A' + vval + if vval[-1] not in 'ABCD': + vval = vval + vval[0] + + self.validated = vval + return vval + + def encode(self): + s = self.validated + + if self.checksum: + v = sum([self.values[c] for c in s]) + s += self.chars[v % 16] + + self.encoded = s + + def decompose(self): + dval = ''.join([self.patterns[c]+'i' for c in self.encoded]) + self.decomposed = dval[:-1] + return self.decomposed + +class Code11(Barcode): + """ + Code 11 is an almost-numeric barcode. It encodes the digits 0-9 plus + dash ("-"). 11 characters total, hence the name. + + value (int or string required.): + The value to encode. + + barWidth (float, default .0075): + X-Dimension, or width of the smallest element + + ratio (float, default 2.2): + The ratio of wide elements to narrow elements. + + gap (float or None, default None): + width of intercharacter gap. None means "use barWidth". + + barHeight (float, see default below): + Height of the symbol. Default is the height of the two + bearer bars (if they exist) plus the greater of .25 inch + or .15 times the symbol's length. + + checksum (0 none, 1 1-digit, 2 2-digit, -1 auto, default -1): + How many checksum digits to include. -1 ("auto") means + 1 if the number of digits is 10 or less, else 2. + + bearers (float, in units of barWidth. default 0): + Height of bearer bars (horizontal bars along the top and + bottom of the barcode). Default is 0 (no bearers). + + quiet (bool, default 1): + Wether to include quiet zones in the symbol. + + lquiet (float, see default below): + Quiet zone size to left of code, if quiet is true. + Default is the greater of .25 inch, or 10 barWidth + + rquiet (float, defaults as above): + Quiet zone size to right left of code, if quiet is true. + + Sources of Information on Code 11: + + http://www.cwi.nl/people/dik/english/codes/barcodes.html + """ + + chars = '0123456789-' + + patterns = { + '0' : 'bsbsB', '1' : 'BsbsB', '2' : 'bSbsB', + '3' : 'BSbsb', '4' : 'bsBsB', '5' : 'BsBsb', + '6' : 'bSBsb', '7' : 'bsbSB', '8' : 'BsbSb', + '9' : 'Bsbsb', '-' : 'bsBsb', 'S' : 'bsBSb' # Start/Stop + } + + values = { + '0' : 0, '1' : 1, '2' : 2, '3' : 3, '4' : 4, + '5' : 5, '6' : 6, '7' : 7, '8' : 8, '9' : 9, + '-' : 10, + } + + stop = 1 + barHeight = None + barWidth = inch * 0.0075 + ratio = 2.2 # XXX ? + checksum = -1 # Auto + bearers = 0.0 + quiet = 1 + lquiet = None + rquiet = None + def __init__(self, value='', **args): + if type(value) == type(1): + value = str(value) + + for k, v in args.items(): + setattr(self, k, v) + + if self.quiet: + if self.lquiet is None: + self.lquiet = min(inch * 0.25, self.barWidth * 10.0) + self.rquiet = min(inch * 0.25, self.barWidth * 10.0) + else: + self.lquiet = self.rquiet = 0.0 + + Barcode.__init__(self, value) + + def validate(self): + vval = "" + self.valid = 1 + s = self.value.strip() + for i in range(0, len(s)): + c = s[i] + if c not in self.chars: + self.Valid = 0 + continue + vval = vval + c + + self.validated = vval + return vval + + def _addCSD(self,s,m): + # compute first checksum + i = c = 0 + v = 1 + V = self.values + while i < len(s): + c += v * V[s[-(i+1)]] + i += 1 + v += 1 + if v==m: + v = 1 + return s+self.chars[c % 11] + + def encode(self): + s = self.validated + + tcs = self.checksum + if tcs<0: + self.checksum = tcs = 1+int(len(s)>10) + + if tcs > 0: s = self._addCSD(s,11) + if tcs > 1: s = self._addCSD(s,10) + + self.encoded = self.stop and ('S' + s + 'S') or s + + def decompose(self): + self.decomposed = ''.join([(self.patterns[c]+'i') for c in self.encoded])[:-1] + return self.decomposed + + def _humanText(self): + return self.stop and self.encoded[1:-1] or self.encoded diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/dmtx.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/dmtx.py new file mode 100644 index 0000000000000000000000000000000000000000..bc155d254e70f411b68765897eeed6a828967398 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/dmtx.py @@ -0,0 +1,273 @@ +try: + from pylibdmtx import pylibdmtx +except ImportError: + pylibdmtx = None + __all__ = () +else: + __all__=('DataMatrix',) + +from reportlab.graphics.barcode.common import Barcode +from reportlab.lib.utils import asBytes +from reportlab.platypus.paraparser import _num as paraparser_num +from reportlab.graphics.widgetbase import Widget +from reportlab.lib.validators import isColor, isString, isColorOrNone, isNumber, isBoxAnchor +from reportlab.lib.attrmap import AttrMap, AttrMapValue +from reportlab.lib.colors import toColor +from reportlab.graphics.shapes import Group, Rect + +def _numConv(x): + return x if isinstance(x,(int,float)) else paraparser_num(x) + +class _DMTXCheck: + @classmethod + def pylibdmtx_check(cls): + if not pylibdmtx: + raise ValueError('The %s class requires package pylibdmtx' % cls.__name__) + +class DataMatrix(Barcode,_DMTXCheck): + def __init__(self, value='', **kwds): + self.pylibdmtx_check() + self._recalc = True + self.value = value + self.cellSize = kwds.pop('cellSize','5x5') + self.size = kwds.pop('size','SquareAuto') + self.encoding = kwds.pop('encoding','Ascii') + self.anchor = kwds.pop('anchor','sw') + self.color = kwds.pop('color',(0,0,0)) + self.bgColor = kwds.pop('bgColor',None) + self.x = kwds.pop('x',0) + self.y = kwds.pop('y',0) + self.border = kwds.pop('border',5) + + @property + def value(self): + return self._value + + @value.setter + def value(self,v): + self._value = asBytes(v) + self._recalc = True + + @property + def size(self): + return self._size + + @size.setter + def size(self,v): + self._size = self._checkVal('size', v, pylibdmtx.ENCODING_SIZE_NAMES) + self._recalc = True + + @property + def border(self): + return self._border + + @border.setter + def border(self,v): + self._border = _numConv(v) + self._recalc = True + + @property + def x(self): + return self._x + + @x.setter + def x(self,v): + self._x = _numConv(v) + self._recalc = True + + @property + def y(self): + return self._y + + @y.setter + def y(self,v): + self._y = _numConv(v) + self._recalc = True + + @property + def cellSize(self): + return self._cellSize + + @size.setter + def cellSize(self,v): + self._cellSize = v + self._recalc = True + + @property + def encoding(self): + return self._encoding + + @encoding.setter + def encoding(self,v): + self._encoding = self._checkVal('encoding', v, pylibdmtx.ENCODING_SCHEME_NAMES) + self._recalc = True + + @property + def anchor(self): + return self._anchor + + @anchor.setter + def anchor(self,v): + self._anchor = self._checkVal('anchor', v, ('n','ne','e','se','s','sw','w','nw','c')) + self._recalc = True + + def recalc(self): + if not self._recalc: return + data = self._value + size = self._size + encoding = self._encoding + e = pylibdmtx.encode(data, size=size, scheme=encoding) + iW = e.width + iH = e.height + p = e.pixels + iCellSize = 5 + bpp = 3 #bytes per pixel + rowLen = iW*bpp + cellLen = iCellSize*bpp + assert len(p)//rowLen == iH + matrix = list(filter(None, + (''.join( + (('x' if p[j:j+bpp] != b'\xff\xff\xff' else ' ') + for j in range(i,i+rowLen,cellLen))).strip() + for i in range(0,iH*rowLen,rowLen*iCellSize)))) + self._nRows = len(matrix) + self._nCols = len(matrix[-1]) + self._matrix = '\n'.join(matrix) + + cellWidth = self._cellSize + if cellWidth: + cellWidth = cellWidth.split('x') + if len(cellWidth)>2: + raise ValueError('cellSize needs to be distance x distance not %r' % self._cellSize) + elif len(cellWidth)==2: + cellWidth, cellHeight = cellWidth + else: + cellWidth = cellHeight = cellWidth[0] + cellWidth = _numConv(cellWidth) + cellHeight = _numConv(cellHeight) + else: + cellWidth = cellHeight = iCellSize + self._cellWidth = cellWidth + self._cellHeight = cellHeight + self._recalc = False + self._bord = max(self.border,cellWidth,cellHeight) + self._width = cellWidth*self._nCols + 2*self._bord + self._height = cellHeight*self._nRows + 2*self._bord + + @property + def matrix(self): + self.recalc() + return self._matrix + + @property + def width(self): + self.recalc() + return self._width + + @property + def height(self): + self.recalc() + return self._height + + @property + def cellWidth(self): + self.recalc() + return self._cellWidth + + @property + def cellHeight(self): + self.recalc() + return self._cellHeight + + def draw(self): + self.recalc() + canv = self.canv + w = self.width + h = self.height + x = self.x + y = self.y + b = self._bord + + anchor = self.anchor + if anchor in ('nw','n','ne'): + y -= h + elif anchor in ('c','e','w'): + y -= h//2 + if anchor in ('ne','e','se'): + x -= w + elif anchor in ('n','c','s'): + x -= w//2 + + canv.saveState() + if self.bgColor: + canv.setFillColor(toColor(self.bgColor)) + canv.rect(x, y-h, w, h, fill=1, stroke=0) + canv.setFillColor(toColor(self.color)) + canv.setStrokeColor(None) + + cellWidth = self.cellWidth + cellHeight = self.cellHeight + yr = y - b - cellHeight + x += b + for row in self.matrix.split('\n'): + xr = x + for c in row: + if c=='x': + canv.rect(xr, yr, cellWidth, cellHeight, fill=1, stroke=0) + xr += cellWidth + yr -= cellHeight + canv.restoreState() + + +class DataMatrixWidget(Widget,_DMTXCheck): + codeName = "DataMatrix" + _attrMap = AttrMap( + BASE = Widget, + value = AttrMapValue(isString, desc='Datamatrix data'), + x = AttrMapValue(isNumber, desc='x-coord'), + y = AttrMapValue(isNumber, desc='y-coord'), + color = AttrMapValue(isColor, desc='foreground color'), + bgColor = AttrMapValue(isColorOrNone, desc='background color'), + encoding = AttrMapValue(isString, desc='encoding'), + size = AttrMapValue(isString, desc='size'), + cellSize = AttrMapValue(isString, desc='cellSize'), + anchor = AttrMapValue(isBoxAnchor, desc='anchor pooint for x,y'), + ) + + _defaults = dict( + x = ('0',_numConv), + y = ('0',_numConv), + color = ('black',toColor), + bgColor = (None,lambda _: toColor(_) if _ is not None else _), + encoding = ('Ascii',None), + size = ('SquareAuto',None), + cellSize = ('5x5',None), + anchor = ('sw', None), + ) + def __init__(self,value='Hello Cruel World!', **kwds): + self.pylibdmtx_check() + self.value = value + for k,(d,c) in self._defaults.items(): + v = kwds.pop(k,d) + if c: v = c(v) + setattr(self,k,v) + + def rect(self, x, y, w, h, fill=1, stroke=0): + self._gadd(Rect(x,y,w,h,strokeColor=None,fillColor=self._fillColor)) + + def saveState(self,*args,**kwds): + pass + + restoreState = setStrokeColor = saveState + + def setFillColor(self,c): + self._fillColor = c + + def draw(self): + m = DataMatrix(value=self.value,**{k: getattr(self,k) for k in self._defaults}) + m.canv = self + m.y += m.height + g = Group() + self._gadd = g.add + m.draw() + return g diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/eanbc.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/eanbc.py new file mode 100644 index 0000000000000000000000000000000000000000..a59a319b3d973ccf23da5ebfb21bb6546d664bd1 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/eanbc.py @@ -0,0 +1,574 @@ +__all__=( + 'Ean13BarcodeWidget','isEanString', + 'Ean8BarcodeWidget', 'UPCA', 'Ean5BarcodeWidget', 'ISBNBarcodeWidget', + ) +from reportlab.graphics.shapes import Group, String, Rect +from reportlab.lib import colors +from reportlab.pdfbase.pdfmetrics import stringWidth +from reportlab.lib.validators import isNumber, isColor, isString, Validator, isBoolean, NoneOr +from reportlab.lib.attrmap import * +from reportlab.graphics.charts.areas import PlotArea +from reportlab.lib.units import mm +from reportlab.lib.utils import asNative + +#work out a list of manufacturer codes.... +_eanNumberSystems = [ + ('00-13', 'USA & Canada'), + ('20-29', 'In-Store Functions'), + ('30-37', 'France'), + ('40-44', 'Germany'), + ('45', 'Japan (also 49)'), + ('46', 'Russian Federation'), + ('471', 'Taiwan'), + ('474', 'Estonia'), + ('475', 'Latvia'), + ('477', 'Lithuania'), + ('479', 'Sri Lanka'), + ('480', 'Philippines'), + ('482', 'Ukraine'), + ('484', 'Moldova'), + ('485', 'Armenia'), + ('486', 'Georgia'), + ('487', 'Kazakhstan'), + ('489', 'Hong Kong'), + ('49', 'Japan (JAN-13)'), + ('50', 'United Kingdom'), + ('520', 'Greece'), + ('528', 'Lebanon'), + ('529', 'Cyprus'), + ('531', 'Macedonia'), + ('535', 'Malta'), + ('539', 'Ireland'), + ('54', 'Belgium & Luxembourg'), + ('560', 'Portugal'), + ('569', 'Iceland'), + ('57', 'Denmark'), + ('590', 'Poland'), + ('594', 'Romania'), + ('599', 'Hungary'), + ('600-601', 'South Africa'), + ('609', 'Mauritius'), + ('611', 'Morocco'), + ('613', 'Algeria'), + ('619', 'Tunisia'), + ('622', 'Egypt'), + ('625', 'Jordan'), + ('626', 'Iran'), + ('64', 'Finland'), + ('690-692', 'China'), + ('70', 'Norway'), + ('729', 'Israel'), + ('73', 'Sweden'), + ('740', 'Guatemala'), + ('741', 'El Salvador'), + ('742', 'Honduras'), + ('743', 'Nicaragua'), + ('744', 'Costa Rica'), + ('746', 'Dominican Republic'), + ('750', 'Mexico'), + ('759', 'Venezuela'), + ('76', 'Switzerland'), + ('770', 'Colombia'), + ('773', 'Uruguay'), + ('775', 'Peru'), + ('777', 'Bolivia'), + ('779', 'Argentina'), + ('780', 'Chile'), + ('784', 'Paraguay'), + ('785', 'Peru'), + ('786', 'Ecuador'), + ('789', 'Brazil'), + ('80-83', 'Italy'), + ('84', 'Spain'), + ('850', 'Cuba'), + ('858', 'Slovakia'), + ('859', 'Czech Republic'), + ('860', 'Yugloslavia'), + ('869', 'Turkey'), + ('87', 'Netherlands'), + ('880', 'South Korea'), + ('885', 'Thailand'), + ('888', 'Singapore'), + ('890', 'India'), + ('893', 'Vietnam'), + ('899', 'Indonesia'), + ('90-91', 'Austria'), + ('93', 'Australia'), + ('94', 'New Zealand'), + ('955', 'Malaysia'), + ('977', 'International Standard Serial Number for Periodicals (ISSN)'), + ('978', 'International Standard Book Numbering (ISBN)'), + ('979', 'International Standard Music Number (ISMN)'), + ('980', 'Refund receipts'), + ('981-982', 'Common Currency Coupons'), + ('99', 'Coupons') + ] + +manufacturerCodes = {} +for (k, v) in _eanNumberSystems: + words = k.split('-') + if len(words)==2: + fromCode = int(words[0]) + toCode = int(words[1]) + for code in range(fromCode, toCode+1): + manufacturerCodes[code] = v + else: + manufacturerCodes[int(k)] = v + +def nDigits(n): + class _ndigits(Validator): + def test(self,x): + return type(x) is str and len(x)<=n and len([c for c in x if c in "0123456789"])==n + return _ndigits() + +class Ean13BarcodeWidget(PlotArea): + codeName = "EAN13" + _attrMap = AttrMap(BASE=PlotArea, + value = AttrMapValue(nDigits(12), desc='the number'), + fontName = AttrMapValue(isString, desc='fontName'), + fontSize = AttrMapValue(isNumber, desc='font size'), + x = AttrMapValue(isNumber, desc='x-coord'), + y = AttrMapValue(isNumber, desc='y-coord'), + barFillColor = AttrMapValue(isColor, desc='bar color'), + barHeight = AttrMapValue(isNumber, desc='Height of bars.'), + barWidth = AttrMapValue(isNumber, desc='Width of bars.'), + barStrokeWidth = AttrMapValue(isNumber, desc='Width of bar borders.'), + barStrokeColor = AttrMapValue(isColor, desc='Color of bar borders.'), + textColor = AttrMapValue(isColor, desc='human readable text color'), + humanReadable = AttrMapValue(isBoolean, desc='if human readable'), + quiet = AttrMapValue(isBoolean, desc='if quiet zone to be used'), + lquiet = AttrMapValue(isBoolean, desc='left quiet zone length'), + rquiet = AttrMapValue(isBoolean, desc='right quiet zone length'), + ) + _digits=12 + _start_right = 7 #for ean-13 left = [0:7] right=[7:13] + _nbars = 113 + barHeight = 25.93*mm #millimeters + barWidth = (37.29/_nbars)*mm + humanReadable = 1 + _0csw = 1 + _1csw = 3 + + #Left Hand Digits. + _left = ( ("0001101", "0011001", "0010011", "0111101", + "0100011", "0110001", "0101111", "0111011", + "0110111", "0001011", + ), #odd left hand digits + ("0100111", "0110011", "0011011", "0100001", + "0011101", "0111001", "0000101", "0010001", + "0001001", "0010111"), #even left hand digits + ) + + _right = ("1110010", "1100110", "1101100", "1000010", + "1011100", "1001110", "1010000", "1000100", + "1001000", "1110100") + + quiet = 1 + rquiet = lquiet = None + _tail = "101" + _sep = "01010" + + _lhconvert={ + "0": (0,0,0,0,0,0), + "1": (0,0,1,0,1,1), + "2": (0,0,1,1,0,1), + "3": (0,0,1,1,1,0), + "4": (0,1,0,0,1,1), + "5": (0,1,1,0,0,1), + "6": (0,1,1,1,0,0), + "7": (0,1,0,1,0,1), + "8": (0,1,0,1,1,0), + "9": (0,1,1,0,1,0) + } + fontSize = 8 #millimeters + fontName = 'Helvetica' + textColor = barFillColor = colors.black + barStrokeColor = None + barStrokeWidth = 0 + x = 0 + y = 0 + def __init__(self,value='123456789012',**kw): + value = str(value) if isinstance(value,int) else asNative(value) + self.value=max(self._digits-len(value),0)*'0'+value[:self._digits] + for k, v in kw.items(): + setattr(self, k, v) + + width = property(lambda self: self.barWidth*(self._nbars-18+self._calc_quiet(self.lquiet)+self._calc_quiet(self.rquiet))) + + def wrap(self,aW,aH): + return self.width,self.barHeight + + def _encode_left(self,s,a): + cp = self._lhconvert[s[0]] #convert the left hand numbers + _left = self._left + z = ord('0') + for i,c in enumerate(s[1:self._start_right]): + a(_left[cp[i]][ord(c)-z]) + + def _short_bar(self,i): + i += 9 - self._lquiet + return self.humanReadable and ((120: v += 1 + else: + v = 0 + return v + + def draw(self): + g = Group() + gAdd = g.add + barWidth = self.barWidth + width = self.width + barHeight = self.barHeight + x = self.x + y = self.y + gAdd(Rect(x,y,width,barHeight,fillColor=None,strokeColor=None,strokeWidth=0)) + s = self.value+self._checkdigit(self.value) + self._lquiet = lquiet = self._calc_quiet(self.lquiet) + rquiet = self._calc_quiet(self.rquiet) + b = [lquiet*'0',self._tail] #the signal string + a = b.append + self._encode_left(s,a) + a(self._sep) + + z = ord('0') + _right = self._right + for c in s[self._start_right:]: + a(_right[ord(c)-z]) + a(self._tail) + a(rquiet*'0') + + fontSize = self.fontSize + barFillColor = self.barFillColor + barStrokeWidth = self.barStrokeWidth + barStrokeColor = self.barStrokeColor + + fth = fontSize*1.2 + b = ''.join(b) + + lrect = None + for i,c in enumerate(b): + if c=="1": + dh = self._short_bar(i) and fth or 0 + yh = y+dh + if lrect and lrect.y==yh: + lrect.width += barWidth + else: + lrect = Rect(x,yh,barWidth,barHeight-dh,fillColor=barFillColor,strokeWidth=barStrokeWidth,strokeColor=barStrokeColor) + gAdd(lrect) + else: + lrect = None + x += barWidth + + if self.humanReadable: self._add_human_readable(s,gAdd) + return g + + def _add_human_readable(self,s,gAdd): + barWidth = self.barWidth + fontSize = self.fontSize + textColor = self.textColor + fontName = self.fontName + fth = fontSize*1.2 + # draw the num below the line. + c = s[0] + w = stringWidth(c,fontName,fontSize) + x = self.x+barWidth*(self._lquiet-8) + y = self.y + 0.2*fth + + gAdd(String(x,y,c,fontName=fontName,fontSize=fontSize,fillColor=textColor)) + x = self.x + (33-9+self._lquiet)*barWidth + + c = s[1:7] + gAdd(String(x,y,c,fontName=fontName,fontSize=fontSize,fillColor=textColor,textAnchor='middle')) + + x += 47*barWidth + c = s[7:] + gAdd(String(x,y,c,fontName=fontName,fontSize=fontSize,fillColor=textColor,textAnchor='middle')) + + def _checkdigit(cls,num): + z = ord('0') + iSum = cls._0csw*sum([(ord(x)-z) for x in num[::2]]) \ + + cls._1csw*sum([(ord(x)-z) for x in num[1::2]]) + return chr(z+((10-(iSum%10))%10)) + _checkdigit=classmethod(_checkdigit) + +class Ean8BarcodeWidget(Ean13BarcodeWidget): + codeName = "EAN8" + _attrMap = AttrMap(BASE=Ean13BarcodeWidget, + value = AttrMapValue(nDigits(7), desc='the number'), + ) + _start_right = 4 #for ean-13 left = [0:7] right=[7:13] + _nbars = 85 + _digits=7 + _0csw = 3 + _1csw = 1 + + def _encode_left(self,s,a): + cp = self._lhconvert[s[0]] #convert the left hand numbers + _left = self._left[0] + z = ord('0') + for i,c in enumerate(s[0:self._start_right]): + a(_left[ord(c)-z]) + + def _short_bar(self,i): + i += 9 - self._lquiet + return self.humanReadable and ((12 255: + self.valid = 0 + break + else: + self.validated = self.value + + def _encode_c40_char(self, char): + o = ord(char) + encoded = [] + + if o == 32 or (o >= 48 and o <= 57) or (o >= 65 and o <= 90): + # Stay in set 0 + if o == 32: + encoded.append(o - 29) + elif o >= 48 and o <= 57: + encoded.append(o - 44) + else: + encoded.append(o - 51) + elif o >= 0 and o <= 31: + encoded.append(0) # Shift to set 1 + encoded.append(o) + elif (o >= 33 and o <= 64) or (o >= 91 and o <= 95): + encoded.append(1) # Shift to set 2 + if o >= 33 and o <= 64: + encoded.append(o - 33) + else: + encoded.append(o - 69) + elif o >= 96 and o <= 127: + encoded.append(2) # Shift to set 3 + encoded.append(o - 96) + elif o >= 128 and o <= 255: + # Extended ASCII + encoded.append(1) # Shift to set 2 + encoded.append(30) # Upper shift / hibit + encoded += self._encode_c40_char(chr(o - 128)) + else: + raise Exception('Cannot encode %s (%s)' % (char, o)) + + return encoded + + def _encode_c40(self, value): + encoded = [] + + for c in value: + encoded += self._encode_c40_char(c) + + while len(encoded) % 3: + encoded.append(0) # Fake padding that makes chunking in the next step easier + + codewords = [] + codewords.append(230) # Switch to C40 encoding + + for i in range(0, len(encoded), 3): + chunk = encoded[i:i+3] + total = chunk[0] * 1600 + chunk[1] * 40 + chunk[2] + 1 + codewords.append(total // 256) + codewords.append(total % 256) + + codewords.append(254) # End of data + + if len(codewords) > self.cw_data: + raise Exception('Too much data to fit into a data matrix of this size') + + if len(codewords) < self.cw_data: + # Real padding + codewords.append(129) # Start padding + while len(codewords) < self.cw_data: + r = ((149 * (len(codewords) + 1)) % 253) + 1 + codewords.append((129 + r) % 254) + + return codewords + + def _gfsum(self, int1, int2): + return int1 ^ int2 + + def _gfproduct(self, int1, int2): + if int1 == 0 or int2 == 0: + return 0 + else: + return ALOGVAL[(LOGVAL[int1] + LOGVAL[int2]) % 255] + + def _get_reed_solomon_code(self, data, num_code_words): + """ + This method is basically verbatim from "huBarcode" which is BSD licensed + https://github.com/hudora/huBarcode/blob/master/hubarcode/datamatrix/reedsolomon.py + """ + cw_factors = FACTORS[num_code_words] + code_words = [0] * num_code_words + + for data_word in data: + tmp = self._gfsum(data_word, code_words[-1]) + for j in range(num_code_words - 1, -1, -1): + code_words[j] = self._gfproduct(tmp, cw_factors[j]) + if j > 0: + code_words[j] = self._gfsum(code_words[j - 1], code_words[j]) + + code_words.reverse() + return code_words + + def _get_next_bits(self, data): + value = data.pop(0) + bits = [] + for i in range(0, 8): + bits.append(value >> i & 1) + bits.reverse() + return bits + + def _place_bit(self, row, col, bit): + if row < 0: + row += self.row_usable_modules + col += (4 - ((self.row_usable_modules + 4) % 8)) + + if col < 0: + col += self.col_usable_modules + row += (4 - ((self.col_usable_modules + 4) % 8)) + + self._matrix[row][col] = bit + + def _place_bit_corner_1(self, data): + bits = self._get_next_bits(data) + self._place_bit(self.row_usable_modules - 1, 0, bits[0]) + self._place_bit(self.row_usable_modules - 1, 1, bits[1]) + self._place_bit(self.row_usable_modules - 1, 2, bits[2]) + self._place_bit(0, self.col_usable_modules - 2, bits[3]) + self._place_bit(0, self.col_usable_modules - 1, bits[4]) + self._place_bit(1, self.col_usable_modules - 1, bits[5]) + self._place_bit(2, self.col_usable_modules - 1, bits[6]) + self._place_bit(3, self.col_usable_modules - 1, bits[7]) + + def _place_bit_corner_2(self, data): + bits = self._get_next_bits(data) + self._place_bit(self.row_usable_modules - 3, 0, bits[0]) + self._place_bit(self.row_usable_modules - 2, 0, bits[1]) + self._place_bit(self.row_usable_modules - 1, 0, bits[2]) + self._place_bit(0, self.col_usable_modules - 4, bits[3]) + self._place_bit(0, self.col_usable_modules - 3, bits[4]) + self._place_bit(0, self.col_usable_modules - 2, bits[5]) + self._place_bit(0, self.col_usable_modules - 1, bits[6]) + self._place_bit(1, self.col_usable_modules - 1, bits[7]) + + def _place_bit_corner_3(self, data): + bits = self._get_next_bits(data) + self._place_bit(self.row_usable_modules - 3, 0, bits[0]) + self._place_bit(self.row_usable_modules - 2, 0, bits[1]) + self._place_bit(self.row_usable_modules - 1, 0, bits[2]) + self._place_bit(0, self.col_usable_modules - 2, bits[3]) + self._place_bit(0, self.col_usable_modules - 1, bits[4]) + self._place_bit(1, self.col_usable_modules - 1, bits[5]) + self._place_bit(2, self.col_usable_modules - 1, bits[6]) + self._place_bit(3, self.col_usable_modules - 1, bits[7]) + + def _place_bit_corner_4(self, data): + bits = self._get_next_bits(data) + self._place_bit(self.row_usable_modules - 1, 0, bits[0]) + self._place_bit(self.row_usable_modules - 1, self.col_usable_modules - 1, bits[1]) + self._place_bit(0, self.col_usable_modules - 3, bits[2]) + self._place_bit(0, self.col_usable_modules - 2, bits[3]) + self._place_bit(0, self.col_usable_modules - 1, bits[4]) + self._place_bit(1, self.col_usable_modules - 3, bits[5]) + self._place_bit(1, self.col_usable_modules - 2, bits[6]) + self._place_bit(1, self.col_usable_modules - 1, bits[7]) + + def _place_bit_standard(self, data, row, col): + bits = self._get_next_bits(data) + self._place_bit(row - 2, col - 2, bits[0]) + self._place_bit(row - 2, col - 1, bits[1]) + self._place_bit(row - 1, col - 2, bits[2]) + self._place_bit(row - 1, col - 1, bits[3]) + self._place_bit(row - 1, col, bits[4]) + self._place_bit(row, col - 2, bits[5]) + self._place_bit(row, col - 1, bits[6]) + self._place_bit(row, col, bits[7]) + + def _create_matrix(self, data): + """ + This method is heavily influenced by "huBarcode" which is BSD licensed + https://github.com/hudora/huBarcode/blob/master/hubarcode/datamatrix/placement.py + """ + rows = self.row_usable_modules + cols = self.col_usable_modules + + self._matrix = self._create_empty_matrix(rows, cols) + + row = 4 + col = 0 + + while True: + if row == rows and col == 0: + self._place_bit_corner_1(data) + elif row == (rows - 2) and col == 0 and (cols % 4): + self._place_bit_corner_2(data) + elif row == (rows - 2) and col == 0 and (cols % 8 == 4): + self._place_bit_corner_3(data) + elif row == (rows + 4) and col == 2 and (cols % 8 == 0): + self._place_bit_corner_4(data) + + while True: + if row < rows and col >= 0 and self._matrix[row][col] is None: + self._place_bit_standard(data, row, col) + + row -= 2 + col += 2 + + if row < 0 or col >= cols: + break + + row += 1 + col += 3 + + while True: + if row >= 0 and col < cols and self._matrix[row][col] is None: + self._place_bit_standard(data, row, col) + + row += 2 + col -= 2 + + if row >= rows or col < 0: + break + + row += 3 + col += 1 + + if row >= rows and col >= cols: + break + + for row in self._matrix: + for i in range(0, cols): + if row[i] is None: + row[i] = 0 + + return self._matrix + + def _create_data_regions(self, matrix): + regions = [] + col_offset = 0 + row_offset = 0 + + rows = int(self.row_usable_modules / self.row_regions) + cols = int(self.col_usable_modules / self.col_regions) + + while col_offset < self.row_regions: + while row_offset < self.col_regions: + r_offset = col_offset * rows + c_offset = row_offset * cols + region = matrix[r_offset:rows+r_offset] + for i in range(0, len(region)): + region[i] = region[i][c_offset:cols+c_offset] + regions.append(region) + row_offset += 1 + row_offset = 0 + col_offset += 1 + + return regions + + def _create_empty_matrix(self, row, col): + matrix = [] + for i in range(0, row): + matrix.append([None] * col) + return matrix + + def _wrap_data_regions_with_finders(self, regions): + wrapped = [] + + for region in regions: + matrix = self._create_empty_matrix( + int(self.col_modules / self.col_regions), + int(self.row_modules / self.row_regions) + ) + + for i, rows in enumerate(region): + for j, data in enumerate(rows): + matrix[i+1][j+1] = data + + for i, row in enumerate(matrix): + if i == 0: + for j, col in enumerate(row): + row[j] = (j + 1) % 2 + elif i + 1 == len(matrix): + for j, col in enumerate(row): + row[j] = 1 + else: + row[0] = 1 + row[-1] = i % 2 + + wrapped.append(matrix) + + return wrapped + + def _merge_data_regions(self, regions): + merged = [] + + for i in range(0, len(regions), self.row_regions): + chunk = regions[i:i+self.row_regions] + j = 0 + while j < len(chunk[0]): + merged_row = [] + for row in chunk: + merged_row += row[j] + merged.append(merged_row) + j += 1 + + return merged + + def encode(self): + if hasattr(self, 'encoded'): + return self.encoded + + encoded = self._encode_c40(self.validated) + encoded += self._get_reed_solomon_code(encoded, self.cw_ecc) + + matrix = self._create_matrix(encoded) + data_regions = self._create_data_regions(matrix) + wrapped = self._wrap_data_regions_with_finders(data_regions) + self.encoded = self._merge_data_regions(wrapped) + + self.encoded.reverse() # Helpful since PDFs start at bottom left corner + + return self.encoded + + def computeSize(self, *args): + self._height = self.row_modules * self.barWidth + self._width = self.col_modules * self.barWidth + + def draw(self): + for y, row in enumerate(self.encoded): + for x, data in enumerate(row): + if data: + self.rect( + self.x + x * self.barWidth, + self.y + y * self.barWidth, + self.barWidth, + self.barWidth + ) diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/fourstate.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/fourstate.py new file mode 100644 index 0000000000000000000000000000000000000000..539d0a5ca09f0c02142a2965ff231a5a8a6b286f --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/fourstate.py @@ -0,0 +1,77 @@ +# +# Copyright (c) 2000 Tyler C. Sarna +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. All advertising materials mentioning features or use of this software +# must display the following acknowledgement: +# This product includes software developed by Tyler C. Sarna. +# 4. Neither the name of the author nor the names of contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS +# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# + +# . 3 T Tracker +# , 2 D Descender +# ' 1 A Ascender +# | 0 H Ascender/Descender + +_rm_patterns = { + "0" : "--||", "1" : "-',|", "2" : "-'|,", "3" : "'-,|", + "4" : "'-|,", "5" : "'',,", "6" : "-,'|", "7" : "-|-|", + "8" : "-|',", "9" : "',-|", "A" : "',',", "B" : "'|-,", + "C" : "-,|'", "D" : "-|,'", "E" : "-||-", "F" : "',,'", + "G" : "',|-", "H" : "'|,-", "I" : ",-'|", "J" : ",'-|", + "K" : ",'',", "L" : "|--|", "M" : "|-',", "N" : "|'-,", + "O" : ",-|'", "P" : ",','", "Q" : ",'|-", "R" : "|-,'", + "S" : "|-|-", "T" : "|',-", "U" : ",,''", "V" : ",|-'", + "W" : ",|'-", "X" : "|,-'", "Y" : "|,'-", "Z" : "||--", + + # start, stop + "(" : "'-,'", ")" : "'|,|" +} + +_ozN_patterns = { + "0" : "||", "1" : "|'", "2" : "|,", "3" : "'|", "4" : "''", + "5" : "',", "6" : ",|", "7" : ",'", "8" : ",,", "9" : ".|" +} + +_ozC_patterns = { + "A" : "|||", "B" : "||'", "C" : "||,", "D" : "|'|", + "E" : "|''", "F" : "|',", "G" : "|,|", "H" : "|,'", + "I" : "|,,", "J" : "'||", "K" : "'|'", "L" : "'|,", + "M" : "''|", "N" : "'''", "O" : "'',", "P" : "',|", + "Q" : "','", "R" : "',,", "S" : ",||", "T" : ",|'", + "U" : ",|,", "V" : ",'|", "W" : ",''", "X" : ",',", + "Y" : ",,|", "Z" : ",,'", "a" : "|,.", "b" : "|.|", + "c" : "|.'", "d" : "|.,", "e" : "|..", "f" : "'|.", + "g" : "''.", "h" : "',.", "i" : "'.|", "j" : "'.'", + "k" : "'.,", "l" : "'..", "m" : ",|.", "n" : ",'.", + "o" : ",,.", "p" : ",.|", "q" : ",.'", "r" : ",.,", + "s" : ",..", "t" : ".|.", "u" : ".'.", "v" : ".,.", + "w" : "..|", "x" : "..'", "y" : "..,", "z" : "...", + "0" : ",,,", "1" : ".||", "2" : ".|'", "3" : ".|,", + "4" : ".'|", "5" : ".''", "6" : ".',", "7" : ".,|", + "8" : ".,'", "9" : ".,,", " " : "||.", "#" : "|'.", +} + +#http://www.auspost.com.au/futurepost/ diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/lto.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/lto.py new file mode 100644 index 0000000000000000000000000000000000000000..2b4756f918479d5e41c396abc1f88f2e0de04cf0 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/lto.py @@ -0,0 +1,195 @@ +# (c) 2008 Jerome Alet - +# Licensing terms : ReportLab's license. + +from reportlab.graphics.barcode.code39 import Standard39 +from reportlab.lib import colors +from reportlab.lib.units import cm +from string import ascii_uppercase, digits as string_digits + +class BaseLTOLabel(Standard39) : + """ + Base class for LTO labels. + + Specification taken from "IBM LTO Ultrium Cartridge Label Specification, Revision 3" + available on May 14th 2008 from : + http://www-1.ibm.com/support/docview.wss?rs=543&context=STCVQ6R&q1=ssg1*&uid=ssg1S7000429&loc=en_US&cs=utf-8&lang=en+en + """ + LABELWIDTH = 7.9 * cm + LABELHEIGHT = 1.7 * cm + LABELROUND = 0.15 * cm + CODERATIO = 2.75 + CODENOMINALWIDTH = 7.4088 * cm + CODEBARHEIGHT = 1.11 * cm + CODEBARWIDTH = 0.0432 * cm + CODEGAP = CODEBARWIDTH + CODELQUIET = 10 * CODEBARWIDTH + CODERQUIET = 10 * CODEBARWIDTH + def __init__(self, prefix="", + number=None, + subtype="1", + border=None, + checksum=False, + availheight=None) : + """ + Initializes an LTO label. + + prefix : Up to six characters from [A-Z][0-9]. Defaults to "". + number : Label's number or None. Defaults to None. + subtype : LTO subtype string , e.g. "1" for LTO1. Defaults to "1". + border : None, or the width of the label's border. Defaults to None. + checksum : Boolean indicates if checksum char has to be printed. Defaults to False. + availheight : Available height on the label, or None for automatic. Defaults to None. + """ + self.height = max(availheight, self.CODEBARHEIGHT) + self.border = border + if (len(subtype) != 1) \ + or (subtype not in ascii_uppercase + string_digits) : + raise ValueError("Invalid subtype '%s'" % subtype) + if ((not number) and (len(prefix) > 6)) \ + or not prefix.isalnum() : + raise ValueError("Invalid prefix '%s'" % prefix) + label = "%sL%s" % ((prefix + str(number or 0).zfill(6 - len(prefix)))[:6], + subtype) + if len(label) != 8 : + raise ValueError("Invalid set of parameters (%s, %s, %s)" \ + % (prefix, number, subtype)) + self.label = label + Standard39.__init__(self, + label, + ratio=self.CODERATIO, + barHeight=self.height, + barWidth=self.CODEBARWIDTH, + gap=self.CODEGAP, + lquiet=self.CODELQUIET, + rquiet=self.CODERQUIET, + quiet=True, + checksum=checksum) + + def drawOn(self, canvas, x, y) : + """Draws the LTO label onto the canvas.""" + canvas.saveState() + canvas.translate(x, y) + if self.border : + canvas.setLineWidth(self.border) + canvas.roundRect(0, 0, + self.LABELWIDTH, + self.LABELHEIGHT, + self.LABELROUND) + Standard39.drawOn(self, + canvas, + (self.LABELWIDTH-self.CODENOMINALWIDTH)/2.0, + self.LABELHEIGHT-self.height) + canvas.restoreState() + +class VerticalLTOLabel(BaseLTOLabel) : + """ + A class for LTO labels with rectangular blocks around the tape identifier. + """ + LABELFONT = ("Helvetica-Bold", 14) + BLOCKWIDTH = 1*cm + BLOCKHEIGHT = 0.45*cm + LINEWIDTH = 0.0125 + NBBLOCKS = 7 + COLORSCHEME = ("red", + "yellow", + "lightgreen", + "lightblue", + "grey", + "orangered", + "pink", + "darkgreen", + "orange", + "purple") + + def __init__(self, *args, **kwargs) : + """ + Initializes the label. + + colored : boolean to determine if blocks have to be colorized. + """ + if "colored" in kwargs: + self.colored = kwargs["colored"] + del kwargs["colored"] + else : + self.colored = False + kwargs["availheight"] = self.LABELHEIGHT-self.BLOCKHEIGHT + BaseLTOLabel.__init__(self, *args, **kwargs) + + def drawOn(self, canvas, x, y) : + """Draws some blocks around the identifier's characters.""" + BaseLTOLabel.drawOn(self, + canvas, + x, + y) + canvas.saveState() + canvas.setLineWidth(self.LINEWIDTH) + canvas.setStrokeColorRGB(0, 0, 0) + canvas.translate(x, y) + xblocks = (self.LABELWIDTH-(self.NBBLOCKS*self.BLOCKWIDTH))/2.0 + for i in range(self.NBBLOCKS) : + (font, size) = self.LABELFONT + newfont = self.LABELFONT + if i == (self.NBBLOCKS - 1) : + part = self.label[i:] + (font, size) = newfont + size /= 2.0 + newfont = (font, size) + else : + part = self.label[i] + canvas.saveState() + canvas.translate(xblocks+(i*self.BLOCKWIDTH), 0) + if self.colored and part.isdigit() : + canvas.setFillColorRGB(*getattr(colors, + self.COLORSCHEME[int(part)], + colors.Color(1, 1, 1)).rgb()) + else: + canvas.setFillColorRGB(1, 1, 1) + canvas.rect(0, 0, self.BLOCKWIDTH, self.BLOCKHEIGHT, fill=True) + canvas.translate((self.BLOCKWIDTH+canvas.stringWidth(part, *newfont))/2.0, + (self.BLOCKHEIGHT/2.0)) + canvas.rotate(90.0) + canvas.setFont(*newfont) + canvas.setFillColorRGB(0, 0, 0) + canvas.drawCentredString(0, 0, part) + canvas.restoreState() + canvas.restoreState() + +def test() : + """Test this.""" + from reportlab.pdfgen.canvas import Canvas + from reportlab.lib import pagesizes + + canvas = Canvas("labels.pdf", pagesize=pagesizes.A4) + canvas.setFont("Helvetica", 30) + (width, height) = pagesizes.A4 + canvas.drawCentredString(width/2.0, height-4*cm, "Sample LTO labels") + xpos = xorig = 2 * cm + ypos = yorig = 2 * cm + colwidth = 10 * cm + lineheight = 3.9 * cm + count = 1234 + BaseLTOLabel("RL", count, "3").drawOn(canvas, xpos, ypos) + ypos += lineheight + count += 1 + BaseLTOLabel("RL", count, "3", + border=0.0125).drawOn(canvas, xpos, ypos) + ypos += lineheight + count += 1 + VerticalLTOLabel("RL", count, "3").drawOn(canvas, xpos, ypos) + ypos += lineheight + count += 1 + VerticalLTOLabel("RL", count, "3", + border=0.0125).drawOn(canvas, xpos, ypos) + ypos += lineheight + count += 1 + VerticalLTOLabel("RL", count, "3", + colored=True).drawOn(canvas, xpos, ypos) + ypos += lineheight + count += 1 + VerticalLTOLabel("RL", count, "3", + border=0.0125, colored=True).drawOn(canvas, xpos, ypos) + canvas.showPage() + canvas.save() + +if __name__ == "__main__" : + test() diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/qr.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/qr.py new file mode 100644 index 0000000000000000000000000000000000000000..5196e1bb78a5ff0a96d9eeb44a7acf41b4769652 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/qr.py @@ -0,0 +1,197 @@ +# +# ReportLab QRCode widget +# +# Ported from the Javascript library QRCode for Javascript by Sam Curren +# +# URL: http://www.d-project.com/ +# http://d-project.googlecode.com/svn/trunk/misc/qrcode/js/qrcode.js +# qrcode.js is copyright (c) 2009 Kazuhiko Arase +# +# Original ReportLab module by German M. Bravo +# +# modified and improved by Anders Hammarquist +# and used with permission under the ReportLab License +# +# The word "QR Code" is registered trademark of +# DENSO WAVE INCORPORATED +# http://www.denso-wave.com/qrcode/faqpatent-e.html + +__all__ = ('QrCodeWidget') + +import itertools + +from reportlab.platypus.flowables import Flowable +from reportlab.graphics.shapes import Group, Rect +from reportlab.lib import colors +from reportlab.lib.validators import isNumber, isNumberOrNone, isColor, Validator +from reportlab.lib.attrmap import AttrMap, AttrMapValue +from reportlab.graphics.widgetbase import Widget +from reportlab.lib.units import mm +from reportlab.lib.utils import asUnicodeEx, isUnicode +from reportlab.graphics.barcode import qrencoder + +class isLevel(Validator): + def test(self, x): + return x in ['L', 'M', 'Q', 'H'] +isLevel = isLevel() + +class isUnicodeOrQRList(Validator): + def _test(self, x): + if isUnicode(x): + return True + if all(isinstance(v, qrencoder.QR) for v in x): + return True + return False + + def test(self, x): + return self._test(x) or self.normalizeTest(x) + + def normalize(self, x): + if self._test(x): + return x + try: + return asUnicodeEx(x) + except UnicodeError: + raise ValueError("Can't convert to unicode: %r" % x) +isUnicodeOrQRList = isUnicodeOrQRList() + +class SRect(Rect): + def __init__(self, x, y, width, height, fillColor=colors.black): + Rect.__init__(self, x, y, width, height, fillColor=fillColor, + strokeColor=None, strokeWidth=0) + +class QrCodeWidget(Widget): + codeName = "QR" + _attrMap = AttrMap( + BASE = Widget, + value = AttrMapValue(isUnicodeOrQRList, desc='QRCode data'), + x = AttrMapValue(isNumber, desc='x-coord'), + y = AttrMapValue(isNumber, desc='y-coord'), + barFillColor = AttrMapValue(isColor, desc='bar color'), + barWidth = AttrMapValue(isNumber, desc='Width of bars.'), # maybe should be named just width? + barHeight = AttrMapValue(isNumber, desc='Height of bars.'), # maybe should be named just height? + barBorder = AttrMapValue(isNumber, desc='Width of QR border.'), # maybe should be named qrBorder? + barLevel = AttrMapValue(isLevel, desc='QR Code level.'), # maybe should be named qrLevel + qrVersion = AttrMapValue(isNumberOrNone, desc='QR Code version. None for auto'), + # Below are ignored, they make no sense + barStrokeWidth = AttrMapValue(isNumber, desc='Width of bar borders.'), + barStrokeColor = AttrMapValue(isColor, desc='Color of bar borders.'), + ) + x = 0 + y = 0 + barFillColor = colors.black + barStrokeColor = None + barStrokeWidth = 0 + barHeight = 32*mm + barWidth = 32*mm + barBorder = 4 + barLevel = 'L' + qrVersion = None + value = None + + def __init__(self, value='Hello World', **kw): + self.value = isUnicodeOrQRList.normalize(value) + for k, v in kw.items(): + setattr(self, k, v) + + ec_level = getattr(qrencoder.QRErrorCorrectLevel, self.barLevel) + + self.__dict__['qr'] = qrencoder.QRCode(self.qrVersion, ec_level) + + if isUnicode(self.value): + self.addData(self.value) + elif self.value: + for v in self.value: + self.addData(v) + + def addData(self, value): + self.qr.addData(value) + + def draw(self): + self.qr.make() + + g = Group() + + color = self.barFillColor + border = self.barBorder + width = self.barWidth + height = self.barHeight + x = self.x + y = self.y + + g.add(SRect(x, y, width, height, fillColor=None)) + + moduleCount = self.qr.getModuleCount() + minwh = float(min(width, height)) + boxsize = minwh / (moduleCount + border * 2.0) + offsetX = x + (width - minwh) / 2.0 + offsetY = y + (minwh - height) / 2.0 + + for r, row in enumerate(self.qr.modules): + row = map(bool, row) + c = 0 + for t, tt in itertools.groupby(row): + isDark = t + count = len(list(tt)) + if isDark: + x = (c + border) * boxsize + y = (r + border + 1) * boxsize + s = SRect(offsetX + x, offsetY + height - y, count * boxsize, boxsize, + fillColor=color) + g.add(s) + c += count + + return g + + +# Flowable version + +class QrCode(Flowable): + height = 32*mm + width = 32*mm + qrBorder = 4 + qrLevel = 'L' + qrVersion = None + value = None + + def __init__(self, value=None, **kw): + self.value = isUnicodeOrQRList.normalize(value) + + for k, v in kw.items(): + setattr(self, k, v) + + ec_level = getattr(qrencoder.QRErrorCorrectLevel, self.qrLevel) + + self.qr = qrencoder.QRCode(self.qrVersion, ec_level) + + if isUnicode(self.value): + self.addData(self.value) + elif self.value: + for v in self.value: + self.addData(v) + + def addData(self, value): + self.qr.addData(value) + + def draw(self): + self.qr.make() + + moduleCount = self.qr.getModuleCount() + border = self.qrBorder + xsize = self.width / (moduleCount + border * 2.0) + ysize = self.height / (moduleCount + border * 2.0) + + for r, row in enumerate(self.qr.modules): + row = map(bool, row) + c = 0 + for t, tt in itertools.groupby(row): + isDark = t + count = len(list(tt)) + if isDark: + x = (c + border) * xsize + y = self.height - (r + border + 1) * ysize + self.rect(x, y, count * xsize, ysize * 1.05) + c += count + + def rect(self, x, y, w, h): + self.canv.rect(x, y, w, h, stroke=0, fill=1) diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/qrencoder.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/qrencoder.py new file mode 100644 index 0000000000000000000000000000000000000000..a9cfeb8cadb77b4f9f0e663c4959742abed825b5 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/qrencoder.py @@ -0,0 +1,1130 @@ +# QRCode for Python +# +# Support for Kanji, Hanzi, ECI, FNC1 and Structurded append, +# and optimizations by Anders Hammarquist +# +# Copyright (c) 2014 Open End AB http://www.openend.se/ +# +# Ported from the Javascript library by Sam Curren +# +# QRCode for Javascript +# http://d-project.googlecode.com/svn/trunk/misc/qrcode/js/qrcode.js +# +# Copyright (c) 2009 Kazuhiko Arase +# +# URL: http://www.d-project.com/ +# +# Licensed under the MIT license: +# http://www.opensource.org/licenses/mit-license.php +# +# The word "QR Code" is registered trademark of +# DENSO WAVE INCORPORATED +# http://www.denso-wave.com/qrcode/faqpatent-e.html + +import re +import itertools +try: + from itertools import zip_longest +except: + from itertools import izip_longest as zip_longest + +try: + unicode +except NameError: + # No unicode in Python 3 + unicode = str + +class QR: + valid = None + bits = None + group = 0 + + def __init__(self, data): + if self.valid and not self.valid(data): + raise ValueError + self.data = data + + def __len__(self): + return len(self.data) + + @property + def bitlength(self): + if self.bits is None: + return 0 + q, r = divmod(len(self), len(self.bits)) + return q * sum(self.bits) + sum(self.bits[:r]) + + def getLengthBits(self, ver): + if 0 < ver < 10: + return self.lengthbits[0] + elif ver < 27: + return self.lengthbits[1] + elif ver < 41: + return self.lengthbits[2] + raise ValueError("Unknown version: " + ver) + + def getLength(self): + return len(self.data) + + def __repr__(self): + return repr(self.data) + + def write_header(self, buffer, version): + buffer.put(self.mode, 4) + lenbits = self.getLengthBits(version) + if lenbits: + buffer.put(len(self.data), lenbits ) + + def write(self, buffer, version): + self.write_header(buffer, version) + for g in zip_longest(*[iter(self.data)] * self.group): + bits = 0 + n = 0 + for i in range(self.group): + if g[i] is not None: + n *= len(self.chars) + n += self.chars.index(g[i]) + bits += self.bits[i] + buffer.put(n, bits) + +class QRNumber(QR): + valid = re.compile(u'[0-9]*$').match + chars = u'0123456789' + bits = (4,3,3) + group = 3 + mode = 0x1 + lengthbits = (10, 12, 14) + +class QRAlphaNum(QR): + valid = re.compile(u'[-0-9A-Z $%*+./:]*$').match + chars = u'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:' + bits = (6,5) + group = 2 + mode = 0x2 + lengthbits = (9, 11, 13) + +class QR8bitByte(QR): + bits = (8,) + group = 1 + mode = 0x4 + lengthbits = (8, 16, 16) + + def __init__(self, data): + if isinstance(data, unicode): + self.data = data.encode('utf-8') # XXX This really needs an ECI too + else: + self.data = data # It'd better be byte data + + def write(self, buffer, version): + self.write_header(buffer, version) + for c in self.data: + if isinstance(c, str): + c = ord(c) + buffer.put(c, 8) + +class QRKanji(QR): + bits = (13,) + group = 1 + mode = 0x8 + lengthbits = (8, 10, 12) + + def __init__(self, data): + try: + self.data = self.unicode_to_qrkanji(data) + except UnicodeEncodeError: + raise ValueError('Not valid kanji') + + def unicode_to_qrkanji(self, data): + codes = [] + for i,c in enumerate(data): + try: + c = c.encode('shift-jis') + try: + c,d = map(ord, c) + except TypeError: + # Python 3 + c,d = c + except UnicodeEncodeError as e: + raise UnicodeEncodeError('qrkanji', data, i, i+1, e.args[4]) + except ValueError: + raise UnicodeEncodeError('qrkanji', data, i, i+1, + 'illegal multibyte sequence') + c = c << 8 | d + if 0x8140 <= c <=0x9ffc: + c -= 0x8140 + c = (((c & 0xff00) >> 8) * 0xc0) + (c & 0xff) + elif 0xe040 <= c <= 0xebbf: + c -= 0xc140 + c = (((c & 0xff00) >> 8) * 0xc0) + (c & 0xff) + else: + raise UnicodeEncodeError('qrkanji', data, i, i+1, + 'illegal multibyte sequence') + codes.append(c) + return codes + + def write(self, buffer, version): + self.write_header(buffer, version) + for d in self.data: + buffer.put(d, 13) + +class QRHanzi(QR): + bits = (13,) + group = 1 + mode = 0xD + lengthbits = (8, 10, 12) + + def __init__(self, data): + try: + self.data = self.unicode_to_qrhanzi(data) + except UnicodeEncodeError: + raise ValueError('Not valid hanzi') + + def unicode_to_qrhanzi(self, data): + codes = [] + for i,c in enumerate(data): + try: + c = c.encode('gb2312') + try: + c,d = map(ord, c) + except TypeError: + # Python 3 + c,d = c + except UnicodeEncodeError as e: + raise UnicodeEncodeError('qrhanzi', data, i, i+1, e.args[4]) + except ValueError: + raise UnicodeEncodeError('qrhanzi', data, i, i+1, + 'illegal multibyte sequence') + c = c << 8 | d + if 0xa1a1 <= c <=0xaafe: + c -= 0xa1a1 + c = (((c & 0xff00) >> 8) * 0x60) + (c & 0xff) + elif 0xb0a1 <= c <= 0xfafe: + c -= 0xa6a1 + c = (((c & 0xff00) >> 8) * 0x60) + (c & 0xff) + else: + raise UnicodeEncodeError('qrhanzi', data, i, i+1, + 'illegal multibyte sequence') + codes.append(c) + return codes + + def write_header(self, buffer, version): + buffer.put(self.mode, 4) + buffer.put(1, 4) # Subset 1: GB2312 encoding + lenbits = self.getLengthBits(version) + if lenbits: + buffer.put(len(self.data), lenbits ) + + def write(self, buffer, version): + self.write_header(buffer, version) + for d in self.data: + buffer.put(d, 13) + + +# Special modes +class QRECI(QR): + mode = 0x7 + lengthbits = (0, 0, 0) + + def __init__(self, data): + if not 0 < data < 999999: + # Spec says 999999, format supports up to 0x1fffff = 2097151 + raise ValueError("ECI out of range") + self.data = data + + def write(self, buffer, version): + self.write_header(buffer, version) + if self.data <= 0x7f: + buffer.put(self.data, 8) + elif self.data <= 0x3fff: + buffer.put(self.data | 0x8000, 16) + elif self.data <= 0x1fffff: + buffer.put(self.data | 0xC00000, 24) + +class QRStructAppend(QR): + mode = 0x3 + lengthbits = (0, 0, 0) + + def __init__(self, part, total, parity): + if not 0 < part <= 16: + raise ValueError("part out of range [1,16]") + if not 0 < total <= 16: + raise ValueError("total out of range [1,16]") + self.part = part + self.total = total + self.parity = parity + + def write(self, buffer, version): + self.write_header(buffer, version) + buffer.put(self.part, 4) + buffer.put(self.total, 4) + buffer.put(self.parity, 8) + +class QRFNC1First(QR): + mode = 0x5 + lengthbits = (0, 0, 0) + + def __init__(self): + pass + + def write(self, buffer, version): + self.write_header(buffer, version) + + +class QRFNC1Second(QR): + valid = re.compile('^([A-Za-z]|[0-9][0-9])$').match + mode = 0x9 + lengthbits = (0, 0, 0) + + def write(self, buffer, version): + self.write_header(buffer, version) + d = self.data + if len(d) == 1: + d = ord(d) + 100 + else: + d = int(d) + buffer.put(d, 8) + +class QRCode: + def __init__(self, version, errorCorrectLevel): + self.version = version + self.errorCorrectLevel = errorCorrectLevel + self.modules = None + self.moduleCount = 0 + self.dataCache = None + self.dataList = [] + + def addData(self, data): + if isinstance(data, QR): + newData = data + else: + for conv in (QRNumber, QRAlphaNum, QRKanji, QR8bitByte): + try: + newData = conv(data) + break + except ValueError: + pass + else: + raise ValueError + + self.dataList.append(newData) + self.dataCache = None + + def isDark(self, row, col): + return self.modules[row][col] + + def getModuleCount(self): + return self.moduleCount + + def calculate_version(self): + # Calculate version for data to fit the QR Code capacity + for version in range(1, 40): + rsBlocks = QRRSBlock.getRSBlocks(version, self.errorCorrectLevel) + totalDataCount = sum(block.dataCount for block in rsBlocks) + length = 0 + for data in self.dataList: + length += 4 + length += data.getLengthBits(version) + length += data.bitlength + if length <= totalDataCount * 8: + break + return version + + def make(self): + if self.version is None: + self.version = self.calculate_version() + self.makeImpl(False, self.getBestMaskPattern()) + + def makeImpl(self, test, maskPattern): + self.moduleCount = self.version * 4 + 17 + self.modules = [ [False] * self.moduleCount + for x in range(self.moduleCount) ] + self.setupPositionProbePattern(0, 0) + self.setupPositionProbePattern(self.moduleCount - 7, 0) + self.setupPositionProbePattern(0, self.moduleCount - 7) + self.setupPositionAdjustPattern() + self.setupTimingPattern() + self.setupTypeInfo(test, maskPattern) + if (self.version >= 7): + self.setupTypeNumber(test) + if (self.dataCache == None): + self.dataCache = QRCode.createData(self.version, + self.errorCorrectLevel, + self.dataList) + self.mapData(self.dataCache, maskPattern) + + _positionProbePattern = [ + [True, True, True, True, True, True, True], + [True, False, False, False, False, False, True], + [True, False, True, True, True, False, True], + [True, False, True, True, True, False, True], + [True, False, True, True, True, False, True], + [True, False, False, False, False, False, True], + [True, True, True, True, True, True, True], + ] + + def setupPositionProbePattern(self, row, col): + if row == 0: + self.modules[row+7][col:col+7] = [False] * 7 + if col == 0: + self.modules[row+7][col+7] = False + else: + self.modules[row+7][col-1] = False + else: + # col == 0 + self.modules[row-1][col:col+8] = [False] * 8 + + for r, data in enumerate(self._positionProbePattern): + self.modules[row+r][col:col+7] = data + if col == 0: + self.modules[row+r][col+7] = False + else: + self.modules[row+r][col-1] = False + + def getBestMaskPattern(self): + minLostPoint = 0 + pattern = 0 + for i in range(8): + self.makeImpl(True, i); + lostPoint = QRUtil.getLostPoint(self); + if (i == 0 or minLostPoint > lostPoint): + minLostPoint = lostPoint + pattern = i + return pattern + + def setupTimingPattern(self): + for r in range(8, self.moduleCount - 8): + self.modules[r][6] = (r % 2 == 0) + self.modules[6][8:self.moduleCount - 8] = itertools.islice( + itertools.cycle([True, False]), self.moduleCount - 16) + + _positionAdjustPattern = [ + [True, True, True, True, True], + [True, False, False, False, True], + [True, False, True, False, True], + [True, False, False, False, True], + [True, True, True, True, True], + ] + + def setupPositionAdjustPattern(self): + pos = QRUtil.getPatternPosition(self.version) + maxpos = self.moduleCount - 8 + for row, col in itertools.product(pos, pos): + if col <= 8 and (row <= 8 or row >= maxpos): + continue + elif col >= maxpos and row <= 8: + continue + for r, data in enumerate(self._positionAdjustPattern): + self.modules[row + r - 2][col-2:col+3] = data + + def setupTypeNumber(self, test): + bits = QRUtil.getBCHTypeNumber(self.version) + for i in range(18): + mod = (not test and ( (bits >> i) & 1) == 1) + self.modules[i // 3][i % 3 + self.moduleCount - 8 - 3] = mod; + for i in range(18): + mod = (not test and ( (bits >> i) & 1) == 1) + self.modules[i % 3 + self.moduleCount - 8 - 3][i // 3] = mod; + + def setupTypeInfo(self, test, maskPattern): + data = (self.errorCorrectLevel << 3) | maskPattern + bits = QRUtil.getBCHTypeInfo(data) + # vertical + for i in range(15): + mod = (not test and ( (bits >> i) & 1) == 1) + if (i < 6): + self.modules[i][8] = mod + elif (i < 8): + self.modules[i + 1][8] = mod + else: + self.modules[self.moduleCount - 15 + i][8] = mod + # horizontal + for i in range(15): + mod = (not test and ( (bits >> i) & 1) == 1); + if (i < 8): + self.modules[8][self.moduleCount - i - 1] = mod + elif (i < 9): + self.modules[8][15 - i - 1 + 1] = mod + else: + self.modules[8][15 - i - 1] = mod + # fixed module + self.modules[self.moduleCount - 8][8] = (not test) + + def _dataPosIterator(self): + cols = itertools.chain(range(self.moduleCount - 1, 6, -2), + range(5, 0, -2)) + rows = (list(range(9, self.moduleCount - 8)), + list(itertools.chain(range(6), range(7, self.moduleCount))), + list(range(9, self.moduleCount))) + rrows = tuple( list(reversed(r)) for r in rows) + + ppos = QRUtil.getPatternPosition(self.version) + ppos = set(itertools.chain.from_iterable( + (p-2, p-1, p, p+1, p+2) for p in ppos)) + maxpos = self.moduleCount - 11 + + for col in cols: + rows, rrows = rrows, rows + if col <= 8: rowidx = 0 + elif col >= self.moduleCount - 8: rowidx = 2 + else: rowidx = 1 + for row in rows[rowidx]: + for c in range(2): + c = col - c + if self.version >= 7: + if row < 6 and c >= self.moduleCount - 11: + continue + elif col < 6 and row >= self.moduleCount - 11: + continue + if row in ppos and c in ppos: + if not (row < 11 and (c < 11 or c > maxpos) or + c < 11 and (row < 11 or row > maxpos)): + continue + + yield (c, row) + + _dataPosList = None + + def dataPosIterator(self): + if not self._dataPosList: + self._dataPosList = list(self._dataPosIterator()) + return self._dataPosList + + def _dataBitIterator(self, data): + for byte in data: + for bit in [0x80, 0x40, 0x20, 0x10, + 0x08, 0x04, 0x02, 0x01]: + yield bool(byte & bit) + + _dataBitList = None + def dataBitIterator(self, data): + if not self._dataBitList: + self._dataBitList = list(self._dataBitIterator(data)) + return iter(self._dataBitList) + + def mapData(self, data, maskPattern): + bits = self.dataBitIterator(data) + mask = QRUtil.getMask(maskPattern) + + for (col, row), dark in zip_longest(self.dataPosIterator(), bits, + fillvalue=False): + self.modules[row][col] = dark ^ mask(row, col) + + PAD0 = 0xEC + PAD1 = 0x11 + + @staticmethod + def createData(version, errorCorrectLevel, dataList): + rsBlocks = QRRSBlock.getRSBlocks(version, errorCorrectLevel) + buffer = QRBitBuffer(); + for data in dataList: + data.write(buffer, version) + # calc num max data. + totalDataCount = 0; + for block in rsBlocks: + totalDataCount += block.dataCount + if (buffer.getLengthInBits() > totalDataCount * 8): + raise Exception("code length overflow. (%d > %d)" % + (buffer.getLengthInBits(), totalDataCount * 8)) + # end code + if (buffer.getLengthInBits() + 4 <= totalDataCount * 8): + buffer.put(0, 4) + # padding + while (buffer.getLengthInBits() % 8 != 0): + buffer.putBit(False) + # padding + while (True): + if (buffer.getLengthInBits() >= totalDataCount * 8): + break + buffer.put(QRCode.PAD0, 8) + if (buffer.getLengthInBits() >= totalDataCount * 8): + break + buffer.put(QRCode.PAD1, 8) + return QRCode.createBytes(buffer, rsBlocks) + + @staticmethod + def createBytes(buffer, rsBlocks): + offset = 0 + maxDcCount = 0 + maxEcCount = 0 + totalCodeCount = 0 + dcdata = [] + ecdata = [] + for block in rsBlocks: + totalCodeCount += block.totalCount + dcCount = block.dataCount + ecCount = block.totalCount - dcCount + maxDcCount = max(maxDcCount, dcCount) + maxEcCount = max(maxEcCount, ecCount) + dcdata.append(buffer.buffer[offset:offset+dcCount]) + offset += dcCount + rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount) + rawPoly = QRPolynomial(dcdata[-1], rsPoly.getLength() - 1) + modPoly = rawPoly.mod(rsPoly) + rLen = rsPoly.getLength() - 1 + mLen = modPoly.getLength() + ecdata.append([ (modPoly.get(i) if i >= 0 else 0) + for i in range(mLen - rLen, mLen) ]) + + data = [ d for dd in itertools.chain( + zip_longest(*dcdata), zip_longest(*ecdata)) + for d in dd if d is not None] + return data + + +class QRErrorCorrectLevel: + L = 1 + M = 0 + Q = 3 + H = 2 + +class QRMaskPattern: + PATTERN000 = 0 + PATTERN001 = 1 + PATTERN010 = 2 + PATTERN011 = 3 + PATTERN100 = 4 + PATTERN101 = 5 + PATTERN110 = 6 + PATTERN111 = 7 + +class QRUtil: + PATTERN_POSITION_TABLE = [ + [], + [6, 18], + [6, 22], + [6, 26], + [6, 30], + [6, 34], + [6, 22, 38], + [6, 24, 42], + [6, 26, 46], + [6, 28, 50], + [6, 30, 54], + [6, 32, 58], + [6, 34, 62], + [6, 26, 46, 66], + [6, 26, 48, 70], + [6, 26, 50, 74], + [6, 30, 54, 78], + [6, 30, 56, 82], + [6, 30, 58, 86], + [6, 34, 62, 90], + [6, 28, 50, 72, 94], + [6, 26, 50, 74, 98], + [6, 30, 54, 78, 102], + [6, 28, 54, 80, 106], + [6, 32, 58, 84, 110], + [6, 30, 58, 86, 114], + [6, 34, 62, 90, 118], + [6, 26, 50, 74, 98, 122], + [6, 30, 54, 78, 102, 126], + [6, 26, 52, 78, 104, 130], + [6, 30, 56, 82, 108, 134], + [6, 34, 60, 86, 112, 138], + [6, 30, 58, 86, 114, 142], + [6, 34, 62, 90, 118, 146], + [6, 30, 54, 78, 102, 126, 150], + [6, 24, 50, 76, 102, 128, 154], + [6, 28, 54, 80, 106, 132, 158], + [6, 32, 58, 84, 110, 136, 162], + [6, 26, 54, 82, 110, 138, 166], + [6, 30, 58, 86, 114, 142, 170] + ] + + G15 = ((1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | + (1 << 0)) + G18 = ((1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | + (1 << 5) | (1 << 2) | (1 << 0)) + G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1) + + @staticmethod + def getBCHTypeInfo(data): + d = data << 10; + while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) >= 0): + d ^= (QRUtil.G15 << (QRUtil.getBCHDigit(d) - + QRUtil.getBCHDigit(QRUtil.G15) ) ) + return ( (data << 10) | d) ^ QRUtil.G15_MASK + + @staticmethod + def getBCHTypeNumber(data): + d = data << 12; + while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) >= 0): + d ^= (QRUtil.G18 << (QRUtil.getBCHDigit(d) - + QRUtil.getBCHDigit(QRUtil.G18) ) ) + return (data << 12) | d + + @staticmethod + def getBCHDigit(data): + digit = 0; + while (data != 0): + digit += 1 + data >>= 1 + return digit + + @staticmethod + def getPatternPosition(version): + return QRUtil.PATTERN_POSITION_TABLE[version - 1] + + maskPattern = { + 0: lambda i,j: (i + j) % 2 == 0, + 1: lambda i,j: i % 2 == 0, + 2: lambda i,j: j % 3 == 0, + 3: lambda i,j: (i + j) % 3 == 0, + 4: lambda i,j: (i // 2 + j // 3) % 2 == 0, + 5: lambda i,j: (i*j)%2 + (i*j)%3 == 0, + 6: lambda i,j: ( (i * j) % 2 + (i * j) % 3) % 2 == 0, + 7: lambda i,j: ( (i * j) % 3 + (i + j) % 2) % 2 == 0 + } + + @classmethod + def getMask(cls, maskPattern): + return cls.maskPattern[maskPattern] + + @staticmethod + def getErrorCorrectPolynomial(errorCorrectLength): + a = QRPolynomial([1], 0); + for i in range(errorCorrectLength): + a = a.multiply(QRPolynomial([1, QRMath.gexp(i)], 0) ) + return a + + @classmethod + def maskScoreRule1vert(cls, modules): + score = 0 + lastCount = [0] + lastRow = None + for row in modules: + # Vertical patterns + if lastRow: + changed = [a ^ b for a,b in zip(row, lastRow)] + scores = [a and (b-4+3) for a,b in + zip_longest(changed, lastCount, fillvalue=0) + if b >= 4] + score += sum(scores) + lastCount = [0 if a else b + 1 + for a,b in zip_longest(changed, lastCount, + fillvalue=0)] + lastRow = row + + score += sum([b-4+3 for b in lastCount if b >= 4]) # final counts + return score + + @classmethod + def maskScoreRule2(cls, modules): + score = 0 + lastRow = modules[0] + for row in modules[1:]: + lastCol0, lastCol1 = row[0], lastRow[0] + for col0, col1 in zip(row[1:], lastRow[1:]): + if col0 == col1 == lastCol0 == lastCol1: + score += 3 + lastCol0, lastCol1 = col0, col1 + lastRow = row + + return score + + @classmethod + def maskScoreRule3hor( + cls, modules, + pattern = [True, False, True, True, True, False, True, + False, False, False, False]): + patternlen = len(pattern) + score = 0 + for row in modules: + j = 0 + maxj = len(row) - patternlen + while j < maxj: + if row[j:j+patternlen] == pattern: + score += 40 + j += patternlen + else: + j += 1 + + return score + + @classmethod + def maskScoreRule4(cls, modules): + cellCount = len(modules)**2 + count = sum(sum(row) for row in modules) + return 10 * (abs(100 * count // cellCount - 50) // 5) + + @classmethod + def getLostPoint(cls, qrCode): + lostPoint = 0; + # LEVEL1 + lostPoint += cls.maskScoreRule1vert(qrCode.modules) + lostPoint += cls.maskScoreRule1vert(zip(*qrCode.modules)) + # LEVEL2 + lostPoint += cls.maskScoreRule2(qrCode.modules) + # LEVEL3 + lostPoint += cls.maskScoreRule3hor(qrCode.modules) + lostPoint += cls.maskScoreRule3hor(zip(*qrCode.modules)) + # LEVEL4 + lostPoint += cls.maskScoreRule4(qrCode.modules) + return lostPoint + +class QRMath: + @staticmethod + def glog(n): + if (n < 1): + raise Exception("glog(" + n + ")") + return LOG_TABLE[n]; + + @staticmethod + def gexp(n): + while n < 0: + n += 255 + while n >= 256: + n -= 255 + return EXP_TABLE[n]; + +EXP_TABLE = [x for x in range(256)] +LOG_TABLE = [x for x in range(256)] +for i in range(8): + EXP_TABLE[i] = 1 << i; +for i in range(8, 256): + EXP_TABLE[i] = (EXP_TABLE[i - 4] ^ EXP_TABLE[i - 5] ^ + EXP_TABLE[i - 6] ^ EXP_TABLE[i - 8]) +for i in range(255): + LOG_TABLE[EXP_TABLE[i] ] = i + +class QRPolynomial: + def __init__(self, num, shift): + if (len(num) == 0): + raise Exception(len(num) + "/" + shift) + offset = 0 + while offset < len(num) and num[offset] == 0: + offset += 1 + self.num = num[offset:] + [0]*shift + + def get(self, index): + return self.num[index] + + def getLength(self): + return len(self.num) + + def multiply(self, e): + num = [0] * (self.getLength() + e.getLength() - 1); + for i in range(self.getLength()): + for j in range(e.getLength()): + num[i + j] ^= QRMath.gexp(QRMath.glog(self.get(i) ) + + QRMath.glog(e.get(j) ) ) + return QRPolynomial(num, 0); + + def mod(self, e): + if (self.getLength() < e.getLength()): + return self; + ratio = QRMath.glog(self.num[0] ) - QRMath.glog(e.num[0] ) + num = [nn ^ QRMath.gexp(QRMath.glog(en) + ratio) + for nn,en in zip(self.num, e.num)] + num += self.num[e.getLength():] + # recursive call + return QRPolynomial(num, 0).mod(e); + +class QRRSBlock: + RS_BLOCK_TABLE = [ + # L + # M + # Q + # H + + # 1 + [1, 26, 19], + [1, 26, 16], + [1, 26, 13], + [1, 26, 9], + + # 2 + [1, 44, 34], + [1, 44, 28], + [1, 44, 22], + [1, 44, 16], + + # 3 + [1, 70, 55], + [1, 70, 44], + [2, 35, 17], + [2, 35, 13], + + # 4 + [1, 100, 80], + [2, 50, 32], + [2, 50, 24], + [4, 25, 9], + + # 5 + [1, 134, 108], + [2, 67, 43], + [2, 33, 15, 2, 34, 16], + [2, 33, 11, 2, 34, 12], + + # 6 + [2, 86, 68], + [4, 43, 27], + [4, 43, 19], + [4, 43, 15], + + # 7 + [2, 98, 78], + [4, 49, 31], + [2, 32, 14, 4, 33, 15], + [4, 39, 13, 1, 40, 14], + + # 8 + [2, 121, 97], + [2, 60, 38, 2, 61, 39], + [4, 40, 18, 2, 41, 19], + [4, 40, 14, 2, 41, 15], + + # 9 + [2, 146, 116], + [3, 58, 36, 2, 59, 37], + [4, 36, 16, 4, 37, 17], + [4, 36, 12, 4, 37, 13], + + # 10 + [2, 86, 68, 2, 87, 69], + [4, 69, 43, 1, 70, 44], + [6, 43, 19, 2, 44, 20], + [6, 43, 15, 2, 44, 16], + + # 11 + [4, 101, 81], + [1, 80, 50, 4, 81, 51], + [4, 50, 22, 4, 51, 23], + [3, 36, 12, 8, 37, 13], + + # 12 + [2, 116, 92, 2, 117, 93], + [6, 58, 36, 2, 59, 37], + [4, 46, 20, 6, 47, 21], + [7, 42, 14, 4, 43, 15], + + # 13 + [4, 133, 107], + [8, 59, 37, 1, 60, 38], + [8, 44, 20, 4, 45, 21], + [12, 33, 11, 4, 34, 12], + + # 14 + [3, 145, 115, 1, 146, 116], + [4, 64, 40, 5, 65, 41], + [11, 36, 16, 5, 37, 17], + [11, 36, 12, 5, 37, 13], + + # 15 + [5, 109, 87, 1, 110, 88], + [5, 65, 41, 5, 66, 42], + [5, 54, 24, 7, 55, 25], + [11, 36, 12], + + # 16 + [5, 122, 98, 1, 123, 99], + [7, 73, 45, 3, 74, 46], + [15, 43, 19, 2, 44, 20], + [3, 45, 15, 13, 46, 16], + + # 17 + [1, 135, 107, 5, 136, 108], + [10, 74, 46, 1, 75, 47], + [1, 50, 22, 15, 51, 23], + [2, 42, 14, 17, 43, 15], + + # 18 + [5, 150, 120, 1, 151, 121], + [9, 69, 43, 4, 70, 44], + [17, 50, 22, 1, 51, 23], + [2, 42, 14, 19, 43, 15], + + # 19 + [3, 141, 113, 4, 142, 114], + [3, 70, 44, 11, 71, 45], + [17, 47, 21, 4, 48, 22], + [9, 39, 13, 16, 40, 14], + + # 20 + [3, 135, 107, 5, 136, 108], + [3, 67, 41, 13, 68, 42], + [15, 54, 24, 5, 55, 25], + [15, 43, 15, 10, 44, 16], + + # 21 + [4, 144, 116, 4, 145, 117], + [17, 68, 42], + [17, 50, 22, 6, 51, 23], + [19, 46, 16, 6, 47, 17], + + # 22 + [2, 139, 111, 7, 140, 112], + [17, 74, 46], + [7, 54, 24, 16, 55, 25], + [34, 37, 13], + + # 23 + [4, 151, 121, 5, 152, 122], + [4, 75, 47, 14, 76, 48], + [11, 54, 24, 14, 55, 25], + [16, 45, 15, 14, 46, 16], + + # 24 + [6, 147, 117, 4, 148, 118], + [6, 73, 45, 14, 74, 46], + [11, 54, 24, 16, 55, 25], + [30, 46, 16, 2, 47, 17], + + # 25 + [8, 132, 106, 4, 133, 107], + [8, 75, 47, 13, 76, 48], + [7, 54, 24, 22, 55, 25], + [22, 45, 15, 13, 46, 16], + + # 26 + [10, 142, 114, 2, 143, 115], + [19, 74, 46, 4, 75, 47], + [28, 50, 22, 6, 51, 23], + [33, 46, 16, 4, 47, 17], + + # 27 + [8, 152, 122, 4, 153, 123], + [22, 73, 45, 3, 74, 46], + [8, 53, 23, 26, 54, 24], + [12, 45, 15, 28, 46, 16], + + # 28 + [3, 147, 117, 10, 148, 118], + [3, 73, 45, 23, 74, 46], + [4, 54, 24, 31, 55, 25], + [11, 45, 15, 31, 46, 16], + + # 29 + [7, 146, 116, 7, 147, 117], + [21, 73, 45, 7, 74, 46], + [1, 53, 23, 37, 54, 24], + [19, 45, 15, 26, 46, 16], + + # 30 + [5, 145, 115, 10, 146, 116], + [19, 75, 47, 10, 76, 48], + [15, 54, 24, 25, 55, 25], + [23, 45, 15, 25, 46, 16], + + # 31 + [13, 145, 115, 3, 146, 116], + [2, 74, 46, 29, 75, 47], + [42, 54, 24, 1, 55, 25], + [23, 45, 15, 28, 46, 16], + + # 32 + [17, 145, 115], + [10, 74, 46, 23, 75, 47], + [10, 54, 24, 35, 55, 25], + [19, 45, 15, 35, 46, 16], + + # 33 + [17, 145, 115, 1, 146, 116], + [14, 74, 46, 21, 75, 47], + [29, 54, 24, 19, 55, 25], + [11, 45, 15, 46, 46, 16], + + # 34 + [13, 145, 115, 6, 146, 116], + [14, 74, 46, 23, 75, 47], + [44, 54, 24, 7, 55, 25], + [59, 46, 16, 1, 47, 17], + + # 35 + [12, 151, 121, 7, 152, 122], + [12, 75, 47, 26, 76, 48], + [39, 54, 24, 14, 55, 25], + [22, 45, 15, 41, 46, 16], + + # 36 + [6, 151, 121, 14, 152, 122], + [6, 75, 47, 34, 76, 48], + [46, 54, 24, 10, 55, 25], + [2, 45, 15, 64, 46, 16], + + # 37 + [17, 152, 122, 4, 153, 123], + [29, 74, 46, 14, 75, 47], + [49, 54, 24, 10, 55, 25], + [24, 45, 15, 46, 46, 16], + + # 38 + [4, 152, 122, 18, 153, 123], + [13, 74, 46, 32, 75, 47], + [48, 54, 24, 14, 55, 25], + [42, 45, 15, 32, 46, 16], + + # 39 + [20, 147, 117, 4, 148, 118], + [40, 75, 47, 7, 76, 48], + [43, 54, 24, 22, 55, 25], + [10, 45, 15, 67, 46, 16], + + # 40 + [19, 148, 118, 6, 149, 119], + [18, 75, 47, 31, 76, 48], + [34, 54, 24, 34, 55, 25], + [20, 45, 15, 61, 46, 16] + + ] + + def __init__(self, totalCount, dataCount): + self.totalCount = totalCount + self.dataCount = dataCount + + @staticmethod + def getRSBlocks(version, errorCorrectLevel): + rsBlock = QRRSBlock.getRsBlockTable(version, errorCorrectLevel); + if rsBlock == None: + raise Exception("bad rs block @ version:" + version + + "/errorCorrectLevel:" + errorCorrectLevel) + length = len(rsBlock) // 3 + list = [] + for i in range(length): + count = rsBlock[i * 3 + 0] + totalCount = rsBlock[i * 3 + 1] + dataCount = rsBlock[i * 3 + 2] + for j in range(count): + list.append(QRRSBlock(totalCount, dataCount)) + return list; + + @staticmethod + def getRsBlockTable(version, errorCorrectLevel): + if errorCorrectLevel == QRErrorCorrectLevel.L: + return QRRSBlock.RS_BLOCK_TABLE[(version - 1) * 4 + 0]; + elif errorCorrectLevel == QRErrorCorrectLevel.M: + return QRRSBlock.RS_BLOCK_TABLE[(version - 1) * 4 + 1]; + elif errorCorrectLevel == QRErrorCorrectLevel.Q: + return QRRSBlock.RS_BLOCK_TABLE[(version - 1) * 4 + 2]; + elif errorCorrectLevel == QRErrorCorrectLevel.H: + return QRRSBlock.RS_BLOCK_TABLE[(version - 1) * 4 + 3]; + else: + return None; + +class QRBitBuffer: + def __init__(self): + self.buffer = [] + self.length = 0 + + def __repr__(self): + return ".".join([str(n) for n in self.buffer]) + + def get(self, index): + bufIndex = index // 8 + return ( (self.buffer[bufIndex] >> (7 - index % 8) ) & 1) == 1 + + def put(self, num, length): + for i in range(length): + self.putBit( ( (num >> (length - i - 1) ) & 1) == 1) + + def getLengthInBits(self): + return self.length + + def putBit(self, bit): + bufIndex = self.length // 8 + if len(self.buffer) <= bufIndex: + self.buffer.append(0) + if bit: + self.buffer[bufIndex] |= (0x80 >> (self.length % 8) ) + self.length += 1 diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/test.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/test.py new file mode 100644 index 0000000000000000000000000000000000000000..2cba0a20f34e498e68c207ff559228079d13c2c6 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/test.py @@ -0,0 +1,280 @@ +#!/usr/pkg/bin/python + +import sys, time + +from reportlab import Version as __RL_Version__ +from reportlab.graphics.barcode.common import * +from reportlab.graphics.barcode.code39 import * +from reportlab.graphics.barcode.code93 import * +from reportlab.graphics.barcode.code128 import * +from reportlab.graphics.barcode.usps import * +from reportlab.graphics.barcode.usps4s import USPS_4State +from reportlab.graphics.barcode.qr import QrCodeWidget +from reportlab.graphics.barcode.dmtx import DataMatrixWidget, pylibdmtx + +from reportlab.platypus import Spacer, SimpleDocTemplate, PageBreak +from reportlab.lib.units import inch +from reportlab.lib import colors + +from reportlab.lib.styles import getSampleStyleSheet +from reportlab.platypus.paragraph import Paragraph +from reportlab.platypus.flowables import XBox, KeepTogether +from reportlab.graphics.shapes import Drawing, Rect, Line + +from reportlab.graphics.barcode import getCodeNames, createBarcodeDrawing, createBarcodeImageInMemory + +def run(): + styles = getSampleStyleSheet() + styleN = styles['Normal'] + styleH = styles['Heading1'] + story = [] + storyAdd = story.append + + #for codeNames in code + storyAdd(Paragraph('I2of5', styleN)) + storyAdd(I2of5('05400141288766', barWidth = inch*0.02, checksum=0)) + storyAdd(I2of5('0001234567890', barWidth = inch*0.02, checksum=1)) + storyAdd(I2of5('00012345678905', barWidth = inch*0.02, checksum=0)) + storyAdd(I2of5('0001234567890', barWidth = inch*0.02, checksum=1, bearerBox = True)) + + + storyAdd(Paragraph('MSI', styleN)) + storyAdd(MSI(1234)) + + storyAdd(Paragraph('Codabar', styleN)) + storyAdd(Codabar("A012345B", barWidth = inch*0.02)) + + storyAdd(Paragraph('Code 11', styleN)) + storyAdd(Code11("01234545634563")) + + storyAdd(Paragraph('Code 39', styleN)) + storyAdd(Standard39("A012345B%R")) + + storyAdd(Paragraph('Extended Code 39', styleN)) + storyAdd(Extended39("A012345B}")) + + storyAdd(Paragraph('Code93', styleN)) + storyAdd(Standard93("CODE 93")) + + storyAdd(Paragraph('Extended Code93', styleN)) + storyAdd(Extended93("L@@K! Code 93 :-)")) #, barWidth=0.005 * inch)) + + storyAdd(Paragraph('Code 128', styleN)) + storyAdd(Code128("AB-12345678")) + + storyAdd(Paragraph('Code 128 Auto', styleN)) + storyAdd(Code128Auto("AB-12345678")) + + storyAdd(Paragraph('USPS FIM', styleN)) + storyAdd(FIM("A")) + + storyAdd(Paragraph('USPS POSTNET', styleN)) + storyAdd(POSTNET('78247-1043')) + + storyAdd(Paragraph('USPS 4 State', styleN)) + storyAdd(USPS_4State('01234567094987654321','01234567891')) + + from reportlab.graphics.barcode import createBarcodeDrawing + + storyAdd(Paragraph('EAN13', styleN)) + storyAdd(createBarcodeDrawing('EAN13', value='123456789012')) + + storyAdd(Paragraph('EAN13 quiet=False', styleN)) + storyAdd(createBarcodeDrawing('EAN13', value='123456789012', quiet=False)) + + storyAdd(Paragraph('EAN8', styleN)) + storyAdd(createBarcodeDrawing('EAN8', value='1234567')) + + storyAdd(PageBreak()) + + storyAdd(Paragraph('EAN5 price=True', styleN)) + storyAdd(createBarcodeDrawing('EAN5', value='11299', price=True)) + + storyAdd(Paragraph('EAN5 price=True quiet=False', styleN)) + storyAdd(createBarcodeDrawing('EAN5', value='11299', price=True, quiet=False)) + + storyAdd(Paragraph('EAN5 price=False', styleN)) + storyAdd(createBarcodeDrawing('EAN5', value='11299', price=False)) + + storyAdd(Paragraph('ISBN alone', styleN)) + storyAdd(createBarcodeDrawing('ISBN', value='9781565924796')) + + storyAdd(Paragraph('ISBN with ean5 price', styleN)) + storyAdd(createBarcodeDrawing('ISBN', value='9781565924796',price='01299')) + + storyAdd(Paragraph('ISBN with ean5 price, quiet=False', styleN)) + storyAdd(createBarcodeDrawing('ISBN', value='9781565924796',price='01299',quiet=False)) + + storyAdd(Paragraph('UPCA', styleN)) + storyAdd(createBarcodeDrawing('UPCA', value='03600029145')) + + storyAdd(Paragraph('USPS_4State', styleN)) + storyAdd(createBarcodeDrawing('USPS_4State', value='01234567094987654321',routing='01234567891')) + + storyAdd(Paragraph('QR', styleN)) + storyAdd(createBarcodeDrawing('QR', value='01234567094987654321')) + + storyAdd(Paragraph('QR', styleN)) + storyAdd(createBarcodeDrawing('QR', value='01234567094987654321',x=30,y=50)) + + def addCross(d,x,y,w=5,h=5, strokeColor='black', strokeWidth=0.5): + w *= 0.5 + h *= 0.5 + d.add(Line(x-w,y,x+w,y,strokeWidth=0.5,strokeColor=colors.blue)) + d.add(Line(x, y-h, x, y+h,strokeWidth=0.5,strokeColor=colors.blue)) + storyAdd(Paragraph('QR in drawing at (0,0)', styleN)) + d = Drawing(100,100) + d.add(Rect(0,0,100,100,strokeWidth=1,strokeColor=colors.red,fillColor=None)) + d.add(QrCodeWidget(value='01234567094987654321')) + storyAdd(d) + + storyAdd(Paragraph('QR in drawing at (10,10)', styleN)) + d = Drawing(100,100) + d.add(Rect(0,0,100,100,strokeWidth=1,strokeColor=colors.red,fillColor=None)) + addCross(d,10,10) + d.add(QrCodeWidget(value='01234567094987654321',x=10,y=10)) + storyAdd(d) + + storyAdd(Paragraph('Label Size', styleN)) + storyAdd(XBox((2.0 + 5.0/8.0)*inch, 1 * inch, '1x2-5/8"')) + + storyAdd(Paragraph('Label Size', styleN)) + storyAdd(XBox((1.75)*inch, .5 * inch, '1/2x1-3/4"')) + + if pylibdmtx: + storyAdd(PageBreak()) + storyAdd(Paragraph('DataMatrix in drawing at (10,10)', styleN)) + d = Drawing(100,100) + d.add(Rect(0,0,100,100,strokeWidth=1,strokeColor=colors.red,fillColor=None)) + addCross(d,10,10) + d.add(DataMatrixWidget(value='1234567890',x=10,y=10)) + storyAdd(d) + storyAdd(Paragraph('DataMatrix in drawing at (10,10)', styleN)) + d = Drawing(100,100) + d.add(Rect(0,0,100,100,strokeWidth=1,strokeColor=colors.red,fillColor=None)) + addCross(d,10,10) + d.add(DataMatrixWidget(value='1234567890',x=10,y=10,color='black',bgColor='lime')) + storyAdd(d) + + storyAdd(Paragraph('DataMatrix in drawing at (90,90) anchor=ne', styleN)) + d = Drawing(100,100) + d.add(Rect(0,0,100,100,strokeWidth=1,strokeColor=colors.red,fillColor=None)) + addCross(d,90,90) + d.add(DataMatrixWidget(value='1234567890',x=90,y=90,color='darkblue',bgColor='yellow', anchor='ne')) + storyAdd(d) + + + SimpleDocTemplate('out.pdf').build(story) + print('saved out.pdf') + +def fullTest(fileName="test_full.pdf"): + """Creates large-ish test document with a variety of parameters""" + + story = [] + + styles = getSampleStyleSheet() + styleN = styles['Normal'] + styleH = styles['Heading1'] + styleH2 = styles['Heading2'] + story = [] + + story.append(Paragraph('ReportLab %s Barcode Test Suite - full output' % __RL_Version__,styleH)) + story.append(Paragraph('Generated at %s' % time.ctime(time.time()), styleN)) + + story.append(Paragraph('About this document', styleH2)) + story.append(Paragraph('History and Status', styleH2)) + + story.append(Paragraph(""" + This is the test suite and docoumentation for the ReportLab open source barcode API. + """, styleN)) + + story.append(Paragraph(""" + Several years ago Ty Sarna contributed a barcode module to the ReportLab community. + Several of the codes were used by him in hiw work and to the best of our knowledge + this was correct. These were written as flowable objects and were available in PDFs, + but not in our graphics framework. However, we had no knowledge of barcodes ourselves + and did not advertise or extend the package. + """, styleN)) + + story.append(Paragraph(""" + We "wrapped" the barcodes to be usable within our graphics framework; they are now available + as Drawing objects which can be rendered to EPS files or bitmaps. For the last 2 years this + has been available in our Diagra and Report Markup Language products. However, we did not + charge separately and use was on an "as is" basis. + """, styleN)) + + story.append(Paragraph(""" + A major licensee of our technology has kindly agreed to part-fund proper productisation + of this code on an open source basis in Q1 2006. This has involved addition of EAN codes + as well as a proper testing program. Henceforth we intend to publicise the code more widely, + gather feedback, accept contributions of code and treat it as "supported". + """, styleN)) + + story.append(Paragraph(""" + This involved making available both downloads and testing resources. This PDF document + is the output of the current test suite. It contains codes you can scan (if you use a nice sharp + laser printer!), and will be extended over coming weeks to include usage examples and notes on + each barcode and how widely tested they are. This is being done through documentation strings in + the barcode objects themselves so should always be up to date. + """, styleN)) + + story.append(Paragraph('Usage examples', styleH2)) + story.append(Paragraph(""" + To be completed + """, styleN)) + + story.append(Paragraph('The codes', styleH2)) + story.append(Paragraph(""" + Below we show a scannable code from each barcode, with and without human-readable text. + These are magnified about 2x from the natural size done by the original author to aid + inspection. This will be expanded to include several test cases per code, and to add + explanations of checksums. Be aware that (a) if you enter numeric codes which are too + short they may be prefixed for you (e.g. "123" for an 8-digit code becomes "00000123"), + and that the scanned results and readable text will generally include extra checksums + at the end. + """, styleN)) + + codeNames = getCodeNames() + from reportlab.lib.utils import flatten + width = [float(x[8:]) for x in sys.argv if x.startswith('--width=')] + height = [float(x[9:]) for x in sys.argv if x.startswith('--height=')] + isoScale = [int(x[11:]) for x in sys.argv if x.startswith('--isoscale=')] + options = {} + if width: options['width'] = width[0] + if height: options['height'] = height[0] + if isoScale: options['isoScale'] = isoScale[0] + scales = [x[8:].split(',') for x in sys.argv if x.startswith('--scale=')] + scales = list(map(float,scales and flatten(scales) or [1])) + scales = list(map(float,scales and flatten(scales) or [1])) + for scale in scales: + story.append(PageBreak()) + story.append(Paragraph('Scale = %.1f'%scale, styleH2)) + story.append(Spacer(36, 12)) + for codeName in codeNames: + s = [Paragraph('Code: ' + codeName, styleH2)] + for hr in (0,1): + s.append(Spacer(36, 12)) + dr = createBarcodeDrawing(codeName, humanReadable=hr,**options) + dr.renderScale = scale + s.append(dr) + s.append(Spacer(36, 12)) + s.append(Paragraph('Barcode should say: ' + dr._bc.value, styleN)) + story.append(KeepTogether(s)) + + SimpleDocTemplate(fileName).build(story) + print('created', fileName) + +if __name__=='__main__': + run() + fullTest() + def createSample(name,memory): + f = open(name,'wb') + f.write(memory) + f.close() + createSample('test_cbcim.png',createBarcodeImageInMemory('EAN13', value='123456789012')) + createSample('test_cbcim.gif',createBarcodeImageInMemory('EAN8', value='1234567', format='gif')) + createSample('test_cbcim.pdf',createBarcodeImageInMemory('UPCA', value='03600029145',format='pdf', barHeight=40)) + createSample('test_cbcim.tiff',createBarcodeImageInMemory('USPS_4State', value='01234567094987654321',routing='01234567891',format='tiff')) + createSample('test_cbcim-1.pdf',createBarcodeImageInMemory('QR', + value='This is the end my only friend the end at the end of the Universe.',format='pdf')) + diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/usps.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/usps.py new file mode 100644 index 0000000000000000000000000000000000000000..a40169b8264526fc953cebb79f95941f4f39659b --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/usps.py @@ -0,0 +1,232 @@ +# +# Copyright (c) 1996-2000 Tyler C. Sarna +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. All advertising materials mentioning features or use of this software +# must display the following acknowledgement: +# This product includes software developed by Tyler C. Sarna. +# 4. Neither the name of the author nor the names of contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS +# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# + +from reportlab.lib.units import inch +from reportlab.graphics.barcode.common import Barcode +from string import digits as string_digits, whitespace as string_whitespace +from reportlab.lib.utils import asNative + +_fim_patterns = { + 'A' : "|| | ||", + 'B' : "| || || |", + 'C' : "|| | | ||", + 'D' : "||| | |||", + # XXX There is an E. + # The below has been seen, but dunno if it is E or not: + # 'E' : '|||| ||||' +} + +_postnet_patterns = { + '1' : "...||", '2' : "..|.|", '3' : "..||.", '4' : ".|..|", + '5' : ".|.|.", '6' : ".||..", '7' : "|...|", '8' : "|..|.", + '9' : "|.|..", '0' : "||...", 'S' : "|", +} + +class FIM(Barcode): + """ + FIM (Facing ID Marks) encode only one letter. + There are currently four defined: + + A Courtesy reply mail with pre-printed POSTNET + B Business reply mail without pre-printed POSTNET + C Business reply mail with pre-printed POSTNET + D OCR Readable mail without pre-printed POSTNET + + Options that may be passed to constructor: + + value (single character string from the set A - D. required.): + The value to encode. + + quiet (bool, default 0): + Whether to include quiet zones in the symbol. + + The following may also be passed, but doing so will generate nonstandard + symbols which should not be used. This is mainly documented here to + show the defaults: + + barHeight (float, default 5/8 inch): + Height of the code. This might legitimately be overriden to make + a taller symbol that will 'bleed' off the edge of the paper, + leaving 5/8 inch remaining. + + lquiet (float, default 1/4 inch): + Quiet zone size to left of code, if quiet is true. + Default is the greater of .25 inch, or .15 times the symbol's + length. + + rquiet (float, default 15/32 inch): + Quiet zone size to right left of code, if quiet is true. + + Sources of information on FIM: + + USPS Publication 25, A Guide to Business Mail Preparation + http://new.usps.com/cpim/ftp/pubs/pub25.pdf + """ + barWidth = inch * (1.0/32.0) + spaceWidth = inch * (1.0/16.0) + barHeight = inch * (5.0/8.0) + rquiet = inch * (0.25) + lquiet = inch * (15.0/32.0) + quiet = 0 + def __init__(self, value='', **args): + value = str(value) if isinstance(value,int) else asNative(value) + for k, v in args.items(): + setattr(self, k, v) + + Barcode.__init__(self, value) + + def validate(self): + self.valid = 1 + self.validated = '' + for c in self.value: + if c in string_whitespace: + continue + elif c in "abcdABCD": + self.validated = self.validated + c.upper() + else: + self.valid = 0 + + if len(self.validated) != 1: + raise ValueError("Input must be exactly one character") + + return self.validated + + def decompose(self): + self.decomposed = '' + for c in self.encoded: + self.decomposed = self.decomposed + _fim_patterns[c] + + return self.decomposed + + def computeSize(self): + self._width = (len(self.decomposed) - 1) * self.spaceWidth + self.barWidth + if self.quiet: + self._width += self.lquiet + self.rquiet + self._height = self.barHeight + + def draw(self): + self._calculate() + left = self.quiet and self.lquiet or 0 + for c in self.decomposed: + if c == '|': + self.rect(left, 0.0, self.barWidth, self.barHeight) + left += self.spaceWidth + self.drawHumanReadable() + + def _humanText(self): + return self.value + +class POSTNET(Barcode): + """ + POSTNET is used in the US to encode "zip codes" (postal codes) on + mail. It can encode 5, 9, or 11 digit codes. I've read that it's + pointless to do 5 digits, since USPS will just have to re-print + them with 9 or 11 digits. + + Sources of information on POSTNET: + + USPS Publication 25, A Guide to Business Mail Preparation + http://new.usps.com/cpim/ftp/pubs/pub25.pdf + """ + quiet = 0 + shortHeight = inch * 0.050 + barHeight = inch * 0.125 + barWidth = inch * 0.018 + spaceWidth = inch * 0.0275 + def __init__(self, value='', **args): + value = str(value) if isinstance(value,int) else asNative(value) + for k, v in args.items(): + setattr(self, k, v) + + Barcode.__init__(self, value) + + def validate(self): + self.validated = '' + self.valid = 1 + count = 0 + for c in self.value: + if c in (string_whitespace + '-'): + pass + elif c in string_digits: + count = count + 1 + if count == 6: + self.validated = self.validated + '-' + self.validated = self.validated + c + else: + self.valid = 0 + + if len(self.validated) not in [5, 10, 12]: + self.valid = 0 + + return self.validated + + def encode(self): + self.encoded = "S" + check = 0 + for c in self.validated: + if c in string_digits: + self.encoded = self.encoded + c + check = check + int(c) + elif c == '-': + pass + else: + raise ValueError("Invalid character in input") + check = (10 - check) % 10 + self.encoded = self.encoded + repr(check) + 'S' + return self.encoded + + def decompose(self): + self.decomposed = '' + for c in self.encoded: + self.decomposed = self.decomposed + _postnet_patterns[c] + return self.decomposed + + def computeSize(self): + self._width = len(self.decomposed) * self.barWidth + (len(self.decomposed) - 1) * self.spaceWidth + self._height = self.barHeight + + def draw(self): + self._calculate() + sdown = self.barHeight - self.shortHeight + left = 0 + + for c in self.decomposed: + if c == '.': + h = self.shortHeight + else: + h = self.barHeight + self.rect(left, 0.0, self.barWidth, h) + left = left + self.barWidth + self.spaceWidth + self.drawHumanReadable() + + def _humanText(self): + return self.encoded[1:-1] diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/usps4s.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/usps4s.py new file mode 100644 index 0000000000000000000000000000000000000000..8d998001dae64e5e0ecff694caaafa24dc96228d --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/barcode/usps4s.py @@ -0,0 +1,465 @@ +#copyright ReportLab Inc. 2000-2016 +#see license.txt for license details +from __future__ import print_function +__version__='3.3.0' +__all__ = ('USPS_4State',) + +from reportlab.graphics.barcode.common import Barcode +from reportlab.lib.utils import asNative + +def nhex(i): + 'normalized hex' + r = hex(i) + r = r[:2]+r[2:].lower() + if r.endswith('l'): r = r[:-1] + return r + +class USPS_4State(Barcode): + ''' USPS 4-State OneView (TM) barcode. All info from USPS-B-3200A + ''' + _widthSize = 1 + _heightSize = 1 + _fontSize = 11 + _humanReadable = 0 + if True: + tops = dict( + F = (0.0625,0.0825), + T = (0.0195,0.0285), + A = (0.0625,0.0825), + D = (0.0195,0.0285), + ) + bottoms = dict( + F = (-0.0625,-0.0825), + T = (-0.0195,-0.0285), + D = (-0.0625,-0.0825), + A = (-0.0195,-0.0285), + ) + dimensions = dict( + width = (0.015, 0.025), + pitch = (0.0416, 0.050), + hcz = (0.125,0.125), + vcz = (0.028,0.028), + ) + else: + tops = dict( + F = (0.067,0.115), + T = (0.021,0.040), + A = (0.067,0.115), + D = (0.021,0.040), + ) + bottoms = dict( + F = (-0.067,-0.115), + D = (-0.067,-0.115), + T = (-0.021,-0.040), + A = (-0.021,-0.040), + ) + dimensions = dict( + width = (0.015, 0.025), + pitch = (0.0416,0.050), + hcz = (0.125,0.125), + vcz = (0.040,0.040), + ) + + def __init__(self,value='01234567094987654321',routing='',**kwd): + self._init() + value = str(value) if isinstance(value,int) else asNative(value) + if not routing: + #legal values for combined tracking + routing + if len(value) in (20,25,29,31): + value, routing = value[:20], value[20:] + else: + raise ValueError('value+routing length must be 20, 25, 29 or 31 digits not %d' % len(value)) + elif len(routing) not in (5,9,11): + raise ValueError('routing length must be 5, 9 or 11 digits not %d' % len(routing)) + self._tracking = value + self._routing = routing + self._setKeywords(**kwd) + + def _init(self): + self._bvalue = None + self._codewords = None + self._characters = None + self._barcodes = None + + def scale(kind,D,s): + V = D[kind] + return 72*(V[0]*(1-s)+s*V[1]) + scale = staticmethod(scale) + + def tracking(self,tracking): + self._init() + self._tracking = tracking + tracking = property(lambda self: self._tracking,tracking) + + def routing(self,routing): + self._init() + self._routing = routing + routing = property(lambda self: self._routing,routing) + + def widthSize(self,value): + self._sized = None + self._widthSize = min(max(0,value),1) + widthSize = property(lambda self: self._widthSize,widthSize) + + def heightSize(self,value): + self._sized = None + self._heightSize = value + heightSize = property(lambda self: self._heightSize,heightSize) + + def fontSize(self,value): + self._sized = None + self._fontSize = value + fontSize = property(lambda self: self._fontSize,fontSize) + + def humanReadable(self,value): + self._sized = None + self._humanReadable = value + humanReadable = property(lambda self: self._humanReadable,humanReadable) + + def binary(self): + '''convert the 4 state string values to binary + >>> print(nhex(USPS_4State('01234567094987654321','').binary)) + 0x1122103b5c2004b1 + >>> print(nhex(USPS_4State('01234567094987654321','01234').binary)) + 0xd138a87bab5cf3804b1 + >>> print(nhex(USPS_4State('01234567094987654321','012345678').binary)) + 0x202bdc097711204d21804b1 + >>> print(nhex(USPS_4State('01234567094987654321','01234567891').binary)) + 0x16907b2a24abc16a2e5c004b1 + ''' + value = self._bvalue + if not value: + routing = self.routing + n = len(routing) + try: + if n==0: + value = 0 + elif n==5: + value = int(routing)+1 + elif n==9: + value = int(routing)+100001 + elif n==11: + value = int(routing)+1000100001 + else: + raise ValueError + except: + raise ValueError('Problem converting %s, routing code must be 0, 5, 9 or 11 digits' % routing) + + tracking = self.tracking + svalue = tracking[0:2] + try: + value *= 10 + value += int(svalue[0]) + value *= 5 + value += int(svalue[1]) + except: + raise ValueError('Problem converting %s, barcode identifier must be 2 digits' % svalue) + + i = 2 + for name,nd in (('special services',3), ('customer identifier',6), ('sequence number',9)): + j = i + i += nd + svalue = tracking[j:i] + try: + if len(svalue)!=nd: raise ValueError + for j in range(nd): + value *= 10 + value += int(svalue[j]) + except: + raise ValueError('Problem converting %s, %s must be %d digits' % (svalue,name,nd)) + self._bvalue = value + return value + binary = property(binary) + + def codewords(self): + '''convert binary value into codewords + >>> print(USPS_4State('01234567094987654321','01234567891').codewords) + (673, 787, 607, 1022, 861, 19, 816, 1294, 35, 602) + ''' + if not self._codewords: + value = self.binary + A, J = divmod(value,636) + A, I = divmod(A,1365) + A, H = divmod(A,1365) + A, G = divmod(A,1365) + A, F = divmod(A,1365) + A, E = divmod(A,1365) + A, D = divmod(A,1365) + A, C = divmod(A,1365) + A, B = divmod(A,1365) + assert 0<=A<=658, 'improper value %s passed to _2codewords A-->%s' % (hex(int(value)),A) + self._fcs = _crc11(value) + if self._fcs&1024: A += 659 + J *= 2 + self._codewords = tuple(map(int,(A,B,C,D,E,F,G,H,I,J))) + return self._codewords + codewords = property(codewords) + + + def table1(self): + self.__class__.table1 = _initNof13Table(5,1287) + return self.__class__.table1 + table1 = property(table1) + + def table2(self): + self.__class__.table2 = _initNof13Table(2,78) + return self.__class__.table2 + table2 = property(table2) + + def characters(self): + ''' convert own codewords to characters + >>> print(' '.join(hex(c)[2:] for c in USPS_4State('01234567094987654321','01234567891').characters)) + dcb 85c 8e4 b06 6dd 1740 17c6 1200 123f 1b2b + ''' + if not self._characters: + codewords = self.codewords + fcs = self._fcs + C = [] + aC = C.append + table1 = self.table1 + table2 = self.table2 + for i in range(10): + cw = codewords[i] + if cw<=1286: + c = table1[cw] + else: + c = table2[cw-1287] + if (fcs>>i)&1: + c = ~c & 0x1fff + aC(c) + self._characters = tuple(C) + return self._characters + characters = property(characters) + + def barcodes(self): + '''Get 4 state bar codes for current routing and tracking + >>> print(USPS_4State('01234567094987654321','01234567891').barcodes) + AADTFFDFTDADTAADAATFDTDDAAADDTDTTDAFADADDDTFFFDDTTTADFAAADFTDAADA + ''' + if not self._barcodes: + C = self.characters + B = [] + aB = B.append + bits2bars = self._bits2bars + for dc,db,ac,ab in self.table4: + aB(bits2bars[((C[dc]>>db)&1)+2*((C[ac]>>ab)&1)]) + self._barcodes = ''.join(B) + return self._barcodes + barcodes = property(barcodes) + + table4 = ((7, 2, 4, 3), (1, 10, 0, 0), (9, 12, 2, 8), (5, 5, 6, 11), + (8, 9, 3, 1), (0, 1, 5, 12), (2, 5, 1, 8), (4, 4, 9, 11), + (6, 3, 8, 10), (3, 9, 7, 6), (5, 11, 1, 4), (8, 5, 2, 12), + (9, 10, 0, 2), (7, 1, 6, 7), (3, 6, 4, 9), (0, 3, 8, 6), + (6, 4, 2, 7), (1, 1, 9, 9), (7, 10, 5, 2), (4, 0, 3, 8), + (6, 2, 0, 4), (8, 11, 1, 0), (9, 8, 3, 12), (2, 6, 7, 7), + (5, 1, 4, 10), (1, 12, 6, 9), (7, 3, 8, 0), (5, 8, 9, 7), + (4, 6, 2, 10), (3, 4, 0, 5), (8, 4, 5, 7), (7, 11, 1, 9), + (6, 0, 9, 6), (0, 6, 4, 8), (2, 1, 3, 2), (5, 9, 8, 12), + (4, 11, 6, 1), (9, 5, 7, 4), (3, 3, 1, 2), (0, 7, 2, 0), + (1, 3, 4, 1), (6, 10, 3, 5), (8, 7, 9, 4), (2, 11, 5, 6), + (0, 8, 7, 12), (4, 2, 8, 1), (5, 10, 3, 0), (9, 3, 0, 9), + (6, 5, 2, 4), (7, 8, 1, 7), (5, 0, 4, 5), (2, 3, 0, 10), + (6, 12, 9, 2), (3, 11, 1, 6), (8, 8, 7, 9), (5, 4, 0, 11), + (1, 5, 2, 2), (9, 1, 4, 12), (8, 3, 6, 6), (7, 0, 3, 7), + (4, 7, 7, 5), (0, 12, 1, 11), (2, 9, 9, 0), (6, 8, 5, 3), + (3, 10, 8, 2)) + + _bits2bars = 'T','D','A','F' + horizontalClearZone = property(lambda self: self.scale('hcz',self.dimensions,self.widthScale)) + verticalClearZone = property(lambda self: self.scale('vcz',self.dimensions,self.heightScale)) + + @property + def barWidth(self): + if '_barWidth' in self.__dict__: + return self.__dict__['_barWidth'] + return self.scale('width',self.dimensions,self.widthScale) + + @barWidth.setter + def barWidth(self,value): + n, x = self.dimensions['width'] + self.__dict__['_barWidth'] = 72*min(max(value/72.0,n),x) + + @property + def pitch(self): + if '_pitch' in self.__dict__: + return self.__dict__['_pitch'] + return self.scale('pitch',self.dimensions,self.widthScale) + + @pitch.setter + def pitch(self,value): + n, x = self.dimensions['pitch'] + self.__dict__['_pitch'] = 72*min(max(value/72.0,n),x) + + @property + def barHeight(self): + if '_barHeight' in self.__dict__: + return self.__dict__['_barHeight'] + return self.scale('F',self.tops,self.heightScale) - self.scale('F',self.bottoms,self.heightScale) + + @barHeight.setter + def barHeight(self,value): + n = self.tops['F'][0] - self.bottoms['F'][0] + x = self.tops['F'][1] - self.bottoms['F'][1] + value = self.__dict__['_barHeight'] = 72*min(max(value/72.0,n),x) + self.heightSize = (value - n)/(x-n) + + widthScale = property(lambda self: min(1,max(0,self.widthSize))) + heightScale = property(lambda self: min(1,max(0,self.heightSize))) + + @property + def width(self): + self.computeSize() + return self._width + + @property + def height(self): + self.computeSize() + return self._height + + #we ignore attempts to set the dimensions + @width.setter + def width(self,v): + pass + @height.setter + def height(self,v): + pass + + def computeSize(self): + if not getattr(self,'_sized',None): + ws = self.widthScale + hs = self.heightScale + barHeight = self.barHeight + barWidth = self.barWidth + pitch = self.pitch + hcz = self.horizontalClearZone + vcz = self.verticalClearZone + self._width = 2*hcz + barWidth + 64*pitch + self._height = 2*vcz+barHeight + if self.humanReadable: + self._height += self.fontSize*1.2+vcz + self._sized = True + + def wrap(self,aW,aH): + self.computeSize() + return self.width, self.height + + def _getBarVInfo(self,y0=0): + vInfo = {} + hs = self.heightScale + for b in ('T','D','A','F'): + y = self.scale(b,self.bottoms,hs)+y0 + vInfo[b] = y,self.scale(b,self.tops,hs)+y0 - y + return vInfo + + def draw(self): + self.computeSize() + hcz = self.horizontalClearZone + vcz = self.verticalClearZone + bw = self.barWidth + x = hcz + y0 = vcz+self.barHeight*0.5 + dw = self.pitch + vInfo = self._getBarVInfo(y0) + for b in self.barcodes: + yb, hb = vInfo[b] + self.rect(x,yb,bw,hb) + x += dw + self.drawHumanReadable() + + def value(self): + tracking = self.tracking + routing = self.routing + routing = routing and (routing,) or () + return ' '.join((tracking[0:2],tracking[2:5],tracking[5:11],tracking[11:])+routing) + value = property(value,lambda self,value: self.__dict__.__setitem__('tracking',value)) + + def drawHumanReadable(self): + if self.humanReadable: + hcz = self.horizontalClearZone + vcz = self.verticalClearZone + fontName = self.fontName + fontSize = self.fontSize + y = self.barHeight+2*vcz+0.2*fontSize + self.annotate(hcz,y,self.value,fontName,fontSize) + + def annotate(self,x,y,text,fontName,fontSize,anchor='middle'): + Barcode.annotate(self,x,y,text,fontName,fontSize,anchor='start') + +def _crc11(value): + ''' + >>> usps = [USPS_4State('01234567094987654321',x).binary for x in ('','01234','012345678','01234567891')] + >>> print(' '.join(nhex(x) for x in usps)) + 0x1122103b5c2004b1 0xd138a87bab5cf3804b1 0x202bdc097711204d21804b1 0x16907b2a24abc16a2e5c004b1 + >>> print(' '.join(nhex(_crc11(x)) for x in usps)) + 0x51 0x65 0x606 0x751 + ''' + hexbytes = nhex(int(value))[2:] + hexbytes = '0'*(26-len(hexbytes))+hexbytes + gp = 0x0F35 + fcs = 0x07FF + data = int(hexbytes[:2],16)<<5 + for b in range(2,8): + if (fcs ^ data)&0x400: + fcs = (fcs<<1)^gp + else: + fcs = fcs<<1 + fcs &= 0x7ff + data <<= 1 + + for x in range(2,2*13,2): + data = int(hexbytes[x:x+2],16)<<3 + for b in range(8): + if (fcs ^ data)&0x400: + fcs = (fcs<<1)^gp + else: + fcs = fcs<<1 + fcs &= 0x7ff + data <<= 1 + return fcs + +def _ru13(i): + '''reverse unsigned 13 bit number + >>> print(_ru13(7936), _ru13(31), _ru13(47), _ru13(7808)) + 31 7936 7808 47 + ''' + r = 0 + for x in range(13): + r <<= 1 + r |= i & 1 + i >>= 1 + return r + +def _initNof13Table(N,lenT): + '''create and return table of 13 bit values with N bits on + >>> T = _initNof13Table(5,1287) + >>> print(' '.join('T[%d]=%d' % (i, T[i]) for i in (0,1,2,3,4,1271,1272,1284,1285,1286))) + T[0]=31 T[1]=7936 T[2]=47 T[3]=7808 T[4]=55 T[1271]=6275 T[1272]=6211 T[1284]=856 T[1285]=744 T[1286]=496 + ''' + T = lenT*[None] + l = 0 + u = lenT-1 + for c in range(8192): + bc = 0 + for b in range(13): + bc += (c&(1< scale the value + otherwise use the absolute value + labelClass the label class to use default Label + all Label keywords are acceptable (including say _text) + ''' + def __init__(self,v,**kwds): + self._v = v + self._kwds = kwds + + def __call__(self,axis): + kwds = self._kwds.copy() + labelClass = kwds.pop('labelClass',Label) + scaleValue = kwds.pop('scaleValue',True) + if not hasattr(axis,'_tickValues'): + axis._pseudo_configure() + sv = (axis.scale if scaleValue else lambda x: x)(self._v) + if axis.isYAxis: + x = axis._x + y = sv + else: + x = sv + y = axis._y + kwds['x'] = x + kwds['y'] = y + return labelClass(**kwds) + +class AxisLineAnnotation: + '''Create a grid like line using the given user value to draw the line + kwds may contain + startOffset if true v is offset from the default grid start position + endOffset if true v is offset from the default grid end position + scaleValue True/not given --> scale the value + otherwise use the absolute value + lo lowest coordinate to draw default 0 + hi highest coordinate to draw at default = length + drawAtLimit True draw line at appropriate limit if its coordinate exceeds the lo, hi range + False ignore if it's outside the range + all Line keywords are acceptable + ''' + def __init__(self,v,**kwds): + self._v = v + self._kwds = kwds + + def __call__(self,axis): + kwds = self._kwds.copy() + scaleValue = kwds.pop('scaleValue',True) + endOffset = kwds.pop('endOffset',False) + startOffset = kwds.pop('startOffset',False) + if axis.isYAxis: + offs = axis._x + d0 = axis._y + else: + offs = axis._y + d0 = axis._x + s = kwds.pop('start',None) + e = kwds.pop('end',None) + if s is None or e is None: + dim = getattr(getattr(axis,'joinAxis',None),'getGridDims',None) + if dim and hasattr(dim,'__call__'): + dim = dim() + if dim: + if s is None: s = dim[0] + if e is None: e = dim[1] + else: + if s is None: s = 0 + if e is None: e = 0 + hi = kwds.pop('hi',axis._length)+d0 + lo = kwds.pop('lo',0)+d0 + lo,hi=min(lo,hi),max(lo,hi) + drawAtLimit = kwds.pop('drawAtLimit',False) + oaglp = axis._get_line_pos + if not scaleValue: + axis._get_line_pos = lambda x: x + try: + v = self._v + if endOffset: + v = v + hi + elif startOffset: + v = v + lo + func = axis._getLineFunc(s-offs,e-offs,kwds.pop('parent',None)) + if not hasattr(axis,'_tickValues'): + axis._pseudo_configure() + d = axis._get_line_pos(v) + if dhi: + if not drawAtLimit: return None + if d d={d} L={L}') + finally: + axis._get_line_pos = oaglp + return L + +class AxisBackgroundAnnotation: + '''Create a set of coloured bars on the background of a chart using axis ticks as the bar borders + colors is a set of colors to use for the background bars. A colour of None is just a skip. + Special effects if you pass a rect or Shaded rect instead. + ''' + def __init__(self,colors,**kwds): + self._colors = colors + self._kwds = kwds + + def __call__(self,axis): + colors = self._colors + if not colors: return + kwds = self._kwds.copy() + isYAxis = axis.isYAxis + if isYAxis: + offs = axis._x + d0 = axis._y + else: + offs = axis._y + d0 = axis._x + s = kwds.pop('start',None) + e = kwds.pop('end',None) + if s is None or e is None: + dim = getattr(getattr(axis,'joinAxis',None),'getGridDims',None) + if dim and hasattr(dim,'__call__'): + dim = dim() + if dim: + if s is None: s = dim[0] + if e is None: e = dim[1] + else: + if s is None: s = 0 + if e is None: e = 0 + if not hasattr(axis,'_tickValues'): + axis._pseudo_configure() + tv = getattr(axis,'_tickValues',None) + if not tv: return + G = Group() + ncolors = len(colors) + v0 = axis._get_line_pos(tv[0]) + for i in range(1,len(tv)): + v1 = axis._get_line_pos(tv[i]) + c = colors[(i-1)%ncolors] + if c: + if isYAxis: + y = v0 + x = s + height = v1-v0 + width = e-s + else: + x = v0 + y = s + width = v1-v0 + height = e-s + if isinstance(c,Color): + r = Rect(x,y,width,height,fillColor=c,strokeColor=None) + elif isinstance(c,Rect): + r = Rect(x,y,width,height) + for k in c.__dict__: + if k not in ('x','y','width','height'): + setattr(r,k,getattr(c,k)) + elif isinstance(c,ShadedRect): + r = ShadedRect(x=x,y=y,width=width,height=height) + for k in c.__dict__: + if k not in ('x','y','width','height'): + setattr(r,k,getattr(c,k)) + G.add(r) + v0 = v1 + return G + +class TickLU: + '''lookup special cases for tick values''' + def __init__(self,*T,**kwds): + self.accuracy = kwds.pop('accuracy',1e-8) + self.T = T + def __contains__(self,t): + accuracy = self.accuracy + for x,v in self.T: + if abs(x-t)0): return + c = self.subGridStrokeColor + w = self.subGridStrokeWidth or 0 + if not(w and c): return + s = self.subGridStart + e = self.subGridEnd + if s is None or e is None: + if dim and hasattr(dim,'__call__'): + dim = dim() + if dim: + if s is None: s = dim[0] + if e is None: e = dim[1] + else: + if s is None: s = 0 + if e is None: e = 0 + if s or e: + if self.isYAxis: offs = self._x + else: offs = self._y + otv = self._calcSubTicks() + try: + self._makeLines(g,s-offs,e-offs,c,w,self.subGridStrokeDashArray,self.subGridStrokeLineJoin,self.subGridStrokeLineCap,self.subGridStrokeMiterLimit,parent=parent,exclude=exclude) + finally: + self._tickValues = otv + + def getGridDims(self,start=None,end=None): + if start is None: start = (self._x,self._y)[self.isYAxis] + if end is None: end = start+self._length + return start,end + + def isYAxis(self): + if getattr(self,'_dataIndex',None)==1: return True + acn = self.__class__.__name__ + return acn[0]=='Y' or acn[:4]=='AdjY' + isYAxis = property(isYAxis) + + def isXAxis(self): + if getattr(self,'_dataIndex',None)==0: return True + acn = self.__class__.__name__ + return acn[0]=='X' or acn[:11]=='NormalDateX' + isXAxis = property(isXAxis) + + def addAnnotations(self,g,A=None): + if A is None: getattr(self,'annotations',[]) + for x in A: + g.add(x(self)) + + def _splitAnnotations(self): + A = getattr(self,'annotations',[])[:] + D = {} + for v in ('early','beforeAxis','afterAxis','beforeTicks', + 'afterTicks','beforeTickLabels', + 'afterTickLabels','late'): + R = [].append + P = [].append + for a in A: + if getattr(a,v,0): + R(a) + else: + P(a) + D[v] = R.__self__ + A[:] = P.__self__ + D['late'] += A + return D + + def draw(self): + g = Group() + A = self._splitAnnotations() + self.addAnnotations(g,A['early']) + + if self.visible: + self.addAnnotations(g,A['beforeAxis']) + g.add(self.makeAxis()) + self.addAnnotations(g,A['afterAxis']) + self.addAnnotations(g,A['beforeTicks']) + g.add(self.makeTicks()) + self.addAnnotations(g,A['afterTicks']) + self.addAnnotations(g,A['beforeTickLabels']) + g.add(self.makeTickLabels()) + self.addAnnotations(g,A['afterTickLabels']) + + self.addAnnotations(g,A['late']) + return g + +class CALabel(PMVLabel): + _attrMap = AttrMap(BASE=PMVLabel, + labelPosFrac = AttrMapValue(isNumber, desc='where in the category range [0,1] the labels should be anchored'), + ) + def __init__(self,**kw): + PMVLabel.__init__(self,**kw) + self._setKeywords( + labelPosFrac = 0.5, + ) + +# Category axes. +class CategoryAxis(_AxisG): + "Abstract category axis, unusable in itself." + _nodoc = 1 + _attrMap = AttrMap( + visible = AttrMapValue(isBoolean, desc='Display entire object, if true.'), + visibleAxis = AttrMapValue(isBoolean, desc='Display axis line, if true.'), + visibleTicks = AttrMapValue(isBoolean, desc='Display axis ticks, if true.'), + visibleLabels = AttrMapValue(isBoolean, desc='Display axis labels, if true.'), + visibleGrid = AttrMapValue(isBoolean, desc='Display axis grid, if true.'), + strokeWidth = AttrMapValue(isNumber, desc='Width of axis line and ticks.'), + strokeColor = AttrMapValue(isColorOrNone, desc='Color of axis line and ticks.'), + strokeDashArray = AttrMapValue(isListOfNumbersOrNone, desc='Dash array used for axis line.'), + strokeLineCap = AttrMapValue(OneOf(0,1,2),desc="Line cap 0=butt, 1=round & 2=square"), + strokeLineJoin = AttrMapValue(OneOf(0,1,2),desc="Line join 0=miter, 1=round & 2=bevel"), + strokeMiterLimit = AttrMapValue(isNumber,desc="miter limit control miter line joins"), + gridStrokeWidth = AttrMapValue(isNumber, desc='Width of grid lines.'), + gridStrokeColor = AttrMapValue(isColorOrNone, desc='Color of grid lines.'), + gridStrokeDashArray = AttrMapValue(isListOfNumbersOrNone, desc='Dash array used for grid lines.'), + gridStrokeLineCap = AttrMapValue(OneOf(0,1,2),desc="Grid Line cap 0=butt, 1=round & 2=square"), + gridStrokeLineJoin = AttrMapValue(OneOf(0,1,2),desc="Grid Line join 0=miter, 1=round & 2=bevel"), + gridStrokeMiterLimit = AttrMapValue(isNumber,desc="Grid miter limit control miter line joins"), + gridStart = AttrMapValue(isNumberOrNone, desc='Start of grid lines wrt axis origin'), + gridEnd = AttrMapValue(isNumberOrNone, desc='End of grid lines wrt axis origin'), + drawGridLast = AttrMapValue(isBoolean, desc='if true draw gridlines after everything else.'), + labels = AttrMapValue(None, desc='Handle of the axis labels.'), + categoryNames = AttrMapValue(isListOfStringsOrNone, desc='List of category names.'), + joinAxis = AttrMapValue(None, desc='Join both axes if true.'), + joinAxisPos = AttrMapValue(isNumberOrNone, desc='Position at which to join with other axis.'), + reverseDirection = AttrMapValue(isBoolean, desc='If true reverse category direction.'), + style = AttrMapValue(OneOf('parallel','stacked','parallel_3d'),"How common category bars are plotted"), + labelAxisMode = AttrMapValue(OneOf('high','low','axis', 'axispmv'), desc="Like joinAxisMode, but for the axis labels"), + tickShift = AttrMapValue(isBoolean, desc='Tick shift typically'), + tickStrokeWidth = AttrMapValue(isNumberOrNone, desc='Width of ticks if specified.'), + tickStrokeColor = AttrMapValue(isColorOrNone, desc='Color of ticks if specified.'), + loPad = AttrMapValue(isNumber, desc='extra inner space before start of the axis'), + hiPad = AttrMapValue(isNumber, desc='extra inner space after end of the axis'), + annotations = AttrMapValue(None,desc='list of annotations'), + loLLen = AttrMapValue(isNumber, desc='extra line length before start of the axis'), + hiLLen = AttrMapValue(isNumber, desc='extra line length after end of the axis'), + skipGrid = AttrMapValue(OneOf('none','top','both','bottom'),"grid lines to skip top bottom both none"), + innerTickDraw = AttrMapValue(isNoneOrCallable, desc="Callable to replace _drawInnerTicks"), + ) + + def __init__(self): + assert self.__class__.__name__!='CategoryAxis', "Abstract Class CategoryAxis Instantiated" + # private properties set by methods. The initial values + # here are to make demos easy; they would always be + # overridden in real life. + self._x = 50 + self._y = 50 + self._length = 100 + self._catCount = 0 + + # public properties + self.visible = 1 + self.visibleAxis = 1 + self.visibleTicks = 1 + self.visibleLabels = 1 + self.visibleGrid = 0 + self.drawGridLast = False + + self.strokeWidth = 1 + self.strokeColor = STATE_DEFAULTS['strokeColor'] + self.strokeDashArray = STATE_DEFAULTS['strokeDashArray'] + + self.gridStrokeLineJoin = self.strokeLineJoin = STATE_DEFAULTS['strokeLineJoin'] + self.gridStrokeLineCap = self.strokeLineCap = STATE_DEFAULTS['strokeLineCap'] + self.gridStrokeMiterLimit = self.strokeMiterLimit = STATE_DEFAULTS['strokeMiterLimit'] + self.gridStrokeWidth = 0.25 + self.gridStrokeColor = STATE_DEFAULTS['strokeColor'] + self.gridStrokeDashArray = STATE_DEFAULTS['strokeDashArray'] + self.gridStart = self.gridEnd = None + + self.strokeLineJoin = STATE_DEFAULTS['strokeLineJoin'] + self.strokeLineCap = STATE_DEFAULTS['strokeLineCap'] + self.strokeMiterLimit = STATE_DEFAULTS['strokeMiterLimit'] + + self.labels = TypedPropertyCollection(CALabel) + # if None, they don't get labels. If provided, + # you need one name per data point and they are + # used for label text. + self.categoryNames = None + self.joinAxis = None + self.joinAxisPos = None + self.joinAxisMode = None + self.labelAxisMode = 'axis' + self.reverseDirection = 0 + self.style = 'parallel' + + #various private things which need to be initialized + self._labelTextFormat = None + self.tickShift = 0 + self.loPad = 0 + self.hiPad = 0 + self.loLLen = 0 + self.hiLLen = 0 + + def setPosition(self, x, y, length): + # ensure floating point + self._x = float(x) + self._y = float(y) + self._length = float(length) + + def configure(self, multiSeries,barWidth=None): + self._catCount = max(list(map(len,multiSeries))) + self._barWidth = barWidth or ((self._length-self.loPad-self.hiPad)/float(self._catCount or 1)) + self._calcTickmarkPositions() + if self.labelAxisMode == 'axispmv': + self._pmv = [sum([series[i] for series in multiSeries]) for i in range(self._catCount)] + + def _calcTickmarkPositions(self): + n = self._catCount + if self.tickShift: + self._tickValues = [t+0.5 for t in range(n)] + else: + if self.reverseDirection: + self._tickValues = list(range(-1,n)) + else: + self._tickValues = list(range(n+1)) + + def _scale(self,idx): + if self.reverseDirection: idx = self._catCount-idx-1 + return idx + + def scale(self, idx): + "Returns the position and width in drawing units" + return (self.loScale(idx), self._barWidth) + + def midScale(self, idx): + "Returns the bar mid position in drawing units" + return self.loScale(idx) + 0.5*self._barWidth + +def _assertYAxis(axis): + assert axis.isYAxis, "Cannot connect to other axes (%s), but Y- ones." % axis.__class__.__name__ +def _assertXAxis(axis): + assert axis.isXAxis, "Cannot connect to other axes (%s), but X- ones." % axis.__class__.__name__ + +class _XTicks: + _tickTweaks = 0 #try 0.25-0.5 + + @property + def actualTickStrokeWidth(self): + return getattr(self,'tickStrokeWidth',self.strokeWidth) + + @property + def actualTickStrokeColor(self): + return getattr(self,'tickStrokeColor',self.strokeColor) + + def _drawTicksInner(self,tU,tD,g): + itd = getattr(self,'innerTickDraw',None) + if itd: + itd(self,tU,tD,g) + elif tU or tD: + sW = self.actualTickStrokeWidth + tW = self._tickTweaks + if tW: + if tU and not tD: + tD = tW*sW + elif tD and not tU: + tU = tW*sW + self._makeLines(g,tU,-tD,self.actualTickStrokeColor,sW,self.strokeDashArray,self.strokeLineJoin,self.strokeLineCap,self.strokeMiterLimit) + + def _drawTicks(self,tU,tD,g=None): + g = g or Group() + if self.visibleTicks: + self._drawTicksInner(tU,tD,g) + return g + + def _drawSubTicks(self,tU,tD,g): + if getattr(self,'visibleSubTicks',0) and self.subTickNum>0: + otv = self._calcSubTicks() + try: + self._subTicking = 1 + self._drawTicksInner(tU,tD,g) + finally: + del self._subTicking + self._tickValues = otv + + def makeTicks(self): + yold=self._y + try: + self._y = self._labelAxisPos(getattr(self,'tickAxisMode','axis')) + g = self._drawTicks(self.tickUp,self.tickDown) + self._drawSubTicks(getattr(self,'subTickHi',0),getattr(self,'subTickLo',0),g) + return g + finally: + self._y = yold + + def _labelAxisPos(self,mode=None): + axis = self.joinAxis + if axis: + mode = mode or self.labelAxisMode + if mode == 'low': + return axis._y + elif mode == 'high': + return axis._y + axis._length + return self._y + +class _YTicks(_XTicks): + + def _labelAxisPos(self,mode=None): + axis = self.joinAxis + if axis: + mode = mode or self.labelAxisMode + if mode == 'low': + return axis._x + elif mode == 'high': + return axis._x + axis._length + return self._x + + def makeTicks(self): + xold=self._x + try: + self._x = self._labelAxisPos(getattr(self,'tickAxisMode','axis')) + g = self._drawTicks(self.tickRight,self.tickLeft) + self._drawSubTicks(getattr(self,'subTickHi',0),getattr(self,'subTickLo',0),g) + return g + finally: + self._x = xold + +class XCategoryAxis(_XTicks,CategoryAxis): + "X/category axis" + + _attrMap = AttrMap(BASE=CategoryAxis, + tickUp = AttrMapValue(isNumber, + desc='Tick length up the axis.'), + tickDown = AttrMapValue(isNumber, + desc='Tick length down the axis.'), + joinAxisMode = AttrMapValue(OneOf('bottom', 'top', 'value', 'points', None), + desc="Mode used for connecting axis ('bottom', 'top', 'value', 'points', None)."), + ) + + _dataIndex = 0 + + def __init__(self): + CategoryAxis.__init__(self) + self.labels.boxAnchor = 'n' #north - top edge + self.labels.dy = -5 + # ultra-simple tick marks for now go between categories + # and have same line style as axis - need more + self.tickUp = 0 # how far into chart does tick go? + self.tickDown = 5 # how far below axis does tick go? + + def demo(self): + self.setPosition(30, 70, 140) + self.configure([(10,20,30,40,50)]) + + self.categoryNames = ['One','Two','Three','Four','Five'] + # all labels top-centre aligned apart from the last + self.labels.boxAnchor = 'n' + self.labels[4].boxAnchor = 'e' + self.labels[4].angle = 90 + + d = Drawing(200, 100) + d.add(self) + return d + + def joinToAxis(self, yAxis, mode='bottom', pos=None): + "Join with y-axis using some mode." + _assertYAxis(yAxis) + if mode == 'bottom': + self._y = yAxis._y + elif mode == 'top': + self._y = yAxis._y + yAxis._length + elif mode == 'value': + self._y = yAxis.scale(pos) + elif mode == 'points': + self._y = pos + + def _joinToAxis(self): + ja = self.joinAxis + if ja: + jam = self.joinAxisMode + if jam in ('bottom', 'top'): + self.joinToAxis(ja, mode=jam) + elif jam in ('value', 'points'): + self.joinToAxis(ja, mode=jam, pos=self.joinAxisPos) + + def loScale(self, idx): + """returns the x position in drawing units""" + return self._x + self.loPad + self._scale(idx)*self._barWidth + + def makeAxis(self): + g = Group() + self._joinToAxis() + if not self.visibleAxis: return g + + axis = Line(self._x-self.loLLen, self._y, self._x + self._length+self.hiLLen, self._y) + axis.strokeColor = self.strokeColor + axis.strokeWidth = self.strokeWidth + axis.strokeDashArray = self.strokeDashArray + g.add(axis) + + return g + + def makeTickLabels(self): + g = Group() + + if not self.visibleLabels: return g + + categoryNames = self.categoryNames + if categoryNames is not None: + catCount = self._catCount + n = len(categoryNames) + reverseDirection = self.reverseDirection + barWidth = self._barWidth + _y = self._labelAxisPos() + _x = self._x + pmv = self._pmv if self.labelAxisMode=='axispmv' else None + + for i in range(catCount): + if reverseDirection: ic = catCount-i-1 + else: ic = i + if ic>=n: continue + label=i-catCount + if label in self.labels: + label = self.labels[label] + else: + label = self.labels[i] + if pmv: + _dy = label.dy + v = label._pmv = pmv[ic] + if v<0: _dy *= -2 + else: + _dy = 0 + lpf = label.labelPosFrac + x = _x + (i+lpf) * barWidth + label.setOrigin(x,_y+_dy) + label.setText(categoryNames[ic] or '') + g.add(label) + + return g + +class YCategoryAxis(_YTicks,CategoryAxis): + "Y/category axis" + + _attrMap = AttrMap(BASE=CategoryAxis, + tickLeft = AttrMapValue(isNumber, + desc='Tick length left of the axis.'), + tickRight = AttrMapValue(isNumber, + desc='Tick length right of the axis.'), + joinAxisMode = AttrMapValue(OneOf(('left', 'right', 'value', 'points', None)), + desc="Mode used for connecting axis ('left', 'right', 'value', 'points', None)."), + ) + + _dataIndex = 1 + + def __init__(self): + CategoryAxis.__init__(self) + self.labels.boxAnchor = 'e' #east - right edge + self.labels.dx = -5 + # ultra-simple tick marks for now go between categories + # and have same line style as axis - need more + self.tickLeft = 5 # how far left of axis does tick go? + self.tickRight = 0 # how far right of axis does tick go? + + def demo(self): + self.setPosition(50, 10, 80) + self.configure([(10,20,30)]) + self.categoryNames = ['One','Two','Three'] + # all labels top-centre aligned apart from the last + self.labels.boxAnchor = 'e' + self.labels[2].boxAnchor = 's' + self.labels[2].angle = 90 + + d = Drawing(200, 100) + d.add(self) + return d + + def joinToAxis(self, xAxis, mode='left', pos=None): + "Join with x-axis using some mode." + + _assertXAxis(xAxis) + if mode == 'left': + self._x = xAxis._x * 1.0 + elif mode == 'right': + self._x = (xAxis._x + xAxis._length) * 1.0 + elif mode == 'value': + self._x = xAxis.scale(pos) * 1.0 + elif mode == 'points': + self._x = pos * 1.0 + + def _joinToAxis(self): + ja = self.joinAxis + if ja: + jam = self.joinAxisMode + if jam in ('left', 'right'): + self.joinToAxis(ja, mode=jam) + elif jam in ('value', 'points'): + self.joinToAxis(ja, mode=jam, pos=self.joinAxisPos) + + def loScale(self, idx): + "Returns the y position in drawing units" + return self._y + self._scale(idx)*self._barWidth + + def makeAxis(self): + g = Group() + self._joinToAxis() + if not self.visibleAxis: return g + + axis = Line(self._x, self._y-self.loLLen, self._x, self._y + self._length+self.hiLLen) + axis.strokeColor = self.strokeColor + axis.strokeWidth = self.strokeWidth + axis.strokeDashArray = self.strokeDashArray + g.add(axis) + + return g + + def makeTickLabels(self): + g = Group() + + if not self.visibleLabels: return g + + categoryNames = self.categoryNames + if categoryNames is not None: + catCount = self._catCount + n = len(categoryNames) + reverseDirection = self.reverseDirection + barWidth = self._barWidth + labels = self.labels + _x = self._labelAxisPos() + _y = self._y + pmv = self._pmv if self.labelAxisMode=='axispmv' else None + + for i in range(catCount): + if reverseDirection: ic = catCount-i-1 + else: ic = i + if ic>=n: continue + label=i-catCount + if label in self.labels: + label = self.labels[label] + else: + label = self.labels[i] + lpf = label.labelPosFrac + y = _y + (i+lpf) * barWidth + if pmv: + _dx = label.dx + v = label._pmv = pmv[ic] + if v<0: _dx *= -2 + else: + _dx = 0 + label.setOrigin(_x+_dx, y) + label.setText(categoryNames[ic] or '') + g.add(label) + return g + +class TickLabeller: + '''Abstract base class which may be used to indicate a change + in the call signature for callable label formats + ''' + def __call__(self,axis,value): + return 'Abstract class instance called' + +#this matches the old python str behaviour +_defaultLabelFormatter = lambda x: '%.12g' % x + +# Value axes. +class ValueAxis(_AxisG): + "Abstract value axis, unusable in itself." + + _attrMap = AttrMap( + forceZero = AttrMapValue(EitherOr((isBoolean,OneOf('near'))), desc='Ensure zero in range if true.'), + visible = AttrMapValue(isBoolean, desc='Display entire object, if true.'), + visibleAxis = AttrMapValue(isBoolean, desc='Display axis line, if true.'), + visibleLabels = AttrMapValue(isBoolean, desc='Display axis labels, if true.'), + visibleTicks = AttrMapValue(isBoolean, desc='Display axis ticks, if true.'), + visibleGrid = AttrMapValue(isBoolean, desc='Display axis grid, if true.'), + strokeWidth = AttrMapValue(isNumber, desc='Width of axis line and ticks.'), + strokeColor = AttrMapValue(isColorOrNone, desc='Color of axis line and ticks.'), + strokeDashArray = AttrMapValue(isListOfNumbersOrNone, desc='Dash array used for axis line.'), + strokeLineCap = AttrMapValue(OneOf(0,1,2),desc="Line cap 0=butt, 1=round & 2=square"), + strokeLineJoin = AttrMapValue(OneOf(0,1,2),desc="Line join 0=miter, 1=round & 2=bevel"), + strokeMiterLimit = AttrMapValue(isNumber,desc="miter limit control miter line joins"), + gridStrokeWidth = AttrMapValue(isNumber, desc='Width of grid lines.'), + gridStrokeColor = AttrMapValue(isColorOrNone, desc='Color of grid lines.'), + gridStrokeDashArray = AttrMapValue(isListOfNumbersOrNone, desc='Dash array used for grid lines.'), + gridStrokeLineCap = AttrMapValue(OneOf(0,1,2),desc="Grid Line cap 0=butt, 1=round & 2=square"), + gridStrokeLineJoin = AttrMapValue(OneOf(0,1,2),desc="Grid Line join 0=miter, 1=round & 2=bevel"), + gridStrokeMiterLimit = AttrMapValue(isNumber,desc="Grid miter limit control miter line joins"), + gridStart = AttrMapValue(isNumberOrNone, desc='Start of grid lines wrt axis origin'), + gridEnd = AttrMapValue(isNumberOrNone, desc='End of grid lines wrt axis origin'), + drawGridLast = AttrMapValue(isBoolean, desc='if true draw gridlines after everything else.'), + minimumTickSpacing = AttrMapValue(isNumber, desc='Minimum value for distance between ticks.'), + maximumTicks = AttrMapValue(isNumber, desc='Maximum number of ticks.'), + labels = AttrMapValue(None, desc='Handle of the axis labels.'), + labelAxisMode = AttrMapValue(OneOf('high','low','axis'), desc="Like joinAxisMode, but for the axis labels"), + labelTextFormat = AttrMapValue(None, desc='Formatting string or function used for axis labels.'), + labelTextPostFormat = AttrMapValue(None, desc='Extra Formatting string.'), + labelTextScale = AttrMapValue(isNumberOrNone, desc='Scaling for label tick values.'), + valueMin = AttrMapValue(isNumberOrNone, desc='Minimum value on axis.'), + valueMax = AttrMapValue(isNumberOrNone, desc='Maximum value on axis.'), + valueStep = AttrMapValue(isNumberOrNone, desc='Step size used between ticks.'), + valueSteps = AttrMapValue(isListOfNumbersOrNone, desc='List of step sizes used between ticks.'), + avoidBoundFrac = AttrMapValue(EitherOr((isNumberOrNone,SequenceOf(isNumber,emptyOK=0,lo=2,hi=2))), desc='Fraction of interval to allow above and below.'), + avoidBoundSpace = AttrMapValue(EitherOr((isNumberOrNone,SequenceOf(isNumber,emptyOK=0,lo=2,hi=2))), desc='Space to allow above and below.'), + abf_ignore_zero = AttrMapValue(EitherOr((NoneOr(isBoolean),SequenceOf(isBoolean,emptyOK=0,lo=2,hi=2))), desc='Set to True to make the avoidBoundFrac calculations treat zero as non-special'), + rangeRound=AttrMapValue(OneOf('none','both','ceiling','floor'),'How to round the axis limits'), + zrangePref = AttrMapValue(isNumberOrNone, desc='Zero range axis limit preference.'), + style = AttrMapValue(OneOf('normal','stacked','parallel_3d'),"How values are plotted!"), + skipEndL = AttrMapValue(OneOf('none','start','end','both'), desc='Skip high/low tick labels'), + origShiftIPC = AttrMapValue(isNumberOrNone, desc='Lowest label shift interval ratio.'), + origShiftMin = AttrMapValue(isNumberOrNone, desc='Minimum amount to shift.'), + origShiftSpecialValue = AttrMapValue(isNumberOrNone, desc='special value for shift'), + tickAxisMode = AttrMapValue(OneOf('high','low','axis'), desc="Like joinAxisMode, but for the ticks"), + reverseDirection = AttrMapValue(isBoolean, desc='If true reverse category direction.'), + annotations = AttrMapValue(None,desc='list of annotations'), + loLLen = AttrMapValue(isNumber, desc='extra line length before start of the axis'), + hiLLen = AttrMapValue(isNumber, desc='extra line length after end of the axis'), + subTickNum = AttrMapValue(isNumber, desc='Number of axis sub ticks, if >0'), + subTickLo = AttrMapValue(isNumber, desc='sub tick down or left'), + subTickHi = AttrMapValue(isNumber, desc='sub tick up or right'), + visibleSubTicks = AttrMapValue(isBoolean, desc='Display axis sub ticks, if true.'), + visibleSubGrid = AttrMapValue(isBoolean, desc='Display axis sub grid, if true.'), + subGridStrokeWidth = AttrMapValue(isNumber, desc='Width of grid lines.'), + subGridStrokeColor = AttrMapValue(isColorOrNone, desc='Color of grid lines.'), + subGridStrokeDashArray = AttrMapValue(isListOfNumbersOrNone, desc='Dash array used for grid lines.'), + subGridStrokeLineCap = AttrMapValue(OneOf(0,1,2),desc="Grid Line cap 0=butt, 1=round & 2=square"), + subGridStrokeLineJoin = AttrMapValue(OneOf(0,1,2),desc="Grid Line join 0=miter, 1=round & 2=bevel"), + subGridStrokeMiterLimit = AttrMapValue(isNumber,desc="Grid miter limit control miter line joins"), + subGridStart = AttrMapValue(isNumberOrNone, desc='Start of grid lines wrt axis origin'), + subGridEnd = AttrMapValue(isNumberOrNone, desc='End of grid lines wrt axis origin'), + tickStrokeWidth = AttrMapValue(isNumber, desc='Width of ticks if specified.'), + subTickStrokeWidth = AttrMapValue(isNumber, desc='Width of sub ticks if specified.'), + subTickStrokeColor = AttrMapValue(isColorOrNone, desc='Color of sub ticks if specified.'), + tickStrokeColor = AttrMapValue(isColorOrNone, desc='Color of ticks if specified.'), + keepTickLabelsInside = AttrMapValue(isBoolean, desc='Ensure tick labels do not project beyond bounds of axis if true'), + skipGrid = AttrMapValue(OneOf('none','top','both','bottom'),"grid lines to skip top bottom both none"), + requiredRange = AttrMapValue(isNumberOrNone, desc='Minimum required value range.'), + innerTickDraw = AttrMapValue(isNoneOrCallable, desc="Callable to replace _drawInnerTicks"), + extraMinMaxValues = AttrMapValue(isListOfNumbersOrNone, desc='extra values to use in min max calculation'), + ) + + def __init__(self,**kw): + assert self.__class__.__name__!='ValueAxis', 'Abstract Class ValueAxis Instantiated' + self._setKeywords(**kw) + self._setKeywords( + _configured = 0, + # private properties set by methods. The initial values + # here are to make demos easy; they would always be + # overridden in real life. + _x = 50, + _y = 50, + _length = 100, + + # public properties + visible = 1, + visibleAxis = 1, + visibleLabels = 1, + visibleTicks = 1, + visibleGrid = 0, + forceZero = 0, + + strokeWidth = 1, + strokeColor = STATE_DEFAULTS['strokeColor'], + strokeDashArray = STATE_DEFAULTS['strokeDashArray'], + strokeLineJoin = STATE_DEFAULTS['strokeLineJoin'], + strokeLineCap = STATE_DEFAULTS['strokeLineCap'], + strokeMiterLimit = STATE_DEFAULTS['strokeMiterLimit'], + gridStrokeWidth = 0.25, + gridStrokeColor = STATE_DEFAULTS['strokeColor'], + gridStrokeDashArray = STATE_DEFAULTS['strokeDashArray'], + gridStrokeLineJoin = STATE_DEFAULTS['strokeLineJoin'], + gridStrokeLineCap = STATE_DEFAULTS['strokeLineCap'], + gridStrokeMiterLimit = STATE_DEFAULTS['strokeMiterLimit'], + gridStart = None, + gridEnd = None, + drawGridLast = False, + visibleSubGrid = 0, + visibleSubTicks = 0, + subTickNum = 0, + subTickLo = 0, + subTickHi = 0, + subGridStrokeLineJoin = STATE_DEFAULTS['strokeLineJoin'], + subGridStrokeLineCap = STATE_DEFAULTS['strokeLineCap'], + subGridStrokeMiterLimit = STATE_DEFAULTS['strokeMiterLimit'], + subGridStrokeWidth = 0.25, + subGridStrokeColor = STATE_DEFAULTS['strokeColor'], + subGridStrokeDashArray = STATE_DEFAULTS['strokeDashArray'], + subGridStart = None, + subGridEnd = None, + labels = TypedPropertyCollection(Label), + keepTickLabelsInside = 0, + + # how close can the ticks be? + minimumTickSpacing = 10, + maximumTicks = 7, + + # a format string like '%0.2f' + # or a function which takes the value as an argument and returns a string + _labelTextFormat = None, + labelAxisMode = 'axis', + labelTextFormat = None, + labelTextPostFormat = None, + labelTextScale = None, + + # if set to None, these will be worked out for you. + # if you override any or all of them, your values + # will be used. + valueMin = None, + valueMax = None, + valueStep = None, + avoidBoundFrac = None, + avoidBoundSpace = None, + abf_ignore_zero = False, + rangeRound = 'none', + zrangePref = 0, + style = 'normal', + skipEndL='none', + origShiftIPC = None, + origShiftMin = None, + origShiftSpecialValue = None, + tickAxisMode = 'axis', + reverseDirection=0, + loLLen=0, + hiLLen=0, + requiredRange=0, + extraMinMaxValues=None, + ) + self.labels.angle = 0 + + def setPosition(self, x, y, length): + # ensure floating point + self._x = float(x) + self._y = float(y) + self._length = float(length) + + def configure(self, dataSeries): + """Let the axis configure its scale and range based on the data. + + Called after setPosition. Let it look at a list of lists of + numbers determine the tick mark intervals. If valueMin, + valueMax and valueStep are configured then it + will use them; if any of them are set to None it + will look at the data and make some sensible decision. + You may override this to build custom axes with + irregular intervals. It creates an internal + variable self._values, which is a list of numbers + to use in plotting. + """ + self._setRange(dataSeries) + self._configure_end() + + def _configure_end(self): + self._calcTickmarkPositions() + self._calcScaleFactor() + self._configured = 1 + + @lru_cache() + def _getValueStepAndTicks(self, valueMin, valueMax): + self._valueMin = valueMin + self._valueMax = valueMax + valueStep,T = self._calcStepAndTickPositions() + return valueStep, T, valueStep*1e-8 + + def _preRangeAdjust(self,valueMin,valueMax): + rr = self.requiredRange + if rr>0: + r = valueMax - valueMin + if r=100 and y1<100: + y2 = y2 + 100 - y1 + y1 = 100 + elif valueMin>=0 and y1<0: + y2 = y2 - y1 + y1 = 0 + valueMin = self._cValueMin = y1 + valueMax = self._cValueMax = y2 + return valueMin,valueMax + + + def _setRange(self, dataSeries): + """Set minimum and maximum axis values. + + The dataSeries argument is assumed to be a list of data + vectors. Each vector is itself a list or tuple of numbers. + + Returns a min, max tuple. + """ + + oMin = valueMin = self.valueMin + oMax = valueMax = self.valueMax + if valueMin is None: valueMin = self._cValueMin = _findMin(dataSeries,self._dataIndex,0, self.extraMinMaxValues) + if valueMax is None: valueMax = self._cValueMax = _findMax(dataSeries,self._dataIndex,0, self.extraMinMaxValues) + if valueMin == valueMax: + if valueMax==0: + if oMin is None and oMax is None: + zrp = getattr(self,'zrangePref',0) + if zrp>0: + valueMax = zrp + valueMin = 0 + elif zrp<0: + valueMax = 0 + valueMin = zrp + else: + valueMax = 0.01 + valueMin = -0.01 + elif self.valueMin is None: + valueMin = -0.01 + else: + valueMax = 0.01 + else: + if valueMax>0: + valueMax = 1.2*valueMax + valueMin = 0.0 + else: + valueMax = 0.0 + valueMin = 1.2*valueMin + + if getattr(self,'_bubblePlot',None): + bubbleMax = float(_findMax(dataSeries,2,0)) + frac=.25 + bubbleV=frac*(valueMax-valueMin) + self._bubbleV = bubbleV + self._bubbleMax = bubbleMax + self._bubbleRadius = frac*self._length + def special(T,x,func,bubbleV=bubbleV,bubbleMax=bubbleMax): + try: + v = T[2] + except IndexError: + v = bubbleMAx*0.1 + bubbleV *= (v/bubbleMax)**0.5 + return func(T[x]+bubbleV,T[x]-bubbleV) + if oMin is None: valueMin = self._cValueMin = _findMin(dataSeries,self._dataIndex,0,special=special,extraMinMaxValues=self.extraMinMaxValues) + if oMax is None: valueMax = self._cValueMax = _findMax(dataSeries,self._dataIndex,0,special=special,extraMinMaxValues=self.extraMinMaxValues) + + valueMin, valueMax = self._preRangeAdjust(valueMin,valueMax) + + rangeRound = self.rangeRound + + cMin = valueMin + cMax = valueMax + forceZero = self.forceZero + if forceZero: + if forceZero=='near': + forceZero = min(abs(valueMin),abs(valueMax)) <= 5*(valueMax-valueMin) + if forceZero: + if valueMax<0: valueMax=0 + elif valueMin>0: valueMin = 0 + + abf = self.avoidBoundFrac + do_rr = not getattr(self,'valueSteps',None) + do_abf = abf and do_rr + if not isSeq(abf): + abf = abf, abf + abfiz = getattr(self,'abf_ignore_zero', False) + if not isSeq(abfiz): + abfiz = abfiz, abfiz + do_rr = rangeRound != 'none' and do_rr + if do_rr: + rrn = rangeRound in ['both','floor'] + rrx = rangeRound in ['both','ceiling'] + else: + rrn = rrx = 0 + + abS = self.avoidBoundSpace + do_abs = abS + if do_abs: + if not isSeq(abS): + abS = abS, abS + aL = float(self._length) + + go = do_rr or do_abf or do_abs + iter = 0 + while go and iter<=10: + iter += 1 + go = 0 + if do_abf or do_abs: + valueStep, T, fuzz = self._getValueStepAndTicks(valueMin, valueMax) + if do_abf: + i0 = valueStep*abf[0] + i1 = valueStep*abf[1] + else: + i0 = i1 = 0 + if do_abs: + sf = (valueMax-valueMin)/aL + i0 = max(i0,abS[0]*sf) + i1 = max(i1,abS[1]*sf) + if rrn: v = T[0] + else: v = valueMin + u = cMin-i0 + if (abfiz[0] or abs(v)>fuzz) and v>=u+fuzz: + valueMin = u + go = 1 + if rrx: v = T[-1] + else: v = valueMax + u = cMax+i1 + if (abfiz[1] or abs(v)>fuzz) and v<=u-fuzz: + valueMax = u + go = 1 + + if do_rr: + valueStep, T, fuzz = self._getValueStepAndTicks(valueMin, valueMax) + if rrn: + if valueMin=T[0]+fuzz + valueMin = T[0] + if rrx: + if valueMax>T[-1]+fuzz: + valueMax = T[-1]+valueStep + go = 1 + else: + go = valueMax<=T[-1]-fuzz + valueMax = T[-1] + if iter and not go: + self._computedValueStep = valueStep + else: + self._computedValueStep = None + + self._valueMin = valueMin + self._valueMax = valueMax + + origShiftIPC = self.origShiftIPC + origShiftMin = self.origShiftMin + if origShiftMin is not None or origShiftIPC is not None: + origShiftSpecialValue = self.origShiftSpecialValue + self._calcValueStep() + valueMax, valueMin = self._valueMax, self._valueMin + if origShiftSpecialValue is None or abs(origShiftSpecialValue-valueMin)<1e-6: + if origShiftIPC: + m = origShiftIPC*self._valueStep + else: + m = 0 + if origShiftMin: + m = max(m,(valueMax-valueMin)*origShiftMin/self._length) + self._valueMin -= m + + self._rangeAdjust() + + def _pseudo_configure(self): + self._valueMin = self.valueMin + self._valueMax = self.valueMax + if hasattr(self,'_subTickValues'): del self._subTickValues + self._configure_end() + + def _rangeAdjust(self): + """Override this if you want to alter the calculated range. + + E.g. if want a minumamum range of 30% or don't want 100% + as the first point. + """ + pass + + def _adjustAxisTicks(self): + '''Override if you want to put slack at the ends of the axis + eg if you don't want the last tick to be at the bottom etc + ''' + pass + + def _calcScaleFactor(self): + """Calculate the axis' scale factor. + This should be called only *after* the axis' range is set. + Returns a number. + """ + self._scaleFactor = self._length / float(self._valueMax - self._valueMin) + return self._scaleFactor + + def _calcStepAndTickPositions(self): + valueStep = getattr(self,'_computedValueStep',None) + if valueStep: + del self._computedValueStep + self._valueStep = valueStep + else: + self._calcValueStep() + valueStep = self._valueStep + valueMin = self._valueMin + valueMax = self._valueMax + fuzz = 1e-8*valueStep + rangeRound = self.rangeRound + i0 = int(float(valueMin)/valueStep) + v = i0*valueStep + if rangeRound in ('both','floor'): + if v>valueMin+fuzz: i0 -= 1 + elif vvalueMax+fuzz: i1 -= 1 + return valueStep,[i*valueStep for i in range(i0,i1+1)] + + def _calcTickPositions(self): + return self._calcStepAndTickPositions()[1] + + def _calcSubTicks(self): + if not hasattr(self,'_tickValues'): + self._pseudo_configure() + otv = self._tickValues + if not hasattr(self,'_subTickValues'): + acn = self.__class__.__name__ + if acn[:11]=='NormalDateX': + iFuzz = 0 + dCnv = int + else: + iFuzz = 1e-8 + dCnv = lambda x:x + + OTV = [tv for tv in otv if getattr(tv,'_doSubTicks',1)] + T = [].append + nst = int(self.subTickNum) + i = len(OTV) + if i<2: + self._subTickValues = [] + else: + if i==2: + dst = OTV[1]-OTV[0] + elif i==3: + dst = max(OTV[1]-OTV[0],OTV[2]-OTV[1]) + else: + i >>= 1 + dst = OTV[i+1] - OTV[i] + fuzz = dst*iFuzz + vn = self._valueMin+fuzz + vx = self._valueMax-fuzz + if OTV[0]>vn: OTV.insert(0,OTV[0]-dst) + if OTV[-1]=vx: continue + T(t) + self._subTickValues = T.__self__ + self._tickValues = self._subTickValues + return otv + + def _calcTickmarkPositions(self): + """Calculate a list of tick positions on the axis. Returns a list of numbers.""" + self._tickValues = getattr(self,'valueSteps',None) + if self._tickValues: return self._tickValues + self._tickValues = self._calcTickPositions() + self._adjustAxisTicks() + return self._tickValues + + def _calcValueStep(self): + '''Calculate _valueStep for the axis or get from valueStep.''' + if self.valueStep is None: + rawRange = self._valueMax - self._valueMin + rawInterval = rawRange / min(float(self.maximumTicks-1),(float(self._length)/self.minimumTickSpacing)) + self._valueStep = nextRoundNumber(rawInterval) + else: + self._valueStep = self.valueStep + + def _allIntTicks(self): + return _allInt(self._tickValues) + + def makeTickLabels(self): + g = Group() + if not self.visibleLabels: return g + + f = self._labelTextFormat # perhaps someone already set it + if f is None: + f = self.labelTextFormat or (self._allIntTicks() and '%.0f' or _defaultLabelFormatter) + elif f is str and self._allIntTicks(): f = '%.0f' + elif hasattr(f,'calcPlaces'): + f.calcPlaces(self._tickValues) + post = self.labelTextPostFormat + scl = self.labelTextScale + pos = [self._x, self._y] + d = self._dataIndex + pos[1-d] = self._labelAxisPos() + labels = self.labels + if self.skipEndL!='none': + if self.isXAxis: + sk = self._x + else: + sk = self._y + if self.skipEndL=='start': + sk = [sk] + else: + sk = [sk,sk+self._length] + if self.skipEndL=='end': + del sk[0] + else: + sk = [] + + nticks = len(self._tickValues) + nticks1 = nticks - 1 + for i,tick in enumerate(self._tickValues): + label = i-nticks + if label in labels: + label = labels[label] + else: + label = labels[i] + if f and label.visible: + v = self.scale(tick) + if sk: + for skv in sk: + if abs(skv-v)<1e-6: + v = None + break + if v is not None: + if scl is not None: + t = tick*scl + else: + t = tick + if isinstance(f, str): txt = f % t + elif isSeq(f): + #it's a list, use as many items as we get + if i < len(f): + txt = f[i] + else: + txt = '' + elif hasattr(f,'__call__'): + if isinstance(f,TickLabeller): + txt = f(self,t) + else: + txt = f(t) + else: + raise ValueError('Invalid labelTextFormat %s' % f) + if post: txt = post % txt + pos[d] = v + label.setOrigin(*pos) + label.setText(txt) + + #special property to ensure a label doesn't project beyond the bounds of an x-axis + if self.keepTickLabelsInside: + if isinstance(self, XValueAxis): #not done yet for y axes + a_x = self._x + if not i: #first one + x0, y0, x1, y1 = label.getBounds() + if x0 < a_x: + label = label.clone(dx=label.dx + a_x - x0) + if i==nticks1: #final one + a_x1 = a_x +self._length + x0, y0, x1, y1 = label.getBounds() + if x1 > a_x1: + label=label.clone(dx=label.dx-x1+a_x1) + g.add(label) + + return g + + def scale(self, value): + """Converts a numeric value to a plotarea position. + The chart first configures the axis, then asks it to + """ + assert self._configured, "Axis cannot scale numbers before it is configured" + if value is None: value = 0 + + #this could be made more efficient by moving the definition of org and sf into the configuration + org = (self._x, self._y)[self._dataIndex] + sf = self._scaleFactor + if self.reverseDirection: + sf = -sf + org += self._length + return org + sf*(value - self._valueMin) + +class XValueAxis(_XTicks,ValueAxis): + "X/value axis" + + _attrMap = AttrMap(BASE=ValueAxis, + tickUp = AttrMapValue(isNumber, + desc='Tick length up the axis.'), + tickDown = AttrMapValue(isNumber, + desc='Tick length down the axis.'), + joinAxis = AttrMapValue(None, + desc='Join both axes if true.'), + joinAxisMode = AttrMapValue(OneOf('bottom', 'top', 'value', 'points', None), + desc="Mode used for connecting axis ('bottom', 'top', 'value', 'points', None)."), + joinAxisPos = AttrMapValue(isNumberOrNone, + desc='Position at which to join with other axis.'), + ) + + # Indicate the dimension of the data we're interested in. + _dataIndex = 0 + + def __init__(self,**kw): + ValueAxis.__init__(self,**kw) + + self.labels.boxAnchor = 'n' + self.labels.dx = 0 + self.labels.dy = -5 + + self.tickUp = 0 + self.tickDown = 5 + + self.joinAxis = None + self.joinAxisMode = None + self.joinAxisPos = None + + def demo(self): + self.setPosition(20, 50, 150) + self.configure([(10,20,30,40,50)]) + + d = Drawing(200, 100) + d.add(self) + return d + + def joinToAxis(self, yAxis, mode='bottom', pos=None): + "Join with y-axis using some mode." + _assertYAxis(yAxis) + if mode == 'bottom': + self._y = yAxis._y * 1.0 + elif mode == 'top': + self._y = (yAxis._y + yAxis._length) * 1.0 + elif mode == 'value': + self._y = yAxis.scale(pos) * 1.0 + elif mode == 'points': + self._y = pos * 1.0 + + def _joinToAxis(self): + ja = self.joinAxis + if ja: + jam = self.joinAxisMode or 'bottom' + if jam in ('bottom', 'top'): + self.joinToAxis(ja, mode=jam) + elif jam in ('value', 'points'): + self.joinToAxis(ja, mode=jam, pos=self.joinAxisPos) + + def makeAxis(self): + g = Group() + self._joinToAxis() + if not self.visibleAxis: return g + + axis = Line(self._x-self.loLLen, self._y, self._x + self._length+self.hiLLen, self._y) + axis.strokeColor = self.strokeColor + axis.strokeWidth = self.strokeWidth + axis.strokeDashArray = self.strokeDashArray + g.add(axis) + + return g + +#additional utilities to help specify calendar dates on which tick marks +#are to be plotted. After some thought, when the magic algorithm fails, +#we can let them specify a number of days-of-the-year to tick in any given +#year. + +################################################################################# +# +# Preliminary support objects/functions for the axis used in time series charts +# +################################################################################# +_months = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'] +_maxDays = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] +def parseDayAndMonth(dmstr): + """This accepts and validates strings like "31-Dec" i.e. dates + of no particular year. 29 Feb is allowed. These can be used + for recurring dates. It returns a (dd, mm) pair where mm is the + month integer. If the text is not valid it raises an error. + """ + + dstr, mstr = dmstr.split('-') + dd = int(dstr) + mstr = mstr.lower() + mm = _months.index(mstr) + 1 + assert dd <= _maxDays[mm-1] + return (dd, mm) + +class _isListOfDaysAndMonths(Validator): + """This accepts and validates lists of strings like "31-Dec" i.e. dates + of no particular year. 29 Feb is allowed. These can be used + for recurring dates. + """ + def test(self,x): + if isSeq(x): + answer = True + for element in x: + try: + dd, mm = parseDayAndMonth(element) + except: + answer = False + return answer + else: + return False + + def normalize(self,x): + #we store them as presented, it's the most presentable way + return x + +isListOfDaysAndMonths = _isListOfDaysAndMonths() + +_NDINTM = 1,2,3,6,12,24,60,120,180,240,300,360,420,480,540,600,720,840,960,1080,1200,2400 +class NormalDateXValueAxis(XValueAxis): + """An X axis applying additional rules. + + Depending on the data and some built-in rules, the axis + displays normalDate values as nicely formatted dates. + + The client chart should have NormalDate X values. + """ + + _attrMap = AttrMap(BASE = XValueAxis, + bottomAxisLabelSlack = AttrMapValue(isNumber, desc="Fractional amount used to adjust label spacing"), + niceMonth = AttrMapValue(isBoolean, desc="Flag for displaying months 'nicely'."), + forceEndDate = AttrMapValue(isBoolean, desc='Flag for enforced displaying of last date value.'), + forceFirstDate = AttrMapValue(isBoolean, desc='Flag for enforced displaying of first date value.'), + forceDatesEachYear = AttrMapValue(isListOfDaysAndMonths, desc='List of dates in format "31-Dec",' + + '"1-Jan". If present they will always be used for tick marks in the current year, rather ' + + 'than the dates chosen by the automatic algorithm. Hyphen compulsory, case of month optional.'), + xLabelFormat = AttrMapValue(None, desc="Label format string (e.g. '{mm}/{yy}') or function."), + dayOfWeekName = AttrMapValue(SequenceOf(isString,emptyOK=0,lo=7,hi=7), desc='Weekday names.'), + monthName = AttrMapValue(SequenceOf(isString,emptyOK=0,lo=12,hi=12), desc='Month names.'), + dailyFreq = AttrMapValue(isBoolean, desc='True if we are to assume daily data to be ticked at end of month.'), + specifiedTickDates = AttrMapValue(NoneOr(SequenceOf(isNormalDate)), desc='Actual tick values to use; no calculations done'), + specialTickClear = AttrMapValue(isBoolean, desc='clear rather than delete close ticks when forced first/end dates'), + skipGrid = AttrMapValue(OneOf('none','top','both','bottom'),"grid lines to skip top bottom both none"), + ) + + _valueClass = normalDate.ND + + def __init__(self,**kw): + XValueAxis.__init__(self,**kw) + + # some global variables still used... + self.bottomAxisLabelSlack = 0.1 + self.niceMonth = 1 + self.forceEndDate = 0 + self.forceFirstDate = 0 + self.forceDatesEachYear = [] + self.dailyFreq = 0 + self.xLabelFormat = "{mm}/{yy}" + self.dayOfWeekName = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] + self.monthName = ['January', 'February', 'March', 'April', 'May', 'June', 'July', + 'August', 'September', 'October', 'November', 'December'] + self.specialTickClear = 0 + self.valueSteps = self.specifiedTickDates = None + + def _scalar2ND(self, x): + "Convert a scalar to a NormalDate value." + d = self._valueClass() + d.normalize(x) + return d + + def _dateFormatter(self, v): + "Create a formatted label for some value." + if not isinstance(v,normalDate.NormalDate): + v = self._scalar2ND(v) + d, m = normalDate._dayOfWeekName, normalDate._monthName + try: + normalDate._dayOfWeekName, normalDate._monthName = self.dayOfWeekName, self.monthName + return v.formatMS(self.xLabelFormat) + finally: + normalDate._dayOfWeekName, normalDate._monthName = d, m + + def _xAxisTicker(self, xVals): + """Complex stuff... + + Needs explanation... + + Yes please says Andy :-(. Modified on 19 June 2006 to attempt to allow + a mode where one can specify recurring days and months. + """ + VC = self._valueClass + axisLength = self._length + formatter = self._dateFormatter + if isinstance(formatter,TickLabeller): + def formatter(tick): + return self._dateFormatter(self,tick) + firstDate = xVals[0] if not self.valueMin else VC(self.valueMin) + endDate = xVals[-1] if not self.valueMax else VC(self.valueMax) + labels = self.labels + fontName, fontSize, leading = labels.fontName, labels.fontSize, labels.leading + textAnchor, boxAnchor, angle = labels.textAnchor, labels.boxAnchor, labels.angle + RBL = _textBoxLimits(formatter(firstDate).split('\n'),fontName, + fontSize,leading or 1.2*fontSize,textAnchor,boxAnchor) + RBL = _rotatedBoxLimits(RBL[0],RBL[1],RBL[2],RBL[3], angle) + xLabelW = RBL[1]-RBL[0] + xLabelH = RBL[3]-RBL[2] + w = max(xLabelW,labels.width or 0,self.minimumTickSpacing) + + W = w+w*self.bottomAxisLabelSlack + ticks = [] + labels = [] + maximumTicks = self.maximumTicks + + if self.specifiedTickDates: + ticks = [VC(x) for x in self.specifiedTickDates] + labels = [formatter(d) for d in ticks] + if self.forceFirstDate and firstDate==ticks[0] and (axisLength/float(ticks[-1]-ticks[0]))*(ticks[1]-ticks[0])<=W: + if self.specialTickClear: + labels[1] = '' + else: + del ticks[1], labels[1] + if self.forceEndDate and endDate==ticks[-1] and (axisLength/float(ticks[-1]-ticks[0]))*(ticks[-1]-ticks[-2])<=W: + if self.specialTickClear: + labels[-2] = '' + else: + del ticks[-2], labels[-2] + return ticks, labels + + #AR 20060619 - first we try the approach where the user has explicitly + #specified the days of year to be ticked. Other explicit routes may + #be added. + if self.forceDatesEachYear: + forcedPartialDates = list(map(parseDayAndMonth, self.forceDatesEachYear)) + #generate the list of dates in the range. + #print 'dates range from %s to %s' % (firstDate, endDate) + firstYear = firstDate.year() + lastYear = endDate.year() + ticks = [] + labels = [] + yyyy = firstYear + #generate all forced dates between the year it starts and the year it + #ends, adding them if within range. + while yyyy <= lastYear: + for (dd, mm) in forcedPartialDates: + theDate = normalDate.ND((yyyy, mm, dd)) + if theDate >= firstDate and theDate <= endDate: + ticks.append(theDate) + labels.append(formatter(theDate)) + yyyy += 1 + + #first and last may still be forced in. + if self.forceFirstDate and firstDate!=ticks[0]: + ticks.insert(0, firstDate) + labels.insert(0,formatter(firstDate)) + if (axisLength/float(ticks[-1]-ticks[0]))*(ticks[1]-ticks[0])<=W: + if self.specialTickClear: + labels[1] = '' + else: + del ticks[1], labels[1] + if self.forceEndDate and endDate!=ticks[-1]: + ticks.append(endDate) + labels.append(formatter(endDate)) + if (axisLength/float(ticks[-1]-ticks[0]))*(ticks[-1]-ticks[-2])<=W: + if self.specialTickClear: + labels[-2] = '' + else: + del ticks[-2], labels[-2] + + #print 'xVals found on forced dates =', ticks + return ticks, labels + + def addTick(i, xVals=xVals, formatter=formatter, ticks=ticks, labels=labels): + ticks.insert(0,xVals[i]) + labels.insert(0,formatter(xVals[i])) + + n = len(xVals) + #otherwise, we apply the 'magic algorithm...' which looks for nice spacing + #based on the size and separation of the labels. + for d in _NDINTM: + k = n/d + if k<=maximumTicks and k*W <= axisLength: + i = n-1 + if self.niceMonth: + j = endDate.month() % (d<=12 and d or 12) + if j: + if self.forceEndDate: + addTick(i) + ticks[0]._doSubTicks=0 + i -= j + + #weird first date ie not at end of month + try: + wfd = firstDate.month() == xVals[1].month() + except: + wfd = 0 + + while i>=wfd: + addTick(i) + i -= d + + if self.forceFirstDate and ticks[0]!=firstDate: + addTick(0) + ticks[0]._doSubTicks=0 + if (axisLength/float(ticks[-1]-ticks[0]))*(ticks[1]-ticks[0])<=W: + if self.specialTickClear: + labels[1] = '' + else: + del ticks[1], labels[1] + if self.forceEndDate and self.niceMonth and j: + if (axisLength/float(ticks[-1]-ticks[0]))*(ticks[-1]-ticks[-2])<=W: + if self.specialTickClear: + labels[-2] = '' + else: + del ticks[-2], labels[-2] + try: + if labels[0] and labels[0]==labels[1]: + del ticks[1], labels[1] + except IndexError: + pass + + return ticks, labels + raise ValueError('Problem selecting NormalDate value axis tick positions') + + def _convertXV(self,data): + '''Convert all XValues to a standard normalDate type''' + + VC = self._valueClass + for D in data: + for i in range(len(D)): + x, y = D[i] + if not isinstance(x,VC): + D[i] = (VC(x),y) + + def _getStepsAndLabels(self,xVals): + if self.dailyFreq: + xEOM = [] + pm = 0 + px = xVals[0] + for x in xVals: + m = x.month() + if pm!=m: + if pm: xEOM.append(px) + pm = m + px = x + px = xVals[-1] + if xEOM[-1]!=x: xEOM.append(px) + steps, labels = self._xAxisTicker(xEOM) + else: + steps, labels = self._xAxisTicker(xVals) + return steps, labels + + def configure(self, data): + self._convertXV(data) + xVals = set() + for x in data: + for dv in x: + xVals.add(dv[0]) + xVals = list(xVals) + xVals.sort() + VC = self._valueClass + steps,labels = self._getStepsAndLabels(xVals) + valueMin, valueMax = self.valueMin, self.valueMax + valueMin = xVals[0] if valueMin is None else VC(valueMin) + valueMax = xVals[-1] if valueMax is None else VC(valueMax) + self._valueMin, self._valueMax = valueMin, valueMax + self._tickValues = steps + self._labelTextFormat = labels + + self._scaleFactor = self._length / float(valueMax - valueMin) + self._tickValues = steps + self._configured = 1 + +class YValueAxis(_YTicks,ValueAxis): + "Y/value axis" + + _attrMap = AttrMap(BASE=ValueAxis, + tickLeft = AttrMapValue(isNumber, + desc='Tick length left of the axis.'), + tickRight = AttrMapValue(isNumber, + desc='Tick length right of the axis.'), + joinAxis = AttrMapValue(None, + desc='Join both axes if true.'), + joinAxisMode = AttrMapValue(OneOf(('left', 'right', 'value', 'points', None)), + desc="Mode used for connecting axis ('left', 'right', 'value', 'points', None)."), + joinAxisPos = AttrMapValue(isNumberOrNone, + desc='Position at which to join with other axis.'), + ) + + # Indicate the dimension of the data we're interested in. + _dataIndex = 1 + + def __init__(self): + ValueAxis.__init__(self) + + self.labels.boxAnchor = 'e' + self.labels.dx = -5 + self.labels.dy = 0 + + self.tickRight = 0 + self.tickLeft = 5 + + self.joinAxis = None + self.joinAxisMode = None + self.joinAxisPos = None + + def demo(self): + data = [(10, 20, 30, 42)] + self.setPosition(100, 10, 80) + self.configure(data) + + drawing = Drawing(200, 100) + drawing.add(self) + return drawing + + def joinToAxis(self, xAxis, mode='left', pos=None): + "Join with x-axis using some mode." + _assertXAxis(xAxis) + if mode == 'left': + self._x = xAxis._x * 1.0 + elif mode == 'right': + self._x = (xAxis._x + xAxis._length) * 1.0 + elif mode == 'value': + self._x = xAxis.scale(pos) * 1.0 + elif mode == 'points': + self._x = pos * 1.0 + + def _joinToAxis(self): + ja = self.joinAxis + if ja: + jam = self.joinAxisMode + if jam in ('left', 'right'): + self.joinToAxis(ja, mode=jam) + elif jam in ('value', 'points'): + self.joinToAxis(ja, mode=jam, pos=self.joinAxisPos) + + def makeAxis(self): + g = Group() + self._joinToAxis() + if not self.visibleAxis: return g + + axis = Line(self._x, self._y-self.loLLen, self._x, self._y + self._length+self.hiLLen) + axis.strokeColor = self.strokeColor + axis.strokeWidth = self.strokeWidth + axis.strokeDashArray = self.strokeDashArray + g.add(axis) + return g + +class TimeValueAxis: + _mc = 60 + _hc = 60*_mc + _dc = 24*_hc + + def __init__(self,*args,**kwds): + if not self.labelTextFormat: + self.labelTextFormat = self.timeLabelTextFormatter + self._saved_tickInfo = {} + + def _calcValueStep(self): + '''Calculate _valueStep for the axis or get from valueStep.''' + if self.valueStep is None: + rawRange = self._valueMax - self._valueMin + rawInterval = rawRange / min(float(self.maximumTicks-1),(float(self._length)/self.minimumTickSpacing)) + #here's where we try to choose the correct value for the unit + if rawInterval >= self._dc: + d = self._dc + self._unit = 'days' + elif rawInterval >= self._hc: + d = self._hc + self._unit = 'hours' + elif rawInterval >= self._mc: + d = self._mc + self._unit = 'minutes' + else: + d = 1 + self._unit = 'seconds' + self._unitd = d + if d>1: + rawInterval = int(rawInterval/d) + self._valueStep = nextRoundNumber(rawInterval) * d + else: + self._valueStep = self.valueStep + + def timeLabelTextFormatter(self,val): + u = self._unitd + k = (u,tuple(self._tickValues)) + if k in self._saved_tickInfo: + fmt = self._saved_tickInfo[k] + else: + uf = float(u) + tv = [v/uf for v in self._tickValues] + s = self._unit[0] + if _allInt(tv): + fmt = lambda x, uf=uf, s=s: '%.0f%s' % (x/uf,s) + else: + stv = ['%.10f' % v for v in tv] + stvl = max((len(v.rstrip('0'))-v.index('.')-1) for v in stv) + if u==1: + fmt = lambda x,uf=uf,fmt='%%.%dfs' % stvl: fmt % (x/uf) + else: + #see if we can represent fractions + fm = 24 if u==self._dc else 60 + fv = [(v - int(v))*fm for v in tv] + if _allInt(fv): + s1 = 'h' if u==self._dc else ('m' if u==self._mc else 's') + fmt = lambda x,uf=uf,fm=fm, fmt='%%d%s%%d%%s' % (s,s1): fmt % (int(x/uf),int((x/uf - int(x/uf))*fm)) + else: + fmt = lambda x,uf=uf,fmt='%%.%df%s' % (stvl,s): fmt % (x/uf) + self._saved_tickInfo[k] = fmt + + return fmt(val) + + + +class XTimeValueAxis(TimeValueAxis,XValueAxis): + def __init__(self,*args,**kwds): + XValueAxis.__init__(self,*args,**kwds) + TimeValueAxis.__init__(self,*args,**kwds) + +class AdjYValueAxis(YValueAxis): + """A Y-axis applying additional rules. + + Depending on the data and some built-in rules, the axis + may choose to adjust its range and origin. + """ + _attrMap = AttrMap(BASE = YValueAxis, + leftAxisPercent = AttrMapValue(isBoolean, desc='When true add percent sign to label values.'), + leftAxisOrigShiftIPC = AttrMapValue(isNumber, desc='Lowest label shift interval ratio.'), + leftAxisOrigShiftMin = AttrMapValue(isNumber, desc='Minimum amount to shift.'), + leftAxisSkipLL0 = AttrMapValue(EitherOr((isBoolean,isListOfNumbers)), desc='Skip/Keep lowest tick label when true/false.\nOr skiplist'), + labelVOffset = AttrMapValue(isNumber, desc='add this to the labels'), + ) + + def __init__(self,**kw): + YValueAxis.__init__(self,**kw) + self.requiredRange = 30 + self.leftAxisPercent = 1 + self.leftAxisOrigShiftIPC = 0.15 + self.leftAxisOrigShiftMin = 12 + self.leftAxisSkipLL0 = self.labelVOffset = 0 + self.valueSteps = None + + def _rangeAdjust(self): + "Adjusts the value range of the axis." + + from reportlab.graphics.charts.utils import find_good_grid, ticks + y_min, y_max = self._valueMin, self._valueMax + m = self.maximumTicks + n = list(filter(lambda x,m=m: x<=m,[4,5,6,7,8,9])) + if not n: n = [m] + + valueStep, requiredRange = self.valueStep, self.requiredRange + if requiredRange and y_max - y_min < requiredRange: + y1, y2 = find_good_grid(y_min, y_max,n=n,grid=valueStep)[:2] + if y2 - y1 < requiredRange: + ym = (y1+y2)*0.5 + y1 = min(ym-requiredRange*0.5,y_min) + y2 = max(ym+requiredRange*0.5,y_max) + if y_min>=100 and y1<100: + y2 = y2 + 100 - y1 + y1 = 100 + elif y_min>=0 and y1<0: + y2 = y2 - y1 + y1 = 0 + self._valueMin, self._valueMax = y1, y2 + + T, L = ticks(self._valueMin, self._valueMax, split=1, n=n, percent=self.leftAxisPercent,grid=valueStep, labelVOffset=self.labelVOffset) + abf = self.avoidBoundFrac + if abf: + i1 = (T[1]-T[0]) + if not isSeq(abf): + i0 = i1 = i1*abf + else: + i0 = i1*abf[0] + i1 = i1*abf[1] + _n = getattr(self,'_cValueMin',T[0]) + _x = getattr(self,'_cValueMax',T[-1]) + if _n - T[0] < i0: self._valueMin = self._valueMin - i0 + if T[-1]-_x < i1: self._valueMax = self._valueMax + i1 + T, L = ticks(self._valueMin, self._valueMax, split=1, n=n, percent=self.leftAxisPercent,grid=valueStep, labelVOffset=self.labelVOffset) + + self._valueMin = T[0] + self._valueMax = T[-1] + self._tickValues = T + if self.labelTextFormat is None: + self._labelTextFormat = L + else: + self._labelTextFormat = self.labelTextFormat + + if abs(self._valueMin-100)<1e-6: + self._calcValueStep() + vMax, vMin = self._valueMax, self._valueMin + m = max(self.leftAxisOrigShiftIPC*self._valueStep, + (vMax-vMin)*self.leftAxisOrigShiftMin/self._length) + self._valueMin = self._valueMin - m + + if self.leftAxisSkipLL0: + if isSeq(self.leftAxisSkipLL0): + for x in self.leftAxisSkipLL0: + try: + L[x] = '' + except IndexError: + pass + L[0] = '' + +class LogValueAxis(ValueAxis): + + def _calcScaleFactor(self): + """Calculate the axis' scale factor. + This should be called only *after* the axis' range is set. + Returns a number. + """ + self._scaleFactor = self._length / float( + math_log10(self._valueMax) - math_log10(self._valueMin)) + return self._scaleFactor + + + def _setRange(self,dataSeries): + valueMin = self.valueMin + valueMax = self.valueMax + aMin = _findMin(dataSeries,self._dataIndex,0,extraMinMaxValues=self.extraMinMaxValues) + aMax = _findMax(dataSeries,self._dataIndex,0,extraMinMaxValues=self.extraMinMaxValues) + if valueMin is None: valueMin = aMin + if valueMax is None: valueMax = aMax + if valueMin>valueMax: + raise ValueError('%s: valueMin=%r should not be greater than valueMax=%r!' % (self.__class__.__name__valueMin, valueMax)) + if valueMin<=0: + raise ValueError('%s: valueMin=%r negative values are not allowed!' % (self.__class__.__name__,valueMin)) + abS = self.avoidBoundSpace + if abS: + lMin = math_log10(aMin) + lMax = math_log10(aMax) + if not isSeq(abS): abS = abS, abS + a0 = abS[0] or 0 + a1 = abS[1] or 0 + L = self._length - (a0 + a1) + sf = (lMax-lMin)/float(L) + lMin -= a0*sf + lMax += a1*sf + valueMin = min(valueMin,10**lMin) + valueMax = max(valueMax,10**lMax) + self._valueMin = valueMin + self._valueMax = valueMax + + def _calcTickPositions(self): + #self._calcValueStep() + valueMin = cMin = math_log10(self._valueMin) + valueMax = cMax = math_log10(self._valueMax) + rr = self.rangeRound + if rr: + if rr in ('both','ceiling'): + i = int(valueMax) + valueMax = i + 1 if ivalueMin else i + + T = [].append + tv = int(valueMin) + if tvself.maximumTicks: i += 1 + self._powerInc = i + while True: + if tv>valueMax: break + if tv>=valueMin: T(10**tv) + tv += i + if valueMin!=cMin: self._valueMin = 10**valueMin + if valueMax!=cMax: self._valueMax = 10**valueMax + return T.__self__ + + def _calcSubTicks(self): + if not hasattr(self,'_tickValues'): + self._pseudo_configure() + otv = self._tickValues + if not hasattr(self,'_subTickValues'): + T = [].append + valueMin = math_log10(self._valueMin) + valueMax = math_log10(self._valueMax)+1 + tv = round(valueMin) + i = self._powerInc + if i==1: + fac = 10 / float(self.subTickNum) + start = 1 + if self.subTickNum == 10: start = 2 + while tv < valueMax: + for j in range(start,self.subTickNum): + v = fac*j*(10**tv) + if v > self._valueMin and v < self._valueMax: + T(v) + tv += i + else: + ng = min(self.subTickNum+1,i-1) + while ng: + if (i % ng)==0: + i /= ng + break + ng -= 1 + else: + i = 1 + tv = round(valueMin) + while True: + v = 10**tv + if v >= self._valueMax: break + if v not in otv: + T(v) + tv += i + self._subTickValues = T.__self__ + self._tickValues = self._subTickValues + return otv + + +class LogAxisTickLabeller(TickLabeller): + def __call__(self,axis,value): + e = math_log10(value) + e = int(e-0.001 if e<0 else e+0.001) + if e==0: return '1' + if e==1: return '10' + return '10%s' % e + +class LogAxisTickLabellerS(TickLabeller): + '''simple log axis labeller tries to use integers + and short forms else exponential format''' + def __call__(self,axis,value): + e = math_log10(value) + p = int(e-0.001 if e<0 else e+0.001) + if p==0: return '1' + s = '1'+p*'0' if p>0 else '0.'+(-(1+p)*'0')+'1' + se = '%.0e' % value + return se if len(se) 0, or ten + # points inside if bar value < 0. This is different + # to label dx/dy which are not dependent on the + # sign of the data. + self.barLabels.nudge = 0 + + # if you have multiple series, by default they butt + # together. + + # we really need some well-designed default lists of + # colors e.g. from Tufte. These will be used in a + # cycle to set the fill color of each series. + self.bars = TypedPropertyCollection(BarChartProperties) + self.bars.strokeWidth = 1 + self.bars.strokeColor = colors.black + self.bars.strokeDashArray = None + + self.bars[0].fillColor = colors.red + self.bars[1].fillColor = colors.green + self.bars[2].fillColor = colors.blue + self.naLabel = self.categoryNALabel = None + self.zIndexOverrides = None + + def demo(self): + """Shows basic use of a bar chart""" + if self.__class__.__name__=='BarChart': + raise NotImplementedError('Abstract Class BarChart has no demo') + drawing = Drawing(200, 100) + bc = self.__class__() + drawing.add(bc) + return drawing + + def getSeriesOrder(self): + bs = getattr(self,'seriesOrder',None) + n = len(self.data) + if not bs: + R = [(ss,) for ss in range(n)] + else: + bars = self.bars + unseen = set(range(n)) + lines = set() + R = [] + for s in bs: + g = {ss for ss in s if 0<=ss<=n} + gl = {ss for ss in g if bars.checkAttr(ss,'isLine',False)} + if gl: + g -= gl + lines |= gl + unseen -= gl + if g: + R.append(tuple(g)) + unseen -= g + if unseen: + R.extend((ss,) for ss in sorted(unseen)) + if lines: + R.extend((ss,) for ss in sorted(lines)) + self._seriesOrder = R + + def _getConfigureData(self): + cAStyle = self.categoryAxis.style + data = self.data + cc = max(list(map(len,data))) #category count + _data = data + if cAStyle not in ('parallel','parallel_3d'): + #stacked or mixed + data = [] + def _accumulate(*D): + pdata = max((len(d) for d in D))*[0] + ndata = pdata[:] + for d in D: + for i,v in enumerate(d): + v = v or 0 + if v<=-1e-6: + ndata[i] += v + else: + pdata[i] += v + data.append(ndata) + data.append(pdata) + if cAStyle=='stacked': + _accumulate(*_data) + else: + self.getSeriesOrder() + for b in self._seriesOrder: + _accumulate(*(_data[j] for j in b)) + self._configureData = data + + def _getMinMax(self): + '''Attempt to return the data range''' + self._getConfigureData() + self.valueAxis._setRange(self._configureData) + return self.valueAxis._valueMin, self.valueAxis._valueMax + + def _drawBegin(self,org,length): + '''Position and configure value axis, return crossing value''' + vA = self.valueAxis + vA.setPosition(self.x, self.y, length) + self._getConfigureData() + vA.configure(self._configureData) + + # if zero is in chart, put the other axis there, otherwise use org + crossesAt = vA.scale(0) + return crossesAt if vA.forceZero or (crossesAt>=org and crossesAt<=org+length) else org + + def _drawFinish(self): + '''finalize the drawing of a barchart''' + cA = self.categoryAxis + vA = self.valueAxis + cA.configure(self._configureData) + self.calcBarPositions() + g = Group() + + zIndex = getattr(self,'zIndexOverrides',None) + if not zIndex: + g.add(self.makeBackground()) + cAdgl = getattr(cA,'drawGridLast',False) + vAdgl = getattr(vA,'drawGridLast',False) + if not cAdgl: cA.makeGrid(g,parent=self, dim=vA.getGridDims) + if not vAdgl: vA.makeGrid(g,parent=self, dim=cA.getGridDims) + g.add(self.makeBars()) + g.add(cA) + g.add(vA) + if cAdgl: cA.makeGrid(g,parent=self, dim=vA.getGridDims) + if vAdgl: vA.makeGrid(g,parent=self, dim=cA.getGridDims) + for a in getattr(self,'annotations',()): g.add(a(self,cA.scale,vA.scale)) + else: + Z=dict( + background=0, + categoryAxis=1, + valueAxis=2, + bars=3, + barLabels=4, + categoryAxisGrid=5, + valueAxisGrid=6, + annotations=7, + ) + for z in zIndex.strip().split(','): + z = z.strip() + if not z: continue + try: + k,v=z.split('=') + except: + raise ValueError('Badly formatted zIndex clause %r in %r\nallowed variables are\n%s' % (z,zIndex,'\n'.join(['%s=%r'% (k,Z[k]) for k in sorted(Z.keys())]))) + if k not in Z: + raise ValueError('Unknown zIndex variable %r in %r\nallowed variables are\n%s' % (k,Z,'\n'.join(['%s=%r'% (k,Z[k]) for k in sorted(Z.keys())]))) + try: + v = literal_eval(v) #only constants allowed + assert isinstance(v,(float,int)) + except: + raise ValueError('Bad zIndex value %r in clause %r of zIndex\nallowed variables are\n%s' % (v,z,zIndex,'\n'.join(['%s=%r'% (k,Z[k]) for k in sorted(Z.keys())]))) + Z[k] = v + Z = [(v,k) for k,v in Z.items()] + Z.sort() + b = self.makeBars() + bl = b.contents.pop(-1) + for v,k in Z: + if k=='background': + g.add(self.makeBackground()) + elif k=='categoryAxis': + g.add(cA) + elif k=='categoryAxisGrid': + cA.makeGrid(g,parent=self, dim=vA.getGridDims) + elif k=='valueAxis': + g.add(vA) + elif k=='valueAxisGrid': + vA.makeGrid(g,parent=self, dim=cA.getGridDims) + elif k=='bars': + g.add(b) + elif k=='barLabels': + g.add(bl) + elif k=='annotations': + for a in getattr(self,'annotations',()): g.add(a(self,cA.scale,vA.scale)) + + del self._configureData + return g + + def calcBarPositions(self): + """Works out where they go. default vertical. + + Sets an attribute _barPositions which is a list of + lists of (x, y, width, height) matching the data. + """ + + flipXY = self._flipXY + if flipXY: + org = self.y + else: + org = self.x + cA = self.categoryAxis + cScale = cA.scale + + data = self.data + + seriesCount = self._seriesCount = len(data) + self._rowLength = rowLength = max(list(map(len,data))) + wG = self.groupSpacing + barSpacing = self.barSpacing + barWidth = self.barWidth + clbs = getattr(self,'categoryLabelBarSize',0) + clbo = getattr(self,'categoryLabelBarOrder','auto') + if clbo=='auto': clbo = flipXY and 'last' or 'first' + clbo = clbo=='first' + style = cA.style + bars = self.bars + lineCount = sum((int(bars.checkAttr(_,'isLine',False)) for _ in range(seriesCount))) + seriesMLineCount = seriesCount - lineCount + if style=='mixed': + ss = self._seriesOrder + barsPerGroup = len(ss) - lineCount + wB = barsPerGroup*barWidth + wS = (barsPerGroup-1)*barSpacing + if barsPerGroup>1: + bGapB = barWidth + bGapS = barSpacing + else: + bGapB = bGapS = 0 + accumNeg = barsPerGroup*rowLength*[0] + accumPos = accumNeg[:] + elif style in ('parallel','parallel_3d'): + barsPerGroup = 1 + wB = seriesMLineCount*barWidth + wS = (seriesMLineCount-1)*barSpacing + bGapB = barWidth + bGapS = barSpacing + else: + barsPerGroup = seriesMLineCount + accumNeg = rowLength*[0] + accumPos = accumNeg[:] + wB = barWidth + wS = bGapB = bGapS = 0 + + self._groupWidth = groupWidth = wG+wB+wS + useAbsolute = self.useAbsolute + + if useAbsolute: + if not isinstance(useAbsolute,str): + useAbsolute = 7 #all three are fixed + else: + useAbsolute = 0 + 1*('b' in useAbsolute)+2*('g' in useAbsolute)+4*('s' in useAbsolute) + else: + useAbsolute = 0 + + aW0 = float(cScale(0)[1]) + aW = aW0 - clbs + + if useAbsolute==0: #case 0 all are free + self._normFactor = fB = fG = fS = aW/groupWidth + elif useAbsolute==7: #all fixed + fB = fG = fS = 1.0 + _cscale = cA._scale + elif useAbsolute==1: #case 1 barWidth is fixed + fB = 1.0 + fG = fS = (aW-wB)/(wG+wS) + elif useAbsolute==2: #groupspacing is fixed + fG=1.0 + fB = fS = (aW-wG)/(wB+wS) + elif useAbsolute==3: #groupspacing & barwidth are fixed + fB = fG = 1.0 + fS = (aW-wG-wB)/wS if wS else 0 + elif useAbsolute==4: #barspacing is fixed + fS=1.0 + fG = fB = (aW-wS)/(wG+wB) + elif useAbsolute==5: #barspacing & barWidth are fixed + fS = fB = 1.0 + fG = (aW-wB-wS)/wG + elif useAbsolute==6: #barspacing & groupspacing are fixed + fS = fG = 1 + fB = (aW-wS-wG)/wB + self._normFactorB = fB + self._normFactorG = fG + self._normFactorS = fS + + # 'Baseline' correction... + vA = self.valueAxis + vScale = vA.scale + vARD = vA.reverseDirection + vm, vM = vA._valueMin, vA._valueMax + if vm <= 0 <= vM: + baseLine = vScale(0) + elif 0 < vm: + baseLine = vScale(vm) + elif vM < 0: + baseLine = vScale(vM) + self._baseLine = baseLine + + width = barWidth*fB + offs = 0.5*wG*fG + bGap = bGapB*fB+bGapS*fS + + if clbs: + if clbo: #the lable bar comes first + lbpf = (offs+clbs/6.0)/aW0 + offs += clbs + else: + lbpf = (offs+wB*fB+wS*fS+clbs/6.0)/aW0 + cA.labels.labelPosFrac = lbpf + + self._barPositions = [] + aBP = self._barPositions.append + reversePlotOrder = self.reversePlotOrder + + def _addBar(colNo, accx): + # Ufff... + if useAbsolute==7: + x = groupWidth*_cscale(colNo) + xVal + org + else: + (g, _) = cScale(colNo) + x = g + xVal + + datum = row[colNo] + if datum is None: + height = None + y = baseLine + else: + if style not in ('parallel','parallel_3d') and not isLine: + if datum<=-1e-6: + y = vScale(accumNeg[accx]) + if (ybaseLine): y = baseLine + accumNeg[accx] += datum + datum = accumNeg[accx] + else: + y = vScale(accumPos[accx]) + if (y>baseLine if vARD else y=0 and 1 or -1)*nudge + if bt=='mid': + b = y+height*0.5 + elif bt=='hi': + if value>=0: + b = y + value + nudge + else: + b = y - nudge + pm = -pm + elif bt=='lo': + if value<=0: + b = y + value + nudge + else: + b = y - nudge + pm = -pm + else: + b = y + value + nudge + label._pmv = pm #the plus minus val + return a,b,pm + + def _addBarLabel(self, g, rowNo, colNo, x, y, width, height): + text = self._getLabelText(rowNo,colNo) + if text: + self._addLabel(text, self.barLabels[(rowNo, colNo)], g, rowNo, colNo, x, y, width, height) + + def _addNABarLabel(self, g, rowNo, colNo, x, y, width, height, calcOnly=False, na=None): + if na is None: na = self.naLabel + if na and na.text: + na = copy.copy(na) + v = self.valueAxis._valueMax<=0 and -1e-8 or 1e-8 + if width is None: width = v + if height is None: height = v + return self._addLabel(na.text, na, g, rowNo, colNo, x, y, width, height, calcOnly=calcOnly) + + def _addLabel(self, text, label, g, rowNo, colNo, x, y, width, height, calcOnly=False): + if label.visible: + labelWidth = stringWidth(text, label.fontName, label.fontSize) + flipXY = self._flipXY + if flipXY: + y0, x0, pm = self._labelXY(label,y,x,height,width) + else: + x0, y0, pm = self._labelXY(label,x,y,width,height) + fixedEnd = getattr(label,'fixedEnd', None) + if fixedEnd is not None: + v = fixedEnd._getValue(self,pm) + x00, y00 = x0, y0 + if flipXY: + x0 = v + else: + y0 = v + else: + if flipXY: + x00 = x0 + y00 = y+height/2.0 + else: + x00 = x+width/2.0 + y00 = y0 + fixedStart = getattr(label,'fixedStart', None) + if fixedStart is not None: + v = fixedStart._getValue(self,pm) + if flipXY: + x00 = v + else: + y00 = v + + if pm<0: + if flipXY: + dx = -2*label.dx + dy = 0 + else: + dy = -2*label.dy + dx = 0 + else: + dy = dx = 0 + if calcOnly: return x0+dx, y0+dy + label.setOrigin(x0+dx, y0+dy) + label.setText(text) + sC, sW = label.lineStrokeColor, label.lineStrokeWidth + if sC and sW: g.insert(0,Line(x00,y00,x0,y0, strokeColor=sC, strokeWidth=sW)) + g.add(label) + alx = getattr(self,'barLabelCallOut',None) + if alx: + label._callOutInfo = (self,g,rowNo,colNo,x,y,width,height,x00,y00,x0,y0) + alx(label) + del label._callOutInfo + + def _makeBar(self,g,x,y,width,height,rowNo,style): + r = Rect(x, y, width, height) + r.strokeWidth = style.strokeWidth + r.fillColor = style.fillColor + r.strokeColor = style.strokeColor + if style.strokeDashArray: + r.strokeDashArray = style.strokeDashArray + g.add(r) + + def _makeBars(self,g,lg): + bars = self.bars + br = getattr(self,'barRecord',None) + BP = self._barPositions + flipXY = self._flipXY + + catNAL = self.categoryNALabel + catNNA = {} + if catNAL: + CBL = [] + rowNoL = len(self.data) - 1 + #find all the categories that have at least one value + for rowNo, row in enumerate(BP): + for colNo, (x, y, width, height) in enumerate(row): + if None not in (width,height): + catNNA[colNo] = 1 + + lines = [].append + lineSyms = [].append + for rowNo, row in enumerate(BP): + styleCount = len(bars) + styleIdx = rowNo % styleCount + rowStyle = bars[styleIdx] + isLine = bars.checkAttr(rowNo, 'isLine', False) + linePts = [].append + for colNo, (x,y,width,height) in enumerate(row): + style = (styleIdx,colNo) in bars and bars[(styleIdx,colNo)] or rowStyle + if None in (width,height): + if not catNAL or colNo in catNNA: + self._addNABarLabel(lg,rowNo,colNo,x,y,width,height) + elif catNAL and colNo not in CBL: + r0 = self._addNABarLabel(lg,rowNo,colNo,x,y,width,height,True,catNAL) + if r0: + x, y, width, height = BP[rowNoL][colNo] + r1 = self._addNABarLabel(lg,rowNoL,colNo,x,y,width,height,True,catNAL) + x = (r0[0]+r1[0])/2.0 + y = (r0[1]+r1[1])/2.0 + self._addNABarLabel(lg,rowNoL,colNo,x,y,0.0001,0.0001,na=catNAL) + CBL.append(colNo) + if isLine: linePts(None) + continue + + # Draw a rectangular symbol for each data item, + # or a normal colored rectangle. + symbol = None + if hasattr(style, 'symbol'): + symbol = copy.deepcopy(style.symbol) + elif hasattr(self.bars, 'symbol'): + symbol = self.bars.symbol + + minDimen=getattr(style,'minDimen',None) + if minDimen: + if flipXY: + if width<0: + width = min(-style.minDimen,width) + else: + width = max(style.minDimen,width) + else: + if height<0: + height = min(-style.minDimen,height) + else: + height = max(style.minDimen,height) + + if isLine: + if not flipXY: + yL = y + height + xL = x + width*0.5 + else: + xL = x + width + yL = y + height*0.5 + linePts(xL) + linePts(yL) + if symbol: + sym = uSymbol2Symbol(tpcGetItem(symbol,colNo),xL,yL,style.strokeColor or style.fillColor) + if sym: lineSyms(sym) + + elif symbol: + symbol.x = x + symbol.y = y + symbol.width = width + symbol.height = height + g.add(symbol) + + elif abs(width)>1e-7 and abs(height)>=1e-7 and (style.fillColor is not None or style.strokeColor is not None): + self._makeBar(g,x,y,width,height,rowNo,style) + if br: br(g.contents[-1],label=self._getLabelText(rowNo,colNo),value=self.data[rowNo][colNo],rowNo=rowNo,colNo=colNo) + + self._addBarLabel(lg,rowNo,colNo,x,y,width,height) + + for linePts in yieldNoneSplits(linePts.__self__): + if linePts: + lines(PolyLine(linePts, + strokeColor=rowStyle.strokeColor or rowStyle.fillColor, + strokeWidth=rowStyle.strokeWidth, + strokeDashArray = rowStyle.strokeDashArray)) + + for pl in lines.__self__: + g.add(pl) + for sym in lineSyms.__self__: + g.add(sym) + + def _computeLabelPosition(self, text, label, rowNo, colNo, x, y, width, height): + if label.visible: + labelWidth = stringWidth(text, label.fontName, label.fontSize) + flipXY = self._flipXY + if flipXY: + y0, x0, pm = self._labelXY(label,y,x,height,width) + else: + x0, y0, pm = self._labelXY(label,x,y,width,height) + fixedEnd = getattr(label,'fixedEnd', None) + if fixedEnd is not None: + v = fixedEnd._getValue(self,pm) + x00, y00 = x0, y0 + if flipXY: + x0 = v + else: + y0 = v + else: + if flipXY: + x00 = x0 + y00 = y+height/2.0 + else: + x00 = x+width/2.0 + y00 = y0 + fixedStart = getattr(label,'fixedStart', None) + if fixedStart is not None: + v = fixedStart._getValue(self,pm) + if flipXY: + x00 = v + else: + y00 = v + + if pm<0: + if flipXY: + dx = -2*label.dx + dy = 0 + else: + dy = -2*label.dy + dx = 0 + else: + dy = dx = 0 + label.setOrigin(x0+dx, y0+dy) + label.setText(text) + return pm,label.getBounds() + + def _computeBarPositions(self): + """Information function, can be called by charts which want to with space around bars""" + cA, vA = self.categoryAxis, self.valueAxis + if vA: vA.joinAxis = cA + if cA: cA.joinAxis = vA + if self._flipXY: + cA.setPosition(self._drawBegin(self.x,self.width), self.y, self.height) + else: + cA.setPosition(self.x, self._drawBegin(self.y,self.height), self.width) + cA.configure(self._configureData) + self.calcBarPositions() + + def _computeMaxSpace(self,size,required): + '''helper for madmen who want to put stuff inside their barcharts + basically after _computebarPositions we slide a line of length size + down the bar profile on either side of the bars to find the + maximum space. If the space at any point is >= required then we're + done. Otherwise we return the largest space location and amount. + ''' + flipXY = self._flipXY + self._computeBarPositions() + lenData = len(self.data) + BP = self._barPositions + C = [] + aC = C.append + if flipXY: + lo = self.x + hi = lo + self.width + end = self.y+self.height + for bp in BP: + for x, y, w, h in bp: + v = x+w + z = y+h + aC((min(y,z),max(y,z), min(x,v) - lo, hi - max(x,v))) + else: + lo = self.y + hi = lo + self.height + end = self.x+self.width + for bp in BP: + for x, y, w, h in bp: + v = y+h + z = x+w + aC((min(x,z), max(x,z), min(y,v) - lo, hi - max(y,v))) + C.sort() + R = [C[0]] + for c in C: + r = R[-1] + if r[0]end: break + j = i + alo = ahi = 0x7fffffff + while jahi: + if alo>maxS: + maxS = alo + maxP = flipXY and (lo,v0,lo+alo,v0+size,0) or (v0,lo,v0+size,lo+alo,0) + if maxS >= required: break + elif ahi>maxS: + maxS = ahi + maxP = flipXY and (hi-ahi,v0,hi,v0+size,1) or (v0,hi-ahi,v0+size,hi,1) + if maxS >= required: break + return maxS, maxP + + def _computeSimpleBarLabelPositions(self): + """Information function, can be called by charts which want to mess with labels""" + cA, vA = self.categoryAxis, self.valueAxis + if vA: vA.joinAxis = cA + if cA: cA.joinAxis = vA + if self._flipXY: + cA.setPosition(self._drawBegin(self.x,self.width), self.y, self.height) + else: + cA.setPosition(self.x, self._drawBegin(self.y,self.height), self.width) + cA.configure(self._configureData) + self.calcBarPositions() + + bars = self.bars + R = [].append + BP = self._barPositions + for rowNo, row in enumerate(BP): + C = [].append + for colNo, (x, y, width, height) in enumerate(row): + if None in (width,height): + na = self.naLabel + if na and na.text: + na = copy.copy(na) + v = self.valueAxis._valueMax<=0 and -1e-8 or 1e-8 + if width is None: width = v + if height is None: height = v + C(self._computeLabelPosition(na.text, na, rowNo, colNo, x, y, width, height)) + else: + C(None) + else: + text = self._getLabelText(rowNo,colNo) + if text: + C(self._computeLabelPosition(text, self.barLabels[(rowNo, colNo)], rowNo, colNo, x, y, width, height)) + else: + C(None) + R(C.__self__) + return R.__self__ + + def makeBars(self): + g = Group() + lg = Group() + self._makeBars(g,lg) + g.add(lg) + return g + + def _desiredCategoryAxisLength(self): + '''for dynamically computing the desired category axis length''' + style = self.categoryAxis.style + data = self.data + n = len(data) + m = max(list(map(len,data))) + if style=='parallel': + groupWidth = (n-1)*self.barSpacing+n*self.barWidth + else: + groupWidth = self.barWidth + return m*(self.groupSpacing+groupWidth) + + def draw(self): + cA, vA = self.categoryAxis, self.valueAxis + if vA: vA.joinAxis = cA + if cA: cA.joinAxis = vA + if self._flipXY: + cA.setPosition(self._drawBegin(self.x,self.width), self.y, self.height) + else: + cA.setPosition(self.x, self._drawBegin(self.y,self.height), self.width) + return self._drawFinish() + +class VerticalBarChart(BarChart): + "Vertical bar chart with multiple side-by-side bars." + _flipXY = 0 + +class HorizontalBarChart(BarChart): + "Horizontal bar chart with multiple side-by-side bars." + _flipXY = 1 + +class _FakeGroup: + def __init__(self, cmp=None): + self._data = [] + self._key = functools.cmp_to_key(cmp) + + def add(self,what): + self._data.append(what) + + def value(self): + return self._data + + def sort(self): + self._data.sort(key=self._key) + +class BarChart3D(BarChart): + _attrMap = AttrMap(BASE=BarChart, + theta_x = AttrMapValue(isNumber, desc='dx/dz'), + theta_y = AttrMapValue(isNumber, desc='dy/dz'), + zDepth = AttrMapValue(isNumber, desc='depth of an individual series'), + zSpace = AttrMapValue(isNumber, desc='z gap around series'), + ) + theta_x = .5 + theta_y = .5 + zDepth = None + zSpace = None + + def calcBarPositions(self): + BarChart.calcBarPositions(self) + seriesCount = self._seriesCount + zDepth = self.zDepth + if zDepth is None: zDepth = self.barWidth + zSpace = self.zSpace + if zSpace is None: zSpace = self.barSpacing + if self.categoryAxis.style=='parallel_3d': + _3d_depth = seriesCount*zDepth+(seriesCount+1)*zSpace + else: + _3d_depth = zDepth + 2*zSpace + _3d_depth *= self._normFactor + self._3d_dx = self.theta_x*_3d_depth + self._3d_dy = self.theta_y*_3d_depth + + def _calc_z0(self,rowNo): + zDepth = self.zDepth + if zDepth is None: zDepth = self.barWidth + zSpace = self.zSpace + if zSpace is None: zSpace = self.barSpacing + if self.categoryAxis.style=='parallel_3d': + z0 = self._normFactor*(rowNo*(zDepth+zSpace)+zSpace) + else: + z0 = self._normFactor*zSpace + return z0 + + def _makeBar(self,g,x,y,width,height,rowNo,style): + zDepth = self.zDepth + if zDepth is None: zDepth = self.barWidth + zSpace = self.zSpace + if zSpace is None: zSpace = self.barSpacing + z0 = self._calc_z0(rowNo) + z1 = z0 + zDepth*self._normFactor + if width<0: + x += width + width = -width + x += z0*self.theta_x + y += z0*self.theta_y + if self._flipXY: + y += zSpace + else: + x += zSpace + g.add((0,z0,z1,x,y,width,height,rowNo,style)) + + def _addBarLabel(self, g, rowNo, colNo, x, y, width, height): + z0 = self._calc_z0(rowNo) + zSpace = self.zSpace + if zSpace is None: zSpace = self.barSpacing + z1 = z0 + x += z0*self.theta_x + y += z0*self.theta_y + if self._flipXY: + y += zSpace + else: + x += zSpace + g.add((1,z0,z1,x,y,width,height,rowNo,colNo)) + + def makeBars(self): + from reportlab.graphics.charts.utils3d import _draw_3d_bar + fg = _FakeGroup(cmp=self._cmpZ) + self._makeBars(fg,fg) + fg.sort() + g = Group() + theta_x = self.theta_x + theta_y = self.theta_y + fg_value = fg.value() + cAStyle = self.categoryAxis.style + if cAStyle=='stacked': + fg_value.reverse() + elif cAStyle=='mixed': + fg_value = [_[1] for _ in sorted((((t[1],t[2],t[3],t[4]),t) for t in fg_value))] + + for t in fg_value: + if t[0]==0: + z0,z1,x,y,width,height,rowNo,style = t[1:] + dz = z1 - z0 + _draw_3d_bar(g, x, x+width, y, y+height, dz*theta_x, dz*theta_y, + fillColor=style.fillColor, fillColorShaded=None, + strokeColor=style.strokeColor, strokeWidth=style.strokeWidth, + shading=0.45) + for t in fg_value: + if t==1: + z0,z1,x,y,width,height,rowNo,colNo = t[1:] + BarChart._addBarLabel(self,g,rowNo,colNo,x,y,width,height) + return g + +class VerticalBarChart3D(BarChart3D,VerticalBarChart): + _cmpZ=lambda self,a,b:cmp((-a[1],a[3],a[0],-a[4]),(-b[1],b[3],b[0],-b[4])) + +class HorizontalBarChart3D(BarChart3D,HorizontalBarChart): + _cmpZ = lambda self,a,b: cmp((-a[1],a[4],a[0],-a[3]),(-b[1],b[4],b[0],-b[3])) #t, z0, z1, x, y = a[:5] + +# Vertical samples. +def sampleV0a(): + "A slightly pathologic bar chart with only TWO data items." + + drawing = Drawing(400, 200) + + data = [(13, 20)] + + bc = VerticalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + + bc.strokeColor = colors.black + + bc.valueAxis.valueMin = 0 + bc.valueAxis.valueMax = 60 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'ne' + bc.categoryAxis.labels.dx = 8 + bc.categoryAxis.labels.dy = -2 + bc.categoryAxis.labels.angle = 30 + bc.categoryAxis.categoryNames = ['Ying', 'Yang'] + + drawing.add(bc) + + return drawing + + +def sampleV0b(): + "A pathologic bar chart with only ONE data item." + + drawing = Drawing(400, 200) + + data = [(42,)] + + bc = VerticalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + bc.strokeColor = colors.black + + bc.valueAxis.valueMin = 0 + bc.valueAxis.valueMax = 50 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'ne' + bc.categoryAxis.labels.dx = 8 + bc.categoryAxis.labels.dy = -2 + bc.categoryAxis.labels.angle = 30 + bc.categoryAxis.categoryNames = ['Jan-99'] + + drawing.add(bc) + + return drawing + + +def sampleV0c(): + "A really pathologic bar chart with NO data items at all!" + + drawing = Drawing(400, 200) + + data = [()] + + bc = VerticalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + bc.strokeColor = colors.black + + bc.valueAxis.valueMin = 0 + bc.valueAxis.valueMax = 60 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'ne' + bc.categoryAxis.labels.dx = 8 + bc.categoryAxis.labels.dy = -2 + bc.categoryAxis.categoryNames = [] + + drawing.add(bc) + + return drawing + + +def sampleV1(): + "Sample of multi-series bar chart." + + drawing = Drawing(400, 200) + + data = [ + (13, 5, 20, 22, 37, 45, 19, 4), + (14, 6, 21, 23, 38, 46, 20, 5) + ] + + bc = VerticalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + bc.strokeColor = colors.black + + bc.valueAxis.valueMin = 0 + bc.valueAxis.valueMax = 60 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'ne' + bc.categoryAxis.labels.dx = 8 + bc.categoryAxis.labels.dy = -2 + bc.categoryAxis.labels.angle = 30 + + catNames = 'Jan Feb Mar Apr May Jun Jul Aug'.split(' ') + catNames = [n+'-99' for n in catNames] + bc.categoryAxis.categoryNames = catNames + drawing.add(bc) + + return drawing + + +def sampleV2a(): + "Sample of multi-series bar chart." + + data = [(2.4, -5.7, 2, 5, 9.2), + (0.6, -4.9, -3, 4, 6.8) + ] + + labels = ("Q3 2000", "Year to Date", "12 months", + "Annualised\n3 years", "Since 07.10.99") + + drawing = Drawing(400, 200) + + bc = VerticalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 120 + bc.width = 300 + bc.data = data + + bc.barSpacing = 0 + bc.groupSpacing = 10 + bc.barWidth = 10 + + bc.valueAxis.valueMin = -15 + bc.valueAxis.valueMax = +15 + bc.valueAxis.valueStep = 5 + bc.valueAxis.labels.fontName = 'Helvetica' + bc.valueAxis.labels.fontSize = 8 + bc.valueAxis.labels.boxAnchor = 'n' # irrelevant (becomes 'c') + bc.valueAxis.labels.textAnchor = 'middle' + + bc.categoryAxis.categoryNames = labels + bc.categoryAxis.labels.fontName = 'Helvetica' + bc.categoryAxis.labels.fontSize = 8 + bc.categoryAxis.labels.dy = -60 + + drawing.add(bc) + + return drawing + + +def sampleV2b(): + "Sample of multi-series bar chart." + + data = [(2.4, -5.7, 2, 5, 9.2), + (0.6, -4.9, -3, 4, 6.8) + ] + + labels = ("Q3 2000", "Year to Date", "12 months", + "Annualised\n3 years", "Since 07.10.99") + + drawing = Drawing(400, 200) + + bc = VerticalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 120 + bc.width = 300 + bc.data = data + + bc.barSpacing = 5 + bc.groupSpacing = 10 + bc.barWidth = 10 + + bc.valueAxis.valueMin = -15 + bc.valueAxis.valueMax = +15 + bc.valueAxis.valueStep = 5 + bc.valueAxis.labels.fontName = 'Helvetica' + bc.valueAxis.labels.fontSize = 8 + bc.valueAxis.labels.boxAnchor = 'n' # irrelevant (becomes 'c') + bc.valueAxis.labels.textAnchor = 'middle' + + bc.categoryAxis.categoryNames = labels + bc.categoryAxis.labels.fontName = 'Helvetica' + bc.categoryAxis.labels.fontSize = 8 + bc.categoryAxis.labels.dy = -60 + + drawing.add(bc) + + return drawing + + +def sampleV2c(): + "Sample of multi-series bar chart." + + data = [(2.4, -5.7, 2, 5, 9.99), + (0.6, -4.9, -3, 4, 9.99) + ] + + labels = ("Q3 2000", "Year to Date", "12 months", + "Annualised\n3 years", "Since 07.10.99") + + drawing = Drawing(400, 200) + + bc = VerticalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 120 + bc.width = 300 + bc.data = data + + bc.barSpacing = 2 + bc.groupSpacing = 10 + bc.barWidth = 10 + + bc.valueAxis.valueMin = -15 + bc.valueAxis.valueMax = +15 + bc.valueAxis.valueStep = 5 + bc.valueAxis.labels.fontName = 'Helvetica' + bc.valueAxis.labels.fontSize = 8 + + bc.categoryAxis.categoryNames = labels + bc.categoryAxis.labels.fontName = 'Helvetica' + bc.categoryAxis.labels.fontSize = 8 + bc.valueAxis.labels.boxAnchor = 'n' + bc.valueAxis.labels.textAnchor = 'middle' + bc.categoryAxis.labels.dy = -60 + + bc.barLabels.nudge = 10 + + bc.barLabelFormat = '%0.2f' + bc.barLabels.dx = 0 + bc.barLabels.dy = 0 + bc.barLabels.boxAnchor = 'n' # irrelevant (becomes 'c') + bc.barLabels.fontName = 'Helvetica' + bc.barLabels.fontSize = 6 + + drawing.add(bc) + + return drawing + + +def sampleV3(): + "Faked horizontal bar chart using a vertical real one (deprecated)." + + names = ("UK Equities", "US Equities", "European Equities", "Japanese Equities", + "Pacific (ex Japan) Equities", "Emerging Markets Equities", + "UK Bonds", "Overseas Bonds", "UK Index-Linked", "Cash") + + series1 = (-1.5, 0.3, 0.5, 1.0, 0.8, 0.7, 0.4, 0.1, 1.0, 0.3) + series2 = (0.0, 0.33, 0.55, 1.1, 0.88, 0.77, 0.44, 0.11, 1.10, 0.33) + + assert len(names) == len(series1), "bad data" + assert len(names) == len(series2), "bad data" + + drawing = Drawing(400, 200) + + bc = VerticalBarChart() + bc.x = 0 + bc.y = 0 + bc.height = 100 + bc.width = 150 + bc.data = (series1,) + bc.bars.fillColor = colors.green + + bc.barLabelFormat = '%0.2f' + bc.barLabels.dx = 0 + bc.barLabels.dy = 0 + bc.barLabels.boxAnchor = 'w' # irrelevant (becomes 'c') + bc.barLabels.angle = 90 + bc.barLabels.fontName = 'Helvetica' + bc.barLabels.fontSize = 6 + bc.barLabels.nudge = 10 + + bc.valueAxis.visible = 0 + bc.valueAxis.valueMin = -2 + bc.valueAxis.valueMax = +2 + bc.valueAxis.valueStep = 1 + + bc.categoryAxis.tickUp = 0 + bc.categoryAxis.tickDown = 0 + bc.categoryAxis.categoryNames = names + bc.categoryAxis.labels.angle = 90 + bc.categoryAxis.labels.boxAnchor = 'w' + bc.categoryAxis.labels.dx = 0 + bc.categoryAxis.labels.dy = -125 + bc.categoryAxis.labels.fontName = 'Helvetica' + bc.categoryAxis.labels.fontSize = 6 + + g = Group(bc) + g.translate(100, 175) + g.rotate(-90) + + drawing.add(g) + + return drawing + + +def sampleV4a(): + "A bar chart showing value axis region starting at *exactly* zero." + + drawing = Drawing(400, 200) + + data = [(13, 20)] + + bc = VerticalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + + bc.strokeColor = colors.black + + bc.valueAxis.valueMin = 0 + bc.valueAxis.valueMax = 60 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'n' + bc.categoryAxis.labels.dy = -5 + bc.categoryAxis.categoryNames = ['Ying', 'Yang'] + + drawing.add(bc) + + return drawing + + +def sampleV4b(): + "A bar chart showing value axis region starting *below* zero." + + drawing = Drawing(400, 200) + + data = [(13, 20)] + + bc = VerticalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + + bc.strokeColor = colors.black + + bc.valueAxis.valueMin = -10 + bc.valueAxis.valueMax = 60 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'n' + bc.categoryAxis.labels.dy = -5 + bc.categoryAxis.categoryNames = ['Ying', 'Yang'] + + drawing.add(bc) + + return drawing + + +def sampleV4c(): + "A bar chart showing value axis region staring *above* zero." + + drawing = Drawing(400, 200) + + data = [(13, 20)] + + bc = VerticalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + + bc.strokeColor = colors.black + + bc.valueAxis.valueMin = 10 + bc.valueAxis.valueMax = 60 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'n' + bc.categoryAxis.labels.dy = -5 + bc.categoryAxis.categoryNames = ['Ying', 'Yang'] + + drawing.add(bc) + + return drawing + + +def sampleV4d(): + "A bar chart showing value axis region entirely *below* zero." + + drawing = Drawing(400, 200) + + data = [(-13, -20)] + + bc = VerticalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + + bc.strokeColor = colors.black + + bc.valueAxis.valueMin = -30 + bc.valueAxis.valueMax = -10 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'n' + bc.categoryAxis.labels.dy = -5 + bc.categoryAxis.categoryNames = ['Ying', 'Yang'] + + drawing.add(bc) + + return drawing + + +### + +##dataSample5 = [(10, 20), (20, 30), (30, 40), (40, 50), (50, 60)] +##dataSample5 = [(10, 60), (20, 50), (30, 40), (40, 30), (50, 20)] +dataSample5 = [(10, 60), (20, 50), (30, 40), (40, 30)] + +def sampleV5a(): + "A simple bar chart with no expressed spacing attributes." + + drawing = Drawing(400, 200) + + data = dataSample5 + + bc = VerticalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + bc.strokeColor = colors.black + + bc.valueAxis.valueMin = 0 + bc.valueAxis.valueMax = 60 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'n' + bc.categoryAxis.labels.dy = -5 + bc.categoryAxis.categoryNames = ['Ying', 'Yang'] + + drawing.add(bc) + + return drawing + + +def sampleV5b(): + "A simple bar chart with proportional spacing." + + drawing = Drawing(400, 200) + + data = dataSample5 + + bc = VerticalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + bc.strokeColor = colors.black + + bc.useAbsolute = 0 + bc.barWidth = 40 + bc.groupSpacing = 20 + bc.barSpacing = 10 + + bc.valueAxis.valueMin = 0 + bc.valueAxis.valueMax = 60 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'n' + bc.categoryAxis.labels.dy = -5 + bc.categoryAxis.categoryNames = ['Ying', 'Yang'] + + drawing.add(bc) + + return drawing + + +def sampleV5c1(): + "Make sampe simple bar chart but with absolute spacing." + + drawing = Drawing(400, 200) + + data = dataSample5 + + bc = VerticalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + bc.strokeColor = colors.black + + bc.useAbsolute = 1 + bc.barWidth = 40 + bc.groupSpacing = 0 + bc.barSpacing = 0 + + bc.valueAxis.valueMin = 0 + bc.valueAxis.valueMax = 60 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'n' + bc.categoryAxis.labels.dy = -5 + bc.categoryAxis.categoryNames = ['Ying', 'Yang'] + + drawing.add(bc) + + return drawing + + +def sampleV5c2(): + "Make sampe simple bar chart but with absolute spacing." + + drawing = Drawing(400, 200) + + data = dataSample5 + + bc = VerticalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + bc.strokeColor = colors.black + + bc.useAbsolute = 1 + bc.barWidth = 40 + bc.groupSpacing = 20 + bc.barSpacing = 0 + + bc.valueAxis.valueMin = 0 + bc.valueAxis.valueMax = 60 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'n' + bc.categoryAxis.labels.dy = -5 + bc.categoryAxis.categoryNames = ['Ying', 'Yang'] + + drawing.add(bc) + + return drawing + + +def sampleV5c3(): + "Make sampe simple bar chart but with absolute spacing." + + drawing = Drawing(400, 200) + + data = dataSample5 + + bc = VerticalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + bc.strokeColor = colors.black + + bc.useAbsolute = 1 + bc.barWidth = 40 + bc.groupSpacing = 0 + bc.barSpacing = 10 + + bc.valueAxis.valueMin = 0 + bc.valueAxis.valueMax = 60 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'n' + bc.categoryAxis.labels.dy = -5 + bc.categoryAxis.categoryNames = ['Ying', 'Yang'] + + drawing.add(bc) + + return drawing + + +def sampleV5c4(): + "Make sampe simple bar chart but with absolute spacing." + + drawing = Drawing(400, 200) + + data = dataSample5 + + bc = VerticalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + bc.strokeColor = colors.black + + bc.useAbsolute = 1 + bc.barWidth = 40 + bc.groupSpacing = 20 + bc.barSpacing = 10 + + bc.valueAxis.valueMin = 0 + bc.valueAxis.valueMax = 60 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'n' + bc.categoryAxis.labels.dy = -5 + bc.categoryAxis.categoryNames = ['Ying', 'Yang'] + + drawing.add(bc) + + return drawing + + +# Horizontal samples + +def sampleH0a(): + "Make a slightly pathologic bar chart with only TWO data items." + + drawing = Drawing(400, 200) + + data = [(13, 20)] + + bc = HorizontalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + + bc.strokeColor = colors.black + + bc.valueAxis.valueMin = 0 + bc.valueAxis.valueMax = 60 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'se' + bc.categoryAxis.labels.angle = 30 + bc.categoryAxis.categoryNames = ['Ying', 'Yang'] + + drawing.add(bc) + + return drawing + + +def sampleH0b(): + "Make a pathologic bar chart with only ONE data item." + + drawing = Drawing(400, 200) + + data = [(42,)] + + bc = HorizontalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + bc.strokeColor = colors.black + + bc.valueAxis.valueMin = 0 + bc.valueAxis.valueMax = 50 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'se' + bc.categoryAxis.labels.angle = 30 + bc.categoryAxis.categoryNames = ['Jan-99'] + + drawing.add(bc) + + return drawing + + +def sampleH0c(): + "Make a really pathologic bar chart with NO data items at all!" + + drawing = Drawing(400, 200) + + data = [()] + + bc = HorizontalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + bc.strokeColor = colors.black + + bc.valueAxis.valueMin = 0 + bc.valueAxis.valueMax = 60 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'se' + bc.categoryAxis.labels.angle = 30 + bc.categoryAxis.categoryNames = [] + + drawing.add(bc) + + return drawing + + +def sampleH1(): + "Sample of multi-series bar chart." + + drawing = Drawing(400, 200) + + data = [ + (13, 5, 20, 22, 37, 45, 19, 4), + (14, 6, 21, 23, 38, 46, 20, 5) + ] + + bc = HorizontalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + bc.strokeColor = colors.black + + bc.valueAxis.valueMin = 0 + bc.valueAxis.valueMax = 60 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'e' + catNames = 'Jan Feb Mar Apr May Jun Jul Aug'.split(' ') + catNames = [n+'-99' for n in catNames] + bc.categoryAxis.categoryNames = catNames + drawing.add(bc, 'barchart') + + return drawing + + +def sampleH2a(): + "Sample of multi-series bar chart." + + data = [(2.4, -5.7, 2, 5, 9.2), + (0.6, -4.9, -3, 4, 6.8) + ] + + labels = ("Q3 2000", "Year to Date", "12 months", + "Annualised\n3 years", "Since 07.10.99") + + drawing = Drawing(400, 200) + + bc = HorizontalBarChart() + bc.x = 80 + bc.y = 50 + bc.height = 120 + bc.width = 300 + bc.data = data + + bc.barSpacing = 0 + bc.groupSpacing = 10 + bc.barWidth = 10 + + bc.valueAxis.valueMin = -15 + bc.valueAxis.valueMax = +15 + bc.valueAxis.valueStep = 5 + bc.valueAxis.labels.fontName = 'Helvetica' + bc.valueAxis.labels.fontSize = 8 + bc.valueAxis.labels.boxAnchor = 'n' # irrelevant (becomes 'c') + bc.valueAxis.labels.textAnchor = 'middle' + bc.valueAxis.configure(bc.data) + + bc.categoryAxis.categoryNames = labels + bc.categoryAxis.labels.fontName = 'Helvetica' + bc.categoryAxis.labels.fontSize = 8 + bc.categoryAxis.labels.dx = -150 + + drawing.add(bc) + + return drawing + + +def sampleH2b(): + "Sample of multi-series bar chart." + + data = [(2.4, -5.7, 2, 5, 9.2), + (0.6, -4.9, -3, 4, 6.8) + ] + + labels = ("Q3 2000", "Year to Date", "12 months", + "Annualised\n3 years", "Since 07.10.99") + + drawing = Drawing(400, 200) + + bc = HorizontalBarChart() + bc.x = 80 + bc.y = 50 + bc.height = 120 + bc.width = 300 + bc.data = data + + bc.barSpacing = 5 + bc.groupSpacing = 10 + bc.barWidth = 10 + + bc.valueAxis.valueMin = -15 + bc.valueAxis.valueMax = +15 + bc.valueAxis.valueStep = 5 + bc.valueAxis.labels.fontName = 'Helvetica' + bc.valueAxis.labels.fontSize = 8 + bc.valueAxis.labels.boxAnchor = 'n' # irrelevant (becomes 'c') + bc.valueAxis.labels.textAnchor = 'middle' + + bc.categoryAxis.categoryNames = labels + bc.categoryAxis.labels.fontName = 'Helvetica' + bc.categoryAxis.labels.fontSize = 8 + bc.categoryAxis.labels.dx = -150 + + drawing.add(bc) + + return drawing + + +def sampleH2c(): + "Sample of multi-series bar chart." + + data = [(2.4, -5.7, 2, 5, 9.99), + (0.6, -4.9, -3, 4, 9.99) + ] + + labels = ("Q3 2000", "Year to Date", "12 months", + "Annualised\n3 years", "Since 07.10.99") + + drawing = Drawing(400, 200) + + bc = HorizontalBarChart() + bc.x = 80 + bc.y = 50 + bc.height = 120 + bc.width = 300 + bc.data = data + + bc.barSpacing = 2 + bc.groupSpacing = 10 + bc.barWidth = 10 + + bc.valueAxis.valueMin = -15 + bc.valueAxis.valueMax = +15 + bc.valueAxis.valueStep = 5 + bc.valueAxis.labels.fontName = 'Helvetica' + bc.valueAxis.labels.fontSize = 8 + bc.valueAxis.labels.boxAnchor = 'n' + bc.valueAxis.labels.textAnchor = 'middle' + + bc.categoryAxis.categoryNames = labels + bc.categoryAxis.labels.fontName = 'Helvetica' + bc.categoryAxis.labels.fontSize = 8 + bc.categoryAxis.labels.dx = -150 + + bc.barLabels.nudge = 10 + + bc.barLabelFormat = '%0.2f' + bc.barLabels.dx = 0 + bc.barLabels.dy = 0 + bc.barLabels.boxAnchor = 'n' # irrelevant (becomes 'c') + bc.barLabels.fontName = 'Helvetica' + bc.barLabels.fontSize = 6 + + drawing.add(bc) + + return drawing + + +def sampleH3(): + "A really horizontal bar chart (compared to the equivalent faked one)." + + names = ("UK Equities", "US Equities", "European Equities", "Japanese Equities", + "Pacific (ex Japan) Equities", "Emerging Markets Equities", + "UK Bonds", "Overseas Bonds", "UK Index-Linked", "Cash") + + series1 = (-1.5, 0.3, 0.5, 1.0, 0.8, 0.7, 0.4, 0.1, 1.0, 0.3) + series2 = (0.0, 0.33, 0.55, 1.1, 0.88, 0.77, 0.44, 0.11, 1.10, 0.33) + + assert len(names) == len(series1), "bad data" + assert len(names) == len(series2), "bad data" + + drawing = Drawing(400, 200) + + bc = HorizontalBarChart() + bc.x = 100 + bc.y = 20 + bc.height = 150 + bc.width = 250 + bc.data = (series1,) + bc.bars.fillColor = colors.green + + bc.barLabelFormat = '%0.2f' + bc.barLabels.dx = 0 + bc.barLabels.dy = 0 + bc.barLabels.boxAnchor = 'w' # irrelevant (becomes 'c') + bc.barLabels.fontName = 'Helvetica' + bc.barLabels.fontSize = 6 + bc.barLabels.nudge = 10 + + bc.valueAxis.visible = 0 + bc.valueAxis.valueMin = -2 + bc.valueAxis.valueMax = +2 + bc.valueAxis.valueStep = 1 + + bc.categoryAxis.tickLeft = 0 + bc.categoryAxis.tickRight = 0 + bc.categoryAxis.categoryNames = names + bc.categoryAxis.labels.boxAnchor = 'w' + bc.categoryAxis.labels.dx = -170 + bc.categoryAxis.labels.fontName = 'Helvetica' + bc.categoryAxis.labels.fontSize = 6 + + g = Group(bc) + drawing.add(g) + + return drawing + + +def sampleH4a(): + "A bar chart showing value axis region starting at *exactly* zero." + + drawing = Drawing(400, 200) + + data = [(13, 20)] + + bc = HorizontalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + + bc.strokeColor = colors.black + + bc.valueAxis.valueMin = 0 + bc.valueAxis.valueMax = 60 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'e' + bc.categoryAxis.categoryNames = ['Ying', 'Yang'] + + drawing.add(bc) + + return drawing + + +def sampleH4b(): + "A bar chart showing value axis region starting *below* zero." + + drawing = Drawing(400, 200) + + data = [(13, 20)] + + bc = HorizontalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + + bc.strokeColor = colors.black + + bc.valueAxis.valueMin = -10 + bc.valueAxis.valueMax = 60 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'e' + bc.categoryAxis.categoryNames = ['Ying', 'Yang'] + + drawing.add(bc) + + return drawing + + +def sampleH4c(): + "A bar chart showing value axis region starting *above* zero." + + drawing = Drawing(400, 200) + + data = [(13, 20)] + + bc = HorizontalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + + bc.strokeColor = colors.black + + bc.valueAxis.valueMin = 10 + bc.valueAxis.valueMax = 60 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'e' + bc.categoryAxis.categoryNames = ['Ying', 'Yang'] + + drawing.add(bc) + + return drawing + + +def sampleH4d(): + "A bar chart showing value axis region entirely *below* zero." + + drawing = Drawing(400, 200) + + data = [(-13, -20)] + + bc = HorizontalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + + bc.strokeColor = colors.black + + bc.valueAxis.valueMin = -30 + bc.valueAxis.valueMax = -10 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'e' + bc.categoryAxis.categoryNames = ['Ying', 'Yang'] + + drawing.add(bc) + + return drawing + + +dataSample5 = [(10, 60), (20, 50), (30, 40), (40, 30)] + +def sampleH5a(): + "A simple bar chart with no expressed spacing attributes." + + drawing = Drawing(400, 200) + + data = dataSample5 + + bc = HorizontalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + bc.strokeColor = colors.black + + bc.valueAxis.valueMin = 0 + bc.valueAxis.valueMax = 60 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'e' + bc.categoryAxis.categoryNames = ['Ying', 'Yang'] + + drawing.add(bc) + + return drawing + + +def sampleH5b(): + "A simple bar chart with proportional spacing." + + drawing = Drawing(400, 200) + + data = dataSample5 + + bc = HorizontalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + bc.strokeColor = colors.black + + bc.useAbsolute = 0 + bc.barWidth = 40 + bc.groupSpacing = 20 + bc.barSpacing = 10 + + bc.valueAxis.valueMin = 0 + bc.valueAxis.valueMax = 60 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'e' + bc.categoryAxis.categoryNames = ['Ying', 'Yang'] + + drawing.add(bc) + + return drawing + + +def sampleH5c1(): + "A simple bar chart with absolute spacing." + + drawing = Drawing(400, 200) + + data = dataSample5 + + bc = HorizontalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + bc.strokeColor = colors.black + + bc.useAbsolute = 1 + bc.barWidth = 10 + bc.groupSpacing = 0 + bc.barSpacing = 0 + + bc.valueAxis.valueMin = 0 + bc.valueAxis.valueMax = 60 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'e' + bc.categoryAxis.categoryNames = ['Ying', 'Yang'] + + drawing.add(bc) + + return drawing + + +def sampleH5c2(): + "Simple bar chart with absolute spacing." + + drawing = Drawing(400, 200) + + data = dataSample5 + + bc = HorizontalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + bc.strokeColor = colors.black + + bc.useAbsolute = 1 + bc.barWidth = 10 + bc.groupSpacing = 20 + bc.barSpacing = 0 + + bc.valueAxis.valueMin = 0 + bc.valueAxis.valueMax = 60 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'e' + bc.categoryAxis.categoryNames = ['Ying', 'Yang'] + + drawing.add(bc) + + return drawing + + +def sampleH5c3(): + "Simple bar chart with absolute spacing." + + drawing = Drawing(400, 200) + + data = dataSample5 + + bc = HorizontalBarChart() + bc.x = 50 + bc.y = 20 + bc.height = 155 + bc.width = 300 + bc.data = data + bc.strokeColor = colors.black + + bc.useAbsolute = 1 + bc.barWidth = 10 + bc.groupSpacing = 0 + bc.barSpacing = 2 + + bc.valueAxis.valueMin = 0 + bc.valueAxis.valueMax = 60 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'e' + bc.categoryAxis.categoryNames = ['Ying', 'Yang'] + + drawing.add(bc) + + return drawing + + +def sampleH5c4(): + "Simple bar chart with absolute spacing." + + drawing = Drawing(400, 200) + + data = dataSample5 + + bc = HorizontalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + bc.strokeColor = colors.black + + bc.useAbsolute = 1 + bc.barWidth = 10 + bc.groupSpacing = 20 + bc.barSpacing = 10 + + bc.valueAxis.valueMin = 0 + bc.valueAxis.valueMax = 60 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'e' + bc.categoryAxis.categoryNames = ['Ying', 'Yang'] + + drawing.add(bc) + + return drawing + +def sampleSymbol1(): + "Simple bar chart using symbol attribute." + + drawing = Drawing(400, 200) + + data = dataSample5 + + bc = VerticalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + bc.strokeColor = colors.black + + bc.barWidth = 10 + bc.groupSpacing = 15 + bc.barSpacing = 3 + + bc.valueAxis.valueMin = 0 + bc.valueAxis.valueMax = 60 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'e' + bc.categoryAxis.categoryNames = ['Ying', 'Yang'] + + from reportlab.graphics.widgets.grids import ShadedRect + sym1 = ShadedRect() + sym1.fillColorStart = colors.black + sym1.fillColorEnd = colors.blue + sym1.orientation = 'horizontal' + sym1.strokeWidth = 0 + + sym2 = ShadedRect() + sym2.fillColorStart = colors.black + sym2.fillColorEnd = colors.pink + sym2.orientation = 'horizontal' + sym2.strokeWidth = 0 + + sym3 = ShadedRect() + sym3.fillColorStart = colors.blue + sym3.fillColorEnd = colors.white + sym3.orientation = 'vertical' + sym3.cylinderMode = 1 + sym3.strokeWidth = 0 + + bc.bars.symbol = sym1 + bc.bars[2].symbol = sym2 + bc.bars[3].symbol = sym3 + + drawing.add(bc) + + return drawing + +def sampleStacked1(): + "Simple bar chart using symbol attribute." + + drawing = Drawing(400, 200) + + data = dataSample5 + + bc = VerticalBarChart() + bc.categoryAxis.style = 'stacked' + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = data + bc.strokeColor = colors.black + + bc.barWidth = 10 + bc.groupSpacing = 15 + bc.valueAxis.valueMin = 0 + + bc.categoryAxis.labels.boxAnchor = 'e' + bc.categoryAxis.categoryNames = ['Ying', 'Yang'] + + from reportlab.graphics.widgets.grids import ShadedRect + bc.bars.symbol = ShadedRect() + bc.bars.symbol.fillColorStart = colors.red + bc.bars.symbol.fillColorEnd = colors.white + bc.bars.symbol.orientation = 'vertical' + bc.bars.symbol.cylinderMode = 1 + bc.bars.symbol.strokeWidth = 0 + + bc.bars[1].symbol = ShadedRect() + bc.bars[1].symbol.fillColorStart = colors.magenta + bc.bars[1].symbol.fillColorEnd = colors.white + bc.bars[1].symbol.orientation = 'vertical' + bc.bars[1].symbol.cylinderMode = 1 + bc.bars[1].symbol.strokeWidth = 0 + + bc.bars[2].symbol = ShadedRect() + bc.bars[2].symbol.fillColorStart = colors.green + bc.bars[2].symbol.fillColorEnd = colors.white + bc.bars[2].symbol.orientation = 'vertical' + bc.bars[2].symbol.cylinderMode = 1 + bc.bars[2].symbol.strokeWidth = 0 + + bc.bars[3].symbol = ShadedRect() + bc.bars[3].symbol.fillColorStart = colors.blue + bc.bars[3].symbol.fillColorEnd = colors.white + bc.bars[3].symbol.orientation = 'vertical' + bc.bars[3].symbol.cylinderMode = 1 + bc.bars[3].symbol.strokeWidth = 0 + + drawing.add(bc) + + return drawing + +#class version of function sampleH5c4 above +class SampleH5c4(Drawing): + "Simple bar chart with absolute spacing." + + def __init__(self,width=400,height=200,*args,**kw): + Drawing.__init__(self,width,height,*args,**kw) + bc = HorizontalBarChart() + bc.x = 50 + bc.y = 50 + bc.height = 125 + bc.width = 300 + bc.data = dataSample5 + bc.strokeColor = colors.black + + bc.useAbsolute = 1 + bc.barWidth = 10 + bc.groupSpacing = 20 + bc.barSpacing = 10 + + bc.valueAxis.valueMin = 0 + bc.valueAxis.valueMax = 60 + bc.valueAxis.valueStep = 15 + + bc.categoryAxis.labels.boxAnchor = 'e' + bc.categoryAxis.categoryNames = ['Ying', 'Yang'] + + self.add(bc,name='HBC') + bc._computeSimpleBarLabelPositions() diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/dotbox.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/dotbox.py new file mode 100644 index 0000000000000000000000000000000000000000..e81404533efaea7c177343040b2e3b1952332e67 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/dotbox.py @@ -0,0 +1,165 @@ +from reportlab.lib.colors import _PCMYK_black +from reportlab.graphics.charts.textlabels import Label +from reportlab.graphics.shapes import Circle, Drawing, Group, Line, Rect, String +from reportlab.graphics.widgetbase import Widget +from reportlab.lib.attrmap import * +from reportlab.lib.validators import * +from reportlab.lib.units import cm +from reportlab.pdfbase.pdfmetrics import getFont +from reportlab.graphics.charts.lineplots import _maxWidth + +class DotBox(Widget): + """Returns a dotbox widget.""" + + #Doesn't use TypedPropertyCollection for labels - this can be a later improvement + _attrMap = AttrMap( + xlabels = AttrMapValue(isNoneOrListOfNoneOrStrings, + desc="List of text labels for boxes on left hand side"), + ylabels = AttrMapValue(isNoneOrListOfNoneOrStrings, + desc="Text label for second box on left hand side"), + labelFontName = AttrMapValue(isString, + desc="Name of font used for the labels"), + labelFontSize = AttrMapValue(isNumber, + desc="Size of font used for the labels"), + labelOffset = AttrMapValue(isNumber, + desc="Space between label text and grid edge"), + strokeWidth = AttrMapValue(isNumber, + desc='Width of the grid and dot outline'), + gridDivWidth = AttrMapValue(isNumber, + desc="Width of each 'box'"), + gridColor = AttrMapValue(isColor, + desc='Colour for the box and gridding'), + dotDiameter = AttrMapValue(isNumber, + desc="Diameter of the circle used for the 'dot'"), + dotColor = AttrMapValue(isColor, + desc='Colour of the circle on the box'), + dotXPosition = AttrMapValue(isNumber, + desc='X Position of the circle'), + dotYPosition = AttrMapValue(isNumber, + desc='X Position of the circle'), + x = AttrMapValue(isNumber, + desc='X Position of dotbox'), + y = AttrMapValue(isNumber, + desc='Y Position of dotbox'), + ) + + def __init__(self): + self.xlabels=["Value", "Blend", "Growth"] + self.ylabels=["Small", "Medium", "Large"] + self.labelFontName = "Helvetica" + self.labelFontSize = 6 + self.labelOffset = 5 + self.strokeWidth = 0.5 + self.gridDivWidth=0.5*cm + self.gridColor=colors.Color(25/255.0,77/255.0,135/255.0) + self.dotDiameter=0.4*cm + self.dotColor=colors.Color(232/255.0,224/255.0,119/255.0) + self.dotXPosition = 1 + self.dotYPosition = 1 + self.x = 30 + self.y = 5 + + + def _getDrawingDimensions(self): + leftPadding=rightPadding=topPadding=bottomPadding=5 + #find width of grid + tx=len(self.xlabels)*self.gridDivWidth + #add padding (and offset) + tx=tx+leftPadding+rightPadding+self.labelOffset + #add in maximum width of text + tx=tx+_maxWidth(self.xlabels, self.labelFontName, self.labelFontSize) + #find height of grid + ty=len(self.ylabels)*self.gridDivWidth + #add padding (and offset) + ty=ty+topPadding+bottomPadding+self.labelOffset + #add in maximum width of text + ty=ty+_maxWidth(self.ylabels, self.labelFontName, self.labelFontSize) + #print (tx, ty) + return (tx,ty) + + def demo(self,drawing=None): + if not drawing: + tx,ty=self._getDrawingDimensions() + drawing = Drawing(tx,ty) + drawing.add(self.draw()) + return drawing + + def draw(self): + g = Group() + + #box + g.add(Rect(self.x,self.y,len(self.xlabels)*self.gridDivWidth,len(self.ylabels)*self.gridDivWidth, + strokeColor=self.gridColor, + strokeWidth=self.strokeWidth, + fillColor=None)) + + #internal gridding + for f in range (1,len(self.ylabels)): + #horizontal + g.add(Line(strokeColor=self.gridColor, + strokeWidth=self.strokeWidth, + x1 = self.x, + y1 = self.y+f*self.gridDivWidth, + x2 = self.x+len(self.xlabels)*self.gridDivWidth, + y2 = self.y+f*self.gridDivWidth)) + for f in range (1,len(self.xlabels)): + #vertical + g.add(Line(strokeColor=self.gridColor, + strokeWidth=self.strokeWidth, + x1 = self.x+f*self.gridDivWidth, + y1 = self.y, + x2 = self.x+f*self.gridDivWidth, + y2 = self.y+len(self.ylabels)*self.gridDivWidth)) + + # draw the 'dot' + g.add(Circle(strokeColor=self.gridColor, + strokeWidth=self.strokeWidth, + fillColor=self.dotColor, + cx = self.x+(self.dotXPosition*self.gridDivWidth), + cy = self.y+(self.dotYPosition*self.gridDivWidth), + r = self.dotDiameter/2.0)) + + #used for centering y-labels (below) + ascent=getFont(self.labelFontName).face.ascent + if ascent==0: + ascent=0.718 # default (from helvetica) + ascent=ascent*self.labelFontSize # normalize + + #do y-labels + if self.ylabels != None: + for f in range (len(self.ylabels)-1,-1,-1): + if self.ylabels[f]!= None: + g.add(String(strokeColor=self.gridColor, + text = self.ylabels[f], + fontName = self.labelFontName, + fontSize = self.labelFontSize, + fillColor=_PCMYK_black, + x = self.x-self.labelOffset, + y = self.y+(f*self.gridDivWidth+(self.gridDivWidth-ascent)/2.0), + textAnchor = 'end')) + + #do x-labels + if self.xlabels != None: + for f in range (0,len(self.xlabels)): + if self.xlabels[f]!= None: + l=Label() + l.x=self.x+(f*self.gridDivWidth)+(self.gridDivWidth+ascent)/2.0 + l.y=self.y+(len(self.ylabels)*self.gridDivWidth)+self.labelOffset + l.angle=90 + l.textAnchor='start' + l.fontName = self.labelFontName + l.fontSize = self.labelFontSize + l.fillColor = _PCMYK_black + l.setText(self.xlabels[f]) + l.boxAnchor = 'sw' + l.draw() + g.add(l) + + return g + + + + +if __name__ == "__main__": + d = DotBox() + d.demo().save(fnRoot="dotbox") \ No newline at end of file diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/doughnut.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/doughnut.py new file mode 100644 index 0000000000000000000000000000000000000000..e5bea872257c7bac6f25f2e2217b0853b944be4d --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/doughnut.py @@ -0,0 +1,473 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/graphics/charts/doughnut.py +# doughnut chart + +__version__='3.3.0' +__doc__="""Doughnut chart + +Produces a circular chart like the doughnut charts produced by Excel. +Can handle multiple series (which produce concentric 'rings' in the chart). + +""" + +from math import sin, cos, pi +from reportlab.lib import colors +from reportlab.lib.validators import isNumber, isListOfStringsOrNone, OneOf,\ + isBoolean, isNumberOrNone, isListOfNoneOrNumber,\ + isListOfListOfNoneOrNumber, EitherOr, NoneOr, \ + isCallable +from reportlab.lib.attrmap import * +from reportlab.graphics.shapes import Group, Drawing, Wedge +from reportlab.graphics.widgetbase import TypedPropertyCollection +from reportlab.graphics.charts.piecharts import AbstractPieChart, WedgeProperties, _addWedgeLabel, fixLabelOverlaps +from reportlab.graphics.charts.areas import PlotArea +from functools import reduce + +class SectorProperties(WedgeProperties): + """This holds descriptive information about the sectors in a doughnut chart. + + It is not to be confused with the 'sector itself'; this just holds + a recipe for how to format one, and does not allow you to hack the + angles. It can format a genuine Sector object for you with its + format method. + """ + _attrMap = AttrMap(BASE=WedgeProperties, + ) + +class Doughnut(AbstractPieChart): + _attrMap = AttrMap(BASE=AbstractPieChart, + x = AttrMapValue(isNumber, desc='X position of the chart within its container.'), + y = AttrMapValue(isNumber, desc='Y position of the chart within its container.'), + width = AttrMapValue(isNumber, desc='width of doughnut bounding box. Need not be same as width.'), + height = AttrMapValue(isNumber, desc='height of doughnut bounding box. Need not be same as height.'), + data = AttrMapValue(EitherOr((isListOfNoneOrNumber,isListOfListOfNoneOrNumber)), desc='list of numbers defining sector sizes; need not sum to 1'), + labels = AttrMapValue(isListOfStringsOrNone, desc="optional list of labels to use for each data point"), + startAngle = AttrMapValue(isNumber, desc="angle of first slice; like the compass, 0 is due North"), + direction = AttrMapValue(OneOf('clockwise', 'anticlockwise'), desc="'clockwise' or 'anticlockwise'"), + slices = AttrMapValue(None, desc="collection of sector descriptor objects"), + simpleLabels = AttrMapValue(isBoolean, desc="If true(default) use String not super duper WedgeLabel"), + # advanced usage + checkLabelOverlap = AttrMapValue(isBoolean, desc="If true check and attempt to fix\n standard label overlaps(default off)",advancedUsage=1), + sideLabels = AttrMapValue(isBoolean, desc="If true attempt to make chart with labels along side and pointers", advancedUsage=1), + innerRadiusFraction = AttrMapValue(isNumberOrNone, + desc='None or the fraction of the radius to be used as the inner hole.\nIf not a suitable default will be used.'), + labelClass=AttrMapValue(NoneOr(isCallable), desc="A class factory to use for non simple labels"), + angleRange = AttrMapValue(isNumber, desc='total degree range for the doughnut defaults to 360'), + ) + + def __init__(self,**kwds): + PlotArea.__init__(self) + setattr(self,'x',kwds.pop('x',0)) + setattr(self,'y',kwds.pop('y',0)) + setattr(self,'width',kwds.pop('width',100)) + setattr(self,'height',kwds.pop('height',100)) + setattr(self,'data',kwds.pop('data',[1,1])) + setattr(self,'labels',kwds.pop('labels',None)) + setattr(self,'startAngle',kwds.pop('startAngle',90)) + setattr(self,'direction',kwds.pop('direction',"clockwise")) + setattr(self,'simpleLabels',kwds.pop('simpleLabels',1)) + setattr(self,'checkLabelOverlap',kwds.pop('checkLabelOverlap',0)) + setattr(self,'sideLabels',kwds.pop('sideLabels',0)) + setattr(self,'innerRadiusFraction',kwds.pop('innerRadiusFraction',None)) + setattr(self,'slices',kwds.pop('slices',TypedPropertyCollection(SectorProperties))) + setattr(self,'angleRange',kwds.pop('angleRange',360)) + + self.slices[0].fillColor = colors.darkcyan + self.slices[1].fillColor = colors.blueviolet + self.slices[2].fillColor = colors.blue + self.slices[3].fillColor = colors.cyan + self.slices[4].fillColor = colors.pink + self.slices[5].fillColor = colors.magenta + self.slices[6].fillColor = colors.yellow + + + def demo(self): + d = Drawing(200, 100) + + dn = Doughnut() + dn.x = 50 + dn.y = 10 + dn.width = 100 + dn.height = 80 + dn.data = [10,20,30,40,50,60] + dn.labels = ['a','b','c','d','e','f'] + + dn.slices.strokeWidth=0.5 + dn.slices[3].popout = 10 + dn.slices[3].strokeWidth = 2 + dn.slices[3].strokeDashArray = [2,2] + dn.slices[3].labelRadius = 1.75 + dn.slices[3].fontColor = colors.red + dn.slices[0].fillColor = colors.darkcyan + dn.slices[1].fillColor = colors.blueviolet + dn.slices[2].fillColor = colors.blue + dn.slices[3].fillColor = colors.cyan + dn.slices[4].fillColor = colors.aquamarine + dn.slices[5].fillColor = colors.cadetblue + dn.slices[6].fillColor = colors.lightcoral + + d.add(dn) + return d + + def normalizeData(self, data=None): + s = sum(data) + f = min(360,self.angleRange)/s if s!=0 else 1 + return [f*d for d in data] + + def makeSectors(self): + # normalize slice data + data = self.data + multi = isListOfListOfNoneOrNumber(data) + if multi: + #it's a nested list, more than one sequence + normData = [] + n = [] + for l in data: + t = self.normalizeData(l) + normData.append(t) + n.append(len(t)) + self._seriesCount = max(n) + else: + normData = self.normalizeData(data) + n = len(normData) + self._seriesCount = n + + #labels + checkLabelOverlap = self.checkLabelOverlap + L = [] + L_add = L.append + + labels = self.labels + if labels is None: + labels = [] + if not multi: + labels = [''] * n + else: + for m in n: + labels = list(labels) + [''] * m + else: + #there's no point in raising errors for less than enough labels if + #we silently create all for the extreme case of no labels. + if not multi: + i = n-len(labels) + if i>0: + labels = list(labels) + [''] * i + else: + tlab = 0 + for m in n: + tlab += m + i = tlab-len(labels) + if i>0: + labels = list(labels) + [''] * i + self.labels = labels + + xradius = self.width/2.0 + yradius = self.height/2.0 + centerx = self.x + xradius + centery = self.y + yradius + + if self.direction == "anticlockwise": + whichWay = 1 + else: + whichWay = -1 + + g = Group() + + startAngle = self.startAngle #% 360 + styleCount = len(self.slices) + irf = self.innerRadiusFraction + + if multi: + #multi-series doughnut + ndata = len(data) + if irf is None: + yir = (yradius/2.5)/ndata + xir = (xradius/2.5)/ndata + else: + yir = yradius*irf + xir = xradius*irf + ydr = (yradius-yir)/ndata + xdr = (xradius-xir)/ndata + for sn,series in enumerate(normData): + for i,angle in enumerate(series): + endAngle = (startAngle + (angle * whichWay)) #% 360 + aa = abs(startAngle-endAngle) + if aa<1e-5: + startAngle = endAngle + continue + if startAngle < endAngle: + a1 = startAngle + a2 = endAngle + else: + a1 = endAngle + a2 = startAngle + startAngle = endAngle + + #if we didn't use %stylecount here we'd end up with the later sectors + #all having the default style + sectorStyle = self.slices[sn,i%styleCount] + + # is it a popout? + cx, cy = centerx, centery + if sectorStyle.popout != 0: + # pop out the sector + averageAngle = (a1+a2)/2.0 + aveAngleRadians = averageAngle * pi/180.0 + popdistance = sectorStyle.popout + cx = centerx + popdistance * cos(aveAngleRadians) + cy = centery + popdistance * sin(aveAngleRadians) + + yr1 = yir+sn*ydr + yr = yr1 + ydr + xr1 = xir+sn*xdr + xr = xr1 + xdr + if len(series) > 1: + theSector = Wedge(cx, cy, xr, a1, a2, yradius=yr, radius1=xr1, yradius1=yr1) + else: + theSector = Wedge(cx, cy, xr, a1, a2, yradius=yr, radius1=xr1, yradius1=yr1, annular=True) + + theSector.fillColor = sectorStyle.fillColor + theSector.strokeColor = sectorStyle.strokeColor + theSector.strokeWidth = sectorStyle.strokeWidth + theSector.strokeDashArray = sectorStyle.strokeDashArray + + shader = sectorStyle.shadingKind + if shader: + nshades = aa / float(sectorStyle.shadingAngle) + if nshades > 1: + shader = colors.Whiter if shader=='lighten' else colors.Blacker + nshades = 1+int(nshades) + shadingAmount = 1-sectorStyle.shadingAmount + if sectorStyle.shadingDirection=='normal': + dsh = (1-shadingAmount)/float(nshades-1) + shf1 = shadingAmount + else: + dsh = (shadingAmount-1)/float(nshades-1) + shf1 = 1 + shda = (a2-a1)/float(nshades) + shsc = sectorStyle.fillColor + theSector.fillColor = None + for ish in range(nshades): + sha1 = a1 + ish*shda + sha2 = a1 + (ish+1)*shda + shc = shader(shsc,shf1 + dsh*ish) + if len(series)>1: + shSector = Wedge(cx, cy, xr, sha1, sha2, yradius=yr, radius1=xr1, yradius1=yr1) + else: + shSector = Wedge(cx, cy, xr, sha1, sha2, yradius=yr, radius1=xr1, yradius1=yr1, annular=True) + shSector.fillColor = shc + shSector.strokeColor = None + shSector.strokeWidth = 0 + g.add(shSector) + + g.add(theSector) + + if sn == 0 and sectorStyle.visible and sectorStyle.label_visible: + text = self.getSeriesName(i,'') + if text: + averageAngle = (a1+a2)/2.0 + aveAngleRadians = averageAngle*pi/180.0 + labelRadius = sectorStyle.labelRadius + rx = xradius*labelRadius + ry = yradius*labelRadius + labelX = centerx + (0.5 * self.width * cos(aveAngleRadians) * labelRadius) + labelY = centery + (0.5 * self.height * sin(aveAngleRadians) * labelRadius) + l = _addWedgeLabel(self,text,averageAngle,labelX,labelY,sectorStyle) + if checkLabelOverlap: + l._origdata = { 'x': labelX, 'y':labelY, 'angle': averageAngle, + 'rx': rx, 'ry':ry, 'cx':cx, 'cy':cy, + 'bounds': l.getBounds(), + } + L_add(l) + + else: + #single series doughnut + if irf is None: + yir = yradius/2.5 + xir = xradius/2.5 + else: + yir = yradius*irf + xir = xradius*irf + for i,angle in enumerate(normData): + endAngle = (startAngle + (angle * whichWay)) #% 360 + aa = abs(startAngle-endAngle) + if aa<1e-5: + startAngle = endAngle + continue + if startAngle < endAngle: + a1 = startAngle + a2 = endAngle + else: + a1 = endAngle + a2 = startAngle + startAngle = endAngle + + #if we didn't use %stylecount here we'd end up with the later sectors + #all having the default style + sectorStyle = self.slices[i%styleCount] + + # is it a popout? + cx, cy = centerx, centery + if sectorStyle.popout != 0: + # pop out the sector + averageAngle = (a1+a2)/2.0 + aveAngleRadians = averageAngle * pi/180.0 + popdistance = sectorStyle.popout + cx = centerx + popdistance * cos(aveAngleRadians) + cy = centery + popdistance * sin(aveAngleRadians) + + if n > 1: + theSector = Wedge(cx, cy, xradius, a1, a2, yradius=yradius, radius1=xir, yradius1=yir) + elif n==1: + theSector = Wedge(cx, cy, xradius, a1, a2, yradius=yradius, radius1=xir, yradius1=yir, annular=True) + + theSector.fillColor = sectorStyle.fillColor + theSector.strokeColor = sectorStyle.strokeColor + theSector.strokeWidth = sectorStyle.strokeWidth + theSector.strokeDashArray = sectorStyle.strokeDashArray + + shader = sectorStyle.shadingKind + if shader: + nshades = aa / float(sectorStyle.shadingAngle) + if nshades > 1: + shader = colors.Whiter if shader=='lighten' else colors.Blacker + nshades = 1+int(nshades) + shadingAmount = 1-sectorStyle.shadingAmount + if sectorStyle.shadingDirection=='normal': + dsh = (1-shadingAmount)/float(nshades-1) + shf1 = shadingAmount + else: + dsh = (shadingAmount-1)/float(nshades-1) + shf1 = 1 + shda = (a2-a1)/float(nshades) + shsc = sectorStyle.fillColor + theSector.fillColor = None + for ish in range(nshades): + sha1 = a1 + ish*shda + sha2 = a1 + (ish+1)*shda + shc = shader(shsc,shf1 + dsh*ish) + if n > 1: + shSector = Wedge(cx, cy, xradius, sha1, sha2, yradius=yradius, radius1=xir, yradius1=yir) + elif n==1: + shSector = Wedge(cx, cy, xradius, sha1, sha2, yradius=yradius, radius1=xir, yradius1=yir, annular=True) + shSector.fillColor = shc + shSector.strokeColor = None + shSector.strokeWidth = 0 + g.add(shSector) + + g.add(theSector) + + # now draw a label + if labels[i] and sectorStyle.visible and sectorStyle.label_visible: + averageAngle = (a1+a2)/2.0 + aveAngleRadians = averageAngle*pi/180.0 + labelRadius = sectorStyle.labelRadius + labelX = centerx + (0.5 * self.width * cos(aveAngleRadians) * labelRadius) + labelY = centery + (0.5 * self.height * sin(aveAngleRadians) * labelRadius) + rx = xradius*labelRadius + ry = yradius*labelRadius + l = _addWedgeLabel(self,labels[i],averageAngle,labelX,labelY,sectorStyle) + if checkLabelOverlap: + l._origdata = { 'x': labelX, 'y':labelY, 'angle': averageAngle, + 'rx': rx, 'ry':ry, 'cx':cx, 'cy':cy, + 'bounds': l.getBounds(), + } + L_add(l) + + if checkLabelOverlap and L: + fixLabelOverlaps(L) + + for l in L: g.add(l) + + return g + + def draw(self): + g = Group() + g.add(self.makeSectors()) + return g + + +def sample1(): + "Make up something from the individual Sectors" + + d = Drawing(400, 400) + g = Group() + + s1 = Wedge(centerx=200, centery=200, radius=150, startangledegrees=0, endangledegrees=120, radius1=100) + s1.fillColor=colors.red + s1.strokeColor=None + d.add(s1) + s2 = Wedge(centerx=200, centery=200, radius=150, startangledegrees=120, endangledegrees=240, radius1=100) + s2.fillColor=colors.green + s2.strokeColor=None + d.add(s2) + s3 = Wedge(centerx=200, centery=200, radius=150, startangledegrees=240, endangledegrees=260, radius1=100) + s3.fillColor=colors.blue + s3.strokeColor=None + d.add(s3) + s4 = Wedge(centerx=200, centery=200, radius=150, startangledegrees=260, endangledegrees=360, radius1=100) + s4.fillColor=colors.gray + s4.strokeColor=None + d.add(s4) + + return d + +def sample2(): + "Make a simple demo" + + d = Drawing(400, 400) + + dn = Doughnut() + dn.x = 50 + dn.y = 50 + dn.width = 300 + dn.height = 300 + dn.data = [10,20,30,40,50,60] + + d.add(dn) + + return d + +def sample3(): + "Make a more complex demo" + + d = Drawing(400, 400) + dn = Doughnut() + dn.x = 50 + dn.y = 50 + dn.width = 300 + dn.height = 300 + dn.data = [[10,20,30,40,50,60], [10,20,30,40]] + dn.labels = ['a','b','c','d','e','f'] + + d.add(dn) + + return d + +def sample4(): + "Make a more complex demo with Label Overlap fixing" + + d = Drawing(400, 400) + dn = Doughnut() + dn.x = 50 + dn.y = 50 + dn.width = 300 + dn.height = 300 + dn.data = [[10,20,30,40,50,60], [10,20,30,40]] + dn.labels = ['a','b','c','d','e','f'] + dn.checkLabelOverlap = True + + d.add(dn) + + return d + +if __name__=='__main__': + + from reportlab.graphics.renderPDF import drawToFile + d = sample1() + drawToFile(d, 'doughnut1.pdf') + d = sample2() + drawToFile(d, 'doughnut2.pdf') + d = sample3() + drawToFile(d, 'doughnut3.pdf') diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/legends.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/legends.py new file mode 100644 index 0000000000000000000000000000000000000000..5731ecca53d47601b660064854a2ab421530e964 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/legends.py @@ -0,0 +1,647 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/graphics/charts/legends.py + +__version__='3.3.0' +__doc__="""This will be a collection of legends to be used with charts.""" + +import copy + +from reportlab.lib import colors +from reportlab.lib.validators import isNumber, OneOf, isString, isColorOrNone,\ + isNumberOrNone, isListOfNumbersOrNone, isBoolean,\ + EitherOr, NoneOr, AutoOr, isAuto, Auto, isBoxAnchor, SequenceOf, isInstanceOf +from reportlab.lib.attrmap import * +from reportlab.pdfbase.pdfmetrics import stringWidth, getFont +from reportlab.graphics.widgetbase import Widget, TypedPropertyCollection, PropHolder +from reportlab.graphics.shapes import Drawing, Group, String, Rect, Line, STATE_DEFAULTS +from reportlab.graphics.widgets.markers import uSymbol2Symbol, isSymbol +from reportlab.lib.utils import isSeq, find_locals, isStr, asNative +from reportlab.graphics.shapes import _baseGFontName + +def _transMax(n,A): + X = n*[0] + m = 0 + for a in A: + m = max(m,len(a)) + for i,x in enumerate(a): + X[i] = max(X[i],x) + X = [0] + X[:m] + for i in range(m): + X[i+1] += X[i] + return X + +def _objStr(s): + if isStr(s): + return asNative(s) + else: + return str(s) + +def _getStr(s): + if isSeq(s): + return list(map(_getStr,s)) + else: + return _objStr(s) + +def _getLines(s): + if isSeq(s): + return tuple([(x or '').split('\n') for x in s]) + else: + return (s or '').split('\n') + +def _getLineCount(s): + T = _getLines(s) + if isSeq(s): + return max([len(x) for x in T]) + else: + return len(T) + +def _getWidths(i,s, fontName, fontSize, subCols): + S = [] + aS = S.append + if isSeq(s): + for j,t in enumerate(s): + sc = subCols[j,i] + fN = getattr(sc,'fontName',fontName) + fS = getattr(sc,'fontSize',fontSize) + m = [stringWidth(x, fN, fS) for x in t.split('\n')] + m = max(sc.minWidth,m and max(m) or 0) + aS(m) + aS(sc.rpad) + del S[-1] + else: + sc = subCols[0,i] + fN = getattr(sc,'fontName',fontName) + fS = getattr(sc,'fontSize',fontSize) + m = [stringWidth(x, fN, fS) for x in s.split('\n')] + aS(max(sc.minWidth,m and max(m) or 0)) + return S + +class SubColProperty(PropHolder): + dividerLines = 0 + _attrMap = AttrMap( + minWidth = AttrMapValue(isNumber,desc="minimum width for this subcol"), + rpad = AttrMapValue(isNumber,desc="right padding for this subcol"), + align = AttrMapValue(OneOf('left','right','center','centre','numeric'),desc='alignment in subCol'), + fontName = AttrMapValue(isString, desc="Font name of the strings"), + fontSize = AttrMapValue(isNumber, desc="Font size of the strings"), + leading = AttrMapValue(isNumberOrNone, desc="leading for the strings"), + fillColor = AttrMapValue(isColorOrNone, desc="fontColor"), + underlines = AttrMapValue(EitherOr((NoneOr(isInstanceOf(Line)),SequenceOf(isInstanceOf(Line),emptyOK=0,lo=0,hi=0x7fffffff))), desc="underline definitions"), + overlines = AttrMapValue(EitherOr((NoneOr(isInstanceOf(Line)),SequenceOf(isInstanceOf(Line),emptyOK=0,lo=0,hi=0x7fffffff))), desc="overline definitions"), + dx = AttrMapValue(isNumber, desc="x offset from default position"), + dy = AttrMapValue(isNumber, desc="y offset from default position"), + vAlign = AttrMapValue(OneOf('top','bottom','middle'),desc='vertical alignment in the row'), + ) + +class LegendCallout: + def _legendValues(legend,*args): + '''return a tuple of values from the first function up the stack with isinstance(self,legend)''' + L = find_locals(lambda L: L.get('self',None) is legend and L or None) + return tuple([L[a] for a in args]) + _legendValues = staticmethod(_legendValues) + + def _selfOrLegendValues(self,legend,*args): + L = find_locals(lambda L: L.get('self',None) is legend and L or None) + return tuple([getattr(self,a,L[a]) for a in args]) + + def __call__(self,legend,g,thisx,y,colName): + col, name = colName + +class LegendSwatchCallout(LegendCallout): + def __call__(self,legend,g,thisx,y,i,colName,swatch): + col, name = colName + +class LegendColEndCallout(LegendCallout): + def __call__(self,legend, g, x, xt, y, width, lWidth): + pass + +class Legend(Widget): + """A simple legend containing rectangular swatches and strings. + + The swatches are filled rectangles whenever the respective + color object in 'colorNamePairs' is a subclass of Color in + reportlab.lib.colors. Otherwise the object passed instead is + assumed to have 'x', 'y', 'width' and 'height' attributes. + A legend then tries to set them or catches any error. This + lets you plug-in any widget you like as a replacement for + the default rectangular swatches. + + Strings can be nicely aligned left or right to the swatches. + """ + + _attrMap = AttrMap( + x = AttrMapValue(isNumber, desc="x-coordinate of upper-left reference point"), + y = AttrMapValue(isNumber, desc="y-coordinate of upper-left reference point"), + deltax = AttrMapValue(isNumberOrNone, desc="x-distance between neighbouring swatches"), + deltay = AttrMapValue(isNumberOrNone, desc="y-distance between neighbouring swatches"), + dxTextSpace = AttrMapValue(isNumber, desc="Distance between swatch rectangle and text"), + autoXPadding = AttrMapValue(isNumber, desc="x Padding between columns if deltax=None",advancedUsage=1), + autoYPadding = AttrMapValue(isNumber, desc="y Padding between rows if deltay=None",advancedUsage=1), + yGap = AttrMapValue(isNumber, desc="Additional gap between rows",advancedUsage=1), + dx = AttrMapValue(isNumber, desc="Width of swatch rectangle"), + dy = AttrMapValue(isNumber, desc="Height of swatch rectangle"), + columnMaximum = AttrMapValue(isNumber, desc="Max. number of items per column"), + alignment = AttrMapValue(OneOf("left", "right"), desc="Alignment of text with respect to swatches"), + colorNamePairs = AttrMapValue(None, desc="List of color/name tuples (color can also be widget)"), + fontName = AttrMapValue(isString, desc="Font name of the strings"), + fontSize = AttrMapValue(isNumber, desc="Font size of the strings"), + leading = AttrMapValue(isNumberOrNone, desc="text leading"), + fillColor = AttrMapValue(isColorOrNone, desc="swatches filling color"), + strokeColor = AttrMapValue(isColorOrNone, desc="Border color of the swatches"), + strokeWidth = AttrMapValue(isNumber, desc="Width of the border color of the swatches"), + swatchMarker = AttrMapValue(NoneOr(AutoOr(isSymbol)), desc="None, Auto() or makeMarker('Diamond') ...",advancedUsage=1), + callout = AttrMapValue(None, desc="a user callout(self,g,x,y,(color,text))",advancedUsage=1), + boxAnchor = AttrMapValue(isBoxAnchor,'Anchor point for the legend area'), + variColumn = AttrMapValue(isBoolean,'If true column widths may vary (default is false)',advancedUsage=1), + dividerLines = AttrMapValue(OneOf(0,1,2,3,4,5,6,7),'If 1 we have dividers between the rows | 2 for extra top | 4 for bottom',advancedUsage=1), + dividerWidth = AttrMapValue(isNumber, desc="dividerLines width",advancedUsage=1), + dividerColor = AttrMapValue(isColorOrNone, desc="dividerLines color",advancedUsage=1), + dividerDashArray = AttrMapValue(isListOfNumbersOrNone, desc='Dash array for dividerLines.',advancedUsage=1), + dividerOffsX = AttrMapValue(SequenceOf(isNumber,emptyOK=0,lo=2,hi=2), desc='divider lines X offsets',advancedUsage=1), + dividerOffsY = AttrMapValue(isNumber, desc="dividerLines Y offset",advancedUsage=1), + colEndCallout = AttrMapValue(None, desc="a user callout(self,g, x, xt, y,width, lWidth)",advancedUsage=1), + subCols = AttrMapValue(None,desc="subColumn properties"), + swatchCallout = AttrMapValue(None, desc="a user swatch callout(self,g,x,y,i,(col,name),swatch)",advancedUsage=1), + swdx = AttrMapValue(isNumber, desc="x position adjustment for the swatch"), + swdy = AttrMapValue(isNumber, desc="y position adjustment for the swatch"), + ) + + def __init__(self): + # Upper-left reference point. + self.x = 0 + self.y = 0 + + # Alginment of text with respect to swatches. + self.alignment = "left" + + # x- and y-distances between neighbouring swatches. + self.deltax = 75 + self.deltay = 20 + self.autoXPadding = 5 + self.autoYPadding = 2 + + # Size of swatch rectangle. + self.dx = 10 + self.dy = 10 + + self.swdx = 0 + self.swdy = 0 + + # Distance between swatch rectangle and text. + self.dxTextSpace = 10 + + # Max. number of items per column. + self.columnMaximum = 3 + + # Color/name pairs. + self.colorNamePairs = [ (colors.red, "red"), + (colors.blue, "blue"), + (colors.green, "green"), + (colors.pink, "pink"), + (colors.yellow, "yellow") ] + + # Font name and size of the labels. + self.fontName = STATE_DEFAULTS['fontName'] + self.fontSize = STATE_DEFAULTS['fontSize'] + self.leading = None #will be used as 1.2*fontSize + self.fillColor = STATE_DEFAULTS['fillColor'] + self.strokeColor = STATE_DEFAULTS['strokeColor'] + self.strokeWidth = STATE_DEFAULTS['strokeWidth'] + self.swatchMarker = None + self.boxAnchor = 'nw' + self.yGap = 0 + self.variColumn = 0 + self.dividerLines = 0 + self.dividerWidth = 0.5 + self.dividerDashArray = None + self.dividerColor = colors.black + self.dividerOffsX = (0,0) + self.dividerOffsY = 0 + self.colEndCallout = None + self._init_subCols() + + def _init_subCols(self): + sc = self.subCols = TypedPropertyCollection(SubColProperty) + sc.rpad = 1 + sc.dx = sc.dy = sc.minWidth = 0 + sc.align = 'right' + sc[0].align = 'left' + sc.vAlign = 'top' #that's current + sc.leading = None + + def _getChartStyleName(self,chart): + for a in 'lines', 'bars', 'slices', 'strands': + if hasattr(chart,a): return a + return None + + def _getChartStyle(self,chart): + return getattr(chart,self._getChartStyleName(chart),None) + + def _getTexts(self,colorNamePairs): + if not isAuto(colorNamePairs): + texts = [_getStr(p[1]) for p in colorNamePairs] + else: + chart = getattr(colorNamePairs,'chart',getattr(colorNamePairs,'obj',None)) + texts = [chart.getSeriesName(i,'series %d' % i) for i in range(chart._seriesCount)] + return texts + + def _calculateMaxBoundaries(self, colorNamePairs): + "Calculate the maximum width of some given strings." + fontName = self.fontName + fontSize = self.fontSize + subCols = self.subCols + + M = [_getWidths(i, m, fontName, fontSize, subCols) for i,m in enumerate(self._getTexts(colorNamePairs))] + if not M: + return [0,0] + n = max([len(m) for m in M]) + if self.variColumn: + columnMaximum = self.columnMaximum + return [_transMax(n,M[r:r+columnMaximum]) for r in range(0,len(M),self.columnMaximum)] + else: + return _transMax(n,M) + + def _calcHeight(self): + dy = self.dy + yGap = self.yGap + thisy = upperlefty = self.y - dy + fontSize = self.fontSize + fontName = self.fontName + ascent=getFont(fontName).face.ascent/1000. + if ascent==0: ascent=0.718 # default (from helvetica) + ascent *= fontSize + leading = fontSize*1.2 + deltay = self.deltay + if not deltay: deltay = max(dy,leading)+self.autoYPadding + columnCount = 0 + count = 0 + lowy = upperlefty + lim = self.columnMaximum - 1 + for name in self._getTexts(self.colorNamePairs): + y0 = thisy+(dy-ascent)*0.5 + y = y0 - _getLineCount(name)*leading + leadingMove = 2*y0-y-thisy + newy = thisy-max(deltay,leadingMove)-yGap + lowy = min(y,newy,lowy) + if count==lim: + count = 0 + thisy = upperlefty + columnCount += 1 + else: + thisy = newy + count = count+1 + return upperlefty - lowy + + def _defaultSwatch(self,x,thisy,dx,dy,fillColor,strokeWidth,strokeColor): + return Rect(x, thisy, dx, dy, + fillColor = fillColor, + strokeColor = strokeColor, + strokeWidth = strokeWidth, + ) + + def draw(self): + colorNamePairs = self.colorNamePairs + autoCP = isAuto(colorNamePairs) + if autoCP: + chart = getattr(colorNamePairs,'chart',getattr(colorNamePairs,'obj',None)) + swatchMarker = None + autoCP = Auto(obj=chart) + n = chart._seriesCount + chartTexts = self._getTexts(colorNamePairs) + else: + swatchMarker = getattr(self,'swatchMarker',None) + if isAuto(swatchMarker): + chart = getattr(swatchMarker,'chart',getattr(swatchMarker,'obj',None)) + swatchMarker = Auto(obj=chart) + n = len(colorNamePairs) + dx = self.dx + dy = self.dy + alignment = self.alignment + columnMaximum = self.columnMaximum + deltax = self.deltax + deltay = self.deltay + dxTextSpace = self.dxTextSpace + fontName = self.fontName + fontSize = self.fontSize + fillColor = self.fillColor + strokeWidth = self.strokeWidth + strokeColor = self.strokeColor + subCols = self.subCols + leading = fontSize*1.2 + yGap = self.yGap + if not deltay: + deltay = max(dy,leading)+self.autoYPadding + ba = self.boxAnchor + maxWidth = self._calculateMaxBoundaries(colorNamePairs) + nCols = int((n+columnMaximum-1)/(columnMaximum*1.0)) + xW = dx+dxTextSpace+self.autoXPadding + variColumn = self.variColumn + if variColumn: + width = sum([m[-1] for m in maxWidth])+xW*nCols + else: + deltax = max(maxWidth[-1]+xW,deltax) + width = nCols*deltax + maxWidth = nCols*[maxWidth] + + thisx = self.x + thisy = self.y - self.dy + if ba not in ('ne','n','nw','autoy'): + height = self._calcHeight() + if ba in ('e','c','w'): + thisy += height/2. + else: + thisy += height + if ba not in ('nw','w','sw','autox'): + if ba in ('n','c','s'): + thisx -= width/2 + else: + thisx -= width + upperlefty = thisy + + g = Group() + + ascent=getFont(fontName).face.ascent/1000. + if ascent==0: ascent=0.718 # default (from helvetica) + ascent *= fontSize # normalize + + lim = columnMaximum - 1 + callout = getattr(self,'callout',None) + scallout = getattr(self,'swatchCallout',None) + dividerLines = self.dividerLines + if dividerLines: + dividerWidth = self.dividerWidth + dividerColor = self.dividerColor + dividerDashArray = self.dividerDashArray + dividerOffsX = self.dividerOffsX + dividerOffsY = self.dividerOffsY + + for i in range(n): + if autoCP: + col = autoCP + col.index = i + name = chartTexts[i] + else: + col, name = colorNamePairs[i] + if isAuto(swatchMarker): + col = swatchMarker + col.index = i + if isAuto(name): + name = getattr(swatchMarker,'chart',getattr(swatchMarker,'obj',None)).getSeriesName(i,'series %d' % i) + T = _getLines(name) + S = [] + aS = S.append + j = int(i/(columnMaximum*1.0)) + jOffs = maxWidth[j] + + # thisy+dy/2 = y+leading/2 + y = y0 = thisy+(dy-ascent)*0.5 + + if callout: callout(self,g,thisx,y,(col,name)) + if alignment == "left": + x = thisx + xn = thisx+jOffs[-1]+dxTextSpace + elif alignment == "right": + x = thisx+dx+dxTextSpace + xn = thisx + else: + raise ValueError("bad alignment") + if not isSeq(name): + T = [T] + lineCount = _getLineCount(name) + yd = y + for k,lines in enumerate(T): + y = y0 + kk = k*2 + x1 = x+jOffs[kk] + x2 = x+jOffs[kk+1] + sc = subCols[k,i] + anchor = sc.align + scdx = sc.dx + scdy = sc.dy + fN = getattr(sc,'fontName',fontName) + fS = getattr(sc,'fontSize',fontSize) + fC = getattr(sc,'fillColor',fillColor) + fL = sc.leading or 1.2*fontSize + if fN==fontName: + fA = (ascent*fS)/fontSize + else: + fA = getFont(fontName).face.ascent/1000. + if fA==0: fA=0.718 + fA *= fS + + vA = sc.vAlign + if vA=='top': + vAdy = 0 + else: + vAdy = -fL * (lineCount - len(lines)) + if vA=='middle': vAdy *= 0.5 + + if anchor=='left': + anchor = 'start' + xoffs = x1 + elif anchor=='right': + anchor = 'end' + xoffs = x2 + elif anchor=='numeric': + xoffs = x2 + else: + anchor = 'middle' + xoffs = 0.5*(x1+x2) + for t in lines: + aS(String(xoffs+scdx,y+scdy+vAdy,t,fontName=fN,fontSize=fS,fillColor=fC, textAnchor = anchor)) + y -= fL + yd = min(yd,y) + y += fL + for iy, a in ((y-max(fL-fA,0),'underlines'),(y+fA,'overlines')): + il = getattr(sc,a,None) + if il: + if not isinstance(il,(tuple,list)): il = (il,) + for l in il: + l = copy.copy(l) + l.y1 += iy + l.y2 += iy + l.x1 += x1 + l.x2 += x2 + aS(l) + x = xn + y = yd + leadingMove = 2*y0-y-thisy + + if dividerLines: + xd = thisx+dx+dxTextSpace+jOffs[-1]+dividerOffsX[1] + yd = thisy+dy*0.5+dividerOffsY + if ((dividerLines&1) and i%columnMaximum) or ((dividerLines&2) and not i%columnMaximum): + g.add(Line(thisx+dividerOffsX[0],yd,xd,yd, + strokeColor=dividerColor, strokeWidth=dividerWidth, strokeDashArray=dividerDashArray)) + + if (dividerLines&4) and (i%columnMaximum==lim or i==(n-1)): + yd -= max(deltay,leadingMove)+yGap + g.add(Line(thisx+dividerOffsX[0],yd,xd,yd, + strokeColor=dividerColor, strokeWidth=dividerWidth, strokeDashArray=dividerDashArray)) + + # Make a 'normal' color swatch... + swatchX = x + getattr(self,'swdx',0) + swatchY = thisy + getattr(self,'swdy',0) + + if isAuto(col): + chart = getattr(col,'chart',getattr(col,'obj',None)) + c = chart.makeSwatchSample(getattr(col,'index',i),swatchX,swatchY,dx,dy) + elif isinstance(col, colors.Color): + if isSymbol(swatchMarker): + c = uSymbol2Symbol(swatchMarker,swatchX+dx/2.,swatchY+dy/2.,col) + else: + c = self._defaultSwatch(swatchX,swatchY,dx,dy,fillColor=col,strokeWidth=strokeWidth,strokeColor=strokeColor) + elif col is not None: + try: + c = copy.deepcopy(col) + c.x = swatchX + c.y = swatchY + c.width = dx + c.height = dy + except: + c = None + else: + c = None + + if c: + g.add(c) + if scallout: scallout(self,g,thisx,y0,i,(col,name),c) + + for s in S: g.add(s) + if self.colEndCallout and (i%columnMaximum==lim or i==(n-1)): + if alignment == "left": + xt = thisx + else: + xt = thisx+dx+dxTextSpace + yd = thisy+dy*0.5+dividerOffsY - (max(deltay,leadingMove)+yGap) + self.colEndCallout(self, g, thisx, xt, yd, jOffs[-1], jOffs[-1]+dx+dxTextSpace) + + if i%columnMaximum==lim: + if variColumn: + thisx += jOffs[-1]+xW + else: + thisx = thisx+deltax + thisy = upperlefty + else: + thisy = thisy-max(deltay,leadingMove)-yGap + + return g + + def demo(self): + "Make sample legend." + + d = Drawing(200, 100) + + legend = Legend() + legend.alignment = 'left' + legend.x = 0 + legend.y = 100 + legend.dxTextSpace = 5 + items = 'red green blue yellow pink black white'.split() + items = [(getattr(colors, i), i) for i in items] + legend.colorNamePairs = items + + d.add(legend, 'legend') + + return d + +class TotalAnnotator(LegendColEndCallout): + def __init__(self, lText='Total', rText='0.0', fontName=_baseGFontName, fontSize=10, + fillColor=colors.black, strokeWidth=0.5, strokeColor=colors.black, strokeDashArray=None, + dx=0, dy=0, dly=0, dlx=(0,0)): + self.lText = lText + self.rText = rText + self.fontName = fontName + self.fontSize = fontSize + self.fillColor = fillColor + self.dy = dy + self.dx = dx + self.dly = dly + self.dlx = dlx + self.strokeWidth = strokeWidth + self.strokeColor = strokeColor + self.strokeDashArray = strokeDashArray + + def __call__(self,legend, g, x, xt, y, width, lWidth): + from reportlab.graphics.shapes import String, Line + fontSize = self.fontSize + fontName = self.fontName + fillColor = self.fillColor + strokeColor = self.strokeColor + strokeWidth = self.strokeWidth + ascent=getFont(fontName).face.ascent/1000. + if ascent==0: ascent=0.718 # default (from helvetica) + ascent *= fontSize + leading = fontSize*1.2 + yt = y+self.dy-ascent*1.3 + if self.lText and fillColor: + g.add(String(xt,yt,self.lText, + fontName=fontName, + fontSize=fontSize, + fillColor=fillColor, + textAnchor = "start")) + if self.rText: + g.add(String(xt+width,yt,self.rText, + fontName=fontName, + fontSize=fontSize, + fillColor=fillColor, + textAnchor = "end")) + if strokeWidth and strokeColor: + yL = y+self.dly-leading + g.add(Line(x+self.dlx[0],yL,x+self.dlx[1]+lWidth,yL, + strokeColor=strokeColor, strokeWidth=strokeWidth, + strokeDashArray=self.strokeDashArray)) + +class LineSwatch(Widget): + """basically a Line with properties added so it can be used in a LineLegend""" + _attrMap = AttrMap( + x = AttrMapValue(isNumber, desc="x-coordinate for swatch line start point"), + y = AttrMapValue(isNumber, desc="y-coordinate for swatch line start point"), + width = AttrMapValue(isNumber, desc="length of swatch line"), + height = AttrMapValue(isNumber, desc="used for line strokeWidth"), + strokeColor = AttrMapValue(isColorOrNone, desc="color of swatch line"), + strokeWidth = AttrMapValue(isNumberOrNone, desc="thickness of the swatch"), + strokeDashArray = AttrMapValue(isListOfNumbersOrNone, desc="dash array for swatch line"), + ) + + def __init__(self): + from reportlab.lib.colors import red + self.x = 0 + self.y = 0 + self.width = 20 + self.height = 1 + self.strokeColor = red + self.strokeDashArray = None + self.strokeWidth = 1 + + def draw(self): + l = Line(self.x,self.y,self.x+self.width,self.y) + l.strokeColor = self.strokeColor + l.strokeDashArray = self.strokeDashArray + l.strokeWidth = self.strokeWidth + return l + +class LineLegend(Legend): + """A subclass of Legend for drawing legends with lines as the + swatches rather than rectangles. Useful for lineCharts and + linePlots. Should be similar in all other ways the the standard + Legend class. + """ + + def __init__(self): + Legend.__init__(self) + + # Size of swatch rectangle. + self.dx = 10 + self.dy = 2 + + def _defaultSwatch(self,x,thisy,dx,dy,fillColor,strokeWidth,strokeColor): + l = LineSwatch() + l.x = x + l.y = thisy + l.width = dx + l.height = dy + l.strokeColor = fillColor + l.strokeWidth = strokeWidth + return l diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/linecharts.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/linecharts.py new file mode 100644 index 0000000000000000000000000000000000000000..4973a5a45b8c44bcd88c07951f26326bfaeb3c02 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/linecharts.py @@ -0,0 +1,801 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/graphics/charts/linecharts.py + +__version__='3.3.0' +__doc__="""This modules defines a very preliminary Line Chart example.""" + +from reportlab.lib import colors +from reportlab.lib.validators import isNumber, isNumberOrNone, isColorOrNone, \ + isListOfStringsOrNone, isBoolean, NoneOr, \ + isListOfNumbersOrNone, isStringOrNone, OneOf, Percentage +from reportlab.lib.attrmap import * +from reportlab.lib.utils import flatten +from reportlab.graphics.widgetbase import TypedPropertyCollection, PropHolder, tpcGetItem +from reportlab.graphics.shapes import Line, Rect, Group, Drawing, Polygon, PolyLine +from reportlab.graphics.widgets.signsandsymbols import NoEntry +from reportlab.graphics.charts.axes import XCategoryAxis, YValueAxis, YCategoryAxis, XValueAxis +from reportlab.graphics.charts.textlabels import Label +from reportlab.graphics.widgets.markers import uSymbol2Symbol, isSymbol, makeMarker +from reportlab.graphics.charts.areas import PlotArea +from reportlab.graphics.charts.legends import _objStr +from .utils import FillPairedData + +class LineChartProperties(PropHolder): + _attrMap = AttrMap( + strokeWidth = AttrMapValue(isNumber, desc='Width of a line.'), + strokeColor = AttrMapValue(isColorOrNone, desc='Color of a line or border.'), + fillColor = AttrMapValue(isColorOrNone, desc='fill color of a bar.'), + strokeDashArray = AttrMapValue(isListOfNumbersOrNone, desc='Dash array of a line.'), + symbol = AttrMapValue(NoneOr(isSymbol), desc='Widget placed at data points.',advancedUsage=1), + shader = AttrMapValue(None, desc='Shader Class.',advancedUsage=1), + filler = AttrMapValue(None, desc='Filler Class.',advancedUsage=1), + name = AttrMapValue(isStringOrNone, desc='Name of the line.'), + lineStyle = AttrMapValue(NoneOr(OneOf('line','joinedLine','bar')), desc="What kind of plot this line is",advancedUsage=1), + barWidth = AttrMapValue(isNumberOrNone,desc="Percentage of available width to be used for a bar",advancedUsage=1), + inFill = AttrMapValue(isBoolean, desc='If true flood fill to x axis',advancedUsage=1), + ) + +class AbstractLineChart(PlotArea): + + def makeSwatchSample(self,rowNo, x, y, width, height): + baseStyle = self.lines + styleIdx = rowNo % len(baseStyle) + style = baseStyle[styleIdx] + color = style.strokeColor + yh2 = y+height/2. + lineStyle = getattr(style,'lineStyle',None) + if lineStyle=='bar': + dash = getattr(style, 'strokeDashArray', getattr(baseStyle,'strokeDashArray',None)) + strokeWidth= getattr(style, 'strokeWidth', getattr(style, 'strokeWidth',None)) + L = Rect(x,y,width,height,strokeWidth=strokeWidth,strokeColor=color,strokeLineCap=0,strokeDashArray=dash,fillColor=getattr(style,'fillColor',color)) + elif self.joinedLines or lineStyle=='joinedLine': + dash = getattr(style, 'strokeDashArray', getattr(baseStyle,'strokeDashArray',None)) + strokeWidth= getattr(style, 'strokeWidth', getattr(style, 'strokeWidth',None)) + L = Line(x,yh2,x+width,yh2,strokeColor=color,strokeLineCap=0) + if strokeWidth: L.strokeWidth = strokeWidth + if dash: L.strokeDashArray = dash + else: + L = None + + if hasattr(style, 'symbol'): + S = style.symbol + elif hasattr(baseStyle, 'symbol'): + S = baseStyle.symbol + else: + S = None + + if S: S = uSymbol2Symbol(S,x+width/2.,yh2,color) + if S and L: + g = Group() + g.add(L) + g.add(S) + return g + return S or L + + def getSeriesName(self,i,default=None): + '''return series name i or default''' + return _objStr(getattr(self.lines[i],'name',default)) + +class LineChart(AbstractLineChart): + pass + +# This is conceptually similar to the VerticalBarChart. +# Still it is better named HorizontalLineChart... :-/ + +class HorizontalLineChart(LineChart): + """Line chart with multiple lines. + + A line chart is assumed to have one category and one value axis. + Despite its generic name this particular line chart class has + a vertical value axis and a horizontal category one. It may + evolve into individual horizontal and vertical variants (like + with the existing bar charts). + + Available attributes are: + + x: x-position of lower-left chart origin + y: y-position of lower-left chart origin + width: chart width + height: chart height + + useAbsolute: disables auto-scaling of chart elements (?) + lineLabelNudge: distance of data labels to data points + lineLabels: labels associated with data values + lineLabelFormat: format string or callback function + groupSpacing: space between categories + + joinedLines: enables drawing of lines + + strokeColor: color of chart lines (?) + fillColor: color for chart background (?) + lines: style list, used cyclically for data series + + valueAxis: value axis object + categoryAxis: category axis object + categoryNames: category names + + data: chart data, a list of data series of equal length + """ + _flipXY = 0 + + _attrMap = AttrMap(BASE=LineChart, + useAbsolute = AttrMapValue(isNumber, desc='Flag to use absolute spacing values.',advancedUsage=1), + lineLabelNudge = AttrMapValue(isNumber, desc='Distance between a data point and its label.',advancedUsage=1), + lineLabels = AttrMapValue(None, desc='Handle to the list of data point labels.'), + lineLabelFormat = AttrMapValue(None, desc='Formatting string or function used for data point labels.'), + lineLabelArray = AttrMapValue(None, desc='explicit array of line label values, must match size of data if present.'), + groupSpacing = AttrMapValue(isNumber, desc='? - Likely to disappear.'), + joinedLines = AttrMapValue(isNumber, desc='Display data points joined with lines if true.'), + lines = AttrMapValue(None, desc='Handle of the lines.'), + valueAxis = AttrMapValue(None, desc='Handle of the value axis.'), + categoryAxis = AttrMapValue(None, desc='Handle of the category axis.'), + categoryNames = AttrMapValue(isListOfStringsOrNone, desc='List of category names.'), + data = AttrMapValue(None, desc='Data to be plotted, list of (lists of) numbers.'), + inFill = AttrMapValue(isBoolean, desc='Whether infilling should be done.',advancedUsage=1), + reversePlotOrder = AttrMapValue(isBoolean, desc='If true reverse plot order.',advancedUsage=1), + annotations = AttrMapValue(None, desc='list of callables, will be called with self, xscale, yscale.',advancedUsage=1), + ) + + def __init__(self): + LineChart.__init__(self) + + # Allow for a bounding rectangle. + self.strokeColor = None + self.fillColor = None + + # Named so we have less recoding for the horizontal one :-) + if self._flipXY: + self.categoryAxis = YCategoryAxis() + self.valueAxis = XValueAxis() + else: + self.categoryAxis = XCategoryAxis() + self.valueAxis = YValueAxis() + + # This defines two series of 3 points. Just an example. + self.data = [(100,110,120,130), + (70, 80, 80, 90)] + self.categoryNames = ('North','South','East','West') + + self.lines = TypedPropertyCollection(LineChartProperties) + self.lines.strokeWidth = 1 + self.lines[0].strokeColor = colors.red + self.lines[1].strokeColor = colors.green + self.lines[2].strokeColor = colors.blue + + # control spacing. if useAbsolute = 1 then + # the next parameters are in points; otherwise + # they are 'proportions' and are normalized to + # fit the available space. + self.useAbsolute = 0 #- not done yet + self.groupSpacing = 1 #5 + + self.lineLabels = TypedPropertyCollection(Label) + self.lineLabelFormat = None + self.lineLabelArray = None + + # This says whether the origin is above or below + # the data point. +10 means put the origin ten points + # above the data point if value > 0, or ten + # points below if data value < 0. This is different + # to label dx/dy which are not dependent on the + # sign of the data. + self.lineLabelNudge = 10 + # If you have multiple series, by default they butt + # together. + + # New line chart attributes. + self.joinedLines = 1 # Connect items with straight lines. + self.inFill = 0 + self.reversePlotOrder = 0 + + def demo(self): + """Shows basic use of a line chart.""" + + drawing = Drawing(200, 100) + + data = [ + (13, 5, 20, 22, 37, 45, 19, 4), + (14, 10, 21, 28, 38, 46, 25, 5) + ] + + lc = HorizontalLineChart() + + lc.x = 20 + lc.y = 10 + lc.height = 85 + lc.width = 170 + lc.data = data + lc.lines.symbol = makeMarker('Circle') + + drawing.add(lc) + + return drawing + + def calcPositions(self): + """Works out where they go. + + Sets an attribute _positions which is a list of + lists of (x, y) matching the data. + """ + + self._seriesCount = len(self.data) + self._rowLength = max(list(map(len,self.data))) + + if self.useAbsolute: + # Dimensions are absolute. + normFactor = 1.0 + else: + # Dimensions are normalized to fit. + normWidth = self.groupSpacing + availWidth = self.categoryAxis.scale(0)[1] + normFactor = availWidth / normWidth + self._normFactor = normFactor + self._vzero = vzero = self.valueAxis.scale(0) + self._hngs = hngs = 0.5 * self.groupSpacing * normFactor + + pairs = set() + P = [].append + cscale = self.categoryAxis.scale + vscale = self.valueAxis.scale + data = self.data + flipXY = self._flipXY + n = len(data) + for rowNo,row in enumerate(data): + if isinstance(row, FillPairedData): + other = row.other + if 0<=other 0: + label.setOrigin(x, y + self.lineLabelNudge) + else: + label.setOrigin(x, y - self.lineLabelNudge) + label.setText(labelText) + else: + label = None + return label + + def drawLabel(self, G, rowNo, colNo, x, y): + '''Draw a label for a given item in the list. + G must have an add method''' + G.add(self._innerDrawLabel(rowNo,colNo,x,y)) + + def makeLines(self): + g = Group() + + labelFmt = self.lineLabelFormat + P = self._positions + if self.reversePlotOrder: P.reverse() + lines = self.lines + styleCount = len(lines) + flipXY = self._flipXY + cA = self.categoryAxis + vA = self.valueAxis + _inFill = self.inFill + if (_inFill or self._pairInFills or + [rowNo for rowNo in range(len(P)) + if getattr(lines[rowNo%styleCount],'inFill',False)] + ): + if flipXY: + infillC = cA._x + infillV0 = vA._y + infillV1 = infillV0 + cA._length + else: + infillC = cA._y + infillV0 = vA._x + infillV1 = infillV0 + cA._length + inFillG = getattr(self,'_inFillG',g) + vzero = self._vzero + bypos = None + + # Iterate over data rows. + for rowNo, row in enumerate(reversed(P) if self.reversePlotOrder else P): + styleIdx = rowNo % styleCount + rowStyle = lines[styleIdx] + strokeColor = rowStyle.strokeColor + fillColor = getattr(rowStyle,'fillColor',strokeColor) + inFill = getattr(rowStyle,'inFill',_inFill) + dash = getattr(rowStyle, 'strokeDashArray', None) + lineStyle = getattr(rowStyle,'lineStyle',None) + + if hasattr(rowStyle, 'strokeWidth'): + strokeWidth = rowStyle.strokeWidth + elif hasattr(lines, 'strokeWidth'): + strokeWidth = lines.strokeWidth + else: + strokeWidth = None + + # Iterate over data columns. + if lineStyle=='bar': + if bypos is None: + if flipXY: + bypos = max(vA._x,vzero) + byneg = min(vA._x+vA._length,vzero) + else: + bypos = max(vA._y,vzero) + byneg = min(vA._y+vA._length,vzero) + barWidth = getattr(rowStyle,'barWidth',Percentage(50)) + if isinstance(barWidth,Percentage): + hbw = self._hngs*barWidth*0.01 + else: + hbw = barWidth*0.5 + for x, y in row: + if flipXY: + v0 = byneg if x x + self.width) or (crossesAt < x)): + x = crossesAt + cA.setPosition(x, y, self.height) + else: + # If zero is in chart, put x axis there, otherwise + # use bottom. + crossesAt = vA.scale(0) + if not ((crossesAt > y + self.height) or (crossesAt < y)): + y = crossesAt + cA.setPosition(x, y, self.width) + cA.configure(self.data) + + self.calcPositions() + + g = Group() + g.add(self.makeBackground()) + if self.inFill: + self._inFillG = Group() + g.add(self._inFillG) + + g.add(cA) + g.add(vA) + cAdgl = getattr(cA,'drawGridLast',False) + vAdgl = getattr(vA,'drawGridLast',False) + if not cAdgl: cA.makeGrid(g,parent=self,dim=vA.getGridDims) + if not vAdgl: vA.makeGrid(g,parent=self,dim=cA.getGridDims) + g.add(self.makeLines()) + if cAdgl: cA.makeGrid(g,parent=self,dim=vA.getGridDims) + if vAdgl: vA.makeGrid(g,parent=self,dim=cA.getGridDims) + for a in getattr(self,'annotations',()): g.add(a(self,cA.scale,vA.scale)) + return g + +def _fakeItemKey(a): + '''t, z0, z1, x, y = a[:5]''' + return (-a[1],a[3],a[0],-a[4]) + +class _FakeGroup: + def __init__(self): + self._data = [] + + def add(self,what): + if what: self._data.append(what) + + def value(self): + return self._data + + def sort(self): + self._data.sort(key=_fakeItemKey) + #for t in self._data: print t + +class HorizontalLineChart3D(HorizontalLineChart): + _attrMap = AttrMap(BASE=HorizontalLineChart, + theta_x = AttrMapValue(isNumber, desc='dx/dz'), + theta_y = AttrMapValue(isNumber, desc='dy/dz'), + zDepth = AttrMapValue(isNumber, desc='depth of an individual series'), + zSpace = AttrMapValue(isNumber, desc='z gap around series'), + ) + theta_x = .5 + theta_y = .5 + zDepth = 10 + zSpace = 3 + + def calcPositions(self): + HorizontalLineChart.calcPositions(self) + nSeries = self._seriesCount + zSpace = self.zSpace + zDepth = self.zDepth + if self.categoryAxis.style=='parallel_3d': + _3d_depth = nSeries*zDepth+(nSeries+1)*zSpace + else: + _3d_depth = zDepth + 2*zSpace + self._3d_dx = self.theta_x*_3d_depth + self._3d_dy = self.theta_y*_3d_depth + + def _calc_z0(self,rowNo): + zSpace = self.zSpace + if self.categoryAxis.style=='parallel_3d': + z0 = rowNo*(self.zDepth+zSpace)+zSpace + else: + z0 = zSpace + return z0 + + def _zadjust(self,x,y,z): + return x+z*self.theta_x, y+z*self.theta_y + + def makeLines(self): + labelFmt = self.lineLabelFormat + P = list(range(len(self._positions))) + if self.reversePlotOrder: P.reverse() + inFill = self.inFill + assert not inFill, "inFill not supported for 3d yet" + #if inFill: + #inFillY = self.categoryAxis._y + #inFillX0 = self.valueAxis._x + #inFillX1 = inFillX0 + self.categoryAxis._length + #inFillG = getattr(self,'_inFillG',g) + zDepth = self.zDepth + _zadjust = self._zadjust + theta_x = self.theta_x + theta_y = self.theta_y + F = _FakeGroup() + from reportlab.graphics.charts.utils3d import _make_3d_line_info + tileWidth = getattr(self,'_3d_tilewidth',None) + if not tileWidth and self.categoryAxis.style!='parallel_3d': tileWidth = 1 + + # Iterate over data rows. + for rowNo in P: + row = self._positions[rowNo] + n = len(row) + styleCount = len(self.lines) + styleIdx = rowNo % styleCount + rowStyle = self.lines[styleIdx] + rowColor = rowStyle.strokeColor + dash = getattr(rowStyle, 'strokeDashArray', None) + z0 = self._calc_z0(rowNo) + z1 = z0 + zDepth + + if hasattr(self.lines[styleIdx], 'strokeWidth'): + strokeWidth = self.lines[styleIdx].strokeWidth + elif hasattr(self.lines, 'strokeWidth'): + strokeWidth = self.lines.strokeWidth + else: + strokeWidth = None + + # Iterate over data columns. + if self.joinedLines: + if n: + x0, y0 = row[0] + for colNo in range(1,n): + x1, y1 = row[colNo] + _make_3d_line_info( F, x0, x1, y0, y1, z0, z1, + theta_x, theta_y, + rowColor, fillColorShaded=None, tileWidth=tileWidth, + strokeColor=None, strokeWidth=None, strokeDashArray=None, + shading=0.1) + x0, y0 = x1, y1 + + if hasattr(self.lines[styleIdx], 'symbol'): + uSymbol = self.lines[styleIdx].symbol + elif hasattr(self.lines, 'symbol'): + uSymbol = self.lines.symbol + else: + uSymbol = None + + if uSymbol: + for colNo in range(n): + x1, y1 = row[colNo] + x1, y1 = _zadjust(x1,y1,z0) + symbol = uSymbol2Symbol(uSymbol,x1,y1,rowColor) + if symbol: F.add((2,z0,z0,x1,y1,symbol)) + + # Draw item labels. + for colNo in range(n): + x1, y1 = row[colNo] + x1, y1 = _zadjust(x1,y1,z0) + L = self._innerDrawLabel(rowNo, colNo, x1, y1) + if L: F.add((2,z0,z0,x1,y1,L)) + + F.sort() + g = Group() + for v in F.value(): g.add(v[-1]) + return g + +class VerticalLineChart(HorizontalLineChart): + _flipXY = 1 + +def sample1(): + drawing = Drawing(400, 200) + + data = [ + (13, 5, 20, 22, 37, 45, 19, 4), + (5, 20, 46, 38, 23, 21, 6, 14) + ] + + lc = HorizontalLineChart() + + lc.x = 50 + lc.y = 50 + lc.height = 125 + lc.width = 300 + lc.data = data + lc.joinedLines = 1 + lc.lines.symbol = makeMarker('FilledDiamond') + lc.lineLabelFormat = '%2.0f' + + catNames = 'Jan Feb Mar Apr May Jun Jul Aug'.split(' ') + lc.categoryAxis.categoryNames = catNames + lc.categoryAxis.labels.boxAnchor = 'n' + + lc.valueAxis.valueMin = 0 + lc.valueAxis.valueMax = 60 + lc.valueAxis.valueStep = 15 + + drawing.add(lc) + + return drawing + +class SampleHorizontalLineChart(HorizontalLineChart): + "Sample class overwriting one method to draw additional horizontal lines." + + def demo(self): + """Shows basic use of a line chart.""" + + drawing = Drawing(200, 100) + + data = [ + (13, 5, 20, 22, 37, 45, 19, 4), + (14, 10, 21, 28, 38, 46, 25, 5) + ] + + lc = SampleHorizontalLineChart() + + lc.x = 20 + lc.y = 10 + lc.height = 85 + lc.width = 170 + lc.data = data + lc.strokeColor = colors.white + lc.fillColor = colors.HexColor(0xCCCCCC) + + drawing.add(lc) + + return drawing + + def makeBackground(self): + g = Group() + + g.add(HorizontalLineChart.makeBackground(self)) + + valAxis = self.valueAxis + valTickPositions = valAxis._tickValues + + for y in valTickPositions: + y = valAxis.scale(y) + g.add(Line(self.x, y, self.x+self.width, y, + strokeColor = self.strokeColor)) + + return g + +def sample1a(): + drawing = Drawing(400, 200) + + data = [ + (13, 5, 20, 22, 37, 45, 19, 4), + (5, 20, 46, 38, 23, 21, 6, 14) + ] + + lc = SampleHorizontalLineChart() + + lc.x = 50 + lc.y = 50 + lc.height = 125 + lc.width = 300 + lc.data = data + lc.joinedLines = 1 + lc.strokeColor = colors.white + lc.fillColor = colors.HexColor(0xCCCCCC) + lc.lines.symbol = makeMarker('FilledDiamond') + lc.lineLabelFormat = '%2.0f' + + catNames = 'Jan Feb Mar Apr May Jun Jul Aug'.split(' ') + lc.categoryAxis.categoryNames = catNames + lc.categoryAxis.labels.boxAnchor = 'n' + + lc.valueAxis.valueMin = 0 + lc.valueAxis.valueMax = 60 + lc.valueAxis.valueStep = 15 + + drawing.add(lc) + + return drawing + +def sample2(): + drawing = Drawing(400, 200) + + data = [ + (13, 5, 20, 22, 37, 45, 19, 4), + (5, 20, 46, 38, 23, 21, 6, 14) + ] + + lc = HorizontalLineChart() + + lc.x = 50 + lc.y = 50 + lc.height = 125 + lc.width = 300 + lc.data = data + lc.joinedLines = 1 + lc.lines.symbol = makeMarker('Smiley') + lc.lineLabelFormat = '%2.0f' + lc.strokeColor = colors.black + lc.fillColor = colors.lightblue + + catNames = 'Jan Feb Mar Apr May Jun Jul Aug'.split(' ') + lc.categoryAxis.categoryNames = catNames + lc.categoryAxis.labels.boxAnchor = 'n' + + lc.valueAxis.valueMin = 0 + lc.valueAxis.valueMax = 60 + lc.valueAxis.valueStep = 15 + + drawing.add(lc) + + return drawing + +def sample3(): + drawing = Drawing(400, 200) + + data = [ + (13, 5, 20, 22, 37, 45, 19, 4), + (5, 20, 46, 38, 23, 21, 6, 14) + ] + + lc = HorizontalLineChart() + + lc.x = 50 + lc.y = 50 + lc.height = 125 + lc.width = 300 + lc.data = data + lc.joinedLines = 1 + lc.lineLabelFormat = '%2.0f' + lc.strokeColor = colors.black + + lc.lines[0].symbol = makeMarker('Smiley') + lc.lines[1].symbol = NoEntry + lc.lines[0].strokeWidth = 2 + lc.lines[1].strokeWidth = 4 + + catNames = 'Jan Feb Mar Apr May Jun Jul Aug'.split(' ') + lc.categoryAxis.categoryNames = catNames + lc.categoryAxis.labels.boxAnchor = 'n' + + lc.valueAxis.valueMin = 0 + lc.valueAxis.valueMax = 60 + lc.valueAxis.valueStep = 15 + + drawing.add(lc) + + return drawing + +def sampleCandleStick(): + from reportlab.graphics.widgetbase import CandleSticks + d = Drawing(400, 200) + chart = HorizontalLineChart() + d.add(chart) + chart.y = 20 + boxMid = (100, 110, 120, 130) + hi = [m+10 for m in boxMid] + lo = [m-10 for m in boxMid] + boxHi = [m+6 for m in boxMid] + boxLo = [m-4 for m in boxMid] + boxFillColor = colors.pink + boxWidth = 20 + crossWidth = 10 + candleStrokeWidth = 0.5 + candleStrokeColor = colors.black + chart.valueAxis.avoidBoundSpace = 5 + + chart.valueAxis.valueMin = min(min(boxMid),min(hi),min(lo),min(boxLo),min(boxHi)) + chart.valueAxis.valueMax = max(max(boxMid),max(hi),max(lo),max(boxLo),max(boxHi)) + lines = chart.lines + lines[0].strokeColor = None + I = range(len(boxMid)) + chart.data = [boxMid] + lines[0].symbol = candles = CandleSticks(chart=chart, boxFillColor=boxFillColor, boxWidth=boxWidth, crossWidth=crossWidth, strokeWidth=candleStrokeWidth, strokeColor=candleStrokeColor) + for i in I: candles[i].setProperties(dict(position=i,boxMid=boxMid[i],crossLo=lo[i],crossHi=hi[i],boxLo=boxLo[i],boxHi=boxHi[i])) + return d diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/lineplots.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/lineplots.py new file mode 100644 index 0000000000000000000000000000000000000000..47184e6c1be1a8cfcba2311d44c702086323b9e0 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/lineplots.py @@ -0,0 +1,1248 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/graphics/charts/lineplots.py + +__version__='3.3.0' +__doc__="""This module defines a very preliminary Line Plot example.""" + +from reportlab.lib import colors +from reportlab.lib.validators import * +from reportlab.lib.attrmap import * +from reportlab.lib.utils import flatten, isStr +from reportlab.graphics.shapes import Drawing, Group, Rect, PolyLine, Polygon, _SetKeyWordArgs +from reportlab.graphics.widgetbase import TypedPropertyCollection, PropHolder, tpcGetItem +from reportlab.graphics.charts.textlabels import Label +from reportlab.graphics.charts.axes import XValueAxis, YValueAxis, AdjYValueAxis, NormalDateXValueAxis +from reportlab.graphics.charts.utils import * +from reportlab.graphics.widgets.markers import uSymbol2Symbol, makeMarker +from reportlab.graphics.widgets.grids import Grid, DoubleGrid, ShadedPolygon +from reportlab.pdfbase.pdfmetrics import stringWidth, getFont +from reportlab.graphics.charts.areas import PlotArea +from .utils import FillPairedData + +# This might be moved again from here... +class LinePlotProperties(PropHolder): + _attrMap = AttrMap( + strokeWidth = AttrMapValue(isNumber, desc='Width of a line.'), + strokeColor = AttrMapValue(isColorOrNone, desc='Color of a line.'), + strokeDashArray = AttrMapValue(isListOfNumbersOrNone, desc='Dash array of a line.'), + fillColor = AttrMapValue(isColorOrNone, desc='Color of infill defaults to the strokeColor.'), + symbol = AttrMapValue(None, desc='Widget placed at data points.',advancedUsage=1), + shader = AttrMapValue(None, desc='Shader Class.',advancedUsage=1), + filler = AttrMapValue(None, desc='Filler Class.',advancedUsage=1), + name = AttrMapValue(isStringOrNone, desc='Name of the line.'), + lineStyle = AttrMapValue(NoneOr(OneOf('line','joinedLine','bar')), desc="What kind of plot this line is",advancedUsage=1), + barWidth = AttrMapValue(isNumberOrNone,desc="Percentage of available width to be used for a bar",advancedUsage=1), + inFill = AttrMapValue(OneOf(0,1,2,True,False), desc='If true flood fill to x axis',advancedUsage=1), + ) + +class InFillValue(int): + def __new__(cls,v,yValue=None): + self = int.__new__(cls,v) + self.yValue = yValue + return self + +class Shader(_SetKeyWordArgs): + _attrMap = AttrMap(BASE=PlotArea, + vertical = AttrMapValue(isBoolean, desc='If true shade to x axis'), + colors = AttrMapValue(SequenceOf(isColorOrNone,lo=2,hi=2), desc='(AxisColor, LineColor)'), + ) + + def shade(self, lp, g, rowNo, rowColor, row): + c = [None,None] + c = getattr(self,'colors',c) or c + if not c[0]: c[0] = getattr(lp,'fillColor',colors.white) + if not c[1]: c[1] = rowColor + +class NoFiller: + def fill(self, lp, g, rowNo, rowColor, points): + pass + +class Filler: + '''mixin providing simple polygon fill''' + _attrMap = AttrMap( + fillColor = AttrMapValue(isColorOrNone, desc='filler interior color'), + strokeColor = AttrMapValue(isColorOrNone, desc='filler edge color'), + strokeWidth = AttrMapValue(isNumberOrNone, desc='filler edge width'), + ) + def __init__(self,**kw): + self.__dict__ = kw + + def fill(self, lp, g, rowNo, rowColor, points): + g.add(Polygon(points, + fillColor=getattr(self,'fillColor',rowColor), + strokeColor=getattr(self,'strokeColor',rowColor), + strokeWidth=getattr(self,'strokeWidth',0.1))) + +class ShadedPolyFiller(Filler,ShadedPolygon): + pass + +class PolyFiller(Filler,Polygon): + pass + +from reportlab.graphics.charts.linecharts import AbstractLineChart +class LinePlot(AbstractLineChart): + """Line plot with multiple lines. + + Both x- and y-axis are value axis (so there are no seperate + X and Y versions of this class). + """ + _attrMap = AttrMap(BASE=PlotArea, + reversePlotOrder = AttrMapValue(isBoolean, desc='If true reverse plot order.',advancedUsage=1), + lineLabelNudge = AttrMapValue(isNumber, desc='Distance between a data point and its label.',advancedUsage=1), + lineLabels = AttrMapValue(None, desc='Handle to the list of data point labels.'), + lineLabelFormat = AttrMapValue(None, desc='Formatting string or function used for data point labels.'), + lineLabelArray = AttrMapValue(None, desc='explicit array of line label values, must match size of data if present.'), + #joinedLines = AttrMapValue(isNumber, desc='Display data points joined with lines if true.'), + strokeColor = AttrMapValue(isColorOrNone, desc='Color used for background border of plot area.'), + fillColor = AttrMapValue(isColorOrNone, desc='Color used for background interior of plot area.'), + lines = AttrMapValue(None, desc='Handle of the lines.'), + xValueAxis = AttrMapValue(None, desc='Handle of the x axis.'), + yValueAxis = AttrMapValue(None, desc='Handle of the y axis.'), + data = AttrMapValue(None, desc='Data to be plotted, list of (lists of) x/y tuples.'), + annotations = AttrMapValue(None, desc='list of callables, will be called with self, xscale, yscale.',advancedUsage=1), + behindAxes = AttrMapValue(isBoolean, desc='If true use separate line group.',advancedUsage=1), + gridFirst = AttrMapValue(isBoolean, desc='If true use draw grids before axes.',advancedUsage=1), + ) + + def __init__(self): + PlotArea.__init__(self) + self.reversePlotOrder = 0 + + self.xValueAxis = XValueAxis() + self.yValueAxis = YValueAxis() + + # this defines two series of 3 points. Just an example. + self.data = [ + ((1,1), (2,2), (2.5,1), (3,3), (4,5)), + ((1,2), (2,3), (2.5,2), (3,4), (4,6)) + ] + + self.lines = TypedPropertyCollection(LinePlotProperties) + self.lines.strokeWidth = 1 + self.joinedLines = 1 # Connect items with straight lines. + self.lines[0].strokeColor = colors.red + self.lines[1].strokeColor = colors.blue + + self.lineLabels = TypedPropertyCollection(Label) + self.lineLabelFormat = None + self.lineLabelArray = None + + # this says whether the origin is inside or outside + # the bar - +10 means put the origin ten points + # above the tip of the bar if value > 0, or ten + # points inside if bar value < 0. This is different + # to label dx/dy which are not dependent on the + # sign of the data. + self.lineLabelNudge = 10 + # if you have multiple series, by default they butt + # together. + + #private attributes + self._inFill = None + self.annotations = [] + self.behindAxes = 0 + self.gridFirst = 0 + + @property + def joinedLines(self): + return self.lines.lineStyle=='joinedLine' + + @joinedLines.setter + def joinedLines(self,v): + self.lines.lineStyle = 'joinedLine' if v else 'line' + + def demo(self): + """Shows basic use of a line chart.""" + + drawing = Drawing(400, 200) + + data = [ + ((1,1), (2,2), (2.5,1), (3,3), (4,5)), + ((1,2), (2,3), (2.5,2), (3.5,5), (4,6)) + ] + + lp = LinePlot() + + lp.x = 50 + lp.y = 50 + lp.height = 125 + lp.width = 300 + lp.data = data + lp.joinedLines = 1 + lp.lineLabelFormat = '%2.0f' + lp.strokeColor = colors.black + + lp.lines[0].strokeColor = colors.red + lp.lines[0].symbol = makeMarker('FilledCircle') + lp.lines[1].strokeColor = colors.blue + lp.lines[1].symbol = makeMarker('FilledDiamond') + + lp.xValueAxis.valueMin = 0 + lp.xValueAxis.valueMax = 5 + lp.xValueAxis.valueStep = 1 + + lp.yValueAxis.valueMin = 0 + lp.yValueAxis.valueMax = 7 + lp.yValueAxis.valueStep = 1 + + drawing.add(lp) + + return drawing + + + def calcPositions(self): + """Works out where they go. + + Sets an attribute _positions which is a list of + lists of (x, y) matching the data. + """ + + self._seriesCount = len(self.data) + self._rowLength = max(list(map(len,self.data))) + + pairs = set() + P = [].append + xscale = self.xValueAxis.scale + yscale = self.yValueAxis.scale + data = self.data + n = len(data) + for rowNo, row in enumerate(data): + if isinstance(row, FillPairedData): + other = row.other + if 0<=other 0: + label.setOrigin(x, y + self.lineLabelNudge) + else: + label.setOrigin(x, y - self.lineLabelNudge) + label.setText(labelText) + else: + label = None + return label + + def drawLabel(self, G, rowNo, colNo, x, y): + '''Draw a label for a given item in the list. + G must have an add method''' + G.add(self._innerDrawLabel(rowNo,colNo,x,y)) + + def makeLines(self): + g = Group() + yA = self.yValueAxis + xA = self.xValueAxis + bubblePlot = getattr(self,'_bubblePlot',None) + if bubblePlot: + bubbleR = min(yA._bubbleRadius,xA._bubbleRadius) + bubbleMax = xA._bubbleMax + + labelFmt = self.lineLabelFormat + + P = self._positions + _inFill = getattr(self,'_inFill',None) + lines = self.lines + styleCount = len(lines) + if (_inFill or self._pairInFills or + [rowNo for rowNo in range(len(P)) + if getattr(lines[rowNo%styleCount],'inFill',False)] + ): + inFillY = getattr(_inFill,'yValue',None) + if inFillY is None: + inFillY = xA._y + else: + inFillY = yA.scale(inFillY) + inFillX0 = yA._x + inFillX1 = inFillX0 + xA._length + inFillG = getattr(self,'_inFillG',g) + bw = None + lG = getattr(self,'_lineG',g) + # Iterate over data rows. + R = range(len(P)) + if self.reversePlotOrder: R = reversed(R) + for rowNo in R: + row = P[rowNo] + styleRowNo = rowNo % styleCount + rowStyle = lines[styleRowNo] + strokeColor = getattr(rowStyle,'strokeColor',None) + strokeWidth = getattr(rowStyle,'strokeWidth',None) + fillColor = getattr(rowStyle, 'fillColor', strokeColor) + inFill = getattr(rowStyle,'inFill',_inFill) + dash = getattr(rowStyle, 'strokeDashArray', None) + lineStyle = getattr(rowStyle,'lineStyle',None) + + if hasattr(rowStyle, 'strokeWidth'): + width = rowStyle.strokeWidth + elif hasattr(lines, 'strokeWidth'): + width = lines.strokeWidth + else: + width = None + + # Iterate over data columns. + if lineStyle=='bar': + if bw is None: + x = max(map(len,P)) - 1 #the number of gaps + bw = (self.width/x - 1) if x>0 else self.width + barWidth = getattr(rowStyle,'barWidth',Percentage(50)) + x = self.yValueAxis + y0 = x.scale(0) + bypos = max(x._y,y0) + byneg = min(x._y+x._length,y0) + xmin = self.xValueAxis._x + xmax = xmin + self.xValueAxis._length + if isinstance(barWidth,Percentage): + bw *= barWidth*0.005 + else: + bw = barWidth*0.5 + for x, y in row: + w = bw + #print(f'{x=} {y=} {y0=} {byneg=} {bypos=}') + _y0 = byneg if y xmax: + w -= xmax - x + g.add(Rect(x,_y0,w,y-_y0,strokeWidth=strokeWidth,strokeColor=strokeColor,fillColor=fillColor)) + elif lineStyle=='joinedLine': + points = flatten(row) + if inFill or isinstance(row,FillPairedData): + filler = getattr(rowStyle, 'filler', None) + if isinstance(row,FillPairedData): + fpoints = points + flatten(reversed(P[row.other])) + else: + fpoints = [inFillX0,inFillY] + points + [inFillX1,inFillY] + if filler: + filler.fill(self,inFillG,rowNo,fillColor,fpoints) + else: + inFillG.add(Polygon(fpoints,fillColor=fillColor,strokeColor=strokeColor if strokeColor==fillColor else None,strokeWidth=width or 0.1)) + if not inFill or inFill==2 or strokeColor!=fillColor: + line = PolyLine(points,strokeColor=strokeColor,strokeLineCap=0,strokeLineJoin=1) + if width: + line.strokeWidth = width + if dash: + line.strokeDashArray = dash + lG.add(line) + + if hasattr(rowStyle, 'symbol'): + uSymbol = rowStyle.symbol + elif hasattr(lines, 'symbol'): + uSymbol = lines.symbol + else: + uSymbol = None + + if uSymbol: + if bubblePlot: drow = self.data[rowNo] + for j,xy in enumerate(row): + if (styleRowNo,j) in lines: + juSymbol = getattr(lines[styleRowNo,j],'symbol',uSymbol) + else: + juSymbol = uSymbol + if juSymbol is uSymbol: + symbol = uSymbol + symColor = strokeColor + else: + symbol = juSymbol + symColor = getattr(symbol,'fillColor',strokeColor) + symbol = uSymbol2Symbol(tpcGetItem(symbol,j),xy[0],xy[1],symColor) + if symbol: + if bubblePlot: + symbol.size = bubbleR*(drow[j][2]/bubbleMax)**0.5 + g.add(symbol) + else: + if bubblePlot: drow = self.data[rowNo] + for j,xy in enumerate(row): + juSymbol = getattr(lines[styleRowNo,j],'symbol',None) + if not juSymbol: continue + symColor = getattr(juSymbol,'fillColor',getattr(juSymbol,'strokeColor',strokeColor)) + symbol = uSymbol2Symbol(juSymbol,xy[0],xy[1],symColor) + if symbol: + if bubblePlot: + symbol.size = bubbleR*(drow[j][2]/bubbleMax)**0.5 + g.add(symbol) + + # Draw data labels. + for colNo,datum in enumerate(row): + x1, y1 = datum + self.drawLabel(g, rowNo, colNo, x1, y1) + + shader = getattr(rowStyle, 'shader', None) + if shader: shader.shade(self,g,rowNo,strokeColor,row) + + return g + + def draw(self): + yA = self.yValueAxis + xA = self.xValueAxis + if getattr(self,'_bubblePlot',None): + yA._bubblePlot = xA._bubblePlot = 1 + yA.setPosition(self.x, self.y, self.height) + if yA: yA.joinAxis = xA + if xA: xA.joinAxis = yA + yA.configure(self.data) + + # if zero is in chart, put x axis there, otherwise use bottom. + xAxisCrossesAt = yA.scale(0) + if ((xAxisCrossesAt > self.y + self.height) or (xAxisCrossesAt < self.y)): + y = self.y + else: + y = xAxisCrossesAt + + xA.setPosition(self.x, y, self.width) + xA.configure(self.data) + self.calcPositions() + g = Group() + g.add(self.makeBackground()) + if self._inFill or self.behindAxes: + xA._joinToAxis() + if self._inFill: + self._inFillG = Group() + g.add(self._inFillG) + if self.behindAxes: + self._lineG = Group() + g.add(self._lineG) + xA._joinToAxis() + yA._joinToAxis() + xAex = xA.visibleAxis and [xA._y] or [] + yAex = yA.visibleAxis and [yA._x] or [] + skipGrid = getattr(xA,'skipGrid','none') + if skipGrid!=None: + if skipGrid in ('both','top'): + yAex.append(xA._x+xA._length) + if skipGrid in ('both','bottom'): + yAex.append(xA._x) + skipGrid = getattr(yA,'skipGrid','none') + if skipGrid!=None: + if skipGrid in ('both','top'): + xAex.append(yA._y+yA._length) + if skipGrid in ('both','bottom'): + xAex.append(yA._y) + if self.gridFirst: + xA.makeGrid(g,parent=self,dim=yA.getGridDims,exclude=yAex) + yA.makeGrid(g,parent=self,dim=xA.getGridDims,exclude=xAex) + g.add(xA.draw()) + g.add(yA.draw()) + if not self.gridFirst: + xAdgl = getattr(xA,'drawGridLast',False) + yAdgl = getattr(yA,'drawGridLast',False) + if not xAdgl: xA.makeGrid(g,parent=self,dim=yA.getGridDims,exclude=yAex) + if not yAdgl: yA.makeGrid(g,parent=self,dim=xA.getGridDims,exclude=xAex) + annotations = getattr(self,'annotations',[]) + for a in annotations: + if getattr(a,'beforeLines',None): + g.add(a(self,xA.scale,yA.scale)) + g.add(self.makeLines()) + if not self.gridFirst: + if xAdgl: xA.makeGrid(g,parent=self,dim=yA.getGridDims,exclude=yAex) + if yAdgl: yA.makeGrid(g,parent=self,dim=xA.getGridDims,exclude=xAex) + for a in annotations: + if not getattr(a,'beforeLines',None): + g.add(a(self,xA.scale,yA.scale)) + return g + + def addCrossHair(self,name,xv,yv,strokeColor=colors.black,strokeWidth=1,beforeLines=True): + from reportlab.graphics.shapes import Group, Line + annotations = [a for a in getattr(self,'annotations',[]) if getattr(a,'name',None)!=name] + def annotation(self,xScale,yScale): + x = xScale(xv) + y = yScale(yv) + g = Group() + xA = xScale.__self__ #the x axis + g.add(Line(xA._x,y,xA._x+xA._length,y,strokeColor=strokeColor,strokeWidth=strokeWidth)) + yA = yScale.__self__ #the y axis + g.add(Line(x,yA._y,x,yA._y+yA._length,strokeColor=strokeColor,strokeWidth=strokeWidth)) + return g + annotation.beforeLines = beforeLines + annotations.append(annotation) + self.annotations = annotations + +class LinePlot3D(LinePlot): + _attrMap = AttrMap(BASE=LinePlot, + theta_x = AttrMapValue(isNumber, desc='dx/dz'), + theta_y = AttrMapValue(isNumber, desc='dy/dz'), + zDepth = AttrMapValue(isNumber, desc='depth of an individual series'), + zSpace = AttrMapValue(isNumber, desc='z gap around series'), + ) + theta_x = .5 + theta_y = .5 + zDepth = 10 + zSpace = 3 + + def calcPositions(self): + LinePlot.calcPositions(self) + nSeries = self._seriesCount + zSpace = self.zSpace + zDepth = self.zDepth + if self.xValueAxis.style=='parallel_3d': + _3d_depth = nSeries*zDepth+(nSeries+1)*zSpace + else: + _3d_depth = zDepth + 2*zSpace + self._3d_dx = self.theta_x*_3d_depth + self._3d_dy = self.theta_y*_3d_depth + + def _calc_z0(self,rowNo): + zSpace = self.zSpace + if self.xValueAxis.style=='parallel_3d': + z0 = rowNo*(self.zDepth+zSpace)+zSpace + else: + z0 = zSpace + return z0 + + def _zadjust(self,x,y,z): + return x+z*self.theta_x, y+z*self.theta_y + + def makeLines(self): + bubblePlot = getattr(self,'_bubblePlot',None) + assert not bubblePlot, "_bubblePlot not supported for 3d yet" + #if bubblePlot: + # yA = self.yValueAxis + # xA = self.xValueAxis + # bubbleR = min(yA._bubbleRadius,xA._bubbleRadius) + # bubbleMax = xA._bubbleMax + + labelFmt = self.lineLabelFormat + positions = self._positions + + P = list(range(len(positions))) + if self.reversePlotOrder: P.reverse() + inFill = getattr(self,'_inFill',None) + assert not inFill, "inFill not supported for 3d yet" + #if inFill: + # inFillY = self.xValueAxis._y + # inFillX0 = self.yValueAxis._x + # inFillX1 = inFillX0 + self.xValueAxis._length + # inFillG = getattr(self,'_inFillG',g) + zDepth = self.zDepth + _zadjust = self._zadjust + theta_x = self.theta_x + theta_y = self.theta_y + from reportlab.graphics.charts.linecharts import _FakeGroup + F = _FakeGroup() + + from reportlab.graphics.charts.utils3d import _make_3d_line_info, find_intersections + if self.xValueAxis.style!='parallel_3d': + tileWidth = getattr(self,'_3d_tilewidth',1) + if getattr(self,'_find_intersections',None): + from copy import copy + fpositions = list(map(copy,positions)) + I = find_intersections(fpositions,small=tileWidth) + ic = None + for i,j,x,y in I: + if ic!=i: + ic = i + jc = 0 + else: + jc+=1 + fpositions[i].insert(j+jc,(x,y)) + tileWidth = None + else: + fpositions = positions + else: + tileWidth = None + fpositions = positions + + # Iterate over data rows. + styleCount = len(self.lines) + for rowNo in P: + row = positions[rowNo] + n = len(row) + rowStyle = self.lines[rowNo % styleCount] + rowColor = rowStyle.strokeColor + dash = getattr(rowStyle, 'strokeDashArray', None) + z0 = self._calc_z0(rowNo) + z1 = z0 + zDepth + + if hasattr(rowStyle, 'strokeWidth'): + width = rowStyle.strokeWidth + elif hasattr(self.lines, 'strokeWidth'): + width = self.lines.strokeWidth + else: + width = None + + # Iterate over data columns. + if self.joinedLines: + if n: + frow = fpositions[rowNo] + x0, y0 = frow[0] + for colNo in range(1,len(frow)): + x1, y1 = frow[colNo] + _make_3d_line_info( F, x0, x1, y0, y1, z0, z1, + theta_x, theta_y, + rowColor, fillColorShaded=None, tileWidth=tileWidth, + strokeColor=None, strokeWidth=None, strokeDashArray=None, + shading=0.1) + x0, y0 = x1, y1 + + if hasattr(rowStyle, 'symbol'): + uSymbol = rowStyle.symbol + elif hasattr(self.lines, 'symbol'): + uSymbol = self.lines.symbol + else: + uSymbol = None + + if uSymbol: + for xy in row: + x1, y1 = row[colNo] + x1, y1 = _zadjust(x1,y1,z0) + symbol = uSymbol2Symbol(uSymbol,xy[0],xy[1],rowColor) + if symbol: F.add((1,z0,z0,x1,y1,symbol)) + + # Draw data labels. + for colNo in range(n): + x1, y1 = row[colNo] + x1, y1 = _zadjust(x1,y1,z0) + L = self._innerDrawLabel(rowNo, colNo, x1, y1) + if L: F.add((2,z0,z0,x1,y1,L)) + + F.sort() + g = Group() + for v in F.value(): g.add(v[-1]) + return g + +_monthlyIndexData = [[(19971202, 100.0), + (19971231, 100.1704367), + (19980131, 101.5639577), + (19980228, 102.1879927), + (19980331, 101.6337257), + (19980430, 102.7640446), + (19980531, 102.9198038), + (19980630, 103.25938789999999), + (19980731, 103.2516421), + (19980831, 105.4744329), + (19980930, 109.3242705), + (19981031, 111.9859291), + (19981130, 110.9184642), + (19981231, 110.9184642), + (19990131, 111.9882532), + (19990228, 109.7912614), + (19990331, 110.24189629999999), + (19990430, 110.4279321), + (19990531, 109.33955469999999), + (19990630, 108.2341748), + (19990731, 110.21294469999999), + (19990831, 110.9683062), + (19990930, 112.4425371), + (19991031, 112.7314032), + (19991130, 112.3509645), + (19991231, 112.3660659), + (20000131, 110.9255248), + (20000229, 110.5266306), + (20000331, 113.3116101), + (20000430, 111.0449133), + (20000531, 111.702717), + (20000630, 113.5832178)], + [(19971202, 100.0), + (19971231, 100.0), + (19980131, 100.8), + (19980228, 102.0), + (19980331, 101.9), + (19980430, 103.0), + (19980531, 103.0), + (19980630, 103.1), + (19980731, 103.1), + (19980831, 102.8), + (19980930, 105.6), + (19981031, 108.3), + (19981130, 108.1), + (19981231, 111.9), + (19990131, 113.1), + (19990228, 110.2), + (19990331, 111.8), + (19990430, 112.3), + (19990531, 110.1), + (19990630, 109.3), + (19990731, 111.2), + (19990831, 111.7), + (19990930, 112.6), + (19991031, 113.2), + (19991130, 113.9), + (19991231, 115.4), + (20000131, 112.7), + (20000229, 113.9), + (20000331, 115.8), + (20000430, 112.2), + (20000531, 112.6), + (20000630, 114.6)]] + +class SimpleTimeSeriesPlot(LinePlot): + """A customized version of LinePlot. + It uses NormalDateXValueAxis() and AdjYValueAxis() for the X and Y axes. + """ + def __init__(self): + LinePlot.__init__(self) + self.xValueAxis = NormalDateXValueAxis() + self.yValueAxis = YValueAxis() + self.data = _monthlyIndexData + +class GridLinePlot(SimpleTimeSeriesPlot): + """A customized version of SimpleTimeSeriesSPlot. + It uses NormalDateXValueAxis() and AdjYValueAxis() for the X and Y axes. + The chart has a default grid background with thin horizontal lines + aligned with the tickmarks (and labels). You can change the back- + ground to be any Grid or ShadedRect, or scale the whole chart. + If you do provide a background, you can specify the colours of the + stripes with 'background.stripeColors'. + """ + + _attrMap = AttrMap(BASE=LinePlot, + background = AttrMapValue(None, desc='Background for chart area (now Grid or ShadedRect).'), + scaleFactor = AttrMapValue(isNumberOrNone, desc='Scalefactor to apply to whole drawing.'), + ) + + def __init__(self): + from reportlab.lib import colors + SimpleTimeSeriesPlot.__init__(self) + self.scaleFactor = None + self.background = Grid() + self.background.orientation = 'horizontal' + self.background.useRects = 0 + self.background.useLines = 1 + self.background.strokeWidth = 0.5 + self.background.strokeColor = colors.black + + def demo(self,drawing=None): + from reportlab.lib import colors + if not drawing: + drawing = Drawing(400, 200) + lp = GridLinePlot() + lp.x = 50 + lp.y = 50 + lp.height = 125 + lp.width = 300 + lp.data = _monthlyIndexData + lp.joinedLines = 1 + lp.strokeColor = colors.black + c0 = colors.PCMYKColor(100,65,0,30, spotName='PANTONE 288 CV', density=100) + lp.lines[0].strokeColor = c0 + lp.lines[0].strokeWidth = 2 + lp.lines[0].strokeDashArray = None + c1 = colors.PCMYKColor(0,79,91,0, spotName='PANTONE Wm Red CV', density=100) + lp.lines[1].strokeColor = c1 + lp.lines[1].strokeWidth = 1 + lp.lines[1].strokeDashArray = [3,1] + lp.xValueAxis.labels.fontSize = 10 + lp.xValueAxis.labels.textAnchor = 'start' + lp.xValueAxis.labels.boxAnchor = 'w' + lp.xValueAxis.labels.angle = -45 + lp.xValueAxis.labels.dx = 0 + lp.xValueAxis.labels.dy = -8 + lp.xValueAxis.xLabelFormat = '{mm}/{yy}' + lp.yValueAxis.labelTextFormat = '%5d%% ' + lp.yValueAxis.tickLeft = 5 + lp.yValueAxis.labels.fontSize = 10 + lp.background = Grid() + lp.background.stripeColors = [colors.pink, colors.lightblue] + lp.background.orientation = 'vertical' + drawing.add(lp,'plot') + return drawing + + def draw(self): + xva, yva = self.xValueAxis, self.yValueAxis + if xva: xva.joinAxis = yva + if yva: yva.joinAxis = xva + + yva.setPosition(self.x, self.y, self.height) + yva.configure(self.data) + + # if zero is in chart, put x axis there, otherwise + # use bottom. + xAxisCrossesAt = yva.scale(0) + if ((xAxisCrossesAt > self.y + self.height) or (xAxisCrossesAt < self.y)): + y = self.y + else: + y = xAxisCrossesAt + + xva.setPosition(self.x, y, self.width) + xva.configure(self.data) + + back = self.background + if isinstance(back, Grid): + if back.orientation == 'vertical' and xva._tickValues: + xpos = list(map(xva.scale, [xva._valueMin] + xva._tickValues)) + steps = [] + for i in range(len(xpos)-1): + steps.append(xpos[i+1] - xpos[i]) + back.deltaSteps = steps + elif back.orientation == 'horizontal' and yva._tickValues: + ypos = list(map(yva.scale, [yva._valueMin] + yva._tickValues)) + steps = [] + for i in range(len(ypos)-1): + steps.append(ypos[i+1] - ypos[i]) + back.deltaSteps = steps + elif isinstance(back, DoubleGrid): + # Ideally, these lines would not be needed... + back.grid0.x = self.x + back.grid0.y = self.y + back.grid0.width = self.width + back.grid0.height = self.height + back.grid1.x = self.x + back.grid1.y = self.y + back.grid1.width = self.width + back.grid1.height = self.height + + # some room left for optimization... + if back.grid0.orientation == 'vertical' and xva._tickValues: + xpos = list(map(xva.scale, [xva._valueMin] + xva._tickValues)) + steps = [] + for i in range(len(xpos)-1): + steps.append(xpos[i+1] - xpos[i]) + back.grid0.deltaSteps = steps + elif back.grid0.orientation == 'horizontal' and yva._tickValues: + ypos = list(map(yva.scale, [yva._valueMin] + yva._tickValues)) + steps = [] + for i in range(len(ypos)-1): + steps.append(ypos[i+1] - ypos[i]) + back.grid0.deltaSteps = steps + if back.grid1.orientation == 'vertical' and xva._tickValues: + xpos = list(map(xva.scale, [xva._valueMin] + xva._tickValues)) + steps = [] + for i in range(len(xpos)-1): + steps.append(xpos[i+1] - xpos[i]) + back.grid1.deltaSteps = steps + elif back.grid1.orientation == 'horizontal' and yva._tickValues: + ypos = list(map(yva.scale, [yva._valueMin] + yva._tickValues)) + steps = [] + for i in range(len(ypos)-1): + steps.append(ypos[i+1] - ypos[i]) + back.grid1.deltaSteps = steps + + self.calcPositions() + + width, height, scaleFactor = self.width, self.height, self.scaleFactor + if scaleFactor and scaleFactor!=1: + #g = Drawing(scaleFactor*width, scaleFactor*height) + g.transform = (scaleFactor, 0, 0, scaleFactor,0,0) + else: + g = Group() + + g.add(self.makeBackground()) + g.add(self.xValueAxis) + g.add(self.yValueAxis) + g.add(self.makeLines()) + + return g + +class AreaLinePlot(LinePlot): + '''we're given data in the form [(X1,Y11,..Y1M)....(Xn,Yn1,...YnM)]'''#' + def __init__(self): + LinePlot.__init__(self) + self._inFill = 1 + self.reversePlotOrder = 1 + self.data = [(1,20,100,30),(2,11,50,15),(3,15,70,40)] + + def draw(self): + try: + odata = self.data + n = len(odata) + m = len(odata[0]) + S = n*[0] + self.data = [] + for i in range(1,m): + D = [] + for j in range(n): + S[j] = S[j] + odata[j][i] + D.append((odata[j][0],S[j])) + self.data.append(D) + return LinePlot.draw(self) + finally: + self.data = odata + +class SplitLinePlot(AreaLinePlot): + def __init__(self): + AreaLinePlot.__init__(self) + self.xValueAxis = NormalDateXValueAxis() + self.yValueAxis = AdjYValueAxis() + self.data=[(20030601,0.95,0.05,0.0),(20030701,0.95,0.05,0.0),(20030801,0.95,0.05,0.0),(20030901,0.95,0.05,0.0),(20031001,0.95,0.05,0.0),(20031101,0.95,0.05,0.0),(20031201,0.95,0.05,0.0),(20040101,0.95,0.05,0.0),(20040201,0.95,0.05,0.0),(20040301,0.95,0.05,0.0),(20040401,0.95,0.05,0.0),(20040501,0.95,0.05,0.0),(20040601,0.95,0.05,0.0),(20040701,0.95,0.05,0.0),(20040801,0.95,0.05,0.0),(20040901,0.95,0.05,0.0),(20041001,0.95,0.05,0.0),(20041101,0.95,0.05,0.0),(20041201,0.95,0.05,0.0),(20050101,0.95,0.05,0.0),(20050201,0.95,0.05,0.0),(20050301,0.95,0.05,0.0),(20050401,0.95,0.05,0.0),(20050501,0.95,0.05,0.0),(20050601,0.95,0.05,0.0),(20050701,0.95,0.05,0.0),(20050801,0.95,0.05,0.0),(20050901,0.95,0.05,0.0),(20051001,0.95,0.05,0.0),(20051101,0.95,0.05,0.0),(20051201,0.95,0.05,0.0),(20060101,0.95,0.05,0.0),(20060201,0.95,0.05,0.0),(20060301,0.95,0.05,0.0),(20060401,0.95,0.05,0.0),(20060501,0.95,0.05,0.0),(20060601,0.95,0.05,0.0),(20060701,0.95,0.05,0.0),(20060801,0.95,0.05,0.0),(20060901,0.95,0.05,0.0),(20061001,0.95,0.05,0.0),(20061101,0.95,0.05,0.0),(20061201,0.95,0.05,0.0),(20070101,0.95,0.05,0.0),(20070201,0.95,0.05,0.0),(20070301,0.95,0.05,0.0),(20070401,0.95,0.05,0.0),(20070501,0.95,0.05,0.0),(20070601,0.95,0.05,0.0),(20070701,0.95,0.05,0.0),(20070801,0.95,0.05,0.0),(20070901,0.95,0.05,0.0),(20071001,0.95,0.05,0.0),(20071101,0.95,0.05,0.0),(20071201,0.95,0.05,0.0),(20080101,0.95,0.05,0.0),(20080201,0.95,0.05,0.0),(20080301,0.95,0.05,0.0),(20080401,0.95,0.05,0.0),(20080501,0.95,0.05,0.0),(20080601,0.95,0.05,0.0),(20080701,0.95,0.05,0.0),(20080801,0.95,0.05,0.0),(20080901,0.95,0.05,0.0),(20081001,0.95,0.05,0.0),(20081101,0.95,0.05,0.0),(20081201,0.95,0.05,0.0),(20090101,0.95,0.05,0.0),(20090201,0.91,0.09,0.0),(20090301,0.91,0.09,0.0),(20090401,0.91,0.09,0.0),(20090501,0.91,0.09,0.0),(20090601,0.91,0.09,0.0),(20090701,0.91,0.09,0.0),(20090801,0.91,0.09,0.0),(20090901,0.91,0.09,0.0),(20091001,0.91,0.09,0.0),(20091101,0.91,0.09,0.0),(20091201,0.91,0.09,0.0),(20100101,0.91,0.09,0.0),(20100201,0.81,0.19,0.0),(20100301,0.81,0.19,0.0),(20100401,0.81,0.19,0.0),(20100501,0.81,0.19,0.0),(20100601,0.81,0.19,0.0),(20100701,0.81,0.19,0.0),(20100801,0.81,0.19,0.0),(20100901,0.81,0.19,0.0),(20101001,0.81,0.19,0.0),(20101101,0.81,0.19,0.0),(20101201,0.81,0.19,0.0),(20110101,0.81,0.19,0.0),(20110201,0.72,0.28,0.0),(20110301,0.72,0.28,0.0),(20110401,0.72,0.28,0.0),(20110501,0.72,0.28,0.0),(20110601,0.72,0.28,0.0),(20110701,0.72,0.28,0.0),(20110801,0.72,0.28,0.0),(20110901,0.72,0.28,0.0),(20111001,0.72,0.28,0.0),(20111101,0.72,0.28,0.0),(20111201,0.72,0.28,0.0),(20120101,0.72,0.28,0.0),(20120201,0.53,0.47,0.0),(20120301,0.53,0.47,0.0),(20120401,0.53,0.47,0.0),(20120501,0.53,0.47,0.0),(20120601,0.53,0.47,0.0),(20120701,0.53,0.47,0.0),(20120801,0.53,0.47,0.0),(20120901,0.53,0.47,0.0),(20121001,0.53,0.47,0.0),(20121101,0.53,0.47,0.0),(20121201,0.53,0.47,0.0),(20130101,0.53,0.47,0.0),(20130201,0.44,0.56,0.0),(20130301,0.44,0.56,0.0),(20130401,0.44,0.56,0.0),(20130501,0.44,0.56,0.0),(20130601,0.44,0.56,0.0),(20130701,0.44,0.56,0.0),(20130801,0.44,0.56,0.0),(20130901,0.44,0.56,0.0),(20131001,0.44,0.56,0.0),(20131101,0.44,0.56,0.0),(20131201,0.44,0.56,0.0),(20140101,0.44,0.56,0.0),(20140201,0.36,0.5,0.14),(20140301,0.36,0.5,0.14),(20140401,0.36,0.5,0.14),(20140501,0.36,0.5,0.14),(20140601,0.36,0.5,0.14),(20140701,0.36,0.5,0.14),(20140801,0.36,0.5,0.14),(20140901,0.36,0.5,0.14),(20141001,0.36,0.5,0.14),(20141101,0.36,0.5,0.14),(20141201,0.36,0.5,0.14),(20150101,0.36,0.5,0.14),(20150201,0.3,0.41,0.29),(20150301,0.3,0.41,0.29),(20150401,0.3,0.41,0.29),(20150501,0.3,0.41,0.29),(20150601,0.3,0.41,0.29),(20150701,0.3,0.41,0.29),(20150801,0.3,0.41,0.29),(20150901,0.3,0.41,0.29),(20151001,0.3,0.41,0.29),(20151101,0.3,0.41,0.29),(20151201,0.3,0.41,0.29),(20160101,0.3,0.41,0.29),(20160201,0.26,0.36,0.38),(20160301,0.26,0.36,0.38),(20160401,0.26,0.36,0.38),(20160501,0.26,0.36,0.38),(20160601,0.26,0.36,0.38),(20160701,0.26,0.36,0.38),(20160801,0.26,0.36,0.38),(20160901,0.26,0.36,0.38),(20161001,0.26,0.36,0.38),(20161101,0.26,0.36,0.38),(20161201,0.26,0.36,0.38),(20170101,0.26,0.36,0.38),(20170201,0.2,0.3,0.5),(20170301,0.2,0.3,0.5),(20170401,0.2,0.3,0.5),(20170501,0.2,0.3,0.5),(20170601,0.2,0.3,0.5),(20170701,0.2,0.3,0.5),(20170801,0.2,0.3,0.5),(20170901,0.2,0.3,0.5),(20171001,0.2,0.3,0.5),(20171101,0.2,0.3,0.5),(20171201,0.2,0.3,0.5),(20180101,0.2,0.3,0.5),(20180201,0.13,0.37,0.5),(20180301,0.13,0.37,0.5),(20180401,0.13,0.37,0.5),(20180501,0.13,0.37,0.5),(20180601,0.13,0.37,0.5),(20180701,0.13,0.37,0.5),(20180801,0.13,0.37,0.5),(20180901,0.13,0.37,0.5),(20181001,0.13,0.37,0.5),(20181101,0.13,0.37,0.5),(20181201,0.13,0.37,0.5),(20190101,0.13,0.37,0.5),(20190201,0.1,0.4,0.5),(20190301,0.1,0.4,0.5),(20190401,0.1,0.4,0.5),(20190501,0.1,0.4,0.5),(20190601,0.1,0.4,0.5),(20190701,0.1,0.4,0.5),(20190801,0.1,0.4,0.5),(20190901,0.1,0.4,0.5),(20191001,0.1,0.4,0.5),(20191101,0.1,0.4,0.5),(20191201,0.1,0.4,0.5),(20200101,0.1,0.4,0.5)] + self.yValueAxis.requiredRange = None + self.yValueAxis.leftAxisPercent = 0 + self.yValueAxis.leftAxisOrigShiftMin = 0 + self.yValueAxis.leftAxisOrigShiftIPC = 0 + self.lines[0].strokeColor = colors.toColor(0x0033cc) + self.lines[1].strokeColor = colors.toColor(0x99c3ff) + self.lines[2].strokeColor = colors.toColor(0xCC0033) + +def _maxWidth(T, fontName, fontSize): + '''return max stringWidth for the list of strings T''' + if not isinstance(T,(tuple,list)): T = (T,) + T = [_f for _f in T if _f] + return T and max(list(map(lambda t,sW=stringWidth,fN=fontName, fS=fontSize: sW(t,fN,fS),T))) or 0 + +class ScatterPlot(LinePlot): + """A scatter plot widget""" + + _attrMap = AttrMap(BASE=LinePlot, + width = AttrMapValue(isNumber, desc="Width of the area inside the axes"), + height = AttrMapValue(isNumber, desc="Height of the area inside the axes"), + outerBorderOn = AttrMapValue(isBoolean, desc="Is there an outer border (continuation of axes)"), + outerBorderColor = AttrMapValue(isColorOrNone, desc="Color of outer border (if any)"), + labelOffset = AttrMapValue(isNumber, desc="Space between label and Axis (or other labels)",advancedUsage=1), + axisTickLengths = AttrMapValue(isNumber, desc="Lenth of the ticks on both axes"), + axisStrokeWidth = AttrMapValue(isNumber, desc="Stroke width for both axes"), + xLabel = AttrMapValue(isString, desc="Label for the whole X-Axis"), + yLabel = AttrMapValue(isString, desc="Label for the whole Y-Axis"), + data = AttrMapValue(isAnything, desc='Data points - a list of x/y tuples.'), + strokeColor = AttrMapValue(isColorOrNone, desc='Color used for border of plot area.'), + fillColor = AttrMapValue(isColorOrNone, desc='Color used for background interior of plot area.'), + leftPadding = AttrMapValue(isNumber, desc='Padding on left of drawing'), + rightPadding = AttrMapValue(isNumber, desc='Padding on right of drawing'), + topPadding = AttrMapValue(isNumber, desc='Padding at top of drawing'), + bottomPadding = AttrMapValue(isNumber, desc='Padding at bottom of drawing'), + ) + + def __init__(self): + LinePlot.__init__(self) + self.width = 142 + self.height = 77 + self.outerBorderOn = 1 + self.outerBorderColor = colors.black + self.background = None + + _labelOffset = 3 + _axisTickLengths = 2 + _axisStrokeWidth = 0.5 + + self.yValueAxis.valueMin = None + self.yValueAxis.valueMax = None + self.yValueAxis.valueStep = None + self.yValueAxis.labelTextFormat = '%s' + + self.xLabel="X Lable" + self.xValueAxis.labels.fontSize = 6 + + self.yLabel="Y Lable" + self.yValueAxis.labels.fontSize = 6 + + self.data =[((0.030, 62.73), + (0.074, 54.363), + (1.216, 17.964)), + + ((1.360, 11.621), + (1.387, 50.011), + (1.428, 68.953)), + + ((1.444, 86.888), + (1.754, 35.58), + (1.766, 36.05))] + + #values for lineplot + self.joinedLines = 0 + + self.leftPadding=5 + self.rightPadding=10 + self.topPadding=5 + self.bottomPadding=5 + + self.x = self.leftPadding+_axisTickLengths+(_labelOffset*2) + self.x=self.x+_maxWidth(str(self.yValueAxis.valueMax), self.yValueAxis.labels.fontName, self.yValueAxis.labels.fontSize) + self.y = self.bottomPadding+_axisTickLengths+_labelOffset+self.xValueAxis.labels.fontSize + + self.xValueAxis.labels.dy = -_labelOffset + self.xValueAxis.tickDown = _axisTickLengths + self.xValueAxis.strokeWidth = _axisStrokeWidth + self.xValueAxis.rangeRound='both' + self.yValueAxis.labels.dx = -_labelOffset + self.yValueAxis.tickLeft = _axisTickLengths + self.yValueAxis.strokeWidth = _axisStrokeWidth + self.yValueAxis.rangeRound='both' + + self.lineLabelFormat="%.2f" + self.lineLabels.fontSize = 5 + self.lineLabels.boxAnchor = 'e' + self.lineLabels.dx = -2 + self.lineLabelNudge = 0 + self.lines.symbol=makeMarker('FilledCircle',size=3) + self.lines[1].symbol=makeMarker('FilledDiamond',size=3) + self.lines[2].symbol=makeMarker('FilledSquare',size=3) + self.lines[2].strokeColor = colors.green + + def _getDrawingDimensions(self): + tx = self.leftPadding+self.yValueAxis.tickLeft+(self.yValueAxis.labels.dx*2)+self.xValueAxis.labels.fontSize + tx=tx+(5*_maxWidth(str(self.yValueAxis.valueMax), self.yValueAxis.labels.fontName, self.yValueAxis.labels.fontSize)) + tx=tx+self.width+self.rightPadding + t=('%.2f%%'%self.xValueAxis.valueMax) + tx=tx+(_maxWidth(t, self.yValueAxis.labels.fontName, self.yValueAxis.labels.fontSize)) + ty = self.bottomPadding+self.xValueAxis.tickDown+(self.xValueAxis.labels.dy*2)+(self.xValueAxis.labels.fontSize*2) + ty=ty+self.yValueAxis.labels.fontSize+self.height+self.topPadding + #print (tx, ty) + return (tx,ty) + + def demo(self,drawing=None): + if not drawing: + tx,ty=self._getDrawingDimensions() + drawing = Drawing(tx,ty) + drawing.add(self.draw()) + return drawing + + def draw(self): + ascent=getFont(self.xValueAxis.labels.fontName).face.ascent + if ascent==0: + ascent=0.718 # default (from helvetica) + ascent=ascent*self.xValueAxis.labels.fontSize # normalize + + #basic LinePlot - does the Axes, Ticks etc + lp = LinePlot.draw(self) + + xLabel = self.xLabel + if xLabel: #Overall label for the X-axis + xl=Label() + xl.x = (self.x+self.width)/2.0 + xl.y = 0 + xl.fontName = self.xValueAxis.labels.fontName + xl.fontSize = self.xValueAxis.labels.fontSize + xl.setText(xLabel) + lp.add(xl) + + yLabel = self.yLabel + if yLabel: #Overall label for the Y-axis + yl=Label() + yl.angle = 90 + yl.x = 0 + yl.y = (self.y+self.height/2.0) + yl.fontName = self.yValueAxis.labels.fontName + yl.fontSize = self.yValueAxis.labels.fontSize + yl.setText(yLabel) + lp.add(yl) + + # do a bounding box - in the same style as the axes + if self.outerBorderOn: + lp.add(Rect(self.x, self.y, self.width, self.height, + strokeColor = self.outerBorderColor, + strokeWidth = self.yValueAxis.strokeWidth, + fillColor = None)) + + lp.shift(self.leftPadding, self.bottomPadding) + + return lp + +def sample1a(): + "A line plot with non-equidistant points in x-axis." + + drawing = Drawing(400, 200) + + data = [ + ((1,1), (2,2), (2.5,1), (3,3), (4,5)), + ((1,2), (2,3), (2.5,2), (3.5,5), (4,6)) + ] + + lp = LinePlot() + + lp.x = 50 + lp.y = 50 + lp.height = 125 + lp.width = 300 + lp.data = data + lp.joinedLines = 1 + lp.strokeColor = colors.black + + lp.lines.symbol = makeMarker('UK_Flag') + + lp.lines[0].strokeWidth = 2 + lp.lines[1].strokeWidth = 4 + + lp.xValueAxis.valueMin = 0 + lp.xValueAxis.valueMax = 5 + lp.xValueAxis.valueStep = 1 + + lp.yValueAxis.valueMin = 0 + lp.yValueAxis.valueMax = 7 + lp.yValueAxis.valueStep = 1 + + drawing.add(lp) + + return drawing + + +def sample1b(): + "A line plot with non-equidistant points in x-axis." + + drawing = Drawing(400, 200) + + data = [ + ((1,1), (2,2), (2.5,1), (3,3), (4,5)), + ((1,2), (2,3), (2.5,2), (3.5,5), (4,6)) + ] + + lp = LinePlot() + + lp.x = 50 + lp.y = 50 + lp.height = 125 + lp.width = 300 + lp.data = data + lp.joinedLines = 1 + lp.lines.symbol = makeMarker('Circle') + lp.lineLabelFormat = '%2.0f' + lp.strokeColor = colors.black + + lp.xValueAxis.valueMin = 0 + lp.xValueAxis.valueMax = 5 + lp.xValueAxis.valueSteps = [1, 2, 2.5, 3, 4, 5] + lp.xValueAxis.labelTextFormat = '%2.1f' + + lp.yValueAxis.valueMin = 0 + lp.yValueAxis.valueMax = 7 + lp.yValueAxis.valueStep = 1 + + drawing.add(lp) + + return drawing + + +def sample1c(): + "A line plot with non-equidistant points in x-axis." + + drawing = Drawing(400, 200) + + data = [ + ((1,1), (2,2), (2.5,1), (3,3), (4,5)), + ((1,2), (2,3), (2.5,2), (3.5,5), (4,6)) + ] + + lp = LinePlot() + + lp.x = 50 + lp.y = 50 + lp.height = 125 + lp.width = 300 + lp.data = data + lp.joinedLines = 1 + lp.lines[0].symbol = makeMarker('FilledCircle') + lp.lines[1].symbol = makeMarker('Circle') + lp.lineLabelFormat = '%2.0f' + lp.strokeColor = colors.black + + lp.xValueAxis.valueMin = 0 + lp.xValueAxis.valueMax = 5 + lp.xValueAxis.valueSteps = [1, 2, 2.5, 3, 4, 5] + lp.xValueAxis.labelTextFormat = '%2.1f' + + lp.yValueAxis.valueMin = 0 + lp.yValueAxis.valueMax = 7 + lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6] + + drawing.add(lp) + + return drawing + + +def preprocessData(series): + "Convert date strings into seconds and multiply values by 100." + + return [(str2seconds(x[0]), x[1]*100) for x in series] + + +def sample2(): + "A line plot with non-equidistant points in x-axis." + + drawing = Drawing(400, 200) + + data = [ + (('25/11/1991',1), + ('30/11/1991',1.000933333), + ('31/12/1991',1.0062), + ('31/01/1992',1.0112), + ('29/02/1992',1.0158), + ('31/03/1992',1.020733333), + ('30/04/1992',1.026133333), + ('31/05/1992',1.030266667), + ('30/06/1992',1.034466667), + ('31/07/1992',1.038733333), + ('31/08/1992',1.0422), + ('30/09/1992',1.045533333), + ('31/10/1992',1.049866667), + ('30/11/1992',1.054733333), + ('31/12/1992',1.061), + ), + ] + + data[0] = preprocessData(data[0]) + + lp = LinePlot() + + lp.x = 50 + lp.y = 50 + lp.height = 125 + lp.width = 300 + lp.data = data + lp.joinedLines = 1 + lp.lines.symbol = makeMarker('FilledDiamond') + lp.strokeColor = colors.black + + start = mktime(mkTimeTuple('25/11/1991')) + t0 = mktime(mkTimeTuple('30/11/1991')) + t1 = mktime(mkTimeTuple('31/12/1991')) + t2 = mktime(mkTimeTuple('31/03/1992')) + t3 = mktime(mkTimeTuple('30/06/1992')) + t4 = mktime(mkTimeTuple('30/09/1992')) + end = mktime(mkTimeTuple('31/12/1992')) + lp.xValueAxis.valueMin = start + lp.xValueAxis.valueMax = end + lp.xValueAxis.valueSteps = [start, t0, t1, t2, t3, t4, end] + lp.xValueAxis.labelTextFormat = seconds2str + lp.xValueAxis.labels[1].dy = -20 + lp.xValueAxis.labels[2].dy = -35 + + lp.yValueAxis.labelTextFormat = '%4.2f' + lp.yValueAxis.valueMin = 100 + lp.yValueAxis.valueMax = 110 + lp.yValueAxis.valueStep = 2 + + drawing.add(lp) + + return drawing + +def sampleFillPairedData(): + d = Drawing(400,200) + chart = SimpleTimeSeriesPlot() + d.add(chart) + chart.data = [FillPairedData(chart.data[0],1),chart.data[1]] + chart.lines[0].filler= Filler(fillColor=colors.toColor('#9f9f9f'),strokeWidth=0,strokeColor=None) + chart.lines[0].strokeColor = None + chart.lines[1].strokeColor = None + return d diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/markers.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/markers.py new file mode 100644 index 0000000000000000000000000000000000000000..10979dfd556787072867d03a1bf5e8bd476db346 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/markers.py @@ -0,0 +1,82 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/graphics/charts/markers.py + +__version__='3.3.0' +__doc__="""This modules defines a collection of markers used in charts. + +The make* functions return a simple shape or a widget as for +the smiley. +""" + +from reportlab.lib import colors +from reportlab.graphics.shapes import Rect, Circle, Polygon +from reportlab.graphics.widgets.signsandsymbols import SmileyFace + + +def makeEmptySquare(x, y, size, color): + "Make an empty square marker." + + d = size/2.0 + rect = Rect(x-d, y-d, 2*d, 2*d) + rect.strokeColor = color + rect.fillColor = None + + return rect + + +def makeFilledSquare(x, y, size, color): + "Make a filled square marker." + + d = size/2.0 + rect = Rect(x-d, y-d, 2*d, 2*d) + rect.strokeColor = color + rect.fillColor = color + + return rect + + +def makeFilledDiamond(x, y, size, color): + "Make a filled diamond marker." + + d = size/2.0 + poly = Polygon((x-d,y, x,y+d, x+d,y, x,y-d)) + poly.strokeColor = color + poly.fillColor = color + + return poly + + +def makeEmptyCircle(x, y, size, color): + "Make a hollow circle marker." + + d = size/2.0 + circle = Circle(x, y, d) + circle.strokeColor = color + circle.fillColor = colors.white + + return circle + + +def makeFilledCircle(x, y, size, color): + "Make a hollow circle marker." + + d = size/2.0 + circle = Circle(x, y, d) + circle.strokeColor = color + circle.fillColor = color + + return circle + + +def makeSmiley(x, y, size, color): + "Make a smiley marker." + + d = size + s = SmileyFace() + s.fillColor = color + s.x = x-d + s.y = y-d + s.size = d*2 + + return s diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/piecharts.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/piecharts.py new file mode 100644 index 0000000000000000000000000000000000000000..fba0ffdb1a3609a96350c5af5147713e9e00902a --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/piecharts.py @@ -0,0 +1,1706 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/graphics/charts/piecharts.py +# experimental pie chart script. Two types of pie - one is a monolithic +#widget with all top-level properties, the other delegates most stuff to +#a wedges collection whic lets you customize the group or every individual +#wedge. + +__version__='3.3.0' +__doc__="""Basic Pie Chart class. + +This permits you to customize and pop out individual wedges; +supports elliptical and circular pies. +""" + +import functools +from math import sin, cos, pi + +from reportlab.lib import colors +from reportlab.lib.validators import isNumber, isListOfNumbersOrNone,\ + isListOfNumbers, isColorOrNone, isString,\ + isListOfStringsOrNone, OneOf,\ + isBoolean, isListOfColors, isNumberOrNone,\ + isNoneOrListOfNoneOrStrings, isTextAnchor,\ + isNoneOrListOfNoneOrNumbers, isBoxAnchor,\ + isStringOrNone, NoneOr, EitherOr,\ + isNumberInRange, isCallable +from reportlab.graphics.widgets.markers import uSymbol2Symbol, isSymbol +from reportlab.lib.attrmap import * +from reportlab.graphics.shapes import Group, Drawing, Ellipse, Wedge, String, STATE_DEFAULTS, ArcPath, Polygon, Rect, PolyLine, Line +from reportlab.graphics.widgetbase import TypedPropertyCollection, PropHolder +from reportlab.graphics.charts.areas import PlotArea +from reportlab.graphics.charts.legends import _objStr +from reportlab.graphics.charts.textlabels import Label +from reportlab import cmp + +_ANGLE2BOXANCHOR={0:'w', 45:'sw', 90:'s', 135:'se', 180:'e', 225:'ne', 270:'n', 315: 'nw', -45: 'nw'} +_ANGLE2RBOXANCHOR={0:'e', 45:'ne', 90:'n', 135:'nw', 180:'w', 225:'sw', 270:'s', 315: 'se', -45: 'se'} + +_ANGLELO = 1e-7 +_ANGLEHI = 360.0 - _ANGLELO + +class WedgeLabel(Label): + def _checkDXY(self,ba): + pass + def _getBoxAnchor(self): + ba = self.boxAnchor + if ba in ('autox','autoy'): + na = (int((self._pmv%360)/45.)*45)%360 + if not (na % 90): # we have a right angle case + da = (self._pmv - na) % 360 + if abs(da)>5: + na += (da>0 and 45 or -45) + ba = (getattr(self,'_anti',None) and _ANGLE2RBOXANCHOR or _ANGLE2BOXANCHOR)[na] + self._checkDXY(ba) + return ba + +class WedgeProperties(PropHolder): + """This holds descriptive information about the wedges in a pie chart. + + It is not to be confused with the 'wedge itself'; this just holds + a recipe for how to format one, and does not allow you to hack the + angles. It can format a genuine Wedge object for you with its + format method. + """ + _attrMap = AttrMap( + strokeWidth = AttrMapValue(isNumber,desc='Width of the wedge border'), + fillColor = AttrMapValue(isColorOrNone,desc='Filling color of the wedge'), + strokeColor = AttrMapValue(isColorOrNone,desc='Color of the wedge border'), + strokeDashArray = AttrMapValue(isListOfNumbersOrNone,desc='Style of the wedge border, expressed as a list of lengths of alternating dashes and blanks'), + strokeLineCap = AttrMapValue(OneOf(0,1,2),desc="Line cap 0=butt, 1=round & 2=square"), + strokeLineJoin = AttrMapValue(OneOf(0,1,2),desc="Line join 0=miter, 1=round & 2=bevel"), + strokeMiterLimit = AttrMapValue(isNumber,desc='Miter limit control miter line joins'), + popout = AttrMapValue(isNumber,desc="How far of centre a wedge to pop"), + fontName = AttrMapValue(isString,desc='Name of the font of the label text'), + fontSize = AttrMapValue(isNumber,desc='Size of the font of the label text in points'), + fontColor = AttrMapValue(isColorOrNone,desc='Color of the font of the label text'), + labelRadius = AttrMapValue(isNumber,desc='Distance between the center of the label box and the center of the pie, expressed in times the radius of the pie'), + label_dx = AttrMapValue(isNumber,desc='X Offset of the label'), + label_dy = AttrMapValue(isNumber,desc='Y Offset of the label'), + label_angle = AttrMapValue(isNumber,desc='Angle of the label, default (0) is horizontal, 90 is vertical, 180 is upside down'), + label_boxAnchor = AttrMapValue(isBoxAnchor,desc='Anchoring point of the label'), + label_boxStrokeColor = AttrMapValue(isColorOrNone,desc='Border color for the label box'), + label_boxStrokeWidth = AttrMapValue(isNumber,desc='Border width for the label box'), + label_boxFillColor = AttrMapValue(isColorOrNone,desc='Filling color of the label box'), + label_strokeColor = AttrMapValue(isColorOrNone,desc='Border color for the label text'), + label_strokeWidth = AttrMapValue(isNumber,desc='Border width for the label text'), + label_text = AttrMapValue(isStringOrNone,desc='Text of the label'), + label_leading = AttrMapValue(isNumberOrNone,desc=''), + label_width = AttrMapValue(isNumberOrNone,desc='Width of the label'), + label_maxWidth = AttrMapValue(isNumberOrNone,desc='Maximum width the label can grow to'), + label_height = AttrMapValue(isNumberOrNone,desc='Height of the label'), + label_textAnchor = AttrMapValue(isTextAnchor,desc='Maximum height the label can grow to'), + label_visible = AttrMapValue(isBoolean,desc="True if the label is to be drawn"), + label_topPadding = AttrMapValue(isNumber,'Padding at top of box'), + label_leftPadding = AttrMapValue(isNumber,'Padding at left of box'), + label_rightPadding = AttrMapValue(isNumber,'Padding at right of box'), + label_bottomPadding = AttrMapValue(isNumber,'Padding at bottom of box'), + label_simple_pointer = AttrMapValue(isBoolean,'Set to True for simple pointers'), + label_pointer_strokeColor = AttrMapValue(isColorOrNone,desc='Color of indicator line'), + label_pointer_strokeWidth = AttrMapValue(isNumber,desc='StrokeWidth of indicator line'), + label_pointer_elbowLength = AttrMapValue(isNumber,desc='Length of final indicator line segment'), + label_pointer_edgePad = AttrMapValue(isNumber,desc='pad between pointer label and box'), + label_pointer_piePad = AttrMapValue(isNumber,desc='pad between pointer label and pie'), + swatchMarker = AttrMapValue(NoneOr(isSymbol), desc="None or makeMarker('Diamond') ...",advancedUsage=1), + visible = AttrMapValue(isBoolean,'Set to false to skip displaying'), + shadingAmount = AttrMapValue(isNumberOrNone,desc='amount by which to shade fillColor'), + shadingAngle = AttrMapValue(isNumber,desc='shading changes at multiple of this angle (in degrees)'), + shadingDirection = AttrMapValue(OneOf('normal','anti'),desc="Whether shading is at start or end of wedge/sector"), + shadingKind = AttrMapValue(OneOf(None,'lighten','darken'),desc="use colors.Whiter or Blacker"), + ) + + def __init__(self): + self.strokeWidth = 0 + self.fillColor = None + self.strokeColor = STATE_DEFAULTS["strokeColor"] + self.strokeDashArray = STATE_DEFAULTS["strokeDashArray"] + self.strokeLineJoin = 1 + self.strokeLineCap = 0 + self.strokeMiterLimit = 0 + self.popout = 0 + self.fontName = STATE_DEFAULTS["fontName"] + self.fontSize = STATE_DEFAULTS["fontSize"] + self.fontColor = STATE_DEFAULTS["fillColor"] + self.labelRadius = 1.2 + self.label_dx = self.label_dy = self.label_angle = 0 + self.label_text = None + self.label_topPadding = self.label_leftPadding = self.label_rightPadding = self.label_bottomPadding = 0 + self.label_boxAnchor = 'autox' + self.label_boxStrokeColor = None #boxStroke + self.label_boxStrokeWidth = 0.5 #boxStrokeWidth + self.label_boxFillColor = None + self.label_strokeColor = None + self.label_strokeWidth = 0.1 + self.label_leading = self.label_width = self.label_maxWidth = self.label_height = None + self.label_textAnchor = 'start' + self.label_simple_pointer = 0 + self.label_visible = 1 + self.label_pointer_strokeColor = colors.black + self.label_pointer_strokeWidth = 0.5 + self.label_pointer_elbowLength = 3 + self.label_pointer_edgePad = 2 + self.label_pointer_piePad = 3 + self.visible = 1 + self.shadingKind = None + self.shadingAmount = 0.5 + self.shadingAngle = 2.0137 + self.shadingDirection = 'normal' #or 'anti' + +def _addWedgeLabel(self,text,angle,labelX,labelY,wedgeStyle,labelClass=None): + # now draw a label + if self.simpleLabels: + theLabel = String(labelX, labelY, text) + if not self.sideLabels: + theLabel.textAnchor = "middle" + else: + if (abs(angle) < 90 ) or (angle >270 and angle<450) or (-450< angle <-270): + theLabel.textAnchor = "start" + else: + theLabel.textAnchor = "end" + theLabel._pmv = angle + theLabel._simple_pointer = 0 + else: + if labelClass is None: + labelClass = getattr(self,'labelClass',WedgeLabel) + theLabel = labelClass() + theLabel._pmv = angle + theLabel.x = labelX + theLabel.y = labelY + theLabel.dx = wedgeStyle.label_dx + if not self.sideLabels: + theLabel.dy = wedgeStyle.label_dy + theLabel.boxAnchor = wedgeStyle.label_boxAnchor + else: + if wedgeStyle.fontSize is None: + sideLabels_dy = self.fontSize / 2.5 + else: + sideLabels_dy = wedgeStyle.fontSize / 2.5 + if wedgeStyle.label_dy is None: + theLabel.dy = sideLabels_dy + else: + theLabel.dy = wedgeStyle.label_dy + sideLabels_dy + if (abs(angle) < 90 ) or (angle >270 and angle<450) or (-450< angle <-270): + theLabel.boxAnchor = 'w' + else: + theLabel.boxAnchor = 'e' + theLabel.angle = wedgeStyle.label_angle + theLabel.boxStrokeColor = wedgeStyle.label_boxStrokeColor + theLabel.boxStrokeWidth = wedgeStyle.label_boxStrokeWidth + theLabel.boxFillColor = wedgeStyle.label_boxFillColor + theLabel.strokeColor = wedgeStyle.label_strokeColor + theLabel.strokeWidth = wedgeStyle.label_strokeWidth + _text = wedgeStyle.label_text + if _text is None: _text = text + theLabel._text = _text + theLabel.leading = wedgeStyle.label_leading + theLabel.width = wedgeStyle.label_width + theLabel.maxWidth = wedgeStyle.label_maxWidth + theLabel.height = wedgeStyle.label_height + theLabel.textAnchor = wedgeStyle.label_textAnchor + theLabel.visible = wedgeStyle.label_visible + theLabel.topPadding = wedgeStyle.label_topPadding + theLabel.leftPadding = wedgeStyle.label_leftPadding + theLabel.rightPadding = wedgeStyle.label_rightPadding + theLabel.bottomPadding = wedgeStyle.label_bottomPadding + theLabel._simple_pointer = wedgeStyle.label_simple_pointer + theLabel.fontSize = wedgeStyle.fontSize + theLabel.fontName = wedgeStyle.fontName + theLabel.fillColor = wedgeStyle.fontColor + return theLabel + +def _fixLabels(labels,n): + if labels is None: + labels = [''] * n + else: + i = n-len(labels) + if i>0: labels = list(labels)+['']*i + return labels + +class AbstractPieChart(PlotArea): + + def makeSwatchSample(self, rowNo, x, y, width, height): + baseStyle = self.slices + styleIdx = rowNo % len(baseStyle) + style = baseStyle[styleIdx] + strokeColor = getattr(style, 'strokeColor', getattr(baseStyle,'strokeColor',None)) + fillColor = getattr(style, 'fillColor', getattr(baseStyle,'fillColor',None)) + strokeDashArray = getattr(style, 'strokeDashArray', getattr(baseStyle,'strokeDashArray',None)) + strokeWidth = getattr(style, 'strokeWidth', getattr(baseStyle, 'strokeWidth',None)) + swatchMarker = getattr(style, 'swatchMarker', getattr(baseStyle, 'swatchMarker',None)) + if swatchMarker: + return uSymbol2Symbol(swatchMarker,x+width/2.,y+height/2.,fillColor) + return Rect(x,y,width,height,strokeWidth=strokeWidth,strokeColor=strokeColor, + strokeDashArray=strokeDashArray,fillColor=fillColor) + + def getSeriesName(self,i,default=None): + '''return series name i or default''' + try: + text = _objStr(self.labels[i]) + except: + text = default + if not self.simpleLabels: + _text = getattr(self.slices[i],'label_text','') + if _text is not None: text = _text + return text + +def boundsOverlap(P,Q): + return not(P[0]>Q[2]-1e-2 or Q[0]>P[2]-1e-2 or P[1]>(0.5*(Q[1]+Q[3]))-1e-2 or Q[1]>(0.5*(P[1]+P[3]))-1e-2) + +def _findOverlapRun(B,i,wrap): + '''find overlap run containing B[i]''' + n = len(B) + R = [i] + while 1: + i = R[-1] + j = (i+1)%n + if j in R or not boundsOverlap(B[i],B[j]): break + R.append(j) + while 1: + i = R[0] + j = (i-1)%n + if j in R or not boundsOverlap(B[i],B[j]): break + R.insert(0,j) + return R + +def findOverlapRun(B,wrap=1): + '''determine a set of overlaps in bounding boxes B or return None''' + n = len(B) + if n>1: + for i in range(n-1): + R = _findOverlapRun(B,i,wrap) + if len(R)>1: return R + return None + +def fixLabelOverlaps(L, sideLabels=False, mult0=1.0): + nL = len(L) + if nL<2: return + B = [l._origdata['bounds'] for l in L] + OK = 1 + RP = [] + iter = 0 + mult0 = float(mult0 + 0) + mult = mult0 + + if not sideLabels: + while iter<30: + R = findOverlapRun(B) + if not R: break + nR = len(R) + if nR==nL: break + if not [r for r in RP if r in R]: + mult = mult0 + da = 0 + r0 = R[0] + rL = R[-1] + bi = B[r0] + taa = aa = _360(L[r0]._pmv) + for r in R[1:]: + b = B[r] + da = max(da,min(b[2]-bi[0],bi[2]-b[0])) + bi = b + aa += L[r]._pmv + aa = aa/float(nR) + utaa = abs(L[rL]._pmv-taa) + ntaa = _360(utaa) + da *= mult*(nR-1)/ntaa + + for r in R: + l = L[r] + orig = l._origdata + angle = l._pmv = _360(l._pmv+da*(_360(l._pmv)-aa)) + rad = angle/_180_pi + l.x = orig['cx'] + orig['rx']*cos(rad) + l.y = orig['cy'] + orig['ry']*sin(rad) + B[r] = l.getBounds() + RP = R + mult *= 1.05 + iter += 1 + + else: + while iter<30: + R = findOverlapRun(B) + if not R: break + nR = len(R) + if nR == nL: break + l1 = L[-1] + orig1 = l1._origdata + bounds1 = orig1['bounds'] + for i,r in enumerate(R): + l = L[r] + orig = l._origdata + bounds = orig['bounds'] + diff1 = 0 + diff2 = 0 + if not i == nR-1: + if not bounds == bounds1: + if bounds[3]>bounds1[1] and bounds1[1]bounds[1] and bounds[1] diff2: + l.y +=0.5*(bounds1[3]-bounds1[1]) + elif diff2 >= diff1: + l.y -= 0.5*(bounds1[3]-bounds1[1]) + B[r] = l.getBounds() + iter += 1 + +def intervalIntersection(A,B): + x,y = max(min(A),min(B)),min(max(A),max(B)) + if x>=y: return None + return x,y + +def _makeSideArcDefs(sa,direction): + sa %= 360 + if 90<=sa<270: + if direction=='clockwise': + a = (0,90,sa),(1,-90,90),(0,-360+sa,-90) + else: + a = (0,sa,270),(1,270,450),(0,450,360+sa) + else: + offs = sa>=270 and 360 or 0 + if direction=='clockwise': + a = (1,offs-90,sa),(0,offs-270,offs-90),(1,-360+sa,offs-270) + else: + a = (1,sa,offs+90),(0,offs+90,offs+270),(1,offs+270,360+sa) + return tuple([a for a in a if a[1]1: a.sort(key=_keyFLA) + return a[0] + +def _fPLSide(l,width,side=None): + data = l._origdata + if side is None: + li = data['li'] + ri = data['ri'] + if li is None: + side = 1 + i = ri + elif ri is None: + side = 0 + i = li + elif li[1]-li[0]>ri[1]-ri[0]: + side = 0 + i = li + else: + side = 1 + i = ri + w = data['width'] + edgePad = data['edgePad'] + if not side: #on left + l._pmv = 180 + l.x = edgePad+w + i = data['li'] + else: + l._pmv = 0 + l.x = width - w - edgePad + i = data['ri'] + mid = data['mid'] = (i[0]+i[1])*0.5 + data['smid'] = sin(mid/_180_pi) + data['cmid'] = cos(mid/_180_pi) + data['side'] = side + return side,w + +#key functions +def _fPLCF(a,b): + return cmp(b._origdata['smid'],a._origdata['smid']) +_fPLCF = functools.cmp_to_key(_fPLCF) + +def _arcCF(a): + return a[1] + +def _fixPointerLabels(n,L,x,y,width,height,side=None): + LR = [],[] + mlr = [0,0] + for l in L: + i,w = _fPLSide(l,width,side) + LR[i].append(l) + mlr[i] = max(w,mlr[i]) + mul = 1 + G = n*[None] + mel = 0 + hh = height*0.5 + yhh = y+hh + m = max(mlr) + for i in (0,1): + T = LR[i] + if T: + B = [] + aB = B.append + S = [] + aS = S.append + T.sort(key=_fPLCF) + p = 0 + yh = y+height + for l in T: + data = l._origdata + inc = x+mul*(m-data['width']) + l.x += inc + G[data['index']] = l + ly = yhh+data['smid']*hh + b = data['bounds'] + b2 = (b[3]-b[1])*0.5 + if ly+b2>yh: ly = yh-b2 + if ly-b2sFree: break + yh = B[j0][3]+sAbove*sNeed/sFree + for r in R: + l = T[r] + data = l._origdata + b = data['bounds'] + b2 = (b[3]-b[1])*0.5 + yh -= 0.5 + ly = l.y = yh-b2 + B[r] = data['bounds'] = (b[0],ly-b2,b[2],yh) + yh = ly - b2 - 0.5 + mlr[i] = m+p + mul = -1 + return G, mlr[0], mlr[1], mel + +def theta0(data, direction): + fac = (2*pi)/sum(data) + rads = [d*fac for d in data] + + r0 = 0 + hrads = [] + for r in rads: + hrads.append(r0+r*0.5) + r0 += r + + vstar = len(data)*1e6 + rstar = 0 + delta = pi/36.0 + for i in range(36): + r = i*delta + v = sum([abs(sin(r+a)) for a in hrads]) + if v < vstar: + if direction == 'clockwise': + rstar=-r + else: + rstar=r + vstar = v + return rstar*180/pi + + +class AngleData(float): + '''use this to carry the data along with the angle''' + def __new__(cls,angle,data): + self = float.__new__(cls,angle) + self._data = data + return self + +class Pie(AbstractPieChart): + _attrMap = AttrMap(BASE=AbstractPieChart, + data = AttrMapValue(isListOfNumbers, desc='List of numbers defining wedge sizes; need not sum to 1'), + labels = AttrMapValue(isListOfStringsOrNone, desc="Optional list of labels to use for each data point"), + startAngle = AttrMapValue(isNumber, desc="Angle of first slice; 0 is due East"), + direction = AttrMapValue(OneOf('clockwise', 'anticlockwise'), desc="'clockwise' or 'anticlockwise'"), + slices = AttrMapValue(None, desc="Collection of wedge descriptor objects"), + simpleLabels = AttrMapValue(isBoolean, desc="If true(default) use a simple String not an advanced WedgeLabel. A WedgeLabel is customisable using the properties prefixed label_ in the collection slices."), + other_threshold = AttrMapValue(isNumber, desc='A value for doing threshholding, not used yet.',advancedUsage=1), + checkLabelOverlap = AttrMapValue(EitherOr((isNumberInRange(0.05,1),isBoolean)), desc="If true check and attempt to fix\n standard label overlaps(default off)",advancedUsage=1), + pointerLabelMode = AttrMapValue(OneOf(None,'LeftRight','LeftAndRight'), desc='',advancedUsage=1), + sameRadii = AttrMapValue(isBoolean, desc="If true make x/y radii the same(default off)",advancedUsage=1), + orderMode = AttrMapValue(OneOf('fixed','alternate'),advancedUsage=1), + xradius = AttrMapValue(isNumberOrNone, desc="X direction Radius"), + yradius = AttrMapValue(isNumberOrNone, desc="Y direction Radius"), + innerRadiusFraction = AttrMapValue(isNumberOrNone, desc="fraction of radii to start wedges at"), + wedgeRecord = AttrMapValue(None, desc="callable(wedge,*args,**kwds)",advancedUsage=1), + sideLabels = AttrMapValue(isBoolean, desc="If true attempt to make piechart with labels along side and pointers"), + sideLabelsOffset = AttrMapValue(isNumber, desc="The fraction of the pie width that the labels are situated at from the edges of the pie"), + labelClass=AttrMapValue(NoneOr(isCallable), desc="A class factory to use for non simple labels"), + angleRange = AttrMapValue(isNumber, desc='total degree range for the doughnut defaults to 360'), + ) + other_threshold=None + + def __init__(self,**kwds): + PlotArea.__init__(self) + setattr(self,'x',kwds.pop('x',0)) + setattr(self,'y',kwds.pop('y',0)) + setattr(self,'width',kwds.pop('width',100)) + setattr(self,'height',kwds.pop('height',100)) + setattr(self,'data',kwds.pop('data',[1,2.3,1.7,4.2])) + setattr(self,'labels',kwds.pop('labels',None)) + setattr(self,'startAngle',kwds.pop('startAngle',90)) + setattr(self,'direction',kwds.pop('direction',"clockwise")) + setattr(self,'simpleLabels',kwds.pop('simpleLabels',1)) + setattr(self,'checkLabelOverlap',kwds.pop('checkLabelOverlap',0)) + setattr(self,'pointerLabelMode',kwds.pop('pointerLabelMode',None)) + setattr(self,'sameRadii',kwds.pop('sameRadii',False)) + setattr(self,'orderMode',kwds.pop('orderMode','fixed')) + setattr(self,'xradius',kwds.pop('xradius',None)) + setattr(self,'yradius',kwds.pop('yradius',None)) + setattr(self,'innerRadiusFraction',kwds.pop('innerRadiusFraction',None)) + setattr(self,'sideLabels',kwds.pop('sideLabels',0)) + setattr(self,'sideLabelsOffset',kwds.pop('sideLabelsOffset',0.1)) + setattr(self,'slices',kwds.pop('slices',TypedPropertyCollection(WedgeProperties))) + setattr(self,'angleRange',kwds.pop('angleRange',360)) + + self.slices[0].fillColor = colors.darkcyan + self.slices[1].fillColor = colors.blueviolet + self.slices[2].fillColor = colors.blue + self.slices[3].fillColor = colors.cyan + self.slices[4].fillColor = colors.pink + self.slices[5].fillColor = colors.magenta + self.slices[6].fillColor = colors.yellow + + def demo(self): + d = Drawing(200, 100) + + pc = Pie() + pc.x = 50 + pc.y = 10 + pc.width = 100 + pc.height = 80 + pc.data = [10,20,30,40,50,60] + pc.labels = ['a','b','c','d','e','f'] + + pc.slices.strokeWidth=0.5 + pc.slices[3].popout = 10 + pc.slices[3].strokeWidth = 2 + pc.slices[3].strokeDashArray = [2,2] + pc.slices[3].labelRadius = 1.75 + pc.slices[3].fontColor = colors.red + pc.slices[0].fillColor = colors.darkcyan + pc.slices[1].fillColor = colors.blueviolet + pc.slices[2].fillColor = colors.blue + pc.slices[3].fillColor = colors.cyan + pc.slices[4].fillColor = colors.aquamarine + pc.slices[5].fillColor = colors.cadetblue + pc.slices[6].fillColor = colors.lightcoral + + d.add(pc) + return d + + def makePointerLabels(self,angles,plMode): + class PL: + def __init__(self,centerx,centery,xradius,yradius,data,lu=0,ru=0): + self.centerx = centerx + self.centery = centery + self.xradius = xradius + self.yradius = yradius + self.data = data + self.lu = lu + self.ru = ru + + labelX = self.width-2 + labelY = self.height + n = nr = nl = maxW = sumH = 0 + styleCount = len(self.slices) + L=[] + L_add = L.append + refArcs = _makeSideArcDefs(self.startAngle,self.direction) + for i, A in angles: + if A[1] is None: continue + sn = self.getSeriesName(i,'') + if not sn: continue + style = self.slices[i%styleCount] + if not style.label_visible or not style.visible: continue + n += 1 + l=_addWedgeLabel(self,sn,180,labelX,labelY,style) + L_add(l) + b = l.getBounds() + w = b[2]-b[0] + h = b[3]-b[1] + ri = [(a[0],intervalIntersection(A,(a[1],a[2]))) for a in refArcs] + li = _findLargestArc(ri,0) + ri = _findLargestArc(ri,1) + if li and ri: + if plMode=='LeftAndRight': + if li[1]-li[0]ri[1]-ri[0]: + ri = None + if ri: nr += 1 + if li: nl += 1 + l._origdata = dict(bounds=b,width=w,height=h,li=li,ri=ri,index=i,edgePad=style.label_pointer_edgePad,piePad=style.label_pointer_piePad,elbowLength=style.label_pointer_elbowLength) + maxW = max(w,maxW) + sumH += h+2 + + if not n: #we have no labels + xradius = self.width*0.5 + yradius = self.height*0.5 + centerx = self.x+xradius + centery = self.y+yradius + if self.xradius: xradius = self.xradius + if self.yradius: yradius = self.yradius + if self.sameRadii: xradius=yradius=min(xradius,yradius) + return PL(centerx,centery,xradius,yradius,[]) + + aonR = nr==n + if sumH=1e-5] + W.sort(key=_arcCF) + T = [[],[]] + i = 0 + while W: + if i<2: + a = W.pop(0) + else: + a = W.pop(-1) + T[i%2].append(a) + i += 1 + i %= 4 + T[1].reverse() + D = T[0]+T[1] + [a for a in D if abs(a[1])<1e-5] + A = [] + a = A.append + for i, angle in D: + endAngle = (startAngle + (angle * whichWay)) + if abs(angle)>=_ANGLELO: + if startAngle >= endAngle: + aa = endAngle,startAngle + else: + aa = startAngle,endAngle + else: + aa = startAngle, None + if wr: + aa = (AngleData(aa[0],angle._data),aa[1]) + startAngle = endAngle + a((i,aa)) + return A + + def makeWedges(self): + angles = self.makeAngles() + #Checking to see whether there are too many wedges packed in too small a space + halfAngles = [] + for i,(a1,a2) in angles: + if a2 is None: + halfAngle = a1 + else: + halfAngle = 0.5*(a2+a1) + halfAngles.append(halfAngle) + sideLabels = self.sideLabels + n = len(angles) + labels = _fixLabels(self.labels,n) + wr = getattr(self,'wedgeRecord',None) + + self._seriesCount = n + styleCount = len(self.slices) + + plMode = self.pointerLabelMode + if sideLabels: + plMode = None + if plMode: + checkLabelOverlap = False + PL=self.makePointerLabels(angles,plMode) + xradius = PL.xradius + yradius = PL.yradius + centerx = PL.centerx + centery = PL.centery + PL_data = PL.data + gSN = lambda i: '' + else: + xradius = self.width*0.5 + yradius = self.height*0.5 + centerx = self.x + xradius + centery = self.y + yradius + if self.xradius: xradius = self.xradius + if self.yradius: yradius = self.yradius + if self.sameRadii: xradius=yradius=min(xradius,yradius) + checkLabelOverlap = self.checkLabelOverlap + gSN = lambda i: self.getSeriesName(i,'') + + g = Group() + g_add = g.add + L = [] + L_add = L.append + + innerRadiusFraction = self.innerRadiusFraction + + + for i,(a1,a2) in angles: + if a2 is None: continue + #if we didn't use %stylecount here we'd end up with the later wedges + #all having the default style + wedgeStyle = self.slices[i%styleCount] + if not wedgeStyle.visible: continue + aa = abs(a2-a1) + + # is it a popout? + cx, cy = centerx, centery + text = gSN(i) + popout = wedgeStyle.popout + if text or popout: + averageAngle = (a1+a2)/2.0 + aveAngleRadians = averageAngle/_180_pi + cosAA = cos(aveAngleRadians) + sinAA = sin(aveAngleRadians) + if popout and aa<_ANGLEHI: + # pop out the wedge + cx = centerx + popout*cosAA + cy = centery + popout*sinAA + + if innerRadiusFraction: + theWedge = Wedge(cx, cy, xradius, a1, a2, yradius=yradius, + radius1=xradius*innerRadiusFraction,yradius1=yradius*innerRadiusFraction) + else: + if aa>=_ANGLEHI: + theWedge = Ellipse(cx, cy, xradius, yradius) + else: + theWedge = Wedge(cx, cy, xradius, a1, a2, yradius=yradius) + + + theWedge.fillColor = wedgeStyle.fillColor + theWedge.strokeColor = wedgeStyle.strokeColor + theWedge.strokeWidth = wedgeStyle.strokeWidth + theWedge.strokeLineJoin = wedgeStyle.strokeLineJoin + theWedge.strokeLineCap = wedgeStyle.strokeLineCap + theWedge.strokeMiterLimit = wedgeStyle.strokeMiterLimit + theWedge.strokeDashArray = wedgeStyle.strokeDashArray + + shader = wedgeStyle.shadingKind + if shader: + nshades = aa / float(wedgeStyle.shadingAngle) + if nshades > 1: + shader = colors.Whiter if shader=='lighten' else colors.Blacker + nshades = 1+int(nshades) + shadingAmount = 1-wedgeStyle.shadingAmount + if wedgeStyle.shadingDirection=='normal': + dsh = (1-shadingAmount)/float(nshades-1) + shf1 = shadingAmount + else: + dsh = (shadingAmount-1)/float(nshades-1) + shf1 = 1 + shda = (a2-a1)/float(nshades) + shsc = wedgeStyle.fillColor + theWedge.fillColor = None + for ish in range(nshades): + sha1 = a1 + ish*shda + sha2 = a1 + (ish+1)*shda + shc = shader(shsc,shf1 + dsh*ish) + if innerRadiusFraction: + shWedge = Wedge(cx, cy, xradius, sha1, sha2, yradius=yradius, + radius1=xradius*innerRadiusFraction,yradius1=yradius*innerRadiusFraction) + else: + shWedge = Wedge(cx, cy, xradius, sha1, sha2, yradius=yradius) + shWedge.fillColor = shc + shWedge.strokeColor = None + shWedge.strokeWidth = 0 + g_add(shWedge) + + g_add(theWedge) + if wr: + wr(theWedge,value=a1._data,label=text) + if wedgeStyle.label_visible: + if not sideLabels: + if text: + labelRadius = wedgeStyle.labelRadius + rx = xradius*labelRadius + ry = yradius*labelRadius + labelX = cx + rx*cosAA + labelY = cy + ry*sinAA + l = _addWedgeLabel(self,text,averageAngle,labelX,labelY,wedgeStyle) + L_add(l) + if not plMode and l._simple_pointer: + l._aax = cx+xradius*cosAA + l._aay = cy+yradius*sinAA + if checkLabelOverlap: + l._origdata = { 'x': labelX, 'y':labelY, 'angle': averageAngle, + 'rx': rx, 'ry':ry, 'cx':cx, 'cy':cy, + 'bounds': l.getBounds(), 'angles':(a1,a2), + } + elif plMode and PL_data: + l = PL_data[i] + if l: + data = l._origdata + sinM = data['smid'] + cosM = data['cmid'] + lX = cx + xradius*cosM + lY = cy + yradius*sinM + lpel = wedgeStyle.label_pointer_elbowLength + lXi = lX + lpel*cosM + lYi = lY + lpel*sinM + L_add(PolyLine((lX,lY,lXi,lYi,l.x,l.y), + strokeWidth=wedgeStyle.label_pointer_strokeWidth, + strokeColor=wedgeStyle.label_pointer_strokeColor)) + L_add(l) + else: + if text: + slices_popout = self.slices.popout + m=0 + for n, angle in angles: + if self.slices[n].fillColor: + m += 1 + else: + r = n%m + self.slices[n].fillColor = self.slices[r].fillColor + self.slices[n].popout = self.slices[r].popout + for j in range(0,m-1): + if self.slices[j].popout > slices_popout: + slices_popout = self.slices[j].popout + labelRadius = wedgeStyle.labelRadius + ry = yradius*labelRadius + if (abs(averageAngle) < 90 ) or (averageAngle >270 and averageAngle <450) or (-450< + averageAngle <-270): + labelX = (1+self.sideLabelsOffset)*self.width + self.x + slices_popout + rx = 0 + else: + labelX = self.x - (self.sideLabelsOffset)*self.width - slices_popout + rx = 0 + labelY = cy + ry*sinAA + l = _addWedgeLabel(self,text,averageAngle,labelX,labelY,wedgeStyle) + L_add(l) + if not plMode: + l._aax = cx+xradius*cosAA + l._aay = cy+yradius*sinAA + if checkLabelOverlap: + l._origdata = { 'x': labelX, 'y':labelY, 'angle': averageAngle, + 'rx': rx, 'ry':ry, 'cx':cx, 'cy':cy, + 'bounds': l.getBounds(), + } + x1,y1,x2,y2 = l.getBounds() + + if checkLabelOverlap and L: + fixLabelOverlaps(L, sideLabels, mult0=checkLabelOverlap) + for l in L: g_add(l) + + if not plMode: + for l in L: + if l._simple_pointer and not sideLabels: + g_add(Line(l.x,l.y,l._aax,l._aay, + strokeWidth=wedgeStyle.label_pointer_strokeWidth, + strokeColor=wedgeStyle.label_pointer_strokeColor)) + elif sideLabels: + x1,y1,x2,y2 = l.getBounds() + #add pointers + if l.x == (1+self.sideLabelsOffset)*self.width + self.x: + g_add(Line(l._aax,l._aay,0.5*(l._aax+l.x),l.y+(0.25*(y2-y1)), + strokeWidth=wedgeStyle.label_pointer_strokeWidth, + strokeColor=wedgeStyle.label_pointer_strokeColor)) + g_add(Line(0.5*(l._aax+l.x),l.y+(0.25*(y2-y1)),l.x,l.y+(0.25*(y2-y1)), + strokeWidth=wedgeStyle.label_pointer_strokeWidth, + strokeColor=wedgeStyle.label_pointer_strokeColor)) + else: + g_add(Line(l._aax,l._aay,0.5*(l._aax+l.x),l.y+(0.25*(y2-y1)), + strokeWidth=wedgeStyle.label_pointer_strokeWidth, + strokeColor=wedgeStyle.label_pointer_strokeColor)) + g_add(Line(0.5*(l._aax+l.x),l.y+(0.25*(y2-y1)),l.x,l.y+(0.25*(y2-y1)), + strokeWidth=wedgeStyle.label_pointer_strokeWidth, + strokeColor=wedgeStyle.label_pointer_strokeColor)) + + return g + + def draw(self): + G = self.makeBackground() + w = self.makeWedges() + if G: return Group(G,w) + return w + +class LegendedPie(Pie): + """Pie with a two part legend (one editable with swatches, one hidden without swatches).""" + + _attrMap = AttrMap(BASE=Pie, + drawLegend = AttrMapValue(isBoolean, desc="If true then create and draw legend"), + legend1 = AttrMapValue(None, desc="Handle to legend for pie"), + legendNumberFormat = AttrMapValue(None, desc="Formatting routine for number on right hand side of legend."), + legendNumberOffset = AttrMapValue(isNumber, desc="Horizontal space between legend and numbers on r/hand side"), + pieAndLegend_colors = AttrMapValue(isListOfColors, desc="Colours used for both swatches and pie"), + legend_names = AttrMapValue(isNoneOrListOfNoneOrStrings, desc="Names used in legend (or None)"), + legend_data = AttrMapValue(isNoneOrListOfNoneOrNumbers, desc="Numbers used on r/hand side of legend (or None)"), + leftPadding = AttrMapValue(isNumber, desc='Padding on left of drawing'), + rightPadding = AttrMapValue(isNumber, desc='Padding on right of drawing'), + topPadding = AttrMapValue(isNumber, desc='Padding at top of drawing'), + bottomPadding = AttrMapValue(isNumber, desc='Padding at bottom of drawing'), + ) + + def __init__(self,**kwds): + setattr(self,'data',kwds.pop('data',[38.4, 20.7, 18.9, 15.4, 6.6])) + Pie.__init__(self,**kwds) + PCMYKColor, black = colors.PCMYKColor, colors.black + self.pieAndLegend_colors = [PCMYKColor(11,11,72,0,spotName='PANTONE 458 CV'), + PCMYKColor(100,65,0,30,spotName='PANTONE 288 CV'), + PCMYKColor(11,11,72,0,spotName='PANTONE 458 CV',density=75), + PCMYKColor(100,65,0,30,spotName='PANTONE 288 CV',density=75), + PCMYKColor(11,11,72,0,spotName='PANTONE 458 CV',density=50), + PCMYKColor(100,65,0,30,spotName='PANTONE 288 CV',density=50)] + + #Allows us up to six 'wedges' to be coloured + self.slices[0].fillColor=self.pieAndLegend_colors[0] + self.slices[1].fillColor=self.pieAndLegend_colors[1] + self.slices[2].fillColor=self.pieAndLegend_colors[2] + self.slices[3].fillColor=self.pieAndLegend_colors[3] + self.slices[4].fillColor=self.pieAndLegend_colors[4] + self.slices[5].fillColor=self.pieAndLegend_colors[5] + + self.slices.strokeWidth = 0.75 + self.slices.strokeColor = black + + legendOffset = 17 + self.legendNumberOffset = 51 + self.legendNumberFormat = '%.1f%%' + self.legend_data = self.data + + #set up the legends + from reportlab.graphics.charts.legends import Legend + self.legend1 = Legend() + self.legend1.x = self.width+legendOffset + self.legend1.y = self.height + self.legend1.deltax = 5.67 + self.legend1.deltay = 14.17 + self.legend1.dxTextSpace = 11.39 + self.legend1.dx = 5.67 + self.legend1.dy = 5.67 + self.legend1.columnMaximum = 7 + self.legend1.alignment = 'right' + self.legend_names = ['AAA:','AA:','A:','BBB:','NR:'] + for f in range(len(self.data)): + self.legend1.colorNamePairs.append((self.pieAndLegend_colors[f], self.legend_names[f])) + self.legend1.fontName = "Helvetica-Bold" + self.legend1.fontSize = 6 + self.legend1.strokeColor = black + self.legend1.strokeWidth = 0.5 + + self._legend2 = Legend() + self._legend2.dxTextSpace = 0 + self._legend2.dx = 0 + self._legend2.alignment = 'right' + self._legend2.fontName = "Helvetica-Oblique" + self._legend2.fontSize = 6 + self._legend2.strokeColor = self.legend1.strokeColor + + self.leftPadding = 5 + self.rightPadding = 5 + self.topPadding = 5 + self.bottomPadding = 5 + self.drawLegend = 1 + + def draw(self): + if self.drawLegend: + self.legend1.colorNamePairs = [] + self._legend2.colorNamePairs = [] + for f in range(len(self.data)): + if self.legend_names == None: + self.slices[f].fillColor = self.pieAndLegend_colors[f] + self.legend1.colorNamePairs.append((self.pieAndLegend_colors[f], None)) + else: + try: + self.slices[f].fillColor = self.pieAndLegend_colors[f] + self.legend1.colorNamePairs.append((self.pieAndLegend_colors[f], self.legend_names[f])) + except IndexError: + self.slices[f].fillColor = self.pieAndLegend_colors[f%len(self.pieAndLegend_colors)] + self.legend1.colorNamePairs.append((self.pieAndLegend_colors[f%len(self.pieAndLegend_colors)], self.legend_names[f])) + if self.legend_data != None: + ldf = self.legend_data[f] + lNF = self.legendNumberFormat + if ldf is None or lNF is None: + pass + elif isinstance(lNF,str): + ldf = lNF % ldf + elif hasattr(lNF,'__call__'): + ldf = lNF(ldf) + else: + raise ValueError("Unknown formatter type %s, expected string or function" % ascii(self.legendNumberFormat)) + self._legend2.colorNamePairs.append((None,ldf)) + p = Pie.draw(self) + if self.drawLegend: + p.add(self.legend1) + #hide from user - keeps both sides lined up! + self._legend2.x = self.legend1.x+self.legendNumberOffset + self._legend2.y = self.legend1.y + self._legend2.deltax = self.legend1.deltax + self._legend2.deltay = self.legend1.deltay + self._legend2.dy = self.legend1.dy + self._legend2.columnMaximum = self.legend1.columnMaximum + p.add(self._legend2) + p.shift(self.leftPadding, self.bottomPadding) + return p + + def _getDrawingDimensions(self): + tx = self.rightPadding + if self.drawLegend: + tx += self.legend1.x+self.legendNumberOffset #self._legend2.x + tx += self._legend2._calculateMaxWidth(self._legend2.colorNamePairs) + ty = self.bottomPadding+self.height+self.topPadding + return (tx,ty) + + def demo(self, drawing=None): + if not drawing: + tx,ty = self._getDrawingDimensions() + drawing = Drawing(tx, ty) + drawing.add(self.draw()) + return drawing + +from reportlab.graphics.charts.utils3d import _getShaded, _2rad, _360, _180_pi +class Wedge3dProperties(PropHolder): + """This holds descriptive information about the wedges in a pie chart. + + It is not to be confused with the 'wedge itself'; this just holds + a recipe for how to format one, and does not allow you to hack the + angles. It can format a genuine Wedge object for you with its + format method. + """ + _attrMap = AttrMap( + fillColor = AttrMapValue(isColorOrNone,desc=''), + fillColorShaded = AttrMapValue(isColorOrNone,desc=''), + fontColor = AttrMapValue(isColorOrNone,desc=''), + fontName = AttrMapValue(isString,desc=''), + fontSize = AttrMapValue(isNumber,desc=''), + label_angle = AttrMapValue(isNumber,desc=''), + label_bottomPadding = AttrMapValue(isNumber,'padding at bottom of box'), + label_boxAnchor = AttrMapValue(isBoxAnchor,desc=''), + label_boxFillColor = AttrMapValue(isColorOrNone,desc=''), + label_boxStrokeColor = AttrMapValue(isColorOrNone,desc=''), + label_boxStrokeWidth = AttrMapValue(isNumber,desc=''), + label_dx = AttrMapValue(isNumber,desc=''), + label_dy = AttrMapValue(isNumber,desc=''), + label_height = AttrMapValue(isNumberOrNone,desc=''), + label_leading = AttrMapValue(isNumberOrNone,desc=''), + label_leftPadding = AttrMapValue(isNumber,'padding at left of box'), + label_maxWidth = AttrMapValue(isNumberOrNone,desc=''), + label_rightPadding = AttrMapValue(isNumber,'padding at right of box'), + label_simple_pointer = AttrMapValue(isBoolean,'set to True for simple pointers'), + label_strokeColor = AttrMapValue(isColorOrNone,desc=''), + label_strokeWidth = AttrMapValue(isNumber,desc=''), + label_text = AttrMapValue(isStringOrNone,desc=''), + label_textAnchor = AttrMapValue(isTextAnchor,desc=''), + label_topPadding = AttrMapValue(isNumber,'padding at top of box'), + label_visible = AttrMapValue(isBoolean,desc="True if the label is to be drawn"), + label_width = AttrMapValue(isNumberOrNone,desc=''), + labelRadius = AttrMapValue(isNumber,desc=''), + popout = AttrMapValue(isNumber,desc=''), + shading = AttrMapValue(isNumber,desc=''), + strokeColor = AttrMapValue(isColorOrNone,desc=''), + strokeColorShaded = AttrMapValue(isColorOrNone,desc=''), + strokeDashArray = AttrMapValue(isListOfNumbersOrNone,desc=''), + strokeWidth = AttrMapValue(isNumber,desc=''), + visible = AttrMapValue(isBoolean,'set to false to skip displaying'), + ) + + def __init__(self): + self.strokeWidth = 0 + self.shading = 0.3 + self.visible = 1 + self.strokeColorShaded = self.fillColorShaded = self.fillColor = None + self.strokeColor = STATE_DEFAULTS["strokeColor"] + self.strokeDashArray = STATE_DEFAULTS["strokeDashArray"] + self.popout = 0 + self.fontName = STATE_DEFAULTS["fontName"] + self.fontSize = STATE_DEFAULTS["fontSize"] + self.fontColor = STATE_DEFAULTS["fillColor"] + self.labelRadius = 1.2 + self.label_dx = self.label_dy = self.label_angle = 0 + self.label_text = None + self.label_topPadding = self.label_leftPadding = self.label_rightPadding = self.label_bottomPadding = 0 + self.label_boxAnchor = 'autox' + self.label_boxStrokeColor = None #boxStroke + self.label_boxStrokeWidth = 0.5 #boxStrokeWidth + self.label_boxFillColor = None + self.label_strokeColor = None + self.label_strokeWidth = 0.1 + self.label_leading = self.label_width = self.label_maxWidth = self.label_height = None + self.label_textAnchor = 'start' + self.label_visible = 1 + self.label_simple_pointer = 0 + +class _SL3D: + def __init__(self,lo,hi): + if lo<0: + lo += 360 + hi += 360 + self.lo = lo + self.hi = hi + self.mid = (lo+hi)*0.5 + self.not360 = abs(hi-lo) < _ANGLEHI + + def __str__(self): + return '_SL3D(%.2f,%.2f)' % (self.lo,self.hi) + +def _keyS3D(a,b): + return -cmp(a[0],b[0]) +_keyS3D = functools.cmp_to_key(_keyS3D) + +_270r = _2rad(270) +class Pie3d(Pie): + _attrMap = AttrMap(BASE=Pie, + perspective = AttrMapValue(isNumber, desc='A flattening parameter.'), + depth_3d = AttrMapValue(isNumber, desc='depth of the pie.'), + angle_3d = AttrMapValue(isNumber, desc='The view angle.'), + ) + perspective = 70 + depth_3d = 25 + angle_3d = 180 + + def _popout(self,i): + return self._sl3d[i].not360 and self.slices[i].popout or 0 + + def CX(self, i,d ): + return self._cx+(d and self._xdepth_3d or 0)+self._popout(i)*cos(_2rad(self._sl3d[i].mid)) + def CY(self,i,d): + return self._cy+(d and self._ydepth_3d or 0)+self._popout(i)*sin(_2rad(self._sl3d[i].mid)) + def OX(self,i,o,d): + return self.CX(i,d)+self._radiusx*cos(_2rad(o)) + def OY(self,i,o,d): + return self.CY(i,d)+self._radiusy*sin(_2rad(o)) + + def rad_dist(self,a): + _3dva = self._3dva + return min(abs(a-_3dva),abs(a-_3dva+360)) + + def __init__(self): + Pie.__init__(self) + self.slices = TypedPropertyCollection(Wedge3dProperties) + self.slices[0].fillColor = colors.darkcyan + self.slices[1].fillColor = colors.blueviolet + self.slices[2].fillColor = colors.blue + self.slices[3].fillColor = colors.cyan + self.slices[4].fillColor = colors.azure + self.slices[5].fillColor = colors.crimson + self.slices[6].fillColor = colors.darkviolet + self.xradius = self.yradius = None + self.width = 300 + self.height = 200 + self.data = [12.50,20.10,2.00,22.00,5.00,18.00,13.00] + + def _fillSide(self,L,i,angle,strokeColor,strokeWidth,fillColor): + rd = self.rad_dist(angle) + if rd0: angle0, angle1 = angle1, angle0 + _sl3d.append(_SL3D(angle0,angle1)) + + labels = _fixLabels(self.labels,n) + a0 = _3d_angle + a1 = _3d_angle+180 + T = [] + S = [] + L = [] + + class WedgeLabel3d(WedgeLabel): + _ydepth_3d = self._ydepth_3d + def _checkDXY(self,ba): + if ba[0]=='n': + if not hasattr(self,'_ody'): + self._ody = self.dy + self.dy = -self._ody + self._ydepth_3d + + checkLabelOverlap = self.checkLabelOverlap + + for i in range(n): + style = slices[i] + if not style.visible: continue + sl = _sl3d[i] + lo = angle0 = sl.lo + hi = angle1 = sl.hi + aa = abs(hi-lo) + if aa<_ANGLELO: continue + fillColor = _getShaded(style.fillColor,style.fillColorShaded,style.shading) + strokeColor = _getShaded(style.strokeColor,style.strokeColorShaded,style.shading) or fillColor + strokeWidth = style.strokeWidth + cx0 = CX(i,0) + cy0 = CY(i,0) + cx1 = CX(i,1) + cy1 = CY(i,1) + if depth_3d: + #background shaded pie bottom + g.add(Wedge(cx1,cy1,radiusx, lo, hi,yradius=radiusy, + strokeColor=strokeColor,strokeWidth=strokeWidth,fillColor=fillColor, + strokeLineJoin=1)) + #connect to top + if lo < a0 < hi: angle0 = a0 + if lo < a1 < hi: angle1 = a1 + p = ArcPath(strokeColor=strokeColor, fillColor=fillColor,strokeWidth=strokeWidth,strokeLineJoin=1) + p.addArc(cx1,cy1,radiusx,angle0,angle1,yradius=radiusy,moveTo=1) + p.lineTo(OX(i,angle1,0),OY(i,angle1,0)) + p.addArc(cx0,cy0,radiusx,angle0,angle1,yradius=radiusy,reverse=1) + p.closePath() + if angle0<=_3dva and angle1>=_3dva: + rd = 0 + else: + rd = min(rad_dist(angle0),rad_dist(angle1)) + S.append((rd,p)) + _fillSide(S,i,lo,strokeColor,strokeWidth,fillColor) + _fillSide(S,i,hi,strokeColor,strokeWidth,fillColor) + + #bright shaded top + fillColor = style.fillColor + strokeColor = style.strokeColor or fillColor + T.append(Wedge(cx0,cy0,radiusx,lo,hi,yradius=radiusy, + strokeColor=strokeColor,strokeWidth=strokeWidth,fillColor=fillColor,strokeLineJoin=1)) + if aa>=_ANGLEHI: + theWedge = Ellipse(cx0, cy0, radiusx, radiusy, + strokeColor=strokeColor,strokeWidth=strokeWidth,fillColor=fillColor,strokeLineJoin=1) + else: + theWedge = Wedge(cx0,cy0,radiusx,lo,hi,yradius=radiusy, + strokeColor=strokeColor,strokeWidth=strokeWidth,fillColor=fillColor,strokeLineJoin=1) + T.append(theWedge) + + text = labels[i] + if style.label_visible and text: + rat = style.labelRadius + self._radiusx *= rat + self._radiusy *= rat + mid = sl.mid + labelX = OX(i,mid,0) + labelY = OY(i,mid,0) + l=_addWedgeLabel(self,text,mid,labelX,labelY,style,labelClass=WedgeLabel3d) + L.append(l) + if checkLabelOverlap: + l._origdata = { 'x': labelX, 'y':labelY, 'angle': mid, + 'rx': self._radiusx, 'ry':self._radiusy, 'cx':CX(i,0), 'cy':CY(i,0), + 'bounds': l.getBounds(), + } + self._radiusx = radiusx + self._radiusy = radiusy + + S.sort(key=_keyS3D) + if checkLabelOverlap and L: + fixLabelOverlaps(L,self.sideLabels) + for x in ([s[1] for s in S]+T+L): + g.add(x) + return g + + def demo(self): + d = Drawing(200, 100) + + pc = Pie() + pc.x = 50 + pc.y = 10 + pc.width = 100 + pc.height = 80 + pc.data = [10,20,30,40,50,60] + pc.labels = ['a','b','c','d','e','f'] + + pc.slices.strokeWidth=0.5 + pc.slices[3].popout = 10 + pc.slices[3].strokeWidth = 2 + pc.slices[3].strokeDashArray = [2,2] + pc.slices[3].labelRadius = 1.75 + pc.slices[3].fontColor = colors.red + pc.slices[0].fillColor = colors.darkcyan + pc.slices[1].fillColor = colors.blueviolet + pc.slices[2].fillColor = colors.blue + pc.slices[3].fillColor = colors.cyan + pc.slices[4].fillColor = colors.aquamarine + pc.slices[5].fillColor = colors.cadetblue + pc.slices[6].fillColor = colors.lightcoral + self.slices[1].visible = 0 + self.slices[3].visible = 1 + self.slices[4].visible = 1 + self.slices[5].visible = 1 + self.slices[6].visible = 0 + + d.add(pc) + return d + + +def sample0a(): + "Make a degenerated pie chart with only one slice." + + d = Drawing(400, 200) + + pc = Pie() + pc.x = 150 + pc.y = 50 + pc.data = [10] + pc.labels = ['a'] + pc.slices.strokeWidth=1#0.5 + + d.add(pc) + + return d + + +def sample0b(): + "Make a degenerated pie chart with only one slice." + + d = Drawing(400, 200) + + pc = Pie() + pc.x = 150 + pc.y = 50 + pc.width = 120 + pc.height = 100 + pc.data = [10] + pc.labels = ['a'] + pc.slices.strokeWidth=1#0.5 + + d.add(pc) + + return d + + +def sample1(): + "Make a typical pie chart with with one slice treated in a special way." + + d = Drawing(400, 200) + + pc = Pie() + pc.x = 150 + pc.y = 50 + pc.data = [10, 20, 30, 40, 50, 60] + pc.labels = ['a', 'b', 'c', 'd', 'e', 'f'] + + pc.slices.strokeWidth=1#0.5 + pc.slices[3].popout = 20 + pc.slices[3].strokeWidth = 2 + pc.slices[3].strokeDashArray = [2,2] + pc.slices[3].labelRadius = 1.75 + pc.slices[3].fontColor = colors.red + + d.add(pc) + + return d + + +def sample2(): + "Make a pie chart with nine slices." + + d = Drawing(400, 200) + + pc = Pie() + pc.x = 125 + pc.y = 25 + pc.data = [0.31, 0.148, 0.108, + 0.076, 0.033, 0.03, + 0.019, 0.126, 0.15] + pc.labels = ['1', '2', '3', '4', '5', '6', '7', '8', 'X'] + + pc.width = 150 + pc.height = 150 + pc.slices.strokeWidth=1#0.5 + + pc.slices[0].fillColor = colors.steelblue + pc.slices[1].fillColor = colors.thistle + pc.slices[2].fillColor = colors.cornflower + pc.slices[3].fillColor = colors.lightsteelblue + pc.slices[4].fillColor = colors.aquamarine + pc.slices[5].fillColor = colors.cadetblue + pc.slices[6].fillColor = colors.lightcoral + pc.slices[7].fillColor = colors.tan + pc.slices[8].fillColor = colors.darkseagreen + + d.add(pc) + + return d + + +def sample3(): + "Make a pie chart with a very slim slice." + + d = Drawing(400, 200) + + pc = Pie() + pc.x = 125 + pc.y = 25 + + pc.data = [74, 1, 25] + + pc.width = 150 + pc.height = 150 + pc.slices.strokeWidth=1#0.5 + pc.slices[0].fillColor = colors.steelblue + pc.slices[1].fillColor = colors.thistle + pc.slices[2].fillColor = colors.cornflower + + d.add(pc) + + return d + + +def sample4(): + "Make a pie chart with several very slim slices." + + d = Drawing(400, 200) + + pc = Pie() + pc.x = 125 + pc.y = 25 + + pc.data = [74, 1, 1, 1, 1, 22] + + pc.width = 150 + pc.height = 150 + pc.slices.strokeWidth=1#0.5 + pc.slices[0].fillColor = colors.steelblue + pc.slices[1].fillColor = colors.thistle + pc.slices[2].fillColor = colors.cornflower + pc.slices[3].fillColor = colors.lightsteelblue + pc.slices[4].fillColor = colors.aquamarine + pc.slices[5].fillColor = colors.cadetblue + + d.add(pc) + + return d + +def sample5(): + "Make a pie with side labels." + + d = Drawing(400, 200) + + pc = Pie() + pc.x = 125 + pc.y = 25 + + pc.data = [7, 1, 1, 1, 1, 2] + pc.labels = ['example1', 'example2', 'example3', 'example4', 'example5', 'example6'] + pc.sideLabels = 1 + + pc.width = 150 + pc.height = 150 + pc.slices.strokeWidth=1#0.5 + pc.slices[0].fillColor = colors.steelblue + pc.slices[1].fillColor = colors.thistle + pc.slices[2].fillColor = colors.cornflower + pc.slices[3].fillColor = colors.lightsteelblue + pc.slices[4].fillColor = colors.aquamarine + pc.slices[5].fillColor = colors.cadetblue + + d.add(pc) + + return d + +def sample6(): + + "Illustrates the pie moving to leave space for the left labels" + + d = Drawing(400, 200) + + pc = Pie() + "The x value of the pie chart is 0" + pc.x = 0 + pc.y = 25 + + pc.data = [74, 1, 1, 1, 1, 22] + pc.labels = ['example1', 'example2', 'example3', 'example4', 'example5', 'example6'] + pc.sideLabels = 1 + + pc.width = 150 + pc.height = 150 + pc.slices.strokeWidth=1#0.5 + pc.slices[0].fillColor = colors.steelblue + pc.slices[1].fillColor = colors.thistle + pc.slices[2].fillColor = colors.cornflower + pc.slices[3].fillColor = colors.lightsteelblue + pc.slices[4].fillColor = colors.aquamarine + pc.slices[5].fillColor = colors.cadetblue + + l = Line(0,0,0,200) + + d.add(pc) + d.add(l) + + return d + +def sample7(): + + "Case with overlapping pointers" + + d = Drawing(400, 200) + + pc = Pie() + pc.y = 50 + pc.x = 150 + pc.width = 100 + pc.height = 100 + + pc.data = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + pc.labels = ['example1', 'example2', 'example3', 'example4', 'example5', 'example6', 'example7', + 'example8', 'example9', 'example10', 'example11', 'example12', 'example13', 'example14', + 'example15', 'example16', 'example17', 'example18', 'example19', 'example20', 'example21', + 'example22', 'example23', 'example24', 'example25', 'example26', 'example27', 'example28'] + pc.sideLabels = 1 + pc.checkLabelOverlap = 1 + pc.simpleLabels = 0 + + + pc.slices.strokeWidth=1#0.5 + pc.slices[0].fillColor = colors.steelblue + pc.slices[1].fillColor = colors.thistle + pc.slices[2].fillColor = colors.cornflower + pc.slices[3].fillColor = colors.lightsteelblue + pc.slices[4].fillColor = colors.aquamarine + pc.slices[5].fillColor = colors.cadetblue + + d.add(pc) + + return d + +def sample8(): + + "Case with overlapping labels" + "Labels overlap if they do not belong to adjacent pie slices due to nature of checkLabelOverlap" + + d = Drawing(400, 200) + + pc = Pie() + pc.y = 50 + pc.x = 150 + pc.width = 100 + pc.height = 100 + + pc.data = [1, 1, 1, 1, 1, 30, 50, 1, 1, 1, 1, 1, 1, 40,20,10] + pc.labels = ['example1', 'example2', 'example3', 'example4', 'example5', 'example6', 'example7', + 'example8', 'example9', 'example10', 'example11', 'example12', 'example13', 'example14', + 'example15', 'example16'] + pc.sideLabels = 1 + pc.checkLabelOverlap = 1 + + pc.slices.strokeWidth=1#0.5 + pc.slices[0].fillColor = colors.steelblue + pc.slices[1].fillColor = colors.thistle + pc.slices[2].fillColor = colors.cornflower + pc.slices[3].fillColor = colors.lightsteelblue + pc.slices[4].fillColor = colors.aquamarine + pc.slices[5].fillColor = colors.cadetblue + + d.add(pc) + + return d + +def sample9(): + + "Case with overlapping labels" + "Labels overlap if they do not belong to adjacent pies due to nature of checkLabelOverlap" + + d = Drawing(400, 200) + + pc = Pie() + pc.x = 125 + pc.y = 50 + + pc.data = [41, 20, 40, 15, 20, 30, 50, 15, 25, 35, 25, 20, 30, 40, 20, 30] + pc.labels = ['example1', 'example2', 'example3', 'example4', 'example5', 'example6', 'example7', + 'example8', 'example9', 'example10', 'example11', 'example12', 'example13', 'example14', + 'example15', 'example16'] + pc.sideLabels = 1 + pc.checkLabelOverlap = 1 + + pc.width = 100 + pc.height = 100 + pc.slices.strokeWidth=1#0.5 + pc.slices[0].fillColor = colors.steelblue + pc.slices[1].fillColor = colors.thistle + pc.slices[2].fillColor = colors.cornflower + pc.slices[3].fillColor = colors.lightsteelblue + pc.slices[4].fillColor = colors.aquamarine + pc.slices[5].fillColor = colors.cadetblue + + d.add(pc) + + return d + +if __name__=='__main__': + """Normally nobody will execute this + + It's helpful for reportlab developers to put a 'main' block in to execute + the most recently edited feature. + """ + import sys + from reportlab.graphics import renderPDF + argv = sys.argv[1:] or ['7'] + for a in argv: + name = a if a.startswith('sample') else 'sample%s' % a + drawing = globals()[name]() + renderPDF.drawToFile(drawing, '%s.pdf' % name) + + + diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/slidebox.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/slidebox.py new file mode 100644 index 0000000000000000000000000000000000000000..f48bba69143fbd398632b57bb0d9e328dcac0061 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/slidebox.py @@ -0,0 +1,185 @@ +from reportlab.lib import colors +from reportlab.lib.colors import black, white +from reportlab.graphics.shapes import Polygon, String, Drawing, Group, Rect +from reportlab.graphics.widgetbase import Widget +from reportlab.lib.attrmap import * +from reportlab.lib.validators import * +from reportlab.lib.units import cm +from reportlab.pdfbase.pdfmetrics import getFont +from reportlab.graphics.widgets.grids import ShadedRect + +class SlideBox(Widget): + """Returns a slidebox widget""" + _attrMap = AttrMap( + labelFontName = AttrMapValue(isString, desc="Name of font used for the labels"), + labelFontSize = AttrMapValue(isNumber, desc="Size of font used for the labels"), + labelStrokeColor = AttrMapValue(isColorOrNone, desc="Colour for for number outlines"), + labelFillColor = AttrMapValue(isColorOrNone, desc="Colour for number insides"), + startColor = AttrMapValue(isColor, desc='Color of first box'), + endColor = AttrMapValue(isColor, desc='Color of last box'), + numberOfBoxes = AttrMapValue(isInt, desc='How many boxes there are'), + trianglePosition = AttrMapValue(isInt, desc='Which box is highlighted by the triangles'), + triangleHeight = AttrMapValue(isNumber, desc="Height of indicator triangles"), + triangleWidth = AttrMapValue(isNumber, desc="Width of indicator triangles"), + triangleFillColor = AttrMapValue(isColor, desc="Colour of indicator triangles"), + triangleStrokeColor = AttrMapValue(isColorOrNone, desc="Colour of indicator triangle outline"), + triangleStrokeWidth = AttrMapValue(isNumber, desc="Colour of indicator triangle outline"), + boxHeight = AttrMapValue(isNumber, desc="Height of the boxes"), + boxWidth = AttrMapValue(isNumber, desc="Width of the boxes"), + boxSpacing = AttrMapValue(isNumber, desc="Space between the boxes"), + boxOutlineColor = AttrMapValue(isColorOrNone, desc="Colour used to outline the boxes (if any)"), + boxOutlineWidth = AttrMapValue(isNumberOrNone, desc="Width of the box outline (if any)"), + leftPadding = AttrMapValue(isNumber, desc='Padding on left of drawing'), + rightPadding = AttrMapValue(isNumber, desc='Padding on right of drawing'), + topPadding = AttrMapValue(isNumber, desc='Padding at top of drawing'), + bottomPadding = AttrMapValue(isNumber, desc='Padding at bottom of drawing'), + background = AttrMapValue(isColorOrNone, desc='Colour of the background to the drawing (if any)'), + sourceLabelText = AttrMapValue(isNoneOrString, desc="Text used for the 'source' label (can be empty)"), + sourceLabelOffset = AttrMapValue(isNumber, desc='Padding at bottom of drawing'), + sourceLabelFontName = AttrMapValue(isString, desc="Name of font used for the 'source' label"), + sourceLabelFontSize = AttrMapValue(isNumber, desc="Font size for the 'source' label"), + sourceLabelFillColor = AttrMapValue(isColorOrNone, desc="Colour ink for the 'source' label (bottom right)"), + ) + + def __init__(self): + self.labelFontName = "Helvetica-Bold" + self.labelFontSize = 10 + self.labelStrokeColor = black + self.labelFillColor = white + self.startColor = colors.Color(232/255.0,224/255.0,119/255.0) + self.endColor = colors.Color(25/255.0,77/255.0,135/255.0) + self.numberOfBoxes = 7 + self.trianglePosition = 7 + self.triangleHeight = 0.12*cm + self.triangleWidth = 0.38*cm + self.triangleFillColor = white + self.triangleStrokeColor = black + self.triangleStrokeWidth = 0.58 + self.boxHeight = 0.55*cm + self.boxWidth = 0.73*cm + self.boxSpacing = 0.075*cm + self.boxOutlineColor = black + self.boxOutlineWidth = 0.58 + self.leftPadding=5 + self.rightPadding=5 + self.topPadding=5 + self.bottomPadding=5 + self.background=None + self.sourceLabelText = "Source: ReportLab" + self.sourceLabelOffset = 0.2*cm + self.sourceLabelFontName = "Helvetica-Oblique" + self.sourceLabelFontSize = 6 + self.sourceLabelFillColor = black + + def _getDrawingDimensions(self): + tx=(self.numberOfBoxes*self.boxWidth) + if self.numberOfBoxes>1: tx=tx+((self.numberOfBoxes-1)*self.boxSpacing) + tx=tx+self.leftPadding+self.rightPadding + ty=self.boxHeight+self.triangleHeight + ty=ty+self.topPadding+self.bottomPadding+self.sourceLabelOffset+self.sourceLabelFontSize + return (tx,ty) + + def _getColors(self): + # for calculating intermediate colors... + numShades = self.numberOfBoxes+1 + fillColorStart = self.startColor + fillColorEnd = self.endColor + colorsList =[] + + for i in range(0,numShades): + colorsList.append(colors.linearlyInterpolatedColor(fillColorStart, fillColorEnd, 0, numShades-1, i)) + return colorsList + + def demo(self,drawing=None): + if not drawing: + tx,ty=self._getDrawingDimensions() + drawing = Drawing(tx,ty) + drawing.add(self.draw()) + return drawing + + def draw(self): + g = Group() + ys = self.bottomPadding+(self.triangleHeight/2)+self.sourceLabelOffset+self.sourceLabelFontSize + if self.background: + x,y = self._getDrawingDimensions() + g.add(Rect(-self.leftPadding,-ys,x,y, + strokeColor=None, + strokeWidth=0, + fillColor=self.background)) + + ascent=getFont(self.labelFontName).face.ascent/1000. + if ascent==0: ascent=0.718 # default (from helvetica) + ascent=ascent*self.labelFontSize # normalize + + colorsList = self._getColors() + + # Draw the boxes - now uses ShadedRect from grids + x=0 + for f in range (0,self.numberOfBoxes): + sr=ShadedRect() + sr.x=x + sr.y=0 + sr.width=self.boxWidth + sr.height=self.boxHeight + sr.orientation = 'vertical' + sr.numShades = 30 + sr.fillColorStart = colorsList[f] + sr.fillColorEnd = colorsList[f+1] + sr.strokeColor = None + sr.strokeWidth = 0 + + g.add(sr) + + g.add(Rect(x,0,self.boxWidth,self.boxHeight, + strokeColor=self.boxOutlineColor, + strokeWidth=self.boxOutlineWidth, + fillColor=None)) + + g.add(String(x+self.boxWidth/2.,(self.boxHeight-ascent)/2., + text = str(f+1), + fillColor = self.labelFillColor, + strokeColor=self.labelStrokeColor, + textAnchor = 'middle', + fontName = self.labelFontName, + fontSize = self.labelFontSize)) + x=x+self.boxWidth+self.boxSpacing + + #do triangles + xt = (self.trianglePosition*self.boxWidth) + if self.trianglePosition>1: + xt = xt+(self.trianglePosition-1)*self.boxSpacing + xt = xt-(self.boxWidth/2) + g.add(Polygon( + strokeColor = self.triangleStrokeColor, + strokeWidth = self.triangleStrokeWidth, + fillColor = self.triangleFillColor, + points=[xt,self.boxHeight-(self.triangleHeight/2), + xt-(self.triangleWidth/2),self.boxHeight+(self.triangleHeight/2), + xt+(self.triangleWidth/2),self.boxHeight+(self.triangleHeight/2), + xt,self.boxHeight-(self.triangleHeight/2)])) + g.add(Polygon( + strokeColor = self.triangleStrokeColor, + strokeWidth = self.triangleStrokeWidth, + fillColor = self.triangleFillColor, + points=[xt,0+(self.triangleHeight/2), + xt-(self.triangleWidth/2),0-(self.triangleHeight/2), + xt+(self.triangleWidth/2),0-(self.triangleHeight/2), + xt,0+(self.triangleHeight/2)])) + + #source label + if self.sourceLabelText != None: + g.add(String(x-self.boxSpacing,0-(self.triangleHeight/2)-self.sourceLabelOffset-(self.sourceLabelFontSize), + text = self.sourceLabelText, + fillColor = self.sourceLabelFillColor, + textAnchor = 'end', + fontName = self.sourceLabelFontName, + fontSize = self.sourceLabelFontSize)) + + g.shift(self.leftPadding, ys) + + return g + + +if __name__ == "__main__": + d = SlideBox() + d.demo().save(fnRoot="slidebox") diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/spider.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/spider.py new file mode 100644 index 0000000000000000000000000000000000000000..c309bd244fe6663925a2c7cef1030f416504d09f --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/spider.py @@ -0,0 +1,411 @@ + #Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/graphics/charts/spider.py +# spider chart, also known as radar chart + +__version__='3.3.0' +__doc__="""Spider Chart + +Normal use shows variation of 5-10 parameters against some 'norm' or target. +When there is more than one series, place the series with the largest +numbers first, as it will be overdrawn by each successive one. +""" + +from math import sin, cos, pi + +from reportlab.lib import colors +from reportlab.lib.validators import isNumber, isListOfNumbersOrNone,\ + isColorOrNone, isListOfStringsOrNone, OneOf,\ + isBoolean, isNumberOrNone,\ + isStringOrNone, isStringOrNone, EitherOr,\ + isCallable, NoneOr +from reportlab.lib.attrmap import * +from reportlab.graphics.shapes import Group, Drawing, Line, Rect, Polygon, PolyLine, \ + STATE_DEFAULTS +from reportlab.graphics.widgetbase import TypedPropertyCollection, PropHolder +from reportlab.graphics.charts.areas import PlotArea +from reportlab.graphics.charts.legends import _objStr +from reportlab.graphics.charts.piecharts import WedgeLabel +from reportlab.graphics.widgets.markers import makeMarker, uSymbol2Symbol, isSymbol + +class StrandProperty(PropHolder): + + _attrMap = AttrMap( + strokeWidth = AttrMapValue(isNumber,desc='width'), + fillColor = AttrMapValue(isColorOrNone,desc='filling color'), + strokeColor = AttrMapValue(isColorOrNone,desc='stroke color'), + strokeDashArray = AttrMapValue(isListOfNumbersOrNone,desc='dashing pattern, e.g. (3,2)'), + symbol = AttrMapValue(EitherOr((isStringOrNone,isSymbol)), desc='Widget placed at data points.',advancedUsage=1), + symbolSize= AttrMapValue(isNumber, desc='Symbol size.',advancedUsage=1), + name = AttrMapValue(isStringOrNone, desc='Name of the strand.'), + ) + + def __init__(self): + self.strokeWidth = 1 + self.fillColor = None + self.strokeColor = STATE_DEFAULTS["strokeColor"] + self.strokeDashArray = STATE_DEFAULTS["strokeDashArray"] + self.symbol = None + self.symbolSize = 5 + self.name = None + +class SpokeProperty(PropHolder): + _attrMap = AttrMap( + strokeWidth = AttrMapValue(isNumber,desc='width'), + fillColor = AttrMapValue(isColorOrNone,desc='filling color'), + strokeColor = AttrMapValue(isColorOrNone,desc='stroke color'), + strokeDashArray = AttrMapValue(isListOfNumbersOrNone,desc='dashing pattern, e.g. (2,1)'), + labelRadius = AttrMapValue(isNumber,desc='label radius',advancedUsage=1), + visible = AttrMapValue(isBoolean,desc="True if the spoke line is to be drawn"), + ) + + def __init__(self,**kw): + self.strokeWidth = 0.5 + self.fillColor = None + self.strokeColor = STATE_DEFAULTS["strokeColor"] + self.strokeDashArray = STATE_DEFAULTS["strokeDashArray"] + self.visible = 1 + self.labelRadius = 1.05 + +class SpokeLabel(WedgeLabel): + def __init__(self,**kw): + WedgeLabel.__init__(self,**kw) + if '_text' not in list(kw.keys()): self._text = '' + +class StrandLabel(SpokeLabel): + _attrMap = AttrMap(BASE=SpokeLabel, + format = AttrMapValue(EitherOr((isStringOrNone,isCallable)),desc="Format for the label"), + dR = AttrMapValue(isNumberOrNone,desc="radial shift for label"), + ) + def __init__(self,**kw): + self.format = '' + self.dR = 0 + SpokeLabel.__init__(self,**kw) + +def _setupLabel(labelClass, text, radius, cx, cy, angle, car, sar, sty): + L = labelClass() + L._text = text + L.x = cx + radius*car + L.y = cy + radius*sar + L._pmv = angle*180/pi + L.boxAnchor = sty.boxAnchor + L.dx = sty.dx + L.dy = sty.dy + L.angle = sty.angle + L.boxAnchor = sty.boxAnchor + L.boxStrokeColor = sty.boxStrokeColor + L.boxStrokeWidth = sty.boxStrokeWidth + L.boxFillColor = sty.boxFillColor + L.strokeColor = sty.strokeColor + L.strokeWidth = sty.strokeWidth + L.leading = sty.leading + L.width = sty.width + L.maxWidth = sty.maxWidth + L.height = sty.height + L.textAnchor = sty.textAnchor + L.visible = sty.visible + L.topPadding = sty.topPadding + L.leftPadding = sty.leftPadding + L.rightPadding = sty.rightPadding + L.bottomPadding = sty.bottomPadding + L.fontName = sty.fontName + L.fontSize = sty.fontSize + L.fillColor = sty.fillColor + return L + +class SpiderChart(PlotArea): + _attrMap = AttrMap(BASE=PlotArea, + data = AttrMapValue(None, desc='Data to be plotted, list of (lists of) numbers.'), + labels = AttrMapValue(isListOfStringsOrNone, desc="optional list of labels to use for each data point"), + startAngle = AttrMapValue(isNumber, desc="angle of first slice; like the compass, 0 is due North"), + direction = AttrMapValue( OneOf('clockwise', 'anticlockwise'), desc="'clockwise' or 'anticlockwise'"), + strands = AttrMapValue(None, desc="collection of strand descriptor objects"), + spokes = AttrMapValue(None, desc="collection of spoke descriptor objects"), + strandLabels = AttrMapValue(None, desc="collection of strand label descriptor objects"), + strandLabelClass=AttrMapValue(NoneOr(isCallable), desc="A class factory to use for the strand labels"), + spokeLabels = AttrMapValue(None, desc="collection of spoke label descriptor objects"), + spokeLabelClass=AttrMapValue(NoneOr(isCallable), desc="A class factory to use for the spoke labels"), + ) + + def makeSwatchSample(self, rowNo, x, y, width, height): + baseStyle = self.strands + styleIdx = rowNo % len(baseStyle) + style = baseStyle[styleIdx] + strokeColor = getattr(style, 'strokeColor', getattr(baseStyle,'strokeColor',None)) + fillColor = getattr(style, 'fillColor', getattr(baseStyle,'fillColor',None)) + strokeDashArray = getattr(style, 'strokeDashArray', getattr(baseStyle,'strokeDashArray',None)) + strokeWidth = getattr(style, 'strokeWidth', getattr(baseStyle, 'strokeWidth',0)) + symbol = getattr(style, 'symbol', getattr(baseStyle, 'symbol',None)) + ym = y+height/2.0 + if fillColor is None and strokeColor is not None and strokeWidth>0: + bg = Line(x,ym,x+width,ym,strokeWidth=strokeWidth,strokeColor=strokeColor, + strokeDashArray=strokeDashArray) + elif fillColor is not None: + bg = Rect(x,y,width,height,strokeWidth=strokeWidth,strokeColor=strokeColor, + strokeDashArray=strokeDashArray,fillColor=fillColor) + else: + bg = None + if symbol: + symbol = uSymbol2Symbol(symbol,x+width/2.,ym,color) + if bg: + g = Group() + g.add(bg) + g.add(symbol) + return g + return symbol or bg + + def getSeriesName(self,i,default=None): + '''return series name i or default''' + return _objStr(getattr(self.strands[i],'name',default)) + + def __init__(self): + PlotArea.__init__(self) + + self.data = [[10,12,14,16,14,12], [6,8,10,12,9,11]] + self.labels = None # or list of strings + self.labels = ['a','b','c','d','e','f'] + self.startAngle = 90 + self.direction = "clockwise" + + self.strands = TypedPropertyCollection(StrandProperty) + self.spokes = TypedPropertyCollection(SpokeProperty) + self.spokeLabels = TypedPropertyCollection(SpokeLabel) + self.spokeLabels._text = None + self.strandLabels = TypedPropertyCollection(StrandLabel) + self.x = 10 + self.y = 10 + self.width = 180 + self.height = 180 + + def demo(self): + d = Drawing(200, 200) + d.add(SpiderChart()) + return d + + def normalizeData(self, outer = 0.0): + """Turns data into normalized ones where each datum is < 1.0, + and 1.0 = maximum radius. Adds 10% at outside edge by default""" + data = self.data + assert min(list(map(min,data))) >=0, "Cannot do spider plots of negative numbers!" + norm = max(list(map(max,data))) + norm *= (1.0+outer) + if norm<1e-9: norm = 1.0 + self._norm = norm + return [[e/norm for e in row] for row in data] + + def _innerDrawLabel(self, sty, radius, cx, cy, angle, car, sar, labelClass=None): + "Draw a label for a given item in the list." + fmt = sty.format + value = radius*self._norm + if not fmt: + text = None + elif isinstance(fmt,str): + if fmt == 'values': + text = sty._text + else: + text = fmt % value + elif hasattr(fmt,'__call__'): + text = fmt(value) + else: + raise ValueError("Unknown formatter type %s, expected string or function" % fmt) + + if text: + dR = sty.dR + if dR: + radius += dR/self._radius + L = _setupLabel(labelClass, text, radius, cx, cy, angle, car, sar, sty) + if dR<0: L._anti = 1 + else: + L = None + return L + + def labelClass(self,kind): + klass = getattr(self,f'{kind}LabelClass',None) + if not klass: + klass = globals()[f'{kind.capitalize()}Label'] + return klass + + def draw(self): + # normalize slice data + g = self.makeBackground() or Group() + + xradius = self.width/2.0 + yradius = self.height/2.0 + self._radius = radius = min(xradius, yradius) + cx = self.x + xradius + cy = self.y + yradius + + data = self.normalizeData() + + self._seriesCount = len(data) + n = len(data[0]) + + #labels + if self.labels is None: + labels = [''] * n + else: + labels = self.labels + #there's no point in raising errors for less than enough errors if + #we silently create all for the extreme case of no labels. + i = n-len(labels) + if i>0: + labels = labels + ['']*i + + S = [] + STRANDS = [] + STRANDAREAS = [] + syms = [] + labs = [] + csa = [] + angle = self.startAngle*pi/180 + direction = self.direction == "clockwise" and -1 or 1 + angleBetween = direction*(2 * pi)/float(n) + spokes = self.spokes + spokeLabels = self.spokeLabels + for i in range(n): + car = cos(angle)*radius + sar = sin(angle)*radius + csa.append((car,sar,angle)) + si = self.spokes[i] + if si.visible: + spoke = Line(cx, cy, cx + car, cy + sar, strokeWidth = si.strokeWidth, strokeColor=si.strokeColor, strokeDashArray=si.strokeDashArray) + S.append(spoke) + sli = spokeLabels[i] + text = sli._text + if not text: text = labels[i] + if text: + S.append(_setupLabel(self.labelClass('spoke'), text, si.labelRadius, cx, cy, angle, car, sar, sli)) + angle += angleBetween + + # now plot the polygons + rowIdx = 0 + strands = self.strands + strandLabels = self.strandLabels + for row in data: + # series plot + rsty = strands[rowIdx] + points = [] + car, sar = csa[-1][:2] + r = row[-1] + points.append(cx+car*r) + points.append(cy+sar*r) + for i in range(n): + car, sar, angle = csa[i] + r = row[i] + points.append(cx+car*r) + points.append(cy+sar*r) + L = self._innerDrawLabel(strandLabels[(rowIdx,i)], r, cx, cy, angle, car, sar, labelClass=self.labelClass('strand')) + if L: labs.append(L) + sty = strands[(rowIdx,i)] + uSymbol = sty.symbol + + # put in a marker, if it needs one + if uSymbol: + s_x = cx+car*r + s_y = cy+sar*r + s_fillColor = sty.fillColor + s_strokeColor = sty.strokeColor + s_strokeWidth = sty.strokeWidth + s_angle = 0 + s_size = sty.symbolSize + if type(uSymbol) is type(''): + symbol = makeMarker(uSymbol, + size = s_size, + x = s_x, + y = s_y, + fillColor = s_fillColor, + strokeColor = s_strokeColor, + strokeWidth = s_strokeWidth, + angle = s_angle, + ) + else: + symbol = uSymbol2Symbol(uSymbol,s_x,s_y,s_fillColor) + for k,v in (('size', s_size), ('fillColor', s_fillColor), + ('x', s_x), ('y', s_y), + ('strokeColor',s_strokeColor), ('strokeWidth',s_strokeWidth), + ('angle',s_angle),): + if getattr(symbol,k,None) is None: + try: + setattr(symbol,k,v) + except: + pass + syms.append(symbol) + + # make up the 'strand' + if rsty.fillColor: + strand = Polygon(points) + strand.fillColor = rsty.fillColor + strand.strokeColor = None + strand.strokeWidth = 0 + STRANDAREAS.append(strand) + if rsty.strokeColor and rsty.strokeWidth: + strand = PolyLine(points) + strand.strokeColor = rsty.strokeColor + strand.strokeWidth = rsty.strokeWidth + strand.strokeDashArray = rsty.strokeDashArray + STRANDS.append(strand) + rowIdx += 1 + + for s in (STRANDAREAS+STRANDS+syms+S+labs): g.add(s) + return g + +def sample1(): + "Make a simple spider chart" + d = Drawing(400, 400) + sp = SpiderChart() + sp.x = 50 + sp.y = 50 + sp.width = 300 + sp.height = 300 + sp.data = [[10,12,14,16,14,12], [6,8,10,12,9,15],[7,8,17,4,12,8]] + sp.labels = ['a','b','c','d','e','f'] + sp.strands[0].strokeColor = colors.cornsilk + sp.strands[1].strokeColor = colors.cyan + sp.strands[2].strokeColor = colors.palegreen + sp.strands[0].fillColor = colors.cornsilk + sp.strands[1].fillColor = colors.cyan + sp.strands[2].fillColor = colors.palegreen + sp.spokes.strokeDashArray = (2,2) + d.add(sp) + return d + + +def sample2(): + "Make a spider chart with markers, but no fill" + d = Drawing(400, 400) + sp = SpiderChart() + sp.x = 50 + sp.y = 50 + sp.width = 300 + sp.height = 300 + sp.data = [[10,12,14,16,14,12], [6,8,10,12,9,15],[7,8,17,4,12,8]] + sp.labels = ['U','V','W','X','Y','Z'] + sp.strands.strokeWidth = 1 + sp.strands[0].fillColor = colors.pink + sp.strands[1].fillColor = colors.lightblue + sp.strands[2].fillColor = colors.palegreen + sp.strands[0].strokeColor = colors.red + sp.strands[1].strokeColor = colors.blue + sp.strands[2].strokeColor = colors.green + sp.strands.symbol = "FilledDiamond" + sp.strands[1].symbol = makeMarker("Circle") + sp.strands[1].symbol.strokeWidth = 0.5 + sp.strands[1].symbol.fillColor = colors.yellow + sp.strands.symbolSize = 6 + sp.strandLabels[0,3]._text = 'special' + sp.strandLabels[0,1]._text = 'one' + sp.strandLabels[0,0]._text = 'zero' + sp.strandLabels[1,0]._text = 'Earth' + sp.strandLabels[2,2]._text = 'Mars' + sp.strandLabels.format = 'values' + sp.strandLabels.dR = -5 + d.add(sp) + return d + + +if __name__=='__main__': + d = sample1() + from reportlab.graphics.renderPDF import drawToFile + drawToFile(d, 'spider.pdf') + d = sample2() + drawToFile(d, 'spider2.pdf') diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/textlabels.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/textlabels.py new file mode 100644 index 0000000000000000000000000000000000000000..538fc54de85cbe1c639203d1bf23393c344e6674 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/textlabels.py @@ -0,0 +1,581 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/graphics/charts/textlabels.py +__version__='3.3.0' + +from reportlab.lib import colors +from reportlab.lib.utils import simpleSplit +from reportlab.lib.geomutils import normalizeTRBL +from reportlab.lib.validators import isNumber, isNumberOrNone, OneOf, isColorOrNone, isString, \ + isTextAnchor, isBoxAnchor, isBoolean, NoneOr, isInstanceOf, isNoneOrString, isNoneOrCallable, \ + isSubclassOf, EitherOr, isListOfNumbers +from reportlab.lib.attrmap import * +from reportlab.pdfbase.pdfmetrics import stringWidth, getAscentDescent +from reportlab.graphics.shapes import Drawing, Group, Circle, Rect, String, STATE_DEFAULTS +from reportlab.graphics.widgetbase import Widget, PropHolder +from reportlab.graphics.shapes import DirectDraw +from reportlab.platypus import XPreformatted, Flowable +from reportlab.lib.styles import ParagraphStyle, PropertySet +from reportlab.lib.enums import TA_LEFT, TA_RIGHT, TA_CENTER +_ta2al = dict(start=TA_LEFT,end=TA_RIGHT,middle=TA_CENTER) +from ..utils import text2Path as _text2Path #here for continuity + +_A2BA= { + 'x': {0:'n', 45:'ne', 90:'e', 135:'se', 180:'s', 225:'sw', 270:'w', 315: 'nw', -45: 'nw'}, + 'y': {0:'e', 45:'se', 90:'s', 135:'sw', 180:'w', 225:'nw', 270:'n', 315: 'ne', -45: 'ne'}, + } + +try: + from rlextra.graphics.canvasadapter import DirectDrawFlowable +except ImportError: + DirectDrawFlowable = None + +_BA2TA={'w':'start','nw':'start','sw':'start','e':'end', 'ne': 'end', 'se':'end', 'n':'middle','s':'middle','c':'middle'} +class Label(Widget): + """A text label to attach to something else, such as a chart axis. + + This allows you to specify an offset, angle and many anchor + properties relative to the label's origin. It allows, for example, + angled multiline axis labels. + """ + # fairly straight port of Robin Becker's textbox.py to new widgets + # framework. + + _attrMap = AttrMap( + x = AttrMapValue(isNumber,desc=''), + y = AttrMapValue(isNumber,desc=''), + dx = AttrMapValue(isNumber,desc='delta x - offset'), + dy = AttrMapValue(isNumber,desc='delta y - offset'), + angle = AttrMapValue(isNumber,desc='angle of label: default (0), 90 is vertical, 180 is upside down, etc'), + boxAnchor = AttrMapValue(isBoxAnchor,desc='anchoring point of the label'), + boxStrokeColor = AttrMapValue(isColorOrNone,desc='border color of the box'), + boxStrokeWidth = AttrMapValue(isNumber,desc='border width'), + boxFillColor = AttrMapValue(isColorOrNone,desc='the filling color of the box'), + boxTarget = AttrMapValue(OneOf('normal','anti','lo','hi'),desc="one of ('normal','anti','lo','hi')"), + boxRx = AttrMapValue(isNumber,desc='box corner x radius'), + boxRy = AttrMapValue(isNumber,desc='box corner y radius'), + fillColor = AttrMapValue(isColorOrNone,desc='label text color'), + strokeColor = AttrMapValue(isColorOrNone,desc='label text border color'), + strokeWidth = AttrMapValue(isNumber,desc='label text border width'), + text = AttrMapValue(isString,desc='the actual text to display'), + fontName = AttrMapValue(isString,desc='the name of the font used'), + fontSize = AttrMapValue(isNumber,desc='the size of the font'), + leading = AttrMapValue(isNumberOrNone,desc=''), + width = AttrMapValue(isNumberOrNone,desc='the width of the label'), + maxWidth = AttrMapValue(isNumberOrNone,desc='maximum width the label can grow to'), + height = AttrMapValue(isNumberOrNone,desc='the height of the text'), + textAnchor = AttrMapValue(isTextAnchor,desc='the anchoring point of the text inside the label'), + visible = AttrMapValue(isBoolean,desc="True if the label is to be drawn"), + topPadding = AttrMapValue(isNumber,desc='padding at top of box'), + leftPadding = AttrMapValue(isNumber,desc='padding at left of box'), + rightPadding = AttrMapValue(isNumber,desc='padding at right of box'), + bottomPadding = AttrMapValue(isNumber,desc='padding at bottom of box'), + padding = AttrMapValue(EitherOr((isNumberOrNone,isListOfNumbers)),'TRBL css like padding'), + useAscentDescent = AttrMapValue(isBoolean,desc="If True then the font's Ascent & Descent will be used to compute default heights and baseline."), + customDrawChanger = AttrMapValue(isNoneOrCallable,desc="An instance of CustomDrawChanger to modify the behavior at draw time", _advancedUsage=1), + ddf = AttrMapValue(NoneOr(isSubclassOf(DirectDraw),'NoneOrDirectDraw'),desc="A DirectDrawFlowable instance", _advancedUsage=1), + ddfKlass = AttrMapValue(NoneOr(isSubclassOf(Flowable),'NoneOrDirectDraw'),desc="A Flowable class for direct drawing (default is XPreformatted", _advancedUsage=1), + ddfStyle = AttrMapValue(NoneOr((isSubclassOf(PropertySet),isInstanceOf(PropertySet))),desc="A style or style class for a ddfKlass or None", _advancedUsage=1), + ) + + def __init__(self,**kw): + self._setKeywords(**kw) + self._setKeywords( + _text = 'Multi-Line\nString', + boxAnchor = 'c', + angle = 0, + x = 0, + y = 0, + dx = 0, + dy = 0, + topPadding = 0, + leftPadding = 0, + rightPadding = 0, + bottomPadding = 0, + boxStrokeWidth = 0.5, + boxStrokeColor = None, + boxTarget = 'normal', + boxRx = 0, + boxRy = 0, + strokeColor = None, + boxFillColor = None, + leading = None, + width = None, + maxWidth = None, + height = None, + fillColor = STATE_DEFAULTS['fillColor'], + fontName = STATE_DEFAULTS['fontName'], + fontSize = STATE_DEFAULTS['fontSize'], + strokeWidth = 0.1, + textAnchor = 'start', + visible = 1, + useAscentDescent = False, + ddf = DirectDrawFlowable, + ddfKlass = getattr(self.__class__,'ddfKlass',None), + ddfStyle = getattr(self.__class__,'ddfStyle',None), + ) + + @property + def padding(self): + p = self.topPadding, self.rightPadding, self.bottomPadding, self.leftPadding + n = len(set(p)) + if n==1: return p[0] + elif n==2 and p[0]==p[2] and p[1]==p[3]: return p[:2] + elif n==3 and p[1]==p[3]: return p[:3] + return p + + @padding.setter + def padding(self,p): + self.topPadding, self.rightPadding, self.bottomPadding, self.leftPadding = normalizeTRBL(p) + + def setText(self, text): + """Set the text property. May contain embedded newline characters. + Called by the containing chart or axis.""" + self._text = text + + + def setOrigin(self, x, y): + """Set the origin. This would be the tick mark or bar top relative to + which it is defined. Called by the containing chart or axis.""" + self.x = x + self.y = y + + + def demo(self): + """This shows a label positioned with its top right corner + at the top centre of the drawing, and rotated 45 degrees.""" + + d = Drawing(200, 100) + + # mark the origin of the label + d.add(Circle(100,90, 5, fillColor=colors.green)) + + lab = Label() + lab.setOrigin(100,90) + lab.boxAnchor = 'ne' + lab.angle = 45 + lab.dx = 0 + lab.dy = -20 + lab.boxStrokeColor = colors.green + lab.setText('Another\nMulti-Line\nString') + d.add(lab) + + return d + + def _getBoxAnchor(self): + '''hook for allowing special box anchor effects''' + ba = self.boxAnchor + if ba in ('autox', 'autoy'): + angle = self.angle + na = (int((angle%360)/45.)*45)%360 + if not (na % 90): # we have a right angle case + da = (angle - na) % 360 + if abs(da)>5: + na = na + (da>0 and 45 or -45) + ba = _A2BA[ba[-1]][na] + return ba + + def _getBaseLineRatio(self): + if self.useAscentDescent: + self._ascent, self._descent = getAscentDescent(self.fontName,self.fontSize) + self._baselineRatio = self._ascent/(self._ascent-self._descent) + else: + self._baselineRatio = 1/1.2 + + def _computeSizeEnd(self,objH): + self._height = self.height or (objH + self.topPadding + self.bottomPadding) + self._ewidth = (self._width-self.leftPadding-self.rightPadding) + self._eheight = (self._height-self.topPadding-self.bottomPadding) + boxAnchor = self._getBoxAnchor() + if boxAnchor in ['n','ne','nw']: + self._top = -self.topPadding + elif boxAnchor in ['s','sw','se']: + self._top = self._height-self.topPadding + else: + self._top = 0.5*self._eheight + self._bottom = self._top - self._eheight + + if boxAnchor in ['ne','e','se']: + self._left = self.leftPadding - self._width + elif boxAnchor in ['nw','w','sw']: + self._left = self.leftPadding + else: + self._left = -self._ewidth*0.5 + self._right = self._left+self._ewidth + + def computeSize(self): + # the thing will draw in its own coordinate system + ddfKlass = getattr(self,'ddfKlass',None) + if not ddfKlass: + self._lineWidths = [] + self._lines = simpleSplit(self._text,self.fontName,self.fontSize,self.maxWidth) + if not self.width: + self._width = self.leftPadding+self.rightPadding + if self._lines: + self._lineWidths = [stringWidth(line,self.fontName,self.fontSize) for line in self._lines] + self._width += max(self._lineWidths) + else: + self._width = self.width + self._getBaseLineRatio() + if self.leading: + self._leading = self.leading + elif self.useAscentDescent: + self._leading = self._ascent - self._descent + else: + self._leading = self.fontSize*1.2 + objH = self._leading*len(self._lines) + else: + if self.ddf is None: + raise RuntimeError('DirectDrawFlowable class is not available you need the rlextra package as well as reportlab') + sty = dict( + name='xlabel-generated', + fontName=self.fontName, + fontSize=self.fontSize, + fillColor=self.fillColor, + strokeColor=self.strokeColor, + ) + + if not self.ddfStyle: + sty = ParagraphStyle(**sty) + elif isinstance(self.ddfStyle,PropertySet): + sty = self.ddfStyle.clone(**sty) + elif isinstance(self.ddfStyle,type) and issubclass(self.ddfStyle,PropertySet): + sty = self.ddfStyle(**sty) + else: + raise ValueError(f'ddfStyle has invalid type {type(self.ddfStyle)}') + + self._style = sty + self._getBaseLineRatio() + if self.useAscentDescent: + sty.autoLeading = True + sty.leading = self._ascent - self._descent + else: + sty.leading = self.leading if self.leading else self.fontSize*1.2 + self._leading = sty.leading + ta = self._getTextAnchor() + + aW = self.maxWidth or 0x7fffffff + if ta!='start': + sty.alignment = TA_LEFT + obj = ddfKlass(self._text,style=sty) + _, objH = obj.wrap(aW,0x7fffffff) + aW = self.maxWidth or obj._width_max + sty.alignment = _ta2al[ta] + self._ddfObj = obj = ddfKlass(self._text,style=sty) + _, objH = obj.wrap(aW,0x7fffffff) + + if not self.width: + self._width = self.leftPadding+self.rightPadding + self._width += obj._width_max + else: + self._width = self.width + self._computeSizeEnd(objH) + + def _getTextAnchor(self): + '''This can be overridden to allow special effects''' + ta = self.textAnchor + if ta=='boxauto': ta = _BA2TA[self._getBoxAnchor()] + return ta + + def _rawDraw(self): + _text = self._text + self._text = _text or '' + self.computeSize() + self._text = _text + g = Group() + g.translate(self.x + self.dx, self.y + self.dy) + g.rotate(self.angle) + + ddfKlass = getattr(self,'ddfKlass',None) + if ddfKlass: + x = self._left + else: + y = self._top - self._leading*self._baselineRatio + textAnchor = self._getTextAnchor() + if textAnchor == 'start': + x = self._left + elif textAnchor == 'middle': + x = self._left + self._ewidth*0.5 + else: + x = self._right + + # paint box behind text just in case they + # fill it + if self.boxFillColor or (self.boxStrokeColor and self.boxStrokeWidth): + g.add(Rect( self._left-self.leftPadding, + self._bottom-self.bottomPadding, + self._width, + self._height, + strokeColor=self.boxStrokeColor, + strokeWidth=self.boxStrokeWidth, + fillColor=self.boxFillColor, + rx=self.boxRx, + ry=self.boxRy, + )) + + if ddfKlass: + g1 = Group() + g1.translate(x,self._top-self._eheight) + g1.add(self.ddf(self._ddfObj)) + g.add(g1) + else: + fillColor, fontName, fontSize = self.fillColor, self.fontName, self.fontSize + strokeColor, strokeWidth, leading = self.strokeColor, self.strokeWidth, self._leading + svgAttrs=getattr(self,'_svgAttrs',{}) + if strokeColor: + for line in self._lines: + s = _text2Path(line, x, y, fontName, fontSize, textAnchor) + s.fillColor = fillColor + s.strokeColor = strokeColor + s.strokeWidth = strokeWidth + g.add(s) + y -= leading + else: + for line in self._lines: + s = String(x, y, line, _svgAttrs=svgAttrs) + s.textAnchor = textAnchor + s.fontName = fontName + s.fontSize = fontSize + s.fillColor = fillColor + g.add(s) + y -= leading + + return g + + def draw(self): + customDrawChanger = getattr(self,'customDrawChanger',None) + if customDrawChanger: + customDrawChanger(True,self) + try: + return self._rawDraw() + finally: + customDrawChanger(False,self) + else: + return self._rawDraw() + +class LabelDecorator: + _attrMap = AttrMap( + x = AttrMapValue(isNumberOrNone,desc=''), + y = AttrMapValue(isNumberOrNone,desc=''), + dx = AttrMapValue(isNumberOrNone,desc=''), + dy = AttrMapValue(isNumberOrNone,desc=''), + angle = AttrMapValue(isNumberOrNone,desc=''), + boxAnchor = AttrMapValue(isBoxAnchor,desc=''), + boxStrokeColor = AttrMapValue(isColorOrNone,desc=''), + boxStrokeWidth = AttrMapValue(isNumberOrNone,desc=''), + boxFillColor = AttrMapValue(isColorOrNone,desc=''), + fillColor = AttrMapValue(isColorOrNone,desc=''), + strokeColor = AttrMapValue(isColorOrNone,desc=''), + strokeWidth = AttrMapValue(isNumberOrNone),desc='', + fontName = AttrMapValue(isNoneOrString,desc=''), + fontSize = AttrMapValue(isNumberOrNone,desc=''), + leading = AttrMapValue(isNumberOrNone,desc=''), + width = AttrMapValue(isNumberOrNone,desc=''), + maxWidth = AttrMapValue(isNumberOrNone,desc=''), + height = AttrMapValue(isNumberOrNone,desc=''), + textAnchor = AttrMapValue(isTextAnchor,desc=''), + visible = AttrMapValue(isBoolean,desc="True if the label is to be drawn"), + ) + + def __init__(self): + self.textAnchor = 'start' + self.boxAnchor = 'w' + for a in self._attrMap.keys(): + if not hasattr(self,a): setattr(self,a,None) + + def decorate(self,l,L): + chart,g,rowNo,colNo,x,y,width,height,x00,y00,x0,y0 = l._callOutInfo + L.setText(chart.categoryAxis.categoryNames[colNo]) + g.add(L) + + def __call__(self,l): + L = Label() + for a,v in self.__dict__.items(): + if v is None: v = getattr(l,a,None) + setattr(L,a,v) + self.decorate(l,L) + +isOffsetMode=OneOf('high','low','bar','axis') +class LabelOffset(PropHolder): + _attrMap = AttrMap( + posMode = AttrMapValue(isOffsetMode,desc="Where to base +ve offset"), + pos = AttrMapValue(isNumber,desc='Value for positive elements'), + negMode = AttrMapValue(isOffsetMode,desc="Where to base -ve offset"), + neg = AttrMapValue(isNumber,desc='Value for negative elements'), + ) + def __init__(self): + self.posMode=self.negMode='axis' + self.pos = self.neg = 0 + + def _getValue(self, chart, val): + flipXY = chart._flipXY + A = chart.categoryAxis + jA = A.joinAxis + if val>=0: + mode = self.posMode + delta = self.pos + else: + mode = self.negMode + delta = self.neg + if flipXY: + v = A._x + else: + v = A._y + if jA: + if flipXY: + _v = jA._x + else: + _v = jA._y + if mode=='high': + v = _v + jA._length + elif mode=='low': + v = _v + elif mode=='bar': + v = _v+val + return v+delta + +NoneOrInstanceOfLabelOffset=NoneOr(isInstanceOf(LabelOffset)) + +class PMVLabel(Label): + _attrMap = AttrMap( + BASE=Label, + ) + + def __init__(self, **kwds): + Label.__init__(self, **kwds) + self._pmv = 0 + + def _getBoxAnchor(self): + a = Label._getBoxAnchor(self) + if self._pmv<0: a = {'nw':'se','n':'s','ne':'sw','w':'e','c':'c','e':'w','sw':'ne','s':'n','se':'nw'}[a] + return a + + def _getTextAnchor(self): + a = Label._getTextAnchor(self) + if self._pmv<0: a = {'start':'end', 'middle':'middle', 'end':'start'}[a] + return a + +class BarChartLabel(PMVLabel): + """ + An extended Label allowing for nudging, lines visibility etc + """ + _attrMap = AttrMap( + BASE=PMVLabel, + lineStrokeWidth = AttrMapValue(isNumberOrNone, desc="Non-zero for a drawn line"), + lineStrokeColor = AttrMapValue(isColorOrNone, desc="Color for a drawn line"), + fixedEnd = AttrMapValue(NoneOrInstanceOfLabelOffset, desc="None or fixed draw ends +/-"), + fixedStart = AttrMapValue(NoneOrInstanceOfLabelOffset, desc="None or fixed draw starts +/-"), + nudge = AttrMapValue(isNumber, desc="Non-zero sign dependent nudge"), + boxTarget = AttrMapValue(OneOf('normal','anti','lo','hi','mid'),desc="one of ('normal','anti','lo','hi','mid')"), + ) + + def __init__(self, **kwds): + PMVLabel.__init__(self, **kwds) + self.lineStrokeWidth = 0 + self.lineStrokeColor = None + self.fixedStart = self.fixedEnd = None + self.nudge = 0 + +class NA_Label(BarChartLabel): + """ + An extended Label allowing for nudging, lines visibility etc + """ + _attrMap = AttrMap( + BASE=BarChartLabel, + text = AttrMapValue(isNoneOrString, desc="Text to be used for N/A values"), + ) + def __init__(self): + BarChartLabel.__init__(self) + self.text = 'n/a' +NoneOrInstanceOfNA_Label=NoneOr(isInstanceOf(NA_Label)) + +from reportlab.graphics.charts.utils import CustomDrawChanger +class RedNegativeChanger(CustomDrawChanger): + def __init__(self,fillColor=colors.red): + CustomDrawChanger.__init__(self) + self.fillColor = fillColor + def _changer(self,obj): + R = {} + if obj._text.startswith('-'): + R['fillColor'] = obj.fillColor + obj.fillColor = self.fillColor + return R + +class XLabel(Label): + '''like label but uses XPreFormatted/Paragraph to draw the _text''' + _attrMap = AttrMap(BASE=Label, + ) + def __init__(self,*args,**kwds): + Label.__init__(self,*args,**kwds) + self.ddfKlass = kwds.pop('ddfKlass',XPreformatted) + self.ddf = kwds.pop('directDrawClass',self.ddf) + + if False: + def __init__(self,*args,**kwds): + self._flowableClass = kwds.pop('flowableClass',XPreformatted) + ddf = kwds.pop('directDrawClass',DirectDrawFlowable) + if ddf is None: + raise RuntimeError('DirectDrawFlowable class is not available you need the rlextra package as well as reportlab') + self._ddf = ddf + Label.__init__(self,*args,**kwds) + def computeSize(self): + # the thing will draw in its own coordinate system + self._lineWidths = [] + sty = self._style = ParagraphStyle('xlabel-generated', + fontName=self.fontName, + fontSize=self.fontSize, + fillColor=self.fillColor, + strokeColor=self.strokeColor, + ) + self._getBaseLineRatio() + if self.useAscentDescent: + sty.autoLeading = True + sty.leading = self._ascent - self._descent + else: + sty.leading = self.leading if self.leading else self.fontSize*1.2 + self._leading = sty.leading + ta = self._getTextAnchor() + aW = self.maxWidth or 0x7fffffff + if ta!='start': + sty.alignment = TA_LEFT + obj = self._flowableClass(self._text,style=sty) + _, objH = obj.wrap(aW,0x7fffffff) + aW = self.maxWidth or obj._width_max + sty.alignment = _ta2al[ta] + self._obj = obj = self._flowableClass(self._text,style=sty) + _, objH = obj.wrap(aW,0x7fffffff) + + if not self.width: + self._width = self.leftPadding+self.rightPadding + self._width += self._obj._width_max + else: + self._width = self.width + self._computeSizeEnd(objH) + + def _rawDraw(self): + _text = self._text + self._text = _text or '' + self.computeSize() + self._text = _text + g = Group() + g.translate(self.x + self.dx, self.y + self.dy) + g.rotate(self.angle) + + x = self._left + + # paint box behind text just in case they + # fill it + if self.boxFillColor or (self.boxStrokeColor and self.boxStrokeWidth): + g.add(Rect( self._left-self.leftPadding, + self._bottom-self.bottomPadding, + self._width, + self._height, + strokeColor=self.boxStrokeColor, + strokeWidth=self.boxStrokeWidth, + fillColor=self.boxFillColor) + ) + g1 = Group() + g1.translate(x,self._top-self._eheight) + g1.add(self._ddf(self._obj)) + g.add(g1) + return g diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/utils.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4d306dc8d8ebadfe4299eea61e825948f3efbb0a --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/utils.py @@ -0,0 +1,483 @@ +#Copyright ReportLab Europe Ltd. 2000-2026 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/graphics/charts/utils.py +__all__ = ( + 'angle2corner', + 'angle2dir', + 'boxCornerCoords', + 'CustomDrawChanger', + 'DrawTimeCollector', + 'FillPairedData', + 'find_good_grid', + 'find_interval', + 'findNones', + 'lineSegmentIntersect', + 'makeCircularString', + 'maverage', + 'mkTimeTuple', + 'nextRoundNumber', + 'pairFixNones', + 'pairMaverage', + 'seconds2str', + 'str2seconds', + 'ticks', + 'xyDist', + ) + +__version__='3.4.8' +__doc__="Utilities used here and there." +from time import mktime, gmtime, strftime +from math import log10, pi, floor, sin, cos, hypot +import weakref +from reportlab.graphics.shapes import transformPoints, inverse, Ellipse, Group, String, numericXShift +from reportlab.lib.utils import flatten +from reportlab.pdfbase.pdfmetrics import stringWidth + +### Dinu's stuff used in some line plots (likely to vansih). +def mkTimeTuple(timeString): + "Convert a 'dd/mm/yyyy' formatted string to a tuple for use in the time module." + + L = [0] * 9 + dd, mm, yyyy = list(map(int, timeString.split('/'))) + L[:3] = [yyyy, mm, dd] + + return tuple(L) + +def str2seconds(timeString): + "Convert a number of seconds since the epoch into a date string." + + return mktime(mkTimeTuple(timeString)) + +def seconds2str(seconds): + "Convert a date string into the number of seconds since the epoch." + + return strftime('%Y-%m-%d', gmtime(seconds)) + +### Aaron's rounding function for making nice values on axes. +def nextRoundNumber(x): + """Return the first 'nice round number' greater than or equal to x + + Used in selecting apropriate tick mark intervals; we say we want + an interval which places ticks at least 10 points apart, work out + what that is in chart space, and ask for the nextRoundNumber(). + Tries the series 1,2,5,10,20,50,100.., going up or down as needed. + """ + + #guess to nearest order of magnitude + if x in (0, 1): + return x + + if x < 0: + return -1.0 * nextRoundNumber(-x) + else: + lg = int(log10(x)) + + if lg == 0: + if x < 1: + base = 0.1 + else: + base = 1.0 + elif lg < 0: + base = 10.0 ** (lg - 1) + else: + base = 10.0 ** lg # e.g. base(153) = 100 + # base will always be lower than x + + if base >= x: + return base * 1.0 + elif (base * 2) >= x: + return base * 2.0 + elif (base * 5) >= x: + return base * 5.0 + else: + return base * 10.0 + +_intervals=(.1, .2, .25, .5) +_j_max=len(_intervals)-1 +def find_interval(lo,hi,I=5): + 'determine tick parameters for range [lo, hi] using I intervals' + + if lo >= hi: + if lo==hi: + if lo==0: + lo = -.1 + hi = .1 + else: + lo = 0.9*lo + hi = 1.1*hi + else: + raise ValueError("lo>hi") + x=(hi - lo)/float(I) + b= (x>0 and (x<1 or x>10)) and 10**floor(log10(x)) or 1 + b = b + while 1: + a = x/b + if a<=_intervals[-1]: break + b = b*10 + + j = 0 + while a>_intervals[j]: j = j + 1 + + while 1: + ss = _intervals[j]*b + n = lo/ss + l = int(n)-(n<0) + n = ss*l + x = ss*(l+I) + a = I*ss + if n>0: + if a>=hi: + n = 0.0 + x = a + elif hi<0: + a = -a + if lo>a: + n = a + x = 0 + if hi<=x and n<=lo: break + j = j + 1 + if j>_j_max: + j = 0 + b = b*10 + return n, x, ss, lo - n + x - hi + +def find_good_grid(lower,upper,n=(4,5,6,7,8,9), grid=None): + if grid: + t = divmod(lower,grid)[0] * grid + hi, z = divmod(upper,grid) + if z>1e-8: hi = hi+1 + hi = hi*grid + else: + try: + n[0] + except TypeError: + n = range(max(1,n-2),max(n+3,2)) + + w = 1e308 + for i in n: + z=find_interval(lower,upper,i) + if z[3] 3 or power < -3: + format = '%+'+repr(w+7)+'.0e' + else: + if power >= 0: + digits = int(power)+w + format = '%' + repr(digits)+'.0f' + else: + digits = w-int(power) + format = '%'+repr(digits+2)+'.'+repr(digits)+'f' + + if percent: format=format+'%%' + T = [] + n = int(float(hi-t)/grid+0.1)+1 + if split: + labels = [] + for i in range(n): + v = t+grid*i + T.append(v) + labels.append(format % (v+labelVOffset)) + return T, labels + else: + for i in range(n): + v = t+grid*i + T.append((v, format % (v+labelVOffset))) + return T + +def findNones(data): + m = len(data) + if None in data: + b = 0 + while b>> [angle2dir(_) for _ in [0,360]+[__[0] for __ in _arange2dirs]+[__[1] for __ in _arange2dirs]] + ['e', 'e', 'e', 'e', 'ne', 'n', 'nw', 'w', 'sw', 's', 'se', 'e', 'ne', 'n', 'nw', 'w', 'sw', 's', 'se', 'e'] + ''' + a = angle % 360 + for lo, hi, d in _arange2dirs: + if lo>> [angle2corner(_) for _ in [0,360]+[__[0] for __ in _arange2dirs]+[__[1] for __ in _arange2dirs]] + ['w', 'w', 'w', 'w', 'sw', 's', 'se', 'e', 'ne', 'n', 'nw', 'w', 'sw', 's', 'se', 'e', 'ne', 'n', 'nw', 'w'] + ''' + return _cornerNames[angle2dir(angle)] + +def boxCornerCoords(bb, cn): + '''return (x,y) for bounding box and corner name + >>> bb=(1,0,0,1);[boxCornerCoords(bb,_) for _ in 'c n ne e se s sw w nw'.split()] + [(0.5, 0.5), (0.5, 1), (1, 1), (1, 0.5), (1, 0), (0.5, 0), (0, 0), (0, 0.5), (0, 1)] + >>> boxCornerCoords(bb,'z') + Traceback (most recent call last): + ... + ValueError: invalid box corner name 'z' + ''' + if bb[0]>bb[2] or bb[1]>bb[3]: + bb = (min(bb[0],bb[2]),min(bb[1],bb[3]),max(bb[0],bb[2]),max(bb[1],bb[3])) + if cn not in ('n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', 'c'): + raise ValueError(f'invalid box corner name {cn!r}') + if cn in ('c','s','n'): + x = (bb[0]+bb[2])/2 + elif cn in ('ne','e','se'): + x = bb[2] + else: + x = bb[0] + if cn in ('e','c','w'): + y = (bb[1]+bb[3])/2 + elif cn in ('nw','n','ne'): + y = bb[3] + else: + y = bb[1] + return x, y + +if __name__=='__main__': + import doctest + doctest.testmod() diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/utils3d.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/utils3d.py new file mode 100644 index 0000000000000000000000000000000000000000..93b9530b79ff135469c01a92f0032f0436fd09b9 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/charts/utils3d.py @@ -0,0 +1,230 @@ +from reportlab.graphics.shapes import Drawing, Polygon, Line + +def _getShaded(col,shd=None,shading=0.1): + if shd is None: + from reportlab.lib.colors import Blacker + if col: shd = Blacker(col,1-shading) + return shd + +def _getLit(col,shd=None,lighting=0.1): + if shd is None: + from reportlab.lib.colors import Whiter + if col: shd = Whiter(col,1-lighting) + return shd + + +def _draw_3d_bar(G, x1, x2, y0, yhigh, xdepth, ydepth, + fillColor=None, fillColorShaded=None, + strokeColor=None, strokeWidth=1, shading=0.1): + fillColorShaded = _getShaded(fillColor,None,shading) + fillColorShadedTop = _getShaded(fillColor,None,shading/2.0) + + def _add_3d_bar(x1, x2, y1, y2, xoff, yoff, + G=G,strokeColor=strokeColor, strokeWidth=strokeWidth, fillColor=fillColor): + G.add(Polygon((x1,y1, x1+xoff,y1+yoff, x2+xoff,y2+yoff, x2,y2), + strokeWidth=strokeWidth, strokeColor=strokeColor, fillColor=fillColor,strokeLineJoin=1)) + + usd = max(y0, yhigh) + if xdepth or ydepth: + if y0!=yhigh: #non-zero height + _add_3d_bar( x2, x2, y0, yhigh, xdepth, ydepth, fillColor=fillColorShaded) #side + + _add_3d_bar(x1, x2, usd, usd, xdepth, ydepth, fillColor=fillColorShadedTop) #top + + G.add(Polygon((x1,y0,x2,y0,x2,yhigh,x1,yhigh), + strokeColor=strokeColor, strokeWidth=strokeWidth, fillColor=fillColor,strokeLineJoin=1)) #front + + if xdepth or ydepth: + G.add(Line( x1, usd, x2, usd, strokeWidth=strokeWidth, strokeColor=strokeColor or fillColorShaded)) + +class _YStrip: + def __init__(self,y0,y1, slope, fillColor, fillColorShaded, shading=0.1): + self.y0 = y0 + self.y1 = y1 + self.slope = slope + self.fillColor = fillColor + self.fillColorShaded = _getShaded(fillColor,fillColorShaded,shading) + +def _ystrip_poly( x0, x1, y0, y1, xoff, yoff): + return [x0,y0,x0+xoff,y0+yoff,x1+xoff,y1+yoff,x1,y1] + + +def _make_3d_line_info( G, x0, x1, y0, y1, z0, z1, + theta_x, theta_y, + fillColor, fillColorShaded=None, tileWidth=1, + strokeColor=None, strokeWidth=None, strokeDashArray=None, + shading=0.1): + zwidth = abs(z1-z0) + xdepth = zwidth*theta_x + ydepth = zwidth*theta_y + depth_slope = xdepth==0 and 1e150 or -ydepth/float(xdepth) + + x = float(x1-x0) + slope = x==0 and 1e150 or (y1-y0)/x + + c = slope>depth_slope and _getShaded(fillColor,fillColorShaded,shading) or fillColor + zy0 = z0*theta_y + zx0 = z0*theta_x + + tileStrokeWidth = 0.6 + if tileWidth is None: + D = [(x1,y1)] + else: + T = ((y1-y0)**2+(x1-x0)**2)**0.5 + tileStrokeWidth *= tileWidth + if Tself.x1: return 1 + if o.s==self.s and o.i in (self.i-1,self.i+1): return + a = self.a + b = self.b + oa = o.a + ob = o.b + det = ob*a - oa*b + if -1e-81 or ou<0 or ou>1: return + x = x0 + u*a + y = self.y0 + u*b + if _ZERO=small: a(seg) + S.sort(key=_segKey) + I = [] + n = len(S) + for i in range(0,n-1): + s = S[i] + for j in range(i+1,n): + if s.intersect(S[j],I)==1: break + I.sort() + return I + +if __name__=='__main__': + from reportlab.graphics.shapes import Drawing + from reportlab.lib.colors import lightgrey, pink + D = Drawing(300,200) + _draw_3d_bar(D, 10, 20, 10, 50, 5, 5, fillColor=lightgrey, strokeColor=pink) + _draw_3d_bar(D, 30, 40, 10, 45, 5, 5, fillColor=lightgrey, strokeColor=pink) + + D.save(formats=['pdf'],outDir='.',fnRoot='_draw_3d_bar') + + print(find_intersections([[(0,0.5),(1,0.5),(0.5,0),(0.5,1)],[(.2666666667,0.4),(0.1,0.4),(0.1,0.2),(0,0),(1,1)],[(0,1),(0.4,0.1),(1,0.1)]])) + print(find_intersections([[(0.1, 0.2), (0.1, 0.4)], [(0, 1), (0.4, 0.1)]])) + print(find_intersections([[(0.2, 0.4), (0.1, 0.4)], [(0.1, 0.8), (0.4, 0.1)]])) + print(find_intersections([[(0,0),(1,1)],[(0.4,0.1),(1,0.1)]])) + print(find_intersections([[(0,0.5),(1,0.5),(0.5,0),(0.5,1)],[(0,0),(1,1)],[(0.1,0.8),(0.4,0.1),(1,0.1)]])) diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/renderPDF.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/renderPDF.py new file mode 100644 index 0000000000000000000000000000000000000000..6caa6ad6f757615e0c18c8cadcc4f3757c245677 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/renderPDF.py @@ -0,0 +1,400 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/graphics/renderPDF.py +# renderPDF - draws Drawings onto a canvas + +__version__='3.3.0' +__doc__="""Render Drawing objects within others PDFs or standalone + +Usage:: + + import renderpdf + renderpdf.draw(drawing, canvas, x, y) + +Execute the script to see some test drawings. +changed +""" + +from io import BytesIO + +from reportlab.graphics.shapes import * +from reportlab.pdfgen.canvas import Canvas +from reportlab.pdfbase.pdfmetrics import stringWidth +from reportlab import rl_config +from reportlab.graphics.renderbase import Renderer, getStateDelta, renderScaledDrawing, STATE_DEFAULTS + +# the main entry point for users... +def draw(drawing, canvas, x, y, showBoundary=rl_config._unset_): + """As it says""" + R = _PDFRenderer() + R.draw(renderScaledDrawing(drawing), canvas, x, y, showBoundary=showBoundary) + +class _PDFRenderer(Renderer): + """This draws onto a PDF document. It needs to be a class + rather than a function, as some PDF-specific state tracking is + needed outside of the state info in the SVG model.""" + + def __init__(self): + self._stroke = 0 + self._fill = 0 + + def drawNode(self, node): + """This is the recursive method called for each node + in the tree""" + #print "pdf:drawNode", self + #if node.__class__ is Wedge: stop + if not (isinstance(node, Path) and node.isClipPath): + self._canvas.saveState() + + #apply state changes + deltas = getStateDelta(node) + self._tracker.push(deltas) + self.applyStateChanges(deltas, {}) + + #draw the object, or recurse + self.drawNodeDispatcher(node) + + self._tracker.pop() + if not (isinstance(node, Path) and node.isClipPath): + self._canvas.restoreState() + + def drawRect(self, rect): + if rect.rx == rect.ry == 0: + #plain old rectangle + self._canvas.rect( + rect.x, rect.y, + rect.width, rect.height, + stroke=self._stroke, + fill=self._fill + ) + else: + #cheat and assume ry = rx; better to generalize + #pdfgen roundRect function. TODO + self._canvas.roundRect( + rect.x, rect.y, + rect.width, rect.height, rect.rx, + fill=self._fill, + stroke=self._stroke + ) + + def drawImage(self, image): + path = image.path + # currently not implemented in other renderers + if path and (hasattr(path,'mode') or os.path.exists(image.path)): + self._canvas.drawInlineImage( + path, + image.x, image.y, + image.width, image.height, + ) + + def drawLine(self, line): + if self._stroke: + self._canvas.line(line.x1, line.y1, line.x2, line.y2) + + def drawCircle(self, circle): + self._canvas.circle( + circle.cx, circle.cy, circle.r, + fill=self._fill, + stroke=self._stroke, + ) + + def drawPolyLine(self, polyline): + if self._stroke: + assert len(polyline.points) >= 2, 'Polyline must have 2 or more points' + head, tail = polyline.points[0:2], polyline.points[2:], + path = self._canvas.beginPath() + path.moveTo(head[0], head[1]) + for i in range(0, len(tail), 2): + path.lineTo(tail[i], tail[i+1]) + self._canvas.drawPath(path) + + def drawWedge(self, wedge): + if wedge.annular: + self.drawPath(wedge.asPolygon()) + else: + centerx, centery, radius, startangledegrees, endangledegrees = \ + wedge.centerx, wedge.centery, wedge.radius, wedge.startangledegrees, wedge.endangledegrees + yradius, radius1, yradius1 = wedge._xtraRadii() + if yradius is None: yradius = radius + angle = endangledegrees-startangledegrees + path = self._canvas.beginPath() + if (radius1==0 or radius1 is None) and (yradius1==0 or yradius1 is None): + path.moveTo(centerx, centery) + path.arcTo(centerx-radius, centery-yradius, centerx+radius, centery+yradius, + startangledegrees, angle) + else: + path.arc(centerx-radius, centery-yradius, centerx+radius, centery+yradius, + startangledegrees, angle) + path.arcTo(centerx-radius1, centery-yradius1, centerx+radius1, centery+yradius1, + endangledegrees, -angle) + path.close() + self._canvas.drawPath(path, + fill=self._fill, + stroke=self._stroke, + ) + + def drawEllipse(self, ellipse): + #need to convert to pdfgen's bounding box representation + x1 = ellipse.cx - ellipse.rx + x2 = ellipse.cx + ellipse.rx + y1 = ellipse.cy - ellipse.ry + y2 = ellipse.cy + ellipse.ry + self._canvas.ellipse(x1,y1,x2,y2,fill=self._fill,stroke=self._stroke) + + def drawPolygon(self, polygon): + assert len(polygon.points) >= 2, 'Polyline must have 2 or more points' + head, tail = polygon.points[0:2], polygon.points[2:], + path = self._canvas.beginPath() + path.moveTo(head[0], head[1]) + for i in range(0, len(tail), 2): + path.lineTo(tail[i], tail[i+1]) + path.close() + self._canvas.drawPath( + path, + stroke=self._stroke, + fill=self._fill, + ) + + def drawString(self, stringObj): + textRenderMode = getattr(stringObj,'textRenderMode',0) + needFill = textRenderMode in (0,2,4,6) + needStroke = textRenderMode in (1,2,5,6) + + if (self._fill and needFill) or (self._stroke and needStroke): + S = self._tracker.getState() + text_anchor, x, y, text, enc = S['textAnchor'], stringObj.x,stringObj.y,stringObj.text, stringObj.encoding + if not text_anchor in ['start','inherited']: + font, font_size = S['fontName'], S['fontSize'] + textLen = stringWidth(text, font, font_size, enc) + if text_anchor=='end': + x -= textLen + elif text_anchor=='middle': + x -= textLen*0.5 + elif text_anchor=='numeric': + x -= numericXShift(text_anchor,text,textLen,font,font_size,enc) + else: + raise ValueError('bad value for textAnchor '+str(text_anchor)) + self._canvas.drawString(x, y, text, mode=textRenderMode or None) + + def drawPath(self, path): + from reportlab.graphics.shapes import _renderPath + pdfPath = self._canvas.beginPath() + drawFuncs = (pdfPath.moveTo, pdfPath.lineTo, pdfPath.curveTo, pdfPath.close) + autoclose = getattr(path,'autoclose','') + fill = self._fill + stroke = self._stroke + isClosed = _renderPath(path, drawFuncs, forceClose=fill and autoclose=='pdf') + dP = self._canvas.drawPath + cP = self._canvas.clipPath if path.isClipPath else dP + fillMode = getattr(path,'fillMode',None) + if autoclose=='svg': + if fill and stroke and not isClosed: + cP(pdfPath, fill=fill, stroke=0) + dP(pdfPath, stroke=stroke, fill=0, fillMode=fillMode) + else: + cP(pdfPath, fill=fill, stroke=stroke, fillMode=fillMode) + elif autoclose=='pdf': + cP(pdfPath, fill=fill, stroke=stroke, fillMode=fillMode) + else: + #our old broken default + if not isClosed: + fill = 0 + cP(pdfPath, fill=fill, stroke=stroke, fillMode=fillMode) + + def setStrokeColor(self,c): + self._canvas.setStrokeColor(c) + + def setFillColor(self,c): + self._canvas.setFillColor(c) + + def applyStateChanges(self, delta, newState): + """This takes a set of states, and outputs the PDF operators + needed to set those properties""" + for key, value in (sorted(delta.items()) if rl_config.invariant else delta.items()): + if key == 'transform': + self._canvas.transform(value[0], value[1], value[2], + value[3], value[4], value[5]) + elif key == 'strokeColor': + #this has different semantics in PDF to SVG; + #we always have a color, and either do or do + #not apply it; in SVG one can have a 'None' color + if value is None: + self._stroke = 0 + else: + self._stroke = 1 + self.setStrokeColor(value) + elif key == 'strokeWidth': + self._canvas.setLineWidth(value) + elif key == 'strokeLineCap': #0,1,2 + self._canvas.setLineCap(value) + elif key == 'strokeLineJoin': + self._canvas.setLineJoin(value) +# elif key == 'stroke_dasharray': +# self._canvas.setDash(array=value) + elif key == 'strokeDashArray': + if value: + if isinstance(value,(list,tuple)) and len(value)==2 and isinstance(value[1],(tuple,list)): + phase = value[0] + value = value[1] + else: + phase = 0 + self._canvas.setDash(value,phase) + else: + self._canvas.setDash() + elif key == 'fillColor': + #this has different semantics in PDF to SVG; + #we always have a color, and either do or do + #not apply it; in SVG one can have a 'None' color + if value is None: + self._fill = 0 + else: + self._fill = 1 + self.setFillColor(value) + elif key in ['fontSize', 'fontName']: + # both need setting together in PDF + # one or both might be in the deltas, + # so need to get whichever is missing + fontname = delta.get('fontName', self._canvas._fontname) + fontsize = delta.get('fontSize', self._canvas._fontsize) + self._canvas.setFont(fontname, fontsize) + elif key=='fillOpacity': + if value is not None: + self._canvas.setFillAlpha(value) + elif key=='strokeOpacity': + if value is not None: + self._canvas.setStrokeAlpha(value) + elif key=='fillOverprint': + self._canvas.setFillOverprint(value) + elif key=='strokeOverprint': + self._canvas.setStrokeOverprint(value) + elif key=='overprintMask': + self._canvas.setOverprintMask(value) + elif key=='fillMode': + self._canvas._fillMode = value + +from reportlab.platypus import Flowable +class GraphicsFlowable(Flowable): + """Flowable wrapper around a Pingo drawing""" + def __init__(self, drawing): + self.drawing = drawing + self.width = self.drawing.width + self.height = self.drawing.height + + def draw(self): + draw(self.drawing, self.canv, 0, 0) + +def drawToFile(d, fn, msg="", showBoundary=rl_config._unset_, autoSize=1, **kwds): + """Makes a one-page PDF with just the drawing. + + If autoSize=1, the PDF will be the same size as + the drawing; if 0, it will place the drawing on + an A4 page with a title above it - possibly overflowing + if too big.""" + d = renderScaledDrawing(d) + for x in ('Name','Size'): + a = 'initialFont'+x + kwds[a] = getattr(d,a,kwds.pop(a,STATE_DEFAULTS['font'+x])) + metadataPath = kwds.pop('metadataPath',None) + c = Canvas(fn,**kwds) + if msg: + c.setFont(rl_config.defaultGraphicsFontName, 36) + c.drawString(80, 750, msg) + c.setTitle(msg) + + if autoSize: + c.setPageSize((d.width, d.height)) + draw(d, c, 0, 0, showBoundary=showBoundary) + else: + #show with a title + c.setFont(rl_config.defaultGraphicsFontName, 12) + y = 740 + i = 1 + y = y - d.height + draw(d, c, 80, y, showBoundary=showBoundary) + + if metadataPath: + from reportlab.pdfbase.pdfdoc import XMP + c._doc.Catalog.Metadata = XMP(path=metadataPath) + c.showPage() + c.save() + if sys.platform=='mac' and not hasattr(fn, "write"): + try: + import macfs, macostools + macfs.FSSpec(fn).SetCreatorType("CARO", "PDF ") + macostools.touched(fn) + except: + pass + +def drawToString(d, msg="", showBoundary=rl_config._unset_,autoSize=1,**kwds): + "Returns a PDF as a string in memory, without touching the disk" + s = BytesIO() + drawToFile(d, s, msg=msg, showBoundary=showBoundary,autoSize=autoSize, **kwds) + return s.getvalue() + +######################################################### +# +# test code. First, define a bunch of drawings. +# Routine to draw them comes at the end. +# +######################################################### +def test(outDir='pdfout',shout=False): + from reportlab.graphics.shapes import _baseGFontName, _baseGFontNameBI + from reportlab.rl_config import verbose + import os + if not os.path.isdir(outDir): + os.mkdir(outDir) + fn = os.path.join(outDir,'renderPDF.pdf') + c = Canvas(fn) + c.setFont(_baseGFontName, 36) + c.drawString(80, 750, 'Graphics Test') + + # print all drawings and their doc strings from the test + # file + + #grab all drawings from the test module + from reportlab.graphics import testshapes + drawings = [] + for funcname in dir(testshapes): + if funcname[0:10] == 'getDrawing': + func = getattr(testshapes,funcname) + drawing = func() #execute it + docstring = getattr(func,'__doc__','') + drawings.append((drawing, docstring)) + + #print in a loop, with their doc strings + c.setFont(_baseGFontName, 12) + y = 740 + i = 1 + for (drawing, docstring) in drawings: + assert (docstring is not None), "Drawing %d has no docstring!" % i + if y < 300: #allows 5-6 lines of text + c.showPage() + y = 740 + # draw a title + y = y - 30 + c.setFont(_baseGFontNameBI,12) + c.drawString(80, y, 'Drawing %d' % i) + c.setFont(_baseGFontName,12) + y = y - 14 + textObj = c.beginText(80, y) + textObj.textLines(docstring) + c.drawText(textObj) + y = textObj.getY() + y = y - drawing.height + draw(drawing, c, 80, y) + i = i + 1 + if y!=740: c.showPage() + + c.save() + if shout or verbose>2: + print('saved %s' % ascii(fn)) + +if __name__=='__main__': + test(shout=True) + import sys + if len(sys.argv)>1: + outdir = sys.argv[1] + else: + outdir = 'pdfout' + test(outdir,shout=True) + #testFlowable() diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/renderPM.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/renderPM.py new file mode 100644 index 0000000000000000000000000000000000000000..16b1b3e045c44aab06ed5c91cd515612dd0a84ed --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/renderPM.py @@ -0,0 +1,824 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history www.reportlab.co.uk/rl-cgi/viewcvs.cgi/rlextra/graphics/Csrc/renderPM/renderP.py +__version__='3.3.0' +__doc__="""Render drawing objects in common bitmap formats + +Usage:: + + from reportlab.graphics import renderPM + renderPM.drawToFile(drawing,filename,fmt='GIF',configPIL={....}) + +Other functions let you create a PM drawing as string or into a PM buffer. +Execute the script to see some test drawings.""" + +from reportlab.graphics.shapes import * +from reportlab.graphics.renderbase import getStateDelta, renderScaledDrawing +from reportlab.pdfbase.pdfmetrics import getFont, unicode2T1, stringWidth +from reportlab.pdfbase.ttfonts import ShapedStr, shapeFragWord +from reportlab.pdfgen.textobject import bidiShapedText +from reportlab.lib.utils import isUnicode, asUnicode +from reportlab.lib.abag import ABag +from reportlab.lib.colors import toColor, white +from reportlab import rl_config +from .utils import setFont as _setFont, RenderPMError + +import os, sys +from io import BytesIO, StringIO +from math import sin, cos, pi, ceil + +def _getPMBackend(backend=None): + if not backend: backend = rl_config.renderPMBackend + if 'cairo' in backend.lower(): + try: + import rlPyCairo as M + except ImportError as errMsg: + raise RenderPMError(f"""cannot import desired renderPM backend {backend} +Seek advice at the users list see +https://groups.google.com/g/reportlab-users""") + else: + raise RenderPMError(f'Invalid renderPM backend, {backend}') + return M + +try: + _pmBackend = _getPMBackend(rl_config.renderPMBackend) +except RenderPMError: + _pmBackend=None + +def _getImage(): + try: + from PIL import Image + except ImportError: + import Image + return Image + +def Color2Hex(c): + #assert isinstance(colorobj, colors.Color) #these checks don't work well RGB + if c: return ((0xFF&int(255*c.red)) << 16) | ((0xFF&int(255*c.green)) << 8) | (0xFF&int(255*c.blue)) + return c + +def CairoColor(c): + ''' + c should be None or something convertible to Color + rlPyCairo.GState can handle Color directly in either RGB24 or ARGB32 + ''' + return toColor(c) if c is not None else c + +# the main entry point for users... +def draw(drawing, canvas, x, y, showBoundary=rl_config._unset_,**kwds): + """As it says""" + R = _PMRenderer() + R.__dict__.update(kwds) + R.draw(renderScaledDrawing(drawing), canvas, x, y, showBoundary=showBoundary) + +from reportlab.graphics.renderbase import Renderer +class _PMRenderer(Renderer): + """This draws onto a pix map image. It needs to be a class + rather than a function, as some image-specific state tracking is + needed outside of the state info in the SVG model.""" + + def pop(self): + self._tracker.pop() + self.applyState() + + def push(self,node): + deltas = getStateDelta(node) + self._tracker.push(deltas) + self.applyState() + + def applyState(self): + s = self._tracker.getState() + self._canvas.ctm = s['ctm'] + self._canvas.strokeWidth = s['strokeWidth'] + alpha = s['strokeOpacity'] + if alpha is not None: + self._canvas.strokeOpacity = alpha + self._canvas.setStrokeColor(s['strokeColor']) + self._canvas.lineCap = s['strokeLineCap'] + self._canvas.lineJoin = s['strokeLineJoin'] + self._canvas.fillMode = s['fillMode'] + da = s['strokeDashArray'] + if not da: + da = None + else: + if not isinstance(da,(list,tuple)): + da = da, + if len(da)!=2 or not isinstance(da[1],(list,tuple)): + da = 0, da #assume phase of 0 + self._canvas.dashArray = da + alpha = s['fillOpacity'] + if alpha is not None: + self._canvas.fillOpacity = alpha + self._canvas.setFillColor(s['fillColor']) + self._canvas.setFont(s['fontName'], s['fontSize']) + + def initState(self,x,y): + deltas = self._tracker._combined[-1] + deltas['transform'] = deltas['ctm'] = self._canvas._baseCTM[0:4]+(x,y) + self._tracker.push(deltas) + self.applyState() + + def drawNode(self, node): + """This is the recursive method called for each node + in the tree""" + + #apply state changes + self.push(node) + + #draw the object, or recurse + self.drawNodeDispatcher(node) + + # restore the state + self.pop() + + def drawRect(self, rect): + c = self._canvas + if rect.rx == rect.ry == 0: + #plain old rectangle, draw clockwise (x-axis to y-axis) direction + c.rect(rect.x,rect.y, rect.width, rect.height) + else: + c.roundRect(rect.x,rect.y, rect.width, rect.height, rect.rx, rect.ry) + + def drawLine(self, line): + self._canvas.line(line.x1,line.y1,line.x2,line.y2) + + def drawImage(self, image): + path = image.path + if isinstance(path,str): + if not (path and os.path.isfile(path)): return + im = _getImage().open(path).convert('RGB') + elif hasattr(path,'convert'): + im = path.convert('RGB') + else: + return + srcW, srcH = im.size + dstW, dstH = image.width, image.height + if dstW is None: dstW = srcW + if dstH is None: dstH = srcH + self._canvas._aapixbuf( + image.x, image.y, dstW, dstH, + (im if self._canvas._backend=='rlPyCairo' #rlPyCairo has a from_pil method + else (im.tobytes if hasattr(im,'tobytes') else im.tostring)()), + srcW, srcH, 3, + ) + + def drawCircle(self, circle): + c = self._canvas + c.circle(circle.cx,circle.cy, circle.r) + c.fillstrokepath() + + def drawPolyLine(self, polyline, _doClose=0): + P = polyline.points + assert len(P) >= 2, 'Polyline must have 1 or more points' + c = self._canvas + c.pathBegin() + c.moveTo(P[0], P[1]) + for i in range(2, len(P), 2): + c.lineTo(P[i], P[i+1]) + if _doClose: + c.pathClose() + c.pathFill() + c.pathStroke() + + def drawEllipse(self, ellipse): + c=self._canvas + c.ellipse(ellipse.cx, ellipse.cy, ellipse.rx,ellipse.ry) + c.fillstrokepath() + + def drawPolygon(self, polygon): + self.drawPolyLine(polygon,_doClose=1) + + def drawString(self, stringObj): + canv = self._canvas + fill = canv.fillColor + textRenderMode = getattr(stringObj,'textRenderMode',0) + if fill is not None or textRenderMode: + S = self._tracker.getState() + text_anchor = S['textAnchor'] + fontName = S['fontName'] + fontSize = S['fontSize'] + text = stringObj.text + x = stringObj.x + y = stringObj.y + if not text_anchor in ['start','inherited']: + textLen = stringWidth(text, fontName,fontSize) + if text_anchor=='end': + x -= textLen + elif text_anchor=='middle': + x -= textLen/2 + elif text_anchor=='numeric': + x -= numericXShift(text_anchor,text,textLen,fontName,fontSize,stringObj.encoding) + else: + raise ValueError('bad value for textAnchor '+str(text_anchor)) + oldTextRenderMode = canv.textRenderMode + canv.textRenderMode = textRenderMode + try: + canv.drawString(x,y,text,_fontInfo=(fontName,fontSize)) + finally: + canv.textRenderMode = oldTextRenderMode + + def drawPath(self, path): + c = self._canvas + if path is EmptyClipPath: + del c._clipPaths[-1] + if c._clipPaths: + P = c._clipPaths[-1] + icp = P.isClipPath + P.isClipPath = 1 + self.drawPath(P) + P.isClipPath = icp + else: + c.clipPathClear() + return + from reportlab.graphics.shapes import _renderPath + drawFuncs = (c.moveTo, c.lineTo, c.curveTo, c.pathClose) + autoclose = getattr(path,'autoclose','') + def rP(forceClose=False): + c.pathBegin() + return _renderPath(path, drawFuncs, forceClose=forceClose) + if path.isClipPath: + rP() + c.clipPathSet() + c._clipPaths.append(path) + fill = c.fillColor is not None + stroke = c.strokeColor is not None + fillMode = getattr(path,'fillMode',-1) + if autoclose=='svg': + if fill and stroke: + rP(forceClose=True) + c.pathFill(fillMode) + rP() + c.pathStroke() + elif fill: + rP(forceClose=True) + c.pathFill(fillMode) + elif stroke: + rP() + c.pathStroke() + elif autoclose=='pdf': + rP(forceClose=True) + if fill: + c.pathFill(fillMode) + if stroke: + c.pathStroke() + else: + if rP(): + c.pathFill(fillMode) + c.pathStroke() + +def _convert2pilp(im): + Image = _getImage() + return im.convert("P", dither=Image.NONE, palette=Image.ADAPTIVE) + +def _convert2pilL(im): + return im.convert("L") + +def _convert2pil1(im): + return im.convert("1") + +def _saveAsPICT(im,fn,fmt,transparent=None): + im = _convert2pilp(im) + cols, rows = im.size + s = _pmBackend.pil2pict(cols,rows,(im.tobytes if hasattr(im,'tobytes') else im.tostring)(),im.im.getpalette()) + if not hasattr(fn,'write'): + with open(os.path.splitext(fn)[0]+'.'+fmt.lower(),'wb') as f: + f.write(s) + if os.name=='mac': + from reportlab.lib.utils import markfilename + markfilename(fn,ext='PICT') + else: + fn.write(s) + +_pycairoFmtsMap = dict(ARGB='ARGB32',RGBA='ARGB32',RGB='RGB24') +BEZIER_ARC_MAGIC = 0.5522847498 #constant for drawing circular arcs w/ Beziers +class PMCanvas: + def __init__(self,w,h,dpi=72,bg=0xffffff,configPIL=None,backend=None, + backendFmt='RGB'): + '''configPIL dict is passed to image save method''' + scale = dpi/72.0 + w = int(w*scale+0.5) + h = int(h*scale+0.5) + self.__dict__['_gs'] = self._getGState(w,h,bg,backend,fmt=backendFmt) + self.__dict__['_bg'] = bg + self.__dict__['_baseCTM'] = (scale,0,0,scale,0,0) + self.__dict__['_clipPaths'] = [] + self.__dict__['configPIL'] = configPIL + self.__dict__['_dpi'] = dpi + self.__dict__['_backend'] = 'rlPyCairo' + self.__dict__['_backendfmt'] = backendFmt + self.__dict__['_colorConverter'] = CairoColor if self._backend=='rlPyCairo' else Color2Hex + self.ctm = self._baseCTM + + @staticmethod + def _getGState(w, h, bg, backend=None, fmt='RGB24'): + mod = _getPMBackend(backend) + if backend is None: + backend = rl_config.renderPMBackend + if 'cairo' in backend.lower(): + fmt = fmt.upper() + fmt = _pycairoFmtsMap.get(fmt,fmt) + try: + return mod.GState(w,h,bg,fmt=fmt) + except AttributeError: + return mod.gstate(w,h,bg=bg) + raise RuntimeError(f'Cannot obtain PM graphics state using backend {backend!r}') + + def _drawTimeResize(self,w,h,bg=None): + if bg is None: bg = self._bg + self._drawing.width, self._drawing.height = w, h + A = {'ctm':None, 'strokeWidth':None, 'strokeColor':None, 'lineCap':None, 'lineJoin':None, 'dashArray':None, 'fillColor':None} + gs = self._gs + fN,fS = gs.fontName, gs.fontSize + for k in A.keys(): + A[k] = getattr(gs,k) + del gs, self._gs + gs = self.__dict__['_gs'] = _pmBackend.gstate(w,h,bg=bg) + for k in A.keys(): + setattr(self,k,A[k]) + gs.setFont(fN,fS) + + def toPIL(self): + im = _getImage().new('RGBA' if self._backend=='rlPyCairo' and getattr(self,'_fmt')=='ARGB32' else 'RGB', size=(self._gs.width, self._gs.height)) + im.frombytes(self._gs.pixBuf) + return im + + def saveToFile(self,fn,fmt=None): + im = self.toPIL() + if fmt is None: + if not isinstance(fn,str): + raise ValueError("Invalid value '%s' for fn when fmt is None" % ascii(fn)) + fmt = os.path.splitext(fn)[1] + if fmt.startswith('.'): fmt = fmt[1:] + configPIL = self.configPIL or {} + configPIL.setdefault('preConvertCB',None) + preConvertCB=configPIL.pop('preConvertCB') + if preConvertCB: + im = preConvertCB(im) + fmt = fmt.upper() + if fmt in ('GIF',): + im = _convert2pilp(im) + elif fmt in ('TIFF','TIFFP','TIFFL','TIF','TIFF1'): + if fmt.endswith('P'): + im = _convert2pilp(im) + elif fmt.endswith('L'): + im = _convert2pilL(im) + elif fmt.endswith('1'): + im = _convert2pil1(im) + fmt='TIFF' + elif fmt in ('PCT','PICT'): + return _saveAsPICT(im,fn,fmt,transparent=configPIL.get('transparent',None)) + elif fmt in ('PNG','BMP', 'PPM'): + pass + elif fmt in ('JPG','JPEG'): + fmt = 'JPEG' + else: + raise RenderPMError("Unknown image kind %s" % fmt) + if fmt=='TIFF': + tc = configPIL.get('transparent',None) + if tc: + from PIL import ImageChops, Image + T = 768*[0] + for o, c in zip((0,256,512), tc.bitmap_rgb()): + T[o+c] = 255 + #if isinstance(fn,str): ImageChops.invert(im.point(T).convert('L').point(255*[0]+[255])).save(fn+'_mask.gif','GIF') + im = Image.merge('RGBA', im.split()+(ImageChops.invert(im.point(T).convert('L').point(255*[0]+[255])),)) + #if isinstance(fn,str): im.save(fn+'_masked.gif','GIF') + for a,d in ('resolution',self._dpi),('resolution unit','inch'): + configPIL[a] = configPIL.get(a,d) + configPIL.setdefault('chops_invert',0) + if configPIL.pop('chops_invert'): + from PIL import ImageChops + im = ImageChops.invert(im) + configPIL.setdefault('preSaveCB',None) + preSaveCB=configPIL.pop('preSaveCB') + if preSaveCB: + im = preSaveCB(im) + im.save(fn,fmt,**configPIL) + if not hasattr(fn,'write') and os.name=='mac': + from reportlab.lib.utils import markfilename + markfilename(fn,ext=fmt) + + def saveToString(self,fmt='GIF'): + s = BytesIO() + self.saveToFile(s,fmt=fmt) + return s.getvalue() + + def _saveToBMP(self,f): + ''' + Niki Spahiev, , asserts that this is a respectable way to get BMP without PIL + f is a file like object to which the BMP is written + ''' + import struct + gs = self._gs + if self._backend=='rlPyCairo' and gs._fmt=='ARGB32': #pixBuf would have 4 bytes + gs._fmt = 'RGB24' #force 3 bytes out until our BMP allows Alpha + pix = gs.pixBuf + gs._fmt = 'ARGB32' + else: + pix = gs.pixBuf + width, height = gs.width, gs.height + f.write(struct.pack('=2sLLLLLLhh24x','BM',len(pix)+54,0,54,40,width,height,1,24)) + rowb = width * 3 + for o in range(len(pix),0,-rowb): + f.write(pix[o-rowb:o]) + f.write( '\0' * 14 ) + + def setFont(self,fontName,fontSize,leading=None): + _setFont(self._gs,fontName,fontSize) + + def __setattr__(self,name,value): + setattr(self._gs,name,value) + + def __getattr__(self,name): + return getattr(self._gs,name) + + def fillstrokepath(self,stroke=1,fill=1): + if fill: self.pathFill() + if stroke: self.pathStroke() + + def _bezierArcSegmentCCW(self, cx,cy, rx,ry, theta0, theta1): + """compute the control points for a bezier arc with theta1-theta0 <= 90. + Points are computed for an arc with angle theta increasing in the + counter-clockwise (CCW) direction. returns a tuple with starting point + and 3 control points of a cubic bezier curve for the curvto opertator""" + + # Requires theta1 - theta0 <= 90 for a good approximation + assert abs(theta1 - theta0) <= 90 + cos0 = cos(pi*theta0/180.0) + sin0 = sin(pi*theta0/180.0) + x0 = cx + rx*cos0 + y0 = cy + ry*sin0 + + cos1 = cos(pi*theta1/180.0) + sin1 = sin(pi*theta1/180.0) + + x3 = cx + rx*cos1 + y3 = cy + ry*sin1 + + dx1 = -rx * sin0 + dy1 = ry * cos0 + + #from pdfgeom + halfAng = pi*(theta1-theta0)/(2.0 * 180.0) + k = abs(4.0 / 3.0 * (1.0 - cos(halfAng) ) /(sin(halfAng)) ) + x1 = x0 + dx1 * k + y1 = y0 + dy1 * k + + dx2 = -rx * sin1 + dy2 = ry * cos1 + + x2 = x3 - dx2 * k + y2 = y3 - dy2 * k + return ((x0,y0), ((x1,y1), (x2,y2), (x3,y3)) ) + + def bezierArcCCW(self, cx,cy, rx,ry, theta0, theta1): + """return a set of control points for Bezier approximation to an arc + with angle increasing counter clockwise. No requirement on (theta1-theta0) <= 90 + However, it must be true that theta1-theta0 > 0.""" + + # I believe this is also clockwise + # pretty much just like Robert Kern's pdfgeom.BezierArc + angularExtent = theta1 - theta0 + # break down the arc into fragments of <=90 degrees + if abs(angularExtent) <= 90.0: # we just need one fragment + angleList = [(theta0,theta1)] + else: + Nfrag = int( ceil( abs(angularExtent)/90.) ) + fragAngle = float(angularExtent)/ Nfrag # this could be negative + angleList = [] + for ii in range(Nfrag): + a = theta0 + ii * fragAngle + b = a + fragAngle # hmm.. is I wonder if this is precise enought + angleList.append((a,b)) + + ctrlpts = [] + for (a,b) in angleList: + if not ctrlpts: # first time + [(x0,y0), pts] = self._bezierArcSegmentCCW(cx,cy, rx,ry, a,b) + ctrlpts.append(pts) + else: + [(tmpx,tmpy), pts] = self._bezierArcSegmentCCW(cx,cy, rx,ry, a,b) + ctrlpts.append(pts) + return ((x0,y0), ctrlpts) + + def addEllipsoidalArc(self, cx,cy, rx, ry, ang1, ang2): + """adds an ellisesoidal arc segment to a path, with an ellipse centered + on cx,cy and with radii (major & minor axes) rx and ry. The arc is + drawn in the CCW direction. Requires: (ang2-ang1) > 0""" + + ((x0,y0), ctrlpts) = self.bezierArcCCW(cx,cy, rx,ry,ang1,ang2) + + self.lineTo(x0,y0) + for ((x1,y1), (x2,y2),(x3,y3)) in ctrlpts: + self.curveTo(x1,y1,x2,y2,x3,y3) + + def drawCentredString(self, x, y, text, text_anchor='middle', direction=None, shaping=False): + self.drawString(x,y,text, text_anchor=text_anchor,direction=direction, shaping=shaping) + + def drawRightString(self, text, x, y, direction=None): + self.drawString(text,x,y,text_anchor='end',direction=direction) + + def drawString(self, x, y, text, _fontInfo=None, text_anchor='left', direction=None, shaping=False): + gs = self._gs + gs_fontSize = gs.fontSize + gs_fontName = gs.fontName + if _fontInfo and _fontInfo!=(gs_fontSize,gs_fontName): + fontName, fontSize = _fontInfo + _setFont(gs,fontName,fontSize) + else: + fontName = gs_fontName + fontSize = gs_fontSize + + text, textLen = bidiShapedText(text,direction,fontName=fontName,fontSize=fontSize,shaping=shaping) + + try: + if text_anchor in ('end','middle', 'end'): + textLen = stringWidth(text, fontName,fontSize) + if text_anchor=='end': + x -= textLen + elif text_anchor=='middle': + x -= textLen/2. + elif text_anchor=='numeric': + x -= numericXShift(text_anchor,text,textLen,fontName,fontSize) + + if self._backend=='rlPyCairo': + gs.drawString(x,y,text) + else: + font = getFont(fontName) + if font._dynamicFont: + gs.drawString(x,y,text) + else: + fc = font + if not isUnicode(text): + try: + text = text.decode('utf8') + except UnicodeDecodeError as e: + i,j = e.args[2:4] + raise UnicodeDecodeError(*(e.args[:4]+('%s\n%s-->%s<--%s' % (e.args[4],text[i-10:i],text[i:j],text[j:j+10]),))) + + FT = unicode2T1(text,[font]+font.substitutionFonts) + n = len(FT) + nm1 = n-1 + for i in range(n): + f, t = FT[i] + if f!=fc: + _setFont(gs,f.fontName,fontSize) + fc = f + gs.drawString(x,y,t) + if i!=nm1: + x += f.stringWidth(t.decode(f.encName),fontSize) + finally: + gs.setFont(gs_fontName,gs_fontSize) + + def line(self,x1,y1,x2,y2): + if self.strokeColor is not None: + self.pathBegin() + self.moveTo(x1,y1) + self.lineTo(x2,y2) + self.pathStroke() + + def rect(self,x,y,width,height,stroke=1,fill=1): + self.pathBegin() + self.moveTo(x, y) + self.lineTo(x+width, y) + self.lineTo(x+width, y + height) + self.lineTo(x, y + height) + self.pathClose() + self.fillstrokepath(stroke=stroke,fill=fill) + + def roundRect(self, x, y, width, height, rx,ry): + """rect(self, x, y, width, height, rx,ry): + Draw a rectangle if rx or rx and ry are specified the corners are + rounded with ellipsoidal arcs determined by rx and ry + (drawn in the counter-clockwise direction)""" + if rx==0: rx = ry + if ry==0: ry = rx + x2 = x + width + y2 = y + height + self.pathBegin() + self.moveTo(x+rx,y) + self.addEllipsoidalArc(x2-rx, y+ry, rx, ry, 270, 360 ) + self.addEllipsoidalArc(x2-rx, y2-ry, rx, ry, 0, 90) + self.addEllipsoidalArc(x+rx, y2-ry, rx, ry, 90, 180) + self.addEllipsoidalArc(x+rx, y+ry, rx, ry, 180, 270) + self.pathClose() + self.fillstrokepath() + + def circle(self, cx, cy, r): + "add closed path circle with center cx,cy and axes r: counter-clockwise orientation" + self.ellipse(cx,cy,r,r) + + def ellipse(self, cx,cy,rx,ry): + """add closed path ellipse with center cx,cy and axes rx,ry: counter-clockwise orientation + (remember y-axis increases downward) """ + self.pathBegin() + # first segment + x0 = cx + rx # (x0,y0) start pt + y0 = cy + + x3 = cx # (x3,y3) end pt of arc + y3 = cy-ry + + x1 = cx+rx + y1 = cy-ry*BEZIER_ARC_MAGIC + + x2 = x3 + rx*BEZIER_ARC_MAGIC + y2 = y3 + self.moveTo(x0, y0) + self.curveTo(x1,y1,x2,y2,x3,y3) + # next segment + x0 = x3 + y0 = y3 + + x3 = cx-rx + y3 = cy + + x1 = cx-rx*BEZIER_ARC_MAGIC + y1 = cy-ry + + x2 = x3 + y2 = cy- ry*BEZIER_ARC_MAGIC + self.curveTo(x1,y1,x2,y2,x3,y3) + # next segment + x0 = x3 + y0 = y3 + + x3 = cx + y3 = cy+ry + + x1 = cx-rx + y1 = cy+ry*BEZIER_ARC_MAGIC + + x2 = cx -rx*BEZIER_ARC_MAGIC + y2 = cy+ry + self.curveTo(x1,y1,x2,y2,x3,y3) + #last segment + x0 = x3 + y0 = y3 + + x3 = cx+rx + y3 = cy + + x1 = cx+rx*BEZIER_ARC_MAGIC + y1 = cy+ry + + x2 = cx+rx + y2 = cy+ry*BEZIER_ARC_MAGIC + self.curveTo(x1,y1,x2,y2,x3,y3) + self.pathClose() + + def saveState(self): + '''do nothing for compatibility''' + pass + + def setFillColor(self,aColor): + self.fillColor = self._colorConverter(aColor) + alpha = getattr(aColor,'alpha',None) + if alpha is not None: + self.fillOpacity = alpha + + def setStrokeColor(self,aColor): + self.strokeColor = self._colorConverter(aColor) + alpha = getattr(aColor,'alpha',None) + if alpha is not None: + self.strokeOpacity = alpha + + restoreState = saveState + + # compatibility routines + def setLineCap(self,cap): + self.lineCap = cap + + def setLineJoin(self,join): + self.lineJoin = join + + def setLineWidth(self,width): + self.strokeWidth = width + + def stringWidth(self, text, fontName=None, fontSize=None): + return stringWidth(text, fontName or self._gs.fontName, + (fontSize if fontSize is not None else self._gs.fontSize)) +def drawToPMCanvas(d, dpi=72, bg=0xffffff, configPIL=None, showBoundary=rl_config._unset_,backend=rl_config.renderPMBackend,backendFmt='RGB',**kwds): + d = renderScaledDrawing(d) + c = PMCanvas(d.width, d.height, dpi=dpi, bg=bg, configPIL=configPIL, backend=backend,backendFmt=backendFmt) + draw(d, c, 0, 0, showBoundary=showBoundary,**kwds) + return c + +def drawToPIL(d, dpi=72, bg=0xffffff, configPIL=None, showBoundary=rl_config._unset_,backend=rl_config.renderPMBackend,backendFmt='RGB', **kwds): + return drawToPMCanvas(d, dpi=dpi, bg=bg, configPIL=configPIL, showBoundary=showBoundary, backend=backend,backendFmt=backendFmt, **kwds).toPIL() + +def drawToPILP(d, dpi=72, bg=0xffffff, configPIL=None, showBoundary=rl_config._unset_,backend=rl_config.renderPMBackend,backendFmt='RGB', **kwds): + Image = _getImage() + im = drawToPIL(d, dpi=dpi, bg=bg, configPIL=configPIL, showBoundary=showBoundary,backend=backend,backendFmt=backendFmt, **kwds) + return im.convert("P", dither=Image.NONE, palette=Image.ADAPTIVE) + +def drawToFile(d,fn,fmt='GIF', dpi=72, bg=0xffffff, configPIL=None, showBoundary=rl_config._unset_,backend=rl_config.renderPMBackend,backendFmt='RGB', **kwds): + '''create a pixmap and draw drawing, d to it then save as a file + configPIL dict is passed to image save method''' + c = drawToPMCanvas(d, dpi=dpi, bg=bg, configPIL=configPIL, showBoundary=showBoundary,backend=backend,backendFmt=backendFmt, **kwds) + c.saveToFile(fn,fmt) + +def drawToString(d,fmt='GIF', dpi=72, bg=0xffffff, configPIL=None, showBoundary=rl_config._unset_,backend=rl_config.renderPMBackend,backendFmt='RGB',**kwds): + s = BytesIO() + drawToFile(d,s,fmt=fmt, dpi=dpi, bg=bg, configPIL=configPIL,backend=backend,backendFmt=backendFmt, **kwds) + return s.getvalue() + +save = drawToFile + +def test(outDir='pmout', shout=False): + def ext(x): + if x=='tiff': x='tif' + return x + #grab all drawings from the test module and write out. + #make a page of links in HTML to assist viewing. + import os + from reportlab.graphics import testshapes + from reportlab.rl_config import verbose + getAllTestDrawings = testshapes.getAllTestDrawings + drawings = [] + if not os.path.isdir(outDir): + os.mkdir(outDir) + htmlTop = """renderPM output results + +

renderPM results of output

+ """ + htmlBottom = """ + + """ + html = [htmlTop] + names = {} + argv = sys.argv[1:] + E = [a for a in argv if a.startswith('--ext=')] + if not E: + E = ['gif','tiff', 'png', 'jpg', 'pct', 'py', 'svg'] + else: + for a in E: + argv.remove(a) + E = (','.join([a[6:] for a in E])).split(',') + + errs = [] + import traceback + from xml.sax.saxutils import escape + def handleError(name,fmt): + msg = 'Problem drawing %s fmt=%s file'%(name,fmt) + if shout or verbose>2: print(msg) + errs.append('

%s

' % msg) + buf = StringIO() + traceback.print_exc(file=buf) + errs.append('
%s
' % escape(buf.getvalue())) + + #print in a loop, with their doc strings + for (drawing, docstring, name) in getAllTestDrawings(doTTF=hasattr(_pmBackend,'ft_get_face')): + i = names[name] = names.setdefault(name,0)+1 + if i>1: name += '.%02d' % (i-1) + if argv and name not in argv: continue + fnRoot = name + w = int(drawing.width) + h = int(drawing.height) + html.append('

Drawing %s

\n
%s
' % (name, docstring)) + + for k in E: + if k in ['gif','png','jpg','pct']: + html.append('

%s format

\n' % k.upper()) + try: + filename = '%s.%s' % (fnRoot, ext(k)) + fullpath = os.path.join(outDir, filename) + if os.path.isfile(fullpath): + os.remove(fullpath) + if k=='pct': + drawToFile(drawing,fullpath,fmt=k,configPIL={'transparent':white}) + elif k in ['py','svg']: + drawing.save(formats=['py','svg'],outDir=outDir,fnRoot=fnRoot) + else: + drawToFile(drawing,fullpath,fmt=k) + if k in ['gif','png','jpg']: + html.append('
\n' % filename) + elif k=='py': + html.append('python source
\n' % filename) + elif k=='svg': + html.append('SVG
\n' % filename) + if shout or verbose>2: print('wrote %s'%ascii(fullpath)) + except AttributeError: + handleError(name,k) + if os.environ.get('RL_NOEPSPREVIEW','0')=='1': drawing.__dict__['preview'] = 0 + for k in ('eps', 'pdf'): + try: + drawing.save(formats=[k],outDir=outDir,fnRoot=fnRoot) + except: + handleError(name,k) + + if errs: + html[0] = html[0].replace('',' (errors)') + html.append('') + html.extend(errs) + html.append(htmlBottom) + htmlFileName = os.path.join(outDir, 'pm-index.html') + with open(htmlFileName, 'w') as f: + f.writelines(html) + if sys.platform=='mac': + from reportlab.lib.utils import markfilename + markfilename(htmlFileName,ext='HTML') + if shout or verbose>2: print('wrote %s' % htmlFileName) + +if __name__=='__main__': + test(shout=True) diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/renderPS.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/renderPS.py new file mode 100644 index 0000000000000000000000000000000000000000..36ff6c4672ba4b72bf31739cc1e4c0df39711e9d --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/renderPS.py @@ -0,0 +1,973 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/graphics/renderPS.py +__version__='3.3.0' +__doc__="""Render drawing objects in Postscript""" + +import math +from io import BytesIO, StringIO +from reportlab.pdfbase.pdfmetrics import getFont, stringWidth, unicode2T1 # for font info +from reportlab.lib.utils import asBytes, char2int, rawBytes, asNative, isUnicode +from reportlab.lib.rl_accel import fp_str +from reportlab.graphics.renderbase import Renderer, getStateDelta, renderScaledDrawing +from reportlab.graphics.shapes import STATE_DEFAULTS +from reportlab import rl_config +from reportlab.pdfgen.canvas import FILL_EVEN_ODD + +_ESCAPEDICT={} +for c in range(256): + if c<32 or c>=127: + _ESCAPEDICT[c]= '\\%03o' % c + elif c in (ord('\\'),ord('('),ord(')')): + _ESCAPEDICT[c] = '\\'+chr(c) + else: + _ESCAPEDICT[c] = chr(c) +del c + +def _escape_and_limit(s): + s = asBytes(s) + R = [] + aR = R.append + n = 0 + for c in s: + c = _ESCAPEDICT[char2int(c)] + aR(c) + n += len(c) + if n>=200: + n = 0 + aR('\\\n') + return ''.join(R) + +# we need to create encoding vectors for each font we use, or they will + # come out in Adobe's old StandardEncoding, which NOBODY uses. +PS_WinAnsiEncoding=""" +/RE { %def + findfont begin + currentdict dup length dict begin + { %forall + 1 index /FID ne { def } { pop pop } ifelse + } forall + /FontName exch def dup length 0 ne { %if + /Encoding Encoding 256 array copy def + 0 exch { %forall + dup type /nametype eq { %ifelse + Encoding 2 index 2 index put + pop 1 add + }{ %else + exch pop + } ifelse + } forall + } if pop + currentdict dup end end + /FontName get exch definefont pop +} bind def + +/WinAnsiEncoding [ + 39/quotesingle 96/grave 128/euro 130/quotesinglbase/florin/quotedblbase + /ellipsis/dagger/daggerdbl/circumflex/perthousand + /Scaron/guilsinglleft/OE 145/quoteleft/quoteright + /quotedblleft/quotedblright/bullet/endash/emdash + /tilde/trademark/scaron/guilsinglright/oe/dotlessi + 159/Ydieresis 164/currency 166/brokenbar 168/dieresis/copyright + /ordfeminine 172/logicalnot 174/registered/macron/ring + 177/plusminus/twosuperior/threesuperior/acute/mu + 183/periodcentered/cedilla/onesuperior/ordmasculine + 188/onequarter/onehalf/threequarters 192/Agrave/Aacute + /Acircumflex/Atilde/Adieresis/Aring/AE/Ccedilla + /Egrave/Eacute/Ecircumflex/Edieresis/Igrave/Iacute + /Icircumflex/Idieresis/Eth/Ntilde/Ograve/Oacute + /Ocircumflex/Otilde/Odieresis/multiply/Oslash + /Ugrave/Uacute/Ucircumflex/Udieresis/Yacute/Thorn + /germandbls/agrave/aacute/acircumflex/atilde/adieresis + /aring/ae/ccedilla/egrave/eacute/ecircumflex + /edieresis/igrave/iacute/icircumflex/idieresis + /eth/ntilde/ograve/oacute/ocircumflex/otilde + /odieresis/divide/oslash/ugrave/uacute/ucircumflex + /udieresis/yacute/thorn/ydieresis +] def +""" + +class PSCanvas: + def __init__(self,size=(300,300), PostScriptLevel=2): + self.width, self.height = size + xtraState = [] + self._xtraState_push = xtraState.append + self._xtraState_pop = xtraState.pop + self.comments = 0 + self.code = [] + self.code_append = self.code.append + self._sep = '\n' + self._strokeColor = self._fillColor = self._lineWidth = \ + self._font = self._fontSize = self._lineCap = \ + self._lineJoin = self._color = None + + self._fontsUsed = [] # track them as we go + self.setFont(STATE_DEFAULTS['fontName'],STATE_DEFAULTS['fontSize']) + self.setStrokeColor(STATE_DEFAULTS['strokeColor']) + self.setLineCap(2) + self.setLineJoin(0) + self.setLineWidth(1) + self.PostScriptLevel=PostScriptLevel + self._fillMode = FILL_EVEN_ODD + + def comment(self,msg): + if self.comments: self.code_append('%'+msg) + + def drawImage(self, image, x1,y1, width=None,height=None): # Postscript Level2 version + # select between postscript level 1 or level 2 + if self.PostScriptLevel==1: + self._drawImageLevel1(image, x1,y1, width, height) + elif self.PostScriptLevel==2: + self._drawImageLevel2(image, x1, y1, width, height) + else : + raise ValueError('Unsupported Postscript Level %s' % self.PostScriptLevel) + + def clear(self): + self.code_append('showpage') # ugh, this makes no sense oh well. + + def _t1_re_encode(self): + if not self._fontsUsed: return + # for each font used, reencode the vectors + C = [] + for fontName in self._fontsUsed: + fontObj = getFont(fontName) + if not fontObj._dynamicFont and fontObj.encName=='WinAnsiEncoding': + C.append('WinAnsiEncoding /%s /%s RE' % (fontName, fontName)) + if C: + C.insert(0,PS_WinAnsiEncoding) + self.code.insert(1, self._sep.join(C)) + + def save(self,f=None): + if not hasattr(f,'write'): + _f = open(f,'wb') + else: + _f = f + if self.code[-1]!='showpage': self.clear() + self.code.insert(0,'''\ +%%!PS-Adobe-3.0 EPSF-3.0 +%%%%BoundingBox: 0 0 %d %d +%%%% Initialization: +/m {moveto} bind def +/l {lineto} bind def +/c {curveto} bind def +''' % (self.width,self.height)) + + self._t1_re_encode() + _f.write(rawBytes(self._sep.join(self.code))) + if _f is not f: + _f.close() + from reportlab.lib.utils import markfilename + markfilename(f,creatorcode='XPR3',filetype='EPSF') + + def saveState(self): + self._xtraState_push((self._fontCodeLoc,)) + self.code_append('gsave') + + def restoreState(self): + self.code_append('grestore') + self._fontCodeLoc, = self._xtraState_pop() + + def stringWidth(self, s, font=None, fontSize=None): + """Return the logical width of the string if it were drawn + in the current font (defaults to self.font).""" + font = font or self._font + fontSize = fontSize or self._fontSize + return stringWidth(s, font, fontSize) + + def setLineCap(self,v): + if self._lineCap!=v: + self._lineCap = v + self.code_append('%d setlinecap'%v) + + def setLineJoin(self,v): + if self._lineJoin!=v: + self._lineJoin = v + self.code_append('%d setlinejoin'%v) + + def setDash(self, array=[], phase=0): + """Two notations. pass two numbers, or an array and phase""" + # copied and modified from reportlab.canvas + psoperation = "setdash" + if isinstance(array,(float,int)): + self.code_append('[%s %s] 0 %s' % (array, phase, psoperation)) + elif isinstance(array,(tuple,list)): + assert phase >= 0, "phase is a length in user space" + textarray = ' '.join(map(str, array)) + self.code_append('[%s] %s %s' % (textarray, phase, psoperation)) + + def setStrokeColor(self, color): + self._strokeColor = color + self.setColor(color) + + def setColor(self, color): + if self._color!=color: + self._color = color + if color: + if hasattr(color, "cyan"): + self.code_append('%s setcmykcolor' % fp_str(color.cyan, color.magenta, color.yellow, color.black)) + else: + self.code_append('%s setrgbcolor' % fp_str(color.red, color.green, color.blue)) + + def setFillColor(self, color): + self._fillColor = color + self.setColor(color) + + def setFillMode(self, v): + self._fillMode = v + + def setLineWidth(self, width): + if width != self._lineWidth: + self._lineWidth = width + self.code_append('%s setlinewidth' % width) + + def setFont(self,font,fontSize,leading=None): + if self._font!=font or self._fontSize!=fontSize: + self._fontCodeLoc = len(self.code) + self._font = font + self._fontSize = fontSize + self.code_append('') + + def line(self, x1, y1, x2, y2): + if self._strokeColor != None: + self.setColor(self._strokeColor) + self.code_append('%s m %s l stroke' % (fp_str(x1, y1), fp_str(x2, y2))) + + def _escape(self, s): + ''' + return a copy of string s with special characters in postscript strings + escaped with backslashes. + ''' + try: + return _escape_and_limit(s) + except: + raise ValueError("cannot escape %s" % ascii(s)) + + def _textOut(self, x, y, s, textRenderMode=0): + if textRenderMode==3: return + xy = fp_str(x,y) + s = self._escape(s) + + if textRenderMode==0: #the standard case + self.setColor(self._fillColor) + self.code_append('%s m (%s) show ' % (xy,s)) + return + + fill = textRenderMode==0 or textRenderMode==2 or textRenderMode==4 or textRenderMode==6 + stroke = textRenderMode==1 or textRenderMode==2 or textRenderMode==5 or textRenderMode==6 + addToClip = textRenderMode>=4 + if fill and stroke: + if self._fillColor is None: + op = '' + else: + op = 'fill ' + self.setColor(self._fillColor) + self.code_append('%s m (%s) true charpath gsave %s' % (xy,s,op)) + self.code_append('grestore ') + if self._strokeColor is not None: + self.setColor(self._strokeColor) + self.code_append('stroke ') + else: #can only be stroke alone + self.setColor(self._strokeColor) + self.code_append('%s m (%s) true charpath stroke ' % (xy,s)) + + def _issueT1String(self,fontObj,x,y,s, textRenderMode=0): + fc = fontObj + code_append = self.code_append + fontSize = self._fontSize + fontsUsed = self._fontsUsed + escape = self._escape + if not isUnicode(s): + try: + s = s.decode('utf8') + except UnicodeDecodeError as e: + i,j = e.args[2:4] + raise UnicodeDecodeError(*(e.args[:4]+('%s\n%s-->%s<--%s' % (e.args[4],s[i-10:i],s[i:j],s[j:j+10]),))) + + for f, t in unicode2T1(s,[fontObj]+fontObj.substitutionFonts): + if f!=fc: + psName = asNative(f.face.name) + code_append('(%s) findfont %s scalefont setfont' % (psName,fp_str(fontSize))) + if psName not in fontsUsed: + fontsUsed.append(psName) + fc = f + self._textOut(x,y,t,textRenderMode) + x += f.stringWidth(t.decode(f.encName),fontSize) + if fontObj!=fc: + self._font = None + self.setFont(fontObj.face.name,fontSize) + + def drawString(self, x, y, s, angle=0, text_anchor='left', textRenderMode=0): + needFill = textRenderMode in (0,2,4,6) + needStroke = textRenderMode in (1,2,5,6) + if needFill or needStroke: + if text_anchor!='left': + textLen = stringWidth(s, self._font,self._fontSize) + if text_anchor=='end': + x -= textLen + elif text_anchor=='middle': + x -= textLen/2. + elif text_anchor=='numeric': + x -= numericXShift(text_anchor,s,textLen,self._font,self._fontSize) + fontObj = getFont(self._font) + if not self.code[self._fontCodeLoc]: + psName = asNative(fontObj.face.name) + self.code[self._fontCodeLoc]='(%s) findfont %s scalefont setfont' % (psName,fp_str(self._fontSize)) + if psName not in self._fontsUsed: + self._fontsUsed.append(psName) + if angle!=0: + self.code_append('gsave %s translate %s rotate' % (fp_str(x,y),fp_str(angle))) + x = y = 0 + oldColor = self._color + if fontObj._dynamicFont: + self._textOut(x, y, s, textRenderMode=textRenderMode) + else: + self._issueT1String(fontObj,x,y,s, textRenderMode=textRenderMode) + self.setColor(oldColor) + if angle!=0: + self.code_append('grestore') + + def drawCentredString(self, x, y, text, text_anchor='middle', textRenderMode=0): + self.drawString(x,y,text, text_anchor=text_anchor, textRenderMode=textRenderMode) + + def drawRightString(self, text, x, y, text_anchor='end', textRenderMode=0): + self.drawString(text,x,y,text_anchor=text_anchor, textRenderMode=textRenderMode) + + def drawCurve(self, x1, y1, x2, y2, x3, y3, x4, y4, closed=0): + codeline = '%s m %s curveto' + data = (fp_str(x1, y1), fp_str(x2, y2, x3, y3, x4, y4)) + if self._fillColor != None: + self.setColor(self._fillColor) + self.code_append((codeline % data) + ' eofill') + if self._strokeColor != None: + self.setColor(self._strokeColor) + self.code_append((codeline % data) + + ((closed and ' closepath') or '') + + ' stroke') + + ######################################################################################## + + def rect(self, x1,y1, x2,y2, stroke=1, fill=1): + "Draw a rectangle between x1,y1, and x2,y2" + # Path is drawn in counter-clockwise direction" + + x1, x2 = min(x1,x2), max(x1, x2) # from piddle.py + y1, y2 = min(y1,y2), max(y1, y2) + self.polygon(((x1,y1),(x2,y1),(x2,y2),(x1,y2)), closed=1, stroke=stroke, fill = fill) + + def roundRect(self, x1,y1, x2,y2, rx=8, ry=8): + """Draw a rounded rectangle between x1,y1, and x2,y2, + with corners inset as ellipses with x radius rx and y radius ry. + These should have x10, and ry>0.""" + # Path is drawn in counter-clockwise direction + + x1, x2 = min(x1,x2), max(x1, x2) # from piddle.py + y1, y2 = min(y1,y2), max(y1, y2) + + # Note: arcto command draws a line from current point to beginning of arc + # save current matrix, translate to center of ellipse, scale by rx ry, and draw + # a circle of unit radius in counterclockwise dir, return to original matrix + # arguments are (cx, cy, rx, ry, startAngle, endAngle) + ellipsePath = 'matrix currentmatrix %s %s translate %s %s scale 0 0 1 %s %s arc setmatrix' + + # choice between newpath and moveTo beginning of arc + # go with newpath for precision, does this violate any assumptions in code??? + rr = ['newpath'] # Round Rect code path + a = rr.append + # upper left corner ellipse is first + a(ellipsePath % (x1+rx, y1+ry, rx, -ry, 90, 180)) + a(ellipsePath % (x1+rx, y2-ry, rx, -ry, 180, 270)) + a(ellipsePath % (x2-rx, y2-ry, rx, -ry, 270, 360)) + a(ellipsePath % (x2-rx, y1+ry, rx, -ry, 0, 90) ) + a('closepath') + + self._fillAndStroke(rr) + + def ellipse(self, x1,y1, x2,y2): + """Draw an orthogonal ellipse inscribed within the rectangle x1,y1,x2,y2. + These should have x1= 0: + arc='arc' + else: + arc='arcn' + data = (x,y, xScale, yScale, startAng, startAng+extent, arc) + + return codeline % data + + def polygon(self, p, closed=0, stroke=1, fill=1): + assert len(p) >= 2, 'Polygon must have 2 or more points' + + start = p[0] + p = p[1:] + + poly = [] + a = poly.append + a("%s m" % fp_str(start)) + for point in p: + a("%s l" % fp_str(point)) + if closed: + a("closepath") + + self._fillAndStroke(poly,stroke=stroke,fill=fill) + + def lines(self, lineList, color=None, width=None): + if self._strokeColor != None: + self._setColor(self._strokeColor) + codeline = '%s m %s l stroke' + for line in lineList: + self.code_append(codeline % (fp_str(line[0]),fp_str(line[1]))) + + def moveTo(self,x,y): + self.code_append('%s m' % fp_str(x, y)) + + def lineTo(self,x,y): + self.code_append('%s l' % fp_str(x, y)) + + def curveTo(self,x1,y1,x2,y2,x3,y3): + self.code_append('%s c' % fp_str(x1,y1,x2,y2,x3,y3)) + + def closePath(self): + self.code_append('closepath') + + def polyLine(self, p): + assert len(p) >= 1, 'Polyline must have 1 or more points' + if self._strokeColor != None: + self.setColor(self._strokeColor) + self.moveTo(p[0][0], p[0][1]) + for t in p[1:]: + self.lineTo(t[0], t[1]) + self.code_append('stroke') + + def drawFigure(self, partList, closed=0): + figureCode = [] + a = figureCode.append + first = 1 + + for part in partList: + op = part[0] + args = list(part[1:]) + + if op == figureLine: + if first: + first = 0 + a("%s m" % fp_str(args[:2])) + else: + a("%s l" % fp_str(args[:2])) + a("%s l" % fp_str(args[2:])) + + elif op == figureArc: + first = 0 + x1,y1,x2,y2,startAngle,extent = args[:6] + a(self._genArcCode(x1,y1,x2,y2,startAngle,extent)) + + elif op == figureCurve: + if first: + first = 0 + a("%s m" % fp_str(args[:2])) + else: + a("%s l" % fp_str(args[:2])) + a("%s curveto" % fp_str(args[2:])) + else: + raise TypeError("unknown figure operator: "+op) + + if closed: + a("closepath") + self._fillAndStroke(figureCode) + + def _fillAndStroke(self,code,clip=0,fill=1,stroke=1,fillMode=None): + fill = self._fillColor and fill + stroke = self._strokeColor and stroke + if fill or stroke or clip: + self.code.extend(code) + if fill: + if fillMode is None: + fillMode = self._fillMode + if stroke or clip: self.code_append("gsave") + self.setColor(self._fillColor) + self.code_append("eofill" if fillMode==FILL_EVEN_ODD else "fill") + if stroke or clip: self.code_append("grestore") + if stroke: + if clip: self.code_append("gsave") + self.setColor(self._strokeColor) + self.code_append("stroke") + if clip: self.code_append("grestore") + if clip: + self.code_append("clip") + self.code_append("newpath") + + def translate(self,x,y): + self.code_append('%s translate' % fp_str(x,y)) + + def scale(self,x,y): + self.code_append('%s scale' % fp_str(x,y)) + + def transform(self,a,b,c,d,e,f): + self.code_append('[%s] concat' % fp_str(a,b,c,d,e,f)) + + def _drawTimeResize(self,w,h): + '''if this is used we're probably in the wrong world''' + self.width, self.height = w, h + + def _drawImageLevel1(self, image, x1, y1, width=None, height=None): + # Postscript Level1 version available for fallback mode when Level2 doesn't work + # For now let's start with 24 bit RGB images (following piddlePDF again) + component_depth = 8 + myimage = image.convert('RGB') + imgwidth, imgheight = myimage.size + if not width: + width = imgwidth + if not height: + height = imgheight + #print 'Image size (%d, %d); Draw size (%d, %d)' % (imgwidth, imgheight, width, height) + # now I need to tell postscript how big image is + + # "image operators assume that they receive sample data from + # their data source in x-axis major index order. The coordinate + # of the lower-left corner of the first sample is (0,0), of the + # second (1,0) and so on" -PS2 ref manual p. 215 + # + # The ImageMatrix maps unit squre of user space to boundary of the source image + # + + # The CurrentTransformationMatrix (CTM) maps the unit square of + # user space to the rect...on the page that is to receive the + # image. A common ImageMatrix is [width 0 0 -height 0 height] + # (for a left to right, top to bottom image ) + + # first let's map the user coordinates start at offset x1,y1 on page + + self.code.extend([ + 'gsave', + '%s %s translate' % (x1,y1), # need to start are lower left of image + '%s %s scale' % (width,height), + '/scanline %d 3 mul string def' % imgwidth # scanline by multiples of image width + ]) + + # now push the dimensions and depth info onto the stack + # and push the ImageMatrix to map the source to the target rectangle (see above) + # finally specify source (PS2 pp. 225 ) and by exmample + self.code.extend([ + '%s %s %s' % (imgwidth, imgheight, component_depth), + '[%s %s %s %s %s %s]' % (imgwidth, 0, 0, -imgheight, 0, imgheight), + '{ currentfile scanline readhexstring pop } false 3', + 'colorimage ' + ]) + + # data source output--now we just need to deliver a hex encode + # series of lines of the right overall size can follow + # piddlePDF again + rawimage = (myimage.tobytes if hasattr(myimage,'tobytes') else myimage.tostring)() + hex_encoded = self._AsciiHexEncode(rawimage) + + # write in blocks of 78 chars per line + outstream = StringIO(hex_encoded) + + dataline = outstream.read(78) + while dataline != "": + self.code_append(dataline) + dataline= outstream.read(78) + self.code_append('% end of image data') # for clarity + self.code_append('grestore') # return coordinates to normal + + # end of drawImage + def _AsciiHexEncode(self, input): # also based on piddlePDF + "Helper function used by images" + output = StringIO() + for char in asBytes(input): + output.write('%02x' % char2int(char)) + return output.getvalue() + + def _drawImageLevel2(self, image, x1,y1, width=None,height=None): # Postscript Level2 version + '''At present we're handling only PIL''' + ### what sort of image are we to draw + if image.mode=='L' : + imBitsPerComponent = 8 + imNumComponents = 1 + myimage = image + elif image.mode == '1': + myimage = image.convert('L') + imNumComponents = 1 + myimage = image + else : + myimage = image.convert('RGB') + imNumComponents = 3 + imBitsPerComponent = 8 + + imwidth, imheight = myimage.size + if not width: + width = imwidth + if not height: + height = imheight + self.code.extend([ + 'gsave', + '%s %s translate' % (x1,y1), # need to start are lower left of image + '%s %s scale' % (width,height)]) + + if imNumComponents == 3 : + self.code_append('/DeviceRGB setcolorspace') + elif imNumComponents == 1 : + self.code_append('/DeviceGray setcolorspace') + # create the image dictionary + self.code_append(""" +<< +/ImageType 1 +/Width %d /Height %d %% dimensions of source image +/BitsPerComponent %d""" % (imwidth, imheight, imBitsPerComponent) ) + + if imNumComponents == 1: + self.code_append('/Decode [0 1]') + if imNumComponents == 3: + self.code_append('/Decode [0 1 0 1 0 1] %% decode color values normally') + + self.code.extend([ '/ImageMatrix [%s 0 0 %s 0 %s]' % (imwidth, -imheight, imheight), + '/DataSource currentfile /ASCIIHexDecode filter', + '>> % End image dictionary', + 'image']) + # after image operator just need to dump image dat to file as hexstring + rawimage = (myimage.tobytes if hasattr(myimage,'tobytes') else myimage.tostring)() + hex_encoded = self._AsciiHexEncode(rawimage) + + # write in blocks of 78 chars per line + outstream = StringIO(hex_encoded) + + dataline = outstream.read(78) + while dataline != "": + self.code_append(dataline) + dataline= outstream.read(78) + self.code_append('> % end of image data') # > is EOD for hex encoded filterfor clarity + self.code_append('grestore') # return coordinates to normal + +# renderpdf - draws them onto a canvas +"""Usage: + from reportlab.graphics import renderPS + renderPS.draw(drawing, canvas, x, y) +Execute the script to see some test drawings.""" +from reportlab.graphics.shapes import * + +# hack so we only get warnings once each +#warnOnce = WarnOnce() + +# the main entry point for users... +def draw(drawing, canvas, x=0, y=0, showBoundary=rl_config.showBoundary): + """As it says""" + R = _PSRenderer() + R.draw(renderScaledDrawing(drawing), canvas, x, y, showBoundary=showBoundary) + +def _pointsFromList(L): + ''' + given a list of coordinates [x0, y0, x1, y1....] + produce a list of points [(x0,y0), (y1,y0),....] + ''' + P=[] + a = P.append + for i in range(0,len(L),2): + a((L[i],L[i+1])) + return P + +class _PSRenderer(Renderer): + """This draws onto a EPS document. It needs to be a class + rather than a function, as some EPS-specific state tracking is + needed outside of the state info in the SVG model.""" + + def drawNode(self, node): + """This is the recursive method called for each node + in the tree""" + self._canvas.comment('begin node %r'%node) + color = self._canvas._color + if not (isinstance(node, Path) and node.isClipPath): + self._canvas.saveState() + + #apply state changes + deltas = getStateDelta(node) + self._tracker.push(deltas) + self.applyStateChanges(deltas, {}) + + #draw the object, or recurse + self.drawNodeDispatcher(node) + + rDeltas = self._tracker.pop() + if not (isinstance(node, Path) and node.isClipPath): + self._canvas.restoreState() + self._canvas.comment('end node %r'%node) + self._canvas._color = color + + #restore things we might have lost (without actually doing anything). + for k, v in rDeltas.items(): + if k in self._restores: + setattr(self._canvas,self._restores[k],v) + +## _restores = {'stroke':'_stroke','stroke_width': '_lineWidth','stroke_linecap':'_lineCap', +## 'stroke_linejoin':'_lineJoin','fill':'_fill','font_family':'_font', +## 'font_size':'_fontSize'} + _restores = {'strokeColor':'_strokeColor','strokeWidth': '_lineWidth','strokeLineCap':'_lineCap', + 'strokeLineJoin':'_lineJoin','fillColor':'_fillColor','fontName':'_font', + 'fontSize':'_fontSize'} + + def drawRect(self, rect): + if rect.rx == rect.ry == 0: + #plain old rectangle + self._canvas.rect( + rect.x, rect.y, + rect.x+rect.width, rect.y+rect.height) + else: + #cheat and assume ry = rx; better to generalize + #pdfgen roundRect function. TODO + self._canvas.roundRect( + rect.x, rect.y, + rect.x+rect.width, rect.y+rect.height, rect.rx, rect.ry + ) + + def drawLine(self, line): + if self._canvas._strokeColor: + self._canvas.line(line.x1, line.y1, line.x2, line.y2) + + def drawCircle(self, circle): + self._canvas.circle( circle.cx, circle.cy, circle.r) + + def drawWedge(self, wedge): + yradius, radius1, yradius1 = wedge._xtraRadii() + if (radius1==0 or radius1 is None) and (yradius1==0 or yradius1 is None) and not wedge.annular: + startangledegrees = wedge.startangledegrees + endangledegrees = wedge.endangledegrees + centerx= wedge.centerx + centery = wedge.centery + radius = wedge.radius + extent = endangledegrees - startangledegrees + self._canvas.drawArc(centerx-radius, centery-yradius, centerx+radius, centery+yradius, + startangledegrees, extent, fromcenter=1) + else: + P = wedge.asPolygon() + if isinstance(P,Path): + self.drawPath(P) + else: + self.drawPolygon(P) + + def drawPolyLine(self, p): + if self._canvas._strokeColor: + self._canvas.polyLine(_pointsFromList(p.points)) + + def drawEllipse(self, ellipse): + #need to convert to pdfgen's bounding box representation + x1 = ellipse.cx - ellipse.rx + x2 = ellipse.cx + ellipse.rx + y1 = ellipse.cy - ellipse.ry + y2 = ellipse.cy + ellipse.ry + self._canvas.ellipse(x1,y1,x2,y2) + + def drawPolygon(self, p): + self._canvas.polygon(_pointsFromList(p.points), closed=1) + + def drawString(self, stringObj): + textRenderMode = getattr(stringObj,'textRenderMode',0) + if self._canvas._fillColor or textRenderMode: + S = self._tracker.getState() + text_anchor, x, y, text = S['textAnchor'], stringObj.x,stringObj.y,stringObj.text + if not text_anchor in ['start','inherited']: + font, fontSize = S['fontName'], S['fontSize'] + textLen = stringWidth(text, font,fontSize) + if text_anchor=='end': + x -= textLen + elif text_anchor=='middle': + x -= textLen/2 + elif text_anchor=='numeric': + x -= numericXShift(text_anchor,text,textLen,font,fontSize,encoding='winansi') + else: + raise ValueError('bad value for text_anchor '+str(text_anchor)) + self._canvas.drawString(x,y,text, textRenderMode=textRenderMode) + + def drawPath(self, path, fillMode=None): + from reportlab.graphics.shapes import _renderPath + c = self._canvas + drawFuncs = (c.moveTo, c.lineTo, c.curveTo, c.closePath) + autoclose = getattr(path,'autoclose','') + def rP(**kwds): + return _renderPath(path, drawFuncs, **kwds) + if fillMode is None: + fillMode = getattr(path,'fillMode',c._fillMode) + fill = c._fillColor is not None + stroke = c._strokeColor is not None + clip = path.isClipPath + fas = lambda **kwds: c._fillAndStroke([], fillMode=fillMode, **kwds) + pathFill = lambda : c._fillAndStroke([], stroke=0, fillMode=fillMode) + pathStroke = lambda : c._fillAndStroke([], fill=0) + if autoclose=='svg': + rP() + fas(stroke=stroke,fill=fill,clip=clip) + elif autoclose=='pdf': + if fill: + rP(forceClose=True) + fas(stroke=stroke,fill=fill,clip=clip) + elif stroke or clip: + rP() + fas(stroke=stroke,fill=0,clip=clip) + else: + if fill and rP(countOnly=True): + rP() + elif stroke or clip: + rP() + fas(stroke=stroke,fill=0,clip=clip) + + def applyStateChanges(self, delta, newState): + """This takes a set of states, and outputs the operators + needed to set those properties""" + for key, value in delta.items(): + if key == 'transform': + self._canvas.transform(value[0], value[1], value[2], + value[3], value[4], value[5]) + elif key == 'strokeColor': + #this has different semantics in PDF to SVG; + #we always have a color, and either do or do + #not apply it; in SVG one can have a 'None' color + self._canvas.setStrokeColor(value) + elif key == 'strokeWidth': + self._canvas.setLineWidth(value) + elif key == 'strokeLineCap': #0,1,2 + self._canvas.setLineCap(value) + elif key == 'strokeLineJoin': + self._canvas.setLineJoin(value) + elif key == 'strokeDashArray': + if value: + if isinstance(value,(list,tuple)) and len(value)==2 and isinstance(value[1],(tuple,list)): + phase = value[0] + value = value[1] + else: + phase = 0 + self._canvas.setDash(value,phase) + else: + self._canvas.setDash() +## elif key == 'stroke_opacity': +## warnOnce('Stroke Opacity not supported yet') + elif key == 'fillColor': + #this has different semantics in PDF to SVG; + #we always have a color, and either do or do + #not apply it; in SVG one can have a 'None' color + self._canvas.setFillColor(value) +## elif key == 'fill_rule': +## warnOnce('Fill rules not done yet') +## elif key == 'fill_opacity': +## warnOnce('Fill opacity not done yet') + elif key in ['fontSize', 'fontName']: + # both need setting together in PDF + # one or both might be in the deltas, + # so need to get whichever is missing + fontname = delta.get('fontName', self._canvas._font) + fontsize = delta.get('fontSize', self._canvas._fontSize) + self._canvas.setFont(fontname, fontsize) + + def drawImage(self, image): + from reportlab.lib.utils import ImageReader + im = ImageReader(image.path) + self._canvas.drawImage(im._image,image.x,image.y,image.width,image.height) + +def drawToFile(d,fn, showBoundary=rl_config.showBoundary,**kwd): + d = renderScaledDrawing(d) + c = PSCanvas((d.width,d.height)) + draw(d, c, 0, 0, showBoundary=showBoundary) + c.save(fn) + +def drawToString(d, showBoundary=rl_config.showBoundary): + "Returns a PS as a string in memory, without touching the disk" + s = BytesIO() + drawToFile(d, s, showBoundary=showBoundary) + return s.getvalue() + +######################################################### +# +# test code. First, define a bunch of drawings. +# Routine to draw them comes at the end. +# +######################################################### +def test(outDir='epsout',shout=False): + from reportlab.graphics import testshapes + from reportlab.rl_config import verbose + OLDFONTS = testshapes._FONTS[:] + testshapes._FONTS[:] = ['Times-Roman','Times-Bold','Times-Italic', 'Times-BoldItalic','Courier'] + try: + import os + # save all drawings and their doc strings from the test file + if not os.path.isdir(outDir): + os.mkdir(outDir) + #grab all drawings from the test module + drawings = [] + + for funcname in dir(testshapes): + if funcname[0:10] == 'getDrawing': + func = getattr(testshapes,funcname) + drawing = func() + docstring = getattr(func,'__doc__','') + drawings.append((drawing, docstring)) + + i = 0 + for (d, docstring) in drawings: + filename = outDir + os.sep + 'renderPS_%d.eps'%i + drawToFile(d,filename) + if shout or verbose>2: print('renderPS test saved %s' % ascii(filename)) + i += 1 + finally: + testshapes._FONTS[:] = OLDFONTS + +if __name__=='__main__': + import sys + if len(sys.argv)>1: + outdir = sys.argv[1] + else: + outdir = 'epsout' + test(outdir,shout=True) diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/renderSVG.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/renderSVG.py new file mode 100644 index 0000000000000000000000000000000000000000..b17bad61aa51f803980a54525ae2fbd6eccba5db --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/renderSVG.py @@ -0,0 +1,979 @@ +__doc__="""An experimental SVG renderer for the ReportLab graphics framework. + +This will create SVG code from the ReportLab Graphics API (RLG). +To read existing SVG code and convert it into ReportLab graphics +objects download the svglib module here: + + http://python.net/~gherman/#svglib +""" + +import math, sys, os, codecs, base64 +from io import BytesIO, StringIO + +from reportlab.pdfbase.pdfmetrics import stringWidth # for font info +from reportlab.lib.rl_accel import fp_str +from reportlab.lib.utils import asNative +from reportlab.graphics.renderbase import getStateDelta, Renderer, renderScaledDrawing +from reportlab.graphics.shapes import STATE_DEFAULTS, Path, UserNode +from reportlab.graphics.shapes import * # (only for test0) +from reportlab import rl_config +from reportlab.lib.utils import RLString, isUnicode, isBytes +from reportlab.pdfgen.canvas import FILL_EVEN_ODD, FILL_NON_ZERO +from .renderPM import _getImage + +from xml.dom import getDOMImplementation + +### some constants ### + +sin = math.sin +cos = math.cos +pi = math.pi + +AREA_STYLES = 'stroke-width stroke-linecap stroke stroke-opacity fill fill-opacity stroke-dasharray stroke-dashoffset fill-rule id'.split() +LINE_STYLES = 'stroke-width stroke-linecap stroke stroke-opacity stroke-dasharray stroke-dashoffset id'.split() +TEXT_STYLES = 'font-family font-weight font-style font-variant font-size id'.split() +EXTRA_STROKE_STYLES = 'stroke-width stroke-linecap stroke stroke-opacity stroke-dasharray stroke-dashoffset'.split() +EXTRA_FILL_STYLES = 'fill fill-opacity'.split() + +### top-level user function ### +def drawToString(d, showBoundary=rl_config.showBoundary,**kwds): + "Returns a SVG as a string in memory, without touching the disk" + s = StringIO() + drawToFile(d, s, showBoundary=showBoundary,**kwds) + return s.getvalue() + +def drawToFile(d, fn, showBoundary=rl_config.showBoundary,**kwds): + d = renderScaledDrawing(d) + c = SVGCanvas((d.width, d.height),**kwds) + draw(d, c, 0, 0, showBoundary=showBoundary) + c.save(fn) + +def draw(drawing, canvas, x=0, y=0, showBoundary=rl_config.showBoundary): + """As it says.""" + r = _SVGRenderer() + r.draw(renderScaledDrawing(drawing), canvas, x, y, showBoundary=showBoundary) + +### helper functions ### +def _pointsFromList(L): + """ + given a list of coordinates [x0, y0, x1, y1....] + produce a list of points [(x0,y0), (y1,y0),....] + """ + + P=[] + for i in range(0,len(L), 2): + P.append((L[i], L[i+1])) + + return P + +def transformNode(doc, newTag, node=None, **attrDict): + """Transform a DOM node into new node and copy selected attributes. + + Creates a new DOM node with tag name 'newTag' for document 'doc' + and copies selected attributes from an existing 'node' as provided + in 'attrDict'. The source 'node' can be None. Attribute values will + be converted to strings. + + E.g. + + n = transformNode(doc, "node1", x="0", y="1") + -> DOM node for + + n = transformNode(doc, "node1", x=0, y=1+1) + -> DOM node for + + n = transformNode(doc, "node1", node0, x="x0", y="x0", zoo=bar()) + -> DOM node for + """ + + newNode = doc.createElement(newTag) + for newAttr, attr in attrDict.items(): + sattr = str(attr) + if not node: + newNode.setAttribute(newAttr, sattr) + else: + attrVal = node.getAttribute(sattr) + newNode.setAttribute(newAttr, attrVal or sattr) + + return newNode + +class EncodedWriter(list): + ''' + EncodedWriter(encoding) assumes .write will be called with + either unicode or utf8 encoded bytes. it will accumulate + unicode + ''' + BOMS = { + 'utf-32':codecs.BOM_UTF32, + 'utf-32-be':codecs.BOM_UTF32_BE, + 'utf-32-le':codecs.BOM_UTF32_LE, + 'utf-16':codecs.BOM_UTF16, + 'utf-16-be':codecs.BOM_UTF16_BE, + 'utf-16-le':codecs.BOM_UTF16_LE, + } + def __init__(self,encoding,bom=False): + list.__init__(self) + self.encoding = encoding = codecs.lookup(encoding).name + if bom and '16' in encoding or '32' in encoding: + self.write(self.BOMS[encoding]) + + def write(self,u): + if isBytes(u): + try: + u = u.decode('utf-8') + except: + et, ev, tb = sys.exc_info() + ev = str(ev) + del et, tb + raise ValueError("String %r not encoded as 'utf-8'\nerror=%s" % (u,ev)) + elif not isUnicode(u): + raise ValueError("EncodedWriter.write(%s) argument should be 'utf-8' bytes or str" % ascii(u)) + self.append(u) + + def getvalue(self): + r = ''.join(self) + del self[:] + return r + +_fillRuleMap = { + FILL_NON_ZERO: 'nonzero', + 'non-zero': 'nonzero', + 'nonzero': 'nonzero', + FILL_EVEN_ODD: 'evenodd', + 'even-odd': 'evenodd', + 'evenodd': 'evenodd', + } + +def py_fp_str(*args): + return ' '.join((('%f' % a).rstrip('0').rstrip('.') for a in args)) + +### classes ### +class SVGCanvas: + def __init__(self, size=(300,300), encoding='utf-8', verbose=0, bom=False, **kwds): + ''' + verbose = 0 >0 means do verbose stuff + useClip = False True means don't use a clipPath definition put the global clip into the clip property + to get around an issue with safari + extraXmlDecl = '' use to add extra xml declarations + scaleGroupId = '' id of an extra group to add around the drawing to allow easy scaling + svgAttrs = {} dictionary of attributes to be applied to the svg tag itself + fontSizer = 'px' a string unit or acallable that returns a string fontSize value + ''' + self.verbose = verbose + self.encoding = codecs.lookup(encoding).name + self.bom = bom + useClip = kwds.pop('useClip',False) + self.fontHacks = kwds.pop('fontHacks',{}) + fz = kwds.pop('fontSizer','px') + if isinstance(fz,str): + self.fontSizer = lambda v: f'%s{fz}' % v + elif callable(fz): + self.fontSizer = fz + else: + raise ValueError(f'{fontSizer=} should be a str unit eg px/pt or a callable that returns a string') + self.extraXmlDecl = kwds.pop('extraXmlDecl','') + scaleGroupId = kwds.pop('scaleGroupId','') + self._fillMode = FILL_EVEN_ODD + + self.width, self.height = self.size = size + # self.height = size[1] + self.code = [] + self.style = {} + self.path = '' + self._strokeColor = self._fillColor = self._lineWidth = \ + self._font = self._fontSize = self._lineCap = \ + self._lineJoin = None + if kwds.pop('use_fp_str',False): + self.fp_str = fp_str + else: + self.fp_str = py_fp_str + self.cfp_str = lambda *args: self.fp_str(*args).replace(' ',',') + + implementation = getDOMImplementation('minidom') + #Based on official example here http://www.w3.org/TR/SVG10/linking.html want: + # + #Thus, + #doctype = implementation.createDocumentType("svg", + # "-//W3C//DTD SVG 20010904//EN", + # "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd") + # + #However, putting that example through http://validator.w3.org/ recommends: + # + #So we'll use that for our SVG 1.0 output. + doctype = implementation.createDocumentType("svg", + "-//W3C//DTD SVG 1.0//EN", + "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd") + self.doc = implementation.createDocument(None,"svg",doctype) + self.svg = self.doc.documentElement + svgAttrs = dict( + width = str(size[0]), + height=str(self.height), + preserveAspectRatio="xMinYMin meet", + viewBox="0 0 %d %d" % (self.width, self.height), + #baseProfile = "full", #disliked in V 1.0 + + #these suggested by Tim Roberts, as updated by peter@maubp.freeserve.co.uk + xmlns="http://www.w3.org/2000/svg", + version="1.0", + ) + svgAttrs['fill-rule'] = _fillRuleMap[self._fillMode] + svgAttrs["xmlns:xlink"] = "http://www.w3.org/1999/xlink" + svgAttrs.update(kwds.pop('svgAttrs',{})) + for k,v in svgAttrs.items(): + self.svg.setAttribute(k,v) + + title = self.doc.createElement('title') + text = self.doc.createTextNode('...') + title.appendChild(text) + self.svg.appendChild(title) + + desc = self.doc.createElement('desc') + text = self.doc.createTextNode('...') + desc.appendChild(text) + self.svg.appendChild(desc) + + self.setFont(STATE_DEFAULTS['fontName'], STATE_DEFAULTS['fontSize']) + self.setStrokeColor(STATE_DEFAULTS['strokeColor']) + self.setLineCap(2) + self.setLineJoin(0) + self.setLineWidth(1) + + if not useClip: + # Add a rectangular clipping path identical to view area. + clipPath = transformNode(self.doc, "clipPath", id="clip") + clipRect = transformNode(self.doc, "rect", x=0, y=0, + width=self.width, height=self.height) + clipPath.appendChild(clipRect) + self.svg.appendChild(clipPath) + gtkw = dict(style="clip-path: url(#clip)") + else: + gtkw = dict(clip="0 0 %d %d" % (self.width,self.height)) + + self.groupTree = transformNode(self.doc, "g", + id="group", + transform="scale(1,-1) translate(0,-%d)" % self.height, + **gtkw + ) + + if scaleGroupId: + self.scaleTree = transformNode(self.doc, "g", id=scaleGroupId, transform="scale(1,1)") + self.scaleTree.appendChild(self.groupTree) + self.svg.appendChild(self.scaleTree) + else: + self.svg.appendChild(self.groupTree) + self.currGroup = self.groupTree + + def save(self, fn=None): + writer = EncodedWriter(self.encoding,bom=self.bom) + self.doc.writexml(writer,addindent="\t",newl="\n",encoding=self.encoding) + + if hasattr(fn,'write'): + f = fn + else: + f = open(fn, 'w',encoding=self.encoding) + + svg = writer.getvalue() + exd = self.extraXmlDecl + if exd: + svg = svg.replace('?>','?>'+exd) + f.write(svg) + if f is not fn: + f.close() + + ### helpers ### + def NOTUSED_stringWidth(self, s, font=None, fontSize=None): + """Return the logical width of the string if it were drawn + in the current font (defaults to self.font). + """ + + font = font or self._font + fontSize = fontSize or self._fontSize + + return stringWidth(s, font, fontSize) + + def _formatStyle(self, include=[], exclude='',**kwds): + style = self.style.copy() + style.update(kwds) + keys = list(style.keys()) + if include: + keys = [k for k in keys if k in include] + if exclude: + exclude = exclude.split() + items = [k+': '+str(style[k]) for k in keys if k not in exclude] + else: + items = [k+': '+str(style[k]) for k in keys] + return '; '.join(items) + ';' + + def _escape(self, s): + '''I don't think this was ever needed; seems to have been copied from renderPS''' + return s + + def _genArcCode(self, x1, y1, x2, y2, startAng, extent): + """Calculate the path for an arc inscribed in rectangle defined + by (x1,y1),(x2,y2).""" + + return + + #calculate semi-minor and semi-major axes of ellipse + xScale = abs((x2-x1)/2.0) + yScale = abs((y2-y1)/2.0) + #calculate centre of ellipse + x, y = (x1+x2)/2.0, (y1+y2)/2.0 + + codeline = 'matrix currentmatrix %s %s translate %s %s scale 0 0 1 %s %s %s setmatrix' + + if extent >= 0: + arc='arc' + else: + arc='arcn' + data = (x,y, xScale, yScale, startAng, startAng+extent, arc) + + return codeline % data + + def _fillAndStroke(self, code, clip=0, link_info=None,styles=AREA_STYLES,fillMode=None): + xtra = {} + if fillMode: + xtra['fill-rule'] = _fillRuleMap[fillMode] + path = transformNode(self.doc, "path", + d=self.path, style=self._formatStyle(styles), + ) + if link_info : + path = self._add_link(path, link_info) + self.currGroup.appendChild(path) + self.path = '' + + + ### styles ### + def setLineCap(self, v): + vals = {0:'butt', 1:'round', 2:'square'} + if self._lineCap != v: + self._lineCap = v + self.style['stroke-linecap'] = vals[v] + + def setLineJoin(self, v): + vals = {0:'miter', 1:'round', 2:'bevel'} + if self._lineJoin != v: + self._lineJoin = v + self.style['stroke-linecap'] = vals[v] + + def setDash(self, array=[], phase=0): + """Two notations. Pass two numbers, or an array and phase.""" + + if isinstance(array,(float,int)): + self.style['stroke-dasharray'] = ', '.join(map(str, ([array, phase]))) + elif isinstance(array,(tuple,list)) and len(array) > 0: + assert phase >= 0, "phase is a length in user space" + self.style['stroke-dasharray'] = ', '.join(map(str, array)) + if phase>0: + self.style['stroke-dashoffset'] = str(phase) + + def setStrokeColor(self, color): + self._strokeColor = color + if color == None: + self.style['stroke'] = 'none' + else: + r, g, b = color.red, color.green, color.blue + self.style['stroke'] = 'rgb(%d%%,%d%%,%d%%)' % (r*100, g*100, b*100) + alpha = color.normalizedAlpha + if alpha!=1: + self.style['stroke-opacity'] = '%s' % alpha + elif 'stroke-opacity' in self.style: + del self.style['stroke-opacity'] + + def setFillColor(self, color): + self._fillColor = color + if color == None: + self.style['fill'] = 'none' + else: + r, g, b = color.red, color.green, color.blue + self.style['fill'] = 'rgb(%d%%,%d%%,%d%%)' % (r*100, g*100, b*100) + alpha = color.normalizedAlpha + if alpha!=1: + self.style['fill-opacity'] = '%s' % alpha + elif 'fill-opacity' in self.style: + del self.style['fill-opacity'] + + def setFillMode(self, v): + self._fillMode = v + self.style['fill-rule'] = _fillRuleMap[v] + + def setLineWidth(self, width): + if width != self._lineWidth: + self._lineWidth = width + self.style['stroke-width'] = width + + def setFont(self, font, fontSize): + if self._font != font or self._fontSize != fontSize: + self._font = font + self._fontSize = fontSize + style = self.style + for k in TEXT_STYLES: + if k in style: + del style[k] + svgAttrs = self.fontHacks[font] if font in self.fontHacks else {} + if isinstance(font,RLString): + svgAttrs.update(iter(font.svgAttrs.items())) + if svgAttrs: + for k,v in svgAttrs.items(): + a = 'font-'+k + if a in TEXT_STYLES: + style[a] = v + if 'font-family' not in style: + style['font-family'] = font + style['font-size'] = self.fontSizer(fontSize) + + def _add_link(self, dom_object, link_info) : + assert isinstance(link_info, dict) + link = transformNode(self.doc, "a", **link_info) + link.appendChild(dom_object) + return link + + ### shapes ### + def rect(self, x1,y1, x2,y2, rx=8, ry=8, link_info=None, **_svgAttrs): + "Draw a rectangle between x1,y1 and x2,y2." + + if self.verbose: print("+++ SVGCanvas.rect") + + x = min(x1,x2) + y = min(y1,y2) + kwds = {} + rect = transformNode(self.doc, "rect", + x=x, y=y, width=max(x1,x2)-x, height=max(y1,y2)-y, + style=self._formatStyle(AREA_STYLES),**_svgAttrs) + + if link_info : + rect = self._add_link(rect, link_info) + + self.currGroup.appendChild(rect) + + def roundRect(self, x1,y1, x2,y2, rx=8, ry=8, link_info=None, **_svgAttrs): + """Draw a rounded rectangle between x1,y1 and x2,y2. + + Corners inset as ellipses with x-radius rx and y-radius ry. + These should have x10, and ry>0. + """ + + rect = transformNode(self.doc, "rect", + x=x1, y=y1, width=x2-x1, height=y2-y1, rx=rx, ry=ry, + style=self._formatStyle(AREA_STYLES), **_svgAttrs) + + if link_info: + rect = self._add_link(rect, link_info) + + self.currGroup.appendChild(rect) + + def drawString(self, s, x, y, angle=0, link_info=None, text_anchor='left', textRenderMode=0, **_svgAttrs): + if textRenderMode==3: return #invisible + s = asNative(s) + if self.verbose: print("+++ SVGCanvas.drawString") + needFill = textRenderMode==0 or textRenderMode==2 or textRenderMode==4 or textRenderMode==6 + needStroke = textRenderMode==1 or textRenderMode==2 or textRenderMode==5 or textRenderMode==6 + + if (self._fillColor!=None and needFill) or (self._strokeColor!=None and needStroke): + if not text_anchor in ['start', 'inherited', 'left']: + textLen = stringWidth(s,self._font,self._fontSize) + if text_anchor=='end': + x -= textLen + elif text_anchor=='middle': + x -= textLen/2. + elif text_anchor=='numeric': + x -= numericXShift(text_anchor,s,textLen,self._font,self._fontSize) + else: + raise ValueError('bad value for text_anchor ' + str(text_anchor)) + s = self._escape(s) + st = self._formatStyle(TEXT_STYLES) + if angle != 0: + st = st + " rotate(%s);" % self.fp_str(angle, x, y) + if needFill: + st += self._formatStyle(EXTRA_FILL_STYLES) + else: + st += " fill:none;" + if needStroke: + st += self._formatStyle(EXTRA_STROKE_STYLES) + else: + st += " stroke:none;" + #if textRenderMode>=4: + # _gstate_clipPathSetOrAddself, -1, 1, 0 /*we are adding*/ + text = transformNode(self.doc, "text", + x=x, y=y, style=st, + transform="translate(0,%d) scale(1,-1)" % (2*y), + **_svgAttrs + ) + content = self.doc.createTextNode(s) + text.appendChild(content) + + if link_info: + text = self._add_link(text, link_info) + + self.currGroup.appendChild(text) + + def drawCentredString(self, s, x, y, angle=0, text_anchor='middle', + link_info=None, textRenderMode=0, **_svgAttrs): + if self.verbose: print("+++ SVGCanvas.drawCentredString") + self.drawString(s,x,y,angle=angle, link_info=link_info, text_anchor=text_anchor, + textRenderMode=textRenderMode, **_svgAttrs) + + def drawRightString(self, text, x, y, angle=0,text_anchor='end', + link_info=None, textRenderMode=0, **_svgAttrs): + if self.verbose: print("+++ SVGCanvas.drawRightString") + self.drawString(text,x,y,angle=angle, link_info=link_info, text_anchor=text_anchor, + textRenderMode=textRenderMode, **_svgAttrs) + + def comment(self, data): + "Add a comment." + + comment = self.doc.createComment(data) + # self.currGroup.appendChild(comment) + + def drawImage(self, image, x, y, width, height, embed=True): + buf = BytesIO() + image.save(buf,'png') + buf = asNative(base64.b64encode(buf.getvalue())) + self.currGroup.appendChild( + transformNode(self.doc,'image', + x=x,y=y,width=width,height=height, + href="data:image/png;base64,"+buf, + transform="matrix(%s)" % self.cfp_str(1,0,0,-1,0,height+2*y), + ) + ) + + def line(self, x1, y1, x2, y2): + if self._strokeColor != None: + if 0: # something is wrong with line in my SVG viewer... + line = transformNode(self.doc, "line", + x=x1, y=y1, x2=x2, y2=y2, + style=self._formatStyle(LINE_STYLES)) + self.currGroup.appendChild(line) + path = transformNode(self.doc, "path", + d="M %s L %s Z" % (self.cfp_str(x1,y1),self.cfp_str(x2,y2)), + style=self._formatStyle(LINE_STYLES)) + self.currGroup.appendChild(path) + + def ellipse(self, x1, y1, x2, y2, link_info=None): + """Draw an orthogonal ellipse inscribed within the rectangle x1,y1,x2,y2. + + These should have x1=180, 0, cfp_str(mx, my))) + else: + s("M %s A %s %d %d %d %s Z" % \ + (cfp_str(mx, my), cfp_str(rx, ry), 0, extent>=180, 0, cfp_str(mx, my))) + + if fromcenter: + s("L %s Z" % cfp_str(cx, cy)) + + path = transformNode(self.doc, "path", + d=' '.join(s.__self__), style=self._formatStyle()) + self.currGroup.appendChild(path) + + def polygon(self, points, closed=0, link_info=None): + assert len(points) >= 2, 'Polygon must have 2 or more points' + + if self._strokeColor!=None or self._fillColor!=None: + pts = ', '.join([fp_str(*p) for p in points]) + polyline = transformNode(self.doc, "polygon", + points=pts, style=self._formatStyle(AREA_STYLES)) + + if link_info: + polyline = self._add_link(polyline, link_info) + + self.currGroup.appendChild(polyline) + + # self._fillAndStroke(polyCode) + + def lines(self, lineList, color=None, width=None): + # print "### lineList", lineList + return + + if self._strokeColor != None: + codeline = '%s m %s l stroke' + for line in lineList: + self.code.append(codeline % (fp_str(line[0]), fp_str(line[1]))) + + def polyLine(self, points): + assert len(points) >= 1, 'Polyline must have 1 or more points' + + if self._strokeColor != None: + pts = ', '.join([fp_str(*p) for p in points]) + polyline = transformNode(self.doc, "polyline", + points=pts, style=self._formatStyle(AREA_STYLES,fill=None)) + self.currGroup.appendChild(polyline) + + ### groups ### + def startGroup(self,attrDict=dict(transform="")): + if self.verbose: print("+++ begin SVGCanvas.startGroup") + currGroup = self.currGroup + group = transformNode(self.doc, "g", **attrDict) + currGroup.appendChild(group) + self.currGroup = group + if self.verbose: print("+++ end SVGCanvas.startGroup") + return currGroup + + def endGroup(self,currGroup): + if self.verbose: print("+++ begin SVGCanvas.endGroup") + self.currGroup = currGroup + if self.verbose: print("+++ end SVGCanvas.endGroup") + + def transform(self, a, b, c, d, e, f): + if self.verbose: print("!!! begin SVGCanvas.transform", a, b, c, d, e, f) + tr = self.currGroup.getAttribute("transform") + if (a, b, c, d, e, f) != (1, 0, 0, 1, 0, 0): + t = 'matrix(%s)' % self.cfp_str(a,b,c,d,e,f) + self.currGroup.setAttribute("transform", "%s %s" % (tr, t)) + + def translate(self, x, y): + if (x,y) != (0,0): + self.currGroup.setAttribute("transform", "%s %s" + % (self.currGroup.getAttribute("transform"), + 'translate(%s)' % self.cfp_str(x,y))) + + def scale(self, sx, sy): + if (sx,sy) != (1,1): + self.currGroup.setAttribute("transform", "%s %s" + % (self.groups[-1].getAttribute("transform"), + 'scale(%s)' % self.cfp_str(sx, sy))) + + ### paths ### + def moveTo(self, x, y): + self.path = self.path + 'M %s ' % self.fp_str(x, y) + + def lineTo(self, x, y): + self.path = self.path + 'L %s ' % self.fp_str(x, y) + + def curveTo(self, x1, y1, x2, y2, x3, y3): + self.path = self.path + 'C %s ' % self.fp_str(x1, y1, x2, y2, x3, y3) + + def closePath(self): + self.path = self.path + 'Z ' + + def saveState(self): + pass + + def restoreState(self): + pass + +class _SVGRenderer(Renderer): + """This draws onto an SVG document. + """ + + def __init__(self): + self.verbose = 0 + + def drawNode(self, node): + """This is the recursive method called for each node in the tree. + """ + + if self.verbose: print("### begin _SVGRenderer.drawNode(%r)" % node) + + self._canvas.comment('begin node %r'%node) + style = self._canvas.style.copy() + if not (isinstance(node, Path) and node.isClipPath): + pass # self._canvas.saveState() + + #apply state changes + deltas = getStateDelta(node) + self._tracker.push(deltas) + self.applyStateChanges(deltas, {}) + + #draw the object, or recurse + self.drawNodeDispatcher(node) + + rDeltas = self._tracker.pop() + if not (isinstance(node, Path) and node.isClipPath): + pass #self._canvas.restoreState() + self._canvas.comment('end node %r'%node) + + #restore things we might have lost (without actually doing anything). + for k, v in rDeltas.items(): + if k in self._restores: + setattr(self._canvas,self._restores[k],v) + self._canvas.style = style + + if self.verbose: print("### end _SVGRenderer.drawNode(%r)" % node) + + _restores = {'strokeColor':'_strokeColor','strokeWidth': '_lineWidth','strokeLineCap':'_lineCap', + 'strokeLineJoin':'_lineJoin','fillColor':'_fillColor','fontName':'_font', + 'fontSize':'_fontSize'} + + def _get_link_info_dict(self, obj): + #We do not want None or False as the link, even if it is the + #attribute's value - use the empty string instead. + url = getattr(obj, "hrefURL", "") or "" + title = getattr(obj, "hrefTitle", "") or "" + if url : + #Is it valid to have a link with no href? The XML requires + #the xlink:href to be present, but you might just want a + #tool tip shown (via the xlink:title attribute). Note that + #giving an href of "" is equivalent to "the current page" + #(a relative link saying go nowhere). + return {"xlink:href":url, "xlink:title":title, "target":"_top"} + #Currently of all the mainstream browsers I have tested, only Safari/webkit + #will show SVG images embedded in HTML using a simple tag. + #However, the links don't work (Safari 3.2.1 on the Mac). + # + #Therefore I use the following, which also works for Firefox, Opera, and + #IE 6.0 with Adobe SVG Viewer 6 beta: + # + # + #Once displayed, Firefox and Safari treat the SVG like a frame, and + #by default clicking on links acts "in frame" and replaces the image. + #Opera does what I expect, and replaces the whole page with the link. + # + #Therefore I use target="_top" to force the links to replace the whole page. + #This now works as expected on Safari 3.2.1, Firefox 3.0.6, Opera 9.20. + #Perhaps the target attribute should be an option, perhaps defaulting to + #"_top" as used here? + else : + return None + + def drawGroup(self, group): + if self.verbose: print("### begin _SVGRenderer.drawGroup") + + currGroup = self._canvas.startGroup() + a, b, c, d, e, f = self._tracker.getState()['transform'] + for childNode in group.getContents(): + if isinstance(childNode, UserNode): + node2 = childNode.provideNode() + else: + node2 = childNode + self.drawNode(node2) + self._canvas.transform(a, b, c, d, e, f) + self._canvas.endGroup(currGroup) + + if self.verbose: print("### end _SVGRenderer.drawGroup") + + def drawRect(self, rect): + link_info = self._get_link_info_dict(rect) + svgAttrs = getattr(rect,'_svgAttrs',{}) + if rect.rx == rect.ry == 0: + #plain old rectangle + self._canvas.rect( + rect.x, rect.y, + rect.x+rect.width, rect.y+rect.height, link_info=link_info, **svgAttrs) + else: + #cheat and assume ry = rx; better to generalize + #pdfgen roundRect function. TODO + self._canvas.roundRect( + rect.x, rect.y, + rect.x+rect.width, rect.y+rect.height, + rect.rx, rect.ry, + link_info=link_info, **svgAttrs) + + def drawString(self, stringObj): + S = self._tracker.getState() + text_anchor, x, y, text = S['textAnchor'], stringObj.x, stringObj.y, stringObj.text + self._canvas.drawString(text,x,y,link_info=self._get_link_info_dict(stringObj), + text_anchor=text_anchor, textRenderMode=getattr(stringObj,'textRenderMode',0), + **getattr(stringObj,'_svgAttrs',{})) + + def drawLine(self, line): + if self._canvas._strokeColor: + self._canvas.line(line.x1, line.y1, line.x2, line.y2) + + def drawCircle(self, circle): + self._canvas.circle( circle.cx, circle.cy, circle.r, link_info=self._get_link_info_dict(circle)) + + def drawWedge(self, wedge): + yradius, radius1, yradius1 = wedge._xtraRadii() + if (radius1==0 or radius1 is None) and (yradius1==0 or yradius1 is None) and not wedge.annular: + centerx, centery, radius, startangledegrees, endangledegrees = \ + wedge.centerx, wedge.centery, wedge.radius, wedge.startangledegrees, wedge.endangledegrees + yradius = wedge.yradius or wedge.radius + (x1, y1) = (centerx-radius, centery-yradius) + (x2, y2) = (centerx+radius, centery+yradius) + extent = endangledegrees - startangledegrees + self._canvas.drawArc(x1, y1, x2, y2, startangledegrees, extent, fromcenter=1) + else: + P = wedge.asPolygon() + if isinstance(P,Path): + self.drawPath(P) + else: + self.drawPolygon(P) + + def drawPolyLine(self, p): + if self._canvas._strokeColor: + self._canvas.polyLine(_pointsFromList(p.points)) + + def drawEllipse(self, ellipse): + #need to convert to pdfgen's bounding box representation + x1 = ellipse.cx - ellipse.rx + x2 = ellipse.cx + ellipse.rx + y1 = ellipse.cy - ellipse.ry + y2 = ellipse.cy + ellipse.ry + self._canvas.ellipse(x1,y1,x2,y2, link_info=self._get_link_info_dict(ellipse)) + + def drawPolygon(self, p): + self._canvas.polygon(_pointsFromList(p.points), closed=1, link_info=self._get_link_info_dict(p)) + + def drawPath(self, path, fillMode=FILL_EVEN_ODD): + # print "### drawPath", path.points + from reportlab.graphics.shapes import _renderPath + c = self._canvas + drawFuncs = (c.moveTo, c.lineTo, c.curveTo, c.closePath) + if fillMode is None: + fillMode = getattr(path,'fillMode',FILL_EVEN_ODD) + link_info = self._get_link_info_dict(path) + autoclose = getattr(path,'autoclose','') + def rP(**kwds): + return _renderPath(path, drawFuncs, **kwds) + if autoclose=='svg': + rP() + c._fillAndStroke([], clip=path.isClipPath, link_info=link_info, fillMode=fillMode) + elif autoclose=='pdf': + rP(forceClose=True) + c._fillAndStroke([], clip=path.isClipPath, link_info=link_info, fillMode=fillMode) + else: + isClosed = rP() + if not isClosed: + ofc = c._fillColor + c.setFillColor(None) + try: + link_info = None + c._fillAndStroke([], clip=path.isClipPath, link_info=link_info, fillMode=fillMode) + finally: + c.setFillColor(ofc) + else: + c._fillAndStroke([], clip=path.isClipPath, link_info=link_info, fillMode=fillMode) + + def drawImage(self, image): + path = image.path + if isinstance(path,str): + if not (path and os.path.isfile(path)): return + im = _getImage().open(path) + elif hasattr(path,'convert'): + im = path + else: + return + srcW, srcH = im.size + dstW, dstH = image.width, image.height + if dstW is None: dstW = srcW + if dstH is None: dstH = srcH + self._canvas.drawImage(im, image.x, image.y, dstW, dstH, embed=True) + + def applyStateChanges(self, delta, newState): + """This takes a set of states, and outputs the operators + needed to set those properties""" + + for key, value in delta.items(): + if key == 'transform': + pass + #self._canvas.transform(value[0], value[1], value[2], value[3], value[4], value[5]) + elif key == 'strokeColor': + self._canvas.setStrokeColor(value) + elif key == 'strokeWidth': + self._canvas.setLineWidth(value) + elif key == 'strokeLineCap': #0,1,2 + self._canvas.setLineCap(value) + elif key == 'strokeLineJoin': + self._canvas.setLineJoin(value) + elif key == 'strokeDashArray': + if value: + if isinstance(value,(list,tuple)) and len(value)==2 and isinstance(value[1],(tuple,list)): + phase = value[0] + value = value[1] + else: + phase = 0 + self._canvas.setDash(value,phase) + else: + self._canvas.setDash() + elif key == 'fillColor': + self._canvas.setFillColor(value) + elif key in ['fontSize', 'fontName']: + fontname = delta.get('fontName', self._canvas._font) + fontsize = delta.get('fontSize', self._canvas._fontSize) + self._canvas.setFont(fontname, fontsize) + elif key == 'fillMode': + self._canvas.setFillMode(value) + +def test(outDir='out-svg'): + # print all drawings and their doc strings from the test + # file + if not os.path.isdir(outDir): + os.mkdir(outDir) + #grab all drawings from the test module + from reportlab.graphics import testshapes + drawings = [] + + for funcname in dir(testshapes): + if funcname[0:10] == 'getDrawing': + func = getattr(testshapes,funcname) + drawing = func() + docstring = getattr(func,'__doc__','') + drawings.append((drawing, docstring)) + + i = 0 + for (d, docstring) in drawings: + filename = os.path.join(outDir,'renderSVG_%d.svg' % i) + drawToFile(d, filename) + i += 1 + + from reportlab.graphics.testshapes import getDrawing01 + d = getDrawing01() + drawToFile(d, os.path.join(outDir,"test.svg")) + + from reportlab.lib.corp import RL_CorpLogo + from reportlab.graphics.shapes import Drawing + + rl = RL_CorpLogo() + d = Drawing(rl.width,rl.height) + d.add(rl) + drawToFile(d, os.path.join(outDir,"corplogo.svg")) + +if __name__=='__main__': + test() diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/renderbase.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/renderbase.py new file mode 100644 index 0000000000000000000000000000000000000000..2b9d7264669abc11468b053ca9519820be1cc114 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/renderbase.py @@ -0,0 +1,356 @@ +#Copyright ReportLab Europe Ltd. 2000-2021 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/graphics/renderbase.py + +__version__='3.13.0' +__doc__='''Superclass for renderers to factor out common functionality and default implementations.''' + +from reportlab.graphics.shapes import * +from reportlab.lib.validators import DerivedValue +from reportlab import rl_config + +from . transform import mmult, inverse + +def getStateDelta(shape): + """Used to compute when we need to change the graphics state. + For example, if we have two adjacent red shapes we don't need + to set the pen color to red in between. Returns the effect + the given shape would have on the graphics state""" + delta = {} + for prop, value in shape.getProperties().items(): + if prop in STATE_DEFAULTS: + delta[prop] = value + return delta + +class StateTracker: + """Keeps a stack of transforms and state + properties. It can contain any properties you + want, but the keys 'transform' and 'ctm' have + special meanings. The getCTM() + method returns the current transformation + matrix at any point, without needing to + invert matrixes when you pop.""" + def __init__(self, defaults=None, defaultObj=None): + # one stack to keep track of what changes... + self._deltas = [] + + # and another to keep track of cumulative effects. Last one in + # list is the current graphics state. We put one in to simplify + # loops below. + self._combined = [] + if defaults is None: + defaults = STATE_DEFAULTS.copy() + if defaultObj: + for k in STATE_DEFAULTS.keys(): + a = 'initial'+k[:1].upper()+k[1:] + if hasattr(defaultObj,a): + defaults[k] = getattr(defaultObj,a) + #ensure that if we have a transform, we have a CTM + if 'transform' in defaults: + defaults['ctm'] = defaults['transform'] + self._combined.append(defaults) + + def _applyDefaultObj(self,d): + return d + + def push(self,delta): + """Take a new state dictionary of changes and push it onto + the stack. After doing this, the combined state is accessible + through getState()""" + + newstate = self._combined[-1].copy() + for key, value in delta.items(): + if key == 'transform': #do cumulative matrix + newstate['transform'] = delta['transform'] + newstate['ctm'] = mmult(self._combined[-1]['ctm'], delta['transform']) + #print 'statetracker transform = (%0.2f, %0.2f, %0.2f, %0.2f, %0.2f, %0.2f)' % tuple(newstate['transform']) + #print 'statetracker ctm = (%0.2f, %0.2f, %0.2f, %0.2f, %0.2f, %0.2f)' % tuple(newstate['ctm']) + + else: #just overwrite it + newstate[key] = value + + self._combined.append(newstate) + self._deltas.append(delta) + + def pop(self): + """steps back one, and returns a state dictionary with the + deltas to reverse out of wherever you are. Depending + on your back end, you may not need the return value, + since you can get the complete state afterwards with getState()""" + del self._combined[-1] + newState = self._combined[-1] + lastDelta = self._deltas[-1] + del self._deltas[-1] + #need to diff this against the last one in the state + reverseDelta = {} + #print 'pop()...' + for key, curValue in lastDelta.items(): + #print ' key=%s, value=%s' % (key, curValue) + prevValue = newState[key] + if prevValue != curValue: + #print ' state popping "%s"="%s"' % (key, curValue) + if key == 'transform': + reverseDelta[key] = inverse(lastDelta['transform']) + else: #just return to previous state + reverseDelta[key] = prevValue + return reverseDelta + + def getState(self): + "returns the complete graphics state at this point" + return self._combined[-1] + + def getCTM(self): + "returns the current transformation matrix at this point""" + return self._combined[-1]['ctm'] + + def __getitem__(self,key): + "returns the complete graphics state value of key at this point" + return self._combined[-1][key] + + def __setitem__(self,key,value): + "sets the complete graphics state value of key to value" + self._combined[-1][key] = value + +def testStateTracker(): + print('Testing state tracker') + defaults = {'fillColor':None, 'strokeColor':None,'fontName':None, 'transform':[1,0,0,1,0,0]} + from reportlab.graphics.shapes import _baseGFontName + deltas = [ + {'fillColor':'red'}, + {'fillColor':'green', 'strokeColor':'blue','fontName':_baseGFontName}, + {'transform':[0.5,0,0,0.5,0,0]}, + {'transform':[0.5,0,0,0.5,2,3]}, + {'strokeColor':'red'} + ] + + st = StateTracker(defaults) + print('initial:', st.getState()) + print() + for delta in deltas: + print('pushing:', delta) + st.push(delta) + print('state: ',st.getState(),'\n') + + for delta in deltas: + print('popping:',st.pop()) + print('state: ',st.getState(),'\n') + +def _expandUserNode(node,canvas): + if isinstance(node, UserNode): + try: + if hasattr(node,'_canvas'): + ocanvas = 1 + else: + node._canvas = canvas + ocanvas = None + onode = node + node = node.provideNode() + finally: + if not ocanvas: del onode._canvas + return node + +def renderScaledDrawing(d): + renderScale = d.renderScale + if renderScale!=1.0: + o = d + d = d.__class__(o.width*renderScale,o.height*renderScale) + d.__dict__ = o.__dict__.copy() + d.scale(renderScale,renderScale) + d.renderScale = 1.0 + return d + +class Renderer: + """Virtual superclass for graphics renderers.""" + + def undefined(self, operation): + raise ValueError("%s operation not defined at superclass class=%s" %(operation, self.__class__)) + + def draw(self, drawing, canvas, x=0, y=0, showBoundary=rl_config._unset_): + """This is the top level function, which draws the drawing at the given + location. The recursive part is handled by drawNode.""" + self._tracker = StateTracker(defaultObj=drawing) + #stash references for ease of communication + if showBoundary is rl_config._unset_: showBoundary=rl_config.showBoundary + self._canvas = canvas + canvas.__dict__['_drawing'] = self._drawing = drawing + drawing._parent = None + try: + #bounding box + if showBoundary: + if hasattr(canvas,'drawBoundary'): + canvas.drawBoundary(showBoundary,x,y,drawing.width,drawing.height) + else: + canvas.rect(x, y, drawing.width, drawing.height) + canvas.saveState() + self.initState(x,y) #this is the push() + self.drawNode(drawing) + self.pop() + canvas.restoreState() + finally: + #remove any circular references + del self._canvas, self._drawing, canvas._drawing, drawing._parent, self._tracker + + def initState(self,x,y): + deltas = self._tracker._combined[-1] + deltas['transform'] = tuple(list(deltas['transform'])[:4])+(x,y) + self._tracker.push(deltas) + self.applyStateChanges(deltas, {}) + + def pop(self): + self._tracker.pop() + + def drawNode(self, node): + """This is the recursive method called for each node + in the tree""" + # Undefined here, but with closer analysis probably can be handled in superclass + self.undefined("drawNode") + + def getStateValue(self, key): + """Return current state parameter for given key""" + currentState = self._tracker._combined[-1] + return currentState[key] + + def fillDerivedValues(self, node): + """Examine a node for any values which are Derived, + and replace them with their calculated values. + Generally things may look at the drawing or their + parent. + + """ + for key, value in node.__dict__.items(): + if isinstance(value, DerivedValue): + #just replace with default for key? + #print ' fillDerivedValues(%s)' % key + newValue = value.getValue(self, key) + #print ' got value of %s' % newValue + node.__dict__[key] = newValue + + def drawNodeDispatcher(self, anode): + """dispatch on the node's (super) class: shared code""" + canvas = getattr(self,'_canvas',None) + + try: + # replace UserNode with its contents + node = _expandUserNode(anode,canvas) + if not node: return + if hasattr(node,'_canvas'): + ocanvas = 1 + else: + node._canvas = canvas + ocanvas = None + nodeparent = node is not anode and not hasattr(node,'_parent') + if nodeparent: node._parent = anode + + self.fillDerivedValues(node) + dtcb = getattr(node,'_drawTimeCallback',None) + if dtcb: + dtcb(node,canvas=canvas,renderer=self) + #draw the object, or recurse + if isinstance(node, Line): + self.drawLine(node) + elif isinstance(node, Path): + self.drawPath(node) + elif isinstance(node, String): + self.drawString(node) + elif isinstance(node, Group): + self.drawGroup(node) + elif isinstance(node, Rect): + self.drawRect(node) + elif isinstance(node, Image): + self.drawImage(node) + elif isinstance(node, Circle): + self.drawCircle(node) + elif isinstance(node, Ellipse): + self.drawEllipse(node) + elif isinstance(node, PolyLine): + self.drawPolyLine(node) + elif isinstance(node, Polygon): + self.drawPolygon(node) + elif isinstance(node, Wedge): + self.drawWedge(node) + elif isinstance(node, DirectDraw): + node.drawDirectly(self) + else: + print('DrawingError','Unexpected element %s in drawing!' % str(node)) + finally: + if not ocanvas: del node._canvas + if nodeparent: del node._parent + + _restores = {'stroke':'_stroke','stroke_width': '_lineWidth','stroke_linecap':'_lineCap', + 'stroke_linejoin':'_lineJoin','fill':'_fill','font_family':'_font', + 'font_size':'_fontSize'} + + def drawGroup(self, group): + # just do the contents. Some renderers might need to override this + # if they need a flipped transform + canvas = getattr(self,'_canvas',None) + for anode in group.getContents(): + node = _expandUserNode(anode,canvas) + if not node: continue + + #here is where we do derived values - this seems to get everything. Touch wood. + self.fillDerivedValues(node) + try: + if hasattr(node,'_canvas'): + ocanvas = 1 + else: + node._canvas = canvas + ocanvas = None + if node is not anode: + anode._parent = group + node._parent = anode + else: + node._parent = group + self.drawNode(node) + finally: + if node is not anode: del anode._parent + del node._parent + if not ocanvas: del node._canvas + + def drawWedge(self, wedge): + # by default ask the wedge to make a polygon of itself and draw that! + #print "drawWedge" + P = wedge.asPolygon() + if isinstance(P,Path): + self.drawPath(P) + else: + self.drawPolygon(P) + + def drawPath(self, path): + polygons = path.asPolygons() + for polygon in polygons: + self.drawPolygon(polygon) + + def drawRect(self, rect): + # could be implemented in terms of polygon + self.undefined("drawRect") + + def drawLine(self, line): + self.undefined("drawLine") + + def drawCircle(self, circle): + self.undefined("drawCircle") + + def drawPolyLine(self, p): + self.undefined("drawPolyLine") + + def drawEllipse(self, ellipse): + self.undefined("drawEllipse") + + def drawPolygon(self, p): + self.undefined("drawPolygon") + + def drawString(self, stringObj): + self.undefined("drawString") + + def applyStateChanges(self, delta, newState): + """This takes a set of states, and outputs the operators + needed to set those properties""" + self.undefined("applyStateChanges") + + def drawImage(self,*args,**kwds): + raise NotImplementedError('drawImage') + +if __name__=='__main__': + print("this file has no script interpretation") + print(__doc__) diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/__init__.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c16b3b27f8b6bc0483be20423de078e44ca1b219 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/__init__.py @@ -0,0 +1 @@ +__doc__="""Example drawings to review, used in autogenerated docs""" diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/bubble.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/bubble.py new file mode 100644 index 0000000000000000000000000000000000000000..57bc012a8960ea4fae0240145f80f5cc65671b1a --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/bubble.py @@ -0,0 +1,73 @@ +#Autogenerated by ReportLab guiedit do not edit +from reportlab.graphics.charts.legends import Legend +from reportlab.graphics.charts.lineplots import ScatterPlot +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin +from reportlab.graphics.charts.textlabels import Label +from reportlab.graphics.samples.excelcolors import * + +class Bubble(_DrawingEditorMixin,Drawing): + def __init__(self,width=200,height=150,*args,**kw): + Drawing.__init__(self,width,height,*args,**kw) + self._add(self,ScatterPlot(),name='chart',validate=None,desc="The main chart") + self.chart.width = 115 + self.chart.height = 80 + self.chart.x = 30 + self.chart.y = 40 + self.chart.lines[0].strokeColor = color01 + self.chart.lines[1].strokeColor = color02 + self.chart.lines[2].strokeColor = color03 + self.chart.lines[3].strokeColor = color04 + self.chart.lines[4].strokeColor = color05 + self.chart.lines[5].strokeColor = color06 + self.chart.lines[6].strokeColor = color07 + self.chart.lines[7].strokeColor = color08 + self.chart.lines[8].strokeColor = color09 + self.chart.lines[9].strokeColor = color10 + self.chart.lines.symbol.kind ='Circle' + self.chart.lines.symbol.size = 15 + self.chart.fillColor = backgroundGrey + self.chart.lineLabels.fontName = 'Helvetica' + self.chart.xValueAxis.labels.fontName = 'Helvetica' + self.chart.xValueAxis.labels.fontSize = 7 + self.chart.xValueAxis.forceZero = 0 + self.chart.data = [((100,100), (200,200), (250,210), (300,300), (350,450))] + self.chart.xValueAxis.avoidBoundFrac = 1 + self.chart.xValueAxis.gridEnd = 115 + self.chart.xValueAxis.tickDown = 3 + self.chart.xValueAxis.visibleGrid = 1 + self.chart.yValueAxis.tickLeft = 3 + self.chart.yValueAxis.labels.fontName = 'Helvetica' + self.chart.yValueAxis.labels.fontSize = 7 + self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") + self.Title.fontName = 'Helvetica-Bold' + self.Title.fontSize = 7 + self.Title.x = 100 + self.Title.y = 135 + self.Title._text = 'Chart Title' + self.Title.maxWidth = 180 + self.Title.height = 20 + self.Title.textAnchor ='middle' + self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") + self.Legend.colorNamePairs = [(color01, 'Widgets')] + self.Legend.fontName = 'Helvetica' + self.Legend.fontSize = 7 + self.Legend.x = 153 + self.Legend.y = 85 + self.Legend.dxTextSpace = 5 + self.Legend.dy = 5 + self.Legend.dx = 5 + self.Legend.deltay = 5 + self.Legend.alignment ='right' + self.chart.lineLabelFormat = None + self.chart.xLabel = 'X Axis' + self.chart.y = 30 + self.chart.yLabel = 'Y Axis' + self.chart.yValueAxis.labelTextFormat = '%d' + self.chart.yValueAxis.forceZero = 1 + self.chart.xValueAxis.forceZero = 1 + + + self._add(self,0,name='preview',validate=None,desc=None) + +if __name__=="__main__": #NORUNTESTS + Bubble().save(formats=['pdf'],outDir=None,fnRoot='bubble') diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/clustered_bar.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/clustered_bar.py new file mode 100644 index 0000000000000000000000000000000000000000..e57836134f7f02ea0c32af0e03b313a59ac1c41d --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/clustered_bar.py @@ -0,0 +1,84 @@ +#Autogenerated by ReportLab guiedit do not edit +from reportlab.graphics.charts.legends import Legend +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.charts.barcharts import HorizontalBarChart +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin +from reportlab.graphics.charts.textlabels import Label + +class ClusteredBar(_DrawingEditorMixin,Drawing): + def __init__(self,width=200,height=150,*args,**kw): + Drawing.__init__(self,width,height,*args,**kw) + self._add(self,HorizontalBarChart(),name='chart',validate=None,desc="The main chart") + self.chart.width = 115 + self.chart.height = 80 + self.chart.x = 30 + self.chart.y = 40 + self.chart.bars[0].fillColor = color01 + self.chart.bars[1].fillColor = color02 + self.chart.bars[2].fillColor = color03 + self.chart.bars[3].fillColor = color04 + self.chart.bars[4].fillColor = color05 + self.chart.bars[5].fillColor = color06 + self.chart.bars[6].fillColor = color07 + self.chart.bars[7].fillColor = color08 + self.chart.bars[8].fillColor = color09 + self.chart.bars[9].fillColor = color10 + self.chart.fillColor = backgroundGrey + self.chart.barLabels.fontName = 'Helvetica' + self.chart.valueAxis.labels.fontName = 'Helvetica' + self.chart.valueAxis.labels.fontSize = 6 + self.chart.valueAxis.forceZero = 1 + self.chart.data = [(100, 150, 180), (125, 180, 200)] + self.chart.groupSpacing = 15 + self.chart.valueAxis.avoidBoundFrac = 1 + self.chart.valueAxis.gridEnd = 80 + self.chart.valueAxis.tickDown = 3 + self.chart.valueAxis.visibleGrid = 1 + self.chart.categoryAxis.categoryNames = ['North', 'South', 'Central'] + self.chart.categoryAxis.tickLeft = 3 + self.chart.categoryAxis.labels.fontName = 'Helvetica' + self.chart.categoryAxis.labels.fontSize = 6 + self.chart.categoryAxis.labels.dx = -3 + self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") + self.Title.fontName = 'Helvetica-Bold' + self.Title.fontSize = 7 + self.Title.x = 100 + self.Title.y = 135 + self.Title._text = 'Chart Title' + self.Title.maxWidth = 180 + self.Title.height = 20 + self.Title.textAnchor ='middle' + self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") + self.Legend.colorNamePairs = [(color01, 'Widgets'), (color02, 'Sprockets')] + self.Legend.fontName = 'Helvetica' + self.Legend.fontSize = 7 + self.Legend.x = 153 + self.Legend.y = 85 + self.Legend.dxTextSpace = 5 + self.Legend.dy = 5 + self.Legend.dx = 5 + self.Legend.deltay = 5 + self.Legend.alignment ='right' + self._add(self,Label(),name='XLabel',validate=None,desc="The label on the horizontal axis") + self.XLabel.fontName = 'Helvetica' + self.XLabel.fontSize = 7 + self.XLabel.x = 85 + self.XLabel.y = 10 + self.XLabel.textAnchor ='middle' + self.XLabel.maxWidth = 100 + self.XLabel.height = 20 + self.XLabel._text = "X Axis" + self._add(self,Label(),name='YLabel',validate=None,desc="The label on the vertical axis") + self.YLabel.fontName = 'Helvetica' + self.YLabel.fontSize = 7 + self.YLabel.x = 12 + self.YLabel.y = 80 + self.YLabel.angle = 90 + self.YLabel.textAnchor ='middle' + self.YLabel.maxWidth = 100 + self.YLabel.height = 20 + self.YLabel._text = "Y Axis" + self._add(self,0,name='preview',validate=None,desc=None) + +if __name__=="__main__": #NORUNTESTS + ClusteredBar().save(formats=['pdf'],outDir=None,fnRoot='clustered_bar') diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/clustered_column.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/clustered_column.py new file mode 100644 index 0000000000000000000000000000000000000000..055f1ea7754f978c55b33195dab184650e015eda --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/clustered_column.py @@ -0,0 +1,83 @@ +#Autogenerated by ReportLab guiedit do not edit +from reportlab.graphics.charts.legends import Legend +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.charts.barcharts import VerticalBarChart +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin +from reportlab.graphics.charts.textlabels import Label + +class ClusteredColumn(_DrawingEditorMixin,Drawing): + def __init__(self,width=200,height=150,*args,**kw): + Drawing.__init__(self,width,height,*args,**kw) + self._add(self,VerticalBarChart(),name='chart',validate=None,desc="The main chart") + self.chart.width = 115 + self.chart.height = 80 + self.chart.x = 30 + self.chart.y = 40 + self.chart.bars[0].fillColor = color01 + self.chart.bars[1].fillColor = color02 + self.chart.bars[2].fillColor = color03 + self.chart.bars[3].fillColor = color04 + self.chart.bars[4].fillColor = color05 + self.chart.bars[5].fillColor = color06 + self.chart.bars[6].fillColor = color07 + self.chart.bars[7].fillColor = color08 + self.chart.bars[8].fillColor = color09 + self.chart.bars[9].fillColor = color10 + self.chart.fillColor = backgroundGrey + self.chart.barLabels.fontName = 'Helvetica' + self.chart.valueAxis.labels.fontName = 'Helvetica' + self.chart.valueAxis.labels.fontSize = 7 + self.chart.valueAxis.forceZero = 1 + self.chart.data = [(100, 150, 180), (125, 180, 200)] + self.chart.groupSpacing = 15 + self.chart.valueAxis.avoidBoundFrac = 1 + self.chart.valueAxis.gridEnd = 115 + self.chart.valueAxis.tickLeft = 3 + self.chart.valueAxis.visibleGrid = 1 + self.chart.categoryAxis.categoryNames = ['North', 'South', 'Central'] + self.chart.categoryAxis.tickDown = 3 + self.chart.categoryAxis.labels.fontName = 'Helvetica' + self.chart.categoryAxis.labels.fontSize = 7 + self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") + self.Title.fontName = 'Helvetica-Bold' + self.Title.fontSize = 7 + self.Title.x = 100 + self.Title.y = 135 + self.Title._text = 'Chart Title' + self.Title.maxWidth = 180 + self.Title.height = 20 + self.Title.textAnchor ='middle' + self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") + self.Legend.colorNamePairs = [(color01, 'Widgets'), (color02, 'Sprockets')] + self.Legend.fontName = 'Helvetica' + self.Legend.fontSize = 7 + self.Legend.x = 153 + self.Legend.y = 85 + self.Legend.dxTextSpace = 5 + self.Legend.dy = 5 + self.Legend.dx = 5 + self.Legend.deltay = 5 + self.Legend.alignment ='right' + self._add(self,Label(),name='XLabel',validate=None,desc="The label on the horizontal axis") + self.XLabel.fontName = 'Helvetica' + self.XLabel.fontSize = 7 + self.XLabel.x = 85 + self.XLabel.y = 10 + self.XLabel.textAnchor ='middle' + self.XLabel.maxWidth = 100 + self.XLabel.height = 20 + self.XLabel._text = "X Axis" + self._add(self,Label(),name='YLabel',validate=None,desc="The label on the vertical axis") + self.YLabel.fontName = 'Helvetica' + self.YLabel.fontSize = 7 + self.YLabel.x = 12 + self.YLabel.y = 80 + self.YLabel.angle = 90 + self.YLabel.textAnchor ='middle' + self.YLabel.maxWidth = 100 + self.YLabel.height = 20 + self.YLabel._text = "Y Axis" + self._add(self,0,name='preview',validate=None,desc=None) + +if __name__=="__main__": #NORUNTESTS + ClusteredColumn().save(formats=['pdf'],outDir=None,fnRoot='clustered_column') diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/excelcolors.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/excelcolors.py new file mode 100644 index 0000000000000000000000000000000000000000..23b0213cd0ca3f3909182991e47139a6f440e6ff --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/excelcolors.py @@ -0,0 +1,45 @@ +# define standard colors to mimic those used by Microsoft Excel +from reportlab.lib.colors import PCMYKColor + +#colour names as comments at the end of each line are as a memory jogger ONLY +#NOT HTML named colours! + +#Main colours as used for bars etc +color01 = PCMYKColor(40,40,0,0) # Lavender +color02 = PCMYKColor(0,66,33,39) # Maroon +color03 = PCMYKColor(0,0,20,0) # Yellow +color04 = PCMYKColor(20,0,0,0) # Cyan +color05 = PCMYKColor(0,100,0,59) # Purple +color06 = PCMYKColor(0,49,49,0) # Salmon +color07 = PCMYKColor(100,49,0,19) # Blue +color08 = PCMYKColor(20,20,0,0) # PaleLavender +color09 = PCMYKColor(100,100,0,49) # NavyBlue +color10 = PCMYKColor(0,100,0,0) # Purple + +#Highlight colors - eg for the tops of bars +color01Light = PCMYKColor(39,39,0,25) # Light Lavender +color02Light = PCMYKColor(0,66,33,54) # Light Maroon +color03Light = PCMYKColor(0,0,19,25) # Light Yellow +color04Light = PCMYKColor(19,0,0,25) # Light Cyan +color05Light = PCMYKColor(0,100,0,69) # Light Purple +color06Light = PCMYKColor(0,49,49,25) # Light Salmon +color07Light = PCMYKColor(100,49,0,39) # Light Blue +color08Light = PCMYKColor(19,19,0,25) # Light PaleLavender +color09Light = PCMYKColor(100,100,0,62) # Light NavyBlue +color10Light = PCMYKColor(0,100,0,25) # Light Purple + +#Lowlight colors - eg for the sides of bars +color01Dark = PCMYKColor(39,39,0,49) # Dark Lavender +color02Dark = PCMYKColor(0,66,33,69) # Dark Maroon +color03Dark = PCMYKColor(0,0,20,49) # Dark Yellow +color04Dark = PCMYKColor(20,0,0,49) # Dark Cyan +color05Dark = PCMYKColor(0,100,0,80) # Dark Purple +color06Dark = PCMYKColor(0,50,50,49) # Dark Salmon +color07Dark = PCMYKColor(100,50,0,59) # Dark Blue +color08Dark = PCMYKColor(20,20,0,49) # Dark PaleLavender +color09Dark = PCMYKColor(100,100,0,79) # Dark NavyBlue +color10Dark = PCMYKColor(0,100,0,49) # Dark Purple + +#for standard grey backgrounds +backgroundGrey = PCMYKColor(0,0,0,24) + diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/exploded_pie.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/exploded_pie.py new file mode 100644 index 0000000000000000000000000000000000000000..c4d99bc7b582bee4feea55449cd87759b2c9e93b --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/exploded_pie.py @@ -0,0 +1,65 @@ +#Autogenerated by ReportLab guiedit do not edit +from reportlab.graphics.charts.piecharts import Pie +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.widgets.grids import ShadedRect +from reportlab.graphics.charts.legends import Legend +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin +from reportlab.graphics.charts.textlabels import Label + +class ExplodedPie(_DrawingEditorMixin,Drawing): + def __init__(self,width=200,height=150,*args,**kw): + Drawing.__init__(self,width,height,*args,**kw) + self._add(self,Pie(),name='chart',validate=None,desc="The main chart") + self.chart.width = 100 + self.chart.height = 100 + self.chart.x = 25 + self.chart.y = 25 + self.chart.slices[0].fillColor = color01 + self.chart.slices[1].fillColor = color02 + self.chart.slices[2].fillColor = color03 + self.chart.slices[3].fillColor = color04 + self.chart.slices[4].fillColor = color05 + self.chart.slices[5].fillColor = color06 + self.chart.slices[6].fillColor = color07 + self.chart.slices[7].fillColor = color08 + self.chart.slices[8].fillColor = color09 + self.chart.slices[9].fillColor = color10 + self.chart.data = (100, 150, 180) + self.chart.startAngle = -90 + self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") + self.Title.fontName = 'Helvetica-Bold' + self.Title.fontSize = 7 + self.Title.x = 100 + self.Title.y = 135 + self.Title._text = 'Chart Title' + self.Title.maxWidth = 180 + self.Title.height = 20 + self.Title.textAnchor ='middle' + self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") + self.Legend.colorNamePairs = [(color01, 'North'), (color02, 'South'), (color03, 'Central')] + self.Legend.fontName = 'Helvetica' + self.Legend.fontSize = 7 + self.Legend.x = 160 + self.Legend.y = 85 + self.Legend.dxTextSpace = 5 + self.Legend.dy = 5 + self.Legend.dx = 5 + self.Legend.deltay = 5 + self.Legend.alignment ='right' + self.Legend.columnMaximum = 10 + self.chart.slices.strokeWidth = 1 + self.chart.slices.fontName = 'Helvetica' + self.background = ShadedRect() + self.background.fillColorStart = backgroundGrey + self.background.fillColorEnd = backgroundGrey + self.background.numShades = 1 + self.background.strokeWidth = 0.5 + self.background.x = 20 + self.background.y = 20 + self.chart.slices.popout = 5 + self.background.height = 110 + self.background.width = 110 + self._add(self,0,name='preview',validate=None,desc=None) + +if __name__=="__main__": #NORUNTESTS + ExplodedPie().save(formats=['pdf'],outDir=None,fnRoot='exploded_pie') diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/filled_radar.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/filled_radar.py new file mode 100644 index 0000000000000000000000000000000000000000..7761a4a55a36a7d58eb4aab667ce8f262944d313 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/filled_radar.py @@ -0,0 +1,54 @@ +#Autogenerated by ReportLab guiedit do not edit +from reportlab.graphics.charts.legends import Legend +from reportlab.graphics.charts.spider import SpiderChart +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin +from reportlab.graphics.charts.textlabels import Label +from reportlab.graphics.samples.excelcolors import * + +class FilledRadarChart(_DrawingEditorMixin,Drawing): + def __init__(self,width=200,height=150,*args,**kw): + Drawing.__init__(self,width,height,*args,**kw) + self._add(self,SpiderChart(),name='chart',validate=None,desc="The main chart") + self.chart.width = 90 + self.chart.height = 90 + self.chart.x = 45 + self.chart.y = 25 + self.chart.strands[0].fillColor = color01 + self.chart.strands[1].fillColor = color02 + self.chart.strands[2].fillColor = color03 + self.chart.strands[3].fillColor = color04 + self.chart.strands[4].fillColor = color05 + self.chart.strands[5].fillColor = color06 + self.chart.strands[6].fillColor = color07 + self.chart.strands[7].fillColor = color08 + self.chart.strands[8].fillColor = color09 + self.chart.strands[9].fillColor = color10 + self.chart.strandLabels.fontName = 'Helvetica' + self.chart.strandLabels.fontSize = 6 + self.chart.fillColor = backgroundGrey + self.chart.data = [(125, 180, 200), (100, 150, 180)] + self.chart.labels = ['North', 'South', 'Central'] + self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") + self.Title.fontName = 'Helvetica-Bold' + self.Title.fontSize = 7 + self.Title.x = 100 + self.Title.y = 135 + self.Title._text = 'Chart Title' + self.Title.maxWidth = 180 + self.Title.height = 20 + self.Title.textAnchor ='middle' + self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") + self.Legend.colorNamePairs = [(color01, 'Widgets'), (color02, 'Sprockets')] + self.Legend.fontName = 'Helvetica' + self.Legend.fontSize = 7 + self.Legend.x = 153 + self.Legend.y = 85 + self.Legend.dxTextSpace = 5 + self.Legend.dy = 5 + self.Legend.dx = 5 + self.Legend.deltay = 5 + self.Legend.alignment ='right' + self._add(self,0,name='preview',validate=None,desc=None) + +if __name__=="__main__": #NORUNTESTS + FilledRadarChart().save(formats=['pdf'],outDir=None,fnRoot='filled_radar') diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/line_chart.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/line_chart.py new file mode 100644 index 0000000000000000000000000000000000000000..dc6bcab005c53378021677396817a432c107a14c --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/line_chart.py @@ -0,0 +1,83 @@ +#Autogenerated by ReportLab guiedit do not edit +from reportlab.graphics.charts.legends import Legend +from reportlab.graphics.charts.lineplots import LinePlot +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin +from reportlab.graphics.charts.textlabels import Label +from reportlab.graphics.samples.excelcolors import * + +class LineChart(_DrawingEditorMixin,Drawing): + def __init__(self,width=200,height=150,*args,**kw): + Drawing.__init__(self,width,height,*args,**kw) + self._add(self,LinePlot(),name='chart',validate=None,desc="The main chart") + self.chart.width = 115 + self.chart.height = 80 + self.chart.x = 30 + self.chart.y = 40 + self.chart.lines[0].strokeColor = color01 + self.chart.lines[1].strokeColor = color02 + self.chart.lines[2].strokeColor = color03 + self.chart.lines[3].strokeColor = color04 + self.chart.lines[4].strokeColor = color05 + self.chart.lines[5].strokeColor = color06 + self.chart.lines[6].strokeColor = color07 + self.chart.lines[7].strokeColor = color08 + self.chart.lines[8].strokeColor = color09 + self.chart.lines[9].strokeColor = color10 + self.chart.fillColor = backgroundGrey + self.chart.lineLabels.fontName = 'Helvetica' + self.chart.xValueAxis.labels.fontName = 'Helvetica' + self.chart.xValueAxis.labels.fontSize = 7 + self.chart.xValueAxis.forceZero = 0 + self.chart.data = [((0, 50), (100,100), (200,200), (250,210), (300,300), (400,500)), ((0, 150), (100,200), (200,300), (250,200), (300,400), (400, 600))] + self.chart.xValueAxis.avoidBoundFrac = 1 + self.chart.xValueAxis.gridEnd = 115 + self.chart.xValueAxis.tickDown = 3 + self.chart.xValueAxis.visibleGrid = 1 + self.chart.yValueAxis.tickLeft = 3 + self.chart.yValueAxis.labels.fontName = 'Helvetica' + self.chart.yValueAxis.labels.fontSize = 7 + self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") + self.Title.fontName = 'Helvetica-Bold' + self.Title.fontSize = 7 + self.Title.x = 100 + self.Title.y = 135 + self.Title._text = 'Chart Title' + self.Title.maxWidth = 180 + self.Title.height = 20 + self.Title.textAnchor ='middle' + self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") + self.Legend.colorNamePairs = [(color01, 'Widgets'), (color02, 'Sprockets')] + self.Legend.fontName = 'Helvetica' + self.Legend.fontSize = 7 + self.Legend.x = 153 + self.Legend.y = 85 + self.Legend.dxTextSpace = 5 + self.Legend.dy = 5 + self.Legend.dx = 5 + self.Legend.deltay = 5 + self.Legend.alignment ='right' + self._add(self,Label(),name='XLabel',validate=None,desc="The label on the horizontal axis") + self.XLabel.fontName = 'Helvetica' + self.XLabel.fontSize = 7 + self.XLabel.x = 85 + self.XLabel.y = 10 + self.XLabel.textAnchor ='middle' + self.XLabel.maxWidth = 100 + self.XLabel.height = 20 + self.XLabel._text = "X Axis" + self._add(self,Label(),name='YLabel',validate=None,desc="The label on the vertical axis") + self.YLabel.fontName = 'Helvetica' + self.YLabel.fontSize = 7 + self.YLabel.x = 12 + self.YLabel.y = 80 + self.YLabel.angle = 90 + self.YLabel.textAnchor ='middle' + self.YLabel.maxWidth = 100 + self.YLabel.height = 20 + self.YLabel._text = "Y Axis" + self.chart.yValueAxis.forceZero = 1 + self.chart.xValueAxis.forceZero = 1 + self._add(self,0,name='preview',validate=None,desc=None) + +if __name__=="__main__": #NORUNTESTS + LineChart().save(formats=['pdf'],outDir=None,fnRoot='line_chart') diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/linechart_with_markers.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/linechart_with_markers.py new file mode 100644 index 0000000000000000000000000000000000000000..981e69ac47a323d4a56c669008b859403a590985 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/linechart_with_markers.py @@ -0,0 +1,94 @@ +#Autogenerated by ReportLab guiedit do not edit +from reportlab.graphics.charts.legends import Legend +from reportlab.graphics.charts.lineplots import LinePlot +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin +from reportlab.graphics.widgets.markers import makeMarker +from reportlab.graphics.charts.textlabels import Label +from reportlab.graphics.samples.excelcolors import * + +class LineChartWithMarkers(_DrawingEditorMixin,Drawing): + def __init__(self,width=200,height=150,*args,**kw): + Drawing.__init__(self,width,height,*args,**kw) + self._add(self,LinePlot(),name='chart',validate=None,desc="The main chart") + self.chart.width = 115 + self.chart.height = 80 + self.chart.x = 30 + self.chart.y = 40 + self.chart.lines[0].strokeColor = color01 + self.chart.lines[1].strokeColor = color02 + self.chart.lines[2].strokeColor = color03 + self.chart.lines[3].strokeColor = color04 + self.chart.lines[4].strokeColor = color05 + self.chart.lines[5].strokeColor = color06 + self.chart.lines[6].strokeColor = color07 + self.chart.lines[7].strokeColor = color08 + self.chart.lines[8].strokeColor = color09 + self.chart.lines[9].strokeColor = color10 + self.chart.lines[0].symbol = makeMarker('FilledSquare') + self.chart.lines[1].symbol = makeMarker('FilledDiamond') + self.chart.lines[2].symbol = makeMarker('FilledStarFive') + self.chart.lines[3].symbol = makeMarker('FilledTriangle') + self.chart.lines[4].symbol = makeMarker('FilledCircle') + self.chart.lines[5].symbol = makeMarker('FilledPentagon') + self.chart.lines[6].symbol = makeMarker('FilledStarSix') + self.chart.lines[7].symbol = makeMarker('FilledHeptagon') + self.chart.lines[8].symbol = makeMarker('FilledOctagon') + self.chart.lines[9].symbol = makeMarker('FilledCross') + self.chart.fillColor = backgroundGrey + self.chart.lineLabels.fontName = 'Helvetica' + self.chart.xValueAxis.labels.fontName = 'Helvetica' + self.chart.xValueAxis.labels.fontSize = 7 + self.chart.xValueAxis.forceZero = 0 + self.chart.data = [((0, 50), (100,100), (200,200), (250,210), (300,300), (400,500)), ((0, 150), (100,200), (200,300), (250,200), (300,400), (400, 600))] + self.chart.xValueAxis.avoidBoundFrac = 1 + self.chart.xValueAxis.gridEnd = 115 + self.chart.xValueAxis.tickDown = 3 + self.chart.xValueAxis.visibleGrid = 1 + self.chart.yValueAxis.tickLeft = 3 + self.chart.yValueAxis.labels.fontName = 'Helvetica' + self.chart.yValueAxis.labels.fontSize = 7 + self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") + self.Title.fontName = 'Helvetica-Bold' + self.Title.fontSize = 7 + self.Title.x = 100 + self.Title.y = 135 + self.Title._text = 'Chart Title' + self.Title.maxWidth = 180 + self.Title.height = 20 + self.Title.textAnchor ='middle' + self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") + self.Legend.colorNamePairs = [(color01, 'Widgets'), (color02, 'Sprockets')] + self.Legend.fontName = 'Helvetica' + self.Legend.fontSize = 7 + self.Legend.x = 153 + self.Legend.y = 85 + self.Legend.dxTextSpace = 5 + self.Legend.dy = 5 + self.Legend.dx = 5 + self.Legend.deltay = 5 + self.Legend.alignment ='right' + self._add(self,Label(),name='XLabel',validate=None,desc="The label on the horizontal axis") + self.XLabel.fontName = 'Helvetica' + self.XLabel.fontSize = 7 + self.XLabel.x = 85 + self.XLabel.y = 10 + self.XLabel.textAnchor ='middle' + self.XLabel.maxWidth = 100 + self.XLabel.height = 20 + self.XLabel._text = "X Axis" + self._add(self,Label(),name='YLabel',validate=None,desc="The label on the vertical axis") + self.YLabel.fontName = 'Helvetica' + self.YLabel.fontSize = 7 + self.YLabel.x = 12 + self.YLabel.y = 80 + self.YLabel.angle = 90 + self.YLabel.textAnchor ='middle' + self.YLabel.maxWidth = 100 + self.YLabel.height = 20 + self.YLabel._text = "Y Axis" + self.chart.yValueAxis.forceZero = 1 + self.chart.xValueAxis.forceZero = 1 + self._add(self,0,name='preview',validate=None,desc=None) + +if __name__=="__main__": #NORUNTESTS + LineChartWithMarkers().save(formats=['pdf'],outDir=None,fnRoot='linechart_with_markers') diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/radar.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/radar.py new file mode 100644 index 0000000000000000000000000000000000000000..b7480546ec963bc43dfdc64d4c278ff2b049da31 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/radar.py @@ -0,0 +1,66 @@ +#Autogenerated by ReportLab guiedit do not edit +from reportlab.graphics.charts.legends import Legend +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.charts.spider import SpiderChart +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin +from reportlab.graphics.charts.textlabels import Label + +class RadarChart(_DrawingEditorMixin,Drawing): + def __init__(self,width=200,height=150,*args,**kw): + Drawing.__init__(self,width,height,*args,**kw) + self._add(self,SpiderChart(),name='chart',validate=None,desc="The main chart") + self.chart.width = 90 + self.chart.height = 90 + self.chart.x = 45 + self.chart.y = 25 + self.chart.strands[0].strokeColor= color01 + self.chart.strands[1].strokeColor= color02 + self.chart.strands[2].strokeColor= color03 + self.chart.strands[3].strokeColor= color04 + self.chart.strands[4].strokeColor= color05 + self.chart.strands[5].strokeColor= color06 + self.chart.strands[6].strokeColor= color07 + self.chart.strands[7].strokeColor= color08 + self.chart.strands[8].strokeColor= color09 + self.chart.strands[9].strokeColor= color10 + self.chart.strands[0].fillColor = None + self.chart.strands[1].fillColor = None + self.chart.strands[2].fillColor = None + self.chart.strands[3].fillColor = None + self.chart.strands[4].fillColor = None + self.chart.strands[5].fillColor = None + self.chart.strands[6].fillColor = None + self.chart.strands[7].fillColor = None + self.chart.strands[8].fillColor = None + self.chart.strands[9].fillColor = None + self.chart.strands.strokeWidth = 1 + self.chart.strandLabels.fontName = 'Helvetica' + self.chart.strandLabels.fontSize = 6 + self.chart.fillColor = backgroundGrey + self.chart.data = [(125, 180, 200), (100, 150, 180)] + self.chart.labels = ['North', 'South', 'Central'] + self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") + self.Title.fontName = 'Helvetica-Bold' + self.Title.fontSize = 7 + self.Title.x = 100 + self.Title.y = 135 + self.Title._text = 'Chart Title' + self.Title.maxWidth = 180 + self.Title.height = 20 + self.Title.textAnchor ='middle' + self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") + self.Legend.colorNamePairs = [(color01, 'Widgets'), (color02, 'Sprockets')] + self.Legend.fontName = 'Helvetica' + self.Legend.fontSize = 7 + self.Legend.x = 153 + self.Legend.y = 85 + self.Legend.dxTextSpace = 5 + self.Legend.dy = 5 + self.Legend.dx = 5 + self.Legend.deltay = 5 + self.Legend.alignment ='right' + self.chart.strands.strokeWidth = 1 + self._add(self,0,name='preview',validate=None,desc=None) + +if __name__=="__main__": #NORUNTESTS + RadarChart().save(formats=['pdf'],outDir=None,fnRoot='radar') diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/runall.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/runall.py new file mode 100644 index 0000000000000000000000000000000000000000..9d6400a5af216801ad24f427a29e9a12651b1368 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/runall.py @@ -0,0 +1,57 @@ +# runs all the GUIedit charts in this directory - +# makes a PDF sample for eaxh existing chart type +import sys +import glob +import inspect + +def moduleClasses(mod): + def P(obj, m=mod.__name__, CT=type): + return (type(obj)==CT and obj.__module__==m) + try: + return inspect.getmembers(mod, P)[0][1] + except: + return None + +def getclass(f): + return moduleClasses(__import__(f)) + +def run(format, VERBOSE=0): + formats = format.split( ',') + for i in range(0, len(formats)): + formats[i] == formats[i].strip().lower() + allfiles = glob.glob('*.py') + allfiles.sort() + for fn in allfiles: + f = fn.split('.')[0] + c = getclass(f) + if c != None: + print(c.__name__) + try: + for fmt in formats: + if fmt: + c().save(formats=[fmt],outDir='.',fnRoot=c.__name__) + if VERBOSE: + print(" %s.%s" % (c.__name__, fmt)) + except: + print(" COULDN'T CREATE '%s.%s'!" % (c.__name__, format)) + +if __name__ == "__main__": + if len(sys.argv) == 1: + run('pdf,pict,png') + else: + try: + if sys.argv[1] == "-h": + print('usage: runall.py [FORMAT] [-h]') + print(' if format is supplied is should be one or more of pdf,gif,eps,png etc') + print(' if format is missing the following formats are assumed: pdf,pict,png') + print(' -h prints this message') + else: + t = sys.argv[1:] + for f in t: + run(f) + except: + print('usage: runall.py [FORMAT][-h]') + print(' if format is supplied is should be one or more of pdf,gif,eps,png etc') + print(' if format is missing the following formats are assumed: pdf,pict,png') + print(' -h prints this message') + raise diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/scatter.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/scatter.py new file mode 100644 index 0000000000000000000000000000000000000000..a5a17f0231bba4ae548cc36ab0ef56167558a87a --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/scatter.py @@ -0,0 +1,71 @@ +#Autogenerated by ReportLab guiedit do not edit +from reportlab.graphics.charts.legends import Legend +from reportlab.graphics.charts.lineplots import ScatterPlot +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin +from reportlab.graphics.charts.textlabels import Label +from reportlab.graphics.samples.excelcolors import * + +class Scatter(_DrawingEditorMixin,Drawing): + def __init__(self,width=200,height=150,*args,**kw): + Drawing.__init__(self,width,height,*args,**kw) + self._add(self,ScatterPlot(),name='chart',validate=None,desc="The main chart") + self.chart.width = 115 + self.chart.height = 80 + self.chart.x = 30 + self.chart.y = 40 + self.chart.lines[0].strokeColor = color01 + self.chart.lines[1].strokeColor = color02 + self.chart.lines[2].strokeColor = color03 + self.chart.lines[3].strokeColor = color04 + self.chart.lines[4].strokeColor = color05 + self.chart.lines[5].strokeColor = color06 + self.chart.lines[6].strokeColor = color07 + self.chart.lines[7].strokeColor = color08 + self.chart.lines[8].strokeColor = color09 + self.chart.lines[9].strokeColor = color10 + self.chart.fillColor = backgroundGrey + self.chart.lineLabels.fontName = 'Helvetica' + self.chart.xValueAxis.labels.fontName = 'Helvetica' + self.chart.xValueAxis.labels.fontSize = 7 + self.chart.xValueAxis.forceZero = 0 + self.chart.data = [((100,100), (200,200), (250,210), (300,300), (400,500)), ((100,200), (200,300), (250,200), (300,400), (400, 600))] + self.chart.xValueAxis.avoidBoundFrac = 1 + self.chart.xValueAxis.gridEnd = 115 + self.chart.xValueAxis.tickDown = 3 + self.chart.xValueAxis.visibleGrid = 1 + self.chart.yValueAxis.tickLeft = 3 + self.chart.yValueAxis.labels.fontName = 'Helvetica' + self.chart.yValueAxis.labels.fontSize = 7 + self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") + self.Title.fontName = 'Helvetica-Bold' + self.Title.fontSize = 7 + self.Title.x = 100 + self.Title.y = 135 + self.Title._text = 'Chart Title' + self.Title.maxWidth = 180 + self.Title.height = 20 + self.Title.textAnchor ='middle' + self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") + self.Legend.colorNamePairs = [(color01, 'Widgets'), (color02, 'Sprockets')] + self.Legend.fontName = 'Helvetica' + self.Legend.fontSize = 7 + self.Legend.x = 153 + self.Legend.y = 85 + self.Legend.dxTextSpace = 5 + self.Legend.dy = 5 + self.Legend.dx = 5 + self.Legend.deltay = 5 + self.Legend.alignment ='right' + self.chart.lineLabelFormat = None + self.chart.xLabel = 'X Axis' + self.chart.y = 30 + self.chart.yLabel = 'Y Axis' + self.chart.yValueAxis.labelTextFormat = '%d' + self.chart.yValueAxis.forceZero = 1 + self.chart.xValueAxis.forceZero = 1 + + + self._add(self,0,name='preview',validate=None,desc=None) + +if __name__=="__main__": #NORUNTESTS + Scatter().save(formats=['pdf'],outDir=None,fnRoot='scatter') diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/scatter_lines.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/scatter_lines.py new file mode 100644 index 0000000000000000000000000000000000000000..b435625beb7d6795e14909d87132c9a85dc92b29 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/scatter_lines.py @@ -0,0 +1,82 @@ +#Autogenerated by ReportLab guiedit do not edit +from reportlab.graphics.charts.legends import Legend +from reportlab.graphics.charts.lineplots import ScatterPlot +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin +from reportlab.graphics.charts.textlabels import Label +from reportlab.graphics.samples.excelcolors import * + +class ScatterLines(_DrawingEditorMixin,Drawing): + def __init__(self,width=200,height=150,*args,**kw): + Drawing.__init__(self,width,height,*args,**kw) + self._add(self,ScatterPlot(),name='chart',validate=None,desc="The main chart") + self.chart.width = 115 + self.chart.height = 80 + self.chart.x = 30 + self.chart.y = 40 + self.chart.lines[0].strokeColor = color01 + self.chart.lines[1].strokeColor = color02 + self.chart.lines[2].strokeColor = color03 + self.chart.lines[3].strokeColor = color04 + self.chart.lines[4].strokeColor = color05 + self.chart.lines[5].strokeColor = color06 + self.chart.lines[6].strokeColor = color07 + self.chart.lines[7].strokeColor = color08 + self.chart.lines[8].strokeColor = color09 + self.chart.lines[9].strokeColor = color10 + self.chart.lines[0].symbol = None + self.chart.lines[1].symbol = None + self.chart.lines[2].symbol = None + self.chart.lines[3].symbol = None + self.chart.lines[4].symbol = None + self.chart.lines[5].symbol = None + self.chart.lines[6].symbol = None + self.chart.lines[7].symbol = None + self.chart.lines[8].symbol = None + self.chart.lines[9].symbol = None + self.chart.fillColor = backgroundGrey + self.chart.lineLabels.fontName = 'Helvetica' + self.chart.xValueAxis.labels.fontName = 'Helvetica' + self.chart.xValueAxis.labels.fontSize = 7 + self.chart.xValueAxis.forceZero = 0 + self.chart.data = [((100,100), (200,200), (250,210), (300,300), (400,500)), ((100,200), (200,300), (250,200), (300,400), (400, 600))] + self.chart.xValueAxis.avoidBoundFrac = 1 + self.chart.xValueAxis.gridEnd = 115 + self.chart.xValueAxis.tickDown = 3 + self.chart.xValueAxis.visibleGrid = 1 + self.chart.yValueAxis.tickLeft = 3 + self.chart.yValueAxis.labels.fontName = 'Helvetica' + self.chart.yValueAxis.labels.fontSize = 7 + self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") + self.Title.fontName = 'Helvetica-Bold' + self.Title.fontSize = 7 + self.Title.x = 100 + self.Title.y = 135 + self.Title._text = 'Chart Title' + self.Title.maxWidth = 180 + self.Title.height = 20 + self.Title.textAnchor ='middle' + self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") + self.Legend.colorNamePairs = [(color01, 'Widgets'), (color02, 'Sprockets')] + self.Legend.fontName = 'Helvetica' + self.Legend.fontSize = 7 + self.Legend.x = 153 + self.Legend.y = 85 + self.Legend.dxTextSpace = 5 + self.Legend.dy = 5 + self.Legend.dx = 5 + self.Legend.deltay = 5 + self.Legend.alignment ='right' + self.chart.lineLabelFormat = None + self.chart.xLabel = 'X Axis' + self.chart.y = 30 + self.chart.yLabel = 'Y Axis' + self.chart.yValueAxis.gridEnd = 115 + self.chart.yValueAxis.visibleGrid = 1 + self.chart.yValueAxis.labelTextFormat = '%d' + self.chart.yValueAxis.forceZero = 1 + self.chart.xValueAxis.forceZero = 1 + self.chart.joinedLines = 1 + self._add(self,0,name='preview',validate=None,desc=None) + +if __name__=="__main__": #NORUNTESTS + ScatterLines().save(formats=['pdf'],outDir=None,fnRoot='scatter_lines') diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/scatter_lines_markers.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/scatter_lines_markers.py new file mode 100644 index 0000000000000000000000000000000000000000..53406056bd28b296c854c4d0c1489af2142df62d --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/scatter_lines_markers.py @@ -0,0 +1,72 @@ +#Autogenerated by ReportLab guiedit do not edit +from reportlab.graphics.charts.legends import Legend +from reportlab.graphics.charts.lineplots import ScatterPlot +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin +from reportlab.graphics.charts.textlabels import Label +from reportlab.graphics.samples.excelcolors import * + +class ScatterLinesMarkers(_DrawingEditorMixin,Drawing): + def __init__(self,width=200,height=150,*args,**kw): + Drawing.__init__(self,width,height,*args,**kw) + self._add(self,ScatterPlot(),name='chart',validate=None,desc="The main chart") + self.chart.width = 115 + self.chart.height = 80 + self.chart.x = 30 + self.chart.y = 40 + self.chart.lines[0].strokeColor = color01 + self.chart.lines[1].strokeColor = color02 + self.chart.lines[2].strokeColor = color03 + self.chart.lines[3].strokeColor = color04 + self.chart.lines[4].strokeColor = color05 + self.chart.lines[5].strokeColor = color06 + self.chart.lines[6].strokeColor = color07 + self.chart.lines[7].strokeColor = color08 + self.chart.lines[8].strokeColor = color09 + self.chart.lines[9].strokeColor = color10 + self.chart.fillColor = backgroundGrey + self.chart.lineLabels.fontName = 'Helvetica' + self.chart.xValueAxis.labels.fontName = 'Helvetica' + self.chart.xValueAxis.labels.fontSize = 7 + self.chart.xValueAxis.forceZero = 0 + self.chart.data = [((100,100), (200,200), (250,210), (300,300), (400,500)), ((100,200), (200,300), (250,200), (300,400), (400, 600))] + self.chart.xValueAxis.avoidBoundFrac = 1 + self.chart.xValueAxis.gridEnd = 115 + self.chart.xValueAxis.tickDown = 3 + self.chart.xValueAxis.visibleGrid = 1 + self.chart.yValueAxis.tickLeft = 3 + self.chart.yValueAxis.labels.fontName = 'Helvetica' + self.chart.yValueAxis.labels.fontSize = 7 + self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") + self.Title.fontName = 'Helvetica-Bold' + self.Title.fontSize = 7 + self.Title.x = 100 + self.Title.y = 135 + self.Title._text = 'Chart Title' + self.Title.maxWidth = 180 + self.Title.height = 20 + self.Title.textAnchor ='middle' + self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") + self.Legend.colorNamePairs = [(color01, 'Widgets'), (color02, 'Sprockets')] + self.Legend.fontName = 'Helvetica' + self.Legend.fontSize = 7 + self.Legend.x = 153 + self.Legend.y = 85 + self.Legend.dxTextSpace = 5 + self.Legend.dy = 5 + self.Legend.dx = 5 + self.Legend.deltay = 5 + self.Legend.alignment ='right' + self.chart.lineLabelFormat = None + self.chart.xLabel = 'X Axis' + self.chart.y = 30 + self.chart.yLabel = 'Y Axis' + self.chart.yValueAxis.gridEnd = 115 + self.chart.yValueAxis.visibleGrid = 1 + self.chart.yValueAxis.labelTextFormat = '%d' + self.chart.yValueAxis.forceZero = 1 + self.chart.xValueAxis.forceZero = 1 + self.chart.joinedLines = 1 + self._add(self,0,name='preview',validate=None,desc=None) + +if __name__=="__main__": #NORUNTESTS + ScatterLinesMarkers().save(formats=['pdf'],outDir=None,fnRoot='scatter_lines_markers') diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/simple_pie.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/simple_pie.py new file mode 100644 index 0000000000000000000000000000000000000000..670beba5984fd0c6b32a61727bad73cc69fe23f3 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/simple_pie.py @@ -0,0 +1,61 @@ +#Autogenerated by ReportLab guiedit do not edit +from reportlab.graphics.charts.piecharts import Pie +from reportlab.graphics.widgets.grids import ShadedRect +from reportlab.graphics.charts.legends import Legend +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin +from reportlab.graphics.charts.textlabels import Label +from reportlab.graphics.samples.excelcolors import * + +class SimplePie(_DrawingEditorMixin,Drawing): + def __init__(self,width=200,height=150,*args,**kw): + Drawing.__init__(self,width,height,*args,**kw) + self._add(self,Pie(),name='chart',validate=None,desc="The main chart") + self.chart.width = 100 + self.chart.height = 100 + self.chart.x = 25 + self.chart.y = 25 + self.chart.slices[0].fillColor = color01 + self.chart.slices[1].fillColor = color02 + self.chart.slices[2].fillColor = color03 + self.chart.slices[3].fillColor = color04 + self.chart.slices[4].fillColor = color05 + self.chart.slices[5].fillColor = color06 + self.chart.slices[6].fillColor = color07 + self.chart.slices[7].fillColor = color08 + self.chart.slices[8].fillColor = color09 + self.chart.slices[9].fillColor = color10 + self.chart.data = (100, 150, 180) + self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") + self.Title.fontName = 'Helvetica-Bold' + self.Title.fontSize = 7 + self.Title.x = 100 + self.Title.y = 135 + self.Title._text = 'Chart Title' + self.Title.maxWidth = 180 + self.Title.height = 20 + self.Title.textAnchor ='middle' + self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") + self.Legend.colorNamePairs = [(color01, 'North'), (color02, 'South'),(color03, 'Central')] + self.Legend.fontName = 'Helvetica' + self.Legend.fontSize = 7 + self.Legend.x = 160 + self.Legend.y = 85 + self.Legend.dxTextSpace = 5 + self.Legend.dy = 5 + self.Legend.dx = 5 + self.Legend.deltay = 5 + self.Legend.alignment ='right' + self.chart.slices.strokeWidth = 1 + self.chart.slices.fontName = 'Helvetica' + self.background = ShadedRect() + self.background.fillColorStart = backgroundGrey + self.background.fillColorEnd = backgroundGrey + self.background.numShades = 1 + self.background.strokeWidth = 0.5 + self.background.x = 25 + self.background.y = 25 + self.Legend.columnMaximum = 10 + self._add(self,0,name='preview',validate=None,desc=None) + +if __name__=="__main__": #NORUNTESTS + SimplePie().save(formats=['pdf'],outDir=None,fnRoot=None) diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/stacked_bar.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/stacked_bar.py new file mode 100644 index 0000000000000000000000000000000000000000..d175651807c43f3126ec60f78b06b2fedb993db7 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/stacked_bar.py @@ -0,0 +1,85 @@ +#Autogenerated by ReportLab guiedit do not edit +from reportlab.graphics.charts.legends import Legend +from reportlab.graphics.charts.barcharts import HorizontalBarChart +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin +from reportlab.graphics.charts.textlabels import Label +from reportlab.graphics.samples.excelcolors import * + +class StackedBar(_DrawingEditorMixin,Drawing): + def __init__(self,width=200,height=150,*args,**kw): + Drawing.__init__(self,width,height,*args,**kw) + self._add(self,HorizontalBarChart(),name='chart',validate=None,desc="The main chart") + self.chart.width = 115 + self.chart.height = 80 + self.chart.x = 30 + self.chart.y = 40 + self.chart.bars[0].fillColor = color01 + self.chart.bars[1].fillColor = color02 + self.chart.bars[2].fillColor = color03 + self.chart.bars[3].fillColor = color04 + self.chart.bars[4].fillColor = color05 + self.chart.bars[5].fillColor = color06 + self.chart.bars[6].fillColor = color07 + self.chart.bars[7].fillColor = color08 + self.chart.bars[8].fillColor = color09 + self.chart.bars[9].fillColor = color10 + self.chart.fillColor = backgroundGrey + self.chart.barLabels.fontName = 'Helvetica' + self.chart.valueAxis.labels.fontName = 'Helvetica' + self.chart.valueAxis.labels.fontSize = 6 + self.chart.valueAxis.forceZero = 1 + self.chart.data = [(100, 150, 180), (125, 180, 200)] + self.chart.groupSpacing = 15 + self.chart.valueAxis.avoidBoundFrac = 1 + self.chart.valueAxis.gridEnd = 80 + self.chart.valueAxis.tickDown = 3 + self.chart.valueAxis.visibleGrid = 1 + self.chart.categoryAxis.categoryNames = ['North', 'South', 'Central'] + self.chart.categoryAxis.tickLeft = 3 + self.chart.categoryAxis.labels.fontName = 'Helvetica' + self.chart.categoryAxis.labels.fontSize = 6 + self.chart.categoryAxis.labels.dx = -3 + self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") + self.Title.fontName = 'Helvetica-Bold' + self.Title.fontSize = 7 + self.Title.x = 100 + self.Title.y = 135 + self.Title._text = 'Chart Title' + self.Title.maxWidth = 180 + self.Title.height = 20 + self.Title.textAnchor ='middle' + self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") + self.Legend.colorNamePairs = [(color01, 'Widgets'), (color02, 'Sprockets')] + self.Legend.fontName = 'Helvetica' + self.Legend.fontSize = 7 + self.Legend.x = 153 + self.Legend.y = 85 + self.Legend.dxTextSpace = 5 + self.Legend.dy = 5 + self.Legend.dx = 5 + self.Legend.deltay = 5 + self.Legend.alignment ='right' + self._add(self,Label(),name='XLabel',validate=None,desc="The label on the horizontal axis") + self.XLabel.fontName = 'Helvetica' + self.XLabel.fontSize = 7 + self.XLabel.x = 85 + self.XLabel.y = 10 + self.XLabel.textAnchor ='middle' + self.XLabel.maxWidth = 100 + self.XLabel.height = 20 + self.XLabel._text = "X Axis" + self._add(self,Label(),name='YLabel',validate=None,desc="The label on the vertical axis") + self.YLabel.fontName = 'Helvetica' + self.YLabel.fontSize = 7 + self.YLabel.x = 12 + self.YLabel.y = 80 + self.YLabel.angle = 90 + self.YLabel.textAnchor ='middle' + self.YLabel.maxWidth = 100 + self.YLabel.height = 20 + self.YLabel._text = "Y Axis" + self.chart.categoryAxis.style='stacked' + self._add(self,0,name='preview',validate=None,desc=None) + +if __name__=="__main__": #NORUNTESTS + StackedBar().save(formats=['pdf'],outDir=None,fnRoot='stacked_bar') diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/stacked_column.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/stacked_column.py new file mode 100644 index 0000000000000000000000000000000000000000..70246c665179a41c12b44ae63008c43ad9549193 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/samples/stacked_column.py @@ -0,0 +1,84 @@ +#Autogenerated by ReportLab guiedit do not edit +from reportlab.graphics.charts.legends import Legend +from reportlab.graphics.charts.barcharts import VerticalBarChart +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin +from reportlab.graphics.charts.textlabels import Label +from reportlab.graphics.samples.excelcolors import * + +class StackedColumn(_DrawingEditorMixin,Drawing): + def __init__(self,width=200,height=150,*args,**kw): + Drawing.__init__(self,width,height,*args,**kw) + self._add(self,VerticalBarChart(),name='chart',validate=None,desc="The main chart") + self.chart.width = 115 + self.chart.height = 80 + self.chart.x = 30 + self.chart.y = 40 + self.chart.bars[0].fillColor = color01 + self.chart.bars[1].fillColor = color02 + self.chart.bars[2].fillColor = color03 + self.chart.bars[3].fillColor = color04 + self.chart.bars[4].fillColor = color05 + self.chart.bars[5].fillColor = color06 + self.chart.bars[6].fillColor = color07 + self.chart.bars[7].fillColor = color08 + self.chart.bars[8].fillColor = color09 + self.chart.bars[9].fillColor = color10 + self.chart.fillColor = backgroundGrey + self.chart.barLabels.fontName = 'Helvetica' + self.chart.valueAxis.labels.fontName = 'Helvetica' + self.chart.valueAxis.labels.fontSize = 7 + self.chart.valueAxis.forceZero = 1 + self.chart.data = [(100, 150, 180), (125, 180, 200)] + self.chart.groupSpacing = 15 + self.chart.valueAxis.avoidBoundFrac = 1 + self.chart.valueAxis.gridEnd = 115 + self.chart.valueAxis.tickLeft = 3 + self.chart.valueAxis.visibleGrid = 1 + self.chart.categoryAxis.categoryNames = ['North', 'South', 'Central'] + self.chart.categoryAxis.tickDown = 3 + self.chart.categoryAxis.labels.fontName = 'Helvetica' + self.chart.categoryAxis.labels.fontSize = 7 + self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") + self.Title.fontName = 'Helvetica-Bold' + self.Title.fontSize = 7 + self.Title.x = 100 + self.Title.y = 135 + self.Title._text = 'Chart Title' + self.Title.maxWidth = 180 + self.Title.height = 20 + self.Title.textAnchor ='middle' + self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") + self.Legend.colorNamePairs = [(color01, 'Widgets'), (color02, 'Sprockets')] + self.Legend.fontName = 'Helvetica' + self.Legend.fontSize = 7 + self.Legend.x = 153 + self.Legend.y = 85 + self.Legend.dxTextSpace = 5 + self.Legend.dy = 5 + self.Legend.dx = 5 + self.Legend.deltay = 5 + self.Legend.alignment ='right' + self._add(self,Label(),name='XLabel',validate=None,desc="The label on the horizontal axis") + self.XLabel.fontName = 'Helvetica' + self.XLabel.fontSize = 7 + self.XLabel.x = 85 + self.XLabel.y = 10 + self.XLabel.textAnchor ='middle' + self.XLabel.maxWidth = 100 + self.XLabel.height = 20 + self.XLabel._text = "X Axis" + self._add(self,Label(),name='YLabel',validate=None,desc="The label on the vertical axis") + self.YLabel.fontName = 'Helvetica' + self.YLabel.fontSize = 7 + self.YLabel.x = 12 + self.YLabel.y = 80 + self.YLabel.angle = 90 + self.YLabel.textAnchor ='middle' + self.YLabel.maxWidth = 100 + self.YLabel.height = 20 + self.YLabel._text = "Y Axis" + self.chart.categoryAxis.style='stacked' + self._add(self,0,name='preview',validate=None,desc=None) + +if __name__=="__main__": #NORUNTESTS + StackedColumn().save(formats=['pdf'],outDir=None,fnRoot='stacked_column') diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/shapes.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/shapes.py new file mode 100644 index 0000000000000000000000000000000000000000..89edd0984e0eee40371c8bd1d9781ed9e80c7764 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/shapes.py @@ -0,0 +1,1572 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/graphics/shapes.py + +__version__='3.5.60' +__doc__='''Core of the graphics library - defines Drawing and Shapes''' + +import os, sys +from math import pi, cos, sin, sqrt, radians, floor + +from reportlab.platypus import Flowable +from reportlab.rl_config import shapeChecking, verbose, defaultGraphicsFontName as _baseGFontName, _unset_, decimalSymbol +from reportlab.lib import logger +from reportlab.lib import colors +from reportlab.lib.validators import * +from reportlab.lib.utils import isSeq, asBytes +isOpacity = NoneOr(isNumberInRange(0,1)) +from reportlab.lib.attrmap import * +from reportlab.lib.rl_accel import fp_str +from reportlab.pdfbase.pdfmetrics import stringWidth +from reportlab.lib.fonts import tt2ps +from reportlab.pdfgen.canvas import FILL_EVEN_ODD, FILL_NON_ZERO +_baseGFontNameB = tt2ps(_baseGFontName,1,0) +_baseGFontNameI = tt2ps(_baseGFontName,0,1) +_baseGFontNameBI = tt2ps(_baseGFontName,1,1) + +# two constants for filling rules +NON_ZERO_WINDING = 'Non-Zero Winding' +EVEN_ODD = 'Even-Odd' + +## these can be overridden at module level before you start +#creating shapes. So, if using a special color model, +#this provides support for the rendering mechanism. +#you can change defaults globally before you start +#making shapes; one use is to substitute another +#color model cleanly throughout the drawing. + +STATE_DEFAULTS = { # sensible defaults for all + 'transform': (1,0,0,1,0,0), + + # styles follow SVG naming + 'strokeColor': colors.black, + 'strokeWidth': 1, + 'strokeLineCap': 0, + 'strokeLineJoin': 0, + 'strokeMiterLimit' : 10, # don't know yet so let bomb here + 'strokeDashArray': None, + 'strokeOpacity': None, #100% + 'fillOpacity': None, + 'fillOverprint': False, + 'strokeOverprint': False, + 'overprintMask': 0, + + 'fillColor': colors.black, #...or text will be invisible + 'fillMode': FILL_EVEN_ODD, #same as pdfgen.canvas + + 'fontSize': 10, + 'fontName': _baseGFontName, + 'textAnchor': 'start' # can be start, middle, end, inherited + } + +#################################################################### +# math utilities. These are now in reportlab.graphics.transform +#################################################################### +from . transform import * + +def _textBoxLimits(text, font, fontSize, leading, textAnchor, boxAnchor): + w = 0 + for t in text: + w = max(w,stringWidth(t,font, fontSize)) + + h = len(text)*leading + yt = fontSize + if boxAnchor[0]=='s': + yb = -h + yt = yt - h + elif boxAnchor[0]=='n': + yb = 0 + else: + yb = -h/2.0 + yt = yt + yb + + if boxAnchor[-1]=='e': + xb = -w + if textAnchor=='end': xt = 0 + elif textAnchor=='start': xt = -w + else: xt = -w/2.0 + elif boxAnchor[-1]=='w': + xb = 0 + if textAnchor=='end': xt = w + elif textAnchor=='start': xt = 0 + else: xt = w/2.0 + else: + xb = -w/2.0 + if textAnchor=='end': xt = -xb + elif textAnchor=='start': xt = xb + else: xt = 0 + + return xb, yb, w, h, xt, yt + +def _rotatedBoxLimits( x, y, w, h, angle): + ''' + Find the corner points of the rotated w x h sized box at x,y + return the corner points and the min max points in the original space + ''' + C = zTransformPoints(rotate(angle),((x,y),(x+w,y),(x+w,y+h),(x,y+h))) + X = [x[0] for x in C] + Y = [x[1] for x in C] + return min(X), max(X), min(Y), max(Y), C + +class _DrawTimeResizeable: + '''Addin class to provide the horribleness of _drawTimeResize''' + def _drawTimeResize(self,w,h): + if hasattr(self,'_canvas'): + canvas = self._canvas + drawing = canvas._drawing + drawing.width, drawing.height = w, h + if hasattr(canvas,'_drawTimeResize'): + canvas._drawTimeResize(w,h) + +class _SetKeyWordArgs: + def __init__(self, keywords={}): + """In general properties may be supplied to the constructor.""" + for key, value in keywords.items(): + setattr(self, key, value) + +################################################################# +# +# Helper functions for working out bounds +# +################################################################# + +def getRectsBounds(rectList): + # filter out any None objects, e.g. empty groups + L = [x for x in rectList if x is not None] + if not L: return None + + xMin, yMin, xMax, yMax = L[0] + for (x1, y1, x2, y2) in L[1:]: + if x1 < xMin: + xMin = x1 + if x2 > xMax: + xMax = x2 + if y1 < yMin: + yMin = y1 + if y2 > yMax: + yMax = y2 + return (xMin, yMin, xMax, yMax) + +def _getBezierExtrema(y0,y1,y2,y3): + ''' + this is used to find if a curveTo path operator has extrema in its range + The curveTo operator is defined by the points y0, y1, y2, y3 + + B(t):=(1-t)^3*y0+3*(1-t)^2*t*y1+3*(1-t)*t^2*y2+t^3*y3 + :=t^3*(y3-3*y2+3*y1-y0)+t^2*(3*y2-6*y1+3*y0)+t*(3*y1-3*y0)+y0 + and is a cubic bezier curve. + + The differential is a quadratic + t^2*(3*y3-9*y2+9*y1-3*y0)+t*(6*y2-12*y1+6*y0)+3*y1-3*y0 + + The extrema must be at real roots, r, of the above which lie in 0<=r<=1 + + The quadratic coefficients are + a=3*y3-9*y2+9*y1-3*y0 b=6*y2-12*y1+6*y0 c=3*y1-3*y0 + or + a=y3-3*y2+3*y1-y0 b=2*y2-4*y1+2*y0 c=y1-y0 (remove common factor of 3) + or + a=y3-3*(y2-y1)-y0 b=2*(y2-2*y1+y0) c=y1-y0 + + The returned value is [y0,x1,x2,y3] where if found x1, x2 are any extremals that were found; + there can be 0, 1 or 2 extremals + ''' + a=y3-3*(y2-y1)-y0 + b=2*(y2-2*y1+y0) + c=y1-y0 + Y = [y0] #the set of points + + #standard method to find roots of quadratic + d = b*b - 4*a*c + if d>=0: + d = sqrt(d) + if b<0: d = -d + q = -0.5*(b+d) + R = [] + try: + R.append(q/a) + except: + pass + try: + R.append(c/q) + except: + pass + b *= 1.5 + c *= 3 + for t in R: + if 0<=t<=1: + #real root in range evaluate spline there and add to X + Y.append(t*(t*(t*a+b)+c)+y0) + Y.append(y3) + return Y + +def getPathBounds(points): + n = len(points) + f = lambda i,p = points: p[i] + xs = list(map(f,range(0,n,2))) + ys = list(map(f,range(1,n,2))) + return (min(xs), min(ys), max(xs), max(ys)) + +def getPointsBounds(pointList): + "Helper function for list of points" + first = pointList[0] + if isSeq(first): + xs = [xy[0] for xy in pointList] + ys = [xy[1] for xy in pointList] + return (min(xs), min(ys), max(xs), max(ys)) + else: + return getPathBounds(pointList) + +################################################################# +# +# And now the shapes themselves.... +# +################################################################# +class Shape(_SetKeyWordArgs,_DrawTimeResizeable): + """Base class for all nodes in the tree. Nodes are simply + packets of data to be created, stored, and ultimately + rendered - they don't do anything active. They provide + convenience methods for verification but do not + check attribiute assignments or use any clever setattr + tricks this time.""" + _attrMap = AttrMap() + + def copy(self): + """Return a clone of this shape.""" + + # implement this in the descendants as they need the right init methods. + raise NotImplementedError("No copy method implemented for %s" % self.__class__.__name__) + + def getProperties(self,recur=1): + """Interface to make it easy to extract automatic + documentation""" + + #basic nodes have no children so this is easy. + #for more complex objects like widgets you + #may need to override this. + props = {} + for key, value in self.__dict__.items(): + if key[0:1] != '_': + props[key] = value + return props + + def setProperties(self, props): + """Supports the bulk setting if properties from, + for example, a GUI application or a config file.""" + + self.__dict__.update(props) + #self.verify() + + def dumpProperties(self, prefix=""): + """Convenience. Lists them on standard output. You + may provide a prefix - mostly helps to generate code + samples for documentation.""" + + propList = list(self.getProperties().items()) + propList.sort() + if prefix: + prefix = prefix + '.' + for (name, value) in propList: + print('%s%s = %s' % (prefix, name, value)) + + def verify(self): + """If the programmer has provided the optional + _attrMap attribute, this checks all expected + attributes are present; no unwanted attributes + are present; and (if a checking function is found) + checks each attribute. Either succeeds or raises + an informative exception.""" + + if self._attrMap is not None: + for key in self.__dict__.keys(): + if key[0] != '_': + assert key in self._attrMap, "Unexpected attribute %s found in %s" % (key, self) + for attr, metavalue in self._attrMap.items(): + assert hasattr(self, attr), "Missing attribute %s from %s" % (attr, self) + value = getattr(self, attr) + assert metavalue.validate(value), "Invalid value %s for attribute %s in class %s" % (value, attr, self.__class__.__name__) + + if shapeChecking: + """This adds the ability to check every attribute assignment as it is made. + It slows down shapes but is a big help when developing. It does not + get defined if rl_config.shapeChecking = 0""" + def __setattr__(self, attr, value): + """By default we verify. This could be off + in some parallel base classes.""" + validateSetattr(self,attr,value) #from reportlab.lib.attrmap + + def getBounds(self): + "Returns bounding rectangle of object as (x1,y1,x2,y2)" + raise NotImplementedError("Shapes and widgets must implement getBounds") + +class Group(Shape): + """Groups elements together. May apply a transform + to its contents. Has a publicly accessible property + 'contents' which may be used to iterate over contents. + In addition, child nodes may be given a name in which + case they are subsequently accessible as properties.""" + + _attrMap = AttrMap( + transform = AttrMapValue(isTransform,desc="Coordinate transformation to apply",advancedUsage=1), + contents = AttrMapValue(isListOfShapes,desc="Contained drawable elements"), + strokeOverprint = AttrMapValue(isBoolean,desc='Turn on stroke overprinting'), + fillOverprint = AttrMapValue(isBoolean,desc='Turn on fill overprinting',advancedUsage=1), + overprintMask = AttrMapValue(isBoolean,desc='overprinting for ordinary CMYK',advancedUsage=1), + ) + + def __init__(self, *elements, **keywords): + """Initial lists of elements may be provided to allow + compact definitions in literal Python code. May or + may not be useful.""" + + # Groups need _attrMap to be an instance rather than + # a class attribute, as it may be extended at run time. + self._attrMap = self._attrMap.clone() + self.contents = [] + self.transform = (1,0,0,1,0,0) + for elt in elements: + self.add(elt) + # this just applies keywords; do it at the end so they + #don;t get overwritten + _SetKeyWordArgs.__init__(self, keywords) + + def _addNamedNode(self,name,node): + 'if name is not None add an attribute pointing to node and add to the attrMap' + if name: + if name not in self._attrMap: + self._attrMap[name] = AttrMapValue(isValidChild) + setattr(self, name, node) + + def add(self, node, name=None): + """Appends non-None child node to the 'contents' attribute. In addition, + if a name is provided, it is subsequently accessible by name + """ + # propagates properties down + if node is not None: + assert isValidChild(node), "Can only add Shape or UserNode objects to a Group" + self.contents.append(node) + self._addNamedNode(name,node) + + def _nn(self,node, name=None): + self.add(node, name=name) + return self.contents[-1] + + def insert(self, i, n, name=None): + 'Inserts sub-node n in contents at specified location' + if n is not None: + assert isValidChild(n), "Can only insert Shape or UserNode objects in a Group" + if i<0: + self.contents[i:i] =[n] + else: + self.contents.insert(i,n) + self._addNamedNode(name,n) + + def expandUserNodes(self): + """Return a new object which only contains primitive shapes.""" + + # many limitations - shared nodes become multiple ones, + obj = isinstance(self,Drawing) and Drawing(self.width,self.height) or Group() + obj._attrMap = self._attrMap.clone() + if hasattr(obj,'transform'): obj.transform = self.transform[:] + + self_contents = self.contents + a = obj.contents.append + for child in self_contents: + if isinstance(child, UserNode): + newChild = child.provideNode() + elif isinstance(child, Group): + newChild = child.expandUserNodes() + else: + newChild = child.copy() + a(newChild) + + self._copyNamedContents(obj) + return obj + + def _explode(self): + ''' return a fully expanded object''' + obj = Group() + if hasattr(self,'__label__'): + obj.__label__=self.__label__ + if hasattr(obj,'transform'): obj.transform = self.transform[:] + P = self.getContents()[:] + while P: + n = P.pop(0) + if isinstance(n, UserNode): + P.insert(0,n.provideNode()) + elif isinstance(n, Group): + n = n._explode() + if n.transform==(1,0,0,1,0,0): + obj.contents.extend(n.contents) + else: + obj.add(n) + else: + obj.add(n) + return obj + + def _copyContents(self,obj): + for child in self.contents: + obj.contents.append(child) + + def _copyNamedContents(self,obj,aKeys=None,noCopy=('contents',)): + from copy import copy + self_contents = self.contents + if not aKeys: aKeys = list(self._attrMap.keys()) + for k, v in self.__dict__.items(): + if v in self_contents: + pos = self_contents.index(v) + setattr(obj, k, obj.contents[pos]) + elif k in aKeys and k not in noCopy: + setattr(obj, k, copy(v)) + + def _copy(self,obj): + """copies to obj""" + obj._attrMap = self._attrMap.clone() + self._copyContents(obj) + self._copyNamedContents(obj) + return obj + + def copy(self): + """returns a copy""" + return self._copy(self.__class__()) + + def rotate(self, theta, cx=0, cy=0): + """Convenience to help you set transforms""" + self.transform = mmult(self.transform, rotate(theta,cx,cy)) + + def translate(self, dx, dy=0): + """Convenience to help you set transforms""" + self.transform = mmult(self.transform, translate(dx, dy)) + + def scale(self, sx, sy=1): + """Convenience to help you set transforms""" + self.transform = mmult(self.transform, scale(sx, sy)) + + def skew(self, kx, ky=0): + """Convenience to help you set transforms""" + self.transform = mmult(mmult(self.transform, skewX(kx)),skewY(ky)) + + def shift(self, x, y=0): + '''Convenience function to set the origin arbitrarily''' + self.transform = self.transform[:-2]+(x,y) + + def asDrawing(self, width, height): + """ Convenience function to make a drawing from a group + After calling this the instance will be a drawing! + """ + self.__class__ = Drawing + self._attrMap.update(getattr(self,'_xtraAttrMap',{})) + self.width = width + self.height = height + + def getContents(self): + '''Return the list of things to be rendered + override to get more complicated behaviour''' + b = getattr(self,'background',None) + C = self.contents + if b and b not in C: C = [b]+C + return C + + def getBounds(self): + if self.contents: + b = [] + for elem in self.contents: + b.append(elem.getBounds()) + x1 = getRectsBounds(b) + if x1 is None: return None + x1, y1, x2, y2 = x1 + trans = self.transform + corners = [[x1,y1], [x1, y2], [x2, y1], [x2,y2]] + newCorners = [] + for corner in corners: + newCorners.append(transformPoint(trans, corner)) + return getPointsBounds(newCorners) + else: + #empty group needs a sane default; this + #will happen when interactively creating a group + #nothing has been added to yet. The alternative is + #to handle None as an allowed return value everywhere. + return None + +def _addObjImport(obj,I,n=None): + '''add an import of obj's class to a dictionary of imports''' #' + from inspect import getmodule + c = obj.__class__ + m = getmodule(c).__name__ + n = n or c.__name__ + if m not in I: + I[m] = [n] + elif n not in I[m]: + I[m].append(n) + +def _repr(self,I=None): + '''return a repr style string with named fixed args first, then keywords''' + if isinstance(self,float): + return fp_str(self) + elif isSeq(self): + s = ','.join((_repr(v,I) for v in self)) + if isinstance(self,list): + return f'[{s}]' + else: + return f'({s}{"," if len(self)==1 else""})'; + elif self is EmptyClipPath: + if I: _addObjImport(self,I,'EmptyClipPath') + return 'EmptyClipPath' + elif isinstance(self,Shape): + if I: _addObjImport(self,I) + from inspect import getfullargspec + args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations = getfullargspec(self.__init__) + if defaults: + kargs = args[-len(defaults):] + del args[-len(defaults):] + else: + kargs = [] + P = self.getProperties() + s = ([_repr(P.pop(n,None),I) for n in args[1:]] + +[f'{n}={_repr(P.pop(n,None),I)}' for n in kargs] + +[f'{n}={_repr(P[n],I)}' for n,v in P.items()]) + return f'{self.__class__.__name__}({",".join(s)})' + else: + return repr(self) + +def _renderGroupPy(G,pfx,I,i=0,indent='\t\t'): + s = '' + C = getattr(G,'transform',None) + if C: s += f'{indent}{pfx}.transform = {_repr(C)}\n' + for n in G.getContents(): + if isinstance(n, Group): + npfx = f'v{i}' + i += 1 + l = getattr(n,'__label__','') + if l: l='#'+l + s += f'{indent}{npfx}={pfx}._nn(Group()){l}\n' + s += _renderGroupPy(n,npfx,I,i,indent) + i -= 1 + else: + s += f'{indent}{pfx}.add({_repr(n,I)})\n' + return s + +def _extraKW(self,pfx,**kw): + kw.update(self.__dict__) + n = len(pfx) + return {k[n:]:v for k,v in kw.items() if k.startswith(pfx)} + +class Drawing(Group, Flowable): + """Outermost container; the thing a renderer works on. + This has no properties except a height, width and list + of contents.""" + + _saveModes = { + 'bmp', + 'eps', + 'gif', + 'jpeg', + 'jpg', + 'pct', + 'pdf', + 'pict', + 'png', + 'ps', + 'py', + 'svg', + 'tif', + 'tiff', + 'tiff1', + 'tiffl', + 'tiffp', + } + + _bmModes = _saveModes - {'eps','pdf','ps','py','svg'} + + _xtraAttrMap = AttrMap( + width = AttrMapValue(isNumber,desc="Drawing width in points."), + height = AttrMapValue(isNumber,desc="Drawing height in points."), + canv = AttrMapValue(None), + background = AttrMapValue(isValidChildOrNone,desc="Background widget for the drawing e.g. Rect(0,0,width,height)"), + hAlign = AttrMapValue(OneOf("LEFT", "RIGHT", "CENTER", "CENTRE"), desc="Horizontal alignment within parent document"), + vAlign = AttrMapValue(OneOf("TOP", "BOTTOM", "CENTER", "CENTRE"), desc="Vertical alignment within parent document"), + #AR temporary hack to track back up. + #fontName = AttrMapValue(isStringOrNone), + renderScale = AttrMapValue(isNumber,desc="Global scaling for rendering"), + initialFontName = AttrMapValue(isStringOrNone,desc="override the STATE_DEFAULTS value for fontName"), + initialFontSize = AttrMapValue(isNumberOrNone,desc="override the STATE_DEFAULTS value for fontSize"), + ) + + _attrMap = AttrMap(BASE=Group, + formats = AttrMapValue(SequenceOf( + OneOf(*_saveModes), + lo=1,emptyOK=0), desc='One or more plot modes'), + ) + _attrMap.update(_xtraAttrMap) + + def __init__(self, width=400, height=200, *nodes, **keywords): + self.background = None + Group.__init__(self,*nodes,**keywords) + self.width = width + self.height = height + self.hAlign = 'LEFT' + self.vAlign = 'BOTTOM' + self.renderScale = 1.0 + + def _renderPy(self): + I = { + 'reportlab.graphics.shapes': ['_DrawingEditorMixin','Drawing','Group'], + 'reportlab.lib.colors': ['Color','CMYKColor','PCMYKColor'], + } + G = _renderGroupPy(self._explode(),'self',I) + n = 'ExplodedDrawing_' + self.__class__.__name__ + s = '#Autogenerated by ReportLab guiedit do not edit\n' + s += ''.join((f'from {m} import {", ".join(o)}\n' for m, o in I.items())) + s += f'\nclass {n}(_DrawingEditorMixin,Drawing):\n' + s += f'\tdef __init__(self,width={self.width},height={self.height},*args,**kw):\n' + s += '\t\tDrawing.__init__(self,width,height,*args,**kw)\n' + s += G + s += f'\n\nif __name__=="__main__": #NORUNTESTS\n\t{n}().save(formats=[\'pdf\'],outDir=\'.\',fnRoot=None)\n' + return s + + def draw(self,showBoundary=_unset_): + """This is used by the Platypus framework to let the document + draw itself in a story. It is specific to PDF and should not + be used directly.""" + from reportlab.graphics import renderPDF + renderPDF.draw(self, self.canv, 0, 0, + showBoundary=showBoundary if showBoundary is not _unset_ else getattr(self,'_showBoundary',_unset_)) + + def wrap(self, availWidth, availHeight): + width = self.width + height = self.height + renderScale = self.renderScale + if renderScale!=1.0: + width *= renderScale + height *= renderScale + return width, height + + def expandUserNodes(self): + """Return a new drawing which only contains primitive shapes.""" + obj = Group.expandUserNodes(self) + obj.width = self.width + obj.height = self.height + return obj + + def copy(self): + """Returns a copy""" + return self._copy(self.__class__(self.width, self.height)) + + def asGroup(self,*args,**kw): + return self._copy(Group(*args,**kw)) + + def save(self, formats=None, verbose=None, fnRoot=None, outDir=None, title='', **kw): + """Saves copies of self in desired location and formats. + Multiple formats can be supported in one call + + the extra keywords can be of the form + _renderPM_dpi=96 (which passes dpi=96 to renderPM) + """ + genFmt = kw.pop('seqNumber','') + if isinstance(genFmt,int): + genFmt = '%4d: ' % genFmt + else: + genFmt = '' + genFmt += 'generating %s file %s' + from reportlab import rl_config + ext = '' + if not fnRoot: + fnRoot = getattr(self,'fileNamePattern',(self.__class__.__name__+'%03d')) + chartId = getattr(self,'chartId',0) + if hasattr(chartId,'__call__'): + chartId = chartId(self) + if hasattr(fnRoot,'__call__'): + fnRoot = fnRoot(chartId) + else: + try: + fnRoot = fnRoot % chartId + except TypeError as err: + #the exact error message changed from 2.2 to 2.3 so we need to + #check a substring + if str(err).find('not all arguments converted') < 0: raise + + if outDir is None: + outDir = getattr(self,'outDir',None) + if hasattr(outDir,'__call__'): + outDir = outDir(self) + if os.path.isabs(fnRoot): + outDir, fnRoot = os.path.split(fnRoot) + else: + outDir = outDir or getattr(self,'outDir','.') + outDir = outDir.rstrip().rstrip(os.sep) + if not outDir: outDir = '.' + if not os.path.isabs(outDir): outDir = os.path.join(getattr(self,'_override_CWD',os.path.dirname(sys.argv[0])),outDir) + if not os.path.isdir(outDir): os.makedirs(outDir) + fnroot = os.path.normpath(os.path.join(outDir,fnRoot)) + plotMode = os.path.splitext(fnroot) + if plotMode[1][1:].lower() in self._saveModes: + fnroot = plotMode[0] + + plotMode = [x.lower() for x in (formats or getattr(self,'formats',['pdf']))] + verbose = (verbose is not None and (verbose,) or (getattr(self,'verbose',verbose),))[0] + _saved = logger.warnOnce.enabled, logger.infoOnce.enabled + logger.warnOnce.enabled = logger.infoOnce.enabled = verbose + if 'pdf' in plotMode: + from reportlab.graphics import renderPDF + filename = fnroot+'.pdf' + if verbose: print(genFmt % ('PDF',filename)) + renderPDF.drawToFile(self, filename, title, showBoundary=getattr(self,'showBorder',rl_config.showBoundary),**_extraKW(self,'_renderPDF_',**kw)) + ext = ext + '/.pdf' + if sys.platform=='mac': + import macfs, macostools + macfs.FSSpec(filename).SetCreatorType("CARO", "PDF ") + macostools.touched(filename) + + for bmFmt in self._bmModes: + if bmFmt in plotMode: + from reportlab.graphics import renderPM + filename = '%s.%s' % (fnroot,bmFmt) + if verbose: print(genFmt % (bmFmt,filename)) + dtc = getattr(self,'_drawTimeCollector',None) + if dtc: + dtcfmts = getattr(dtc,'formats',[bmFmt]) + if bmFmt in dtcfmts and not getattr(dtc,'disabled',0): + dtc.clear() + else: + dtc = None + renderPM.drawToFile(self, filename,fmt=bmFmt,showBoundary=getattr(self,'showBorder',rl_config.showBoundary),**_extraKW(self,'_renderPM_',**kw)) + ext = ext + '/.' + bmFmt + if dtc: dtc.save(filename) + + if 'eps' in plotMode: + try: + from rlextra.graphics import renderPS_SEP as renderPS + except ImportError: + from reportlab.graphics import renderPS + filename = fnroot+'.eps' + if verbose: print(genFmt % ('EPS',filename)) + renderPS.drawToFile(self, + filename, + title = fnroot, + dept = getattr(self,'EPS_info',['Testing'])[0], + company = getattr(self,'EPS_info',['','ReportLab'])[1], + preview = getattr(self,'preview',rl_config.eps_preview), + showBoundary=getattr(self,'showBorder',rl_config.showBoundary), + ttf_embed=getattr(self,'ttf_embed',rl_config.eps_ttf_embed), + **_extraKW(self,'_renderPS_',**kw)) + ext = ext + '/.eps' + + if 'svg' in plotMode: + from reportlab.graphics import renderSVG + filename = fnroot+'.svg' + if verbose: print(genFmt % ('SVG',filename)) + renderSVG.drawToFile(self, + filename, + showBoundary=getattr(self,'showBorder',rl_config.showBoundary),**_extraKW(self,'_renderSVG_',**kw)) + ext = ext + '/.svg' + + if 'ps' in plotMode: + from reportlab.graphics import renderPS + filename = fnroot+'.ps' + if verbose: print(genFmt % ('EPS',filename)) + renderPS.drawToFile(self, filename, showBoundary=getattr(self,'showBorder',rl_config.showBoundary),**_extraKW(self,'_renderPS_',**kw)) + ext = ext + '/.ps' + + if 'py' in plotMode: + filename = fnroot+'.py' + if verbose: print(genFmt % ('py',filename)) + with open(filename,'wb') as f: + f.write(asBytes(self._renderPy().replace('\n',os.linesep))) + ext = ext + '/.py' + + logger.warnOnce.enabled, logger.infoOnce.enabled = _saved + if hasattr(self,'saveLogger'): + self.saveLogger(fnroot,ext) + return ext and fnroot+ext[1:] or '' + + def asString(self, format, verbose=None, preview=0, **kw): + """Converts to an 8 bit string in given format.""" + assert format in self._saveModes, 'Unknown file format "%s"' % format + from reportlab import rl_config + #verbose = verbose is not None and (verbose,) or (getattr(self,'verbose',verbose),)[0] + if format == 'pdf': + from reportlab.graphics import renderPDF + title = kw.pop('title','') + return renderPDF.drawToString(self, title, showBoundary=getattr(self,'showBorder',rl_config.showBoundary),**_extraKW(self,'_renderPDF_',**kw)) + elif format in self._bmModes: + from reportlab.graphics import renderPM + return renderPM.drawToString(self, fmt=format,showBoundary=getattr(self,'showBorder', + rl_config.showBoundary),**_extraKW(self,'_renderPM_',**kw)) + elif format == 'eps': + try: + from rlextra.graphics import renderPS_SEP as renderPS + except ImportError: + from reportlab.graphics import renderPS + + return renderPS.drawToString(self, + preview = preview, + showBoundary=getattr(self,'showBorder',rl_config.showBoundary)) + elif format == 'ps': + from reportlab.graphics import renderPS + return renderPS.drawToString(self, showBoundary=getattr(self,'showBorder',rl_config.showBoundary)) + elif format == 'py': + return self._renderPy() + elif format == 'svg': + from reportlab.graphics import renderSVG + return renderSVG.drawToString(self,showBoundary=getattr(self,'showBorder',rl_config.showBoundary),**_extraKW(self,'_renderSVG_',**kw)) + + def resized(self,kind='fit',lpad=0,rpad=0,bpad=0,tpad=0): + '''return a base class drawing which ensures all the contents fits''' + C = self.getContents() + oW = self.width + oH = self.height + drawing = Drawing(oW,oH,*C) + xL,yL,xH,yH = drawing.getBounds() + if kind=='fit' or (kind=='expand' and (xLoW-rpad or yLoH-tpad)): + drawing.width = xH-xL+lpad+rpad + drawing.height = yH-yL+tpad+bpad + drawing.transform = (1,0,0,1,lpad-xL,bpad-yL) + elif kind=='fitx' or (kind=='expandx' and (xLoW-rpad)): + drawing.width = xH-xL+lpad+rpad + drawing.transform = (1,0,0,1,lpad-xL,0) + elif kind=='fity' or (kind=='expandy' and (yLoH-tpad)): + drawing.height = yH-yL+tpad+bpad + drawing.transform = (1,0,0,1,0,bpad-yL) + return drawing + +class _DrawingEditorMixin: + '''This is a mixin to provide functionality for edited drawings''' + def _add(self,obj,value,name=None,validate=None,desc=None,pos=None): + ''' + effectively setattr(obj,name,value), but takes care of things with _attrMaps etc + ''' + ivc = isValidChild(value) + if name and hasattr(obj,'_attrMap'): + if '_attrMap' not in obj.__dict__: + obj._attrMap = obj._attrMap.clone() + if ivc and validate is None: validate = isValidChild + obj._attrMap[name] = AttrMapValue(validate,desc) + if hasattr(obj,'add') and ivc: + if pos: + obj.insert(pos,value,name) + else: + obj.add(value,name) + elif name: + setattr(obj,name,value) + else: + raise ValueError("Can't add, need name") + +class isStrokeDashArray(Validator): + def test(self,x): + return isListOfNumbersOrNone.test(x) or (isinstance(x,(list,tuple)) and isNumber(x[0]) and isListOfNumbers(x[1])) +isStrokeDashArray = isStrokeDashArray() + +class LineShape(Shape): + # base for types of lines + + _attrMap = AttrMap( + strokeColor = AttrMapValue(isColorOrNone), + strokeWidth = AttrMapValue(isNumber), + strokeLineCap = AttrMapValue(OneOf(0,1,2),desc="Line cap 0=butt, 1=round & 2=square"), + strokeLineJoin = AttrMapValue(OneOf(0,1,2),desc="Line join 0=miter, 1=round & 2=bevel"), + strokeMiterLimit = AttrMapValue(isNumber,desc="miter limit control miter line joins"), + strokeDashArray = AttrMapValue(isStrokeDashArray,desc="[numbers] or [phase,[numbers]]"), + strokeOpacity = AttrMapValue(isOpacity,desc="The level of transparency of the line, any real number betwen 0 and 1"), + strokeOverprint = AttrMapValue(isBoolean,desc='Turn on stroke overprinting'), + overprintMask = AttrMapValue(isBoolean,desc='overprinting for ordinary CMYK',advancedUsage=1), + ) + + def __init__(self, kw): + self.strokeColor = STATE_DEFAULTS['strokeColor'] + self.strokeWidth = 1 + self.strokeLineCap = 0 + self.strokeLineJoin = 0 + self.strokeMiterLimit = 0 + self.strokeDashArray = None + self.strokeOpacity = None + self.setProperties(kw) + +class Line(LineShape): + _attrMap = AttrMap(BASE=LineShape, + x1 = AttrMapValue(isNumber,desc=""), + y1 = AttrMapValue(isNumber,desc=""), + x2 = AttrMapValue(isNumber,desc=""), + y2 = AttrMapValue(isNumber,desc=""), + ) + + def __init__(self, x1, y1, x2, y2, **kw): + LineShape.__init__(self, kw) + self.x1 = x1 + self.y1 = y1 + self.x2 = x2 + self.y2 = y2 + + def getBounds(self): + "Returns bounding rectangle of object as (x1,y1,x2,y2)" + return (self.x1, self.y1, self.x2, self.y2) + +class SolidShape(LineShape): + # base for anything with outline and content + + _attrMap = AttrMap(BASE=LineShape, + fillColor = AttrMapValue(isColorOrNone,desc="filling color of the shape, e.g. red"), + fillOpacity = AttrMapValue(isOpacity,desc="the level of transparency of the color, any real number between 0 and 1"), + fillOverprint = AttrMapValue(isBoolean,desc='Turn on fill overprinting'), + overprintMask = AttrMapValue(isBoolean,desc='overprinting for ordinary CMYK',advancedUsage=1), + fillMode = AttrMapValue(OneOf(FILL_EVEN_ODD,FILL_NON_ZERO)), + ) + + def __init__(self, kw): + self.fillColor = STATE_DEFAULTS['fillColor'] + self.fillOpacity = None + # do this at the end so keywords overwrite + #the above settings + LineShape.__init__(self, kw) + +# path operator constants +_MOVETO, _LINETO, _CURVETO, _CLOSEPATH = list(range(4)) +_PATH_OP_ARG_COUNT = (2, 2, 6, 0) # [moveTo, lineTo, curveTo, closePath] +_PATH_OP_NAMES=['moveTo','lineTo','curveTo','closePath'] + +def _renderPath(path,drawFuncs,countOnly=False,forceClose=False): + """Helper function for renderers.""" + # this could be a method of Path... + points = path.points + i = 0 + hadClosePath = 0 + hadMoveTo = 0 + active = not countOnly + for op in path.operators: + if op == _MOVETO: + if forceClose: + if hadMoveTo and pop!=_CLOSEPATH: + hadClosePath += 1 + if active: + drawFuncs[_CLOSEPATH]() + hadMoveTo += 1 + nArgs = _PATH_OP_ARG_COUNT[op] + j = i + nArgs + drawFuncs[op](*points[i:j]) + i = j + if op == _CLOSEPATH: + hadClosePath += 1 + pop = op + if forceClose and hadMoveTo and pop!=_CLOSEPATH: + hadClosePath += 1 + if active: + drawFuncs[_CLOSEPATH]() + return hadMoveTo == hadClosePath + +_fillModeMap = { + None: None, + FILL_NON_ZERO: FILL_NON_ZERO, + 'non-zero': FILL_NON_ZERO, + 'nonzero': FILL_NON_ZERO, + FILL_EVEN_ODD: FILL_EVEN_ODD, + 'even-odd': FILL_EVEN_ODD, + 'evenodd': FILL_EVEN_ODD, + } + +class Path(SolidShape): + """Path, made up of straight lines and bezier curves.""" + + _attrMap = AttrMap(BASE=SolidShape, + points = AttrMapValue(isListOfNumbers), + operators = AttrMapValue(isListOfNumbers), + isClipPath = AttrMapValue(isBoolean), + autoclose = AttrMapValue(NoneOr(OneOf('svg','pdf'))), + fillMode = AttrMapValue(OneOf(FILL_EVEN_ODD,FILL_NON_ZERO)), + ) + + def __init__(self, points=None, operators=None, isClipPath=0, autoclose=None, fillMode=FILL_EVEN_ODD, **kw): + SolidShape.__init__(self, kw) + if points is None: + points = [] + if operators is None: + operators = [] + assert len(points) % 2 == 0, 'Point list must have even number of elements!' + self.points = points + self.operators = operators + self.isClipPath = isClipPath + self.autoclose=autoclose + self.fillMode = fillMode + + def copy(self): + new = self.__class__(self.points[:], self.operators[:]) + new.setProperties(self.getProperties()) + return new + + def moveTo(self, x, y): + self.points.extend([x, y]) + self.operators.append(_MOVETO) + + def lineTo(self, x, y): + self.points.extend([x, y]) + self.operators.append(_LINETO) + + def curveTo(self, x1, y1, x2, y2, x3, y3): + self.points.extend([x1, y1, x2, y2, x3, y3]) + self.operators.append(_CURVETO) + + def closePath(self): + self.operators.append(_CLOSEPATH) + + def getBounds(self): + points = self.points + try: #in case this complex algorithm is not yet ready :) + X = [] + aX = X.append + eX = X.extend + Y=[] + aY = Y.append + eY = Y.extend + i = 0 + for op in self.operators: + nArgs = _PATH_OP_ARG_COUNT[op] + j = i + nArgs + if nArgs==2: + #either moveTo or lineT0 + aX(points[i]) + aY(points[i+1]) + elif nArgs==6: + #curveTo + x1,x2,x3 = points[i:j:2] + eX(_getBezierExtrema(X[-1],x1,x2,x3)) + y1,y2,y3 = points[i+1:j:2] + eY(_getBezierExtrema(Y[-1],y1,y2,y3)) + i = j + return min(X),min(Y),max(X),max(Y) + except: + return getPathBounds(points) + +EmptyClipPath=Path() #special path + +def getArcPoints(centerx, centery, radius, startangledegrees, endangledegrees, yradius=None, degreedelta=None, reverse=None): + if yradius is None: yradius = radius + points = [] + degreestoradians = pi/180.0 + startangle = startangledegrees*degreestoradians + endangle = endangledegrees*degreestoradians + while endangle.001: + degreedelta = min(angle,degreedelta or 1.) + radiansdelta = degreedelta*degreestoradians + n = max(int(angle/radiansdelta+0.5),1) + radiansdelta = angle/n + n += 1 + else: + n = 1 + radiansdelta = 0 + + for angle in range(n): + angle = startangle+angle*radiansdelta + a((centerx+radius*cos(angle),centery+yradius*sin(angle))) + + if reverse: points.reverse() + return points + +class ArcPath(Path): + '''Path with an addArc method''' + def addArc(self, centerx, centery, radius, startangledegrees, endangledegrees, yradius=None, degreedelta=None, moveTo=None, reverse=None): + P = getArcPoints(centerx, centery, radius, startangledegrees, endangledegrees, yradius=yradius, degreedelta=degreedelta, reverse=reverse) + if moveTo or not len(self.operators): + self.moveTo(P[0][0],P[0][1]) + del P[0] + for x, y in P: self.lineTo(x,y) + +def definePath(pathSegs=[],isClipPath=0, dx=0, dy=0, **kw): + O = [] + P = [] + for seg in pathSegs: + if not isSeq(seg): + opName = seg + args = [] + else: + opName = seg[0] + args = seg[1:] + if opName not in _PATH_OP_NAMES: + raise ValueError('bad operator name %s' % opName) + op = _PATH_OP_NAMES.index(opName) + if len(args)!=_PATH_OP_ARG_COUNT[op]: + raise ValueError('%s bad arguments %s' % (opName,str(args))) + O.append(op) + P.extend(list(args)) + for d,o in (dx,0), (dy,1): + for i in range(o,len(P),2): + P[i] = P[i]+d + + #if there's a bounding box given we constrain so our points lie in it + #partial bbox is allowed and does something sensible + bbox = kw.pop('bbox',None) + if bbox: + for j in 0,1: + d = bbox[j],bbox[j+2] + if d[0] is None and d[1] is None: continue + a = P[j::2] + a, b = min(a), max(a) + if d[0] is not None and d[1] is not None: + c, d = min(d), max(d) + fac = (b-a) + if abs(fac)>=1e-6: + fac = (d-c)/fac + for i in range(j,len(P),2): + P[i] = c + fac*(P[i]-a) + else: + #there's no range in the bbox so fixed as average + for i in range(j,len(P),2): + P[i] = (c + d)*0.5 + else: + #if there's a lower bound shift so min is lower bound + #else there's an upper bound shift so max is upper bound + c = d[0] - a if d[0] is not None else d[1] - b + for i in range(j,len(P),2): + P[i] += c + + return Path(P,O,isClipPath,**kw) + +class Rect(SolidShape): + """Rectangle, possibly with rounded corners.""" + + _attrMap = AttrMap(BASE=SolidShape, + x = AttrMapValue(isNumber), + y = AttrMapValue(isNumber), + width = AttrMapValue(isNumber,desc="width of the object in points"), + height = AttrMapValue(isNumber,desc="height of the objects in points"), + rx = AttrMapValue(isNumber), + ry = AttrMapValue(isNumber), + ) + + def __init__(self, x, y, width, height, rx=0, ry=0, **kw): + SolidShape.__init__(self, kw) + self.x = x + self.y = y + self.width = width + self.height = height + self.rx = rx + self.ry = ry + + def copy(self): + new = self.__class__(self.x, self.y, self.width, self.height) + new.setProperties(self.getProperties()) + return new + + def getBounds(self): + return (self.x, self.y, self.x + self.width, self.y + self.height) + +class Image(SolidShape): + """Bitmap image.""" + + _attrMap = AttrMap(BASE=SolidShape, + x = AttrMapValue(isNumber), + y = AttrMapValue(isNumber), + width = AttrMapValue(isNumberOrNone,desc="width of the object in points"), + height = AttrMapValue(isNumberOrNone,desc="height of the objects in points"), + path = AttrMapValue(None), + ) + + def __init__(self, x, y, width, height, path, **kw): + SolidShape.__init__(self, kw) + self.x = x + self.y = y + self.width = width + self.height = height + self.path = path + + def copy(self): + new = self.__class__(self.x, self.y, self.width, self.height, self.path) + new.setProperties(self.getProperties()) + return new + + def getBounds(self): + # bug fix contributed by Marcel Tromp + return (self.x, self.y, self.x + self.width, self.y + self.height) + +class Circle(SolidShape): + + _attrMap = AttrMap(BASE=SolidShape, + cx = AttrMapValue(isNumber,desc="x of the centre"), + cy = AttrMapValue(isNumber,desc="y of the centre"), + r = AttrMapValue(isNumber,desc="radius in points"), + ) + + def __init__(self, cx, cy, r, **kw): + SolidShape.__init__(self, kw) + self.cx = cx + self.cy = cy + self.r = r + + def copy(self): + new = self.__class__(self.cx, self.cy, self.r) + new.setProperties(self.getProperties()) + return new + + def getBounds(self): + return (self.cx - self.r, self.cy - self.r, self.cx + self.r, self.cy + self.r) + +class Ellipse(SolidShape): + _attrMap = AttrMap(BASE=SolidShape, + cx = AttrMapValue(isNumber,desc="x of the centre"), + cy = AttrMapValue(isNumber,desc="y of the centre"), + rx = AttrMapValue(isNumber,desc="x radius"), + ry = AttrMapValue(isNumber,desc="y radius"), + ) + + def __init__(self, cx, cy, rx, ry, **kw): + SolidShape.__init__(self, kw) + self.cx = cx + self.cy = cy + self.rx = rx + self.ry = ry + + def copy(self): + new = self.__class__(self.cx, self.cy, self.rx, self.ry) + new.setProperties(self.getProperties()) + return new + + def getBounds(self): + return (self.cx - self.rx, self.cy - self.ry, self.cx + self.rx, self.cy + self.ry) + +class Wedge(SolidShape): + """A "slice of a pie" by default translates to a polygon moves anticlockwise + from start angle to end angle""" + + _attrMap = AttrMap(BASE=SolidShape, + centerx = AttrMapValue(isNumber,desc="x of the centre"), + centery = AttrMapValue(isNumber,desc="y of the centre"), + radius = AttrMapValue(isNumber,desc="radius in points"), + startangledegrees = AttrMapValue(isNumber), + endangledegrees = AttrMapValue(isNumber), + yradius = AttrMapValue(isNumberOrNone), + radius1 = AttrMapValue(isNumberOrNone), + yradius1 = AttrMapValue(isNumberOrNone), + annular = AttrMapValue(isBoolean,desc='treat as annular ring'), + ) + + degreedelta = 1 # jump every 1 degrees + + def __init__(self, centerx, centery, radius, startangledegrees, endangledegrees, yradius=None, + annular=False, **kw): + SolidShape.__init__(self, kw) + while endangledegrees0.001: + degreedelta = min(self.degreedelta or 1.,angle) + radiansdelta = degreedelta*degreestoradians + n = max(1,int(angle/radiansdelta+0.5)) + radiansdelta = angle/n + n += 1 + else: + n = 1 + radiansdelta = 0 + CA = [] + CAA = CA.append + a = points.append + for angle in range(n): + angle = startangle+angle*radiansdelta + CAA((cos(angle),sin(angle))) + for c,s in CA: + a(centerx+radius*c) + a(centery+yradius*s) + if (radius1==0 or radius1 is None) and (yradius1==0 or yradius1 is None): + a(centerx); a(centery) + else: + CA.reverse() + for c,s in CA: + a(centerx+radius1*c) + a(centery+yradius1*s) + if self.annular: + P = Path(fillMode=getattr(self,'fillMode', FILL_EVEN_ODD)) + P.moveTo(points[0],points[1]) + for x in range(2,2*n,2): + P.lineTo(points[x],points[x+1]) + P.closePath() + P.moveTo(points[2*n],points[2*n+1]) + for x in range(2*n+2,4*n,2): + P.lineTo(points[x],points[x+1]) + P.closePath() + return P + else: + return Polygon(points) + + def copy(self): + new = self.__class__(self.centerx, + self.centery, + self.radius, + self.startangledegrees, + self.endangledegrees) + new.setProperties(self.getProperties()) + return new + + def getBounds(self): + return self.asPolygon().getBounds() + +class Polygon(SolidShape): + """Defines a closed shape; Is implicitly + joined back to the start for you.""" + + _attrMap = AttrMap(BASE=SolidShape, + points = AttrMapValue(isListOfNumbers,desc="list of numbers in the form x1, y1, x2, y2 ... xn, yn"), + ) + + def __init__(self, points=[], **kw): + SolidShape.__init__(self, kw) + assert len(points) % 2 == 0, 'Point list must have even number of elements!' + self.points = points or [] + + def copy(self): + new = self.__class__(self.points) + new.setProperties(self.getProperties()) + return new + + def getBounds(self): + return getPointsBounds(self.points) + +class PolyLine(LineShape): + """Series of line segments. Does not define a + closed shape; never filled even if apparently joined. + Put the numbers in the list, not two-tuples.""" + + _attrMap = AttrMap(BASE=LineShape, + points = AttrMapValue(isListOfNumbers,desc="list of numbers in the form x1, y1, x2, y2 ... xn, yn"), + ) + + def __init__(self, points=[], **kw): + LineShape.__init__(self, kw) + points = points or [] + lenPoints = len(points) + if lenPoints: + if isSeq(points[0]): + L = [] + for (x,y) in points: + L.append(x) + L.append(y) + points = L + else: + assert len(points) % 2 == 0, 'Point list must have even number of elements!' + self.points = points + + def copy(self): + new = self.__class__(self.points) + new.setProperties(self.getProperties()) + return new + + def getBounds(self): + return getPointsBounds(self.points) + +class Hatching(Path): + '''define a hatching of a set of polygons defined by lists of the form [x0,y0,x1,y1,....,xn,yn]''' + + _attrMap = AttrMap(BASE=Path, + xyLists = AttrMapValue(EitherOr((isListOfNumbers,SequenceOf(isListOfNumbers,lo=1)),"xy list(s)"),desc="list(s) of numbers in the form x1, y1, x2, y2 ... xn, yn"), + angles = AttrMapValue(EitherOr((isNumber,isListOfNumbers,"angle(s)")),desc="the angle or list of angles at which hatching lines should be drawn"), + spacings = AttrMapValue(EitherOr((isNumber,isListOfNumbers,"spacings(s)")),desc="orthogonal distance(s) between hatching lines"), + ) + + def __init__(self, spacings=2, angles=45, xyLists=[], **kwds): + Path.__init__(self, **kwds) + if isListOfNumbers(xyLists): + xyLists = (xyLists,) + if isNumber(angles): + angles = (angles,) #turn into a sequence + if isNumber(spacings): + spacings = (spacings,) #turn into a sequence + i = len(angles)-len(spacings) + if i>0: + spacings = list(spacings)+i*[spacings[-1]] + + self.xyLists = xyLists + self.angles = angles + self.spacings = spacings + + moveTo = self.moveTo + lineTo = self.lineTo + + for i, theta in enumerate(angles): + spacing = spacings[i] + theta = radians(theta) + cosTheta = cos(theta) + sinTheta = sin(theta) + + spanMin = 0x7fffffff + spanMax = -spanMin + + # Loop to determine the span over which diagonal lines must be drawn. + for P in xyLists: + for j in range(0,len(P),2): + # rotated point, since the stripes may be at an angle. + y = P[j+1]*cosTheta-P[j]*sinTheta + spanMin = min(y,spanMin) + spanMax = max(y,spanMax) + + # Turn the span into a discrete step range. + spanStart = int(floor(spanMin/spacing)) - 1 + spanEnd = int(floor(spanMax/spacing)) + 1 + + # Loop to create all stripes. + for step in range(spanStart,spanEnd): + nodeX = [] + stripeY = spacing*step + + # Loop to build a node list for one row of stripes. + for P in xyLists: + k = len(P)-2 #start by comparing with the last point + for j in range(0,len(P),2): + a = P[k] + b = P[k+1] + a1 = a*cosTheta + b*sinTheta + b1 = b*cosTheta - a*sinTheta + x = P[j] + y = P[j+1] + + x1 = x*cosTheta+y*sinTheta + y1 = y*cosTheta-x*sinTheta + + # Find the node, if any. + if (b1=stripeY) or y1=stripeY: + nodeX.append(a1+(x1-a1)*(stripeY-b1)/(y1-b1)) + + k = j + + nodeX.sort() + + # Loop to draw one row of line segments. + for j in range(0,len(nodeX),2): + # Rotate the points back to their original coordinate system. + a = nodeX[j]*cosTheta - stripeY*sinTheta + b = stripeY*cosTheta+nodeX[j]*sinTheta + x = nodeX[j+1]*cosTheta - stripeY*sinTheta + y = stripeY*cosTheta + nodeX[j+1]*sinTheta + + #Draw a single stripe segment. + moveTo(a,b) + lineTo(x,y) + +def numericXShift(tA,text,w,fontName,fontSize,encoding=None,pivotCharacter=decimalSymbol): + dp = getattr(tA,'_dp',pivotCharacter) + i = text.rfind(dp) + if i>=0: + dpOffs = getattr(tA,'_dpLen',0) + w = dpOffs + stringWidth(text[:i],fontName,fontSize,encoding) + return w + +class String(Shape): + """Not checked against the spec, just a way to make something work. + Can be anchored left, middle or end.""" + + # to do. + _attrMap = AttrMap( + x = AttrMapValue(isNumber,desc="x point of anchoring"), + y = AttrMapValue(isNumber,desc="y point of anchoring"), + text = AttrMapValue(isString,desc="the text of the string"), + fontName = AttrMapValue(None,desc="font name of the text - font is either acrobat standard or registered when using external font."), + fontSize = AttrMapValue(isNumber,desc="font size"), + fillColor = AttrMapValue(isColorOrNone,desc="color of the font"), + textAnchor = AttrMapValue(OneOf('start','middle','end','numeric'),desc="treat (x,y) as one of the options below."), + encoding = AttrMapValue(isString), + textRenderMode = AttrMapValue(OneOf(0,1,2,3,4,5,6,7),desc="Control whether text is filled/stroked etc etc"), + ) + encoding = 'utf8' + + def __init__(self, x, y, text, **kw): + self.x = x + self.y = y + self.text = text + self.textAnchor = 'start' + self.fontName = STATE_DEFAULTS['fontName'] + self.fontSize = STATE_DEFAULTS['fontSize'] + self.fillColor = STATE_DEFAULTS['fillColor'] + self.setProperties(kw) + + def getEast(self): + return self.x + stringWidth(self.text,self.fontName,self.fontSize, self.encoding) + + def copy(self): + new = self.__class__(self.x, self.y, self.text) + new.setProperties(self.getProperties()) + return new + + def getBounds(self): + # assumes constant drop of 0.2*size to baseline + t = self.text + w = stringWidth(t,self.fontName,self.fontSize,self.encoding) + tA = self.textAnchor + x = self.x + if tA!='start': + if tA=='middle': + x -= 0.5*w + elif tA=='end': + x -= w + elif tA=='numeric': + x -= numericXShift(tA,t,w,self.fontName,self.fontSize,self.encoding) + return (x, self.y - 0.2 * self.fontSize, x+w, self.y + self.fontSize) + +class UserNode(_DrawTimeResizeable): + """A simple template for creating a new node. The user (Python + programmer) may subclasses this. provideNode() must be defined to + provide a Shape primitive when called by a renderer. It does + NOT inherit from Shape, as the renderer always replaces it, and + your own classes can safely inherit from it without getting + lots of unintended behaviour.""" + + def provideNode(self): + """Override this to create your own node. This lets widgets be + added to drawings; they must create a shape (typically a group) + so that the renderer can draw the custom node.""" + + raise NotImplementedError("this method must be redefined by the user/programmer") + +class DirectDraw(Shape): + """try to draw directly on the canvas""" + def drawDirectly(self,canvas): + raise NotImplementedError("this method must be redefined by the user/programmer") + +def test(): + r = Rect(10,10,200,50) + import pprint + pp = pprint.pprint + w = sys.stdout.write + w('a Rectangle: ') + pp(r.getProperties()) + w('\nverifying...') + r.verify() + w(' OK\n') + #print 'setting rect.z = "spam"' + #r.z = 'spam' + w('deleting rect.width ') + del r.width + w('verifying...') + r.verify() + +if __name__=='__main__': + test() diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/svgpath.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/svgpath.py new file mode 100644 index 0000000000000000000000000000000000000000..e46481f59e42f98b335c0aaba70e1129fe4a5367 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/svgpath.py @@ -0,0 +1,451 @@ +'''this code is derived from that used by svglib.''' +__all__=('SvgPath',) +import re, copy +from math import acos, ceil, copysign, cos, degrees, fabs, hypot, radians, sin, sqrt +from .shapes import Group, mmult, rotate, translate, transformPoint, Path, FILL_EVEN_ODD, _CLOSEPATH, UserNode + +def split_floats(op, min_num, value): + """Split `value`, a list of numbers as a string, to a list of float numbers. + + Also optionally insert a `l` or `L` operation depending on the operation + and the length of values. + Example: with op='m' and value='10,20 30,40,' the returned value will be + ['m', [10.0, 20.0], 'l', [30.0, 40.0]] + """ + floats = [float(seq) for seq in re.findall(r'(-?\d*\.?\d*(?:[eE][+-]?\d+)?)', value) if seq] + res = [] + for i in range(0, len(floats), min_num): + if i > 0 and op in {'m', 'M'}: + op = 'l' if op == 'm' else 'L' + res.extend([op, floats[i:i + min_num]]) + return res + +def split_arc_values(op, value): + float_re = r'(-?\d*\.?\d*(?:[eE][+-]?\d+)?)' + flag_re = r'([1|0])' + # 3 numb, 2 flags, 1 coord pair + a_seq_re = r'[\s,]*'.join([ + float_re, float_re, float_re, flag_re, flag_re, float_re, float_re + ]) + r'[\s,]*' + res = [] + for seq in re.finditer(a_seq_re, value.strip()): + res.extend([op, [float(num) for num in seq.groups()]]) + return res + +def normalise_svg_path(attr): + """Normalise SVG path. + + This basically introduces operator codes for multi-argument + parameters. Also, it fixes sequences of consecutive M or m + operators to MLLL... and mlll... operators. It adds an empty + list as argument for Z and z only in order to make the resul- + ting list easier to iterate over. + + E.g. "M 10 20, M 20 20, L 30 40, 40 40, Z" + -> ['M', [10, 20], 'L', [20, 20], 'L', [30, 40], 'L', [40, 40], 'Z', []] + """ + + # operator codes mapped to the minimum number of expected arguments + ops = { + 'A': 7, 'a': 7, + 'Q': 4, 'q': 4, 'T': 2, 't': 2, 'S': 4, 's': 4, + 'M': 2, 'L': 2, 'm': 2, 'l': 2, 'H': 1, 'V': 1, + 'h': 1, 'v': 1, 'C': 6, 'c': 6, 'Z': 0, 'z': 0, + } + op_keys = ops.keys() + + # do some preprocessing + result = [] + groups = re.split('([achlmqstvz])', attr.strip(), flags=re.I) + op = None + for item in groups: + if item.strip() == '': + continue + if item in op_keys: + # fix sequences of M to one M plus a sequence of L operators, + # same for m and l. + if item == 'M' and item == op: + op = 'L' + elif item == 'm' and item == op: + op = 'l' + else: + op = item + if ops[op] == 0: # Z, z + result.extend([op, []]) + else: + if op.lower() == 'a': + result.extend(split_arc_values(op, item)) + else: + result.extend(split_floats(op, ops[op], item)) + op = result[-2] # Remember last op + + return result + +def convert_quadratic_to_cubic_path(q0, q1, q2): + """ + Convert a quadratic Bezier curve through q0, q1, q2 to a cubic one. + """ + c0 = q0 + c1 = (q0[0] + 2 / 3 * (q1[0] - q0[0]), q0[1] + 2 / 3 * (q1[1] - q0[1])) + c2 = (c1[0] + 1 / 3 * (q2[0] - q0[0]), c1[1] + 1 / 3 * (q2[1] - q0[1])) + c3 = q2 + return c0, c1, c2, c3 + +# *********************************************** +# Helper functions for elliptical arc conversion. +# *********************************************** +def vector_angle(u, v): + d = hypot(*u) * hypot(*v) + if d == 0: + return 0 + c = (u[0] * v[0] + u[1] * v[1]) / d + if c < -1: + c = -1 + elif c > 1: + c = 1 + s = u[0] * v[1] - u[1] * v[0] + return degrees(copysign(acos(c), s)) + +def end_point_to_center_parameters(x1, y1, x2, y2, fA, fS, rx, ry, phi=0): + ''' + See http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes F.6.5 + note that we reduce phi to zero outside this routine + ''' + rx = fabs(rx) + ry = fabs(ry) + + # step 1 + if phi: + phi_rad = radians(phi) + sin_phi = sin(phi_rad) + cos_phi = cos(phi_rad) + tx = 0.5 * (x1 - x2) + ty = 0.5 * (y1 - y2) + x1d = cos_phi * tx - sin_phi * ty + y1d = sin_phi * tx + cos_phi * ty + else: + x1d = 0.5 * (x1 - x2) + y1d = 0.5 * (y1 - y2) + + # step 2 + # we need to calculate + # (rx*rx*ry*ry-rx*rx*y1d*y1d-ry*ry*x1d*x1d) + # ----------------------------------------- + # (rx*rx*y1d*y1d+ry*ry*x1d*x1d) + # + # that is equivalent to + # + # rx*rx*ry*ry + # = ----------------------------- - 1 + # (rx*rx*y1d*y1d+ry*ry*x1d*x1d) + # + # 1 + # = -------------------------------- - 1 + # x1d*x1d/(rx*rx) + y1d*y1d/(ry*ry) + # + # = 1/r - 1 + # + # it turns out r is what they recommend checking + # for the negative radicand case + r = x1d * x1d / (rx * rx) + y1d * y1d / (ry * ry) + if r > 1: + rr = sqrt(r) + rx *= rr + ry *= rr + r = x1d * x1d / (rx * rx) + y1d * y1d / (ry * ry) + r = 1 / r - 1 + elif r != 0: + r = 1 / r - 1 + if -1e-10 < r < 0: + r = 0 + r = sqrt(r) + if fA == fS: + r = -r + cxd = (r * rx * y1d) / ry + cyd = -(r * ry * x1d) / rx + + # step 3 + if phi: + cx = cos_phi * cxd - sin_phi * cyd + 0.5 * (x1 + x2) + cy = sin_phi * cxd + cos_phi * cyd + 0.5 * (y1 + y2) + else: + cx = cxd + 0.5 * (x1 + x2) + cy = cyd + 0.5 * (y1 + y2) + + # step 4 + theta1 = vector_angle((1, 0), ((x1d - cxd) / rx, (y1d - cyd) / ry)) + dtheta = vector_angle( + ((x1d - cxd) / rx, (y1d - cyd) / ry), + ((-x1d - cxd) / rx, (-y1d - cyd) / ry) + ) % 360 + if fS == 0 and dtheta > 0: + dtheta -= 360 + elif fS == 1 and dtheta < 0: + dtheta += 360 + return cx, cy, rx, ry, -theta1, -dtheta + +def bezier_arc_from_centre(cx, cy, rx, ry, start_ang=0, extent=90): + if abs(extent) <= 90: + nfrag = 1 + frag_angle = extent + else: + nfrag = ceil(abs(extent) / 90) + frag_angle = extent / nfrag + if frag_angle == 0: + return [] + + frag_rad = radians(frag_angle) + half_rad = frag_rad * 0.5 + kappa = abs(4 / 3 * (1 - cos(half_rad)) / sin(half_rad)) + + if frag_angle < 0: + kappa = -kappa + + point_list = [] + theta1 = radians(start_ang) + start_rad = theta1 + frag_rad + + c1 = cos(theta1) + s1 = sin(theta1) + for i in range(nfrag): + c0 = c1 + s0 = s1 + theta1 = start_rad + i * frag_rad + c1 = cos(theta1) + s1 = sin(theta1) + point_list.append((cx + rx * c0, + cy - ry * s0, + cx + rx * (c0 - kappa * s0), + cy - ry * (s0 + kappa * c0), + cx + rx * (c1 + kappa * s1), + cy - ry * (s1 - kappa * c1), + cx + rx * c1, + cy - ry * s1)) + return point_list + +def bezier_arc_from_end_points(x1, y1, rx, ry, phi, fA, fS, x2, y2): + if (x1 == x2 and y1 == y2): + # From https://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes: + # If the endpoints (x1, y1) and (x2, y2) are identical, then this is + # equivalent to omitting the elliptical arc segment entirely. + return [] + if phi: + # Our box bezier arcs can't handle rotations directly + # move to a well known point, eliminate phi and transform the other point + mx = mmult(rotate(-phi), translate(-x1, -y1)) + tx2, ty2 = transformPoint(mx, (x2, y2)) + # Convert to box form in unrotated coords + cx, cy, rx, ry, start_ang, extent = end_point_to_center_parameters( + 0, 0, tx2, ty2, fA, fS, rx, ry + ) + bp = bezier_arc_from_centre(cx, cy, rx, ry, start_ang, extent) + # Re-rotate by the desired angle and add back the translation + mx = mmult(translate(x1, y1), rotate(phi)) + res = [] + for x1, y1, x2, y2, x3, y3, x4, y4 in bp: + res.append( + transformPoint(mx, (x1, y1)) + transformPoint(mx, (x2, y2)) + + transformPoint(mx, (x3, y3)) + transformPoint(mx, (x4, y4)) + ) + return res + else: + cx, cy, rx, ry, start_ang, extent = end_point_to_center_parameters( + x1, y1, x2, y2, fA, fS, rx, ry + ) + return bezier_arc_from_centre(cx, cy, rx, ry, start_ang, extent) + +class SvgPath(Path,UserNode): + """Path, from an svg path string""" + def __init__(self, s, isClipPath=0, autoclose=None, fillMode=FILL_EVEN_ODD, **kw): + vswap = kw.pop('vswap',0) + hswap = kw.pop('hswap',0) + super().__init__( + points=None,operators=None, + isClipPath=isClipPath, + autoclose=autoclose, + fillMode=fillMode, **kw) + if not s: return + normPath = normalise_svg_path(s) + points = self.points + # Track subpaths needing to be closed later + unclosed_subpath_pointers = [] + subpath_start = [] + lastop = '' + last_quadratic_cp = None + + for i in range(0, len(normPath), 2): + op, nums = normPath[i:i+2] + + if op in ('m', 'M') and i > 0 and self.operators[-1] != _CLOSEPATH: + unclosed_subpath_pointers.append(len(self.operators)) + + # moveto absolute + if op == 'M': + self.moveTo(*nums) + subpath_start = points[-2:] + # lineto absolute + elif op == 'L': + self.lineTo(*nums) + + # moveto relative + elif op == 'm': + if len(points) >= 2: + if lastop in ('Z', 'z'): + starting_point = subpath_start + else: + starting_point = points[-2:] + xn, yn = starting_point[0] + nums[0], starting_point[1] + nums[1] + self.moveTo(xn, yn) + else: + self.moveTo(*nums) + subpath_start = points[-2:] + # lineto relative + elif op == 'l': + xn, yn = points[-2] + nums[0], points[-1] + nums[1] + self.lineTo(xn, yn) + + # horizontal/vertical line absolute + elif op == 'H': + self.lineTo(nums[0], points[-1]) + elif op == 'V': + self.lineTo(points[-2], nums[0]) + + # horizontal/vertical line relative + elif op == 'h': + self.lineTo(points[-2] + nums[0], points[-1]) + elif op == 'v': + self.lineTo(points[-2], points[-1] + nums[0]) + + # cubic bezier, absolute + elif op == 'C': + self.curveTo(*nums) + elif op == 'S': + x2, y2, xn, yn = nums + if len(points) < 4 or lastop not in {'c', 'C', 's', 'S'}: + xp, yp, x0, y0 = points[-2:] * 2 + else: + xp, yp, x0, y0 = points[-4:] + xi, yi = x0 + (x0 - xp), y0 + (y0 - yp) + self.curveTo(xi, yi, x2, y2, xn, yn) + + # cubic bezier, relative + elif op == 'c': + xp, yp = points[-2:] + x1, y1, x2, y2, xn, yn = nums + self.curveTo(xp + x1, yp + y1, xp + x2, yp + y2, xp + xn, yp + yn) + elif op == 's': + x2, y2, xn, yn = nums + if len(points) < 4 or lastop not in {'c', 'C', 's', 'S'}: + xp, yp, x0, y0 = points[-2:] * 2 + else: + xp, yp, x0, y0 = points[-4:] + xi, yi = x0 + (x0 - xp), y0 + (y0 - yp) + self.curveTo(xi, yi, x0 + x2, y0 + y2, x0 + xn, y0 + yn) + + # quadratic bezier, absolute + elif op == 'Q': + x0, y0 = points[-2:] + x1, y1, xn, yn = nums + last_quadratic_cp = (x1, y1) + (x0, y0), (x1, y1), (x2, y2), (xn, yn) = \ + convert_quadratic_to_cubic_path((x0, y0), (x1, y1), (xn, yn)) + self.curveTo(x1, y1, x2, y2, xn, yn) + elif op == 'T': + if last_quadratic_cp is not None: + xp, yp = last_quadratic_cp + else: + xp, yp = points[-2:] + x0, y0 = points[-2:] + xi, yi = x0 + (x0 - xp), y0 + (y0 - yp) + last_quadratic_cp = (xi, yi) + xn, yn = nums + (x0, y0), (x1, y1), (x2, y2), (xn, yn) = \ + convert_quadratic_to_cubic_path((x0, y0), (xi, yi), (xn, yn)) + self.curveTo(x1, y1, x2, y2, xn, yn) + + # quadratic bezier, relative + elif op == 'q': + x0, y0 = points[-2:] + x1, y1, xn, yn = nums + x1, y1, xn, yn = x0 + x1, y0 + y1, x0 + xn, y0 + yn + last_quadratic_cp = (x1, y1) + (x0, y0), (x1, y1), (x2, y2), (xn, yn) = \ + convert_quadratic_to_cubic_path((x0, y0), (x1, y1), (xn, yn)) + self.curveTo(x1, y1, x2, y2, xn, yn) + elif op == 't': + if last_quadratic_cp is not None: + xp, yp = last_quadratic_cp + else: + xp, yp = points[-2:] + x0, y0 = points[-2:] + xn, yn = nums + xn, yn = x0 + xn, y0 + yn + xi, yi = x0 + (x0 - xp), y0 + (y0 - yp) + last_quadratic_cp = (xi, yi) + (x0, y0), (x1, y1), (x2, y2), (xn, yn) = \ + convert_quadratic_to_cubic_path((x0, y0), (xi, yi), (xn, yn)) + self.curveTo(x1, y1, x2, y2, xn, yn) + + # elliptical arc + elif op in ('A', 'a'): + rx, ry, phi, fA, fS, x2, y2 = nums + x1, y1 = points[-2:] + if op == 'a': + x2 += x1 + y2 += y1 + if abs(rx) <= 1e-10 or abs(ry) <= 1e-10: + self.lineTo(x2, y2) + else: + bp = bezier_arc_from_end_points(x1, y1, rx, ry, phi, fA, fS, x2, y2) + for _, _, x1, y1, x2, y2, xn, yn in bp: + self.curveTo(x1, y1, x2, y2, xn, yn) + + # close self + elif op in ('Z', 'z'): + self.closePath() + + else: + logger.debug("Suspicious self operator: %s", op) + + if op not in ('Q', 'q', 'T', 't'): + last_quadratic_cp = None + lastop = op + + if self.operators[-1] != _CLOSEPATH: + unclosed_subpath_pointers.append(len(self.operators)) + + if vswap or hswap: + b = self.getBounds() + if hswap: + m = b[2]+b[0] + for i in range(0,len(points),2): + points[i] = m - points[i] + if vswap: + m = b[3]+b[1] + for i in range(1,len(points),2): + points[i] = m - points[i] + + if unclosed_subpath_pointers and self.fillColor is not None: + # ReportLab doesn't fill unclosed paths, so we are creating a copy + # of self with all subpaths closed, but without stroke. + # https://bitbucket.org/rptlab/reportlab/issues/99/ + closed_path = Path() + closed_path.__dict__.update(copy.deepcopy(self.__dict__)) + for pointer in reversed(unclosed_subpath_pointers): + closed_path.operators.insert(pointer, _CLOSEPATH) + self.__closed_path = closed_path + self.fillColor = None + else: + self.__closed_path = None + + def provideNode(self): + p = Path() + p.__dict__ = self.__dict__.copy() + del p._SvgPath__closed_path + if self.__closed_path: + g = Group() + g.add(self.__closed_path) + g.add(p) + return g + else: + return p diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/testdrawings.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/testdrawings.py new file mode 100644 index 0000000000000000000000000000000000000000..ebbf015309814c7448c904bd9cd2ed259b44b12c --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/testdrawings.py @@ -0,0 +1,296 @@ +#!/bin/env python +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/graphics/testdrawings.py +__version__='3.3.0' +__doc__="""Defines some standard drawings to use as test cases + +This contains a number of routines to generate test drawings +for reportlab/graphics. For now they are contrived, but we will expand them +to try and trip up any parser. Feel free to add more. + +""" + +from reportlab.graphics.shapes import * +from reportlab.lib import colors + +def getDrawing1(): + """Hello World, on a rectangular background""" + + D = Drawing(400, 200) + D.add(Rect(50, 50, 300, 100, fillColor=colors.yellow)) #round corners + D.add(String(180,100, 'Hello World', fillColor=colors.red)) + + + return D + + +def getDrawing2(): + """This demonstrates the basic shapes. There are + no groups or references. Each solid shape should have + a purple fill.""" + D = Drawing(400, 200) #, fillColor=colors.purple) + + D.add(Line(10,10,390,190)) + D.add(Circle(100,100,20, fillColor=colors.purple)) + D.add(Circle(200,100,20, fillColor=colors.purple)) + D.add(Circle(300,100,20, fillColor=colors.purple)) + + D.add(Wedge(330,100,40, -10,40, fillColor=colors.purple)) + + D.add(PolyLine([120,10,130,20,140,10,150,20,160,10, + 170,20,180,10,190,20,200,10])) + + D.add(Polygon([300,20,350,20,390,80,300,75, 330, 40])) + + D.add(Ellipse(50, 150, 40, 20)) + + D.add(Rect(120, 150, 60, 30, + strokeWidth=10, + strokeColor=colors.red, + fillColor=colors.yellow)) #square corners + + D.add(Rect(220, 150, 60, 30, 10, 10)) #round corners + + D.add(String(10,50, 'Basic Shapes', fillColor=colors.black)) + + return D + + +##def getDrawing2(): +## """This drawing uses groups. Each group has two circles and a comment. +## The line style is set at group level and should be red for the left, +## bvlue for the right.""" +## D = Drawing(400, 200) +## +## Group1 = Group() +## +## Group1.add(String(50, 50, 'Group 1', fillColor=colors.black)) +## Group1.add(Circle(75,100,25)) +## Group1.add(Circle(125,100,25)) +## D.add(Group1) +## +## Group2 = Group( +## String(250, 50, 'Group 2', fillColor=colors.black), +## Circle(275,100,25), +## Circle(325,100,25)#, + + +##def getDrawing2(): +## """This drawing uses groups. Each group has two circles and a comment. +## The line style is set at group level and should be red for the left, +## bvlue for the right.""" +## D = Drawing(400, 200) +## +## Group1 = Group() +## +## Group1.add(String(50, 50, 'Group 1', fillColor=colors.black)) +## Group1.add(Circle(75,100,25)) +## Group1.add(Circle(125,100,25)) +## D.add(Group1) +## +## Group2 = Group( +## String(250, 50, 'Group 2', fillColor=colors.black), +## Circle(275,100,25), +## Circle(325,100,25)#, +## +## #group attributes +## #strokeColor=colors.blue +## ) +## D.add(Group2) + +## return D +## +## +##def getDrawing3(): +## """This uses a named reference object. The house is a 'subroutine' +## the basic brick colored walls are defined, but the roof and window +## color are undefined and may be set by the container.""" +## +## D = Drawing(400, 200, fill=colors.bisque) +## +## +## House = Group( +## Rect(2,20,36,30, fill=colors.bisque), #walls +## Polygon([0,20,40,20,20,5]), #roof +## Rect(8, 38, 8, 12), #door +## Rect(25, 38, 8, 7), #window +## Rect(8, 25, 8, 7), #window +## Rect(25, 25, 8, 7) #window +## +## ) +## D.addDef('MyHouse', House) +## +## # one row all the same color +## D.add(String(20, 40, 'British Street...',fill=colors.black)) +## for i in range(6): +## x = i * 50 +## D.add(NamedReference('MyHouse', +## House, +## transform=translate(x, 40), +## fill = colors.brown +## ) +## ) +## +## # now do a row all different +## D.add(String(20, 120, 'Mediterranean Street...',fill=colors.black)) +## x = 0 +## for color in (colors.blue, colors.yellow, colors.orange, +## colors.red, colors.green, colors.chartreuse): +## D.add(NamedReference('MyHouse', +## House, +## transform=translate(x,120), +## fill = color, +## ) +## ) +## x = x + 50 +## #..by popular demand, the mayor gets a big one at the end +## D.add(NamedReference('MyHouse', +## House, +## transform=mmult(translate(x,110), scale(1.2,1.2)), +## fill = color, +## ) +## ) +## +## +## return D +## +##def getDrawing4(): +## """This tests that attributes are 'unset' correctly when +## one steps back out of a drawing node. All the circles are part of a +## group setting the line color to blue; the second circle explicitly +## sets it to red. Ideally, the third circle should go back to blue.""" +## D = Drawing(400, 200) +## +## +## G = Group( +## Circle(100,100,20), +## Circle(200,100,20, stroke=colors.blue), +## Circle(300,100,20), +## stroke=colors.red, +## stroke_width=3, +## fill=colors.aqua +## ) +## D.add(G) +## +## +## D.add(String(10,50, 'Stack Unwinding - should be red, blue, red')) +## +## return D +## +## +##def getDrawing5(): +## """This Rotates Coordinate Axes""" +## D = Drawing(400, 200) +## +## +## +## Axis = Group( +## Line(0,0,100,0), #x axis +## Line(0,0,0,50), # y axis +## Line(0,10,10,10), #ticks on y axis +## Line(0,20,10,20), +## Line(0,30,10,30), +## Line(0,40,10,40), +## Line(10,0,10,10), #ticks on x axis +## Line(20,0,20,10), +## Line(30,0,30,10), +## Line(40,0,40,10), +## Line(50,0,50,10), +## Line(60,0,60,10), +## Line(70,0,70,10), +## Line(80,0,80,10), +## Line(90,0,90,10), +## String(20, 35, 'Axes', fill=colors.black) +## ) +## +## D.addDef('Axes', Axis) +## +## D.add(NamedReference('Axis', Axis, +## transform=translate(10,10))) +## D.add(NamedReference('Axis', Axis, +## transform=mmult(translate(150,10),rotate(15))) +## ) +## return D +## +##def getDrawing6(): +## """This Rotates Text""" +## D = Drawing(400, 300, fill=colors.black) +## +## xform = translate(200,150) +## C = (colors.black,colors.red,colors.green,colors.blue,colors.brown,colors.gray, colors.pink, +## colors.lavender,colors.lime, colors.mediumblue, colors.magenta, colors.limegreen) +## +## for i in range(12): +## D.add(String(0, 0, ' - - Rotated Text', fill=C[i%len(C)], transform=mmult(xform, rotate(30*i)))) +## +## return D +## +##def getDrawing7(): +## """This defines and tests a simple UserNode0 (the trailing zero denotes +## an experimental method which is not part of the supported API yet). +## Each of the four charts is a subclass of UserNode which generates a random +## series when rendered.""" +## +## class MyUserNode(UserNode0): +## import whrandom, math +## +## +## def provideNode(self, sender): +## """draw a simple chart that changes everytime it's drawn""" +## # print "here's a random number %s" % self.whrandom.random() +## #print "MyUserNode.provideNode being called by %s" % sender +## g = Group() +## #g._state = self._state # this is naughty +## PingoNode.__init__(g, self._state) # is this less naughty ? +## w = 80.0 +## h = 50.0 +## g.add(Rect(0,0, w, h, stroke=colors.black)) +## N = 10.0 +## x,y = (0,h) +## dx = w/N +## for ii in range(N): +## dy = (h/N) * self.whrandom.random() +## g.add(Line(x,y,x+dx, y-dy)) +## x = x + dx +## y = y - dy +## return g +## +## D = Drawing(400,200, fill=colors.white) # AR - same size as others +## +## D.add(MyUserNode()) +## +## graphcolor= [colors.green, colors.red, colors.brown, colors.purple] +## for ii in range(4): +## D.add(Group( MyUserNode(stroke=graphcolor[ii], stroke_width=2), +## transform=translate(ii*90,0) )) +## +## #un = MyUserNode() +## #print un.provideNode() +## return D +## +##def getDrawing8(): +## """Test Path operations--lineto, curveTo, etc.""" +## D = Drawing(400, 200, fill=None, stroke=colors.purple, stroke_width=2) +## +## xform = translate(200,100) +## C = (colors.black,colors.red,colors.green,colors.blue,colors.brown,colors.gray, colors.pink, +## colors.lavender,colors.lime, colors.mediumblue, colors.magenta, colors.limegreen) +## p = Path(50,50) +## p.lineTo(100,100) +## p.moveBy(-25,25) +## p.curveTo(150,125, 125,125, 200,50) +## p.curveTo(175, 75, 175, 98, 62, 87) +## +## +## D.add(p) +## D.add(String(10,30, 'Tests of path elements-lines and bezier curves-and text formating')) +## D.add(Line(220,150, 220,200, stroke=colors.red)) +## D.add(String(220,180, "Text should be centered", text_anchor="middle") ) +## +## +## return D + + +if __name__=='__main__': + print(__doc__) diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/testshapes.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/testshapes.py new file mode 100644 index 0000000000000000000000000000000000000000..a4317ef1b02ccd87b5e27d4f0e4c6212d6d53397 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/testshapes.py @@ -0,0 +1,576 @@ +#!/bin/env python +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/graphics/testshapes.py + +# testshapes.py - draws shapes onto a PDF canvas. + + +__version__ = ''' $Id $ ''' +__doc__='''Execute this script to see some test drawings. + +This contains a number of routines to generate test drawings +for reportlab/graphics. For now many of them are contrived, +but we will expand them to try and trip up any parser. +Feel free to add more. +''' + +import os, sys +from io import BytesIO + +from reportlab.lib import colors +from reportlab.lib.units import cm +from reportlab.lib.utils import asNative, base64_decodebytes +from reportlab.pdfgen.canvas import Canvas +from reportlab.pdfbase.pdfmetrics import stringWidth +from reportlab.graphics.shapes import * +import unittest + +_FONTS = ['Times-Roman','Vera','Times-BoldItalic',] + +def _setup(): + from reportlab.pdfbase import pdfmetrics, ttfonts + pdfmetrics.registerFont(ttfonts.TTFont("Vera", "Vera.ttf")) + pdfmetrics.registerFont(ttfonts.TTFont("VeraBd", "VeraBd.ttf")) + pdfmetrics.registerFont(ttfonts.TTFont("VeraIt", "VeraIt.ttf")) + pdfmetrics.registerFont(ttfonts.TTFont("VeraBI", "VeraBI.ttf")) + F = ['Times-Roman','Courier','Helvetica','Vera', 'VeraBd', 'VeraIt', 'VeraBI'] + if sys.platform=='win32': + for name, ttf in [ + ('Adventurer Light SF','Advlit.ttf'),('ArialMS','ARIAL.TTF'), + ('Arial Unicode MS', 'ARIALUNI.TTF'), + ('Book Antiqua','BKANT.TTF'), + ('Century Gothic','GOTHIC.TTF'), + ('Comic Sans MS', 'COMIC.TTF'), + ('Elementary Heavy SF Bold','Vwagh.ttf'), + ('Firenze SF','flot.ttf'), + ('Garamond','GARA.TTF'), + ('Jagger','Rols.ttf'), + ('Monotype Corsiva','MTCORSVA.TTF'), + ('Seabird SF','seag.ttf'), + ('Tahoma','TAHOMA.TTF'), + ('VerdanaMS','VERDANA.TTF'), + ]: + for D in (r'c:\WINNT',r'c:\Windows'): + fn = os.path.join(D,'Fonts',ttf) + if os.path.isfile(fn): + try: + f = ttfonts.TTFont(name, fn) + pdfmetrics.registerFont(f) + F.append(name) + except: + pass + return F + +def resetFonts(): + for f in _setup(): + if f not in _FONTS: + _FONTS.append(f) +from reportlab.rl_config import register_reset +register_reset(resetFonts) +resetFonts() + +######################################################### +# +# Collections of shape drawings. +# +######################################################### +def getFailedDrawing(funcName): + """Generate a drawing in case something goes really wrong. + + This will create a drawing to be displayed whenever some + other drawing could not be executed, because the generating + function does something terribly wrong! The box contains + an attention triangle, plus some error message. + """ + + D = Drawing(400, 200) + + points = [200,170, 140,80, 260,80] + D.add(Polygon(points, + strokeWidth=0.5*cm, + strokeColor=colors.red, + fillColor=colors.yellow)) + + s = String(200, 40, + "Error in generating function '%s'!" % funcName, + textAnchor='middle') + D.add(s) + + return D + + +# These are the real drawings to be eye-balled. + +def getDrawing01(): + """Hello World, on a rectangular background. + + The rectangle's fillColor is yellow. + The string's fillColor is red. + """ + + D = Drawing(400, 200) + D.add(Rect(50, 50, 300, 100, fillColor=colors.yellow)) + D.add(String(180,100, 'Hello World', fillColor=colors.red)) + D.add(String(180,86, b'Special characters \xc2\xa2\xc2\xa9\xc2\xae\xc2\xa3\xce\xb1\xce\xb2', fillColor=colors.red)) + + return D + + +def getDrawing02(): + """Various Line shapes. + + The lines are blue and their strokeWidth is 5 mm. + One line has a strokeDashArray set to [5, 10, 15]. + """ + + D = Drawing(400, 200) + D.add(Line(50,50, 300,100, + strokeColor=colors.blue, + strokeWidth=0.5*cm, + )) + D.add(Line(50,100, 300,50, + strokeColor=colors.blue, + strokeWidth=0.5*cm, + strokeDashArray=[5, 10, 15], + )) + + #x = 1/0 # Comment this to see the actual drawing! + + return D + + +def getDrawing03(): + """Text strings in various sizes and different fonts. + + Font size increases from 12 to 36 and from bottom left + to upper right corner. The first ones should be in + Times-Roman. Finally, a solitary Courier string at + the top right corner. + """ + + D = Drawing(400, 200) + for size in range(12, 36, 4): + D.add(String(10+size*2, + 10+size*2, + 'Hello World', + fontName=_FONTS[0], + fontSize=size)) + + D.add(String(150, 150, + 'Hello World', + fontName=_FONTS[1], + fontSize=36)) + return D + + +def getDrawing04(): + """Text strings in various colours. + + Colours are blue, yellow and red from bottom left + to upper right. + """ + + D = Drawing(400, 200) + i = 0 + for color in (colors.blue, colors.yellow, colors.red): + D.add(String(50+i*30, 50+i*30, + 'Hello World', fillColor=color)) + i = i + 1 + + return D + + +def getDrawing05(): + """Text strings with various anchors (alignments). + + Text alignment conforms to the anchors in the left column. + """ + + D = Drawing(400, 200) + + lineX = 250 + D.add(Line(lineX,10, lineX,190, strokeColor=colors.gray)) + + y = 130 + for anchor in ('start', 'middle', 'end'): + D.add(String(lineX, y, 'Hello World', textAnchor=anchor)) + D.add(String(50, y, anchor + ':')) + y = y - 30 + + return D + + +def getDrawing06(): + """This demonstrates all the basic shapes at once. + + There are no groups or references. + Each solid shape should have a green fill. + """ + + green = colors.green + + D = Drawing(400, 200) #, fillColor=green) + + D.add(Line(10,10, 390,190)) + + D.add(Circle(100,100,20, fillColor=green)) + D.add(Circle(200,100,40, fillColor=green)) + D.add(Circle(300,100,30, fillColor=green)) + + D.add(Wedge(330,100,40, -10,40, fillColor=green)) + + D.add(PolyLine([120,10, 130,20, 140,10, 150,20, 160,10, + 170,20, 180,10, 190,20, 200,10], fillColor=green)) + + D.add(Polygon([300,20, 350,20, 390,80, 300,75, 330,40], fillColor=green)) + + D.add(Ellipse(50,150, 40, 20, fillColor=green)) + + D.add(Rect(120,150, 60,30, + strokeWidth=10, + strokeColor=colors.yellow, + fillColor=green)) #square corners + D.add(Rect(220, 150, 60, 30, 10, 10, fillColor=green)) #round corners + + D.add(String(10,50, 'Basic Shapes', fillColor=colors.black, fontName='Helvetica')) + + return D + +def getDrawing07(): + """This tests the ability to translate and rotate groups. The first set of axes should be + near the bottom left of the drawing. The second should be rotated counterclockwise + by 15 degrees. The third should be rotated by 30 degrees.""" + D = Drawing(400, 200) + + Axis = Group( + Line(0,0,100,0), #x axis + Line(0,0,0,50), # y axis + Line(0,10,10,10), #ticks on y axis + Line(0,20,10,20), + Line(0,30,10,30), + Line(0,40,10,40), + Line(10,0,10,10), #ticks on x axis + Line(20,0,20,10), + Line(30,0,30,10), + Line(40,0,40,10), + Line(50,0,50,10), + Line(60,0,60,10), + Line(70,0,70,10), + Line(80,0,80,10), + Line(90,0,90,10), + String(20, 35, 'Axes', fill=colors.black) + ) + + firstAxisGroup = Group(Axis) + firstAxisGroup.translate(10,10) + D.add(firstAxisGroup) + + secondAxisGroup = Group(Axis) + secondAxisGroup.translate(150,10) + secondAxisGroup.rotate(15) + + D.add(secondAxisGroup) + + + thirdAxisGroup = Group(Axis, transform=mmult(translate(300,10), rotate(30))) + D.add(thirdAxisGroup) + + return D + + +def getDrawing08(): + """This tests the ability to scale coordinates. The bottom left set of axes should be + near the bottom left of the drawing. The bottom right should be stretched vertically + by a factor of 2. The top left one should be stretched horizontally by a factor of 2. + The top right should have the vertical axiss leaning over to the right by 30 degrees.""" + D = Drawing(400, 200) + + Axis = Group( + Line(0,0,100,0), #x axis + Line(0,0,0,50), # y axis + Line(0,10,10,10), #ticks on y axis + Line(0,20,10,20), + Line(0,30,10,30), + Line(0,40,10,40), + Line(10,0,10,10), #ticks on x axis + Line(20,0,20,10), + Line(30,0,30,10), + Line(40,0,40,10), + Line(50,0,50,10), + Line(60,0,60,10), + Line(70,0,70,10), + Line(80,0,80,10), + Line(90,0,90,10), + String(20, 35, 'Axes', fill=colors.black) + ) + + firstAxisGroup = Group(Axis) + firstAxisGroup.translate(10,10) + D.add(firstAxisGroup) + + secondAxisGroup = Group(Axis) + secondAxisGroup.translate(150,10) + secondAxisGroup.scale(1,2) + D.add(secondAxisGroup) + + thirdAxisGroup = Group(Axis) + thirdAxisGroup.translate(10,125) + thirdAxisGroup.scale(2,1) + D.add(thirdAxisGroup) + + fourthAxisGroup = Group(Axis) + fourthAxisGroup.translate(250,125) + fourthAxisGroup.skew(30,0) + D.add(fourthAxisGroup) + + + return D + +def getDrawing09(): + """This tests rotated strings + + Some renderers will have a separate mechanism for font drawing. This test + just makes sure strings get transformed the same way as regular graphics.""" + D = Drawing(400, 200) + + fontName = _FONTS[0] + fontSize = 12 + text = "I should be totally horizontal and enclosed in a box" + textWidth = stringWidth(text, fontName, fontSize) + + + g1 = Group( + String(20, 20, text, fontName=fontName, fontSize = fontSize), + Rect(18, 18, textWidth + 4, fontSize + 4, fillColor=None) + ) + D.add(g1) + + text = "I should slope up by 15 degrees, so my right end is higher than my left" + textWidth = stringWidth(text, fontName, fontSize) + g2 = Group( + String(20, 20, text, fontName=fontName, fontSize = fontSize), + Rect(18, 18, textWidth + 4, fontSize + 4, fillColor=None) + ) + g2.translate(0, 50) + g2.rotate(15) + D.add(g2) + + return D + +def getDrawing10(): + """This tests nested groups with multiple levels of coordinate transformation. + Each box should be staggered up and to the right, moving by 25 points each time.""" + D = Drawing(400, 200) + + fontName = _FONTS[0] + fontSize = 12 + + g1 = Group( + Rect(0, 0, 100, 20, fillColor=colors.yellow), + String(5, 5, 'Text in the box', fontName=fontName, fontSize = fontSize) + ) + D.add(g1) + + g2 = Group(g1, transform = translate(25,25)) + D.add(g2) + + g3 = Group(g2, transform = translate(25,25)) + D.add(g3) + + g4 = Group(g3, transform = translate(25,25)) + D.add(g4) + + + return D + +from reportlab.graphics.widgets.signsandsymbols import SmileyFace +def getDrawing11(): + '''test of anchoring''' + def makeSmiley(x, y, size, color): + "Make a smiley data item representation." + d = size + s = SmileyFace() + s.fillColor = color + s.x = x-d + s.y = y-d + s.size = d*2 + return s + + D = Drawing(400, 200) #, fillColor=colors.purple) + g = Group(transform=(1,0,0,1,0,0)) + g.add(makeSmiley(100,100,10,colors.red)) + g.add(Line(90,100,110,100,strokeColor=colors.green)) + g.add(Line(100,90,100,110,strokeColor=colors.green)) + D.add(g) + g = Group(transform=(2,0,0,2,100,-100)) + g.add(makeSmiley(100,100,10,colors.blue)) + g.add(Line(90,100,110,100,strokeColor=colors.green)) + g.add(Line(100,90,100,110,strokeColor=colors.green)) + D.add(g) + g = Group(transform=(2,0,0,2,0,0)) + return D + + +def getDrawing12(): + """Text strings in a non-standard font. + All that is required is to place the .afm and .pfb files + on the font path given in rl_config.py, + for example in reportlab/fonts/. + """ + faceName = "DarkGardenMK" + D = Drawing(400, 200) + for size in range(12, 36, 4): + D.add(String(10+size*2, + 10+size*2, + 'Hello World', + fontName=faceName, + fontSize=size)) + return D + +def getDrawing13(): + 'Test Various TTF Fonts' + + def drawit(F,w=400,h=200,fontSize=12,slack=2,gap=5): + D = Drawing(w,h) + th = 2*gap + fontSize*1.2 + gh = gap + .2*fontSize + y = h + maxx = 0 + for fontName in F: + y -= th + text = fontName+asNative(b': I should be totally horizontal and enclosed in a box and end in alphabetagamma \xc2\xa2\xc2\xa9\xc2\xae\xc2\xa3\xca\xa5\xd0\x96\xd6\x83\xd7\x90\xd9\x82\xe0\xa6\x95\xce\xb1\xce\xb2\xce\xb3') + textWidth = stringWidth(text, fontName, fontSize) + maxx = max(maxx,textWidth+20) + D.add( + Group(Rect(8, y-gh, textWidth + 4, th, strokeColor=colors.red, strokeWidth=.5, fillColor=colors.lightgrey), + String(10, y, text, fontName=fontName, fontSize = fontSize))) + y -= 5 + return maxx, h-y+gap, D + maxx, maxy, D = drawit(_FONTS) + if maxx>400 or maxy>200: _,_,D = drawit(_FONTS,maxx,maxy) + return D + +def smallArrow(): + '''create a small PIL image''' + from reportlab.graphics.renderPM import _getImage + b = base64_decodebytes(b'''R0lGODdhCgAHAIMAAP/////29v/d3f+ysv9/f/9VVf9MTP8iIv8ICP8AAAAAAAAAAAAAAAAAAAAA +AAAAACwAAAAACgAHAAAIMwABCBxIsKABAQASFli4MAECAgEAJJhIceKBAQkyasx4YECBjx8TICAQ +AIDJkwYEAFgZEAA7''') + return _getImage().open(BytesIO(b)) + +def getDrawing14(): + '''test shapes.Image''' + from reportlab.graphics.shapes import Image + D = Drawing(400, 200) + im0 = smallArrow() + D.add(Image(x=0,y=0,width=None,height=None,path=im0)) + im1 = smallArrow() + D.add(Image(x=400-20,y=200-14,width=20,height=14,path=im1)) + return D + +def getAllFunctionDrawingNames(doTTF=1): + "Get a list of drawing function names from somewhere." + + funcNames = [] + + # Here we get the names from the global name space. + symbols = list(globals().keys()) + symbols.sort() + for funcName in symbols: + if funcName[0:10] == 'getDrawing': + if doTTF or funcName!='getDrawing13': + funcNames.append(funcName) + + return funcNames + +def _evalFuncDrawing(name, D, l=None, g=None): + if g is None: g = globals() + if l is None: l = locals() + func = l.get(name,g.get(name,None)) + try: + d = func() + except: + d = getFailedDrawing(name) + D.append((d, getattr(func,'.__doc__',''), name[3:])) + +def getAllTestDrawings(doTTF=1): + D = [] + for f in getAllFunctionDrawingNames(doTTF=doTTF): + _evalFuncDrawing(f,D) + return D + +def writePDF(drawings): + "Create and save a PDF file containing some drawings." + + pdfPath = os.path.splitext(sys.argv[0])[0] + '.pdf' + c = Canvas(pdfPath) + c.setFont(_FONTS[0], 32) + c.drawString(80, 750, 'ReportLab Graphics-Shapes Test') + + # Print drawings in a loop, with their doc strings. + c.setFont(_FONTS[0], 12) + y = 740 + i = 1 + for (drawing, docstring, funcname) in drawings: + if y < 300: # Allows 5-6 lines of text. + c.showPage() + y = 740 + # Draw a title. + y = y - 30 + c.setFont(_FONTS[2],12) + c.drawString(80, y, '%s (#%d)' % (funcname, i)) + c.setFont(_FONTS[0],12) + y = y - 14 + textObj = c.beginText(80, y) + textObj.textLines(docstring) + c.drawText(textObj) + y = textObj.getY() + y = y - drawing.height + drawing.drawOn(c, 80, y) + i = i + 1 + + c.save() + print('wrote %s ' % pdfPath) + + +class ShapesTestCase(unittest.TestCase): + "Test generating all kinds of shapes." + + def setUp(self): + "Prepare some things before the tests start." + + self.funcNames = getAllFunctionDrawingNames() + self.drawings = [] + + + def tearDown(self): + "Do what has to be done after the tests are over." + + writePDF(self.drawings) + + + # This should always succeed. If each drawing would be + # wrapped in a dedicated test method like this one, it + # would be possible to have a count for wrong tests + # as well... Something like this is left for later... + def testAllDrawings(self): + "Make a list of drawings." + + for f in self.funcNames: + if f[0:10] == 'getDrawing': + # Make an instance and get its doc string. + # If that fails, use a default error drawing. + _evalFuncDrawing(f,self.drawings) + + +def makeSuite(): + "Make a test suite for unit testing." + + suite = unittest.TestSuite() + suite.addTest(ShapesTestCase('testAllDrawings')) + return suite + + +if __name__ == "__main__": + unittest.TextTestRunner().run(makeSuite()) diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/transform.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/transform.py new file mode 100644 index 0000000000000000000000000000000000000000..fb4be2f691826f0aa4f7515b99aef1dcfb383ab7 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/transform.py @@ -0,0 +1,99 @@ +'''functions for 2D affine transformations''' +__all__ = ( + 'nullTransform', + 'translate', + 'scale', + 'rotate', + 'skewX', + 'skewY', + 'mmult', + 'combineTransforms', + 'inverse', + 'zTransformPoint', + 'transformPoint', + 'transformPoints', + 'zTransformPoints', + ) +from math import cos, sin, tan, radians + +# constructors for matrices: +def nullTransform(): + return (1, 0, 0, 1, 0, 0) + +def translate(dx, dy=0): + return (1, 0, 0, 1, dx, dy) + +def scale(sx, sy=1): + return (sx, 0, 0, sy, 0, 0) + +def rotate(angle, cx=0, cy=0): + a = radians(angle) + sina = sin(a) + cosa = cos(a) + return (cosa, sina, -sina, cosa, cx, cy) + +def skewX(angle): + return (1, 0, tan(radians(angle)), 1, 0, 0) + +def skewY(angle): + return (1, tan(radians(angle)), 0, 1, 0, 0) + +def skew(ax, ay=0): + if ay: + return mmult(skewX(ax),skewY(ay)) + else: + return skewX(ax) + +def mmult(A, B): + "A postmultiplied by B" + # I checked this RGB + # [a0 a2 a4] [b0 b2 b4] + # [a1 a3 a5] * [b1 b3 b5] + # [ 1 ] [ 1 ] + # + return (A[0]*B[0] + A[2]*B[1], + A[1]*B[0] + A[3]*B[1], + A[0]*B[2] + A[2]*B[3], + A[1]*B[2] + A[3]*B[3], + A[0]*B[4] + A[2]*B[5] + A[4], + A[1]*B[4] + A[3]*B[5] + A[5]) + +def combineTransforms(*T): + ''' + given transform matrices in the order they should be applied generate + a combined transform. + + combineTransforms(T0,T1,T2) == mmult(T2,mmult(T1,T0)) + == T2*T1*T0 + so that T0 is applied first, then T1 and finally T2. + ''' + nT = len(T) + return ( + mmult(T[1],T[0]) if nT==2 + else mmult(combineTransforms(*T[2:]), mmult(T[1],T[0])) if nT>2 + else T[0] if nT==1 + else nullTransform() + ) + +def inverse(A): + "For A affine 2D represented as 6vec return 6vec version of A**(-1)" + # I checked this RGB + det = float(A[0]*A[3] - A[2]*A[1]) + R = [A[3]/det, -A[1]/det, -A[2]/det, A[0]/det] + return tuple(R+[-R[0]*A[4]-R[2]*A[5],-R[1]*A[4]-R[3]*A[5]]) + +def zTransformPoint(A,v): + "Apply the homogenous part of atransformation a to vector v --> A*v" + return (A[0]*v[0]+A[2]*v[1],A[1]*v[0]+A[3]*v[1]) + +def transformPoint(A,v): + "Apply transformation a to vector v --> A*v" + return (A[0]*v[0]+A[2]*v[1]+A[4],A[1]*v[0]+A[3]*v[1]+A[5]) + +def transformPoints(matrix, V): + r = [transformPoint(matrix,v) for v in V] + if isinstance(V,tuple): r = tuple(r) + return r + +def zTransformPoints(matrix, V): + return list(map(lambda x,matrix=matrix: zTransformPoint(matrix,x), V)) diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/utils.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..010a23a7fa3ade3e66b13084062873276795ce60 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/utils.py @@ -0,0 +1,211 @@ +__all__ = ( + 'setFont', + 'pathNumTrunc', + 'processGlyph', + 'text2PathDescription', + 'text2Path', + 'RenderPMError', + ) +from reportlab.pdfbase.pdfmetrics import getFont, unicode2T1, stringWidth +from reportlab.pdfbase.ttfonts import ShapedStr +from reportlab.lib.utils import open_and_read, isBytes, rl_exec +from .shapes import _baseGFontName, _PATH_OP_ARG_COUNT, _PATH_OP_NAMES, definePath +from sys import exc_info + +class RenderPMError(Exception): + pass + +def _errorDump(fontName, fontSize): + s1, s2 = list(map(str,exc_info()[:2])) + from reportlab import rl_config + if rl_config.verbose>=2: + import os + _ = os.path.join(os.path.dirname(rl_config.__file__),'fonts') + print('!!!!! %s: %s' % (_,os.listdir(_))) + for _ in ('T1SearchPath','TTFSearchPath'): + print('!!!!! rl_config.%s = %s' % (_,repr(getattr(rl_config,_)))) + code = 'raise RenderPMError("Error in setFont(%s,%s) missing the T1 files?\\nOriginally %s: %s")' % (repr(fontName),repr(fontSize),s1,s2) + code += ' from None' + rl_exec(code,dict(RenderPMError=RenderPMError)) + +def setFont(gs,fontName,fontSize): + try: + gs.setFont(fontName,fontSize) + except ValueError as e: + _errorDump(fontName,fontSize) + #old code that used makeT1Font + #if not e.args[0].endswith("Can't find font!"): + # _errorDump(fontName,fontSize) + + #here's where we try to add a font to the canvas + #from _rl_renderPM import makeT1Font + #try: + # f = getFont(fontName) + # makeT1Font(fontName,f.face.findT1File(),f.encoding.vector,open_and_read) + #except: + # _errorDump(fontName,fontSize) + #gs.setFont(fontName,fontSize) + +def pathNumTrunc(n): + if int(n)==n: return int(n) + return round(n,5) + + +def __makeTextPathsCode__(tp=None, _TP = ('freetype',)): + from reportlab.rl_config import textPaths, renderPMBackend + if tp is not None: textPaths = tp + if textPaths=='backend': + tp = 'freetype' + elif textPaths in _TP: + tp = textPaths + else: + raise ValueError(f"textPaths={textPaths!r} should be one of 'backend', 'freetype')") + TP = (tp,) + tuple((_ for _ in _TP if _!=tp)) + for tp in TP: + if tp=='freetype': + try: + import freetype + except ImportError: + continue + import io + class FTTextPath: + ftLFlags = freetype.FT_LOAD_DEFAULT | freetype.FT_LOAD_NO_SCALE | freetype.FT_LOAD_NO_BITMAP + def __init__(self): + self.faces = {} + + def setFont(self,fontName): + if fontName not in self.faces: + font = getFont(fontName) + if not font: + raise ValueError(f'font {fontName!r} has not been registered') + if font._dynamicFont: + path_or_stream = font.face._ttf_data + #path_or_stream = getattr(font,'_ttfont_data',None) + #if not path_or_stream: + #path_or_stream = font._ttfont_data + path_or_stream = io.BytesIO(path_or_stream) + else: + path_or_stream = getattr(font.face,'pfbFileName',None) + if not path_or_stream: + path_or_stream = font.face.findT1File() + face = freetype.Face(path_or_stream) + self.faces[fontName] = (face,font) + return self.faces[fontName] + + def move_to(self, a, ctx): + if self.P: self.P_append(('closePath',)) + self.P_append(('moveTo',self.xpt(a.x),self.ypt(a.y))) + + def line_to(self, a, ctx): + self.P_append(('lineTo',self.xpt(a.x),self.ypt(a.y))) + + def conic_to(self, a, b, ctx): + '''using the cubic equivalent''' + x0,y0 = self.P[-1][-2:] if self.P else (a.x, a.y) + x1 = self.xpt(a.x) + y1 = self.ypt(a.y) + x2 = self.xpt(b.x) + y2 = self.ypt(b.y) + self.P_append(('curveTo',x0+((x1-x0)*2)/3,y0+((y1-y0)*2)/3,x1+(x2-x1)/3,y1+(y2-y1)/3,x2,y2)) + + def cubic_to(self, a, b, c, ctx): + self.P_append(('curveTo',self.xpt(a.x),self.ypt(a.y),self.xpt(b.x),self.ypt(b.y),self.xpt(c.x),self.ypt(c.y))) + + def close_path(self,ctx=None): + self.P.append(('closePath',)) + + def _text2Path(self, text, x=0, y=0, fontName=_baseGFontName, fontSize=1000, **kwds): + face, font = self.setFont(fontName) + scale = fontSize/face.units_per_EM #font scaling + __dx__ = x/scale + __dy__ = y/scale + self.P = [] + self.P_append = self.P.append + truncate = kwds.pop('truncate',0) + if truncate: + self.xpt = lambda x: pathNumTrunc(scale*(x+__dx__)) + self.ypt = lambda y: pathNumTrunc(scale*(y+__dy__)) + else: + self.xpt = lambda x: scale*(x + __dx__) + self.ypt = lambda y: scale*(y + __dy__) + + lineHeight = fontSize*1.2/scale + ftLFlags = self.ftLFlags + if isinstance(text,ShapedStr): + sdata = text.__shapeData__ + dscale = face.units_per_EM / 1000 + fontC2G = font.face.charToGlyph + else: + sdata = None + for i,c in enumerate(text): + if c=='\n': + __dx__ = 0 + __dy__ -= lineHeight + continue + if sdata: + sd = sdata[i] + sdx_offset = sd.x_offset*dscale + sdy_offset = sd.y_offset*dscale + __dx__ += sdx_offset + __dy__ += sdy_offset + face.load_glyph(fontC2G[ord(c)],ftLFlags) + else: + face.load_char(c, ftLFlags) + face.glyph.outline.decompose(self, move_to=self.move_to, line_to=self.line_to, conic_to=self.conic_to, cubic_to=self.cubic_to) + if sdata: + __dx__ -= sdx_offset + __dy__ -= sdy_offset + __dx__ += sd.x_advance*dscale if sdata else face.glyph.metrics.horiAdvance + if self.P: self.P_append(('closePath',)) + return self.P + + def text2PathDescription(text, x=0, y=0, fontName=_baseGFontName, fontSize=1000, + anchor='start', truncate=1, pathReverse=0, gs=None): + '''freetype text2PathDescription(text, x=0, y=0, fontName='fontname', + fontSize=1000, font = 'fontName', + anchor='start', truncate=1, pathReverse=0, gs=None) + ''' + font = getFont(fontName) + if font._multiByte and not font._dynamicFont: + raise ValueError("text2PathDescription doesn't support multi byte fonts like %r" % fontName) + P_extend = [].extend + if not anchor=='start': + textLen = stringWidth(text, fontName, fontSize) + if anchor=='end': + x = x-textLen + elif anchor=='middle': + x = x - textLen/2. + if gs is None: + gs = FTTextPath() + if font._dynamicFont: + P_extend(gs._text2Path(text,x=x,y=y,fontName=fontName,fontSize=fontSize, truncate=truncate,pathReverse=pathReverse)) + else: + if isBytes(text): + try: + text = text.decode('utf8') + except UnicodeDecodeError as e: + i,j = e.args[2:4] + raise UnicodeDecodeError(*(e.args[:4]+('%s\n%s-->%s<--%s' % (e.args[4],text[max(i-10,0):i],text[i:j],text[j:j+10]),))) + FT = unicode2T1(text,[font]+font.substitutionFonts) + nm1 = len(FT)-1 + for i, (f, t) in enumerate(FT): + if isinstance(t,bytes): t = t.decode(f.encName) + P_extend(gs._text2Path(t,x=x,y=y,fontName=f.fontName,fontSize=fontSize, truncate=truncate,pathReverse=pathReverse)) + if i!=nm1: + x += f.stringWidth(t, fontSize) + return P_extend.__self__ + return dict(text2PathDescription=text2PathDescription,FTTextPath=FTTextPath) + else: + def _(*args,**kwds): + raise RuntimeError(f'''This installation of reportLab has lacks PYCAIRO extra. +It cannot create paths from text. +Could not create text2PathDescription for using backends from {TP!a}''') + return dict(processGlyph=_,setFont=_,FTTextPath=_,text2PathDescription=_) + +globals().update(__makeTextPathsCode__()) + +def text2Path(text, x=0, y=0, fontName=_baseGFontName, fontSize=1000, + anchor='start', truncate=1, pathReverse=0, gs=None, **kwds): + t2pd = kwds.pop('text2PathDescription',text2PathDescription) + return definePath(t2pd(text,x=x,y=y,fontName=fontName, + fontSize=fontSize,anchor=anchor,truncate=truncate,pathReverse=pathReverse, gs=gs),**kwds) diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/widgetbase.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/widgetbase.py new file mode 100644 index 0000000000000000000000000000000000000000..977e906dca88bd16e99d9513ff57714422d1e11a --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/widgetbase.py @@ -0,0 +1,655 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/graphics/widgetbase.py +__version__='3.3.0' +__doc__='''Base class for user-defined graphical widgets''' + +from reportlab.graphics import shapes +from reportlab import rl_config +from reportlab.lib import colors +from reportlab.lib.validators import * +from reportlab.lib.attrmap import * +from weakref import ref as weakref_ref + +class PropHolder: + '''Base for property holders''' + + _attrMap = None + + def verify(self): + """If the _attrMap attribute is not None, this + checks all expected attributes are present; no + unwanted attributes are present; and (if a + checking function is found) checks each + attribute has a valid value. Either succeeds + or raises an informative exception. + """ + + if self._attrMap is not None: + for key in self.__dict__.keys(): + if key[0] != '_': + msg = "Unexpected attribute %s found in %s" % (key, self) + assert key in self._attrMap, msg + for attr, metavalue in self._attrMap.items(): + msg = "Missing attribute %s from %s" % (attr, self) + assert hasattr(self, attr), msg + value = getattr(self, attr) + args = (value, attr, self.__class__.__name__) + assert metavalue.validate(value), "Invalid value %s for attribute %s in class %s" % args + + if rl_config.shapeChecking: + """This adds the ability to check every attribute assignment + as it is made. It slows down shapes but is a big help when + developing. It does not get defined if rl_config.shapeChecking = 0. + """ + + def __setattr__(self, name, value): + """By default we verify. This could be off + in some parallel base classes.""" + validateSetattr(self,name,value) + + + def getProperties(self,recur=1): + """Returns a list of all properties which can be edited and + which are not marked as private. This may include 'child + widgets' or 'primitive shapes'. You are free to override + this and provide alternative implementations; the default + one simply returns everything without a leading underscore. + """ + + from reportlab.lib.validators import isValidChild + + # TODO when we need it, but not before - + # expose sequence contents? + + props = {} + for name in self.__dict__.keys(): + if name[0:1] != '_': + component = getattr(self, name) + + if recur and isValidChild(component): + # child object, get its properties too + childProps = component.getProperties(recur=recur) + for childKey, childValue in childProps.items(): + #key might be something indexed like '[2].fillColor' + #or simple like 'fillColor'; in the former case we + #don't need a '.' between me and my child. + if childKey[0] == '[': + props['%s%s' % (name, childKey)] = childValue + else: + props['%s.%s' % (name, childKey)] = childValue + else: + props[name] = component + + return props + + + def setProperties(self, propDict): + """Permits bulk setting of properties. These may include + child objects e.g. "chart.legend.width = 200". + + All assignments will be validated by the object as if they + were set individually in python code. + + All properties of a top-level object are guaranteed to be + set before any of the children, which may be helpful to + widget designers. + """ + + childPropDicts = {} + for name, value in propDict.items(): + parts = name.split('.', 1) + if len(parts) == 1: + #simple attribute, set it now + setattr(self, name, value) + else: + (childName, remains) = parts + try: + childPropDicts[childName][remains] = value + except KeyError: + childPropDicts[childName] = {remains: value} + + # now assign to children + for childName, childPropDict in childPropDicts.items(): + child = getattr(self, childName) + child.setProperties(childPropDict) + + + def dumpProperties(self, prefix=""): + """Convenience. Lists them on standard output. You + may provide a prefix - mostly helps to generate code + samples for documentation. + """ + + propList = list(self.getProperties().items()) + propList.sort() + if prefix: + prefix = prefix + '.' + for (name, value) in propList: + print('%s%s = %s' % (prefix, name, value)) + + +class Widget(PropHolder, shapes.UserNode): + """Base for all user-defined widgets. Keep as simple as possible. Does + not inherit from Shape so that we can rewrite shapes without breaking + widgets and vice versa.""" + + def _setKeywords(self,**kw): + for k,v in kw.items(): + if k not in self.__dict__: + setattr(self,k,v) + + def draw(self): + msg = "draw() must be implemented for each Widget!" + raise NotImplementedError(msg) + + def demo(self): + msg = "demo() must be implemented for each Widget!" + raise NotImplementedError(msg) + + def provideNode(self): + return self.draw() + + def getBounds(self): + "Return outer boundary as x1,y1,x2,y2. Can be overridden for efficiency" + return self.draw().getBounds() + +class ScaleWidget(Widget): + '''Contents with a scale and offset''' + _attrMap = AttrMap( + x = AttrMapValue(isNumber,desc="x offset"), + y = AttrMapValue(isNumber,desc="y offset"), + scale = AttrMapValue(isNumber,desc="scale"), + contents = AttrMapValue(None,desc="Contained drawable elements"), + ) + def __init__(self,x=0,y=0,scale=1.0,contents=None): + self.x = x + self.y = y + if not contents: contents=[] + elif not isinstance(contents,(tuple,list)): + contents = (contents,) + self.contents = list(contents) + self.scale = scale + + def draw(self): + return shapes.Group(transform=(self.scale,0,0,self.scale,self.x,self.y),*self.contents) + +_ItemWrapper={} + +class CloneMixin: + def clone(self,**kwds): + n = self.__class__() + n.__dict__.clear() + n.__dict__.update(self.__dict__) + if kwds: n.__dict__.update(kwds) + return n + +class TypedPropertyCollection(PropHolder): + """A container with properties for objects of the same kind. + + This makes it easy to create lists of objects. You initialize + it with a class of what it is to contain, and that is all you + can add to it. You can assign properties to the collection + as a whole, or to a numeric index within it; if so it creates + a new child object to hold that data. + + So: + wedges = TypedPropertyCollection(WedgeProperties) + wedges.strokeWidth = 2 # applies to all + wedges.strokeColor = colors.red # applies to all + wedges[3].strokeColor = colors.blue # only to one + + The last line should be taken as a prescription of how to + create wedge no. 3 if one is needed; no error is raised if + there are only two data points. + + We try and make sensible use of tuple indices. + line[(3,x)] is backed by line[(3,)] == line[3] & line + """ + + def __init__(self, exampleClass, **kwds): + #give it same validation rules as what it holds + self.__dict__['_value'] = exampleClass(**kwds) + self.__dict__['_children'] = {} + + def wKlassFactory(self,Klass): + class WKlass(Klass,CloneMixin): + def __getattr__(self,name): + try: + return self.__class__.__bases__[0].__getattr__(self,name) + except: + parent = self.parent + c = parent._children + x = self.__propholder_index__ + while x: + if x in c: + return getattr(c[x],name) + x = x[:-1] + return getattr(parent,name) + @property + def parent(self): + return self.__propholder_parent__() + return WKlass + + def __getitem__(self, x): + x = tuple(x) if isinstance(x,(tuple,list)) else (x,) + try: + return self._children[x] + except KeyError: + Klass = self._value.__class__ + if Klass in _ItemWrapper: + WKlass = _ItemWrapper[Klass] + else: + _ItemWrapper[Klass] = WKlass = self.wKlassFactory(Klass) + + child = WKlass() + + for i in filter(lambda x,K=list(child.__dict__.keys()): x in K,list(child._attrMap.keys())): + del child.__dict__[i] + child.__dict__.update(dict( + __propholder_parent__ = weakref_ref(self), + __propholder_index__ = x[:-1]) + ) + + self._children[x] = child + return child + + def __contains__(self,key): + return (tuple(key) if isinstance(key,(tuple,list)) else (key,)) in self._children + + def __setitem__(self, key, value): + assert isinstance(value, self._value.__class__), ( + "This collection can only hold objects of type %s" % self._value.__class__.__name__) + + def __len__(self): + return len(list(self._children.keys())) + + def getProperties(self,recur=1): + # return any children which are defined and whatever + # differs from the parent + props = {} + + for key, value in self._value.getProperties(recur=recur).items(): + props['%s' % key] = value + + for idx in self._children.keys(): + childProps = self._children[idx].getProperties(recur=recur) + for key, value in childProps.items(): + if not hasattr(self,key) or getattr(self, key)!=value: + newKey = '[%s].%s' % (idx if len(idx)>1 else idx[0], key) + props[newKey] = value + return props + + def setVector(self,**kw): + for name, value in kw.items(): + for i, v in enumerate(value): + setattr(self[i],name,v) + + def __getattr__(self,name): + return getattr(self._value,name) + + def __setattr__(self,name,value): + return setattr(self._value,name,value) + + def checkAttr(self, key, a, default=None): + return getattr(self[key], a, default) if key in self else default + +def tpcGetItem(obj,x): + '''return obj if it's not a TypedPropertyCollection else obj[x]''' + return obj[x] if isinstance(obj,TypedPropertyCollection) else obj + +def isWKlass(obj): + if not hasattr(obj,'__propholder_parent__'): return + ph = obj.__propholder_parent__ + if not isinstance(ph,weakref_ref): return + return isinstance(ph(),TypedPropertyCollection) + +## No longer needed! +class StyleProperties(PropHolder): + """A container class for attributes used in charts and legends. + + Attributes contained can be those for any graphical element + (shape?) in the ReportLab graphics package. The idea for this + container class is to be useful in combination with legends + and/or the individual appearance of data series in charts. + + A legend could be as simple as a wrapper around a list of style + properties, where the 'desc' attribute contains a descriptive + string and the rest could be used by the legend e.g. to draw + something like a color swatch. The graphical presentation of + the legend would be its own business, though. + + A chart could be inspecting a legend or, more directly, a list + of style properties to pick individual attributes that it knows + about in order to render a particular row of the data. A bar + chart e.g. could simply use 'strokeColor' and 'fillColor' for + drawing the bars while a line chart could also use additional + ones like strokeWidth. + """ + + _attrMap = AttrMap( + strokeWidth = AttrMapValue(isNumber,desc='width of the stroke line'), + strokeLineCap = AttrMapValue(isNumber,desc='Line cap 0=butt, 1=round & 2=square',advancedUsage=1), + strokeLineJoin = AttrMapValue(isNumber,desc='Line join 0=miter, 1=round & 2=bevel',advancedUsage=1), + strokeMiterLimit = AttrMapValue(None,desc='miter limit control miter line joins',advancedUsage=1), + strokeDashArray = AttrMapValue(isListOfNumbersOrNone,desc='dashing patterns e.g. (1,3)'), + strokeOpacity = AttrMapValue(isNumber,desc='level of transparency (alpha) accepts values between 0..1',advancedUsage=1), + strokeColor = AttrMapValue(isColorOrNone,desc='the color of the stroke'), + fillColor = AttrMapValue(isColorOrNone,desc='the filling color'), + desc = AttrMapValue(isString), + ) + + def __init__(self, **kwargs): + "Initialize with attributes if any." + + for k, v in kwargs.items(): + setattr(self, k, v) + + + def __setattr__(self, name, value): + "Verify attribute name and value, before setting it." + validateSetattr(self,name,value) + + +class TwoCircles(Widget): + def __init__(self): + self.leftCircle = shapes.Circle(100,100,20, fillColor=colors.red) + self.rightCircle = shapes.Circle(300,100,20, fillColor=colors.red) + + def draw(self): + return shapes.Group(self.leftCircle, self.rightCircle) + + +class Face(Widget): + """This draws a face with two eyes. + + It exposes a couple of properties + to configure itself and hides all other details. + """ + + _attrMap = AttrMap( + x = AttrMapValue(isNumber), + y = AttrMapValue(isNumber), + size = AttrMapValue(isNumber), + skinColor = AttrMapValue(isColorOrNone), + eyeColor = AttrMapValue(isColorOrNone), + mood = AttrMapValue(OneOf('happy','sad','ok')), + ) + + def __init__(self): + self.x = 10 + self.y = 10 + self.size = 80 + self.skinColor = None + self.eyeColor = colors.blue + self.mood = 'happy' + + def demo(self): + pass + + def draw(self): + s = self.size # abbreviate as we will use this a lot + g = shapes.Group() + g.transform = [1,0,0,1,self.x, self.y] + + # background + g.add(shapes.Circle(s * 0.5, s * 0.5, s * 0.5, fillColor=self.skinColor)) + + # left eye + g.add(shapes.Circle(s * 0.35, s * 0.65, s * 0.1, fillColor=colors.white)) + g.add(shapes.Circle(s * 0.35, s * 0.65, s * 0.05, fillColor=self.eyeColor)) + + # right eye + g.add(shapes.Circle(s * 0.65, s * 0.65, s * 0.1, fillColor=colors.white)) + g.add(shapes.Circle(s * 0.65, s * 0.65, s * 0.05, fillColor=self.eyeColor)) + + # nose + g.add(shapes.Polygon( + points=[s * 0.5, s * 0.6, s * 0.4, s * 0.3, s * 0.6, s * 0.3], + fillColor=None)) + + # mouth + if self.mood == 'happy': + offset = -0.05 + elif self.mood == 'sad': + offset = +0.05 + else: + offset = 0 + + g.add(shapes.Polygon( + points = [ + s * 0.3, s * 0.2, #left of mouth + s * 0.7, s * 0.2, #right of mouth + s * 0.6, s * (0.2 + offset), # the bit going up or down + s * 0.4, s * (0.2 + offset) # the bit going up or down + ], + fillColor = colors.pink, + strokeColor = colors.red, + strokeWidth = s * 0.03 + )) + + return g + + +class TwoFaces(Widget): + def __init__(self): + self.faceOne = Face() + self.faceOne.mood = "happy" + self.faceTwo = Face() + self.faceTwo.x = 100 + self.faceTwo.mood = "sad" + + def draw(self): + """Just return a group""" + return shapes.Group(self.faceOne, self.faceTwo) + + def demo(self): + """The default case already looks good enough, + no implementation needed here""" + pass + +class Sizer(Widget): + "Container to show size of all enclosed objects" + + _attrMap = AttrMap(BASE=shapes.SolidShape, + contents = AttrMapValue(isListOfShapes,desc="Contained drawable elements"), + ) + def __init__(self, *elements): + self.contents = [] + self.fillColor = colors.cyan + self.strokeColor = colors.magenta + + for elem in elements: + self.add(elem) + + def _addNamedNode(self,name,node): + 'if name is not None add an attribute pointing to node and add to the attrMap' + if name: + if name not in list(self._attrMap.keys()): + self._attrMap[name] = AttrMapValue(isValidChild) + setattr(self, name, node) + + def add(self, node, name=None): + """Appends non-None child node to the 'contents' attribute. In addition, + if a name is provided, it is subsequently accessible by name + """ + # propagates properties down + if node is not None: + assert isValidChild(node), "Can only add Shape or UserNode objects to a Group" + self.contents.append(node) + self._addNamedNode(name,node) + + def getBounds(self): + # get bounds of each object + if self.contents: + b = [] + for elem in self.contents: + b.append(elem.getBounds()) + return shapes.getRectsBounds(b) + else: + return (0,0,0,0) + + def draw(self): + g = shapes.Group() + (x1, y1, x2, y2) = self.getBounds() + r = shapes.Rect( + x = x1, + y = y1, + width = x2-x1, + height = y2-y1, + fillColor = self.fillColor, + strokeColor = self.strokeColor + ) + g.add(r) + for elem in self.contents: + g.add(elem) + return g + +class CandleStickProperties(PropHolder): + _attrMap = AttrMap( + strokeWidth = AttrMapValue(isNumber, desc='Width of a line.'), + strokeColor = AttrMapValue(isColorOrNone, desc='Color of a line or border.'), + strokeDashArray = AttrMapValue(isListOfNumbersOrNone, desc='Dash array of a line.'), + crossWidth = AttrMapValue(isNumberOrNone,desc="cross line width",advancedUsage=1), + crossLo = AttrMapValue(isNumberOrNone,desc="cross line low value",advancedUsage=1), + crossHi = AttrMapValue(isNumberOrNone,desc="cross line high value",advancedUsage=1), + boxWidth = AttrMapValue(isNumberOrNone,desc="width of the box part",advancedUsage=1), + boxFillColor = AttrMapValue(isColorOrNone, desc='fill color of box'), + boxStrokeColor = AttrMapValue(NotSetOr(isColorOrNone), desc='stroke color of box'), + boxStrokeDashArray = AttrMapValue(NotSetOr(isListOfNumbersOrNone), desc='Dash array of the box.'), + boxStrokeWidth = AttrMapValue(NotSetOr(isNumber), desc='Width of the box lines.'), + boxLo = AttrMapValue(isNumberOrNone,desc="low value of the box",advancedUsage=1), + boxMid = AttrMapValue(isNumberOrNone,desc="middle box line value",advancedUsage=1), + boxHi = AttrMapValue(isNumberOrNone,desc="high value of the box",advancedUsage=1), + boxSides = AttrMapValue(isBoolean,desc="whether to show box sides",advancedUsage=1), + position = AttrMapValue(isNumberOrNone,desc="position of the candle",advancedUsage=1), + chart = AttrMapValue(None,desc="our chart",advancedUsage=1), + candleKind = AttrMapValue(OneOf('vertical','horizontal'),desc="candle direction",advancedUsage=1), + axes = AttrMapValue(SequenceOf(isString,emptyOK=0,lo=2,hi=2),desc="candle direction",advancedUsage=1), + ) + + def __init__(self,**kwds): + self.strokeWidth = kwds.pop('strokeWidth',1) + self.strokeColor = kwds.pop('strokeColor',colors.black) + self.strokeDashArray = kwds.pop('strokeDashArray',None) + self.crossWidth = kwds.pop('crossWidth',5) + self.crossLo = kwds.pop('crossLo',None) + self.crossHi = kwds.pop('crossHi',None) + self.boxWidth = kwds.pop('boxWidth',None) + self.boxFillColor = kwds.pop('boxFillColor',None) + self.boxStrokeColor =kwds.pop('boxStrokeColor',NotSetOr._not_set) + self.boxStrokeWidth =kwds.pop('boxStrokeWidth',NotSetOr._not_set) + self.boxStrokeDashArray =kwds.pop('boxStrokeDashArray',NotSetOr._not_set) + self.boxLo = kwds.pop('boxLo',None) + self.boxMid = kwds.pop('boxMid',None) + self.boxHi = kwds.pop('boxHi',None) + self.boxSides = kwds.pop('boxSides',True) + self.position = kwds.pop('position',None) + self.candleKind = kwds.pop('candleKind','vertical') + self.axes = kwds.pop('axes',['categoryAxis','valueAxis']) + chart = kwds.pop('chart',None) + self.chart = weakref_ref(chart) if chart else (lambda:None) + + def __call__(self,_x,_y,_size,_color): + '''the symbol interface''' + chart = self.chart() + xA = getattr(chart,self.axes[0]) + _xScale = getattr(xA,'midScale',None) + if not _xScale: _xScale = getattr(xA,'scale') + xScale = lambda x: _xScale(x) if x is not None else None + yA = getattr(chart,self.axes[1]) + _yScale = getattr(yA,'midScale',None) + if not _yScale: _yScale = getattr(yA,'scale') + yScale = lambda x: _yScale(x) if x is not None else None + G = shapes.Group().add + strokeWidth = self.strokeWidth + strokeColor = self.strokeColor + strokeDashArray = self.strokeDashArray + crossWidth = self.crossWidth + crossLo = yScale(self.crossLo) + crossHi = yScale(self.crossHi) + boxWidth = self.boxWidth + boxFillColor = self.boxFillColor + boxStrokeColor = NotSetOr.conditionalValue(self.boxStrokeColor,strokeColor) + boxStrokeWidth = NotSetOr.conditionalValue(self.boxStrokeWidth,strokeWidth) + boxStrokeDashArray = NotSetOr.conditionalValue(self.boxStrokeDashArray,strokeDashArray) + boxLo = yScale(self.boxLo) + boxMid = yScale(self.boxMid) + boxHi = yScale(self.boxHi) + position = xScale(self.position) + candleKind = self.candleKind + haveBox = None not in (boxWidth,boxLo,boxHi) + haveLine = None not in (crossLo,crossHi) + def aLine(x0,y0,x1,y1): + if candleKind!='vertical': + x0,y0 = y0,x0 + x1,y1 = y1,x1 + G(shapes.Line(x0,y0,x1,y1,strokeWidth=strokeWidth,strokeColor=strokeColor,strokeDashArray=strokeDashArray)) + if haveBox: + boxLo, boxHi = min(boxLo,boxHi), max(boxLo,boxHi) + if haveLine: + crossLo, crossHi = min(crossLo,crossHi), max(crossLo,crossHi) + if not haveBox or crossLo>=boxHi or crossHi<=boxLo: + aLine(position,crossLo,position,crossHi) + if crossWidth is not None: + aLine(position-crossWidth*0.5,crossLo,position+crossWidth*0.5,crossLo) + aLine(position-crossWidth*0.5,crossHi,position+crossWidth*0.5,crossHi) + elif haveBox: + if crossLoboxHi: + aLine(position,boxHi,position,crossHi) + aLine(position-crossWidth*0.5,crossHi,position+crossWidth*0.5,crossHi) + if haveBox: + x = position - boxWidth*0.5 + y = boxLo + h = boxHi - boxLo + w = boxWidth + if candleKind!='vertical': + x, y, w, h = y, x, h, w + G(shapes.Rect(x,y,w,h,strokeColor=boxStrokeColor if self.boxSides else None,strokeWidth=boxStrokeWidth,strokeDashArray=boxStrokeDashArray,fillColor=boxFillColor)) + if not self.boxSides: + aLine(position-0.5*boxWidth,boxHi,position+0.5*boxWidth,boxHi) + aLine(position-0.5*boxWidth,boxLo,position+0.5*boxWidth,boxLo) + + if boxMid is not None: + aLine(position-0.5*boxWidth,boxMid,position+0.5*boxWidth,boxMid) + return G.__self__ + +def CandleSticks(**kwds): + return TypedPropertyCollection(CandleStickProperties,**kwds) + +def test(): + from reportlab.graphics.charts.piecharts import WedgeProperties + wedges = TypedPropertyCollection(WedgeProperties) + wedges.fillColor = colors.red + wedges.setVector(fillColor=(colors.blue,colors.green,colors.white)) + print(len(_ItemWrapper)) + + d = shapes.Drawing(400, 200) + tc = TwoCircles() + d.add(tc) + from reportlab.graphics import renderPDF + renderPDF.drawToFile(d, 'sample_widget.pdf', 'A Sample Widget') + print('saved sample_widget.pdf') + + d = shapes.Drawing(400, 200) + f = Face() + f.skinColor = colors.yellow + f.mood = "sad" + d.add(f, name='theFace') + print('drawing 1 properties:') + d.dumpProperties() + renderPDF.drawToFile(d, 'face.pdf', 'A Sample Widget') + print('saved face.pdf') + + d2 = d.expandUserNodes() + renderPDF.drawToFile(d2, 'face_copy.pdf', 'An expanded drawing') + print('saved face_copy.pdf') + print('drawing 2 properties:') + d2.dumpProperties() + + +if __name__=='__main__': + test() diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/widgets/__init__.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/widgets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6d8f6f784ba813e7d96b25d07885a95b2b812928 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/widgets/__init__.py @@ -0,0 +1,5 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/graphics/widgets/__init__.py +__version__='3.3.0' +__doc__='''Some non-chart widgets''' diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/widgets/adjustableArrow.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/widgets/adjustableArrow.py new file mode 100644 index 0000000000000000000000000000000000000000..bdd18c9f1af4cb421e1ad3f24a434a8b665d6f7c --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/widgets/adjustableArrow.py @@ -0,0 +1,126 @@ +from reportlab.lib import colors +from reportlab.lib.validators import * +from reportlab.lib.attrmap import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin, Group, Polygon +from reportlab.graphics.widgetbase import Widget + +class AdjustableArrow(Widget): + """This widget draws an arrow (style one). + + possible attributes: + 'x', 'y', 'size', 'fillColor' + + """ + _attrMap = AttrMap( + x = AttrMapValue(isNumber,desc='symbol x coordinate'), + y = AttrMapValue(isNumber,desc='symbol y coordinate'), + dx = AttrMapValue(isNumber,desc='symbol x coordinate adjustment'), + dy = AttrMapValue(isNumber,desc='symbol x coordinate adjustment'), + stemThickness = AttrMapValue(isNumber, 'width of the stem'), + stemLength = AttrMapValue(isNumber, 'length of the stem'), + headProjection = AttrMapValue(isNumber, 'how much the head projects from the stem'), + headLength = AttrMapValue(isNumber, 'length of the head'), + headSweep = AttrMapValue(isNumber, 'howmuch the head sweeps back (-ve) or forwards (+ve)'), + scale = AttrMapValue(isNumber, 'scaling factor'), + fillColor = AttrMapValue(isColorOrNone), + strokeColor = AttrMapValue(isColorOrNone), + strokeWidth = AttrMapValue(isNumber), + boxAnchor = AttrMapValue(isBoxAnchor,desc='anchoring point of the label'), + right =AttrMapValue(isBoolean,desc='If True (default) the arrow is horizontal pointing right\nFalse means it points up'), + angle = AttrMapValue(isNumber, desc='angle of arrow default (0), right True 0 is horizontal to right else vertical up'), + ) + def __init__(self,**kwds): + self._setKeywords(**kwds) + self._setKeywords(**dict( + x = 0, + y = 0, + fillColor = colors.red, + strokeWidth = 0, + strokeColor = None, + boxAnchor = 'c', + angle = 0, + stemThickness = 33, + stemLength = 50, + headProjection = 15, + headLength = 50, + headSweep = 0, + scale = 1., + right=True, + )) + + def draw(self): + # general widget bits + g = Group() + + x = self.x + y = self.y + scale = self.scale + stemThickness = self.stemThickness*scale + stemLength = self.stemLength*scale + headProjection = self.headProjection*scale + headLength = self.headLength*scale + headSweep = self.headSweep*scale + w = stemLength+headLength + h = 2*headProjection+stemThickness + # shift to the boxAnchor + boxAnchor = self.boxAnchor + if self.right: + if boxAnchor in ('sw','w','nw'): + dy = -h + elif boxAnchor in ('s','c','n'): + dy = -h*0.5 + else: + dy = 0 + if boxAnchor in ('w','c','e'): + dx = -w*0.5 + elif boxAnchor in ('nw','n','ne'): + dx = -w + else: + dx = 0 + points = [ + dx, dy+headProjection+stemThickness, + dx+stemLength, dy+headProjection+stemThickness, + dx+stemLength+headSweep, dy+2*headProjection+stemThickness, + dx+stemLength+headLength, dy+0.5*stemThickness+headProjection, + dx+stemLength+headSweep, dy, + dx+stemLength, dy+headProjection, + dx, dy+headProjection, + ] + else: + w,h = h,w + if boxAnchor in ('nw','n','ne'): + dy = -h + elif boxAnchor in ('w','c','e'): + dy = -h*0.5 + else: + dy = 0 + if boxAnchor in ('ne','e','se'): + dx = -w + elif boxAnchor in ('n','c','s'): + dx = -w*0.5 + else: + dx = 0 + points = [ + dx+headProjection, dy, #sw + dx+headProjection+stemThickness, dy, #se + dx+headProjection+stemThickness, dy+stemLength, + dx+w, dy+stemLength+headSweep, + dx+headProjection+0.5*stemThickness, dy+h, + dx, dy+stemLength+headSweep, + dx+headProjection, dy+stemLength, + ] + + g.add(Polygon( + points = points, + fillColor = self.fillColor, + strokeColor = self.strokeColor, + strokeWidth = self.strokeWidth, + )) + g.translate(x,y) + g.rotate(self.angle) + return g + +class AdjustableArrowDrawing(_DrawingEditorMixin,Drawing): + def __init__(self,width=100,height=63,*args,**kw): + Drawing.__init__(self,width,height,*args,**kw) + self._add(self,AdjustableArrow(),name='adjustableArrow',validate=None,desc=None) diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/widgets/eventcal.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/widgets/eventcal.py new file mode 100644 index 0000000000000000000000000000000000000000..55758b1cbd4e38bf7a4b13ef0f088b9ce537a366 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/widgets/eventcal.py @@ -0,0 +1,299 @@ +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/graphics/widgets/eventcal.py +# Event Calendar widget +# author: Andy Robinson + +__version__='3.3.0' +__doc__="""This file is a +""" + +from reportlab.lib import colors +from reportlab.graphics.shapes import Rect, Drawing, Group, String +from reportlab.graphics.charts.textlabels import Label +from reportlab.graphics.widgetbase import Widget + + +class EventCalendar(Widget): + def __init__(self): + self.x = 0 + self.y = 0 + self.width = 300 + self.height = 150 + self.timeColWidth = None # if declared, use it; otherwise auto-size. + self.trackRowHeight = 20 + self.data = [] # list of Event objects + self.trackNames = None + + self.startTime = None #displays ALL data on day if not set + self.endTime = None # displays ALL data on day if not set + self.day = 0 + + + # we will keep any internal geometry variables + # here. These are computed by computeSize(), + # which is the first thing done when drawing. + self._talksVisible = [] # subset of data which will get plotted, cache + self._startTime = None + self._endTime = None + self._trackCount = 0 + self._colWidths = [] + self._colLeftEdges = [] # left edge of each column + + def computeSize(self): + "Called at start of draw. Sets various column widths" + self._talksVisible = self.getRelevantTalks(self.data) + self._trackCount = len(self.getAllTracks()) + self.computeStartAndEndTimes() + self._colLeftEdges = [self.x] + if self.timeColWidth is None: + w = self.width / (1 + self._trackCount) + self._colWidths = [w] * (1+ self._trackCount) + for i in range(self._trackCount): + self._colLeftEdges.append(self._colLeftEdges[-1] + w) + else: + self._colWidths = [self.timeColWidth] + w = (self.width - self.timeColWidth) / self._trackCount + for i in range(self._trackCount): + self._colWidths.append(w) + self._colLeftEdges.append(self._colLeftEdges[-1] + w) + + + + def computeStartAndEndTimes(self): + "Work out first and last times to display" + if self.startTime: + self._startTime = self.startTime + else: + for (title, speaker, trackId, day, start, duration) in self._talksVisible: + + if self._startTime is None: #first one + self._startTime = start + else: + if start < self._startTime: + self._startTime = start + + if self.endTime: + self._endTime = self.endTime + else: + for (title, speaker, trackId, day, start, duration) in self._talksVisible: + if self._endTime is None: #first one + self._endTime = start + duration + else: + if start + duration > self._endTime: + self._endTime = start + duration + + + + + def getAllTracks(self): + tracks = [] + for (title, speaker, trackId, day, hours, duration) in self.data: + if trackId is not None: + if trackId not in tracks: + tracks.append(trackId) + tracks.sort() + return tracks + + def getRelevantTalks(self, talkList): + "Scans for tracks actually used" + used = [] + for talk in talkList: + (title, speaker, trackId, day, hours, duration) = talk + assert trackId != 0, "trackId must be None or 1,2,3... zero not allowed!" + if day == self.day: + if (((self.startTime is None) or ((hours + duration) >= self.startTime)) + and ((self.endTime is None) or (hours <= self.endTime))): + used.append(talk) + return used + + def scaleTime(self, theTime): + "Return y-value corresponding to times given" + axisHeight = self.height - self.trackRowHeight + # compute fraction between 0 and 1, 0 is at start of period + proportionUp = ((theTime - self._startTime) / (self._endTime - self._startTime)) + y = self.y + axisHeight - (axisHeight * proportionUp) + return y + + + def getTalkRect(self, startTime, duration, trackId, text): + "Return shapes for a specific talk" + g = Group() + y_bottom = self.scaleTime(startTime + duration) + y_top = self.scaleTime(startTime) + y_height = y_top - y_bottom + + if trackId is None: + #spans all columns + x = self._colLeftEdges[1] + width = self.width - self._colWidths[0] + else: + #trackId is 1-based and these arrays have the margin info in column + #zero, so no need to add 1 + x = self._colLeftEdges[trackId] + width = self._colWidths[trackId] + + lab = Label() + lab.setText(text) + lab.setOrigin(x + 0.5*width, y_bottom+0.5*y_height) + lab.boxAnchor = 'c' + lab.width = width + lab.height = y_height + lab.fontSize = 6 + + r = Rect(x, y_bottom, width, y_height, fillColor=colors.cyan) + g.add(r) + g.add(lab) + + #now for a label + # would expect to color-code and add text + return g + + def draw(self): + self.computeSize() + g = Group() + + # time column + g.add(Rect(self.x, self.y, self._colWidths[0], self.height - self.trackRowHeight, fillColor=colors.cornsilk)) + + # track headers + x = self.x + self._colWidths[0] + y = self.y + self.height - self.trackRowHeight + for trk in range(self._trackCount): + wid = self._colWidths[trk+1] + r = Rect(x, y, wid, self.trackRowHeight, fillColor=colors.yellow) + s = String(x + 0.5*wid, y, 'Track %d' % trk, align='middle') + g.add(r) + g.add(s) + x = x + wid + + for talk in self._talksVisible: + (title, speaker, trackId, day, start, duration) = talk + r = self.getTalkRect(start, duration, trackId, title + '\n' + speaker) + g.add(r) + + + return g + + + + +def test(): + "Make a conference event for day 1 of UP Python 2003" + + + d = Drawing(400,200) + + cal = EventCalendar() + cal.x = 50 + cal.y = 25 + cal.data = [ + # these might be better as objects instead of tuples, since I + # predict a large number of "optionsl" variables to affect + # formatting in future. + + #title, speaker, track id, day, start time (hrs), duration (hrs) + # track ID is 1-based not zero-based! + ('Keynote: Why design another programming language?', 'Guido van Rossum', None, 1, 9.0, 1.0), + + ('Siena Web Service Architecture', 'Marc-Andre Lemburg', 1, 1, 10.5, 1.5), + ('Extreme Programming in Python', 'Chris Withers', 2, 1, 10.5, 1.5), + ('Pattern Experiences in C++', 'Mark Radford', 3, 1, 10.5, 1.5), + ('What is the Type of std::toupper()', 'Gabriel Dos Reis', 4, 1, 10.5, 1.5), + ('Linguistic Variables: Clear Thinking with Fuzzy Logic ', 'Walter Banks', 5, 1, 10.5, 1.5), + + ('lunch, short presentations, vendor presentations', '', None, 1, 12.0, 2.0), + + ("CORBA? Isn't that obsolete", 'Duncan Grisby', 1, 1, 14.0, 1.5), + ("Python Design Patterns", 'Duncan Booth', 2, 1, 14.0, 1.5), + ("Inside Security Checks and Safe Exceptions", 'Brandon Bray', 3, 1, 14.0, 1.5), + ("Studying at a Distance", 'Panel Discussion, Panel to include Alan Lenton & Francis Glassborow', 4, 1, 14.0, 1.5), + ("Coding Standards - Given the ANSI C Standard why do I still need a coding Standard", 'Randy Marques', 5, 1, 14.0, 1.5), + + ("RESTful Python", 'Hamish Lawson', 1, 1, 16.0, 1.5), + ("Parsing made easier - a radical old idea", 'Andrew Koenig', 2, 1, 16.0, 1.5), + ("C++ & Multimethods", 'Julian Smith', 3, 1, 16.0, 1.5), + ("C++ Threading", 'Kevlin Henney', 4, 1, 16.0, 1.5), + ("The Organisation Strikes Back", 'Alan Griffiths & Sarah Lees', 5, 1, 16.0, 1.5), + + ('Birds of a Feather meeting', '', None, 1, 17.5, 2.0), + + ('Keynote: In the Spirit of C', 'Greg Colvin', None, 2, 9.0, 1.0), + + ('The Infinite Filing Cabinet - object storage in Python', 'Jacob Hallen', 1, 2, 10.5, 1.5), + ('Introduction to Python and Jython for C++ and Java Programmers', 'Alex Martelli', 2, 2, 10.5, 1.5), + ('Template metaprogramming in Haskell', 'Simon Peyton Jones', 3, 2, 10.5, 1.5), + ('Plenty People Programming: C++ Programming in a Group, Workshop with a difference', 'Nico Josuttis', 4, 2, 10.5, 1.5), + ('Design and Implementation of the Boost Graph Library', 'Jeremy Siek', 5, 2, 10.5, 1.5), + + ('lunch, short presentations, vendor presentations', '', None, 2, 12.0, 2.0), + + ("Building GUI Applications with PythonCard and PyCrust", 'Andy Todd', 1, 2, 14.0, 1.5), + ("Integrating Python, C and C++", 'Duncan Booth', 2, 2, 14.0, 1.5), + ("Secrets and Pitfalls of Templates", 'Nicolai Josuttis & David Vandevoorde', 3, 2, 14.0, 1.5), + ("Being a Mentor", 'Panel Discussion, Panel to include Alan Lenton & Francis Glassborow', 4, 2, 14.0, 1.5), + ("The Embedded C Extensions to C", 'Willem Wakker', 5, 2, 14.0, 1.5), + + ("Lightning Talks", 'Paul Brian', 1, 2, 16.0, 1.5), + ("Scripting Java Applications with Jython", 'Anthony Eden', 2, 2, 16.0, 1.5), + ("Metaprogramming and the Boost Metaprogramming Library", 'David Abrahams', 3, 2, 16.0, 1.5), + ("A Common Vendor ABI for C++ -- GCC's why, what and not", 'Nathan Sidwell & Gabriel Dos Reis', 4, 2, 16.0, 1.5), + ("The Timing and Cost of Choices", 'Hubert Matthews', 5, 2, 16.0, 1.5), + + ('Birds of a Feather meeting', '', None, 2, 17.5, 2.0), + + ('Keynote: The Cost of C & C++ Compatibility', 'Andy Koenig', None, 3, 9.0, 1.0), + + ('Prying Eyes: Generic Observer Implementations in C++', 'Andrei Alexandrescu', 1, 2, 10.5, 1.5), + ('The Roadmap to Generative Programming With C++', 'Ulrich Eisenecker', 2, 2, 10.5, 1.5), + ('Design Patterns in C++ and C# for the Common Language Runtime', 'Brandon Bray', 3, 2, 10.5, 1.5), + ('Extreme Hour (XH): (workshop) - Jutta Eckstein and Nico Josuttis', 'Jutta Ecstein', 4, 2, 10.5, 1.5), + ('The Lambda Library : Unnamed Functions for C++', 'Jaako Jarvi', 5, 2, 10.5, 1.5), + + ('lunch, short presentations, vendor presentations', '', None, 3, 12.0, 2.0), + + ('Reflective Metaprogramming', 'Daveed Vandevoorde', 1, 3, 14.0, 1.5), + ('Advanced Template Issues and Solutions (double session)', 'Herb Sutter',2, 3, 14.0, 3), + ('Concurrent Programming in Java (double session)', 'Angelika Langer', 3, 3, 14.0, 3), + ('What can MISRA-C (2nd Edition) do for us?', 'Chris Hills', 4, 3, 14.0, 1.5), + ('C++ Metaprogramming Concepts and Results', 'Walter E Brown', 5, 3, 14.0, 1.5), + + ('Binding C++ to Python with the Boost Python Library', 'David Abrahams', 1, 3, 16.0, 1.5), + ('Using Aspect Oriented Programming for Enterprise Application Integration', 'Arno Schmidmeier', 4, 3, 16.0, 1.5), + ('Defective C++', 'Marc Paterno', 5, 3, 16.0, 1.5), + + ("Speakers' Banquet & Birds of a Feather meeting", '', None, 3, 17.5, 2.0), + + ('Keynote: The Internet, Software and Computers - A Report Card', 'Alan Lenton', None, 4, 9.0, 1.0), + + ('Multi-Platform Software Development; Lessons from the Boost libraries', 'Beman Dawes', 1, 5, 10.5, 1.5), + ('The Stability of the C++ ABI', 'Steve Clamage', 2, 5, 10.5, 1.5), + ('Generic Build Support - A Pragmatic Approach to the Software Build Process', 'Randy Marques', 3, 5, 10.5, 1.5), + ('How to Handle Project Managers: a survival guide', 'Barb Byro', 4, 5, 10.5, 1.5), + + ('lunch, ACCU AGM', '', None, 5, 12.0, 2.0), + + ('Sauce: An OO recursive descent parser; its design and implementation.', 'Jon Jagger', 1, 5, 14.0, 1.5), + ('GNIRTS ESAC REWOL - Bringing the UNIX filters to the C++ iostream library.', 'JC van Winkel', 2, 5, 14.0, 1.5), + ('Pattern Writing: Live and Direct', 'Frank Buschmann & Kevlin Henney', 3, 5, 14.0, 3.0), + ('The Future of Programming Languages - A Goldfish Bowl', 'Francis Glassborow and friends', 3, 5, 14.0, 1.5), + + ('Honey, I Shrunk the Threads: Compile-time checked multithreaded transactions in C++', 'Andrei Alexandrescu', 1, 5, 16.0, 1.5), + ('Fun and Functionality with Functors', 'Lois Goldthwaite', 2, 5, 16.0, 1.5), + ('Agile Enough?', 'Alan Griffiths', 4, 5, 16.0, 1.5), + ("Conference Closure: A brief plenary session", '', None, 5, 17.5, 0.5), + + ] + + #return cal + cal.day = 1 + + d.add(cal) + + + for format in ['pdf']:#,'gif','png']: + out = d.asString(format) + open('eventcal.%s' % format, 'wb').write(out) + print('saved eventcal.%s' % format) + +if __name__=='__main__': + test() diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/widgets/flags.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/widgets/flags.py new file mode 100644 index 0000000000000000000000000000000000000000..7afd6b5a1318dc581bd190b128a96bbc2c720a1c --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/widgets/flags.py @@ -0,0 +1,879 @@ +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/graphics/widgets/flags.py +# Flag Widgets - a collection of flags as widgets +# author: John Precedo (johnp@reportlab.com) + +__version__='3.3.0' +__doc__="""This file is a collection of flag graphics as widgets. + +All flags are represented at the ratio of 1:2, even where the official ratio for the flag is something else +(such as 3:5 for the German national flag). The only exceptions are for where this would look _very_ wrong, +such as the Danish flag whose (ratio is 28:37), or the Swiss flag (which is square). + +Unless otherwise stated, these flags are all the 'national flags' of the countries, rather than their +state flags, naval flags, ensigns or any other variants. (National flags are the flag flown by civilians +of a country and the ones usually used to represent a country abroad. State flags are the variants used by +the government and by diplomatic missions overseas). + +To check on how close these are to the 'official' representations of flags, check the World Flag Database at +http://www.flags.ndirect.co.uk/ + +The flags this file contains are: + +EU Members: +United Kingdom, Austria, Belgium, Denmark, Finland, France, Germany, Greece, Ireland, Italy, Luxembourg, +Holland (The Netherlands), Spain, Sweden + +Others: +USA, Czech Republic, European Union, Switzerland, Turkey, Brazil + +(Brazilian flag contributed by Publio da Costa Melo [publio@planetarium.com.br]). +""" + +from reportlab.lib import colors +from reportlab.lib.validators import * +from reportlab.lib.attrmap import * +from reportlab.graphics.shapes import Line, Rect, Polygon, Drawing, Group, String, Circle, Wedge +from reportlab.graphics import renderPDF +from reportlab.graphics.widgets.signsandsymbols import _Symbol +import copy +from math import sin, cos, pi + +validFlag=OneOf(None, + 'UK', + 'USA', + 'Afghanistan', + 'Austria', + 'Belgium', + 'China', + 'Cuba', + 'Denmark', + 'Finland', + 'France', + 'Germany', + 'Greece', + 'Ireland', + 'Italy', + 'Japan', + 'Luxembourg', + 'Holland', + 'Palestine', + 'Portugal', + 'Russia', + 'Spain', + 'Sweden', + 'Norway', + 'CzechRepublic', + 'Turkey', + 'Switzerland', + 'EU', + 'Brazil' + ) + +_size = 100. + +class Star(_Symbol): + """This draws a 5-pointed star. + + possible attributes: + 'x', 'y', 'size', 'fillColor', 'strokeColor' + + """ + _attrMap = AttrMap(BASE=_Symbol, + angle = AttrMapValue(isNumber, desc='angle in degrees'), + ) + _size = 100. + + def __init__(self): + _Symbol.__init__(self) + self.size = 100 + self.fillColor = colors.yellow + self.strokeColor = None + self.angle = 0 + + def demo(self): + D = Drawing(200, 100) + et = Star() + et.x=50 + et.y=0 + D.add(et) + labelFontSize = 10 + D.add(String(et.x+(et.size/2.0),(et.y-(1.2*labelFontSize)), + et.__class__.__name__, fillColor=colors.black, textAnchor='middle', + fontSize=labelFontSize)) + return D + + def draw(self): + s = float(self.size) #abbreviate as we will use this a lot + g = Group() + + # new algorithm from markers.StarFive + R = float(self.size)/2 + r = R*sin(18*(pi/180.0))/cos(36*(pi/180.0)) + P = [] + angle = 90 + for i in range(5): + for radius in R, r: + theta = angle*(pi/180.0) + P.append(radius*cos(theta)) + P.append(radius*sin(theta)) + angle = angle + 36 + # star specific bits + star = Polygon(P, + fillColor = self.fillColor, + strokeColor = self.strokeColor, + strokeWidth=s/50) + g.rotate(self.angle) + g.shift(self.x+self.dx,self.y+self.dy) + g.add(star) + + return g + +class Flag(_Symbol): + """This is a generic flag class that all the flags in this file use as a basis. + + This class basically provides edges and a tidy-up routine to hide any bits of + line that overlap the 'outside' of the flag + + possible attributes: + 'x', 'y', 'size', 'fillColor' + """ + + _attrMap = AttrMap(BASE=_Symbol, + fillColor = AttrMapValue(isColor, desc='Background color'), + border = AttrMapValue(isBoolean, 'Whether a background is drawn'), + kind = AttrMapValue(validFlag, desc='Which flag'), + ) + + _cache = {} + + def __init__(self,**kw): + _Symbol.__init__(self) + self.kind = None + self.size = 100 + self.fillColor = colors.white + self.border=1 + self.setProperties(kw) + + def availableFlagNames(self): + '''return a list of the things we can display''' + return [x for x in self._attrMap['kind'].validate._enum if x is not None] + + def _Flag_None(self): + s = _size # abbreviate as we will use this a lot + g = Group() + g.add(Rect(0, 0, s*2, s, fillColor = colors.purple, strokeColor = colors.black, strokeWidth=0)) + return g + + def _borderDraw(self,f): + s = self.size # abbreviate as we will use this a lot + g = Group() + g.add(f) + x, y, sW = self.x+self.dx, self.y+self.dy, self.strokeWidth/2. + g.insert(0,Rect(-sW, -sW, width=getattr(self,'_width',2*s)+3*sW, height=getattr(self,'_height',s)+2*sW, + fillColor = None, strokeColor = self.strokeColor, strokeWidth=sW*2)) + g.shift(x,y) + g.scale(s/_size, s/_size) + return g + + def draw(self): + kind = self.kind or 'None' + f = self._cache.get(kind) + if not f: + f = getattr(self,'_Flag_'+kind)() + self._cache[kind] = f._explode() + return self._borderDraw(f) + + def clone(self): + return copy.copy(self) + + def demo(self): + D = Drawing(200, 100) + name = self.availableFlagNames() + import time + name = name[int(time.time()) % len(name)] + fx = Flag() + fx.kind = name + fx.x = 0 + fx.y = 0 + D.add(fx) + labelFontSize = 10 + D.add(String(fx.x+(fx.size/2.0),(fx.y-(1.2*labelFontSize)), + name, fillColor=colors.black, textAnchor='middle', + fontSize=labelFontSize)) + labelFontSize = int(fx.size/4.0) + D.add(String(fx.x+(fx.size),(fx.y+((fx.size/2.0))), + "SAMPLE", fillColor=colors.gold, textAnchor='middle', + fontSize=labelFontSize, fontName="Helvetica-Bold")) + return D + + def _Flag_UK(self): + s = _size + g = Group() + w = s*2 + g.add(Rect(0, 0, w, s, fillColor = colors.navy, strokeColor = colors.black, strokeWidth=0)) + g.add(Polygon([0,0, s*.225,0, w,s*(1-.1125), w,s, w-s*.225,s, 0, s*.1125], fillColor = colors.mintcream, strokeColor=None, strokeWidth=0)) + g.add(Polygon([0,s*(1-.1125), 0, s, s*.225,s, w, s*.1125, w,0, w-s*.225,0], fillColor = colors.mintcream, strokeColor=None, strokeWidth=0)) + g.add(Polygon([0, s-(s/15.0), (s-((s/10.0)*4)), (s*0.65), (s-(s/10.0)*3), (s*0.65), 0, s], fillColor = colors.red, strokeColor = None, strokeWidth=0)) + g.add(Polygon([0, 0, (s-((s/10.0)*3)), (s*0.35), (s-((s/10.0)*2)), (s*0.35), (s/10.0), 0], fillColor = colors.red, strokeColor = None, strokeWidth=0)) + g.add(Polygon([w, s, (s+((s/10.0)*3)), (s*0.65), (s+((s/10.0)*2)), (s*0.65), w-(s/10.0), s], fillColor = colors.red, strokeColor = None, strokeWidth=0)) + g.add(Polygon([w, (s/15.0), (s+((s/10.0)*4)), (s*0.35), (s+((s/10.0)*3)), (s*0.35), w, 0], fillColor = colors.red, strokeColor = None, strokeWidth=0)) + g.add(Rect(((s*0.42)*2), 0, width=(0.16*s)*2, height=s, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0)) + g.add(Rect(0, (s*0.35), width=w, height=s*0.3, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0)) + g.add(Rect(((s*0.45)*2), 0, width=(0.1*s)*2, height=s, fillColor = colors.red, strokeColor = None, strokeWidth=0)) + g.add(Rect(0, (s*0.4), width=w, height=s*0.2, fillColor = colors.red, strokeColor = None, strokeWidth=0)) + return g + + def _Flag_USA(self): + s = _size # abbreviate as we will use this a lot + g = Group() + + box = Rect(0, 0, s*2, s, fillColor = colors.mintcream, strokeColor = colors.black, strokeWidth=0) + g.add(box) + + for stripecounter in range (13,0, -1): + stripeheight = s/13.0 + if not (stripecounter%2 == 0): + stripecolor = colors.red + else: + stripecolor = colors.mintcream + redorwhiteline = Rect(0, (s-(stripeheight*stripecounter)), width=s*2, height=stripeheight, + fillColor = stripecolor, strokeColor = None, strokeWidth=20) + g.add(redorwhiteline) + + bluebox = Rect(0, (s-(stripeheight*7)), width=0.8*s, height=stripeheight*7, + fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) + g.add(bluebox) + + lss = s*0.045 + lss2 = lss/2.0 + s9 = s/9.0 + s7 = s/7.0 + for starxcounter in range(5): + for starycounter in range(4): + ls = Star() + ls.size = lss + ls.x = 0-s/22.0+lss/2.0+s7+starxcounter*s7 + ls.fillColor = colors.mintcream + ls.y = s-(starycounter+1)*s9+lss2 + g.add(ls) + + for starxcounter in range(6): + for starycounter in range(5): + ls = Star() + ls.size = lss + ls.x = 0-(s/22.0)+lss/2.0+s/14.0+starxcounter*s7 + ls.fillColor = colors.mintcream + ls.y = s-(starycounter+1)*s9+(s/18.0)+lss2 + g.add(ls) + return g + + def _Flag_Afghanistan(self): + s = _size + g = Group() + + box = Rect(0, 0, s*2, s, + fillColor = colors.mintcream, strokeColor = colors.black, strokeWidth=0) + g.add(box) + + greenbox = Rect(0, ((s/3.0)*2.0), width=s*2.0, height=s/3.0, + fillColor = colors.limegreen, strokeColor = None, strokeWidth=0) + g.add(greenbox) + + blackbox = Rect(0, 0, width=s*2.0, height=s/3.0, + fillColor = colors.black, strokeColor = None, strokeWidth=0) + g.add(blackbox) + return g + + def _Flag_Austria(self): + s = _size # abbreviate as we will use this a lot + g = Group() + + box = Rect(0, 0, s*2, s, fillColor = colors.mintcream, + strokeColor = colors.black, strokeWidth=0) + g.add(box) + + + redbox1 = Rect(0, 0, width=s*2.0, height=s/3.0, + fillColor = colors.red, strokeColor = None, strokeWidth=0) + g.add(redbox1) + + redbox2 = Rect(0, ((s/3.0)*2.0), width=s*2.0, height=s/3.0, + fillColor = colors.red, strokeColor = None, strokeWidth=0) + g.add(redbox2) + return g + + def _Flag_Belgium(self): + s = _size + g = Group() + + box = Rect(0, 0, s*2, s, + fillColor = colors.black, strokeColor = colors.black, strokeWidth=0) + g.add(box) + + + box1 = Rect(0, 0, width=(s/3.0)*2.0, height=s, + fillColor = colors.black, strokeColor = None, strokeWidth=0) + g.add(box1) + + box2 = Rect(((s/3.0)*2.0), 0, width=(s/3.0)*2.0, height=s, + fillColor = colors.gold, strokeColor = None, strokeWidth=0) + g.add(box2) + + box3 = Rect(((s/3.0)*4.0), 0, width=(s/3.0)*2.0, height=s, + fillColor = colors.red, strokeColor = None, strokeWidth=0) + g.add(box3) + return g + + def _Flag_China(self): + s = _size + g = Group() + self._width = w = s*1.5 + g.add(Rect(0, 0, w, s, fillColor=colors.red, strokeColor=None, strokeWidth=0)) + + def addStar(x,y,size,angle,g=g,w=s/20.0,x0=0,y0=s/2.0): + s = Star() + s.fillColor=colors.yellow + s.angle = angle + s.size = size*w*2 + s.x = x*w+x0 + s.y = y*w+y0 + g.add(s) + + addStar(5,5,3, 0) + addStar(10,1,1,36.86989765) + addStar(12,3,1,8.213210702) + addStar(12,6,1,16.60154960) + addStar(10,8,1,53.13010235) + return g + + def _Flag_Cuba(self): + s = _size + g = Group() + + for i in range(5): + stripe = Rect(0, i*s/5.0, width=s*2, height=s/5.0, + fillColor = [colors.darkblue, colors.mintcream][i%2], + strokeColor = None, + strokeWidth=0) + g.add(stripe) + + redwedge = Polygon(points = [ 0, 0, 4*s/5.0, (s/2.0), 0, s], + fillColor = colors.red, strokeColor = None, strokeWidth=0) + g.add(redwedge) + + star = Star() + star.x = 2.5*s/10.0 + star.y = s/2.0 + star.size = 3*s/10.0 + star.fillColor = colors.white + g.add(star) + + box = Rect(0, 0, s*2, s, + fillColor = None, + strokeColor = colors.black, + strokeWidth=0) + g.add(box) + + return g + + def _Flag_Denmark(self): + s = _size + g = Group() + self._width = w = s*1.4 + + box = Rect(0, 0, w, s, + fillColor = colors.red, strokeColor = colors.black, strokeWidth=0) + g.add(box) + + whitebox1 = Rect(((s/5.0)*2), 0, width=s/6.0, height=s, + fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) + g.add(whitebox1) + + whitebox2 = Rect(0, ((s/2.0)-(s/12.0)), width=w, height=s/6.0, + fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) + g.add(whitebox2) + return g + + def _Flag_Finland(self): + s = _size + g = Group() + + # crossbox specific bits + box = Rect(0, 0, s*2, s, + fillColor = colors.ghostwhite, strokeColor = colors.black, strokeWidth=0) + g.add(box) + + blueline1 = Rect((s*0.6), 0, width=0.3*s, height=s, + fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) + g.add(blueline1) + + blueline2 = Rect(0, (s*0.4), width=s*2, height=s*0.3, + fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) + g.add(blueline2) + return g + + def _Flag_France(self): + s = _size + g = Group() + + box = Rect(0, 0, s*2, s, fillColor = colors.navy, strokeColor = colors.black, strokeWidth=0) + g.add(box) + + bluebox = Rect(0, 0, width=((s/3.0)*2.0), height=s, + fillColor = colors.blue, strokeColor = None, strokeWidth=0) + g.add(bluebox) + + whitebox = Rect(((s/3.0)*2.0), 0, width=((s/3.0)*2.0), height=s, + fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) + g.add(whitebox) + + redbox = Rect(((s/3.0)*4.0), 0, width=((s/3.0)*2.0), height=s, + fillColor = colors.red, + strokeColor = None, + strokeWidth=0) + g.add(redbox) + return g + + def _Flag_Germany(self): + s = _size + g = Group() + + box = Rect(0, 0, s*2, s, + fillColor = colors.gold, strokeColor = colors.black, strokeWidth=0) + g.add(box) + + blackbox1 = Rect(0, ((s/3.0)*2.0), width=s*2.0, height=s/3.0, + fillColor = colors.black, strokeColor = None, strokeWidth=0) + g.add(blackbox1) + + redbox1 = Rect(0, (s/3.0), width=s*2.0, height=s/3.0, + fillColor = colors.orangered, strokeColor = None, strokeWidth=0) + g.add(redbox1) + return g + + def _Flag_Greece(self): + s = _size + g = Group() + + box = Rect(0, 0, s*2, s, fillColor = colors.gold, + strokeColor = colors.black, strokeWidth=0) + g.add(box) + + for stripecounter in range (9,0, -1): + stripeheight = s/9.0 + if not (stripecounter%2 == 0): + stripecolor = colors.deepskyblue + else: + stripecolor = colors.mintcream + + blueorwhiteline = Rect(0, (s-(stripeheight*stripecounter)), width=s*2, height=stripeheight, + fillColor = stripecolor, strokeColor = None, strokeWidth=20) + g.add(blueorwhiteline) + + bluebox1 = Rect(0, ((s)-stripeheight*5), width=(stripeheight*5), height=stripeheight*5, + fillColor = colors.deepskyblue, strokeColor = None, strokeWidth=0) + g.add(bluebox1) + + whiteline1 = Rect(0, ((s)-stripeheight*3), width=stripeheight*5, height=stripeheight, + fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) + g.add(whiteline1) + + whiteline2 = Rect((stripeheight*2), ((s)-stripeheight*5), width=stripeheight, height=stripeheight*5, + fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) + g.add(whiteline2) + + return g + + def _Flag_Ireland(self): + s = _size + g = Group() + + box = Rect(0, 0, s*2, s, + fillColor = colors.forestgreen, strokeColor = colors.black, strokeWidth=0) + g.add(box) + + whitebox = Rect(((s*2.0)/3.0), 0, width=(2.0*(s*2.0)/3.0), height=s, + fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) + g.add(whitebox) + + orangebox = Rect(((2.0*(s*2.0)/3.0)), 0, width=(s*2.0)/3.0, height=s, + fillColor = colors.darkorange, strokeColor = None, strokeWidth=0) + g.add(orangebox) + return g + + def _Flag_Italy(self): + s = _size + g = Group() + g.add(Rect(0,0,s*2,s,fillColor=colors.forestgreen,strokeColor=None, strokeWidth=0)) + g.add(Rect((2*s)/3.0, 0, width=(s*4)/3.0, height=s, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0)) + g.add(Rect((4*s)/3.0, 0, width=(s*2)/3.0, height=s, fillColor = colors.red, strokeColor = None, strokeWidth=0)) + return g + + def _Flag_Japan(self): + s = _size + g = Group() + w = self._width = s*1.5 + g.add(Rect(0,0,w,s,fillColor=colors.mintcream,strokeColor=None, strokeWidth=0)) + g.add(Circle(cx=w/2.0,cy=s/2.0,r=0.3*w,fillColor=colors.red,strokeColor=None, strokeWidth=0)) + return g + + def _Flag_Luxembourg(self): + s = _size + g = Group() + + box = Rect(0, 0, s*2, s, + fillColor = colors.mintcream, strokeColor = colors.black, strokeWidth=0) + g.add(box) + + redbox = Rect(0, ((s/3.0)*2.0), width=s*2.0, height=s/3.0, + fillColor = colors.red, strokeColor = None, strokeWidth=0) + g.add(redbox) + + bluebox = Rect(0, 0, width=s*2.0, height=s/3.0, + fillColor = colors.dodgerblue, strokeColor = None, strokeWidth=0) + g.add(bluebox) + return g + + def _Flag_Holland(self): + s = _size + g = Group() + + box = Rect(0, 0, s*2, s, + fillColor = colors.mintcream, strokeColor = colors.black, strokeWidth=0) + g.add(box) + + redbox = Rect(0, ((s/3.0)*2.0), width=s*2.0, height=s/3.0, + fillColor = colors.red, strokeColor = None, strokeWidth=0) + g.add(redbox) + + bluebox = Rect(0, 0, width=s*2.0, height=s/3.0, + fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) + g.add(bluebox) + return g + + def _Flag_Portugal(self): + return Group() + + def _Flag_Russia(self): + s = _size + g = Group() + w = self._width = s*1.5 + t = s/3.0 + g.add(Rect(0, 0, width=w, height=t, fillColor = colors.red, strokeColor = None, strokeWidth=0)) + g.add(Rect(0, t, width=w, height=t, fillColor = colors.blue, strokeColor = None, strokeWidth=0)) + g.add(Rect(0, 2*t, width=w, height=t, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0)) + return g + + def _Flag_Spain(self): + s = _size + g = Group() + w = self._width = s*1.5 + g.add(Rect(0, 0, width=w, height=s, fillColor = colors.red, strokeColor = None, strokeWidth=0)) + g.add(Rect(0, (s/4.0), width=w, height=s/2.0, fillColor = colors.yellow, strokeColor = None, strokeWidth=0)) + return g + + def _Flag_Sweden(self): + s = _size + g = Group() + self._width = s*1.4 + box = Rect(0, 0, self._width, s, + fillColor = colors.dodgerblue, strokeColor = colors.black, strokeWidth=0) + g.add(box) + + box1 = Rect(((s/5.0)*2), 0, width=s/6.0, height=s, + fillColor = colors.gold, strokeColor = None, strokeWidth=0) + g.add(box1) + + box2 = Rect(0, ((s/2.0)-(s/12.0)), width=self._width, height=s/6.0, + fillColor = colors.gold, + strokeColor = None, + strokeWidth=0) + g.add(box2) + return g + + def _Flag_Norway(self): + s = _size + g = Group() + self._width = s*1.4 + + box = Rect(0, 0, self._width, s, + fillColor = colors.red, strokeColor = colors.black, strokeWidth=0) + g.add(box) + + box = Rect(0, 0, self._width, s, + fillColor = colors.red, strokeColor = colors.black, strokeWidth=0) + g.add(box) + + whiteline1 = Rect(((s*0.2)*2), 0, width=s*0.2, height=s, + fillColor = colors.ghostwhite, strokeColor = None, strokeWidth=0) + g.add(whiteline1) + + whiteline2 = Rect(0, (s*0.4), width=self._width, height=s*0.2, + fillColor = colors.ghostwhite, strokeColor = None, strokeWidth=0) + g.add(whiteline2) + + blueline1 = Rect(((s*0.225)*2), 0, width=0.1*s, height=s, + fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) + g.add(blueline1) + + blueline2 = Rect(0, (s*0.45), width=self._width, height=s*0.1, + fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) + g.add(blueline2) + return g + + def _Flag_CzechRepublic(self): + s = _size + g = Group() + box = Rect(0, 0, s*2, s, + fillColor = colors.mintcream, + strokeColor = colors.black, + strokeWidth=0) + g.add(box) + + redbox = Rect(0, 0, width=s*2, height=s/2.0, + fillColor = colors.red, + strokeColor = None, + strokeWidth=0) + g.add(redbox) + + bluewedge = Polygon(points = [ 0, 0, s, (s/2.0), 0, s], + fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) + g.add(bluewedge) + return g + + def _Flag_Palestine(self): + s = _size + g = Group() + box = Rect(0, s/3.0, s*2, s/3.0, + fillColor = colors.mintcream, + strokeColor = None, + strokeWidth=0) + g.add(box) + + greenbox = Rect(0, 0, width=s*2, height=s/3.0, + fillColor = colors.limegreen, + strokeColor = None, + strokeWidth=0) + g.add(greenbox) + + blackbox = Rect(0, 2*s/3.0, width=s*2, height=s/3.0, + fillColor = colors.black, + strokeColor = None, + strokeWidth=0) + g.add(blackbox) + + redwedge = Polygon(points = [ 0, 0, 2*s/3.0, (s/2.0), 0, s], + fillColor = colors.red, strokeColor = None, strokeWidth=0) + g.add(redwedge) + return g + + def _Flag_Turkey(self): + s = _size + g = Group() + + box = Rect(0, 0, s*2, s, + fillColor = colors.red, + strokeColor = colors.black, + strokeWidth=0) + g.add(box) + + whitecircle = Circle(cx=((s*0.35)*2), cy=s/2.0, r=s*0.3, + fillColor = colors.mintcream, + strokeColor = None, + strokeWidth=0) + g.add(whitecircle) + + redcircle = Circle(cx=((s*0.39)*2), cy=s/2.0, r=s*0.24, + fillColor = colors.red, + strokeColor = None, + strokeWidth=0) + g.add(redcircle) + + ws = Star() + ws.angle = 15 + ws.size = s/5.0 + ws.x = (s*0.5)*2+ws.size/2.0 + ws.y = (s*0.5) + ws.fillColor = colors.mintcream + ws.strokeColor = None + g.add(ws) + return g + + def _Flag_Switzerland(self): + s = _size + g = Group() + self._width = s + + g.add(Rect(0, 0, s, s, fillColor = colors.red, strokeColor = colors.black, strokeWidth=0)) + g.add(Line((s/2.0), (s/5.5), (s/2), (s-(s/5.5)), + fillColor = colors.mintcream, strokeColor = colors.mintcream, strokeWidth=(s/5.0))) + g.add(Line((s/5.5), (s/2.0), (s-(s/5.5)), (s/2.0), + fillColor = colors.mintcream, strokeColor = colors.mintcream, strokeWidth=s/5.0)) + return g + + def _Flag_EU(self): + s = _size + g = Group() + w = self._width = 1.5*s + + g.add(Rect(0, 0, w, s, fillColor = colors.darkblue, strokeColor = None, strokeWidth=0)) + centerx=w/2.0 + centery=s/2.0 + radius=s/3.0 + yradius = radius + xradius = radius + nStars = 12 + delta = 2*pi/nStars + for i in range(nStars): + rad = i*delta + gs = Star() + gs.x=cos(rad)*radius+centerx + gs.y=sin(rad)*radius+centery + gs.size=s/10.0 + gs.fillColor=colors.gold + g.add(gs) + return g + + def _Flag_Brazil(self): + s = _size # abbreviate as we will use this a lot + g = Group() + + m = s/14.0 + self._width = w = (m * 20) + + def addStar(x,y,size, g=g, w=w, s=s, m=m): + st = Star() + st.fillColor=colors.mintcream + st.size = size*m + st.x = (w/2.0) + (x * (0.35 * m)) + st.y = (s/2.0) + (y * (0.35 * m)) + g.add(st) + + g.add(Rect(0, 0, w, s, fillColor = colors.green, strokeColor = None, strokeWidth=0)) + g.add(Polygon(points = [ 1.7*m, (s/2.0), (w/2.0), s-(1.7*m), w-(1.7*m),(s/2.0),(w/2.0), 1.7*m], + fillColor = colors.yellow, strokeColor = None, strokeWidth=0)) + g.add(Circle(cx=w/2.0, cy=s/2.0, r=3.5*m, + fillColor=colors.blue,strokeColor=None, strokeWidth=0)) + g.add(Wedge((w/2.0)-(2*m), 0, 8.5*m, 50, 98.1, 8.5*m, + fillColor=colors.mintcream,strokeColor=None, strokeWidth=0)) + g.add(Wedge((w/2.0), (s/2.0), 3.501*m, 156, 352, 3.501*m, + fillColor=colors.mintcream,strokeColor=None, strokeWidth=0)) + g.add(Wedge((w/2.0)-(2*m), 0, 8*m, 48.1, 100, 8*m, + fillColor=colors.blue,strokeColor=None, strokeWidth=0)) + g.add(Rect(0, 0, w, (s/4.0) + 1.7*m, + fillColor = colors.green, strokeColor = None, strokeWidth=0)) + g.add(Polygon(points = [ 1.7*m,(s/2.0), (w/2.0),s/2.0 - 2*m, w-(1.7*m),(s/2.0) , (w/2.0),1.7*m], + fillColor = colors.yellow, strokeColor = None, strokeWidth=0)) + g.add(Wedge(w/2.0, s/2.0, 3.502*m, 166, 342.1, 3.502*m, + fillColor=colors.blue,strokeColor=None, strokeWidth=0)) + + addStar(3.2,3.5,0.3) + addStar(-8.5,1.5,0.3) + addStar(-7.5,-3,0.3) + addStar(-4,-5.5,0.3) + addStar(0,-4.5,0.3) + addStar(7,-3.5,0.3) + addStar(-3.5,-0.5,0.25) + addStar(0,-1.5,0.25) + addStar(1,-2.5,0.25) + addStar(3,-7,0.25) + addStar(5,-6.5,0.25) + addStar(6.5,-5,0.25) + addStar(7,-4.5,0.25) + addStar(-5.5,-3.2,0.25) + addStar(-6,-4.2,0.25) + addStar(-1,-2.75,0.2) + addStar(2,-5.5,0.2) + addStar(4,-5.5,0.2) + addStar(5,-7.5,0.2) + addStar(5,-5.5,0.2) + addStar(6,-5.5,0.2) + addStar(-8.8,-3.2,0.2) + addStar(2.5,0.5,0.2) + addStar(-0.2,-3.2,0.14) + addStar(-7.2,-2,0.14) + addStar(0,-8,0.1) + + sTmp = "ORDEM E PROGRESSO" + nTmp = len(sTmp) + delta = 0.850848010347/nTmp + radius = 7.9 *m + centerx = (w/2.0)-(2*m) + centery = 0 + for i in range(nTmp): + rad = 2*pi - i*delta -4.60766922527 + x=cos(rad)*radius+centerx + y=sin(rad)*radius+centery + if i == 6: + z = 0.35*m + else: + z= 0.45*m + g2 = Group(String(x, y, sTmp[i], fontName='Helvetica-Bold', + fontSize = z,strokeColor=None,fillColor=colors.green)) + g2.rotate(rad) + g.add(g2) + return g + +def makeFlag(name): + flag = Flag() + flag.kind = name + return flag + +def test(): + """This function produces three pdf files with examples of all the signs and symbols from this file. + """ +# page 1 + + labelFontSize = 10 + + X = (20,245) + + flags = [ + 'UK', + 'USA', + 'Afghanistan', + 'Austria', + 'Belgium', + 'Denmark', + 'Cuba', + 'Finland', + 'France', + 'Germany', + 'Greece', + 'Ireland', + 'Italy', + 'Luxembourg', + 'Holland', + 'Palestine', + 'Portugal', + 'Spain', + 'Sweden', + 'Norway', + 'CzechRepublic', + 'Turkey', + 'Switzerland', + 'EU', + 'Brazil', + ] + y = Y0 = 530 + f = 0 + D = None + for name in flags: + if not D: D = Drawing(450,650) + flag = makeFlag(name) + i = flags.index(name) + flag.x = X[i%2] + flag.y = y + D.add(flag) + D.add(String(flag.x+(flag.size/2.0),(flag.y-(1.2*labelFontSize)), + name, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) + if i%2: y = y - 125 + if (i%2 and y<0) or name==flags[-1]: + renderPDF.drawToFile(D, 'flags%02d.pdf'%f, 'flags.py - Page #%d'%(f+1)) + y = Y0 + f = f+1 + D = None + +if __name__=='__main__': + test() diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/widgets/grids.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/widgets/grids.py new file mode 100644 index 0000000000000000000000000000000000000000..a1bfa6336f00667bc5c66d4b6406ef8a240b45b3 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/widgets/grids.py @@ -0,0 +1,542 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/graphics/widgets/grids.py +__version__='3.3.0' + +from reportlab.lib import colors +from reportlab.lib.validators import isNumber, isColorOrNone, isBoolean, isListOfNumbers, OneOf, isListOfColors, isNumberOrNone +from reportlab.lib.attrmap import AttrMap, AttrMapValue +from reportlab.graphics.shapes import Drawing, Group, Line, Rect, LineShape, definePath, EmptyClipPath +from reportlab.graphics.widgetbase import Widget +from math import radians +from reportlab.graphics.transform import translate, rotate, mmult, transformPoints, inverse +from reportlab.lib.utils import flatten + +def frange(start, end=None, inc=None): + "A range function, that does accept float increments..." + + if end == None: + end = start + 0.0 + start = 0.0 + + if inc == None: + inc = 1.0 + + L = [] + end = end - inc*0.0001 #to avoid numrical problems + while 1: + next = start + len(L) * inc + if inc > 0 and next >= end: + break + elif inc < 0 and next <= end: + break + L.append(next) + + return L + + +def makeDistancesList(list): + """Returns a list of distances between adjacent numbers in some input list. + + E.g. [1, 1, 2, 3, 5, 7] -> [0, 1, 1, 2, 2] + """ + + d = [] + for i in range(len(list[:-1])): + d.append(list[i+1] - list[i]) + + return d + + +class Grid(Widget): + """This makes a rectangular grid of equidistant stripes. + + The grid contains an outer border rectangle, and stripes + inside which can be drawn with lines and/or as solid tiles. + The drawing order is: outer rectangle, then lines and tiles. + + The stripes' width is indicated as 'delta'. The sequence of + stripes can have an offset named 'delta0'. Both values need + to be positive! + """ + + _attrMap = AttrMap( + x = AttrMapValue(isNumber, desc="The grid's lower-left x position."), + y = AttrMapValue(isNumber, desc="The grid's lower-left y position."), + width = AttrMapValue(isNumber, desc="The grid's width."), + height = AttrMapValue(isNumber, desc="The grid's height."), + orientation = AttrMapValue(OneOf(('vertical', 'horizontal')), + desc='Determines if stripes are vertical or horizontal.'), + useLines = AttrMapValue(OneOf((0, 1)), + desc='Determines if stripes are drawn with lines.'), + useRects = AttrMapValue(OneOf((0, 1)), + desc='Determines if stripes are drawn with solid rectangles.'), + delta = AttrMapValue(isNumber, + desc='Determines the width/height of the stripes.'), + delta0 = AttrMapValue(isNumber, + desc='Determines the stripes initial width/height offset.'), + deltaSteps = AttrMapValue(isListOfNumbers, + desc='List of deltas to be used cyclically.'), + stripeColors = AttrMapValue(isListOfColors, + desc='Colors applied cyclically in the right or upper direction.'), + fillColor = AttrMapValue(isColorOrNone, + desc='Background color for entire rectangle.'), + strokeColor = AttrMapValue(isColorOrNone, + desc='Color used for lines.'), + strokeWidth = AttrMapValue(isNumber, + desc='Width used for lines.'), + rectStrokeColor = AttrMapValue(isColorOrNone, desc='Color for outer rect stroke.'), + rectStrokeWidth = AttrMapValue(isNumberOrNone, desc='Width for outer rect stroke.'), + ) + + def __init__(self): + self.x = 0 + self.y = 0 + self.width = 100 + self.height = 100 + self.orientation = 'vertical' + self.useLines = 0 + self.useRects = 1 + self.delta = 20 + self.delta0 = 0 + self.deltaSteps = [] + self.fillColor = colors.white + self.stripeColors = [colors.red, colors.green, colors.blue] + self.strokeColor = colors.black + self.strokeWidth = 2 + + + def demo(self): + D = Drawing(100, 100) + + g = Grid() + D.add(g) + + return D + + def makeOuterRect(self): + strokeColor = getattr(self,'rectStrokeColor',self.strokeColor) + strokeWidth = getattr(self,'rectStrokeWidth',self.strokeWidth) + if self.fillColor or (strokeColor and strokeWidth): + rect = Rect(self.x, self.y, self.width, self.height) + rect.fillColor = self.fillColor + rect.strokeColor = strokeColor + rect.strokeWidth = strokeWidth + return rect + else: + return None + + def makeLinePosList(self, start, isX=0): + "Returns a list of positions where to place lines." + + w, h = self.width, self.height + if isX: + length = w + else: + length = h + if self.deltaSteps: + r = [start + self.delta0] + i = 0 + while 1: + if r[-1] > start + length: + del r[-1] + break + r.append(r[-1] + self.deltaSteps[i % len(self.deltaSteps)]) + i = i + 1 + else: + r = frange(start + self.delta0, start + length, self.delta) + + r.append(start + length) + if self.delta0 != 0: + r.insert(0, start) + #print 'Grid.makeLinePosList() -> %s' % r + return r + + + def makeInnerLines(self): + # inner grid lines + group = Group() + + w, h = self.width, self.height + + if self.useLines == 1: + if self.orientation == 'vertical': + r = self.makeLinePosList(self.x, isX=1) + for x in r: + line = Line(x, self.y, x, self.y + h) + line.strokeColor = self.strokeColor + line.strokeWidth = self.strokeWidth + group.add(line) + elif self.orientation == 'horizontal': + r = self.makeLinePosList(self.y, isX=0) + for y in r: + line = Line(self.x, y, self.x + w, y) + line.strokeColor = self.strokeColor + line.strokeWidth = self.strokeWidth + group.add(line) + + return group + + + def makeInnerTiles(self): + # inner grid lines + group = Group() + + w, h = self.width, self.height + + # inner grid stripes (solid rectangles) + if self.useRects == 1: + cols = self.stripeColors + + if self.orientation == 'vertical': + r = self.makeLinePosList(self.x, isX=1) + elif self.orientation == 'horizontal': + r = self.makeLinePosList(self.y, isX=0) + + dist = makeDistancesList(r) + + i = 0 + for j in range(len(dist)): + if self.orientation == 'vertical': + x = r[j] + stripe = Rect(x, self.y, dist[j], h) + elif self.orientation == 'horizontal': + y = r[j] + stripe = Rect(self.x, y, w, dist[j]) + stripe.fillColor = cols[i % len(cols)] + stripe.strokeColor = None + group.add(stripe) + i = i + 1 + + return group + + + def draw(self): + # general widget bits + group = Group() + + group.add(self.makeOuterRect()) + group.add(self.makeInnerTiles()) + group.add(self.makeInnerLines(),name='_gridLines') + + return group + + +class DoubleGrid(Widget): + """This combines two ordinary Grid objects orthogonal to each other. + """ + + _attrMap = AttrMap( + x = AttrMapValue(isNumber, desc="The grid's lower-left x position."), + y = AttrMapValue(isNumber, desc="The grid's lower-left y position."), + width = AttrMapValue(isNumber, desc="The grid's width."), + height = AttrMapValue(isNumber, desc="The grid's height."), + grid0 = AttrMapValue(None, desc="The first grid component."), + grid1 = AttrMapValue(None, desc="The second grid component."), + ) + + def __init__(self): + self.x = 0 + self.y = 0 + self.width = 100 + self.height = 100 + + g0 = Grid() + g0.x = self.x + g0.y = self.y + g0.width = self.width + g0.height = self.height + g0.orientation = 'vertical' + g0.useLines = 1 + g0.useRects = 0 + g0.delta = 20 + g0.delta0 = 0 + g0.deltaSteps = [] + g0.fillColor = colors.white + g0.stripeColors = [colors.red, colors.green, colors.blue] + g0.strokeColor = colors.black + g0.strokeWidth = 1 + + g1 = Grid() + g1.x = self.x + g1.y = self.y + g1.width = self.width + g1.height = self.height + g1.orientation = 'horizontal' + g1.useLines = 1 + g1.useRects = 0 + g1.delta = 20 + g1.delta0 = 0 + g1.deltaSteps = [] + g1.fillColor = colors.white + g1.stripeColors = [colors.red, colors.green, colors.blue] + g1.strokeColor = colors.black + g1.strokeWidth = 1 + + self.grid0 = g0 + self.grid1 = g1 + + +## # This gives an AttributeError: +## # DoubleGrid instance has no attribute 'grid0' +## def __setattr__(self, name, value): +## if name in ('x', 'y', 'width', 'height'): +## setattr(self.grid0, name, value) +## setattr(self.grid1, name, value) + + + def demo(self): + D = Drawing(100, 100) + g = DoubleGrid() + D.add(g) + return D + + + def draw(self): + group = Group() + g0, g1 = self.grid0, self.grid1 + # Order groups to make sure both v and h lines + # are visible (works only when there is only + # one kind of stripes, v or h). + G = g0.useRects == 1 and g1.useRects == 0 and (g0,g1) or (g1,g0) + for g in G: + group.add(g.makeOuterRect()) + for g in G: + group.add(g.makeInnerTiles()) + group.add(g.makeInnerLines(),name='_gridLines') + + return group + + +class ShadedRect(Widget): + """This makes a rectangle with shaded colors between two colors. + + Colors are interpolated linearly between 'fillColorStart' + and 'fillColorEnd', both of which appear at the margins. + If 'numShades' is set to one, though, only 'fillColorStart' + is used. + """ + + _attrMap = AttrMap( + x = AttrMapValue(isNumber, desc="The grid's lower-left x position."), + y = AttrMapValue(isNumber, desc="The grid's lower-left y position."), + width = AttrMapValue(isNumber, desc="The grid's width."), + height = AttrMapValue(isNumber, desc="The grid's height."), + orientation = AttrMapValue(OneOf(('vertical', 'horizontal')), desc='Determines if stripes are vertical or horizontal.'), + numShades = AttrMapValue(isNumber, desc='The number of interpolating colors.'), + fillColorStart = AttrMapValue(isColorOrNone, desc='Start value of the color shade.'), + fillColorEnd = AttrMapValue(isColorOrNone, desc='End value of the color shade.'), + strokeColor = AttrMapValue(isColorOrNone, desc='Color used for border line.'), + strokeWidth = AttrMapValue(isNumber, desc='Width used for lines.'), + cylinderMode = AttrMapValue(isBoolean, desc='True if shading reverses in middle.'), + ) + + def __init__(self,**kw): + self.x = 0 + self.y = 0 + self.width = 100 + self.height = 100 + self.orientation = 'vertical' + self.numShades = 20 + self.fillColorStart = colors.pink + self.fillColorEnd = colors.black + self.strokeColor = colors.black + self.strokeWidth = 2 + self.cylinderMode = 0 + self.setProperties(kw) + + def demo(self): + D = Drawing(100, 100) + g = ShadedRect() + D.add(g) + + return D + + def _flipRectCorners(self): + "Flip rectangle's corners if width or height is negative." + x, y, width, height, fillColorStart, fillColorEnd = self.x, self.y, self.width, self.height, self.fillColorStart, self.fillColorEnd + if width < 0 and height > 0: + x = x + width + width = -width + if self.orientation=='vertical': fillColorStart, fillColorEnd = fillColorEnd, fillColorStart + elif height<0 and width>0: + y = y + height + height = -height + if self.orientation=='horizontal': fillColorStart, fillColorEnd = fillColorEnd, fillColorStart + elif height < 0 and height < 0: + x = x + width + width = -width + y = y + height + height = -height + return x, y, width, height, fillColorStart, fillColorEnd + + def draw(self): + # general widget bits + group = Group() + x, y, w, h, c0, c1 = self._flipRectCorners() + vertical = self.orientation == 'vertical' + cylinderMode = self.cylinderMode + linG = getattr(getattr(self,'_canvas',None),'linearGradient',None) + if linG: + canv = linG.__self__ + canv.saveState() + p = canv.beginPath() + p.rect(x, y, w, h) + canv.clipPath(p, stroke=0) + if cylinderMode: + if vertical: + linG(x, y, x+w/2, y, (c0,c1), extend=False) + linG(x+w/2, y, x+w, y, (c1,c0), extend=False) + else: + linG(x, y, x, y+h/2, (c0,c1), extend=False) + linG(x, y+h/2, x, y+h, (c1,c0), extend=False) + else: + if vertical: + linG(x, y, x+w, y, (c0,c1), extend=False) + else: + linG(x, y, x, y+h, (c0,c1), extend=False) + canv.restoreState() + else: + numShades = self.numShades + if cylinderMode: + if not numShades%2: numShades = numShades+1 + halfNumShades = int((numShades-1)/2) + 1 + num = float(numShades) # must make it float! + if vertical: + if numShades == 1: + V = [x] + else: + V = frange(x, x + w, w/num) + else: + if numShades == 1: + V = [y] + else: + V = frange(y, y + h, h/num) + + for v in V: + stripe = vertical and Rect(v, y, w/num, h) or Rect(x, v, w, h/num) + if cylinderMode: + if V.index(v)>=halfNumShades: + col = colors.linearlyInterpolatedColor(c1,c0,V[halfNumShades],V[-1], v) + else: + col = colors.linearlyInterpolatedColor(c0,c1,V[0],V[halfNumShades], v) + else: + col = colors.linearlyInterpolatedColor(c0,c1,V[0],V[-1], v) + stripe.fillColor = col + stripe.strokeColor = col + stripe.strokeWidth = 1 + group.add(stripe) + if self.strokeColor and self.strokeWidth>=0: + rect = Rect(x, y, w, h) + rect.strokeColor = self.strokeColor + rect.strokeWidth = self.strokeWidth + rect.fillColor = None + group.add(rect) + return group + + +def colorRange(c0, c1, n): + "Return a range of intermediate colors between c0 and c1" + if n==1: return [c0] + + C = [] + if n>1: + lim = n-1 + for i in range(n): + C.append(colors.linearlyInterpolatedColor(c0,c1,0,lim, i)) + return C + + +def centroid(P): + '''compute average point of a set of points''' + cx = 0 + cy = 0 + for x,y in P: + cx+=x + cy+=y + n = len(P) + return cx/n, cy/n + +def rotatedEnclosingRect(P, angle, rect): + ''' + given P a sequence P of x,y coordinate pairs and an angle in degrees + find the centroid of P and the axis at angle theta through it + find the extreme points of P wrt axis parallel distance and axis + orthogonal distance. Then compute the least rectangle that will still + enclose P when rotated by angle. Positive angles correspond to clockwise + rotation of the enclosing rect. + ''' + x0, y0 = centroid(P) + theta = radians(angle) + #translate to the centroid and rotate + mx = mmult(translate(x0,y0),rotate(angle)) + + #compute min and max of x and y of the rotated points + tp = flatten(transformPoints(mx,P)) + xx = tp[::2] + yx = tp[1::2] + xn = min(xx) + xx = max(xx) + yn = min(yx) + yx = max(yx) + + #make the enclosing rect and invert the original transform + rect.x = xn + rect.width = xx-xn + rect.y = yn + rect.height = yx-yn + g = Group(transform=inverse(mx)) + g.add(rect) + return g + +class ShadedPolygon(Widget,LineShape): + '''given a list of points [(x0,y0),....] we construct an enclosing + shaded rectangle and mask using the polygon points. + At angle 0 the shading fillColorStart left --> fillColorEnd right. + positive angles rotate the shading clockwise. + ''' + _attrMap = AttrMap(BASE=LineShape, + angle = AttrMapValue(isNumber,desc="Shading angle"), + fillColorStart = AttrMapValue(isColorOrNone), + fillColorEnd = AttrMapValue(isColorOrNone), + numShades = AttrMapValue(isNumber, desc='The number of interpolating colors.'), + cylinderMode = AttrMapValue(isBoolean, desc='True if shading reverses in middle.'), + points = AttrMapValue(isListOfNumbers), + ) + + def __init__(self,**kw): + self.angle = 90 + self.fillColorStart = colors.red + self.fillColorEnd = colors.green + self.cylinderMode = 0 + self.numShades = 50 + self.points = [-1,-1,2,2,3,-1] + LineShape.__init__(self,kw) + + def draw(self): + P = self.points + P = list(zip(P[::2],P[1::2])) + path = definePath([('moveTo',)+P[0]]+[('lineTo',)+x for x in P[1:]]+['closePath'], + fillColor=None, strokeColor=None) + path.isClipPath = 1 + g = Group() + g.add(path) + angle = self.angle % 360 + orientation = 'horizontal' if 0<=angle<=45 or 315<=angle<=360 or 135<=angle<=225 else 'vertical' + rect = ShadedRect(strokeWidth=0,strokeColor=None,orientation=orientation) + for k in 'fillColorStart', 'fillColorEnd', 'numShades', 'cylinderMode': + setattr(rect,k,getattr(self,k)) + g.add(rotatedEnclosingRect(P, angle, rect)) + g.add(EmptyClipPath) + path = path.copy() + path.isClipPath = 0 + path.strokeColor = self.strokeColor + path.strokeWidth = self.strokeWidth + g.add(path) + return g + +if __name__=='__main__': #noruntests + angle=45 + D = Drawing(120,120) + D.add(ShadedPolygon(points=(10,10,60,60,110,10),strokeColor=None,strokeWidth=1,angle=90,numShades=50,cylinderMode=0)) + D.save(formats=['pdf','gif'],fnRoot='shobj',outDir='/tmp') diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/widgets/markers.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/widgets/markers.py new file mode 100644 index 0000000000000000000000000000000000000000..30e47682e295b5f691f0d2ae6f6a1c8514cece35 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/widgets/markers.py @@ -0,0 +1,245 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details + +__version__='3.3.0' +__doc__="""This modules defines a collection of markers used in charts. +""" + +from reportlab.graphics.shapes import Rect, Circle, Polygon, Drawing, Group +from reportlab.graphics.widgets.signsandsymbols import SmileyFace +from reportlab.graphics.widgetbase import Widget +from reportlab.lib.validators import isNumber, isColorOrNone, OneOf, Validator +from reportlab.lib.attrmap import AttrMap, AttrMapValue +from reportlab.lib.colors import black +from reportlab.lib.utils import isClass +from reportlab.graphics.widgets.flags import Flag, _Symbol +from math import sin, cos, pi +_toradians = pi/180.0 + +class Marker(Widget): + '''A polymorphic class of markers''' + _attrMap = AttrMap(BASE=Widget, + kind = AttrMapValue( + OneOf(None, 'Square', 'Diamond', 'Circle', 'Cross', 'Triangle', 'StarSix', + 'Pentagon', 'Hexagon', 'Heptagon', 'Octagon', 'StarFive', + 'FilledSquare', 'FilledCircle', 'FilledDiamond', 'FilledCross', + 'FilledTriangle','FilledStarSix', 'FilledPentagon', 'FilledHexagon', + 'FilledHeptagon', 'FilledOctagon', 'FilledStarFive', + 'Smiley','ArrowHead', 'FilledArrowHead'), + desc='marker type name'), + size = AttrMapValue(isNumber,desc='marker size'), + x = AttrMapValue(isNumber,desc='marker x coordinate'), + y = AttrMapValue(isNumber,desc='marker y coordinate'), + dx = AttrMapValue(isNumber,desc='marker x coordinate adjustment'), + dy = AttrMapValue(isNumber,desc='marker y coordinate adjustment'), + angle = AttrMapValue(isNumber,desc='marker rotation'), + fillColor = AttrMapValue(isColorOrNone, desc='marker fill colour'), + strokeColor = AttrMapValue(isColorOrNone, desc='marker stroke colour'), + strokeWidth = AttrMapValue(isNumber, desc='marker stroke width'), + arrowBarbDx = AttrMapValue(isNumber, desc='arrow only the delta x for the barbs'), + arrowHeight = AttrMapValue(isNumber, desc='arrow only height'), + ) + + def __init__(self,*args,**kw): + self.setProperties(kw) + self._setKeywords( + kind = None, + strokeColor = black, + strokeWidth = 0.1, + fillColor = None, + size = 5, + x = 0, + y = 0, + dx = 0, + dy = 0, + angle = 0, + arrowBarbDx = -1.25, + arrowHeight = 1.875, + ) + + def clone(self,**kwds): + n = self.__class__(**self.__dict__) + if kwds: n.__dict__.update(kwds) + return n + + def _Smiley(self): + x, y = self.x+self.dx, self.y+self.dy + d = self.size/2.0 + s = SmileyFace() + s.fillColor = self.fillColor + s.strokeWidth = self.strokeWidth + s.strokeColor = self.strokeColor + s.x = x-d + s.y = y-d + s.size = d*2 + return s + + def _Square(self): + x, y = self.x+self.dx, self.y+self.dy + d = self.size/2.0 + s = Rect(x-d,y-d,2*d,2*d,fillColor=self.fillColor,strokeColor=self.strokeColor,strokeWidth=self.strokeWidth) + return s + + def _Diamond(self): + d = self.size/2.0 + return self._doPolygon((-d,0,0,d,d,0,0,-d)) + + def _Circle(self): + x, y = self.x+self.dx, self.y+self.dy + s = Circle(x,y,self.size/2.0,fillColor=self.fillColor,strokeColor=self.strokeColor,strokeWidth=self.strokeWidth) + return s + + def _Cross(self): + x, y = self.x+self.dx, self.y+self.dy + s = float(self.size) + h, s = s/2, s/6 + return self._doPolygon((-s,-h,-s,-s,-h,-s,-h,s,-s,s,-s,h,s,h,s,s,h,s,h,-s,s,-s,s,-h)) + + def _Triangle(self): + x, y = self.x+self.dx, self.y+self.dy + r = float(self.size)/2 + c = 30*_toradians + s = sin(30*_toradians)*r + c = cos(c)*r + return self._doPolygon((0,r,-c,-s,c,-s)) + + def _StarSix(self): + r = float(self.size)/2 + c = 30*_toradians + s = sin(c)*r + c = cos(c)*r + z = s/2 + g = c/2 + return self._doPolygon((0,r,-z,s,-c,s,-s,0,-c,-s,-z,-s,0,-r,z,-s,c,-s,s,0,c,s,z,s)) + + def _StarFive(self): + R = float(self.size)/2 + r = R*sin(18*_toradians)/cos(36*_toradians) + P = [] + angle = 90 + for i in range(5): + for radius in R, r: + theta = angle*_toradians + P.append(radius*cos(theta)) + P.append(radius*sin(theta)) + angle = angle + 36 + return self._doPolygon(P) + + def _Pentagon(self): + return self._doNgon(5) + + def _Hexagon(self): + return self._doNgon(6) + + def _Heptagon(self): + return self._doNgon(7) + + def _Octagon(self): + return self._doNgon(8) + + def _ArrowHead(self): + s = self.size + h = self.arrowHeight + b = self.arrowBarbDx + return self._doPolygon((0,0,b,-h,s,0,b,h)) + + def _doPolygon(self,P): + x, y = self.x+self.dx, self.y+self.dy + if x or y: P = list(map(lambda i,P=P,A=[x,y]: P[i] + A[i&1], list(range(len(P))))) + return Polygon(P, strokeWidth =self.strokeWidth, strokeColor=self.strokeColor, fillColor=self.fillColor) + + def _doFill(self): + old = self.fillColor + if old is None: + self.fillColor = self.strokeColor + r = (self.kind and getattr(self,'_'+self.kind[6:]) or Group)() + self.fillColor = old + return r + + def _doNgon(self,n): + P = [] + size = float(self.size)/2 + for i in range(n): + r = (2.*i/n+0.5)*pi + P.append(size*cos(r)) + P.append(size*sin(r)) + return self._doPolygon(P) + + _FilledCircle = _doFill + _FilledSquare = _doFill + _FilledDiamond = _doFill + _FilledCross = _doFill + _FilledTriangle = _doFill + _FilledStarSix = _doFill + _FilledPentagon = _doFill + _FilledHexagon = _doFill + _FilledHeptagon = _doFill + _FilledOctagon = _doFill + _FilledStarFive = _doFill + _FilledArrowHead = _doFill + + def draw(self): + if self.kind: + m = getattr(self,'_'+self.kind) + if self.angle: + _x, _dx, _y, _dy = self.x, self.dx, self.y, self.dy + self.x, self.dx, self.y, self.dy = 0,0,0,0 + try: + m = m() + finally: + self.x, self.dx, self.y, self.dy = _x, _dx, _y, _dy + if not isinstance(m,Group): + _m, m = m, Group() + m.add(_m) + if self.angle: m.rotate(self.angle) + x, y = _x+_dx, _y+_dy + if x or y: m.shift(x,y) + else: + m = m() + else: + m = Group() + return m + +def uSymbol2Symbol(uSymbol,x,y,color): + if isClass(uSymbol) and issubclass(uSymbol,Widget): + size = 10. + symbol = uSymbol() + symbol.x = x - (size/2) + symbol.y = y - (size/2) + try: + symbol.size = size + symbol.color = color + except: + pass + elif isinstance(uSymbol,Marker) or isinstance(uSymbol,_Symbol): + symbol = uSymbol.clone() + if isinstance(uSymbol,Marker): symbol.fillColor = symbol.fillColor or color + symbol.x, symbol.y = x, y + elif callable(uSymbol): + symbol = uSymbol(x, y, 5, color) + else: + symbol = None + return symbol + +class _isSymbol(Validator): + def test(self,x): + return hasattr(x,'__call__') or isinstance(x,Marker) or isinstance(x,_Symbol) or (isClass(x) and issubclass(x,Widget)) + +isSymbol = _isSymbol() + +def makeMarker(name,**kw): + if Marker._attrMap['kind'].validate(name): + m = Marker(**kw) + m.kind = name + elif name[-5:]=='_Flag' and Flag._attrMap['kind'].validate(name[:-5]): + m = Flag(**kw) + m.kind = name[:-5] + m.size = 10 + else: + raise ValueError("Invalid marker name %s" % name) + return m + +if __name__=='__main__': + D = Drawing() + D.add(Marker()) + D.save(fnRoot='Marker',formats=['pdf'], outDir='/tmp') diff --git a/.venv/lib/python3.13/site-packages/reportlab/graphics/widgets/signsandsymbols.py b/.venv/lib/python3.13/site-packages/reportlab/graphics/widgets/signsandsymbols.py new file mode 100644 index 0000000000000000000000000000000000000000..8b75b5bb61b146edd1596a5da3303750fed0606d --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/graphics/widgets/signsandsymbols.py @@ -0,0 +1,977 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/graphics/widgets/signsandsymbols.py +# signsandsymbols.py +# A collection of new widgets +# author: John Precedo (johnp@reportlab.com) + +__version__='3.3.0' +__doc__="""This file is a collection of widgets to produce some common signs and symbols. + +Widgets include: + +- ETriangle (an equilateral triangle), +- RTriangle (a right angled triangle), +- Octagon, +- Crossbox, +- Tickbox, +- SmileyFace, +- StopSign, +- NoEntry, +- NotAllowed (the red roundel from 'no smoking' signs), +- NoSmoking, +- DangerSign (a black exclamation point in a yellow triangle), +- YesNo (returns a tickbox or a crossbox depending on a testvalue), +- FloppyDisk, +- ArrowOne, and +- ArrowTwo +- CrossHair +""" + +from reportlab.lib import colors +from reportlab.lib.validators import * +from reportlab.lib.attrmap import * +from reportlab.lib.utils import isStr, asUnicode +from reportlab.graphics import shapes +from reportlab.graphics.widgetbase import Widget +from reportlab.graphics import renderPDF + + +class _Symbol(Widget): + """Abstract base widget + possible attributes: + 'x', 'y', 'size', 'fillColor', 'strokeColor' + """ + _nodoc = 1 + _attrMap = AttrMap( + x = AttrMapValue(isNumber,desc='symbol x coordinate'), + y = AttrMapValue(isNumber,desc='symbol y coordinate'), + dx = AttrMapValue(isNumber,desc='symbol x coordinate adjustment'), + dy = AttrMapValue(isNumber,desc='symbol x coordinate adjustment'), + size = AttrMapValue(isNumber), + fillColor = AttrMapValue(isColorOrNone), + strokeColor = AttrMapValue(isColorOrNone), + strokeWidth = AttrMapValue(isNumber), + ) + def __init__(self): + assert self.__class__.__name__!='_Symbol', 'Abstract class _Symbol instantiated' + self.x = self.y = self.dx = self.dy = 0 + self.size = 100 + self.fillColor = colors.red + self.strokeColor = None + self.strokeWidth = 0.1 + + def demo(self): + D = shapes.Drawing(200, 100) + s = float(self.size) + ob = self.__class__() + ob.x=50 + ob.y=0 + ob.draw() + D.add(ob) + D.add(shapes.String(ob.x+(s/2),(ob.y-12), + ob.__class__.__name__, fillColor=colors.black, textAnchor='middle', + fontSize=10)) + return D + +class ETriangle(_Symbol): + """This draws an equilateral triangle.""" + + def __init__(self): + _Symbol.__init__(self) + + def draw(self): + # general widget bits + s = float(self.size) # abbreviate as we will use this a lot + g = shapes.Group() + + # Triangle specific bits + ae = s*0.125 #(ae = 'an eighth') + triangle = shapes.Polygon(points = [ + self.x, self.y, + self.x+s, self.y, + self.x+(s/2),self.y+s], + fillColor = self.fillColor, + strokeColor = self.strokeColor, + strokeWidth=s/50.) + g.add(triangle) + return g + +class RTriangle(_Symbol): + """This draws a right-angled triangle. + + possible attributes: + 'x', 'y', 'size', 'fillColor', 'strokeColor' + + """ + + def __init__(self): + self.x = 0 + self.y = 0 + self.size = 100 + self.fillColor = colors.green + self.strokeColor = None + + def draw(self): + # general widget bits + s = float(self.size) # abbreviate as we will use this a lot + g = shapes.Group() + + # Triangle specific bits + ae = s*0.125 #(ae = 'an eighth') + triangle = shapes.Polygon(points = [ + self.x, self.y, + self.x+s, self.y, + self.x,self.y+s], + fillColor = self.fillColor, + strokeColor = self.strokeColor, + strokeWidth=s/50.) + g.add(triangle) + return g + +class Octagon(_Symbol): + """This widget draws an Octagon. + + possible attributes: + 'x', 'y', 'size', 'fillColor', 'strokeColor' + + """ + + def __init__(self): + self.x = 0 + self.y = 0 + self.size = 100 + self.fillColor = colors.yellow + self.strokeColor = None + + def draw(self): + # general widget bits + s = float(self.size) # abbreviate as we will use this a lot + g = shapes.Group() + + # Octagon specific bits + athird=s/3 + + octagon = shapes.Polygon(points=[self.x+athird, self.y, + self.x, self.y+athird, + self.x, self.y+(athird*2), + self.x+athird, self.y+s, + self.x+(athird*2), self.y+s, + self.x+s, self.y+(athird*2), + self.x+s, self.y+athird, + self.x+(athird*2), self.y], + strokeColor = self.strokeColor, + fillColor = self.fillColor, + strokeWidth=10) + g.add(octagon) + return g + +class Crossbox(_Symbol): + """This draws a black box with a red cross in it - a 'checkbox'. + + possible attributes: + 'x', 'y', 'size', 'crossColor', 'strokeColor', 'crosswidth' + + """ + + _attrMap = AttrMap(BASE=_Symbol, + crossColor = AttrMapValue(isColorOrNone), + crosswidth = AttrMapValue(isNumber), + ) + + def __init__(self): + self.x = 0 + self.y = 0 + self.size = 100 + self.fillColor = colors.white + self.crossColor = colors.red + self.strokeColor = colors.black + self.crosswidth = 10 + + def draw(self): + # general widget bits + s = float(self.size) # abbreviate as we will use this a lot + g = shapes.Group() + + # crossbox specific bits + box = shapes.Rect(self.x+1, self.y+1, s-2, s-2, + fillColor = self.fillColor, + strokeColor = self.strokeColor, + strokeWidth=2) + g.add(box) + + crossLine1 = shapes.Line(self.x+(s*0.15), self.y+(s*0.15), self.x+(s*0.85), self.y+(s*0.85), + fillColor = self.crossColor, + strokeColor = self.crossColor, + strokeWidth = self.crosswidth) + g.add(crossLine1) + + crossLine2 = shapes.Line(self.x+(s*0.15), self.y+(s*0.85), self.x+(s*0.85) ,self.y+(s*0.15), + fillColor = self.crossColor, + strokeColor = self.crossColor, + strokeWidth = self.crosswidth) + g.add(crossLine2) + + return g + + +class Tickbox(_Symbol): + """This draws a black box with a red tick in it - another 'checkbox'. + + possible attributes: + 'x', 'y', 'size', 'tickColor', 'strokeColor', 'tickwidth' + +""" + + _attrMap = AttrMap(BASE=_Symbol, + tickColor = AttrMapValue(isColorOrNone), + tickwidth = AttrMapValue(isNumber), + ) + + def __init__(self): + self.x = 0 + self.y = 0 + self.size = 100 + self.tickColor = colors.red + self.strokeColor = colors.black + self.fillColor = colors.white + self.tickwidth = 10 + + def draw(self): + # general widget bits + s = float(self.size) # abbreviate as we will use this a lot + g = shapes.Group() + + # tickbox specific bits + box = shapes.Rect(self.x+1, self.y+1, s-2, s-2, + fillColor = self.fillColor, + strokeColor = self.strokeColor, + strokeWidth=2) + g.add(box) + + tickLine = shapes.PolyLine(points = [self.x+(s*0.15), self.y+(s*0.35), self.x+(s*0.35), self.y+(s*0.15), + self.x+(s*0.35), self.y+(s*0.15), self.x+(s*0.85) ,self.y+(s*0.85)], + fillColor = self.tickColor, + strokeColor = self.tickColor, + strokeWidth = self.tickwidth) + g.add(tickLine) + + return g + +class SmileyFace(_Symbol): + """This draws a classic smiley face. + + possible attributes: + 'x', 'y', 'size', 'fillColor' + + """ + + def __init__(self): + _Symbol.__init__(self) + self.x = 0 + self.y = 0 + self.size = 100 + self.fillColor = colors.yellow + self.strokeColor = colors.black + + def draw(self): + # general widget bits + s = float(self.size) # abbreviate as we will use this a lot + g = shapes.Group() + + # SmileyFace specific bits + g.add(shapes.Circle(cx=self.x+(s/2), cy=self.y+(s/2), r=s/2, + fillColor=self.fillColor, strokeColor=self.strokeColor, + strokeWidth=max(s/38.,self.strokeWidth))) + + for i in (1,2): + g.add(shapes.Ellipse(self.x+(s/3)*i,self.y+(s/3)*2, s/30, s/10, + fillColor=self.strokeColor, strokeColor = self.strokeColor, + strokeWidth=max(s/38.,self.strokeWidth))) + + # calculate a pointslist for the mouth + # THIS IS A HACK! - don't use if there is a 'shapes.Arc' + centerx=self.x+(s/2) + centery=self.y+(s/2) + radius=s/3 + yradius = radius + xradius = radius + startangledegrees=200 + endangledegrees=340 + degreedelta = 1 + pointslist = [] + a = pointslist.append + from math import sin, cos, pi + degreestoradians = pi/180.0 + radiansdelta = degreedelta*degreestoradians + startangle = startangledegrees*degreestoradians + endangle = endangledegrees*degreestoradians + while endangle= searchto: + break # EXIT LOOP + match = m.group(0) + end = start + len(match) + c = match[0] + if c not in "#'\"": + # Must have matched a keyword. + if start != searchfrom: + # there's still a redundant char before and after it, strip! + match = match[1:-1] + start = start + 1 + else: + # this is the first keyword in the text. + # Only a space at the end. + match = match[:-1] + end = end - 1 + tags_append((keywordTag, start, end, None)) + # If this was a defining keyword, look ahead to the + # following identifier. + if match in ["def", "class"]: + m = idSearch(pytext, end) + if m is not None: + start = m.start() + if start == end: + match = m.group(0) + end = start + len(match) + tags_append((identifierTag, start, end, None)) + elif c == "#": + tags_append((commentTag, start, end, None)) + else: + tags_append((stringTag, start, end, None)) + return tags + + +def test(path): + f = open(path) + text = f.read() + f.close() + tags = fontify(text) + for tag, start, end, sublist in tags: + print(tag, repr(text[start:end])) diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/__init__.py b/.venv/lib/python3.13/site-packages/reportlab/lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1f1353555a65ec0bd14b504272f5c90f5243b3d7 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/__init__.py @@ -0,0 +1,7 @@ +#!/bin/env python +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/__init__.py +__version__='3.3.0' +import os +RL_DEBUG = 'RL_DEBUG' in os.environ diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/abag.py b/.venv/lib/python3.13/site-packages/reportlab/lib/abag.py new file mode 100644 index 0000000000000000000000000000000000000000..456af1b0858b11e71465ff6f9ff6d9ec29ca43f4 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/abag.py @@ -0,0 +1,36 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/abag.py +__version__='3.3.0' +__doc__='''Data structure to hold a collection of attributes, used by styles.''' +class ABag: + """ + 'Attribute Bag' - a trivial BAG class for holding attributes. + + This predates modern Python. Doing this again, we'd use a subclass + of dict. + + You may initialize with keyword arguments. + a = ABag(k0=v0,....,kx=vx,....) ==> getattr(a,'kx')==vx + + c = a.clone(ak0=av0,.....) copy with optional additional attributes. + """ + def __init__(self,**attr): + self.__dict__.update(attr) + + def clone(self,**attr): + n = self.__class__(**self.__dict__) + if attr: n.__dict__.update(attr) + return n + + def __repr__(self): + D = self.__dict__ + K = list(D.keys()) + K.sort() + return '%s(%s)' % (self.__class__.__name__,', '.join(['%s=%r' % (k,D[k]) for k in K])) + +if __name__=="__main__": + AB = ABag(a=1, c="hello") + CD = AB.clone() + print(AB) + print(CD) diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/arciv.py b/.venv/lib/python3.13/site-packages/reportlab/lib/arciv.py new file mode 100644 index 0000000000000000000000000000000000000000..e66755427a63ef26ade0574f9818c70778e06fe8 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/arciv.py @@ -0,0 +1,214 @@ +#copyright ReportLab Europe Limited. 2000-2016 +#see license.txt for license details +''' +Arciv Stream ciphering +''' +__all__='''ArcIV encode decode'''.split() +__version__="1.0" +from reportlab.lib.utils import isUnicode +class ArcIV: + ''' + performs 'ArcIV' Stream Encryption of S using key + Based on what is widely thought to be RSA's ArcIV algorithm. + It produces output streams that are identical. + + NB there is no separate decoder arciv(arciv(s,key),key) == s + ''' + def __init__(self,key): + self._key = key + self.reset() + + def reset(self): + '''restore the cipher to it's start state''' + #Initialize private key, k With the values of the key mod 256. + #and sbox With numbers 0 - 255. Then compute sbox + key = self._key + if isUnicode(key): key = key.encode('utf8') + sbox = list(range(256)) + k = list(range(256)) + lk = len(key) + for i in sbox: + k[i] = key[i % lk] % 256 + + #Re-order sbox using the private key, k. + #Iterating each element of sbox re-calculate the counter j + #Then interchange the elements sbox[a] & sbox[b] + j = 0 + for i in range(256): + j = (j+sbox[i]+k[i]) % 256 + sbox[i], sbox[j] = sbox[j], sbox[i] + self._sbox, self._i, self._j = sbox, 0, 0 + + def _encode(self, B): + ''' + return the list of encoded bytes of B, B might be a string or a + list of integers between 0 <= i <= 255 + ''' + sbox, i, j = self._sbox, self._i, self._j + + C = list(B.encode('utf8')) if isinstance(B,str) else (list(B) if isinstance(B,bytes) else B[:]) + n = len(C) + p = 0 + while p -1: + # it is an EUC family encoding. + for col in range(1, 95): + ch = int2Byte(row + 160) + int2Byte(col+160) + cells.append(ch) +## elif self.encodingName.find('GB') > -1: +## # it is an EUC family encoding. +## for col in range(1, 95): +## ch = int2Byte(row + 160) + int2Byte(col+160) + else: + cells.append([None] * 94) + return cells + + def draw(self): + self.drawLabels(topLeft= 'R%d' % self.row) + + # work out which characters we need for the row + #assert self.encodingName.find('EUC') > -1, 'Only handles EUC encoding today, you gave me %s!' % self.encodingName + + # pad out by 1 to match Ken Lunde's tables + charList = [None] + self.makeRow(self.row) + self.drawChars(charList) + self.canv.grid(self.xlist, self.ylist) + + +class Big5CodeChart(CodeChartBase): + """Formats one 'row' of the 94x160 space used in Big 5 + + These deliberately resemble the code charts in Ken Lunde's "Understanding + CJKV Information Processing", to enable manual checking.""" + def __init__(self, row, faceName, encodingName): + self.row = row + self.codePoints = 160 + self.boxSize = 18 + self.charsPerRow = 16 + self.rows = 10 + self.hex = 1 + self.faceName = faceName + self.encodingName = encodingName + self.rowLabels = ['4','5','6','7','A','B','C','D','E','F'] + try: + # the dependent files might not be available + font = cidfonts.CIDFont(self.faceName, self.encodingName) + pdfmetrics.registerFont(font) + except: + # fall back to English and at least show we can draw the boxes + self.faceName = 'Helvetica' + self.encodingName = 'WinAnsiEncoding' + self.fontName = self.faceName + '-' + self.encodingName + self.calcLayout() + + def makeRow(self, row): + """Works out the character values for this Big5 row. + Rows start at 0xA1""" + cells = [] + if self.encodingName.find('B5') > -1: + # big 5, different row size + for y in [4,5,6,7,10,11,12,13,14,15]: + for x in range(16): + col = y*16+x + ch = int2Byte(row) + int2Byte(col) + cells.append(ch) + + else: + cells.append([None] * 160) + return cells + + def draw(self): + self.drawLabels(topLeft='%02X' % self.row) + + charList = self.makeRow(self.row) + self.drawChars(charList) + self.canv.grid(self.xlist, self.ylist) + + +def hBoxText(msg, canvas, x, y, fontName): + """Helper for stringwidth tests on Asian fonts. + + Registers font if needed. Then draws the string, + and a box around it derived from the stringWidth function""" + canvas.saveState() + try: + font = pdfmetrics.getFont(fontName) + except KeyError: + font = cidfonts.UnicodeCIDFont(fontName) + pdfmetrics.registerFont(font) + + canvas.setFillGray(0.8) + canvas.rect(x,y,pdfmetrics.stringWidth(msg, fontName, 16),16,stroke=0,fill=1) + canvas.setFillGray(0) + canvas.setFont(fontName, 16,16) + canvas.drawString(x,y,msg) + canvas.restoreState() + + +class CodeWidget(Widget): + """Block showing all the characters""" + def __init__(self): + self.x = 0 + self.y = 0 + self.width = 160 + self.height = 160 + + def draw(self): + dx = self.width / 16.0 + dy = self.height / 16.0 + g = Group() + g.add(Rect(self.x, self.y, self.width, self.height, + fillColor=None, strokeColor=colors.black)) + for x in range(16): + for y in range(16): + charValue = y * 16 + x + if charValue > 32: + s = String(self.x + x * dx, + self.y + (self.height - y*dy), int2Byte(charValue)) + g.add(s) + return g + + + + + + +def test(): + c = Canvas('codecharts.pdf') + c.setFont('Helvetica-Bold', 24) + c.drawString(72, 750, 'Testing code page charts') + cc1 = SingleByteEncodingChart() + cc1.drawOn(c, 72, 500) + + cc2 = SingleByteEncodingChart(charsPerRow=32) + cc2.drawOn(c, 72, 300) + + cc3 = SingleByteEncodingChart(charsPerRow=25, hex=0) + cc3.drawOn(c, 72, 100) + +## c.showPage() +## +## c.setFont('Helvetica-Bold', 24) +## c.drawString(72, 750, 'Multi-byte Kuten code chart examples') +## KutenRowCodeChart(1, 'HeiseiMin-W3','EUC-H').drawOn(c, 72, 600) +## KutenRowCodeChart(16, 'HeiseiMin-W3','EUC-H').drawOn(c, 72, 450) +## KutenRowCodeChart(84, 'HeiseiMin-W3','EUC-H').drawOn(c, 72, 300) +## +## c.showPage() +## c.setFont('Helvetica-Bold', 24) +## c.drawString(72, 750, 'Big5 Code Chart Examples') +## #Big5CodeChart(0xA1, 'MSungStd-Light-Acro','ETenms-B5-H').drawOn(c, 72, 500) + + c.save() + print('saved codecharts.pdf') + +if __name__=='__main__': + test() diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/colors.py b/.venv/lib/python3.13/site-packages/reportlab/lib/colors.py new file mode 100644 index 0000000000000000000000000000000000000000..28c4eb9b2c1f4af920b8573b7e6d203edbaf8fd5 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/colors.py @@ -0,0 +1,1147 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/colors.py +__version__='3.3.0' +__doc__='''Defines standard colour-handling classes and colour names. + +We define standard classes to hold colours in two models: RGB and CMYK. +rhese can be constructed from several popular formats. We also include + +- pre-built colour objects for the HTML standard colours + +- pre-built colours used in ReportLab's branding + +- various conversion and construction functions + +These tests are here because doctest cannot find them otherwise. +>>> toColor('rgb(128,0,0)')==toColor('rgb(50%,0%,0%)') +True +>>> toColor('rgb(50%,0%,0%)')!=Color(0.5,0,0,1) +True +>>> toColor('hsl(0,100%,50%)')==toColor('rgb(255,0,0)') +True +>>> toColor('hsl(-120,100%,50%)')==toColor('rgb(0,0,255)') +True +>>> toColor('hsl(120,100%,50%)')==toColor('rgb(0,255,0)') +True +>>> toColor('rgba( 255,0,0,0.5)')==Color(1,0,0,0.5) +True +>>> toColor('cmyk(1,0,0,0 )')==CMYKColor(1,0,0,0) +True +>>> toColor('pcmyk( 100 , 0 , 0 , 0 )')==PCMYKColor(100,0,0,0) +True +>>> toColor('cmyka(1,0,0,0,0.5)')==CMYKColor(1,0,0,0,alpha=0.5) +True +>>> toColor('pcmyka(100,0,0,0,0.5)')==PCMYKColor(100,0,0,0,alpha=0.5) +True +>>> toColor('pcmyka(100,0,0,0)') +Traceback (most recent call last): + .... +ValueError: css color 'pcmyka(100,0,0,0)' has wrong number of components +''' +import math, re, functools +from reportlab.lib.rl_accel import fp_str +from reportlab.lib.utils import asNative, isStr, rl_safe_eval, rl_extended_literal_eval +from reportlab import rl_config +from ast import literal_eval + +class Color: + """This class is used to represent color. Components red, green, blue + are in the range 0 (dark) to 1 (full intensity).""" + + def __init__(self, red=0, green=0, blue=0, alpha=1): + "Initialize with red, green, blue in range [0-1]." + self.red = red + self.green = green + self.blue = blue + self.alpha = alpha + + def __repr__(self): + return "Color(%s)" % fp_str(*(self.red, self.green, self.blue,self.alpha)).replace(' ',',') + + @property + def __key__(self): + '''simple comparison by component; cmyk != color ever + >>> from reportlab import cmp + >>> cmp(Color(0,0,0),None) + -1 + >>> cmp(Color(0,0,0),black) + 0 + >>> cmp(Color(0,0,0),CMYKColor(0,0,0,1)),Color(0,0,0).rgba()==CMYKColor(0,0,0,1).rgba() + (1, True) + ''' + return self.red, self.green, self.blue, self.alpha + + def __hash__(self): + return hash(self.__key__) + + def __comparable__(self,other): + return not isinstance(other,CMYKColor) and isinstance(other,Color) + + def __lt__(self,other): + if not self.__comparable__(other): return True + try: + return self.__key__ < other.__key__ + except: + pass + return True + + def __eq__(self,other): + if not self.__comparable__(other): return False + try: + return self.__key__ == other.__key__ + except: + return False + + def rgb(self): + "Returns a three-tuple of components" + return (self.red, self.green, self.blue) + + def rgba(self): + "Returns a four-tuple of components" + return (self.red, self.green, self.blue, self.alpha) + + def bitmap_rgb(self): + return tuple([int(x*255)&255 for x in self.rgb()]) + + def bitmap_rgba(self): + return tuple([int(x*255)&255 for x in self.rgba()]) + + def hexval(self): + return '0x%02x%02x%02x' % self.bitmap_rgb() + + def hexvala(self): + return '0x%02x%02x%02x%02x' % self.bitmap_rgba() + + def int_rgb(self): + v = self.bitmap_rgb() + return v[0]<<16|v[1]<<8|v[2] + + def int_rgba(self): + v = self.bitmap_rgba() + return int(v[0]<<24|v[1]<<16|v[2]<<8|v[3]) + + def int_argb(self): + v = self.bitmap_rgba() + return int(v[3]<<24|v[0]<<16|v[1]<<8|v[2]) + + _cKwds='red green blue alpha'.split() + def cKwds(self): + for k in self._cKwds: + yield k,getattr(self,k) + cKwds=property(cKwds) + + def clone(self,**kwds): + '''copy then change values in kwds''' + D = dict([kv for kv in self.cKwds]) + D.update(kwds) + return self.__class__(**D) + + def _lookupName(self,D={}): + if not D: + for n,v in getAllNamedColors().items(): + if not isinstance(v,CMYKColor): + t = v.red,v.green,v.blue + if t in D: + n = n+'/'+D[t] + D[t] = n + t = self.red,self.green,self.blue + return t in D and D[t] or None + + @property + def normalizedAlpha(self): + return self.alpha +Color = functools.total_ordering(Color) + +def opaqueColor(c): + '''utility to check we have a color that's not fully transparent''' + return isinstance(c,Color) and c.alpha>0 + +class CMYKColor(Color): + """This represents colors using the CMYK (cyan, magenta, yellow, black) + model commonly used in professional printing. This is implemented + as a derived class so that renderers which only know about RGB "see it" + as an RGB color through its 'red','green' and 'blue' attributes, according + to an approximate function. + + The RGB approximation is worked out when the object in constructed, so + the color attributes should not be changed afterwards. + + Extra attributes may be attached to the class to support specific ink models, + and renderers may look for these.""" + + _scale = 1.0 + def __init__(self, cyan=0, magenta=0, yellow=0, black=0, + spotName=None, density=1, knockout=None, alpha=1): + """ + Initialize with four colors in range [0-1]. the optional + spotName, density & knockout may be of use to specific renderers. + spotName is intended for use as an identifier to the renderer not client programs. + density is used to modify the overall amount of ink. + knockout is a renderer dependent option that determines whether the applied colour + knocksout (removes) existing colour; None means use the global default. + """ + self.cyan = cyan + self.magenta = magenta + self.yellow = yellow + self.black = black + self.spotName = spotName + self.density = max(min(density,1),0) # force into right range + self.knockout = knockout + self.alpha = alpha + + # now work out the RGB approximation. override + self.red, self.green, self.blue = cmyk2rgb( (cyan, magenta, yellow, black) ) + + if density<1: + #density adjustment of rgb approximants, effectively mix with white + r, g, b = self.red, self.green, self.blue + r = density*(r-1)+1 + g = density*(g-1)+1 + b = density*(b-1)+1 + self.red, self.green, self.blue = (r,g,b) + + def __repr__(self): + return "%s(%s%s%s%s%s)" % (self.__class__.__name__, + fp_str(self.cyan, self.magenta, self.yellow, self.black).replace(' ',','), + (self.spotName and (',spotName='+repr(self.spotName)) or ''), + (self.density!=1 and (',density='+fp_str(self.density)) or ''), + (self.knockout is not None and (',knockout=%d' % self.knockout) or ''), + (self.alpha is not None and (',alpha=%s' % self.alpha) or ''), + ) + + def fader(self, n, reverse=False): + '''return n colors based on density fade + *NB* note this dosen't reach density zero''' + scale = self._scale + dd = scale/float(n) + L = [self.clone(density=scale - i*dd) for i in range(n)] + if reverse: L.reverse() + return L + + @property + def __key__(self): + """obvious way to compare colours + Comparing across the two color models is of limited use. + >>> cmp(CMYKColor(0,0,0,1),None) + -1 + >>> cmp(CMYKColor(0,0,0,1),_CMYK_black) + 0 + >>> cmp(PCMYKColor(0,0,0,100),_CMYK_black) + 0 + >>> cmp(CMYKColor(0,0,0,1),Color(0,0,1)),Color(0,0,0).rgba()==CMYKColor(0,0,0,1).rgba() + (-1, True) + """ + return self.cyan, self.magenta, self.yellow, self.black, self.density, self.spotName, self.alpha + + def __comparable__(self,other): + return isinstance(other,CMYKColor) + + def cmyk(self): + "Returns a tuple of four color components - syntactic sugar" + return (self.cyan, self.magenta, self.yellow, self.black) + + def cmyka(self): + "Returns a tuple of five color components - syntactic sugar" + return (self.cyan, self.magenta, self.yellow, self.black, self.alpha) + + def _density_str(self): + return fp_str(self.density) + _cKwds='cyan magenta yellow black density alpha spotName knockout'.split() + + def _lookupName(self,D={}): + if not D: + for n,v in getAllNamedColors().items(): + if isinstance(v,CMYKColor): + t = v.cyan,v.magenta,v.yellow,v.black + if t in D: + n = n+'/'+D[t] + D[t] = n + t = self.cyan,self.magenta,self.yellow,self.black + return t in D and D[t] or None + + @property + def normalizedAlpha(self): + return self.alpha*self._scale + +class PCMYKColor(CMYKColor): + '''100 based CMYKColor with density and a spotName; just like Rimas uses''' + _scale = 100. + def __init__(self,cyan,magenta,yellow,black,density=100,spotName=None,knockout=None,alpha=100): + CMYKColor.__init__(self,cyan/100.,magenta/100.,yellow/100.,black/100.,spotName,density/100.,knockout=knockout,alpha=alpha/100.) + + def __repr__(self): + return "%s(%s%s%s%s%s)" % (self.__class__.__name__, + fp_str(self.cyan*100, self.magenta*100, self.yellow*100, self.black*100).replace(' ',','), + (self.spotName and (',spotName='+repr(self.spotName)) or ''), + (self.density!=1 and (',density='+fp_str(self.density*100)) or ''), + (self.knockout is not None and (',knockout=%d' % self.knockout) or ''), + (self.alpha is not None and (',alpha=%s' % (fp_str(self.alpha*100))) or ''), + ) + + def cKwds(self): + K=self._cKwds + S=K[:6] + for k in self._cKwds: + v=getattr(self,k) + if k in S: v*=100 + yield k,v + cKwds=property(cKwds) + +class CMYKColorSep(CMYKColor): + '''special case color for making separating pdfs''' + _scale = 1. + def __init__(self, cyan=0, magenta=0, yellow=0, black=0, + spotName=None, density=1,alpha=1): + CMYKColor.__init__(self,cyan,magenta,yellow,black,spotName,density,knockout=None,alpha=alpha) + _cKwds='cyan magenta yellow black density alpha spotName'.split() + +class PCMYKColorSep(PCMYKColor,CMYKColorSep): + '''special case color for making separating pdfs''' + _scale = 100. + def __init__(self, cyan=0, magenta=0, yellow=0, black=0, + spotName=None, density=100, alpha=100): + PCMYKColor.__init__(self,cyan,magenta,yellow,black,density,spotName,knockout=None,alpha=alpha) + _cKwds='cyan magenta yellow black density alpha spotName'.split() + +def cmyk2rgb(cmyk,density=1): + "Convert from a CMYK color tuple to an RGB color tuple" + c,m,y,k = cmyk + # From the Adobe Postscript Ref. Manual 2nd ed. + r = 1.0 - min(1.0, c + k) + g = 1.0 - min(1.0, m + k) + b = 1.0 - min(1.0, y + k) + return (r,g,b) + +def rgb2cmyk(r,g,b): + '''one way to get cmyk from rgb''' + c = 1 - r + m = 1 - g + y = 1 - b + k = min(c,m,y) + c = min(1,max(0,c-k)) + m = min(1,max(0,m-k)) + y = min(1,max(0,y-k)) + k = min(1,max(0,k)) + return (c,m,y,k) + +def color2bw(colorRGB): + "Transform an RGB color to a black and white equivalent." + + col = colorRGB + r, g, b, a = col.red, col.green, col.blue, col.alpha + n = (r + g + b) / 3.0 + bwColorRGB = Color(n, n, n, a) + return bwColorRGB + +def HexColor(val, htmlOnly=False, hasAlpha=False): + """This function converts a hex string, or an actual integer number, + into the corresponding color. E.g., in "#AABBCC" or 0xAABBCC, + AA is the red, BB is the green, and CC is the blue (00-FF). + + An alpha value can also be given in the form #AABBCCDD or 0xAABBCCDD where + DD is the alpha value if hasAlpha is True. + + For completeness I assume that #aabbcc or 0xaabbcc are hex numbers + otherwise a pure integer is converted as decimal rgb. If htmlOnly is true, + only the #aabbcc form is allowed. + + >>> HexColor('#ffffff') + Color(1,1,1,1) + >>> HexColor('#FFFFFF') + Color(1,1,1,1) + >>> HexColor('0xffffff') + Color(1,1,1,1) + >>> HexColor('16777215') + Color(1,1,1,1) + + An '0x' or '#' prefix is required for hex (as opposed to decimal): + + >>> HexColor('ffffff') + Traceback (most recent call last): + ValueError: invalid literal for int() with base 10: 'ffffff' + + >>> HexColor('#FFFFFF', htmlOnly=True) + Color(1,1,1,1) + >>> HexColor('0xffffff', htmlOnly=True) + Traceback (most recent call last): + ValueError: not a hex string + >>> HexColor('16777215', htmlOnly=True) + Traceback (most recent call last): + ValueError: not a hex string + + """ #" for emacs + + if isStr(val): + val = asNative(val) + b = 10 + if val[:1] == '#': + val = val[1:] + b = 16 + if len(val) == 8: + alpha = True + else: + if htmlOnly: + raise ValueError('not a hex string') + if val[:2].lower() == '0x': + b = 16 + val = val[2:] + if len(val) == 8: + alpha = True + val = int(val,b) + if hasAlpha: + return Color(((val>>24)&0xFF)/255.0,((val>>16)&0xFF)/255.0,((val>>8)&0xFF)/255.0,(val&0xFF)/255.0) + return Color(((val>>16)&0xFF)/255.0,((val>>8)&0xFF)/255.0,(val&0xFF)/255.0) + +def linearlyInterpolatedColor(c0, c1, x0, x1, x): + """ + Linearly interpolates colors. Can handle RGB, CMYK and PCMYK + colors - give ValueError if colours aren't the same. + Doesn't currently handle 'Spot Color Interpolation'. + """ + + if c0.__class__ != c1.__class__: + raise ValueError("Color classes must be the same for interpolation!\nGot %r and %r'"%(c0,c1)) + if x1x0 + if xx1+1e-8: # fudge factor for numerical problems + raise ValueError("Can't interpolate: x=%f is not between %f and %f!" % (x,x0,x1)) + if x<=x0: + return c0 + elif x>=x1: + return c1 + + cname = c0.__class__.__name__ + dx = float(x1-x0) + x = x-x0 + + if cname == 'Color': # RGB + r = c0.red+x*(c1.red - c0.red)/dx + g = c0.green+x*(c1.green- c0.green)/dx + b = c0.blue+x*(c1.blue - c0.blue)/dx + a = c0.alpha+x*(c1.alpha - c0.alpha)/dx + return Color(r,g,b,alpha=a) + elif cname == 'CMYKColor': + if cmykDistance(c0,c1)<1e-8: + #colors same do density and preserve spotName if any + assert c0.spotName == c1.spotName, "Identical cmyk, but different spotName" + c = c0.cyan + m = c0.magenta + y = c0.yellow + k = c0.black + d = c0.density+x*(c1.density - c0.density)/dx + a = c0.alpha+x*(c1.alpha - c0.alpha)/dx + return CMYKColor(c,m,y,k, density=d, spotName=c0.spotName, alpha=a) + elif cmykDistance(c0,_CMYK_white)<1e-8: + #special c0 is white + c = c1.cyan + m = c1.magenta + y = c1.yellow + k = c1.black + d = x*c1.density/dx + a = x*c1.alpha/dx + return CMYKColor(c,m,y,k, density=d, spotName=c1.spotName, alpha=a) + elif cmykDistance(c1,_CMYK_white)<1e-8: + #special c1 is white + c = c0.cyan + m = c0.magenta + y = c0.yellow + k = c0.black + d = x*c0.density/dx + d = c0.density*(1-x/dx) + a = c0.alpha*(1-x/dx) + return PCMYKColor(c,m,y,k, density=d, spotName=c0.spotName, alpha=a) + else: + c = c0.cyan+x*(c1.cyan - c0.cyan)/dx + m = c0.magenta+x*(c1.magenta - c0.magenta)/dx + y = c0.yellow+x*(c1.yellow - c0.yellow)/dx + k = c0.black+x*(c1.black - c0.black)/dx + d = c0.density+x*(c1.density - c0.density)/dx + a = c0.alpha+x*(c1.alpha - c0.alpha)/dx + return CMYKColor(c,m,y,k, density=d, alpha=a) + elif cname == 'PCMYKColor': + if cmykDistance(c0,c1)<1e-8: + #colors same do density and preserve spotName if any + assert c0.spotName == c1.spotName, "Identical cmyk, but different spotName" + c = c0.cyan + m = c0.magenta + y = c0.yellow + k = c0.black + d = c0.density+x*(c1.density - c0.density)/dx + a = c0.alpha+x*(c1.alpha - c0.alpha)/dx + return PCMYKColor(c*100,m*100,y*100,k*100, density=d*100, + spotName=c0.spotName, alpha=100*a) + elif cmykDistance(c0,_CMYK_white)<1e-8: + #special c0 is white + c = c1.cyan + m = c1.magenta + y = c1.yellow + k = c1.black + d = x*c1.density/dx + a = x*c1.alpha/dx + return PCMYKColor(c*100,m*100,y*100,k*100, density=d*100, + spotName=c1.spotName, alpha=a*100) + elif cmykDistance(c1,_CMYK_white)<1e-8: + #special c1 is white + c = c0.cyan + m = c0.magenta + y = c0.yellow + k = c0.black + d = x*c0.density/dx + d = c0.density*(1-x/dx) + a = c0.alpha*(1-x/dx) + return PCMYKColor(c*100,m*100,y*100,k*100, density=d*100, + spotName=c0.spotName, alpha=a*100) + else: + c = c0.cyan+x*(c1.cyan - c0.cyan)/dx + m = c0.magenta+x*(c1.magenta - c0.magenta)/dx + y = c0.yellow+x*(c1.yellow - c0.yellow)/dx + k = c0.black+x*(c1.black - c0.black)/dx + d = c0.density+x*(c1.density - c0.density)/dx + a = c0.alpha+x*(c1.alpha - c0.alpha)/dx + return PCMYKColor(c*100,m*100,y*100,k*100, density=d*100, alpha=a*100) + else: + raise ValueError("Can't interpolate: Unknown color class %s!" % cname) + +def obj_R_G_B(c): + '''attempt to convert an object to (red,green,blue)''' + if isinstance(c,Color): + return c.red,c.green,c.blue + elif isinstance(c,(tuple,list)): + if len(c)==3: + return tuple(c) + elif len(c)==4: + return toColor(c).rgb() + else: + raise ValueError('obj_R_G_B(%r) bad argument' % (c)) + +# special case -- indicates no drawing should be done +# this is a hangover from PIDDLE - suggest we ditch it since it is not used anywhere +transparent = Color(0,0,0,alpha=0) + +_CMYK_white=CMYKColor(0,0,0,0) +_PCMYK_white=PCMYKColor(0,0,0,0) +_CMYK_black=CMYKColor(0,0,0,1) +_PCMYK_black=PCMYKColor(0,0,0,100) + +# Special colors +ReportLabBlueOLD = HexColor(0x4e5688) +ReportLabBlue = HexColor(0x00337f) +ReportLabBluePCMYK = PCMYKColor(100,65,0,30,spotName='Pantone 288U') +ReportLabLightBlue = HexColor(0xb7b9d3) +ReportLabFidBlue=HexColor(0x3366cc) +ReportLabFidRed=HexColor(0xcc0033) +ReportLabGreen = HexColor(0x336600) +ReportLabLightGreen = HexColor(0x339933) + +# color constants -- mostly from HTML standard +aliceblue = HexColor(0xF0F8FF) +antiquewhite = HexColor(0xFAEBD7) +aqua = HexColor(0x00FFFF) +aquamarine = HexColor(0x7FFFD4) +azure = HexColor(0xF0FFFF) +beige = HexColor(0xF5F5DC) +bisque = HexColor(0xFFE4C4) +black = HexColor(0x000000) +blanchedalmond = HexColor(0xFFEBCD) +blue = HexColor(0x0000FF) +blueviolet = HexColor(0x8A2BE2) +brown = HexColor(0xA52A2A) +burlywood = HexColor(0xDEB887) +cadetblue = HexColor(0x5F9EA0) +chartreuse = HexColor(0x7FFF00) +chocolate = HexColor(0xD2691E) +coral = HexColor(0xFF7F50) +cornflowerblue = cornflower = HexColor(0x6495ED) +cornsilk = HexColor(0xFFF8DC) +crimson = HexColor(0xDC143C) +cyan = HexColor(0x00FFFF) +darkblue = HexColor(0x00008B) +darkcyan = HexColor(0x008B8B) +darkgoldenrod = HexColor(0xB8860B) +darkgray = HexColor(0xA9A9A9) +darkgrey = darkgray +darkgreen = HexColor(0x006400) +darkkhaki = HexColor(0xBDB76B) +darkmagenta = HexColor(0x8B008B) +darkolivegreen = HexColor(0x556B2F) +darkorange = HexColor(0xFF8C00) +darkorchid = HexColor(0x9932CC) +darkred = HexColor(0x8B0000) +darksalmon = HexColor(0xE9967A) +darkseagreen = HexColor(0x8FBC8B) +darkslateblue = HexColor(0x483D8B) +darkslategray = HexColor(0x2F4F4F) +darkslategrey = darkslategray +darkturquoise = HexColor(0x00CED1) +darkviolet = HexColor(0x9400D3) +deeppink = HexColor(0xFF1493) +deepskyblue = HexColor(0x00BFFF) +dimgray = HexColor(0x696969) +dimgrey = dimgray +dodgerblue = HexColor(0x1E90FF) +firebrick = HexColor(0xB22222) +floralwhite = HexColor(0xFFFAF0) +forestgreen = HexColor(0x228B22) +fuchsia = HexColor(0xFF00FF) +gainsboro = HexColor(0xDCDCDC) +ghostwhite = HexColor(0xF8F8FF) +gold = HexColor(0xFFD700) +goldenrod = HexColor(0xDAA520) +gray = HexColor(0x808080) +grey = gray +green = HexColor(0x008000) +greenyellow = HexColor(0xADFF2F) +honeydew = HexColor(0xF0FFF0) +hotpink = HexColor(0xFF69B4) +indianred = HexColor(0xCD5C5C) +indigo = HexColor(0x4B0082) +ivory = HexColor(0xFFFFF0) +khaki = HexColor(0xF0E68C) +lavender = HexColor(0xE6E6FA) +lavenderblush = HexColor(0xFFF0F5) +lawngreen = HexColor(0x7CFC00) +lemonchiffon = HexColor(0xFFFACD) +lightblue = HexColor(0xADD8E6) +lightcoral = HexColor(0xF08080) +lightcyan = HexColor(0xE0FFFF) +lightgoldenrodyellow = HexColor(0xFAFAD2) +lightgreen = HexColor(0x90EE90) +lightgrey = HexColor(0xD3D3D3) +lightpink = HexColor(0xFFB6C1) +lightsalmon = HexColor(0xFFA07A) +lightseagreen = HexColor(0x20B2AA) +lightskyblue = HexColor(0x87CEFA) +lightslategray = HexColor(0x778899) +lightslategrey = lightslategray +lightsteelblue = HexColor(0xB0C4DE) +lightyellow = HexColor(0xFFFFE0) +lime = HexColor(0x00FF00) +limegreen = HexColor(0x32CD32) +linen = HexColor(0xFAF0E6) +magenta = HexColor(0xFF00FF) +maroon = HexColor(0x800000) +mediumaquamarine = HexColor(0x66CDAA) +mediumblue = HexColor(0x0000CD) +mediumorchid = HexColor(0xBA55D3) +mediumpurple = HexColor(0x9370DB) +mediumseagreen = HexColor(0x3CB371) +mediumslateblue = HexColor(0x7B68EE) +mediumspringgreen = HexColor(0x00FA9A) +mediumturquoise = HexColor(0x48D1CC) +mediumvioletred = HexColor(0xC71585) +midnightblue = HexColor(0x191970) +mintcream = HexColor(0xF5FFFA) +mistyrose = HexColor(0xFFE4E1) +moccasin = HexColor(0xFFE4B5) +navajowhite = HexColor(0xFFDEAD) +navy = HexColor(0x000080) +oldlace = HexColor(0xFDF5E6) +olive = HexColor(0x808000) +olivedrab = HexColor(0x6B8E23) +orange = HexColor(0xFFA500) +orangered = HexColor(0xFF4500) +orchid = HexColor(0xDA70D6) +palegoldenrod = HexColor(0xEEE8AA) +palegreen = HexColor(0x98FB98) +paleturquoise = HexColor(0xAFEEEE) +palevioletred = HexColor(0xDB7093) +papayawhip = HexColor(0xFFEFD5) +peachpuff = HexColor(0xFFDAB9) +peru = HexColor(0xCD853F) +pink = HexColor(0xFFC0CB) +plum = HexColor(0xDDA0DD) +powderblue = HexColor(0xB0E0E6) +purple = HexColor(0x800080) +red = HexColor(0xFF0000) +rosybrown = HexColor(0xBC8F8F) +royalblue = HexColor(0x4169E1) +saddlebrown = HexColor(0x8B4513) +salmon = HexColor(0xFA8072) +sandybrown = HexColor(0xF4A460) +seagreen = HexColor(0x2E8B57) +seashell = HexColor(0xFFF5EE) +sienna = HexColor(0xA0522D) +silver = HexColor(0xC0C0C0) +skyblue = HexColor(0x87CEEB) +slateblue = HexColor(0x6A5ACD) +slategray = HexColor(0x708090) +slategrey = slategray +snow = HexColor(0xFFFAFA) +springgreen = HexColor(0x00FF7F) +steelblue = HexColor(0x4682B4) +tan = HexColor(0xD2B48C) +teal = HexColor(0x008080) +thistle = HexColor(0xD8BFD8) +tomato = HexColor(0xFF6347) +turquoise = HexColor(0x40E0D0) +violet = HexColor(0xEE82EE) +wheat = HexColor(0xF5DEB3) +white = HexColor(0xFFFFFF) +whitesmoke = HexColor(0xF5F5F5) +yellow = HexColor(0xFFFF00) +yellowgreen = HexColor(0x9ACD32) +fidblue=HexColor(0x3366cc) +fidred=HexColor(0xcc0033) +fidlightblue=HexColor("#d6e0f5") + +ColorType=type(black) + + ################################################################ + # + # Helper functions for dealing with colors. These tell you + # which are predefined, so you can print color charts; + # and can give the nearest match to an arbitrary color object + # + ################################################################# + +def colorDistance(col1, col2): + """Returns a number between 0 and root(3) stating how similar + two colours are - distance in r,g,b, space. Only used to find + names for things.""" + return math.sqrt( + (col1.red - col2.red)**2 + + (col1.green - col2.green)**2 + + (col1.blue - col2.blue)**2 + ) + +def cmykDistance(col1, col2): + """Returns a number between 0 and root(4) stating how similar + two colours are - distance in r,g,b, space. Only used to find + names for things.""" + return math.sqrt( + (col1.cyan - col2.cyan)**2 + + (col1.magenta - col2.magenta)**2 + + (col1.yellow - col2.yellow)**2 + + (col1.black - col2.black)**2 + ) + +_namedColors = None + +def getAllNamedColors(): + #returns a dictionary of all the named ones in the module + # uses a singleton for efficiency + global _namedColors + if _namedColors is not None: return _namedColors + from reportlab.lib import colors + _namedColors = {} + for name, value in colors.__dict__.items(): + if isinstance(value, Color): + _namedColors[name] = value + + return _namedColors + +def describe(aColor,mode=0): + '''finds nearest colour match to aColor. + mode=0 print a string desription + mode=1 return a string description + mode=2 return (distance, colorName) + ''' + namedColors = getAllNamedColors() + closest = (10, None, None) #big number, name, color + for name, color in namedColors.items(): + distance = colorDistance(aColor, color) + if distance < closest[0]: + closest = (distance, name, color) + if mode<=1: + s = 'best match is %s, distance %0.4f' % (closest[1], closest[0]) + if mode==0: print(s) + else: return s + elif mode==2: + return (closest[1], closest[0]) + else: + raise ValueError("Illegal value for mode "+str(mode)) + +def hue2rgb(m1, m2, h): + if h<0: h += 1 + if h>1: h -= 1 + if h*6<1: return m1+(m2-m1)*h*6 + if h*2<1: return m2 + if h*3<2: return m1+(m2-m1)*(4-6*h) + return m1 + +def hsl2rgb(h, s, l): + if l<=0.5: + m2 = l*(s+1) + else: + m2 = l+s-l*s + m1 = l*2-m2 + return hue2rgb(m1, m2, h+1./3),hue2rgb(m1, m2, h),hue2rgb(m1, m2, h-1./3) + +import re +_re_css_func = re.compile(r'^\s*(pcmyk|cmyk|rgb|hsl)(a|)\s*(.*)\s*$') +_re_css_args = re.compile(r'^\(\s*([^)/]*)(?:\s*/\s*(\d{0,3}(?:\.\d*|)%?)|)\)$') +class cssParse: + ''' + best effort convert css like rgb/rgba colours into reportlab Color + we support functions rgb/a, cmyk/a, pcmyk/a & hsl/a + + rgb & rgba have special treatment if the r g b arguments have a + decimal point and no % signs. In that case the r g b values are + treated as simple floats and must lie in [0,1]. Otherwise we assume + the r g b values will be treated as 255 fractions ie 1 --> 1/255. + + if arguments have a percentage sign appended then the values are first + divided by 100. + + The alpha values can be specified using the a form and adding + an extra argument or using the simple form and adding / before + the closing parenthesis. The alpha values can have decimal points and + percent signs as desired. It's not clear if we should force rgb alpha + values into 8 bit form. + + Arguments can be separated by comma or space. + ''' + def pcVal(self,v,n='argument'): + v = v.strip() + try: + c=float(v.rstrip('%')) + if c<0 or c>100: raise ValueError + return c/100. + except: + raise ValueError(f'bad {n} percentage value {v!r} in css color {self.s!r}') + return c + + def rgbPcVal(self,v): + return int(self.pcVal(v)*255+0.5)/255. + + def rgbVal(self,v): + v = v.strip() + try: + c=float(v) + #if 0255: raise ValueError + return int(c)/255. + except: + raise ValueError(f'bad argument value {v!r} in css color {self.s!r}') + + def floatVal(self,v): + try: + c=float(v) + if c<0 or c>1: raise ValueError + return c + except: + raise ValueError(f'bad argument value {v!r} in css color {self.s!r}') + + def hueVal(self,v): + v = v.strip() + try: + c=float(v) + return ((c%360+360)%360)/360. + except: + raise ValueError(f'bad hue argument value {v!r} in css color {self.s!r}') + + def alphaVal(self,v,c=1,n='alpha'): + try: + a = float(v) + if a>c or a<0: raise VaueError + return a + except: + raise ValueError(f'bad {n} argument value {v!r} in css color {self.s!r}') + + _n_c = dict(pcmyk=(4,100,True,False),cmyk=(4,1,True,False),hsl=(3,1,False,True),rgb=(3,1,False,False)) + + def __call__(self,s): + f = _re_css_func.match(s) + if not f: return #we didn't match the start of a css func + self.s = s + b,c,cmyk,hsl = self._n_c[f.group(1)] + n = _re_css_args.match(f.group(3)) + if not n: raise ValueError(f'css color {s!r} has bad argument list {f.group(3)!r}') + ha = f.group(2) + ha1 = n.group(2) + if ha and ha1: + raise ValueError(f'css color {s!r} has both inline alpha and /alpha%') + n = n.group(1) + n = n.split(',') if ',' in n else n.strip().split() #split on comma or spaces + if len(n)!=(b+(ha and 1 or 0)): + raise ValueError(f'css color {s!r} has wrong number of components') + if ha: + a = n[b] + n = n[:b] + a = self.pcVal(a,'alpha') if '%' in a else self.alphaVal(a,c) + elif ha1: + a = self.pcVal(ha1,f'/{ha1}') if '%' in ha1 else self.alphaVal(ha1,c) + else: + a = c + + pc = ''.join(n) + dp = '.' in pc + pc = '%' in pc + + if cmyk: + C = self.alphaVal(n[0],c,'cyan') + M = self.alphaVal(n[1],c,'magenta') + Y = self.alphaVal(n[2],c,'yellow') + K = self.alphaVal(n[3],c,'black') + return (c>1 and PCMYKColor or CMYKColor)(C,M,Y,K,alpha=a) + else: + if hsl: + R,G,B= hsl2rgb(self.hueVal(n[0]),self.pcVal(n[1]),self.pcVal(n[2])) + elif dp and not pc: + R,G,B = map(self.floatVal,n) + else: + R,G,B = list(map(pc and self.rgbPcVal or self.rgbVal,n)) + #a = int(a*255+0.5)/255. + + return Color(R,G,B,a) + +cssParse=cssParse() + +class toColor: + """Accepot an expression returnng a Color subclass. + + This used to accept arbitrary Python expressions, which resulted in increasngly devilish CVEs and + security holes from tie to time. In April 2023 we are creating explicit, "dumb" parsing code to + replace this. Acceptable patterns are + + a Color instance passed in by the Python programmer + a named list of colours ('pink' etc') + list of 3 or 4 numbers + all CSS colour expression + """ + _G = {} #globals we like (eventually) + + def __init__(self): + self.extraColorsNS = {} #used for overriding/adding to existing color names + #make case insensitive if that's your wish + + def setExtraColorsNameSpace(self,NS): + self.extraColorsNS = NS + + def __call__(self,arg,default=None): + '''try to map an arbitrary arg to a color instance + ''' + if isinstance(arg,Color): return arg + if isinstance(arg,(tuple,list)): + assert 3<=len(arg)<=4, 'Can only convert 3 and 4 sequences to color' + assert 0<=min(arg) and max(arg)<=1 + return len(arg)==3 and Color(arg[0],arg[1],arg[2]) or CMYKColor(arg[0],arg[1],arg[2],arg[3]) + elif isStr(arg): + arg = asNative(arg) + C = cssParse(arg) + if C: return C + if arg in self.extraColorsNS: return self.extraColorsNS[arg] + C = getAllNamedColors() + s = arg.lower() + if s in C: return C[s] + + + # allow expressions like 'Blacker(red, 0.5)' + # >>> re.compile(r"(Blacker|Whiter)\((\w+)\,\s?([0-9.]+)\)").match(msg).groups() + # ('Blacker', 'red', '0.5') + # >>> + pat = re.compile(r"(Blacker|Whiter)\((\w+)\,\s?([0-9.]+)\)") + m = pat.match(arg) + if m: + funcname, rootcolor, num = m.groups() + if funcname == 'Blacker': + return Blacker(rootcolor, float(num)) + else: + return Whiter(rootcolor, float(num)) + + try: + import ast + expr = ast.literal_eval(arg) #safe probably only a tuple or list of values + return toColor(expr) + except (SyntaxError, ValueError): + pass + + if rl_config.toColorCanUse=='rl_safe_eval': + #the most dangerous option + G = C.copy() + G.update(self.extraColorsNS) + if not self._G: + C = globals() + self._G = {s:C[s] for s in '''Blacker CMYKColor CMYKColorSep Color ColorType HexColor PCMYKColor PCMYKColorSep Whiter + _chooseEnforceColorSpace _enforceCMYK _enforceError _enforceRGB _enforceSEP _enforceSEP_BLACK + _enforceSEP_CMYK _namedColors _re_css asNative cmyk2rgb cmykDistance color2bw colorDistance + cssParse describe fade fp_str getAllNamedColors hsl2rgb hue2rgb isStr linearlyInterpolatedColor + literal_eval obj_R_G_B opaqueColor rgb2cmyk setColors toColor toColorOrNone'''.split()} + G.update(self._G) + try: + return toColor(rl_safe_eval(arg,g=G,l={})) + except: + pass + elif rl_config.toColorCanUse=='rl_extended_literal_eval': + C = globals() + S = getAllNamedColors().copy() + C = {k:C[k] for k in '''Blacker CMYKColor CMYKColorSep Color ColorType HexColor PCMYKColor PCMYKColorSep Whiter + _chooseEnforceColorSpace _enforceCMYK _enforceError _enforceRGB _enforceSEP _enforceSEP_BLACK + _enforceSEP_CMYK _namedColors _re_css asNative cmyk2rgb cmykDistance color2bw colorDistance + cssParse describe fade fp_str getAllNamedColors hsl2rgb hue2rgb linearlyInterpolatedColor + obj_R_G_B opaqueColor rgb2cmyk setColors toColor toColorOrNone'''.split() + if callable(C.get(k,None))} + try: + return rl_extended_literal_eval(arg,C,S) + except (ValueError, SyntaxError): + pass + + try: + return HexColor(arg) + except: + if default is None: + raise ValueError('Invalid color value %r' % arg) + return default + +toColor = toColor() + +def toColorOrNone(arg,default=None): + '''as above but allows None as a legal value''' + if arg is None: + return None + else: + return toColor(arg, default) + +def setColors(**kw): + UNDEF = [] + progress = 1 + assigned = {} + while kw and progress: + progress = 0 + for k, v in kw.items(): + if isinstance(v,(tuple,list)): + c = list(map(lambda x,UNDEF=UNDEF: toColor(x,UNDEF),v)) + if isinstance(v,tuple): c = tuple(c) + ok = UNDEF not in c + else: + c = toColor(v,UNDEF) + ok = c is not UNDEF + if ok: + assigned[k] = c + del kw[k] + progress = 1 + + if kw: raise ValueError("Can't convert\n%s" % str(kw)) + getAllNamedColors() + for k, c in assigned.items(): + globals()[k] = c + if isinstance(c,Color): _namedColors[k] = c + +def Whiter(c,f): + '''given a color combine with white as c*f w*(1-f) 0<=f<=1''' + c = toColor(c) + if isinstance(c,CMYKColorSep): + c = c.clone() + if isinstance(c,PCMYKColorSep): + c.__class__ = PCMYKColor + else: + c.__class__ = CMYKColor + if isinstance(c,PCMYKColor): + w = _PCMYK_white + elif isinstance(c,CMYKColor): w = _CMYK_white + else: w = white + return linearlyInterpolatedColor(w, c, 0, 1, f) + +def Blacker(c,f): + '''given a color combine with black as c*f+b*(1-f) 0<=f<=1''' + c = toColor(c) + if isinstance(c,CMYKColorSep): + c = c.clone() + if isinstance(c,PCMYKColorSep): + c.__class__ = PCMYKColor + else: + c.__class__ = CMYKColor + if isinstance(c,PCMYKColor): + b = _PCMYK_black + elif isinstance(c,CMYKColor): b = _CMYK_black + else: b = black + return linearlyInterpolatedColor(b, c, 0, 1, f) + +def fade(aSpotColor, percentages): + """Waters down spot colors and returns a list of new ones + + e.g fade(myColor, [100,80,60,40,20]) returns a list of five colors + """ + out = [] + for percent in percentages: + frac = percent * 0.01 #assume they give us numbers from 0 to 100 + newCyan = frac * aSpotColor.cyan + newMagenta = frac * aSpotColor.magenta + newYellow = frac * aSpotColor.yellow + newBlack = frac * aSpotColor.black + newDensity = frac * aSpotColor.density + newSpot = CMYKColor( newCyan, newMagenta, newYellow, newBlack, + spotName = aSpotColor.spotName, + density = newDensity) + out.append(newSpot) + return out + +def _enforceError(kind,c,tc): + if isinstance(tc,Color): + xtra = tc._lookupName() + xtra = xtra and '(%s)'%xtra or '' + else: + xtra = '' + raise ValueError('Non %s color %r%s' % (kind,c,xtra)) + +def _enforceSEP(c): + '''pure separating colors only, this makes black a problem''' + tc = toColor(c) + if not isinstance(tc,CMYKColorSep): + _enforceError('separating',c,tc) + return tc + +def _enforceSEP_BLACK(c): + '''separating + blacks only''' + tc = toColor(c) + if not isinstance(tc,CMYKColorSep): + if isinstance(tc,Color) and tc.red==tc.blue==tc.green: #ahahahah it's a grey + tc = _CMYK_black.clone(density=1-tc.red) + elif not (isinstance(tc,CMYKColor) and tc.cyan==tc.magenta==tc.yellow==0): #ie some shade of grey + _enforceError('separating or black',c,tc) + return tc + +def _enforceSEP_CMYK(c): + '''separating or cmyk only''' + tc = toColor(c) + if not isinstance(tc,CMYKColorSep): + if isinstance(tc,Color) and tc.red==tc.blue==tc.green: #ahahahah it's a grey + tc = _CMYK_black.clone(density=1-tc.red) + elif not isinstance(tc,CMYKColor): + _enforceError('separating or CMYK',c,tc) + return tc + +def _enforceCMYK(c): + '''cmyk outputs only (rgb greys converted)''' + tc = toColor(c) + if not isinstance(tc,CMYKColor): + if isinstance(tc,Color) and tc.red==tc.blue==tc.green: #ahahahah it's a grey + tc = _CMYK_black.clone(black=1-tc.red,alpha=tc.alpha) + else: + _enforceError('CMYK',c,tc) + elif isinstance(tc,CMYKColorSep): + tc = tc.clone() + tc.__class__ = CMYKColor + return tc + +def _enforceRGB(c): + tc = toColor(c) + if isinstance(tc,CMYKColor): + if tc.cyan==tc.magenta==tc.yellow==0: #ahahahah it's grey + v = 1-tc.black*tc.density + tc = Color(v,v,v,alpha=tc.alpha) + else: + _enforceError('RGB',c,tc) + return tc + +def _chooseEnforceColorSpace(enforceColorSpace): + if enforceColorSpace is not None and not callable(enforceColorSpace): + if isinstance(enforceColorSpace,str): enforceColorSpace=enforceColorSpace.upper() + if enforceColorSpace=='CMYK': + enforceColorSpace = _enforceCMYK + elif enforceColorSpace=='RGB': + enforceColorSpace = _enforceRGB + elif enforceColorSpace=='SEP': + enforceColorSpace = _enforceSEP + elif enforceColorSpace=='SEP_BLACK': + enforceColorSpace = _enforceSEP_BLACK + elif enforceColorSpace=='SEP_CMYK': + enforceColorSpace = _enforceSEP_CMYK + else: + raise ValueError('Invalid value for Canvas argument enforceColorSpace=%r' % enforceColorSpace) + return enforceColorSpace + +if __name__ == "__main__": + import doctest + doctest.testmod() diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/corp.py b/.venv/lib/python3.13/site-packages/reportlab/lib/corp.py new file mode 100644 index 0000000000000000000000000000000000000000..a85f923e8c6624827a39572bdc5d29703615f817 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/corp.py @@ -0,0 +1,481 @@ +#!/bin/env python +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +__version__='3.3.0' +__doc__="""Generate ReportLab logo in a variety of sizes and formats. + + +This module includes some reusable routines for ReportLab's + 'Corporate Image' - the logo, standard page backdrops and + so on - you are advised to do the same for your own company!""" + +from reportlab.lib.units import inch,cm +from reportlab.lib.validators import * +from reportlab.lib.attrmap import * +from reportlab.lib.formatters import DecimalFormatter +from reportlab.graphics.shapes import definePath, Group, Drawing, Rect, PolyLine, String +from reportlab.graphics.widgetbase import Widget +from reportlab.lib.colors import Color, black, white, ReportLabBlue +from reportlab.pdfbase.pdfmetrics import stringWidth + +class RL_CorpLogo(Widget): + '''Dinu's fat letter logo as hacked into decent paths by Robin''' + _attrMap = AttrMap( + x = AttrMapValue(isNumber,'Logo x-coord'), + y = AttrMapValue(isNumber,'Logo y-coord'), + angle = AttrMapValue(isNumber,'Logo rotation'), + strokeColor = AttrMapValue(isColorOrNone, 'Logo lettering stroke color'), + fillColor = AttrMapValue(isColorOrNone, 'Logo lettering fill color'), + strokeWidth = AttrMapValue(isNumber,'Logo lettering stroke width'), + background = AttrMapValue(isColorOrNone,desc="Logo background color"), + border = AttrMapValue(isColorOrNone,desc="Logo border color"), + borderWidth = AttrMapValue(isNumber,desc="Logo border width (1)"), + shadow = AttrMapValue(isNumberOrNone,desc="None or fraction of background for shadowing" ), + width = AttrMapValue(isNumber, desc="width in points of the logo (default 129)"), + height = AttrMapValue(isNumber, desc="height in points of the logo (default 86)"), + skewX = AttrMapValue(isNumber, desc="x-skew of the logo (default 10)"), + skewY = AttrMapValue(isNumber, desc="y-skew of the logo (default 0)"), + showPage = AttrMapValue(EitherOr((isBoolean,SequenceOf(isBoolean,lo=2,hi=2))), desc="If true or (true(top),true(bottom)) show the page lines"), + xFlip = AttrMapValue(isBoolean, desc="If true do x reversal"), + yFlip = AttrMapValue(isBoolean, desc="If true do y reversal"), + oColors = AttrMapValue(NoneOr(EitherOr((isColor,SequenceOf(isColorOrNone,lo=2,hi=2)))),desc="None or fill/stroke colors for the o in ReportLab"), + pageColors = AttrMapValue(NoneOr(EitherOr((isColor,SequenceOf(isColorOrNone,lo=2,hi=2)))),desc="None or fill/stroke colors for the page outline"), + prec = AttrMapValue(NoneOr(isInt),desc="None or precision negative means strip excess"), + ) + + def __init__(self): + self.fillColor = white + self.strokeColor = None + self.strokeWidth = 0.1 + self.background = ReportLabBlue + self.border = None + self.borderWidth = 1 + self.shadow = 0.5 + self.height = 86 + self.width = 130 + self.x = self.y = self.angle = self.skewY = self._dx = 0 + self.skewX = 10 + self._dy = 35.5 + self.showPage = 1 + self.oColors = None #ie use the default + self.pageColors = None #ie use the default + self.prec = None + + def demo(self): + D = Drawing(self.width, self.height) + D.add(self) + return D + + def _paintLogo(self, g, dx=0, dy=0, strokeColor=None, strokeWidth=0.1, fillColor=white, _ocolors=None, _pagecolors=None): + OP = [('moveTo' ,62.10648,6.51392 ), ('curveTo' ,62.10648,4.44205 ,61.47118,2.79288 ,60.2003,1.56631 ), ('curveTo' ,58.92971,0.33978 ,57.22626,-0.27348 ,55.08965,-0.27348 ), ('curveTo' ,52.99018,-0.27348 ,51.31914,0.35221 ,50.07595,1.60362 ), ('curveTo' ,48.8419,2.8633 ,48.22517,4.55394 ,48.22517,6.67551 ), ('curveTo' ,48.22517,8.79709 ,48.85575,10.50016 ,50.1175,11.78472 ), ('curveTo' ,51.36982,13.07755 ,53.03172,13.72396 ,55.1035,13.72396 ), ('curveTo' ,57.28608,13.72396 ,58.99866,13.08168 ,60.24185,11.79712 ), ('curveTo' ,61.48503,10.51259 ,62.10648,8.75154 ,62.10648,6.51392 ), 'closePath', ('moveTo' ,56.73358,6.67551 ), ('curveTo' ,56.73358,7.17276 ,56.69675,7.62236 ,56.62308,8.02428 ), ('curveTo' ,56.54942,8.42623 ,56.44334,8.77016 ,56.30544,9.05607 ), ('curveTo' ,56.16724,9.34198 ,56.00134,9.56369 ,55.80804,9.72113 ), ('curveTo' ,55.61474,9.8786 ,55.39817,9.95733 ,55.1589,9.95733 ), ('curveTo' ,54.68921,9.95733 ,54.31174,9.65898 ,54.02621,9.06229 ), ('curveTo' ,53.74068,8.54018 ,53.59807,7.75702 ,53.59807,6.71282 ), ('curveTo' ,53.59807,5.68515 ,53.74068,4.90202 ,54.02621,4.36332 ), ('curveTo' ,54.31174,3.76663 ,54.69392,3.46828 ,55.17275,3.46828 ), ('curveTo' ,55.62388,3.46828 ,55.99692,3.7625 ,56.29159,4.35088 ), ('curveTo' ,56.58625,5.0056 ,56.73358,5.78047 ,56.73358,6.67551 ), 'closePath'] + P = [ + ('moveTo' ,15.7246,0 ), ('lineTo' ,9.49521,0 ), ('lineTo' ,6.64988,6.83711 ), ('curveTo' ,6.62224,6.95315 ,6.57391,7.10646 ,6.50485,7.29708 ), ('curveTo' ,6.43578,7.48767 ,6.35059,7.71559 ,6.24931,7.98079 ), ('lineTo' ,6.29074,6.71282 ), ('lineTo' ,6.29074,0 ), ('lineTo' ,0.55862,0 ), ('lineTo' ,0.55862,19.19365 ), ('lineTo' ,6.45649,19.19365 ), ('curveTo' ,9.05324,19.19365 ,10.99617,18.73371 ,12.28532,17.8138 ), ('curveTo' ,13.92439,16.63697 ,14.7439,14.96293 ,14.7439,12.79161 ), ('curveTo' ,14.7439,10.47114 ,13.64354,8.86755 ,11.44276,7.98079 ), 'closePath', ('moveTo' ,6.31838,10.30542 ), ('lineTo' ,6.70513,10.30542 ), ('curveTo' ,7.36812,10.30542 ,7.92062,10.53331 ,8.36261,10.98912 ), ('curveTo' ,8.80461,11.44491 ,9.0256,12.02504 ,9.0256,12.72947 ), ('curveTo' ,9.0256,14.16321 ,8.19227,14.88004 ,6.52556,14.88004 ), ('lineTo' ,6.31838,14.88004 ), 'closePath', + ('moveTo' ,25.06173,4.54978 ), ('lineTo' ,30.47611,4.45033 ), ('curveTo' ,30.08951,2.88402 ,29.33668,1.70513 ,28.21787,0.91369 ), ('curveTo' ,27.09906,0.12223 ,25.63726,-0.27348 ,23.83245,-0.27348 ), ('curveTo' ,21.69611,-0.27348 ,20.02024,0.32322 ,18.80475,1.5166 ), ('curveTo' ,17.59846,2.72658 ,16.99531,4.37988 ,16.99531,6.47662 ), ('curveTo' ,16.99531,8.6065 ,17.64451,10.34269 ,18.94286,11.68527 ), ('curveTo' ,20.24124,13.03612 ,21.91711,13.71152 ,23.97056,13.71152 ), ('curveTo' ,26.01482,13.71152 ,27.64466,13.06096 ,28.86015,11.75985 ), ('curveTo' ,30.07566,10.45042 ,30.68326,8.71423 ,30.68326,6.5512 ), ('lineTo' ,30.65586,5.66859 ), ('lineTo' ,22.53407,5.66859 ), ('curveTo' ,22.59855,4.29287 ,23.03132,3.60503 ,23.83245,3.60503 ), ('curveTo' ,24.45861,3.60503 ,24.86837,3.91994 ,25.06173,4.54978 ), 'closePath', ('moveTo' ,25.18604,8.35371 ), ('curveTo' ,25.18604,8.60235 ,25.15384,8.83024 ,25.08937,9.03742 ), ('curveTo' ,25.02489,9.24463 ,24.93514,9.42278 ,24.82001,9.57197 ), ('curveTo' ,24.70492,9.72113 ,24.56911,9.83923 ,24.41255,9.92624 ), ('curveTo' ,24.25603,10.01326 ,24.08568,10.05678 ,23.90152,10.05678 ), ('curveTo' ,23.51474,10.05678 ,23.20169,9.89725 ,22.96225,9.57819 ), ('curveTo' ,22.72283,9.25913 ,22.60314,8.85096 ,22.60314,8.35371 ), 'closePath', + ('moveTo' ,38.36308,-5.99181 ), ('lineTo' ,32.82428,-5.99181 ), ('lineTo' ,32.82428,13.43804 ), ('lineTo' ,38.36308,13.43804 ), ('lineTo' ,38.23873,11.53608 ), ('curveTo' ,38.46886,11.93387 ,38.70371,12.27159 ,38.94327,12.54922 ), ('curveTo' ,39.18254,12.82685 ,39.44037,13.05268 ,39.71676,13.22671 ), ('curveTo' ,39.99286,13.40074 ,40.28988,13.52712 ,40.60753,13.60585 ), ('curveTo' ,40.92518,13.68459 ,41.27759,13.72396 ,41.66419,13.72396 ), ('curveTo' ,43.10068,13.72396 ,44.2702,13.07755 ,45.17246,11.78472 ), ('curveTo' ,46.06588,10.50844 ,46.51229,8.81368 ,46.51229,6.70038 ), ('curveTo' ,46.51229,4.55394 ,46.08415,2.85502 ,45.22785,1.60362 ), ('curveTo' ,44.38983,0.35221 ,43.23416,-0.27348 ,41.76084,-0.27348 ), ('curveTo' ,40.41659,-0.27348 ,39.24235,0.42679 ,38.23873,1.82739 ), ('curveTo' ,38.2847,1.40472 ,38.31239,1.04007 ,38.32153,0.73345 ), ('curveTo' ,38.34923,0.41851 ,38.36308,0.04146 ,38.36308,-0.3978 ), 'closePath', ('moveTo' ,40.7802,6.84954 ), ('curveTo' ,40.7802,7.72802 ,40.66734,8.40964 ,40.44193,8.89448 ), ('curveTo' ,40.21621,9.37929 ,39.89621,9.62168 ,39.48191,9.62168 ), ('curveTo' ,38.62533,9.62168 ,38.19718,8.68108 ,38.19718,6.79983 ), ('curveTo' ,38.19718,4.87712 ,38.61177,3.91581 ,39.44037,3.91581 ), ('curveTo' ,39.85466,3.91581 ,40.18174,4.1727 ,40.42101,4.68654 ), ('curveTo' ,40.66057,5.20037 ,40.7802,5.92135 ,40.7802,6.84954 ), 'closePath', + ('moveTo' ,69.78629,0 ), ('lineTo' ,64.2475,0 ), ('lineTo' ,64.2475,13.43804 ), ('lineTo' ,69.78629,13.43804 ), ('lineTo' ,69.49605,10.81507 ), ('curveTo' ,70.33407,12.77921 ,71.71988,13.76126 ,73.65346,13.76126 ), ('lineTo' ,73.65346,8.16725 ), ('curveTo' ,73.04586,8.4656 ,72.5302,8.61478 ,72.10647,8.61478 ), ('curveTo' ,71.36068,8.61478 ,70.78756,8.37236 ,70.38711,7.88755 ), ('curveTo' ,69.98637,7.40274 ,69.78629,6.69623 ,69.78629,5.76804 ), 'closePath', + ('moveTo' ,81.55427,0 ), ('lineTo' ,76.00163,0 ), ('lineTo' ,76.00163,9.42278 ), ('lineTo' ,74.42725,9.42278 ), ('lineTo' ,74.42725,13.43804 ), ('lineTo' ,76.00163,13.43804 ), ('lineTo' ,76.00163,17.39113 ), ('lineTo' ,81.55427,17.39113 ), ('lineTo' ,81.55427,13.43804 ), ('lineTo' ,83.39121,13.43804 ), ('lineTo' ,83.39121,9.42278 ), ('lineTo' ,81.55427,9.42278 ), 'closePath', + ('moveTo' ,95.17333,0 ), ('lineTo' ,85.09024,0 ), ('lineTo' ,85.09024,19.19365 ), ('lineTo' ,90.85002,19.19365 ), ('lineTo' ,90.85002,4.61196 ), ('lineTo' ,95.17333,4.61196 ), 'closePath', + ('moveTo' ,110.00787,0 ), ('lineTo' ,104.45523,0 ), ('curveTo' ,104.5012,0.44754 ,104.53803,0.87433 ,104.56573,1.2804 ), ('curveTo' ,104.59313,1.68651 ,104.62083,2.01385 ,104.64853,2.26246 ), ('curveTo' ,103.69087,0.57182 ,102.40644,-0.27348 ,100.79492,-0.27348 ), ('curveTo' ,99.39527,-0.27348 ,98.28557,0.35637 ,97.46611,1.61605 ), ('curveTo' ,96.65578,2.86746 ,96.25062,4.59952 ,96.25062,6.81227 ), ('curveTo' ,96.25062,8.95041 ,96.66963,10.63276 ,97.50765,11.8593 ), ('curveTo' ,98.34538,13.10242 ,99.4872,13.72396 ,100.93312,13.72396 ), ('curveTo' ,102.41557,13.72396 ,103.61249,12.92008 ,104.52418,11.31231 ), ('curveTo' ,104.50591,11.47806 ,104.49206,11.62309 ,104.48293,11.74741 ), ('curveTo' ,104.4735,11.87173 ,104.46437,11.9753 ,104.45523,12.05819 ), ('lineTo' ,104.39983,12.84135 ), ('lineTo' ,104.35858,13.43804 ), ('lineTo' ,110.00787,13.43804 ), 'closePath', ('moveTo' ,104.39983,6.88685 ), ('curveTo' ,104.39983,7.38409 ,104.37921,7.80676 ,104.33766,8.15481 ), ('curveTo' ,104.29641,8.5029 ,104.22952,8.78672 ,104.13758,9.00636 ), ('curveTo' ,104.04535,9.22598 ,103.92572,9.38341 ,103.77839,9.47874 ), ('curveTo' ,103.63106,9.57403 ,103.45161,9.62168 ,103.23974,9.62168 ), ('curveTo' ,102.30036,9.62168 ,101.83096,8.49875 ,101.83096,6.25285 ), ('curveTo' ,101.83096,4.64508 ,102.24967,3.8412 ,103.0877,3.8412 ), ('curveTo' ,103.96255,3.8412 ,104.39983,4.85641 ,104.39983,6.88685 ), 'closePath', + ('moveTo' ,118.22604,0 ), ('lineTo' ,112.5629,0 ), ('lineTo' ,112.5629,20.99616 ), ('lineTo' ,118.10169,20.99616 ), ('lineTo' ,118.10169,13.63694 ), ('curveTo' ,118.10169,13.01538 ,118.07399,12.30268 ,118.01889,11.49877 ), ('curveTo' ,118.52542,12.31096 ,119.03636,12.88693 ,119.55202,13.22671 ), ('curveTo' ,120.08625,13.55821 ,120.75838,13.72396 ,121.5687,13.72396 ), ('curveTo' ,123.07885,13.72396 ,124.24837,13.09827 ,125.07697,11.84686 ), ('curveTo' ,125.90586,10.60373 ,126.32015,8.85099 ,126.32015,6.5885 ), ('curveTo' ,126.32015,4.42546 ,125.89201,2.74314 ,125.03571,1.54147 ), ('curveTo' ,124.18826,0.3315 ,123.01432,-0.27348 ,121.51331,-0.27348 ), ('curveTo' ,120.78608,-0.27348 ,120.16905,-0.12432 ,119.66252,0.17403 ), ('curveTo' ,119.41383,0.3315 ,119.15835,0.54283 ,118.8961,0.80803 ), ('curveTo' ,118.63356,1.07322 ,118.36866,1.40472 ,118.10169,1.80252 ), ('curveTo' ,118.11112,1.64505 ,118.12025,1.51039 ,118.12939,1.3985 ), ('curveTo' ,118.13852,1.28662 ,118.14766,1.19339 ,118.15709,1.11881 ), 'closePath', ('moveTo' ,120.58806,6.70038 ), ('curveTo' ,120.58806,8.62306 ,120.11837,9.5844 ,119.17898,9.5844 ), ('curveTo' ,118.35039,9.5844 ,117.93609,8.67693 ,117.93609,6.86198 ), ('curveTo' ,117.93609,4.96417 ,118.36424,4.01526 ,119.22053,4.01526 ), ('curveTo' ,120.13222,4.01526 ,120.58806,4.91027 ,120.58806,6.70038 ), 'closePath', + ] + + + showPage = self.showPage + PP = [] + if showPage: + if not isSeq(showPage): + showPage = (showPage,showPage) + if showPage[0]: #top + PP.extend([('moveTo' ,32.70766,14.52164 ), ('lineTo' ,32.70766,47.81862 ), ('lineTo' ,80.14849,47.81862 ), ('lineTo' ,90.46172,37.21073 ), ('lineTo' ,90.46172,20.12025 ), ('lineTo' ,85.15777,20.12025 ), ('lineTo' ,85.15777,30.72814 ), ('lineTo' ,73.66589,30.72814 ), ('lineTo' ,73.66589,42.22002 ), ('lineTo' ,38.30626,42.22002 ), ('lineTo' ,38.30626,14.52164 ), 'closePath', ('moveTo' ,79.2645,36.32674 ), ('lineTo' ,85.15777,36.32674 ), ('lineTo' ,79.2645,42.22002 ), 'closePath']) + if showPage[1]: #bottom + PP.extend([('moveTo',38.30626,-7.28346),('lineTo',38.30626,-25.55261),('lineTo',85.15777,-25.55261),('lineTo',85.15777,-1.39019),('lineTo',90.46172,-1.39019),('lineTo',90.46172,-31.15121),('lineTo',32.70766,-31.15121),('lineTo',32.70766,-7.28346), 'closePath']) + + if _ocolors: + OP = self.applyPrec(OP,self.prec) + g.add(definePath(OP,strokeColor=_ocolors[0],strokeWidth=strokeWidth,fillColor=_ocolors[1], dx=dx, dy=dy)) + else: + P += OP + if self.showPage and _pagecolors: + PP = self.applyPrec(PP,self.prec) + g.add(definePath(PP,strokeColor=_pagecolors[0],strokeWidth=strokeWidth,fillColor=_pagecolors[1], dx=dx, dy=dy)) + else: + P += PP + P = self.applyPrec(P,self.prec) + g.add(definePath(P,strokeColor=strokeColor,strokeWidth=strokeWidth,fillColor=fillColor, dx=dx, dy=dy)) + + @staticmethod + def applyPrec(P,prec): + if prec is None: return P + R = [].append + f = DecimalFormatter(places=prec) + for p in P: + if isSeq(p): + n = [].append + for e in p: + if isinstance(e,float): + e = float(f(e)) + n(e) + p = n.__self__ + R(p) + return R.__self__ + + def draw(self): + fillColor = self.fillColor + strokeColor = self.strokeColor + g = Group() + bg = self.background + bd = self.border + bdw = self.borderWidth + shadow = self.shadow + x, y = self.x, self.y + if bg: + if shadow is not None and 0<=shadow<1: + shadow = Color(bg.red*shadow,bg.green*shadow,bg.blue*shadow) + self._paintLogo(g,dy=-2.5, dx=2,fillColor=shadow) + self._paintLogo(g,fillColor=fillColor,strokeColor=strokeColor, + _ocolors=self.oColors or None,_pagecolors=self.pageColors or None) + g.skew(kx=self.skewX, ky=self.skewY) + g.shift(self._dx,self._dy) + G = Group() + G.add(g) + _w, _h = 130, 86 + w, h = self.width, self.height + if bg or (bd and bdw): + G.insert(0,Rect(0,0,_w,_h,fillColor=bg,strokeColor=bd,strokeWidth=bdw)) + if w!=_w or h!=_h: G.scale(w/float(_w),h/float(_h)) + + angle = self.angle + if self.angle: + w, h = w/2., h/2. + G.shift(-w,-h) + G.rotate(angle) + G.shift(w,h) + xFlip = getattr(self,'xFlip',0) and -1 or 0 + yFlip = getattr(self,'yFlip',0) and -1 or 0 + if xFlip or yFlip: + sx = xFlip or 1 + sy = yFlip or 1 + G.shift(sx*x+w*xFlip,sy*y+yFlip*h) + G = Group(G,transform=(sx,0,0,sy,0,0)) + else: + G.shift(x,y) + return G + +class RL_CorpLogoReversed(RL_CorpLogo): + def __init__(self): + RL_CorpLogo.__init__(self) + self.background = white + self.fillColor = ReportLabBlue + +class RL_CorpLogoThin(Widget): + """The ReportLab Logo. + + New version created by John Precedo on 7-8 August 2001. + Based on bitmapped imaged from E-Id. + Improved by Robin Becker.""" + + _attrMap = AttrMap( + x = AttrMapValue(isNumber), + y = AttrMapValue(isNumber), + height = AttrMapValue(isNumberOrNone), + width = AttrMapValue(isNumberOrNone), + fillColor = AttrMapValue(isColorOrNone), + strokeColor = AttrMapValue( isColorOrNone) + ) + + _h = 90.5 + _w = 136.5 + _text='R e p o r t L a b' + _fontName = 'Helvetica-Bold' + _fontSize = 16 + + def __init__(self): + self.fillColor = ReportLabBlue + self.strokeColor = white + self.x = 0 + self.y = 0 + self.height = self._h + self.width = self._w + + def demo(self): + D = Drawing(self.width, self.height) + D.add(self) + return D + + def _getText(self, x=0, y=0, color=None): + return String(x,y, self._text, fontName=self._fontName, fontSize=self._fontSize, fillColor=color) + + def _sw(self,f=None,l=None): + text = self._text + if f is None: f = 0 + if l is None: l = len(text) + return stringWidth(text[f:l],self._fontName,self._fontSize) + + def _addPage(self, g, strokeWidth=3, color=None, dx=0, dy=0): + x1, x2 = 31.85+dx, 80.97+dx + fL = 10 # fold length + y1, y2 = dy-34, dy+50.5 + L = [[x1,dy-4,x1,y1, x2, y1, x2, dy-1], + [x1,dy+11,x1,y2,x2-fL,y2,x2,y2-fL,x2,dy+14], + [x2-10,y2,x2-10,y2-fL,x2,y2-fL]] + + for l in L: + g.add(PolyLine(l, strokeWidth=strokeWidth, strokeColor=color, strokeLineJoin=0)) + + def draw(self): + sx = 0.5 + fillColor = self.fillColor + strokeColor = self.strokeColor + shadow = Color(fillColor.red*sx,fillColor.green*sx,fillColor.blue*sx) + g = Group() + g2= Group() + g.add(Rect(fillColor=fillColor, strokeColor=fillColor, x=0, y=0, width=self._w, height=self._h)) + sx = (self._w-2)/self._sw() + g2.scale(sx,1) + self._addPage(g2,strokeWidth=3,dx=2,dy=-2.5,color=shadow) + self._addPage(g2,strokeWidth=3,color=strokeColor) + g2.scale(1/sx,1) + g2.add(self._getText(x=1,y=0,color=shadow)) + g2.add(self._getText(x=0,y=1,color=strokeColor)) + g2.scale(sx,1) + g2.skew(kx=10, ky=0) + g2.shift(0,38) + g.add(g2) + g.scale(self.width/self._w,self.height/self._h) + g.shift(self.x,self.y) + return g + +class ReportLabLogo: + """vector reportlab logo centered in a 250x by 150y rectangle""" + + def __init__(self, atx=0, aty=0, width=2.5*inch, height=1.5*inch, powered_by=0): + self.origin = (atx, aty) + self.dimensions = (width, height) + self.powered_by = powered_by + + def draw(self, canvas): + from reportlab.graphics import renderPDF + canvas.saveState() + (atx,aty) = self.origin + (width, height) = self.dimensions + logo = RL_CorpLogo() + logo.width, logo.height = width, height + renderPDF.draw(logo.demo(),canvas,atx,aty,0) + canvas.restoreState() + +class RL_BusinessCard(Widget): + """Widget that creates a single business card. + Uses RL_CorpLogo for the logo. + + For a black border around your card, set self.border to 1. + To change the details on the card, over-ride the following properties: + self.name, self.position, self.telephone, self.mobile, self.fax, self.email, self.web + The office locations are set in self.rh_blurb_top ("London office" etc), and + self.rh_blurb_bottom ("New York office" etc). + """ + # for items where it 'isString' the string can be an empty one... + _attrMap = AttrMap( + fillColor = AttrMapValue(isColorOrNone), + strokeColor = AttrMapValue(isColorOrNone), + altStrokeColor = AttrMapValue(isColorOrNone), + x = AttrMapValue(isNumber), + y = AttrMapValue(isNumber), + height = AttrMapValue(isNumber), + width = AttrMapValue(isNumber), + borderWidth = AttrMapValue(isNumber), + bleed=AttrMapValue(isNumberOrNone), + cropMarks=AttrMapValue(isBoolean), + border=AttrMapValue(isBoolean), + name=AttrMapValue(isString), + position=AttrMapValue(isString), + telephone=AttrMapValue(isString), + mobile=AttrMapValue(isString), + fax=AttrMapValue(isString), + email=AttrMapValue(isString), + web=AttrMapValue(isString), + rh_blurb_top=AttrMapValue(isListOfStringsOrNone), + rh_blurb_bottom=AttrMapValue(isListOfStringsOrNone) + ) + + _h = 5.35*cm + _w = 8.5*cm + _fontName = 'Helvetica-Bold' + _strapline = "strategic reporting solutions for e-business" + + + def __init__(self): + self.fillColor = ReportLabBlue + self.strokeColor = black + self.altStrokeColor = white + self.x = 0 + self.y = 0 + self.height = self._h + self.width = self._w + self.borderWidth = self.width/6.15 + self.bleed=0.2*cm + self.cropMarks=1 + self.border=0 + #Over-ride these with your own info + self.name="Joe Cool" + self.position="Freelance Demonstrator" + self.telephone="020 8545 7271" + self.mobile="-" + self.fax="020 8544 1311" + self.email="info@reportlab.com" + self.web="www.reportlab.com" + self.rh_blurb_top = ["London office:", + "ReportLab Europe Ltd", + "Media House", + "3 Palmerston Road", + "Wimbledon", + "London SW19 1PG", + "United Kingdom"] + + def demo(self): + D = Drawing(self.width, self.height) + D.add(self) + return D + + def draw(self): + fillColor = self.fillColor + strokeColor = self.strokeColor + + g = Group() + g.add(Rect(x = 0, y = 0, + fillColor = self.fillColor, + strokeColor = self.fillColor, + width = self.borderWidth, + height = self.height)) + g.add(Rect(x = 0, y = self.height-self.borderWidth, + fillColor = self.fillColor, + strokeColor = self.fillColor, + width = self.width, + height = self.borderWidth)) + + g2 = Group() + rl=RL_CorpLogo() + rl.height = 1.25*cm + rl.width = 1.9*cm + rl.draw() + g2.add(rl) + g.add(g2) + g2.shift(x=(self.width-(rl.width+(self.width/42))), + y=(self.height - (rl.height+(self.height/42)))) + + g.add(String(x = self.borderWidth/5.0, + y = ((self.height - (rl.height+(self.height/42)))+((38/90.5)*rl.height)), + fontSize = 6, + fillColor = self.altStrokeColor, + fontName = "Helvetica-BoldOblique", + textAnchor = 'start', + text = self._strapline)) + + leftText=["Tel:", "Mobile:", "Fax:", "Email:", "Web:"] + leftDetails=[self.telephone,self.mobile,self.fax,self.email,self.web] + leftText.reverse() + leftDetails.reverse() + for f in range(len(leftText),0,-1): + g.add(String(x = self.borderWidth+(self.borderWidth/5.0), + y = (self.borderWidth/5.0)+((f-1)*(5*1.2)), + fontSize = 5, + fillColor = self.strokeColor, + fontName = "Helvetica", + textAnchor = 'start', + text = leftText[f-1])) + g.add(String(x = self.borderWidth+(self.borderWidth/5.0)+self.borderWidth, + y = (self.borderWidth/5.0)+((f-1)*(5*1.2)), + fontSize = 5, + fillColor = self.strokeColor, + fontName = "Helvetica", + textAnchor = 'start', + text = leftDetails[f-1])) + + + ty = (self.height-self.borderWidth-(self.borderWidth/5.0)+2) +# g.add(Line(self.borderWidth, ty, self.borderWidth+(self.borderWidth/5.0), ty)) +# g.add(Line(self.borderWidth+(self.borderWidth/5.0), ty, self.borderWidth+(self.borderWidth/5.0), +# ty+(self.borderWidth/5.0))) +# g.add(Line(self.borderWidth, ty-10, +# self.borderWidth+(self.borderWidth/5.0), ty-10)) + + rightText=self.rh_blurb_top + for f in range(1,(len(rightText)+1)): + g.add(String(x = self.width-(self.borderWidth/5.0), + y = ty-((f)*(5*1.2)), + fontSize = 5, + fillColor = self.strokeColor, + fontName = "Helvetica", + textAnchor = 'end', + text = rightText[f-1])) + + g.add(String(x = self.borderWidth+(self.borderWidth/5.0), + y = ty-10, + fontSize = 10, + fillColor = self.strokeColor, + fontName = "Helvetica", + textAnchor = 'start', + text = self.name)) + + ty1 = ty-10*1.2 + + g.add(String(x = self.borderWidth+(self.borderWidth/5.0), + y = ty1-8, + fontSize = 8, + fillColor = self.strokeColor, + fontName = "Helvetica", + textAnchor = 'start', + text = self.position)) + if self.border: + g.add(Rect(x = 0, y = 0, + fillColor=None, + strokeColor = black, + width = self.width, + height = self.height)) + g.shift(self.x,self.y) + return g + + +def test(formats=['pdf','eps','jpg','gif','svg']): + """This function produces a pdf with examples. """ + + #white on blue + rl = RL_CorpLogo() + rl.width = 129 + rl.height = 86 + D = Drawing(rl.width,rl.height) + D.add(rl) + D.__dict__['verbose'] = 1 + D.save(fnRoot='corplogo_whiteonblue',formats=formats) + + + #blue on white + rl = RL_CorpLogoReversed() + rl.width = 129 + rl.height = 86 + D = Drawing(rl.width,rl.height) + D.add(rl) + D.__dict__['verbose'] = 1 + D.save(fnRoot='corplogo_blueonwhite',formats=formats) + + #gray on white + rl = RL_CorpLogoReversed() + rl.fillColor = Color(0.2, 0.2, 0.2) + rl.width = 129 + rl.height = 86 + D = Drawing(rl.width,rl.height) + D.add(rl) + D.__dict__['verbose'] = 1 + D.save(fnRoot='corplogo_grayonwhite',formats=formats) + + + rl = RL_BusinessCard() + rl.x=25 + rl.y=25 + rl.border=1 + D = Drawing(rl.width+50,rl.height+50) + D.add(rl) + D.__dict__['verbose'] = 1 + D.save(fnRoot='RL_BusinessCard',formats=formats) + +if __name__=='__main__': + test() diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/enums.py b/.venv/lib/python3.13/site-packages/reportlab/lib/enums.py new file mode 100644 index 0000000000000000000000000000000000000000..69ca834097488aa748e6f4d496d33dd4196ef647 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/enums.py @@ -0,0 +1,11 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/enums.py +__version__='3.3.0' +__doc__=""" +Container for constants. Hardly used! +""" +TA_LEFT = 0 +TA_CENTER = 1 +TA_RIGHT = 2 +TA_JUSTIFY = 4 \ No newline at end of file diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/extformat.py b/.venv/lib/python3.13/site-packages/reportlab/lib/extformat.py new file mode 100644 index 0000000000000000000000000000000000000000..5c149e1b862d9d9bc4fe2e40ec3eae5df726dc0a --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/extformat.py @@ -0,0 +1,91 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +__version__='3.3.0' +__doc__='''Apparently not used anywhere, purpose unknown!''' +try: + from tokenize import tokenprog +except ImportError: + from tokenize import Token + import re + tokenprog = re.compile(Token) + del Token, re +import sys + +def _matchorfail(text, pos): + match = tokenprog.match(text, pos) + if match is None: raise ValueError(text, pos) + return match, match.end() + +''' + Extended dictionary formatting + We allow expressions in the parentheses instead of + just a simple variable. +''' +def dictformat(_format, L={}, G={}): + format = _format + + S = {} + chunks = [] + pos = 0 + n = 0 + + while 1: + pc = format.find("%", pos) + if pc < 0: break + nextchar = format[pc+1] + + if nextchar == "(": + chunks.append(format[pos:pc]) + pos, level = pc+2, 1 + while level: + match, pos = _matchorfail(format, pos) + tstart, tend = match.regs[3] + token = format[tstart:tend] + if token == "(": level = level+1 + elif token == ")": level = level-1 + vname = '__superformat_%d' % n + n += 1 + S[vname] = eval(format[pc+2:pos-1],G,L) + chunks.append('%%(%s)' % vname) + else: + nc = pc+1+(nextchar=="%") + chunks.append(format[pos:nc]) + pos = nc + + if pos < len(format): chunks.append(format[pos:]) + return (''.join(chunks)) % S + +def magicformat(format): + """Evaluate and substitute the appropriate parts of the string.""" + frame = sys._getframe(1) + return dictformat(format,frame.f_locals, frame.f_globals) + +if __name__=='__main__': + from reportlab.lib.formatters import DecimalFormatter + _DF={} + def df(n,dp=2,ds='.',ts=','): + try: + _df = _DF[dp,ds] + except KeyError: + _df = _DF[dp,ds] = DecimalFormatter(places=dp,decimalSep=ds,thousandSep=ts) + return _df(n) + + from reportlab.lib.extformat import magicformat + + Z={'abc': ('ab','c')} + x = 300000.23 + percent=79.2 + class dingo: + a=3 + print((magicformat(''' +$%%(df(x,dp=3))s --> $%(df(x,dp=3))s +$%%(df(x,dp=2,ds=',',ts='.'))s --> $%(df(x,dp=2,ds=',',ts='.'))s +%%(percent).2f%%%% --> %(percent).2f%% +%%(dingo.a)s --> %(dingo.a)s +%%(Z['abc'][0])s --> %(Z['abc'][0])s +'''))) + def func0(aa=1): + def func1(bb=2): + print((magicformat('bb=%(bb)s Z=%(Z)r'))) + func1('BB') + func0('AA') diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/fontfinder.py b/.venv/lib/python3.13/site-packages/reportlab/lib/fontfinder.py new file mode 100644 index 0000000000000000000000000000000000000000..ceef67c9878b71f1deefd7a2c29a75f5bc144de5 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/fontfinder.py @@ -0,0 +1,360 @@ +#Copyright ReportLab Europe Ltd. 2000-2019 +#see license.txt for license details +__version__='3.4.22' + +#modification of users/robin/ttflist.py. +__doc__="""This provides some general-purpose tools for finding fonts. + +The FontFinder object can search for font files. It aims to build +a catalogue of fonts which our framework can work with. It may be useful +if you are building GUIs or design-time interfaces and want to present users +with a choice of fonts. + +There are 3 steps to using it +1. create FontFinder and set options and directories +2. search +3. query + +>>> import fontfinder +>>> ff = fontfinder.FontFinder() +>>> ff.addDirectories([dir1, dir2, dir3]) +>>> ff.search() +>>> ff.getFamilyNames() #or whichever queries you want... + +Because the disk search takes some time to find and parse hundreds of fonts, +it can use a cache to store a file with all fonts found. The cache file name + +For each font found, it creates a structure with +- the short font name +- the long font name +- the principal file (.pfb for type 1 fonts), and the metrics file if appropriate +- the time modified (unix time stamp) +- a type code ('ttf') +- the family name +- bold and italic attributes + +One common use is to display families in a dialog for end users; +then select regular, bold and italic variants of the font. To get +the initial list, use getFamilyNames; these will be in alpha order. + +>>> ff.getFamilyNames() +['Bitstream Vera Sans', 'Century Schoolbook L', 'Dingbats', 'LettErrorRobot', +'MS Gothic', 'MS Mincho', 'Nimbus Mono L', 'Nimbus Roman No9 L', +'Nimbus Sans L', 'Vera', 'Standard Symbols L', +'URW Bookman L', 'URW Chancery L', 'URW Gothic L', 'URW Palladio L'] + +One can then obtain a specific font as follows + +>>> f = ff.getFont('Bitstream Vera Sans', bold=False, italic=True) +>>> f.fullName +'Bitstream Vera Sans' +>>> f.fileName +'C:\\code\\reportlab\\fonts\\Vera.ttf' +>>> + +It can also produce an XML report of fonts found by family, for the benefit +of non-Python applications. + +Future plans might include using this to auto-register fonts; and making it +update itself smartly on repeated instantiation. +""" +import sys, os, pickle +from hashlib import md5 +from xml.sax.saxutils import quoteattr +from time import process_time as clock +from reportlab.lib.utils import asBytes, asNative as _asNative + +def asNative(s): + try: + return _asNative(s) + except: + return _asNative(s,enc='latin-1') + +EXTENSIONS = ['.ttf','.ttc','.otf','.pfb','.pfa'] + +# PDF font flags (see PDF Reference Guide table 5.19) +FF_FIXED = 1 << 1-1 +FF_SERIF = 1 << 2-1 +FF_SYMBOLIC = 1 << 3-1 +FF_SCRIPT = 1 << 4-1 +FF_NONSYMBOLIC = 1 << 6-1 +FF_ITALIC = 1 << 7-1 +FF_ALLCAP = 1 << 17-1 +FF_SMALLCAP = 1 << 18-1 +FF_FORCEBOLD = 1 << 19-1 + +class FontDescriptor: + """This is a short descriptive record about a font. + + typeCode should be a file extension e.g. ['ttf','ttc','otf','pfb','pfa'] + """ + def __init__(self): + self.name = None + self.fullName = None + self.familyName = None + self.styleName = None + self.isBold = False #true if it's somehow bold + self.isItalic = False #true if it's italic or oblique or somehow slanty + self.isFixedPitch = False + self.isSymbolic = False #false for Dingbats, Symbols etc. + + self.typeCode = None #normally the extension minus the dot + self.fileName = None #full path to where we found it. + self.metricsFileName = None #defined only for type='type1pc', or 'type1mac' + + self.timeModified = 0 + + def __repr__(self): + return "FontDescriptor(%s)" % self.name + + def getTag(self): + "Return an XML tag representation" + attrs = [] + for k, v in self.__dict__.items(): + if k not in ['timeModified']: + if v: + attrs.append('%s=%s' % (k, quoteattr(str(v)))) + return '' + +from reportlab.lib.utils import rl_isdir, rl_isfile, rl_listdir, rl_getmtime +class FontFinder: + def __init__(self, dirs=[], useCache=True, validate=False, recur=False, fsEncoding=None, verbose=0): + self.useCache = useCache + self.validate = validate + if fsEncoding is None: + fsEncoding = sys.getfilesystemencoding() + self._fsEncoding = fsEncoding or 'utf8' + + self._dirs = set() + self._recur = recur + self.addDirectories(dirs) + self._fonts = [] + + self._skippedFiles = [] #list of filenames we did not handle + self._badFiles = [] #list of filenames we rejected + + self._fontsByName = {} + self._fontsByFamily = {} + self._fontsByFamilyBoldItalic = {} #indexed by bold, italic + self.verbose = verbose + + def addDirectory(self, dirName, recur=None): + #aesthetics - if there are 2 copies of a font, should the first or last + #be picked up? might need reversing + if rl_isdir(dirName): + self._dirs.add(dirName) + if recur if recur is not None else self._recur: + for r,D,F in os.walk(dirName): + for d in D: + self._dirs.add(os.path.join(r,d)) + + def addDirectories(self, dirNames,recur=None): + for dirName in dirNames: + self.addDirectory(dirName,recur=recur) + + def getFamilyNames(self): + "Returns a list of the distinct font families found" + if not self._fontsByFamily: + fonts = self._fonts + for font in fonts: + fam = font.familyName + if fam is None: continue + if fam in self._fontsByFamily: + self._fontsByFamily[fam].append(font) + else: + self._fontsByFamily[fam] = [font] + fsEncoding = self._fsEncoding + names = list(asBytes(_,enc=fsEncoding) for _ in self._fontsByFamily.keys()) + names.sort() + return names + + def getFontsInFamily(self, familyName): + "Return list of all font objects with this family name" + return self._fontsByFamily.get(familyName,[]) + + def getFamilyXmlReport(self): + """Reports on all families found as XML. + """ + lines = [] + lines.append('') + lines.append("") + for dirName in self._dirs: + lines.append(" " % quoteattr(asNative(dirName))) + for familyName in self.getFamilyNames(): + if familyName: #skip null case + lines.append(' ' % quoteattr(asNative(familyName))) + for font in self.getFontsInFamily(familyName): + lines.append(' ' + font.getTag()) + lines.append(' ') + lines.append("") + return '\n'.join(lines) + + def getFontsWithAttributes(self, **kwds): + """This is a general lightweight search.""" + selected = [] + for font in self._fonts: + OK = True + for k, v in kwds.items(): + if getattr(font, k, None) != v: + OK = False + if OK: + selected.append(font) + return selected + + def getFont(self, familyName, bold=False, italic=False): + """Try to find a font matching the spec""" + + for font in self._fonts: + if font.familyName == familyName: + if font.isBold == bold: + if font.isItalic == italic: + return font + + raise KeyError("Cannot find font %s with bold=%s, italic=%s" % (familyName, bold, italic)) + + def _getCacheFileName(self): + """Base this on the directories...same set of directories + should give same cache""" + fsEncoding = self._fsEncoding + hash = md5(b''.join(asBytes(_,enc=fsEncoding) for _ in sorted(self._dirs)),usedforsecurity=False).hexdigest() + from reportlab.lib.utils import get_rl_tempfile + fn = get_rl_tempfile('fonts_%s.dat' % hash) + return fn + + def save(self, fileName): + f = open(fileName, 'wb') + pickle.dump(self, f) + f.close() + + def load(self, fileName): + f = open(fileName, 'rb') + finder2 = pickle.load(f) + f.close() + self.__dict__.update(finder2.__dict__) + + def search(self): + if self.verbose: + started = clock() + if not self._dirs: + raise ValueError("Font search path is empty! Please specify search directories using addDirectory or addDirectories") + + if self.useCache: + cfn = self._getCacheFileName() + if rl_isfile(cfn): + try: + self.load(cfn) + if self.verbose>=3: + print("loaded cached file with %d fonts (%s)" % (len(self._fonts), cfn)) + return + except: + pass #pickle load failed. Ho hum, maybe it's an old pickle. Better rebuild it. + + for dirName in self._dirs: + try: + fileNames = rl_listdir(dirName) + except: + continue + for fileName in fileNames: + root, ext = os.path.splitext(fileName) + if ext.lower() in EXTENSIONS: + #it's a font + f = FontDescriptor() + f.fileName = fileName = os.path.normpath(os.path.join(dirName, fileName)) + try: + f.timeModified = rl_getmtime(fileName) + except: + self._skippedFiles.append(fileName) + continue + + ext = ext.lower() + if ext[0] == '.': + ext = ext[1:] + f.typeCode = ext #strip the dot + + #what to do depends on type. We only accept .pfb if we + #have .afm to go with it, and don't handle .otf now. + + if ext in ('otf', 'pfa'): + self._skippedFiles.append(fileName) + + elif ext in ('ttf','ttc'): + #parsing should check it for us + from reportlab.pdfbase.ttfonts import TTFontFile, TTFError + try: + font = TTFontFile(fileName,validate=self.validate) + except TTFError: + self._badFiles.append(fileName) + continue + f.name = font.name + f.fullName = font.fullName + f.styleName = font.styleName + f.familyName = font.familyName + f.isBold = (FF_FORCEBOLD == FF_FORCEBOLD & font.flags) + f.isItalic = (FF_ITALIC == FF_ITALIC & font.flags) + + elif ext == 'pfb': + + # type 1; we need an AFM file or have to skip. + if rl_isfile(os.path.join(dirName, root + '.afm')): + f.metricsFileName = os.path.normpath(os.path.join(dirName, root + '.afm')) + elif rl_isfile(os.path.join(dirName, root + '.AFM')): + f.metricsFileName = os.path.normpath(os.path.join(dirName, root + '.AFM')) + else: + self._skippedFiles.append(fileName) + continue + from reportlab.pdfbase.pdfmetrics import parseAFMFile + + (info, glyphs) = parseAFMFile(f.metricsFileName) + f.name = info['FontName'] + f.fullName = info.get('FullName', f.name) + f.familyName = info.get('FamilyName', None) + f.isItalic = (float(info.get('ItalicAngle', 0)) > 0.0) + #if the weight has the word bold, deem it bold + f.isBold = ('bold' in info.get('Weight','').lower()) + + self._fonts.append(f) + if self.useCache: + self.save(cfn) + + if self.verbose: + finished = clock() + print("found %d fonts; skipped %d; bad %d. Took %0.2f seconds" % ( + len(self._fonts), len(self._skippedFiles), len(self._badFiles), + finished - started + )) + +def test(): + #windows-centric test maybe + from reportlab import rl_config + ff = FontFinder(verbose=rl_config.verbose) + ff.useCache = True + ff.validate = True + + import reportlab + ff.addDirectory('C:\\windows\\fonts') + rlFontDir = os.path.join(os.path.dirname(reportlab.__file__), 'fonts') + ff.addDirectory(rlFontDir) + ff.search() + + print('cache file name...') + print(ff._getCacheFileName()) + + print('families...') + for familyName in ff.getFamilyNames(): + print('\t%s' % familyName) + + print() + outw = sys.stdout.write + outw('fonts called Vera:') + for font in ff.getFontsInFamily('Bitstream Vera Sans'): + outw(' %s' % font.name) + print() + outw('Bold fonts\n\t') + for font in ff.getFontsWithAttributes(isBold=True, isItalic=False): + outw(font.fullName+' ') + print() + print('family report') + print(ff.getFamilyXmlReport()) + +if __name__=='__main__': + test() diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/fonts.py b/.venv/lib/python3.13/site-packages/reportlab/lib/fonts.py new file mode 100644 index 0000000000000000000000000000000000000000..144548f3163647978ccd8277734bfb4d33561474 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/fonts.py @@ -0,0 +1,96 @@ +#!/bin/env python +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/fonts.py +__version__='3.3.0' +__doc__='''Utilities to associate bold and italic versions of fonts into families + +Bold, italic and plain fonts are usually implemented in separate disk files; +but non-trivial apps want this to do the right thing. We therefore +need to keep 'mappings' between the font family name and the right group +of up to 4 implementation fonts to use. + +Most font-handling code lives in pdfbase, and this probably should too. + +''' +############################################################################### +# A place to put useful font stuff +############################################################################### +# +# Font Mappings +# The brute force approach to finding the correct postscript font name; +# much safer than the rule-based ones we tried. +# preprocessor to reduce font face names to the shortest list +# possible. Add any aliases you wish; it keeps looking up +# until it finds no more translations to do. Any input +# will be lowercased before checking. +_family_alias = { + 'serif':'times', + 'sansserif':'helvetica', + 'monospaced':'courier', + 'arial':'helvetica' + } +#maps a piddle font to a postscript one. +_tt2ps_map = { + #face, bold, italic -> ps name + ('times', 0, 0) :'Times-Roman', + ('times', 1, 0) :'Times-Bold', + ('times', 0, 1) :'Times-Italic', + ('times', 1, 1) :'Times-BoldItalic', + + ('courier', 0, 0) :'Courier', + ('courier', 1, 0) :'Courier-Bold', + ('courier', 0, 1) :'Courier-Oblique', + ('courier', 1, 1) :'Courier-BoldOblique', + + ('helvetica', 0, 0) :'Helvetica', + ('helvetica', 1, 0) :'Helvetica-Bold', + ('helvetica', 0, 1) :'Helvetica-Oblique', + ('helvetica', 1, 1) :'Helvetica-BoldOblique', + + # there is only one Symbol font + ('symbol', 0, 0) :'Symbol', + ('symbol', 1, 0) :'Symbol', + ('symbol', 0, 1) :'Symbol', + ('symbol', 1, 1) :'Symbol', + + # ditto for dingbats + ('zapfdingbats', 0, 0) :'ZapfDingbats', + ('zapfdingbats', 1, 0) :'ZapfDingbats', + ('zapfdingbats', 0, 1) :'ZapfDingbats', + ('zapfdingbats', 1, 1) :'ZapfDingbats', + } + +_ps2tt_map={} +for k in sorted(_tt2ps_map.keys()): + v = _tt2ps_map[k].lower() + if v not in _ps2tt_map: + _ps2tt_map[v] = k + v = k[0].lower() + if v not in _ps2tt_map: + _ps2tt_map[v] = k + +def ps2tt(psfn): + 'ps fontname to family name, bold, italic' + psfn = psfn.lower() + if psfn in _ps2tt_map: + return _ps2tt_map[psfn] + raise ValueError("Can't map determine family/bold/italic for %s" % psfn) + +def tt2ps(fn,b,i): + 'family name + bold & italic to ps font name' + K = (fn.lower(),b,i) + if K in _tt2ps_map: + return _tt2ps_map[K] + else: + fn, b1, i1 = ps2tt(K[0]) + K = fn, b1|b, i1|i + if K in _tt2ps_map: + return _tt2ps_map[K] + raise ValueError("Can't find concrete font for family=%s, bold=%d, italic=%d" % (fn, b, i)) + +def addMapping(face, bold, italic, psname): + 'allow a custom font to be put in the mapping' + k = face.lower(), bold, italic + _tt2ps_map[k] = psname + _ps2tt_map[psname.lower()] = k diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/formatters.py b/.venv/lib/python3.13/site-packages/reportlab/lib/formatters.py new file mode 100644 index 0000000000000000000000000000000000000000..459ce4e653fce0b0eca4e4166500c6f745a03f6a --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/formatters.py @@ -0,0 +1,109 @@ +#!/bin/env python +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/formatters.py +__all__=('Formatter','DecimalFormatter') +__version__='3.3.0' +__doc__=""" +These help format numbers and dates in a user friendly way. +Used by the graphics framework. +""" +import re + +class Formatter: + "Base formatter - simply applies python format strings" + def __init__(self, pattern): + self.pattern = pattern + def format(self, obj): + return self.pattern % obj + def __repr__(self): + return "%s('%s')" % (self.__class__.__name__, self.pattern) + def __call__(self, x): + return self.format(x) + + +_ld_re=re.compile(r'^\d*\.') +_tz_re=re.compile('0+$') +class DecimalFormatter(Formatter): + """lets you specify how to build a decimal. + + A future NumberFormatter class will take Microsoft-style patterns + instead - "$#,##0.00" is WAY easier than this.""" + def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): + if places=='auto': + self.calcPlaces = self._calcPlaces + else: + self.places = places + self.dot = decimalSep + self.comma = thousandSep + self.prefix = prefix + self.suffix = suffix + + def _calcPlaces(self,V): + '''called with the full set of values to be formatted so we can calculate places''' + self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) + + def format(self, num): + # positivize the numbers + sign=num<0 + if sign: + num = -num + places, sep = self.places, self.dot + strip = places<=0 + if places and strip: places = -places + strInt = ('%.' + str(places) + 'f') % num + if places: + strInt, strFrac = strInt.split('.') + strFrac = sep + strFrac + if strip: + while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] + else: + strFrac = '' + + if self.comma is not None: + strNew = '' + while strInt: + left, right = strInt[0:-3], strInt[-3:] + if left == '': + #strNew = self.comma + right + strNew + strNew = right + strNew + else: + strNew = self.comma + right + strNew + strInt = left + strInt = strNew + + strBody = strInt + strFrac + if sign: strBody = '-' + strBody + if self.prefix: + strBody = self.prefix + strBody + if self.suffix: + strBody = strBody + self.suffix + return strBody + + def __repr__(self): + return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( + self.__class__.__name__, + self.places, + repr(self.dot), + repr(self.comma), + repr(self.prefix), + repr(self.suffix) + ) + +if __name__=='__main__': + def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): + f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) + r = f(n) + print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) + t(1000.9,'1,000.9',1,thousandSep=',') + t(1000.95,'1,001.0',1,thousandSep=',') + t(1000.95,'1,001',-1,thousandSep=',') + t(1000.9,'1,001',0,thousandSep=',') + t(1000.9,'1000.9',1) + t(1000.95,'1001.0',1) + t(1000.95,'1001',-1) + t(1000.9,'1001',0) + t(1000.1,'1000.1',1) + t(1000.55,'1000.6',1) + t(1000.449,'1000.4',-1) + t(1000.45,'1000',0) diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/geomutils.py b/.venv/lib/python3.13/site-packages/reportlab/lib/geomutils.py new file mode 100644 index 0000000000000000000000000000000000000000..4efbfa2f0497975a1418d06b368147d866e3745b --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/geomutils.py @@ -0,0 +1,33 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +__version__='3.3.0' +__doc__='''Utility functions for geometrical operations.''' + +def normalizeTRBL(p): + ''' + Useful for interpreting short descriptions of paddings, borders, margin, etc. + Expects a single value or a tuple of length 1 to 4. + Returns a tuple representing (clockwise) the value(s) applied to the 4 sides of a rectangle: + If a single value is given, that value is applied to all four sides. + If two or three values are given, the missing values are taken from the opposite side(s). + If four values are given they are returned unchanged. + + >>> normalizeTRBL(1) + (1, 1, 1, 1) + >>> normalizeTRBL((1, 1.2)) + (1, 1.2, 1, 1.2) + >>> normalizeTRBL((1, 1.2, 0)) + (1, 1.2, 0, 1.2) + >>> normalizeTRBL((1, 1.2, 0, 8)) + (1, 1.2, 0, 8) + ''' + if not isinstance(p, (tuple, list)): + return (p,)*4 + else: + l = len(p) + + if l==1: return (p[0],)*4 + + if l < 1 or l > 4: + raise ValueError('normalizeTRBL needs between 1 and 4 values but got %d.' % l) + return tuple(p) + tuple([ p[i-2] for i in range(l, 4) ]) diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/logger.py b/.venv/lib/python3.13/site-packages/reportlab/lib/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..04f11737db26e77cf5eec5adc3c07c02df2f7d79 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/logger.py @@ -0,0 +1,61 @@ +#!/bin/env python +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/logger.py +__version__='3.3.0' +__doc__="Logging and warning framework, predating Python's logging package" +from sys import stderr +class Logger: + ''' + An extended file type thing initially equivalent to sys.stderr + You can add/remove file type things; it has a write method + ''' + def __init__(self): + self._fps = [stderr] + self._fns = {} + + def add(self,fp): + '''add the file/string fp to the destinations''' + if isinstance(fp,str): + if fp in self._fns: return + fp = open(fn,'wb') + self._fns[fn] = fp + self._fps.append(fp) + + def remove(self,fp): + '''remove the file/string fp from the destinations''' + if isinstance(fp,str): + if fp not in self._fns: return + fn = fp + fp = self._fns[fn] + del self.fns[fn] + if fp in self._fps: + del self._fps[self._fps.index(fp)] + + def write(self,text): + '''write text to all the destinations''' + if text[-1]!='\n': text=text+'\n' + for fp in self._fps: fp.write(text) + + def __call__(self,text): + self.write(text) + +logger=Logger() + +class WarnOnce: + + def __init__(self,kind='Warn'): + self.uttered = {} + self.pfx = '%s: '%kind + self.enabled = 1 + + def once(self,warning): + if warning not in self.uttered: + if self.enabled: logger.write(self.pfx + warning) + self.uttered[warning] = 1 + + def __call__(self,warning): + self.once(warning) + +warnOnce=WarnOnce() +infoOnce=WarnOnce('Info') diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/normalDate.py b/.venv/lib/python3.13/site-packages/reportlab/lib/normalDate.py new file mode 100644 index 0000000000000000000000000000000000000000..cfca9f101796ca2b58f0f448cd370aaee7b00ecd --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/normalDate.py @@ -0,0 +1,656 @@ +#!/usr/bin/env python +# normalDate.py - version 1.0 - 20000717 +#hacked by Robin Becker 10/Apr/2001 +#major changes include +# using Types instead of type(0) etc +# BusinessDate class +# __radd__, __rsub__ methods +# formatMS stuff + +# derived from an original version created +# by Jeff Bauer of Rubicon Research and used +# with his kind permission +__version__='3.3.18' +__doc__="Jeff Bauer's lightweight date class, extended by us. Predates Python's datetime module." + +_bigBangScalar = -4345732 # based on (-9999, 1, 1) BC/BCE minimum +_bigCrunchScalar = 2958463 # based on (9999,12,31) AD/CE maximum +_daysInMonthNormal = [31,28,31,30,31,30,31,31,30,31,30,31] +_daysInMonthLeapYear = [31,29,31,30,31,30,31,31,30,31,30,31] +_dayOfWeekName = '''Monday Tuesday Wednesday Thursday Friday Saturday Sunday''' +_dayOfWeekNameLower = _dayOfWeekName.lower().split() +_dayOfWeekName = _dayOfWeekName.split() +_monthName = '''January February March April May June + July August September October November December''' +_monthNameLower = _monthName.lower().split() +_monthName = _monthName.split() + +import re, time, datetime +from .utils import isStr + +if hasattr(time,'struct_time'): + _DateSeqTypes = (list,tuple,time.struct_time) +else: + _DateSeqTypes = (list,tuple) + +_fmtPat = re.compile('\\{(m{1,5}|yyyy|yy|d{1,4})\\}',re.MULTILINE|re.IGNORECASE) +_iso_re = re.compile(r'(\d\d\d\d|\d\d)-(\d\d)-(\d\d)') + +def getStdMonthNames(): + return _monthNameLower + +def getStdShortMonthNames(): + return [x[:3] for x in getStdMonthNames()] + +def getStdDayNames(): + return _dayOfWeekNameLower + +def getStdShortDayNames(): + return [x[:3] for x in getStdDayNames()] + +def isLeapYear(year): + """determine if specified year is leap year, returns Python boolean""" + if year < 1600: + if year % 4: + return 0 + else: + return 1 + elif year % 4 != 0: + return 0 + elif year % 100 != 0: + return 1 + elif year % 400 != 0: + return 0 + else: + return 1 + +class NormalDateException(Exception): + """Exception class for NormalDate""" + pass + +class NormalDate: + """ + NormalDate is a specialized class to handle dates without + all the excess baggage (time zones, daylight savings, leap + seconds, etc.) of other date structures. The minimalist + strategy greatly simplifies its implementation and use. + + Internally, NormalDate is stored as an integer with values + in a discontinuous range of -99990101 to 99991231. The + integer value is used principally for storage and to simplify + the user interface. Internal calculations are performed by + a scalar based on Jan 1, 1900. + + Valid NormalDate ranges include (-9999,1,1) B.C.E. through + (9999,12,31) C.E./A.D. + + + 1.0 + No changes, except the version number. After 3 years of use by + various parties I think we can consider it stable. + + 0.8 + Added Prof. Stephen Walton's suggestion for a range method + - module author resisted the temptation to use lambda <0.5 wink> + + 0.7 + Added Dan Winkler's suggestions for __add__, __sub__ methods + + 0.6 + Modifications suggested by Kevin Digweed to fix: + - dayOfWeek, dayOfWeekAbbrev, clone methods + - Permit NormalDate to be a better behaved superclass + + 0.5 + Minor tweaking + + 0.4 + - Added methods __cmp__, __hash__ + - Added Epoch variable, scoped to the module + - Added setDay, setMonth, setYear methods + + 0.3 + Minor touch-ups + + 0.2 + - Fixed bug for certain B.C.E leap years + - Added Jim Fulton's suggestions for short alias class name =ND + and __getstate__, __setstate__ methods + + Special thanks: Roedy Green + """ + def __init__(self, normalDate=None): + """ + Accept 1 of 4 values to initialize a NormalDate: + 1. None - creates a NormalDate for the current day + 2. integer in yyyymmdd format + 3. string in yyyymmdd format + 4. tuple in (yyyy, mm, dd) - localtime/gmtime can also be used + 5. string iso date format see _iso_re above + 6. datetime.datetime or datetime.date + """ + if normalDate is None: + self.setNormalDate(time.localtime(time.time())) + else: + self.setNormalDate(normalDate) + + def add(self, days): + """add days to date; use negative integers to subtract""" + if not isinstance(days,int): + raise NormalDateException( \ + 'add method parameter must be integer type') + self.normalize(self.scalar() + days) + + def __add__(self, days): + """add integer to normalDate and return a new, calculated value""" + if not isinstance(days,int): + raise NormalDateException( \ + '__add__ parameter must be integer type') + cloned = self.clone() + cloned.add(days) + return cloned + + def __radd__(self,days): + '''for completeness''' + return self.__add__(days) + + def clone(self): + """return a cloned instance of this normalDate""" + return self.__class__(self.normalDate) + + def __lt__(self,other): + if not hasattr(other,'normalDate'): + return False + return self.normalDate < other.normalDate + + def __le__(self,other): + if not hasattr(other,'normalDate'): + return False + return self.normalDate <= other.normalDate + + def __eq__(self,other): + if not hasattr(other,'normalDate'): + return False + return self.normalDate == other.normalDate + + def __ne__(self,other): + if not hasattr(other,'normalDate'): + return True + return self.normalDate != other.normalDate + + def __ge__(self,other): + if not hasattr(other,'normalDate'): + return True + return self.normalDate >= other.normalDate + + def __gt__(self,other): + if not hasattr(other,'normalDate'): + return True + return self.normalDate > other.normalDate + + def day(self): + """return the day as integer 1-31""" + return int(repr(self.normalDate)[-2:]) + + def dayOfWeek(self): + """return integer representing day of week, Mon=0, Tue=1, etc.""" + return dayOfWeek(*self.toTuple()) + + @property + def __day_of_week_name__(self): + return getattr(self,'_dayOfWeekName',_dayOfWeekName) + + def dayOfWeekAbbrev(self): + """return day of week abbreviation for current date: Mon, Tue, etc.""" + return self.__day_of_week_name__[self.dayOfWeek()][:3] + + def dayOfWeekName(self): + """return day of week name for current date: Monday, Tuesday, etc.""" + return self.__day_of_week_name__[self.dayOfWeek()] + + def dayOfYear(self): + """day of year""" + if self.isLeapYear(): + daysByMonth = _daysInMonthLeapYear + else: + daysByMonth = _daysInMonthNormal + priorMonthDays = 0 + for m in range(self.month() - 1): + priorMonthDays = priorMonthDays + daysByMonth[m] + return self.day() + priorMonthDays + + def daysBetweenDates(self, normalDate): + """ + return value may be negative, since calculation is + self.scalar() - arg + """ + if isinstance(normalDate,NormalDate): + return self.scalar() - normalDate.scalar() + else: + return self.scalar() - NormalDate(normalDate).scalar() + + def equals(self, target): + if isinstance(target,NormalDate): + if target is None: + return self.normalDate is None + else: + return self.normalDate == target.normalDate + else: + return 0 + + def endOfMonth(self): + """returns (cloned) last day of month""" + return self.__class__(self.__repr__()[-8:-2]+str(self.lastDayOfMonth())) + + def firstDayOfMonth(self): + """returns (cloned) first day of month""" + return self.__class__(self.__repr__()[-8:-2]+"01") + + def formatUS(self): + """return date as string in common US format: MM/DD/YY""" + d = self.__repr__() + return "%s/%s/%s" % (d[-4:-2], d[-2:], d[-6:-4]) + + def formatUSCentury(self): + """return date as string in 4-digit year US format: MM/DD/YYYY""" + d = self.__repr__() + return "%s/%s/%s" % (d[-4:-2], d[-2:], d[-8:-4]) + + def _fmtM(self): + return str(self.month()) + + def _fmtMM(self): + return '%02d' % self.month() + + def _fmtMMM(self): + return self.monthAbbrev() + + def _fmtMMMM(self): + return self.monthName() + + def _fmtMMMMM(self): + return self.monthName()[0] + + def _fmtD(self): + return str(self.day()) + + def _fmtDD(self): + return '%02d' % self.day() + + def _fmtDDD(self): + return self.dayOfWeekAbbrev() + + def _fmtDDDD(self): + return self.dayOfWeekName() + + def _fmtYY(self): + return '%02d' % (self.year()%100) + + def _fmtYYYY(self): + return str(self.year()) + + def formatMS(self,fmt): + '''format like MS date using the notation + {YY} --> 2 digit year + {YYYY} --> 4 digit year + {M} --> month as digit + {MM} --> 2 digit month + {MMM} --> abbreviated month name + {MMMM} --> monthname + {MMMMM} --> first character of monthname + {D} --> day of month as digit + {DD} --> 2 digit day of month + {DDD} --> abrreviated weekday name + {DDDD} --> weekday name + ''' + r = fmt[:] + f = 0 + while 1: + m = _fmtPat.search(r,f) + if m: + y = getattr(self,'_fmt'+(m.group()[1:-1].upper()))() + i, j = m.span() + r = (r[0:i] + y) + r[j:] + f = i + len(y) + else: + return r + + def __getstate__(self): + """minimize persistent storage requirements""" + return self.normalDate + + def __hash__(self): + return hash(self.normalDate) + + def __int__(self): + return self.normalDate + + def isLeapYear(self): + """ + determine if specified year is leap year, returning true (1) or + false (0) + """ + return isLeapYear(self.year()) + + def _isValidNormalDate(self, normalDate): + """checks for date validity in [-]yyyymmdd format""" + if not isinstance(normalDate,int): + return 0 + if len(repr(normalDate)) > 9: + return 0 + if normalDate < 0: + dateStr = "%09d" % normalDate + else: + dateStr = "%08d" % normalDate + if len(dateStr) < 8: + return 0 + elif len(dateStr) == 9: + if (dateStr[0] != '-' and dateStr[0] != '+'): + return 0 + year = int(dateStr[:-4]) + if year < -9999 or year > 9999 or year == 0: + return 0 # note: zero (0) is not a valid year + month = int(dateStr[-4:-2]) + if month < 1 or month > 12: + return 0 + if isLeapYear(year): + maxDay = _daysInMonthLeapYear[month - 1] + else: + maxDay = _daysInMonthNormal[month - 1] + day = int(dateStr[-2:]) + if day < 1 or day > maxDay: + return 0 + if year == 1582 and month == 10 and day > 4 and day < 15: + return 0 # special case of 10 days dropped: Oct 5-14, 1582 + return 1 + + def lastDayOfMonth(self): + """returns last day of the month as integer 28-31""" + if self.isLeapYear(): + return _daysInMonthLeapYear[self.month() - 1] + else: + return _daysInMonthNormal[self.month() - 1] + + def localeFormat(self): + """override this method to use your preferred locale format""" + return self.formatUS() + + def month(self): + """returns month as integer 1-12""" + return int(repr(self.normalDate)[-4:-2]) + + @property + def __month_name__(self): + return getattr(self,'_monthName',_monthName) + + def monthAbbrev(self): + """returns month as a 3-character abbreviation, i.e. Jan, Feb, etc.""" + return self.__month_name__[self.month() - 1][:3] + + def monthName(self): + """returns month name, i.e. January, February, etc.""" + return self.__month_name__[self.month() - 1] + + def normalize(self, scalar): + """convert scalar to normalDate""" + if scalar < _bigBangScalar: + msg = "normalize(%d): scalar below minimum" % \ + _bigBangScalar + raise NormalDateException(msg) + if scalar > _bigCrunchScalar: + msg = "normalize(%d): scalar exceeds maximum" % \ + _bigCrunchScalar + raise NormalDateException(msg) + from math import floor + if scalar >= -115860: + year = 1600 + int(floor((scalar + 109573) / 365.2425)) + elif scalar >= -693597: + year = 4 + int(floor((scalar + 692502) / 365.2425)) + else: + year = -4 + int(floor((scalar + 695058) / 365.2425)) + days = scalar - firstDayOfYear(year) + 1 + if days <= 0: + year = year - 1 + days = scalar - firstDayOfYear(year) + 1 + daysInYear = 365 + if isLeapYear(year): + daysInYear = daysInYear + 1 + if days > daysInYear: + year = year + 1 + days = scalar - firstDayOfYear(year) + 1 + # add 10 days if between Oct 15, 1582 and Dec 31, 1582 + if (scalar >= -115860 and scalar <= -115783): + days = days + 10 + if isLeapYear(year): + daysByMonth = _daysInMonthLeapYear + else: + daysByMonth = _daysInMonthNormal + dc = 0; month = 12 + for m in range(len(daysByMonth)): + dc = dc + daysByMonth[m] + if dc >= days: + month = m + 1 + break + # add up the days in prior months + priorMonthDays = 0 + for m in range(month - 1): + priorMonthDays = priorMonthDays + daysByMonth[m] + day = days - priorMonthDays + self.setNormalDate((year, month, day)) + + def range(self, days): + """Return a range of normalDates as a list. Parameter + may be an int or normalDate.""" + if not isinstance(days,int): + days = days - self # if not int, assume arg is normalDate type + r = [] + for i in range(days): + r.append(self + i) + return r + + def __repr__(self): + """print format: [-]yyyymmdd""" + # Note: When disassembling a NormalDate string, be sure to + # count from the right, i.e. epochMonth = int(repr(Epoch)[-4:-2]), + # or the slice won't work for dates B.C. + if self.normalDate < 0: + return "%09d" % self.normalDate + else: + return "%08d" % self.normalDate + + def scalar(self): + """days since baseline date: Jan 1, 1900""" + (year, month, day) = self.toTuple() + days = firstDayOfYear(year) + day - 1 + if self.isLeapYear(): + for m in range(month - 1): + days = days + _daysInMonthLeapYear[m] + else: + for m in range(month - 1): + days = days + _daysInMonthNormal[m] + if year == 1582: + if month > 10 or (month == 10 and day > 4): + days = days - 10 + return days + + def setDay(self, day): + """set the day of the month""" + maxDay = self.lastDayOfMonth() + if day < 1 or day > maxDay: + msg = "day is outside of range 1 to %d" % maxDay + raise NormalDateException(msg) + (y, m, d) = self.toTuple() + self.setNormalDate((y, m, day)) + + def setMonth(self, month): + """set the month [1-12]""" + if month < 1 or month > 12: + raise NormalDateException('month is outside range 1 to 12') + (y, m, d) = self.toTuple() + self.setNormalDate((y, month, d)) + + def setNormalDate(self, normalDate): + """ + accepts date as scalar string/integer (yyyymmdd) or tuple + (year, month, day, ...)""" + if isinstance(normalDate,int): + self.normalDate = normalDate + elif isStr(normalDate): + try: + self.normalDate = int(normalDate) + except: + m = _iso_re.match(normalDate) + if m: + self.setNormalDate(m.group(1)+m.group(2)+m.group(3)) + else: + raise NormalDateException("unable to setNormalDate(%s)" % repr(normalDate)) + elif isinstance(normalDate,_DateSeqTypes): + self.normalDate = int("%04d%02d%02d" % normalDate[:3]) + elif isinstance(normalDate,NormalDate): + self.normalDate = normalDate.normalDate + elif isinstance(normalDate,(datetime.datetime,datetime.date)): + self.normalDate = (normalDate.year*100+normalDate.month)*100+normalDate.day + else: + self.normalDate = None + if not self._isValidNormalDate(self.normalDate): + raise NormalDateException("unable to setNormalDate(%s)" % repr(normalDate)) + + def setYear(self, year): + if year == 0: + raise NormalDateException('cannot set year to zero') + elif year < -9999: + raise NormalDateException('year cannot be less than -9999') + elif year > 9999: + raise NormalDateException('year cannot be greater than 9999') + (y, m, d) = self.toTuple() + self.setNormalDate((year, m, d)) + + __setstate__ = setNormalDate + + def __sub__(self, v): + if isinstance(v,int): + return self.__add__(-v) + return self.scalar() - v.scalar() + + def __rsub__(self,v): + if isinstance(v,int): + return NormalDate(v) - self + else: + return v.scalar() - self.scalar() + + def toTuple(self): + """return date as (year, month, day) tuple""" + return (self.year(), self.month(), self.day()) + + def year(self): + """return year in yyyy format, negative values indicate B.C.""" + return int(repr(self.normalDate)[:-4]) + +################# Utility functions ################# + +def bigBang(): + """return lower boundary as a NormalDate""" + return NormalDate((-9999, 1, 1)) + +def bigCrunch(): + """return upper boundary as a NormalDate""" + return NormalDate((9999, 12, 31)) + +def dayOfWeek(y, m, d): + """return integer representing day of week, Mon=0, Tue=1, etc.""" + if m == 1 or m == 2: + m = m + 12 + y = y - 1 + return (d + 2*m + 3*(m+1)//5 + y + y//4 - y//100 + y//400) % 7 + +def firstDayOfYear(year): + """number of days to the first of the year, relative to Jan 1, 1900""" + if not isinstance(year,int): + msg = "firstDayOfYear() expected integer, got %s" % type(year) + raise NormalDateException(msg) + if year == 0: + raise NormalDateException('first day of year cannot be zero (0)') + elif year < 0: # BCE calculation + firstDay = (year * 365) + int((year - 1) / 4) - 693596 + else: # CE calculation + leapAdjust = int((year + 3) / 4) + if year > 1600: + leapAdjust = leapAdjust - int((year + 99 - 1600) / 100) + \ + int((year + 399 - 1600) / 400) + firstDay = year * 365 + leapAdjust - 693963 + if year > 1582: + firstDay = firstDay - 10 + return firstDay + +def FND(d): + '''convert to ND if required''' + return isinstance(d,NormalDate) and d or ND(d) + +Epoch=bigBang() +ND=NormalDate +BDEpoch=ND(15821018) +BDEpochScalar = -115857 + +class BusinessDate(NormalDate): + """ + Specialised NormalDate + """ + def add(self, days): + """add days to date; use negative integers to subtract""" + if not isinstance(days,int): + raise NormalDateException('add method parameter must be integer') + self.normalize(self.scalar() + days) + + def __add__(self, days): + """add integer to BusinessDate and return a new, calculated value""" + if not isinstance(days,int): + raise NormalDateException('__add__ parameter must be integer') + cloned = self.clone() + cloned.add(days) + return cloned + + def __sub__(self, v): + return isinstance(v,int) and self.__add__(-v) or self.scalar() - v.scalar() + + def asNormalDate(self): + return ND(self.normalDate) + + def daysBetweenDates(self, normalDate): + return self.asNormalDate.daysBetweenDates(normalDate) + + def _checkDOW(self): + if self.dayOfWeek()>4: raise NormalDateException("%r isn't a business day" % self.normalDate) + + def normalize(self, i): + i = int(i) + NormalDate.normalize(self,(i//5)*7+i%5+BDEpochScalar) + + def scalar(self): + d = self.asNormalDate() + i = d - BDEpoch #luckily BDEpoch is a Monday so we don't have a problem + #concerning the relative weekday + return 5*(i//7) + i%7 + + def setNormalDate(self, normalDate): + NormalDate.setNormalDate(self,normalDate) + self._checkDOW() + +if __name__ == '__main__': + today = NormalDate() + print("NormalDate test:") + print(" Today (%s) is: %s %s" % (today, today.dayOfWeekAbbrev(), today.localeFormat())) + yesterday = today - 1 + print(" Yesterday was: %s %s" % (yesterday.dayOfWeekAbbrev(), yesterday.localeFormat())) + tomorrow = today + 1 + print(" Tomorrow will be: %s %s" % (tomorrow.dayOfWeekAbbrev(), tomorrow.localeFormat())) + print(" Days between tomorrow and yesterday: %d" % (tomorrow - yesterday)) + print(today.formatMS('{d}/{m}/{yy}')) + print(today.formatMS('{dd}/{m}/{yy}')) + print(today.formatMS('{ddd} {d}/{m}/{yy}')) + print(today.formatMS('{dddd} {d}/{m}/{yy}')) + print(today.formatMS('{d}/{mm}/{yy}')) + print(today.formatMS('{d}/{mmm}/{yy}')) + print(today.formatMS('{d}/{mmmm}/{yy}')) + print(today.formatMS('{d}/{m}/{yyyy}')) + b = BusinessDate('20010116') + print('b=',b,'b.scalar()', b.scalar()) diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/pagesizes.py b/.venv/lib/python3.13/site-packages/reportlab/lib/pagesizes.py new file mode 100644 index 0000000000000000000000000000000000000000..6a2d9a1874f627329d343235e569d9564177bc7d --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/pagesizes.py @@ -0,0 +1,84 @@ +#!/bin/env python +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/pagesizes.py + +"""This module defines a few common page sizes in points (1/72 inch). +To be expanded to include things like label sizes, envelope windows +etc.""" +__version__='3.4.18' + +from reportlab.lib.units import mm, inch + +#ISO 216 standard paer sizes; see eg https://en.wikipedia.org/wiki/ISO_216 +A0 = (841*mm,1189*mm) +A1 = (594*mm,841*mm) +A2 = (420*mm,594*mm) +A3 = (297*mm,420*mm) +A4 = (210*mm,297*mm) +A5 = (148*mm,210*mm) +A6 = (105*mm,148*mm) +A7 = (74*mm,105*mm) +A8 = (52*mm,74*mm) +A9 = (37*mm,52*mm) +A10 = (26*mm,37*mm) + +B0 = (1000*mm,1414*mm) +B1 = (707*mm,1000*mm) +B2 = (500*mm,707*mm) +B3 = (353*mm,500*mm) +B4 = (250*mm,353*mm) +B5 = (176*mm,250*mm) +B6 = (125*mm,176*mm) +B7 = (88*mm,125*mm) +B8 = (62*mm,88*mm) +B9 = (44*mm,62*mm) +B10 = (31*mm,44*mm) + +C0 = (917*mm,1297*mm) +C1 = (648*mm,917*mm) +C2 = (458*mm,648*mm) +C3 = (324*mm,458*mm) +C4 = (229*mm,324*mm) +C5 = (162*mm,229*mm) +C6 = (114*mm,162*mm) +C7 = (81*mm,114*mm) +C8 = (57*mm,81*mm) +C9 = (40*mm,57*mm) +C10 = (28*mm,40*mm) + +#American paper sizes +LETTER = (8.5*inch, 11*inch) +LEGAL = (8.5*inch, 14*inch) +ELEVENSEVENTEEN = (11*inch, 17*inch) + +# From https://en.wikipedia.org/wiki/Paper_size +JUNIOR_LEGAL = (5*inch, 8*inch) +HALF_LETTER = (5.5*inch, 8*inch) +GOV_LETTER = (8*inch, 10.5*inch) +GOV_LEGAL = (8.5*inch, 13*inch) +TABLOID = ELEVENSEVENTEEN +LEDGER = (17*inch, 11*inch) + +# lower case is deprecated as of 12/2001, but here +# for compatability +letter=LETTER +legal=LEGAL +elevenSeventeen = ELEVENSEVENTEEN + +#functions to mess with pagesizes +def landscape(pagesize): + """Use this to get page orientation right""" + a, b = pagesize + if a < b: + return (b, a) + else: + return (a, b) + +def portrait(pagesize): + """Use this to get page orientation right""" + a, b = pagesize + if a >= b: + return (b, a) + else: + return (a, b) diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/pdfencrypt.py b/.venv/lib/python3.13/site-packages/reportlab/lib/pdfencrypt.py new file mode 100644 index 0000000000000000000000000000000000000000..467bf47ff40575eaa04da55c29f4e35711419dec --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/pdfencrypt.py @@ -0,0 +1,776 @@ +#copyright ReportLab Europe Limited. 2000-2016 +#see license.txt for license details +__version__='3.3.0' + +"""helpers for pdf encryption/decryption""" +import sys, os +from binascii import hexlify, unhexlify +from hashlib import md5 +from io import BytesIO + +from reportlab.lib.utils import asBytes, int2Byte, rawBytes, asNative +from reportlab.pdfgen.canvas import Canvas +from reportlab.pdfbase.pdfdoc import PDFObject +from reportlab.platypus.flowables import Flowable +from reportlab import rl_config + +try: + import pyaes + from hashlib import sha256 +except ImportError: + pyaes = None + +def xorKey(num,key): + "xor's each byte of the key with the number, which is <256" + if num==0: return key + return bytes(num^k for k in key) + +#AR debug hooks - leaving in for now +CLOBBERID = 0 # set a constant Doc ID to allow comparison with other software like iText +CLOBBERPERMISSIONS = 0 +DEBUG = rl_config.debug # print stuff to trace calculations + +# permission bits +reserved1 = 1 # bit 1 must be 0 +reserved2 = 1<<1 # bit 2 must be 0 +printable = 1<<2 +modifiable = 1<<3 +copypastable = 1<<4 +annotatable = 1<<5 +# others [7..32] are reserved, must be 1 +higherbits = 0 +for i in range(6,31): + higherbits = higherbits | (1<\x99\x89i\xf7\xc4\xb4\'\xe9k\xc9\xfa\xa6p\x80\xcd\xaa\xaf|\x97\xf7\xcc \xc1\xef\xc7\x97\xd2;\xaf\xe1\xfc\x16,\xd3\x0b\x19\xa1\x02\xe6\x01\xcb\x1c\xd8\xe6\\H}\r\xdc\x85\xe1\xbc\xc4\x02>|\xc5\x97\xb5T\xad\x0cT\x95\xb1\xdc!\xb6+E#\xa1\xa4O\xf3j\x98"\xc2\x1a\xcb\x8cHB\xd8B~\xa7\x7f7\xd2\xe8\x131.\xd7\xa9\x0b\r\xdd2\x0b}\xc0\xffm\x9e3\xe2/\xea\x84W\x82\xbd\xc8K\xc2;?\xbe#\x84`W\xf3\xe0\xec\x9e\x85\x9c\xcb\xc7\xc9#\x19\xff\xde\x17\xea\xb2\xd4\x0e\x9a\xbd\xbaz\xbd\x87O\xd4\xf4\xac\xb3(z\x92\xfc\xbc\x85i\x8d\x1f\xfb!\t|w,\x8bI\xc9_D`A\xbc}\x0e+r\x1b-%F(@\xc8\\cL\x172(\x9c\x95BM\xa1\x89UG\x9d\xfd\xed\xce\xd8\x1f\xb1' + def os_urandom(n): + global _os_random_x + b = [_os_random_b[(i+_os_random_x)%256] for i in range(n)] + b = bytes(b) + _os_random_x = (_os_random_x + n) % 256 + return b +else: + os_urandom = os.urandom + +# no encryption +class StandardEncryption: + prepared = 0 + def __init__(self, userPassword, ownerPassword=None, canPrint=1, canModify=1, canCopy=1, canAnnotate=1, strength=None): + ''' + This class defines the encryption properties to be used while creating a pdf document. + Once initiated, a StandardEncryption object can be applied to a Canvas or a BaseDocTemplate. + The userPassword parameter sets the user password on the encrypted pdf. + The ownerPassword parameter sets the owner password on the encrypted pdf. + The boolean flags canPrint, canModify, canCopy, canAnnotate determine wether a user can + perform the corresponding actions on the pdf when only a user password has been supplied. + If the user supplies the owner password while opening the pdf, all actions can be performed regardless + of the flags. + Note that the security provided by these encryption settings (and even more so for the flags) is very weak. + ''' + self.userPassword = userPassword + if ownerPassword: + self.ownerPassword = ownerPassword + else: + self.ownerPassword = userPassword + if strength is None: + strength = rl_config.encryptionStrength + if strength == 40: + self.revision = 2 + elif strength == 128: + self.revision = 3 + elif strength == 256: + if not pyaes: + raise ValueError('strength==256 is not supported as package pyaes is not importable') + self.revision = 5 + else: + raise ValueError('Unknown encryption strength=%s' % repr(strength)) + self.canPrint = canPrint + self.canModify = canModify + self.canCopy = canCopy + self.canAnnotate = canAnnotate + self.O = self.U = self.P = self.key = self.OE = self.UE = self.Perms = None + def setAllPermissions(self, value): + self.canPrint = \ + self.canModify = \ + self.canCopy = \ + self.canAnnotate = value + def permissionBits(self): + p = 0 + if self.canPrint: p = p | printable + if self.canModify: p = p | modifiable + if self.canCopy: p = p | copypastable + if self.canAnnotate: p = p | annotatable + p = p | higherbits + return p + def encode(self, t): + "encode a string, stream, text" + if not self.prepared: + raise ValueError("encryption not prepared!") + if self.objnum is None: + raise ValueError("not registered in PDF object") + return encodePDF(self.key, self.objnum, self.version, t, revision=self.revision) + def prepare(self, document, overrideID=None): + # get ready to do encryption + if DEBUG>=10: print('StandardEncryption.prepare(...) - revision %d' % self.revision) + if self.prepared: + raise ValueError("encryption already prepared!") + # get the unescaped string value of the document id (first array element). + # we allow one to be passed in instead to permit reproducible tests + # of our algorithm, but in real life overrideID will always be None + if overrideID: + internalID = overrideID + else: + externalID = document.ID() # initialize it... + internalID = document.signature.digest() + #AR debugging + if CLOBBERID: + internalID = "xxxxxxxxxxxxxxxx" + + if DEBUG>=10: + print('userPassword = %r' % self.userPassword) + print('ownerPassword = %r' % self.ownerPassword) + print('internalID = %r' % internalID) + self.P = int(self.permissionBits() - 2**31) + if CLOBBERPERMISSIONS: self.P = -44 # AR hack + if DEBUG>=10: + print("self.P = %s" % repr(self.P)) + if self.revision == 5: + + # Init vectro for AES cipher (should be 16 bytes null array) + iv = b'\x00' * 16 + + # Random User salts + uvs = os_urandom(8) + uks = os_urandom(8) + + # the main encryption key + self.key = asBytes(os_urandom(32)) + + if DEBUG>=10: + print("uvs (hex) = %s" % hexText(uvs)) + print("uks (hex) = %s" % hexText(uks)) + print("self.key (hex) = %s" % hexText(self.key)) + + # Calculate the sha-256 hash of the User password (U) + md = sha256(asBytes(self.userPassword[:127]) + uvs) + self.U = md.digest() + uvs + uks + + if DEBUG>=10: + print("self.U (hex) = %s" % hexText(self.U)) + + # Calculate the User encryption key (UE) + md = sha256(asBytes(self.userPassword[:127]) + uks) + + encrypter = pyaes.Encrypter(pyaes.AESModeOfOperationCBC(md.digest(), iv=iv)) + self.UE = encrypter.feed(self.key) + self.UE += encrypter.feed() + + if DEBUG>=10: + print("self.UE (hex) = %s" % hexText(self.UE)) + + # Random Owner salts + ovs = os_urandom(8) + oks = os_urandom(8) + + # Calculate the hash of the Owner password (U) + md = sha256(asBytes(self.ownerPassword[:127]) + ovs + self.U ) + self.O = md.digest() + ovs + oks + + if DEBUG>=10: + print("self.O (hex) = %s" % hexText(self.O)) + + # Calculate the User encryption key (OE) + md = sha256(asBytes(self.ownerPassword[:127]) + oks + self.U) + + encrypter = pyaes.Encrypter(pyaes.AESModeOfOperationCBC(md.digest(), iv=iv)) + self.OE = encrypter.feed(self.key) + self.OE += encrypter.feed() + + if DEBUG>=10: + print("self.OE (hex) = %s" % hexText(self.OE)) + + # Compute permissions array + permsarr = [ + self.P & 0xFF, # store the permission value in the first 32-bits + self.P >> 8 & 0xFF, + self.P >> 16 & 0xFF, + self.P >> 24 & 0xFF, + 0xFF, + 0xFF, + 0xFF, + 0xFF, + ord('T'), # 'T' if EncryptMetaData is True (default), 'F' otherwise + ord('a'), # a, d, b are magic values + ord('d'), + ord('b'), + 0x01, # trailing zeros will be ignored + 0x01, + 0x01, + 0x01 + ] + + # the permission array should be enrypted in the Perms field + encrypter = pyaes.Encrypter(pyaes.AESModeOfOperationCBC(self.key, iv=iv)) + self.Perms = encrypter.feed(bytes(permsarr)) + self.Perms += encrypter.feed() + + if DEBUG>=10: + print("self.Perms (hex) = %s" % hexText(self.Perms)) + + elif self.revision in (2, 3): + self.O = computeO(self.userPassword, self.ownerPassword, self.revision) + + if DEBUG>=10: + print("self.O (as hex) = %s" % hexText(self.O)) + + #print "\nself.O", self.O, repr(self.O) + self.key = encryptionkey(self.userPassword, self.O, self.P, internalID, revision=self.revision) + if DEBUG>=10: + print("self.key (hex) = %s" % hexText(self.key)) + self.U = computeU(self.key, revision=self.revision, documentId=internalID) + if DEBUG>=10: + print("self.U (as hex) = %s" % hexText(self.U)) + + self.objnum = self.version = None + self.prepared = 1 + def register(self, objnum, version): + # enter a new direct object + if not self.prepared: + raise ValueError("encryption not prepared!") + self.objnum = objnum + self.version = version + def info(self): + # the representation of self in file if any (should be None or PDFDict) + if not self.prepared: + raise ValueError("encryption not prepared!") + return StandardEncryptionDictionary(O=self.O, OE=self.OE, U=self.U, UE=self.UE, P=self.P, Perms=self.Perms, revision=self.revision) + +class StandardEncryptionDictionary(PDFObject): + __RefOnly__ = 1 + def __init__(self, O, OE, U, UE, P, Perms, revision): + self.O, self.OE, self.U, self.UE, self.P, self.Perms = O, OE, U, UE, P, Perms + self.revision = revision + def format(self, document): + # use a dummy document to bypass encryption + from reportlab.pdfbase.pdfdoc import DummyDoc, PDFDictionary, PDFName + dummy = DummyDoc() + dict = {"Filter": PDFName("Standard"), + "O": hexText(self.O), + "U": hexText(self.U), + "P": self.P} + if self.revision == 5: + dict['Length'] = 256 + dict['R'] = 5 + dict['V'] = 5 + dict['O'] = hexText(self.O) + dict['U'] = hexText(self.U) + dict['OE'] = hexText(self.OE) + dict['UE'] = hexText(self.UE) + dict['Perms'] = hexText(self.Perms) + dict['StrF'] = PDFName("StdCF") + dict['StmF'] = PDFName("StdCF") + stdcf = { + "Length": 32, + "AuthEvent": PDFName("DocOpen"), + "CFM": PDFName("AESV3") + } + cf = { + "StdCF": PDFDictionary(stdcf) + } + + dict['CF'] = PDFDictionary(cf) + + elif self.revision == 3: + dict['Length'] = 128 + dict['R'] = 3 + dict['V'] = 2 + else: + dict['R'] = 2 + dict['V'] = 1 + pdfdict = PDFDictionary(dict) + return pdfdict.format(dummy) + +# from pdf spec +padding = """ +28 BF 4E 5E 4E 75 8A 41 64 00 4E 56 FF FA 01 08 +2E 2E 00 B6 D0 68 3E 80 2F 0C A9 FE 64 53 69 7A +""" + +def hexText(text): + "a legitimate way to show strings in PDF" + return '<%s>' % asNative(hexlify(rawBytes(text))).upper() + +def unHexText(hexText): + equalityCheck(hexText[0], '<', 'bad hex text') + equalityCheck(hexText[-1], '>', 'bad hex text') + return unhexlify(hexText[1:-1]) + +PadString = rawBytes(''.join(chr(int(c, 16)) for c in padding.strip().split())) + +def checkRevision(revision): + if revision is None: + strength = rl_config.encryptionStrength + if strength == 40: + revision = 2 + elif strength == 128: + revision = 3 + elif strength == 256: + if not pyaes: + raise ValueError('strength==256 is not supported as package pyaes is not importable') + revision = 5 + else: + raise ValueError('Unknown encryption strength=%s' % repr(strength)) + return revision + +def encryptionkey(password, OwnerKey, Permissions, FileId1, revision=None): + revision = checkRevision(revision) + # FileId1 is first string of the fileid array + # add padding string + #AR force same as iText example + #Permissions = -1836 #int(Permissions - 2**31) + password = asBytes(password) + PadString + # truncate to 32 bytes + password = password[:32] + # translate permissions to string, low order byte first + p = Permissions# + 2**32L + permissionsString = b"" + for i in range(4): + byte = (p & 0xff) # seems to match what iText does + p = p>>8 + permissionsString += int2Byte(byte % 256) + + hash = md5(asBytes(password)) + hash.update(asBytes(OwnerKey)) + hash.update(asBytes(permissionsString)) + hash.update(asBytes(FileId1)) + + md5output = hash.digest() + + if revision==2: + key = md5output[:5] + elif revision==3: #revision 3 algorithm - loop 50 times + for x in range(50): + md5output = md5(md5output).digest() + key = md5output[:16] + if DEBUG>=10: print('encryptionkey(%s,%s,%s,%s,%s)==>%s' % tuple([hexText(str(x)) for x in (password, OwnerKey, Permissions, FileId1, revision, key)])) + return key + +def computeO(userPassword, ownerPassword, revision): + from reportlab.lib.arciv import ArcIV + #print 'digest of hello is %s' % md5('hello').digest() + assert revision in (2,3), 'Unknown algorithm revision %s' % revision + if not ownerPassword: + ownerPassword = userPassword + + ownerPad = asBytes(ownerPassword) + PadString + ownerPad = ownerPad[0:32] + + password = asBytes(userPassword) + PadString + userPad = password[:32] + + digest = md5(ownerPad).digest() + if DEBUG>=10: print('PadString=%s\nownerPad=%s\npassword=%s\nuserPad=%s\ndigest=%s\nrevision=%s' % (ascii(PadString),ascii(ownerPad),ascii(password),ascii(userPad),ascii(digest),revision)) + if revision == 2: + O = ArcIV(digest[:5]).encode(userPad) + elif revision == 3: + for i in range(50): + digest = md5(digest).digest() + digest = digest[:16] + O = userPad + for i in range(20): + thisKey = xorKey(i, digest) + O = ArcIV(thisKey).encode(O) + if DEBUG>=10: print('computeO(%s,%s,%s)==>%s' % tuple([hexText(str(x)) for x in (userPassword, ownerPassword, revision,O)])) + return O + +def computeU(encryptionkey, encodestring=PadString,revision=None,documentId=None): + revision = checkRevision(revision) + from reportlab.lib.arciv import ArcIV + if revision == 2: + result = ArcIV(encryptionkey).encode(encodestring) + elif revision == 3: + assert documentId is not None, "Revision 3 algorithm needs the document ID!" + h = md5(PadString) + h.update(rawBytes(documentId)) + tmp = h.digest() + tmp = ArcIV(encryptionkey).encode(tmp) + for n in range(1,20): + thisKey = xorKey(n, encryptionkey) + tmp = ArcIV(thisKey).encode(tmp) + while len(tmp) < 32: + tmp += b'\0' + result = tmp + if DEBUG>=10: print('computeU(%s,%s,%s,%s)==>%s' % tuple([hexText(str(x)) for x in (encryptionkey, encodestring,revision,documentId,result)])) + return result + +def checkU(encryptionkey, U): + decoded = computeU(encryptionkey, U) + #print len(decoded), len(U), len(PadString) + if decoded!=PadString: + if len(decoded)!=len(PadString): + raise ValueError("lengths don't match! (password failed)") + raise ValueError("decode of U doesn't match fixed padstring (password failed)") + +def encodePDF(key, objectNumber, generationNumber, string, revision=None): + "Encodes a string or stream" + revision = checkRevision(revision) + #print 'encodePDF (%s, %d, %d, %s)' % (hexText(key), objectNumber, generationNumber, string) + # extend 3 bytes of the object Number, low byte first + if revision in (2,3): + newkey = key + n = objectNumber + for i in range(3): + newkey += int2Byte(n & 0xff) + n = n>>8 + # extend 2 bytes of the generationNumber + n = generationNumber + for i in range(2): + newkey += int2Byte(n & 0xff) + n = n>>8 + md5output = md5(newkey).digest() + if revision == 2: + key = md5output[:10] + elif revision == 3: + key = md5output #all 16 bytes + from reportlab.lib.arciv import ArcIV + encrypted = ArcIV(key).encode(string) + #print 'encrypted=', hexText(encrypted) + elif revision == 5: + iv = os_urandom(16) + encrypter = pyaes.Encrypter(pyaes.AESModeOfOperationCBC(key, iv=iv)) + + # pkcs7 style padding so that the size of the encrypted block is multiple of 16 + string_len = len(string) + padding = "" + padding_len = (16 - (string_len % 16)) if string_len > 16 else (16 - string_len) + if padding_len > 0: + padding = chr(padding_len) * padding_len + + if isinstance(string, str): + string = (string + padding).encode("utf-8") + else: + string += asBytes(padding) + + encrypted = iv + encrypter.feed(string) + encrypted += encrypter.feed() + + if DEBUG>=10: print('encodePDF(%s,%s,%s,%s,%s)==>%s' % tuple([hexText(str(x)) for x in (key, objectNumber, generationNumber, string, revision,encrypted)])) + return encrypted + +def equalityCheck(observed,expected,label): + assert observed==expected,'%s\n expected=%s\n observed=%s' % (label,expected,observed) +###################################################################### +# +# quick tests of algorithm, should be moved elsewhere +# +###################################################################### +def test(): + # do a 40 bit example known to work in Acrobat Reader 4.0 + enc = StandardEncryption('User','Owner', strength=40) + enc.prepare(None, overrideID='xxxxxxxxxxxxxxxx') + + expectedO = '' + expectedU = '<09F26CF46190AF8F93B304AD50C16B615DC43C228C9B2D2EA34951A80617B2B1>' + expectedKey = '' # 5 byte key = 40 bits + + equalityCheck(hexText(enc.O),expectedO, '40 bit O value') + equalityCheck(hexText(enc.U),expectedU, '40 bit U value') + equalityCheck(hexText(enc.key),expectedKey, '40 bit key value') + + # now for 128 bit example + enc = StandardEncryption('userpass','ownerpass', strength=128) + enc.prepare(None, overrideID = 'xxxxxxxxxxxxxxxx') + + expectedO = '<68E5704AC779A5F0CD89704406587A52F25BF61CADC56A0F8DB6C4DB0052534D>' + expectedU = '' + expectedKey = '<13DDE7585D9BE366C976DDD56AF541D1>' # 16 byte key = 128 bits + + equalityCheck(hexText(enc.O), expectedO, '128 bit O value') + equalityCheck(hexText(enc.U), expectedU, '128 bit U value') + equalityCheck(hexText(enc.key), expectedKey, '128 key value') + + ###################################################################### + # + # These represent the higher level API functions + # + ###################################################################### + +def encryptCanvas(canvas, + userPassword, ownerPassword=None, + canPrint=1, canModify=1, canCopy=1, canAnnotate=1, + strength=40): + "Applies encryption to the document being generated" + + enc = StandardEncryption(userPassword, ownerPassword, + canPrint, canModify, canCopy, canAnnotate, + strength=strength) + canvas._doc.encrypt = enc + +# Platypus stuff needs work, sadly. I wanted to do it without affecting +# needing changes to latest release. +class EncryptionFlowable(StandardEncryption, Flowable): + """Drop this in your Platypus story and it will set up the encryption options. + + If you do it multiple times, the last one before saving will win.""" + + def wrap(self, availWidth, availHeight): + return (0,0) + + def draw(self): + encryptCanvas(self.canv, + self.userPassword, + self.ownerPassword, + self.canPrint, + self.canModify, + self.canCopy, + self.canAnnotate) + +## I am thinking about this one. Needs a change to reportlab to +## work. +def encryptDocTemplate(dt, + userPassword, ownerPassword=None, + canPrint=1, canModify=1, canCopy=1, canAnnotate=1, + strength=40): + "For use in Platypus. Call before build()." + raise Exception("Not implemented yet") + + +def encryptPdfInMemory(inputPDF, + userPassword, ownerPassword=None, + canPrint=1, canModify=1, canCopy=1, canAnnotate=1, + strength=40): + """accepts a PDF file 'as a byte array in memory'; return encrypted one. + + This is a high level convenience and does not touch the hard disk in any way. + If you are encrypting the same file over and over again, it's better to use + pageCatcher and cache the results.""" + + try: + from rlextra.pageCatcher.pageCatcher import storeFormsInMemory, restoreFormsInMemory + except ImportError: + raise ImportError('''reportlab.lib.pdfencrypt.encryptPdfInMemory failed because rlextra cannot be imported. +See https://www.reportlab.com/downloads''') + + (bboxInfo, pickledForms) = storeFormsInMemory(inputPDF, all=1, BBoxes=1) + names = list(bboxInfo.keys()) + + firstPageSize = bboxInfo['PageForms0'][2:] + + #now make a new PDF document + buf = BytesIO() + canv = Canvas(buf, pagesize=firstPageSize) + + # set a standard ID while debugging + if CLOBBERID: + canv._doc._ID = "[(xxxxxxxxxxxxxxxx)(xxxxxxxxxxxxxxxx)]" + + formNames = restoreFormsInMemory(pickledForms, canv) + for formName in formNames: + canv.setPageSize(bboxInfo[formName][2:]) + canv.doForm(formName) + canv.showPage() + encryptCanvas(canv, + userPassword, ownerPassword, + canPrint, canModify, canCopy, canAnnotate, + strength=strength) + canv.save() + return buf.getvalue() + +def encryptPdfOnDisk(inputFileName, outputFileName, + userPassword, ownerPassword=None, + canPrint=1, canModify=1, canCopy=1, canAnnotate=1, + strength=40): + "Creates encrypted file OUTPUTFILENAME. Returns size in bytes." + + inputPDF = open(inputFileName, 'rb').read() + outputPDF = encryptPdfInMemory(inputPDF, + userPassword, ownerPassword, + canPrint, canModify, canCopy, canAnnotate, + strength=strength) + open(outputFileName, 'wb').write(outputPDF) + return len(outputPDF) + + +def scriptInterp(): + sys_argv = sys.argv[:] # copy + + usage = """PDFENCRYPT USAGE: + +PdfEncrypt encrypts your PDF files. + +Line mode usage: + +% pdfencrypt.exe pdffile [-o ownerpassword] | [owner ownerpassword], +\t[-u userpassword] | [user userpassword], +\t[-p 1|0] | [printable 1|0], +\t[-m 1|0] | [modifiable 1|0], +\t[-c 1|0] | [copypastable 1|0], +\t[-a 1|0] | [annotatable 1|0], +\t[-s savefilename] | [savefile savefilename], +\t[-v 1|0] | [verbose 1|0], +\t[-e128], [encrypt128], +\t[-h] | [help] + +-o or owner set the owner password. +-u or user set the user password. +-p or printable set the printable attribute (must be 1 or 0). +-m or modifiable sets the modifiable attribute (must be 1 or 0). +-c or copypastable sets the copypastable attribute (must be 1 or 0). +-a or annotatable sets the annotatable attribute (must be 1 or 0). +-s or savefile sets the name for the output PDF file +-v or verbose prints useful output to the screen. + (this defaults to 'pdffile_encrypted.pdf'). +'-e128' or 'encrypt128' allows you to use 128 bit encryption (in beta). +'-e256' or 'encrypt256' allows you to use 256 bit encryption (in beta AES). + +-h or help prints this message. + +See PdfEncryptIntro.pdf for more information. +""" + + known_modes = ['-o', 'owner', + '-u', 'user', + '-p', 'printable', + '-m', 'modifiable', + '-c', 'copypastable', + '-a', 'annotatable', + '-s', 'savefile', + '-v', 'verbose', + '-h', 'help', + '-e128', 'encrypt128', + '-e256', 'encryptAES', + ] + + OWNER = '' + USER = '' + PRINTABLE = 1 + MODIFIABLE = 1 + COPYPASTABLE = 1 + ANNOTATABLE = 1 + SAVEFILE = 'encrypted.pdf' + + #try: + caller = sys_argv[0] # may be required later - eg if called by security.py + argv = list(sys_argv)[1:] + if len(argv)>0: + if argv[0] == '-h' or argv[0] == 'help': + print(usage) + return + if len(argv)<2: + raise ValueError("Must include a filename and one or more arguments!") + if argv[0] not in known_modes: + infile = argv[0] + argv = argv[1:] + if not os.path.isfile(infile): + raise ValueError("Can't open input file '%s'!" % infile) + else: + raise ValueError("First argument must be name of the PDF input file!") + + # meaningful name at this stage + STRENGTH = 40 + for (s,_a) in ((128,('-e128','encrypt128')),(256,('-e256','encrypt256'))): + for a in _a: + if a in argv: + STRENGTH = s + argv.remove(a) + + if ('-v' in argv) or ('verbose' in argv): + if '-v' in argv: + pos = argv.index('-v') + arg = "-v" + elif 'verbose' in argv: + pos = argv.index('verbose') + arg = "verbose" + try: + verbose = int(argv[pos+1]) + except: + verbose = 1 + argv.remove(argv[pos+1]) + argv.remove(arg) + else: + from reportlab.rl_config import verbose + + #argument, valid license variable, invalid license variable, text for print + arglist = (('-o', 'OWNER', OWNER, 'Owner password'), + ('owner', 'OWNER', OWNER, 'Owner password'), + ('-u', 'USER', USER, 'User password'), + ('user', 'USER', USER, 'User password'), + ('-p', 'PRINTABLE', PRINTABLE, "'Printable'"), + ('printable', 'PRINTABLE', PRINTABLE, "'Printable'"), + ('-m', 'MODIFIABLE', MODIFIABLE, "'Modifiable'"), + ('modifiable', 'MODIFIABLE', MODIFIABLE, "'Modifiable'"), + ('-c', 'COPYPASTABLE', COPYPASTABLE, "'Copypastable'"), + ('copypastable', 'COPYPASTABLE', COPYPASTABLE, "'Copypastable'"), + ('-a', 'ANNOTATABLE', ANNOTATABLE, "'Annotatable'"), + ('annotatable', 'ANNOTATABLE', ANNOTATABLE, "'Annotatable'"), + ('-s', 'SAVEFILE', SAVEFILE, "Output file"), + ('savefile', 'SAVEFILE', SAVEFILE, "Output file"), + ) + + binaryrequired = ('-p', 'printable', '-m', 'modifiable', 'copypastable', '-c', 'annotatable', '-a') + + for thisarg in arglist: + if thisarg[0] in argv: + pos = argv.index(thisarg[0]) + if thisarg[0] in binaryrequired: + if argv[pos+1] not in ('1', '0'): + raise ValueError("%s value must be either '1' or '0'!" % thisarg[1]) + try: + if argv[pos+1] not in known_modes: + if thisarg[0] in binaryrequired: + exec(thisarg[1] +' = int(argv[pos+1])',vars()) + else: + exec(thisarg[1] +' = argv[pos+1]',vars()) + if verbose: + print("%s set to: '%s'." % (thisarg[3], argv[pos+1])) + argv.remove(argv[pos+1]) + argv.remove(thisarg[0]) + except: + raise "Unable to set %s." % thisarg[3] + + if verbose>4: + #useful if feeling paranoid and need to double check things at this point... + print("\ninfile:", infile) + print("STRENGTH:", STRENGTH) + print("SAVEFILE:", SAVEFILE) + print("USER:", USER) + print("OWNER:", OWNER) + print("PRINTABLE:", PRINTABLE) + print("MODIFIABLE:", MODIFIABLE) + print("COPYPASTABLE:", COPYPASTABLE) + print("ANNOTATABLE:", ANNOTATABLE) + print("SAVEFILE:", SAVEFILE) + print("VERBOSE:", verbose) + + + if SAVEFILE == 'encrypted.pdf': + if infile[-4:] == '.pdf' or infile[-4:] == '.PDF': + tinfile = infile[:-4] + else: + tinfile = infile + SAVEFILE = tinfile+"_encrypted.pdf" + + filesize = encryptPdfOnDisk(infile, SAVEFILE, USER, OWNER, + PRINTABLE, MODIFIABLE, COPYPASTABLE, ANNOTATABLE, + strength=STRENGTH) + + if verbose: + print("wrote output file '%s'(%s bytes)\n owner password is '%s'\n user password is '%s'" % (SAVEFILE, filesize, OWNER, USER)) + + if len(argv)>0: + raise ValueError("\nUnrecognised arguments : %s\nknown arguments are:\n%s" % (str(argv)[1:-1], known_modes)) + else: + print(usage) + +def main(): + scriptInterp() + +if __name__=="__main__": #NO RUNTESTS + a = [x for x in sys.argv if x[:7]=='--debug'] + if a: + sys.argv = [x for x in sys.argv if x[:7]!='--debug'] + DEBUG = len(a) + if '--test' in sys.argv: test() + else: main() diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/pygments2xpre.py b/.venv/lib/python3.13/site-packages/reportlab/lib/pygments2xpre.py new file mode 100644 index 0000000000000000000000000000000000000000..8a32681bc6aedce559dbbce2a05549cddb2d853d --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/pygments2xpre.py @@ -0,0 +1,71 @@ +"""Helps you output colourised code snippets in ReportLab documents. + +Platypus has an 'XPreformatted' flowable for handling preformatted +text, with variations in fonts and colors. If Pygments is installed, +calling 'pygments2xpre' will return content suitable for display in +an XPreformatted object. If it's not installed, you won't get colours. + +For a list of available lexers see http://pygments.org/docs/ + +""" +__all__ = ('pygments2xpre',) +import re +from io import StringIO + +def _2xpre(s,styles): + "Helper to transform Pygments HTML output to ReportLab markup" + s = s.replace('
','') + s = s.replace('
','') + s = s.replace('
','')
+    s = s.replace('
','') + for k,c in styles+[('p','#000000'),('n','#000000'),('err','#000000')]: + s = s.replace('' % k,'' % c) + s = re.sub(r''% k,'' % c,s) + s = re.sub(r'','',s) + return s + +def pygments2xpre(s, language="python"): + "Return markup suitable for XPreformatted" + try: + from pygments import highlight + from pygments.formatters import HtmlFormatter + except ImportError: + return s + + from pygments.lexers import get_lexer_by_name + rconv = lambda x: x + out = StringIO() + + l = get_lexer_by_name(language) + + h = HtmlFormatter() + highlight(s,l,h,out) + styles = [(cls, style.split(';')[0].split(':')[1].strip()) + for cls, (style, ttype, level) in h.class2style.items() + if cls and style and style.startswith('color:')] + return rconv(_2xpre(out.getvalue(),styles)) + +def convertSourceFiles(filenames): + "Helper function - makes minimal PDF document" + + from reportlab.platypus import Paragraph, SimpleDocTemplate, XPreformatted + from reportlab.lib.styles import getSampleStyleSheet + styT=getSampleStyleSheet()["Title"] + styC=getSampleStyleSheet()["Code"] + doc = SimpleDocTemplate("pygments2xpre.pdf") + S = [].append + for filename in filenames: + S(Paragraph(filename,style=styT)) + src = open(filename, 'r').read() + fmt = pygments2xpre(src) + S(XPreformatted(fmt, style=styC)) + doc.build(S.__self__) + print('saved pygments2xpre.pdf') + +if __name__=='__main__': + import sys + filenames = sys.argv[1:] + if not filenames: + print('usage: pygments2xpre.py file1.py [file2.py] [...]') + sys.exit(0) + convertSourceFiles(filenames) diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/randomtext.py b/.venv/lib/python3.13/site-packages/reportlab/lib/randomtext.py new file mode 100644 index 0000000000000000000000000000000000000000..088bcd62f45fadfdb45205fe5ec63fca1070a430 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/randomtext.py @@ -0,0 +1,366 @@ +#!/bin/env python +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/randomtext.py + +__version__='3.3.0' + +############################################################################### +# generates so-called 'Greek Text' for use in filling documents. +############################################################################### +__doc__="""Like Lorem Ipsum, but more fun and extensible. + +This module exposes a function randomText() which generates paragraphs. +These can be used when testing out document templates and stylesheets. +A number of 'themes' are provided - please contribute more! +We need some real Greek text too. + +There are currently six themes provided: + STARTUP (words suitable for a business plan - or not as the case may be), + COMPUTERS (names of programming languages and operating systems etc), + BLAH (variations on the word 'blah'), + BUZZWORD (buzzword bingo), + STARTREK (Star Trek), + PRINTING (print-related terms) + PYTHON (snippets and quotes from Monty Python) + CHOMSKY (random lingusitic nonsense) + +EXAMPLE USAGE: + from reportlab.lib import randomtext + print randomtext.randomText(randomtext.PYTHON, 10) + + This prints a random number of random sentences (up to a limit + of ten) using the theme 'PYTHON'. + +""" + +#theme one :-) +STARTUP = ['strategic', 'direction', 'proactive', 'venture capital', + 'reengineering', 'forecast', 'resources', 'SWOT analysis', + 'forward-thinking', 'profit', 'growth', 'doubletalk', 'B2B', 'B2C', + 'venture capital', 'IPO', "NASDAQ meltdown - we're all doomed!"] + +#theme two - computery things. +COMPUTERS = ['Python', 'Perl', 'Pascal', 'Java', 'Javascript', + 'VB', 'Basic', 'LISP', 'Fortran', 'ADA', 'APL', 'C', 'C++', + 'assembler', 'Larry Wall', 'Guido van Rossum', 'XML', 'HTML', + 'cgi', 'cgi-bin', 'Amiga', 'Macintosh', 'Dell', 'Microsoft', + 'firewall', 'server', 'Linux', 'Unix', 'MacOS', 'BeOS', 'AS/400', + 'sendmail', 'TCP/IP', 'SMTP', 'RFC822-compliant', 'dynamic', + 'Internet', 'A/UX', 'Amiga OS', 'BIOS', 'boot managers', 'CP/M', + 'DOS', 'file system', 'FreeBSD', 'Freeware', 'GEOS', 'GNU', + 'Hurd', 'Linux', 'Mach', 'Macintosh OS', 'mailing lists', 'Minix', + 'Multics', 'NetWare', 'NextStep', 'OS/2', 'Plan 9', 'Realtime', + 'UNIX', 'VMS', 'Windows', 'X Windows', 'Xinu', 'security', 'Intel', + 'encryption', 'PGP' , 'software', 'ActiveX', 'AppleScript', 'awk', + 'BETA', 'COBOL', 'Delphi', 'Dylan', 'Eiffel', 'extreme programming', + 'Forth', 'Fortran', 'functional languages', 'Guile', 'format your hard drive', + 'Icon', 'IDL', 'Infer', 'Intercal', 'J', 'Java', 'JavaScript', 'CD-ROM', + 'JCL', 'Lisp', '"literate programming"', 'Logo', 'MUMPS', 'C: drive', + 'Modula-2', 'Modula-3', 'Oberon', 'Occam', 'OpenGL', 'parallel languages', + 'Pascal', 'Perl', 'PL/I', 'PostScript', 'Prolog', 'hardware', 'Blue Screen of Death', + 'Rexx', 'RPG', 'Scheme', 'scripting languages', 'Smalltalk', 'crash!', 'disc crash', + 'Spanner', 'SQL', 'Tcl/Tk', 'TeX', 'TOM', 'Visual', 'Visual Basic', '4GL', + 'VRML', 'Virtual Reality Modeling Language', 'difference engine', '...went into "yo-yo mode"', + 'Sun', 'Sun Microsystems', 'Hewlett Packard', 'output device', + 'CPU', 'memory', 'registers', 'monitor', 'TFT display', 'plasma screen', + 'bug report', '"mis-feature"', '...millions of bugs!', 'pizza', + '"illiterate programming"','...lots of pizza!', 'pepperoni pizza', + 'coffee', 'Jolt Cola[TM]', 'beer', 'BEER!'] + +#theme three - 'blah' - for when you want to be subtle. :-) +BLAH = ['Blah', 'BLAH', 'blahblah', 'blahblahblah', 'blah-blah', + 'blah!', '"Blah Blah Blah"', 'blah-de-blah', 'blah?', 'blah!!!', + 'blah...', 'Blah.', 'blah;', 'blah, Blah, BLAH!', 'Blah!!!'] + +#theme four - 'buzzword bingo' time! +BUZZWORD = ['intellectual capital', 'market segment', 'flattening', + 'regroup', 'platform', 'client-based', 'long-term', 'proactive', + 'quality vector', 'out of the loop', 'implement', + 'streamline', 'cost-centered', 'phase', 'synergy', + 'synergize', 'interactive', 'facilitate', + 'appropriate', 'goal-setting', 'empowering', 'low-risk high-yield', + 'peel the onion', 'goal', 'downsize', 'result-driven', + 'conceptualize', 'multidisciplinary', 'gap analysis', 'dysfunctional', + 'networking', 'knowledge management', 'goal-setting', + 'mastery learning', 'communication', 'real-estate', 'quarterly', + 'scalable', 'Total Quality Management', 'best of breed', + 'nimble', 'monetize', 'benchmark', 'hardball', + 'client-centered', 'vision statement', 'empowerment', + 'lean & mean', 'credibility', 'synergistic', + 'backward-compatible', 'hardball', 'stretch the envelope', + 'bleeding edge', 'networking', 'motivation', 'best practice', + 'best of breed', 'implementation', 'Total Quality Management', + 'undefined', 'disintermediate', 'mindset', 'architect', + 'gap analysis', 'morale', 'objective', 'projection', + 'contribution', 'proactive', 'go the extra mile', 'dynamic', + 'world class', 'real estate', 'quality vector', 'credibility', + 'appropriate', 'platform', 'projection', 'mastery learning', + 'recognition', 'quality', 'scenario', 'performance based', + 'solutioning', 'go the extra mile', 'downsize', 'phase', + 'networking', 'experiencing slippage', 'knowledge management', + 'high priority', 'process', 'ethical', 'value-added', 'implement', + 're-factoring', 're-branding', 'embracing change'] + +#theme five - Star Trek +STARTREK = ['Starfleet', 'Klingon', 'Romulan', 'Cardassian', 'Vulcan', + 'Benzite', 'IKV Pagh', 'emergency transponder', 'United Federation of Planets', + 'Bolian', "K'Vort Class Bird-of-Prey", 'USS Enterprise', 'USS Intrepid', + 'USS Reliant', 'USS Voyager', 'Starfleet Academy', 'Captain Picard', + 'Captain Janeway', 'Tom Paris', 'Harry Kim', 'Counsellor Troi', + 'Lieutenant Worf', 'Lieutenant Commander Data', 'Dr. Beverly Crusher', + 'Admiral Nakamura', 'Irumodic Syndrome', 'Devron system', 'Admiral Pressman', + 'asteroid field', 'sensor readings', 'Binars', 'distress signal', 'shuttlecraft', + 'cloaking device', 'shuttle bay 2', 'Dr. Pulaski', 'Lwaxana Troi', 'Pacifica', + 'William Riker', "Chief O'Brian", 'Soyuz class science vessel', 'Wolf-359', + 'Galaxy class vessel', 'Utopia Planitia yards', 'photon torpedo', 'Archer IV', + 'quantum flux', 'spacedock', 'Risa', 'Deep Space Nine', 'blood wine', + 'quantum torpedoes', 'holodeck', 'Romulan Warbird', 'Betazoid', 'turbolift', 'battle bridge', + 'Memory Alpha', '...with a phaser!', 'Romulan ale', 'Ferrengi', 'Klingon opera', + 'Quark', 'wormhole', 'Bajoran', 'cruiser', 'warship', 'battlecruiser', '"Intruder alert!"', + 'scout ship', 'science vessel', '"Borg Invasion imminent!" ', '"Abandon ship!"', + 'Red Alert!', 'warp-core breech', '"All hands abandon ship! This is not a drill!"'] + +#theme six - print-related terms +PRINTING = ['points', 'picas', 'leading', 'kerning', 'CMYK', 'offset litho', + 'type', 'font family', 'typography', 'type designer', + 'baseline', 'white-out type', 'WOB', 'bicameral', 'bitmap', + 'blockletter', 'bleed', 'margin', 'body', 'widow', 'orphan', + 'cicero', 'cursive', 'letterform', 'sidehead', 'dingbat', 'leader', + 'DPI', 'drop-cap', 'paragraph', 'En', 'Em', 'flush left', 'left justified', + 'right justified', 'centered', 'italic', 'Latin letterform', 'ligature', + 'uppercase', 'lowercase', 'serif', 'sans-serif', 'weight', 'type foundry', + 'fleuron', 'folio', 'gutter', 'whitespace', 'humanist letterform', 'caption', + 'page', 'frame', 'ragged setting', 'flush-right', 'rule', 'drop shadows', + 'prepress', 'spot-colour', 'duotones', 'colour separations', 'four-colour printing', + 'Pantone[TM]', 'service bureau', 'imagesetter'] + +#it had to be done!... +#theme seven - the "full Monty"! +PYTHON = ['Good evening ladies and Bruces','I want to buy some cheese', 'You do have some cheese, do you?', + "Of course sir, it's a cheese shop sir, we've got...",'discipline?... naked? ... With a melon!?', + 'The Church Police!!' , "There's a dead bishop on the landing", 'Would you like a twist of lemming sir?', + '"Conquistador Coffee brings a new meaning to the word vomit"','Your lupins please', + 'Crelm Toothpaste, with the miracle ingredient Fraudulin', + "Well there's the first result and the Silly Party has held Leicester.", + 'Hello, I would like to buy a fish license please', "Look, it's people like you what cause unrest!", + "When we got home, our Dad would thrash us to sleep with his belt!", 'Luxury', "Gumby Brain Specialist", + "My brain hurts!!!", "My brain hurts too.", "How not to be seen", + "In this picture there are 47 people. None of them can be seen", + "Mrs Smegma, will you stand up please?", + "Mr. Nesbitt has learned the first lesson of 'Not Being Seen', not to stand up.", + "My hovercraft is full of eels", "Ah. You have beautiful thighs.", "My nipples explode with delight", + "Drop your panties Sir William, I cannot wait 'til lunchtime", + "I'm a completely self-taught idiot.", "I always wanted to be a lumberjack!!!", + "Told you so!! Oh, coitus!!", "", + "Nudge nudge?", "Know what I mean!", "Nudge nudge, nudge nudge?", "Say no more!!", + "Hello, well it's just after 8 o'clock, and time for the penguin on top of your television set to explode", + "Oh, intercourse the penguin!!", "Funny that penguin being there, isn't it?", + "I wish to register a complaint.", "Now that's what I call a dead parrot", "Pining for the fjords???", + "No, that's not dead, it's ,uhhhh, resting", "This is an ex-parrot!!", + "That parrot is definitely deceased.", "No, no, no - it's spelt Raymond Luxury Yach-t, but it's pronounced 'Throatwobbler Mangrove'.", + "You're a very silly man and I'm not going to interview you.", "No Mungo... never kill a customer." + "And I'd like to conclude by putting my finger up my nose", + "egg and Spam", "egg bacon and Spam", "egg bacon sausage and Spam", "Spam bacon sausage and Spam", + "Spam egg Spam Spam bacon and Spam", "Spam sausage Spam Spam Spam bacon Spam tomato and Spam", + "Spam Spam Spam egg and Spam", "Spam Spam Spam Spam Spam Spam baked beans Spam Spam Spam", + "Spam!!", "I don't like Spam!!!", "You can't have egg, bacon, Spam and sausage without the Spam!", + "I'll have your Spam. I Love it!", + "I'm having Spam Spam Spam Spam Spam Spam Spam baked beans Spam Spam Spam and Spam", + "Have you got anything without Spam?", "There's Spam egg sausage and Spam, that's not got much Spam in it.", + "No one expects the Spanish Inquisition!!", "Our weapon is surprise, surprise and fear!", + "Get the comfy chair!", "Amongst our weaponry are such diverse elements as: fear, surprise, ruthless efficiency, an almost fanatical devotion to the Pope, and nice red uniforms - Oh damn!", + "Nobody expects the... Oh bugger!", "What swims in the sea and gets caught in nets? Henri Bergson?", + "Goats. Underwater goats with snorkels and flippers?", "A buffalo with an aqualung?", + "Dinsdale was a looney, but he was a happy looney.", "Dinsdale!!", + "The 127th Upper-Class Twit of the Year Show", "What a great Twit!", + "thought by many to be this year's outstanding twit", + "...and there's a big crowd here today to see these prize idiots in action.", + "And now for something completely different.", "Stop that, it's silly", + "We interrupt this program to annoy you and make things generally irritating", + "This depraved and degrading spectacle is going to stop right now, do you hear me?", + "Stop right there!", "This is absolutely disgusting and I'm not going to stand for it", + "I object to all this sex on the television. I mean, I keep falling off", + "Right! Stop that, it's silly. Very silly indeed", "Very silly indeed", "Lemon curry?", + "And now for something completely different, a man with 3 buttocks", + "I've heard of unisex, but I've never had it", "That's the end, stop the program! Stop it!"] +leadins=[ + "To characterize a linguistic level L,", + "On the other hand,", + "This suggests that", + "It appears that", + "Furthermore,", + "We will bring evidence in favor of the following thesis: ", + "To provide a constituent structure for T(Z,K),", + "From C1, it follows that", + "For any transformation which is sufficiently diversified in application to be of any interest,", + "Analogously,", + "Clearly,", + "Note that", + "Of course,", + "Suppose, for instance, that", + "Thus", + "With this clarification,", + "Conversely,", + "We have already seen that", + "By combining adjunctions and certain deformations,", + "I suggested that these results would follow from the assumption that", + "If the position of the trace in (99c) were only relatively inaccessible to movement,", + "However, this assumption is not correct, since", + "Comparing these examples with their parasitic gap counterparts in (96) and (97), we see that", + "In the discussion of resumptive pronouns following (81),", + "So far,", + "Nevertheless,", + "For one thing,", + "Summarizing, then, we assume that", + "A consequence of the approach just outlined is that", + "Presumably,", + "On our assumptions,", + "It may be, then, that", + "It must be emphasized, once again, that", + "Let us continue to suppose that", + "Notice, incidentally, that", + "A majority of informed linguistic specialists agree that", + "There is also a different approach to the [unification] problem,", + "This approach divorces the cognitive sciences from a biological setting,", + "The approach relies on the \"Turing Test,\" devised by mathematician Alan Turing,", + "Adopting this approach,", + "There is no fact, no meaningful question to be answered,", + "Another superficial similarity is the interest in simulation of behavior,", + "A lot of sophistication has been developed about the utilization of machines for complex purposes,", + ] + +subjects = [ + "the notion of level of grammaticalness", + "a case of semigrammaticalness of a different sort", + "most of the methodological work in modern linguistics", + "a subset of English sentences interesting on quite independent grounds", + "the natural general principle that will subsume this case", + "an important property of these three types of EC", + "any associated supporting element", + "the appearance of parasitic gaps in domains relatively inaccessible to ordinary extraction", + "the speaker-hearer's linguistic intuition", + "the descriptive power of the base component", + "the earlier discussion of deviance", + "this analysis of a formative as a pair of sets of features", + "this selectionally introduced contextual feature", + "a descriptively adequate grammar", + "the fundamental error of regarding functional notions as categorial", + "relational information", + "the systematic use of complex symbols", + "the theory of syntactic features developed earlier", + ] + +verbs= [ + "can be defined in such a way as to impose", + "delimits", + "suffices to account for", + "cannot be arbitrary in", + "is not subject to", + "does not readily tolerate", + "raises serious doubts about", + "is not quite equivalent to", + "does not affect the structure of", + "may remedy and, at the same time, eliminate", + "is not to be considered in determining", + "is to be regarded as", + "is unspecified with respect to", + "is, apparently, determined by", + "is necessary to impose an interpretation on", + "appears to correlate rather closely with", + "is rather different from", + ] + +objects = [ + "problems of phonemic and morphological analysis.", + "a corpus of utterance tokens upon which conformity has been defined by the paired utterance test.", + "the traditional practice of grammarians.", + "the levels of acceptability from fairly high (e.g. (99a)) to virtual gibberish (e.g. (98d)).", + "a stipulation to place the constructions into these various categories.", + "a descriptive fact.", + "a parasitic gap construction.", + "the extended c-command discussed in connection with (34).", + "the ultimate standard that determines the accuracy of any proposed grammar.", + "the system of base rules exclusive of the lexicon.", + "irrelevant intervening contexts in selectional rules.", + "nondistinctness in the sense of distinctive feature theory.", + "a general convention regarding the forms of the grammar.", + "an abstract underlying order.", + "an important distinction in language use.", + "the requirement that branching is not tolerated within the dominance scope of a complex symbol.", + "the strong generative capacity of the theory.", + ] + +def format_wisdom(text,line_length=72): + try: + import textwrap + return textwrap.fill(text, line_length) + except: + return text + +def chomsky(times = 1): + if not isinstance(times, int): + return format_wisdom(__doc__) + import random + prevparts = [] + newparts = [] + output = [] + for i in range(times): + for partlist in (leadins, subjects, verbs, objects): + while 1: + part = random.choice(partlist) + if part not in prevparts: + break + newparts.append(part) + output.append(' '.join(newparts)) + prevparts = newparts + newparts = [] + return format_wisdom(' '.join(output)) + +def randomText(theme=STARTUP, sentences=5): + #this may or may not be appropriate in your company + if type(theme)==type(''): + if theme.lower()=='chomsky': return chomsky(sentences) + elif theme.upper() in ('STARTUP','COMPUTERS','BLAH','BUZZWORD','STARTREK','PRINTING','PYTHON'): + theme = globals()[theme.upper()] + else: + raise ValueError('Unknown theme "%s"' % theme) + + from random import randint, choice + + RANDOMWORDS = theme + + #sentences = 5 + output = "" + for sentenceno in range(randint(1,sentences)): + output = output + 'Blah' + for wordno in range(randint(10,25)): + if randint(0,4)==0: + word = choice(RANDOMWORDS) + else: + word = 'blah' + output = output + ' ' +word + output = output+'. ' + return output + +if __name__=='__main__': + import sys, random + from reportlab.rl_config import invariant as rl_invariant + if rl_invariant: + random.seed(1854640162) + print(f'{" ".join((str(random.randrange(100)) for _ in range(10)))}') + argv = sys.argv[1:] + if argv: + theme = argv.pop(0) + if argv: + sentences = int(argv.pop(0)) + else: + sentences = 5 + try: + print(randomText(theme,sentences)) + except: + sys.stderr.write("Usage: randomtext.py [theme [#sentences]]\n") + sys.stderr.write(" theme in chomsky|STARTUP|COMPUTERS|BLAH|BUZZWORD|STARTREK|PRINTING|PYTHON\n") + raise + else: + print(chomsky(5)) diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/rl_accel.py b/.venv/lib/python3.13/site-packages/reportlab/lib/rl_accel.py new file mode 100644 index 0000000000000000000000000000000000000000..0b32d3ae520ed993e94a86537ff2633b62eb363d --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/rl_accel.py @@ -0,0 +1,361 @@ +#this is the interface module that imports all from the C extension _rl_accel +_c_funcs = {} +_py_funcs = {} +### NOTE! FP_STR SHOULD PROBABLY ALWAYS DO A PYTHON STR() CONVERSION ON ARGS +### IN CASE THEY ARE "LAZY OBJECTS". ACCELLERATOR DOESN'T DO THIS (YET) +__all__ = list(filter(None,''' + fp_str + unicode2T1 + instanceStringWidthT1 + instanceStringWidthTTF + asciiBase85Encode + asciiBase85Decode + escapePDF + sameFrag + calcChecksum + add32 + hex32 + '''.split())) +import reportlab +testing = getattr(reportlab,'_rl_testing',False) +del reportlab + +for fn in __all__: + D={} + try: + exec('from _rl_accel import %s as f' % fn,D) + _c_funcs[fn] = D['f'] + if testing: _py_funcs[fn] = None + except ImportError: + _py_funcs[fn] = None + del D + +if _py_funcs: + from reportlab.lib.utils import isUnicode, isSeq, rawBytes, asNative, asBytes + from math import log + from struct import unpack + +if 'fp_str' in _py_funcs: + _log_10 = lambda x,log=log,_log_e_10=log(10.0): log(x)/_log_e_10 + _fp_fmts = "%.0f", "%.1f", "%.2f", "%.3f", "%.4f", "%.5f", "%.6f" + def _py_fp_str(*a): + '''convert separate arguments (or single sequence arg) into space separated numeric strings''' + if len(a)==1 and isSeq(a[0]): a = a[0] + s = [] + A = s.append + for i in a: + sa =abs(i) + if sa<=1e-7: A('0') + else: + l = sa<=1 and 6 or min(max(0,(6-int(_log_10(sa)))),6) + n = _fp_fmts[l]%i + if l: + j = len(n) + while j: + j -= 1 + if n[j]!='0': + if n[j]!='.': j += 1 + break + n = n[:j] + A((n[0]!='0' or len(n)==1) and n or n[1:]) + return ' '.join(s) + + #hack test for comma users + if ',' in _py_fp_str(0.25): + _FP_STR = _fp_str + def __py_fp_str(*a): + return _FP_STR(*a).replace(',','.') + _py_funcs['fp_str'] = _py_fp_str + +if 'unicode2T1' in _py_funcs: + def _py_unicode2T1(utext,fonts): + '''return a list of (font,string) pairs representing the unicode text''' + R = [] + font, fonts = fonts[0], fonts[1:] + enc = font.encName + if 'UCS-2' in enc: + enc = 'UTF16' + while utext: + try: + if isUnicode(utext): + s = utext.encode(enc) + else: + s = utext + R.append((font,s)) + break + except UnicodeEncodeError as e: + i0, il = e.args[2:4] + if i0: + R.append((font,utext[:i0].encode(enc))) + if fonts: + R.extend(_py_unicode2T1(utext[i0:il],fonts)) + else: + R.append((font._notdefFont,font._notdefChar*(il-i0))) + utext = utext[il:] + return R + _py_funcs['unicode2T1'] = _py_unicode2T1 + +if 'instanceStringWidthT1' in _py_funcs: + def _py_instanceStringWidthT1(self, text, size, encoding='utf8'): + """This is the "purist" approach to width""" + if not isUnicode(text): text = text.decode(encoding) + return sum((sum(map(f.widths.__getitem__,t)) for f, t in _py_unicode2T1(text,[self]+self.substitutionFonts)))*0.001*size + _py_funcs['instanceStringWidthT1'] = _py_instanceStringWidthT1 + +if 'instanceStringWidthTTF' in _py_funcs: + def _py_instanceStringWidthTTF(self, text, size, encoding='utf8'): + "Calculate text width" + if not isUnicode(text): + text = text.decode(encoding or 'utf8') + g = self.face.charWidths.get + dw = self.face.defaultWidth + return 0.001*size*sum((g(ord(u),dw) for u in text)) + _py_funcs['instanceStringWidthTTF'] = _py_instanceStringWidthTTF + +if 'hex32' in _py_funcs: + def _py_hex32(i): + return '0X%8.8X' % (int(i)&0xFFFFFFFF) + _py_funcs['hex32'] = _py_hex32 + +if 'add32' in _py_funcs: + def add32(x, y): + "Calculate (x + y) modulo 2**32" + return (x+y) & 0xFFFFFFFF + _py_funcs['add32'] = add32 + +if 'calcChecksum' in _py_funcs: + def _py_calcChecksum(data): + """Calculates TTF-style checksums""" + data = rawBytes(data) + if len(data)&3: data = data + (4-(len(data)&3))*b"\0" + return sum(unpack(">%dl" % (len(data)>>2), data)) & 0xFFFFFFFF + _py_funcs['calcChecksum'] = _py_calcChecksum + +if 'escapePDF' in _py_funcs: + _ESCAPEDICT={} + for c in range(256): + if c<32 or c>=127: + _ESCAPEDICT[c]= '\\%03o' % c + elif c in (ord('\\'),ord('('),ord(')')): + _ESCAPEDICT[c] = '\\'+chr(c) + else: + _ESCAPEDICT[c] = chr(c) + del c + #Michael Hudson donated this + def _py_escapePDF(s): + r = [] + for c in s: + if not type(c) is int: + c = ord(c) + r.append(_ESCAPEDICT[c]) + return ''.join(r) + _py_funcs['escapePDF'] = _py_escapePDF + +if 'asciiBase85Encode' in _py_funcs: + def _py_asciiBase85Encode(input): + """Encodes input using ASCII-Base85 coding. + + This is a compact encoding used for binary data within + a PDF file. Four bytes of binary data become five bytes of + ASCII. This is the default method used for encoding images.""" + doOrd = isUnicode(input) + # special rules apply if not a multiple of four bytes. + whole_word_count, remainder_size = divmod(len(input), 4) + cut = 4 * whole_word_count + body, lastbit = input[0:cut], input[cut:] + + out = [].append + for i in range(whole_word_count): + offset = i*4 + b1 = body[offset] + b2 = body[offset+1] + b3 = body[offset+2] + b4 = body[offset+3] + if doOrd: + b1 = ord(b1) + b2 = ord(b2) + b3 = ord(b3) + b4 = ord(b4) + + if b1<128: + num = (((((b1<<8)|b2)<<8)|b3)<<8)|b4 + else: + num = 16777216 * b1 + 65536 * b2 + 256 * b3 + b4 + + if num == 0: + #special case + out('z') + else: + #solve for five base-85 numbers + temp, c5 = divmod(num, 85) + temp, c4 = divmod(temp, 85) + temp, c3 = divmod(temp, 85) + c1, c2 = divmod(temp, 85) + assert ((85**4) * c1) + ((85**3) * c2) + ((85**2) * c3) + (85*c4) + c5 == num, 'dodgy code!' + out(chr(c1+33)) + out(chr(c2+33)) + out(chr(c3+33)) + out(chr(c4+33)) + out(chr(c5+33)) + + # now we do the final bit at the end. I repeated this separately as + # the loop above is the time-critical part of a script, whereas this + # happens only once at the end. + + #encode however many bytes we have as usual + if remainder_size > 0: + lastbit += (4-len(lastbit))*('\0' if doOrd else b'\000') + b1 = lastbit[0] + b2 = lastbit[1] + b3 = lastbit[2] + b4 = lastbit[3] + if doOrd: + b1 = ord(b1) + b2 = ord(b2) + b3 = ord(b3) + b4 = ord(b4) + + num = 16777216 * b1 + 65536 * b2 + 256 * b3 + b4 + + #solve for c1..c5 + temp, c5 = divmod(num, 85) + temp, c4 = divmod(temp, 85) + temp, c3 = divmod(temp, 85) + c1, c2 = divmod(temp, 85) + + #print 'encoding: %d %d %d %d -> %d -> %d %d %d %d %d' % ( + # b1,b2,b3,b4,num,c1,c2,c3,c4,c5) + lastword = chr(c1+33) + chr(c2+33) + chr(c3+33) + chr(c4+33) + chr(c5+33) + #write out most of the bytes. + out(lastword[0:remainder_size + 1]) + + #terminator code for ascii 85 + out('~>') + return ''.join(out.__self__) + _py_funcs['asciiBase85Encode'] = _py_asciiBase85Encode + +if 'asciiBase85Decode' in _py_funcs: + def _py_asciiBase85Decode(input): + """Decodes input using ASCII-Base85 coding. + + This is not normally used - Acrobat Reader decodes for you + - but a round trip is essential for testing.""" + #strip all whitespace + stripped = ''.join(asNative(input).split()) + #check end + assert stripped[-2:] == '~>', 'Invalid terminator for Ascii Base 85 Stream' + stripped = stripped[:-2] #chop off terminator + + #may have 'z' in it which complicates matters - expand them + stripped = stripped.replace('z','!!!!!') + # special rules apply if not a multiple of five bytes. + whole_word_count, remainder_size = divmod(len(stripped), 5) + #print '%d words, %d leftover' % (whole_word_count, remainder_size) + #assert remainder_size != 1, 'invalid Ascii 85 stream!' + cut = 5 * whole_word_count + body, lastbit = stripped[0:cut], stripped[cut:] + + out = [].append + for i in range(whole_word_count): + offset = i*5 + c1 = ord(body[offset]) - 33 + c2 = ord(body[offset+1]) - 33 + c3 = ord(body[offset+2]) - 33 + c4 = ord(body[offset+3]) - 33 + c5 = ord(body[offset+4]) - 33 + + num = ((85**4) * c1) + ((85**3) * c2) + ((85**2) * c3) + (85*c4) + c5 + + temp, b4 = divmod(num,256) + temp, b3 = divmod(temp,256) + b1, b2 = divmod(temp, 256) + + assert num == 16777216 * b1 + 65536 * b2 + 256 * b3 + b4, 'dodgy code!' + out(chr(b1)) + out(chr(b2)) + out(chr(b3)) + out(chr(b4)) + + #decode however many bytes we have as usual + if remainder_size > 0: + while len(lastbit) < 5: + lastbit = lastbit + '!' + c1 = ord(lastbit[0]) - 33 + c2 = ord(lastbit[1]) - 33 + c3 = ord(lastbit[2]) - 33 + c4 = ord(lastbit[3]) - 33 + c5 = ord(lastbit[4]) - 33 + num = (((85*c1+c2)*85+c3)*85+c4)*85 + (c5 + +(0,0,0xFFFFFF,0xFFFF,0xFF)[remainder_size]) + temp, b4 = divmod(num,256) + temp, b3 = divmod(temp,256) + b1, b2 = divmod(temp, 256) + assert num == 16777216 * b1 + 65536 * b2 + 256 * b3 + b4, 'dodgy code!' + #print 'decoding: %d %d %d %d %d -> %d -> %d %d %d %d' % ( + # c1,c2,c3,c4,c5,num,b1,b2,b3,b4) + + #the last character needs 1 adding; the encoding loses + #data by rounding the number to x bytes, and when + #divided repeatedly we get one less + if remainder_size == 2: + lastword = chr(b1) + elif remainder_size == 3: + lastword = chr(b1) + chr(b2) + elif remainder_size == 4: + lastword = chr(b1) + chr(b2) + chr(b3) + else: + lastword = '' + out(lastword) + + r = ''.join(out.__self__) + return asBytes(r,enc='latin1') + _py_funcs['asciiBase85Decode'] = _py_asciiBase85Decode + +if 'sameFrag' in _py_funcs: + def _py_sameFrag(f,g, _cmp=('fontName', 'fontSize', 'textColor', 'rise', 'us_lines', 'link', "backColor", "nobr")): + fdict = f.__dict__ + gdict = g.__dict__ + if 'cbDefn' in fdict or 'lineBreak' in fdict or 'cbDefn' in gdict or 'lineBreak' in gdict: return 0 + fg = fdict.get + gg = gdict.get + return [fg(k) for k in _cmp]==[gg(k) for k in _cmp] + _py_funcs['sameFrag'] = _py_sameFrag + +G=globals() +for fn in __all__: + f = _c_funcs[fn] if fn in _c_funcs else _py_funcs[fn] + if not f: + raise RuntimeError('function %s is not properly defined' % fn) + G[fn] = f +del fn, f, G + +if __name__=='__main__': + import sys, subprocess + funclist = ','.join("""add32 asciiBase85Decode asciiBase85Encode + calcChecksum escapePDF fp_str hex32 + instanceStringWidthT1 instanceStringWidthTTF + sameFrag unicode2T1""".split()) + for cmd,xs in ( + ("instanceStringWidthTTF(font,text,10)",("font=TTFont('Vera','Vera.ttf')","text='abcde fghi . jkl ; mno'")), + ("instanceStringWidthT1(font,'abcde fghi . jkl ; mno',10)", + ("fonts=[getFont('Helvetica')]+getFont('Helvetica').substitutionFonts""", + "font=fonts[0]","text='abcde fghi . jkl ; mno'")), + ("escapePDF(text)",("text='\x11abcdefghijkl\xf3'",)), + ("fp_str(1.23456,2.7891666,2,13,11)",()), + ("calcChecksum(text)",("text=5*' abcdefgiijklMnoPQrstuvwxyz1234567890'",)), + ("hex32(0x12345678)",()), + ("add32(0x12345678,123456789)",()), + ("asciiBase85Encode(src)",("src=5*' abcdefgiijklMnoPQrstuvwxyz1234567890'",)), + ("asciiBase85Decode(_85text)",("_85text=asciiBase85Encode(5*' abcdefgiijklMnoPQrstuvwxyz1234567890')",)), + ): + for modname in '_rl_accel','reportlab.lib.rl_accel': + s = ';'.join(( + "from reportlab.pdfbase.pdfmetrics import getFont", + "from reportlab.pdfbase.ttfonts import TTFont", + f"from {modname} import {funclist}", + )+xs) + if modname!='_rl_accel': + s = "import sys;sys.modules['_rl_accel']=None;"+s + print(f'timing {modname} {cmd}') + for i in range(2): + subprocess.check_call([sys.executable,'-mtimeit','-s',s,cmd]) diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/rl_safe_eval.py b/.venv/lib/python3.13/site-packages/reportlab/lib/rl_safe_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..920f73009f4f1ca011ac092ed9d277945ed84faa --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/rl_safe_eval.py @@ -0,0 +1,1287 @@ +#this code is copied/stolen/borrowed/modified from various sources including +#https://github.com/zopefoundation/AccessControl +#https://github.com/zopefoundation/RestrictedPython +#https://github.com/danthedeckie/simpleeval +#hopefully we are standing on giants' shoulders +import sys, os, ast, re, weakref, time, copy, math, types +eval_debug = int(os.environ.get('EVAL_DEBUG','0')) +strTypes = (bytes,str) +isPy39 = sys.version_info[:2]>=(3,9) +isPy313 = sys.version_info[:2]>=(3,13) + +import textwrap + +class BadCode(ValueError): + pass + +# For AugAssign the operator must be converted to a string. +augOps = { + ast.Add: '+=', + ast.Sub: '-=', + ast.Mult: '*=', + ast.Div: '/=', + ast.Mod: '%=', + ast.Pow: '**=', + ast.LShift: '<<=', + ast.RShift: '>>=', + ast.BitOr: '|=', + ast.BitXor: '^=', + ast.BitAnd: '&=', + ast.FloorDiv: '//=', + ast.MatMult: '@=', +} + +# For creation allowed magic method names. See also +# https://docs.python.org/3/reference/datamodel.html#special-method-names +__allowed_magic_methods__ = frozenset([ + '__init__', + '__contains__', + '__lt__', + '__le__', + '__eq__', + '__ne__', + '__gt__', + '__ge__', + ]) + +def __fix_set__(value, default=frozenset()): + if isinstance(value,(tuple,list,set,dict)): + return frozenset(value) + elif isinstance(value,frozenset): + return value + elif bool(value): + return default + else: + return frozenset() + +__rl_unsafe__ = frozenset('''builtins breakpoint __annotations__ co_argcount co_cellvars co_code co_consts + __code__ co_filename co_firstlineno co_flags co_freevars co_kwonlyargcount + co_lnotab co_name co_names co_nlocals co_posonlyargcount co_stacksize + co_varnames cr_await cr_code cr_frame cr_origin cr_running __defaults__ + f_back f_builtins f_code f_exc_traceback f_exc_type f_exc_value f_globals + f_lasti f_lineno f_locals f_restricted f_trace __func__ func_code func_defaults + func_doc func_globals func_name gi_code gi_frame gi_running gi_yieldfrom + __globals__ im_class im_func im_self __iter__ __kwdefaults__ __module__ + __name__ next __qualname__ __self__ tb_frame tb_lasti tb_lineno tb_next + globals vars locals + type eval exec aiter anext compile open + dir print classmethod staticmethod __import__ super property'''.split() + ) +__rl_unsafe_re__ = re.compile(r'\b(?:%s)' % '|'.join(__rl_unsafe__),re.M) + + +def copy_locations(new_node, old_node): + ast.copy_location(new_node, old_node) + ast.fix_missing_locations(new_node) + +class UntrustedAstTransformer(ast.NodeTransformer): + + def __init__(self, names_seen=None, nameIsAllowed=None): + super(UntrustedAstTransformer, self).__init__() + self.names_seen = {} if names_seen is None else names_seen + self.nameIsAllowed = nameIsAllowed + + # Global counter to construct temporary variable names. + self._tmp_idx = 0 + self._tmp_pfx = '_tmp%s' % repr(time.time()).replace('.','') + + @property + def tmpName(self): + name = '%s%s' % (self._tmp_pfx,self._tmp_idx) + self._tmp_idx += 1 + return name + + def error(self, node, msg): + raise BadCode('Line %s: %s' % (getattr(node, 'lineno', '??'), msg)) + + def guard_iter(self, node): + """ + Converts: + for x in expr + to + for x in __rl_getiter__(expr) + + Also used for + * list comprehensions + * dict comprehensions + * set comprehensions + * generator expresions + """ + node = self.visit_children(node) + + if isinstance(node.target, ast.Tuple): + spec = self.gen_unpack_spec(node.target) + new_iter = ast.Call( + func=ast.Name('__rl_iter_unpack_sequence__', ast.Load()), + args=[node.iter, spec, ast.Name('__rl_getiter__', ast.Load())], + keywords=[]) + else: + new_iter = ast.Call( + func=ast.Name('__rl_getiter__', ast.Load()), + args=[node.iter], + keywords=[]) + + copy_locations(new_iter, node.iter) + node.iter = new_iter + return node + + def is_starred(self, ob): + return isinstance(ob, ast.Starred) + + def gen_unpack_spec(self, tpl): + """Generate a specification for '__rl_unpack_sequence__'. + + This spec is used to protect sequence unpacking. + The primary goal of this spec is to tell which elements in a sequence + are sequences again. These 'child' sequences have to be protected + again. + + For example there is a sequence like this: + (a, (b, c), (d, (e, f))) = g + + On a higher level the spec says: + - There is a sequence of len 3 + - The element at index 1 is a sequence again with len 2 + - The element at index 2 is a sequence again with len 2 + - The element at index 1 in this subsequence is a sequence again + with len 2 + + With this spec '__rl_unpack_sequence__' does something like this for + protection (len checks are omitted): + + t = list(__rl_getiter__(g)) + t[1] = list(__rl_getiter__(t[1])) + t[2] = list(__rl_getiter__(t[2])) + t[2][1] = list(__rl_getiter__(t[2][1])) + return t + + The 'real' spec for the case above is then: + spec = { + 'min_len': 3, + 'childs': ( + (1, {'min_len': 2, 'childs': ()}), + (2, { + 'min_len': 2, + 'childs': ( + (1, {'min_len': 2, 'childs': ()}) + ) + } + ) + ) + } + + So finally the assignment above is converted into: + (a, (b, c), (d, (e, f))) = __rl_unpack_sequence__(g, spec) + """ + spec = ast.Dict(keys=[], values=[]) + + spec.keys.append(ast.Constant('childs')) + spec.values.append(ast.Tuple([], ast.Load())) + + # starred elements in a sequence do not contribute into the min_len. + # For example a, b, *c = g + # g must have at least 2 elements, not 3. 'c' is empyt if g has only 2. + min_len = len([ob for ob in tpl.elts if not self.is_starred(ob)]) + offset = 0 + + for idx, val in enumerate(tpl.elts): + # After a starred element specify the child index from the back. + # Since it is unknown how many elements from the sequence are + # consumed by the starred element. + # For example a, *b, (c, d) = g + # Then (c, d) has the index '-1' + if self.is_starred(val): + offset = min_len + 1 + + elif isinstance(val, ast.Tuple): + el = ast.Tuple([], ast.Load()) + el.elts.append(ast.Constant(idx - offset)) + el.elts.append(self.gen_unpack_spec(val)) + spec.values[0].elts.append(el) + + spec.keys.append(ast.Constant('min_len')) + spec.values.append(ast.Constant(min_len)) + + return spec + + def protect_unpack_sequence(self, target, value): + spec = self.gen_unpack_spec(target) + return ast.Call( + func=ast.Name('__rl_unpack_sequence__', ast.Load()), + args=[value, spec, ast.Name('__rl_getiter__', ast.Load())], + keywords=[]) + + def gen_unpack_wrapper(self, node, target, ctx='store'): + """Helper function to protect tuple unpacks. + + node: used to copy the locations for the new nodes. + target: is the tuple which must be protected. + ctx: Defines the context of the returned temporary node. + + It returns a tuple with two element. + + Element 1: Is a temporary name node which must be used to + replace the target. + The context (store, param) is defined + by the 'ctx' parameter.. + + Element 2: Is a try .. finally where the body performs the + protected tuple unpack of the temporary variable + into the original target. + """ + + # Generate a tmp name to replace the tuple with. + tnam = self.tmpName + + # Generates an expressions which protects the unpack. + # converter looks like 'wrapper(tnam)'. + # 'wrapper' takes care to protect sequence unpacking with __rl_getiter__. + converter = self.protect_unpack_sequence( + target, + ast.Name(tnam, ast.Load())) + + # Assign the expression to the original names. + # Cleanup the temporary variable. + # Generates: + # try: + # # converter is 'wrapper(tnam)' + # arg = converter + # finally: + # del tmp_arg + try_body = [ast.Assign(targets=[target], value=converter)] + finalbody = [self.gen_del_stmt(tnam)] + + cleanup = ast.Try( + body=try_body, finalbody=finalbody, handlers=[], orelse=[]) + + if ctx == 'store': + ctx = ast.Store() + elif ctx == 'param': + ctx = ast.Param() + else: # pragma: no cover + # Only store and param are defined ctx. + raise NotImplementedError('bad ctx "%s"' % type(ctx)) + + # This node is used to catch the tuple in a tmp variable. + tmp_target = ast.Name(tnam, ctx) + + copy_locations(tmp_target, node) + copy_locations(cleanup, node) + + return (tmp_target, cleanup) + + def gen_lambda(self, args, body): + return ast.Lambda( + args=ast.arguments( + args=args, vararg=None, kwarg=None, defaults=[]), + body=body) + + def gen_del_stmt(self, name_to_del): + return ast.Delete(targets=[ast.Name(name_to_del, ast.Del())]) + + def transform_slice(self, slice_): + """Transform slices into function parameters. + + ast.Slice nodes are only allowed within a ast.Subscript node. + To use a slice as an argument of ast.Call it has to be converted. + Conversion is done by calling the 'slice' function from builtins + """ + + if isinstance(slice_, ast.Index): + return slice_.value + + elif isinstance(slice_, ast.Slice): + # Create a python slice object. + args = [] + + if slice_.lower: + args.append(slice_.lower) + else: + args.append(ast.Constant(None)) + + if slice_.upper: + args.append(slice_.upper) + else: + args.append(ast.Constant(None)) + + if slice_.step: + args.append(slice_.step) + else: + args.append(ast.Constant(None)) + + return ast.Call( + func=ast.Name('slice', ast.Load()), + args=args, + keywords=[]) + + elif isinstance(slice_, ast.ExtSlice): + dims = ast.Tuple([], ast.Load()) + for item in slice_.dims: + dims.elts.append(self.transform_slice(item)) + return dims + + elif isPy39: + return slice_ + + else: # pragma: no cover + # Index, Slice and ExtSlice are only defined Slice types. + raise NotImplementedError("Unknown slice type: %s" % slice_) + + def isAllowedName(self, node, name): + if name is None: return + self.nameIsAllowed(name) + + def check_function_argument_names(self, node): + # In python3 arguments are always identifiers. + # In python2 the 'Python.asdl' specifies expressions, but + # the python grammer allows only identifiers or a tuple of + # identifiers. If its a tuple 'tuple parameter unpacking' is used, + # which is gone in python3. + # See https://www.python.org/dev/peps/pep-3113/ + + for arg in node.args.args: + self.isAllowedName(node, arg.arg) + + if node.args.vararg: + self.isAllowedName(node, node.args.vararg.arg) + + if node.args.kwarg: + self.isAllowedName(node, node.args.kwarg.arg) + + for arg in node.args.kwonlyargs: + self.isAllowedName(node, arg.arg) + + def check_import_names(self, node): + """Check the names being imported. + + This is a protection against rebinding dunder names like + __rl_getitem__,__rl_set__ via imports. + + => 'from _a import x' is ok, because '_a' is not added to the scope. + """ + for name in node.names: + if '*' in name.name: + self.error(node, '"*" imports are not allowed.') + self.isAllowedName(node, name.name) + if name.asname: + self.isAllowedName(node, name.asname) + + return self.visit_children(node) + + def gen_attr_check(self, node, attr_name): + """Check if 'attr_name' is allowed on the object in node. + + It generates (_getattr_(node, attr_name) and node). + """ + + call_getattr = ast.Call( + func=ast.Name('__rl_getattr__', ast.Load()), + args=[node, ast.Constant(attr_name)], + keywords=[]) + + return ast.BoolOp(op=ast.And(), values=[call_getattr, node]) + + def visit_Constant(self, node): + """Allow constant literals with restriction for Ellipsis. + + Constant replaces Num, Str, Bytes, NameConstant and Ellipsis in + Python 3.8+. + :see: https://docs.python.org/dev/whatsnew/3.8.html#deprecated + """ + if node.value is Ellipsis: + # Deny using `...`. + # Special handling necessary as ``self.not_allowed(node)`` + # would return the Error Message: + # 'Constant statements are not allowed.' + # which is only partial true. + self.error(node, 'Ellipsis statements are not allowed.') + return + return self.visit_children(node) + + # ast for Variables + def visit_Name(self, node): + node = self.visit_children(node) + + if isinstance(node.ctx, ast.Load): + if node.id == 'print': + self.error(node,'print function is not allowed') + self.names_seen[node.id] = True + + self.isAllowedName(node, node.id) + return node + + def visit_Call(self, node): + """Checks calls with '*args' and '**kwargs'. + + Note: The following happens only if '*args' or '**kwargs' is used. + + Transfroms 'foo()' into + __rl_apply__(foo, ) + + The thing is that '__rl_apply__' has only '*args', '**kwargs', so it gets + Python to collapse all the myriad ways to call functions + into one manageable from. + + From there, '__rl_apply__()' wraps args and kws in guarded accessors, + then calls the function, returning the value. + """ + + if isinstance(node.func, ast.Name): + if node.func.id == 'exec': + self.error(node, 'Exec calls are not allowed.') + elif node.func.id == 'eval': + self.error(node, 'Eval calls are not allowed.') + + needs_wrap = False + + for pos_arg in node.args: + if isinstance(pos_arg, ast.Starred): + needs_wrap = True + + for keyword_arg in node.keywords: + if keyword_arg.arg is None: + needs_wrap = True + + node = self.visit_children(node) + + #if not needs_wrap: + # return node + + node.args.insert(0, node.func) + node.func = ast.Name('__rl_apply__', ast.Load()) + copy_locations(node.func, node.args[0]) + return node + + def visit_Attribute(self, node): + """Checks and mutates attribute access/assignment. + + 'a.b' becomes '__rl_getattr__(a, "b")' + """ + if node.attr.startswith('__') and node.attr != '__' and not self.nameIsAllowed(node.attr,False): + self.error(node, '"%s" is an invalid attribute'%node.attr) + + if isinstance(node.ctx, ast.Load): + node = self.visit_children(node) + new_node = ast.Call( + func=ast.Name('__rl_getattr__', ast.Load()), + args=[node.value, ast.Constant(node.attr)], + keywords=[]) + + copy_locations(new_node, node) + return new_node + + elif isinstance(node.ctx, (ast.Store, ast.Del)): + node = self.visit_children(node) + new_value = ast.Call( + func=ast.Name('__rl_sd__', ast.Load()), + args=[node.value], + keywords=[]) + + copy_locations(new_value, node.value) + node.value = new_value + return node + + else: # pragma: no cover + # Impossible Case only ctx Load, Store and Del are defined in ast. + raise NotImplementedError("Unknown ctx type: %s" % type(node.ctx)) + + # Subscripting + def visit_Subscript(self, node): + """Transforms all kinds of subscripts. + + 'v[a]' becomes '__rl_getitem__(foo, a)' + 'v[:b]' becomes '__rl_getitem__(foo, slice(None, b, None))' + 'v[a:]' becomes '__rl_getitem__(foo, slice(a, None, None))' + 'v[a:b]' becomes '__rl_getitem__(foo, slice(a, b, None))' + 'v[a:b:c]' becomes '__rl_getitem__(foo, slice(a, b, c))' + 'v[a,b:c] becomes '__rl_getitem__(foo, (a, slice(b, c, None)))' + #'v[a] = c' becomes '_rl_write__(v)[a] = c' + #'del v[a]' becomes 'del __rl_sd__(v)[a]' + """ + node = self.visit_children(node) + + # 'AugStore' and 'AugLoad' are defined in 'Python.asdl' as possible + # 'expr_context'. However, according to Python/ast.c + # they are NOT used by the implementation => No need to worry here. + # Instead ast.c creates 'AugAssign' nodes, which can be visit_ed. + + if isinstance(node.ctx, ast.Load): + new_node = ast.Call( + func=ast.Name('__rl_getitem__', ast.Load()), + args=[node.value, self.transform_slice(node.slice)], + keywords=[]) + + copy_locations(new_node, node) + return new_node + + elif isinstance(node.ctx, (ast.Del, ast.Store)): + #new_value = ast.Call( + # func=ast.Name('__rl_sd__', ast.Load()), + # args=[node.value], + # keywords=[]) + + #copy_locations(new_value, node) + #node.value = new_value + return node + + else: # pragma: no cover + # Impossible Case only ctx Load, Store and Del are defined in ast. + raise NotImplementedError("Unknown ctx type: %s" % type(node.ctx)) + + # Statements + def visit_Assign(self, node): + node = self.visit_children(node) + + if not any(isinstance(t, ast.Tuple) for t in node.targets): + return node + + # Handle sequence unpacking. + # For briefness this example omits cleanup of the temporary variables. + # Check 'transform_tuple_assign' how its done. + # + # - Single target (with nested support) + # (a, (b, (c, d))) = + # is converted to + # (a, t1) = __rl_getiter__() + # (b, t2) = __rl_getiter__(t1) + # (c, d) = __rl_getiter__(t2) + # + # - Multi targets + # (a, b) = (c, d) = + # is converted to + # (c, d) = __rl_getiter__() + # (a, b) = __rl_getiter__() + # Why is this valid ? The original bytecode for this multi targets + # behaves the same way. + + # ast.NodeTransformer works with list results. + # He injects it at the rightplace of the node's parent statements. + new_nodes = [] + + # python fills the right most target first. + for target in reversed(node.targets): + if isinstance(target, ast.Tuple): + wrapper = ast.Assign( + targets=[target], + value=self.protect_unpack_sequence(target, node.value)) + new_nodes.append(wrapper) + else: + new_node = ast.Assign(targets=[target], value=node.value) + new_nodes.append(new_node) + + for new_node in new_nodes: + copy_locations(new_node, node) + + return new_nodes + + def visit_AugAssign(self, node): + """Forbid certain kinds of AugAssign + + According to the language reference (and ast.c) the following nodes + are are possible: + Name, Attribute, Subscript + + Note that although augmented assignment of attributes and + subscripts is disallowed, augmented assignment of names (such + as 'n += 1') is allowed. + 'n += 1' becomes 'n = __rl_augAssign__("+=", n, 1)' + """ + + node = self.visit_children(node) + + if isinstance(node.target, ast.Attribute): + self.error(node, "Augmented assignment of attributes is not allowed.") + + elif isinstance(node.target, ast.Subscript): + self.error(node, "Augmented assignment of object items and slices is not allowed.") + + elif isinstance(node.target, ast.Name): + new_node = ast.Assign( + targets=[node.target], + value=ast.Call( + func=ast.Name('__rl_augAssign__', ast.Load()), + args=[ + ast.Constant(augOps[type(node.op)]), + ast.Name(node.target.id, ast.Load()), + node.value + ], + keywords=[])) + + copy_locations(new_node, node) + return new_node + else: # pragma: no cover + # Impossible Case - Only Node Types: + # * Name + # * Attribute + # * Subscript + # defined, those are checked before. + raise NotImplementedError("Unknown target type: %s" % type(node.target)) + + def visit_While(node): + self.visit_children(node) + return node + + def visit_ExceptHandler(self, node): + """Protect tuple unpacking on exception handlers. + + try: + ..... + except Exception as (a, b): + .... + + becomes + + try: + ..... + except Exception as tmp: + try: + (a, b) = __rl_getiter__(tmp) + finally: + del tmp + """ + node = self.visit_children(node) + + self.isAllowedName(node, node.name) + return node + + def visit_With(self, node): + """Protect tuple unpacking on with statements.""" + node = self.visit_children(node) + + items = node.items + + for item in reversed(items): + if isinstance(item.optional_vars, ast.Tuple): + tmp_target, unpack = self.gen_unpack_wrapper( + node, + item.optional_vars) + + item.optional_vars = tmp_target + node.body.insert(0, unpack) + + return node + + # Function and class definitions + def visit_FunctionDef(self, node): + """Allow function definitions (`def`) with some restrictions.""" + self.isAllowedName(node, node.name) + self.check_function_argument_names(node) + return self.visit_children(node) + + def visit_Lambda(self, node): + """Allow lambda with some restrictions.""" + self.check_function_argument_names(node) + return self.visit_children(node) + + def visit_ClassDef(self, node): + """Check the name of a class definition.""" + self.isAllowedName(node, node.name) + node = self.visit_children(node) + if any(keyword.arg == 'metaclass' for keyword in node.keywords): + self.error(node, 'The keyword argument "metaclass" is not allowed.') + CLASS_DEF = textwrap.dedent('''\ + class %s(metaclass=__metaclass__): + pass + ''' % node.name) + new_class_node = ast.parse(CLASS_DEF).body[0] + new_class_node.body = node.body + new_class_node.bases = node.bases + new_class_node.decorator_list = node.decorator_list + return new_class_node + + # Imports + def visit_Import(self, node): + return self.check_import_names(node) + + node = self.visit_children(node) + new_node = ast.Call( + func=ast.Name('__rl_add__', ast.Load()), + args=[node.left, node.right], + keywords=[]) + copy_locations(new_node, node) + return new_node + + def visit_BinOp(self,node): + node = self.visit_children(node) + op = node.op + if isinstance(op,(ast.Mult,ast.Add,ast.Pow)): + opf = ('__rl_mult__' if isinstance(op,ast.Mult) + else '__rl_add__' if isinstance(op,ast.Add) + else '__rl_pow__') + new_node = ast.Call( + func=ast.Name(opf, ast.Load()), + args=[node.left, node.right], + keywords=[]) + copy_locations(new_node, node) + return new_node + return node + + visit_ImportFrom = visit_Import + visit_For = guard_iter + visit_comprehension = guard_iter + + def generic_visit(self, node): + """Reject nodes which do not have a corresponding `visit` method.""" + self.not_allowed(node) + + def not_allowed(self, node): + self.error(node, '%s statements are not allowed.'%node.__class__.__name__) + + def visit_children(self, node): + """Visit the contents of a node.""" + return super(UntrustedAstTransformer, self).generic_visit(node) + + if eval_debug>=2: + def visit(self, node): + method = 'visit_' + node.__class__.__name__ + visitor = getattr(self, method, self.generic_visit) + print('visitor=%s=%r node=%r' % (method,visitor,node)) + return visitor(node) + + visit_Ellipsis = not_allowed + visit_MatMult = not_allowed + visit_Exec = not_allowed + visit_Nonlocal = not_allowed + visit_AsyncFunctionDef = not_allowed + visit_Await = not_allowed + visit_AsyncFor = not_allowed + visit_AsyncWith = not_allowed + visit_Print = not_allowed + + visit_Constant = visit_children + visit_Num = visit_children + visit_Str = visit_children + visit_Bytes = visit_children + visit_List = visit_children + visit_Tuple = visit_children + visit_Set = visit_children + visit_Dict = visit_children + visit_FormattedValue = visit_children + visit_JoinedStr = visit_children + visit_NameConstant = visit_children + visit_Load = visit_children + visit_Store = visit_children + visit_Del = visit_children + visit_Starred = visit_children + visit_Expression = visit_children + visit_Expr = visit_children + visit_UnaryOp = visit_children + visit_UAdd = visit_children + visit_USub = visit_children + visit_Not = visit_children + visit_Invert = visit_children + visit_Add = visit_children + visit_Sub = visit_children + visit_Mult = visit_children + visit_Div = visit_children + visit_FloorDiv = visit_children + visit_Pow = visit_children + visit_Mod = visit_children + visit_LShift = visit_children + visit_RShift = visit_children + visit_BitOr = visit_children + visit_BitXor = visit_children + visit_BitAnd = visit_children + visit_BoolOp = visit_children + visit_And = visit_children + visit_Or = visit_children + visit_Compare = visit_children + visit_Eq = visit_children + visit_NotEq = visit_children + visit_Lt = visit_children + visit_LtE = visit_children + visit_Gt = visit_children + visit_GtE = visit_children + visit_Is = visit_children + visit_IsNot = visit_children + visit_In = visit_children + visit_NotIn = visit_children + visit_keyword = visit_children + visit_IfExp = visit_children + visit_Index = visit_children + visit_Slice = visit_children + visit_ExtSlice = visit_children + visit_ListComp = visit_children + visit_SetComp = visit_children + visit_GeneratorExp = visit_children + visit_DictComp = visit_children + visit_Raise = visit_children + visit_Assert = visit_children + visit_Delete = visit_children + visit_Pass = visit_children + visit_alias = visit_children + visit_If = visit_children + visit_Break = visit_children + visit_Continue = visit_children + visit_Try = visit_children + visit_TryFinally = visit_children + visit_TryExcept = visit_children + visit_withitem = visit_children + visit_arguments = visit_children + visit_arg = visit_children + visit_Return = visit_children + visit_Yield = visit_children + visit_YieldFrom = visit_children + visit_Global = visit_children + visit_Module = visit_children + visit_Param = visit_children + +def astFormat(node): + return ast.dump(copy.deepcopy(node),annotate_fields=True, include_attributes=True,indent=4) + +class __rl_SafeIter__: + def __init__(self, it, owner): + self.__rl_iter__ = owner().__rl_real_iter__(it) + self.__rl_owner__ = owner + + def __iter__(self): + return self + + def __next__(self): + self.__rl_owner__().__rl_check__() + return next(self.__rl_iter__) + + next = __next__ # Python 2 compat + +__rl_safe_builtins__ = {} #constructed below +def safer_globals(g=None): + if g is None: + g = sys._getframe(1).f_globals.copy() + for name in ('__annotations__', '__doc__', '__loader__', '__name__', '__package__', '__spec__'): + if name in g: + del g[name] + g['__builtins__'] = __rl_safe_builtins__.copy() + return g + +math_log10 = math.log10 +__rl_undef__ = object() +class __RL_SAFE_ENV__: + __time_time__ = time.time + __weakref_ref__ = weakref.ref + __slicetype__ = type(slice(0)) + def __init__(self, timeout=None, allowed_magic_methods=None, allowed_magic_names=None): + self.timeout = timeout if timeout is not None else self.__rl_tmax__ + self.allowed_magic_methods = __fix_set__(allowed_magic_methods, __allowed_magic_methods__) + self.allowed_magic_names = __fix_set__(allowed_magic_names) + import builtins + self.__rl_gen_range__ = builtins.range + + self.__rl_real_iter__ = builtins.iter + + class __rl_dict__(dict): + def __new__(cls, *args,**kwds): + if len(args)==1 and not isinstance(args[0],dict): + try: + it = self.__real_iter__(args[0]) + except TypeError: + pass + else: + args = (self.__rl_getiter__(it),) + return dict.__new__(cls,*args,**kwds) + + class __rl_missing_func__: + def __init__(self,name): + self.__name__ = name + def __call__(self,*args,**kwds): + raise BadCode('missing global %s' % self.__name__) + + self.real_bi = builtins + self.bi_replace = ( + ('open',__rl_missing_func__('open')), + ('iter',self.__rl_getiter__), + ) + + __rl_safe_builtins__.update({_:getattr(builtins,_) for _ in + ('''None False True abs bool callable chr complex divmod float hash hex id int + isinstance issubclass len oct ord range repr round slice str tuple setattr + classmethod staticmethod property divmod next object getattr dict iter pow list + type max min sum enumerate zip hasattr filter map any all sorted reversed range + set frozenset + + ArithmeticError AssertionError AttributeError BaseException BufferError BytesWarning + DeprecationWarning EOFError EnvironmentError Exception FloatingPointError FutureWarning + GeneratorExit IOError ImportError ImportWarning IndentationError IndexError KeyError + KeyboardInterrupt LookupError MemoryError NameError NotImplementedError OSError + OverflowError PendingDeprecationWarning ReferenceError RuntimeError RuntimeWarning + StopIteration SyntaxError SyntaxWarning SystemError SystemExit TabError TypeError + UnboundLocalError UnicodeDecodeError UnicodeEncodeError UnicodeError UnicodeTranslateError + UnicodeWarning UserWarning ValueError Warning ZeroDivisionError + __build_class__''' + ).split()}) + + self.__rl_builtins__ = __rl_builtins__ = {_:__rl_missing_func__(_) for _ in dir(builtins) if callable(getattr(builtins,_))} + __rl_builtins__.update(__rl_safe_builtins__) + + #these are used in the tree visitor + __rl_builtins__['__rl_add__'] = self.__rl_add__ + __rl_builtins__['__rl_mult__'] = self.__rl_mult__ + __rl_builtins__['__rl_pow__'] = self.__rl_pow__ + __rl_builtins__['__rl_sd__'] = self.__rl_sd__ + __rl_builtins__['__rl_augAssign__'] = self.__rl_augAssign__ + __rl_builtins__['__rl_getitem__'] = self.__rl_getitem__ + __rl_builtins__['__rl_getattr__'] = self.__rl_getattr__ + __rl_builtins__['__rl_getiter__'] = self.__rl_getiter__ + __rl_builtins__['__rl_max_len__'] = self.__rl_max_len__ + __rl_builtins__['__rl_max_pow_digits__'] = self.__rl_max_pow_digits__ + __rl_builtins__['__rl_iter_unpack_sequence__'] = self.__rl_iter_unpack_sequence__ + __rl_builtins__['__rl_unpack_sequence__'] = self.__rl_unpack_sequence__ + __rl_builtins__['__rl_apply__'] = lambda func,*args,**kwds: self.__rl_apply__(func,args,kwds) + __rl_builtins__['__rl_SafeIter__'] = __rl_SafeIter__ + + #these are tested builtins + __rl_builtins__['getattr'] = self.__rl_getattr__ + __rl_builtins__['dict'] = __rl_dict__ + __rl_builtins__['iter'] = self.__rl_getiter__ + __rl_builtins__['pow'] = self.__rl_pow__ + __rl_builtins__['list'] = self.__rl_list__ + __rl_builtins__['type'] = self.__rl_type__ + __rl_builtins__['max'] = self.__rl_max__ + __rl_builtins__['min'] = self.__rl_min__ + __rl_builtins__['sum'] = self.__rl_sum__ + __rl_builtins__['enumerate'] = self.__rl_enumerate__ + __rl_builtins__['zip'] = self.__rl_zip__ + __rl_builtins__['hasattr'] = self.__rl_hasattr__ + __rl_builtins__['filter'] = self.__rl_filter__ + __rl_builtins__['map'] = self.__rl_map__ + __rl_builtins__['any'] = self.__rl_any__ + __rl_builtins__['all'] = self.__rl_all__ + __rl_builtins__['sorted'] = self.__rl_sorted__ + __rl_builtins__['reversed'] = self.__rl_reversed__ + __rl_builtins__['range'] = self.__rl_range__ + __rl_builtins__['set'] = self.__rl_set__ + __rl_builtins__['frozenset'] = self.__rl_frozenset__ + + def __rl_type__(self,*args): + if len(args)==1: return type(*args) + raise BadCode('type call error') + + def __rl_check__(self): + if self.__time_time__() >= self.__rl_limit__: + raise BadCode('Resources exceeded') + + def __rl_sd__(self,obj): + return obj + + def __rl_getiter__(self,it): + return __rl_SafeIter__(it,owner=self.__weakref_ref__(self)) + + def __rl_max__(self,arg,*args,**kwds): + if args: + arg = [arg] + arg.extend(args) + return max(self.__rl_args_iter__(arg),**kwds) + + def __rl_min__(self,arg,*args,**kwds): + if args: + arg = [arg] + arg.extend(args) + return min(self.__rl_args_iter__(arg),**kwds) + + def __rl_sum__(self, sequence, start=0): + return sum(self.__rl_args_iter__(sequence), start) + + def __rl_enumerate__(self, seq): + return enumerate(self.__rl_args_iter__(seq)) + + def __rl_zip__(self,*args): + return zip(*[self.__rl_args_iter__(self.__rl_getitem__(args, i)) for i in range(len(args))]) + + def __rl_hasattr__(self, obj, name): + try: + self.__rl_getattr__(obj, name) + except (AttributeError, BadCode, TypeError): + return False + return True + + def __rl_filter__(self, f, seq): + return filter(f,self.__rl_args_iter__(seq)) + + def __rl_map__(self, f, seq): + return map(f,self.__rl_args_iter__(seq)) + + def __rl_any__(self, seq): + return any(self.__rl_args_iter__(seq)) + + def __rl_all__(self, seq): + return all(self.__rl_args_iter__(seq)) + + def __rl_sorted__(self, seq, **kwds): + return sorted(self.__rl_args_iter__(seq),**kwds) + + def __rl_reversed__(self, seq): + return self.__rl_args_iter__(reversed(seq)) + + def __rl_range__(self,start,*args): + return self.__rl_getiter__(range(start,*args)) + + def __rl_set__(self, it): + return set(self.__rl_args_iter__(it)) + + def __rl_frozenset__(self, it=()): + return frozenset(self.__rl_args_iter__(it)) + + def __rl_iter_unpack_sequence__(self, it, spec, _getiter_): + """Protect sequence unpacking of targets in a 'for loop'. + + The target of a for loop could be a sequence. + For example "for a, b in it" + => Each object from the iterator needs guarded sequence unpacking. + """ + # The iteration itself needs to be protected as well. + for ob in _getiter_(it): + yield self.__rl_unpack_sequence__(ob, spec, _getiter_) + + def __rl_unpack_sequence__(self, it, spec, _getiter_): + """Protect nested sequence unpacking. + + Protect the unpacking of 'it' by wrapping it with '_getiter_'. + Furthermore for each child element, defined by spec, + __rl_unpack_sequence__ is called again. + + Have a look at transformer.py 'gen_unpack_spec' for a more detailed + explanation. + """ + # Do the guarded unpacking of the sequence. + ret = list(self.__rl_getiter__(it)) + + # If the sequence is shorter then expected the interpreter will raise + # 'ValueError: need more than X value to unpack' anyway + # => No childs are unpacked => nothing to protect. + if len(ret) < spec['min_len']: + return ret + + # For all child elements do the guarded unpacking again. + for (idx, child_spec) in spec['childs']: + ret[idx] = self.__rl_unpack_sequence__(ret[idx], child_spec, _getiter_) + return ret + + def __rl_is_allowed_name__(self, name, crash=True): + """Check names if they are allowed. + If ``allow_magic_methods is True`` names in `__allowed_magic_methods__` + are additionally allowed although their names start with `_`. + """ + if isinstance(name,strTypes): + if (name not in self.allowed_magic_names + and (name in __rl_unsafe__ or (name.startswith('__') + and name!='__' + and name not in self.allowed_magic_methods))): + if not crash: return False + raise BadCode('unsafe access of %s' % name) + return True + + def __rl_getattr__(self, obj, a, *args): + if isinstance(obj, strTypes) and a=='format': + raise BadCode('%s.format is not implemented' % type(obj)) + self.__rl_is_allowed_name__(a) + return getattr(obj,a,*args) + + def __rl_getitem__(self, obj, a): + if type(a) is self.__slicetype__: + if a.step is not None: + v = obj[a] + else: + start = a.start + stop = a.stop + if start is None: + start = 0 + if stop is None: + v = obj[start:] + else: + v = obj[start:stop] + return v + elif isinstance(a,strTypes): + self.__rl_is_allowed_name__(a) + return obj[a] + return obj[a] + + __rl_tmax__ = 5 + __rl_max_len__ = 100000 + __rl_max_pow_digits__ = 100 + + def __rl_add__(self, a, b): + if (hasattr(a, '__len__') and hasattr(b, '__len__') + and (len(a) + len(b)) > self.__rl_max_len__): + raise BadCode("excessive length") + return a + b + + def __rl_mult__(self, a, b): + if ((hasattr(a, '__len__') and b * len(a) > self.__rl_max_len__) + or (hasattr(b, '__len__') and a * len(b) > self.__rl_max_len__)): + raise BadCode("excessive length") + return a * b + + def __rl_pow__(self, a, b): + try: + if b>0: + if int(b*math_log10(a)+1)>self.__rl_max_pow_digits__: + raise BadCode + except: + raise BadCode('%r**%r invalid or too large' % (a,b)) + return a ** b + + def __rl_augAssign__(self,op,v,i): + if op=='+=': return self.__rl_add__(v,i) + if op=='-=': return v-i + if op=='*=': return self.__rl_mult__(v,i) + if op=='/=': return v/i + if op=='%=': return v%i + if op=='**=': return self.__rl_pow__(v,i) + if op=='<<=': return v<>=': return v>>i + if op=='|=': return v|i + if op=='^=': return v^i + if op=='&=': return v&i + if op=='//=': return v//i + + def __rl_apply__(self, func, args, kwds): + obj = getattr(func,'__self__',None) + if obj: + if isinstance(obj,dict) and func.__name__ in ('pop','setdefault','get', 'popitem'): + self.__rl_is_allowed_name__(args[0]) + return func(*[a for a in self.__rl_getiter__(args)], **{k:v for k,v in kwds.items()}) + + def __rl_args_iter__(self,*args): + if len(args) == 1: + i = args[0] + # Don't double-wrap + if isinstance(i, __rl_SafeIter__): + return i + if not isinstance(i,self.__rl_gen_range__): + return self.__rl_getiter__(i) + return self.__rl_getiter__(iter(*args)) + + def __rl_list__(self,it): + return list(self.__rl_getiter__(it)) + + def __rl_compile__(self, src, fname='', mode="eval", flags=0, inherit=True, visit=None): + names_seen = {} + if not visit: + bcode = compile(src, fname, mode=mode, flags=flags, dont_inherit=not inherit) + else: + astc = ast.parse(src, fname, mode) + if eval_debug>0: + print('pre:\n%s\n'%astFormat(astc)) + astc = visit(astc) + if eval_debug>0: + print('post:\n%s\n'%astFormat(astc)) + bcode = compile(astc, fname, mode=mode) + return bcode, names_seen + + def __rl_safe_eval__(self, expr, g, l, mode, timeout=None, allowed_magic_methods=None, __frame_depth__=3, + allowed_magic_names=None): + if allowed_magic_methods is not None: + self.allowed_magic_methods = __fix_set__(allowed_magic_methods, __allowed_magic_methods__) + if allowed_magic_names is not None: + self.allowed_magic_names = __fix_set__(allowed_magic_names) + + bcode, ns = self.__rl_compile__(expr, fname='', mode=mode, flags=0, inherit=True, + visit=UntrustedAstTransformer(nameIsAllowed=self.__rl_is_allowed_name__).visit) + if None in (l,g): + G = sys._getframe(__frame_depth__) + L = {n:r for n,r in G.f_locals.items()} if l is None else l + G = G.f_globals.copy() if g is None else g + else: + G = g + L = l + obi = (G['__builtins__'],) if '__builtins__' in G else False + G['__builtins__'] = self.__rl_builtins__ + self.__rl_limit__ = self.__time_time__() + (timeout if timeout is not None else self.timeout) + if allowed_magic_methods is not None: + self.allowed_magic_methods = ( __allowed_magic_methods__ if allowed_magic_methods==True + else allowed_magic_methods) if allowed_magic_methods else [] + sbi = [].append + bi = self.real_bi + bir = self.bi_replace + for n, r in bir: + sbi(getattr(bi,n)) + setattr(bi,n,r) + try: + return eval(bcode,G,L) + finally: + sbi = sbi.__self__ + for i, (n, r) in enumerate(bir): + setattr(bi,n,sbi[i]) + if obi: + G['__builtins__'] = obi[0] + +class __rl_safe_eval__: + '''creates one environment and re-uses it''' + mode = 'eval' + def __init__(self): + self.env = None + + def __call__(self, expr, g=None, l=None, timeout=None, allowed_magic_methods=None, allowed_magic_names=None): + if not self.env: self.env = __RL_SAFE_ENV__() + return self.env.__rl_safe_eval__(expr, g, l, self.mode, timeout=timeout, + allowed_magic_methods=allowed_magic_methods, + __frame_depth__=2, allowed_magic_names=allowed_magic_names) + +class __rl_safe_exec__(__rl_safe_eval__): + mode = 'exec' + +def rl_extended_literal_eval(expr, safe_callables=None, safe_names=None): + if safe_callables is None: + safe_callables = {} + if safe_names is None: + safe_names = {} + safe_names = safe_names.copy() + safe_names.update({'None': None, 'True': True, 'False': False}) + #make these readonly with MappingProxyType + safe_names = types.MappingProxyType(safe_names) + safe_callables = types.MappingProxyType(safe_callables) + if isinstance(expr, str): + expr = ast.parse(expr, mode='eval') + if isinstance(expr, ast.Expression): + expr = expr.body + + safe_test = lambda n: isinstance(n, ast.Constant) or isinstance(n,ast.Name) and n.id in safe_names + safe_extract = lambda n: n.value if isinstance(n,ast.Constant) else safe_names[n.id] + + def _convert(node): + if isinstance(node, ast.Constant): + return node.value + elif isinstance(node, ast.Tuple): + return tuple(map(_convert, node.elts)) + elif isinstance(node, ast.List): + return list(map(_convert, node.elts)) + elif isinstance(node, ast.Dict): + return dict((_convert(k), _convert(v)) for k, v + in zip(node.keys, node.values)) + elif safe_test(node): + return safe_extract(node) + elif isinstance(node, ast.UnaryOp) and \ + isinstance(node.op, (ast.UAdd, ast.USub)) and \ + isinstance(node.operand, (ast.Constant, ast.UnaryOp, ast.BinOp)): + operand = _convert(node.operand) + if isinstance(node.op, ast.UAdd): + return + operand + else: + return - operand + elif isinstance(node, ast.BinOp) and \ + isinstance(node.op, (ast.Add, ast.Sub)) and \ + isinstance(node.right, (ast.Constant, ast.UnaryOp, ast.BinOp)) and \ + isinstance(node.right.n, complex) and \ + isinstance(node.left, (ast.Constant, ast.UnaryOp, astBinOp)): + left = _convert(node.left) + right = _convert(node.right) + if isinstance(node.op, ast.Add): + return left + right + else: + return left - right + elif isinstance(node, ast.Call) and \ + isinstance(node.func, ast.Name) and \ + node.func.id in safe_callables: + return safe_callables[node.func.id]( + *[_convert(n) for n in node.args], + **{kw.arg: _convert(kw.value) for kw in node.keywords}) + raise ValueError('Bad expression') + return _convert(expr) + +rl_safe_exec = __rl_safe_exec__() +rl_safe_eval = __rl_safe_eval__() + +def rl_less_safe_eval(expr,NS): + '''eval with our so called safe globals''' + if not __rl_safe_builtins__: + rl_safe_eval('""') + return eval(expr,__rl_safe_builtins__,NS) diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/rltempfile.py b/.venv/lib/python3.13/site-packages/reportlab/lib/rltempfile.py new file mode 100644 index 0000000000000000000000000000000000000000..6f14064afd3bdc182c4559341833eb065260f091 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/rltempfile.py @@ -0,0 +1,38 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +# $URI:$ +__version__='3.3.0' +__doc__='''Helper for the test suite - determines where to write output. + +When our test suite runs as source, a script "test_foo.py" will typically +create "test_foo.pdf" alongside it. But if you are testing a package of +compiled code inside a zip archive, this won't work. This determines +where to write test suite output, creating a subdirectory of /tmp/ or +whatever if needed. + +''' +_rl_tempdir=None +__all__ = ('get_rl_tempdir', 'get_rl_tempdir') +import os, tempfile +def _rl_getuid(): + if hasattr(os,'getuid'): + return os.getuid() + else: + return '' + +def get_rl_tempdir(*subdirs): + global _rl_tempdir + if _rl_tempdir is None: + _rl_tempdir = os.path.join(tempfile.gettempdir(),'ReportLab_tmp%s' % str(_rl_getuid())) + d = _rl_tempdir + if subdirs: d = os.path.join(*((d,)+subdirs)) + try: + os.makedirs(d) + except: + pass + return d + +def get_rl_tempfile(fn=None): + if not fn: + fn = tempfile.mktemp() + return os.path.join(get_rl_tempdir(),fn) diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/rparsexml.py b/.venv/lib/python3.13/site-packages/reportlab/lib/rparsexml.py new file mode 100644 index 0000000000000000000000000000000000000000..702e2f7ec62f4e02c9f12392d359abba39555980 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/rparsexml.py @@ -0,0 +1,421 @@ +"""Very simple and fast XML parser, used for intra-paragraph text. + +Devised by Aaron Watters in the bad old days before Python had fast +parsers available. Constructs the lightest possible in-memory +representation; parses most files we have seen in pure python very +quickly. + +This is used to parse intra-paragraph markup. + +Example parse:: + + text in xml + + ( "this", + {"type": "xml"}, + [ "text ", + ("b", None, ["in"], None), + " xml" + ] + None ) + + { 0: "this" + "type": "xml" + 1: ["text ", + {0: "b", 1:["in"]}, + " xml"] + } + +Ie, xml tag translates to a tuple: + (name, dictofattributes, contentlist, miscellaneousinfo) + +where miscellaneousinfo can be anything, (but defaults to None) +(with the intention of adding, eg, line number information) + +special cases: name of "" means "top level, no containing tag". +Top level parse always looks like this:: + + ("", list, None, None) + + contained text of None means + +In order to support stuff like:: + + + +AT THE MOMENT & ETCETERA ARE IGNORED. THEY MUST BE PROCESSED +IN A POST-PROCESSING STEP. + +PROLOGUES ARE NOT UNDERSTOOD. OTHER STUFF IS PROBABLY MISSING. +""" + +simpleparse = 1 + +class smartDecode: + @staticmethod + def __call__(s): + from charset_normalizer import detect + def __call__(s): + if isinstance(s,str): return s + cdd = detect(s) + return s.decode(cdd["encoding"]) + smartDecode.__class__.__call__ = staticmethod(__call__) + return __call__(s) +smartDecode = smartDecode() + +NONAME = "" +NAMEKEY = 0 +CONTENTSKEY = 1 +CDATAMARKER = "" +replacelist = [("<", "<"), (">", ">"), ("&", "&")] # amp must be last +#replacelist = [] +def unEscapeContentList(contentList): + result = [] + for e in contentList: + if "&" in e: + for (old, new) in replacelist: + e = e.replace(old, new) + result.append(e) + return result + +def parsexmlSimple(xmltext, oneOutermostTag=0,eoCB=None,entityReplacer=unEscapeContentList): + """official interface: discard unused cursor info""" + (result, cursor) = parsexml0(xmltext,entityReplacer=entityReplacer) + if oneOutermostTag: + return result[2][0] + else: + return result + +if simpleparse: + parsexml = parsexmlSimple + +def parseFile(filename): + raw = open(filename, 'r').read() + return parsexml(raw) + +verbose = 0 + +def skip_prologue(text, cursor): + """skip any prologue found after cursor, return index of rest of text""" + ### NOT AT ALL COMPLETE!!! definitely can be confused!!! + prologue_elements = ("!DOCTYPE", "?xml", "!--") + done = None + while done is None: + #print "trying to skip:", repr(text[cursor:cursor+20]) + openbracket = text.find("<", cursor) + if openbracket<0: break + past = openbracket+1 + found = None + for e in prologue_elements: + le = len(e) + if text[past:past+le]==e: + found = 1 + cursor = text.find(">", past) + if cursor<0: + raise ValueError("can't close prologue %r" % e) + cursor = cursor+1 + if found is None: + done=1 + #print "done skipping" + return cursor + +def parsexml0(xmltext, startingat=0, toplevel=1, + # snarf in some globals + entityReplacer=unEscapeContentList, + #len=len, None=None + #LENCDATAMARKER=LENCDATAMARKER, CDATAMARKER=CDATAMARKER + ): + """simple recursive descent xml parser... + return (dictionary, endcharacter) + special case: comment returns (None, endcharacter)""" + xmltext = smartDecode(xmltext) + #print "parsexml0", repr(xmltext[startingat: startingat+10]) + # DEFAULTS + NameString = NONAME + ContentList = AttDict = ExtraStuff = None + if toplevel is not None: + #if verbose: print "at top level" + #if startingat!=0: + # raise ValueError, "have to start at 0 for top level!" + xmltext = xmltext.strip() + cursor = startingat + #look for interesting starting points + firstbracket = xmltext.find("<", cursor) + afterbracket2char = xmltext[firstbracket+1:firstbracket+3] + #print "a", repr(afterbracket2char) + #firstampersand = xmltext.find("&", cursor) + #if firstampersand>0 and firstampersand0: + #afterbracket2char = xmltext[firstbracket:firstbracket+2] + if toplevel is not None: + #print "toplevel with no outer tag" + NameString = name = NONAME + cursor = skip_prologue(xmltext, cursor) + #break + elif firstbracket<0: + raise ValueError("non top level entry should be at start tag: %s" % repr(xmltext[:10])) + # special case: CDATA + elif afterbracket2char=="![" and xmltext[firstbracket:firstbracket+9]=="": + raise ValueError("invalid comment: contains double dashes %s" % repr(xmltext[cursor:cursor+20])) + return (None, endcomment+1) # shortcut exit + else: + # get the rest of the tag + #if verbose: print "parsing start tag" + # make sure the tag isn't in doublequote pairs + closebracket = xmltext.find(">", firstbracket) + noclose = closebracket<0 + startsearch = closebracket+1 + pastfirstbracket = firstbracket+1 + tagcontent = xmltext[pastfirstbracket:closebracket] + # shortcut, no equal means nothing but name in the tag content + if '=' not in tagcontent: + if tagcontent[-1]=="/": + # simple case + #print "simple case", tagcontent + tagcontent = tagcontent[:-1] + docontents = None + name = tagcontent.strip() + NameString = name + cursor = startsearch + else: + if '"' in tagcontent: + # check double quotes + stop = None + # not inside double quotes! (the split should have odd length) + if noclose or len((tagcontent+".").split('"'))% 2: + stop=1 + while stop is None: + closebracket = xmltext.find(">", startsearch) + startsearch = closebracket+1 + noclose = closebracket<0 + tagcontent = xmltext[pastfirstbracket:closebracket] + # not inside double quotes! (the split should have odd length) + if noclose or len((tagcontent+".").split('"'))% 2: + stop=1 + if noclose: + raise ValueError("unclosed start tag %s" % repr(xmltext[firstbracket:firstbracket+20])) + cursor = startsearch + #cursor = closebracket+1 + # handle simple tag /> syntax + if xmltext[closebracket-1]=="/": + #if verbose: print "it's a simple tag" + closebracket = closebracket-1 + tagcontent = tagcontent[:-1] + docontents = None + #tagcontent = xmltext[firstbracket+1:closebracket] + tagcontent = tagcontent.strip() + taglist = tagcontent.split("=") + #if not taglist: + # raise ValueError, "tag with no name %s" % repr(xmltext[firstbracket:firstbracket+20]) + taglist0 = taglist[0] + taglist0list = taglist0.split() + #if len(taglist0list)>2: + # raise ValueError, "bad tag head %s" % repr(taglist0) + name = taglist0list[0] + #print "tag name is", name + NameString = name + # now parse the attributes + attributename = taglist0list[-1] + # put a fake att name at end of last taglist entry for consistent parsing + taglist[-1] = taglist[-1]+" f" + AttDict = D = {} + taglistindex = 1 + lasttaglistindex = len(taglist) + #for attentry in taglist[1:]: + while taglistindexlasttaglistindex: + raise ValueError("unclosed value " + repr(attentry)) + nextattentry = taglist[taglistindex] + taglistindex = taglistindex+1 + attentry = "%s=%s" % (attentry, nextattentry) + attentry = attentry.strip() # only needed for while loop... + attlist = attentry.split() + nextattname = attlist[-1] + attvalue = attentry[:-len(nextattname)] + attvalue = attvalue.strip() + try: + first = attvalue[0]; last=attvalue[-1] + except: + raise ValueError("attvalue,attentry,attlist="+repr((attvalue, attentry,attlist))) + if first==last=='"' or first==last=="'": + attvalue = attvalue[1:-1] + #print attributename, "=", attvalue + D[attributename] = attvalue + attributename = nextattname + # pass over other tags and content looking for end tag + if docontents is not None: + #print "now looking for end tag" + ContentList = L + while docontents is not None: + nextopenbracket = xmltext.find("<", cursor) + if nextopenbracket", nextopenbracket) + if nextclosebracket\n%s\n" % (name, attributes, textpprint, name) + # otherwise must be a simple tag + return "<%s %s/>" % (name, attributes) + +def testparse(s,dump=0): + from time import time + from pprint import pprint + now = time() + D = parsexmlSimple(s,oneOutermostTag=1) + print("DONE", time()-now) + if dump&4: + pprint(D) + #pprint(D) + if dump&1: + print("============== reformatting") + p = pprettyprint(D) + print(p) + +def test(dump=0): + testparse("""text <>in xml + + text in xml ]]> + just testing brackets feature + """,dump=dump) + +if __name__=="__main__": + test(dump=1) + import sys, os + from time import time + import reportlab + now = time() + seen = 0 + for f in sys.argv[1:]: + if not os.path.isfile(f): + print("!!!!! no file at {f!r}") + else: + with open(f) as _f: + t = _f.read() + print(f"parsing {f!r} |t|={len(t)}") + testparse(t,dump=1) + seen += 1 + if seen: + print(f"timed at {time()-now:.2f} secs.") diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/sequencer.py b/.venv/lib/python3.13/site-packages/reportlab/lib/sequencer.py new file mode 100644 index 0000000000000000000000000000000000000000..f40cef1b85c15c6a42ac33988084931529f6b992 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/sequencer.py @@ -0,0 +1,311 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +__version__='3.3.0' +__doc__="""A Sequencer class counts things. It aids numbering and formatting lists.""" +__all__='''Sequencer getSequencer setSequencer'''.split() +# +# roman numbers conversion thanks to +# +# fredrik lundh, november 1996 (based on a C hack from 1984) +# +# fredrik@pythonware.com +# http://www.pythonware.com + +_RN_TEMPLATES = [ 0, 0o1, 0o11, 0o111, 0o12, 0o2, 0o21, 0o211, 0o2111, 0o13 ] +_RN_LETTERS = "IVXLCDM" + +def _format_I(value): + if value < 0 or value > 3999: + raise ValueError("illegal value") + str = "" + base = -1 + while value: + value, index = divmod(value, 10) + tmp = _RN_TEMPLATES[index] + while tmp: + tmp, index = divmod(tmp, 8) + str = _RN_LETTERS[index+base] + str + base += 2 + return str + +def _format_i(num): + return _format_I(num).lower() + +def _format_123(num): + """The simplest formatter""" + return str(num) + +def _format_ABC(num): + """Uppercase. Wraps around at 26.""" + n = (num -1) % 26 + return chr(n+65) + +def _format_abc(num): + """Lowercase. Wraps around at 26.""" + n = (num -1) % 26 + return chr(n+97) + +_type2formatter = { + 'I':_format_I, + 'i':_format_i, + '1':_format_123, + 'A':_format_ABC, + 'a':_format_abc, + } + +class _Counter: + """Private class used by Sequencer. Each counter + knows its format, and the IDs of anything it + resets, as well as its value. Starts at zero + and increments just before you get the new value, + so that it is still 'Chapter 5' and not 'Chapter 6' + when you print 'Figure 5.1'""" + + def __init__(self): + self._base = 0 + self._value = self._base + self._formatter = _format_123 + self._resets = [] + + def setFormatter(self, formatFunc): + self._formatter = formatFunc + + def reset(self, value=None): + if value: + self._value = value + else: + self._value = self._base + + def next(self): + self._value += 1 + v = self._value + for counter in self._resets: + counter.reset() + return v + __next__ = next + + def _this(self): + return self._value + + def nextf(self): + """Returns next value formatted""" + return self._formatter(next(self)) + + def thisf(self): + return self._formatter(self._this()) + + def chain(self, otherCounter): + if not otherCounter in self._resets: + self._resets.append(otherCounter) + +class Sequencer: + """Something to make it easy to number paragraphs, sections, + images and anything else. The features include registering + new string formats for sequences, and 'chains' whereby + some counters are reset when their parents. + It keeps track of a number of + 'counters', which are created on request: + Usage:: + + >>> seq = layout.Sequencer() + >>> seq.next('Bullets') + 1 + >>> seq.next('Bullets') + 2 + >>> seq.next('Bullets') + 3 + >>> seq.reset('Bullets') + >>> seq.next('Bullets') + 1 + >>> seq.next('Figures') + 1 + >>> + """ + + def __init__(self): + self._counters = {} #map key to current number + self._formatters = {} + self._reset() + + def _reset(self): + self._counters.clear() + self._formatters.clear() + self._formatters.update({ + # the formats it knows initially + '1':_format_123, + 'A':_format_ABC, + 'a':_format_abc, + 'I':_format_I, + 'i':_format_i, + }) + d = dict(_counters=self._counters,_formatters=self._formatters) + self.__dict__.clear() + self.__dict__.update(d) + self._defaultCounter = None + + def _getCounter(self, counter=None): + """Creates one if not present""" + try: + return self._counters[counter] + except KeyError: + cnt = _Counter() + self._counters[counter] = cnt + return cnt + + def _this(self, counter=None): + """Retrieves counter value but does not increment. For + new counters, sets base value to 1.""" + if not counter: + counter = self._defaultCounter + return self._getCounter(counter)._this() + + def __next__(self): + """Retrieves the numeric value for the given counter, then + increments it by one. New counters start at one.""" + return next(self._getCounter(self._defaultCounter)) + + def next(self,counter=None): + if not counter: + return next(self) + else: + dc = self._defaultCounter + try: + self._defaultCounter = counter + return next(self) + finally: + self._defaultCounter = dc + + def thisf(self, counter=None): + if not counter: + counter = self._defaultCounter + return self._getCounter(counter).thisf() + + def nextf(self, counter=None): + """Retrieves the numeric value for the given counter, then + increments it by one. New counters start at one.""" + if not counter: + counter = self._defaultCounter + return self._getCounter(counter).nextf() + + def setDefaultCounter(self, default=None): + """Changes the key used for the default""" + self._defaultCounter = default + + def registerFormat(self, format, func): + """Registers a new formatting function. The funtion + must take a number as argument and return a string; + fmt is a short menmonic string used to access it.""" + self._formatters[format] = func + + def setFormat(self, counter, format): + """Specifies that the given counter should use + the given format henceforth.""" + func = self._formatters[format] + self._getCounter(counter).setFormatter(func) + + def reset(self, counter=None, base=0): + if not counter: + counter = self._defaultCounter + self._getCounter(counter)._value = base + + def chain(self, parent, child): + p = self._getCounter(parent) + c = self._getCounter(child) + p.chain(c) + + def __getitem__(self, key): + """Allows compact notation to support the format function. + s['key'] gets current value, s['key+'] increments.""" + if key[-1:] == '+': + counter = key[:-1] + return self.nextf(counter) + else: + return self.thisf(key) + + def format(self, template): + """The crowning jewels - formats multi-level lists.""" + return template % self + + def dump(self): + """Write current state to stdout for diagnostics""" + counters = list(self._counters.items()) + counters.sort() + print('Sequencer dump:') + for (key, counter) in counters: + print(' %s: value = %d, base = %d, format example = %s' % ( + key, counter._this(), counter._base, counter.thisf())) + +"""Your story builder needs to set this to""" +_sequencer = None + +def getSequencer(): + global _sequencer + if _sequencer is None: + _sequencer = Sequencer() + return _sequencer + +def setSequencer(seq): + global _sequencer + s = _sequencer + _sequencer = seq + return s + +def _reset(): + global _sequencer + if _sequencer: + _sequencer._reset() + +from reportlab.rl_config import register_reset +register_reset(_reset) +del register_reset + +def test(): + s = Sequencer() + print('Counting using default sequence: %d %d %d' % (next(s),next(s), next(s))) + print('Counting Figures: Figure %d, Figure %d, Figure %d' % ( + s.next('figure'), s.next('figure'), s.next('figure'))) + print('Back to default again: %d' % next(s)) + s.setDefaultCounter('list1') + print('Set default to list1: %d %d %d' % (next(s),next(s), next(s))) + s.setDefaultCounter() + print('Set default to None again: %d %d %d' % (next(s),next(s), next(s))) + print() + print('Creating Appendix counter with format A, B, C...') + s.setFormat('Appendix', 'A') + print(' Appendix %s, Appendix %s, Appendix %s' % ( + s.nextf('Appendix'), s.nextf('Appendix'),s.nextf('Appendix'))) + + def format_french(num): + return ('un','deux','trois','quatre','cinq')[(num-1)%5] + print() + print('Defining a custom format with french words:') + s.registerFormat('french', format_french) + s.setFormat('FrenchList', 'french') + print(' ' +(' '.join(str(s.nextf('FrenchList')) for i in range(1,6)))) + print() + print('Chaining H1 and H2 - H2 goes back to one when H1 increases') + s.chain('H1','H2') + print(' H1 = %d' % s.next('H1')) + print(' H2 = %d' % s.next('H2')) + print(' H2 = %d' % s.next('H2')) + print(' H2 = %d' % s.next('H2')) + print(' H1 = %d' % s.next('H1')) + print(' H2 = %d' % s.next('H2')) + print(' H2 = %d' % s.next('H2')) + print(' H2 = %d' % s.next('H2')) + print() + print('GetItem notation - append a plus to increment') + print(' seq["Appendix"] = %s' % s["Appendix"]) + print(' seq["Appendix+"] = %s' % s["Appendix+"]) + print(' seq["Appendix+"] = %s' % s["Appendix+"]) + print(' seq["Appendix"] = %s' % s["Appendix"]) + print() + print('Finally, string format notation for nested lists. Cool!') + print('The expression ("Figure %(Chapter)s.%(Figure+)s" % seq) gives:') + print(' Figure %(Chapter)s.%(Figure+)s' % s) + print(' Figure %(Chapter)s.%(Figure+)s' % s) + print(' Figure %(Chapter)s.%(Figure+)s' % s) + + +if __name__=='__main__': + test() diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/styles.py b/.venv/lib/python3.13/site-packages/reportlab/lib/styles.py new file mode 100644 index 0000000000000000000000000000000000000000..23558b2ad980b8a8c2081f09a26cfc2458dda879 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/styles.py @@ -0,0 +1,436 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/styles.py +__version__='3.3.0' +__doc__='''Classes for ParagraphStyle and similar things. + +A style is a collection of attributes, but with some extra features +to allow 'inheritance' from a parent, and to ensure nobody makes +changes after construction. + +ParagraphStyle shows all the attributes available for formatting +paragraphs. + +getSampleStyleSheet() returns a stylesheet you can use for initial +development, with a few basic heading and text styles. +''' +__all__=( + 'PropertySet', + 'ParagraphStyle', + 'str2alignment', + 'LineStyle', + 'ListStyle', + 'StyleSheet1', + 'getSampleStyleSheet', + ) +from reportlab.lib.colors import black +from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT, TA_JUSTIFY +from reportlab.lib.fonts import tt2ps +from reportlab.rl_config import canvas_basefontname as _baseFontName, \ + underlineWidth as _baseUnderlineWidth, \ + underlineOffset as _baseUnderlineOffset, \ + underlineGap as _baseUnderlineGap, \ + strikeWidth as _baseStrikeWidth, \ + strikeOffset as _baseStrikeOffset, \ + strikeGap as _baseStrikeGap, \ + spaceShrinkage as _spaceShrinkage, \ + platypus_link_underline as _platypus_link_underline, \ + hyphenationLang as _hyphenationLang, \ + hyphenationMinWordLength as _hyphenationMinWordLength, \ + uriWasteReduce as _uriWasteReduce, \ + embeddedHyphenation as _embeddedHyphenation +_baseFontNameB = tt2ps(_baseFontName,1,0) +_baseFontNameI = tt2ps(_baseFontName,0,1) +_baseFontNameBI = tt2ps(_baseFontName,1,1) + +########################################################### +# This class provides an 'instance inheritance' +# mechanism for its descendants, simpler than acquisition +# but not as far-reaching +########################################################### +class PropertySet: + defaults = {} + + def __init__(self, name, parent=None, **kw): + """When initialized, it copies the class defaults; + then takes a copy of the attributes of the parent + if any. All the work is done in init - styles + should cost little to use at runtime.""" + # step one - validate the hell out of it + assert 'name' not in self.defaults, "Class Defaults may not contain a 'name' attribute" + assert 'parent' not in self.defaults, "Class Defaults may not contain a 'parent' attribute" + if parent: + assert parent.__class__ == self.__class__, "Parent style %s must have same class as new style %s" % (parent.__class__.__name__,self.__class__.__name__) + + #step two + self.name = name + self.parent = parent + self.__dict__.update(self.defaults) + + #step two - copy from parent if any. Try to be + # very strict that only keys in class defaults are + # allowed, so they cannot inherit + self.refresh() + self._setKwds(**kw) + + def _setKwds(self,**kw): + #step three - copy keywords if any + for key, value in kw.items(): + self.__dict__[key] = value + + def __repr__(self): + return "<%s '%s'>" % (self.__class__.__name__, self.name) + + def refresh(self): + """re-fetches attributes from the parent on demand; + use if you have been hacking the styles. This is + used by __init__""" + if self.parent: + for key, value in self.parent.__dict__.items(): + if (key not in ['name','parent']): + self.__dict__[key] = value + + def listAttrs(self, indent=''): + print(indent + 'name =', self.name) + print(indent + 'parent =', self.parent) + keylist = list(self.__dict__.keys()) + keylist.sort() + keylist.remove('name') + keylist.remove('parent') + for key in keylist: + value = self.__dict__.get(key, None) + print(indent + '%s = %s' % (key, value)) + + def clone(self, name, parent=None, **kwds): + r = self.__class__(name,parent) + r.__dict__ = self.__dict__.copy() + r.name = name + r.parent = parent is None and self or parent + r._setKwds(**kwds) + return r + +class ParagraphStyle(PropertySet): + defaults = { + 'fontName':_baseFontName, + 'fontSize':10, + 'leading':12, + 'leftIndent':0, + 'rightIndent':0, + 'firstLineIndent':0, + 'alignment':TA_LEFT, + 'spaceBefore':0, + 'spaceAfter':0, + 'bulletFontName':_baseFontName, + 'bulletFontSize':10, + 'bulletIndent':0, + #'bulletColor':black, + 'textColor': black, + 'backColor':None, + 'wordWrap':None, #None means do nothing special + #CJK use Chinese Line breaking + #LTR RTL use left to right / right to left + #with support from pyfribi2 if available + 'shaping': 0, + 'borderWidth': 0, + 'borderPadding': 0, + 'borderColor': None, + 'borderRadius': None, + 'allowWidows': 1, + 'allowOrphans': 0, + 'textTransform':None, #uppercase lowercase (captitalize not yet) or None or absent + 'endDots':None, #dots on the last line of left/right justified paras + #string or object with text and optional fontName, fontSize, textColor & backColor + #dy + 'splitLongWords':1, #make best efforts to split long words + 'underlineWidth': _baseUnderlineWidth, #underline width default + 'bulletAnchor': 'start', #where the bullet is anchored ie start, middle, end or numeric + 'justifyLastLine': 0, #n allow justification on the last line for more than n words 0 means don't bother + 'justifyBreaks': 0, #justify lines broken with
+ 'spaceShrinkage': _spaceShrinkage, #allow shrinkage of percentage of space to fit on line + 'strikeWidth': _baseStrikeWidth, #stroke width default + 'underlineOffset': _baseUnderlineOffset, #fraction of fontsize to offset underlines + 'underlineGap': _baseUnderlineGap, #gap for double/triple underline + 'strikeOffset': _baseStrikeOffset, #fraction of fontsize to offset strikethrough + 'strikeGap': _baseStrikeGap, #gap for double/triple strike + 'linkUnderline': _platypus_link_underline, + 'underlineColor': None, + 'strikeColor': None, + 'hyphenationLang': _hyphenationLang, + #'hyphenationMinWordLength': _hyphenationMinWordLength, + 'embeddedHyphenation': _embeddedHyphenation, + 'uriWasteReduce': _uriWasteReduce, + } + +def str2alignment(v,__map__=dict( + centre=TA_CENTER, + center=TA_CENTER, + left=TA_LEFT,right=TA_RIGHT, + justify=TA_JUSTIFY)): + _ = __map__.get(v.lower(),None) + if _ is None: raise ValueError(f'{v!r} is illegal value for alignment') + return _ + +class LineStyle(PropertySet): + defaults = { + 'width':1, + 'color': black + } + def prepareCanvas(self, canvas): + """You can ask a LineStyle to set up the canvas for drawing + the lines.""" + canvas.setLineWidth(1) + #etc. etc. + +class ListStyle(PropertySet): + defaults = dict( + leftIndent=18, + rightIndent=0, + bulletAlign='left', + bulletType='1', + bulletColor=black, + bulletFontName='Helvetica', + bulletFontSize=12, + bulletOffsetY=0, + bulletDedent='auto', + bulletDir='ltr', + bulletFormat=None, + start=None, #starting value for a list; if a list then the start sequence + ) + +_stylesheet1_undefined = object() + +class StyleSheet1: + """ + This may or may not be used. The idea is to: + + 1. slightly simplify construction of stylesheets; + + 2. enforce rules to validate styles when added + (e.g. we may choose to disallow having both + 'heading1' and 'Heading1' - actual rules are + open to discussion); + + 3. allow aliases and alternate style lookup + mechanisms + + 4. Have a place to hang style-manipulation + methods (save, load, maybe support a GUI + editor) + + Access is via getitem, so they can be + compatible with plain old dictionaries. + """ + + def __init__(self): + self.byName = {} + self.byAlias = {} + + def __getitem__(self, key): + try: + return self.byAlias[key] + except KeyError: + try: + return self.byName[key] + except KeyError: + raise KeyError("Style '%s' not found in stylesheet" % key) + + def get(self,key,default=_stylesheet1_undefined): + try: + return self[key] + except KeyError: + if default!=_stylesheet1_undefined: return default + raise + + def __contains__(self, key): + return key in self.byAlias or key in self.byName + + def has_key(self,key): + return key in self + + def add(self, style, alias=None): + key = style.name + if key in self.byName: + raise KeyError("Style '%s' already defined in stylesheet" % key) + if key in self.byAlias: + raise KeyError("Style name '%s' is already an alias in stylesheet" % key) + + if alias: + if alias in self.byName: + raise KeyError("Style '%s' already defined in stylesheet" % alias) + if alias in self.byAlias: + raise KeyError("Alias name '%s' is already an alias in stylesheet" % alias) + #passed all tests? OK, add it + self.byName[key] = style + if alias: + self.byAlias[alias] = style + + def __getattr__(self,a): + if a in self: return self.get(a) + raise AttributeError(f'{self.__class__.__name__} instance has no attribute {a!a}') + + def list(self): + styles = list(self.byName.items()) + styles.sort() + alii = {} + for (alias, style) in list(self.byAlias.items()): + alii[style] = alias + for (name, style) in styles: + alias = alii.get(style, None) + print(name, alias) + style.listAttrs(' ') + print() + +def testStyles(): + pNormal = ParagraphStyle('Normal',None) + pNormal.fontName = _baseFontName + pNormal.fontSize = 12 + pNormal.leading = 14.4 + + pNormal.listAttrs() + print() + pPre = ParagraphStyle('Literal', pNormal) + pPre.fontName = 'Courier' + pPre.listAttrs() + return pNormal, pPre + +def getSampleStyleSheet(): + """Returns a stylesheet object""" + stylesheet = StyleSheet1() + + stylesheet.add(ParagraphStyle(name='Normal', + fontName=_baseFontName, + fontSize=10, + leading=12) + ) + + stylesheet.add(ParagraphStyle(name='BodyText', + parent=stylesheet['Normal'], + spaceBefore=6) + ) + stylesheet.add(ParagraphStyle(name='Italic', + parent=stylesheet['BodyText'], + fontName = _baseFontNameI) + ) + + stylesheet.add(ParagraphStyle(name='Heading1', + parent=stylesheet['Normal'], + fontName = _baseFontNameB, + fontSize=18, + leading=22, + spaceAfter=6), + alias='h1') + + stylesheet.add(ParagraphStyle(name='Title', + parent=stylesheet['Normal'], + fontName = _baseFontNameB, + fontSize=18, + leading=22, + alignment=TA_CENTER, + spaceAfter=6), + alias='title') + + stylesheet.add(ParagraphStyle(name='Heading2', + parent=stylesheet['Normal'], + fontName = _baseFontNameB, + fontSize=14, + leading=18, + spaceBefore=12, + spaceAfter=6), + alias='h2') + + stylesheet.add(ParagraphStyle(name='Heading3', + parent=stylesheet['Normal'], + fontName = _baseFontNameBI, + fontSize=12, + leading=14, + spaceBefore=12, + spaceAfter=6), + alias='h3') + + stylesheet.add(ParagraphStyle(name='Heading4', + parent=stylesheet['Normal'], + fontName = _baseFontNameBI, + fontSize=10, + leading=12, + spaceBefore=10, + spaceAfter=4), + alias='h4') + + stylesheet.add(ParagraphStyle(name='Heading5', + parent=stylesheet['Normal'], + fontName = _baseFontNameB, + fontSize=9, + leading=10.8, + spaceBefore=8, + spaceAfter=4), + alias='h5') + + stylesheet.add(ParagraphStyle(name='Heading6', + parent=stylesheet['Normal'], + fontName = _baseFontNameB, + fontSize=7, + leading=8.4, + spaceBefore=6, + spaceAfter=2), + alias='h6') + + stylesheet.add(ParagraphStyle(name='Bullet', + parent=stylesheet['Normal'], + firstLineIndent=0, + spaceBefore=3), + alias='bu') + + stylesheet.add(ParagraphStyle(name='Definition', + parent=stylesheet['Normal'], + firstLineIndent=0, + leftIndent=36, + bulletIndent=0, + spaceBefore=6, + bulletFontName=_baseFontNameBI), + alias='df') + + stylesheet.add(ParagraphStyle(name='Code', + parent=stylesheet['Normal'], + fontName='Courier', + fontSize=8, + leading=8.8, + firstLineIndent=0, + leftIndent=36, + hyphenationLang='')) + + stylesheet.add(ListStyle(name='UnorderedList', + parent=None, + leftIndent=18, + rightIndent=0, + bulletAlign='left', + bulletType='1', + bulletColor=black, + bulletFontName='Helvetica', + bulletFontSize=12, + bulletOffsetY=0, + bulletDedent='auto', + bulletDir='ltr', + bulletFormat=None, + #start='circle square blackstar sparkle disc diamond'.split(), + start=None, + ), + alias='ul') + + stylesheet.add(ListStyle(name='OrderedList', + parent=None, + leftIndent=18, + rightIndent=0, + bulletAlign='left', + bulletType='1', + bulletColor=black, + bulletFontName='Helvetica', + bulletFontSize=12, + bulletOffsetY=0, + bulletDedent='auto', + bulletDir='ltr', + bulletFormat=None, + #start='1 a A i I'.split(), + start=None, + ), + alias='ol') + return stylesheet diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/testutils.py b/.venv/lib/python3.13/site-packages/reportlab/lib/testutils.py new file mode 100644 index 0000000000000000000000000000000000000000..a3ebcccb3deb66057abfd2abd28672a700107881 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/testutils.py @@ -0,0 +1,406 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +import reportlab +reportlab._rl_testing=True +del reportlab +__version__='4.0.1' +__doc__="""Provides support for the test suite. + +The test suite as a whole, and individual tests, need to share +certain support functions. We have to put these in here so they +can always be imported, and so that individual tests need to import +nothing more than "reportlab.whatever..." +""" + +import sys, os, fnmatch, re, functools +from configparser import ConfigParser +import unittest, random +from reportlab.lib.utils import isCompactDistro, __rl_loader__, rl_isdir, asUnicode +from reportlab.rl_config import invariant as rl_invariant + +def invariantSeed(n): + if rl_invariant: random.seed(n) + +def haveRenderPM(): + from reportlab.graphics.renderPM import _getPMBackend, RenderPMError + try: + return _getPMBackend() + except RenderPMError: + return False + +DEJAVUSANS = ('DejaVuSans','DejaVuSans-Bold','DejaVuSans-Oblique','DejaVuSans-BoldOblique') +def haveDejaVu(): + from reportlab.pdfbase.ttfonts import TTFont + for x in DEJAVUSANS: + try: + TTFont(x,x+'.ttf') + except: + return False + return True + +# Helper functions. +def isWritable(D): + try: + fn = '00DELETE.ME' + f = open(fn, 'w') + f.write('test of writability - can be deleted') + f.close() + if os.path.isfile(fn): + os.remove(fn) + return 1 + except: + return 0 + +_OUTDIR = None +RL_HOME = None +testsFolder = None +def setOutDir(name): + """Is it a writable file system distro being invoked within + test directory? If so, can write test output here. If not, + it had better go in a temp directory. Only do this once per + process""" + global _OUTDIR, RL_HOME, testsFolder + if _OUTDIR: return _OUTDIR + D = [d[9:] for d in sys.argv if d.startswith('--outdir=')] + if not D: + D = os.environ.get('RL_TEST_OUTDIR','') + if D: D=[D] + if D: + _OUTDIR = D[-1] + try: + os.makedirs(_OUTDIR) + except: + pass + for d in D: + if d in sys.argv: + sys.argv.remove(d) + else: + assert name=='__main__',"setOutDir should only be called in the main script" + scriptDir=os.path.dirname(sys.argv[0]) + if not scriptDir: scriptDir=os.getcwd() + _OUTDIR = scriptDir + + if not isWritable(_OUTDIR): + _OUTDIR = get_rl_tempdir('reportlab_test') + + import reportlab + RL_HOME=reportlab.__path__[0] + if not os.path.isabs(RL_HOME): RL_HOME=os.path.normpath(os.path.abspath(RL_HOME)) + topDir = os.path.dirname(RL_HOME) + testsFolder = os.path.join(topDir,'tests') + if not os.path.isdir(testsFolder): + testsFolder = os.path.join(os.path.dirname(topDir),'tests') + if not os.path.isdir(testsFolder): + if name=='__main__': + scriptDir=os.path.dirname(sys.argv[0]) + if not scriptDir: scriptDir=os.getcwd() + testsFolder = os.path.abspath(scriptDir) + else: + testsFolder = None + if testsFolder: + sys.path.insert(0,os.path.dirname(testsFolder)) + return _OUTDIR + +_mockumap = ( + None if os.environ.get('OFFLINE_MOCK','1')!='1' + else'http://www.reportlab.com/rsrc/encryption.gif', + ) +def mockUrlRead(name): + if name in _mockumap: + with open(os.path.join(testsFolder,os.path.basename(name)),'rb') as f: + return f.read() + else: + from urllib.request import urlopen + return urlopen(name).read() + +def outputfile(fn): + """This works out where to write test output. If running + code in a locked down file system, this will be a + temp directory; otherwise, the output of 'test_foo.py' will + normally be a file called 'test_foo.pdf', next door. + """ + D = setOutDir(__name__) + if fn: D = os.path.join(D,fn) + return D + +def printLocation(depth=1): + if sys._getframe(depth).f_locals.get('__name__')=='__main__': + outDir = outputfile('') + if outDir!=_OUTDIR: + print('Logs and output files written to folder "%s"' % outDir) + +def makeSuiteForClasses(*classes,testMethodPrefix=None): + "Return a test suite with tests loaded from provided classes." + + suite = unittest.TestSuite() + loader = unittest.TestLoader() + if testMethodPrefix: + loader.testMethodPrefix = testMethodPrefix + for C in classes: + suite.addTest(loader.loadTestsFromTestCase(C)) + return suite + +def getCVSEntries(folder, files=1, folders=0): + """Returns a list of filenames as listed in the CVS/Entries file. + + 'folder' is the folder that should contain the CVS subfolder. + If there is no such subfolder an empty list is returned. + 'files' is a boolean; 1 and 0 means to return files or not. + 'folders' is a boolean; 1 and 0 means to return folders or not. + """ + + join = os.path.join + + # If CVS subfolder doesn't exist return empty list. + try: + f = open(join(folder, 'CVS', 'Entries')) + except IOError: + return [] + + # Return names of files and/or folders in CVS/Entries files. + allEntries = [] + for line in f.readlines(): + if folders and line[0] == 'D' \ + or files and line[0] != 'D': + entry = line.split('/')[1] + if entry: + allEntries.append(join(folder, entry)) + + return allEntries + + +# Still experimental class extending ConfigParser's behaviour. +class ExtConfigParser(ConfigParser): + "A slightly extended version to return lists of strings." + + pat = re.compile(r'\s*\[.*\]\s*') + + def getstringlist(self, section, option): + "Coerce option to a list of strings or return unchanged if that fails." + + value = ConfigParser.get(self, section, option) + + # This seems to allow for newlines inside values + # of the config file, but be careful!! + val = value.replace('\n', '') + + if self.pat.match(val): + return eval(val,{__builtins__:None}) + else: + return value + + +# This class as suggested by /F with an additional hook +# to be able to filter filenames. + +class GlobDirectoryWalker: + "A forward iterator that traverses files in a directory tree." + + def __init__(self, directory, pattern='*'): + self.index = 0 + self.pattern = pattern + directory.replace('/',os.sep) + if os.path.isdir(directory): + self.stack = [directory] + self.files = [] + else: + if not isCompactDistro() or not __rl_loader__ or not rl_isdir(directory): + raise ValueError('"%s" is not a directory' % directory) + self.directory = directory[len(__rl_loader__.archive)+len(os.sep):] + pfx = self.directory+os.sep + n = len(pfx) + self.files = list(map(lambda x, n=n: x[n:],list(filter(lambda x,pfx=pfx: x.startswith(pfx),list(__rl_loader__._files.keys()))))) + self.files.sort() + self.stack = [] + + def __getitem__(self, index): + while 1: + try: + file = self.files[self.index] + self.index = self.index + 1 + except IndexError: + # pop next directory from stack + self.directory = self.stack.pop() + self.files = os.listdir(self.directory) + # now call the hook + self.files = self.filterFiles(self.directory, self.files) + self.index = 0 + else: + # got a filename + fullname = os.path.join(self.directory, file) + if os.path.isdir(fullname) and not os.path.islink(fullname): + self.stack.append(fullname) + if fnmatch.fnmatch(file, self.pattern): + return fullname + + def filterFiles(self, folder, files): + "Filter hook, overwrite in subclasses as needed." + + return files + + +class RestrictedGlobDirectoryWalker(GlobDirectoryWalker): + "An restricted directory tree iterator." + + def __init__(self, directory, pattern='*', ignore=None): + GlobDirectoryWalker.__init__(self, directory, pattern) + + if ignore == None: + ignore = [] + ip = [].append + if isinstance(ignore,(tuple,list)): + for p in ignore: + ip(p) + elif isinstance(ignore,str): + ip(ignore) + self.ignorePatterns = ([_.replace('/',os.sep) for _ in ip.__self__] if os.sep != '/' + else ip.__self__) + + def filterFiles(self, folder, files): + "Filters all items from files matching patterns to ignore." + + fnm = fnmatch.fnmatch + indicesToDelete = [] + for i,f in enumerate(files): + for p in self.ignorePatterns: + if fnm(f, p) or fnm(os.path.join(folder,f),p): + indicesToDelete.append(i) + indicesToDelete.reverse() + for i in indicesToDelete: + del files[i] + + return files + + +class CVSGlobDirectoryWalker(GlobDirectoryWalker): + "An directory tree iterator that checks for CVS data." + + def filterFiles(self, folder, files): + """Filters files not listed in CVS subfolder. + + This will look in the CVS subfolder of 'folder' for + a file named 'Entries' and filter all elements from + the 'files' list that are not listed in 'Entries'. + """ + + join = os.path.join + cvsFiles = getCVSEntries(folder) + if cvsFiles: + indicesToDelete = [] + for i in range(len(files)): + f = files[i] + if join(folder, f) not in cvsFiles: + indicesToDelete.append(i) + indicesToDelete.reverse() + for i in indicesToDelete: + del files[i] + + return files + + +# An experimental untested base class with additional 'security'. + +class SecureTestCase(unittest.TestCase): + """Secure testing base class with additional pre- and postconditions. + + We try to ensure that each test leaves the environment it has + found unchanged after the test is performed, successful or not. + + Currently we restore sys.path and the working directory, but more + of this could be added easily, like removing temporary files or + similar things. + + Use this as a base class replacing unittest.TestCase and call + these methods in subclassed versions before doing your own + business! + """ + + def setUp(self): + "Remember sys.path and current working directory." + self._initialPath = sys.path[:] + self._initialWorkDir = os.getcwd() + + def tearDown(self): + "Restore previous sys.path and working directory." + sys.path = self._initialPath + os.chdir(self._initialWorkDir) + +class NearTestCase(unittest.TestCase): + def assertNear(a,b,accuracy=1e-5): + if isinstance(a,(float,int)): + if abs(a-b)>accuracy: + raise AssertionError("%s not near %s" % (a, b)) + else: + for ae,be in zip(a,b): + if abs(ae-be)>accuracy: + raise AssertionError("%s not near %s" % (a, b)) + assertNear = staticmethod(assertNear) + +class ScriptThatMakesFileTest(unittest.TestCase): + """Runs a Python script at OS level, expecting it to produce a file. + + It CDs to the working directory to run the script.""" + def __init__(self, scriptDir, scriptName, outFileName, verbose=0): + self.scriptDir = scriptDir + self.scriptName = scriptName + self.outFileName = outFileName + self.verbose = verbose + # normally, each instance is told which method to run) + unittest.TestCase.__init__(self) + + def setUp(self): + self.cwd = os.getcwd() + global testsFolder + scriptDir=self.scriptDir + if not os.path.isabs(scriptDir): + scriptDir=os.path.join(testsFolder,scriptDir) + + os.chdir(scriptDir) + assert os.path.isfile(self.scriptName), "Script %s not found!" % self.scriptName + if os.path.isfile(self.outFileName): + os.remove(self.outFileName) + + def tearDown(self): + os.chdir(self.cwd) + + def runTest(self): + fmt = sys.platform=='win32' and '"%s" %s' or '%s %s' + import subprocess + out = subprocess.check_output((sys.executable,self.scriptName)) + #p = os.popen(fmt % (sys.executable,self.scriptName),'r') + #out = p.read() + if self.verbose: + print(out) + #status = p.close() + assert os.path.isfile(self.outFileName), "File %s not created!" % self.outFileName + +def equalStrings(a,b,enc='utf8'): + return a==b if type(a)==type(b) else asUnicode(a,enc)==asUnicode(b,enc) + +def eqCheck(r,x): + if r!=x: + print('Strings unequal\nexp: %s\ngot: %s' % (ascii(x),ascii(r))) + +def rlextraNeeded(): + try: + import rlextra + return False + except: + return True + +def rlSkipIf(cond,reason,__module__=None): + def inner(func): + @functools.wraps(func) + def wrapper(*args,**kwds): + if cond and os.environ.get('RL_indicateSkips','0')=='1': + print(f''' +skipping {func.__module__ or __module__}.{func.__name__} {reason}''') + return unittest.skipIf(cond,reason)(func)(*args,**kwds) + return wrapper + return inner + +def rlSkipUnless(cond,reason,__module__=None): + return rlSkipIf(not cond,reason,__module__=__module__) + +def rlSkip(reason,__module__=None): + return rlSkipIf(True,reason,__module__=__module__) diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/textsplit.py b/.venv/lib/python3.13/site-packages/reportlab/lib/textsplit.py new file mode 100644 index 0000000000000000000000000000000000000000..4c6eeaf209cc154a29134292b68fc105af3045b9 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/textsplit.py @@ -0,0 +1,241 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/textsplit.py + +"""Helpers for text wrapping, hyphenation, Asian text splitting and kinsoku shori. + +How to split a 'big word' depends on the language and the writing system. This module +works on a Unicode string. It ought to grow by allowing ore algoriths to be plugged +in based on possible knowledge of the language and desirable 'niceness' of the algorithm. + +""" + +__version__='3.3.0' + +from unicodedata import category +from reportlab.pdfbase.pdfmetrics import stringWidth +from reportlab.rl_config import _FUZZ +from reportlab.lib.utils import isUnicode + +CANNOT_START_LINE = [ + #strongly prohibited e.g. end brackets, stop, exclamation... + u'!\',.:;?!")]\u3001\u3002\u300d\u300f\u3011\u3015\uff3d\u3011\uff09', + #middle priority e.g. continuation small vowels - wrapped on two lines but one string... + u'\u3005\u2015\u3041\u3043\u3045\u3047\u3049\u3063\u3083\u3085\u3087\u308e\u30a1\u30a3' + u'\u30a5\u30a7\u30a9\u30c3\u30e3\u30e5\u30e7\u30ee\u30fc\u30f5\u30f6', + #weakly prohibited - continuations, celsius symbol etc. + u'\u309b\u309c\u30fb\u30fd\u30fe\u309d\u309e\u2015\u2010\xb0\u2032\u2033\u2103\uffe0\uff05\u2030' + ] + +ALL_CANNOT_START = u''.join(CANNOT_START_LINE) +CANNOT_END_LINE = [ + #strongly prohibited + u'\u2018\u201c\uff08[{\uff08\u3014\uff3b\uff5b\u3008\u300a\u300c\u300e\u3010', + #weaker - currency symbols, hash, postcode - prefixes + u'$\u00a3@#\uffe5\uff04\uffe1\uff20\u3012\u00a7' + ] +ALL_CANNOT_END = u''.join(CANNOT_END_LINE) + +def is_multi_byte(ch): + "Is this an Asian character?" + return (ord(ch) >= 0x3000) + +def getCharWidths(word, fontName, fontSize): + """Returns a list of glyph widths. + + >>> getCharWidths('Hello', 'Courier', 10) + [6.0, 6.0, 6.0, 6.0, 6.0] + >>> from reportlab.pdfbase.cidfonts import UnicodeCIDFont + >>> from reportlab.pdfbase.pdfmetrics import registerFont + >>> registerFont(UnicodeCIDFont('HeiseiMin-W3')) + >>> getCharWidths(u'\u6771\u4EAC', 'HeiseiMin-W3', 10) #most kanji are 100 ems + [10.0, 10.0] + """ + #character-level function call; the performance is going to SUCK + + return [stringWidth(uChar, fontName, fontSize) for uChar in word] + +def wordSplit(word, maxWidths, fontName, fontSize, encoding='utf8'): + """Attempts to break a word which lacks spaces into two parts, the first of which + fits in the remaining space. It is allowed to add hyphens or whatever it wishes. + + This is intended as a wrapper for some language- and user-choice-specific splitting + algorithms. It should only be called after line breaking on spaces, which covers western + languages and is highly optimised already. It works on the 'last unsplit word'. + + Presumably with further study one could write a Unicode splitting algorithm for text + fragments whick was much faster. + + Courier characters should be 6 points wide. + >>> wordSplit('HelloWorld', 30, 'Courier', 10) + [[0.0, 'Hello'], [0.0, 'World']] + >>> wordSplit('HelloWorld', 31, 'Courier', 10) + [[1.0, 'Hello'], [1.0, 'World']] + """ + if not isUnicode(word): + uword = word.decode(encoding) + else: + uword = word + + charWidths = getCharWidths(uword, fontName, fontSize) + lines = dumbSplit(uword, charWidths, maxWidths) + + if not isUnicode(word): + lines2 = [] + #convert back + for (extraSpace, text) in lines: + lines2.append([extraSpace, text.encode(encoding)]) + lines = lines2 + + return lines + +def dumbSplit(word, widths, maxWidths): + """This function attempts to fit as many characters as possible into the available + space, cutting "like a knife" between characters. This would do for Chinese. + It returns a list of (text, extraSpace) items where text is a Unicode string, + and extraSpace is the points of unused space available on the line. This is a + structure which is fairly easy to display, and supports 'backtracking' approaches + after the fact. + + Test cases assume each character is ten points wide... + + >>> dumbSplit(u'Hello', [10]*5, 60) + [[10, u'Hello']] + >>> dumbSplit(u'Hello', [10]*5, 50) + [[0, u'Hello']] + >>> dumbSplit(u'Hello', [10]*5, 40) + [[0, u'Hell'], [30, u'o']] + """ + _more = """ + #>>> dumbSplit(u'Hello', [10]*5, 4) # less than one character + #(u'', u'Hello') + # this says 'Nihongo wa muzukashii desu ne!' (Japanese is difficult isn't it?) in 12 characters + >>> jtext = u'\u65e5\u672c\u8a9e\u306f\u96e3\u3057\u3044\u3067\u3059\u306d\uff01' + >>> dumbSplit(jtext, [10]*11, 30) # + (u'\u65e5\u672c\u8a9e', u'\u306f\u96e3\u3057\u3044\u3067\u3059\u306d\uff01') + """ + if not isinstance(maxWidths,(list,tuple)): maxWidths = [maxWidths] + assert isUnicode(word) + lines = [] + i = widthUsed = lineStartPos = 0 + maxWidth = maxWidths[0] + nW = len(word) + while i maxWidth + _FUZZ and widthUsed>0: + extraSpace = maxWidth - widthUsed + if ord(c)<0x3000: + # we appear to be inside a non-Asian script section. + # (this is a very crude test but quick to compute). + # This is likely to be quite rare so the speed of the + # code below is hopefully not a big issue. The main + # situation requiring this is that a document title + # with an english product name in it got cut. + + + # we count back and look for + # - a space-like character + # - reversion to Kanji (which would be a good split point) + # - in the worst case, roughly half way back along the line + limitCheck = (lineStartPos+i)>>1 #(arbitrary taste issue) + for j in range(i-1,limitCheck,-1): + cj = word[j] + if category(cj)=='Zs' or ord(cj)>=0x3000: + k = j+1 + if k + if c not in ALL_CANNOT_START and i>lineStartPos+1: + #otherwise we need to push the character back + #the i>lineStart+1 condition ensures progress + i -= 1 + extraSpace += w + + #lines.append([maxWidth-sum(widths[lineStartPos:i]), word[lineStartPos:i].strip()]) + lines.append([extraSpace, word[lineStartPos:i].strip()]) + try: + maxWidth = maxWidths[len(lines)] + except IndexError: + maxWidth = maxWidths[-1] # use the last one + lineStartPos = i + widthUsed = 0 + + #any characters left? + if widthUsed > 0: + lines.append([maxWidth - widthUsed, word[lineStartPos:]]) + + return lines + +def kinsokuShoriSplit(word, widths, availWidth): + #NOT USED OR FINISHED YET! + """Split according to Japanese rules according to CJKV (Lunde). + + Essentially look for "nice splits" so that we don't end a line + with an open bracket, or start one with a full stop, or stuff like + that. There is no attempt to try to split compound words into + constituent kanji. It currently uses wrap-down: packs as much + on a line as possible, then backtracks if needed + + This returns a number of words each of which should just about fit + on a line. If you give it a whole paragraph at once, it will + do all the splits. + + It's possible we might slightly step over the width limit + if we do hanging punctuation marks in future (e.g. dangle a Japanese + full stop in the right margin rather than using a whole character + box. + + """ + lines = [] + assert len(word) == len(widths) + curWidth = 0.0 + curLine = [] + i = 0 #character index - we backtrack at times so cannot use for loop + while 1: + ch = word[i] + w = widths[i] + if curWidth + w < availWidth: + curLine.append(ch) + curWidth += w + else: + #end of line. check legality + if ch in CANNOT_END_LINE[0]: + pass + #to be completed + +# This recipe refers: +# +# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061 +import re +rx=re.compile("([\u2e80-\uffff])", re.UNICODE) +def cjkwrap(text, width, encoding="utf8"): + return reduce(lambda line, word, width=width: '%s%s%s' % + (line, + [' ','\n', ''][(len(line)-line.rfind('\n')-1 + + len(word.split('\n',1)[0] ) >= width) or + line[-1:] == '\0' and 2], + word), + rx.sub(r'\1\0 ', str(text,encoding)).split(' ') + ).replace('\0', '').encode(encoding) + +if __name__=='__main__': + import doctest + from reportlab.lib import textsplit + doctest.testmod(textsplit) diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/units.py b/.venv/lib/python3.13/site-packages/reportlab/lib/units.py new file mode 100644 index 0000000000000000000000000000000000000000..14d78915a4b46ad183d3e7e4150e492482fa6f82 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/units.py @@ -0,0 +1,30 @@ +#!/bin/env python +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/units.py +__version__='3.3.0' +__doc__='''Defines inch, cm, mm etc as multiples of a point + +You can now in user-friendly units by doing:: + + from reportlab.lib.units import inch + r = Rect(0, 0, 3 * inch, 6 * inch) + +''' +inch = 72.0 +cm = inch / 2.54 +mm = cm * 0.1 +pica = 12.0 + +def toLength(s): + '''convert a string to a length''' + try: + if s[-2:]=='cm': return float(s[:-2])*cm + if s[-2:]=='in': return float(s[:-2])*inch + if s[-2:]=='pt': return float(s[:-2]) + if s[-1:]=='i': return float(s[:-1])*inch + if s[-2:]=='mm': return float(s[:-2])*mm + if s[-4:]=='pica': return float(s[:-4])*pica + return float(s) + except: + raise ValueError("Can't convert '%s' to length" % s) diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/utils.py b/.venv/lib/python3.13/site-packages/reportlab/lib/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3fbc9bbefd5dac57a3973e7c17651fd06d941733 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/utils.py @@ -0,0 +1,1398 @@ +#Copyright ReportLab Europe Ltd. 2000-2019 +#see license.txt for license details +# $URI:$ +__version__='3.5.34' +__doc__='''Gazillions of miscellaneous internal utility functions''' + +import os, pickle, sys, time, types, datetime, importlib +from ast import literal_eval +from base64 import decodebytes as base64_decodebytes, encodebytes as base64_encodebytes +from io import BytesIO +from hashlib import md5 + +from reportlab.lib.rltempfile import get_rl_tempfile, get_rl_tempdir +from . rl_safe_eval import rl_safe_exec, rl_safe_eval, safer_globals, rl_extended_literal_eval +from PIL import Image + +class __UNSET__: + @staticmethod + def __bool__(): + return False + @staticmethod + def __str__(): + return '__UNSET__' + __repr__ = __str__ +__UNSET__ = __UNSET__() + +try: + import platform + isPyPy = platform.python_implementation()=='PyPy' +except: + isPyPy = False + +def isFunction(v): + return type(v) == type(isFunction) + +class c: + def m(self): pass + +def isMethod(v,mt=type(c.m)): + return type(v) == mt +del c + +def isModule(v): + return type(v) == type(sys) + +def isSeq(v,_st=(tuple,list)): + return isinstance(v,_st) + +def isNative(v): + return isinstance(v, str) + +#isStr is supposed to be for arbitrary stringType +#isBytes for bytes strings only +#isUnicode for proper unicode +_rl_NoneType=type(None) +strTypes = (str,bytes) +def _digester(s): + return md5(s if isBytes(s) else s.encode('utf8'),usedforsecurity=False).hexdigest() + +def asBytes(v,enc='utf8'): + if isinstance(v,bytes): return v + try: + return v.encode(enc) + except: + annotateException('asBytes(%s,enc=%s) error: ' % (ascii(v),ascii(enc))) + +def asUnicode(v,enc='utf8'): + if isinstance(v,str): return v + try: + return v.decode(enc) + except: + annotateException('asUnicode(%s,enc=%s) error: ' % (ascii(v),ascii(enc))) + +def asUnicodeEx(v,enc='utf8'): + if isinstance(v,str): return v + try: + return v.decode(enc) if isinstance(v,bytes) else str(v) + except: + annotateException('asUnicodeEx(%s,enc=%s) error: ' % (ascii(v),ascii(enc))) + +def asNative(v,enc='utf8'): + return asUnicode(v,enc=enc) + +def int2Byte(i): + return bytes([i]) + +def isStr(v): + return isinstance(v, (str,bytes)) + +def isBytes(v): + return isinstance(v, bytes) + +def isUnicode(v): + return isinstance(v, str) + +def isClass(v): + return isinstance(v, type) + +def isNonPrimitiveInstance(x): + return not isinstance(x,(float,int,type,tuple,list,dict,str,bytes,complex,bool,slice,_rl_NoneType, + types.FunctionType,types.LambdaType,types.CodeType, + types.MappingProxyType,types.SimpleNamespace, + types.GeneratorType,types.MethodType,types.BuiltinFunctionType, + types.BuiltinMethodType,types.ModuleType,types.TracebackType, + types.FrameType,types.GetSetDescriptorType,types.MemberDescriptorType)) + +def instantiated(v): + return not isinstance(v,type) + +def bytestr(x,enc='utf8'): + if isinstance(x,str): + return x.encode(enc) + elif isinstance(x,bytes): + return x + else: + return str(x).encode(enc) + +def encode_label(args): + return base64_encodebytes(ascii(args).encode('ascii')).strip().decode('ascii') + +def decode_label(label): + return literal_eval(base64_decodebytes(label.encode('ascii')).decode('ascii')) + +def rawUnicode(s): + '''converts first 256 unicodes 1-1''' + return s.decode('latin1') if not isinstance(s,str) else s + +def rawBytes(s): + '''converts first 256 unicodes 1-1''' + return s.encode('latin1') if isinstance(s,str) else s +import builtins +rl_exec = getattr(builtins,'exec') +del builtins +def char2int(s): + return s if isinstance(s,int) else ord(s if isinstance(s,str) else s.decode('latin1')) +def rl_reraise(t, v, b=None): + if v.__traceback__ is not b: + raise v.with_traceback(b) + raise v +def rl_add_builtins(**kwd): + import builtins + for k,v in kwd.items(): + setattr(builtins,k,v) + +def zipImported(ldr=None): + try: + if not ldr: + ldr = sys._getframe(1).f_globals['__loader__'] + from zipimport import zipimporter + return ldr if isinstance(ldr,zipimporter) and len(ldr._files) else None + except: + return None + +def _findFiles(dirList,ext='.ttf'): + from os.path import isfile, isdir, join as path_join + from os import listdir + ext = ext.lower() + R = [] + A = R.append + for D in dirList: + if not isdir(D): continue + for fn in listdir(D): + fn = path_join(D,fn) + if isfile(fn) and (not ext or fn.lower().endswith(ext)): A(fn) + return R + +class CIDict(dict): + def __init__(self,*args,**kwds): + for a in args: self.update(a) + self.update(kwds) + + def update(self,D): + for k,v in D.items(): self[k] = v + + def __setitem__(self,k,v): + try: + k = k.lower() + except: + pass + dict.__setitem__(self,k,v) + + def __getitem__(self,k): + try: + k = k.lower() + except: + pass + return dict.__getitem__(self,k) + + def __delitem__(self,k): + try: + k = k.lower() + except: + pass + return dict.__delitem__(self,k) + + def get(self,k,dv=None): + try: + return self[k] + except KeyError: + return dv + + def __contains__(self,k): + try: + self[k] + return True + except: + return False + + def pop(self,k,*a): + try: + k = k.lower() + except: + pass + return dict.pop(*((self,k)+a)) + + def setdefault(self,k,*a): + try: + k = k.lower() + except: + pass + return dict.setdefault(*((self,k)+a)) + +if os.name == 'mac': + #with the Mac, we need to tag the file in a special + #way so the system knows it is a PDF file. + #This supplied by Joe Strout + import macfs, macostools + _KNOWN_MAC_EXT = { + 'BMP' : ('ogle','BMP '), + 'EPS' : ('ogle','EPSF'), + 'EPSF': ('ogle','EPSF'), + 'GIF' : ('ogle','GIFf'), + 'JPG' : ('ogle','JPEG'), + 'JPEG': ('ogle','JPEG'), + 'PCT' : ('ttxt','PICT'), + 'PICT': ('ttxt','PICT'), + 'PNG' : ('ogle','PNGf'), + 'PPM' : ('ogle','.PPM'), + 'TIF' : ('ogle','TIFF'), + 'TIFF': ('ogle','TIFF'), + 'PDF' : ('CARO','PDF '), + 'HTML': ('MSIE','TEXT'), + } + def markfilename(filename,creatorcode=None,filetype=None,ext='PDF'): + try: + if creatorcode is None or filetype is None and ext is not None: + try: + creatorcode, filetype = _KNOWN_MAC_EXT[ext.upper()] + except: + return + macfs.FSSpec(filename).SetCreatorType(creatorcode,filetype) + macostools.touched(filename) + except: + pass +else: + def markfilename(filename,creatorcode=None,filetype=None): + pass + +import reportlab +__RL_DIR=os.path.dirname(reportlab.__file__) #possibly relative +_RL_DIR=os.path.isabs(__RL_DIR) and __RL_DIR or os.path.abspath(__RL_DIR) +del reportlab + +#Attempt to detect if this copy of reportlab is running in a +#file system (as opposed to mostly running in a zip or McMillan +#archive or Jar file). This is used by test cases, so that +#we can write test cases that don't get activated in frozen form. +try: + __file__ +except: + __file__ = sys.argv[0] +import glob, fnmatch +try: + __rl_loader__ = __loader__ + _isFSD = not __rl_loader__ + if not zipImported(ldr=__rl_loader__): + raise NotImplementedError("can't handle compact distro type %r" % __rl_loader__) + _archive = os.path.normcase(os.path.normpath(__rl_loader__.archive)) + _archivepfx = _archive + os.sep + _archivedir = os.path.dirname(_archive) + _archivedirpfx = _archivedir + os.sep + _archivepfxlen = len(_archivepfx) + _archivedirpfxlen = len(_archivedirpfx) + def __startswith_rl(fn, + _archivepfx=_archivepfx, + _archivedirpfx=_archivedirpfx, + _archive=_archive, + _archivedir=_archivedir, + os_path_normpath=os.path.normpath, + os_path_normcase=os.path.normcase, + os_getcwd=os.getcwd, + os_sep=os.sep, + os_sep_len = len(os.sep)): + '''if the name starts with a known prefix strip it off''' + fn = os_path_normpath(fn.replace('/',os_sep)) + nfn = os_path_normcase(fn) + if nfn in (_archivedir,_archive): return 1,'' + if nfn.startswith(_archivepfx): return 1,fn[_archivepfxlen:] + if nfn.startswith(_archivedirpfx): return 1,fn[_archivedirpfxlen:] + cwd = os_path_normcase(os_getcwd()) + n = len(cwd) + if nfn.startswith(cwd): + if fn[n:].startswith(os_sep): return 1, fn[n+os_sep_len:] + if n==len(fn): return 1,'' + return not os.path.isabs(fn),fn + + def _startswith_rl(fn): + return __startswith_rl(fn)[1] + + def rl_glob(pattern,glob=glob.glob,fnmatch=fnmatch.fnmatch, _RL_DIR=_RL_DIR,pjoin=os.path.join): + c, pfn = __startswith_rl(pattern) + r = glob(pfn) + if c or r==[]: + r += list(map(lambda x,D=_archivepfx,pjoin=pjoin: pjoin(_archivepfx,x),list(filter(lambda x,pfn=pfn,fnmatch=fnmatch: fnmatch(x,pfn),list(__rl_loader__._files.keys()))))) + return r +except: + _isFSD = os.path.isfile(__file__) #slight risk of wrong path + __rl_loader__ = None + def _startswith_rl(fn): + return fn + def rl_glob(pattern,glob=glob.glob): + return glob(pattern) +del glob, fnmatch +_isFSSD = _isFSD and os.path.isfile(os.path.splitext(__file__)[0] +'.py') + +def isFileSystemDistro(): + '''return truth if a file system distribution''' + return _isFSD + +def isCompactDistro(): + '''return truth if not a file system distribution''' + return not _isFSD + +def isSourceDistro(): + '''return truth if a source file system distribution''' + return _isFSSD + +def normalize_path(p): + return os.path.normcase(os.path.abspath(os.path.normpath(p))) + +_importlib_invalidate_caches = getattr(importlib,'invalidate_caches',lambda :None) + +def recursiveImport(modulename, baseDir=None, noCWD=0, debug=0): + """Dynamically imports possible packagized module, or raises ImportError""" + path = [normalize_path(p) for p in sys.path] + if baseDir: + for p in baseDir if isinstance(baseDir,(list,tuple)) else (baseDir,): + if p: + p = normalize_path(p) + if p not in path: path.insert(0,p) + if noCWD: + for p in ('','.',normalize_path('.')): + while p in path: + if debug: print('removed "%s" from path' % p) + path.remove(p) + else: + p = os.getcwd() + if p not in path: + path.insert(0,p) + + #make import errors a bit more informative + opath = sys.path + try: + sys.path = path + _importlib_invalidate_caches() + if debug: + print() + print(20*'+') + print('+++++ modulename=%s' % ascii(modulename)) + print('+++++ cwd=%s' % ascii(os.getcwd())) + print('+++++ sys.path=%s' % ascii(sys.path)) + print('+++++ os.paths.isfile(%s)=%s' % (ascii('./%s.py'%modulename), ascii(os.path.isfile('./%s.py'%modulename)))) + print('+++++ opath=%s' % ascii(opath)) + print(20*'-') + return importlib.import_module(modulename) + except ImportError: + annotateException("Could not import %r\nusing sys.path %r in cwd=%r" % ( + modulename,sys.path,os.getcwd()) + ) + except: + annotateException("Exception %s while importing %r\nusing sys.path %r in cwd=%r" % ( + str(sys.exc_info()[1]), modulename,sys.path,os.getcwd())) + finally: + sys.path = opath + _importlib_invalidate_caches() + if debug: + print('===== restore sys.path=%s' % repr(opath)) + +haveImages = Image is not None + +class ArgvDictValue: + '''A type to allow clients of getArgvDict to specify a conversion function''' + def __init__(self,value,func): + self.value = value + self.func = func + +def getArgvDict(**kw): + ''' Builds a dictionary from its keyword arguments with overrides from sys.argv. + Attempts to be smart about conversions, but the value can be an instance + of ArgDictValue to allow specifying a conversion function. + ''' + def handleValue(v,av,func): + if func: + v = func(av) + else: + if isStr(v): + v = av + elif isinstance(v,float): + v = float(av) + elif isinstance(v,int): + v = int(av) + elif isinstance(v,list): + v = list(literal_eval(av),{}) + elif isinstance(v,tuple): + v = tuple(literal_eval(av),{}) + else: + raise TypeError("Can't convert string %r to %s" % (av,type(v))) + return v + + A = sys.argv[1:] + R = {} + for k, v in kw.items(): + if isinstance(v,ArgvDictValue): + v, func = v.value, v.func + else: + func = None + handled = 0 + ke = k+'=' + for a in A: + if a.startswith(ke): + av = a[len(ke):] + A.remove(a) + R[k] = handleValue(v,av,func) + handled = 1 + break + + if not handled: R[k] = handleValue(v,v,func) + + return R + +def getHyphenater(hDict=None): + try: + from reportlab.lib.pyHnj import Hyphen + if hDict is None: hDict=os.path.join(os.path.dirname(__file__),'hyphen.mashed') + return Hyphen(hDict) + except ImportError as errMsg: + if str(errMsg)!='No module named pyHnj': raise + return None + +def _className(self): + '''Return a shortened class name''' + try: + name = self.__class__.__name__ + i=name.rfind('.') + if i>=0: return name[i+1:] + return name + except AttributeError: + return str(self) + +def open_for_read_by_name(name,mode='b'): + if 'r' not in mode: mode = 'r'+mode + try: + return open(name,mode) + except IOError: + if _isFSD or __rl_loader__ is None: raise + #we have a __rl_loader__, perhaps the filename starts with + #the dirname(reportlab.__file__) or is relative + name = _startswith_rl(name) + s = __rl_loader__.get_data(name) + if 'b' not in mode and os.linesep!='\n': s = s.replace(os.linesep,'\n') + return BytesIO(s) + +from urllib.parse import unquote, urlparse +from urllib.request import urlopen, Request +def rlUrlRead(name, headers=None): + if headers==None: headers = {} + headers.setdefault('User-Agent','ReportLabAgent') + return urlopen(Request(name,headers=headers)).read() + +def open_for_read(name,mode='b'): + #auto initialized function` + #copied here from urllib.URLopener.open_data because + # 1) they want to remove it + # 2) the existing one is borken + def datareader(url, unquote=unquote): + """Use "data" URL.""" + # ignore POSTed data + # + # syntax of data URLs: + # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data + # mediatype := [ type "/" subtype ] *( ";" parameter ) + # data := *urlchar + # parameter := attribute "=" value + try: + typ, data = url.split(',', 1) + except ValueError: + raise IOError('data error', 'bad data URL') + if not typ: + typ = 'text/plain;charset=US-ASCII' + semi = typ.rfind(';') + if semi >= 0 and '=' not in typ[semi:]: + encoding = typ[semi+1:] + typ = typ[:semi] + else: + encoding = '' + if encoding == 'base64': + # XXX is this encoding/decoding ok? + data = base64_decodebytes(data.encode('ascii')) + else: + data = unquote(data).encode('latin-1') + return data + from reportlab.rl_config import trustedHosts, trustedSchemes + if trustedHosts: + import re, fnmatch + def xre(s): + s = fnmatch.translate(s) + return s[4:-3] if s.startswith('(?s:') else s[:-7] + trustedHosts = re.compile(''.join(('^(?:', + '|'.join(map(xre,trustedHosts)), + ')\\Z'))) + + def open_for_read(name,mode='b'): + '''attempt to open a file or URL for reading''' + if hasattr(name,'read'): return name + try: + return open_for_read_by_name(name,mode) + except: + try: + if not trustedHosts: raise ValueError + netloc = urlparse(name) + scheme = netloc.scheme + netloc = netloc.netloc.lower() + if (not scheme + or scheme not in trustedSchemes + or (scheme=='file' and not ( + (netloc=='' and trustedHosts.match('localhost')) + or + (netloc!='' and trustedHosts.match(netloc)) + )) + or (scheme not in ('data','file') and not trustedHosts.match(netloc))): + raise ValueError + return BytesIO((datareader if scheme=='data' else rlUrlRead)(name)) + except: + raise IOError(f'Cannot open resource {name!r}') + globals()['open_for_read'] = open_for_read + return open_for_read(name,mode) + +def open_and_read(name,mode='b'): + f = open_for_read(name,mode) + if name is not f and hasattr(f,'__exit__'): + with f: + return f.read() + else: + return f.read() + +def open_and_readlines(name,mode='t'): + return open_and_read(name,mode).split('\n') + +def rl_isfile(fn,os_path_isfile=os.path.isfile): + if hasattr(fn,'read'): return True + if os_path_isfile(fn): return True + if _isFSD or __rl_loader__ is None: return False + fn = _startswith_rl(fn) + return fn in list(__rl_loader__._files.keys()) + +def rl_isdir(pn,os_path_isdir=os.path.isdir,os_path_normpath=os.path.normpath): + if os_path_isdir(pn): return True + if _isFSD or __rl_loader__ is None: return False + pn = _startswith_rl(os_path_normpath(pn)) + if not pn.endswith(os.sep): pn += os.sep + return len(list(filter(lambda x,pn=pn: x.startswith(pn),list(__rl_loader__._files.keys()))))>0 + +def rl_listdir(pn,os_path_isdir=os.path.isdir,os_path_normpath=os.path.normpath,os_listdir=os.listdir): + if os_path_isdir(pn) or _isFSD or __rl_loader__ is None: return os_listdir(pn) + pn = _startswith_rl(os_path_normpath(pn)) + if not pn.endswith(os.sep): pn += os.sep + return [x[len(pn):] for x in __rl_loader__._files.keys() if x.startswith(pn)] + +def rl_getmtime(pn,os_path_isfile=os.path.isfile,os_path_normpath=os.path.normpath,os_path_getmtime=os.path.getmtime,time_mktime=time.mktime): + if os_path_isfile(pn) or _isFSD or __rl_loader__ is None: return os_path_getmtime(pn) + p = _startswith_rl(os_path_normpath(pn)) + try: + e = __rl_loader__._files[p] + except KeyError: + return os_path_getmtime(pn) + s = e[5] + d = e[6] + return time_mktime((((d>>9)&0x7f)+1980,(d>>5)&0xf,d&0x1f,(s>>11)&0x1f,(s>>5)&0x3f,(s&0x1f)<<1,0,0,0)) + +from importlib import util as importlib_util +def __rl_get_module__(name,dir): + for ext in ('.py','.pyw','.pyo','.pyc','.pyd'): + path = os.path.join(dir,name+ext) + if os.path.isfile(path): + spec = importlib_util.spec_from_file_location(name,path) + module = importlib_util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + raise ImportError('no suitable file found') + +def rl_get_module(name,dir): + if name in sys.modules: + om = sys.modules[name] + del sys.modules[name] + else: + om = None + try: + try: + return __rl_get_module__(name,dir) + except: + if isCompactDistro(): + #attempt a load from inside the zip archive + import zipimport + dir = _startswith_rl(dir) + dir = (dir=='.' or not dir) and _archive or os.path.join(_archive,dir.replace('/',os.sep)) + zi = zipimport.zipimporter(dir) + return zi.load_module(name) + raise ImportError('%s[%s]' % (name,dir)) + finally: + if om: sys.modules[name] = om + +def _isPILImage(im): + try: + return isinstance(im,Image.Image) + except AttributeError: + return 0 + +class ImageReader: + "Wraps up PIL to get data from bitmaps" + _cache={} + _max_image_size = None + def __init__(self, fileName,ident=None): + if isinstance(fileName,ImageReader): + self.__dict__ = fileName.__dict__ #borgize + return + self._ident = ident + #start wih lots of null private fields, to be populated by + #the relevant engine. + self.fileName = fileName + self._image = None + self._width = None + self._height = None + self._transparent = None + self._data = None + if _isPILImage(fileName): + self._image = fileName + self.fp = getattr(fileName,'fp',None) + try: + self.fileName = self._image.fileName + except AttributeError: + self.fileName = 'PILIMAGE_%d' % id(self) + else: + try: + from reportlab.rl_config import imageReaderFlags + if imageReaderFlags != 0: + raise ValueError('imageReaderFlags values other than 0 are no longer supported; all images are interned now') + fp = open_for_read(fileName,'b') + if not isinstance(fp, BytesIO): + tfp, fp = fp, BytesIO(fp.read()) + tfp.close() + del tfp + self.fp = fp + self._image = self._read_image(self.fp) + self._image.fileName = fileName if isinstance(fileName,str) else repr(fileName) + self.check_pil_image_size(self._image) + if getattr(self._image,'format',None)=='JPEG': + self.jpeg_fh = self._jpeg_fh + except: + annotateException('\nfileName=%r identity=%s'%(fileName,self.identity())) + + def identity(self): + '''try to return information that will identify the instance''' + fn = self.fileName + if not isStr(fn): + fn = getattr(getattr(self,'fp',None),'name',None) + ident = self._ident + return '[%s@%s%s%s]' % (self.__class__.__name__,hex(id(self)),ident and (' ident=%r' % ident) or '',fn and (' filename=%r' % fn) or '') + + def _read_image(self,fp): + return Image.open(fp) + + @classmethod + def check_pil_image_size(cls, im): + max_image_size = cls._max_image_size + if max_image_size is None: return + w, h = im.size + m = im.mode + size = max(1,((1 if m=='1' else 8*len(m))*w*h)>>3) + if size>max_image_size: + raise MemoryError('PIL %s %s x %s image would use %s > %s bytes' + %(m,w,h,size,max_image_size)) + @classmethod + def set_max_image_size(cls,max_image_size=None): + cls._max_image_size = max_image_size + if max_image_size is not None: + from reportlab.rl_config import register_reset + register_reset(cls.set_max_image_size) + + def _jpeg_fh(self): + fp = self.fp + fp.seek(0) + return fp + + def jpeg_fh(self): + return None + + def getSize(self): + if (self._width is None or self._height is None): + self._width, self._height = self._image.size + return (self._width, self._height) + + def getRGBData(self): + "Return byte array of RGB data as string" + try: + if self._data is None: + self._dataA = None + im = self._image + mode = self.mode = im.mode + if mode in ('LA','RGBA'): + if getattr(Image,'VERSION','').startswith('1.1.7'): + im.load() + self._dataA = ImageReader(im.split()[3 if mode=='RGBA' else 1]) + nm = mode[:-1] + im = im.convert(nm) + self.mode = nm + elif mode not in ('L','RGB','CMYK'): + if im.format=='PNG' and im.mode=='P' and 'transparency' in im.info: + im = im.convert('RGBA') + self._dataA = ImageReader(im.split()[3]) + im = im.convert('RGB') + else: + im = im.convert('RGB') + self.mode = 'RGB' + self._data = (im.tobytes if hasattr(im, 'tobytes') else im.tostring)() #make pillow and PIL both happy, for now + return self._data + except: + annotateException('\nidentity=%s'%self.identity()) + + def getImageData(self): + width, height = self.getSize() + return width, height, self.getRGBData() + + def getTransparent(self): + if "transparency" in self._image.info: + transparency = self._image.info["transparency"] * 3 + palette = self._image.palette + try: + palette = palette.palette + except: + try: + palette = palette.data + except: + return None + return palette[transparency:transparency+3] + else: + return None + +class LazyImageReader(ImageReader): + pass #now same as base class since we intern everything + +def getImageData(imageFileName): + "Get width, height and RGB pixels from image file. Wraps PIL" + try: + return imageFileName.getImageData() + except AttributeError: + return ImageReader(imageFileName).getImageData() + +class DebugMemo: + '''Intended as a simple report back encapsulator + + Typical usages: + + 1. To record error data:: + + dbg = DebugMemo(fn='dbgmemo.dbg',myVar=value) + dbg.add(anotherPayload='aaaa',andagain='bbb') + dbg.dump() + + 2. To show the recorded info:: + + dbg = DebugMemo(fn='dbgmemo.dbg',mode='r') + dbg.load() + dbg.show() + + 3. To re-use recorded information:: + + dbg = DebugMemo(fn='dbgmemo.dbg',mode='r') + dbg.load() + myTestFunc(dbg.payload('myVar'),dbg.payload('andagain')) + + In addition to the payload variables the dump records many useful bits + of information which are also printed in the show() method. + ''' + def __init__(self,fn='rl_dbgmemo.dbg',mode='w',getScript=1,modules=(),capture_traceback=1, stdout=None, **kw): + import socket + self.fn = fn + if not stdout: + self.stdout = sys.stdout + else: + if hasattr(stdout,'write'): + self.stdout = stdout + else: + self.stdout = open(stdout,'w') + if mode!='w': return + self.store = store = {} + if capture_traceback and sys.exc_info() != (None,None,None): + import traceback + s = BytesIO() + traceback.print_exc(None,s) + store['__traceback'] = s.getvalue() + cwd=os.getcwd() + lcwd = os.listdir(cwd) + pcwd = os.path.dirname(cwd) + lpcwd = pcwd and os.listdir(pcwd) or '???' + exed = os.path.abspath(os.path.dirname(sys.argv[0])) + project_version='???' + md=None + try: + import marshal + md=marshal.loads(__rl_loader__.get_data('meta_data.mar')) + project_version=md['project_version'] + except: + pass + env = os.environ + K=list(env.keys()) + K.sort() + store.update({ 'gmt': time.asctime(time.gmtime(time.time())), + 'platform': sys.platform, + 'version': sys.version, + 'hexversion': hex(sys.hexversion), + 'executable': sys.executable, + 'exec_prefix': sys.exec_prefix, + 'prefix': sys.prefix, + 'path': sys.path, + 'argv': sys.argv, + 'cwd': cwd, + 'hostname': socket.gethostname(), + 'lcwd': lcwd, + 'lpcwd': lpcwd, + 'byteorder': sys.byteorder, + 'maxint': getattr(sys,'maxunicode','????'), + 'api_version': getattr(sys,'api_version','????'), + 'version_info': getattr(sys,'version_info','????'), + 'winver': getattr(sys,'winver','????'), + 'environment': '\n\t\t\t'.join(['']+['%s=%r' % (k,env[k]) for k in K]), + '__rl_loader__': repr(__rl_loader__), + 'project_meta_data': md, + 'project_version': project_version, + }) + for M,A in ( + (sys,('getwindowsversion','getfilesystemencoding')), + (os,('uname', 'ctermid', 'getgid', 'getuid', 'getegid', + 'geteuid', 'getlogin', 'getgroups', 'getpgrp', 'getpid', 'getppid', + )), + ): + for a in A: + if hasattr(M,a): + try: + store[a] = getattr(M,a)() + except: + pass + if exed!=cwd: + try: + store.update({'exed': exed, 'lexed': os.listdir(exed),}) + except: + pass + if getScript: + fn = os.path.abspath(sys.argv[0]) + if os.path.isfile(fn): + try: + store['__script'] = (fn,open(fn,'r').read()) + except: + pass + module_versions = {} + for n,m in sys.modules.items(): + if n=='reportlab' or n=='rlextra' or n[:10]=='reportlab.' or n[:8]=='rlextra.': + v = [getattr(m,x,None) for x in ('__version__','__path__','__file__')] + if [_f for _f in v if _f]: + v = [v[0]] + [_f for _f in v[1:] if _f] + module_versions[n] = tuple(v) + store['__module_versions'] = module_versions + self.store['__payload'] = {} + self._add(kw) + + def _add(self,D): + payload = self.store['__payload'] + for k, v in D.items(): + payload[k] = v + + def add(self,**kw): + self._add(kw) + + def _dump(self,f): + try: + pos=f.tell() + pickle.dump(self.store,f) + except: + S=self.store.copy() + ff=BytesIO() + for k,v in S.items(): + try: + pickle.dump({k:v},ff) + except: + S[k] = '' % v + f.seek(pos,0) + pickle.dump(S,f) + + def dump(self): + f = open(self.fn,'wb') + try: + self._dump(f) + finally: + f.close() + + def dumps(self): + f = BytesIO() + self._dump(f) + return f.getvalue() + + def _load(self,f): + self.store = pickle.load(f) + + def load(self): + f = open(self.fn,'rb') + try: + self._load(f) + finally: + f.close() + + def loads(self,s): + self._load(BytesIO(s)) + + def _show_module_versions(self,k,v): + self._writeln(k[2:]) + K = list(v.keys()) + K.sort() + for k in K: + vk = vk0 = v[k] + if isinstance(vk,tuple): vk0 = vk[0] + try: + __import__(k) + m = sys.modules[k] + d = getattr(m,'__version__',None)==vk0 and 'SAME' or 'DIFFERENT' + except: + m = None + d = '??????unknown??????' + self._writeln(' %s = %s (%s)' % (k,vk,d)) + + def _banner(self,k,what): + self._writeln('###################%s %s##################' % (what,k[2:])) + + def _start(self,k): + self._banner(k,'Start ') + + def _finish(self,k): + self._banner(k,'Finish ') + + def _show_lines(self,k,v): + self._start(k) + self._writeln(v) + self._finish(k) + + def _show_file(self,k,v): + k = '%s %s' % (k,os.path.basename(v[0])) + self._show_lines(k,v[1]) + + def _show_payload(self,k,v): + if v: + import pprint + self._start(k) + pprint.pprint(v,self.stdout) + self._finish(k) + + def _show_extensions(self): + for mn in ('_rl_accel','sgmlop','_imaging','Image'): + try: + A = [mn].append + __import__(mn) + m = sys.modules[mn] + A(m.__file__) + for vn in ('__version__','VERSION','_version','version'): + if hasattr(m,vn): + A('%s=%r' % (vn,getattr(m,vn))) + except: + A('not found') + self._writeln(' '+' '.join(A.__self__)) + + specials = {'__module_versions': _show_module_versions, + '__payload': _show_payload, + '__traceback': _show_lines, + '__script': _show_file, + } + def show(self): + K = list(self.store.keys()) + K.sort() + for k in K: + if k not in list(self.specials.keys()): self._writeln('%-15s = %s' % (k,self.store[k])) + for k in K: + if k in list(self.specials.keys()): self.specials[k](self,k,self.store[k]) + self._show_extensions() + + def payload(self,name): + return self.store['__payload'][name] + + def __setitem__(self,name,value): + self.store['__payload'][name] = value + + def __getitem__(self,name): + return self.store['__payload'][name] + + def _writeln(self,msg): + self.stdout.write(msg+'\n') + +def _flatten(L,a): + for x in L: + if isSeq(x): _flatten(x,a) + else: a(x) + +def flatten(L): + '''recursively flatten the list or tuple L''' + R = [] + _flatten(L,R.append) + return R + +def find_locals(func,depth=0): + '''apply func to the locals at each stack frame till func returns a non false value''' + while 1: + _ = func(sys._getframe(depth).f_locals) + if _: return _ + depth += 1 + +class _FmtSelfDict: + def __init__(self,obj,overrideArgs): + self.obj = obj + self._overrideArgs = overrideArgs + def __getitem__(self,k): + try: + return self._overrideArgs[k] + except KeyError: + try: + return self.obj.__dict__[k] + except KeyError: + return getattr(self.obj,k) + +class FmtSelfDict: + '''mixin to provide the _fmt method''' + def _fmt(self,fmt,**overrideArgs): + D = _FmtSelfDict(self, overrideArgs) + return fmt % D + +def _simpleSplit(txt,mW,SW): + L = [] + ws = SW(' ') + O = [] + w = -ws + for t in txt.split(): + lt = SW(t) + if w+ws+lt<=mW or O==[]: + O.append(t) + w = w + ws + lt + else: + L.append(' '.join(O)) + O = [t] + w = lt + if O!=[]: L.append(' '.join(O)) + return L + +def simpleSplit(text,fontName,fontSize,maxWidth): + from reportlab.pdfbase.pdfmetrics import stringWidth + lines = asUnicode(text).split(u'\n') + SW = lambda text, fN=fontName, fS=fontSize: stringWidth(text, fN, fS) + if maxWidth: + L = [] + for l in lines: + L.extend(_simpleSplit(l,maxWidth,SW)) + lines = L + return lines + +def escapeTextOnce(text): + "Escapes once only" + from xml.sax.saxutils import escape + if text is None: + return text + if isBytes(text): s = text.decode('utf8') + text = escape(text) + text = text.replace(u'&amp;',u'&') + text = text.replace(u'&gt;', u'>') + text = text.replace(u'&lt;', u'<') + return text + +def fileName2FSEnc(fn): + if isUnicode(fn): + return fn + else: + for enc in fsEncodings: + try: + return fn.decode(enc) + except: + pass + raise ValueError('cannot convert %r to filesystem encoding' % fn) + +import itertools +def prev_this_next(items): + """ + Loop over a collection with look-ahead and look-back. + + From Thomas Guest, + http://wordaligned.org/articles/zippy-triples-served-with-python + + Seriously useful looping tool (Google "zippy triples") + lets you loop a collection and see the previous and next items, + which get set to None at the ends. + + To be used in layout algorithms where one wants a peek at the + next item coming down the pipe. + + """ + + extend = itertools.chain([None], items, [None]) + prev, this, next = itertools.tee(extend, 3) + try: + next(this) + next(next) + next(next) + except StopIteration: + pass + return zip(prev, this, next) + +def commasplit(s): + ''' + Splits the string s at every unescaped comma and returns the result as a list. + To escape a comma, double it. Individual items are stripped. + To avoid the ambiguity of 3 successive commas to denote a comma at the beginning + or end of an item, add a space between the item seperator and the escaped comma. + + >>> commasplit(u'a,b,c') == [u'a', u'b', u'c'] + True + >>> commasplit('a,, , b , c ') == [u'a,', u'b', u'c'] + True + >>> commasplit(u'a, ,,b, c') == [u'a', u',b', u'c'] + ''' + if isBytes(s): s = s.decode('utf8') + n = len(s)-1 + s += u' ' + i = 0 + r=[u''] + while i<=n: + if s[i]==u',': + if s[i+1]==u',': + r[-1]+=u',' + i += 1 + else: + r[-1] = r[-1].strip() + if i!=n: r.append(u'') + else: + r[-1] += s[i] + i+=1 + r[-1] = r[-1].strip() + return r + +def commajoin(l): + ''' + Inverse of commasplit, except that whitespace around items is not conserved. + Adds more whitespace than needed for simplicity and performance. + + >>> commasplit(commajoin(['a', 'b', 'c'])) == [u'a', u'b', u'c'] + True + >>> commasplit((commajoin([u'a,', u' b ', u'c'])) == [u'a,', u'b', u'c'] + True + >>> commasplit((commajoin([u'a ', u',b', u'c'])) == [u'a', u',b', u'c'] + ''' + return u','.join([ u' ' + asUnicode(i).replace(u',', u',,') + u' ' for i in l ]) + +def findInPaths(fn,paths,isfile=True,fail=False): + '''search for relative files in likely places''' + exists = isfile and os.path.isfile or os.path.isdir + if exists(fn): return fn + pjoin = os.path.join + if not os.path.isabs(fn): + for p in paths: + pfn = pjoin(p,fn) + if exists(pfn): + return pfn + if fail: raise ValueError('cannot locate %r with paths=%r' % (fn,paths)) + return fn + +def annotateException(msg,enc='utf8',postMsg='',sep=' '): + '''add msg to the args of an existing exception''' + t,v,b=sys.exc_info() + rl_reraise(t,t(sep.join((_ for _ in (msg,str(v),postMsg) if _))),b) + +def escapeOnce(data): + """Ensure XML output is escaped just once, irrespective of input + + >>> escapeOnce('A & B') + 'A & B' + >>> escapeOnce('C & D') + 'C & D' + >>> escapeOnce('E &amp; F') + 'E & F' + + """ + data = data.replace("&", "&") + + #...but if it was already escaped, make sure it + # is not done twice....this will turn any tags + # back to how they were at the start. + data = data.replace("&amp;", "&") + data = data.replace("&gt;", ">") + data = data.replace("&lt;", "<") + data = data.replace("&#", "&#") + + #..and just in case someone had double-escaped it, do it again + data = data.replace("&amp;", "&") + data = data.replace("&gt;", ">") + data = data.replace("&lt;", "<") + return data + +class IdentStr(str): + '''useful for identifying things that get split''' + def __new__(cls,value): + if isinstance(value,IdentStr): + inc = value.__inc + value = value[:-(2+len(str(inc)))] + inc += 1 + else: + inc = 0 + value += '[%d]' % inc + self = str.__new__(cls,value) + self.__inc = inc + return self + +class RLString(str): + '''allows specification of extra properties of a string using a dictionary of extra attributes + eg fontName = RLString('proxima-nova-bold', + svgAttrs=dict(family='"proxima-nova"',weight='bold')) + ''' + def __new__(cls,v,**kwds): + self = str.__new__(cls,v) + for k,v in kwds.items(): + setattr(self,k,v) + return self + +def makeFileName(s): + '''force filename strings to unicode so python can handle encoding stuff''' + if not isUnicode(s): + s = s.decode('utf8') + return s + +class FixedOffsetTZ(datetime.tzinfo): + """Fixed offset in minutes east from UTC.""" + + def __init__(self, h, m, name): + self.__offset = datetime.timedelta(hours=h, minutes = m) + self.__name = name + + def utcoffset(self, dt): + return self.__offset + + def tzname(self, dt): + return self.__name + + def dst(self, dt): + return datetime.timedelta(0) + +class TimeStamp: + def __init__(self,invariant=None): + if invariant is None: + from reportlab.rl_config import invariant + t = os.environ.get('SOURCE_DATE_EPOCH','').strip() + if invariant or t: + t = int(t) if t else 946684800.0 + lt = time.gmtime(t) + dhh = dmm = 0 + self.tzname = 'UTC' + else: + t = time.time() + local_time = time.localtime(t) + lt = tuple(local_time) + dhh = int(local_time.tm_gmtoff / (3600.0)) + dmm = (local_time.tm_gmtoff % 3600) % 60 + self.tzname = local_time.tm_zone + self.t = t + self.lt = lt + self.YMDhms = tuple(lt)[:6] + self.dhh = dhh + self.dmm = dmm + + @property + def datetime(self): + if self.tzname: + return datetime.datetime.fromtimestamp(self.t,FixedOffsetTZ(self.dhh,self.dmm,self.tzname)) + else: + return datetime.datetime.now() + + @property + def asctime(self): + return time.asctime(self.lt) + +def recursiveGetAttr(obj, name, g=None): + "Can call down into e.g. object1.object2[4].attr" + if not isStr(name): raise TypeError('invalid recursive access of %s.%s' % (repr(obj),name)) + name = asNative(name) + name = name.strip() + if not name: raise ValueError('empty recursive access of %s' % repr(obj)) + dot = '.' if name and name[0] not in '[.(' else '' + return rl_safe_eval('obj%s%s'%(dot,name), g={}, l=dict(obj=obj)) + +def recursiveSetAttr(obj, name, value): + "Can call down into e.g. object1.object2[4].attr = value" + #get the thing above last. + tokens = name.split('.') + if len(tokens) == 1: + setattr(obj, name, value) + else: + most = '.'.join(tokens[:-1]) + last = tokens[-1] + parent = recursiveGetAttr(obj, most) + setattr(parent, last, value) + +def recursiveDelAttr(obj, name): + tokens = name.split('.') + if len(tokens) == 1: + delattr(obj, name) + else: + most = '.'.join(tokens[:-1]) + last = tokens[-1] + parent = recursiveGetAttr(obj, most) + delattr(parent, last) + +def yieldNoneSplits(L): + '''yield sublists of L separated by None; the Nones disappear''' + i = 0 + n = len(L) + while i=self.lim: + for _ in list(store.keys())[:-self.lim]: + del store[_] + + def __contains__(self,k): + return k in self.store + + def __getitem__(self,k): + return self.store[k] + + def get(self,k,default=None): + return self.store.get(k,default) + +class rl_warn: + __shared_state = {} #resistance is futile we are a BORG + def __init__(self): + self.__dict__ = self.__shared_state + + def __call__(self,message): + if not self.__shared_state: + self.__warnings_seen = {} + from reportlab.rl_config import register_reset + register_reset(self.__reset) + import inspect, warnings + self.__inspect = inspect + self.__warnings = warnings + + if message not in self.__warnings_seen: + self.__warnings.warn(message,stacklevel=2) + frame = self.__inspect.stack()[1] + self.__warnings_seen.setdefault(message,set()).add( + f'in {frame.function} @ {frame.filename}:{frame.lineno}') + + def __reset(self): + self.__warnings_seen.clear() + + @property + def warnings_seen(self): + return self.__warnings_seen + +rl_warn = rl_warn() diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/validators.py b/.venv/lib/python3.13/site-packages/reportlab/lib/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..658dee1b7dd289d3780f5e7877cf2a8a78168d08 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/validators.py @@ -0,0 +1,382 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/validators.py +__version__='3.5.33' +__doc__="""Standard verifying functions used by attrmap.""" + +import codecs, re +from reportlab.lib.utils import isSeq, isBytes, isStr +from reportlab.lib import colors +try: + _re_Pattern = re.Pattern +except AttributeError: + _re_Pattern = re._pattern_type + +class Percentage(float): + pass + +class Validator: + "base validator class" + def __call__(self,x): + return self.test(x) + + def __str__(self): + return getattr(self,'_str',self.__class__.__name__) + + def normalize(self,x): + return x + + def normalizeTest(self,x): + try: + self.normalize(x) + return True + except: + return False + +class _isAnything(Validator): + def test(self,x): + return True + +class _isNothing(Validator): + def test(self,x): + return False + +class _isBoolean(Validator): + def test(self,x): + if isinstance(int,bool): return x in (0,1) + return self.normalizeTest(x) + + def normalize(self,x): + if x in (0,1): return x + try: + S = x.upper() + except: + raise ValueError('Must be boolean not %s' % ascii(s)) + if S in ('YES','TRUE'): return True + if S in ('NO','FALSE',None): return False + raise ValueError('Must be boolean not %s' % ascii(s)) + +class _isString(Validator): + def test(self,x): + return isStr(x) + +class _isCodec(Validator): + def test(self,x): + if not isStr(x): + return False + try: + a,b,c,d = codecs.lookup(x) + return True + except LookupError: + return False + +class _isNumber(Validator): + def test(self,x): + if isinstance(x,(float,int)): return True + return self.normalizeTest(x) + + def normalize(self,x): + try: + return float(x) + except: + return int(x) + +class _isInt(Validator): + def test(self,x): + if not isinstance(x,int) and not isStr(x): return False + return self.normalizeTest(x) + + def normalize(self,x): + return int(x.decode('utf8') if isBytes(x) else x) + +class _isNumberOrNone(_isNumber): + def test(self,x): + return x is None or isNumber(x) + + def normalize(self,x): + if x is None: return x + return _isNumber.normalize(x) + +class _isListOfNumbersOrNone(Validator): + "ListOfNumbersOrNone validator class." + def test(self, x): + if x is None: return True + return isListOfNumbers(x) + +class isNumberInRange(_isNumber): + def __init__(self, min, max): + self.min = min + self.max = max + + def test(self, x): + try: + n = self.normalize(x) + if self.min <= n <= self.max: + return True + except ValueError: + pass + return False + + +class _isListOfShapes(Validator): + "ListOfShapes validator class." + def test(self, x): + from reportlab.graphics.shapes import Shape + if isSeq(x): + answer = 1 + for e in x: + if not isinstance(e, Shape): + answer = 0 + return answer + else: + return False + +class _isListOfStringsOrNone(Validator): + "ListOfStringsOrNone validator class." + + def test(self, x): + if x is None: return True + return isListOfStrings(x) + +class _isTransform(Validator): + "Transform validator class." + def test(self, x): + if isSeq(x): + if len(x) == 6: + for element in x: + if not isNumber(element): + return False + return True + else: + return False + else: + return False + +class _isColor(Validator): + "Color validator class." + def test(self, x): + return isinstance(x, colors.Color) + +class _isColorOrNone(Validator): + "ColorOrNone validator class." + def test(self, x): + if x is None: return True + return isColor(x) + +from reportlab.lib.normalDate import NormalDate +class _isNormalDate(Validator): + def test(self,x): + if isinstance(x,NormalDate): + return True + return x is not None and self.normalizeTest(x) + + def normalize(self,x): + return NormalDate(x) + +class _isValidChild(Validator): + "ValidChild validator class." + def test(self, x): + """Is this child allowed in a drawing or group? + I.e. does it descend from Shape or UserNode? + """ + + from reportlab.graphics.shapes import UserNode, Shape + return isinstance(x, UserNode) or isinstance(x, Shape) + +class _isValidChildOrNone(_isValidChild): + def test(self,x): + return _isValidChild.test(self,x) or x is None + +class _isCallable(Validator): + def test(self, x): + return hasattr(x,'__call__') + +class OneOf(Validator): + """Make validator functions for list of choices. + + Usage: + f = reportlab.lib.validators.OneOf('happy','sad') + or + f = reportlab.lib.validators.OneOf(('happy','sad')) + f('sad'),f('happy'), f('grumpy') + (1,1,0) + """ + def __init__(self, enum,*args): + if isSeq(enum): + if args!=(): + raise ValueError("Either all singleton args or a single sequence argument") + self._enum = tuple(enum)+args + else: + self._enum = (enum,)+args + self._patterns = tuple((_ for _ in self._enum if isinstance(_,_re_Pattern))) + if self._patterns: + self._enum = tuple((_ for _ in self._enum if not isinstance(_,_re_Pattern))) + self.test = self._test_patterns + + def test(self, x): + return x in self._enum + + def _test_patterns(self, x): + v = x in self._enum + #print(f'{x=} {self._enum=!r} {self._patterns=!r} {v=}') + if v: return True + for p in self._patterns: + v = p.match(x) + if v: return True + return False + +class SequenceOf(Validator): + def __init__(self,elemTest,name=None,emptyOK=1, NoneOK=0, lo=0,hi=0x7fffffff): + self._elemTest = elemTest + self._emptyOK = emptyOK + self._NoneOK = NoneOK + self._lo, self._hi = lo, hi + if name: self._str = name + + def test(self, x): + if not isSeq(x): + if x is None: return self._NoneOK + return False + if x==[] or x==(): + return self._emptyOK + elif not self._lo<=len(x)<=self._hi: return False + for e in x: + if not self._elemTest(e): return False + return True + +class EitherOr(Validator): + def __init__(self,tests,name=None): + if not isSeq(tests): tests = (tests,) + self._tests = tests + if name: self._str = name + + def test(self, x): + for t in self._tests: + if t(x): return True + return False + +class NoneOr(EitherOr): + def test(self, x): + return x is None or super().test(x) + +class NotSetOr(EitherOr): + _not_set = object() + def test(self, x): + return x is NotSetOr._not_set or super().test(x) + + @staticmethod + def conditionalValue(v,a): + return a if v is NotSetOr._not_set else v + +class _isNotSet(Validator): + def test(self,x): + return x is NotSetOr._not_set + +class Auto(Validator): + def __init__(self,**kw): + self.__dict__.update(kw) + + def test(self,x): + return x is self.__class__ or isinstance(x,self.__class__) + +class AutoOr(EitherOr): + def test(self,x): + return isAuto(x) or super().test(x) + +class isInstanceOf(Validator): + def __init__(self,klass=None): + self._klass = klass + def test(self,x): + return isinstance(x,self._klass) + +class isSubclassOf(Validator): + def __init__(self,klass=None): + self._klass = klass + def test(self,x): + return isinstance(x,type) and issubclass(x,self._klass) + +class matchesPattern(Validator): + """Matches value, or its string representation, against regex""" + def __init__(self, pattern): + self._pattern = re.compile(pattern) + + def test(self,x): + x = str(x) + print('testing %s against %s' % (x, self._pattern)) + return (self._pattern.match(x) != None) + +class DerivedValue: + """This is used for magic values which work themselves out. + An example would be an "inherit" property, so that one can have + + drawing.chart.categoryAxis.labels.fontName = inherit + + and pick up the value from the top of the drawing. + Validators will permit this provided that a value can be pulled + in which satisfies it. And the renderer will have special + knowledge of these so they can evaluate themselves. + """ + def getValue(self, renderer, attr): + """Override this. The renderers will pass the renderer, + and the attribute name. Algorithms can then backtrack up + through all the stuff the renderer provides, including + a correct stack of parent nodes.""" + return None + +class Inherit(DerivedValue): + def __repr__(self): + return "inherit" + + def getValue(self, renderer, attr): + return renderer.getStateValue(attr) +inherit = Inherit() + +class NumericAlign(str): + '''for creating the numeric string value for anchors etc etc + dp is the character to align on (the last occurrence will be used) + dpLen is the length of characters after the dp + ''' + def __new__(cls,dp='.',dpLen=0): + self = str.__new__(cls,'numeric') + self._dp=dp + self._dpLen = dpLen + return self + + +isAuto = Auto() +isBoolean = _isBoolean() +isString = _isString() +isCodec = _isCodec() +isNumber = _isNumber() +isInt = _isInt() +isNoneOrInt = NoneOr(isInt,'isNoneOrInt') +isNumberOrNone = _isNumberOrNone() +isTextAnchor = OneOf('start','middle','end','boxauto') +isListOfNumbers = SequenceOf(isNumber,'isListOfNumbers') +isListOfNoneOrNumber = SequenceOf(isNumberOrNone,'isListOfNoneOrNumber') +isListOfListOfNoneOrNumber = SequenceOf(isListOfNoneOrNumber,'isListOfListOfNoneOrNumber') +isListOfNumbersOrNone = _isListOfNumbersOrNone() +isListOfShapes = _isListOfShapes() +isListOfStrings = SequenceOf(isString,'isListOfStrings') +isListOfStringsOrNone = _isListOfStringsOrNone() +isTransform = _isTransform() +isColor = _isColor() +isListOfColors = SequenceOf(isColor,'isListOfColors') +isColorOrNone = _isColorOrNone() +isShape = isValidChild = _isValidChild() +isNoneOrShape = isValidChildOrNone = _isValidChildOrNone() +isAnything = _isAnything() +isNothing = _isNothing() +isXYCoord = SequenceOf(isNumber,lo=2,hi=2,emptyOK=0) +isBoxAnchor = OneOf('nw','n','ne','w','c','e','sw','s','se', 'autox', 'autoy') +isNoneOrString = NoneOr(isString,'NoneOrString') +isNoneOrListOfNoneOrStrings=SequenceOf(isNoneOrString,'isNoneOrListOfNoneOrStrings',NoneOK=1) +isListOfNoneOrString=SequenceOf(isNoneOrString,'isListOfNoneOrString',NoneOK=0) +isNoneOrListOfNoneOrNumbers=SequenceOf(isNumberOrNone,'isNoneOrListOfNoneOrNumbers',NoneOK=1) +isCallable = _isCallable() +isNoneOrCallable = NoneOr(isCallable) +isStringOrCallable=EitherOr((isString,isCallable),'isStringOrCallable') +isStringOrCallableOrNone=NoneOr(isStringOrCallable,'isStringOrCallableNone') +isStringOrNone=NoneOr(isString,'isStringOrNone') +isNormalDate=_isNormalDate() +isNotSet=_isNotSet() diff --git a/.venv/lib/python3.13/site-packages/reportlab/lib/yaml.py b/.venv/lib/python3.13/site-packages/reportlab/lib/yaml.py new file mode 100644 index 0000000000000000000000000000000000000000..31a0ef0081ef14c826e4e46465eecbf9b8c5745e --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/lib/yaml.py @@ -0,0 +1,185 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/yaml.py +# parses "Yet Another Markup Language" into a list of tuples. +# Each tuple says what the data is e.g. +# ('Paragraph', 'Heading1', 'Why Reportlab Rules') +# and the pattern depends on type. +""" +.h1 Welcome to YAML! +YAML is "Yet Another Markup Language" - a markup language +which is easier to type in than XML, yet gives us a +reasonable selection of formats. + +The general rule is that if a line begins with a '.', +it requires special processing. Otherwise lines +are concatenated to paragraphs, and blank lines +separate paragraphs. + +If the line ".foo bar bletch" is encountered, +it immediately ends and writes out any current +paragraph. + +It then looks for a parser method called 'foo'; +if found, it is called with arguments (bar, bletch). + +If this is not found, it assumes that 'foo' is a +paragraph style, and the text for the first line +of the paragraph is 'bar bletch'. It would be +up to the formatter to decide whether on not 'foo' +was a valid paragraph. + +Special commands understood at present are: +dot image filename +- adds the image to the document +dot beginPre Code +- begins a Preformatted object in style 'Code' +dot endPre +- ends a preformatted object. +""" +__version__='3.3.0' + +import sys + +#modes: +PLAIN = 1 +PREFORMATTED = 2 + +BULLETCHAR = '\267' # assumes font Symbol, but works on all platforms + +class BaseParser: + """"Simplest possible parser with only the most basic options. + + This defines the line-handling abilities and basic mechanism. + The class YAMLParser includes capabilities for a fairly rich + story.""" + + def __init__(self): + self.reset() + + def reset(self): + self._lineNo = 0 + self._style = 'Normal' # the default + self._results = [] + self._buf = [] + self._mode = PLAIN + + def parseFile(self, filename): + #returns list of objects + data = open(filename, 'r').readlines() + + for line in data: + #strip trailing newlines + self.readLine(line[:-1]) + self.endPara() + return self._results + + def parseText(self, textBlock): + "Parses the a possible multi-line text block" + lines = textBlock.split('\n') + for line in lines: + self.readLine(line) + self.endPara() + return self._results + + def readLine(self, line): + #this is the inner loop + self._lineNo = self._lineNo + 1 + stripped = line.lstrip() + if len(stripped) == 0: + if self._mode == PLAIN: + self.endPara() + else: #preformatted, append it + self._buf.append(line) + elif line[0]=='.': + # we have a command of some kind + self.endPara() + words = stripped[1:].split() + cmd, args = words[0], words[1:] + + #is it a parser method? + if hasattr(self.__class__, cmd): + #this was very bad; any type error in the method was hidden + #we have to hack the traceback + try: + getattr(self,cmd)(*args) + except TypeError as err: + sys.stderr.write("Parser method: %s(*%s) %s at line %d\n" % (cmd, args, err, self._lineNo)) + raise + else: + # assume it is a paragraph style - + # becomes the formatter's problem + self.endPara() #end the last one + words = stripped.split(' ', 1) + assert len(words)==2, "Style %s but no data at line %d" % (words[0], self._lineNo) + (styletag, data) = words + self._style = styletag[1:] + self._buf.append(data) + else: + #we have data, add to para + self._buf.append(line) + + def endPara(self): + #ends the current paragraph, or preformatted block + + text = ' '.join(self._buf) + if text: + if self._mode == PREFORMATTED: + #item 3 is list of lines + self._results.append(('PREFORMATTED', self._style, + '\n'.join(self._buf))) + else: + self._results.append(('PARAGRAPH', self._style, text)) + self._buf = [] + self._style = 'Normal' + + def beginPre(self, stylename): + self._mode = PREFORMATTED + self._style = stylename + + def endPre(self): + self.endPara() + self._mode = PLAIN + + def image(self, filename): + self.endPara() + self._results.append(('IMAGE', filename)) + + +class Parser(BaseParser): + """This adds a basic set of "story" components compatible with HTML & PDF. + + Images, spaces""" + + def vSpace(self, points): + """Inserts a vertical spacer""" + self._results.append(('VSpace', points)) + + def pageBreak(self): + """Inserts a frame break""" + self._results.append(('PageBreak','blah')) # must be a tuple + + def custom(self, moduleName, funcName): + """Goes and gets the Python object and adds it to the story""" + self.endPara() + self._results.append(('Custom',moduleName, funcName)) + + def nextPageTemplate(self, templateName): + self._results.append(('NextPageTemplate',templateName)) + +def parseFile(filename): + p = Parser() + return p.parseFile(filename) + +def parseText(textBlock): + p = Parser() + return p.parseText(textBlock) + + +if __name__=='__main__': #NORUNTESTS + if len(sys.argv) != 2: + results = parseText(__doc__) + else: + results = parseFile(sys.argv[1]) + import pprint + pprint.pprint(results) diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/__init__.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2fb35f3c91c6369d7b5561bb0f2d27e39acdb95a --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/__init__.py @@ -0,0 +1,6 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/pdfbase/__init__.py +__version__='3.3.0' +__doc__="""Internal functionality for creating PDF files - not part of API +""" diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_can_cmap_data.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_can_cmap_data.py new file mode 100644 index 0000000000000000000000000000000000000000..93d4aa821900feec34d336ae58aa5667d60f151a --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_can_cmap_data.py @@ -0,0 +1,58 @@ +# +""" +This is a utility to 'can' the widths data for certain CID fonts. +Now we're using Unicode, we don't need 20 CMAP files for each Asian +language, nor the widths of the non-normal characters encoded in each +font. we just want a dictionary of the character widths in a given +font which are NOT 1000 ems wide, keyed on Unicode character (not CID). + +Running off CMAP files we get the following widths...:: + + >>> font = UnicodeCIDFont('HeiseiMin-W3') + >>> font.stringWidth(unicode(','), 10) + 2.5 + >>> font.stringWidth(unicode('m'), 10) + 7.7800000000000002 + >>> font.stringWidth(u'\u6771\u4EAC', 10) + 20.0 + >>> + +""" + +from reportlab.pdfbase._cidfontdata import defaultUnicodeEncodings +from reportlab.pdfbase.cidfonts import UnicodeCIDFont + + +def run(): + + buf = [] + buf.append('widthsByUnichar = {}') + for fontName, (language, encName) in defaultUnicodeEncodings.items(): + print('handling %s : %s : %s' % (fontName, language, encName)) + + #this does just about all of it for us, as all the info + #we need is present. + font = UnicodeCIDFont(fontName) + + widthsByCID = font.face._explicitWidths + cmap = font.encoding._cmap + nonStandardWidthsByUnichar = {} + for codePoint, cid in cmap.items(): + width = widthsByCID.get(cid, 1000) + if width != 1000: + nonStandardWidthsByUnichar[chr(codePoint)] = width + + + + print('created font width map (%d items). ' % len(nonStandardWidthsByUnichar)) + + buf.append('widthsByUnichar["%s"] = %s' % (fontName, repr(nonStandardWidthsByUnichar))) + + + src = '\n'.join(buf) + '\n' + open('canned_widths.py','w').write(src) + print('wrote canned_widths.py') + +if __name__=='__main__': + run() + diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_cidfontdata.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_cidfontdata.py new file mode 100644 index 0000000000000000000000000000000000000000..b04b2c48a47c53bee04cfeee596ca6dace1be9ad --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_cidfontdata.py @@ -0,0 +1,483 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/pdfbase/_cidfontdata.py +#$Header $ +__version__='3.3.0' +__doc__=""" +This defines additional static data to support CID fonts. + +Canned data is provided for the Japanese fonts supported by Adobe. We +can add Chinese, Korean and Vietnamese in due course. The data was +extracted by creating very simple postscript documents and running +through Distiller, then examining the resulting PDFs. + +Each font is described as a big nested dictionary. This lets us keep +code out of the module altogether and avoid circular dependencies. + +The encoding and font data are grouped by some standard 'language +prefixes':: + + chs = Chinese Simplified (mainland) + cht = Chinese Traditional (Taiwan) + kor = Korean + jpn = Japanese +""" + + +languages = ['jpn', 'kor', 'cht', 'chs'] + +#breaking down the lists let us check if something is present +#for a specific language +typeFaces_chs = ['STSong-Light'] # to do +typeFaces_cht = ['MSung-Light'] #, 'MHei-Medium'] # to do +typeFaces_jpn = ['HeiseiMin-W3', 'HeiseiKakuGo-W5'] +typeFaces_kor = ['HYSMyeongJo-Medium','HYGothic-Medium'] + +allowedTypeFaces = typeFaces_chs + typeFaces_cht + typeFaces_jpn + typeFaces_kor + + + + +encodings_jpn = [ + # official encoding names, comments taken verbatim from PDF Spec + '83pv-RKSJ-H', #Macintosh, JIS X 0208 character set with KanjiTalk6 + #extensions, Shift-JIS encoding, Script Manager code 1 + '90ms-RKSJ-H', #Microsoft Code Page 932 (lfCharSet 0x80), JIS X 0208 + #character set with NEC and IBM extensions + '90ms-RKSJ-V', #Vertical version of 90ms-RKSJ-H + '90msp-RKSJ-H', #Same as 90ms-RKSJ-H, but replaces half-width Latin + #characters with proportional forms + '90msp-RKSJ-V', #Vertical version of 90msp-RKSJ-H + '90pv-RKSJ-H', #Macintosh, JIS X 0208 character set with KanjiTalk7 + #extensions, Shift-JIS encoding, Script Manager code 1 + 'Add-RKSJ-H', #JIS X 0208 character set with Fujitsu FMR extensions, + #Shift-JIS encoding + 'Add-RKSJ-V', #Vertical version of Add-RKSJ-H + 'EUC-H', #JIS X 0208 character set, EUC-JP encoding + 'EUC-V', #Vertical version of EUC-H + 'Ext-RKSJ-H', #JIS C 6226 (JIS78) character set with NEC extensions, + #Shift-JIS encoding + 'Ext-RKSJ-V', #Vertical version of Ext-RKSJ-H + 'H', #JIS X 0208 character set, ISO-2022-JP encoding, + 'V', #Vertical version of H + 'UniJIS-UCS2-H', #Unicode (UCS-2) encoding for the Adobe-Japan1 character + #collection + 'UniJIS-UCS2-V', #Vertical version of UniJIS-UCS2-H + 'UniJIS-UCS2-HW-H', #Same as UniJIS-UCS2-H, but replaces proportional Latin + #characters with half-width forms + 'UniJIS-UCS2-HW-V' #Vertical version of UniJIS-UCS2-HW-H + ] +encodings_kor = [ + 'KSC-EUC-H', # KS X 1001:1992 character set, EUC-KR encoding + 'KSC-EUC-V', # Vertical version of KSC-EUC-H + 'KSCms-UHC-H', # Microsoft Code Page 949 (lfCharSet 0x81), KS X 1001:1992 + #character set plus 8,822 additional hangul, Unified Hangul + #Code (UHC) encoding + 'KSCms-UHC-V', #Vertical version of KSCms-UHC-H + 'KSCms-UHC-HW-H', #Same as KSCms-UHC-H, but replaces proportional Latin + # characters with halfwidth forms + 'KSCms-UHC-HW-V', #Vertical version of KSCms-UHC-HW-H + 'KSCpc-EUC-H', #Macintosh, KS X 1001:1992 character set with MacOS-KH + #extensions, Script Manager Code 3 + 'UniKS-UCS2-H', #Unicode (UCS-2) encoding for the Adobe-Korea1 character collection + 'UniKS-UCS2-V' #Vertical version of UniKS-UCS2-H + + ] + +encodings_chs = [ + + 'GB-EUC-H', # Microsoft Code Page 936 (lfCharSet 0x86), GB 2312-80 + # character set, EUC-CN encoding + 'GB-EUC-V', # Vertical version of GB-EUC-H + 'GBpc-EUC-H', # Macintosh, GB 2312-80 character set, EUC-CN encoding, + # Script Manager code 2 + 'GBpc-EUC-V', # Vertical version of GBpc-EUC-H + 'GBK-EUC-H', # Microsoft Code Page 936 (lfCharSet 0x86), GBK character + # set, GBK encoding + 'GBK-EUC-V', # Vertical version of GBK-EUC-V + 'UniGB-UCS2-H', # Unicode (UCS-2) encoding for the Adobe-GB1 + # character collection + 'UniGB-UCS2-V' # Vertical version of UniGB-UCS2-H. + ] + +encodings_cht = [ + 'B5pc-H', # Macintosh, Big Five character set, Big Five encoding, + # Script Manager code 2 + 'B5pc-V', # Vertical version of B5pc-H + 'ETen-B5-H', # Microsoft Code Page 950 (lfCharSet 0x88), Big Five + # character set with ETen extensions + 'ETen-B5-V', # Vertical version of ETen-B5-H + 'ETenms-B5-H', # Microsoft Code Page 950 (lfCharSet 0x88), Big Five + # character set with ETen extensions; this uses proportional + # forms for half-width Latin characters. + 'ETenms-B5-V', # Vertical version of ETenms-B5-H + 'CNS-EUC-H', # CNS 11643-1992 character set, EUC-TW encoding + 'CNS-EUC-V', # Vertical version of CNS-EUC-H + 'UniCNS-UCS2-H', # Unicode (UCS-2) encoding for the Adobe-CNS1 + # character collection + 'UniCNS-UCS2-V' # Vertical version of UniCNS-UCS2-H. + ] + +# the Identity encodings simply dump out all character +# in the font in the order they were defined. +allowedEncodings = (['Identity-H', 'Identity-V'] + + encodings_chs + + encodings_cht + + encodings_jpn + + encodings_kor + ) + +defaultUnicodeEncodings = { + #we ddefine a default Unicode encoding for each face name; + #this should be the most commonly used horizontal unicode encoding; + #also define a 3-letter language code. + 'HeiseiMin-W3': ('jpn','UniJIS-UCS2-H'), + 'HeiseiKakuGo-W5': ('jpn','UniJIS-UCS2-H'), + 'STSong-Light': ('chs', 'UniGB-UCS2-H'), + 'MSung-Light': ('cht', 'UniGB-UCS2-H'), + #'MHei-Medium': ('cht', 'UniGB-UCS2-H'), + 'HYSMyeongJo-Medium': ('kor', 'UniKS-UCS2-H'), + 'HYGothic-Medium': ('kor','UniKS-UCS2-H'), + } + +typeFaces_chs = ['STSong-Light'] # to do +typeFaces_cht = ['MSung-Light', 'MHei-Medium'] # to do +typeFaces_jpn = ['HeiseiMin-W3', 'HeiseiKakuGo-W5'] +typeFaces_kor = ['HYSMyeongJo-Medium','HYGothic-Medium'] + + +#declare separately those used for unicode +unicode_encodings = [enc for enc in allowedEncodings if 'UCS2' in enc] + + +CIDFontInfo = {} +#statically describe the fonts in Adobe's Japanese Language Packs +CIDFontInfo['HeiseiMin-W3'] = { + 'Type':'/Font', + 'Subtype':'/Type0', + 'Name': '/%(internalName)s' , #<-- the internal name + 'BaseFont': '/HeiseiMin-W3', + 'Encoding': '/%(encodings)s', + + #there could be several descendant fonts if it is an old-style + #type 0 compound font. For CID fonts there is just one. + 'DescendantFonts': [{ + 'Type':'/Font', + 'Subtype':'/CIDFontType0', + 'BaseFont':'/HeiseiMin-W3', + 'FontDescriptor': { + 'Type': '/FontDescriptor', + 'Ascent': 723, + 'CapHeight': 709, + 'Descent': -241, + 'Flags': 6, + 'FontBBox': (-123, -257, 1001, 910), + 'FontName': '/HeiseiMin-W3', + 'ItalicAngle': 0, + 'StemV': 69, + 'XHeight': 450#, +# 'Style': {'Panose': '<010502020400000000000000>'} + }, + 'CIDSystemInfo': { + 'Registry': '(Adobe)', + 'Ordering': '(Japan1)', + 'Supplement': 2 + }, + #default width is 1000 em units + 'DW': 1000, + #widths of any which are not the default. + 'W': [1, [250, 333, 408, 500], + 5, [500, 833, 778, 180, 333], + 10, [333, 500, 564, 250, 333, 250, 278, 500], + 18, 26, 500, 27, 28, 278, 29, 31, 564, + 32, [444, 921, 722, 667], + 36, [667, 722, 611, 556, 722], + 41, [722, 333, 389, 722, 611, 889, 722], + 48, [722, 556, 722, 667, 556, 611, 722], + 55, [722, 944, 722], + 58, [722, 611, 333, 500, 333, 469, 500, 333, + 444, 500, 444, 500, 444, 333, 500], + 73, [500, 278], + 75, [278, 500, 278, 778, 500], 80, 82, 500, + 83, [333, 389, 278, 500], + 87, [500, 722, 500], + 90, [500, 444, 480, 200, 480, 333], + 97, [278], 99, [200], 101, [333, 500], 103, [500, 167], + 107, [500], 109, [500, 333], 111, [333, 556], + 113, [556, 500], 117, [250], 119, [350, 333, 444], + 123, [500], 126, [444, 333], 128, 137, 333, + 138, [1000, 889, 276, 611, 722, 889, 310, 667, 278], + 147, [278, 500, 722, 500, 564, 760, 564, 760], + 157, 158, 300, 159, [500, 300, 750], 162, 163, 750, + 164, 169, 722, 170, [667, 611], 172, 174, 611, 175, + 178, 333, 179, 185, 722, 187, 191, 722, 192, + [556, 444], 194, 203, 444, 204, 207, 278, 208, + 214, 500, 216, 222, 500, + 223, [556, 722, 611, 500, 389, 980, 444], + 231, [500], 323, [500], 325, [500], + 327, 389, 500] +## 'W': ( +## # starting at character ID 1, next n characters have the widths given. +## 1, (277,305,500,668,668,906,727,305,445,445,508,668,305,379,305,539), +## # all Characters from ID 17 to 26 are 668 em units wide +## 17, 26, 668, +## 27, (305, 305, 668, 668, 668, 566, 871, 727, 637, 652, 699, 574, 555, +## 676, 687, 242, 492, 664, 582, 789, 707, 734, 582, 734, 605, 605, +## 641, 668, 727, 945, 609, 609, 574, 445, 668, 445, 668, 668, 590, +## 555, 609, 547, 602, 574, 391, 609, 582, 234, 277, 539, 234, 895, +## 582, 605, 602, 602, 387, 508, 441, 582, 562, 781, 531, 570, 555, +## 449, 246, 449, 668), +## # these must be half width katakana and the like. +## 231, 632, 500 +## ) + }]# end list of descendant fonts + } #end HeiseiMin-W3 + +CIDFontInfo['HeiseiKakuGo-W5'] = {'Type':'/Font', + 'Subtype':'/Type0', + 'Name': '/%(internalName)s', #<-- the internal name + 'BaseFont': '/HeiseiKakuGo-W5', + 'Encoding': '/%(encodings)s', + 'DescendantFonts': [{'Type':'/Font', + 'Subtype':'/CIDFontType0', + 'BaseFont':'/HeiseiKakuGo-W5', + 'FontDescriptor': { + 'Type': '/FontDescriptor', + 'Ascent': 752, + 'CapHeight': 737, + 'Descent': -221, + 'Flags': 4, + 'FontBBox': [-92, -250, 1010, 922], + 'FontName': '/HeiseKakuGo-W5', + 'ItalicAngle': 0, + 'StemH': 0, + 'StemV': 114, + 'XHeight': 553, +## 'Style': {'Panose': '<0801020b0600000000000000>'} + }, + 'CIDSystemInfo': { + 'Registry': '(Adobe)', + 'Ordering': '(Japan1)', + 'Supplement': 2 + }, + 'DW': 1000, + 'W': ( + 1, (277,305,500,668,668,906,727,305,445,445,508,668,305,379,305,539), + 17, 26, 668, + 27, (305, 305, 668, 668, 668, 566, 871, 727, 637, 652, 699, 574, 555, + 676, 687, 242, 492, 664, 582, 789, 707, 734, 582, 734, 605, 605, + 641, 668, 727, 945, 609, 609, 574, 445, 668, 445, 668, 668, 590, + 555, 609, 547, 602, 574, 391, 609, 582, 234, 277, 539, 234, 895, + 582, 605, 602, 602, 387, 508, 441, 582, 562, 781, 531, 570, 555, + 449, 246, 449, 668), + 231, 632, 500 + ) + }] # end descendant fonts + } + +CIDFontInfo['HYGothic-Medium'] = {'Type':'/Font', + 'Subtype':'/Type0', + 'Name': '/%(internalName)s', #<-- the internal name + 'BaseFont': '/' + 'HYGothic-Medium', + 'Encoding': '/%(encodings)s', + 'DescendantFonts': [{'Type':'/Font', + 'Subtype':'/CIDFontType0', + 'BaseFont':'/'+'HYGothic-Medium', + 'FontDescriptor': { + 'Type': '/FontDescriptor', + 'Ascent': 752, + 'AvgWidth': -271, + 'CapHeight': 737, + 'Descent': -142, + 'Flags': 6, + 'FontBBox': [-6, -145, 1003, 880], + 'FontName': '/'+'HYSMyeongJo-Medium', + 'ItalicAngle': 0, + 'Leading': 148, + 'MaxWidth': 1000, + 'MissingWidth': 500, + 'StemH': 0, + 'StemV': 58, + 'XHeight': 553 + }, + 'CIDSystemInfo': { + 'Registry': '(Adobe)', + 'Ordering': '(Korea1)', + 'Supplement': 1 + }, + 'DW': 1000, + 'W': (1, 94, 500) + }] # end descendant fonts + } + +CIDFontInfo['HYSMyeongJo-Medium'] = {'Type':'/Font', + 'Subtype':'/Type0', + 'Name': '/%(internalName)s', #<-- the internal name + 'BaseFont': '/' + 'HYSMyeongJo-Medium', + 'Encoding': '/%(encodings)s', + 'DescendantFonts': [{'Type':'/Font', + 'Subtype':'/CIDFontType2', + 'BaseFont':'/'+'HYSMyeongJo-Medium', + 'FontDescriptor': { + 'Type': '/FontDescriptor', + 'Ascent': 752, + 'AvgWidth': 500, + 'CapHeight': 737, + 'Descent': -271, + 'Flags': 6, + 'FontBBox': [0, -148, 1001, 880], + 'FontName': '/'+'HYSMyeongJo-Medium', + 'ItalicAngle': 0, + 'Leading': 148, + 'MaxWidth': 1000, + 'MissingWidth': 500, + 'StemH': 91, + 'StemV': 58, + 'XHeight': 553 + }, + 'CIDSystemInfo': { + 'Registry': '(Adobe)', + 'Ordering': '(Korea1)', + 'Supplement': 1 + }, + 'DW': 1000, + 'W': [1, [333, 416], + 3, [416, 833, 625, 916, 833, 250, 500], + 10, 11, 500, + 12, [833, 291, 833, 291, 375, 625], + 18, 26, 625, 27, 28, 333, 29, 30, 833, + 31, [916, 500, 1000, 791, 708], + 36, [708, 750, 708, 666, 750, 791, 375, + 500, 791, 666, 916, 791, 750, 666, + 750, 708, 666, 791], + 54, [791, 750, 1000, 708], + 58, [708, 666, 500, 375, 500], + 63, 64, 500, + 65, [333, 541, 583, 541, 583], + 70, [583, 375, 583], + 73, [583, 291, 333, 583, 291, 875, 583], + 80, 82, 583, + 83, [458, 541, 375, 583], + 87, [583, 833, 625], + 90, [625, 500, 583], 93, 94, 583, + 95, [750] + ] + }] # end descendant fonts + } + +#WARNING - not checked, just copied Korean to get some output + +CIDFontInfo['STSong-Light'] = {'Type':'/Font', + 'Subtype':'/Type0', + 'Name': '/%(internalName)s', #<-- the internal name + 'BaseFont': '/' + 'STSong-Light', + 'Encoding': '/%(encodings)s', + 'DescendantFonts': [{'Type':'/Font', + 'Subtype':'/CIDFontType0', + 'BaseFont':'/'+'STSong-Light', + 'FontDescriptor': { + 'Type': '/FontDescriptor', + 'Ascent': 752, + 'CapHeight': 737, + 'Descent': -271, + 'Flags': 6, + 'FontBBox': [-25, -254, 1000, 880], + 'FontName': '/'+'STSongStd-Light', + 'ItalicAngle': 0, + 'Leading': 148, + 'MaxWidth': 1000, + 'MissingWidth': 500, + 'StemH': 91, + 'StemV': 58, + 'XHeight': 553 + }, + 'CIDSystemInfo': { + 'Registry': '(Adobe)', + 'Ordering': '(GB1)', + 'Supplement': 0 + }, + 'DW': 1000, + 'W': [1, [207, 270, 342, 467, 462, 797, 710, 239, 374], + 10, [374, 423, 605, 238, 375, 238, 334, 462], + 18, 26, 462, 27, 28, 238, 29, 31, 605, + 32, [344, 748, 684, 560, 695, 739, 563, 511, 729, + 793, 318, 312, 666, 526, 896, 758, 772, 544, + 772, 628, 465, 607, 753, 711, 972, 647, 620, + 607, 374, 333, 374, 606, 500, 239, 417, 503, + 427, 529, 415, 264, 444, 518, 241, 230, 495, + 228, 793, 527, 524], + 81, [524, 504, 338, 336, 277, 517, 450, 652, 466, + 452, 407, 370, 258, 370, 605] + ] + }] # end descendant fonts + } +CIDFontInfo['MSung-Light'] = {'Type':'/Font', + 'Subtype':'/Type0', + 'Name': '/%(internalName)s', #<-- the internal name + 'BaseFont': '/' + 'MSung-Light', + 'Encoding': '/%(encodings)s', + 'DescendantFonts': [{'Type':'/Font', + 'Subtype':'/CIDFontType0', + 'BaseFont':'/'+'MSung-Light', + 'FontDescriptor': { + 'Type': '/FontDescriptor', + 'Ascent': 752, + 'CapHeight': 737, + 'Descent': -271, + 'Flags': 6, + 'FontBBox': [-160, -249, 1015, 888], + 'FontName': '/'+'MSung-Light', + 'ItalicAngle': 0, + 'Leading': 148, + 'MaxWidth': 1000, + 'MissingWidth': 500, + 'StemH': 45, + 'StemV': 58, + 'XHeight': 553 + }, + 'CIDSystemInfo': { + 'Registry': '(Adobe)', + 'Ordering': '(CNS1)', + 'Supplement': 1 + }, + 'DW': 1000, + 'W': [1, 2, 250, 3, [408, 668, 490, 875, 698, 250, 240], + 10, [240, 417, 667, 250, 313, 250, 520, 500], + 18, 26, 500, 27, 28, 250, 29, 31, 667, + 32, [396, 921, 677, 615, 719, 760, 625, 552, 771, + 802, 354], + 43, [354, 781, 604, 927, 750, 823, 563, 823, 729, + 542, 698, 771, 729, 948, 771, 677, 635, 344, + 520, 344, 469, 500, 250, 469, 521, 427, 521, + 438, 271, 469, 531, 250], + 75, [250, 458, 240, 802, 531, 500, 521], + 82, [521, 365, 333, 292, 521, 458, 677, 479, 458, + 427, 480, 496, 480, 667]] + + }] # end descendant fonts + } + + +#this data was derived from the above width information and removes all dependency on CMAP files as long as we only use the unicode fonts. +widthsByUnichar = {} +widthsByUnichar["MSung-Light"] = {u' ': 250, u'$': 490, u'(': 240, u',': 250, u'0': 500, u'4': 500, u'8': 500, u'<': 667, u'@': 921, u'D': 760, u'H': 802, u'L': 604, u'P': 563, u'T': 698, u'X': 771, u'\\': 520, u'`': 250, u'd': 521, u'h': 531, u'l': 240, u'p': 521, u't': 292, u'x': 479, u'|': 496, u'#': 668, u"'": 250, u'+': 667, u'/': 520, u'3': 500, u'7': 500, u';': 250, u'?': 396, u'C': 719, u'G': 771, u'K': 781, u'O': 823, u'S': 542, u'W': 948, u'[': 344, u'_': 500, u'c': 427, u'g': 469, u'k': 458, u'o': 500, u's': 333, u'w': 677, u'{': 480, u'"': 408, u'&': 698, u'*': 417, u'.': 250, u'2': 500, u'6': 500, u':': 250, u'>': 667, u'B': 615, u'F': 552, u'J': 354, u'N': 750, u'R': 729, u'V': 729, u'Z': 635, u'^': 469, u'b': 521, u'f': 271, u'j': 250, u'n': 531, u'r': 365, u'v': 458, u'z': 427, u'~': 667, u'!': 250, u'%': 875, u')': 240, u'-': 313, u'1': 500, u'5': 500, u'9': 500, u'=': 667, u'A': 677, u'E': 625, u'I': 354, u'M': 927, u'Q': 823, u'U': 771, u'Y': 677, u']': 344, u'a': 469, u'e': 438, u'i': 250, u'm': 802, u'q': 521, u'u': 521, u'y': 458, u'}': 480} +widthsByUnichar["HeiseiKakuGo-W5"] = {u'\uff81': 500, u'\uff85': 500, u'\uff89': 500, u'\uff8d': 500, u'\uff91': 500, u'\uff95': 500, u'\uff99': 500, u'\uff9d': 500, u' ': 277, u'$': 668, u'(': 445, u',': 305, u'0': 668, u'\u0332': 668, u'4': 668, u'8': 668, u'<': 668, u'@': 871, u'D': 699, u'H': 687, u'L': 582, u'P': 582, u'T': 641, u'X': 609, u'`': 590, u'\uff62': 500, u'd': 602, u'\uff66': 500, u'h': 582, u'\uff6a': 500, u'l': 234, u'\uff6e': 500, u'p': 602, u'\uff72': 500, u't': 441, u'\uff76': 500, u'x': 531, u'\uff7a': 500, u'|': 246, u'\uff7e': 500, u'\uff82': 500, u'\uff86': 500, u'\uff8a': 500, u'\uff8e': 500, u'\uff92': 500, u'\uff96': 500, u'\uff9a': 500, u'\uff9e': 500, u'#': 668, u"'": 305, u'+': 668, u'/': 539, u'3': 668, u'7': 668, u';': 305, u'?': 566, u'C': 652, u'G': 676, u'K': 664, u'O': 734, u'S': 605, u'W': 945, u'[': 445, u'_': 668, u'\uff61': 500, u'c': 547, u'\uff65': 500, u'g': 609, u'\uff69': 500, u'k': 539, u'\uff6d': 500, u'o': 605, u'\uff71': 500, u's': 508, u'\uff75': 500, u'w': 781, u'\uff79': 500, u'{': 449, u'\uff7d': 500, u'\u0300': 590, u'\uff83': 500, u'\u2002': 500, u'\uff87': 500, u'\uff8b': 500, u'\uff8f': 500, u'\uff93': 500, u'\uff97': 500, u'\uff9b': 500, u'\uff9f': 500, u'"': 500, u'\xa5': 668, u'&': 727, u'*': 508, u'.': 305, u'2': 668, u'6': 668, u':': 305, u'>': 668, u'B': 637, u'F': 555, u'J': 492, u'N': 707, u'\u203e': 500, u'R': 605, u'V': 727, u'Z': 574, u'^': 668, u'b': 609, u'\uff64': 500, u'f': 391, u'\uff68': 500, u'j': 277, u'\uff6c': 500, u'n': 582, u'\uff70': 500, u'r': 387, u'\uff74': 500, u'v': 562, u'\uff78': 500, u'z': 555, u'\uff7c': 500, u'~': 668, u'\uff80': 500, u'\u0303': 668, u'\uff84': 500, u'\uff88': 500, u'\uff8c': 500, u'\u2011': 379, u'\uff90': 500, u'\uff94': 500, u'\uff98': 500, u'\uff9c': 500, u'!': 305, u'%': 906, u')': 445, u'-': 379, u'1': 668, u'5': 668, u'9': 668, u'=': 668, u'A': 727, u'E': 574, u'I': 242, u'M': 789, u'Q': 734, u'U': 668, u'Y': 609, u']': 445, u'a': 555, u'\uff63': 500, u'e': 574, u'\uff67': 500, u'i': 234, u'\uffe8': 500, u'\uff6b': 500, u'm': 895, u'\uff6f': 500, u'q': 602, u'\uff73': 500, u'u': 582, u'\uff77': 500, u'y': 570, u'\uff7b': 500, u'}': 449, u'\uff7f': 500} +widthsByUnichar["HYSMyeongJo-Medium"] = {u' ': 333, u'$': 625, u'(': 500, u',': 291, u'0': 625, u'4': 625, u'8': 625, u'<': 833, u'D': 750, u'H': 791, u'L': 666, u'P': 666, u'T': 791, u'X': 708, u'\\': 375, u'`': 333, u'd': 583, u'h': 583, u'l': 291, u'p': 583, u't': 375, u'x': 625, u'|': 583, u'#': 833, u"'": 250, u'+': 833, u'/': 375, u'3': 625, u'7': 625, u';': 333, u'?': 500, u'C': 708, u'G': 750, u'K': 791, u'O': 750, u'S': 666, u'[': 500, u'_': 500, u'c': 541, u'g': 583, u'k': 583, u'o': 583, u's': 541, u'w': 833, u'{': 583, u'"': 416, u'&': 833, u'*': 500, u'.': 291, u'2': 625, u'6': 625, u':': 333, u'>': 916, u'B': 708, u'F': 666, u'J': 500, u'N': 791, u'R': 708, u'V': 750, u'Z': 666, u'^': 500, u'b': 583, u'f': 375, u'j': 333, u'n': 583, u'r': 458, u'v': 583, u'z': 500, u'~': 750, u'!': 416, u'%': 916, u')': 500, u'-': 833, u'1': 625, u'5': 625, u'9': 625, u'=': 833, u'A': 791, u'E': 708, u'I': 375, u'M': 916, u'Q': 750, u'U': 791, u'Y': 708, u']': 500, u'a': 541, u'e': 583, u'i': 291, u'm': 875, u'q': 583, u'u': 583, u'y': 625, u'}': 583} +widthsByUnichar["STSong-Light"] = {u' ': 207, u'$': 462, u'(': 374, u',': 238, u'0': 462, u'4': 462, u'8': 462, u'<': 605, u'@': 748, u'D': 739, u'H': 793, u'L': 526, u'P': 544, u'T': 607, u'X': 647, u'\\': 333, u'`': 239, u'd': 529, u'h': 518, u'l': 228, u'p': 524, u't': 277, u'x': 466, u'|': 258, u'#': 467, u"'": 239, u'+': 605, u'/': 334, u'3': 462, u'7': 462, u';': 238, u'?': 344, u'C': 695, u'G': 729, u'K': 666, u'O': 772, u'S': 465, u'W': 972, u'[': 374, u'_': 500, u'c': 427, u'g': 444, u'k': 495, u'o': 524, u's': 336, u'w': 652, u'{': 370, u'"': 342, u'&': 710, u'*': 423, u'.': 238, u'2': 462, u'6': 462, u':': 238, u'>': 605, u'B': 560, u'F': 511, u'J': 312, u'N': 758, u'R': 628, u'V': 711, u'Z': 607, u'^': 606, u'b': 503, u'f': 264, u'j': 230, u'n': 527, u'r': 338, u'v': 450, u'z': 407, u'~': 605, u'!': 270, u'%': 797, u')': 374, u'-': 375, u'1': 462, u'5': 462, u'9': 462, u'=': 605, u'A': 684, u'E': 563, u'I': 318, u'M': 896, u'Q': 772, u'U': 753, u'Y': 620, u']': 374, u'a': 417, u'e': 415, u'i': 241, u'm': 793, u'q': 504, u'u': 517, u'y': 452, u'}': 370} +widthsByUnichar["HeiseiMin-W3"] = {u'\uff81': 500, u'\u0302': 333, u'\uff85': 500, u'\u0306': 333, u'\uff89': 500, u'\u030a': 333, u'\uff8d': 500, u'\uff91': 500, u'\ufb02': 556, u'\uff95': 500, u'\uff99': 500, u'\uff9d': 500, u' ': 250, u'\xa3': 500, u'\u2122': 980, u'$': 500, u'(': 333, u'\xab': 500, u',': 250, u'\xaf': 333, u'0': 500, u'\xb3': 300, u'\u0332': 500, u'4': 500, u'\xb7': 250, u'8': 500, u'\xbb': 500, u'<': 564, u'\xbf': 444, u'@': 921, u'\xc3': 722, u'\u0142': 278, u'D': 722, u'\xc7': 667, u'H': 722, u'\xcb': 611, u'L': 611, u'\xcf': 333, u'P': 556, u'\xd3': 722, u'\u0152': 889, u'T': 611, u'X': 722, u'\xdb': 722, u'\\': 278, u'\xdf': 500, u'\uff64': 500, u'`': 333, u'\xe3': 444, u'\uff62': 500, u'd': 500, u'\xe7': 444, u'\uff66': 500, u'h': 500, u'\xeb': 444, u'\uff6a': 500, u'l': 278, u'\xef': 278, u'\uff6e': 500, u'p': 500, u'\xf3': 500, u'\uff72': 500, u't': 278, u'\uff76': 500, u'x': 500, u'\xfb': 500, u'\uff7a': 500, u'|': 200, u'\xff': 500, u'\u017e': 444, u'\u0301': 333, u'\uff82': 500, u'\u0305': 500, u'\uff86': 500, u'\uff8a': 500, u'\uff8e': 500, u'\u2013': 500, u'\uff92': 500, u'\uff96': 500, u'\uff9a': 500, u'\uff9e': 500, u'#': 500, u'\xa4': 500, u"'": 180, u'\u203a': 333, u'+': 564, u'\xac': 564, u'/': 278, u'\u0131': 278, u'3': 500, u'7': 500, u'\xb8': 333, u';': 278, u'\xbc': 750, u'?': 444, u'\u0141': 611, u'\xc0': 722, u'C': 667, u'\xc4': 722, u'G': 722, u'\xc8': 611, u'K': 722, u'\xcc': 333, u'O': 722, u'\xd0': 722, u'S': 556, u'\u2022': 350, u'\xd4': 722, u'W': 944, u'\uff78': 500, u'\xd8': 722, u'[': 333, u'\xdc': 722, u'_': 500, u'\u0161': 389, u'\xe0': 444, u'c': 444, u'\uff65': 500, u'\xe4': 444, u'g': 500, u'\uff69': 500, u'\xe8': 444, u'k': 500, u'\uff6d': 500, u'\xec': 278, u'o': 500, u'\uff71': 500, u'\xf0': 500, u's': 389, u'\uff75': 500, u'\xf4': 500, u'w': 722, u'\uff79': 500, u'\xf8': 500, u'{': 480, u'\uff7e': 500, u'\u017d': 611, u'\xfc': 500, u'\u0300': 333, u'\uff83': 500, u'\u2002': 500, u'\u0304': 333, u'\uff87': 500, u'\u0308': 333, u'\uff8b': 500, u'\u030c': 333, u'\uff8f': 500, u'\uff93': 500, u'\u2012': 500, u'\uff97': 500, u'\uff9b': 500, u'\u201a': 333, u'\uff9f': 500, u'\u201e': 444, u'\xa1': 333, u'"': 408, u'\xa5': 500, u'&': 778, u'\xa9': 760, u'\u0328': 333, u'*': 500, u'\xad': 564, u'.': 250, u'\uffe8': 500, u'2': 500, u'\xb5': 500, u'6': 500, u'\xb9': 300, u':': 278, u'\xbd': 750, u'>': 564, u'\xc1': 722, u'\uff61': 500, u'B': 667, u'\xc5': 722, u'F': 556, u'\xc9': 611, u'J': 389, u'\xcd': 333, u'N': 722, u'\xd1': 722, u'\u203e': 500, u'R': 667, u'\xd5': 722, u'V': 722, u'\xd9': 722, u'Z': 611, u'\xdd': 722, u'^': 469, u'\xe1': 444, u'\u0160': 556, u'b': 500, u'\xe5': 444, u'\u2039': 333, u'f': 333, u'\xe9': 444, u'\uff68': 500, u'j': 278, u'\xed': 278, u'\uff6c': 500, u'n': 500, u'\xf1': 500, u'\uff70': 500, u'r': 333, u'\xf5': 500, u'\uff74': 500, u'v': 500, u'\xf9': 500, u'\u0178': 722, u'z': 444, u'\xfd': 500, u'\uff7c': 500, u'~': 333, u'\uff80': 500, u'\u0303': 333, u'\uff84': 500, u'\u0307': 333, u'\uff88': 500, u'\u030b': 333, u'\uff8c': 500, u'\u2011': 333, u'\uff90': 500, u'\uff94': 500, u'\uff98': 500, u'\uff9c': 500, u'\u2044': 167, u'!': 333, u'\xa2': 500, u'%': 833, u'\u0327': 333, u'\xa6': 200, u')': 333, u'\xaa': 276, u'-': 333, u'\xae': 760, u'1': 500, u'\xb2': 300, u'5': 500, u'9': 500, u'\xba': 310, u'=': 564, u'\xbe': 750, u'A': 722, u'\u01c0': 200, u'\xc2': 722, u'E': 611, u'\xc6': 889, u'I': 333, u'\xca': 611, u'M': 889, u'\xce': 333, u'Q': 722, u'\u0153': 722, u'\xd2': 722, u'U': 722, u'\xd6': 722, u'Y': 722, u'\ufb01': 556, u'\xda': 722, u']': 333, u'\xde': 556, u'a': 444, u'\uff63': 500, u'\xe2': 444, u'e': 444, u'\uff67': 500, u'\xe6': 667, u'i': 278, u'\uff7d': 500, u'\uff6b': 500, u'\xea': 444, u'm': 778, u'\uff6f': 500, u'\xee': 278, u'q': 500, u'\uff73': 500, u'\xf2': 500, u'u': 500, u'\uff77': 500, u'\xf6': 500, u'y': 500, u'\uff7b': 500, u'\xfa': 500, u'}': 480, u'\uff7f': 500, u'\xfe': 500} +widthsByUnichar["HYGothic-Medium"] = {u' ': 500, u'$': 500, u'(': 500, u',': 500, u'0': 500, u'4': 500, u'8': 500, u'<': 500, u'@': 500, u'D': 500, u'H': 500, u'L': 500, u'P': 500, u'T': 500, u'X': 500, u'\\': 500, u'`': 500, u'd': 500, u'h': 500, u'l': 500, u'p': 500, u't': 500, u'x': 500, u'|': 500, u'#': 500, u"'": 500, u'+': 500, u'/': 500, u'3': 500, u'7': 500, u';': 500, u'?': 500, u'C': 500, u'G': 500, u'K': 500, u'O': 500, u'S': 500, u'W': 500, u'[': 500, u'_': 500, u'c': 500, u'g': 500, u'k': 500, u'o': 500, u's': 500, u'w': 500, u'{': 500, u'"': 500, u'&': 500, u'*': 500, u'.': 500, u'2': 500, u'6': 500, u':': 500, u'>': 500, u'B': 500, u'F': 500, u'J': 500, u'N': 500, u'R': 500, u'V': 500, u'Z': 500, u'^': 500, u'b': 500, u'f': 500, u'j': 500, u'n': 500, u'r': 500, u'v': 500, u'z': 500, u'!': 500, u'%': 500, u')': 500, u'-': 500, u'1': 500, u'5': 500, u'9': 500, u'=': 500, u'A': 500, u'E': 500, u'I': 500, u'M': 500, u'Q': 500, u'U': 500, u'Y': 500, u']': 500, u'a': 500, u'e': 500, u'i': 500, u'm': 500, u'q': 500, u'u': 500, u'y': 500, u'}': 500} + + +#shift-jis saying 'This is Heisei-Minchou' +message1 = '\202\261\202\352\202\315\225\275\220\254\226\276\222\251\202\305\202\267\201B' +message2 = '\202\261\202\352\202\315\225\275\220\254\212p\203S\203V\203b\203N\202\305\202\267\201B' + +##def pswidths(text): +## words = text.split() +## out = [] +## for word in words: +## if word == '[': +## out.append(word) +## else: +## out.append(word + ',') +## return eval(''.join(out),{}) diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata.py new file mode 100644 index 0000000000000000000000000000000000000000..037412d1f2d21610b777baa0f7aa9bfff4b70e91 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata.py @@ -0,0 +1,255 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/pdfbase/_fontdata.py +#$Header $ +__version__='3.3.0' +__doc__="""Database of font related things + + - standardFonts - tuple of the 14 standard string font names + - standardEncodings - tuple of the known standard font names + - encodings - a mapping object from standard encoding names (and minor variants) + to the encoding vectors ie the tuple of string glyph names + - widthsByFontGlyph - fontname x glyphname --> width of glyph + - widthVectorsByFont - fontName -> vector of widths + + This module defines a static, large data structure. At the request + of the Jython project, we have split this off into separate modules + as Jython cannot handle more than 64k of bytecode in the 'top level' + code of a Python module. +""" +import os, sys + +# mapping of name to width vector, starts empty until fonts are added +# e.g. widths['Courier'] = [...600,600,600,...] +widthVectorsByFont = {} +fontsByName = {} +fontsByBaseEnc = {} +# this is a list of the standard 14 font names in Acrobat Reader +standardFonts = ( + 'Courier', 'Courier-Bold', 'Courier-Oblique', 'Courier-BoldOblique', + 'Helvetica', 'Helvetica-Bold', 'Helvetica-Oblique', 'Helvetica-BoldOblique', + 'Times-Roman', 'Times-Bold', 'Times-Italic', 'Times-BoldItalic', + 'Symbol','ZapfDingbats') + +standardFontAttributes = { + #family, bold, italic defined for basic ones + 'Courier':('Courier',0,0), + 'Courier-Bold':('Courier',1,0), + 'Courier-Oblique':('Courier',0,1), + 'Courier-BoldOblique':('Courier',1,1), + + 'Helvetica':('Helvetica',0,0), + 'Helvetica-Bold':('Helvetica',1,0), + 'Helvetica-Oblique':('Helvetica',0,1), + 'Helvetica-BoldOblique':('Helvetica',1,1), + + 'Times-Roman':('Times-Roman',0,0), + 'Times-Bold':('Times-Roman',1,0), + 'Times-Italic':('Times-Roman',0,1), + 'Times-BoldItalic':('Times-Roman',1,1), + + 'Symbol':('Symbol',0,0), + 'ZapfDingbats':('ZapfDingbats',0,0) + + } + +#this maps fontnames to the equivalent filename root. +_font2fnrMapWin32 = { + 'symbol': 'sy______', + 'zapfdingbats': 'zd______', + 'helvetica': '_a______', + 'helvetica-bold': '_ab_____', + 'helvetica-boldoblique': '_abi____', + 'helvetica-oblique': '_ai_____', + 'times-bold': '_eb_____', + 'times-bolditalic': '_ebi____', + 'times-italic': '_ei_____', + 'times-roman': '_er_____', + 'courier-bold': 'cob_____', + 'courier-boldoblique': 'cobo____', + 'courier': 'com_____', + 'courier-oblique': 'coo_____', + } +if sys.platform in ('linux2',): + _font2fnrMapLinux2 ={ + 'symbol': 'Symbol', + 'zapfdingbats': 'ZapfDingbats', + 'helvetica': 'Arial', + 'helvetica-bold': 'Arial-Bold', + 'helvetica-boldoblique': 'Arial-BoldItalic', + 'helvetica-oblique': 'Arial-Italic', + 'times-bold': 'TimesNewRoman-Bold', + 'times-bolditalic':'TimesNewRoman-BoldItalic', + 'times-italic': 'TimesNewRoman-Italic', + 'times-roman': 'TimesNewRoman', + 'courier-bold': 'Courier-Bold', + 'courier-boldoblique': 'Courier-BoldOblique', + 'courier': 'Courier', + 'courier-oblique': 'Courier-Oblique', + } + _font2fnrMap = _font2fnrMapLinux2 + for k, v in _font2fnrMap.items(): + if k in _font2fnrMapWin32.keys(): + _font2fnrMapWin32[v.lower()] = _font2fnrMapWin32[k] + del k, v +else: + _font2fnrMap = _font2fnrMapWin32 + +def _findFNR(fontName): + return _font2fnrMap[fontName.lower()] + +from reportlab.rl_config import T1SearchPath +from reportlab.lib.utils import rl_isfile +def _searchT1Dirs(n,rl_isfile=rl_isfile,T1SearchPath=T1SearchPath): + assert T1SearchPath!=[], "No Type-1 font search path" + for d in T1SearchPath: + f = os.path.join(d,n) + if rl_isfile(f): return f + return None +del T1SearchPath, rl_isfile + +def findT1File(fontName,ext='.pfb'): + if sys.platform in ('linux2',) and ext=='.pfb': + try: + f = _searchT1Dirs(_findFNR(fontName)) + if f: return f + except: + pass + + try: + f = _searchT1Dirs(_font2fnrMapWin32[fontName.lower()]+ext) + if f: return f + except: + pass + + return _searchT1Dirs(_findFNR(fontName)+ext) + +# this lists the predefined font encodings - WinAnsi and MacRoman. We have +# not added MacExpert - it's possible, but would complicate life and nobody +# is asking. StandardEncoding means something special. +standardEncodings = ('WinAnsiEncoding','MacRomanEncoding','StandardEncoding','SymbolEncoding','ZapfDingbatsEncoding','PDFDocEncoding', 'MacExpertEncoding') + +#this is the global mapping of standard encodings to name vectors +class _Name2StandardEncodingMap(dict): + '''Trivial fake dictionary with some [] magic''' + _XMap = {'winansi':'WinAnsiEncoding','macroman': 'MacRomanEncoding','standard':'StandardEncoding','symbol':'SymbolEncoding', 'zapfdingbats':'ZapfDingbatsEncoding','pdfdoc':'PDFDocEncoding', 'macexpert':'MacExpertEncoding'} + def __setitem__(self,x,v): + y = x.lower() + if y[-8:]=='encoding': y = y[:-8] + y = self._XMap[y] + if y in self: raise IndexError('Encoding %s is already set' % y) + dict.__setitem__(self,y,v) + + def __getitem__(self,x): + y = x.lower() + if y[-8:]=='encoding': y = y[:-8] + y = self._XMap[y] + return dict.__getitem__(self,y) + +encodings = _Name2StandardEncodingMap() + +#due to compiled method size limits in Jython, +#we pull these in from separate modules to keep this module +#well under 64k. We might well be able to ditch many of +#these anyway now we run on Unicode. + +from reportlab.pdfbase._fontdata_enc_winansi import WinAnsiEncoding +from reportlab.pdfbase._fontdata_enc_macroman import MacRomanEncoding +from reportlab.pdfbase._fontdata_enc_standard import StandardEncoding +from reportlab.pdfbase._fontdata_enc_symbol import SymbolEncoding +from reportlab.pdfbase._fontdata_enc_zapfdingbats import ZapfDingbatsEncoding +from reportlab.pdfbase._fontdata_enc_pdfdoc import PDFDocEncoding +from reportlab.pdfbase._fontdata_enc_macexpert import MacExpertEncoding +encodings.update({ + 'WinAnsiEncoding': WinAnsiEncoding, + 'MacRomanEncoding': MacRomanEncoding, + 'StandardEncoding': StandardEncoding, + 'SymbolEncoding': SymbolEncoding, + 'ZapfDingbatsEncoding': ZapfDingbatsEncoding, + 'PDFDocEncoding': PDFDocEncoding, + 'MacExpertEncoding': MacExpertEncoding, +}) + +ascent_descent = { + 'Courier': (629, -157), + 'Courier-Bold': (626, -142), + 'Courier-BoldOblique': (626, -142), + 'Courier-Oblique': (629, -157), + 'Helvetica': (718, -207), + 'Helvetica-Bold': (718, -207), + 'Helvetica-BoldOblique': (718, -207), + 'Helvetica-Oblique': (718, -207), + 'Times-Roman': (683, -217), + 'Times-Bold': (676, -205), + 'Times-BoldItalic': (699, -205), + 'Times-Italic': (683, -205), + 'Symbol': (0, 0), + 'ZapfDingbats': (0, 0) + } + +# ditto about 64k limit - profusion of external files +import reportlab.pdfbase._fontdata_widths_courier +import reportlab.pdfbase._fontdata_widths_courierbold +import reportlab.pdfbase._fontdata_widths_courieroblique +import reportlab.pdfbase._fontdata_widths_courierboldoblique +import reportlab.pdfbase._fontdata_widths_helvetica +import reportlab.pdfbase._fontdata_widths_helveticabold +import reportlab.pdfbase._fontdata_widths_helveticaoblique +import reportlab.pdfbase._fontdata_widths_helveticaboldoblique +import reportlab.pdfbase._fontdata_widths_timesroman +import reportlab.pdfbase._fontdata_widths_timesbold +import reportlab.pdfbase._fontdata_widths_timesitalic +import reportlab.pdfbase._fontdata_widths_timesbolditalic +import reportlab.pdfbase._fontdata_widths_symbol +import reportlab.pdfbase._fontdata_widths_zapfdingbats +widthsByFontGlyph = { + 'Courier': + reportlab.pdfbase._fontdata_widths_courier.widths, + 'Courier-Bold': + reportlab.pdfbase._fontdata_widths_courierbold.widths, + 'Courier-Oblique': + reportlab.pdfbase._fontdata_widths_courieroblique.widths, + 'Courier-BoldOblique': + reportlab.pdfbase._fontdata_widths_courierboldoblique.widths, + 'Helvetica': + reportlab.pdfbase._fontdata_widths_helvetica.widths, + 'Helvetica-Bold': + reportlab.pdfbase._fontdata_widths_helveticabold.widths, + 'Helvetica-Oblique': + reportlab.pdfbase._fontdata_widths_helveticaoblique.widths, + 'Helvetica-BoldOblique': + reportlab.pdfbase._fontdata_widths_helveticaboldoblique.widths, + 'Times-Roman': + reportlab.pdfbase._fontdata_widths_timesroman.widths, + 'Times-Bold': + reportlab.pdfbase._fontdata_widths_timesbold.widths, + 'Times-Italic': + reportlab.pdfbase._fontdata_widths_timesitalic.widths, + 'Times-BoldItalic': + reportlab.pdfbase._fontdata_widths_timesbolditalic.widths, + 'Symbol': + reportlab.pdfbase._fontdata_widths_symbol.widths, + 'ZapfDingbats': + reportlab.pdfbase._fontdata_widths_zapfdingbats.widths, +} + + +#preserve the initial values here +def _reset( + initial_dicts=dict( + ascent_descent=ascent_descent.copy(), + fontsByBaseEnc=fontsByBaseEnc.copy(), + fontsByName=fontsByName.copy(), + standardFontAttributes=standardFontAttributes.copy(), + widthVectorsByFont=widthVectorsByFont.copy(), + widthsByFontGlyph=widthsByFontGlyph.copy(), + ) + ): + for k,v in initial_dicts.items(): + d=globals()[k] + d.clear() + d.update(v) + +from reportlab.rl_config import register_reset +register_reset(_reset) +del register_reset diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_enc_macexpert.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_enc_macexpert.py new file mode 100644 index 0000000000000000000000000000000000000000..f0372db7ae78b7113dc64eb29a9a79fa12a38f68 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_enc_macexpert.py @@ -0,0 +1,28 @@ +MacExpertEncoding = (None, None, None, None, None, None, None, None, None, None, None, None, None, None, + None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, + 'space', 'exclamsmall', 'Hungarumlautsmall', 'centoldstyle', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall', + 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'comma', 'hyphen', + 'period', 'fraction', 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle', + 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'colon', 'semicolon', None, + 'threequartersemdash', None, 'questionsmall', None, None, None, None, 'Ethsmall', None, None, 'onequarter', + 'onehalf', 'threequarters', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', + None, None, None, None, None, None, 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', None, + 'parenrightinferior', 'Circumflexsmall', 'hypheninferior', 'Gravesmall', 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', + 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', + 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', + 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', None, None, 'asuperior', 'centsuperior', None, None, None, + None, 'Aacutesmall', 'Agravesmall', 'Acircumflexsmall', 'Adieresissmall', 'Atildesmall', 'Aringsmall', + 'Ccedillasmall', 'Eacutesmall', 'Egravesmall', 'Ecircumflexsmall', 'Edieresissmall', 'Iacutesmall', 'Igravesmall', + 'Icircumflexsmall', 'Idieresissmall', 'Ntildesmall', 'Oacutesmall', 'Ogravesmall', 'Ocircumflexsmall', + 'Odieresissmall', 'Otildesmall', 'Uacutesmall', 'Ugravesmall', 'Ucircumflexsmall', 'Udieresissmall', None, + 'eightsuperior', 'fourinferior', 'threeinferior', 'sixinferior', 'eightinferior', 'seveninferior', 'Scaronsmall', + None, 'centinferior', 'twoinferior', None, 'Dieresissmall', None, 'Caronsmall', 'osuperior', 'fiveinferior', None, + 'commainferior', 'periodinferior', 'Yacutesmall', None, 'dollarinferior', None, None, 'Thornsmall', None, + 'nineinferior', 'zeroinferior', 'Zcaronsmall', 'AEsmall', 'Oslashsmall', 'questiondownsmall', 'oneinferior', + 'Lslashsmall', None, None, None, None, None, None, 'Cedillasmall', None, None, None, None, None, 'OEsmall', + 'figuredash', 'hyphensuperior', None, None, None, None, 'exclamdownsmall', None, 'Ydieresissmall', None, + 'onesuperior', 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior', 'sixsuperior', 'sevensuperior', + 'ninesuperior', 'zerosuperior', None, 'esuperior', 'rsuperior', 'tsuperior', None, None, 'isuperior', 'ssuperior', + 'dsuperior', None, None, None, None, None, 'lsuperior', 'Ogoneksmall', 'Brevesmall', 'Macronsmall', 'bsuperior', + 'nsuperior', 'msuperior', 'commasuperior', 'periodsuperior', 'Dotaccentsmall', 'Ringsmall', None, None, None, None) + diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_enc_macroman.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_enc_macroman.py new file mode 100644 index 0000000000000000000000000000000000000000..b406712457fc6db60c234e6e759899f4e1c1d809 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_enc_macroman.py @@ -0,0 +1,35 @@ +MacRomanEncoding = ( + None, None, None, None, None, None, None, None, None, None, None, None, + None, None, None, None, None, None, None, None, None, None, None, None, + None, None, None, None, None, None, None, None, 'space', 'exclam', + 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', + 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', + 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', + 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', + 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', + 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', + 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', + 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', + 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', + 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', + 'asciitilde', None, 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', + 'Ntilde', 'Odieresis', 'Udieresis', 'aacute', 'agrave', 'acircumflex', + 'adieresis', 'atilde', 'aring', 'ccedilla', 'eacute', 'egrave', + 'ecircumflex', 'edieresis', 'iacute', 'igrave', 'icircumflex', + 'idieresis', 'ntilde', 'oacute', 'ograve', 'ocircumflex', 'odieresis', + 'otilde', 'uacute', 'ugrave', 'ucircumflex', 'udieresis', 'dagger', + 'degree', 'cent', 'sterling', 'section', 'bullet', 'paragraph', + 'germandbls', 'registered', 'copyright', 'trademark', 'acute', + 'dieresis', None, 'AE', 'Oslash', None, 'plusminus', None, None, 'yen', + 'mu', None, None, None, None, None, 'ordfeminine', 'ordmasculine', None, + 'ae', 'oslash', 'questiondown', 'exclamdown', 'logicalnot', None, 'florin', + None, None, 'guillemotleft', 'guillemotright', 'ellipsis', 'space', 'Agrave', + 'Atilde', 'Otilde', 'OE', 'oe', 'endash', 'emdash', 'quotedblleft', + 'quotedblright', 'quoteleft', 'quoteright', 'divide', None, 'ydieresis', + 'Ydieresis', 'fraction', 'currency', 'guilsinglleft', 'guilsinglright', + 'fi', 'fl', 'daggerdbl', 'periodcentered', 'quotesinglbase', + 'quotedblbase', 'perthousand', 'Acircumflex', 'Ecircumflex', 'Aacute', + 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', + 'Oacute', 'Ocircumflex', None, 'Ograve', 'Uacute', 'Ucircumflex', + 'Ugrave', 'dotlessi', 'circumflex', 'tilde', 'macron', 'breve', + 'dotaccent', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron') diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_enc_pdfdoc.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_enc_pdfdoc.py new file mode 100644 index 0000000000000000000000000000000000000000..39ccf5ce166bae6dfcbc409aadf6e722ed390c1a --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_enc_pdfdoc.py @@ -0,0 +1,22 @@ +PDFDocEncoding = (None, None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None, + None,None,None,None,None,"breve","caron","circumflex", + "dotaccent","hungarumlaut","ogonek","ring","tilde","space","exclam","quotedbl","numbersign","dollar","percent", + "ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero", + "one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater", + "question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X", + "Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g", + "h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright", + "asciitilde",None,"bullet","dagger","daggerdbl","ellipsis","emdash","endash","florin","fraction","guilsinglleft", + "guilsinglright","minus","perthousand","quotedblbase","quotedblleft","quotedblright","quoteleft","quoteright", + "quotesinglbase","trademark","fi","fl","Lslash","OE","Scaron","Ydieresis","Zcaron","dotlessi","lslash","oe", + "scaron","zcaron",None,"Euro","exclamdown","cent","sterling","currency","yen","brokenbar","section","dieresis", + "copyright","ordfeminine","guillemotleft","logicalnot",None,"registered","macron","degree","plusminus","twosuperior", + "threesuperior","acute","mu","paragraph","periodcentered","cedilla","onesuperior","ordmasculine","guillemotright", + "onequarter","onehalf","threequarters","questiondown","Agrave","Aacute","Acircumflex","Atilde","Adieresis","Aring", + "AE","Ccedilla","Egrave","Eacute","Ecircumflex","Edieresis","Igrave","Iacute","Icircumflex","Idieresis","Eth", + "Ntilde","Ograve","Oacute","Ocircumflex","Otilde","Odieresis","multiply","Oslash","Ugrave","Uacute","Ucircumflex", + "Udieresis","Yacute","Thorn","germandbls","agrave","aacute","acircumflex","atilde","adieresis","aring","ae", + "ccedilla","egrave","eacute","ecircumflex","edieresis","igrave","iacute","icircumflex","idieresis","eth","ntilde", + "ograve","oacute","ocircumflex","otilde","odieresis","divide","oslash","ugrave","uacute","ucircumflex","udieresis", + "yacute","thorn","ydieresis") + diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_enc_standard.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_enc_standard.py new file mode 100644 index 0000000000000000000000000000000000000000..e17aa68036a610bd2c7433181ba0bdfe96302534 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_enc_standard.py @@ -0,0 +1,15 @@ +StandardEncoding =(None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,"space","exclam", + "quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus", + "comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon", + "semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O", + "P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore", + "quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y", + "z","braceleft","bar","braceright","asciitilde",None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None, + None,None,None,"exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft", + "guillemotleft","guilsinglleft","guilsinglright","fi","fl",None,"endash","dagger","daggerdbl","periodcentered",None, + "paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand", + None,"questiondown",None,"grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis",None,"ring", + "cedilla",None,"hungarumlaut","ogonek","caron","emdash",None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,"AE",None,"ordfeminine", + None,None,None,None,"Lslash","Oslash","OE","ordmasculine",None,None,None,None,None,"ae",None,None,None,"dotlessi",None,None,"lslash","oslash", + "oe","germandbls",None,None,None,None) + diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_enc_symbol.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_enc_symbol.py new file mode 100644 index 0000000000000000000000000000000000000000..cc399bbe05e57b2277b6df8f0164db1bdc20e502 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_enc_symbol.py @@ -0,0 +1,30 @@ +SymbolEncoding = ( + None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, + None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, 'space', + 'exclam', 'universal', 'numbersign', 'existential', 'percent', 'ampersand', 'suchthat', + 'parenleft', 'parenright', 'asteriskmath', 'plus', 'comma', 'minus', 'period', 'slash', 'zero', + 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', + 'less', 'equal', 'greater', 'question', 'congruent', 'Alpha', 'Beta', 'Chi', 'Delta', 'Epsilon', + 'Phi', 'Gamma', 'Eta', 'Iota', 'theta1', 'Kappa', 'Lambda', 'Mu', 'Nu', 'Omicron', 'Pi', 'Theta', + 'Rho', 'Sigma', 'Tau', 'Upsilon', 'sigma1', 'Omega', 'Xi', 'Psi', 'Zeta', 'bracketleft', + 'therefore', 'bracketright', 'perpendicular', 'underscore', 'radicalex', 'alpha', 'beta', 'chi', + 'delta', 'epsilon', 'phi', 'gamma', 'eta', 'iota', 'phi1', 'kappa', 'lambda', 'mu', 'nu', + 'omicron', 'pi', 'theta', 'rho', 'sigma', 'tau', 'upsilon', 'omega1', 'omega', 'xi', 'psi', 'zeta', + 'braceleft', 'bar', 'braceright', 'similar', None, None, None, None, None, None, None, None, None, + None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, + None, None, None, None, None, None, None, None, 'Euro', 'Upsilon1', 'minute', 'lessequal', + 'fraction', 'infinity', 'florin', 'club', 'diamond', 'heart', 'spade', 'arrowboth', 'arrowleft', + 'arrowup', 'arrowright', 'arrowdown', 'degree', 'plusminus', 'second', 'greaterequal', 'multiply', + 'proportional', 'partialdiff', 'bullet', 'divide', 'notequal', 'equivalence', 'approxequal', + 'ellipsis', 'arrowvertex', 'arrowhorizex', 'carriagereturn', 'aleph', 'Ifraktur', 'Rfraktur', + 'weierstrass', 'circlemultiply', 'circleplus', 'emptyset', 'intersection', 'union', + 'propersuperset', 'reflexsuperset', 'notsubset', 'propersubset', 'reflexsubset', 'element', + 'notelement', 'angle', 'gradient', 'registerserif', 'copyrightserif', 'trademarkserif', 'product', + 'radical', 'dotmath', 'logicalnot', 'logicaland', 'logicalor', 'arrowdblboth', 'arrowdblleft', + 'arrowdblup', 'arrowdblright', 'arrowdbldown', 'lozenge', 'angleleft', 'registersans', + 'copyrightsans', 'trademarksans', 'summation', 'parenlefttp', 'parenleftex', 'parenleftbt', + 'bracketlefttp', 'bracketleftex', 'bracketleftbt', 'bracelefttp', 'braceleftmid', 'braceleftbt', + 'braceex', None, 'angleright', 'integral', 'integraltp', 'integralex', 'integralbt', + 'parenrighttp', 'parenrightex', 'parenrightbt', 'bracketrighttp', 'bracketrightex', + 'bracketrightbt', 'bracerighttp', 'bracerightmid', 'bracerightbt', None) + diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_enc_winansi.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_enc_winansi.py new file mode 100644 index 0000000000000000000000000000000000000000..8cf18ba8a82ee3d77ff68edc0f133b39726f5052 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_enc_winansi.py @@ -0,0 +1,37 @@ +WinAnsiEncoding = ( + None, None, None, None, None, None, None, None, None, None, None, None, + None, None, None, None, None, None, None, None, None, None, None, None, + None, None, None, None, None, None, None, None, 'space', 'exclam', + 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', + 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', + 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', + 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', + 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', + 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', + 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', + 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', + 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', + 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', + 'asciitilde', 'bullet', 'Euro', 'bullet', 'quotesinglbase', 'florin', + 'quotedblbase', 'ellipsis', 'dagger', 'daggerdbl', 'circumflex', + 'perthousand', 'Scaron', 'guilsinglleft', 'OE', 'bullet', 'Zcaron', + 'bullet', 'bullet', 'quoteleft', 'quoteright', 'quotedblleft', + 'quotedblright', 'bullet', 'endash', 'emdash', 'tilde', 'trademark', + 'scaron', 'guilsinglright', 'oe', 'bullet', 'zcaron', 'Ydieresis', + 'space', 'exclamdown', 'cent', 'sterling', 'currency', 'yen', 'brokenbar', + 'section', 'dieresis', 'copyright', 'ordfeminine', 'guillemotleft', + 'logicalnot', 'hyphen', 'registered', 'macron', 'degree', 'plusminus', + 'twosuperior', 'threesuperior', 'acute', 'mu', 'paragraph', 'periodcentered', + 'cedilla', 'onesuperior', 'ordmasculine', 'guillemotright', 'onequarter', + 'onehalf', 'threequarters', 'questiondown', 'Agrave', 'Aacute', + 'Acircumflex', 'Atilde', 'Adieresis', 'Aring', 'AE', 'Ccedilla', + 'Egrave', 'Eacute', 'Ecircumflex', 'Edieresis', 'Igrave', 'Iacute', + 'Icircumflex', 'Idieresis', 'Eth', 'Ntilde', 'Ograve', 'Oacute', + 'Ocircumflex', 'Otilde', 'Odieresis', 'multiply', 'Oslash', 'Ugrave', + 'Uacute', 'Ucircumflex', 'Udieresis', 'Yacute', 'Thorn', 'germandbls', + 'agrave', 'aacute', 'acircumflex', 'atilde', 'adieresis', 'aring', 'ae', + 'ccedilla', 'egrave', 'eacute', 'ecircumflex', 'edieresis', 'igrave', + 'iacute', 'icircumflex', 'idieresis', 'eth', 'ntilde', 'ograve', 'oacute', + 'ocircumflex', 'otilde', 'odieresis', 'divide', 'oslash', 'ugrave', 'uacute', + 'ucircumflex', 'udieresis', 'yacute', 'thorn', 'ydieresis') + diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_enc_zapfdingbats.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_enc_zapfdingbats.py new file mode 100644 index 0000000000000000000000000000000000000000..80b66756bb6d62bfb6dcd244f6433f76cd30ac99 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_enc_zapfdingbats.py @@ -0,0 +1,20 @@ +ZapfDingbatsEncoding = ( None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, + None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, + 'space', 'a1', 'a2', 'a202', 'a3', 'a4', 'a5', 'a119', 'a118', 'a117', 'a11', 'a12', 'a13', 'a14', + 'a15', 'a16', 'a105', 'a17', 'a18', 'a19', 'a20', 'a21', 'a22', 'a23', 'a24', 'a25', 'a26', 'a27', + 'a28', 'a6', 'a7', 'a8', 'a9', 'a10', 'a29', 'a30', 'a31', 'a32', 'a33', 'a34', 'a35', 'a36', + 'a37', 'a38', 'a39', 'a40', 'a41', 'a42', 'a43', 'a44', 'a45', 'a46', 'a47', 'a48', 'a49', 'a50', + 'a51', 'a52', 'a53', 'a54', 'a55', 'a56', 'a57', 'a58', 'a59', 'a60', 'a61', 'a62', 'a63', 'a64', + 'a65', 'a66', 'a67', 'a68', 'a69', 'a70', 'a71', 'a72', 'a73', 'a74', 'a203', 'a75', 'a204', 'a76', + 'a77', 'a78', 'a79', 'a81', 'a82', 'a83', 'a84', 'a97', 'a98', 'a99', 'a100', None, 'a89', 'a90', + 'a93', 'a94', 'a91', 'a92', 'a205', 'a85', 'a206', 'a86', 'a87', 'a88', 'a95', 'a96', None, None, + None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, + None, 'a101', 'a102', 'a103', 'a104', 'a106', 'a107', 'a108', 'a112', 'a111', 'a110', 'a109', + 'a120', 'a121', 'a122', 'a123', 'a124', 'a125', 'a126', 'a127', 'a128', 'a129', 'a130', 'a131', + 'a132', 'a133', 'a134', 'a135', 'a136', 'a137', 'a138', 'a139', 'a140', 'a141', 'a142', 'a143', + 'a144', 'a145', 'a146', 'a147', 'a148', 'a149', 'a150', 'a151', 'a152', 'a153', 'a154', 'a155', + 'a156', 'a157', 'a158', 'a159', 'a160', 'a161', 'a163', 'a164', 'a196', 'a165', 'a192', 'a166', + 'a167', 'a168', 'a169', 'a170', 'a171', 'a172', 'a173', 'a162', 'a174', 'a175', 'a176', 'a177', + 'a178', 'a179', 'a193', 'a180', 'a199', 'a181', 'a200', 'a182', None, 'a201', 'a183', 'a184', + 'a197', 'a185', 'a194', 'a198', 'a186', 'a195', 'a187', 'a188', 'a189', 'a190', 'a191', None) + diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_courier.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_courier.py new file mode 100644 index 0000000000000000000000000000000000000000..f196a19ade080eacd50f981c3a6e506a8ca22a30 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_courier.py @@ -0,0 +1,229 @@ +widths = {'A': 600, + 'AE': 600, + 'Aacute': 600, + 'Acircumflex': 600, + 'Adieresis': 600, + 'Agrave': 600, + 'Aring': 600, + 'Atilde': 600, + 'B': 600, + 'C': 600, + 'Ccedilla': 600, + 'D': 600, + 'E': 600, + 'Eacute': 600, + 'Ecircumflex': 600, + 'Edieresis': 600, + 'Egrave': 600, + 'Eth': 600, + 'Euro': 600, + 'F': 600, + 'G': 600, + 'H': 600, + 'I': 600, + 'Iacute': 600, + 'Icircumflex': 600, + 'Idieresis': 600, + 'Igrave': 600, + 'J': 600, + 'K': 600, + 'L': 600, + 'Lslash': 600, + 'M': 600, + 'N': 600, + 'Ntilde': 600, + 'O': 600, + 'OE': 600, + 'Oacute': 600, + 'Ocircumflex': 600, + 'Odieresis': 600, + 'Ograve': 600, + 'Oslash': 600, + 'Otilde': 600, + 'P': 600, + 'Q': 600, + 'R': 600, + 'S': 600, + 'Scaron': 600, + 'T': 600, + 'Thorn': 600, + 'U': 600, + 'Uacute': 600, + 'Ucircumflex': 600, + 'Udieresis': 600, + 'Ugrave': 600, + 'V': 600, + 'W': 600, + 'X': 600, + 'Y': 600, + 'Yacute': 600, + 'Ydieresis': 600, + 'Z': 600, + 'Zcaron': 600, + 'a': 600, + 'aacute': 600, + 'acircumflex': 600, + 'acute': 600, + 'adieresis': 600, + 'ae': 600, + 'agrave': 600, + 'ampersand': 600, + 'aring': 600, + 'asciicircum': 600, + 'asciitilde': 600, + 'asterisk': 600, + 'at': 600, + 'atilde': 600, + 'b': 600, + 'backslash': 600, + 'bar': 600, + 'braceleft': 600, + 'braceright': 600, + 'bracketleft': 600, + 'bracketright': 600, + 'breve': 600, + 'brokenbar': 600, + 'bullet': 600, + 'c': 600, + 'caron': 600, + 'ccedilla': 600, + 'cedilla': 600, + 'cent': 600, + 'circumflex': 600, + 'colon': 600, + 'comma': 600, + 'copyright': 600, + 'currency': 600, + 'd': 600, + 'dagger': 600, + 'daggerdbl': 600, + 'degree': 600, + 'dieresis': 600, + 'divide': 600, + 'dollar': 600, + 'dotaccent': 600, + 'dotlessi': 600, + 'e': 600, + 'eacute': 600, + 'ecircumflex': 600, + 'edieresis': 600, + 'egrave': 600, + 'eight': 600, + 'ellipsis': 600, + 'emdash': 600, + 'endash': 600, + 'equal': 600, + 'eth': 600, + 'exclam': 600, + 'exclamdown': 600, + 'f': 600, + 'fi': 600, + 'five': 600, + 'fl': 600, + 'florin': 600, + 'four': 600, + 'fraction': 600, + 'g': 600, + 'germandbls': 600, + 'grave': 600, + 'greater': 600, + 'guillemotleft': 600, + 'guillemotright': 600, + 'guilsinglleft': 600, + 'guilsinglright': 600, + 'h': 600, + 'hungarumlaut': 600, + 'hyphen': 600, + 'i': 600, + 'iacute': 600, + 'icircumflex': 600, + 'idieresis': 600, + 'igrave': 600, + 'j': 600, + 'k': 600, + 'l': 600, + 'less': 600, + 'logicalnot': 600, + 'lslash': 600, + 'm': 600, + 'macron': 600, + 'minus': 600, + 'mu': 600, + 'multiply': 600, + 'n': 600, + 'nine': 600, + 'ntilde': 600, + 'numbersign': 600, + 'o': 600, + 'oacute': 600, + 'ocircumflex': 600, + 'odieresis': 600, + 'oe': 600, + 'ogonek': 600, + 'ograve': 600, + 'one': 600, + 'onehalf': 600, + 'onequarter': 600, + 'onesuperior': 600, + 'ordfeminine': 600, + 'ordmasculine': 600, + 'oslash': 600, + 'otilde': 600, + 'p': 600, + 'paragraph': 600, + 'parenleft': 600, + 'parenright': 600, + 'percent': 600, + 'period': 600, + 'periodcentered': 600, + 'perthousand': 600, + 'plus': 600, + 'plusminus': 600, + 'q': 600, + 'question': 600, + 'questiondown': 600, + 'quotedbl': 600, + 'quotedblbase': 600, + 'quotedblleft': 600, + 'quotedblright': 600, + 'quoteleft': 600, + 'quoteright': 600, + 'quotesinglbase': 600, + 'quotesingle': 600, + 'r': 600, + 'registered': 600, + 'ring': 600, + 's': 600, + 'scaron': 600, + 'section': 600, + 'semicolon': 600, + 'seven': 600, + 'six': 600, + 'slash': 600, + 'space': 600, + 'sterling': 600, + 't': 600, + 'thorn': 600, + 'three': 600, + 'threequarters': 600, + 'threesuperior': 600, + 'tilde': 600, + 'trademark': 600, + 'two': 600, + 'twosuperior': 600, + 'u': 600, + 'uacute': 600, + 'ucircumflex': 600, + 'udieresis': 600, + 'ugrave': 600, + 'underscore': 600, + 'v': 600, + 'w': 600, + 'x': 600, + 'y': 600, + 'yacute': 600, + 'ydieresis': 600, + 'yen': 600, + 'z': 600, + 'zcaron': 600, + 'zero': 600} diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_courierbold.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_courierbold.py new file mode 100644 index 0000000000000000000000000000000000000000..f196a19ade080eacd50f981c3a6e506a8ca22a30 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_courierbold.py @@ -0,0 +1,229 @@ +widths = {'A': 600, + 'AE': 600, + 'Aacute': 600, + 'Acircumflex': 600, + 'Adieresis': 600, + 'Agrave': 600, + 'Aring': 600, + 'Atilde': 600, + 'B': 600, + 'C': 600, + 'Ccedilla': 600, + 'D': 600, + 'E': 600, + 'Eacute': 600, + 'Ecircumflex': 600, + 'Edieresis': 600, + 'Egrave': 600, + 'Eth': 600, + 'Euro': 600, + 'F': 600, + 'G': 600, + 'H': 600, + 'I': 600, + 'Iacute': 600, + 'Icircumflex': 600, + 'Idieresis': 600, + 'Igrave': 600, + 'J': 600, + 'K': 600, + 'L': 600, + 'Lslash': 600, + 'M': 600, + 'N': 600, + 'Ntilde': 600, + 'O': 600, + 'OE': 600, + 'Oacute': 600, + 'Ocircumflex': 600, + 'Odieresis': 600, + 'Ograve': 600, + 'Oslash': 600, + 'Otilde': 600, + 'P': 600, + 'Q': 600, + 'R': 600, + 'S': 600, + 'Scaron': 600, + 'T': 600, + 'Thorn': 600, + 'U': 600, + 'Uacute': 600, + 'Ucircumflex': 600, + 'Udieresis': 600, + 'Ugrave': 600, + 'V': 600, + 'W': 600, + 'X': 600, + 'Y': 600, + 'Yacute': 600, + 'Ydieresis': 600, + 'Z': 600, + 'Zcaron': 600, + 'a': 600, + 'aacute': 600, + 'acircumflex': 600, + 'acute': 600, + 'adieresis': 600, + 'ae': 600, + 'agrave': 600, + 'ampersand': 600, + 'aring': 600, + 'asciicircum': 600, + 'asciitilde': 600, + 'asterisk': 600, + 'at': 600, + 'atilde': 600, + 'b': 600, + 'backslash': 600, + 'bar': 600, + 'braceleft': 600, + 'braceright': 600, + 'bracketleft': 600, + 'bracketright': 600, + 'breve': 600, + 'brokenbar': 600, + 'bullet': 600, + 'c': 600, + 'caron': 600, + 'ccedilla': 600, + 'cedilla': 600, + 'cent': 600, + 'circumflex': 600, + 'colon': 600, + 'comma': 600, + 'copyright': 600, + 'currency': 600, + 'd': 600, + 'dagger': 600, + 'daggerdbl': 600, + 'degree': 600, + 'dieresis': 600, + 'divide': 600, + 'dollar': 600, + 'dotaccent': 600, + 'dotlessi': 600, + 'e': 600, + 'eacute': 600, + 'ecircumflex': 600, + 'edieresis': 600, + 'egrave': 600, + 'eight': 600, + 'ellipsis': 600, + 'emdash': 600, + 'endash': 600, + 'equal': 600, + 'eth': 600, + 'exclam': 600, + 'exclamdown': 600, + 'f': 600, + 'fi': 600, + 'five': 600, + 'fl': 600, + 'florin': 600, + 'four': 600, + 'fraction': 600, + 'g': 600, + 'germandbls': 600, + 'grave': 600, + 'greater': 600, + 'guillemotleft': 600, + 'guillemotright': 600, + 'guilsinglleft': 600, + 'guilsinglright': 600, + 'h': 600, + 'hungarumlaut': 600, + 'hyphen': 600, + 'i': 600, + 'iacute': 600, + 'icircumflex': 600, + 'idieresis': 600, + 'igrave': 600, + 'j': 600, + 'k': 600, + 'l': 600, + 'less': 600, + 'logicalnot': 600, + 'lslash': 600, + 'm': 600, + 'macron': 600, + 'minus': 600, + 'mu': 600, + 'multiply': 600, + 'n': 600, + 'nine': 600, + 'ntilde': 600, + 'numbersign': 600, + 'o': 600, + 'oacute': 600, + 'ocircumflex': 600, + 'odieresis': 600, + 'oe': 600, + 'ogonek': 600, + 'ograve': 600, + 'one': 600, + 'onehalf': 600, + 'onequarter': 600, + 'onesuperior': 600, + 'ordfeminine': 600, + 'ordmasculine': 600, + 'oslash': 600, + 'otilde': 600, + 'p': 600, + 'paragraph': 600, + 'parenleft': 600, + 'parenright': 600, + 'percent': 600, + 'period': 600, + 'periodcentered': 600, + 'perthousand': 600, + 'plus': 600, + 'plusminus': 600, + 'q': 600, + 'question': 600, + 'questiondown': 600, + 'quotedbl': 600, + 'quotedblbase': 600, + 'quotedblleft': 600, + 'quotedblright': 600, + 'quoteleft': 600, + 'quoteright': 600, + 'quotesinglbase': 600, + 'quotesingle': 600, + 'r': 600, + 'registered': 600, + 'ring': 600, + 's': 600, + 'scaron': 600, + 'section': 600, + 'semicolon': 600, + 'seven': 600, + 'six': 600, + 'slash': 600, + 'space': 600, + 'sterling': 600, + 't': 600, + 'thorn': 600, + 'three': 600, + 'threequarters': 600, + 'threesuperior': 600, + 'tilde': 600, + 'trademark': 600, + 'two': 600, + 'twosuperior': 600, + 'u': 600, + 'uacute': 600, + 'ucircumflex': 600, + 'udieresis': 600, + 'ugrave': 600, + 'underscore': 600, + 'v': 600, + 'w': 600, + 'x': 600, + 'y': 600, + 'yacute': 600, + 'ydieresis': 600, + 'yen': 600, + 'z': 600, + 'zcaron': 600, + 'zero': 600} diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_courierboldoblique.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_courierboldoblique.py new file mode 100644 index 0000000000000000000000000000000000000000..f196a19ade080eacd50f981c3a6e506a8ca22a30 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_courierboldoblique.py @@ -0,0 +1,229 @@ +widths = {'A': 600, + 'AE': 600, + 'Aacute': 600, + 'Acircumflex': 600, + 'Adieresis': 600, + 'Agrave': 600, + 'Aring': 600, + 'Atilde': 600, + 'B': 600, + 'C': 600, + 'Ccedilla': 600, + 'D': 600, + 'E': 600, + 'Eacute': 600, + 'Ecircumflex': 600, + 'Edieresis': 600, + 'Egrave': 600, + 'Eth': 600, + 'Euro': 600, + 'F': 600, + 'G': 600, + 'H': 600, + 'I': 600, + 'Iacute': 600, + 'Icircumflex': 600, + 'Idieresis': 600, + 'Igrave': 600, + 'J': 600, + 'K': 600, + 'L': 600, + 'Lslash': 600, + 'M': 600, + 'N': 600, + 'Ntilde': 600, + 'O': 600, + 'OE': 600, + 'Oacute': 600, + 'Ocircumflex': 600, + 'Odieresis': 600, + 'Ograve': 600, + 'Oslash': 600, + 'Otilde': 600, + 'P': 600, + 'Q': 600, + 'R': 600, + 'S': 600, + 'Scaron': 600, + 'T': 600, + 'Thorn': 600, + 'U': 600, + 'Uacute': 600, + 'Ucircumflex': 600, + 'Udieresis': 600, + 'Ugrave': 600, + 'V': 600, + 'W': 600, + 'X': 600, + 'Y': 600, + 'Yacute': 600, + 'Ydieresis': 600, + 'Z': 600, + 'Zcaron': 600, + 'a': 600, + 'aacute': 600, + 'acircumflex': 600, + 'acute': 600, + 'adieresis': 600, + 'ae': 600, + 'agrave': 600, + 'ampersand': 600, + 'aring': 600, + 'asciicircum': 600, + 'asciitilde': 600, + 'asterisk': 600, + 'at': 600, + 'atilde': 600, + 'b': 600, + 'backslash': 600, + 'bar': 600, + 'braceleft': 600, + 'braceright': 600, + 'bracketleft': 600, + 'bracketright': 600, + 'breve': 600, + 'brokenbar': 600, + 'bullet': 600, + 'c': 600, + 'caron': 600, + 'ccedilla': 600, + 'cedilla': 600, + 'cent': 600, + 'circumflex': 600, + 'colon': 600, + 'comma': 600, + 'copyright': 600, + 'currency': 600, + 'd': 600, + 'dagger': 600, + 'daggerdbl': 600, + 'degree': 600, + 'dieresis': 600, + 'divide': 600, + 'dollar': 600, + 'dotaccent': 600, + 'dotlessi': 600, + 'e': 600, + 'eacute': 600, + 'ecircumflex': 600, + 'edieresis': 600, + 'egrave': 600, + 'eight': 600, + 'ellipsis': 600, + 'emdash': 600, + 'endash': 600, + 'equal': 600, + 'eth': 600, + 'exclam': 600, + 'exclamdown': 600, + 'f': 600, + 'fi': 600, + 'five': 600, + 'fl': 600, + 'florin': 600, + 'four': 600, + 'fraction': 600, + 'g': 600, + 'germandbls': 600, + 'grave': 600, + 'greater': 600, + 'guillemotleft': 600, + 'guillemotright': 600, + 'guilsinglleft': 600, + 'guilsinglright': 600, + 'h': 600, + 'hungarumlaut': 600, + 'hyphen': 600, + 'i': 600, + 'iacute': 600, + 'icircumflex': 600, + 'idieresis': 600, + 'igrave': 600, + 'j': 600, + 'k': 600, + 'l': 600, + 'less': 600, + 'logicalnot': 600, + 'lslash': 600, + 'm': 600, + 'macron': 600, + 'minus': 600, + 'mu': 600, + 'multiply': 600, + 'n': 600, + 'nine': 600, + 'ntilde': 600, + 'numbersign': 600, + 'o': 600, + 'oacute': 600, + 'ocircumflex': 600, + 'odieresis': 600, + 'oe': 600, + 'ogonek': 600, + 'ograve': 600, + 'one': 600, + 'onehalf': 600, + 'onequarter': 600, + 'onesuperior': 600, + 'ordfeminine': 600, + 'ordmasculine': 600, + 'oslash': 600, + 'otilde': 600, + 'p': 600, + 'paragraph': 600, + 'parenleft': 600, + 'parenright': 600, + 'percent': 600, + 'period': 600, + 'periodcentered': 600, + 'perthousand': 600, + 'plus': 600, + 'plusminus': 600, + 'q': 600, + 'question': 600, + 'questiondown': 600, + 'quotedbl': 600, + 'quotedblbase': 600, + 'quotedblleft': 600, + 'quotedblright': 600, + 'quoteleft': 600, + 'quoteright': 600, + 'quotesinglbase': 600, + 'quotesingle': 600, + 'r': 600, + 'registered': 600, + 'ring': 600, + 's': 600, + 'scaron': 600, + 'section': 600, + 'semicolon': 600, + 'seven': 600, + 'six': 600, + 'slash': 600, + 'space': 600, + 'sterling': 600, + 't': 600, + 'thorn': 600, + 'three': 600, + 'threequarters': 600, + 'threesuperior': 600, + 'tilde': 600, + 'trademark': 600, + 'two': 600, + 'twosuperior': 600, + 'u': 600, + 'uacute': 600, + 'ucircumflex': 600, + 'udieresis': 600, + 'ugrave': 600, + 'underscore': 600, + 'v': 600, + 'w': 600, + 'x': 600, + 'y': 600, + 'yacute': 600, + 'ydieresis': 600, + 'yen': 600, + 'z': 600, + 'zcaron': 600, + 'zero': 600} diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_courieroblique.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_courieroblique.py new file mode 100644 index 0000000000000000000000000000000000000000..f196a19ade080eacd50f981c3a6e506a8ca22a30 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_courieroblique.py @@ -0,0 +1,229 @@ +widths = {'A': 600, + 'AE': 600, + 'Aacute': 600, + 'Acircumflex': 600, + 'Adieresis': 600, + 'Agrave': 600, + 'Aring': 600, + 'Atilde': 600, + 'B': 600, + 'C': 600, + 'Ccedilla': 600, + 'D': 600, + 'E': 600, + 'Eacute': 600, + 'Ecircumflex': 600, + 'Edieresis': 600, + 'Egrave': 600, + 'Eth': 600, + 'Euro': 600, + 'F': 600, + 'G': 600, + 'H': 600, + 'I': 600, + 'Iacute': 600, + 'Icircumflex': 600, + 'Idieresis': 600, + 'Igrave': 600, + 'J': 600, + 'K': 600, + 'L': 600, + 'Lslash': 600, + 'M': 600, + 'N': 600, + 'Ntilde': 600, + 'O': 600, + 'OE': 600, + 'Oacute': 600, + 'Ocircumflex': 600, + 'Odieresis': 600, + 'Ograve': 600, + 'Oslash': 600, + 'Otilde': 600, + 'P': 600, + 'Q': 600, + 'R': 600, + 'S': 600, + 'Scaron': 600, + 'T': 600, + 'Thorn': 600, + 'U': 600, + 'Uacute': 600, + 'Ucircumflex': 600, + 'Udieresis': 600, + 'Ugrave': 600, + 'V': 600, + 'W': 600, + 'X': 600, + 'Y': 600, + 'Yacute': 600, + 'Ydieresis': 600, + 'Z': 600, + 'Zcaron': 600, + 'a': 600, + 'aacute': 600, + 'acircumflex': 600, + 'acute': 600, + 'adieresis': 600, + 'ae': 600, + 'agrave': 600, + 'ampersand': 600, + 'aring': 600, + 'asciicircum': 600, + 'asciitilde': 600, + 'asterisk': 600, + 'at': 600, + 'atilde': 600, + 'b': 600, + 'backslash': 600, + 'bar': 600, + 'braceleft': 600, + 'braceright': 600, + 'bracketleft': 600, + 'bracketright': 600, + 'breve': 600, + 'brokenbar': 600, + 'bullet': 600, + 'c': 600, + 'caron': 600, + 'ccedilla': 600, + 'cedilla': 600, + 'cent': 600, + 'circumflex': 600, + 'colon': 600, + 'comma': 600, + 'copyright': 600, + 'currency': 600, + 'd': 600, + 'dagger': 600, + 'daggerdbl': 600, + 'degree': 600, + 'dieresis': 600, + 'divide': 600, + 'dollar': 600, + 'dotaccent': 600, + 'dotlessi': 600, + 'e': 600, + 'eacute': 600, + 'ecircumflex': 600, + 'edieresis': 600, + 'egrave': 600, + 'eight': 600, + 'ellipsis': 600, + 'emdash': 600, + 'endash': 600, + 'equal': 600, + 'eth': 600, + 'exclam': 600, + 'exclamdown': 600, + 'f': 600, + 'fi': 600, + 'five': 600, + 'fl': 600, + 'florin': 600, + 'four': 600, + 'fraction': 600, + 'g': 600, + 'germandbls': 600, + 'grave': 600, + 'greater': 600, + 'guillemotleft': 600, + 'guillemotright': 600, + 'guilsinglleft': 600, + 'guilsinglright': 600, + 'h': 600, + 'hungarumlaut': 600, + 'hyphen': 600, + 'i': 600, + 'iacute': 600, + 'icircumflex': 600, + 'idieresis': 600, + 'igrave': 600, + 'j': 600, + 'k': 600, + 'l': 600, + 'less': 600, + 'logicalnot': 600, + 'lslash': 600, + 'm': 600, + 'macron': 600, + 'minus': 600, + 'mu': 600, + 'multiply': 600, + 'n': 600, + 'nine': 600, + 'ntilde': 600, + 'numbersign': 600, + 'o': 600, + 'oacute': 600, + 'ocircumflex': 600, + 'odieresis': 600, + 'oe': 600, + 'ogonek': 600, + 'ograve': 600, + 'one': 600, + 'onehalf': 600, + 'onequarter': 600, + 'onesuperior': 600, + 'ordfeminine': 600, + 'ordmasculine': 600, + 'oslash': 600, + 'otilde': 600, + 'p': 600, + 'paragraph': 600, + 'parenleft': 600, + 'parenright': 600, + 'percent': 600, + 'period': 600, + 'periodcentered': 600, + 'perthousand': 600, + 'plus': 600, + 'plusminus': 600, + 'q': 600, + 'question': 600, + 'questiondown': 600, + 'quotedbl': 600, + 'quotedblbase': 600, + 'quotedblleft': 600, + 'quotedblright': 600, + 'quoteleft': 600, + 'quoteright': 600, + 'quotesinglbase': 600, + 'quotesingle': 600, + 'r': 600, + 'registered': 600, + 'ring': 600, + 's': 600, + 'scaron': 600, + 'section': 600, + 'semicolon': 600, + 'seven': 600, + 'six': 600, + 'slash': 600, + 'space': 600, + 'sterling': 600, + 't': 600, + 'thorn': 600, + 'three': 600, + 'threequarters': 600, + 'threesuperior': 600, + 'tilde': 600, + 'trademark': 600, + 'two': 600, + 'twosuperior': 600, + 'u': 600, + 'uacute': 600, + 'ucircumflex': 600, + 'udieresis': 600, + 'ugrave': 600, + 'underscore': 600, + 'v': 600, + 'w': 600, + 'x': 600, + 'y': 600, + 'yacute': 600, + 'ydieresis': 600, + 'yen': 600, + 'z': 600, + 'zcaron': 600, + 'zero': 600} diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_helvetica.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_helvetica.py new file mode 100644 index 0000000000000000000000000000000000000000..10d74db28996b951e6a4205179db9b1626d84bab --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_helvetica.py @@ -0,0 +1,229 @@ +widths = {'A': 667, + 'AE': 1000, + 'Aacute': 667, + 'Acircumflex': 667, + 'Adieresis': 667, + 'Agrave': 667, + 'Aring': 667, + 'Atilde': 667, + 'B': 667, + 'C': 722, + 'Ccedilla': 722, + 'D': 722, + 'E': 667, + 'Eacute': 667, + 'Ecircumflex': 667, + 'Edieresis': 667, + 'Egrave': 667, + 'Eth': 722, + 'Euro': 556, + 'F': 611, + 'G': 778, + 'H': 722, + 'I': 278, + 'Iacute': 278, + 'Icircumflex': 278, + 'Idieresis': 278, + 'Igrave': 278, + 'J': 500, + 'K': 667, + 'L': 556, + 'Lslash': 556, + 'M': 833, + 'N': 722, + 'Ntilde': 722, + 'O': 778, + 'OE': 1000, + 'Oacute': 778, + 'Ocircumflex': 778, + 'Odieresis': 778, + 'Ograve': 778, + 'Oslash': 778, + 'Otilde': 778, + 'P': 667, + 'Q': 778, + 'R': 722, + 'S': 667, + 'Scaron': 667, + 'T': 611, + 'Thorn': 667, + 'U': 722, + 'Uacute': 722, + 'Ucircumflex': 722, + 'Udieresis': 722, + 'Ugrave': 722, + 'V': 667, + 'W': 944, + 'X': 667, + 'Y': 667, + 'Yacute': 667, + 'Ydieresis': 667, + 'Z': 611, + 'Zcaron': 611, + 'a': 556, + 'aacute': 556, + 'acircumflex': 556, + 'acute': 333, + 'adieresis': 556, + 'ae': 889, + 'agrave': 556, + 'ampersand': 667, + 'aring': 556, + 'asciicircum': 469, + 'asciitilde': 584, + 'asterisk': 389, + 'at': 1015, + 'atilde': 556, + 'b': 556, + 'backslash': 278, + 'bar': 260, + 'braceleft': 334, + 'braceright': 334, + 'bracketleft': 278, + 'bracketright': 278, + 'breve': 333, + 'brokenbar': 260, + 'bullet': 350, + 'c': 500, + 'caron': 333, + 'ccedilla': 500, + 'cedilla': 333, + 'cent': 556, + 'circumflex': 333, + 'colon': 278, + 'comma': 278, + 'copyright': 737, + 'currency': 556, + 'd': 556, + 'dagger': 556, + 'daggerdbl': 556, + 'degree': 400, + 'dieresis': 333, + 'divide': 584, + 'dollar': 556, + 'dotaccent': 333, + 'dotlessi': 278, + 'e': 556, + 'eacute': 556, + 'ecircumflex': 556, + 'edieresis': 556, + 'egrave': 556, + 'eight': 556, + 'ellipsis': 1000, + 'emdash': 1000, + 'endash': 556, + 'equal': 584, + 'eth': 556, + 'exclam': 278, + 'exclamdown': 333, + 'f': 278, + 'fi': 500, + 'five': 556, + 'fl': 500, + 'florin': 556, + 'four': 556, + 'fraction': 167, + 'g': 556, + 'germandbls': 611, + 'grave': 333, + 'greater': 584, + 'guillemotleft': 556, + 'guillemotright': 556, + 'guilsinglleft': 333, + 'guilsinglright': 333, + 'h': 556, + 'hungarumlaut': 333, + 'hyphen': 333, + 'i': 222, + 'iacute': 278, + 'icircumflex': 278, + 'idieresis': 278, + 'igrave': 278, + 'j': 222, + 'k': 500, + 'l': 222, + 'less': 584, + 'logicalnot': 584, + 'lslash': 222, + 'm': 833, + 'macron': 333, + 'minus': 584, + 'mu': 556, + 'multiply': 584, + 'n': 556, + 'nine': 556, + 'ntilde': 556, + 'numbersign': 556, + 'o': 556, + 'oacute': 556, + 'ocircumflex': 556, + 'odieresis': 556, + 'oe': 944, + 'ogonek': 333, + 'ograve': 556, + 'one': 556, + 'onehalf': 834, + 'onequarter': 834, + 'onesuperior': 333, + 'ordfeminine': 370, + 'ordmasculine': 365, + 'oslash': 611, + 'otilde': 556, + 'p': 556, + 'paragraph': 537, + 'parenleft': 333, + 'parenright': 333, + 'percent': 889, + 'period': 278, + 'periodcentered': 278, + 'perthousand': 1000, + 'plus': 584, + 'plusminus': 584, + 'q': 556, + 'question': 556, + 'questiondown': 611, + 'quotedbl': 355, + 'quotedblbase': 333, + 'quotedblleft': 333, + 'quotedblright': 333, + 'quoteleft': 222, + 'quoteright': 222, + 'quotesinglbase': 222, + 'quotesingle': 191, + 'r': 333, + 'registered': 737, + 'ring': 333, + 's': 500, + 'scaron': 500, + 'section': 556, + 'semicolon': 278, + 'seven': 556, + 'six': 556, + 'slash': 278, + 'space': 278, + 'sterling': 556, + 't': 278, + 'thorn': 556, + 'three': 556, + 'threequarters': 834, + 'threesuperior': 333, + 'tilde': 333, + 'trademark': 1000, + 'two': 556, + 'twosuperior': 333, + 'u': 556, + 'uacute': 556, + 'ucircumflex': 556, + 'udieresis': 556, + 'ugrave': 556, + 'underscore': 556, + 'v': 500, + 'w': 722, + 'x': 500, + 'y': 500, + 'yacute': 500, + 'ydieresis': 500, + 'yen': 556, + 'z': 500, + 'zcaron': 500, + 'zero': 556} diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_helveticabold.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_helveticabold.py new file mode 100644 index 0000000000000000000000000000000000000000..7b9acd2cd0af9ac87003600d8671d3332ed5b701 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_helveticabold.py @@ -0,0 +1,229 @@ +widths = {'A': 722, + 'AE': 1000, + 'Aacute': 722, + 'Acircumflex': 722, + 'Adieresis': 722, + 'Agrave': 722, + 'Aring': 722, + 'Atilde': 722, + 'B': 722, + 'C': 722, + 'Ccedilla': 722, + 'D': 722, + 'E': 667, + 'Eacute': 667, + 'Ecircumflex': 667, + 'Edieresis': 667, + 'Egrave': 667, + 'Eth': 722, + 'Euro': 556, + 'F': 611, + 'G': 778, + 'H': 722, + 'I': 278, + 'Iacute': 278, + 'Icircumflex': 278, + 'Idieresis': 278, + 'Igrave': 278, + 'J': 556, + 'K': 722, + 'L': 611, + 'Lslash': 611, + 'M': 833, + 'N': 722, + 'Ntilde': 722, + 'O': 778, + 'OE': 1000, + 'Oacute': 778, + 'Ocircumflex': 778, + 'Odieresis': 778, + 'Ograve': 778, + 'Oslash': 778, + 'Otilde': 778, + 'P': 667, + 'Q': 778, + 'R': 722, + 'S': 667, + 'Scaron': 667, + 'T': 611, + 'Thorn': 667, + 'U': 722, + 'Uacute': 722, + 'Ucircumflex': 722, + 'Udieresis': 722, + 'Ugrave': 722, + 'V': 667, + 'W': 944, + 'X': 667, + 'Y': 667, + 'Yacute': 667, + 'Ydieresis': 667, + 'Z': 611, + 'Zcaron': 611, + 'a': 556, + 'aacute': 556, + 'acircumflex': 556, + 'acute': 333, + 'adieresis': 556, + 'ae': 889, + 'agrave': 556, + 'ampersand': 722, + 'aring': 556, + 'asciicircum': 584, + 'asciitilde': 584, + 'asterisk': 389, + 'at': 975, + 'atilde': 556, + 'b': 611, + 'backslash': 278, + 'bar': 280, + 'braceleft': 389, + 'braceright': 389, + 'bracketleft': 333, + 'bracketright': 333, + 'breve': 333, + 'brokenbar': 280, + 'bullet': 350, + 'c': 556, + 'caron': 333, + 'ccedilla': 556, + 'cedilla': 333, + 'cent': 556, + 'circumflex': 333, + 'colon': 333, + 'comma': 278, + 'copyright': 737, + 'currency': 556, + 'd': 611, + 'dagger': 556, + 'daggerdbl': 556, + 'degree': 400, + 'dieresis': 333, + 'divide': 584, + 'dollar': 556, + 'dotaccent': 333, + 'dotlessi': 278, + 'e': 556, + 'eacute': 556, + 'ecircumflex': 556, + 'edieresis': 556, + 'egrave': 556, + 'eight': 556, + 'ellipsis': 1000, + 'emdash': 1000, + 'endash': 556, + 'equal': 584, + 'eth': 611, + 'exclam': 333, + 'exclamdown': 333, + 'f': 333, + 'fi': 611, + 'five': 556, + 'fl': 611, + 'florin': 556, + 'four': 556, + 'fraction': 167, + 'g': 611, + 'germandbls': 611, + 'grave': 333, + 'greater': 584, + 'guillemotleft': 556, + 'guillemotright': 556, + 'guilsinglleft': 333, + 'guilsinglright': 333, + 'h': 611, + 'hungarumlaut': 333, + 'hyphen': 333, + 'i': 278, + 'iacute': 278, + 'icircumflex': 278, + 'idieresis': 278, + 'igrave': 278, + 'j': 278, + 'k': 556, + 'l': 278, + 'less': 584, + 'logicalnot': 584, + 'lslash': 278, + 'm': 889, + 'macron': 333, + 'minus': 584, + 'mu': 611, + 'multiply': 584, + 'n': 611, + 'nine': 556, + 'ntilde': 611, + 'numbersign': 556, + 'o': 611, + 'oacute': 611, + 'ocircumflex': 611, + 'odieresis': 611, + 'oe': 944, + 'ogonek': 333, + 'ograve': 611, + 'one': 556, + 'onehalf': 834, + 'onequarter': 834, + 'onesuperior': 333, + 'ordfeminine': 370, + 'ordmasculine': 365, + 'oslash': 611, + 'otilde': 611, + 'p': 611, + 'paragraph': 556, + 'parenleft': 333, + 'parenright': 333, + 'percent': 889, + 'period': 278, + 'periodcentered': 278, + 'perthousand': 1000, + 'plus': 584, + 'plusminus': 584, + 'q': 611, + 'question': 611, + 'questiondown': 611, + 'quotedbl': 474, + 'quotedblbase': 500, + 'quotedblleft': 500, + 'quotedblright': 500, + 'quoteleft': 278, + 'quoteright': 278, + 'quotesinglbase': 278, + 'quotesingle': 238, + 'r': 389, + 'registered': 737, + 'ring': 333, + 's': 556, + 'scaron': 556, + 'section': 556, + 'semicolon': 333, + 'seven': 556, + 'six': 556, + 'slash': 278, + 'space': 278, + 'sterling': 556, + 't': 333, + 'thorn': 611, + 'three': 556, + 'threequarters': 834, + 'threesuperior': 333, + 'tilde': 333, + 'trademark': 1000, + 'two': 556, + 'twosuperior': 333, + 'u': 611, + 'uacute': 611, + 'ucircumflex': 611, + 'udieresis': 611, + 'ugrave': 611, + 'underscore': 556, + 'v': 556, + 'w': 778, + 'x': 556, + 'y': 556, + 'yacute': 556, + 'ydieresis': 556, + 'yen': 556, + 'z': 500, + 'zcaron': 500, + 'zero': 556} diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_helveticaboldoblique.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_helveticaboldoblique.py new file mode 100644 index 0000000000000000000000000000000000000000..7b9acd2cd0af9ac87003600d8671d3332ed5b701 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_helveticaboldoblique.py @@ -0,0 +1,229 @@ +widths = {'A': 722, + 'AE': 1000, + 'Aacute': 722, + 'Acircumflex': 722, + 'Adieresis': 722, + 'Agrave': 722, + 'Aring': 722, + 'Atilde': 722, + 'B': 722, + 'C': 722, + 'Ccedilla': 722, + 'D': 722, + 'E': 667, + 'Eacute': 667, + 'Ecircumflex': 667, + 'Edieresis': 667, + 'Egrave': 667, + 'Eth': 722, + 'Euro': 556, + 'F': 611, + 'G': 778, + 'H': 722, + 'I': 278, + 'Iacute': 278, + 'Icircumflex': 278, + 'Idieresis': 278, + 'Igrave': 278, + 'J': 556, + 'K': 722, + 'L': 611, + 'Lslash': 611, + 'M': 833, + 'N': 722, + 'Ntilde': 722, + 'O': 778, + 'OE': 1000, + 'Oacute': 778, + 'Ocircumflex': 778, + 'Odieresis': 778, + 'Ograve': 778, + 'Oslash': 778, + 'Otilde': 778, + 'P': 667, + 'Q': 778, + 'R': 722, + 'S': 667, + 'Scaron': 667, + 'T': 611, + 'Thorn': 667, + 'U': 722, + 'Uacute': 722, + 'Ucircumflex': 722, + 'Udieresis': 722, + 'Ugrave': 722, + 'V': 667, + 'W': 944, + 'X': 667, + 'Y': 667, + 'Yacute': 667, + 'Ydieresis': 667, + 'Z': 611, + 'Zcaron': 611, + 'a': 556, + 'aacute': 556, + 'acircumflex': 556, + 'acute': 333, + 'adieresis': 556, + 'ae': 889, + 'agrave': 556, + 'ampersand': 722, + 'aring': 556, + 'asciicircum': 584, + 'asciitilde': 584, + 'asterisk': 389, + 'at': 975, + 'atilde': 556, + 'b': 611, + 'backslash': 278, + 'bar': 280, + 'braceleft': 389, + 'braceright': 389, + 'bracketleft': 333, + 'bracketright': 333, + 'breve': 333, + 'brokenbar': 280, + 'bullet': 350, + 'c': 556, + 'caron': 333, + 'ccedilla': 556, + 'cedilla': 333, + 'cent': 556, + 'circumflex': 333, + 'colon': 333, + 'comma': 278, + 'copyright': 737, + 'currency': 556, + 'd': 611, + 'dagger': 556, + 'daggerdbl': 556, + 'degree': 400, + 'dieresis': 333, + 'divide': 584, + 'dollar': 556, + 'dotaccent': 333, + 'dotlessi': 278, + 'e': 556, + 'eacute': 556, + 'ecircumflex': 556, + 'edieresis': 556, + 'egrave': 556, + 'eight': 556, + 'ellipsis': 1000, + 'emdash': 1000, + 'endash': 556, + 'equal': 584, + 'eth': 611, + 'exclam': 333, + 'exclamdown': 333, + 'f': 333, + 'fi': 611, + 'five': 556, + 'fl': 611, + 'florin': 556, + 'four': 556, + 'fraction': 167, + 'g': 611, + 'germandbls': 611, + 'grave': 333, + 'greater': 584, + 'guillemotleft': 556, + 'guillemotright': 556, + 'guilsinglleft': 333, + 'guilsinglright': 333, + 'h': 611, + 'hungarumlaut': 333, + 'hyphen': 333, + 'i': 278, + 'iacute': 278, + 'icircumflex': 278, + 'idieresis': 278, + 'igrave': 278, + 'j': 278, + 'k': 556, + 'l': 278, + 'less': 584, + 'logicalnot': 584, + 'lslash': 278, + 'm': 889, + 'macron': 333, + 'minus': 584, + 'mu': 611, + 'multiply': 584, + 'n': 611, + 'nine': 556, + 'ntilde': 611, + 'numbersign': 556, + 'o': 611, + 'oacute': 611, + 'ocircumflex': 611, + 'odieresis': 611, + 'oe': 944, + 'ogonek': 333, + 'ograve': 611, + 'one': 556, + 'onehalf': 834, + 'onequarter': 834, + 'onesuperior': 333, + 'ordfeminine': 370, + 'ordmasculine': 365, + 'oslash': 611, + 'otilde': 611, + 'p': 611, + 'paragraph': 556, + 'parenleft': 333, + 'parenright': 333, + 'percent': 889, + 'period': 278, + 'periodcentered': 278, + 'perthousand': 1000, + 'plus': 584, + 'plusminus': 584, + 'q': 611, + 'question': 611, + 'questiondown': 611, + 'quotedbl': 474, + 'quotedblbase': 500, + 'quotedblleft': 500, + 'quotedblright': 500, + 'quoteleft': 278, + 'quoteright': 278, + 'quotesinglbase': 278, + 'quotesingle': 238, + 'r': 389, + 'registered': 737, + 'ring': 333, + 's': 556, + 'scaron': 556, + 'section': 556, + 'semicolon': 333, + 'seven': 556, + 'six': 556, + 'slash': 278, + 'space': 278, + 'sterling': 556, + 't': 333, + 'thorn': 611, + 'three': 556, + 'threequarters': 834, + 'threesuperior': 333, + 'tilde': 333, + 'trademark': 1000, + 'two': 556, + 'twosuperior': 333, + 'u': 611, + 'uacute': 611, + 'ucircumflex': 611, + 'udieresis': 611, + 'ugrave': 611, + 'underscore': 556, + 'v': 556, + 'w': 778, + 'x': 556, + 'y': 556, + 'yacute': 556, + 'ydieresis': 556, + 'yen': 556, + 'z': 500, + 'zcaron': 500, + 'zero': 556} diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_helveticaoblique.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_helveticaoblique.py new file mode 100644 index 0000000000000000000000000000000000000000..10d74db28996b951e6a4205179db9b1626d84bab --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_helveticaoblique.py @@ -0,0 +1,229 @@ +widths = {'A': 667, + 'AE': 1000, + 'Aacute': 667, + 'Acircumflex': 667, + 'Adieresis': 667, + 'Agrave': 667, + 'Aring': 667, + 'Atilde': 667, + 'B': 667, + 'C': 722, + 'Ccedilla': 722, + 'D': 722, + 'E': 667, + 'Eacute': 667, + 'Ecircumflex': 667, + 'Edieresis': 667, + 'Egrave': 667, + 'Eth': 722, + 'Euro': 556, + 'F': 611, + 'G': 778, + 'H': 722, + 'I': 278, + 'Iacute': 278, + 'Icircumflex': 278, + 'Idieresis': 278, + 'Igrave': 278, + 'J': 500, + 'K': 667, + 'L': 556, + 'Lslash': 556, + 'M': 833, + 'N': 722, + 'Ntilde': 722, + 'O': 778, + 'OE': 1000, + 'Oacute': 778, + 'Ocircumflex': 778, + 'Odieresis': 778, + 'Ograve': 778, + 'Oslash': 778, + 'Otilde': 778, + 'P': 667, + 'Q': 778, + 'R': 722, + 'S': 667, + 'Scaron': 667, + 'T': 611, + 'Thorn': 667, + 'U': 722, + 'Uacute': 722, + 'Ucircumflex': 722, + 'Udieresis': 722, + 'Ugrave': 722, + 'V': 667, + 'W': 944, + 'X': 667, + 'Y': 667, + 'Yacute': 667, + 'Ydieresis': 667, + 'Z': 611, + 'Zcaron': 611, + 'a': 556, + 'aacute': 556, + 'acircumflex': 556, + 'acute': 333, + 'adieresis': 556, + 'ae': 889, + 'agrave': 556, + 'ampersand': 667, + 'aring': 556, + 'asciicircum': 469, + 'asciitilde': 584, + 'asterisk': 389, + 'at': 1015, + 'atilde': 556, + 'b': 556, + 'backslash': 278, + 'bar': 260, + 'braceleft': 334, + 'braceright': 334, + 'bracketleft': 278, + 'bracketright': 278, + 'breve': 333, + 'brokenbar': 260, + 'bullet': 350, + 'c': 500, + 'caron': 333, + 'ccedilla': 500, + 'cedilla': 333, + 'cent': 556, + 'circumflex': 333, + 'colon': 278, + 'comma': 278, + 'copyright': 737, + 'currency': 556, + 'd': 556, + 'dagger': 556, + 'daggerdbl': 556, + 'degree': 400, + 'dieresis': 333, + 'divide': 584, + 'dollar': 556, + 'dotaccent': 333, + 'dotlessi': 278, + 'e': 556, + 'eacute': 556, + 'ecircumflex': 556, + 'edieresis': 556, + 'egrave': 556, + 'eight': 556, + 'ellipsis': 1000, + 'emdash': 1000, + 'endash': 556, + 'equal': 584, + 'eth': 556, + 'exclam': 278, + 'exclamdown': 333, + 'f': 278, + 'fi': 500, + 'five': 556, + 'fl': 500, + 'florin': 556, + 'four': 556, + 'fraction': 167, + 'g': 556, + 'germandbls': 611, + 'grave': 333, + 'greater': 584, + 'guillemotleft': 556, + 'guillemotright': 556, + 'guilsinglleft': 333, + 'guilsinglright': 333, + 'h': 556, + 'hungarumlaut': 333, + 'hyphen': 333, + 'i': 222, + 'iacute': 278, + 'icircumflex': 278, + 'idieresis': 278, + 'igrave': 278, + 'j': 222, + 'k': 500, + 'l': 222, + 'less': 584, + 'logicalnot': 584, + 'lslash': 222, + 'm': 833, + 'macron': 333, + 'minus': 584, + 'mu': 556, + 'multiply': 584, + 'n': 556, + 'nine': 556, + 'ntilde': 556, + 'numbersign': 556, + 'o': 556, + 'oacute': 556, + 'ocircumflex': 556, + 'odieresis': 556, + 'oe': 944, + 'ogonek': 333, + 'ograve': 556, + 'one': 556, + 'onehalf': 834, + 'onequarter': 834, + 'onesuperior': 333, + 'ordfeminine': 370, + 'ordmasculine': 365, + 'oslash': 611, + 'otilde': 556, + 'p': 556, + 'paragraph': 537, + 'parenleft': 333, + 'parenright': 333, + 'percent': 889, + 'period': 278, + 'periodcentered': 278, + 'perthousand': 1000, + 'plus': 584, + 'plusminus': 584, + 'q': 556, + 'question': 556, + 'questiondown': 611, + 'quotedbl': 355, + 'quotedblbase': 333, + 'quotedblleft': 333, + 'quotedblright': 333, + 'quoteleft': 222, + 'quoteright': 222, + 'quotesinglbase': 222, + 'quotesingle': 191, + 'r': 333, + 'registered': 737, + 'ring': 333, + 's': 500, + 'scaron': 500, + 'section': 556, + 'semicolon': 278, + 'seven': 556, + 'six': 556, + 'slash': 278, + 'space': 278, + 'sterling': 556, + 't': 278, + 'thorn': 556, + 'three': 556, + 'threequarters': 834, + 'threesuperior': 333, + 'tilde': 333, + 'trademark': 1000, + 'two': 556, + 'twosuperior': 333, + 'u': 556, + 'uacute': 556, + 'ucircumflex': 556, + 'udieresis': 556, + 'ugrave': 556, + 'underscore': 556, + 'v': 500, + 'w': 722, + 'x': 500, + 'y': 500, + 'yacute': 500, + 'ydieresis': 500, + 'yen': 556, + 'z': 500, + 'zcaron': 500, + 'zero': 556} diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_symbol.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_symbol.py new file mode 100644 index 0000000000000000000000000000000000000000..a18f2f693d8bdc1fc4568b42a0468c919860aada --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_symbol.py @@ -0,0 +1,190 @@ +widths = {'Alpha': 722, + 'Beta': 667, + 'Chi': 722, + 'Delta': 612, + 'Epsilon': 611, + 'Eta': 722, + 'Euro': 750, + 'Gamma': 603, + 'Ifraktur': 686, + 'Iota': 333, + 'Kappa': 722, + 'Lambda': 686, + 'Mu': 889, + 'Nu': 722, + 'Omega': 768, + 'Omicron': 722, + 'Phi': 763, + 'Pi': 768, + 'Psi': 795, + 'Rfraktur': 795, + 'Rho': 556, + 'Sigma': 592, + 'Tau': 611, + 'Theta': 741, + 'Upsilon': 690, + 'Upsilon1': 620, + 'Xi': 645, + 'Zeta': 611, + 'aleph': 823, + 'alpha': 631, + 'ampersand': 778, + 'angle': 768, + 'angleleft': 329, + 'angleright': 329, + 'apple': 790, + 'approxequal': 549, + 'arrowboth': 1042, + 'arrowdblboth': 1042, + 'arrowdbldown': 603, + 'arrowdblleft': 987, + 'arrowdblright': 987, + 'arrowdblup': 603, + 'arrowdown': 603, + 'arrowhorizex': 1000, + 'arrowleft': 987, + 'arrowright': 987, + 'arrowup': 603, + 'arrowvertex': 603, + 'asteriskmath': 500, + 'bar': 200, + 'beta': 549, + 'braceex': 494, + 'braceleft': 480, + 'braceleftbt': 494, + 'braceleftmid': 494, + 'bracelefttp': 494, + 'braceright': 480, + 'bracerightbt': 494, + 'bracerightmid': 494, + 'bracerighttp': 494, + 'bracketleft': 333, + 'bracketleftbt': 384, + 'bracketleftex': 384, + 'bracketlefttp': 384, + 'bracketright': 333, + 'bracketrightbt': 384, + 'bracketrightex': 384, + 'bracketrighttp': 384, + 'bullet': 460, + 'carriagereturn': 658, + 'chi': 549, + 'circlemultiply': 768, + 'circleplus': 768, + 'club': 753, + 'colon': 278, + 'comma': 250, + 'congruent': 549, + 'copyrightsans': 790, + 'copyrightserif': 790, + 'degree': 400, + 'delta': 494, + 'diamond': 753, + 'divide': 549, + 'dotmath': 250, + 'eight': 500, + 'element': 713, + 'ellipsis': 1000, + 'emptyset': 823, + 'epsilon': 439, + 'equal': 549, + 'equivalence': 549, + 'eta': 603, + 'exclam': 333, + 'existential': 549, + 'five': 500, + 'florin': 500, + 'four': 500, + 'fraction': 167, + 'gamma': 411, + 'gradient': 713, + 'greater': 549, + 'greaterequal': 549, + 'heart': 753, + 'infinity': 713, + 'integral': 274, + 'integralbt': 686, + 'integralex': 686, + 'integraltp': 686, + 'intersection': 768, + 'iota': 329, + 'kappa': 549, + 'lambda': 549, + 'less': 549, + 'lessequal': 549, + 'logicaland': 603, + 'logicalnot': 713, + 'logicalor': 603, + 'lozenge': 494, + 'minus': 549, + 'minute': 247, + 'mu': 576, + 'multiply': 549, + 'nine': 500, + 'notelement': 713, + 'notequal': 549, + 'notsubset': 713, + 'nu': 521, + 'numbersign': 500, + 'omega': 686, + 'omega1': 713, + 'omicron': 549, + 'one': 500, + 'parenleft': 333, + 'parenleftbt': 384, + 'parenleftex': 384, + 'parenlefttp': 384, + 'parenright': 333, + 'parenrightbt': 384, + 'parenrightex': 384, + 'parenrighttp': 384, + 'partialdiff': 494, + 'percent': 833, + 'period': 250, + 'perpendicular': 658, + 'phi': 521, + 'phi1': 603, + 'pi': 549, + 'plus': 549, + 'plusminus': 549, + 'product': 823, + 'propersubset': 713, + 'propersuperset': 713, + 'proportional': 713, + 'psi': 686, + 'question': 444, + 'radical': 549, + 'radicalex': 500, + 'reflexsubset': 713, + 'reflexsuperset': 713, + 'registersans': 790, + 'registerserif': 790, + 'rho': 549, + 'second': 411, + 'semicolon': 278, + 'seven': 500, + 'sigma': 603, + 'sigma1': 439, + 'similar': 549, + 'six': 500, + 'slash': 278, + 'space': 250, + 'spade': 753, + 'suchthat': 439, + 'summation': 713, + 'tau': 439, + 'therefore': 863, + 'theta': 521, + 'theta1': 631, + 'three': 500, + 'trademarksans': 786, + 'trademarkserif': 890, + 'two': 500, + 'underscore': 500, + 'union': 768, + 'universal': 713, + 'upsilon': 576, + 'weierstrass': 987, + 'xi': 493, + 'zero': 500, + 'zeta': 494} diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_timesbold.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_timesbold.py new file mode 100644 index 0000000000000000000000000000000000000000..97adc79a7432d19b4e461b0d1df8bcaca5213b16 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_timesbold.py @@ -0,0 +1,229 @@ +widths = {'A': 722, + 'AE': 1000, + 'Aacute': 722, + 'Acircumflex': 722, + 'Adieresis': 722, + 'Agrave': 722, + 'Aring': 722, + 'Atilde': 722, + 'B': 667, + 'C': 722, + 'Ccedilla': 722, + 'D': 722, + 'E': 667, + 'Eacute': 667, + 'Ecircumflex': 667, + 'Edieresis': 667, + 'Egrave': 667, + 'Eth': 722, + 'Euro': 500, + 'F': 611, + 'G': 778, + 'H': 778, + 'I': 389, + 'Iacute': 389, + 'Icircumflex': 389, + 'Idieresis': 389, + 'Igrave': 389, + 'J': 500, + 'K': 778, + 'L': 667, + 'Lslash': 667, + 'M': 944, + 'N': 722, + 'Ntilde': 722, + 'O': 778, + 'OE': 1000, + 'Oacute': 778, + 'Ocircumflex': 778, + 'Odieresis': 778, + 'Ograve': 778, + 'Oslash': 778, + 'Otilde': 778, + 'P': 611, + 'Q': 778, + 'R': 722, + 'S': 556, + 'Scaron': 556, + 'T': 667, + 'Thorn': 611, + 'U': 722, + 'Uacute': 722, + 'Ucircumflex': 722, + 'Udieresis': 722, + 'Ugrave': 722, + 'V': 722, + 'W': 1000, + 'X': 722, + 'Y': 722, + 'Yacute': 722, + 'Ydieresis': 722, + 'Z': 667, + 'Zcaron': 667, + 'a': 500, + 'aacute': 500, + 'acircumflex': 500, + 'acute': 333, + 'adieresis': 500, + 'ae': 722, + 'agrave': 500, + 'ampersand': 833, + 'aring': 500, + 'asciicircum': 581, + 'asciitilde': 520, + 'asterisk': 500, + 'at': 930, + 'atilde': 500, + 'b': 556, + 'backslash': 278, + 'bar': 220, + 'braceleft': 394, + 'braceright': 394, + 'bracketleft': 333, + 'bracketright': 333, + 'breve': 333, + 'brokenbar': 220, + 'bullet': 350, + 'c': 444, + 'caron': 333, + 'ccedilla': 444, + 'cedilla': 333, + 'cent': 500, + 'circumflex': 333, + 'colon': 333, + 'comma': 250, + 'copyright': 747, + 'currency': 500, + 'd': 556, + 'dagger': 500, + 'daggerdbl': 500, + 'degree': 400, + 'dieresis': 333, + 'divide': 570, + 'dollar': 500, + 'dotaccent': 333, + 'dotlessi': 278, + 'e': 444, + 'eacute': 444, + 'ecircumflex': 444, + 'edieresis': 444, + 'egrave': 444, + 'eight': 500, + 'ellipsis': 1000, + 'emdash': 1000, + 'endash': 500, + 'equal': 570, + 'eth': 500, + 'exclam': 333, + 'exclamdown': 333, + 'f': 333, + 'fi': 556, + 'five': 500, + 'fl': 556, + 'florin': 500, + 'four': 500, + 'fraction': 167, + 'g': 500, + 'germandbls': 556, + 'grave': 333, + 'greater': 570, + 'guillemotleft': 500, + 'guillemotright': 500, + 'guilsinglleft': 333, + 'guilsinglright': 333, + 'h': 556, + 'hungarumlaut': 333, + 'hyphen': 333, + 'i': 278, + 'iacute': 278, + 'icircumflex': 278, + 'idieresis': 278, + 'igrave': 278, + 'j': 333, + 'k': 556, + 'l': 278, + 'less': 570, + 'logicalnot': 570, + 'lslash': 278, + 'm': 833, + 'macron': 333, + 'minus': 570, + 'mu': 556, + 'multiply': 570, + 'n': 556, + 'nine': 500, + 'ntilde': 556, + 'numbersign': 500, + 'o': 500, + 'oacute': 500, + 'ocircumflex': 500, + 'odieresis': 500, + 'oe': 722, + 'ogonek': 333, + 'ograve': 500, + 'one': 500, + 'onehalf': 750, + 'onequarter': 750, + 'onesuperior': 300, + 'ordfeminine': 300, + 'ordmasculine': 330, + 'oslash': 500, + 'otilde': 500, + 'p': 556, + 'paragraph': 540, + 'parenleft': 333, + 'parenright': 333, + 'percent': 1000, + 'period': 250, + 'periodcentered': 250, + 'perthousand': 1000, + 'plus': 570, + 'plusminus': 570, + 'q': 556, + 'question': 500, + 'questiondown': 500, + 'quotedbl': 555, + 'quotedblbase': 500, + 'quotedblleft': 500, + 'quotedblright': 500, + 'quoteleft': 333, + 'quoteright': 333, + 'quotesinglbase': 333, + 'quotesingle': 278, + 'r': 444, + 'registered': 747, + 'ring': 333, + 's': 389, + 'scaron': 389, + 'section': 500, + 'semicolon': 333, + 'seven': 500, + 'six': 500, + 'slash': 278, + 'space': 250, + 'sterling': 500, + 't': 333, + 'thorn': 556, + 'three': 500, + 'threequarters': 750, + 'threesuperior': 300, + 'tilde': 333, + 'trademark': 1000, + 'two': 500, + 'twosuperior': 300, + 'u': 556, + 'uacute': 556, + 'ucircumflex': 556, + 'udieresis': 556, + 'ugrave': 556, + 'underscore': 500, + 'v': 500, + 'w': 722, + 'x': 500, + 'y': 500, + 'yacute': 500, + 'ydieresis': 500, + 'yen': 500, + 'z': 444, + 'zcaron': 444, + 'zero': 500} diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_timesbolditalic.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_timesbolditalic.py new file mode 100644 index 0000000000000000000000000000000000000000..e7c6be43abf9269fdc1adce400b3cc16dcabd71e --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_timesbolditalic.py @@ -0,0 +1,229 @@ +widths = {'A': 667, + 'AE': 944, + 'Aacute': 667, + 'Acircumflex': 667, + 'Adieresis': 667, + 'Agrave': 667, + 'Aring': 667, + 'Atilde': 667, + 'B': 667, + 'C': 667, + 'Ccedilla': 667, + 'D': 722, + 'E': 667, + 'Eacute': 667, + 'Ecircumflex': 667, + 'Edieresis': 667, + 'Egrave': 667, + 'Eth': 722, + 'Euro': 500, + 'F': 667, + 'G': 722, + 'H': 778, + 'I': 389, + 'Iacute': 389, + 'Icircumflex': 389, + 'Idieresis': 389, + 'Igrave': 389, + 'J': 500, + 'K': 667, + 'L': 611, + 'Lslash': 611, + 'M': 889, + 'N': 722, + 'Ntilde': 722, + 'O': 722, + 'OE': 944, + 'Oacute': 722, + 'Ocircumflex': 722, + 'Odieresis': 722, + 'Ograve': 722, + 'Oslash': 722, + 'Otilde': 722, + 'P': 611, + 'Q': 722, + 'R': 667, + 'S': 556, + 'Scaron': 556, + 'T': 611, + 'Thorn': 611, + 'U': 722, + 'Uacute': 722, + 'Ucircumflex': 722, + 'Udieresis': 722, + 'Ugrave': 722, + 'V': 667, + 'W': 889, + 'X': 667, + 'Y': 611, + 'Yacute': 611, + 'Ydieresis': 611, + 'Z': 611, + 'Zcaron': 611, + 'a': 500, + 'aacute': 500, + 'acircumflex': 500, + 'acute': 333, + 'adieresis': 500, + 'ae': 722, + 'agrave': 500, + 'ampersand': 778, + 'aring': 500, + 'asciicircum': 570, + 'asciitilde': 570, + 'asterisk': 500, + 'at': 832, + 'atilde': 500, + 'b': 500, + 'backslash': 278, + 'bar': 220, + 'braceleft': 348, + 'braceright': 348, + 'bracketleft': 333, + 'bracketright': 333, + 'breve': 333, + 'brokenbar': 220, + 'bullet': 350, + 'c': 444, + 'caron': 333, + 'ccedilla': 444, + 'cedilla': 333, + 'cent': 500, + 'circumflex': 333, + 'colon': 333, + 'comma': 250, + 'copyright': 747, + 'currency': 500, + 'd': 500, + 'dagger': 500, + 'daggerdbl': 500, + 'degree': 400, + 'dieresis': 333, + 'divide': 570, + 'dollar': 500, + 'dotaccent': 333, + 'dotlessi': 278, + 'e': 444, + 'eacute': 444, + 'ecircumflex': 444, + 'edieresis': 444, + 'egrave': 444, + 'eight': 500, + 'ellipsis': 1000, + 'emdash': 1000, + 'endash': 500, + 'equal': 570, + 'eth': 500, + 'exclam': 389, + 'exclamdown': 389, + 'f': 333, + 'fi': 556, + 'five': 500, + 'fl': 556, + 'florin': 500, + 'four': 500, + 'fraction': 167, + 'g': 500, + 'germandbls': 500, + 'grave': 333, + 'greater': 570, + 'guillemotleft': 500, + 'guillemotright': 500, + 'guilsinglleft': 333, + 'guilsinglright': 333, + 'h': 556, + 'hungarumlaut': 333, + 'hyphen': 333, + 'i': 278, + 'iacute': 278, + 'icircumflex': 278, + 'idieresis': 278, + 'igrave': 278, + 'j': 278, + 'k': 500, + 'l': 278, + 'less': 570, + 'logicalnot': 606, + 'lslash': 278, + 'm': 778, + 'macron': 333, + 'minus': 606, + 'mu': 576, + 'multiply': 570, + 'n': 556, + 'nine': 500, + 'ntilde': 556, + 'numbersign': 500, + 'o': 500, + 'oacute': 500, + 'ocircumflex': 500, + 'odieresis': 500, + 'oe': 722, + 'ogonek': 333, + 'ograve': 500, + 'one': 500, + 'onehalf': 750, + 'onequarter': 750, + 'onesuperior': 300, + 'ordfeminine': 266, + 'ordmasculine': 300, + 'oslash': 500, + 'otilde': 500, + 'p': 500, + 'paragraph': 500, + 'parenleft': 333, + 'parenright': 333, + 'percent': 833, + 'period': 250, + 'periodcentered': 250, + 'perthousand': 1000, + 'plus': 570, + 'plusminus': 570, + 'q': 500, + 'question': 500, + 'questiondown': 500, + 'quotedbl': 555, + 'quotedblbase': 500, + 'quotedblleft': 500, + 'quotedblright': 500, + 'quoteleft': 333, + 'quoteright': 333, + 'quotesinglbase': 333, + 'quotesingle': 278, + 'r': 389, + 'registered': 747, + 'ring': 333, + 's': 389, + 'scaron': 389, + 'section': 500, + 'semicolon': 333, + 'seven': 500, + 'six': 500, + 'slash': 278, + 'space': 250, + 'sterling': 500, + 't': 278, + 'thorn': 500, + 'three': 500, + 'threequarters': 750, + 'threesuperior': 300, + 'tilde': 333, + 'trademark': 1000, + 'two': 500, + 'twosuperior': 300, + 'u': 556, + 'uacute': 556, + 'ucircumflex': 556, + 'udieresis': 556, + 'ugrave': 556, + 'underscore': 500, + 'v': 444, + 'w': 667, + 'x': 500, + 'y': 444, + 'yacute': 444, + 'ydieresis': 444, + 'yen': 500, + 'z': 389, + 'zcaron': 389, + 'zero': 500} diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_timesitalic.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_timesitalic.py new file mode 100644 index 0000000000000000000000000000000000000000..77aaa16fb3c888b274e1b5b6e78e96ee47480f13 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_timesitalic.py @@ -0,0 +1,229 @@ +widths = {'A': 611, + 'AE': 889, + 'Aacute': 611, + 'Acircumflex': 611, + 'Adieresis': 611, + 'Agrave': 611, + 'Aring': 611, + 'Atilde': 611, + 'B': 611, + 'C': 667, + 'Ccedilla': 667, + 'D': 722, + 'E': 611, + 'Eacute': 611, + 'Ecircumflex': 611, + 'Edieresis': 611, + 'Egrave': 611, + 'Eth': 722, + 'Euro': 500, + 'F': 611, + 'G': 722, + 'H': 722, + 'I': 333, + 'Iacute': 333, + 'Icircumflex': 333, + 'Idieresis': 333, + 'Igrave': 333, + 'J': 444, + 'K': 667, + 'L': 556, + 'Lslash': 556, + 'M': 833, + 'N': 667, + 'Ntilde': 667, + 'O': 722, + 'OE': 944, + 'Oacute': 722, + 'Ocircumflex': 722, + 'Odieresis': 722, + 'Ograve': 722, + 'Oslash': 722, + 'Otilde': 722, + 'P': 611, + 'Q': 722, + 'R': 611, + 'S': 500, + 'Scaron': 500, + 'T': 556, + 'Thorn': 611, + 'U': 722, + 'Uacute': 722, + 'Ucircumflex': 722, + 'Udieresis': 722, + 'Ugrave': 722, + 'V': 611, + 'W': 833, + 'X': 611, + 'Y': 556, + 'Yacute': 556, + 'Ydieresis': 556, + 'Z': 556, + 'Zcaron': 556, + 'a': 500, + 'aacute': 500, + 'acircumflex': 500, + 'acute': 333, + 'adieresis': 500, + 'ae': 667, + 'agrave': 500, + 'ampersand': 778, + 'aring': 500, + 'asciicircum': 422, + 'asciitilde': 541, + 'asterisk': 500, + 'at': 920, + 'atilde': 500, + 'b': 500, + 'backslash': 278, + 'bar': 275, + 'braceleft': 400, + 'braceright': 400, + 'bracketleft': 389, + 'bracketright': 389, + 'breve': 333, + 'brokenbar': 275, + 'bullet': 350, + 'c': 444, + 'caron': 333, + 'ccedilla': 444, + 'cedilla': 333, + 'cent': 500, + 'circumflex': 333, + 'colon': 333, + 'comma': 250, + 'copyright': 760, + 'currency': 500, + 'd': 500, + 'dagger': 500, + 'daggerdbl': 500, + 'degree': 400, + 'dieresis': 333, + 'divide': 675, + 'dollar': 500, + 'dotaccent': 333, + 'dotlessi': 278, + 'e': 444, + 'eacute': 444, + 'ecircumflex': 444, + 'edieresis': 444, + 'egrave': 444, + 'eight': 500, + 'ellipsis': 889, + 'emdash': 889, + 'endash': 500, + 'equal': 675, + 'eth': 500, + 'exclam': 333, + 'exclamdown': 389, + 'f': 278, + 'fi': 500, + 'five': 500, + 'fl': 500, + 'florin': 500, + 'four': 500, + 'fraction': 167, + 'g': 500, + 'germandbls': 500, + 'grave': 333, + 'greater': 675, + 'guillemotleft': 500, + 'guillemotright': 500, + 'guilsinglleft': 333, + 'guilsinglright': 333, + 'h': 500, + 'hungarumlaut': 333, + 'hyphen': 333, + 'i': 278, + 'iacute': 278, + 'icircumflex': 278, + 'idieresis': 278, + 'igrave': 278, + 'j': 278, + 'k': 444, + 'l': 278, + 'less': 675, + 'logicalnot': 675, + 'lslash': 278, + 'm': 722, + 'macron': 333, + 'minus': 675, + 'mu': 500, + 'multiply': 675, + 'n': 500, + 'nine': 500, + 'ntilde': 500, + 'numbersign': 500, + 'o': 500, + 'oacute': 500, + 'ocircumflex': 500, + 'odieresis': 500, + 'oe': 667, + 'ogonek': 333, + 'ograve': 500, + 'one': 500, + 'onehalf': 750, + 'onequarter': 750, + 'onesuperior': 300, + 'ordfeminine': 276, + 'ordmasculine': 310, + 'oslash': 500, + 'otilde': 500, + 'p': 500, + 'paragraph': 523, + 'parenleft': 333, + 'parenright': 333, + 'percent': 833, + 'period': 250, + 'periodcentered': 250, + 'perthousand': 1000, + 'plus': 675, + 'plusminus': 675, + 'q': 500, + 'question': 500, + 'questiondown': 500, + 'quotedbl': 420, + 'quotedblbase': 556, + 'quotedblleft': 556, + 'quotedblright': 556, + 'quoteleft': 333, + 'quoteright': 333, + 'quotesinglbase': 333, + 'quotesingle': 214, + 'r': 389, + 'registered': 760, + 'ring': 333, + 's': 389, + 'scaron': 389, + 'section': 500, + 'semicolon': 333, + 'seven': 500, + 'six': 500, + 'slash': 278, + 'space': 250, + 'sterling': 500, + 't': 278, + 'thorn': 500, + 'three': 500, + 'threequarters': 750, + 'threesuperior': 300, + 'tilde': 333, + 'trademark': 980, + 'two': 500, + 'twosuperior': 300, + 'u': 500, + 'uacute': 500, + 'ucircumflex': 500, + 'udieresis': 500, + 'ugrave': 500, + 'underscore': 500, + 'v': 444, + 'w': 667, + 'x': 444, + 'y': 444, + 'yacute': 444, + 'ydieresis': 444, + 'yen': 500, + 'z': 389, + 'zcaron': 389, + 'zero': 500} diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_timesroman.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_timesroman.py new file mode 100644 index 0000000000000000000000000000000000000000..82d0347c8547e891c91c53e82c452ccde808baed --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_timesroman.py @@ -0,0 +1,229 @@ +widths = {'A': 722, + 'AE': 889, + 'Aacute': 722, + 'Acircumflex': 722, + 'Adieresis': 722, + 'Agrave': 722, + 'Aring': 722, + 'Atilde': 722, + 'B': 667, + 'C': 667, + 'Ccedilla': 667, + 'D': 722, + 'E': 611, + 'Eacute': 611, + 'Ecircumflex': 611, + 'Edieresis': 611, + 'Egrave': 611, + 'Eth': 722, + 'Euro': 500, + 'F': 556, + 'G': 722, + 'H': 722, + 'I': 333, + 'Iacute': 333, + 'Icircumflex': 333, + 'Idieresis': 333, + 'Igrave': 333, + 'J': 389, + 'K': 722, + 'L': 611, + 'Lslash': 611, + 'M': 889, + 'N': 722, + 'Ntilde': 722, + 'O': 722, + 'OE': 889, + 'Oacute': 722, + 'Ocircumflex': 722, + 'Odieresis': 722, + 'Ograve': 722, + 'Oslash': 722, + 'Otilde': 722, + 'P': 556, + 'Q': 722, + 'R': 667, + 'S': 556, + 'Scaron': 556, + 'T': 611, + 'Thorn': 556, + 'U': 722, + 'Uacute': 722, + 'Ucircumflex': 722, + 'Udieresis': 722, + 'Ugrave': 722, + 'V': 722, + 'W': 944, + 'X': 722, + 'Y': 722, + 'Yacute': 722, + 'Ydieresis': 722, + 'Z': 611, + 'Zcaron': 611, + 'a': 444, + 'aacute': 444, + 'acircumflex': 444, + 'acute': 333, + 'adieresis': 444, + 'ae': 667, + 'agrave': 444, + 'ampersand': 778, + 'aring': 444, + 'asciicircum': 469, + 'asciitilde': 541, + 'asterisk': 500, + 'at': 921, + 'atilde': 444, + 'b': 500, + 'backslash': 278, + 'bar': 200, + 'braceleft': 480, + 'braceright': 480, + 'bracketleft': 333, + 'bracketright': 333, + 'breve': 333, + 'brokenbar': 200, + 'bullet': 350, + 'c': 444, + 'caron': 333, + 'ccedilla': 444, + 'cedilla': 333, + 'cent': 500, + 'circumflex': 333, + 'colon': 278, + 'comma': 250, + 'copyright': 760, + 'currency': 500, + 'd': 500, + 'dagger': 500, + 'daggerdbl': 500, + 'degree': 400, + 'dieresis': 333, + 'divide': 564, + 'dollar': 500, + 'dotaccent': 333, + 'dotlessi': 278, + 'e': 444, + 'eacute': 444, + 'ecircumflex': 444, + 'edieresis': 444, + 'egrave': 444, + 'eight': 500, + 'ellipsis': 1000, + 'emdash': 1000, + 'endash': 500, + 'equal': 564, + 'eth': 500, + 'exclam': 333, + 'exclamdown': 333, + 'f': 333, + 'fi': 556, + 'five': 500, + 'fl': 556, + 'florin': 500, + 'four': 500, + 'fraction': 167, + 'g': 500, + 'germandbls': 500, + 'grave': 333, + 'greater': 564, + 'guillemotleft': 500, + 'guillemotright': 500, + 'guilsinglleft': 333, + 'guilsinglright': 333, + 'h': 500, + 'hungarumlaut': 333, + 'hyphen': 333, + 'i': 278, + 'iacute': 278, + 'icircumflex': 278, + 'idieresis': 278, + 'igrave': 278, + 'j': 278, + 'k': 500, + 'l': 278, + 'less': 564, + 'logicalnot': 564, + 'lslash': 278, + 'm': 778, + 'macron': 333, + 'minus': 564, + 'mu': 500, + 'multiply': 564, + 'n': 500, + 'nine': 500, + 'ntilde': 500, + 'numbersign': 500, + 'o': 500, + 'oacute': 500, + 'ocircumflex': 500, + 'odieresis': 500, + 'oe': 722, + 'ogonek': 333, + 'ograve': 500, + 'one': 500, + 'onehalf': 750, + 'onequarter': 750, + 'onesuperior': 300, + 'ordfeminine': 276, + 'ordmasculine': 310, + 'oslash': 500, + 'otilde': 500, + 'p': 500, + 'paragraph': 453, + 'parenleft': 333, + 'parenright': 333, + 'percent': 833, + 'period': 250, + 'periodcentered': 250, + 'perthousand': 1000, + 'plus': 564, + 'plusminus': 564, + 'q': 500, + 'question': 444, + 'questiondown': 444, + 'quotedbl': 408, + 'quotedblbase': 444, + 'quotedblleft': 444, + 'quotedblright': 444, + 'quoteleft': 333, + 'quoteright': 333, + 'quotesinglbase': 333, + 'quotesingle': 180, + 'r': 333, + 'registered': 760, + 'ring': 333, + 's': 389, + 'scaron': 389, + 'section': 500, + 'semicolon': 278, + 'seven': 500, + 'six': 500, + 'slash': 278, + 'space': 250, + 'sterling': 500, + 't': 278, + 'thorn': 500, + 'three': 500, + 'threequarters': 750, + 'threesuperior': 300, + 'tilde': 333, + 'trademark': 980, + 'two': 500, + 'twosuperior': 300, + 'u': 500, + 'uacute': 500, + 'ucircumflex': 500, + 'udieresis': 500, + 'ugrave': 500, + 'underscore': 500, + 'v': 500, + 'w': 722, + 'x': 500, + 'y': 500, + 'yacute': 500, + 'ydieresis': 500, + 'yen': 500, + 'z': 444, + 'zcaron': 444, + 'zero': 500} diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_zapfdingbats.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_zapfdingbats.py new file mode 100644 index 0000000000000000000000000000000000000000..5fc9f7ff8d2c980c7bca1814db2f3e7079f476ee --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_fontdata_widths_zapfdingbats.py @@ -0,0 +1,202 @@ +widths = {'a1': 974, + 'a10': 692, + 'a100': 668, + 'a101': 732, + 'a102': 544, + 'a103': 544, + 'a104': 910, + 'a105': 911, + 'a106': 667, + 'a107': 760, + 'a108': 760, + 'a109': 626, + 'a11': 960, + 'a110': 694, + 'a111': 595, + 'a112': 776, + 'a117': 690, + 'a118': 791, + 'a119': 790, + 'a12': 939, + 'a120': 788, + 'a121': 788, + 'a122': 788, + 'a123': 788, + 'a124': 788, + 'a125': 788, + 'a126': 788, + 'a127': 788, + 'a128': 788, + 'a129': 788, + 'a13': 549, + 'a130': 788, + 'a131': 788, + 'a132': 788, + 'a133': 788, + 'a134': 788, + 'a135': 788, + 'a136': 788, + 'a137': 788, + 'a138': 788, + 'a139': 788, + 'a14': 855, + 'a140': 788, + 'a141': 788, + 'a142': 788, + 'a143': 788, + 'a144': 788, + 'a145': 788, + 'a146': 788, + 'a147': 788, + 'a148': 788, + 'a149': 788, + 'a15': 911, + 'a150': 788, + 'a151': 788, + 'a152': 788, + 'a153': 788, + 'a154': 788, + 'a155': 788, + 'a156': 788, + 'a157': 788, + 'a158': 788, + 'a159': 788, + 'a16': 933, + 'a160': 894, + 'a161': 838, + 'a162': 924, + 'a163': 1016, + 'a164': 458, + 'a165': 924, + 'a166': 918, + 'a167': 927, + 'a168': 928, + 'a169': 928, + 'a17': 945, + 'a170': 834, + 'a171': 873, + 'a172': 828, + 'a173': 924, + 'a174': 917, + 'a175': 930, + 'a176': 931, + 'a177': 463, + 'a178': 883, + 'a179': 836, + 'a18': 974, + 'a180': 867, + 'a181': 696, + 'a182': 874, + 'a183': 760, + 'a184': 946, + 'a185': 865, + 'a186': 967, + 'a187': 831, + 'a188': 873, + 'a189': 927, + 'a19': 755, + 'a190': 970, + 'a191': 918, + 'a192': 748, + 'a193': 836, + 'a194': 771, + 'a195': 888, + 'a196': 748, + 'a197': 771, + 'a198': 888, + 'a199': 867, + 'a2': 961, + 'a20': 846, + 'a200': 696, + 'a201': 874, + 'a202': 974, + 'a203': 762, + 'a204': 759, + 'a205': 509, + 'a206': 410, + 'a21': 762, + 'a22': 761, + 'a23': 571, + 'a24': 677, + 'a25': 763, + 'a26': 760, + 'a27': 759, + 'a28': 754, + 'a29': 786, + 'a3': 980, + 'a30': 788, + 'a31': 788, + 'a32': 790, + 'a33': 793, + 'a34': 794, + 'a35': 816, + 'a36': 823, + 'a37': 789, + 'a38': 841, + 'a39': 823, + 'a4': 719, + 'a40': 833, + 'a41': 816, + 'a42': 831, + 'a43': 923, + 'a44': 744, + 'a45': 723, + 'a46': 749, + 'a47': 790, + 'a48': 792, + 'a49': 695, + 'a5': 789, + 'a50': 776, + 'a51': 768, + 'a52': 792, + 'a53': 759, + 'a54': 707, + 'a55': 708, + 'a56': 682, + 'a57': 701, + 'a58': 826, + 'a59': 815, + 'a6': 494, + 'a60': 789, + 'a61': 789, + 'a62': 707, + 'a63': 687, + 'a64': 696, + 'a65': 689, + 'a66': 786, + 'a67': 787, + 'a68': 713, + 'a69': 791, + 'a7': 552, + 'a70': 785, + 'a71': 791, + 'a72': 873, + 'a73': 761, + 'a74': 762, + 'a75': 759, + 'a76': 892, + 'a77': 892, + 'a78': 788, + 'a79': 784, + 'a8': 537, + 'a81': 438, + 'a82': 138, + 'a83': 277, + 'a84': 415, + 'a85': 509, + 'a86': 410, + 'a87': 234, + 'a88': 234, + 'a89': 390, + 'a9': 577, + 'a90': 390, + 'a91': 276, + 'a92': 276, + 'a93': 317, + 'a94': 317, + 'a95': 334, + 'a96': 334, + 'a97': 392, + 'a98': 392, + 'a99': 668, + 'space': 278} diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_glyphlist.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_glyphlist.py new file mode 100644 index 0000000000000000000000000000000000000000..9fe0b3cbac061b5e2e7031d0010af5d7750d91b1 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/_glyphlist.py @@ -0,0 +1,4330 @@ +#see https://github.com/adobe-type-tools/agl-aglfn +# ----------------------------------------------------------- +# Copyright 2002-2019 Adobe (http://www.adobe.com/). +# +# Redistribution and use in source and binary forms, with or +# without modification, are permitted provided that the +# following conditions are met: +# +# Redistributions of source code must retain the above +# copyright notice, this list of conditions and the following +# disclaimer. +# +# Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials +# provided with the distribution. +# +# Neither the name of Adobe nor the names of its contributors +# may be used to endorse or promote products derived from this +# software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND +# CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ----------------------------------------------------------- +# Name: Adobe Glyph List +# Table version: 2.0 +# Date: September 20, 2002 +# URL: https://github.com/adobe-type-tools/agl-aglfn +# +# Format: two semicolon-delimited fields: +# (1) glyph name--upper/lowercase letters and digits +# (2) Unicode scalar value--four uppercase hexadecimal digits +# +# END +_glyphname2unicode = { + 'A': 0x0041, + 'AE': 0x00C6, + 'AEacute': 0x01FC, + 'AEmacron': 0x01E2, + 'AEsmall': 0xF7E6, + 'Aacute': 0x00C1, + 'Aacutesmall': 0xF7E1, + 'Abreve': 0x0102, + 'Abreveacute': 0x1EAE, + 'Abrevecyrillic': 0x04D0, + 'Abrevedotbelow': 0x1EB6, + 'Abrevegrave': 0x1EB0, + 'Abrevehookabove': 0x1EB2, + 'Abrevetilde': 0x1EB4, + 'Acaron': 0x01CD, + 'Acircle': 0x24B6, + 'Acircumflex': 0x00C2, + 'Acircumflexacute': 0x1EA4, + 'Acircumflexdotbelow': 0x1EAC, + 'Acircumflexgrave': 0x1EA6, + 'Acircumflexhookabove': 0x1EA8, + 'Acircumflexsmall': 0xF7E2, + 'Acircumflextilde': 0x1EAA, + 'Acute': 0xF6C9, + 'Acutesmall': 0xF7B4, + 'Acyrillic': 0x0410, + 'Adblgrave': 0x0200, + 'Adieresis': 0x00C4, + 'Adieresiscyrillic': 0x04D2, + 'Adieresismacron': 0x01DE, + 'Adieresissmall': 0xF7E4, + 'Adotbelow': 0x1EA0, + 'Adotmacron': 0x01E0, + 'Agrave': 0x00C0, + 'Agravesmall': 0xF7E0, + 'Ahookabove': 0x1EA2, + 'Aiecyrillic': 0x04D4, + 'Ainvertedbreve': 0x0202, + 'Alpha': 0x0391, + 'Alphatonos': 0x0386, + 'Amacron': 0x0100, + 'Amonospace': 0xFF21, + 'Aogonek': 0x0104, + 'Aring': 0x00C5, + 'Aringacute': 0x01FA, + 'Aringbelow': 0x1E00, + 'Aringsmall': 0xF7E5, + 'Asmall': 0xF761, + 'Atilde': 0x00C3, + 'Atildesmall': 0xF7E3, + 'Aybarmenian': 0x0531, + 'B': 0x0042, + 'Bcircle': 0x24B7, + 'Bdotaccent': 0x1E02, + 'Bdotbelow': 0x1E04, + 'Becyrillic': 0x0411, + 'Benarmenian': 0x0532, + 'Beta': 0x0392, + 'Bhook': 0x0181, + 'Blinebelow': 0x1E06, + 'Bmonospace': 0xFF22, + 'Brevesmall': 0xF6F4, + 'Bsmall': 0xF762, + 'Btopbar': 0x0182, + 'C': 0x0043, + 'Caarmenian': 0x053E, + 'Cacute': 0x0106, + 'Caron': 0xF6CA, + 'Caronsmall': 0xF6F5, + 'Ccaron': 0x010C, + 'Ccedilla': 0x00C7, + 'Ccedillaacute': 0x1E08, + 'Ccedillasmall': 0xF7E7, + 'Ccircle': 0x24B8, + 'Ccircumflex': 0x0108, + 'Cdot': 0x010A, + 'Cdotaccent': 0x010A, + 'Cedillasmall': 0xF7B8, + 'Chaarmenian': 0x0549, + 'Cheabkhasiancyrillic': 0x04BC, + 'Checyrillic': 0x0427, + 'Chedescenderabkhasiancyrillic': 0x04BE, + 'Chedescendercyrillic': 0x04B6, + 'Chedieresiscyrillic': 0x04F4, + 'Cheharmenian': 0x0543, + 'Chekhakassiancyrillic': 0x04CB, + 'Cheverticalstrokecyrillic': 0x04B8, + 'Chi': 0x03A7, + 'Chook': 0x0187, + 'Circumflexsmall': 0xF6F6, + 'Cmonospace': 0xFF23, + 'Coarmenian': 0x0551, + 'Csmall': 0xF763, + 'D': 0x0044, + 'DZ': 0x01F1, + 'DZcaron': 0x01C4, + 'Daarmenian': 0x0534, + 'Dafrican': 0x0189, + 'Dcaron': 0x010E, + 'Dcedilla': 0x1E10, + 'Dcircle': 0x24B9, + 'Dcircumflexbelow': 0x1E12, + 'Dcroat': 0x0110, + 'Ddotaccent': 0x1E0A, + 'Ddotbelow': 0x1E0C, + 'Decyrillic': 0x0414, + 'Deicoptic': 0x03EE, + 'Delta': 0x2206, + 'Deltagreek': 0x0394, + 'Dhook': 0x018A, + 'Dieresis': 0xF6CB, + 'DieresisAcute': 0xF6CC, + 'DieresisGrave': 0xF6CD, + 'Dieresissmall': 0xF7A8, + 'Digammagreek': 0x03DC, + 'Djecyrillic': 0x0402, + 'Dlinebelow': 0x1E0E, + 'Dmonospace': 0xFF24, + 'Dotaccentsmall': 0xF6F7, + 'Dslash': 0x0110, + 'Dsmall': 0xF764, + 'Dtopbar': 0x018B, + 'Dz': 0x01F2, + 'Dzcaron': 0x01C5, + 'Dzeabkhasiancyrillic': 0x04E0, + 'Dzecyrillic': 0x0405, + 'Dzhecyrillic': 0x040F, + 'E': 0x0045, + 'Eacute': 0x00C9, + 'Eacutesmall': 0xF7E9, + 'Ebreve': 0x0114, + 'Ecaron': 0x011A, + 'Ecedillabreve': 0x1E1C, + 'Echarmenian': 0x0535, + 'Ecircle': 0x24BA, + 'Ecircumflex': 0x00CA, + 'Ecircumflexacute': 0x1EBE, + 'Ecircumflexbelow': 0x1E18, + 'Ecircumflexdotbelow': 0x1EC6, + 'Ecircumflexgrave': 0x1EC0, + 'Ecircumflexhookabove': 0x1EC2, + 'Ecircumflexsmall': 0xF7EA, + 'Ecircumflextilde': 0x1EC4, + 'Ecyrillic': 0x0404, + 'Edblgrave': 0x0204, + 'Edieresis': 0x00CB, + 'Edieresissmall': 0xF7EB, + 'Edot': 0x0116, + 'Edotaccent': 0x0116, + 'Edotbelow': 0x1EB8, + 'Efcyrillic': 0x0424, + 'Egrave': 0x00C8, + 'Egravesmall': 0xF7E8, + 'Eharmenian': 0x0537, + 'Ehookabove': 0x1EBA, + 'Eightroman': 0x2167, + 'Einvertedbreve': 0x0206, + 'Eiotifiedcyrillic': 0x0464, + 'Elcyrillic': 0x041B, + 'Elevenroman': 0x216A, + 'Emacron': 0x0112, + 'Emacronacute': 0x1E16, + 'Emacrongrave': 0x1E14, + 'Emcyrillic': 0x041C, + 'Emonospace': 0xFF25, + 'Encyrillic': 0x041D, + 'Endescendercyrillic': 0x04A2, + 'Eng': 0x014A, + 'Enghecyrillic': 0x04A4, + 'Enhookcyrillic': 0x04C7, + 'Eogonek': 0x0118, + 'Eopen': 0x0190, + 'Epsilon': 0x0395, + 'Epsilontonos': 0x0388, + 'Ercyrillic': 0x0420, + 'Ereversed': 0x018E, + 'Ereversedcyrillic': 0x042D, + 'Escyrillic': 0x0421, + 'Esdescendercyrillic': 0x04AA, + 'Esh': 0x01A9, + 'Esmall': 0xF765, + 'Eta': 0x0397, + 'Etarmenian': 0x0538, + 'Etatonos': 0x0389, + 'Eth': 0x00D0, + 'Ethsmall': 0xF7F0, + 'Etilde': 0x1EBC, + 'Etildebelow': 0x1E1A, + 'Euro': 0x20AC, + 'Ezh': 0x01B7, + 'Ezhcaron': 0x01EE, + 'Ezhreversed': 0x01B8, + 'F': 0x0046, + 'Fcircle': 0x24BB, + 'Fdotaccent': 0x1E1E, + 'Feharmenian': 0x0556, + 'Feicoptic': 0x03E4, + 'Fhook': 0x0191, + 'Fitacyrillic': 0x0472, + 'Fiveroman': 0x2164, + 'Fmonospace': 0xFF26, + 'Fourroman': 0x2163, + 'Fsmall': 0xF766, + 'G': 0x0047, + 'GBsquare': 0x3387, + 'Gacute': 0x01F4, + 'Gamma': 0x0393, + 'Gammaafrican': 0x0194, + 'Gangiacoptic': 0x03EA, + 'Gbreve': 0x011E, + 'Gcaron': 0x01E6, + 'Gcedilla': 0x0122, + 'Gcircle': 0x24BC, + 'Gcircumflex': 0x011C, + 'Gcommaaccent': 0x0122, + 'Gdot': 0x0120, + 'Gdotaccent': 0x0120, + 'Gecyrillic': 0x0413, + 'Ghadarmenian': 0x0542, + 'Ghemiddlehookcyrillic': 0x0494, + 'Ghestrokecyrillic': 0x0492, + 'Gheupturncyrillic': 0x0490, + 'Ghook': 0x0193, + 'Gimarmenian': 0x0533, + 'Gjecyrillic': 0x0403, + 'Gmacron': 0x1E20, + 'Gmonospace': 0xFF27, + 'Grave': 0xF6CE, + 'Gravesmall': 0xF760, + 'Gsmall': 0xF767, + 'Gsmallhook': 0x029B, + 'Gstroke': 0x01E4, + 'H': 0x0048, + 'H18533': 0x25CF, + 'H18543': 0x25AA, + 'H18551': 0x25AB, + 'H22073': 0x25A1, + 'HPsquare': 0x33CB, + 'Haabkhasiancyrillic': 0x04A8, + 'Hadescendercyrillic': 0x04B2, + 'Hardsigncyrillic': 0x042A, + 'Hbar': 0x0126, + 'Hbrevebelow': 0x1E2A, + 'Hcedilla': 0x1E28, + 'Hcircle': 0x24BD, + 'Hcircumflex': 0x0124, + 'Hdieresis': 0x1E26, + 'Hdotaccent': 0x1E22, + 'Hdotbelow': 0x1E24, + 'Hmonospace': 0xFF28, + 'Hoarmenian': 0x0540, + 'Horicoptic': 0x03E8, + 'Hsmall': 0xF768, + 'Hungarumlaut': 0xF6CF, + 'Hungarumlautsmall': 0xF6F8, + 'Hzsquare': 0x3390, + 'I': 0x0049, + 'IAcyrillic': 0x042F, + 'IJ': 0x0132, + 'IUcyrillic': 0x042E, + 'Iacute': 0x00CD, + 'Iacutesmall': 0xF7ED, + 'Ibreve': 0x012C, + 'Icaron': 0x01CF, + 'Icircle': 0x24BE, + 'Icircumflex': 0x00CE, + 'Icircumflexsmall': 0xF7EE, + 'Icyrillic': 0x0406, + 'Idblgrave': 0x0208, + 'Idieresis': 0x00CF, + 'Idieresisacute': 0x1E2E, + 'Idieresiscyrillic': 0x04E4, + 'Idieresissmall': 0xF7EF, + 'Idot': 0x0130, + 'Idotaccent': 0x0130, + 'Idotbelow': 0x1ECA, + 'Iebrevecyrillic': 0x04D6, + 'Iecyrillic': 0x0415, + 'Ifraktur': 0x2111, + 'Igrave': 0x00CC, + 'Igravesmall': 0xF7EC, + 'Ihookabove': 0x1EC8, + 'Iicyrillic': 0x0418, + 'Iinvertedbreve': 0x020A, + 'Iishortcyrillic': 0x0419, + 'Imacron': 0x012A, + 'Imacroncyrillic': 0x04E2, + 'Imonospace': 0xFF29, + 'Iniarmenian': 0x053B, + 'Iocyrillic': 0x0401, + 'Iogonek': 0x012E, + 'Iota': 0x0399, + 'Iotaafrican': 0x0196, + 'Iotadieresis': 0x03AA, + 'Iotatonos': 0x038A, + 'Ismall': 0xF769, + 'Istroke': 0x0197, + 'Itilde': 0x0128, + 'Itildebelow': 0x1E2C, + 'Izhitsacyrillic': 0x0474, + 'Izhitsadblgravecyrillic': 0x0476, + 'J': 0x004A, + 'Jaarmenian': 0x0541, + 'Jcircle': 0x24BF, + 'Jcircumflex': 0x0134, + 'Jecyrillic': 0x0408, + 'Jheharmenian': 0x054B, + 'Jmonospace': 0xFF2A, + 'Jsmall': 0xF76A, + 'K': 0x004B, + 'KBsquare': 0x3385, + 'KKsquare': 0x33CD, + 'Kabashkircyrillic': 0x04A0, + 'Kacute': 0x1E30, + 'Kacyrillic': 0x041A, + 'Kadescendercyrillic': 0x049A, + 'Kahookcyrillic': 0x04C3, + 'Kappa': 0x039A, + 'Kastrokecyrillic': 0x049E, + 'Kaverticalstrokecyrillic': 0x049C, + 'Kcaron': 0x01E8, + 'Kcedilla': 0x0136, + 'Kcircle': 0x24C0, + 'Kcommaaccent': 0x0136, + 'Kdotbelow': 0x1E32, + 'Keharmenian': 0x0554, + 'Kenarmenian': 0x053F, + 'Khacyrillic': 0x0425, + 'Kheicoptic': 0x03E6, + 'Khook': 0x0198, + 'Kjecyrillic': 0x040C, + 'Klinebelow': 0x1E34, + 'Kmonospace': 0xFF2B, + 'Koppacyrillic': 0x0480, + 'Koppagreek': 0x03DE, + 'Ksicyrillic': 0x046E, + 'Ksmall': 0xF76B, + 'L': 0x004C, + 'LJ': 0x01C7, + 'LL': 0xF6BF, + 'Lacute': 0x0139, + 'Lambda': 0x039B, + 'Lcaron': 0x013D, + 'Lcedilla': 0x013B, + 'Lcircle': 0x24C1, + 'Lcircumflexbelow': 0x1E3C, + 'Lcommaaccent': 0x013B, + 'Ldot': 0x013F, + 'Ldotaccent': 0x013F, + 'Ldotbelow': 0x1E36, + 'Ldotbelowmacron': 0x1E38, + 'Liwnarmenian': 0x053C, + 'Lj': 0x01C8, + 'Ljecyrillic': 0x0409, + 'Llinebelow': 0x1E3A, + 'Lmonospace': 0xFF2C, + 'Lslash': 0x0141, + 'Lslashsmall': 0xF6F9, + 'Lsmall': 0xF76C, + 'M': 0x004D, + 'MBsquare': 0x3386, + 'Macron': 0xF6D0, + 'Macronsmall': 0xF7AF, + 'Macute': 0x1E3E, + 'Mcircle': 0x24C2, + 'Mdotaccent': 0x1E40, + 'Mdotbelow': 0x1E42, + 'Menarmenian': 0x0544, + 'Mmonospace': 0xFF2D, + 'Msmall': 0xF76D, + 'Mturned': 0x019C, + 'Mu': 0x039C, + 'N': 0x004E, + 'NJ': 0x01CA, + 'Nacute': 0x0143, + 'Ncaron': 0x0147, + 'Ncedilla': 0x0145, + 'Ncircle': 0x24C3, + 'Ncircumflexbelow': 0x1E4A, + 'Ncommaaccent': 0x0145, + 'Ndotaccent': 0x1E44, + 'Ndotbelow': 0x1E46, + 'Nhookleft': 0x019D, + 'Nineroman': 0x2168, + 'Nj': 0x01CB, + 'Njecyrillic': 0x040A, + 'Nlinebelow': 0x1E48, + 'Nmonospace': 0xFF2E, + 'Nowarmenian': 0x0546, + 'Nsmall': 0xF76E, + 'Ntilde': 0x00D1, + 'Ntildesmall': 0xF7F1, + 'Nu': 0x039D, + 'O': 0x004F, + 'OE': 0x0152, + 'OEsmall': 0xF6FA, + 'Oacute': 0x00D3, + 'Oacutesmall': 0xF7F3, + 'Obarredcyrillic': 0x04E8, + 'Obarreddieresiscyrillic': 0x04EA, + 'Obreve': 0x014E, + 'Ocaron': 0x01D1, + 'Ocenteredtilde': 0x019F, + 'Ocircle': 0x24C4, + 'Ocircumflex': 0x00D4, + 'Ocircumflexacute': 0x1ED0, + 'Ocircumflexdotbelow': 0x1ED8, + 'Ocircumflexgrave': 0x1ED2, + 'Ocircumflexhookabove': 0x1ED4, + 'Ocircumflexsmall': 0xF7F4, + 'Ocircumflextilde': 0x1ED6, + 'Ocyrillic': 0x041E, + 'Odblacute': 0x0150, + 'Odblgrave': 0x020C, + 'Odieresis': 0x00D6, + 'Odieresiscyrillic': 0x04E6, + 'Odieresissmall': 0xF7F6, + 'Odotbelow': 0x1ECC, + 'Ogoneksmall': 0xF6FB, + 'Ograve': 0x00D2, + 'Ogravesmall': 0xF7F2, + 'Oharmenian': 0x0555, + 'Ohm': 0x2126, + 'Ohookabove': 0x1ECE, + 'Ohorn': 0x01A0, + 'Ohornacute': 0x1EDA, + 'Ohorndotbelow': 0x1EE2, + 'Ohorngrave': 0x1EDC, + 'Ohornhookabove': 0x1EDE, + 'Ohorntilde': 0x1EE0, + 'Ohungarumlaut': 0x0150, + 'Oi': 0x01A2, + 'Oinvertedbreve': 0x020E, + 'Omacron': 0x014C, + 'Omacronacute': 0x1E52, + 'Omacrongrave': 0x1E50, + 'Omega': 0x2126, + 'Omegacyrillic': 0x0460, + 'Omegagreek': 0x03A9, + 'Omegaroundcyrillic': 0x047A, + 'Omegatitlocyrillic': 0x047C, + 'Omegatonos': 0x038F, + 'Omicron': 0x039F, + 'Omicrontonos': 0x038C, + 'Omonospace': 0xFF2F, + 'Oneroman': 0x2160, + 'Oogonek': 0x01EA, + 'Oogonekmacron': 0x01EC, + 'Oopen': 0x0186, + 'Oslash': 0x00D8, + 'Oslashacute': 0x01FE, + 'Oslashsmall': 0xF7F8, + 'Osmall': 0xF76F, + 'Ostrokeacute': 0x01FE, + 'Otcyrillic': 0x047E, + 'Otilde': 0x00D5, + 'Otildeacute': 0x1E4C, + 'Otildedieresis': 0x1E4E, + 'Otildesmall': 0xF7F5, + 'P': 0x0050, + 'Pacute': 0x1E54, + 'Pcircle': 0x24C5, + 'Pdotaccent': 0x1E56, + 'Pecyrillic': 0x041F, + 'Peharmenian': 0x054A, + 'Pemiddlehookcyrillic': 0x04A6, + 'Phi': 0x03A6, + 'Phook': 0x01A4, + 'Pi': 0x03A0, + 'Piwrarmenian': 0x0553, + 'Pmonospace': 0xFF30, + 'Psi': 0x03A8, + 'Psicyrillic': 0x0470, + 'Psmall': 0xF770, + 'Q': 0x0051, + 'Qcircle': 0x24C6, + 'Qmonospace': 0xFF31, + 'Qsmall': 0xF771, + 'R': 0x0052, + 'Raarmenian': 0x054C, + 'Racute': 0x0154, + 'Rcaron': 0x0158, + 'Rcedilla': 0x0156, + 'Rcircle': 0x24C7, + 'Rcommaaccent': 0x0156, + 'Rdblgrave': 0x0210, + 'Rdotaccent': 0x1E58, + 'Rdotbelow': 0x1E5A, + 'Rdotbelowmacron': 0x1E5C, + 'Reharmenian': 0x0550, + 'Rfraktur': 0x211C, + 'Rho': 0x03A1, + 'Ringsmall': 0xF6FC, + 'Rinvertedbreve': 0x0212, + 'Rlinebelow': 0x1E5E, + 'Rmonospace': 0xFF32, + 'Rsmall': 0xF772, + 'Rsmallinverted': 0x0281, + 'Rsmallinvertedsuperior': 0x02B6, + 'S': 0x0053, + 'SF010000': 0x250C, + 'SF020000': 0x2514, + 'SF030000': 0x2510, + 'SF040000': 0x2518, + 'SF050000': 0x253C, + 'SF060000': 0x252C, + 'SF070000': 0x2534, + 'SF080000': 0x251C, + 'SF090000': 0x2524, + 'SF100000': 0x2500, + 'SF110000': 0x2502, + 'SF190000': 0x2561, + 'SF200000': 0x2562, + 'SF210000': 0x2556, + 'SF220000': 0x2555, + 'SF230000': 0x2563, + 'SF240000': 0x2551, + 'SF250000': 0x2557, + 'SF260000': 0x255D, + 'SF270000': 0x255C, + 'SF280000': 0x255B, + 'SF360000': 0x255E, + 'SF370000': 0x255F, + 'SF380000': 0x255A, + 'SF390000': 0x2554, + 'SF400000': 0x2569, + 'SF410000': 0x2566, + 'SF420000': 0x2560, + 'SF430000': 0x2550, + 'SF440000': 0x256C, + 'SF450000': 0x2567, + 'SF460000': 0x2568, + 'SF470000': 0x2564, + 'SF480000': 0x2565, + 'SF490000': 0x2559, + 'SF500000': 0x2558, + 'SF510000': 0x2552, + 'SF520000': 0x2553, + 'SF530000': 0x256B, + 'SF540000': 0x256A, + 'Sacute': 0x015A, + 'Sacutedotaccent': 0x1E64, + 'Sampigreek': 0x03E0, + 'Scaron': 0x0160, + 'Scarondotaccent': 0x1E66, + 'Scaronsmall': 0xF6FD, + 'Scedilla': 0x015E, + 'Schwa': 0x018F, + 'Schwacyrillic': 0x04D8, + 'Schwadieresiscyrillic': 0x04DA, + 'Scircle': 0x24C8, + 'Scircumflex': 0x015C, + 'Scommaaccent': 0x0218, + 'Sdotaccent': 0x1E60, + 'Sdotbelow': 0x1E62, + 'Sdotbelowdotaccent': 0x1E68, + 'Seharmenian': 0x054D, + 'Sevenroman': 0x2166, + 'Shaarmenian': 0x0547, + 'Shacyrillic': 0x0428, + 'Shchacyrillic': 0x0429, + 'Sheicoptic': 0x03E2, + 'Shhacyrillic': 0x04BA, + 'Shimacoptic': 0x03EC, + 'Sigma': 0x03A3, + 'Sixroman': 0x2165, + 'Smonospace': 0xFF33, + 'Softsigncyrillic': 0x042C, + 'Ssmall': 0xF773, + 'Stigmagreek': 0x03DA, + 'T': 0x0054, + 'Tau': 0x03A4, + 'Tbar': 0x0166, + 'Tcaron': 0x0164, + 'Tcedilla': 0x0162, + 'Tcircle': 0x24C9, + 'Tcircumflexbelow': 0x1E70, + 'Tcommaaccent': 0x0162, + 'Tdotaccent': 0x1E6A, + 'Tdotbelow': 0x1E6C, + 'Tecyrillic': 0x0422, + 'Tedescendercyrillic': 0x04AC, + 'Tenroman': 0x2169, + 'Tetsecyrillic': 0x04B4, + 'Theta': 0x0398, + 'Thook': 0x01AC, + 'Thorn': 0x00DE, + 'Thornsmall': 0xF7FE, + 'Threeroman': 0x2162, + 'Tildesmall': 0xF6FE, + 'Tiwnarmenian': 0x054F, + 'Tlinebelow': 0x1E6E, + 'Tmonospace': 0xFF34, + 'Toarmenian': 0x0539, + 'Tonefive': 0x01BC, + 'Tonesix': 0x0184, + 'Tonetwo': 0x01A7, + 'Tretroflexhook': 0x01AE, + 'Tsecyrillic': 0x0426, + 'Tshecyrillic': 0x040B, + 'Tsmall': 0xF774, + 'Twelveroman': 0x216B, + 'Tworoman': 0x2161, + 'U': 0x0055, + 'Uacute': 0x00DA, + 'Uacutesmall': 0xF7FA, + 'Ubreve': 0x016C, + 'Ucaron': 0x01D3, + 'Ucircle': 0x24CA, + 'Ucircumflex': 0x00DB, + 'Ucircumflexbelow': 0x1E76, + 'Ucircumflexsmall': 0xF7FB, + 'Ucyrillic': 0x0423, + 'Udblacute': 0x0170, + 'Udblgrave': 0x0214, + 'Udieresis': 0x00DC, + 'Udieresisacute': 0x01D7, + 'Udieresisbelow': 0x1E72, + 'Udieresiscaron': 0x01D9, + 'Udieresiscyrillic': 0x04F0, + 'Udieresisgrave': 0x01DB, + 'Udieresismacron': 0x01D5, + 'Udieresissmall': 0xF7FC, + 'Udotbelow': 0x1EE4, + 'Ugrave': 0x00D9, + 'Ugravesmall': 0xF7F9, + 'Uhookabove': 0x1EE6, + 'Uhorn': 0x01AF, + 'Uhornacute': 0x1EE8, + 'Uhorndotbelow': 0x1EF0, + 'Uhorngrave': 0x1EEA, + 'Uhornhookabove': 0x1EEC, + 'Uhorntilde': 0x1EEE, + 'Uhungarumlaut': 0x0170, + 'Uhungarumlautcyrillic': 0x04F2, + 'Uinvertedbreve': 0x0216, + 'Ukcyrillic': 0x0478, + 'Umacron': 0x016A, + 'Umacroncyrillic': 0x04EE, + 'Umacrondieresis': 0x1E7A, + 'Umonospace': 0xFF35, + 'Uogonek': 0x0172, + 'Upsilon': 0x03A5, + 'Upsilon1': 0x03D2, + 'Upsilonacutehooksymbolgreek': 0x03D3, + 'Upsilonafrican': 0x01B1, + 'Upsilondieresis': 0x03AB, + 'Upsilondieresishooksymbolgreek': 0x03D4, + 'Upsilonhooksymbol': 0x03D2, + 'Upsilontonos': 0x038E, + 'Uring': 0x016E, + 'Ushortcyrillic': 0x040E, + 'Usmall': 0xF775, + 'Ustraightcyrillic': 0x04AE, + 'Ustraightstrokecyrillic': 0x04B0, + 'Utilde': 0x0168, + 'Utildeacute': 0x1E78, + 'Utildebelow': 0x1E74, + 'V': 0x0056, + 'Vcircle': 0x24CB, + 'Vdotbelow': 0x1E7E, + 'Vecyrillic': 0x0412, + 'Vewarmenian': 0x054E, + 'Vhook': 0x01B2, + 'Vmonospace': 0xFF36, + 'Voarmenian': 0x0548, + 'Vsmall': 0xF776, + 'Vtilde': 0x1E7C, + 'W': 0x0057, + 'Wacute': 0x1E82, + 'Wcircle': 0x24CC, + 'Wcircumflex': 0x0174, + 'Wdieresis': 0x1E84, + 'Wdotaccent': 0x1E86, + 'Wdotbelow': 0x1E88, + 'Wgrave': 0x1E80, + 'Wmonospace': 0xFF37, + 'Wsmall': 0xF777, + 'X': 0x0058, + 'Xcircle': 0x24CD, + 'Xdieresis': 0x1E8C, + 'Xdotaccent': 0x1E8A, + 'Xeharmenian': 0x053D, + 'Xi': 0x039E, + 'Xmonospace': 0xFF38, + 'Xsmall': 0xF778, + 'Y': 0x0059, + 'Yacute': 0x00DD, + 'Yacutesmall': 0xF7FD, + 'Yatcyrillic': 0x0462, + 'Ycircle': 0x24CE, + 'Ycircumflex': 0x0176, + 'Ydieresis': 0x0178, + 'Ydieresissmall': 0xF7FF, + 'Ydotaccent': 0x1E8E, + 'Ydotbelow': 0x1EF4, + 'Yericyrillic': 0x042B, + 'Yerudieresiscyrillic': 0x04F8, + 'Ygrave': 0x1EF2, + 'Yhook': 0x01B3, + 'Yhookabove': 0x1EF6, + 'Yiarmenian': 0x0545, + 'Yicyrillic': 0x0407, + 'Yiwnarmenian': 0x0552, + 'Ymonospace': 0xFF39, + 'Ysmall': 0xF779, + 'Ytilde': 0x1EF8, + 'Yusbigcyrillic': 0x046A, + 'Yusbigiotifiedcyrillic': 0x046C, + 'Yuslittlecyrillic': 0x0466, + 'Yuslittleiotifiedcyrillic': 0x0468, + 'Z': 0x005A, + 'Zaarmenian': 0x0536, + 'Zacute': 0x0179, + 'Zcaron': 0x017D, + 'Zcaronsmall': 0xF6FF, + 'Zcircle': 0x24CF, + 'Zcircumflex': 0x1E90, + 'Zdot': 0x017B, + 'Zdotaccent': 0x017B, + 'Zdotbelow': 0x1E92, + 'Zecyrillic': 0x0417, + 'Zedescendercyrillic': 0x0498, + 'Zedieresiscyrillic': 0x04DE, + 'Zeta': 0x0396, + 'Zhearmenian': 0x053A, + 'Zhebrevecyrillic': 0x04C1, + 'Zhecyrillic': 0x0416, + 'Zhedescendercyrillic': 0x0496, + 'Zhedieresiscyrillic': 0x04DC, + 'Zlinebelow': 0x1E94, + 'Zmonospace': 0xFF3A, + 'Zsmall': 0xF77A, + 'Zstroke': 0x01B5, + 'a': 0x0061, + 'aabengali': 0x0986, + 'aacute': 0x00E1, + 'aadeva': 0x0906, + 'aagujarati': 0x0A86, + 'aagurmukhi': 0x0A06, + 'aamatragurmukhi': 0x0A3E, + 'aarusquare': 0x3303, + 'aavowelsignbengali': 0x09BE, + 'aavowelsigndeva': 0x093E, + 'aavowelsigngujarati': 0x0ABE, + 'abbreviationmarkarmenian': 0x055F, + 'abbreviationsigndeva': 0x0970, + 'abengali': 0x0985, + 'abopomofo': 0x311A, + 'abreve': 0x0103, + 'abreveacute': 0x1EAF, + 'abrevecyrillic': 0x04D1, + 'abrevedotbelow': 0x1EB7, + 'abrevegrave': 0x1EB1, + 'abrevehookabove': 0x1EB3, + 'abrevetilde': 0x1EB5, + 'acaron': 0x01CE, + 'acircle': 0x24D0, + 'acircumflex': 0x00E2, + 'acircumflexacute': 0x1EA5, + 'acircumflexdotbelow': 0x1EAD, + 'acircumflexgrave': 0x1EA7, + 'acircumflexhookabove': 0x1EA9, + 'acircumflextilde': 0x1EAB, + 'acute': 0x00B4, + 'acutebelowcmb': 0x0317, + 'acutecmb': 0x0301, + 'acutecomb': 0x0301, + 'acutedeva': 0x0954, + 'acutelowmod': 0x02CF, + 'acutetonecmb': 0x0341, + 'acyrillic': 0x0430, + 'adblgrave': 0x0201, + 'addakgurmukhi': 0x0A71, + 'adeva': 0x0905, + 'adieresis': 0x00E4, + 'adieresiscyrillic': 0x04D3, + 'adieresismacron': 0x01DF, + 'adotbelow': 0x1EA1, + 'adotmacron': 0x01E1, + 'ae': 0x00E6, + 'aeacute': 0x01FD, + 'aekorean': 0x3150, + 'aemacron': 0x01E3, + 'afii00208': 0x2015, + 'afii08941': 0x20A4, + 'afii10017': 0x0410, + 'afii10018': 0x0411, + 'afii10019': 0x0412, + 'afii10020': 0x0413, + 'afii10021': 0x0414, + 'afii10022': 0x0415, + 'afii10023': 0x0401, + 'afii10024': 0x0416, + 'afii10025': 0x0417, + 'afii10026': 0x0418, + 'afii10027': 0x0419, + 'afii10028': 0x041A, + 'afii10029': 0x041B, + 'afii10030': 0x041C, + 'afii10031': 0x041D, + 'afii10032': 0x041E, + 'afii10033': 0x041F, + 'afii10034': 0x0420, + 'afii10035': 0x0421, + 'afii10036': 0x0422, + 'afii10037': 0x0423, + 'afii10038': 0x0424, + 'afii10039': 0x0425, + 'afii10040': 0x0426, + 'afii10041': 0x0427, + 'afii10042': 0x0428, + 'afii10043': 0x0429, + 'afii10044': 0x042A, + 'afii10045': 0x042B, + 'afii10046': 0x042C, + 'afii10047': 0x042D, + 'afii10048': 0x042E, + 'afii10049': 0x042F, + 'afii10050': 0x0490, + 'afii10051': 0x0402, + 'afii10052': 0x0403, + 'afii10053': 0x0404, + 'afii10054': 0x0405, + 'afii10055': 0x0406, + 'afii10056': 0x0407, + 'afii10057': 0x0408, + 'afii10058': 0x0409, + 'afii10059': 0x040A, + 'afii10060': 0x040B, + 'afii10061': 0x040C, + 'afii10062': 0x040E, + 'afii10063': 0xF6C4, + 'afii10064': 0xF6C5, + 'afii10065': 0x0430, + 'afii10066': 0x0431, + 'afii10067': 0x0432, + 'afii10068': 0x0433, + 'afii10069': 0x0434, + 'afii10070': 0x0435, + 'afii10071': 0x0451, + 'afii10072': 0x0436, + 'afii10073': 0x0437, + 'afii10074': 0x0438, + 'afii10075': 0x0439, + 'afii10076': 0x043A, + 'afii10077': 0x043B, + 'afii10078': 0x043C, + 'afii10079': 0x043D, + 'afii10080': 0x043E, + 'afii10081': 0x043F, + 'afii10082': 0x0440, + 'afii10083': 0x0441, + 'afii10084': 0x0442, + 'afii10085': 0x0443, + 'afii10086': 0x0444, + 'afii10087': 0x0445, + 'afii10088': 0x0446, + 'afii10089': 0x0447, + 'afii10090': 0x0448, + 'afii10091': 0x0449, + 'afii10092': 0x044A, + 'afii10093': 0x044B, + 'afii10094': 0x044C, + 'afii10095': 0x044D, + 'afii10096': 0x044E, + 'afii10097': 0x044F, + 'afii10098': 0x0491, + 'afii10099': 0x0452, + 'afii10100': 0x0453, + 'afii10101': 0x0454, + 'afii10102': 0x0455, + 'afii10103': 0x0456, + 'afii10104': 0x0457, + 'afii10105': 0x0458, + 'afii10106': 0x0459, + 'afii10107': 0x045A, + 'afii10108': 0x045B, + 'afii10109': 0x045C, + 'afii10110': 0x045E, + 'afii10145': 0x040F, + 'afii10146': 0x0462, + 'afii10147': 0x0472, + 'afii10148': 0x0474, + 'afii10192': 0xF6C6, + 'afii10193': 0x045F, + 'afii10194': 0x0463, + 'afii10195': 0x0473, + 'afii10196': 0x0475, + 'afii10831': 0xF6C7, + 'afii10832': 0xF6C8, + 'afii10846': 0x04D9, + 'afii299': 0x200E, + 'afii300': 0x200F, + 'afii301': 0x200D, + 'afii57381': 0x066A, + 'afii57388': 0x060C, + 'afii57392': 0x0660, + 'afii57393': 0x0661, + 'afii57394': 0x0662, + 'afii57395': 0x0663, + 'afii57396': 0x0664, + 'afii57397': 0x0665, + 'afii57398': 0x0666, + 'afii57399': 0x0667, + 'afii57400': 0x0668, + 'afii57401': 0x0669, + 'afii57403': 0x061B, + 'afii57407': 0x061F, + 'afii57409': 0x0621, + 'afii57410': 0x0622, + 'afii57411': 0x0623, + 'afii57412': 0x0624, + 'afii57413': 0x0625, + 'afii57414': 0x0626, + 'afii57415': 0x0627, + 'afii57416': 0x0628, + 'afii57417': 0x0629, + 'afii57418': 0x062A, + 'afii57419': 0x062B, + 'afii57420': 0x062C, + 'afii57421': 0x062D, + 'afii57422': 0x062E, + 'afii57423': 0x062F, + 'afii57424': 0x0630, + 'afii57425': 0x0631, + 'afii57426': 0x0632, + 'afii57427': 0x0633, + 'afii57428': 0x0634, + 'afii57429': 0x0635, + 'afii57430': 0x0636, + 'afii57431': 0x0637, + 'afii57432': 0x0638, + 'afii57433': 0x0639, + 'afii57434': 0x063A, + 'afii57440': 0x0640, + 'afii57441': 0x0641, + 'afii57442': 0x0642, + 'afii57443': 0x0643, + 'afii57444': 0x0644, + 'afii57445': 0x0645, + 'afii57446': 0x0646, + 'afii57448': 0x0648, + 'afii57449': 0x0649, + 'afii57450': 0x064A, + 'afii57451': 0x064B, + 'afii57452': 0x064C, + 'afii57453': 0x064D, + 'afii57454': 0x064E, + 'afii57455': 0x064F, + 'afii57456': 0x0650, + 'afii57457': 0x0651, + 'afii57458': 0x0652, + 'afii57470': 0x0647, + 'afii57505': 0x06A4, + 'afii57506': 0x067E, + 'afii57507': 0x0686, + 'afii57508': 0x0698, + 'afii57509': 0x06AF, + 'afii57511': 0x0679, + 'afii57512': 0x0688, + 'afii57513': 0x0691, + 'afii57514': 0x06BA, + 'afii57519': 0x06D2, + 'afii57534': 0x06D5, + 'afii57636': 0x20AA, + 'afii57645': 0x05BE, + 'afii57658': 0x05C3, + 'afii57664': 0x05D0, + 'afii57665': 0x05D1, + 'afii57666': 0x05D2, + 'afii57667': 0x05D3, + 'afii57668': 0x05D4, + 'afii57669': 0x05D5, + 'afii57670': 0x05D6, + 'afii57671': 0x05D7, + 'afii57672': 0x05D8, + 'afii57673': 0x05D9, + 'afii57674': 0x05DA, + 'afii57675': 0x05DB, + 'afii57676': 0x05DC, + 'afii57677': 0x05DD, + 'afii57678': 0x05DE, + 'afii57679': 0x05DF, + 'afii57680': 0x05E0, + 'afii57681': 0x05E1, + 'afii57682': 0x05E2, + 'afii57683': 0x05E3, + 'afii57684': 0x05E4, + 'afii57685': 0x05E5, + 'afii57686': 0x05E6, + 'afii57687': 0x05E7, + 'afii57688': 0x05E8, + 'afii57689': 0x05E9, + 'afii57690': 0x05EA, + 'afii57694': 0xFB2A, + 'afii57695': 0xFB2B, + 'afii57700': 0xFB4B, + 'afii57705': 0xFB1F, + 'afii57716': 0x05F0, + 'afii57717': 0x05F1, + 'afii57718': 0x05F2, + 'afii57723': 0xFB35, + 'afii57793': 0x05B4, + 'afii57794': 0x05B5, + 'afii57795': 0x05B6, + 'afii57796': 0x05BB, + 'afii57797': 0x05B8, + 'afii57798': 0x05B7, + 'afii57799': 0x05B0, + 'afii57800': 0x05B2, + 'afii57801': 0x05B1, + 'afii57802': 0x05B3, + 'afii57803': 0x05C2, + 'afii57804': 0x05C1, + 'afii57806': 0x05B9, + 'afii57807': 0x05BC, + 'afii57839': 0x05BD, + 'afii57841': 0x05BF, + 'afii57842': 0x05C0, + 'afii57929': 0x02BC, + 'afii61248': 0x2105, + 'afii61289': 0x2113, + 'afii61352': 0x2116, + 'afii61573': 0x202C, + 'afii61574': 0x202D, + 'afii61575': 0x202E, + 'afii61664': 0x200C, + 'afii63167': 0x066D, + 'afii64937': 0x02BD, + 'agrave': 0x00E0, + 'agujarati': 0x0A85, + 'agurmukhi': 0x0A05, + 'ahiragana': 0x3042, + 'ahookabove': 0x1EA3, + 'aibengali': 0x0990, + 'aibopomofo': 0x311E, + 'aideva': 0x0910, + 'aiecyrillic': 0x04D5, + 'aigujarati': 0x0A90, + 'aigurmukhi': 0x0A10, + 'aimatragurmukhi': 0x0A48, + 'ainarabic': 0x0639, + 'ainfinalarabic': 0xFECA, + 'aininitialarabic': 0xFECB, + 'ainmedialarabic': 0xFECC, + 'ainvertedbreve': 0x0203, + 'aivowelsignbengali': 0x09C8, + 'aivowelsigndeva': 0x0948, + 'aivowelsigngujarati': 0x0AC8, + 'akatakana': 0x30A2, + 'akatakanahalfwidth': 0xFF71, + 'akorean': 0x314F, + 'alef': 0x05D0, + 'alefarabic': 0x0627, + 'alefdageshhebrew': 0xFB30, + 'aleffinalarabic': 0xFE8E, + 'alefhamzaabovearabic': 0x0623, + 'alefhamzaabovefinalarabic': 0xFE84, + 'alefhamzabelowarabic': 0x0625, + 'alefhamzabelowfinalarabic': 0xFE88, + 'alefhebrew': 0x05D0, + 'aleflamedhebrew': 0xFB4F, + 'alefmaddaabovearabic': 0x0622, + 'alefmaddaabovefinalarabic': 0xFE82, + 'alefmaksuraarabic': 0x0649, + 'alefmaksurafinalarabic': 0xFEF0, + 'alefmaksurainitialarabic': 0xFEF3, + 'alefmaksuramedialarabic': 0xFEF4, + 'alefpatahhebrew': 0xFB2E, + 'alefqamatshebrew': 0xFB2F, + 'aleph': 0x2135, + 'allequal': 0x224C, + 'alpha': 0x03B1, + 'alphatonos': 0x03AC, + 'amacron': 0x0101, + 'amonospace': 0xFF41, + 'ampersand': 0x0026, + 'ampersandmonospace': 0xFF06, + 'ampersandsmall': 0xF726, + 'amsquare': 0x33C2, + 'anbopomofo': 0x3122, + 'angbopomofo': 0x3124, + 'angkhankhuthai': 0x0E5A, + 'angle': 0x2220, + 'anglebracketleft': 0x3008, + 'anglebracketleftvertical': 0xFE3F, + 'anglebracketright': 0x3009, + 'anglebracketrightvertical': 0xFE40, + 'angleleft': 0x2329, + 'angleright': 0x232A, + 'angstrom': 0x212B, + 'anoteleia': 0x0387, + 'anudattadeva': 0x0952, + 'anusvarabengali': 0x0982, + 'anusvaradeva': 0x0902, + 'anusvaragujarati': 0x0A82, + 'aogonek': 0x0105, + 'apaatosquare': 0x3300, + 'aparen': 0x249C, + 'apostrophearmenian': 0x055A, + 'apostrophemod': 0x02BC, + 'apple': 0xF8FF, + 'approaches': 0x2250, + 'approxequal': 0x2248, + 'approxequalorimage': 0x2252, + 'approximatelyequal': 0x2245, + 'araeaekorean': 0x318E, + 'araeakorean': 0x318D, + 'arc': 0x2312, + 'arighthalfring': 0x1E9A, + 'aring': 0x00E5, + 'aringacute': 0x01FB, + 'aringbelow': 0x1E01, + 'arrowboth': 0x2194, + 'arrowdashdown': 0x21E3, + 'arrowdashleft': 0x21E0, + 'arrowdashright': 0x21E2, + 'arrowdashup': 0x21E1, + 'arrowdblboth': 0x21D4, + 'arrowdbldown': 0x21D3, + 'arrowdblleft': 0x21D0, + 'arrowdblright': 0x21D2, + 'arrowdblup': 0x21D1, + 'arrowdown': 0x2193, + 'arrowdownleft': 0x2199, + 'arrowdownright': 0x2198, + 'arrowdownwhite': 0x21E9, + 'arrowheaddownmod': 0x02C5, + 'arrowheadleftmod': 0x02C2, + 'arrowheadrightmod': 0x02C3, + 'arrowheadupmod': 0x02C4, + 'arrowhorizex': 0xF8E7, + 'arrowleft': 0x2190, + 'arrowleftdbl': 0x21D0, + 'arrowleftdblstroke': 0x21CD, + 'arrowleftoverright': 0x21C6, + 'arrowleftwhite': 0x21E6, + 'arrowright': 0x2192, + 'arrowrightdblstroke': 0x21CF, + 'arrowrightheavy': 0x279E, + 'arrowrightoverleft': 0x21C4, + 'arrowrightwhite': 0x21E8, + 'arrowtableft': 0x21E4, + 'arrowtabright': 0x21E5, + 'arrowup': 0x2191, + 'arrowupdn': 0x2195, + 'arrowupdnbse': 0x21A8, + 'arrowupdownbase': 0x21A8, + 'arrowupleft': 0x2196, + 'arrowupleftofdown': 0x21C5, + 'arrowupright': 0x2197, + 'arrowupwhite': 0x21E7, + 'arrowvertex': 0xF8E6, + 'asciicircum': 0x005E, + 'asciicircummonospace': 0xFF3E, + 'asciitilde': 0x007E, + 'asciitildemonospace': 0xFF5E, + 'ascript': 0x0251, + 'ascriptturned': 0x0252, + 'asmallhiragana': 0x3041, + 'asmallkatakana': 0x30A1, + 'asmallkatakanahalfwidth': 0xFF67, + 'asterisk': 0x002A, + 'asteriskaltonearabic': 0x066D, + 'asteriskarabic': 0x066D, + 'asteriskmath': 0x2217, + 'asteriskmonospace': 0xFF0A, + 'asterisksmall': 0xFE61, + 'asterism': 0x2042, + 'asuperior': 0xF6E9, + 'asymptoticallyequal': 0x2243, + 'at': 0x0040, + 'atilde': 0x00E3, + 'atmonospace': 0xFF20, + 'atsmall': 0xFE6B, + 'aturned': 0x0250, + 'aubengali': 0x0994, + 'aubopomofo': 0x3120, + 'audeva': 0x0914, + 'augujarati': 0x0A94, + 'augurmukhi': 0x0A14, + 'aulengthmarkbengali': 0x09D7, + 'aumatragurmukhi': 0x0A4C, + 'auvowelsignbengali': 0x09CC, + 'auvowelsigndeva': 0x094C, + 'auvowelsigngujarati': 0x0ACC, + 'avagrahadeva': 0x093D, + 'aybarmenian': 0x0561, + 'ayin': 0x05E2, + 'ayinaltonehebrew': 0xFB20, + 'ayinhebrew': 0x05E2, + 'b': 0x0062, + 'babengali': 0x09AC, + 'backslash': 0x005C, + 'backslashmonospace': 0xFF3C, + 'badeva': 0x092C, + 'bagujarati': 0x0AAC, + 'bagurmukhi': 0x0A2C, + 'bahiragana': 0x3070, + 'bahtthai': 0x0E3F, + 'bakatakana': 0x30D0, + 'bar': 0x007C, + 'barmonospace': 0xFF5C, + 'bbopomofo': 0x3105, + 'bcircle': 0x24D1, + 'bdotaccent': 0x1E03, + 'bdotbelow': 0x1E05, + 'beamedsixteenthnotes': 0x266C, + 'because': 0x2235, + 'becyrillic': 0x0431, + 'beharabic': 0x0628, + 'behfinalarabic': 0xFE90, + 'behinitialarabic': 0xFE91, + 'behiragana': 0x3079, + 'behmedialarabic': 0xFE92, + 'behmeeminitialarabic': 0xFC9F, + 'behmeemisolatedarabic': 0xFC08, + 'behnoonfinalarabic': 0xFC6D, + 'bekatakana': 0x30D9, + 'benarmenian': 0x0562, + 'bet': 0x05D1, + 'beta': 0x03B2, + 'betasymbolgreek': 0x03D0, + 'betdagesh': 0xFB31, + 'betdageshhebrew': 0xFB31, + 'bethebrew': 0x05D1, + 'betrafehebrew': 0xFB4C, + 'bhabengali': 0x09AD, + 'bhadeva': 0x092D, + 'bhagujarati': 0x0AAD, + 'bhagurmukhi': 0x0A2D, + 'bhook': 0x0253, + 'bihiragana': 0x3073, + 'bikatakana': 0x30D3, + 'bilabialclick': 0x0298, + 'bindigurmukhi': 0x0A02, + 'birusquare': 0x3331, + 'blackcircle': 0x25CF, + 'blackdiamond': 0x25C6, + 'blackdownpointingtriangle': 0x25BC, + 'blackleftpointingpointer': 0x25C4, + 'blackleftpointingtriangle': 0x25C0, + 'blacklenticularbracketleft': 0x3010, + 'blacklenticularbracketleftvertical': 0xFE3B, + 'blacklenticularbracketright': 0x3011, + 'blacklenticularbracketrightvertical': 0xFE3C, + 'blacklowerlefttriangle': 0x25E3, + 'blacklowerrighttriangle': 0x25E2, + 'blackrectangle': 0x25AC, + 'blackrightpointingpointer': 0x25BA, + 'blackrightpointingtriangle': 0x25B6, + 'blacksmallsquare': 0x25AA, + 'blacksmilingface': 0x263B, + 'blacksquare': 0x25A0, + 'blackstar': 0x2605, + 'blackupperlefttriangle': 0x25E4, + 'blackupperrighttriangle': 0x25E5, + 'blackuppointingsmalltriangle': 0x25B4, + 'blackuppointingtriangle': 0x25B2, + 'blank': 0x2423, + 'blinebelow': 0x1E07, + 'block': 0x2588, + 'bmonospace': 0xFF42, + 'bobaimaithai': 0x0E1A, + 'bohiragana': 0x307C, + 'bokatakana': 0x30DC, + 'bparen': 0x249D, + 'bqsquare': 0x33C3, + 'braceex': 0xF8F4, + 'braceleft': 0x007B, + 'braceleftbt': 0xF8F3, + 'braceleftmid': 0xF8F2, + 'braceleftmonospace': 0xFF5B, + 'braceleftsmall': 0xFE5B, + 'bracelefttp': 0xF8F1, + 'braceleftvertical': 0xFE37, + 'braceright': 0x007D, + 'bracerightbt': 0xF8FE, + 'bracerightmid': 0xF8FD, + 'bracerightmonospace': 0xFF5D, + 'bracerightsmall': 0xFE5C, + 'bracerighttp': 0xF8FC, + 'bracerightvertical': 0xFE38, + 'bracketleft': 0x005B, + 'bracketleftbt': 0xF8F0, + 'bracketleftex': 0xF8EF, + 'bracketleftmonospace': 0xFF3B, + 'bracketlefttp': 0xF8EE, + 'bracketright': 0x005D, + 'bracketrightbt': 0xF8FB, + 'bracketrightex': 0xF8FA, + 'bracketrightmonospace': 0xFF3D, + 'bracketrighttp': 0xF8F9, + 'breve': 0x02D8, + 'brevebelowcmb': 0x032E, + 'brevecmb': 0x0306, + 'breveinvertedbelowcmb': 0x032F, + 'breveinvertedcmb': 0x0311, + 'breveinverteddoublecmb': 0x0361, + 'bridgebelowcmb': 0x032A, + 'bridgeinvertedbelowcmb': 0x033A, + 'brokenbar': 0x00A6, + 'bstroke': 0x0180, + 'bsuperior': 0xF6EA, + 'btopbar': 0x0183, + 'buhiragana': 0x3076, + 'bukatakana': 0x30D6, + 'bullet': 0x2022, + 'bulletinverse': 0x25D8, + 'bulletoperator': 0x2219, + 'bullseye': 0x25CE, + 'c': 0x0063, + 'caarmenian': 0x056E, + 'cabengali': 0x099A, + 'cacute': 0x0107, + 'cadeva': 0x091A, + 'cagujarati': 0x0A9A, + 'cagurmukhi': 0x0A1A, + 'calsquare': 0x3388, + 'candrabindubengali': 0x0981, + 'candrabinducmb': 0x0310, + 'candrabindudeva': 0x0901, + 'candrabindugujarati': 0x0A81, + 'capslock': 0x21EA, + 'careof': 0x2105, + 'caron': 0x02C7, + 'caronbelowcmb': 0x032C, + 'caroncmb': 0x030C, + 'carriagereturn': 0x21B5, + 'cbopomofo': 0x3118, + 'ccaron': 0x010D, + 'ccedilla': 0x00E7, + 'ccedillaacute': 0x1E09, + 'ccircle': 0x24D2, + 'ccircumflex': 0x0109, + 'ccurl': 0x0255, + 'cdot': 0x010B, + 'cdotaccent': 0x010B, + 'cdsquare': 0x33C5, + 'cedilla': 0x00B8, + 'cedillacmb': 0x0327, + 'cent': 0x00A2, + 'centigrade': 0x2103, + 'centinferior': 0xF6DF, + 'centmonospace': 0xFFE0, + 'centoldstyle': 0xF7A2, + 'centsuperior': 0xF6E0, + 'chaarmenian': 0x0579, + 'chabengali': 0x099B, + 'chadeva': 0x091B, + 'chagujarati': 0x0A9B, + 'chagurmukhi': 0x0A1B, + 'chbopomofo': 0x3114, + 'cheabkhasiancyrillic': 0x04BD, + 'checkmark': 0x2713, + 'checyrillic': 0x0447, + 'chedescenderabkhasiancyrillic': 0x04BF, + 'chedescendercyrillic': 0x04B7, + 'chedieresiscyrillic': 0x04F5, + 'cheharmenian': 0x0573, + 'chekhakassiancyrillic': 0x04CC, + 'cheverticalstrokecyrillic': 0x04B9, + 'chi': 0x03C7, + 'chieuchacirclekorean': 0x3277, + 'chieuchaparenkorean': 0x3217, + 'chieuchcirclekorean': 0x3269, + 'chieuchkorean': 0x314A, + 'chieuchparenkorean': 0x3209, + 'chochangthai': 0x0E0A, + 'chochanthai': 0x0E08, + 'chochingthai': 0x0E09, + 'chochoethai': 0x0E0C, + 'chook': 0x0188, + 'cieucacirclekorean': 0x3276, + 'cieucaparenkorean': 0x3216, + 'cieuccirclekorean': 0x3268, + 'cieuckorean': 0x3148, + 'cieucparenkorean': 0x3208, + 'cieucuparenkorean': 0x321C, + 'circle': 0x25CB, + 'circlemultiply': 0x2297, + 'circleot': 0x2299, + 'circleplus': 0x2295, + 'circlepostalmark': 0x3036, + 'circlewithlefthalfblack': 0x25D0, + 'circlewithrighthalfblack': 0x25D1, + 'circumflex': 0x02C6, + 'circumflexbelowcmb': 0x032D, + 'circumflexcmb': 0x0302, + 'clear': 0x2327, + 'clickalveolar': 0x01C2, + 'clickdental': 0x01C0, + 'clicklateral': 0x01C1, + 'clickretroflex': 0x01C3, + 'club': 0x2663, + 'clubsuitblack': 0x2663, + 'clubsuitwhite': 0x2667, + 'cmcubedsquare': 0x33A4, + 'cmonospace': 0xFF43, + 'cmsquaredsquare': 0x33A0, + 'coarmenian': 0x0581, + 'colon': 0x003A, + 'colonmonetary': 0x20A1, + 'colonmonospace': 0xFF1A, + 'colonsign': 0x20A1, + 'colonsmall': 0xFE55, + 'colontriangularhalfmod': 0x02D1, + 'colontriangularmod': 0x02D0, + 'comma': 0x002C, + 'commaabovecmb': 0x0313, + 'commaaboverightcmb': 0x0315, + 'commaaccent': 0xF6C3, + 'commaarabic': 0x060C, + 'commaarmenian': 0x055D, + 'commainferior': 0xF6E1, + 'commamonospace': 0xFF0C, + 'commareversedabovecmb': 0x0314, + 'commareversedmod': 0x02BD, + 'commasmall': 0xFE50, + 'commasuperior': 0xF6E2, + 'commaturnedabovecmb': 0x0312, + 'commaturnedmod': 0x02BB, + 'compass': 0x263C, + 'congruent': 0x2245, + 'contourintegral': 0x222E, + 'control': 0x2303, + 'controlACK': 0x0006, + 'controlBEL': 0x0007, + 'controlBS': 0x0008, + 'controlCAN': 0x0018, + 'controlCR': 0x000D, + 'controlDC1': 0x0011, + 'controlDC2': 0x0012, + 'controlDC3': 0x0013, + 'controlDC4': 0x0014, + 'controlDEL': 0x007F, + 'controlDLE': 0x0010, + 'controlEM': 0x0019, + 'controlENQ': 0x0005, + 'controlEOT': 0x0004, + 'controlESC': 0x001B, + 'controlETB': 0x0017, + 'controlETX': 0x0003, + 'controlFF': 0x000C, + 'controlFS': 0x001C, + 'controlGS': 0x001D, + 'controlHT': 0x0009, + 'controlLF': 0x000A, + 'controlNAK': 0x0015, + 'controlRS': 0x001E, + 'controlSI': 0x000F, + 'controlSO': 0x000E, + 'controlSOT': 0x0002, + 'controlSTX': 0x0001, + 'controlSUB': 0x001A, + 'controlSYN': 0x0016, + 'controlUS': 0x001F, + 'controlVT': 0x000B, + 'copyright': 0x00A9, + 'copyrightsans': 0xF8E9, + 'copyrightserif': 0xF6D9, + 'cornerbracketleft': 0x300C, + 'cornerbracketlefthalfwidth': 0xFF62, + 'cornerbracketleftvertical': 0xFE41, + 'cornerbracketright': 0x300D, + 'cornerbracketrighthalfwidth': 0xFF63, + 'cornerbracketrightvertical': 0xFE42, + 'corporationsquare': 0x337F, + 'cosquare': 0x33C7, + 'coverkgsquare': 0x33C6, + 'cparen': 0x249E, + 'cruzeiro': 0x20A2, + 'cstretched': 0x0297, + 'curlyand': 0x22CF, + 'curlyor': 0x22CE, + 'currency': 0x00A4, + 'cyrBreve': 0xF6D1, + 'cyrFlex': 0xF6D2, + 'cyrbreve': 0xF6D4, + 'cyrflex': 0xF6D5, + 'd': 0x0064, + 'daarmenian': 0x0564, + 'dabengali': 0x09A6, + 'dadarabic': 0x0636, + 'dadeva': 0x0926, + 'dadfinalarabic': 0xFEBE, + 'dadinitialarabic': 0xFEBF, + 'dadmedialarabic': 0xFEC0, + 'dagesh': 0x05BC, + 'dageshhebrew': 0x05BC, + 'dagger': 0x2020, + 'daggerdbl': 0x2021, + 'dagujarati': 0x0AA6, + 'dagurmukhi': 0x0A26, + 'dahiragana': 0x3060, + 'dakatakana': 0x30C0, + 'dalarabic': 0x062F, + 'dalet': 0x05D3, + 'daletdagesh': 0xFB33, + 'daletdageshhebrew': 0xFB33, + 'dalethebrew': 0x05D3, + 'dalfinalarabic': 0xFEAA, + 'dammaarabic': 0x064F, + 'dammalowarabic': 0x064F, + 'dammatanaltonearabic': 0x064C, + 'dammatanarabic': 0x064C, + 'danda': 0x0964, + 'dargahebrew': 0x05A7, + 'dargalefthebrew': 0x05A7, + 'dasiapneumatacyrilliccmb': 0x0485, + 'dblGrave': 0xF6D3, + 'dblanglebracketleft': 0x300A, + 'dblanglebracketleftvertical': 0xFE3D, + 'dblanglebracketright': 0x300B, + 'dblanglebracketrightvertical': 0xFE3E, + 'dblarchinvertedbelowcmb': 0x032B, + 'dblarrowleft': 0x21D4, + 'dblarrowright': 0x21D2, + 'dbldanda': 0x0965, + 'dblgrave': 0xF6D6, + 'dblgravecmb': 0x030F, + 'dblintegral': 0x222C, + 'dbllowline': 0x2017, + 'dbllowlinecmb': 0x0333, + 'dbloverlinecmb': 0x033F, + 'dblprimemod': 0x02BA, + 'dblverticalbar': 0x2016, + 'dblverticallineabovecmb': 0x030E, + 'dbopomofo': 0x3109, + 'dbsquare': 0x33C8, + 'dcaron': 0x010F, + 'dcedilla': 0x1E11, + 'dcircle': 0x24D3, + 'dcircumflexbelow': 0x1E13, + 'dcroat': 0x0111, + 'ddabengali': 0x09A1, + 'ddadeva': 0x0921, + 'ddagujarati': 0x0AA1, + 'ddagurmukhi': 0x0A21, + 'ddalarabic': 0x0688, + 'ddalfinalarabic': 0xFB89, + 'dddhadeva': 0x095C, + 'ddhabengali': 0x09A2, + 'ddhadeva': 0x0922, + 'ddhagujarati': 0x0AA2, + 'ddhagurmukhi': 0x0A22, + 'ddotaccent': 0x1E0B, + 'ddotbelow': 0x1E0D, + 'decimalseparatorarabic': 0x066B, + 'decimalseparatorpersian': 0x066B, + 'decyrillic': 0x0434, + 'degree': 0x00B0, + 'dehihebrew': 0x05AD, + 'dehiragana': 0x3067, + 'deicoptic': 0x03EF, + 'dekatakana': 0x30C7, + 'deleteleft': 0x232B, + 'deleteright': 0x2326, + 'delta': 0x03B4, + 'deltaturned': 0x018D, + 'denominatorminusonenumeratorbengali': 0x09F8, + 'dezh': 0x02A4, + 'dhabengali': 0x09A7, + 'dhadeva': 0x0927, + 'dhagujarati': 0x0AA7, + 'dhagurmukhi': 0x0A27, + 'dhook': 0x0257, + 'dialytikatonos': 0x0385, + 'dialytikatonoscmb': 0x0344, + 'diamond': 0x2666, + 'diamondsuitwhite': 0x2662, + 'dieresis': 0x00A8, + 'dieresisacute': 0xF6D7, + 'dieresisbelowcmb': 0x0324, + 'dieresiscmb': 0x0308, + 'dieresisgrave': 0xF6D8, + 'dieresistonos': 0x0385, + 'dihiragana': 0x3062, + 'dikatakana': 0x30C2, + 'dittomark': 0x3003, + 'divide': 0x00F7, + 'divides': 0x2223, + 'divisionslash': 0x2215, + 'djecyrillic': 0x0452, + 'dkshade': 0x2593, + 'dlinebelow': 0x1E0F, + 'dlsquare': 0x3397, + 'dmacron': 0x0111, + 'dmonospace': 0xFF44, + 'dnblock': 0x2584, + 'dochadathai': 0x0E0E, + 'dodekthai': 0x0E14, + 'dohiragana': 0x3069, + 'dokatakana': 0x30C9, + 'dollar': 0x0024, + 'dollarinferior': 0xF6E3, + 'dollarmonospace': 0xFF04, + 'dollaroldstyle': 0xF724, + 'dollarsmall': 0xFE69, + 'dollarsuperior': 0xF6E4, + 'dong': 0x20AB, + 'dorusquare': 0x3326, + 'dotaccent': 0x02D9, + 'dotaccentcmb': 0x0307, + 'dotbelowcmb': 0x0323, + 'dotbelowcomb': 0x0323, + 'dotkatakana': 0x30FB, + 'dotlessi': 0x0131, + 'dotlessj': 0xF6BE, + 'dotlessjstrokehook': 0x0284, + 'dotmath': 0x22C5, + 'dottedcircle': 0x25CC, + 'doubleyodpatah': 0xFB1F, + 'doubleyodpatahhebrew': 0xFB1F, + 'downtackbelowcmb': 0x031E, + 'downtackmod': 0x02D5, + 'dparen': 0x249F, + 'dsuperior': 0xF6EB, + 'dtail': 0x0256, + 'dtopbar': 0x018C, + 'duhiragana': 0x3065, + 'dukatakana': 0x30C5, + 'dz': 0x01F3, + 'dzaltone': 0x02A3, + 'dzcaron': 0x01C6, + 'dzcurl': 0x02A5, + 'dzeabkhasiancyrillic': 0x04E1, + 'dzecyrillic': 0x0455, + 'dzhecyrillic': 0x045F, + 'e': 0x0065, + 'eacute': 0x00E9, + 'earth': 0x2641, + 'ebengali': 0x098F, + 'ebopomofo': 0x311C, + 'ebreve': 0x0115, + 'ecandradeva': 0x090D, + 'ecandragujarati': 0x0A8D, + 'ecandravowelsigndeva': 0x0945, + 'ecandravowelsigngujarati': 0x0AC5, + 'ecaron': 0x011B, + 'ecedillabreve': 0x1E1D, + 'echarmenian': 0x0565, + 'echyiwnarmenian': 0x0587, + 'ecircle': 0x24D4, + 'ecircumflex': 0x00EA, + 'ecircumflexacute': 0x1EBF, + 'ecircumflexbelow': 0x1E19, + 'ecircumflexdotbelow': 0x1EC7, + 'ecircumflexgrave': 0x1EC1, + 'ecircumflexhookabove': 0x1EC3, + 'ecircumflextilde': 0x1EC5, + 'ecyrillic': 0x0454, + 'edblgrave': 0x0205, + 'edeva': 0x090F, + 'edieresis': 0x00EB, + 'edot': 0x0117, + 'edotaccent': 0x0117, + 'edotbelow': 0x1EB9, + 'eegurmukhi': 0x0A0F, + 'eematragurmukhi': 0x0A47, + 'efcyrillic': 0x0444, + 'egrave': 0x00E8, + 'egujarati': 0x0A8F, + 'eharmenian': 0x0567, + 'ehbopomofo': 0x311D, + 'ehiragana': 0x3048, + 'ehookabove': 0x1EBB, + 'eibopomofo': 0x311F, + 'eight': 0x0038, + 'eightarabic': 0x0668, + 'eightbengali': 0x09EE, + 'eightcircle': 0x2467, + 'eightcircleinversesansserif': 0x2791, + 'eightdeva': 0x096E, + 'eighteencircle': 0x2471, + 'eighteenparen': 0x2485, + 'eighteenperiod': 0x2499, + 'eightgujarati': 0x0AEE, + 'eightgurmukhi': 0x0A6E, + 'eighthackarabic': 0x0668, + 'eighthangzhou': 0x3028, + 'eighthnotebeamed': 0x266B, + 'eightideographicparen': 0x3227, + 'eightinferior': 0x2088, + 'eightmonospace': 0xFF18, + 'eightoldstyle': 0xF738, + 'eightparen': 0x247B, + 'eightperiod': 0x248F, + 'eightpersian': 0x06F8, + 'eightroman': 0x2177, + 'eightsuperior': 0x2078, + 'eightthai': 0x0E58, + 'einvertedbreve': 0x0207, + 'eiotifiedcyrillic': 0x0465, + 'ekatakana': 0x30A8, + 'ekatakanahalfwidth': 0xFF74, + 'ekonkargurmukhi': 0x0A74, + 'ekorean': 0x3154, + 'elcyrillic': 0x043B, + 'element': 0x2208, + 'elevencircle': 0x246A, + 'elevenparen': 0x247E, + 'elevenperiod': 0x2492, + 'elevenroman': 0x217A, + 'ellipsis': 0x2026, + 'ellipsisvertical': 0x22EE, + 'emacron': 0x0113, + 'emacronacute': 0x1E17, + 'emacrongrave': 0x1E15, + 'emcyrillic': 0x043C, + 'emdash': 0x2014, + 'emdashvertical': 0xFE31, + 'emonospace': 0xFF45, + 'emphasismarkarmenian': 0x055B, + 'emptyset': 0x2205, + 'enbopomofo': 0x3123, + 'encyrillic': 0x043D, + 'endash': 0x2013, + 'endashvertical': 0xFE32, + 'endescendercyrillic': 0x04A3, + 'eng': 0x014B, + 'engbopomofo': 0x3125, + 'enghecyrillic': 0x04A5, + 'enhookcyrillic': 0x04C8, + 'enspace': 0x2002, + 'eogonek': 0x0119, + 'eokorean': 0x3153, + 'eopen': 0x025B, + 'eopenclosed': 0x029A, + 'eopenreversed': 0x025C, + 'eopenreversedclosed': 0x025E, + 'eopenreversedhook': 0x025D, + 'eparen': 0x24A0, + 'epsilon': 0x03B5, + 'epsilontonos': 0x03AD, + 'equal': 0x003D, + 'equalmonospace': 0xFF1D, + 'equalsmall': 0xFE66, + 'equalsuperior': 0x207C, + 'equivalence': 0x2261, + 'erbopomofo': 0x3126, + 'ercyrillic': 0x0440, + 'ereversed': 0x0258, + 'ereversedcyrillic': 0x044D, + 'escyrillic': 0x0441, + 'esdescendercyrillic': 0x04AB, + 'esh': 0x0283, + 'eshcurl': 0x0286, + 'eshortdeva': 0x090E, + 'eshortvowelsigndeva': 0x0946, + 'eshreversedloop': 0x01AA, + 'eshsquatreversed': 0x0285, + 'esmallhiragana': 0x3047, + 'esmallkatakana': 0x30A7, + 'esmallkatakanahalfwidth': 0xFF6A, + 'estimated': 0x212E, + 'esuperior': 0xF6EC, + 'eta': 0x03B7, + 'etarmenian': 0x0568, + 'etatonos': 0x03AE, + 'eth': 0x00F0, + 'etilde': 0x1EBD, + 'etildebelow': 0x1E1B, + 'etnahtafoukhhebrew': 0x0591, + 'etnahtafoukhlefthebrew': 0x0591, + 'etnahtahebrew': 0x0591, + 'etnahtalefthebrew': 0x0591, + 'eturned': 0x01DD, + 'eukorean': 0x3161, + 'euro': 0x20AC, + 'evowelsignbengali': 0x09C7, + 'evowelsigndeva': 0x0947, + 'evowelsigngujarati': 0x0AC7, + 'exclam': 0x0021, + 'exclamarmenian': 0x055C, + 'exclamdbl': 0x203C, + 'exclamdown': 0x00A1, + 'exclamdownsmall': 0xF7A1, + 'exclammonospace': 0xFF01, + 'exclamsmall': 0xF721, + 'existential': 0x2203, + 'ezh': 0x0292, + 'ezhcaron': 0x01EF, + 'ezhcurl': 0x0293, + 'ezhreversed': 0x01B9, + 'ezhtail': 0x01BA, + 'f': 0x0066, + 'fadeva': 0x095E, + 'fagurmukhi': 0x0A5E, + 'fahrenheit': 0x2109, + 'fathaarabic': 0x064E, + 'fathalowarabic': 0x064E, + 'fathatanarabic': 0x064B, + 'fbopomofo': 0x3108, + 'fcircle': 0x24D5, + 'fdotaccent': 0x1E1F, + 'feharabic': 0x0641, + 'feharmenian': 0x0586, + 'fehfinalarabic': 0xFED2, + 'fehinitialarabic': 0xFED3, + 'fehmedialarabic': 0xFED4, + 'feicoptic': 0x03E5, + 'female': 0x2640, + 'ff': 0xFB00, + 'ffi': 0xFB03, + 'ffl': 0xFB04, + 'fi': 0xFB01, + 'fifteencircle': 0x246E, + 'fifteenparen': 0x2482, + 'fifteenperiod': 0x2496, + 'figuredash': 0x2012, + 'filledbox': 0x25A0, + 'filledrect': 0x25AC, + 'finalkaf': 0x05DA, + 'finalkafdagesh': 0xFB3A, + 'finalkafdageshhebrew': 0xFB3A, + 'finalkafhebrew': 0x05DA, + 'finalmem': 0x05DD, + 'finalmemhebrew': 0x05DD, + 'finalnun': 0x05DF, + 'finalnunhebrew': 0x05DF, + 'finalpe': 0x05E3, + 'finalpehebrew': 0x05E3, + 'finaltsadi': 0x05E5, + 'finaltsadihebrew': 0x05E5, + 'firsttonechinese': 0x02C9, + 'fisheye': 0x25C9, + 'fitacyrillic': 0x0473, + 'five': 0x0035, + 'fivearabic': 0x0665, + 'fivebengali': 0x09EB, + 'fivecircle': 0x2464, + 'fivecircleinversesansserif': 0x278E, + 'fivedeva': 0x096B, + 'fiveeighths': 0x215D, + 'fivegujarati': 0x0AEB, + 'fivegurmukhi': 0x0A6B, + 'fivehackarabic': 0x0665, + 'fivehangzhou': 0x3025, + 'fiveideographicparen': 0x3224, + 'fiveinferior': 0x2085, + 'fivemonospace': 0xFF15, + 'fiveoldstyle': 0xF735, + 'fiveparen': 0x2478, + 'fiveperiod': 0x248C, + 'fivepersian': 0x06F5, + 'fiveroman': 0x2174, + 'fivesuperior': 0x2075, + 'fivethai': 0x0E55, + 'fl': 0xFB02, + 'florin': 0x0192, + 'fmonospace': 0xFF46, + 'fmsquare': 0x3399, + 'fofanthai': 0x0E1F, + 'fofathai': 0x0E1D, + 'fongmanthai': 0x0E4F, + 'forall': 0x2200, + 'four': 0x0034, + 'fourarabic': 0x0664, + 'fourbengali': 0x09EA, + 'fourcircle': 0x2463, + 'fourcircleinversesansserif': 0x278D, + 'fourdeva': 0x096A, + 'fourgujarati': 0x0AEA, + 'fourgurmukhi': 0x0A6A, + 'fourhackarabic': 0x0664, + 'fourhangzhou': 0x3024, + 'fourideographicparen': 0x3223, + 'fourinferior': 0x2084, + 'fourmonospace': 0xFF14, + 'fournumeratorbengali': 0x09F7, + 'fouroldstyle': 0xF734, + 'fourparen': 0x2477, + 'fourperiod': 0x248B, + 'fourpersian': 0x06F4, + 'fourroman': 0x2173, + 'foursuperior': 0x2074, + 'fourteencircle': 0x246D, + 'fourteenparen': 0x2481, + 'fourteenperiod': 0x2495, + 'fourthai': 0x0E54, + 'fourthtonechinese': 0x02CB, + 'fparen': 0x24A1, + 'fraction': 0x2044, + 'franc': 0x20A3, + 'g': 0x0067, + 'gabengali': 0x0997, + 'gacute': 0x01F5, + 'gadeva': 0x0917, + 'gafarabic': 0x06AF, + 'gaffinalarabic': 0xFB93, + 'gafinitialarabic': 0xFB94, + 'gafmedialarabic': 0xFB95, + 'gagujarati': 0x0A97, + 'gagurmukhi': 0x0A17, + 'gahiragana': 0x304C, + 'gakatakana': 0x30AC, + 'gamma': 0x03B3, + 'gammalatinsmall': 0x0263, + 'gammasuperior': 0x02E0, + 'gangiacoptic': 0x03EB, + 'gbopomofo': 0x310D, + 'gbreve': 0x011F, + 'gcaron': 0x01E7, + 'gcedilla': 0x0123, + 'gcircle': 0x24D6, + 'gcircumflex': 0x011D, + 'gcommaaccent': 0x0123, + 'gdot': 0x0121, + 'gdotaccent': 0x0121, + 'gecyrillic': 0x0433, + 'gehiragana': 0x3052, + 'gekatakana': 0x30B2, + 'geometricallyequal': 0x2251, + 'gereshaccenthebrew': 0x059C, + 'gereshhebrew': 0x05F3, + 'gereshmuqdamhebrew': 0x059D, + 'germandbls': 0x00DF, + 'gershayimaccenthebrew': 0x059E, + 'gershayimhebrew': 0x05F4, + 'getamark': 0x3013, + 'ghabengali': 0x0998, + 'ghadarmenian': 0x0572, + 'ghadeva': 0x0918, + 'ghagujarati': 0x0A98, + 'ghagurmukhi': 0x0A18, + 'ghainarabic': 0x063A, + 'ghainfinalarabic': 0xFECE, + 'ghaininitialarabic': 0xFECF, + 'ghainmedialarabic': 0xFED0, + 'ghemiddlehookcyrillic': 0x0495, + 'ghestrokecyrillic': 0x0493, + 'gheupturncyrillic': 0x0491, + 'ghhadeva': 0x095A, + 'ghhagurmukhi': 0x0A5A, + 'ghook': 0x0260, + 'ghzsquare': 0x3393, + 'gihiragana': 0x304E, + 'gikatakana': 0x30AE, + 'gimarmenian': 0x0563, + 'gimel': 0x05D2, + 'gimeldagesh': 0xFB32, + 'gimeldageshhebrew': 0xFB32, + 'gimelhebrew': 0x05D2, + 'gjecyrillic': 0x0453, + 'glottalinvertedstroke': 0x01BE, + 'glottalstop': 0x0294, + 'glottalstopinverted': 0x0296, + 'glottalstopmod': 0x02C0, + 'glottalstopreversed': 0x0295, + 'glottalstopreversedmod': 0x02C1, + 'glottalstopreversedsuperior': 0x02E4, + 'glottalstopstroke': 0x02A1, + 'glottalstopstrokereversed': 0x02A2, + 'gmacron': 0x1E21, + 'gmonospace': 0xFF47, + 'gohiragana': 0x3054, + 'gokatakana': 0x30B4, + 'gparen': 0x24A2, + 'gpasquare': 0x33AC, + 'gradient': 0x2207, + 'grave': 0x0060, + 'gravebelowcmb': 0x0316, + 'gravecmb': 0x0300, + 'gravecomb': 0x0300, + 'gravedeva': 0x0953, + 'gravelowmod': 0x02CE, + 'gravemonospace': 0xFF40, + 'gravetonecmb': 0x0340, + 'greater': 0x003E, + 'greaterequal': 0x2265, + 'greaterequalorless': 0x22DB, + 'greatermonospace': 0xFF1E, + 'greaterorequivalent': 0x2273, + 'greaterorless': 0x2277, + 'greateroverequal': 0x2267, + 'greatersmall': 0xFE65, + 'gscript': 0x0261, + 'gstroke': 0x01E5, + 'guhiragana': 0x3050, + 'guillemotleft': 0x00AB, + 'guillemotright': 0x00BB, + 'guilsinglleft': 0x2039, + 'guilsinglright': 0x203A, + 'gukatakana': 0x30B0, + 'guramusquare': 0x3318, + 'gysquare': 0x33C9, + 'h': 0x0068, + 'haabkhasiancyrillic': 0x04A9, + 'haaltonearabic': 0x06C1, + 'habengali': 0x09B9, + 'hadescendercyrillic': 0x04B3, + 'hadeva': 0x0939, + 'hagujarati': 0x0AB9, + 'hagurmukhi': 0x0A39, + 'haharabic': 0x062D, + 'hahfinalarabic': 0xFEA2, + 'hahinitialarabic': 0xFEA3, + 'hahiragana': 0x306F, + 'hahmedialarabic': 0xFEA4, + 'haitusquare': 0x332A, + 'hakatakana': 0x30CF, + 'hakatakanahalfwidth': 0xFF8A, + 'halantgurmukhi': 0x0A4D, + 'hamzaarabic': 0x0621, + 'hamzalowarabic': 0x0621, + 'hangulfiller': 0x3164, + 'hardsigncyrillic': 0x044A, + 'harpoonleftbarbup': 0x21BC, + 'harpoonrightbarbup': 0x21C0, + 'hasquare': 0x33CA, + 'hatafpatah': 0x05B2, + 'hatafpatah16': 0x05B2, + 'hatafpatah23': 0x05B2, + 'hatafpatah2f': 0x05B2, + 'hatafpatahhebrew': 0x05B2, + 'hatafpatahnarrowhebrew': 0x05B2, + 'hatafpatahquarterhebrew': 0x05B2, + 'hatafpatahwidehebrew': 0x05B2, + 'hatafqamats': 0x05B3, + 'hatafqamats1b': 0x05B3, + 'hatafqamats28': 0x05B3, + 'hatafqamats34': 0x05B3, + 'hatafqamatshebrew': 0x05B3, + 'hatafqamatsnarrowhebrew': 0x05B3, + 'hatafqamatsquarterhebrew': 0x05B3, + 'hatafqamatswidehebrew': 0x05B3, + 'hatafsegol': 0x05B1, + 'hatafsegol17': 0x05B1, + 'hatafsegol24': 0x05B1, + 'hatafsegol30': 0x05B1, + 'hatafsegolhebrew': 0x05B1, + 'hatafsegolnarrowhebrew': 0x05B1, + 'hatafsegolquarterhebrew': 0x05B1, + 'hatafsegolwidehebrew': 0x05B1, + 'hbar': 0x0127, + 'hbopomofo': 0x310F, + 'hbrevebelow': 0x1E2B, + 'hcedilla': 0x1E29, + 'hcircle': 0x24D7, + 'hcircumflex': 0x0125, + 'hdieresis': 0x1E27, + 'hdotaccent': 0x1E23, + 'hdotbelow': 0x1E25, + 'he': 0x05D4, + 'heart': 0x2665, + 'heartsuitblack': 0x2665, + 'heartsuitwhite': 0x2661, + 'hedagesh': 0xFB34, + 'hedageshhebrew': 0xFB34, + 'hehaltonearabic': 0x06C1, + 'heharabic': 0x0647, + 'hehebrew': 0x05D4, + 'hehfinalaltonearabic': 0xFBA7, + 'hehfinalalttwoarabic': 0xFEEA, + 'hehfinalarabic': 0xFEEA, + 'hehhamzaabovefinalarabic': 0xFBA5, + 'hehhamzaaboveisolatedarabic': 0xFBA4, + 'hehinitialaltonearabic': 0xFBA8, + 'hehinitialarabic': 0xFEEB, + 'hehiragana': 0x3078, + 'hehmedialaltonearabic': 0xFBA9, + 'hehmedialarabic': 0xFEEC, + 'heiseierasquare': 0x337B, + 'hekatakana': 0x30D8, + 'hekatakanahalfwidth': 0xFF8D, + 'hekutaarusquare': 0x3336, + 'henghook': 0x0267, + 'herutusquare': 0x3339, + 'het': 0x05D7, + 'hethebrew': 0x05D7, + 'hhook': 0x0266, + 'hhooksuperior': 0x02B1, + 'hieuhacirclekorean': 0x327B, + 'hieuhaparenkorean': 0x321B, + 'hieuhcirclekorean': 0x326D, + 'hieuhkorean': 0x314E, + 'hieuhparenkorean': 0x320D, + 'hihiragana': 0x3072, + 'hikatakana': 0x30D2, + 'hikatakanahalfwidth': 0xFF8B, + 'hiriq': 0x05B4, + 'hiriq14': 0x05B4, + 'hiriq21': 0x05B4, + 'hiriq2d': 0x05B4, + 'hiriqhebrew': 0x05B4, + 'hiriqnarrowhebrew': 0x05B4, + 'hiriqquarterhebrew': 0x05B4, + 'hiriqwidehebrew': 0x05B4, + 'hlinebelow': 0x1E96, + 'hmonospace': 0xFF48, + 'hoarmenian': 0x0570, + 'hohipthai': 0x0E2B, + 'hohiragana': 0x307B, + 'hokatakana': 0x30DB, + 'hokatakanahalfwidth': 0xFF8E, + 'holam': 0x05B9, + 'holam19': 0x05B9, + 'holam26': 0x05B9, + 'holam32': 0x05B9, + 'holamhebrew': 0x05B9, + 'holamnarrowhebrew': 0x05B9, + 'holamquarterhebrew': 0x05B9, + 'holamwidehebrew': 0x05B9, + 'honokhukthai': 0x0E2E, + 'hookabovecomb': 0x0309, + 'hookcmb': 0x0309, + 'hookpalatalizedbelowcmb': 0x0321, + 'hookretroflexbelowcmb': 0x0322, + 'hoonsquare': 0x3342, + 'horicoptic': 0x03E9, + 'horizontalbar': 0x2015, + 'horncmb': 0x031B, + 'hotsprings': 0x2668, + 'house': 0x2302, + 'hparen': 0x24A3, + 'hsuperior': 0x02B0, + 'hturned': 0x0265, + 'huhiragana': 0x3075, + 'huiitosquare': 0x3333, + 'hukatakana': 0x30D5, + 'hukatakanahalfwidth': 0xFF8C, + 'hungarumlaut': 0x02DD, + 'hungarumlautcmb': 0x030B, + 'hv': 0x0195, + 'hyphen': 0x002D, + 'hypheninferior': 0xF6E5, + 'hyphenmonospace': 0xFF0D, + 'hyphensmall': 0xFE63, + 'hyphensuperior': 0xF6E6, + 'hyphentwo': 0x2010, + 'i': 0x0069, + 'iacute': 0x00ED, + 'iacyrillic': 0x044F, + 'ibengali': 0x0987, + 'ibopomofo': 0x3127, + 'ibreve': 0x012D, + 'icaron': 0x01D0, + 'icircle': 0x24D8, + 'icircumflex': 0x00EE, + 'icyrillic': 0x0456, + 'idblgrave': 0x0209, + 'ideographearthcircle': 0x328F, + 'ideographfirecircle': 0x328B, + 'ideographicallianceparen': 0x323F, + 'ideographiccallparen': 0x323A, + 'ideographiccentrecircle': 0x32A5, + 'ideographicclose': 0x3006, + 'ideographiccomma': 0x3001, + 'ideographiccommaleft': 0xFF64, + 'ideographiccongratulationparen': 0x3237, + 'ideographiccorrectcircle': 0x32A3, + 'ideographicearthparen': 0x322F, + 'ideographicenterpriseparen': 0x323D, + 'ideographicexcellentcircle': 0x329D, + 'ideographicfestivalparen': 0x3240, + 'ideographicfinancialcircle': 0x3296, + 'ideographicfinancialparen': 0x3236, + 'ideographicfireparen': 0x322B, + 'ideographichaveparen': 0x3232, + 'ideographichighcircle': 0x32A4, + 'ideographiciterationmark': 0x3005, + 'ideographiclaborcircle': 0x3298, + 'ideographiclaborparen': 0x3238, + 'ideographicleftcircle': 0x32A7, + 'ideographiclowcircle': 0x32A6, + 'ideographicmedicinecircle': 0x32A9, + 'ideographicmetalparen': 0x322E, + 'ideographicmoonparen': 0x322A, + 'ideographicnameparen': 0x3234, + 'ideographicperiod': 0x3002, + 'ideographicprintcircle': 0x329E, + 'ideographicreachparen': 0x3243, + 'ideographicrepresentparen': 0x3239, + 'ideographicresourceparen': 0x323E, + 'ideographicrightcircle': 0x32A8, + 'ideographicsecretcircle': 0x3299, + 'ideographicselfparen': 0x3242, + 'ideographicsocietyparen': 0x3233, + 'ideographicspace': 0x3000, + 'ideographicspecialparen': 0x3235, + 'ideographicstockparen': 0x3231, + 'ideographicstudyparen': 0x323B, + 'ideographicsunparen': 0x3230, + 'ideographicsuperviseparen': 0x323C, + 'ideographicwaterparen': 0x322C, + 'ideographicwoodparen': 0x322D, + 'ideographiczero': 0x3007, + 'ideographmetalcircle': 0x328E, + 'ideographmooncircle': 0x328A, + 'ideographnamecircle': 0x3294, + 'ideographsuncircle': 0x3290, + 'ideographwatercircle': 0x328C, + 'ideographwoodcircle': 0x328D, + 'ideva': 0x0907, + 'idieresis': 0x00EF, + 'idieresisacute': 0x1E2F, + 'idieresiscyrillic': 0x04E5, + 'idotbelow': 0x1ECB, + 'iebrevecyrillic': 0x04D7, + 'iecyrillic': 0x0435, + 'ieungacirclekorean': 0x3275, + 'ieungaparenkorean': 0x3215, + 'ieungcirclekorean': 0x3267, + 'ieungkorean': 0x3147, + 'ieungparenkorean': 0x3207, + 'igrave': 0x00EC, + 'igujarati': 0x0A87, + 'igurmukhi': 0x0A07, + 'ihiragana': 0x3044, + 'ihookabove': 0x1EC9, + 'iibengali': 0x0988, + 'iicyrillic': 0x0438, + 'iideva': 0x0908, + 'iigujarati': 0x0A88, + 'iigurmukhi': 0x0A08, + 'iimatragurmukhi': 0x0A40, + 'iinvertedbreve': 0x020B, + 'iishortcyrillic': 0x0439, + 'iivowelsignbengali': 0x09C0, + 'iivowelsigndeva': 0x0940, + 'iivowelsigngujarati': 0x0AC0, + 'ij': 0x0133, + 'ikatakana': 0x30A4, + 'ikatakanahalfwidth': 0xFF72, + 'ikorean': 0x3163, + 'ilde': 0x02DC, + 'iluyhebrew': 0x05AC, + 'imacron': 0x012B, + 'imacroncyrillic': 0x04E3, + 'imageorapproximatelyequal': 0x2253, + 'imatragurmukhi': 0x0A3F, + 'imonospace': 0xFF49, + 'increment': 0x2206, + 'infinity': 0x221E, + 'iniarmenian': 0x056B, + 'integral': 0x222B, + 'integralbottom': 0x2321, + 'integralbt': 0x2321, + 'integralex': 0xF8F5, + 'integraltop': 0x2320, + 'integraltp': 0x2320, + 'intersection': 0x2229, + 'intisquare': 0x3305, + 'invbullet': 0x25D8, + 'invcircle': 0x25D9, + 'invsmileface': 0x263B, + 'iocyrillic': 0x0451, + 'iogonek': 0x012F, + 'iota': 0x03B9, + 'iotadieresis': 0x03CA, + 'iotadieresistonos': 0x0390, + 'iotalatin': 0x0269, + 'iotatonos': 0x03AF, + 'iparen': 0x24A4, + 'irigurmukhi': 0x0A72, + 'ismallhiragana': 0x3043, + 'ismallkatakana': 0x30A3, + 'ismallkatakanahalfwidth': 0xFF68, + 'issharbengali': 0x09FA, + 'istroke': 0x0268, + 'isuperior': 0xF6ED, + 'iterationhiragana': 0x309D, + 'iterationkatakana': 0x30FD, + 'itilde': 0x0129, + 'itildebelow': 0x1E2D, + 'iubopomofo': 0x3129, + 'iucyrillic': 0x044E, + 'ivowelsignbengali': 0x09BF, + 'ivowelsigndeva': 0x093F, + 'ivowelsigngujarati': 0x0ABF, + 'izhitsacyrillic': 0x0475, + 'izhitsadblgravecyrillic': 0x0477, + 'j': 0x006A, + 'jaarmenian': 0x0571, + 'jabengali': 0x099C, + 'jadeva': 0x091C, + 'jagujarati': 0x0A9C, + 'jagurmukhi': 0x0A1C, + 'jbopomofo': 0x3110, + 'jcaron': 0x01F0, + 'jcircle': 0x24D9, + 'jcircumflex': 0x0135, + 'jcrossedtail': 0x029D, + 'jdotlessstroke': 0x025F, + 'jecyrillic': 0x0458, + 'jeemarabic': 0x062C, + 'jeemfinalarabic': 0xFE9E, + 'jeeminitialarabic': 0xFE9F, + 'jeemmedialarabic': 0xFEA0, + 'jeharabic': 0x0698, + 'jehfinalarabic': 0xFB8B, + 'jhabengali': 0x099D, + 'jhadeva': 0x091D, + 'jhagujarati': 0x0A9D, + 'jhagurmukhi': 0x0A1D, + 'jheharmenian': 0x057B, + 'jis': 0x3004, + 'jmonospace': 0xFF4A, + 'jparen': 0x24A5, + 'jsuperior': 0x02B2, + 'k': 0x006B, + 'kabashkircyrillic': 0x04A1, + 'kabengali': 0x0995, + 'kacute': 0x1E31, + 'kacyrillic': 0x043A, + 'kadescendercyrillic': 0x049B, + 'kadeva': 0x0915, + 'kaf': 0x05DB, + 'kafarabic': 0x0643, + 'kafdagesh': 0xFB3B, + 'kafdageshhebrew': 0xFB3B, + 'kaffinalarabic': 0xFEDA, + 'kafhebrew': 0x05DB, + 'kafinitialarabic': 0xFEDB, + 'kafmedialarabic': 0xFEDC, + 'kafrafehebrew': 0xFB4D, + 'kagujarati': 0x0A95, + 'kagurmukhi': 0x0A15, + 'kahiragana': 0x304B, + 'kahookcyrillic': 0x04C4, + 'kakatakana': 0x30AB, + 'kakatakanahalfwidth': 0xFF76, + 'kappa': 0x03BA, + 'kappasymbolgreek': 0x03F0, + 'kapyeounmieumkorean': 0x3171, + 'kapyeounphieuphkorean': 0x3184, + 'kapyeounpieupkorean': 0x3178, + 'kapyeounssangpieupkorean': 0x3179, + 'karoriisquare': 0x330D, + 'kashidaautoarabic': 0x0640, + 'kashidaautonosidebearingarabic': 0x0640, + 'kasmallkatakana': 0x30F5, + 'kasquare': 0x3384, + 'kasraarabic': 0x0650, + 'kasratanarabic': 0x064D, + 'kastrokecyrillic': 0x049F, + 'katahiraprolongmarkhalfwidth': 0xFF70, + 'kaverticalstrokecyrillic': 0x049D, + 'kbopomofo': 0x310E, + 'kcalsquare': 0x3389, + 'kcaron': 0x01E9, + 'kcedilla': 0x0137, + 'kcircle': 0x24DA, + 'kcommaaccent': 0x0137, + 'kdotbelow': 0x1E33, + 'keharmenian': 0x0584, + 'kehiragana': 0x3051, + 'kekatakana': 0x30B1, + 'kekatakanahalfwidth': 0xFF79, + 'kenarmenian': 0x056F, + 'kesmallkatakana': 0x30F6, + 'kgreenlandic': 0x0138, + 'khabengali': 0x0996, + 'khacyrillic': 0x0445, + 'khadeva': 0x0916, + 'khagujarati': 0x0A96, + 'khagurmukhi': 0x0A16, + 'khaharabic': 0x062E, + 'khahfinalarabic': 0xFEA6, + 'khahinitialarabic': 0xFEA7, + 'khahmedialarabic': 0xFEA8, + 'kheicoptic': 0x03E7, + 'khhadeva': 0x0959, + 'khhagurmukhi': 0x0A59, + 'khieukhacirclekorean': 0x3278, + 'khieukhaparenkorean': 0x3218, + 'khieukhcirclekorean': 0x326A, + 'khieukhkorean': 0x314B, + 'khieukhparenkorean': 0x320A, + 'khokhaithai': 0x0E02, + 'khokhonthai': 0x0E05, + 'khokhuatthai': 0x0E03, + 'khokhwaithai': 0x0E04, + 'khomutthai': 0x0E5B, + 'khook': 0x0199, + 'khorakhangthai': 0x0E06, + 'khzsquare': 0x3391, + 'kihiragana': 0x304D, + 'kikatakana': 0x30AD, + 'kikatakanahalfwidth': 0xFF77, + 'kiroguramusquare': 0x3315, + 'kiromeetorusquare': 0x3316, + 'kirosquare': 0x3314, + 'kiyeokacirclekorean': 0x326E, + 'kiyeokaparenkorean': 0x320E, + 'kiyeokcirclekorean': 0x3260, + 'kiyeokkorean': 0x3131, + 'kiyeokparenkorean': 0x3200, + 'kiyeoksioskorean': 0x3133, + 'kjecyrillic': 0x045C, + 'klinebelow': 0x1E35, + 'klsquare': 0x3398, + 'kmcubedsquare': 0x33A6, + 'kmonospace': 0xFF4B, + 'kmsquaredsquare': 0x33A2, + 'kohiragana': 0x3053, + 'kohmsquare': 0x33C0, + 'kokaithai': 0x0E01, + 'kokatakana': 0x30B3, + 'kokatakanahalfwidth': 0xFF7A, + 'kooposquare': 0x331E, + 'koppacyrillic': 0x0481, + 'koreanstandardsymbol': 0x327F, + 'koroniscmb': 0x0343, + 'kparen': 0x24A6, + 'kpasquare': 0x33AA, + 'ksicyrillic': 0x046F, + 'ktsquare': 0x33CF, + 'kturned': 0x029E, + 'kuhiragana': 0x304F, + 'kukatakana': 0x30AF, + 'kukatakanahalfwidth': 0xFF78, + 'kvsquare': 0x33B8, + 'kwsquare': 0x33BE, + 'l': 0x006C, + 'labengali': 0x09B2, + 'lacute': 0x013A, + 'ladeva': 0x0932, + 'lagujarati': 0x0AB2, + 'lagurmukhi': 0x0A32, + 'lakkhangyaothai': 0x0E45, + 'lamaleffinalarabic': 0xFEFC, + 'lamalefhamzaabovefinalarabic': 0xFEF8, + 'lamalefhamzaaboveisolatedarabic': 0xFEF7, + 'lamalefhamzabelowfinalarabic': 0xFEFA, + 'lamalefhamzabelowisolatedarabic': 0xFEF9, + 'lamalefisolatedarabic': 0xFEFB, + 'lamalefmaddaabovefinalarabic': 0xFEF6, + 'lamalefmaddaaboveisolatedarabic': 0xFEF5, + 'lamarabic': 0x0644, + 'lambda': 0x03BB, + 'lambdastroke': 0x019B, + 'lamed': 0x05DC, + 'lameddagesh': 0xFB3C, + 'lameddageshhebrew': 0xFB3C, + 'lamedhebrew': 0x05DC, + 'lamfinalarabic': 0xFEDE, + 'lamhahinitialarabic': 0xFCCA, + 'laminitialarabic': 0xFEDF, + 'lamjeeminitialarabic': 0xFCC9, + 'lamkhahinitialarabic': 0xFCCB, + 'lamlamhehisolatedarabic': 0xFDF2, + 'lammedialarabic': 0xFEE0, + 'lammeemhahinitialarabic': 0xFD88, + 'lammeeminitialarabic': 0xFCCC, + 'largecircle': 0x25EF, + 'lbar': 0x019A, + 'lbelt': 0x026C, + 'lbopomofo': 0x310C, + 'lcaron': 0x013E, + 'lcedilla': 0x013C, + 'lcircle': 0x24DB, + 'lcircumflexbelow': 0x1E3D, + 'lcommaaccent': 0x013C, + 'ldot': 0x0140, + 'ldotaccent': 0x0140, + 'ldotbelow': 0x1E37, + 'ldotbelowmacron': 0x1E39, + 'leftangleabovecmb': 0x031A, + 'lefttackbelowcmb': 0x0318, + 'less': 0x003C, + 'lessequal': 0x2264, + 'lessequalorgreater': 0x22DA, + 'lessmonospace': 0xFF1C, + 'lessorequivalent': 0x2272, + 'lessorgreater': 0x2276, + 'lessoverequal': 0x2266, + 'lesssmall': 0xFE64, + 'lezh': 0x026E, + 'lfblock': 0x258C, + 'lhookretroflex': 0x026D, + 'lira': 0x20A4, + 'liwnarmenian': 0x056C, + 'lj': 0x01C9, + 'ljecyrillic': 0x0459, + 'll': 0xF6C0, + 'lladeva': 0x0933, + 'llagujarati': 0x0AB3, + 'llinebelow': 0x1E3B, + 'llladeva': 0x0934, + 'llvocalicbengali': 0x09E1, + 'llvocalicdeva': 0x0961, + 'llvocalicvowelsignbengali': 0x09E3, + 'llvocalicvowelsigndeva': 0x0963, + 'lmiddletilde': 0x026B, + 'lmonospace': 0xFF4C, + 'lmsquare': 0x33D0, + 'lochulathai': 0x0E2C, + 'logicaland': 0x2227, + 'logicalnot': 0x00AC, + 'logicalnotreversed': 0x2310, + 'logicalor': 0x2228, + 'lolingthai': 0x0E25, + 'longs': 0x017F, + 'lowlinecenterline': 0xFE4E, + 'lowlinecmb': 0x0332, + 'lowlinedashed': 0xFE4D, + 'lozenge': 0x25CA, + 'lparen': 0x24A7, + 'lslash': 0x0142, + 'lsquare': 0x2113, + 'lsuperior': 0xF6EE, + 'ltshade': 0x2591, + 'luthai': 0x0E26, + 'lvocalicbengali': 0x098C, + 'lvocalicdeva': 0x090C, + 'lvocalicvowelsignbengali': 0x09E2, + 'lvocalicvowelsigndeva': 0x0962, + 'lxsquare': 0x33D3, + 'm': 0x006D, + 'mabengali': 0x09AE, + 'macron': 0x00AF, + 'macronbelowcmb': 0x0331, + 'macroncmb': 0x0304, + 'macronlowmod': 0x02CD, + 'macronmonospace': 0xFFE3, + 'macute': 0x1E3F, + 'madeva': 0x092E, + 'magujarati': 0x0AAE, + 'magurmukhi': 0x0A2E, + 'mahapakhhebrew': 0x05A4, + 'mahapakhlefthebrew': 0x05A4, + 'mahiragana': 0x307E, + 'maichattawalowleftthai': 0xF895, + 'maichattawalowrightthai': 0xF894, + 'maichattawathai': 0x0E4B, + 'maichattawaupperleftthai': 0xF893, + 'maieklowleftthai': 0xF88C, + 'maieklowrightthai': 0xF88B, + 'maiekthai': 0x0E48, + 'maiekupperleftthai': 0xF88A, + 'maihanakatleftthai': 0xF884, + 'maihanakatthai': 0x0E31, + 'maitaikhuleftthai': 0xF889, + 'maitaikhuthai': 0x0E47, + 'maitholowleftthai': 0xF88F, + 'maitholowrightthai': 0xF88E, + 'maithothai': 0x0E49, + 'maithoupperleftthai': 0xF88D, + 'maitrilowleftthai': 0xF892, + 'maitrilowrightthai': 0xF891, + 'maitrithai': 0x0E4A, + 'maitriupperleftthai': 0xF890, + 'maiyamokthai': 0x0E46, + 'makatakana': 0x30DE, + 'makatakanahalfwidth': 0xFF8F, + 'male': 0x2642, + 'mansyonsquare': 0x3347, + 'maqafhebrew': 0x05BE, + 'mars': 0x2642, + 'masoracirclehebrew': 0x05AF, + 'masquare': 0x3383, + 'mbopomofo': 0x3107, + 'mbsquare': 0x33D4, + 'mcircle': 0x24DC, + 'mcubedsquare': 0x33A5, + 'mdotaccent': 0x1E41, + 'mdotbelow': 0x1E43, + 'meemarabic': 0x0645, + 'meemfinalarabic': 0xFEE2, + 'meeminitialarabic': 0xFEE3, + 'meemmedialarabic': 0xFEE4, + 'meemmeeminitialarabic': 0xFCD1, + 'meemmeemisolatedarabic': 0xFC48, + 'meetorusquare': 0x334D, + 'mehiragana': 0x3081, + 'meizierasquare': 0x337E, + 'mekatakana': 0x30E1, + 'mekatakanahalfwidth': 0xFF92, + 'mem': 0x05DE, + 'memdagesh': 0xFB3E, + 'memdageshhebrew': 0xFB3E, + 'memhebrew': 0x05DE, + 'menarmenian': 0x0574, + 'merkhahebrew': 0x05A5, + 'merkhakefulahebrew': 0x05A6, + 'merkhakefulalefthebrew': 0x05A6, + 'merkhalefthebrew': 0x05A5, + 'mhook': 0x0271, + 'mhzsquare': 0x3392, + 'middledotkatakanahalfwidth': 0xFF65, + 'middot': 0x00B7, + 'mieumacirclekorean': 0x3272, + 'mieumaparenkorean': 0x3212, + 'mieumcirclekorean': 0x3264, + 'mieumkorean': 0x3141, + 'mieumpansioskorean': 0x3170, + 'mieumparenkorean': 0x3204, + 'mieumpieupkorean': 0x316E, + 'mieumsioskorean': 0x316F, + 'mihiragana': 0x307F, + 'mikatakana': 0x30DF, + 'mikatakanahalfwidth': 0xFF90, + 'minus': 0x2212, + 'minusbelowcmb': 0x0320, + 'minuscircle': 0x2296, + 'minusmod': 0x02D7, + 'minusplus': 0x2213, + 'minute': 0x2032, + 'miribaarusquare': 0x334A, + 'mirisquare': 0x3349, + 'mlonglegturned': 0x0270, + 'mlsquare': 0x3396, + 'mmcubedsquare': 0x33A3, + 'mmonospace': 0xFF4D, + 'mmsquaredsquare': 0x339F, + 'mohiragana': 0x3082, + 'mohmsquare': 0x33C1, + 'mokatakana': 0x30E2, + 'mokatakanahalfwidth': 0xFF93, + 'molsquare': 0x33D6, + 'momathai': 0x0E21, + 'moverssquare': 0x33A7, + 'moverssquaredsquare': 0x33A8, + 'mparen': 0x24A8, + 'mpasquare': 0x33AB, + 'mssquare': 0x33B3, + 'msuperior': 0xF6EF, + 'mturned': 0x026F, + 'mu': 0x00B5, + 'mu1': 0x00B5, + 'muasquare': 0x3382, + 'muchgreater': 0x226B, + 'muchless': 0x226A, + 'mufsquare': 0x338C, + 'mugreek': 0x03BC, + 'mugsquare': 0x338D, + 'muhiragana': 0x3080, + 'mukatakana': 0x30E0, + 'mukatakanahalfwidth': 0xFF91, + 'mulsquare': 0x3395, + 'multiply': 0x00D7, + 'mumsquare': 0x339B, + 'munahhebrew': 0x05A3, + 'munahlefthebrew': 0x05A3, + 'musicalnote': 0x266A, + 'musicalnotedbl': 0x266B, + 'musicflatsign': 0x266D, + 'musicsharpsign': 0x266F, + 'mussquare': 0x33B2, + 'muvsquare': 0x33B6, + 'muwsquare': 0x33BC, + 'mvmegasquare': 0x33B9, + 'mvsquare': 0x33B7, + 'mwmegasquare': 0x33BF, + 'mwsquare': 0x33BD, + 'n': 0x006E, + 'nabengali': 0x09A8, + 'nabla': 0x2207, + 'nacute': 0x0144, + 'nadeva': 0x0928, + 'nagujarati': 0x0AA8, + 'nagurmukhi': 0x0A28, + 'nahiragana': 0x306A, + 'nakatakana': 0x30CA, + 'nakatakanahalfwidth': 0xFF85, + 'napostrophe': 0x0149, + 'nasquare': 0x3381, + 'nbopomofo': 0x310B, + 'nbspace': 0x00A0, + 'ncaron': 0x0148, + 'ncedilla': 0x0146, + 'ncircle': 0x24DD, + 'ncircumflexbelow': 0x1E4B, + 'ncommaaccent': 0x0146, + 'ndotaccent': 0x1E45, + 'ndotbelow': 0x1E47, + 'nehiragana': 0x306D, + 'nekatakana': 0x30CD, + 'nekatakanahalfwidth': 0xFF88, + 'newsheqelsign': 0x20AA, + 'nfsquare': 0x338B, + 'ngabengali': 0x0999, + 'ngadeva': 0x0919, + 'ngagujarati': 0x0A99, + 'ngagurmukhi': 0x0A19, + 'ngonguthai': 0x0E07, + 'nhiragana': 0x3093, + 'nhookleft': 0x0272, + 'nhookretroflex': 0x0273, + 'nieunacirclekorean': 0x326F, + 'nieunaparenkorean': 0x320F, + 'nieuncieuckorean': 0x3135, + 'nieuncirclekorean': 0x3261, + 'nieunhieuhkorean': 0x3136, + 'nieunkorean': 0x3134, + 'nieunpansioskorean': 0x3168, + 'nieunparenkorean': 0x3201, + 'nieunsioskorean': 0x3167, + 'nieuntikeutkorean': 0x3166, + 'nihiragana': 0x306B, + 'nikatakana': 0x30CB, + 'nikatakanahalfwidth': 0xFF86, + 'nikhahitleftthai': 0xF899, + 'nikhahitthai': 0x0E4D, + 'nine': 0x0039, + 'ninearabic': 0x0669, + 'ninebengali': 0x09EF, + 'ninecircle': 0x2468, + 'ninecircleinversesansserif': 0x2792, + 'ninedeva': 0x096F, + 'ninegujarati': 0x0AEF, + 'ninegurmukhi': 0x0A6F, + 'ninehackarabic': 0x0669, + 'ninehangzhou': 0x3029, + 'nineideographicparen': 0x3228, + 'nineinferior': 0x2089, + 'ninemonospace': 0xFF19, + 'nineoldstyle': 0xF739, + 'nineparen': 0x247C, + 'nineperiod': 0x2490, + 'ninepersian': 0x06F9, + 'nineroman': 0x2178, + 'ninesuperior': 0x2079, + 'nineteencircle': 0x2472, + 'nineteenparen': 0x2486, + 'nineteenperiod': 0x249A, + 'ninethai': 0x0E59, + 'nj': 0x01CC, + 'njecyrillic': 0x045A, + 'nkatakana': 0x30F3, + 'nkatakanahalfwidth': 0xFF9D, + 'nlegrightlong': 0x019E, + 'nlinebelow': 0x1E49, + 'nmonospace': 0xFF4E, + 'nmsquare': 0x339A, + 'nnabengali': 0x09A3, + 'nnadeva': 0x0923, + 'nnagujarati': 0x0AA3, + 'nnagurmukhi': 0x0A23, + 'nnnadeva': 0x0929, + 'nohiragana': 0x306E, + 'nokatakana': 0x30CE, + 'nokatakanahalfwidth': 0xFF89, + 'nonbreakingspace': 0x00A0, + 'nonenthai': 0x0E13, + 'nonuthai': 0x0E19, + 'noonarabic': 0x0646, + 'noonfinalarabic': 0xFEE6, + 'noonghunnaarabic': 0x06BA, + 'noonghunnafinalarabic': 0xFB9F, + 'nooninitialarabic': 0xFEE7, + 'noonjeeminitialarabic': 0xFCD2, + 'noonjeemisolatedarabic': 0xFC4B, + 'noonmedialarabic': 0xFEE8, + 'noonmeeminitialarabic': 0xFCD5, + 'noonmeemisolatedarabic': 0xFC4E, + 'noonnoonfinalarabic': 0xFC8D, + 'notcontains': 0x220C, + 'notelement': 0x2209, + 'notelementof': 0x2209, + 'notequal': 0x2260, + 'notgreater': 0x226F, + 'notgreaternorequal': 0x2271, + 'notgreaternorless': 0x2279, + 'notidentical': 0x2262, + 'notless': 0x226E, + 'notlessnorequal': 0x2270, + 'notparallel': 0x2226, + 'notprecedes': 0x2280, + 'notsubset': 0x2284, + 'notsucceeds': 0x2281, + 'notsuperset': 0x2285, + 'nowarmenian': 0x0576, + 'nparen': 0x24A9, + 'nssquare': 0x33B1, + 'nsuperior': 0x207F, + 'ntilde': 0x00F1, + 'nu': 0x03BD, + 'nuhiragana': 0x306C, + 'nukatakana': 0x30CC, + 'nukatakanahalfwidth': 0xFF87, + 'nuktabengali': 0x09BC, + 'nuktadeva': 0x093C, + 'nuktagujarati': 0x0ABC, + 'nuktagurmukhi': 0x0A3C, + 'numbersign': 0x0023, + 'numbersignmonospace': 0xFF03, + 'numbersignsmall': 0xFE5F, + 'numeralsigngreek': 0x0374, + 'numeralsignlowergreek': 0x0375, + 'numero': 0x2116, + 'nun': 0x05E0, + 'nundagesh': 0xFB40, + 'nundageshhebrew': 0xFB40, + 'nunhebrew': 0x05E0, + 'nvsquare': 0x33B5, + 'nwsquare': 0x33BB, + 'nyabengali': 0x099E, + 'nyadeva': 0x091E, + 'nyagujarati': 0x0A9E, + 'nyagurmukhi': 0x0A1E, + 'o': 0x006F, + 'oacute': 0x00F3, + 'oangthai': 0x0E2D, + 'obarred': 0x0275, + 'obarredcyrillic': 0x04E9, + 'obarreddieresiscyrillic': 0x04EB, + 'obengali': 0x0993, + 'obopomofo': 0x311B, + 'obreve': 0x014F, + 'ocandradeva': 0x0911, + 'ocandragujarati': 0x0A91, + 'ocandravowelsigndeva': 0x0949, + 'ocandravowelsigngujarati': 0x0AC9, + 'ocaron': 0x01D2, + 'ocircle': 0x24DE, + 'ocircumflex': 0x00F4, + 'ocircumflexacute': 0x1ED1, + 'ocircumflexdotbelow': 0x1ED9, + 'ocircumflexgrave': 0x1ED3, + 'ocircumflexhookabove': 0x1ED5, + 'ocircumflextilde': 0x1ED7, + 'ocyrillic': 0x043E, + 'odblacute': 0x0151, + 'odblgrave': 0x020D, + 'odeva': 0x0913, + 'odieresis': 0x00F6, + 'odieresiscyrillic': 0x04E7, + 'odotbelow': 0x1ECD, + 'oe': 0x0153, + 'oekorean': 0x315A, + 'ogonek': 0x02DB, + 'ogonekcmb': 0x0328, + 'ograve': 0x00F2, + 'ogujarati': 0x0A93, + 'oharmenian': 0x0585, + 'ohiragana': 0x304A, + 'ohookabove': 0x1ECF, + 'ohorn': 0x01A1, + 'ohornacute': 0x1EDB, + 'ohorndotbelow': 0x1EE3, + 'ohorngrave': 0x1EDD, + 'ohornhookabove': 0x1EDF, + 'ohorntilde': 0x1EE1, + 'ohungarumlaut': 0x0151, + 'oi': 0x01A3, + 'oinvertedbreve': 0x020F, + 'okatakana': 0x30AA, + 'okatakanahalfwidth': 0xFF75, + 'okorean': 0x3157, + 'olehebrew': 0x05AB, + 'omacron': 0x014D, + 'omacronacute': 0x1E53, + 'omacrongrave': 0x1E51, + 'omdeva': 0x0950, + 'omega': 0x03C9, + 'omega1': 0x03D6, + 'omegacyrillic': 0x0461, + 'omegalatinclosed': 0x0277, + 'omegaroundcyrillic': 0x047B, + 'omegatitlocyrillic': 0x047D, + 'omegatonos': 0x03CE, + 'omgujarati': 0x0AD0, + 'omicron': 0x03BF, + 'omicrontonos': 0x03CC, + 'omonospace': 0xFF4F, + 'one': 0x0031, + 'onearabic': 0x0661, + 'onebengali': 0x09E7, + 'onecircle': 0x2460, + 'onecircleinversesansserif': 0x278A, + 'onedeva': 0x0967, + 'onedotenleader': 0x2024, + 'oneeighth': 0x215B, + 'onefitted': 0xF6DC, + 'onegujarati': 0x0AE7, + 'onegurmukhi': 0x0A67, + 'onehackarabic': 0x0661, + 'onehalf': 0x00BD, + 'onehangzhou': 0x3021, + 'oneideographicparen': 0x3220, + 'oneinferior': 0x2081, + 'onemonospace': 0xFF11, + 'onenumeratorbengali': 0x09F4, + 'oneoldstyle': 0xF731, + 'oneparen': 0x2474, + 'oneperiod': 0x2488, + 'onepersian': 0x06F1, + 'onequarter': 0x00BC, + 'oneroman': 0x2170, + 'onesuperior': 0x00B9, + 'onethai': 0x0E51, + 'onethird': 0x2153, + 'oogonek': 0x01EB, + 'oogonekmacron': 0x01ED, + 'oogurmukhi': 0x0A13, + 'oomatragurmukhi': 0x0A4B, + 'oopen': 0x0254, + 'oparen': 0x24AA, + 'openbullet': 0x25E6, + 'option': 0x2325, + 'ordfeminine': 0x00AA, + 'ordmasculine': 0x00BA, + 'orthogonal': 0x221F, + 'oshortdeva': 0x0912, + 'oshortvowelsigndeva': 0x094A, + 'oslash': 0x00F8, + 'oslashacute': 0x01FF, + 'osmallhiragana': 0x3049, + 'osmallkatakana': 0x30A9, + 'osmallkatakanahalfwidth': 0xFF6B, + 'ostrokeacute': 0x01FF, + 'osuperior': 0xF6F0, + 'otcyrillic': 0x047F, + 'otilde': 0x00F5, + 'otildeacute': 0x1E4D, + 'otildedieresis': 0x1E4F, + 'oubopomofo': 0x3121, + 'overline': 0x203E, + 'overlinecenterline': 0xFE4A, + 'overlinecmb': 0x0305, + 'overlinedashed': 0xFE49, + 'overlinedblwavy': 0xFE4C, + 'overlinewavy': 0xFE4B, + 'overscore': 0x00AF, + 'ovowelsignbengali': 0x09CB, + 'ovowelsigndeva': 0x094B, + 'ovowelsigngujarati': 0x0ACB, + 'p': 0x0070, + 'paampssquare': 0x3380, + 'paasentosquare': 0x332B, + 'pabengali': 0x09AA, + 'pacute': 0x1E55, + 'padeva': 0x092A, + 'pagedown': 0x21DF, + 'pageup': 0x21DE, + 'pagujarati': 0x0AAA, + 'pagurmukhi': 0x0A2A, + 'pahiragana': 0x3071, + 'paiyannoithai': 0x0E2F, + 'pakatakana': 0x30D1, + 'palatalizationcyrilliccmb': 0x0484, + 'palochkacyrillic': 0x04C0, + 'pansioskorean': 0x317F, + 'paragraph': 0x00B6, + 'parallel': 0x2225, + 'parenleft': 0x0028, + 'parenleftaltonearabic': 0xFD3E, + 'parenleftbt': 0xF8ED, + 'parenleftex': 0xF8EC, + 'parenleftinferior': 0x208D, + 'parenleftmonospace': 0xFF08, + 'parenleftsmall': 0xFE59, + 'parenleftsuperior': 0x207D, + 'parenlefttp': 0xF8EB, + 'parenleftvertical': 0xFE35, + 'parenright': 0x0029, + 'parenrightaltonearabic': 0xFD3F, + 'parenrightbt': 0xF8F8, + 'parenrightex': 0xF8F7, + 'parenrightinferior': 0x208E, + 'parenrightmonospace': 0xFF09, + 'parenrightsmall': 0xFE5A, + 'parenrightsuperior': 0x207E, + 'parenrighttp': 0xF8F6, + 'parenrightvertical': 0xFE36, + 'partialdiff': 0x2202, + 'paseqhebrew': 0x05C0, + 'pashtahebrew': 0x0599, + 'pasquare': 0x33A9, + 'patah': 0x05B7, + 'patah11': 0x05B7, + 'patah1d': 0x05B7, + 'patah2a': 0x05B7, + 'patahhebrew': 0x05B7, + 'patahnarrowhebrew': 0x05B7, + 'patahquarterhebrew': 0x05B7, + 'patahwidehebrew': 0x05B7, + 'pazerhebrew': 0x05A1, + 'pbopomofo': 0x3106, + 'pcircle': 0x24DF, + 'pdotaccent': 0x1E57, + 'pe': 0x05E4, + 'pecyrillic': 0x043F, + 'pedagesh': 0xFB44, + 'pedageshhebrew': 0xFB44, + 'peezisquare': 0x333B, + 'pefinaldageshhebrew': 0xFB43, + 'peharabic': 0x067E, + 'peharmenian': 0x057A, + 'pehebrew': 0x05E4, + 'pehfinalarabic': 0xFB57, + 'pehinitialarabic': 0xFB58, + 'pehiragana': 0x307A, + 'pehmedialarabic': 0xFB59, + 'pekatakana': 0x30DA, + 'pemiddlehookcyrillic': 0x04A7, + 'perafehebrew': 0xFB4E, + 'percent': 0x0025, + 'percentarabic': 0x066A, + 'percentmonospace': 0xFF05, + 'percentsmall': 0xFE6A, + 'period': 0x002E, + 'periodarmenian': 0x0589, + 'periodcentered': 0x00B7, + 'periodhalfwidth': 0xFF61, + 'periodinferior': 0xF6E7, + 'periodmonospace': 0xFF0E, + 'periodsmall': 0xFE52, + 'periodsuperior': 0xF6E8, + 'perispomenigreekcmb': 0x0342, + 'perpendicular': 0x22A5, + 'perthousand': 0x2030, + 'peseta': 0x20A7, + 'pfsquare': 0x338A, + 'phabengali': 0x09AB, + 'phadeva': 0x092B, + 'phagujarati': 0x0AAB, + 'phagurmukhi': 0x0A2B, + 'phi': 0x03C6, + 'phi1': 0x03D5, + 'phieuphacirclekorean': 0x327A, + 'phieuphaparenkorean': 0x321A, + 'phieuphcirclekorean': 0x326C, + 'phieuphkorean': 0x314D, + 'phieuphparenkorean': 0x320C, + 'philatin': 0x0278, + 'phinthuthai': 0x0E3A, + 'phisymbolgreek': 0x03D5, + 'phook': 0x01A5, + 'phophanthai': 0x0E1E, + 'phophungthai': 0x0E1C, + 'phosamphaothai': 0x0E20, + 'pi': 0x03C0, + 'pieupacirclekorean': 0x3273, + 'pieupaparenkorean': 0x3213, + 'pieupcieuckorean': 0x3176, + 'pieupcirclekorean': 0x3265, + 'pieupkiyeokkorean': 0x3172, + 'pieupkorean': 0x3142, + 'pieupparenkorean': 0x3205, + 'pieupsioskiyeokkorean': 0x3174, + 'pieupsioskorean': 0x3144, + 'pieupsiostikeutkorean': 0x3175, + 'pieupthieuthkorean': 0x3177, + 'pieuptikeutkorean': 0x3173, + 'pihiragana': 0x3074, + 'pikatakana': 0x30D4, + 'pisymbolgreek': 0x03D6, + 'piwrarmenian': 0x0583, + 'plus': 0x002B, + 'plusbelowcmb': 0x031F, + 'pluscircle': 0x2295, + 'plusminus': 0x00B1, + 'plusmod': 0x02D6, + 'plusmonospace': 0xFF0B, + 'plussmall': 0xFE62, + 'plussuperior': 0x207A, + 'pmonospace': 0xFF50, + 'pmsquare': 0x33D8, + 'pohiragana': 0x307D, + 'pointingindexdownwhite': 0x261F, + 'pointingindexleftwhite': 0x261C, + 'pointingindexrightwhite': 0x261E, + 'pointingindexupwhite': 0x261D, + 'pokatakana': 0x30DD, + 'poplathai': 0x0E1B, + 'postalmark': 0x3012, + 'postalmarkface': 0x3020, + 'pparen': 0x24AB, + 'precedes': 0x227A, + 'prescription': 0x211E, + 'primemod': 0x02B9, + 'primereversed': 0x2035, + 'product': 0x220F, + 'projective': 0x2305, + 'prolongedkana': 0x30FC, + 'propellor': 0x2318, + 'propersubset': 0x2282, + 'propersuperset': 0x2283, + 'proportion': 0x2237, + 'proportional': 0x221D, + 'psi': 0x03C8, + 'psicyrillic': 0x0471, + 'psilipneumatacyrilliccmb': 0x0486, + 'pssquare': 0x33B0, + 'puhiragana': 0x3077, + 'pukatakana': 0x30D7, + 'pvsquare': 0x33B4, + 'pwsquare': 0x33BA, + 'q': 0x0071, + 'qadeva': 0x0958, + 'qadmahebrew': 0x05A8, + 'qafarabic': 0x0642, + 'qaffinalarabic': 0xFED6, + 'qafinitialarabic': 0xFED7, + 'qafmedialarabic': 0xFED8, + 'qamats': 0x05B8, + 'qamats10': 0x05B8, + 'qamats1a': 0x05B8, + 'qamats1c': 0x05B8, + 'qamats27': 0x05B8, + 'qamats29': 0x05B8, + 'qamats33': 0x05B8, + 'qamatsde': 0x05B8, + 'qamatshebrew': 0x05B8, + 'qamatsnarrowhebrew': 0x05B8, + 'qamatsqatanhebrew': 0x05B8, + 'qamatsqatannarrowhebrew': 0x05B8, + 'qamatsqatanquarterhebrew': 0x05B8, + 'qamatsqatanwidehebrew': 0x05B8, + 'qamatsquarterhebrew': 0x05B8, + 'qamatswidehebrew': 0x05B8, + 'qarneyparahebrew': 0x059F, + 'qbopomofo': 0x3111, + 'qcircle': 0x24E0, + 'qhook': 0x02A0, + 'qmonospace': 0xFF51, + 'qof': 0x05E7, + 'qofdagesh': 0xFB47, + 'qofdageshhebrew': 0xFB47, + 'qofhebrew': 0x05E7, + 'qparen': 0x24AC, + 'quarternote': 0x2669, + 'qubuts': 0x05BB, + 'qubuts18': 0x05BB, + 'qubuts25': 0x05BB, + 'qubuts31': 0x05BB, + 'qubutshebrew': 0x05BB, + 'qubutsnarrowhebrew': 0x05BB, + 'qubutsquarterhebrew': 0x05BB, + 'qubutswidehebrew': 0x05BB, + 'question': 0x003F, + 'questionarabic': 0x061F, + 'questionarmenian': 0x055E, + 'questiondown': 0x00BF, + 'questiondownsmall': 0xF7BF, + 'questiongreek': 0x037E, + 'questionmonospace': 0xFF1F, + 'questionsmall': 0xF73F, + 'quotedbl': 0x0022, + 'quotedblbase': 0x201E, + 'quotedblleft': 0x201C, + 'quotedblmonospace': 0xFF02, + 'quotedblprime': 0x301E, + 'quotedblprimereversed': 0x301D, + 'quotedblright': 0x201D, + 'quoteleft': 0x2018, + 'quoteleftreversed': 0x201B, + 'quotereversed': 0x201B, + 'quoteright': 0x2019, + 'quoterightn': 0x0149, + 'quotesinglbase': 0x201A, + 'quotesingle': 0x0027, + 'quotesinglemonospace': 0xFF07, + 'r': 0x0072, + 'raarmenian': 0x057C, + 'rabengali': 0x09B0, + 'racute': 0x0155, + 'radeva': 0x0930, + 'radical': 0x221A, + 'radicalex': 0xF8E5, + 'radoverssquare': 0x33AE, + 'radoverssquaredsquare': 0x33AF, + 'radsquare': 0x33AD, + 'rafe': 0x05BF, + 'rafehebrew': 0x05BF, + 'ragujarati': 0x0AB0, + 'ragurmukhi': 0x0A30, + 'rahiragana': 0x3089, + 'rakatakana': 0x30E9, + 'rakatakanahalfwidth': 0xFF97, + 'ralowerdiagonalbengali': 0x09F1, + 'ramiddlediagonalbengali': 0x09F0, + 'ramshorn': 0x0264, + 'ratio': 0x2236, + 'rbopomofo': 0x3116, + 'rcaron': 0x0159, + 'rcedilla': 0x0157, + 'rcircle': 0x24E1, + 'rcommaaccent': 0x0157, + 'rdblgrave': 0x0211, + 'rdotaccent': 0x1E59, + 'rdotbelow': 0x1E5B, + 'rdotbelowmacron': 0x1E5D, + 'referencemark': 0x203B, + 'reflexsubset': 0x2286, + 'reflexsuperset': 0x2287, + 'registered': 0x00AE, + 'registersans': 0xF8E8, + 'registerserif': 0xF6DA, + 'reharabic': 0x0631, + 'reharmenian': 0x0580, + 'rehfinalarabic': 0xFEAE, + 'rehiragana': 0x308C, + 'rekatakana': 0x30EC, + 'rekatakanahalfwidth': 0xFF9A, + 'resh': 0x05E8, + 'reshdageshhebrew': 0xFB48, + 'reshhebrew': 0x05E8, + 'reversedtilde': 0x223D, + 'reviahebrew': 0x0597, + 'reviamugrashhebrew': 0x0597, + 'revlogicalnot': 0x2310, + 'rfishhook': 0x027E, + 'rfishhookreversed': 0x027F, + 'rhabengali': 0x09DD, + 'rhadeva': 0x095D, + 'rho': 0x03C1, + 'rhook': 0x027D, + 'rhookturned': 0x027B, + 'rhookturnedsuperior': 0x02B5, + 'rhosymbolgreek': 0x03F1, + 'rhotichookmod': 0x02DE, + 'rieulacirclekorean': 0x3271, + 'rieulaparenkorean': 0x3211, + 'rieulcirclekorean': 0x3263, + 'rieulhieuhkorean': 0x3140, + 'rieulkiyeokkorean': 0x313A, + 'rieulkiyeoksioskorean': 0x3169, + 'rieulkorean': 0x3139, + 'rieulmieumkorean': 0x313B, + 'rieulpansioskorean': 0x316C, + 'rieulparenkorean': 0x3203, + 'rieulphieuphkorean': 0x313F, + 'rieulpieupkorean': 0x313C, + 'rieulpieupsioskorean': 0x316B, + 'rieulsioskorean': 0x313D, + 'rieulthieuthkorean': 0x313E, + 'rieultikeutkorean': 0x316A, + 'rieulyeorinhieuhkorean': 0x316D, + 'rightangle': 0x221F, + 'righttackbelowcmb': 0x0319, + 'righttriangle': 0x22BF, + 'rihiragana': 0x308A, + 'rikatakana': 0x30EA, + 'rikatakanahalfwidth': 0xFF98, + 'ring': 0x02DA, + 'ringbelowcmb': 0x0325, + 'ringcmb': 0x030A, + 'ringhalfleft': 0x02BF, + 'ringhalfleftarmenian': 0x0559, + 'ringhalfleftbelowcmb': 0x031C, + 'ringhalfleftcentered': 0x02D3, + 'ringhalfright': 0x02BE, + 'ringhalfrightbelowcmb': 0x0339, + 'ringhalfrightcentered': 0x02D2, + 'rinvertedbreve': 0x0213, + 'rittorusquare': 0x3351, + 'rlinebelow': 0x1E5F, + 'rlongleg': 0x027C, + 'rlonglegturned': 0x027A, + 'rmonospace': 0xFF52, + 'rohiragana': 0x308D, + 'rokatakana': 0x30ED, + 'rokatakanahalfwidth': 0xFF9B, + 'roruathai': 0x0E23, + 'rparen': 0x24AD, + 'rrabengali': 0x09DC, + 'rradeva': 0x0931, + 'rragurmukhi': 0x0A5C, + 'rreharabic': 0x0691, + 'rrehfinalarabic': 0xFB8D, + 'rrvocalicbengali': 0x09E0, + 'rrvocalicdeva': 0x0960, + 'rrvocalicgujarati': 0x0AE0, + 'rrvocalicvowelsignbengali': 0x09C4, + 'rrvocalicvowelsigndeva': 0x0944, + 'rrvocalicvowelsigngujarati': 0x0AC4, + 'rsuperior': 0xF6F1, + 'rtblock': 0x2590, + 'rturned': 0x0279, + 'rturnedsuperior': 0x02B4, + 'ruhiragana': 0x308B, + 'rukatakana': 0x30EB, + 'rukatakanahalfwidth': 0xFF99, + 'rupeemarkbengali': 0x09F2, + 'rupeesignbengali': 0x09F3, + 'rupiah': 0xF6DD, + 'ruthai': 0x0E24, + 'rvocalicbengali': 0x098B, + 'rvocalicdeva': 0x090B, + 'rvocalicgujarati': 0x0A8B, + 'rvocalicvowelsignbengali': 0x09C3, + 'rvocalicvowelsigndeva': 0x0943, + 'rvocalicvowelsigngujarati': 0x0AC3, + 's': 0x0073, + 'sabengali': 0x09B8, + 'sacute': 0x015B, + 'sacutedotaccent': 0x1E65, + 'sadarabic': 0x0635, + 'sadeva': 0x0938, + 'sadfinalarabic': 0xFEBA, + 'sadinitialarabic': 0xFEBB, + 'sadmedialarabic': 0xFEBC, + 'sagujarati': 0x0AB8, + 'sagurmukhi': 0x0A38, + 'sahiragana': 0x3055, + 'sakatakana': 0x30B5, + 'sakatakanahalfwidth': 0xFF7B, + 'sallallahoualayhewasallamarabic': 0xFDFA, + 'samekh': 0x05E1, + 'samekhdagesh': 0xFB41, + 'samekhdageshhebrew': 0xFB41, + 'samekhhebrew': 0x05E1, + 'saraaathai': 0x0E32, + 'saraaethai': 0x0E41, + 'saraaimaimalaithai': 0x0E44, + 'saraaimaimuanthai': 0x0E43, + 'saraamthai': 0x0E33, + 'saraathai': 0x0E30, + 'saraethai': 0x0E40, + 'saraiileftthai': 0xF886, + 'saraiithai': 0x0E35, + 'saraileftthai': 0xF885, + 'saraithai': 0x0E34, + 'saraothai': 0x0E42, + 'saraueeleftthai': 0xF888, + 'saraueethai': 0x0E37, + 'saraueleftthai': 0xF887, + 'sarauethai': 0x0E36, + 'sarauthai': 0x0E38, + 'sarauuthai': 0x0E39, + 'sbopomofo': 0x3119, + 'scaron': 0x0161, + 'scarondotaccent': 0x1E67, + 'scedilla': 0x015F, + 'schwa': 0x0259, + 'schwacyrillic': 0x04D9, + 'schwadieresiscyrillic': 0x04DB, + 'schwahook': 0x025A, + 'scircle': 0x24E2, + 'scircumflex': 0x015D, + 'scommaaccent': 0x0219, + 'sdotaccent': 0x1E61, + 'sdotbelow': 0x1E63, + 'sdotbelowdotaccent': 0x1E69, + 'seagullbelowcmb': 0x033C, + 'second': 0x2033, + 'secondtonechinese': 0x02CA, + 'section': 0x00A7, + 'seenarabic': 0x0633, + 'seenfinalarabic': 0xFEB2, + 'seeninitialarabic': 0xFEB3, + 'seenmedialarabic': 0xFEB4, + 'segol': 0x05B6, + 'segol13': 0x05B6, + 'segol1f': 0x05B6, + 'segol2c': 0x05B6, + 'segolhebrew': 0x05B6, + 'segolnarrowhebrew': 0x05B6, + 'segolquarterhebrew': 0x05B6, + 'segoltahebrew': 0x0592, + 'segolwidehebrew': 0x05B6, + 'seharmenian': 0x057D, + 'sehiragana': 0x305B, + 'sekatakana': 0x30BB, + 'sekatakanahalfwidth': 0xFF7E, + 'semicolon': 0x003B, + 'semicolonarabic': 0x061B, + 'semicolonmonospace': 0xFF1B, + 'semicolonsmall': 0xFE54, + 'semivoicedmarkkana': 0x309C, + 'semivoicedmarkkanahalfwidth': 0xFF9F, + 'sentisquare': 0x3322, + 'sentosquare': 0x3323, + 'seven': 0x0037, + 'sevenarabic': 0x0667, + 'sevenbengali': 0x09ED, + 'sevencircle': 0x2466, + 'sevencircleinversesansserif': 0x2790, + 'sevendeva': 0x096D, + 'seveneighths': 0x215E, + 'sevengujarati': 0x0AED, + 'sevengurmukhi': 0x0A6D, + 'sevenhackarabic': 0x0667, + 'sevenhangzhou': 0x3027, + 'sevenideographicparen': 0x3226, + 'seveninferior': 0x2087, + 'sevenmonospace': 0xFF17, + 'sevenoldstyle': 0xF737, + 'sevenparen': 0x247A, + 'sevenperiod': 0x248E, + 'sevenpersian': 0x06F7, + 'sevenroman': 0x2176, + 'sevensuperior': 0x2077, + 'seventeencircle': 0x2470, + 'seventeenparen': 0x2484, + 'seventeenperiod': 0x2498, + 'seventhai': 0x0E57, + 'sfthyphen': 0x00AD, + 'shaarmenian': 0x0577, + 'shabengali': 0x09B6, + 'shacyrillic': 0x0448, + 'shaddaarabic': 0x0651, + 'shaddadammaarabic': 0xFC61, + 'shaddadammatanarabic': 0xFC5E, + 'shaddafathaarabic': 0xFC60, + 'shaddakasraarabic': 0xFC62, + 'shaddakasratanarabic': 0xFC5F, + 'shade': 0x2592, + 'shadedark': 0x2593, + 'shadelight': 0x2591, + 'shademedium': 0x2592, + 'shadeva': 0x0936, + 'shagujarati': 0x0AB6, + 'shagurmukhi': 0x0A36, + 'shalshelethebrew': 0x0593, + 'shbopomofo': 0x3115, + 'shchacyrillic': 0x0449, + 'sheenarabic': 0x0634, + 'sheenfinalarabic': 0xFEB6, + 'sheeninitialarabic': 0xFEB7, + 'sheenmedialarabic': 0xFEB8, + 'sheicoptic': 0x03E3, + 'sheqel': 0x20AA, + 'sheqelhebrew': 0x20AA, + 'sheva': 0x05B0, + 'sheva115': 0x05B0, + 'sheva15': 0x05B0, + 'sheva22': 0x05B0, + 'sheva2e': 0x05B0, + 'shevahebrew': 0x05B0, + 'shevanarrowhebrew': 0x05B0, + 'shevaquarterhebrew': 0x05B0, + 'shevawidehebrew': 0x05B0, + 'shhacyrillic': 0x04BB, + 'shimacoptic': 0x03ED, + 'shin': 0x05E9, + 'shindagesh': 0xFB49, + 'shindageshhebrew': 0xFB49, + 'shindageshshindot': 0xFB2C, + 'shindageshshindothebrew': 0xFB2C, + 'shindageshsindot': 0xFB2D, + 'shindageshsindothebrew': 0xFB2D, + 'shindothebrew': 0x05C1, + 'shinhebrew': 0x05E9, + 'shinshindot': 0xFB2A, + 'shinshindothebrew': 0xFB2A, + 'shinsindot': 0xFB2B, + 'shinsindothebrew': 0xFB2B, + 'shook': 0x0282, + 'sigma': 0x03C3, + 'sigma1': 0x03C2, + 'sigmafinal': 0x03C2, + 'sigmalunatesymbolgreek': 0x03F2, + 'sihiragana': 0x3057, + 'sikatakana': 0x30B7, + 'sikatakanahalfwidth': 0xFF7C, + 'siluqhebrew': 0x05BD, + 'siluqlefthebrew': 0x05BD, + 'similar': 0x223C, + 'sindothebrew': 0x05C2, + 'siosacirclekorean': 0x3274, + 'siosaparenkorean': 0x3214, + 'sioscieuckorean': 0x317E, + 'sioscirclekorean': 0x3266, + 'sioskiyeokkorean': 0x317A, + 'sioskorean': 0x3145, + 'siosnieunkorean': 0x317B, + 'siosparenkorean': 0x3206, + 'siospieupkorean': 0x317D, + 'siostikeutkorean': 0x317C, + 'six': 0x0036, + 'sixarabic': 0x0666, + 'sixbengali': 0x09EC, + 'sixcircle': 0x2465, + 'sixcircleinversesansserif': 0x278F, + 'sixdeva': 0x096C, + 'sixgujarati': 0x0AEC, + 'sixgurmukhi': 0x0A6C, + 'sixhackarabic': 0x0666, + 'sixhangzhou': 0x3026, + 'sixideographicparen': 0x3225, + 'sixinferior': 0x2086, + 'sixmonospace': 0xFF16, + 'sixoldstyle': 0xF736, + 'sixparen': 0x2479, + 'sixperiod': 0x248D, + 'sixpersian': 0x06F6, + 'sixroman': 0x2175, + 'sixsuperior': 0x2076, + 'sixteencircle': 0x246F, + 'sixteencurrencydenominatorbengali': 0x09F9, + 'sixteenparen': 0x2483, + 'sixteenperiod': 0x2497, + 'sixthai': 0x0E56, + 'slash': 0x002F, + 'slashmonospace': 0xFF0F, + 'slong': 0x017F, + 'slongdotaccent': 0x1E9B, + 'smileface': 0x263A, + 'smonospace': 0xFF53, + 'sofpasuqhebrew': 0x05C3, + 'softhyphen': 0x00AD, + 'softsigncyrillic': 0x044C, + 'sohiragana': 0x305D, + 'sokatakana': 0x30BD, + 'sokatakanahalfwidth': 0xFF7F, + 'soliduslongoverlaycmb': 0x0338, + 'solidusshortoverlaycmb': 0x0337, + 'sorusithai': 0x0E29, + 'sosalathai': 0x0E28, + 'sosothai': 0x0E0B, + 'sosuathai': 0x0E2A, + 'space': 0x0020, + 'spacehackarabic': 0x0020, + 'spade': 0x2660, + 'spadesuitblack': 0x2660, + 'spadesuitwhite': 0x2664, + 'sparen': 0x24AE, + 'squarebelowcmb': 0x033B, + 'squarecc': 0x33C4, + 'squarecm': 0x339D, + 'squarediagonalcrosshatchfill': 0x25A9, + 'squarehorizontalfill': 0x25A4, + 'squarekg': 0x338F, + 'squarekm': 0x339E, + 'squarekmcapital': 0x33CE, + 'squareln': 0x33D1, + 'squarelog': 0x33D2, + 'squaremg': 0x338E, + 'squaremil': 0x33D5, + 'squaremm': 0x339C, + 'squaremsquared': 0x33A1, + 'squareorthogonalcrosshatchfill': 0x25A6, + 'squareupperlefttolowerrightfill': 0x25A7, + 'squareupperrighttolowerleftfill': 0x25A8, + 'squareverticalfill': 0x25A5, + 'squarewhitewithsmallblack': 0x25A3, + 'srsquare': 0x33DB, + 'ssabengali': 0x09B7, + 'ssadeva': 0x0937, + 'ssagujarati': 0x0AB7, + 'ssangcieuckorean': 0x3149, + 'ssanghieuhkorean': 0x3185, + 'ssangieungkorean': 0x3180, + 'ssangkiyeokkorean': 0x3132, + 'ssangnieunkorean': 0x3165, + 'ssangpieupkorean': 0x3143, + 'ssangsioskorean': 0x3146, + 'ssangtikeutkorean': 0x3138, + 'ssuperior': 0xF6F2, + 'sterling': 0x00A3, + 'sterlingmonospace': 0xFFE1, + 'strokelongoverlaycmb': 0x0336, + 'strokeshortoverlaycmb': 0x0335, + 'subset': 0x2282, + 'subsetnotequal': 0x228A, + 'subsetorequal': 0x2286, + 'succeeds': 0x227B, + 'suchthat': 0x220B, + 'suhiragana': 0x3059, + 'sukatakana': 0x30B9, + 'sukatakanahalfwidth': 0xFF7D, + 'sukunarabic': 0x0652, + 'summation': 0x2211, + 'sun': 0x263C, + 'superset': 0x2283, + 'supersetnotequal': 0x228B, + 'supersetorequal': 0x2287, + 'svsquare': 0x33DC, + 'syouwaerasquare': 0x337C, + 't': 0x0074, + 'tabengali': 0x09A4, + 'tackdown': 0x22A4, + 'tackleft': 0x22A3, + 'tadeva': 0x0924, + 'tagujarati': 0x0AA4, + 'tagurmukhi': 0x0A24, + 'taharabic': 0x0637, + 'tahfinalarabic': 0xFEC2, + 'tahinitialarabic': 0xFEC3, + 'tahiragana': 0x305F, + 'tahmedialarabic': 0xFEC4, + 'taisyouerasquare': 0x337D, + 'takatakana': 0x30BF, + 'takatakanahalfwidth': 0xFF80, + 'tatweelarabic': 0x0640, + 'tau': 0x03C4, + 'tav': 0x05EA, + 'tavdages': 0xFB4A, + 'tavdagesh': 0xFB4A, + 'tavdageshhebrew': 0xFB4A, + 'tavhebrew': 0x05EA, + 'tbar': 0x0167, + 'tbopomofo': 0x310A, + 'tcaron': 0x0165, + 'tccurl': 0x02A8, + 'tcedilla': 0x0163, + 'tcheharabic': 0x0686, + 'tchehfinalarabic': 0xFB7B, + 'tchehinitialarabic': 0xFB7C, + 'tchehmedialarabic': 0xFB7D, + 'tcircle': 0x24E3, + 'tcircumflexbelow': 0x1E71, + 'tcommaaccent': 0x0163, + 'tdieresis': 0x1E97, + 'tdotaccent': 0x1E6B, + 'tdotbelow': 0x1E6D, + 'tecyrillic': 0x0442, + 'tedescendercyrillic': 0x04AD, + 'teharabic': 0x062A, + 'tehfinalarabic': 0xFE96, + 'tehhahinitialarabic': 0xFCA2, + 'tehhahisolatedarabic': 0xFC0C, + 'tehinitialarabic': 0xFE97, + 'tehiragana': 0x3066, + 'tehjeeminitialarabic': 0xFCA1, + 'tehjeemisolatedarabic': 0xFC0B, + 'tehmarbutaarabic': 0x0629, + 'tehmarbutafinalarabic': 0xFE94, + 'tehmedialarabic': 0xFE98, + 'tehmeeminitialarabic': 0xFCA4, + 'tehmeemisolatedarabic': 0xFC0E, + 'tehnoonfinalarabic': 0xFC73, + 'tekatakana': 0x30C6, + 'tekatakanahalfwidth': 0xFF83, + 'telephone': 0x2121, + 'telephoneblack': 0x260E, + 'telishagedolahebrew': 0x05A0, + 'telishaqetanahebrew': 0x05A9, + 'tencircle': 0x2469, + 'tenideographicparen': 0x3229, + 'tenparen': 0x247D, + 'tenperiod': 0x2491, + 'tenroman': 0x2179, + 'tesh': 0x02A7, + 'tet': 0x05D8, + 'tetdagesh': 0xFB38, + 'tetdageshhebrew': 0xFB38, + 'tethebrew': 0x05D8, + 'tetsecyrillic': 0x04B5, + 'tevirhebrew': 0x059B, + 'tevirlefthebrew': 0x059B, + 'thabengali': 0x09A5, + 'thadeva': 0x0925, + 'thagujarati': 0x0AA5, + 'thagurmukhi': 0x0A25, + 'thalarabic': 0x0630, + 'thalfinalarabic': 0xFEAC, + 'thanthakhatlowleftthai': 0xF898, + 'thanthakhatlowrightthai': 0xF897, + 'thanthakhatthai': 0x0E4C, + 'thanthakhatupperleftthai': 0xF896, + 'theharabic': 0x062B, + 'thehfinalarabic': 0xFE9A, + 'thehinitialarabic': 0xFE9B, + 'thehmedialarabic': 0xFE9C, + 'thereexists': 0x2203, + 'therefore': 0x2234, + 'theta': 0x03B8, + 'theta1': 0x03D1, + 'thetasymbolgreek': 0x03D1, + 'thieuthacirclekorean': 0x3279, + 'thieuthaparenkorean': 0x3219, + 'thieuthcirclekorean': 0x326B, + 'thieuthkorean': 0x314C, + 'thieuthparenkorean': 0x320B, + 'thirteencircle': 0x246C, + 'thirteenparen': 0x2480, + 'thirteenperiod': 0x2494, + 'thonangmonthothai': 0x0E11, + 'thook': 0x01AD, + 'thophuthaothai': 0x0E12, + 'thorn': 0x00FE, + 'thothahanthai': 0x0E17, + 'thothanthai': 0x0E10, + 'thothongthai': 0x0E18, + 'thothungthai': 0x0E16, + 'thousandcyrillic': 0x0482, + 'thousandsseparatorarabic': 0x066C, + 'thousandsseparatorpersian': 0x066C, + 'three': 0x0033, + 'threearabic': 0x0663, + 'threebengali': 0x09E9, + 'threecircle': 0x2462, + 'threecircleinversesansserif': 0x278C, + 'threedeva': 0x0969, + 'threeeighths': 0x215C, + 'threegujarati': 0x0AE9, + 'threegurmukhi': 0x0A69, + 'threehackarabic': 0x0663, + 'threehangzhou': 0x3023, + 'threeideographicparen': 0x3222, + 'threeinferior': 0x2083, + 'threemonospace': 0xFF13, + 'threenumeratorbengali': 0x09F6, + 'threeoldstyle': 0xF733, + 'threeparen': 0x2476, + 'threeperiod': 0x248A, + 'threepersian': 0x06F3, + 'threequarters': 0x00BE, + 'threequartersemdash': 0xF6DE, + 'threeroman': 0x2172, + 'threesuperior': 0x00B3, + 'threethai': 0x0E53, + 'thzsquare': 0x3394, + 'tihiragana': 0x3061, + 'tikatakana': 0x30C1, + 'tikatakanahalfwidth': 0xFF81, + 'tikeutacirclekorean': 0x3270, + 'tikeutaparenkorean': 0x3210, + 'tikeutcirclekorean': 0x3262, + 'tikeutkorean': 0x3137, + 'tikeutparenkorean': 0x3202, + 'tilde': 0x02DC, + 'tildebelowcmb': 0x0330, + 'tildecmb': 0x0303, + 'tildecomb': 0x0303, + 'tildedoublecmb': 0x0360, + 'tildeoperator': 0x223C, + 'tildeoverlaycmb': 0x0334, + 'tildeverticalcmb': 0x033E, + 'timescircle': 0x2297, + 'tipehahebrew': 0x0596, + 'tipehalefthebrew': 0x0596, + 'tippigurmukhi': 0x0A70, + 'titlocyrilliccmb': 0x0483, + 'tiwnarmenian': 0x057F, + 'tlinebelow': 0x1E6F, + 'tmonospace': 0xFF54, + 'toarmenian': 0x0569, + 'tohiragana': 0x3068, + 'tokatakana': 0x30C8, + 'tokatakanahalfwidth': 0xFF84, + 'tonebarextrahighmod': 0x02E5, + 'tonebarextralowmod': 0x02E9, + 'tonebarhighmod': 0x02E6, + 'tonebarlowmod': 0x02E8, + 'tonebarmidmod': 0x02E7, + 'tonefive': 0x01BD, + 'tonesix': 0x0185, + 'tonetwo': 0x01A8, + 'tonos': 0x0384, + 'tonsquare': 0x3327, + 'topatakthai': 0x0E0F, + 'tortoiseshellbracketleft': 0x3014, + 'tortoiseshellbracketleftsmall': 0xFE5D, + 'tortoiseshellbracketleftvertical': 0xFE39, + 'tortoiseshellbracketright': 0x3015, + 'tortoiseshellbracketrightsmall': 0xFE5E, + 'tortoiseshellbracketrightvertical': 0xFE3A, + 'totaothai': 0x0E15, + 'tpalatalhook': 0x01AB, + 'tparen': 0x24AF, + 'trademark': 0x2122, + 'trademarksans': 0xF8EA, + 'trademarkserif': 0xF6DB, + 'tretroflexhook': 0x0288, + 'triagdn': 0x25BC, + 'triaglf': 0x25C4, + 'triagrt': 0x25BA, + 'triagup': 0x25B2, + 'ts': 0x02A6, + 'tsadi': 0x05E6, + 'tsadidagesh': 0xFB46, + 'tsadidageshhebrew': 0xFB46, + 'tsadihebrew': 0x05E6, + 'tsecyrillic': 0x0446, + 'tsere': 0x05B5, + 'tsere12': 0x05B5, + 'tsere1e': 0x05B5, + 'tsere2b': 0x05B5, + 'tserehebrew': 0x05B5, + 'tserenarrowhebrew': 0x05B5, + 'tserequarterhebrew': 0x05B5, + 'tserewidehebrew': 0x05B5, + 'tshecyrillic': 0x045B, + 'tsuperior': 0xF6F3, + 'ttabengali': 0x099F, + 'ttadeva': 0x091F, + 'ttagujarati': 0x0A9F, + 'ttagurmukhi': 0x0A1F, + 'tteharabic': 0x0679, + 'ttehfinalarabic': 0xFB67, + 'ttehinitialarabic': 0xFB68, + 'ttehmedialarabic': 0xFB69, + 'tthabengali': 0x09A0, + 'tthadeva': 0x0920, + 'tthagujarati': 0x0AA0, + 'tthagurmukhi': 0x0A20, + 'tturned': 0x0287, + 'tuhiragana': 0x3064, + 'tukatakana': 0x30C4, + 'tukatakanahalfwidth': 0xFF82, + 'tusmallhiragana': 0x3063, + 'tusmallkatakana': 0x30C3, + 'tusmallkatakanahalfwidth': 0xFF6F, + 'twelvecircle': 0x246B, + 'twelveparen': 0x247F, + 'twelveperiod': 0x2493, + 'twelveroman': 0x217B, + 'twentycircle': 0x2473, + 'twentyhangzhou': 0x5344, + 'twentyparen': 0x2487, + 'twentyperiod': 0x249B, + 'two': 0x0032, + 'twoarabic': 0x0662, + 'twobengali': 0x09E8, + 'twocircle': 0x2461, + 'twocircleinversesansserif': 0x278B, + 'twodeva': 0x0968, + 'twodotenleader': 0x2025, + 'twodotleader': 0x2025, + 'twodotleadervertical': 0xFE30, + 'twogujarati': 0x0AE8, + 'twogurmukhi': 0x0A68, + 'twohackarabic': 0x0662, + 'twohangzhou': 0x3022, + 'twoideographicparen': 0x3221, + 'twoinferior': 0x2082, + 'twomonospace': 0xFF12, + 'twonumeratorbengali': 0x09F5, + 'twooldstyle': 0xF732, + 'twoparen': 0x2475, + 'twoperiod': 0x2489, + 'twopersian': 0x06F2, + 'tworoman': 0x2171, + 'twostroke': 0x01BB, + 'twosuperior': 0x00B2, + 'twothai': 0x0E52, + 'twothirds': 0x2154, + 'u': 0x0075, + 'uacute': 0x00FA, + 'ubar': 0x0289, + 'ubengali': 0x0989, + 'ubopomofo': 0x3128, + 'ubreve': 0x016D, + 'ucaron': 0x01D4, + 'ucircle': 0x24E4, + 'ucircumflex': 0x00FB, + 'ucircumflexbelow': 0x1E77, + 'ucyrillic': 0x0443, + 'udattadeva': 0x0951, + 'udblacute': 0x0171, + 'udblgrave': 0x0215, + 'udeva': 0x0909, + 'udieresis': 0x00FC, + 'udieresisacute': 0x01D8, + 'udieresisbelow': 0x1E73, + 'udieresiscaron': 0x01DA, + 'udieresiscyrillic': 0x04F1, + 'udieresisgrave': 0x01DC, + 'udieresismacron': 0x01D6, + 'udotbelow': 0x1EE5, + 'ugrave': 0x00F9, + 'ugujarati': 0x0A89, + 'ugurmukhi': 0x0A09, + 'uhiragana': 0x3046, + 'uhookabove': 0x1EE7, + 'uhorn': 0x01B0, + 'uhornacute': 0x1EE9, + 'uhorndotbelow': 0x1EF1, + 'uhorngrave': 0x1EEB, + 'uhornhookabove': 0x1EED, + 'uhorntilde': 0x1EEF, + 'uhungarumlaut': 0x0171, + 'uhungarumlautcyrillic': 0x04F3, + 'uinvertedbreve': 0x0217, + 'ukatakana': 0x30A6, + 'ukatakanahalfwidth': 0xFF73, + 'ukcyrillic': 0x0479, + 'ukorean': 0x315C, + 'umacron': 0x016B, + 'umacroncyrillic': 0x04EF, + 'umacrondieresis': 0x1E7B, + 'umatragurmukhi': 0x0A41, + 'umonospace': 0xFF55, + 'underscore': 0x005F, + 'underscoredbl': 0x2017, + 'underscoremonospace': 0xFF3F, + 'underscorevertical': 0xFE33, + 'underscorewavy': 0xFE4F, + 'union': 0x222A, + 'universal': 0x2200, + 'uogonek': 0x0173, + 'uparen': 0x24B0, + 'upblock': 0x2580, + 'upperdothebrew': 0x05C4, + 'upsilon': 0x03C5, + 'upsilondieresis': 0x03CB, + 'upsilondieresistonos': 0x03B0, + 'upsilonlatin': 0x028A, + 'upsilontonos': 0x03CD, + 'uptackbelowcmb': 0x031D, + 'uptackmod': 0x02D4, + 'uragurmukhi': 0x0A73, + 'uring': 0x016F, + 'ushortcyrillic': 0x045E, + 'usmallhiragana': 0x3045, + 'usmallkatakana': 0x30A5, + 'usmallkatakanahalfwidth': 0xFF69, + 'ustraightcyrillic': 0x04AF, + 'ustraightstrokecyrillic': 0x04B1, + 'utilde': 0x0169, + 'utildeacute': 0x1E79, + 'utildebelow': 0x1E75, + 'uubengali': 0x098A, + 'uudeva': 0x090A, + 'uugujarati': 0x0A8A, + 'uugurmukhi': 0x0A0A, + 'uumatragurmukhi': 0x0A42, + 'uuvowelsignbengali': 0x09C2, + 'uuvowelsigndeva': 0x0942, + 'uuvowelsigngujarati': 0x0AC2, + 'uvowelsignbengali': 0x09C1, + 'uvowelsigndeva': 0x0941, + 'uvowelsigngujarati': 0x0AC1, + 'v': 0x0076, + 'vadeva': 0x0935, + 'vagujarati': 0x0AB5, + 'vagurmukhi': 0x0A35, + 'vakatakana': 0x30F7, + 'vav': 0x05D5, + 'vavdagesh': 0xFB35, + 'vavdagesh65': 0xFB35, + 'vavdageshhebrew': 0xFB35, + 'vavhebrew': 0x05D5, + 'vavholam': 0xFB4B, + 'vavholamhebrew': 0xFB4B, + 'vavvavhebrew': 0x05F0, + 'vavyodhebrew': 0x05F1, + 'vcircle': 0x24E5, + 'vdotbelow': 0x1E7F, + 'vecyrillic': 0x0432, + 'veharabic': 0x06A4, + 'vehfinalarabic': 0xFB6B, + 'vehinitialarabic': 0xFB6C, + 'vehmedialarabic': 0xFB6D, + 'vekatakana': 0x30F9, + 'venus': 0x2640, + 'verticalbar': 0x007C, + 'verticallineabovecmb': 0x030D, + 'verticallinebelowcmb': 0x0329, + 'verticallinelowmod': 0x02CC, + 'verticallinemod': 0x02C8, + 'vewarmenian': 0x057E, + 'vhook': 0x028B, + 'vikatakana': 0x30F8, + 'viramabengali': 0x09CD, + 'viramadeva': 0x094D, + 'viramagujarati': 0x0ACD, + 'visargabengali': 0x0983, + 'visargadeva': 0x0903, + 'visargagujarati': 0x0A83, + 'vmonospace': 0xFF56, + 'voarmenian': 0x0578, + 'voicediterationhiragana': 0x309E, + 'voicediterationkatakana': 0x30FE, + 'voicedmarkkana': 0x309B, + 'voicedmarkkanahalfwidth': 0xFF9E, + 'vokatakana': 0x30FA, + 'vparen': 0x24B1, + 'vtilde': 0x1E7D, + 'vturned': 0x028C, + 'vuhiragana': 0x3094, + 'vukatakana': 0x30F4, + 'w': 0x0077, + 'wacute': 0x1E83, + 'waekorean': 0x3159, + 'wahiragana': 0x308F, + 'wakatakana': 0x30EF, + 'wakatakanahalfwidth': 0xFF9C, + 'wakorean': 0x3158, + 'wasmallhiragana': 0x308E, + 'wasmallkatakana': 0x30EE, + 'wattosquare': 0x3357, + 'wavedash': 0x301C, + 'wavyunderscorevertical': 0xFE34, + 'wawarabic': 0x0648, + 'wawfinalarabic': 0xFEEE, + 'wawhamzaabovearabic': 0x0624, + 'wawhamzaabovefinalarabic': 0xFE86, + 'wbsquare': 0x33DD, + 'wcircle': 0x24E6, + 'wcircumflex': 0x0175, + 'wdieresis': 0x1E85, + 'wdotaccent': 0x1E87, + 'wdotbelow': 0x1E89, + 'wehiragana': 0x3091, + 'weierstrass': 0x2118, + 'wekatakana': 0x30F1, + 'wekorean': 0x315E, + 'weokorean': 0x315D, + 'wgrave': 0x1E81, + 'whitebullet': 0x25E6, + 'whitecircle': 0x25CB, + 'whitecircleinverse': 0x25D9, + 'whitecornerbracketleft': 0x300E, + 'whitecornerbracketleftvertical': 0xFE43, + 'whitecornerbracketright': 0x300F, + 'whitecornerbracketrightvertical': 0xFE44, + 'whitediamond': 0x25C7, + 'whitediamondcontainingblacksmalldiamond': 0x25C8, + 'whitedownpointingsmalltriangle': 0x25BF, + 'whitedownpointingtriangle': 0x25BD, + 'whiteleftpointingsmalltriangle': 0x25C3, + 'whiteleftpointingtriangle': 0x25C1, + 'whitelenticularbracketleft': 0x3016, + 'whitelenticularbracketright': 0x3017, + 'whiterightpointingsmalltriangle': 0x25B9, + 'whiterightpointingtriangle': 0x25B7, + 'whitesmallsquare': 0x25AB, + 'whitesmilingface': 0x263A, + 'whitesquare': 0x25A1, + 'whitestar': 0x2606, + 'whitetelephone': 0x260F, + 'whitetortoiseshellbracketleft': 0x3018, + 'whitetortoiseshellbracketright': 0x3019, + 'whiteuppointingsmalltriangle': 0x25B5, + 'whiteuppointingtriangle': 0x25B3, + 'wihiragana': 0x3090, + 'wikatakana': 0x30F0, + 'wikorean': 0x315F, + 'wmonospace': 0xFF57, + 'wohiragana': 0x3092, + 'wokatakana': 0x30F2, + 'wokatakanahalfwidth': 0xFF66, + 'won': 0x20A9, + 'wonmonospace': 0xFFE6, + 'wowaenthai': 0x0E27, + 'wparen': 0x24B2, + 'wring': 0x1E98, + 'wsuperior': 0x02B7, + 'wturned': 0x028D, + 'wynn': 0x01BF, + 'x': 0x0078, + 'xabovecmb': 0x033D, + 'xbopomofo': 0x3112, + 'xcircle': 0x24E7, + 'xdieresis': 0x1E8D, + 'xdotaccent': 0x1E8B, + 'xeharmenian': 0x056D, + 'xi': 0x03BE, + 'xmonospace': 0xFF58, + 'xparen': 0x24B3, + 'xsuperior': 0x02E3, + 'y': 0x0079, + 'yaadosquare': 0x334E, + 'yabengali': 0x09AF, + 'yacute': 0x00FD, + 'yadeva': 0x092F, + 'yaekorean': 0x3152, + 'yagujarati': 0x0AAF, + 'yagurmukhi': 0x0A2F, + 'yahiragana': 0x3084, + 'yakatakana': 0x30E4, + 'yakatakanahalfwidth': 0xFF94, + 'yakorean': 0x3151, + 'yamakkanthai': 0x0E4E, + 'yasmallhiragana': 0x3083, + 'yasmallkatakana': 0x30E3, + 'yasmallkatakanahalfwidth': 0xFF6C, + 'yatcyrillic': 0x0463, + 'ycircle': 0x24E8, + 'ycircumflex': 0x0177, + 'ydieresis': 0x00FF, + 'ydotaccent': 0x1E8F, + 'ydotbelow': 0x1EF5, + 'yeharabic': 0x064A, + 'yehbarreearabic': 0x06D2, + 'yehbarreefinalarabic': 0xFBAF, + 'yehfinalarabic': 0xFEF2, + 'yehhamzaabovearabic': 0x0626, + 'yehhamzaabovefinalarabic': 0xFE8A, + 'yehhamzaaboveinitialarabic': 0xFE8B, + 'yehhamzaabovemedialarabic': 0xFE8C, + 'yehinitialarabic': 0xFEF3, + 'yehmedialarabic': 0xFEF4, + 'yehmeeminitialarabic': 0xFCDD, + 'yehmeemisolatedarabic': 0xFC58, + 'yehnoonfinalarabic': 0xFC94, + 'yehthreedotsbelowarabic': 0x06D1, + 'yekorean': 0x3156, + 'yen': 0x00A5, + 'yenmonospace': 0xFFE5, + 'yeokorean': 0x3155, + 'yeorinhieuhkorean': 0x3186, + 'yerahbenyomohebrew': 0x05AA, + 'yerahbenyomolefthebrew': 0x05AA, + 'yericyrillic': 0x044B, + 'yerudieresiscyrillic': 0x04F9, + 'yesieungkorean': 0x3181, + 'yesieungpansioskorean': 0x3183, + 'yesieungsioskorean': 0x3182, + 'yetivhebrew': 0x059A, + 'ygrave': 0x1EF3, + 'yhook': 0x01B4, + 'yhookabove': 0x1EF7, + 'yiarmenian': 0x0575, + 'yicyrillic': 0x0457, + 'yikorean': 0x3162, + 'yinyang': 0x262F, + 'yiwnarmenian': 0x0582, + 'ymonospace': 0xFF59, + 'yod': 0x05D9, + 'yoddagesh': 0xFB39, + 'yoddageshhebrew': 0xFB39, + 'yodhebrew': 0x05D9, + 'yodyodhebrew': 0x05F2, + 'yodyodpatahhebrew': 0xFB1F, + 'yohiragana': 0x3088, + 'yoikorean': 0x3189, + 'yokatakana': 0x30E8, + 'yokatakanahalfwidth': 0xFF96, + 'yokorean': 0x315B, + 'yosmallhiragana': 0x3087, + 'yosmallkatakana': 0x30E7, + 'yosmallkatakanahalfwidth': 0xFF6E, + 'yotgreek': 0x03F3, + 'yoyaekorean': 0x3188, + 'yoyakorean': 0x3187, + 'yoyakthai': 0x0E22, + 'yoyingthai': 0x0E0D, + 'yparen': 0x24B4, + 'ypogegrammeni': 0x037A, + 'ypogegrammenigreekcmb': 0x0345, + 'yr': 0x01A6, + 'yring': 0x1E99, + 'ysuperior': 0x02B8, + 'ytilde': 0x1EF9, + 'yturned': 0x028E, + 'yuhiragana': 0x3086, + 'yuikorean': 0x318C, + 'yukatakana': 0x30E6, + 'yukatakanahalfwidth': 0xFF95, + 'yukorean': 0x3160, + 'yusbigcyrillic': 0x046B, + 'yusbigiotifiedcyrillic': 0x046D, + 'yuslittlecyrillic': 0x0467, + 'yuslittleiotifiedcyrillic': 0x0469, + 'yusmallhiragana': 0x3085, + 'yusmallkatakana': 0x30E5, + 'yusmallkatakanahalfwidth': 0xFF6D, + 'yuyekorean': 0x318B, + 'yuyeokorean': 0x318A, + 'yyabengali': 0x09DF, + 'yyadeva': 0x095F, + 'z': 0x007A, + 'zaarmenian': 0x0566, + 'zacute': 0x017A, + 'zadeva': 0x095B, + 'zagurmukhi': 0x0A5B, + 'zaharabic': 0x0638, + 'zahfinalarabic': 0xFEC6, + 'zahinitialarabic': 0xFEC7, + 'zahiragana': 0x3056, + 'zahmedialarabic': 0xFEC8, + 'zainarabic': 0x0632, + 'zainfinalarabic': 0xFEB0, + 'zakatakana': 0x30B6, + 'zaqefgadolhebrew': 0x0595, + 'zaqefqatanhebrew': 0x0594, + 'zarqahebrew': 0x0598, + 'zayin': 0x05D6, + 'zayindagesh': 0xFB36, + 'zayindageshhebrew': 0xFB36, + 'zayinhebrew': 0x05D6, + 'zbopomofo': 0x3117, + 'zcaron': 0x017E, + 'zcircle': 0x24E9, + 'zcircumflex': 0x1E91, + 'zcurl': 0x0291, + 'zdot': 0x017C, + 'zdotaccent': 0x017C, + 'zdotbelow': 0x1E93, + 'zecyrillic': 0x0437, + 'zedescendercyrillic': 0x0499, + 'zedieresiscyrillic': 0x04DF, + 'zehiragana': 0x305C, + 'zekatakana': 0x30BC, + 'zero': 0x0030, + 'zeroarabic': 0x0660, + 'zerobengali': 0x09E6, + 'zerodeva': 0x0966, + 'zerogujarati': 0x0AE6, + 'zerogurmukhi': 0x0A66, + 'zerohackarabic': 0x0660, + 'zeroinferior': 0x2080, + 'zeromonospace': 0xFF10, + 'zerooldstyle': 0xF730, + 'zeropersian': 0x06F0, + 'zerosuperior': 0x2070, + 'zerothai': 0x0E50, + 'zerowidthjoiner': 0xFEFF, + 'zerowidthnonjoiner': 0x200C, + 'zerowidthspace': 0x200B, + 'zeta': 0x03B6, + 'zhbopomofo': 0x3113, + 'zhearmenian': 0x056A, + 'zhebrevecyrillic': 0x04C2, + 'zhecyrillic': 0x0436, + 'zhedescendercyrillic': 0x0497, + 'zhedieresiscyrillic': 0x04DD, + 'zihiragana': 0x3058, + 'zikatakana': 0x30B8, + 'zinorhebrew': 0x05AE, + 'zlinebelow': 0x1E95, + 'zmonospace': 0xFF5A, + 'zohiragana': 0x305E, + 'zokatakana': 0x30BE, + 'zparen': 0x24B5, + 'zretroflexhook': 0x0290, + 'zstroke': 0x01B6, + 'zuhiragana': 0x305A, + 'zukatakana': 0x30BA, + } +_glyphname2unicodes = { + 'dalethatafpatah': (0x05D3,0x05B2), + 'dalethatafpatahhebrew': (0x05D3,0x05B2), + 'dalethatafsegol': (0x05D3,0x05B1), + 'dalethatafsegolhebrew': (0x05D3,0x05B1), + 'dalethiriq': (0x05D3,0x05B4), + 'dalethiriqhebrew': (0x05D3,0x05B4), + 'daletholam': (0x05D3,0x05B9), + 'daletholamhebrew': (0x05D3,0x05B9), + 'daletpatah': (0x05D3,0x05B7), + 'daletpatahhebrew': (0x05D3,0x05B7), + 'daletqamats': (0x05D3,0x05B8), + 'daletqamatshebrew': (0x05D3,0x05B8), + 'daletqubuts': (0x05D3,0x05BB), + 'daletqubutshebrew': (0x05D3,0x05BB), + 'daletsegol': (0x05D3,0x05B6), + 'daletsegolhebrew': (0x05D3,0x05B6), + 'daletsheva': (0x05D3,0x05B0), + 'daletshevahebrew': (0x05D3,0x05B0), + 'dalettsere': (0x05D3,0x05B5), + 'dalettserehebrew': (0x05D3,0x05B5), + 'finalkafqamats': (0x05DA,0x05B8), + 'finalkafqamatshebrew': (0x05DA,0x05B8), + 'finalkafsheva': (0x05DA,0x05B0), + 'finalkafshevahebrew': (0x05DA,0x05B0), + 'hamzadammaarabic': (0x0621,0x064F), + 'hamzadammatanarabic': (0x0621,0x064C), + 'hamzafathaarabic': (0x0621,0x064E), + 'hamzafathatanarabic': (0x0621,0x064B), + 'hamzalowkasraarabic': (0x0621,0x0650), + 'hamzalowkasratanarabic': (0x0621,0x064D), + 'hamzasukunarabic': (0x0621,0x0652), + 'lamedholam': (0x05DC,0x05B9), + 'lamedholamdagesh': (0x05DC,0x05B9,0x05BC), + 'lamedholamdageshhebrew': (0x05DC,0x05B9,0x05BC), + 'lamedholamhebrew': (0x05DC,0x05B9), + 'lammeemjeeminitialarabic': (0xFEDF,0xFEE4,0xFEA0), + 'lammeemkhahinitialarabic': (0xFEDF,0xFEE4,0xFEA8), + 'noonhehinitialarabic': (0xFEE7,0xFEEC), + 'qofhatafpatah': (0x05E7,0x05B2), + 'qofhatafpatahhebrew': (0x05E7,0x05B2), + 'qofhatafsegol': (0x05E7,0x05B1), + 'qofhatafsegolhebrew': (0x05E7,0x05B1), + 'qofhiriq': (0x05E7,0x05B4), + 'qofhiriqhebrew': (0x05E7,0x05B4), + 'qofholam': (0x05E7,0x05B9), + 'qofholamhebrew': (0x05E7,0x05B9), + 'qofpatah': (0x05E7,0x05B7), + 'qofpatahhebrew': (0x05E7,0x05B7), + 'qofqamats': (0x05E7,0x05B8), + 'qofqamatshebrew': (0x05E7,0x05B8), + 'qofqubuts': (0x05E7,0x05BB), + 'qofqubutshebrew': (0x05E7,0x05BB), + 'qofsegol': (0x05E7,0x05B6), + 'qofsegolhebrew': (0x05E7,0x05B6), + 'qofsheva': (0x05E7,0x05B0), + 'qofshevahebrew': (0x05E7,0x05B0), + 'qoftsere': (0x05E7,0x05B5), + 'qoftserehebrew': (0x05E7,0x05B5), + 'rehyehaleflamarabic': (0x0631,0xFEF3,0xFE8E,0x0644), + 'reshhatafpatah': (0x05E8,0x05B2), + 'reshhatafpatahhebrew': (0x05E8,0x05B2), + 'reshhatafsegol': (0x05E8,0x05B1), + 'reshhatafsegolhebrew': (0x05E8,0x05B1), + 'reshhiriq': (0x05E8,0x05B4), + 'reshhiriqhebrew': (0x05E8,0x05B4), + 'reshholam': (0x05E8,0x05B9), + 'reshholamhebrew': (0x05E8,0x05B9), + 'reshpatah': (0x05E8,0x05B7), + 'reshpatahhebrew': (0x05E8,0x05B7), + 'reshqamats': (0x05E8,0x05B8), + 'reshqamatshebrew': (0x05E8,0x05B8), + 'reshqubuts': (0x05E8,0x05BB), + 'reshqubutshebrew': (0x05E8,0x05BB), + 'reshsegol': (0x05E8,0x05B6), + 'reshsegolhebrew': (0x05E8,0x05B6), + 'reshsheva': (0x05E8,0x05B0), + 'reshshevahebrew': (0x05E8,0x05B0), + 'reshtsere': (0x05E8,0x05B5), + 'reshtserehebrew': (0x05E8,0x05B5), + 'shaddafathatanarabic': (0x0651,0x064B), + 'tchehmeeminitialarabic': (0xFB7C,0xFEE4), + } diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/acroform.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/acroform.py new file mode 100644 index 0000000000000000000000000000000000000000..ea91a9ce17722dd38e03becb131956dbde7cf160 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/acroform.py @@ -0,0 +1,1223 @@ +__all__=('AcroForm',) +from reportlab.pdfbase.pdfdoc import (PDFObject, PDFArray, PDFDictionary, PDFString, pdfdocEnc, + PDFName, PDFStream, PDFStreamFilterZCompress, escapePDF) +from reportlab.pdfbase.pdfmetrics import stringWidth +from reportlab.lib.colors import Color, CMYKColor, Whiter, Blacker, opaqueColor +from reportlab.lib.rl_accel import fp_str +from reportlab.lib.utils import isStr, asNative +import weakref + +_useDefault=object() + +visibilities = dict( + visible=0, + hidden=0, + visibleNonPrinting=0, + hiddenPrintable=0, + ) + +orientations = { + 0: [], + 90: [], + 180: [], + 270: [], + } + +#adobe counts bits 1 - 32 +fieldFlagValues = dict( + readOnly = 1<<0, + required = 1<<1, + noExport = 1<<2, + noToggleToOff = 1<<14, + radio = 1<<15, + pushButton = 1<<16, + radiosInUnison = 1<<25, + #text fields + multiline = 1<<12, + password = 1<<13, + fileSelect = 1<<20, #1.4 + doNotSpellCheck = 1<<22, #1.4 + doNotScroll = 1<<23, #1.4 + comb = 1<<24, #1.5 + richText = 1<<25, #1.5 + + #choice fields + combo = 1<<17, + edit = 1<<18, + sort = 1<<19, + multiSelect = 1<<21, #1.4 + commitOnSelChange = 1<<26, #1.5 + ) + +annotationFlagValues = dict( + invisible=1<<0, + hidden=1<<1, + nozoom=1<<3, + norotate=1<<4, + noview=1<<5, + readonly=1<<6, + locked=1<<7, #1.4 + togglenoview=1<<8, #1.9 + lockedcontents=1<<9, #1.7 + ) +annotationFlagValues['print']=1<<2 + +_bsStyles = dict( + solid='S', + dashed='D', + bevelled='B', + inset='I', + underlined='U', + ) + +def bsPDF(borderWidth,borderStyle,dashLen): + d = dict(W=borderWidth,S=PDFName(_bsStyles[borderStyle])) + if borderStyle=='dashed': + if not dashLen: + dashLen = [3] + elif not isinstance(dashLen,(list,tuple)): + dashLen = [dashLen] + d['D'] = PDFArray(dashLen) + return PDFDictionary(d) + +def escPDF(s): + return escapePDF(s).replace('%','\\045') + +def makeFlags(s,d=annotationFlagValues): + if not isinstance(s,int): + v = s + s = 0 + for x in v.split(): + s |= d[x] + return s + +class PDFFromString(PDFObject): + def __init__(self,s): + if not isStr(s): + raise ValueError('need a unicode/bytes argument not %r' % s) + self._s = s + + def format(self,document): + return pdfdocEnc(self._s) + +class RadioGroup(PDFObject): + def __init__(self,name,tooltip='',fieldFlags='noToggleToOff required radio'): + if not name: + raise ValueError('RadioGroup created with no name') + self.TU = tooltip + self.Ff = makeFlags(fieldFlags,fieldFlagValues) + self.kids = [] + self.T = name + self.V = None + + def format(self,doc): + kids = self.kids + d = len(kids) + if d<2: raise ValueError('RadioGroup:%s has %d < 2 RadioBoxes' % (self.T,d)) + + d = dict( + Ff=self.Ff, + Kids = PDFArray([k for k in self.kids]), + FT = PDFName('Btn'), + T = PDFString(self.T), + #DA = PDFString('0 g'), + ) + if self.V: d['V'] = PDFName(self.V) + if self.TU: d['TU'] =PDFString(self.TU) + r = PDFDictionary(d).format(doc) + return r + + +def _pdfObjToStr(obj): + if isinstance(obj,PDFArray): + return '[%s]' % ''.join((_pdfObjToStr(e) for e in obj.sequence)) + if isinstance(obj,PDFFromString): + return obj._s + return str(obj) + +_NotSet = object() + +class AcroForm(PDFObject): + formFontNames = { + "Helvetica": "Helv", + "Helvetica-Bold": "HeBo", + 'Courier': "Cour", + 'Courier-Bold': "CoBo", + 'Courier-Oblique': "CoOb", + 'Courier-BoldOblique': "CoBO", + 'Helvetica-Oblique': "HeOb", + 'Helvetica-BoldOblique': "HeBO", + 'Times-Roman': "Time", + 'Times-Bold': "TiBo", + 'Times-Italic': "TiIt", + 'Times-BoldItalic': "TiBI", + } + def __init__(self,canv,**kwds): + self.referenceMap = {} + self._canv = weakref.ref(canv) + self.fonts = {} + self.fields = [] + self._radios = {} + self._refMap = {} + self._pdfdocenc = {} + self.sigFlags = None + self.extras = {} + + @property + def useDefault(self): + return _useDefault + + @property + def canv(self): + _canv = self._canv() + if _canv is None: + raise ValueError('%s.canv is no longer available' % self.__class__.__name__) + return _canv + + def fontRef(self,f): + return '/Font << /%s %s >>' % (f,self.fonts[f]) + + def format(self,doc): + d = dict( + Fields = PDFArray([self.getRef(f) for f in self.fields]), + ) + if self.sigFlags: d['SigFlags'] = self.sigFlags + if self.fonts: + FK = list(sorted(self.fonts.keys())) + F = [self.fontRef(f) for f in FK] + d['DA'] = PDFString('/%s 0 Tf 0 g' % FK[0]) + d['DR'] = PDFFromString('<< /Encoding\n<<\n/RLAFencoding\n%s\n>>\n%s\n>>' % (self.encRefStr,'\n'.join(F))) + d.update(self.extras) + r = PDFDictionary(d).format(doc) + return r + + def colorTuple(self,c): + # ISO-32000-1, Table 189: An array of numbers that shall be in ther + # range 0.0 to 1.0 specifying the colour [..]. The number of array + # elements determines the colour space in which the colour shall + # be defined: + # 0 No colour; transparent 1 DeviceGray 3 DeviceRGB 4 DeviceCMYK + if c is None or c.alpha == 0: + return () + return c.cmyk() if isinstance(c,CMYKColor) else c.rgb() + + def streamFillColor(self,c): + t = self.colorTuple(c) + return fp_str(*t)+(' k' if len(t)==4 else ' rg') + + def streamStrokeColor(self,c): + t = self.colorTuple(c) + return fp_str(*t)+(' K' if len(t)==4 else ' RG') + + def checkboxAP(self, + key, #N/D/R + value, #Yes/Off + buttonStyle='circle', + shape='square', + fillColor=None, + borderColor=None, + textColor=None, + borderWidth=None, + borderStyle='solid', + size=20, + dashLen=3, + ): + stream = [].append + ds = size + if shape=='square': + stream('q') + if opaqueColor(fillColor): + streamFill = self.streamFillColor(fillColor) + stream('1 g 1 G %(streamFill)s 0 0 %(size)s %(size)s re f') + if borderWidth is not None and opaqueColor(borderColor): + streamStroke = self.streamStrokeColor(borderColor) + hbw = borderWidth*0.5 + smbw = size - borderWidth + ds = smbw + if borderStyle=='underlined': + stream('%(streamStroke)s %(borderWidth)s w 0 %(hbw)s m %(size)s %(hbw)s l s') + elif borderStyle in ('dashed','inset','bevelled','solid'): + if borderStyle=='dashed': + dash = ' [%s ] 0 d' % fp_str(dashLen) + else: + dash = '' + stream('%(streamStroke)s%(dash)s %(borderWidth)s w %(hbw)s %(hbw)s %(smbw)s %(smbw)s re s') + + if borderStyle in ('bevelled','inset') and opaqueColor(fillColor): + _2bw = 2*borderWidth + sm2bw = size - _2bw + ds = sm2bw + bbs0 = Blacker(fillColor,0.5) + bbs1 = fillColor + if key!='D': + bbs0, bbs1 = bbs1, bbs0 + bbs0 = self.streamFillColor(bbs0) + bbs1 = self.streamFillColor(bbs1) + stream('%(bbs0)s %(borderWidth)s %(borderWidth)s m %(borderWidth)s %(smbw)s l %(smbw)s %(smbw)s l %(sm2bw)s %(sm2bw)s l %(_2bw)s %(sm2bw)s l %(_2bw)s %(_2bw)s l f %(bbs1)s %(smbw)s %(smbw)s m %(smbw)s %(borderWidth)s l %(borderWidth)s %(borderWidth)s l %(_2bw)s %(_2bw)s l %(sm2bw)s %(_2bw)s l %(sm2bw)s %(sm2bw)s l f') + stream('Q') + elif shape=='circle': + cas = lambda _r,**_casKwds: self.circleArcStream(size,_r,**_casKwds) + r = size*0.5 + if opaqueColor(fillColor): + streamFill = self.streamFillColor(fillColor) + stream('q 1 g 1 G %(streamFill)s') + stream(cas(r)) + stream('f') + stream('Q') + if borderWidth is not None and opaqueColor(borderColor): + stream('q') + streamStroke = self.streamStrokeColor(borderColor) + hbw = borderWidth*0.5 + ds = size - borderWidth + if borderStyle=='underlined': + stream('q %(streamStroke)s %(borderWidth)s w 0 %(hbw)s m %(size)s %(hbw)s l s Q') + elif borderStyle in ('dashed','inset','bevelled','solid'): + if borderStyle=='dashed': + dash = ' [3 ] 0 d' + else: + dash = '' + stream('%(streamStroke)s%(dash)s %(borderWidth)s w') + stream(cas(r-hbw)) + stream('s') + stream('Q') + if borderStyle in ('bevelled','inset') and opaqueColor(fillColor): + _3bwh = 3*hbw + ds = size - _3bwh + bbs0 = Blacker(fillColor,0.5) + bbs1 = Whiter(fillColor,0.5) + a0 = (0,1) + a1 = (2,3) + if borderStyle=='inset': + bbs0, bbs1 = bbs1, bbs0 + if key!='D': + bbs0, bbs1 = bbs1, bbs0 + bbs0 = self.streamStrokeColor(bbs0) + bbs1 = self.streamStrokeColor(bbs1) + stream('q %(bbs0)s %(borderWidth)s w') + stream(cas(r-_3bwh,rotated=True,arcs=a0)) + stream('S Q %(bbs1)s q') + stream(cas(r-_3bwh,rotated=True,arcs=a1)) + stream('S Q') + if value=='Yes': + if opaqueColor(textColor): + textFillColor = self.streamFillColor(textColor) + textStrokeColor = self.streamStrokeColor(textColor) + else: + textFillColor = '0 g' + textStrokeColor = '0 G' + stream('q %(textFillColor)s %(textStrokeColor)s') + cbm = cbmarks[buttonStyle] + if shape=='circle' and buttonStyle=='circle': + stream(cas((max(r-(size-ds),1))*0.5)) + stream('f') + else: + stream(cbm.scaledRender(size,size-ds)) + stream('Q') + stream = ('\n'.join(stream.__self__) % vars()).replace(' ',' ').replace('\n\n','\n') + return self.makeStream( + size, size, stream, + Resources = PDFFromString('<< /ProcSet [/PDF] >>'), + ) + + @staticmethod + def circleArcStream(size, r, arcs=(0,1,2,3), rotated=False): + R = [].append + rlen = R.__self__.__len__ + hsize = size * 0.5 + f = size / 20.0 + size *= f + hsize *= f + r *= f + cp = fp_str(0.55231 * r) + r = fp_str(r) + hsize = fp_str(hsize) + mx = '0.7071 0.7071 -0.7071 0.7071' if rotated else '1 0 0 1' + R('%(mx)s %(hsize)s %(hsize)s cm') + if 0 in arcs: + if rlen()==1: R('%(r)s 0 m') + R('%(r)s %(cp)s %(cp)s %(r)s 0 %(r)s c') + if 1 in arcs: + if rlen()==1: R('0 %(r)s m') + R('-%(cp)s %(r)s -%(r)s %(cp)s -%(r)s 0 c') + if 2 in arcs: + if rlen()==1: R('-%(r)s 0 m') + R('-%(r)s -%(cp)s -%(cp)s -%(r)s 0 -%(r)s c') + if 3 in arcs: + if rlen()==1: R('0 -%(r)s m') + R('%(cp)s -%(r)s %(r)s -%(cp)s %(r)s 0 c') + return '\n'.join(R.__self__) % vars() + + def zdMark(self,c,size,ds,iFontName): + c = ZDSyms[c] + W = H = size-ds + fs = H/1.2 + w = float(stringWidth(c,'ZapfDingbats',fs)) + if w>W: + fs *= W/w + dx = ds + 0.5*(W-w) + dy = 0 + return 'BT %(iFontName)s %(fs)s Tf %(dx)s %(dy)s Td %(fs)s TL (%(c)s) Tj ET' % vars() + + + def getRef(self,obj): + return self.canv._doc.Reference(obj) + + def getRefStr(self,obj): + return asNative(self.getRef(obj).format(self.canv._doc)) + + _defaultValues = dict( + cmyk_textColor=CMYKColor(0,0,0,0.9), + cmyk_borderColor=CMYKColor(0,0,0,0.9), + cmyk_fillColor=CMYKColor(0.12,0.157,0,0), + rgb_textColor=Color(0.1,0.1,0.1), + rgb_borderColor=Color(0.1,0.1,0.1), + rgb_fillColor=Color(0.8,0.843,1), + borderWidth=1, + ) + + def setDefault(self, name, value): + if '_defaultValues' not in self.__dict__: + self._defaultValues = self.__class__._defaultValues.clone() + + d = self._defaultValues() + if name in d.keys(): + if '_' in name: + #its a colour name + if name[:4]=='cmyk': + if isinstance(value,(CMYKColor,NoneType)): + d[name] = value + return + elif isinstance(value,(Color,NoneType)): + d[name] = value + return + elif isinstance(value(float,int,NoneType)): + #it's a number + d[name] = value + return + raise ValueError(f'Invalid value in acroForm.setDefault({name!r},{value!r})') + raise ValueError(f'Invalid name in acroForm.setDefault({name!r},{value!r})') + + def getDefaults(self,textColor,borderColor,fillColor, borderWidth): + pfx = (isinstance(fillColor,CMYKColor) + or isinstance(textColor,CMYKColor) + or isinstance(borderColor,CMYKColor)) + if not pfx: pfx = getattr(self.canv._enforceColorSpace,'__name__','_enforceRGB')!='_enforceRGB' + + pfx = 'cmyk_' if pfx else 'rgb_' + d = self._defaultValues + return (textColor if textColor is not _useDefault else d[pfx+'textColor'], + borderColor if borderColor is not _useDefault else d[pfx+'borderColor'], + fillColor if fillColor is not _useDefault else d[pfx+'fillColor'], + borderWidth if borderWidth is not _useDefault else d['borderWidth'], + ) + + @staticmethod + def varyColors(key,t,b,f): + if key!='N': + func = Whiter if key=='R' else Blacker + t,b,f = [func(c,0.9) if c is not None else None for c in (t,b,f)] + return t,b,f + + def checkForceBorder(self,x,y,width,height,forceBorder,shape,borderStyle,borderWidth,borderColor,fillColor): + if forceBorder: + canv = self.canv + canv.saveState() + canv.resetTransforms() + if borderWidth is not None and opaqueColor(borderColor): + hbw = 0.5*borderWidth + canv.setLineWidth(borderWidth) + canv.setStrokeColor(borderColor) + s = 1 + else: + s = hbw = 0 + width -= 2*hbw + height -= 2*hbw + x += hbw + y += hbw + doFill = opaqueColor(fillColor) + if doFill: + canv.setFillColor(fillColor) + if shape=='square': + canv.rect(x,y,width,height,stroke=s,fill=1 if doFill else 0) + else: + r = min(width,height) * 0.5 + canv.circle(x+r,y+r,r,stroke=s,fill=1 if doFill else 0) + canv.restoreState() + + def checkbox(self, + checked=False, + buttonStyle='check', + shape='square', + fillColor=_useDefault, + borderColor=_useDefault, + textColor=_useDefault, + borderWidth=_useDefault, + borderStyle='solid', + size=20, + x=0, + y=0, + tooltip=None, + name=None, + annotationFlags='print', + fieldFlags='required', + forceBorder=False, + relative=False, + dashLen = 3, + ): + initialValue = 'Yes' if checked else 'Off' + textColor,borderColor,fillColor,borderWidth = self.getDefaults(textColor,borderColor,fillColor,borderWidth) + canv = self.canv + if relative: + x, y = self.canv.absolutePosition(x,y) + doc = canv._doc + AP = {} + for key in 'NDR': + APV = {} + tC,bC,fC = self.varyColors(key,textColor,borderColor,fillColor) + for value in ('Yes','Off'): + ap = self.checkboxAP( + key, + value, + buttonStyle=buttonStyle, + shape=shape, + fillColor=fC, + borderColor=bC, + textColor=tC, + borderWidth=borderWidth, + borderStyle=borderStyle, + size=size, + dashLen=dashLen, + ) + if ap._af_refstr in self._refMap: + ref = self._refMap[ap._af_refstr] + else: + ref = self.getRef(ap) + self._refMap[ap._af_refstr] = ref + APV[value]=ref + AP[key] = PDFDictionary(APV) + del APV + CB = dict( + FT = PDFName('Btn'), + P = doc.thisPageRef(), + V = PDFName(initialValue), + AS = PDFName(initialValue), + #DV = PDFName(initialValue), + Rect = PDFArray((x,y,x+size,y+size)), + AP = PDFDictionary(AP), + Subtype = PDFName('Widget'), + Type = PDFName('Annot'), + F = makeFlags(annotationFlags,annotationFlagValues), + Ff = makeFlags(fieldFlags,fieldFlagValues), + H=PDFName('N'), + ) + if tooltip: + CB['TU'] = PDFString(tooltip) + if not name: + name = 'AFF%03d' % len(self.fields) + if borderWidth: CB['BS'] = bsPDF(borderWidth,borderStyle,dashLen) + CB['T'] = PDFString(name) + MK = dict(CA='(%s)' % ZDSyms[buttonStyle]) + if borderColor is not None: + MK['BC'] = PDFArray(self.colorTuple(borderColor)) + if fillColor is not None: + MK['BG'] = PDFArray(self.colorTuple(fillColor)) + CB['MK'] = PDFDictionary(MK) + CB = PDFDictionary(CB) + self.canv._addAnnotation(CB) + self.fields.append(self.getRef(CB)) + self.checkForceBorder(x,y,size,size,forceBorder,shape,borderStyle,borderWidth,borderColor,fillColor) + + def radio(self, + value=None, + selected=False, + buttonStyle='circle', + shape='circle', + fillColor=_useDefault, + borderColor=_useDefault, + textColor=_useDefault, + borderWidth=_useDefault, + borderStyle='solid', + size=20, + x=0, + y=0, + tooltip=None, + name=None, + annotationFlags='print', + fieldFlags='noToggleToOff required radio', + forceBorder=False, + relative=False, + dashLen=3, + ): + if name not in self._radios: + group = RadioGroup(name,tooltip=tooltip,fieldFlags=fieldFlags) + group._ref = self.getRef(group) + self._radios[name] = group + self.fields.append(group._ref) + else: + group = self._radios[name] + fieldFlags = makeFlags(fieldFlags,fieldFlagValues) + if fieldFlags!=group.Ff: + raise ValueError('radio.%s.%s created with different flags' % (name,value)) + if not value: + raise ValueError('bad value %r for radio.%s' % (value,name)) + initialValue = value if selected else 'Off' + textColor,borderColor,fillColor,borderWidth = self.getDefaults(textColor,borderColor,fillColor,borderWidth) + + if initialValue==value: + if group.V is not None: + if group.V!=value: + raise ValueError('radio.%s.%s sets initial value conflicting with %s'%(name,value,group.V)) + else: + group.V = value + canv = self.canv + if relative: + x, y = self.canv.absolutePosition(x,y) + doc = canv._doc + AP = {} + for key in 'NDR': + APV = {} + tC,bC,fC = self.varyColors(key,textColor,borderColor,fillColor) + for v in (value,'Off'): + ap = self.checkboxAP( + key, + 'Yes' if v==value else 'Off', + buttonStyle=buttonStyle, + shape=shape, + fillColor=fC, + borderColor=bC, + textColor=tC, + borderWidth=borderWidth, + borderStyle=borderStyle, + size=size, + dashLen=dashLen, + ) + if ap._af_refstr in self._refMap: + ref = self._refMap[ap._af_refstr] + else: + ref = self.getRef(ap) + self._refMap[ap._af_refstr] = ref + APV[v]=ref + AP[key] = PDFDictionary(APV) + del APV + RB = dict( + FT = PDFName('Btn'), + P = doc.thisPageRef(), + AS = PDFName(initialValue), + #DV = PDFName(initialValue), + Rect = PDFArray((x,y,x+size,y+size)), + AP = PDFDictionary(AP), + Subtype = PDFName('Widget'), + Type = PDFName('Annot'), + F = makeFlags(annotationFlags,annotationFlagValues), + Parent = group._ref, + #DA = PDFString('1 g '+(self.streamFillColor(fillColor) if fillColor else '-0.25 0.75 -0.25 rg')) + H=PDFName('N'), + ) + #RB['T'] = PDFString(name) + MK = dict(CA='(%s)' % ZDSyms[buttonStyle]) + if borderColor is not None: + MK['BC'] = PDFArray(self.colorTuple(borderColor)) + if fillColor is not None: + MK['BG'] = PDFArray(self.colorTuple(fillColor)) + if borderWidth: RB['BS'] = bsPDF(borderWidth,borderStyle,dashLen) + RB['MK'] = PDFDictionary(MK) + RB = PDFDictionary(RB) + self.canv._addAnnotation(RB) + group.kids.append(self.getRef(RB)) + self.checkForceBorder(x,y,size,size,forceBorder,shape,borderStyle,borderWidth,borderColor,fillColor) + + def makeStream(self, + width, + height, + stream, + **D + ): + D['Matrix'] = PDFArray([1.0,0.0,0.0,1.0,0.0,0.0]) + D['BBox'] = PDFArray([0,0,width,height]) + D['Subtype'] = PDFName('Form') + D['Type'] = PDFName('XObject') + D['FormType'] = 1 + + s = PDFStream( + PDFDictionary(D), + stream, + filters = [PDFStreamFilterZCompress()] if self.canv._doc.compression else None, + ) + #compute a lookup string + s._af_refstr = stream+'\n'.join(('%s=%r' % (k,_pdfObjToStr(v)) for k,v in sorted(D.items()))) + return s + + def txAP(self, + key, #N/D/R + value, + iFontName, + rFontName, + fontSize, + shape='square', + fillColor=None, + borderColor=None, + textColor=None, + borderWidth=None, + borderStyle='solid', + width=120, + height=36, + dashLen=3, + wkind='textfield', + labels=[], + I=[], + sel_bg='0.600006 0.756866 0.854904 rg', + sel_fg='0 g', + ): + _stream = [] + stream = _stream.append + if opaqueColor(fillColor): + streamFill = self.streamFillColor(fillColor) + stream('%(streamFill)s\n0 0 %(width)s %(height)s re\nf') + # Pre-initialise border-derived variables so they are always defined for + # the /Tx clipping-region stream that follows, even when no border is drawn. + hbw = _2bw = 0 + bww = width + bwh = height + undash = '' + if borderWidth!=None and borderWidth>0 and opaqueColor(borderColor): + hbw = borderWidth*0.5 + bww = width - borderWidth + bwh = height - borderWidth + _2bw = 2*borderWidth + if borderStyle in ('bevelled','inset'): + bw2w = width - _2bw + bw2h = height - _2bw + if borderStyle == 'bevelled': + bbs0 = '1 g' + if fillColor or borderColor: + bbs1 = '-0.250977 0.749023 -0.250977 rg' + else: + bbs1 = '.75293 g' + else: + bbs0 = '.501953 g' + bbs1 = '.75293 g' + stream('%(bbs0)s\n%(borderWidth)s %(borderWidth)s m\n%(borderWidth)s %(bwh)s l\n%(bww)s %(bwh)s l\n%(bw2w)s %(bw2h)s l\n%(_2bw)s %(bw2h)s l\n%(_2bw)s %(_2bw)s l\nf\n%(bbs1)s\n%(bww)s %(bwh)s m\n%(bww)s %(borderWidth)s l\n%(borderWidth)s %(borderWidth)s l\n%(_2bw)s %(_2bw)s l\n%(bw2w)s %(_2bw)s l\n%(bw2w)s %(bw2h)s l\nf') + else: + hbw = _2bw = borderWidth = 0 + bww = width + bwh = height + undash = '' + if opaqueColor(borderColor) and borderWidth: + streamStroke = self.streamStrokeColor(borderColor) + if borderStyle=='underlined': + stream('%(streamStroke)s %(borderWidth)s w 0 %(hbw)s m %(width)s %(hbw)s l s') + elif borderStyle in ('dashed','inset','bevelled','solid'): + if borderStyle=='dashed': + dash = '\n[%s ] 0 d\n' % fp_str(dashLen) + undash = '[] 0 d' + else: + dash = '\n%s w' % borderWidth + stream('%(streamStroke)s\n%(dash)s\n%(hbw)s %(hbw)s %(bww)s %(bwh)s re\ns') + _4bw = 4*borderWidth + w4bw = width - _4bw + h4bw = height - _4bw + textFill = self.streamFillColor(textColor) if opaqueColor(textColor) else '0 g' + stream('/Tx BMC \nq\n%(_2bw)s %(_2bw)s %(w4bw)s %(h4bw)s re\nW\nn') + leading = 1.2 * fontSize + if wkind=='listbox': + nopts = int(h4bw/leading) + leading = h4bw/float(nopts) + if nopts>len(labels): + i0 = 0 + nopts = len(labels) + elif len(I)<=1: + i0 = I[0] if I else 0 + if i0: + if i0=i: + i0 = i + else: #|I|>1 + if I[1]y: i0 = i - y + ilim = min(y,i0+nopts) + if I: + i = i0 + y = height - _2bw - leading + stream(sel_bg) + while i>' % vars()), + ) + + def makeFont(self,fontName): + if fontName is None: + fontName = 'Helvetica' + if fontName not in self.formFontNames: + raise ValueError('form font name, %r, is not one of the standard 14 fonts' % fontName) + fn = self.formFontNames[fontName] + ref = self.getRefStr(PDFFromString('<< /BaseFont /%s /Subtype /Type1 /Name /%s /Type /Font /Encoding %s >>' % ( + fontName,fn,self.encRefStr))) + if fn not in self.fonts: + self.fonts[fn] = ref + return ref, fn + + def _textfield(self, + value='', + fillColor=_useDefault, + borderColor=_useDefault, + textColor=_useDefault, + borderWidth=_useDefault, + borderStyle='solid', + width=120, + height=36, + x=0, + y=0, + tooltip=None, + name=None, + annotationFlags='print', + fieldFlags='', + forceBorder=False, + relative=False, + maxlen=100, + fontName=None, + fontSize=None, + wkind=None, + options=None, + dashLen=3, + ): + rFontName, iFontName = self.makeFont(fontName) + # Decide which widget dictionary entries to write before fontSize gets + # its rendering default. Omitting /DA, /MK /BG, and /MK /BC when they + # were not explicitly requested lets the field inherit appearance from + # the AcroForm-level /DA//DR or the PDF viewer's built-in default. + _write_da = textColor is not None or fontName is not None or fontSize is not None + if fontSize is None: + fontSize = 12 + textColor,borderColor,fillColor,borderWidth = self.getDefaults(textColor,borderColor,fillColor,borderWidth) + canv = self.canv + if relative: + x, y = self.canv.absolutePosition(x,y) + doc = canv._doc + rFontName = '<>' % (iFontName,rFontName) + Ff = makeFlags(fieldFlags,fieldFlagValues) + if wkind!='textfield': + #options must be a list of pairs (label value) + #value must be a list of the values + FT='Ch' + if wkind=='choice': + Ff |= fieldFlagValues['combo'] #just in case + V = [] + Opt = [] + AP = [] + I = [] + TF = [] + if not isinstance(options,(list,tuple)): + raise TypeError('%s options=%r is wrong type' % (wkind,options)) + for v in options: + if isStr(v): + Opt.append(PDFString(v)) + l = v + elif isinstance(v,(list,tuple)): + if len(v)==1: + v=l=v[0] + else: + l,v = v + Opt.append(PDFArray([PDFString(v),PDFString(l)])) + else: + raise TypeError('%s option %r is wrong type' % (wkind,v)) + AP.append(v) + TF.append(l) + Opt = PDFArray(Opt) + if value: + if not isinstance(value,(list,tuple)): + value = [value] + for v in value: + if v not in AP: + if v not in TF: + raise ValueError('%s value %r is not in option\nvalues %r\nor labels %r' % (wkind,v,AP,TF)) + else: + v = AP[TF.index(v)] + I.append(AP.index(v)) + V.append(PDFString(v)) + I.sort() + if not (Ff & fieldFlagValues['multiSelect']) or len(value)==1: + if wkind=='choice': + value = TF[I[0]] + else: + value = value[:1] + V = V[:1] + V = V[0] if len(V)==1 else PDFArray(V) + lbextras = dict(labels=TF,I=I,wkind=wkind) + else: + V = PDFString(value) + else: + I = Opt = [] + lbextras = {} + FT='Tx' + if not isStr(value): + raise TypeError('textfield value=%r is wrong type' % value) + V = PDFString(value) + AP = {} + for key in 'N': + tC,bC,fC = self.varyColors(key,textColor,borderColor,fillColor) + ap = self.txAP( + key, + value, + iFontName, + rFontName, + fontSize, + fillColor=fC, + borderColor=bC, + textColor=tC, + borderWidth=borderWidth, + borderStyle=borderStyle, + width=width, + height=height, + dashLen = dashLen, + **lbextras + ) + if ap._af_refstr in self._refMap: + ref = self._refMap[ap._af_refstr] + else: + ref = self.getRef(ap) + self._refMap[ap._af_refstr] = ref + AP[key] = ref + + TF = dict( + FT = PDFName(FT), + P = doc.thisPageRef(), + V = V, + #AS = PDFName(value), + DV = V, + Rect = PDFArray((x,y,x+width,y+height)), + AP = PDFDictionary(AP), + Subtype = PDFName('Widget'), + Type = PDFName('Annot'), + F = makeFlags(annotationFlags,annotationFlagValues), + Ff = Ff, + #H=PDFName('N'), + ) + # Write /DA only when font or text color was explicitly requested. + # Omitting /DA lets the widget inherit its default appearance from the + # AcroForm /DA string instead of overriding it with a widget-level entry. + if _write_da: + da_color = self.streamFillColor(textColor) if opaqueColor(textColor) else '0 g' + TF['DA'] = PDFString('/%s %d Tf %s' % (iFontName,fontSize, da_color)) + if Opt: TF['Opt'] = Opt + if I: TF['I'] = PDFArray(I) + if maxlen: + TF['MaxLen'] = maxlen + if tooltip: + TF['TU'] = PDFString(tooltip) + if not name: + name = 'AFF%03d' % len(self.fields) + TF['T'] = PDFString(name) + MK = {} + if fillColor is not None: + MK['BG'] = PDFArray(self.colorTuple(fillColor)) + # Acrobat seems to draw a thin border when BS is defined, so only + # include this if there actually is a border to draw + if borderWidth: + TF['BS'] = bsPDF(borderWidth,borderStyle,dashLen) + if borderColor is not None: + MK['BC'] = PDFArray(self.colorTuple(borderColor)) + if MK: + TF['MK'] = PDFDictionary(MK) + + TF = PDFDictionary(TF) + self.canv._addAnnotation(TF) + self.fields.append(self.getRef(TF)) + self.checkForceBorder(x,y,width,height,forceBorder,'square',borderStyle,borderWidth,borderColor,fillColor) + + def textfield(self, + value='', + fillColor=_useDefault, + borderColor=_useDefault, + textColor=_useDefault, + borderWidth=_useDefault, + borderStyle='solid', + width=120, + height=36, + x=0, + y=0, + tooltip=None, + name=None, + annotationFlags='print', + fieldFlags='', + forceBorder=False, + relative=False, + maxlen=100, + fontName=None, + fontSize=None, + dashLen=3, + ): + return self._textfield( + value=value, + fillColor=fillColor, + borderColor=borderColor, + textColor=textColor, + borderWidth=borderWidth, + borderStyle=borderStyle, + width=width, + height=height, + x=x, + y=y, + tooltip=tooltip, + name=name, + annotationFlags=annotationFlags, + fieldFlags=fieldFlags, + forceBorder=forceBorder, + relative=relative, + maxlen=maxlen, + fontName=fontName, + fontSize=fontSize, + dashLen=dashLen, + wkind='textfield', + ) + + def listbox(self, + value='', + fillColor=_useDefault, + borderColor=_useDefault, + textColor=_useDefault, + borderWidth=_useDefault, + borderStyle='solid', + width=120, + height=36, + x=0, + y=0, + tooltip=None, + name=None, + annotationFlags='print', + fieldFlags='', + forceBorder=False, + relative=False, + fontName=None, + fontSize=None, + dashLen=3, + maxlen=None, + options=[], + ): + return self._textfield( + value=value, + fillColor=fillColor, + borderColor=borderColor, + textColor=textColor, + borderWidth=borderWidth, + borderStyle=borderStyle, + width=width, + height=height, + x=x, + y=y, + tooltip=tooltip, + name=name, + annotationFlags=annotationFlags, + fieldFlags=fieldFlags, + forceBorder=forceBorder, + relative=relative, + maxlen=maxlen, + fontName=fontName, + fontSize=fontSize, + dashLen=dashLen, + wkind='listbox', + options = options, + ) + def choice(self, + value='', + fillColor=_useDefault, + borderColor=_useDefault, + textColor=_useDefault, + borderWidth=_useDefault, + borderStyle='solid', + width=120, + height=36, + x=0, + y=0, + tooltip=None, + name=None, + annotationFlags='print', + fieldFlags='combo', + forceBorder=False, + relative=False, + fontName=None, + fontSize=None, + dashLen=3, + maxlen=None, + options=[], + ): + return self._textfield( + value=value, + fillColor=fillColor, + borderColor=borderColor, + textColor=textColor, + borderWidth=borderWidth, + borderStyle=borderStyle, + width=width, + height=height, + x=x, + y=y, + tooltip=tooltip, + name=name, + annotationFlags=annotationFlags, + fieldFlags=fieldFlags, + forceBorder=forceBorder, + relative=relative, + maxlen=maxlen, + fontName=fontName, + fontSize=fontSize, + dashLen=dashLen, + wkind='choice', + options = options, + ) + + def checkboxRelative(self, **kwds): + "same as checkbox except the x and y are relative to the canvas coordinate transform" + kwds['relative']=True + self.checkbox(**kwds) + + def radioRelative(self, **kwds): + "same as radio except the x and y are relative to the canvas coordinate transform" + kwds['relative']=True + self.radio(**kwds) + + def textfieldRelative(self, **kwds): + "same as textfield except the x and y are relative to the canvas coordinate transform" + kwds['relative']=True + self.textfield(**kwds) + + def listboxRelative(self, **kwds): + "same as textfield except the x and y are relative to the canvas coordinate transform" + kwds['relative']=True + self.textfield(**kwds) + def choiceRelative(self, **kwds): + "same as textfield except the x and y are relative to the canvas coordinate transform" + kwds['relative']=True + self.textfield(**kwds) + + @property + def encRefStr(self): + if not self._pdfdocenc: + self._pdfdocenc = PDFFromString('''<>''') + return self.getRefStr(self._pdfdocenc) + +class CBMark: + opNames = 'm l c h'.split() + opCount = 1,1,3,0 + + def __init__(self,ops,points,bounds,slack=0.05): + self.ops = ops + self.xmin,self.ymin,self.xmax,self.ymax = bounds + self.points = points + self.slack = slack + + def scaledRender(self,size,ds=0): + ''' + >>> print(cbmarks['check'].scaledRender(20)) + 12.97075 14.68802 m 15.00139 17.16992 l 15.9039 18.1727 17.93454 18.67409 19.2883 18.67409 c 19.46379 18.27298 l 17.13231 15.51532 l 11.91783 8.62117 l 8.307799 3.030641 l 7.430362 1.526462 l 7.305014 1.275766 7.154596 .97493 6.9039 .824513 c 6.577994 .674095 5.825905 .674095 5.47493 .674095 c 4.672702 .674095 4.497214 .674095 4.321727 .799443 c 4.071031 .97493 3.945682 1.325905 3.770195 1.67688 c 3.218663 2.830084 2.240947 5.337047 2.240947 6.590529 c 2.240947 7.016713 2.491643 7.21727 2.817549 7.442897 c 3.344011 7.818942 4.0961 8.245125 4.747911 8.245125 c 5.249304 8.245125 5.299443 7.818942 5.449861 7.417827 c 5.951253 6.239554 l 6.026462 6.038997 6.252089 5.337047 6.527855 5.337047 c 6.778552 5.337047 7.079387 5.913649 7.179666 6.089136 c 12.97075 14.68802 l h f + >>> print(cbmarks['cross'].scaledRender(20)) + 19.9104 17.43931 m 12.41908 10 l 19.9104 2.534682 l 18.37572 1 l 10.9104 8.491329 l 3.445087 1 l 1.910405 2.534682 l 9.427746 10 l 1.910405 17.46532 l 3.445087 19 l 10.9104 11.50867 l 18.37572 19 l 19.9104 17.43931 l h f + >>> print(cbmarks['circle'].scaledRender(20)) + 1.872576 9.663435 m 1.872576 14.64958 5.936288 18.61357 10.89751 18.61357 c 15.8338 18.61357 19.87258 14.59972 19.87258 9.663435 c 19.87258 4.727147 15.8338 .688366 10.89751 .688366 c 5.936288 .688366 1.872576 4.677285 1.872576 9.663435 c h f + >>> print(cbmarks['star'].scaledRender(20)) + 10.85542 18.3253 m 12.90361 11.84337 l 19.84337 11.84337 l 14.25301 7.650602 l 16.42169 1 l 10.85542 5.096386 l 5.289157 1 l 7.481928 7.650602 l 1.843373 11.84337 l 8.759036 11.84337 l 10.85542 18.3253 l h f + >>> print(cbmarks['diamond'].scaledRender(20)) + 17.43533 9.662031 m 15.63282 7.484006 l 10.85118 .649513 l 8.422809 4.329624 l 5.919332 7.659249 l 4.267038 9.662031 l 6.16968 12.0153 l 10.85118 18.64951 l 12.75382 15.4701 15.00695 12.49096 17.43533 9.662031 c h f + ''' + #work out the scale and translation + W = H = size - 2*ds + xmin = self.xmin + ymin = self.ymin + w = self.xmax-xmin + h = self.ymax-ymin + slack = self.slack*min(W,H) + sx = (W - 2*slack)/float(w) + sy = (H - 2*slack)/float(h) + sx = sy = min(sx,sy) + w *= sx + h *= sy + dx = ds+(W - w)*0.5 + dy = ds+(H - h)*0.5 + xsc = lambda v: fp_str((v-xmin)*sx+dx) + ysc = lambda v: fp_str((v-ymin)*sy+dy) + + opNames = self.opNames + opCount = self.opCount + C = [].append + i = 0 + points = self.points + for op in self.ops: + c = opCount[op] + for _ in range(c): + C(xsc(points[i])) + C(ysc(points[i+1])) + i += 2 + C(opNames[op]) + C('f') + return ' '.join(C.__self__) + +cbmarks = dict( + check=CBMark( + [0, 1, 2, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 1, 3], + [462, 546, 543, 645, 579, 685, 660, 705, 714, 705, 721, 689, 628, 579, 420, 304, 276, 81, 241, 21, 236, 11, 230, -1, 220, -7, 207, -13, 177, -13, 163, -13, 131, -13, 124, -13, 117, -8, 107, -1, 102, 13, 95, 27, 73, 73, 34, 173, 34, 223, 34, 240, 44, 248, 57, 257, 78, 272, 108, 289, 134, 289, 154, 289, 156, 272, 162, 256, 182, 209, 185, 201, 194, 173, 205, 173, 215, 173, 227, 196, 231, 203, 462, 546], + (34,-12,721,706), + ), + cross = CBMark( + [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3], + [727, 632, 439, 346, 727, 59, 668, 0, 381, 288, 94, 0, 35, 59, 324, 346, 35, 633, 94, 692, 381, 404, 668, 692, 727, 632], + (35,0,727,692), + ), + circle = CBMark( + [0, 2, 2, 2, 2, 3], + [35, 346, 35, 546, 198, 705, 397, 705, 595, 705, 757, 544, 757, 346, 757, 148, 595, -14, 397, -14, 198, -14, 35, 146, 35, 346], + (35,-14,757,705), + ), + star = CBMark( + [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3], + [409, 705, 494, 436, 782, 436, 550, 262, 640, -14, 409, 156, 178, -14, 269, 262, 35, 436, 322, 436, 409, 705], + (35,-14,782,705), + ), + diamond = CBMark( + [0, 1, 1, 1, 1, 1, 1, 1, 2, 3], + [560, 346, 488, 259, 297, -14, 200, 133, 100, 266, 34, 346, 110, 440, 297, 705, 373, 578, 463, 459, 560, 346], + (34,-14,560,705), + ), + ) +ZDSyms=dict(check='4',cross='5',circle='l',star='N',diamond='u') + +if __name__ == "__main__": + import doctest + doctest.testmod() diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/cidfonts.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/cidfonts.py new file mode 100644 index 0000000000000000000000000000000000000000..e204391ae167fb33eb7d0fc782e65fa23ce67697 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/cidfonts.py @@ -0,0 +1,516 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/pdfbase/cidfonts.py +#$Header $ +__version__='3.3.0' +__doc__="""CID (Asian multi-byte) font support. + +This defines classes to represent CID fonts. They know how to calculate +their own width and how to write themselves into PDF files.""" + +import os +import marshal +import time +from hashlib import md5 + +from reportlab.pdfbase import pdfmetrics +from reportlab.pdfbase._cidfontdata import allowedTypeFaces, allowedEncodings, CIDFontInfo, \ + defaultUnicodeEncodings, widthsByUnichar +from reportlab.pdfgen.canvas import Canvas +from reportlab.pdfbase import pdfdoc +from reportlab.lib.rl_accel import escapePDF +from reportlab.rl_config import CMapSearchPath +from reportlab.lib.utils import isSeq, isBytes + +#quick hackery for 2.0 release. Now we always do unicode, and have built in +#the CMAP data, any code to load CMap files is not needed. +DISABLE_CMAP = True + + +def findCMapFile(name): + "Returns full filename, or raises error" + for dirname in CMapSearchPath: + cmapfile = dirname + os.sep + name + if os.path.isfile(cmapfile): + #print "found", cmapfile + return cmapfile + raise IOError('CMAP file for encodings "%s" not found!' % name) + +def structToPDF(structure): + "Converts deeply nested structure to PDFdoc dictionary/array objects" + if isinstance(structure,dict): + newDict = {} + for k, v in structure.items(): + newDict[k] = structToPDF(v) + return pdfdoc.PDFDictionary(newDict) + elif isSeq(structure): + newList = [] + for elem in structure: + newList.append(structToPDF(elem)) + return pdfdoc.PDFArray(newList) + else: + return structure + +class CIDEncoding(pdfmetrics.Encoding): + """Multi-byte encoding. These are loaded from CMAP files. + + A CMAP file is like a mini-codec. It defines the correspondence + between code points in the (multi-byte) input data and Character + IDs. """ + # aims to do similar things to Brian Hooper's CMap class, + # but I could not get it working and had to rewrite. + # also, we should really rearrange our current encoding + # into a SingleByteEncoding since many of its methods + # should not apply here. + + def __init__(self, name, useCache=1): + self.name = name + self._mapFileHash = None + self._codeSpaceRanges = [] + self._notDefRanges = [] + self._cmap = {} + self.source = None + if not DISABLE_CMAP: + if useCache: + from reportlab.lib.utils import get_rl_tempdir + fontmapdir = get_rl_tempdir('FastCMAPS') + if os.path.isfile(fontmapdir + os.sep + name + '.fastmap'): + self.fastLoad(fontmapdir) + self.source = fontmapdir + os.sep + name + '.fastmap' + else: + self.parseCMAPFile(name) + self.source = 'CMAP: ' + name + self.fastSave(fontmapdir) + else: + self.parseCMAPFile(name) + + def _hash(self, text): + hasher = md5(usedforsecurity=False) + hasher.update(text) + return hasher.digest() + + def parseCMAPFile(self, name): + """This is a tricky one as CMAP files are Postscript + ones. Some refer to others with a 'usecmap' + command""" + #started = time.clock() + cmapfile = findCMapFile(name) + # this will CRAWL with the unicode encodings... + rawdata = open(cmapfile, 'r').read() + + self._mapFileHash = self._hash(rawdata) + #if it contains the token 'usecmap', parse the other + #cmap file first.... + usecmap_pos = rawdata.find('usecmap') + if usecmap_pos > -1: + #they tell us to look in another file + #for the code space ranges. The one + # to use will be the previous word. + chunk = rawdata[0:usecmap_pos] + words = chunk.split() + otherCMAPName = words[-1] + #print 'referred to another CMAP %s' % otherCMAPName + self.parseCMAPFile(otherCMAPName) + # now continue parsing this, as it may + # override some settings + + + words = rawdata.split() + while words != []: + if words[0] == 'begincodespacerange': + words = words[1:] + while words[0] != 'endcodespacerange': + strStart, strEnd, words = words[0], words[1], words[2:] + start = int(strStart[1:-1], 16) + end = int(strEnd[1:-1], 16) + self._codeSpaceRanges.append((start, end),) + elif words[0] == 'beginnotdefrange': + words = words[1:] + while words[0] != 'endnotdefrange': + strStart, strEnd, strValue = words[0:3] + start = int(strStart[1:-1], 16) + end = int(strEnd[1:-1], 16) + value = int(strValue) + self._notDefRanges.append((start, end, value),) + words = words[3:] + elif words[0] == 'begincidrange': + words = words[1:] + while words[0] != 'endcidrange': + strStart, strEnd, strValue = words[0:3] + start = int(strStart[1:-1], 16) + end = int(strEnd[1:-1], 16) + value = int(strValue) + # this means that 'start' corresponds to 'value', + # start+1 corresponds to value+1 and so on up + # to end + offset = 0 + while start + offset <= end: + self._cmap[start + offset] = value + offset + offset = offset + 1 + words = words[3:] + + else: + words = words[1:] + #finished = time.clock() + #print 'parsed CMAP %s in %0.4f seconds' % (self.name, finished - started) + + def translate(self, text): + "Convert a string into a list of CIDs" + output = [] + cmap = self._cmap + lastChar = '' + for char in text: + if lastChar != '': + #print 'convert character pair "%s"' % (lastChar + char) + num = ord(lastChar) * 256 + ord(char) + else: + #print 'convert character "%s"' % char + num = ord(char) + lastChar = char + found = 0 + for low, high in self._codeSpaceRanges: + if low < num < high: + try: + cid = cmap[num] + #print '%d -> %d' % (num, cid) + except KeyError: + #not defined. Try to find the appropriate + # notdef character, or failing that return + # zero + cid = 0 + for low2, high2, notdef in self._notDefRanges: + if low2 < num < high2: + cid = notdef + break + output.append(cid) + found = 1 + break + if found: + lastChar = '' + else: + lastChar = char + return output + + def fastSave(self, directory): + f = open(os.path.join(directory, self.name + '.fastmap'), 'wb') + marshal.dump(self._mapFileHash, f) + marshal.dump(self._codeSpaceRanges, f) + marshal.dump(self._notDefRanges, f) + marshal.dump(self._cmap, f) + f.close() + + def fastLoad(self, directory): + started = time.clock() + f = open(os.path.join(directory, self.name + '.fastmap'), 'rb') + self._mapFileHash = marshal.load(f) + self._codeSpaceRanges = marshal.load(f) + self._notDefRanges = marshal.load(f) + self._cmap = marshal.load(f) + f.close() + finished = time.clock() + #print 'loaded %s in %0.4f seconds' % (self.name, finished - started) + + def getData(self): + """Simple persistence helper. Return a dict with all that matters.""" + return { + 'mapFileHash': self._mapFileHash, + 'codeSpaceRanges': self._codeSpaceRanges, + 'notDefRanges': self._notDefRanges, + 'cmap': self._cmap, + } + +class CIDTypeFace(pdfmetrics.TypeFace): + """Multi-byte type face. + + Conceptually similar to a single byte typeface, + but the glyphs are identified by a numeric Character + ID (CID) and not a glyph name. """ + def __init__(self, name): + """Initialised from one of the canned dictionaries in allowedEncodings + + Or rather, it will be shortly...""" + pdfmetrics.TypeFace.__init__(self, name) + self._extractDictInfo(name) + def _extractDictInfo(self, name): + try: + fontDict = CIDFontInfo[name] + except KeyError: + raise KeyError("Unable to find information on CID typeface '%s'" % name + + "Only the following font names work:" + repr(allowedTypeFaces)) + descFont = fontDict['DescendantFonts'][0] + self.ascent = descFont['FontDescriptor']['Ascent'] + self.descent = descFont['FontDescriptor']['Descent'] + self._defaultWidth = descFont['DW'] + self._explicitWidths = self._expandWidths(descFont['W']) + + # should really support self.glyphWidths, self.glyphNames + # but not done yet. + + + def _expandWidths(self, compactWidthArray): + """Expands Adobe nested list structure to get a dictionary of widths. + + Here is an example of such a structure.:: + + ( + # starting at character ID 1, next n characters have the widths given. + 1, (277,305,500,668,668,906,727,305,445,445,508,668,305,379,305,539), + # all Characters from ID 17 to 26 are 668 em units wide + 17, 26, 668, + 27, (305, 305, 668, 668, 668, 566, 871, 727, 637, 652, 699, 574, 555, + 676, 687, 242, 492, 664, 582, 789, 707, 734, 582, 734, 605, 605, + 641, 668, 727, 945, 609, 609, 574, 445, 668, 445, 668, 668, 590, + 555, 609, 547, 602, 574, 391, 609, 582, 234, 277, 539, 234, 895, + 582, 605, 602, 602, 387, 508, 441, 582, 562, 781, 531, 570, 555, + 449, 246, 449, 668), + # these must be half width katakana and the like. + 231, 632, 500 + ) + + """ + data = compactWidthArray[:] + widths = {} + while data: + start, data = data[0], data[1:] + if isSeq(data[0]): + items, data = data[0], data[1:] + for offset in range(len(items)): + widths[start + offset] = items[offset] + else: + end, width, data = data[0], data[1], data[2:] + for idx in range(start, end+1): + widths[idx] = width + return widths + + def getCharWidth(self, characterId): + return self._explicitWidths.get(characterId, self._defaultWidth) + +class CIDFont(pdfmetrics.Font): + "Represents a built-in multi-byte font" + _multiByte = 1 + + def __init__(self, face, encoding): + + assert face in allowedTypeFaces, "TypeFace '%s' not supported! Use any of these instead: %s" % (face, allowedTypeFaces) + self.faceName = face + #should cache in registry... + self.face = CIDTypeFace(face) + + assert encoding in allowedEncodings, "Encoding '%s' not supported! Use any of these instead: %s" % (encoding, allowedEncodings) + self.encodingName = encoding + self.encoding = CIDEncoding(encoding) + + #legacy hack doing quick cut and paste. + self.fontName = self.faceName + '-' + self.encodingName + self.name = self.fontName + + # need to know if it is vertical or horizontal + self.isVertical = (self.encodingName[-1] == 'V') + + #no substitutes initially + self.substitutionFonts = [] + + def formatForPdf(self, text): + encoded = escapePDF(text) + #print 'encoded CIDFont:', encoded + return encoded + + def stringWidth(self, text, size, encoding=None): + """This presumes non-Unicode input. UnicodeCIDFont wraps it for that context""" + cidlist = self.encoding.translate(text) + if self.isVertical: + #this part is "not checked!" but seems to work. + #assume each is 1000 ems high + return len(cidlist) * size + else: + w = 0 + for cid in cidlist: + w = w + self.face.getCharWidth(cid) + return 0.001 * w * size + + + def addObjects(self, doc): + """The explicit code in addMinchoObjects and addGothicObjects + will be replaced by something that pulls the data from + _cidfontdata.py in the next few days.""" + internalName = 'F' + repr(len(doc.fontMapping)+1) + + bigDict = CIDFontInfo[self.face.name] + bigDict['Name'] = '/' + internalName + bigDict['Encoding'] = '/' + self.encodingName + + #convert to PDF dictionary/array objects + cidObj = structToPDF(bigDict) + + # link into document, and add to font map + r = doc.Reference(cidObj, internalName) + fontDict = doc.idToObject['BasicFonts'].dict + fontDict[internalName] = r + doc.fontMapping[self.name] = '/' + internalName + + +class UnicodeCIDFont(CIDFont): + """Wraps up CIDFont to hide explicit encoding choice; + encodes text for output as UTF16. + + lang should be one of 'jpn',chs','cht','kor' for now. + if vertical is set, it will select a different widths array + and possibly glyphs for some punctuation marks. + + halfWidth is only for Japanese. + + + >>> dodgy = UnicodeCIDFont('nonexistent') + Traceback (most recent call last): + ... + KeyError: "don't know anything about CID font nonexistent" + >>> heisei = UnicodeCIDFont('HeiseiMin-W3') + >>> heisei.name + 'HeiseiMin-W3' + >>> heisei.language + 'jpn' + >>> heisei.encoding.name + 'UniJIS-UCS2-H' + >>> #This is how PDF data gets encoded. + >>> print(heisei.formatForPdf('hello')) + \\000h\\000e\\000l\\000l\\000o + >>> tokyo = u'\u6771\u4AEC' + >>> print(heisei.formatForPdf(tokyo)) + gqJ\\354 + >>> print(heisei.stringWidth(tokyo,10)) + 20.0 + >>> print(heisei.stringWidth('hello world',10)) + 45.83 + """ + + def __init__(self, face, isVertical=False, isHalfWidth=False): + #pass + try: + lang, defaultEncoding = defaultUnicodeEncodings[face] + except KeyError: + raise KeyError("don't know anything about CID font %s" % face) + + #we know the languages now. + self.language = lang + + #rebuilt encoding string. They follow rules which work + #for the 7 fonts provided. + enc = defaultEncoding[:-1] + if isHalfWidth: + enc = enc + 'HW-' + if isVertical: + enc = enc + 'V' + else: + enc = enc + 'H' + + #now we can do the more general case + CIDFont.__init__(self, face, enc) + #self.encName = 'utf_16_le' + #it's simpler for unicode, just use the face name + self.name = self.fontName = face + self.vertical = isVertical + self.isHalfWidth = isHalfWidth + + self.unicodeWidths = widthsByUnichar[self.name] + + + def formatForPdf(self, text): + #these ones should be encoded asUTF16 minus the BOM + from codecs import utf_16_be_encode + #print 'formatting %s: %s' % (type(text), repr(text)) + if isBytes(text): + text = text.decode('utf8') + utfText = utf_16_be_encode(text)[0] + encoded = escapePDF(utfText) + #print ' encoded:',encoded + return encoded + # + #result = escapePDF(encoded) + #print ' -> %s' % repr(result) + #return result + + + def stringWidth(self, text, size, encoding=None): + "Just ensure we do width test on characters, not bytes..." + if isBytes(text): + text = text.decode('utf8') + + widths = self.unicodeWidths + return size * 0.001 * sum([widths.get(uch, 1000) for uch in text]) + #return CIDFont.stringWidth(self, text, size, encoding) + + +def precalculate(cmapdir): + # crunches through all, making 'fastmap' files + import os + files = os.listdir(cmapdir) + for file in files: + if os.path.isfile(cmapdir + os.sep + file + '.fastmap'): + continue + try: + enc = CIDEncoding(file) + except: + print('cannot parse %s, skipping' % enc) + continue + enc.fastSave(cmapdir) + print('saved %s.fastmap' % file) + +def test(): + # only works if you have cirrect encodings on your box! + c = Canvas('test_japanese.pdf') + c.setFont('Helvetica', 30) + c.drawString(100,700, 'Japanese Font Support') + + pdfmetrics.registerFont(CIDFont('HeiseiMin-W3','90ms-RKSJ-H')) + pdfmetrics.registerFont(CIDFont('HeiseiKakuGo-W5','90ms-RKSJ-H')) + + + # the two typefaces + c.setFont('HeiseiMin-W3-90ms-RKSJ-H', 16) + # this says "This is HeiseiMincho" in shift-JIS. Not all our readers + # have a Japanese PC, so I escaped it. On a Japanese-capable + # system, print the string to see Kanji + message1 = '\202\261\202\352\202\315\225\275\220\254\226\276\222\251\202\305\202\267\201B' + c.drawString(100, 675, message1) + c.save() + print('saved test_japanese.pdf') + + +## print 'CMAP_DIR = ', CMAP_DIR +## tf1 = CIDTypeFace('HeiseiMin-W3') +## print 'ascent = ',tf1.ascent +## print 'descent = ',tf1.descent +## for cid in [1,2,3,4,5,18,19,28,231,1742]: +## print 'width of cid %d = %d' % (cid, tf1.getCharWidth(cid)) + + encName = '90ms-RKSJ-H' + enc = CIDEncoding(encName) + print(message1, '->', enc.translate(message1)) + + f = CIDFont('HeiseiMin-W3','90ms-RKSJ-H') + print('width = %0.2f' % f.stringWidth(message1, 10)) + + + #testing all encodings +## import time +## started = time.time() +## import glob +## for encName in _cidfontdata.allowedEncodings: +## #encName = '90ms-RKSJ-H' +## enc = CIDEncoding(encName) +## print 'encoding %s:' % encName +## print ' codeSpaceRanges = %s' % enc._codeSpaceRanges +## print ' notDefRanges = %s' % enc._notDefRanges +## print ' mapping size = %d' % len(enc._cmap) +## finished = time.time() +## print 'constructed all encodings in %0.2f seconds' % (finished - started) + +if __name__=='__main__': + import doctest + from reportlab.pdfbase import cidfonts + doctest.testmod(cidfonts) + #test() + + + + diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/pdfdoc.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/pdfdoc.py new file mode 100644 index 0000000000000000000000000000000000000000..9f34282e83ac21eb1d9cbcd5120edb53de61c65f --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/pdfdoc.py @@ -0,0 +1,2417 @@ +#Copyright ReportLab Europe Ltd. 2000-2023 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/pdfbase/pdfdoc.py +__version__='4.2.0' +__doc__=""" +The module pdfdoc.py handles the 'outer structure' of PDF documents, ensuring that +all objects are properly cross-referenced and indexed to the nearest byte. The +'inner structure' - the page descriptions - are presumed to be generated before +each page is saved. +pdfgen.py calls this and provides a 'canvas' object to handle page marking operators. +piddlePDF calls pdfgen and offers a high-level interface. + +The classes within this generally mirror structures in the PDF file +and are not part of any public interface. Instead, canvas and font +classes are made available elsewhere for users to manipulate. +""" +import binascii, codecs, zlib +from collections import OrderedDict +from reportlab.pdfbase import pdfutils +from reportlab import rl_config +from reportlab.lib.utils import open_for_read, makeFileName, isSeq, isBytes, isUnicode, _digester, isStr, bytestr, annotateException, TimeStamp +from reportlab.lib.rl_accel import escapePDF, fp_str, asciiBase85Encode, asciiBase85Decode +from reportlab.pdfbase import pdfmetrics +from hashlib import md5 + +from sys import stderr + +class PDFError(Exception): + pass + +# __InternalName__ is a special attribute that can only be set by the Document arbitrator +__InternalName__ = "__InternalName__" + +# __RefOnly__ marks reference only elements that must be formatted on top level +__RefOnly__ = "__RefOnly__" + +# __Comment__ provides a (one line) comment to inline with an object ref, if present +# if it is more than one line then percentize it... +__Comment__ = "__Comment__" + +# name for standard font dictionary +BasicFonts = "BasicFonts" + +# name for the pages object +Pages = "Pages" + + +PDF_VERSION_DEFAULT = (1, 3) +PDF_SUPPORT_VERSION = dict( #map keyword to min version that supports it + transparency = (1, 4), + ) + +def pdfdocEnc(x): + return x.encode('extpdfdoc') if isinstance(x,str) else x + +def format(element, document, toplevel=0): + """Indirection step for formatting. + Ensures that document parameters alter behaviour + of formatting for all elements. + """ + if isinstance(element,PDFObject): + if not toplevel and hasattr(element, __RefOnly__): + # the object cannot be a component at non top level. + # make a reference to it and return it's format + return document.Reference(element).format(document) + else: + f = element.format(document) + if not rl_config.invariant and rl_config.pdfComments and hasattr(element, __Comment__): + f = pdfdocEnc("%% %s\n" % element.__Comment__)+f + return f + elif type(element) in (float, int): + #use a controlled number formatting routine + #instead of str, so Jython/Python etc do not differ + return pdfdocEnc(fp_str(element)) + elif isBytes(element): + return element + elif isUnicode(element): + return pdfdocEnc(element) + else: + return pdfdocEnc(str(element)) + +def xObjectName(externalname): + return "FormXob.%s" % externalname + +# backwards compatibility +formName = xObjectName + +# no encryption +class NoEncryption: + def encode(self, t): + "encode a string, stream, text" + return t + def prepare(self, document): + # get ready to do encryption + pass + def register(self, objnum, version): + # enter a new direct object + pass + def info(self): + # the representation of self in file if any (should be None or PDFDict) + return None + +class PDFObject: + pass + +class DummyDoc(PDFObject): + "used to bypass encryption when required" + encrypt = NoEncryption() + +### the global document structure manager +class PDFDocument(PDFObject): + # set this to define filters + defaultStreamFilters = None + encrypt = NoEncryption() # default no encryption + def __init__(self, + dummyoutline=0, + compression=rl_config.pageCompression, + invariant=rl_config.invariant, + filename=None, + pdfVersion=PDF_VERSION_DEFAULT, + lang=None, + ): + self._ID = None + self.objectcounter = 0 + self.shadingCounter = 0 + self.inObject = None + self.pageCounter = 1 + + # allow None value to be passed in to mean 'give system defaults' + if invariant is None: + self.invariant = rl_config.invariant + else: + self.invariant = invariant + self.setCompression(compression) + self._pdfVersion = pdfVersion + # signature for creating PDF ID + sig = self.signature = md5(usedforsecurity=False) + sig.update(b"a reportlab document") + self._timeStamp = TimeStamp(self.invariant) + cat = self._timeStamp.t + cat = ascii(cat) + sig.update(bytestr(cat)) # initialize with timestamp digest + # mapping of internal identifier ("Page001") to PDF objectnumber and generation number (34, 0) + self.idToObjectNumberAndVersion = {} + # mapping of internal identifier ("Page001") to PDF object (PDFPage instance) + self.idToObject = {} + # internal id to file location + self.idToOffset = {} + # number to id + self.numberToId = {} + cat = self.Catalog = self._catalog = PDFCatalog() + pages = self.Pages = PDFPages() + cat.Pages = pages + lang = lang if lang else rl_config.documentLang + if lang: + cat.Lang = PDFString(lang) + self.outline = self.Outlines = cat.Outlines = PDFOutlines0() if dummyoutline else PDFOutlines() + self.info = PDFInfo() + #self.Reference(self.Catalog) + #self.Reference(self.Info) + self.fontMapping = {} + #make an empty font dictionary + DD = PDFDictionary({}) + DD.__Comment__ = "The standard fonts dictionary" + self.Reference(DD, BasicFonts) + self.delayedFonts = [] + + def setCompression(self, onoff): + # XXX: maybe this should also set self.defaultStreamFilters? + self.compression = onoff + + def ensureMinPdfVersion(self, *keys): + "Ensure that the pdf version is greater than or equal to that specified by the keys" + for k in keys: + self._pdfVersion = max(self._pdfVersion, PDF_SUPPORT_VERSION[k]) + + def updateSignature(self, thing): + "add information to the signature" + if self._ID: return # but not if its used already! + self.signature.update(bytestr(thing)) + + def ID(self): + "A unique fingerprint for the file (unless in invariant mode)" + if self._ID: + return self._ID + digest = self.signature.digest() + doc = DummyDoc() + IDs = PDFText(digest,enc='raw').format(doc) + self._ID = (b'\n['+IDs+IDs+b']\n% ReportLab generated PDF document -- digest (opensource)\n') + return self._ID + + def SaveToFile(self, filename, canvas): + if getattr(self,'_savedToFile',False): + raise RuntimeError("class %s instances can only be saved once" % self.__class__.__name__) + self._savedToFile = True + if hasattr(getattr(filename, "write",None),'__call__'): + myfile = 0 + f = filename + filename = getattr(f,'name',None) + if isinstance(filename,int): + filename = ''% filename + elif not isStr(filename): #try to fix bug reported by Robert Schroll + filename = '<%s@0X%8.8X>' % (f.__class__.__name__,id(f)) + filename = makeFileName(filename) + elif isStr(filename): + myfile = 1 + filename = makeFileName(filename) + f = open(filename, "wb") + else: + raise TypeError('Cannot use %s as a filename or file' % repr(filename)) + + data = self.GetPDFData(canvas) + if isUnicode(data): + data = data.encode('latin1') + f.write(data) + if myfile: + f.close() + import os + if os.name=='mac': + from reportlab.lib.utils import markfilename + markfilename(filename) # do platform specific file junk + if getattr(canvas,'_verbosity',None): print('saved %s' % (filename,)) + + def GetPDFData(self, canvas): + # realize delayed fonts + for fnt in self.delayedFonts: + fnt.addObjects(self) + # add info stuff to signature + self.info.invariant = self.invariant + self.info.digest(self.signature) + ### later: maybe add more info to sig? + # prepare outline + self.Reference(self.Catalog) + self.Reference(self.info) + self.Outlines.prepare(self, canvas) + if self.Outlines.ready<0: + self.Catalog.Outlines = None + return self.format() + + def inPage(self): + """specify the current object as a page (enables reference binding and other page features)""" + if self.inObject is not None: + if self.inObject=="page": return + raise ValueError("can't go in page already in object %s" % self.inObject) + self.inObject = "page" + + def inForm(self): + """specify that we are in a form xobject (disable page features, etc)""" + # don't need this check anymore since going in a form pushes old context at canvas level. + #if self.inObject not in ["form", None]: + # raise ValueError("can't go in form already in object %s" % self.inObject) + self.inObject = "form" + # don't need to do anything else, I think... + + def getInternalFontName(self, psfontname): + fm = self.fontMapping + if psfontname in fm: + return fm[psfontname] + else: + try: + # does pdfmetrics know about it? if so, add + fontObj = pdfmetrics.getFont(psfontname) + if fontObj._dynamicFont: + raise PDFError("getInternalFontName(%s) called for a dynamic font" % repr(psfontname)) + fontObj.addObjects(self) + return fm[psfontname] + except KeyError: + raise PDFError("Font %s not known!" % repr(psfontname)) + + def thisPageName(self): + return "Page"+repr(self.pageCounter) + + def thisPageRef(self): + return PDFObjectReference(self.thisPageName()) + + def addPage(self, page): + name = self.thisPageName() + self.Reference(page, name) + self.Pages.addPage(page) + self.pageCounter += 1 + self.inObject = None + + def addForm(self, name, form): + """add a Form XObject.""" + # XXX should check that name is a legal PDF name + if self.inObject != "form": + self.inForm() + self.Reference(form, xObjectName(name)) + self.inObject = None + + def annotationName(self, externalname): + return "Annot.%s"%externalname + + def addAnnotation(self, name, annotation): + self.Reference(annotation, self.annotationName(name)) + + def refAnnotation(self, name): + internalname = self.annotationName(name) + return PDFObjectReference(internalname) + + def addShading(self, shading): + name = "Sh%d" % self.shadingCounter + self.Reference(shading, name) + self.shadingCounter += 1 + return name + + def addColor(self,cmyk): + sname = cmyk.spotName + if not sname: + if cmyk.cyan==0 and cmyk.magenta==0 and cmyk.yellow==0: + sname = 'BLACK' + elif cmyk.black==0 and cmyk.magenta==0 and cmyk.yellow==0: + sname = 'CYAN' + elif cmyk.cyan==0 and cmyk.black==0 and cmyk.yellow==0: + sname = 'MAGENTA' + elif cmyk.cyan==0 and cmyk.magenta==0 and cmyk.black==0: + sname = 'YELLOW' + if not sname: + raise ValueError("CMYK colour %r used without a spotName" % cmyk) + else: + cmyk = cmyk.clone(spotName = sname) + name = PDFName(sname)[1:] + if name not in self.idToObject: + sep = PDFSeparationCMYKColor(cmyk).value() #PDFArray([/Separation /name /DeviceCMYK tint_tf]) + self.Reference(sep,name) + return name,sname + + def setTitle(self, title): + "embeds in PDF file" + if title is None: + self.info.title = '(anonymous)' + else: + self.info.title = title + + def setAuthor(self, author): + "embedded in PDF file" + #allow resetting to clear it + if author is None: + self.info.author = '(anonymous)' + else: + self.info.author = author + + def setSubject(self, subject): + "embeds in PDF file" + + #allow resetting to clear it + if subject is None: + self.info.subject = '(unspecified)' + else: + self.info.subject = subject + + def setCreator(self, creator): + "embeds in PDF file" + if creator is None: #allow resetting to clear it + self.info.creator = '(unspecified)' + else: + self.info.creator = creator + + def setProducer(self, producer): + "embeds in PDF file" + if producer is None: + self.info.producer = _default_producer + else: + self.info.producer = producer + + def setKeywords(self, keywords): + "embeds a string containing keywords in PDF file" + + #allow resetting to clear it but ensure it's a string + if keywords is None: + self.info.keywords = '' + else: + self.info.keywords = keywords + + def setDateFormatter(self, dateFormatter): + self.info._dateFormatter = dateFormatter + + def getAvailableFonts(self): + fontnames = list(self.fontMapping.keys()) + # the standard 14 are also always available! (even if not initialized yet) + from reportlab.pdfbase import _fontdata + for name in _fontdata.standardFonts: + if name not in fontnames: + fontnames.append(name) + fontnames.sort() + return fontnames + + def format(self): + # register the Catalog/INfo and then format the objects one by one until exhausted + # (possible infinite loop if there is a bug that continually makes new objects/refs...) + # Prepare encryption + self.encrypt.prepare(self) + cat = self.Catalog + info = self.info + self.Reference(cat) + self.Reference(info) + # register the encryption dictionary if present + encryptref = None + encryptinfo = self.encrypt.info() + if encryptinfo: + encryptref = self.Reference(encryptinfo) + # make std fonts (this could be made optional + counter = 0 # start at first object (object 1 after preincrement) + ids = [] # the collection of object ids in object number order + numbertoid = self.numberToId + idToNV = self.idToObjectNumberAndVersion + idToOb = self.idToObject + idToOf = self.idToOffset + ### note that new entries may be "appended" DURING FORMATTING + # __accum__ allows objects to know where they are in the file etc etc + self.__accum__ = File = PDFFile(self._pdfVersion) # output collector + while True: + counter += 1 # do next object... + if counter not in numbertoid: break + oid = numbertoid[counter] + #printidToOb + obj = idToOb[oid] + IO = PDFIndirectObject(oid, obj) + # register object number and version + IOf = IO.format(self) + # add a comment to the PDF output + if not rl_config.invariant and rl_config.pdfComments: + try: + classname = obj.__class__.__name__ + except: + classname = ascii(obj) + File.add("%% %s: class %s \n" % (ascii(oid), classname[:50])) + offset = File.add(IOf) + idToOf[oid] = offset + ids.append(oid) + del self.__accum__ + # sanity checks (must happen AFTER formatting) + lno = len(numbertoid) + if counter-1!=lno: + raise ValueError("counter %s doesn't match number to id dictionary %s" %(counter, lno)) + # now add the xref + xref = PDFCrossReferenceTable() + xref.addsection(0, ids) + xreff = xref.format(self) + xrefoffset = File.add(xreff) + # now add the trailer + trailer = PDFTrailer( + startxref = xrefoffset, + Size = lno+1, + Root = self.Reference(cat), + Info = self.Reference(info), + Encrypt = encryptref, + ID = self.ID(), + ) + trailerf = trailer.format(self) + File.add(trailerf) + for ds in getattr(self,'_digiSigs',[]): + ds.sign(File) + # return string format for pdf file + return File.format(self) + + def hasForm(self, name): + """test for existence of named form""" + internalname = xObjectName(name) + return internalname in self.idToObject + + def getFormBBox(self, name, boxType="MediaBox"): + """get the declared bounding box of the form as a list. + If you specify a different PDF box definition (e.g. the + ArtBox) and it has one, that's what you'll get.""" + internalname = xObjectName(name) + if internalname in self.idToObject: + theform = self.idToObject[internalname] + if hasattr(theform,'_extra_pageCatcher_info'): + return theform._extra_pageCatcher_info[boxType] + if isinstance(theform, PDFFormXObject): + # internally defined form + return theform.BBoxList() + elif isinstance(theform, PDFStream): + # externally defined form + return list(theform.dictionary.dict[boxType].sequence) + else: + raise ValueError("I don't understand the form instance %s" % repr(name)) + + def getXObjectName(self, name): + """Lets canvas find out what form is called internally. + Never mind whether it is defined yet or not.""" + return xObjectName(name) + + def xobjDict(self, formnames): + """construct an xobject dict (for inclusion in a resource dict, usually) + from a list of form names (images not yet supported)""" + D = {} + for name in formnames: + internalname = xObjectName(name) + reference = PDFObjectReference(internalname) + D[internalname] = reference + #print "xobjDict D", D + return PDFDictionary(D) + + def Reference(self, obj, name=None): + ### note references may "grow" during the final formatting pass: don't use d.keys()! + # don't make references to other references, or non instances, unless they are named! + iob = isinstance(obj,PDFObject) + idToObject = self.idToObject + if name is None and (not iob or obj.__class__ is PDFObjectReference): + return obj + if hasattr(obj, __InternalName__): + # already registered + intname = obj.__InternalName__ + if name is not None and name!=intname: + raise ValueError("attempt to reregister object %s with new name %s" % ( + repr(intname), repr(name))) + if intname not in idToObject: + raise ValueError("object of type %s named as %s, but not registered" % (type(obj),ascii(intname))) + return PDFObjectReference(intname) + # otherwise register the new object + objectcounter = self.objectcounter = self.objectcounter+1 + if name is None: + name = "R"+repr(objectcounter) + if name in idToObject: + other = idToObject[name] + if other!=obj: + raise ValueError("redefining named object: "+repr(name)) + return PDFObjectReference(name) + if iob: + obj.__InternalName__ = name + #print "name", name, "counter", objectcounter + self.idToObjectNumberAndVersion[name] = (objectcounter, 0) + self.numberToId[objectcounter] = name + idToObject[name] = obj + return PDFObjectReference(name) + +### chapter 4 Objects +PDFtrue = "true" +PDFfalse = "false" +PDFnull = "null" + +class PDFText(PDFObject): + def __init__(self, t, enc='utf-8'): + self.t = t + self.enc = enc + def format(self, document): + t = self.t + if isUnicode(t): + t = t.encode(self.enc) + result = binascii.hexlify(document.encrypt.encode(t)) + return b"<" + result + b">" + def __str__(self): + dummydoc = DummyDoc() + return self.format(dummydoc) + +def PDFnumber(n): + return n + +import re +_re_cleanparens=re.compile('[^()]') +del re +def _isbalanced(s): + '''test whether a string is balanced in parens''' + s = _re_cleanparens.sub('',s) + n = 0 + for c in s: + if c=='(': n+=1 + else: + n -= 1 + if n<0: return 0 + return not n and 1 or 0 + +def _checkPdfdoc(utext): + '''return true if no Pdfdoc encoding errors''' + try: + utext.encode('pdfdoc') + return 1 + except UnicodeEncodeError as e: + return 0 + +class PDFString(PDFObject): + unicodeEncValid = False + def __init__(self, s, escape=1, enc='auto'): + '''s can be unicode/utf8 or a PDFString + if escape is true then the output will be passed through escape + if enc is raw then bytes will be left alone + if enc is auto we'll try and automatically adapt to utf_16_be/utf_16_le if the + effective string is not entirely in pdfdoc + if self.unicodeEncValid unicode will use the specifed encoding + ''' + if isinstance(s,PDFString): + self.s = s.s + self.escape = s.escape + self.enc = s.enc + else: + self.s = s + self.escape = escape + self.enc = enc + def format(self, document): + s = self.s + enc = getattr(self,'enc','auto') + if isBytes(s): + if enc == 'auto': + try: + if s.startswith(codecs.BOM_UTF16_BE): + u = s.decode('utf_16_be') + elif s.startswith(codecs.BOM_UTF16_LE): + u = s.decode('utf_16_le') + else: + u = s.decode('utf8') + if _checkPdfdoc(u): + s = u.encode('pdfdoc') + else: + s = codecs.BOM_UTF16_BE+u.encode('utf_16_be') + except: + try: + s.decode('pdfdoc') + except: + stderr.write('Error in %s' % (repr(s),)) + raise + elif isUnicode(s): + if enc == 'auto': + if _checkPdfdoc(s): + s = s.encode('pdfdoc') + else: + s = codecs.BOM_UTF16_BE+s.encode('utf_16_be') + elif self.unicodeEncValid: + s = s.encode(self.enc) + else: + s = codecs.BOM_UTF16_BE+s.encode('utf_16_be') + else: + raise ValueError('PDFString argument must be str/unicode not %s' % type(s)) + + escape = getattr(self,'escape',1) + if not isinstance(document.encrypt,NoEncryption): + s = document.encrypt.encode(s) + escape = 1 + if escape: + try: + es = "(%s)" % escapePDF(s) + except: + raise ValueError("cannot escape %s %s" % (s, repr(s))) + if escape&2: + es = es.replace('\\012','\n') + if escape&4 and _isbalanced(es): + es = es.replace('\\(','(').replace('\\)',')') + return pdfdocEnc(es) + else: + return b'(' + s + b')' + + def __str__(self): + return "(%s)" % escapePDF(self.s) + +def PDFName(data,lo=chr(0x21),hi=chr(0x7e)): + # might need to change this to class for encryption + # NOTE: RESULT MUST ALWAYS SUPPORT MEANINGFUL COMPARISONS (EQUALITY) AND HASH + # first convert the name + L = list(data) + for i,c in enumerate(L): + if chi or c in "%()<>{}[]#": + L[i] = "#"+hex(ord(c))[2:] # forget the 0x thing... + return "/"+(''.join(L)) + +class PDFDictionary(PDFObject): + multiline = True + def __init__(self, dict=None): + """dict should be namestring to value eg "a": 122 NOT pdfname to value NOT "/a":122""" + if dict is None: + self.dict = {} + else: + self.dict = dict.copy() + def __setitem__(self, name, value): + self.dict[name] = value + def __getitem__(self, a): + return self.dict[a] + def __contains__(self,a): + return a in self.dict + def Reference(self, name, document): + self.dict[name] = document.Reference(self.dict[name]) + def format(self, document,IND=b'\n '): + dict = self.dict + try: + keys = list(dict.keys()) + except: + print(ascii(dict)) + raise + if not isinstance(dict,OrderedDict): keys.sort() + L = [(format(PDFName(k),document)+b" "+format(dict[k],document)) for k in keys] + if (self.multiline and rl_config.pdfMultiLine) or self.multiline=='forced': + L = IND.join(L) + else: + # break up every 6 elements anyway + t=L.insert + for i in reversed(range(6, len(L), 6)): + t(i,b'\n ') + L = b" ".join(L) + return b'<<\n'+L+b'\n>>' + + def copy(self): + return PDFDictionary(self.dict) + + def normalize(self): + #normalize the names to use RL standard ie Name not /Name + D = self.dict + K = [k for k in D.keys() if k.startswith('/')] + for k in K: + D[k[1:]] = D.pop(k) + +class checkPDFNames: + def __init__(self,*names): + self.names = list(map(PDFName,names)) + def __call__(self,value): + if not value.startswith('/'): + value=PDFName(value) + if value in self.names: + return value + +def checkPDFBoolean(value): + if value in ('true','false'): return value + +class CheckedPDFDictionary(PDFDictionary): + validate = {} + def __init__(self,dict=None,validate=None): + PDFDictionary.__init__(self,dict) + if validate: self.validate = validate + + def __setitem__(self,name,value): + if name not in self.validate: + raise ValueError('invalid key, %r' % name) + cvalue = self.validate[name](value) + if cvalue is None: + raise ValueError('Bad value %r for key %r' % (value,name)) + PDFDictionary.__setitem__(self,name,cvalue) + +class ViewerPreferencesPDFDictionary(CheckedPDFDictionary): + validate=dict( + HideToolbar=checkPDFBoolean, + HideMenubar=checkPDFBoolean, + HideWindowUI=checkPDFBoolean, + FitWindow=checkPDFBoolean, + CenterWindow=checkPDFBoolean, + DisplayDocTitle=checkPDFBoolean, #contributed by mark Erbaugh + NonFullScreenPageMode=checkPDFNames(*'UseNone UseOutlines UseThumbs UseOC'.split()), + Direction=checkPDFNames(*'L2R R2L'.split()), + ViewArea=checkPDFNames(*'MediaBox CropBox BleedBox TrimBox ArtBox'.split()), + ViewClip=checkPDFNames(*'MediaBox CropBox BleedBox TrimBox ArtBox'.split()), + PrintArea=checkPDFNames(*'MediaBox CropBox BleedBox TrimBox ArtBox'.split()), + PrintClip=checkPDFNames(*'MediaBox CropBox BleedBox TrimBox ArtBox'.split()), + PrintScaling=checkPDFNames(*'None AppDefault'.split()), + Duplex=checkPDFNames(*'Simplex DuplexFlipShortEdge DuplexFlipLongEdge'.split()), + ) + +# stream filters are objects to support round trip and +# possibly in the future also support parameters +class PDFStreamFilterZCompress: + pdfname = "FlateDecode" + def encode(self, text): + if isUnicode(text): + text = text.encode('utf8') + return zlib.compress(text) + def decode(self, encoded): + return zlib.decompress(encoded) + +# need only one of these, unless we implement parameters later +PDFZCompress = PDFStreamFilterZCompress() + +class PDFStreamFilterBase85Encode: + pdfname = "ASCII85Decode" + def encode(self, text): + from reportlab.pdfbase.pdfutils import _wrap + text = asciiBase85Encode(text) + if rl_config.wrapA85: + text = _wrap(text) + return text + def decode(self, text): + return asciiBase85Decode(text) + +# need only one of these too +PDFBase85Encode = PDFStreamFilterBase85Encode() + +class PDFStream(PDFObject): + '''set dictionary elements explicitly stream.dictionary[name]=value''' + ### compression stuff not implemented yet + __RefOnly__ = 1 # must be at top level + def __init__(self, dictionary=None, content=None, filters=None): + if dictionary is None: + dictionary = PDFDictionary() + self.dictionary = dictionary + self.content = content + self.filters = filters + def format(self, document): + dictionary = self.dictionary + # copy it for modification + dictionary = PDFDictionary(dictionary.dict.copy()) + content = self.content + filters = self.filters + if self.content is None: + raise ValueError("stream content not set") + if filters is None: + filters = document.defaultStreamFilters + # only apply filters if they haven't been applied elsewhere + if filters is not None and "Filter" not in dictionary.dict: + # apply filters in reverse order listed + rf = list(filters) + rf.reverse() + fnames = [] + for f in rf: + #print "*****************content:"; print repr(content[:200]) + #print "*****************filter", f.pdfname + content = f.encode(content) + fnames.insert(0, PDFName(f.pdfname)) + #print "*****************finally:"; print content[:200] + #print "****** FILTERS", fnames + #stop + dictionary["Filter"] = PDFArray(fnames) + # "stream encoding is done after all filters have been applied" + content = document.encrypt.encode(content) + fc = format(content, document) + dictionary["Length"] = len(content) + fd = format(dictionary, document) + return fd+b'\nstream\n'+fc+b'endstream\n' + +def teststream(content=None): + #content = "" # test + if content is None: + content = teststreamcontent + content = content.strip() + '\n' + S = PDFStream(content = content, + filters=rl_config.useA85 and [PDFBase85Encode,PDFZCompress] or [PDFZCompress]) + # nothing else needed... + S.__Comment__ = "test stream" + return S + +teststreamcontent = """ +1 0 0 1 0 0 cm BT /F9 12 Tf 14.4 TL ET +1.00 0.00 1.00 rg +n 72.00 72.00 432.00 648.00 re B* +""" +class PDFArray(PDFObject): + multiline = True + def __init__(self, sequence): + self.sequence = list(sequence) + def References(self, document): + """make all objects in sequence references""" + self.sequence = list(map(document.Reference, self.sequence)) + def format(self, document, IND=b'\n '): + L = [format(e, document) for e in self.sequence] + if (self.multiline and rl_config.pdfMultiLine) or self.multiline=='forced': + L = IND.join(L) + else: + n=len(L) + if n>10: + # break up every 10 elements anyway + t=L.insert + for i in reversed(range(10, n, 10)): + t(i,b'\n ') + L = b' '.join(L) + else: + L = b' '.join(L) + return b'[ ' + L + b' ]' + +class PDFArrayCompact(PDFArray): + multiline=False + +class PDFIndirectObject(PDFObject): + __RefOnly__ = 1 + def __init__(self, name, content): + self.name = name + self.content = content + def format(self, document): + name = self.name + n, v = document.idToObjectNumberAndVersion[name] + # set encryption parameters + document.encrypt.register(n, v) + fcontent = format(self.content, document, toplevel=1) # yes this is at top level + return (pdfdocEnc("%s %s obj\n"%(n,v)) + +fcontent+ (b'' if fcontent.endswith(b'\n') else b'\n') + +b'endobj\n') + +class PDFObjectReference(PDFObject): + def __init__(self, name): + self.name = name + def format(self, document): + try: + return pdfdocEnc("%s %s R" % document.idToObjectNumberAndVersion[self.name]) + except: + raise KeyError("forward reference to %s not resolved upon final formatting" % repr(self.name)) + +class PDFFile(PDFObject): + ### just accumulates strings: keeps track of current offset + def __init__(self,pdfVersion=PDF_VERSION_DEFAULT): + self.strings = [] + self.write = self.strings.append + self.offset = 0 + ### chapter 5 + # Following Ken Lunde's advice and the PDF spec, this includes + # some high-order bytes. I chose the characters for Tokyo + # in Shift-JIS encoding, as these cannot be mistaken for + # any other encoding, and we'll be able to tell if something + # has run our PDF files through a dodgy Unicode conversion. + self.add((pdfdocEnc("%%PDF-%s.%s" % pdfVersion) + + b'\n%\223\214\213\236 ReportLab Generated PDF document (opensource)\n' + )) + + def closeOrReset(self): + pass + + def add(self, s): + """should be constructed as late as possible, return position where placed""" + s = pdfdocEnc(s) + result = self.offset + self.offset = result+len(s) + self.write(s) + return result + + def format(self, document): + return b''.join(self.strings) + +class PDFCrossReferenceSubsection(PDFObject): + def __init__(self, firstentrynumber, idsequence): + self.firstentrynumber = firstentrynumber + self.idsequence = idsequence + def format(self, document): + """id sequence should represent contiguous object nums else error. free numbers not supported (yet)""" + firstentrynumber = self.firstentrynumber + idsequence = self.idsequence + entries = list(idsequence) + nentries = len(idsequence) + # special case: object number 0 is always free + taken = {} + if firstentrynumber==0: + taken[0] = "standard free entry" + nentries = nentries+1 + entries.insert(0, "0000000000 65535 f ") + idToNV = document.idToObjectNumberAndVersion + idToOffset = document.idToOffset + lastentrynumber = firstentrynumber+nentries-1 + for id in idsequence: + (num, version) = idToNV[id] + if num in taken: + raise ValueError("object number collision %s %s %s" % (num, repr(id), repr(taken[id]))) + if num>lastentrynumber or num +class DuplicatePageLabelPage(Exception): + pass +class PDFPageLabels(PDFCatalog): + __comment__ = None + __RefOnly__ = 0 + __Defaults__ = {} + __NoDefault__ = ["Nums"] + __Refs__ = [] + + def __init__(self): + self.labels = [] + + def addPageLabel(self, page, label): + """ Adds a new PDFPageLabel to this catalog. + The 'page' argument, an integer, is the page number in the PDF document + with which the 'label' should be associated. Page numbering in the PDF + starts at zero! Thus, to change the label on the first page, '0' should be + provided as an argument, and to change the 6th page, '5' should be provided + as the argument. + + The 'label' argument should be a PDFPageLabel instance, which describes the + format of the labels starting on page 'page' in the PDF and continuing + until the next encounter of a PDFPageLabel. + + The order in which labels are added is not important. + """ + self.labels.append((page, label)) + + def format(self, document): + try: + self.labels.sort() + except DuplicatePageLabelPage: + tmp = sorted([x[0] for x in self.labels]) + annotateException('\n\n!!!!! Duplicate PageLabel seen for pages %r' % list(set([x for x in tmp if tmp.count(x)>1]))) + labels = [] + for page, label in self.labels: + labels.append(page) + labels.append(label) + + self.Nums = PDFArray(labels) #PDFArray makes a copy with list() + return PDFCatalog.format(self, document) + +class PDFPageLabel(PDFCatalog): + __Comment__ = None + __RefOnly__ = 0 + __Defaults__ = {} + __NoDefault__ = "Type S P St".split() + __convertible__ = 'ARABIC ROMAN_UPPER ROMAN_LOWER LETTERS_UPPER LETTERS_LOWER' + + ARABIC = 'D' + ROMAN_UPPER = 'R' + ROMAN_LOWER = 'r' + LETTERS_UPPER = 'A' + LETTERS_LOWER = 'a' + + def __init__(self, style=None, start=None, prefix=None): + """ + A PDFPageLabel changes the style of page numbering as displayed in a PDF + viewer. PDF page labels have nothing to do with 'physical' page numbers + printed on a canvas, but instead influence the 'logical' page numbers + displayed by PDF viewers. However, when using roman numerals (i, ii, + iii...) or page prefixes for appendecies (A.1, A.2...) on the physical + pages PDF page labels are necessary to change the logical page numbers + displayed by the PDF viewer to match up with the physical numbers. A + PDFPageLabel changes the properties of numbering at the page on which it + appears (see the class 'PDFPageLabels' for specifying where a PDFPageLabel + is associated) and all subsequent pages, until a new PDFPageLabel is + encountered. + + The arguments to this initialiser determine the properties of all + subsequent page labels. 'style' determines the numberings style, arabic, + roman, letters; 'start' specifies the starting number; and 'prefix' any + prefix to be applied to the page numbers. All these arguments can be left + out or set to None. + + * style: + + - None: No numbering, can be used to display the prefix only. + - PDFPageLabel.ARABIC: Use arabic numbers: 1, 2, 3, 4... + - PDFPageLabel.ROMAN_UPPER: Use upper case roman numerals: I, II, III... + - PDFPageLabel.ROMAN_LOWER: Use lower case roman numerals: i, ii, iii... + - PDFPageLabel.LETTERS_UPPER: Use upper case letters: A, B, C, D... + - PDFPageLabel.LETTERS_LOWER: Use lower case letters: a, b, c, d... + + * start: + + - An integer specifying the starting number for this PDFPageLabel. This + can be used when numbering style changes to reset the page number back + to one, ie from roman to arabic, or from arabic to appendecies. Can be + any positive integer or None. I'm not sure what the effect of + specifying None is, probably that page numbering continues with the + current sequence, I'd have to check the spec to clarify though. + + * prefix: + + - A string which is prefixed to the page numbers. Can be used to display + appendecies in the format: A.1, A.2, ..., B.1, B.2, ... where a + PDFPageLabel is used to set the properties for the first page of each + appendix to restart the page numbering at one and set the prefix to the + appropriate letter for current appendix. The prefix can also be used to + display text only, if the 'style' is set to None. This can be used to + display strings such as 'Front', 'Back', or 'Cover' for the covers on + books. + + """ + if style: + if style.upper() in self.__convertible__: style = getattr(self,style.upper()) + self.S = PDFName(style) + if start: self.St = PDFnumber(start) + if prefix: self.P = PDFString(prefix) + + def __lt__(self,oth): + if rl_config.errorOnDuplicatePageLabelPage: + raise DuplicatePageLabelPage() + return False +#ends code contributed by Christian Jacobs + +def testpage(document): + P = PDFPage() + P.Contents = teststream() + pages = document.Pages + P.Parent = document.Reference(pages) + P.MediaBox = PDFArray([0, 0, 595, 841]) + resources = PDFResourceDictionary() + resources.allProcs() # enable all procsets + resources.basicFonts() + P.Resources = resources + pages.addPage(P) + +#### DUMMY OUTLINES IMPLEMENTATION FOR testing +DUMMYOUTLINE = """ +<< + /Count + 0 + /Type + /Outlines +>>""" + +class PDFOutlines0(PDFObject): + __Comment__ = "TEST OUTLINE!" + text = DUMMYOUTLINE.replace("\n", '\n') + __RefOnly__ = 1 + def format(self, document): + return pdfdocEnc(self.text) + +class OutlineEntryObject(PDFObject): + "an entry in an outline" + Title = Dest = Parent = Prev = Next = First = Last = Count = None + def format(self, document): + D = {} + D["Title"] = PDFString(self.Title) + D["Parent"] = self.Parent + D["Dest"] = self.Dest + for n in ("Prev", "Next", "First", "Last", "Count"): + v = getattr(self, n) + if v is not None: + D[n] = v + PD = PDFDictionary(D) + return PD.format(document) + +class PDFOutlines(PDFObject): + """ + takes a recursive list of outline destinations like:: + + out = PDFOutline1() + out.setNames(canvas, # requires canvas for name resolution + "chapter1dest", + ("chapter2dest", + ["chapter2section1dest", + "chapter2section2dest", + "chapter2conclusiondest"] + ), # end of chapter2 description + "chapter3dest", + ("chapter4dest", ["c4s1", "c4s2"]) + ) + + Higher layers may build this structure incrementally. KISS at base level. + """ + # first attempt, many possible features missing. + #no init for now + mydestinations = ready = None + counter = 0 + currentlevel = -1 # ie, no levels yet + + def __init__(self): + self.destinationnamestotitles = {} + self.destinationstotitles = {} + self.levelstack = [] + self.buildtree = [] + self.closedict = {} # dictionary of "closed" destinations in the outline + + def addOutlineEntry(self, destinationname, level=0, title=None, closed=None): + """destinationname of None means "close the tree" """ + if destinationname is None and level!=0: + raise ValueError("close tree must have level of 0") + if not isinstance(level,int): raise ValueError("level must be integer, got %s" % type(level)) + if level<0: raise ValueError("negative levels not allowed") + if title is None: title = destinationname + currentlevel = self.currentlevel + stack = self.levelstack + tree = self.buildtree + # adjust currentlevel and stack to match level + if level>currentlevel: + if level>currentlevel+1: + raise ValueError("can't jump from outline level %s to level %s, need intermediates (destinationname=%r, title=%r)" %(currentlevel, level, destinationname, title)) + level = currentlevel = currentlevel+1 + stack.append([]) + while levelref + if isSeq(object): + L = [] + for o in object: + L.append(self.translateNames(canvas, o)) + if isinstance(object,tuple): + return tuple(L) + return L + # bug contributed by Benjamin Dumke + raise TypeError("in outline, destination name must be string: got a %s"%type(object)) + + def prepare(self, document, canvas): + """prepare all data structures required for save operation (create related objects)""" + if self.mydestinations is None: + if self.levelstack: + self.addOutlineEntry(None) # close the tree + destnames = self.levelstack[0] + #from pprint import pprint; pprint(destnames); stop + self.mydestinations = self.translateNames(canvas, destnames) + else: + self.first = self.last = None + self.count = 0 + self.ready = -1 + return + #self.first = document.objectReference("Outline.First") + #self.last = document.objectReference("Outline.Last") + # XXXX this needs to be generalized for closed entries! + self.count = count(self.mydestinations, self.closedict) + (self.first, self.last) = self.maketree(document, self.mydestinations, toplevel=1) + self.ready = 1 + + def maketree(self, document, destinationtree, Parent=None, toplevel=0): + if toplevel: + levelname = "Outline" + Parent = document.Reference(document.Outlines) + else: + self.count += 1 + levelname = "Outline.%s" % self.count + if Parent is None: + raise ValueError("non-top level outline elt parent must be specified") + if not isSeq(destinationtree): + raise ValueError("destinationtree must be list or tuple, got %s") + nelts = len(destinationtree) + lastindex = nelts-1 + lastelt = firstref = lastref = None + destinationnamestotitles = self.destinationnamestotitles + closedict = self.closedict + for index in range(nelts): + eltobj = OutlineEntryObject() + eltobj.Parent = Parent + eltname = "%s.%s" % (levelname, index) + eltref = document.Reference(eltobj, eltname) + #document.add(eltname, eltobj) + if lastelt is not None: + lastelt.Next = eltref + eltobj.Prev = lastref + if firstref is None: + firstref = eltref + lastref = eltref + lastelt = eltobj # advance eltobj + lastref = eltref + elt = destinationtree[index] + if isinstance(elt,dict): + # simple leaf {name: dest} + leafdict = elt + elif isinstance(elt,tuple): + # leaf with subsections: ({name: ref}, subsections) XXXX should clean up (see count(...)) + try: + (leafdict, subsections) = elt + except: + raise ValueError("destination tree elt tuple should have two elts, got %s" % len(elt)) + eltobj.Count = count(subsections, closedict) + (eltobj.First, eltobj.Last) = self.maketree(document, subsections, eltref) + else: + raise ValueError("destination tree elt should be dict or tuple, got %s" % type(elt)) + try: + [(Title, Dest)] = list(leafdict.items()) + except: + raise ValueError("bad outline leaf dictionary, should have one entry "+bytestr(elt)) + eltobj.Title = destinationnamestotitles[Title] + eltobj.Dest = Dest + if isinstance(elt,tuple) and Dest in closedict: + # closed subsection, count should be negative + eltobj.Count = -eltobj.Count + return (firstref, lastref) + +def count(tree, closedict=None): + """utility for outline: recursively count leaves in a tuple/list tree""" + if isinstance(tree,tuple): + # leaf with subsections XXXX should clean up this structural usage + (leafdict, subsections) = tree + [(Title, Dest)] = list(leafdict.items()) + if closedict and Dest in closedict: + return 1 # closed tree element + if isSeq(tree): + #return reduce(add, map(count, tree)) + counts = [] + for e in tree: + counts.append(count(e, closedict)) + return sum(counts) #used to be: return reduce(add, counts) + return 1 + +_default_producer = "ReportLab PDF Library - (opensource)" +class PDFInfo(PDFObject): + """PDF documents can have basic information embedded, viewable from + File | Document Info in Acrobat Reader. If this is wrong, you get + Postscript errors while printing, even though it does not print.""" + producer = _default_producer + creator = "anonymous" + title = "untitled" + author = "anonymous" + subject = "unspecified" + keywords = "" + _dateFormatter = None + + def __init__(self): + self.trapped = 'False' #could be 'True' or 'Unknown' + + def digest(self, md5object): + # add self information to signature + for x in (self.title, self.author, self.subject, self.keywords): + md5object.update(bytestr(x)) + + def format(self, document): + D = {} + D["Title"] = PDFString(self.title) + D["Author"] = PDFString(self.author) + D['ModDate'] = D["CreationDate"] = PDFDate(ts=document._timeStamp,dateFormatter=self._dateFormatter) + D["Producer"] = PDFString(self.producer) + D["Creator"] = PDFString(self.creator) + D["Subject"] = PDFString(self.subject) + D["Keywords"] = PDFString(self.keywords) + D["Trapped"] = PDFName(self.trapped) + + PD = PDFDictionary(D) + return PD.format(document) + + def copy(self): + "shallow copy - useful in pagecatchering" + thing = self.__klass__() + for k, v in self.__dict__.items(): + setattr(thing, k, v) + return thing +# skipping thumbnails, etc + +class Annotation(PDFObject): + """superclass for all annotations.""" + defaults = [("Type", PDFName("Annot"),)] + required = ("Type", "Rect", "Contents", "Subtype") + permitted = required+( + "Border", "C", "T", "M", "F", "H", "BS", "AA", "AS", "Popup", "P", "AP") + def cvtdict(self, d, escape=1): + """transform dict args from python form to pdf string rep as needed""" + Rect = d["Rect"] + if not isStr(Rect): + d["Rect"] = PDFArray(Rect) + d["Contents"] = PDFString(d["Contents"],escape) + return d + def AnnotationDict(self, **kw): + if 'escape' in kw: + escape = kw['escape'] + del kw['escape'] + else: + escape = 1 + d = {} + for (name,val) in self.defaults: + d[name] = val + d.update(kw) + for name in self.required: + if name not in d: + raise ValueError(f"keyword argument {name} missing") + d = self.cvtdict(d,escape=escape) + permitted = self.permitted + for name in d.keys(): + if name not in permitted: + raise ValueError("%s bad annotation dictionary name %s" % (self.__class__.__name__,name)) + return PDFDictionary(d) + def Dict(self): + raise ValueError("DictString undefined for virtual superclass Annotation, must overload") + # but usually + #return self.AnnotationDict(self, Rect=(a,b,c,d)) or whatever + def format(self, document): + D = self.Dict() + return D.format(document) + +class FreeTextAnnotation(Annotation): + permitted = Annotation.permitted + ("DA",) + def __init__(self, Rect, Contents, DA, **kw): + self.Rect = Rect + self.Contents = Contents + self.DA = DA + self.otherkw = kw + def Dict(self): + d = {} + d.update(self.otherkw) + d["Rect"] = self.Rect + d["Contents"] = self.Contents + d["DA"] = self.DA + d["Subtype"] = "/FreeText" + return self.AnnotationDict(**d) + +class LinkAnnotation(Annotation): + + permitted = Annotation.permitted + ( + "Dest", "A", "PA") + def __init__(self, Rect, Contents, Destination, Border="[0 0 1]", **kw): + self.Border = Border + self.Rect = Rect + self.Contents = Contents + self.Destination = Destination + self.otherkw = kw + + def dummyDictString(self): # old, testing + return """ + << /Type /Annot /Subtype /Link /Rect [71 717 190 734] /Border [16 16 1] + /Dest [23 0 R /Fit] >> + """ + + def Dict(self): + d = {} + d.update(self.otherkw) + d["Border"] = self.Border + d["Rect"] = self.Rect + d["Contents"] = self.Contents + d["Subtype"] = "/Link" + d["Dest"] = self.Destination + return self.AnnotationDict(**d) + +class HighlightAnnotation(Annotation): + """ + HighlightAnnotation is an annotation that highlights the selected area. + + Rect is the mouseover area that will show the contents. + + QuadPoints is a list of points to highlight, you can have many groups of + four QuadPoints to allow highlighting many lines. + """ + permitted = Annotation.permitted + ("QuadPoints", ) + + def __init__(self, Rect, Contents, QuadPoints, Color=[0.83, 0.89, 0.95], **kw): + self.Rect = Rect + self.Contents = Contents + self.otherkw = kw + self.QuadPoints = QuadPoints + self.Color = Color + + def cvtdict(self, d, escape=1): + """transform dict args from python form to pdf string rep as needed""" + Rect = d["Rect"] + Quad = d["QuadPoints"] + Color = d["C"] + if not isinstance(Rect, str): + d["Rect"] = PDFArray(Rect).format(d, IND=b" ") + if not isinstance(Quad, str): + d["QuadPoints"] = PDFArray(Quad).format(d, IND=b" ") + if not isinstance(Color, str): + d["C"] = PDFArray(Color).format(d, IND=b" ") + d["Contents"] = PDFString(d["Contents"], escape) + return d + + def Dict(self): + d = {} + d.update(self.otherkw) + d["Rect"] = self.Rect + d["Contents"] = self.Contents + d["Subtype"] = "/Highlight" + d["QuadPoints"] = self.QuadPoints + d["C"] = self.Color + return self.AnnotationDict(**d) + +class TextAnnotation(HighlightAnnotation): + permitted = HighlightAnnotation.permitted + ( + "Open", "Name") + def __init__(self, Rect, Contents, **kw): + HighlightAnnotation.__init__(self, + Rect, + Contents, + QuadPoints=kw.pop("QuadPoints",None) or rect_to_quad(Rect), + Color=kw.pop("Color",(0,0,0)), + **kw) + def Dict(self): + d = HighlightAnnotation.Dict(self) + d["Subtype"] = "/Text" + return d + +def rect_to_quad(Rect): + """ + Utility method to convert a Rect to a QuadPoint + """ + return [Rect[0], Rect[1], Rect[2], Rect[1], + Rect[0], Rect[3], Rect[2], Rect[3]] + +# skipping names tree +# skipping actions +# skipping names trees +# skipping to chapter 7 + +class PDFRectangle(PDFObject): + def __init__(self, llx, lly, urx, ury): + self.llx, self.lly, self.ulx, self.ury = llx, lly, urx, ury + def format(self, document): + A = PDFArray([self.llx, self.lly, self.ulx, self.ury]) + return format(A, document) + +class PDFDate(PDFObject): + # gmt offset now suppported properly + def __init__(self, ts=None, dateFormatter=None): + if ts is None: + ts = TimeStamp() + self._init(ts) + self.dateFormatter = dateFormatter + + def _init(self,ts): + self.date = ts.YMDhms + self.dhh = ts.dhh + self.dmm = ts.dmm + + def format(self, doc): + dfmt = self.dateFormatter or ( + lambda yyyy,mm,dd,hh,m,s: + "D:%04d%02d%02d%02d%02d%02d%+03d'%02d'" + % (yyyy,mm,dd,hh,m,s,self.dhh,self.dmm)) + return format(PDFString(dfmt(*self.date)), doc) + +class Destination(PDFObject): + """ + + not a PDFObject! This is a placeholder that can delegates + to a pdf object only after it has been defined by the methods + below. + + EG a Destination can refer to Appendix A before it has been + defined, but only if Appendix A is explicitly noted as a destination + and resolved before the document is generated... + + For example the following sequence causes resolution before doc generation. + d = Destination() + d.fit() # or other format defining method call + d.setPage(p) + (at present setPageRef is called on generation of the page). + """ + representation = format = page = None + def __init__(self,name): + self.name = name + self.fmt = self.page = None + def format(self, document): + f = self.fmt + if f is None: raise ValueError("format not resolved, probably missing URL scheme or undefined destination target for '%s'" % self.name) + p = self.page + if p is None: raise ValueError("Page not bound, probably missing URL scheme or undefined destination target for '%s'" % self.name) + f.page = p + return f.format(document) + def xyz(self, left, top, zoom): # see pdfspec mar 11 99 pp184+ + self.fmt = PDFDestinationXYZ(None, left, top, zoom) + def fit(self): + self.fmt = PDFDestinationFit(None) + def fitb(self): + self.fmt = PDFDestinationFitB(None) + def fith(self, top): + self.fmt = PDFDestinationFitH(None,top) + def fitv(self, left): + self.fmt = PDFDestinationFitV(None, left) + def fitbh(self, top): + self.fmt = PDFDestinationFitBH(None, top) + def fitbv(self, left): + self.fmt = PDFDestinationFitBV(None, left) + def fitr(self, left, bottom, right, top): + self.fmt = PDFDestinationFitR(None, left, bottom, right, top) + def setPage(self, page): + self.page = page + #self.fmt.page = page # may not yet be defined! + +class PDFDestinationXYZ(PDFObject): + typename = "XYZ" + def __init__(self, page, left, top, zoom): + self.page = page + self.top = top + self.zoom = zoom + self.left = left + def format(self, document): + pageref = document.Reference(self.page) + A = PDFArray( [ pageref, PDFName(self.typename), self.left, self.top, self.zoom ] ) + return format(A, document) + +class PDFDestinationFit(PDFObject): + typename = "Fit" + def __init__(self, page): + self.page = page + def format(self, document): + pageref = document.Reference(self.page) + A = PDFArray( [ pageref, PDFName(self.typename) ] ) + return format(A, document) + +class PDFDestinationFitB(PDFDestinationFit): + typename = "FitB" + +class PDFDestinationFitH(PDFObject): + typename = "FitH" + def __init__(self, page, top): + self.page = page; self.top=top + def format(self, document): + pageref = document.Reference(self.page) + A = PDFArray( [ pageref, PDFName(self.typename), self.top ] ) + return format(A, document) + +class PDFDestinationFitBH(PDFDestinationFitH): + typename = "FitBH" + +class PDFDestinationFitV(PDFObject): + typename = "FitV" + def __init__(self, page, left): + self.page = page; self.left=left + def format(self, document): + pageref = document.Reference(self.page) + A = PDFArray( [ pageref, PDFName(self.typename), self.left ] ) + return format(A, document) + +class PDFDestinationFitBV(PDFDestinationFitV): + typename = "FitBV" + +class PDFDestinationFitR(PDFObject): + typename = "FitR" + def __init__(self, page, left, bottom, right, top): + self.page = page; self.left=left; self.bottom=bottom; self.right=right; self.top=top + def format(self, document): + pageref = document.Reference(self.page) + A = PDFArray( [ pageref, PDFName(self.typename), self.left, self.bottom, self.right, self.top] ) + return format(A, document) + +# named destinations need nothing + +# skipping filespecs + +class PDFResourceDictionary(PDFObject): + """each element *could* be reset to a reference if desired""" + def __init__(self,**kwds): + for _ in self.dict_attributes: + setattr(self,_,kwds.pop(_,{})) + # define the basicprocs + self.basicProcs() + if 'ProcSet' in kwds: + self.ProcSet= kwds.pop('ProcSet') + stdprocs = [PDFName(s) for s in "PDF Text ImageB ImageC ImageI".split()] + dict_attributes = ("ColorSpace", "XObject", "ExtGState", "Font", "Pattern", "Properties", "Shading") + + def allProcs(self): + # define all standard procsets + self.ProcSet = self.stdprocs + + def basicProcs(self): + self.ProcSet = self.stdprocs[:2] # just PDF and Text + + def basicFonts(self): + self.Font = PDFObjectReference(BasicFonts) + + def setColorSpace(self,colorsUsed): + for c,s in colorsUsed.items(): + self.ColorSpace[s] = PDFObjectReference(c) + + def setShading(self,shadingUsed): + for c,s in shadingUsed.items(): + self.Shading[s] = PDFObjectReference(c) + + def format(self, document): + D = {} + for dname in self.dict_attributes: + v = getattr(self, dname) + if isinstance(v,dict): + if v: + dv = PDFDictionary(v) + D[dname] = dv + else: + D[dname] = v + v = self.ProcSet + dname = "ProcSet" + if isSeq(v): + if v: + dv = PDFArray(v) + D[dname] = dv + else: + D[dname] = v + DD = PDFDictionary(D) + return format(DD, document) + +############################################################################## +# +# Font objects - the PDFDocument.addFont() method knows which of these +# to construct when given a user-facing Font object +# +############################################################################## +class PDFType1Font(PDFObject): + """no init: set attributes explicitly""" + __RefOnly__ = 1 + # note! /Name appears to be an undocumented attribute.... + name_attributes = "Type Subtype BaseFont Name".split() + Type = "Font" + Subtype = "Type1" + # these attributes are assumed to already be of the right type + local_attributes = "FirstChar LastChar Widths Encoding ToUnicode FontDescriptor".split() + def format(self, document): + D = {} + for name in self.name_attributes: + if hasattr(self, name): + value = getattr(self, name) + D[name] = PDFName(value) + for name in self.local_attributes: + if hasattr(self, name): + value = getattr(self, name) + D[name] = value + #print D + PD = PDFDictionary(D) + return PD.format(document) + +## These attribute listings will be useful in future, even if we +## put them elsewhere + +class PDFTrueTypeFont(PDFType1Font): + Subtype = "TrueType" + #local_attributes = "FirstChar LastChar Widths Encoding ToUnicode FontDescriptor".split() #same + +##class PDFMMType1Font(PDFType1Font): +## Subtype = "MMType1" +## +##class PDFType3Font(PDFType1Font): +## Subtype = "Type3" +## local_attributes = "FirstChar LastChar Widths CharProcs FontBBox FontMatrix Resources Encoding".split() +## +##class PDFType0Font(PDFType1Font): +## Subtype = "Type0" +## local_attributes = "DescendantFonts Encoding".split( +## +##class PDFCIDFontType0(PDFType1Font): +## Subtype = "CIDFontType0" +## local_attributes = "CIDSystemInfo FontDescriptor DW W DW2 W2 Registry Ordering Supplement".split() +## +##class PDFCIDFontType0(PDFType1Font): +## Subtype = "CIDFontType2" +## local_attributes = "BaseFont CIDToGIDMap CIDSystemInfo FontDescriptor DW W DW2 W2".split() +## +##class PDFEncoding(PDFType1Font): +## Type = "Encoding" +## name_attributes = "Type BaseEncoding".split() +## # these attributes are assumed to already be of the right type +## local_attributes = ["Differences"] +## + +# UGLY ALERT - this needs turning into something O-O, it was hacked +# across from the pdfmetrics.Encoding class to avoid circularity + +# skipping CMaps + +class PDFFormXObject(PDFObject): + # like page requires .info set by some higher level (doc) + # XXXX any resource used in a form must be propagated up to the page that (recursively) uses + # the form!! (not implemented yet). + XObjects = Annots = BBox = Matrix = Contents = stream = Resources = None + hasImages = 1 # probably should change + compression = 0 + def __init__(self, lowerx, lowery, upperx, uppery): + #not done + self.lowerx = lowerx; self.lowery=lowery; self.upperx=upperx; self.uppery=uppery + + def setStreamList(self, data): + if isSeq(data): + data = '\n'.join(data) + self.stream = pdfdocEnc(data) + + def BBoxList(self): + "get the declared bounding box for the form as a list" + if self.BBox: + return list(self.BBox.sequence) + else: + return [self.lowerx, self.lowery, self.upperx, self.uppery] + + def format(self, document): + self.BBox = self.BBox or PDFArray([self.lowerx, self.lowery, self.upperx, self.uppery]) + self.Matrix = self.Matrix or PDFArray([1, 0, 0, 1, 0, 0]) + if not self.Annots: + self.Annots = None + else: + #these must be transferred to the page when the form is used + raise ValueError("annotations don't work in PDFFormXObjects yet") + if not self.Contents: + stream = self.stream + if not stream: + self.Contents = teststream() + else: + S = PDFStream() + S.content = stream + # need to add filter stuff (?) + S.__Comment__ = "xobject form stream" + self.Contents = S + if not self.Resources: + resources = PDFResourceDictionary() + # fonts! + resources.basicFonts() + if self.hasImages: + resources.allProcs() + else: + resources.basicProcs() + if self.XObjects: + #print "XObjects", self.XObjects.dict + resources.XObject = self.XObjects + self.Resources=resources + if self.compression: + self.Contents.filters = rl_config.useA85 and [PDFBase85Encode, PDFZCompress] or [PDFZCompress] + sdict = self.Contents.dictionary + sdict["Type"] = PDFName("XObject") + sdict["Subtype"] = PDFName("Form") + sdict["FormType"] = 1 + sdict["BBox"] = self.BBox + sdict["Matrix"] = self.Matrix + sdict["Resources"] = self.Resources + return self.Contents.format(document) + +class PDFPostScriptXObject(PDFObject): + "For embedding PD (e.g. tray commands) in PDF" + def __init__(self, content=None): + self.content = content + + def format(self, document): + S = PDFStream() + S.content = self.content + S.__Comment__ = "xobject postscript stream" + sdict = S.dictionary + sdict["Type"] = PDFName("XObject") + sdict["Subtype"] = PDFName("PS") + return S.format(document) + +_mode2CS={'RGB':'DeviceRGB', 'L':'DeviceGray', 'CMYK':'DeviceCMYK'} +class PDFImageXObject(PDFObject): + # first attempts at a hard-coded one + # in the file, Image XObjects are stream objects. We already + # have a PDFStream object with 3 attributes: dictionary, content + # and filters. So the job of this thing is to construct the + # right PDFStream instance and ask it to format itself. + def __init__(self, name, source=None, mask=None): + self.name = name + self.width = 24 + self.height = 23 + self.bitsPerComponent = 1 + self.colorSpace = 'DeviceGray' + self._filters = rl_config.useA85 and ('ASCII85Decode',) or () + self.streamContent = """ + 003B00 002700 002480 0E4940 114920 14B220 3CB650 + 75FE88 17FF8C 175F14 1C07E2 3803C4 703182 F8EDFC + B2BBC2 BB6F84 31BFC2 18EA3C 0E3E00 07FC00 03F800 + 1E1800 1FF800> + """ + self.mask = mask + + if source is None: + pass # use the canned one. + elif hasattr(source,'jpeg_fh'): + self.loadImageFromSRC(source) #it is already a PIL Image + else: + # it is a filename + import os + ext = os.path.splitext(source)[1].lower() + src = open_for_read(source) + try: + if not(ext in ('.jpg', '.jpeg') and self.loadImageFromJPEG(src)): + if rl_config.useA85: + self.loadImageFromA85(src) + else: + self.loadImageFromRaw(src) + finally: + src.close() + + def loadImageFromA85(self,source): + IMG=[] + imagedata = pdfutils.makeA85Image(source,IMG=IMG,detectJpeg=True) + if not imagedata: + return self.loadImageFromSRC(IMG[0]) + imagedata = [s.strip() for s in imagedata] + words = imagedata[1].split() + self.width, self.height = (int(words[1]),int(words[3])) + self.colorSpace = {'/RGB':'DeviceRGB', '/G':'DeviceGray', '/CMYK':'DeviceCMYK'}[words[7]] + self.bitsPerComponent = 8 + self._filters = 'ASCII85Decode','FlateDecode' #'A85','Fl' + if IMG: self._checkTransparency(IMG[0]) + elif self.mask=='auto': self.mask = None + self.streamContent = ''.join(imagedata[3:-1]) + + def loadImageFromJPEG(self,imageFile): + try: + try: + info = pdfutils.readJPEGInfo(imageFile) + finally: + imageFile.seek(0) #reset file pointer + except: + return False + self.width, self.height = info[0], info[1] + self.bitsPerComponent = 8 + if info[2] == 1: + self.colorSpace = 'DeviceGray' + elif info[2] == 3: + self.colorSpace = 'DeviceRGB' + else: #maybe should generate an error, is this right for CMYK? + self.colorSpace = 'DeviceCMYK' + self._dotrans = 1 + self.streamContent = imageFile.read() + if rl_config.useA85: + self.streamContent = asciiBase85Encode(self.streamContent) + self._filters = 'ASCII85Decode','DCTDecode' #'A85','DCT' + else: + self._filters = 'DCTDecode', #'DCT' + self.mask = None + return True + + def loadImageFromRaw(self,source): + IMG=[] + imagedata = pdfutils.makeRawImage(source,IMG=IMG,detectJpeg=True) + if not imagedata: + return self.loadImageFromSRC(IMG[0]) + words = imagedata[1].split() + self.width = int(words[1]) + self.height = int(words[3]) + self.colorSpace = {'/RGB':'DeviceRGB', '/G':'DeviceGray', '/CMYK':'DeviceCMYK'}[words[7]] + self.bitsPerComponent = 8 + self._filters = 'FlateDecode', #'Fl' + if IMG: self._checkTransparency(IMG[0]) + elif self.mask=='auto': self.mask = None + self.streamContent = b''.join(imagedata[3:-1]) + + def _checkTransparency(self,im): + if self.mask=='auto': + if im._dataA: + self.mask = None + self._smask = PDFImageXObject(_digester(im._dataA.getRGBData()),im._dataA,mask=None) + self._smask._decode = [0,1] + else: + tc = im.getTransparent() + if tc: + self.mask = (tc[0], tc[0], tc[1], tc[1], tc[2], tc[2]) + else: + self.mask = None + elif hasattr(self.mask,'rgb'): + _ = self.mask.rgb() + self.mask = _[0],_[0],_[1],_[1],_[2],_[2] + + def loadImageFromSRC(self, im): + "Extracts the stream, width and height" + fp = im.jpeg_fh() + if fp: + self.loadImageFromJPEG(fp) + else: + self.width, self.height = im.getSize() + raw = im.getRGBData() + #assert len(raw) == self.width*self.height, "Wrong amount of data for image expected %sx%s=%s got %s" % (self.width,self.height,self.width*self.height,len(raw)) + self.streamContent = zlib.compress(raw) + if rl_config.useA85: + self.streamContent = asciiBase85Encode(self.streamContent) + self._filters = 'ASCII85Decode','FlateDecode' #'A85','Fl' + else: + self._filters = 'FlateDecode', #'Fl' + self.colorSpace= _mode2CS[im.mode] + self.bitsPerComponent = 8 + self._checkTransparency(im) + + def format(self, document): + S = PDFStream(content = self.streamContent) + dict = S.dictionary + dict["Type"] = PDFName("XObject") + dict["Subtype"] = PDFName("Image") + dict["Width"] = self.width + dict["Height"] = self.height + dict["BitsPerComponent"] = self.bitsPerComponent + dict["ColorSpace"] = PDFName(self.colorSpace) + if self.colorSpace=='DeviceCMYK' and getattr(self,'_dotrans',0): + dict["Decode"] = PDFArray([1,0,1,0,1,0,1,0]) + elif getattr(self,'_decode',None): + dict["Decode"] = PDFArray(self._decode) + dict["Filter"] = PDFArray(map(PDFName,self._filters)) + dict["Length"] = len(self.streamContent) + if self.mask: dict["Mask"] = PDFArray(self.mask) + if getattr(self,'smask',None): dict["SMask"] = self.smask + return S.format(document) + +class PDFSeparationCMYKColor: + def __init__(self, cmyk): + from reportlab.lib.colors import CMYKColor + if not isinstance(cmyk,CMYKColor): + raise ValueError('%s needs a CMYKColor argument' % self.__class__.__name__) + elif not cmyk.spotName: + raise ValueError('%s needs a CMYKColor argument with a spotName' % self.__class__.__name__) + self.cmyk = cmyk + + def _makeFuncPS(self): + '''create the postscript code for the tint transfer function + effectively this is tint*c, tint*y, ... tint*k''' + R = [].append + for i,v in enumerate(self.cmyk.cmyk()): + v=float(v) + if i==3: + if v==0.0: + R('pop') + R('0.0') + else: + R(str(v)) + R('mul') + else: + if v==0: + R('0.0') + else: + R('dup') + R(str(v)) + R('mul') + R('exch') + return '{%s}' % (' '.join(R.__self__)) + + def value(self): + return PDFArrayCompact(( + PDFName('Separation'), + PDFName(self.cmyk.spotName), + PDFName('DeviceCMYK'), + PDFStream( + dictionary=PDFDictionary(dict( + FunctionType=4, + Domain=PDFArrayCompact((0,1)), + Range=PDFArrayCompact((0,1,0,1,0,1,0,1)) + )), + content=self._makeFuncPS(), + filters=None,#[PDFBase85Encode, PDFZCompress], + ) + )) + +class PDFFunction(PDFObject): + """superclass for all function types.""" + defaults = [] + required = ("FunctionType", "Domain") + permitted = required+("Range",) + def FunctionDict(self, **kw): + d = {} + for (name,val) in self.defaults: + d[name] = val + d.update(kw) + for name in self.required: + if name not in d: + raise ValueError("keyword argument %s missing" % name) + permitted = self.permitted + for name in d.keys(): + if name not in permitted: + raise ValueError("bad annotation dictionary name %s" % name) + return PDFDictionary(d) + + def Dict(self, document): + raise ValueError("Dict undefined for virtual superclass PDFShading, must overload") + # but usually + #return self.FunctionDict(self, ...) + + def format(self, document): + D = self.Dict(document) + return D.format(document) + +class PDFExponentialFunction(PDFFunction): + defaults = PDFFunction.defaults + [("Domain", PDFArrayCompact((0.0, 1.0)))] + required = PDFFunction.required + ("N",) + permitted = PDFFunction.permitted + ("C0", "C1", "N") + def __init__(self, C0, C1, N, **kw): + self.C0 = C0 + self.C1 = C1 + self.N = N + self.otherkw = kw + def Dict(self, document): + d = {} + d.update(self.otherkw) + d["FunctionType"] = 2 + d["C0"] = PDFArrayCompact(self.C0) + d["C1"] = PDFArrayCompact(self.C1) + d["N"] = self.N + return self.FunctionDict(**d) + +class PDFStitchingFunction(PDFFunction): + required = PDFFunction.required + ("Functions", "Bounds", "Encode") + permitted = PDFFunction.permitted + ("Functions", "Bounds", "Encode") + def __init__(self, Functions, Bounds, Encode, **kw): + self.Functions = Functions + self.Bounds = Bounds + self.Encode = Encode + self.otherkw = kw + def Dict(self, document): + d = {} + d.update(self.otherkw) + d["FunctionType"] = 3 + d["Functions"] = PDFArray([document.Reference(x) for x in self.Functions]) + d["Bounds"] = PDFArray(self.Bounds) + d["Encode"] = PDFArray(self.Encode) + return self.FunctionDict(**d) + +class PDFShading(PDFObject): + """superclass for all shading types.""" + required = ("ShadingType", "ColorSpace") + permitted = required+("Background", "BBox", "AntiAlias") + def ShadingDict(self, **kw): + d = {} + d.update(kw) + for name in self.required: + if name not in d: + raise ValueError("keyword argument %s missing" % name) + permitted = self.permitted + for name in d.keys(): + if name not in permitted: + raise ValueError("bad annotation dictionary name %s" % name) + return PDFDictionary(d) + + def Dict(self, document): + raise ValueError("Dict undefined for virtual superclass PDFShading, must overload") + # but usually + #return self.ShadingDict(self, ...) + + def format(self, document): + D = self.Dict(document) + return D.format(document) + +class PDFFunctionShading(PDFShading): + required = PDFShading.required + ("Function",) + permitted = PDFShading.permitted + ("Domain", "Matrix", "Function") + def __init__(self, Function, ColorSpace, **kw): + self.Function = Function + self.ColorSpace = ColorSpace + self.otherkw = kw + def Dict(self, document): + d = {} + d.update(self.otherkw) + d["ShadingType"] = 1 + d["ColorSpace"] = PDFName(self.ColorSpace) + d["Function"] = document.Reference(self.Function) + return self.ShadingDict(**d) + +class PDFAxialShading(PDFShading): + required = PDFShading.required + ("Coords", "Function") + permitted = PDFShading.permitted + ( + "Coords", "Domain", "Function", "Extend") + def __init__(self, x0, y0, x1, y1, Function, ColorSpace, **kw): + self.Coords = (x0, y0, x1, y1) + self.Function = Function + self.ColorSpace = ColorSpace + self.otherkw = kw + def Dict(self, document): + d = {} + d.update(self.otherkw) + d["ShadingType"] = 2 + d["ColorSpace"] = PDFName(self.ColorSpace) + d["Coords"] = PDFArrayCompact(self.Coords) + d["Function"] = document.Reference(self.Function) + return self.ShadingDict(**d) + +class PDFRadialShading(PDFShading): + required = PDFShading.required + ("Coords", "Function") + permitted = PDFShading.permitted + ( + "Coords", "Domain", "Function", "Extend") + def __init__(self, x0, y0, r0, x1, y1, r1, Function, ColorSpace, **kw): + self.Coords = (x0, y0, r0, x1, y1, r1) + self.Function = Function + self.ColorSpace = ColorSpace + self.otherkw = kw + def Dict(self, document): + d = {} + d.update(self.otherkw) + d["ShadingType"] = 3 + d["ColorSpace"] = PDFName(self.ColorSpace) + d["Coords"] = PDFArrayCompact(self.Coords) + d["Function"] = document.Reference(self.Function) + return self.ShadingDict(**d) + +if __name__=="__main__": + print("There is no script interpretation for pdfdoc.") diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/pdfform.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/pdfform.py new file mode 100644 index 0000000000000000000000000000000000000000..57a72227bd13f65a3e6d57a8d1a8e70d88ca9f19 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/pdfform.py @@ -0,0 +1,582 @@ + +"""Support for Acrobat Forms in ReportLab documents + +This module is somewhat experimental at this time. + +Includes basic support for + textfields, + select fields (drop down lists), and + check buttons. + +The public interface consists of functions at the moment. +At some later date these operations may be made into canvas +methods. (comments?) + +The ...Absolute(...) functions position the fields with respect +to the absolute canvas coordinate space -- that is, they do not +respect any coordinate transforms in effect for the canvas. + +The ...Relative(...) functions position the ONLY THE LOWER LEFT +CORNER of the field using the coordinate transform in effect for +the canvas. THIS WILL ONLY WORK CORRECTLY FOR TRANSLATED COORDINATES +-- THE SHAPE, SIZE, FONTSIZE, AND ORIENTATION OF THE FIELD WILL NOT BE EFFECTED +BY SCALING, ROTATION, SKEWING OR OTHER NON-TRANSLATION COORDINATE +TRANSFORMS. + +Please note that all field names (titles) in a given document must be unique. +Textfields and select fields only support the "base 14" canvas fonts +at this time. + +See individual function docstrings below for more information. + +The function test1(...) generates a simple test file. + +THIS CONTRIBUTION WAS COMMISSIONED BY REPORTLAB USERS +WHO WISH TO REMAIN ANONYMOUS. +""" + +### NOTE: MAKE THE STRING FORMATS DYNAMIC IN PATTERNS TO SUPPORT ENCRYPTION XXXX + +from reportlab.pdfbase.pdfdoc import PDFString, PDFStream, PDFDictionary, PDFName, PDFObject +from reportlab.lib.colors import obj_R_G_B + +#==========================public interfaces + +def textFieldAbsolute(canvas, title, x, y, width, height, value="", maxlen=1000000, multiline=0): + """Place a text field on the current page + with name title at ABSOLUTE position (x,y) with + dimensions (width, height), using value as the default value and + maxlen as the maximum permissible length. If multiline is set make + it a multiline field. + """ + theform = getForm(canvas) + return theform.textField(canvas, title, x, y, x+width, y+height, value, maxlen, multiline) + +def textFieldRelative(canvas, title, xR, yR, width, height, value="", maxlen=1000000, multiline=0): + "same as textFieldAbsolute except the x and y are relative to the canvas coordinate transform" + (xA, yA) = canvas.absolutePosition(xR,yR) + return textFieldAbsolute(canvas, title, xA, yA, width, height, value, maxlen, multiline) + +def buttonFieldAbsolute(canvas, title, value, x, y, width=16.7704, height=14.907): + """Place a check button field on the current page + with name title and default value value (one of "Yes" or "Off") + at ABSOLUTE position (x,y). + """ + theform = getForm(canvas) + return theform.buttonField(canvas, title, value, x, y, width=width, height=height) + +def buttonFieldRelative(canvas, title, value, xR, yR, width=16.7704, height=14.907): + "same as buttonFieldAbsolute except the x and y are relative to the canvas coordinate transform" + (xA, yA) = canvas.absolutePosition(xR,yR) + return buttonFieldAbsolute(canvas, title, value, xA, yA, width=width, height=height) + +def selectFieldAbsolute(canvas, title, value, options, x, y, width, height): + """Place a select field (drop down list) on the current page + with name title and + with options listed in the sequence options + default value value (must be one of options) + at ABSOLUTE position (x,y) with dimensions (width, height).""" + theform = getForm(canvas) + theform.selectField(canvas, title, value, options, x, y, x+width, y+height) + +def selectFieldRelative(canvas, title, value, options, xR, yR, width, height): + "same as textFieldAbsolute except the x and y are relative to the canvas coordinate transform" + (xA, yA) = canvas.absolutePosition(xR,yR) + return selectFieldAbsolute(canvas, title, value, options, xA, yA, width, height) + +#==========================end of public interfaces + +from reportlab.pdfbase.pdfpattern import PDFPattern, PDFPatternIf + +def getForm(canvas): + "get form from canvas, create the form if needed" + try: + return canvas.AcroForm + except AttributeError: + theform = canvas.AcroForm = AcroForm() + # install the form in the document + d = canvas._doc + cat = d._catalog + cat.AcroForm = theform + return theform + +class AcroForm(PDFObject): + def __init__(self): + self.fields = [] + def textField(self, canvas, title, xmin, ymin, xmax, ymax, value="", maxlen=1000000, multiline=0): + # determine the page ref + doc = canvas._doc + page = doc.thisPageRef() + # determine text info + R, G, B = obj_R_G_B(canvas._fillColorObj) + #print "rgb", (R,G,B) + font = canvas. _fontname + fontsize = canvas. _fontsize + field = TextField(title, value, xmin, ymin, xmax, ymax, page, maxlen, + font, fontsize, R, G, B, multiline) + self.fields.append(field) + canvas._addAnnotation(field) + def selectField(self, canvas, title, value, options, xmin, ymin, xmax, ymax): + # determine the page ref + doc = canvas._doc + page = doc.thisPageRef() + # determine text info + R, G, B = obj_R_G_B(canvas._fillColorObj) + #print "rgb", (R,G,B) + font = canvas. _fontname + fontsize = canvas. _fontsize + field = SelectField(title, value, options, xmin, ymin, xmax, ymax, page, + font=font, fontsize=fontsize, R=R, G=G, B=B) + self.fields.append(field) + canvas._addAnnotation(field) + def buttonField(self, canvas, title, value, xmin, ymin, width=16.7704, height=14.907): + # determine the page ref + doc = canvas._doc + page = doc.thisPageRef() + field = ButtonField(title, value, xmin, ymin, page, width=width, height=height) + self.fields.append(field) + canvas._addAnnotation(field) + def format(self, document): + from reportlab.pdfbase.pdfdoc import PDFArray + proxy = PDFPattern(FormPattern, + Resources=getattr(self,'resources',None) or FormResources(), + NeedAppearances=getattr(self,'needAppearances','false'), + fields=PDFArray(self.fields), SigFlags=getattr(self,'sigFlags',0)) + return proxy.format(document) + +FormPattern = [ +'<<\r\n', +'/NeedAppearances ',['NeedAppearances'],'\r\n' +'/DA ', PDFString('/Helv 0 Tf 0 g '), '\r\n', +'/DR ',["Resources"],'\r\n', +'/Fields ', ["fields"],'\r\n', +PDFPatternIf('SigFlags',['\r\n/SigFlags ',['SigFlags']]), +'>>' +] + +def FormFontsDictionary(): + from reportlab.pdfbase.pdfdoc import PDFDictionary + fontsdictionary = PDFDictionary() + fontsdictionary.__RefOnly__ = 1 + for fullname, shortname in FORMFONTNAMES.items(): + fontsdictionary[shortname] = FormFont(fullname, shortname) + fontsdictionary["ZaDb"] = PDFPattern(ZaDbPattern) + return fontsdictionary + +def FormResources(): + return PDFPattern(FormResourcesDictionaryPattern, + Encoding=PDFPattern(EncodingPattern,PDFDocEncoding=PDFPattern(PDFDocEncodingPattern)), + Font=FormFontsDictionary()) + +ZaDbPattern = [ +' <<' +' /BaseFont' +' /ZapfDingbats' +' /Name' +' /ZaDb' +' /Subtype' +' /Type1' +' /Type' +' /Font' +'>>'] + + +FormResourcesDictionaryPattern = [ +'<<', +' /Encoding ', +["Encoding"], '\r\n', +' /Font ', +["Font"], '\r\n', +'>>' +] + +FORMFONTNAMES = { + "Helvetica": "Helv", + "Helvetica-Bold": "HeBo", + 'Courier': "Cour", + 'Courier-Bold': "CoBo", + 'Courier-Oblique': "CoOb", + 'Courier-BoldOblique': "CoBO", + 'Helvetica-Oblique': "HeOb", + 'Helvetica-BoldOblique': "HeBO", + 'Times-Roman': "Time", + 'Times-Bold': "TiBo", + 'Times-Italic': "TiIt", + 'Times-BoldItalic': "TiBI", + } + +EncodingPattern = [ +'<<', +' /PDFDocEncoding ', +["PDFDocEncoding"], '\r\n', +'>>', +] + +PDFDocEncodingPattern = [ +'<<' +' /Differences' +' [' +' 24' +' /breve' +' /caron' +' /circumflex' +' /dotaccent' +' /hungarumlaut' +' /ogonek' +' /ring' +' /tilde' +' 39' +' /quotesingle' +' 96' +' /grave' +' 128' +' /bullet' +' /dagger' +' /daggerdbl' +' /ellipsis' +' /emdash' +' /endash' +' /florin' +' /fraction' +' /guilsinglleft' +' /guilsinglright' +' /minus' +' /perthousand' +' /quotedblbase' +' /quotedblleft' +' /quotedblright' +' /quoteleft' +' /quoteright' +' /quotesinglbase' +' /trademark' +' /fi' +' /fl' +' /Lslash' +' /OE' +' /Scaron' +' /Ydieresis' +' /Zcaron' +' /dotlessi' +' /lslash' +' /oe' +' /scaron' +' /zcaron' +' 160' +' /Euro' +' 164' +' /currency' +' 166' +' /brokenbar' +' 168' +' /dieresis' +' /copyright' +' /ordfeminine' +' 172' +' /logicalnot' +' /.notdef' +' /registered' +' /macron' +' /degree' +' /plusminus' +' /twosuperior' +' /threesuperior' +' /acute' +' /mu' +' 183' +' /periodcentered' +' /cedilla' +' /onesuperior' +' /ordmasculine' +' 188' +' /onequarter' +' /onehalf' +' /threequarters' +' 192' +' /Agrave' +' /Aacute' +' /Acircumflex' +' /Atilde' +' /Adieresis' +' /Aring' +' /AE' +' /Ccedilla' +' /Egrave' +' /Eacute' +' /Ecircumflex' +' /Edieresis' +' /Igrave' +' /Iacute' +' /Icircumflex' +' /Idieresis' +' /Eth' +' /Ntilde' +' /Ograve' +' /Oacute' +' /Ocircumflex' +' /Otilde' +' /Odieresis' +' /multiply' +' /Oslash' +' /Ugrave' +' /Uacute' +' /Ucircumflex' +' /Udieresis' +' /Yacute' +' /Thorn' +' /germandbls' +' /agrave' +' /aacute' +' /acircumflex' +' /atilde' +' /adieresis' +' /aring' +' /ae' +' /ccedilla' +' /egrave' +' /eacute' +' /ecircumflex' +' /edieresis' +' /igrave' +' /iacute' +' /icircumflex' +' /idieresis' +' /eth' +' /ntilde' +' /ograve' +' /oacute' +' /ocircumflex' +' /otilde' +' /odieresis' +' /divide' +' /oslash' +' /ugrave' +' /uacute' +' /ucircumflex' +' /udieresis' +' /yacute' +' /thorn' +' /ydieresis' +' ]' +' /Type' +' /Encoding' +'>>'] + +def FormFont(BaseFont, Name): + from reportlab.pdfbase.pdfdoc import PDFName + return PDFPattern(FormFontPattern, BaseFont=PDFName(BaseFont), Name=PDFName(Name), Encoding=PDFPattern(PDFDocEncodingPattern)) + +FormFontPattern = [ +'<<', +' /BaseFont ', +["BaseFont"], '\r\n', +' /Encoding ', +["Encoding"], '\r\n', +' /Name ', +["Name"], '\r\n', +' /Subtype ' +' /Type1 ' +' /Type ' +' /Font ' +'>>' ] + +def resetPdfForm(): + pass +from reportlab.rl_config import register_reset +register_reset(resetPdfForm) +resetPdfForm() + +def TextField(title, value, xmin, ymin, xmax, ymax, page, + maxlen=1000000, font="Helvetica-Bold", fontsize=9, R=0, G=0, B=0.627, multiline=0): + from reportlab.pdfbase.pdfdoc import PDFString, PDFName + Flags = 0 + if multiline: + Flags = Flags | (1<<12) # bit 13 is at position 12 :) + fontname = FORMFONTNAMES[font] + return PDFPattern(TextFieldPattern, + value=PDFString(value), maxlen=maxlen, page=page, + title=PDFString(title), + xmin=xmin, ymin=ymin, xmax=xmax, ymax=ymax, + fontname=PDFName(fontname), fontsize=fontsize, R=R, G=G, B=B, Flags=Flags) + + +TextFieldPattern = [ +'<<' +' /DA' +' (', ["fontname"],' ',["fontsize"],' Tf ',["R"],' ',["G"],' ',["B"],' rg)' +' /DV ', +["value"], '\r\n', +' /F 4 /FT /Tx' +'/MK << /BC [ 0 0 0 ] >>' +' /MaxLen ', +["maxlen"], '\r\n', +' /P ', +["page"], '\r\n', +' /Rect ' +' [', ["xmin"], " ", ["ymin"], " ", ["xmax"], " ", ["ymax"], ' ]' +'/Subtype /Widget' +' /T ', +["title"], '\r\n', +' /Type' +' /Annot' +' /V ', +["value"], '\r\n', +' /Ff ', +["Flags"],'\r\n', +'>>'] + +def SelectField(title, value, options, xmin, ymin, xmax, ymax, page, + font="Helvetica-Bold", fontsize=9, R=0, G=0, B=0.627): + #print "ARGS", (title, value, options, xmin, ymin, xmax, ymax, page, font, fontsize, R, G, B) + from reportlab.pdfbase.pdfdoc import PDFString, PDFName, PDFArray + if value not in options: + raise ValueError("value %s must be one of options %s" % (repr(value), repr(options))) + fontname = FORMFONTNAMES[font] + optionstrings = list(map(PDFString, options)) + optionarray = PDFArray(optionstrings) + return PDFPattern(SelectFieldPattern, + Options=optionarray, + Selected=PDFString(value), Page=page, + Name=PDFString(title), + xmin=xmin, ymin=ymin, xmax=xmax, ymax=ymax, + fontname=PDFName(fontname), fontsize=fontsize, R=R, G=G, B=B) + +SelectFieldPattern = [ +'<< % a select list\r\n' +' /DA ', +' (', ["fontname"],' ',["fontsize"],' Tf ',["R"],' ',["G"],' ',["B"],' rg)\r\n', +#' (/Helv 12 Tf 0 g)\r\n', +' /DV ', +["Selected"],'\r\n', +' /F ', +' 4\r\n', +' /FT ', +' /Ch\r\n', +' /MK ', +' <<', +' /BC', +' [', +' 0', +' 0', +' 0', +' ]', +' /BG', +' [', +' 1', +' 1', +' 1', +' ]', +' >>\r\n', +' /Opt ', +["Options"],'\r\n', +' /P ', +["Page"],'\r\n', +'/Rect', +' [',["xmin"], " ", ["ymin"], " ", ["xmax"], " ", ["ymax"], +' ] \r\n', +'/Subtype', +' /Widget\r\n', +' /T ', +["Name"],'\r\n', +' /Type ', +' /Annot', +' /V ', +["Selected"],'\r\n', +'>>'] + +def ButtonField(title, value, xmin, ymin, page, width=16.7704, height=14.907): + if value not in ("Yes", "Off"): + raise ValueError("button value must be 'Yes' or 'Off': "+repr(value)) + fontSize = (11.3086/14.907)*height + dx = (3.6017/16.7704)*width + dy = (3.3881/14.907)*height + return PDFPattern(ButtonFieldPattern, + Name=PDFString(title), + xmin=xmin, ymin=ymin, xmax=xmin+width, ymax=ymin+width, + Hide=PDFPattern(['<< /S /Hide >>']), + APDOff=ButtonStream('0.749 g 0 0 %(width)s %(height)s re f\r\n' % vars(), width=width, height=height), + APDYes=ButtonStream('0.749 g 0 0 %(width)s %(height)s re f q 1 1 %(width)s %(height)s re W n BT /ZaDb %(fontSize)s Tf 0 g 1 0 0 1 %(dx)s %(dy)s Tm (4) Tj ET\r\n' % vars(), + width=width, height=height), + APNYes=ButtonStream('q 1 1 %(width)s %(height)s re W n BT /ZaDb %(fontSize)s Tf 0 g 1 0 0 1 %(dx)s %(dy)s Tm (4) Tj ET Q\r\n' % vars(), + width=width, height=height), + Value=PDFName(value), + Page=page) + +ButtonFieldPattern = ['<< ', +'/AA', +' <<', +' /D ', +["Hide"],'\r\n', +#' %(imported.18.0)s', +' >> ', +'/AP ', +' <<', +' /D', +' <<', +' /Off ', +#' %(imported.40.0)s', +["APDOff"], '\r\n', +' /Yes ', +#' %(imported.39.0)s', +["APDYes"], '\r\n', +' >>', '\r\n', +' /N', +' << ', +' /Yes ', +#' %(imported.38.0)s', +["APNYes"], '\r\n', +' >>', +' >>\r\n', +' /AS ', +["Value"], '\r\n', +' /DA ', +PDFString('/ZaDb 0 Tf 0 g'), '\r\n', +'/DV ', +["Value"], '\r\n', +'/F ', +' 4 ', +'/FT ', +' /Btn ', +'/H ', +' /T ', +'/MK ', +' <<', +' /AC (\\376\\377)', +#PDFString('\376\377'), +' /CA ', +PDFString('4'), +' /RC ', +PDFString('\376\377'), +' >> ','\r\n', +'/P ', +["Page"], '\r\n', +'/Rect', +' [',["xmin"], " ", ["ymin"], " ", ["xmax"], " ", ["ymax"], +' ] ','\r\n', +'/Subtype', +' /Widget ', +'/T ', +["Name"], '\r\n', +'/Type', +' /Annot ', +'/V ', +["Value"], '\r\n', +' >>'] + + +def buttonStreamDictionary(width=16.7704, height=14.907): + "everything except the length for the button appearance streams" + result = PDFDictionary() + result["SubType"] = "/Form" + result["BBox"] = "[0 0 %(width)s %(height)s]" % vars() + font = PDFDictionary() + font["ZaDb"] = PDFPattern(ZaDbPattern) + resources = PDFDictionary() + resources["ProcSet"] = "[ /PDF /Text ]" + resources["Font"] = font + result["Resources"] = resources + return result + +def ButtonStream(content, width=16.7704, height=14.907): + result = PDFStream(buttonStreamDictionary(width=width,height=height), content) + result.filters = [] + return result diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/pdfmetrics.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/pdfmetrics.py new file mode 100644 index 0000000000000000000000000000000000000000..e97a016017f1370c7fa625397b7e868494b4aeca --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/pdfmetrics.py @@ -0,0 +1,828 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/pdfbase/pdfmetrics.py +#$Header $ +__version__='3.3.0' +__doc__="""This provides a database of font metric information and +efines Font, Encoding and TypeFace classes aimed at end users. + +There are counterparts to some of these in pdfbase/pdfdoc.py, but +the latter focus on constructing the right PDF objects. These +classes are declarative and focus on letting the user construct +and query font objects. + +The module maintains a registry of font objects at run time. + +It is independent of the canvas or any particular context. It keeps +a registry of Font, TypeFace and Encoding objects. Ideally these +would be pre-loaded, but due to a nasty circularity problem we +trap attempts to access them and do it on first access. +""" +import os, sys, encodings +from reportlab.pdfbase import _fontdata +from reportlab.lib.logger import warnOnce +from reportlab.lib.utils import rl_isfile, rl_glob, rl_isdir, open_and_read, open_and_readlines, findInPaths, isSeq, isStr +from reportlab.rl_config import defaultEncoding, T1SearchPath +from reportlab.lib.rl_accel import unicode2T1, instanceStringWidthT1 +from reportlab.pdfbase import rl_codecs +_notdefChar = b'n' + +rl_codecs.RL_Codecs.register() +standardFonts = _fontdata.standardFonts +standardEncodings = _fontdata.standardEncodings + +_typefaces = {} +_encodings = {} +_fonts = {} +_dynFaceNames = {} #record dynamicFont face names + +class FontError(Exception): + pass +class FontNotFoundError(Exception): + pass + +def parseAFMFile(afmFileName): + """Quick and dirty - gives back a top-level dictionary + with top-level items, and a 'widths' key containing + a dictionary of glyph names and widths. Just enough + needed for embedding. A better parser would accept + options for what data you wwanted, and preserve the + order.""" + + lines = open_and_readlines(afmFileName, 'r') + if len(lines)<=1: + #likely to be a MAC file + if lines: lines = lines[0].split('\r') + if len(lines)<=1: + raise ValueError('AFM file %s hasn\'t enough data' % afmFileName) + topLevel = {} + glyphLevel = [] + + lines = [l.strip() for l in lines] + lines = [l for l in lines if not l.lower().startswith('comment')] + #pass 1 - get the widths + inMetrics = 0 # os 'TOP', or 'CHARMETRICS' + for line in lines: + if line[0:16] == 'StartCharMetrics': + inMetrics = 1 + elif line[0:14] == 'EndCharMetrics': + inMetrics = 0 + elif inMetrics: + chunks = line.split(';') + chunks = [chunk.strip() for chunk in chunks] + cidChunk, widthChunk, nameChunk = chunks[0:3] + + # character ID + l, r = cidChunk.split() + assert l == 'C', 'bad line in font file %s' % line + cid = int(r) + + # width + l, r = widthChunk.split() + assert l == 'WX', 'bad line in font file %s' % line + try: + width = int(r) + except ValueError: + width = float(r) + + # name + l, r = nameChunk.split() + assert l == 'N', 'bad line in font file %s' % line + name = r + + glyphLevel.append((cid, width, name)) + + # pass 2 font info + inHeader = 0 + for line in lines: + if line[0:16] == 'StartFontMetrics': + inHeader = 1 + if line[0:16] == 'StartCharMetrics': + inHeader = 0 + elif inHeader: + if line[0:7] == 'Comment': pass + try: + left, right = line.split(' ',1) + except: + raise ValueError("Header information error in afm %s: line='%s'" % (afmFileName, line)) + try: + right = int(right) + except: + pass + topLevel[left] = right + + + return (topLevel, glyphLevel) + +class TypeFace: + def __init__(self, name): + self.name = name + self.glyphNames = [] + self.glyphWidths = {} + self.ascent = 0 + self.descent = 0 + + + # all typefaces of whatever class should have these 3 attributes. + # these are the basis for family detection. + self.familyName = None # should set on load/construction if possible + self.bold = 0 # bold faces should set this + self.italic = 0 #italic faces should set this + + if name == 'ZapfDingbats': + self.requiredEncoding = 'ZapfDingbatsEncoding' + elif name == 'Symbol': + self.requiredEncoding = 'SymbolEncoding' + else: + self.requiredEncoding = None + if name in standardFonts: + self.builtIn = 1 + self._loadBuiltInData(name) + else: + self.builtIn = 0 + + def _loadBuiltInData(self, name): + """Called for the built in 14 fonts. Gets their glyph data. + We presume they never change so this can be a shared reference.""" + name = str(name) #needed for pycanvas&jython/2.1 compatibility + self.glyphWidths = _fontdata.widthsByFontGlyph[name] + self.glyphNames = list(self.glyphWidths.keys()) + self.ascent,self.descent = _fontdata.ascent_descent[name] + + def getFontFiles(self): + "Info function, return list of the font files this depends on." + return [] + + def findT1File(self, ext='.pfb'): + possible_exts = (ext.lower(), ext.upper()) + if hasattr(self,'pfbFileName'): + r_basename = os.path.splitext(self.pfbFileName)[0] + for e in possible_exts: + if rl_isfile(r_basename + e): + return r_basename + e + try: + r = _fontdata.findT1File(self.name) + except: + afm = bruteForceSearchForAFM(self.name) + if afm: + if ext.lower() == '.pfb': + for e in possible_exts: + pfb = os.path.splitext(afm)[0] + e + if rl_isfile(pfb): + r = pfb + else: + r = None + elif ext.lower() == '.afm': + r = afm + else: + r = None + if r is None: + warnOnce("Can't find %s for face '%s'" % (ext, self.name)) + return r + +def bruteForceSearchForFile(fn,searchPath=None): + if searchPath is None: from reportlab.rl_config import T1SearchPath as searchPath + if rl_isfile(fn): return fn + bfn = os.path.basename(fn) + for dirname in searchPath: + if not rl_isdir(dirname): continue + tfn = os.path.join(dirname,bfn) + if rl_isfile(tfn): return tfn + return fn + +def bruteForceSearchForAFM(faceName): + """Looks in all AFM files on path for face with given name. + + Returns AFM file name or None. Ouch!""" + from reportlab.rl_config import T1SearchPath + + for dirname in T1SearchPath: + if not rl_isdir(dirname): continue + possibles = rl_glob(dirname + os.sep + '*.[aA][fF][mM]') + for possible in possibles: + try: + topDict, glyphDict = parseAFMFile(possible) + if topDict['FontName'] == faceName: + return possible + except: + t,v,b=sys.exc_info() + v.args = (' '.join(map(str,v.args))+', while looking for faceName=%r' % faceName,) + raise + + +#for faceName in standardFonts: +# registerTypeFace(TypeFace(faceName)) + + +class Encoding: + """Object to help you create and refer to encodings.""" + def __init__(self, name, base=None): + self.name = name + self.frozen = 0 + if name in standardEncodings: + assert base is None, "Can't have a base encoding for a standard encoding" + self.baseEncodingName = name + self.vector = _fontdata.encodings[name] + elif base == None: + # assume based on the usual one + self.baseEncodingName = defaultEncoding + self.vector = _fontdata.encodings[defaultEncoding] + elif isStr(base): + baseEnc = getEncoding(base) + self.baseEncodingName = baseEnc.name + self.vector = baseEnc.vector[:] + elif isSeq(base): + self.baseEncodingName = defaultEncoding + self.vector = base[:] + elif isinstance(base, Encoding): + # accept a vector + self.baseEncodingName = base.name + self.vector = base.vector[:] + + def __getitem__(self, index): + "Return glyph name for that code point, or None" + # THIS SHOULD BE INLINED FOR SPEED + return self.vector[index] + + def __setitem__(self, index, value): + # should fail if they are frozen + assert self.frozen == 0, 'Cannot modify a frozen encoding' + if self.vector[index]!=value: + L = list(self.vector) + L[index] = value + self.vector = tuple(L) + + def freeze(self): + self.vector = tuple(self.vector) + self.frozen = 1 + + def isEqual(self, other): + return self.name==other.name and tuple(self.vector)==tuple(other.vector) + + def modifyRange(self, base, newNames): + """Set a group of character names starting at the code point 'base'.""" + assert self.frozen == 0, 'Cannot modify a frozen encoding' + idx = base + for name in newNames: + self.vector[idx] = name + idx = idx + 1 + + def getDifferences(self, otherEnc): + """ + Return a compact list of the code points differing between two encodings + + This is in the Adobe format: list of + [[b1, name1, name2, name3], + [b2, name4]] + + where b1...bn is the starting code point, and the glyph names following + are assigned consecutive code points. + + """ + + ranges = [] + curRange = None + for i in range(len(self.vector)): + glyph = self.vector[i] + if glyph==otherEnc.vector[i]: + if curRange: + ranges.append(curRange) + curRange = [] + else: + if curRange: + curRange.append(glyph) + elif glyph: + curRange = [i, glyph] + if curRange: + ranges.append(curRange) + return ranges + + def makePDFObject(self): + "Returns a PDF Object representing self" + # avoid circular imports - this cannot go at module level + from reportlab.pdfbase import pdfdoc + + D = {} + baseEncodingName = self.baseEncodingName + baseEnc = getEncoding(baseEncodingName) + differences = self.getDifferences(baseEnc) #[None] * 256) + + # if no differences, we just need the base name + if differences == []: + return pdfdoc.PDFName(baseEncodingName) + else: + #make up a dictionary describing the new encoding + diffArray = [] + for range in differences: + diffArray.append(range[0]) # numbers go 'as is' + for glyphName in range[1:]: + if glyphName is not None: + # there is no way to 'unset' a character in the base font. + diffArray.append('/' + glyphName) + + #print 'diffArray = %s' % diffArray + D["Differences"] = pdfdoc.PDFArray(diffArray) + if baseEncodingName in ('MacRomanEncoding','MacExpertEncoding','WinAnsiEncoding'): + #https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf page 263 + D["BaseEncoding"] = pdfdoc.PDFName(baseEncodingName) + D["Type"] = pdfdoc.PDFName("Encoding") + PD = pdfdoc.PDFDictionary(D) + return PD + +#for encName in standardEncodings: +# registerEncoding(Encoding(encName)) + + +standardT1SubstitutionFonts = [] +class Font: + """Represents a font (i.e combination of face and encoding). + + Defines suitable machinery for single byte fonts. This is + a concrete class which can handle the basic built-in fonts; + not clear yet if embedded ones need a new font class or + just a new typeface class (which would do the job through + composition)""" + + _multiByte = 0 # do not want our own stringwidth + _dynamicFont = 0 # do not want dynamic subsetting + shapable = False + + def __init__(self, name, faceName, encName, substitutionFonts=None): + self.fontName = name + face = self.face = getTypeFace(faceName) + self.encoding= getEncoding(encName) + self.encName = encName + self.substitutionFonts = (standardT1SubstitutionFonts + if face.builtIn and face.requiredEncoding is None + else substitutionFonts or []) + self._calcWidths() + self._notdefChar = _notdefChar + self._notdefFont = name=='ZapfDingbats' and self or _notdefFont + + def stringWidth(self, text, size, encoding='utf8'): + return instanceStringWidthT1(self, text, size, encoding=encoding) + + def __repr__(self): + return "<%s %s>" % (self.__class__.__name__, self.face.name) + + def _calcWidths(self): + """Vector of widths for stringWidth function""" + #synthesize on first request + w = [0] * 256 + gw = self.face.glyphWidths + vec = self.encoding.vector + for i in range(256): + glyphName = vec[i] + if glyphName is not None: + try: + width = gw[glyphName] + w[i] = width + except KeyError: + import reportlab.rl_config + if reportlab.rl_config.warnOnMissingFontGlyphs: + print('typeface "%s" does not have a glyph "%s", bad font!' % (self.face.name, glyphName)) + else: + pass + self.widths = w + + def _formatWidths(self): + "returns a pretty block in PDF Array format to aid inspection" + text = b'[' + for i in range(256): + text = text + b' ' + bytes(str(self.widths[i]),'utf8') + if i == 255: + text = text + b' ]' + if i % 16 == 15: + text = text + b'\n' + return text + + def addObjects(self, doc): + """Makes and returns one or more PDF objects to be added + to the document. The caller supplies the internal name + to be used (typically F1, F2... in sequence) """ + # avoid circular imports - this cannot go at module level + from reportlab.pdfbase import pdfdoc + + # construct a Type 1 Font internal object + internalName = 'F' + repr(len(doc.fontMapping)+1) + pdfFont = pdfdoc.PDFType1Font() + pdfFont.Name = internalName + pdfFont.BaseFont = self.face.name + pdfFont.__Comment__ = 'Font %s' % self.fontName + e = self.encoding.makePDFObject() + if not isStr(e) or e in ('/MacRomanEncoding','/MacExpertEncoding','/WinAnsiEncoding'): + #https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf page 255 + pdfFont.Encoding = e + + # is it a built-in one? if not, need more stuff. + if not self.face.name in standardFonts: + pdfFont.FirstChar = 0 + pdfFont.LastChar = 255 + pdfFont.Widths = pdfdoc.PDFArray(self.widths) + pdfFont.FontDescriptor = self.face.addObjects(doc) + # now link it in + ref = doc.Reference(pdfFont, internalName) + + # also refer to it in the BasicFonts dictionary + fontDict = doc.idToObject['BasicFonts'].dict + fontDict[internalName] = pdfFont + + # and in the font mappings + doc.fontMapping[self.fontName] = '/' + internalName + +PFB_MARKER=chr(0x80) +PFB_ASCII=chr(1) +PFB_BINARY=chr(2) +PFB_EOF=chr(3) + +def _pfbCheck(p,d,m,fn): + if chr(d[p])!=PFB_MARKER or chr(d[p+1])!=m: + raise ValueError('Bad pfb file\'%s\' expected chr(%d)chr(%d) at char %d, got chr(%d)chr(%d)' % (fn,ord(PFB_MARKER),ord(m),p,d[p],d[p+1])) + if m==PFB_EOF: return + p = p + 2 + l = (((((d[p+3])<<8)|(d[p+2])<<8)|(d[p+1]))<<8)|(d[p]) + p = p + 4 + if p+l>len(d): + raise ValueError('Bad pfb file\'%s\' needed %d+%d bytes have only %d!' % (fn,p,l,len(d))) + return p, p+l + +_postScriptNames2Unicode = None +class EmbeddedType1Face(TypeFace): + """A Type 1 font other than one of the basic 14. + + Its glyph data will be embedded in the PDF file.""" + def __init__(self, afmFileName, pfbFileName): + # ignore afm file for now + TypeFace.__init__(self, None) + #None is a hack, name will be supplied by AFM parse lower done + #in this __init__ method. + afmFileName = findInPaths(afmFileName,T1SearchPath) + pfbFileName = findInPaths(pfbFileName,T1SearchPath) + self.afmFileName = os.path.abspath(afmFileName) + self.pfbFileName = os.path.abspath(pfbFileName) + self.requiredEncoding = None + self._loadGlyphs(pfbFileName) + self._loadMetrics(afmFileName) + + def getFontFiles(self): + return [self.afmFileName, self.pfbFileName] + + def _loadGlyphs(self, pfbFileName): + """Loads in binary glyph data, and finds the four length + measurements needed for the font descriptor""" + pfbFileName = bruteForceSearchForFile(pfbFileName) + assert rl_isfile(pfbFileName), 'file %s not found' % pfbFileName + d = open_and_read(pfbFileName, 'b') + s1, l1 = _pfbCheck(0,d,PFB_ASCII,pfbFileName) + s2, l2 = _pfbCheck(l1,d,PFB_BINARY,pfbFileName) + s3, l3 = _pfbCheck(l2,d,PFB_ASCII,pfbFileName) + _pfbCheck(l3,d,PFB_EOF,pfbFileName) + self._binaryData = d[s1:l1]+d[s2:l2]+d[s3:l3] + + self._length = len(self._binaryData) + self._length1 = l1-s1 + self._length2 = l2-s2 + self._length3 = l3-s3 + + + def _loadMetrics(self, afmFileName): + """Loads in and parses font metrics""" + #assert os.path.isfile(afmFileName), "AFM file %s not found" % afmFileName + afmFileName = bruteForceSearchForFile(afmFileName) + (topLevel, glyphData) = parseAFMFile(afmFileName) + + self.name = topLevel['FontName'] + self.familyName = topLevel['FamilyName'] + self.ascent = topLevel.get('Ascender', 1000) + self.descent = topLevel.get('Descender', 0) + self.capHeight = topLevel.get('CapHeight', 1000) + self.italicAngle = topLevel.get('ItalicAngle', 0) + self.stemV = topLevel.get('stemV', 0) + self.xHeight = topLevel.get('XHeight', 1000) + + strBbox = topLevel.get('FontBBox', [0,0,1000,1000]) + tokens = strBbox.split() + self.bbox = [] + for tok in tokens: + self.bbox.append(int(tok)) + + glyphWidths = {} + for (cid, width, name) in glyphData: + glyphWidths[name] = width + self.glyphWidths = glyphWidths + self.glyphNames = list(glyphWidths.keys()) + self.glyphNames.sort() + + # for font-specific encodings like Symbol, Dingbats, Carta we + # need to make a new encoding as well.... + if topLevel.get('EncodingScheme', None) == 'FontSpecific': + global _postScriptNames2Unicode + if _postScriptNames2Unicode is None: + try: + from reportlab.pdfbase._glyphlist import _glyphname2unicode + _postScriptNames2Unicode = _glyphname2unicode + del _glyphname2unicode + except: + _postScriptNames2Unicode = {} + raise ValueError( + "cannot import module reportlab.pdfbase._glyphlist module\n" + "you can obtain a version from here\n" + "https://www.reportlab.com/ftp/_glyphlist.py\n" + ) + + names = [None] * 256 + ex = {} + rex = {} + for (code, width, name) in glyphData: + if 0<=code<=255: + names[code] = name + u = _postScriptNames2Unicode.get(name,None) + if u is not None: + rex[code] = u + ex[u] = code + encName = encodings.normalize_encoding('rl-dynamic-%s-encoding' % self.name) + rl_codecs.RL_Codecs.add_dynamic_codec(encName,ex,rex) + self.requiredEncoding = encName + enc = Encoding(encName, names) + registerEncoding(enc) + + def addObjects(self, doc): + """Add whatever needed to PDF file, and return a FontDescriptor reference""" + from reportlab.pdfbase import pdfdoc + + fontFile = pdfdoc.PDFStream() + fontFile.content = self._binaryData + #fontFile.dictionary['Length'] = self._length + fontFile.dictionary['Length1'] = self._length1 + fontFile.dictionary['Length2'] = self._length2 + fontFile.dictionary['Length3'] = self._length3 + #fontFile.filters = [pdfdoc.PDFZCompress] + + fontFileRef = doc.Reference(fontFile, 'fontFile:' + self.pfbFileName) + + fontDescriptor = pdfdoc.PDFDictionary({ + 'Type': '/FontDescriptor', + 'Ascent':self.ascent, + 'CapHeight':self.capHeight, + 'Descent':self.descent, + 'Flags': 34, + 'FontBBox':pdfdoc.PDFArray(self.bbox), + 'FontName':pdfdoc.PDFName(self.name), + 'ItalicAngle':self.italicAngle, + 'StemV':self.stemV, + 'XHeight':self.xHeight, + 'FontFile': fontFileRef, + }) + fontDescriptorRef = doc.Reference(fontDescriptor, 'fontDescriptor:' + self.name) + return fontDescriptorRef + +def registerTypeFace(face): + assert isinstance(face, TypeFace), 'Not a TypeFace: %s' % face + _typefaces[face.name] = face + if not face.name in standardFonts: + # HACK - bold/italic do not apply for type 1, so egister + # all combinations of mappings. + registerFontFamily(face.name) + +def registerEncoding(enc): + assert isinstance(enc, Encoding), 'Not an Encoding: %s' % enc + if enc.name in _encodings: + # already got one, complain if they are not the same + if enc.isEqual(_encodings[enc.name]): + enc.freeze() + else: + raise FontError('Encoding "%s" already registered with a different name vector!' % enc.name) + else: + _encodings[enc.name] = enc + enc.freeze() + # have not yet dealt with immutability! + +def registerFontFamily(family,normal=None,bold=None,italic=None,boldItalic=None): + from reportlab.lib import fonts + if not normal: normal = family + family = family.lower() + if not boldItalic: boldItalic = italic or bold or normal + if not bold: bold = normal + if not italic: italic = normal + fonts.addMapping(family, 0, 0, normal) + fonts.addMapping(family, 1, 0, bold) + fonts.addMapping(family, 0, 1, italic) + fonts.addMapping(family, 1, 1, boldItalic) + +def registerFont(font): + "Registers a font, including setting up info for accelerated stringWidth" + #assert isinstance(font, Font), 'Not a Font: %s' % font + fontName = font.fontName + if font._dynamicFont: + faceName = font.face.name + if fontName not in _fonts: + if faceName in _dynFaceNames: + ofont = _dynFaceNames[faceName] + if not ofont._dynamicFont: + raise ValueError('Attempt to register fonts %r %r for face %r' % (ofont, font, faceName)) + else: + _fonts[fontName] = ofont + else: + _dynFaceNames[faceName] = _fonts[fontName] = font + else: + _fonts[fontName] = font + + if font._multiByte: + # CID fonts don't need to have typeface registered. + #need to set mappings so it can go in a paragraph even if within + # bold tags + registerFontFamily(font.fontName) + +def getTypeFace(faceName): + """Lazily construct known typefaces if not found""" + try: + return _typefaces[faceName] + except KeyError: + # not found, construct it if known + if faceName in standardFonts: + face = TypeFace(faceName) + (face.familyName, face.bold, face.italic) = _fontdata.standardFontAttributes[faceName] + registerTypeFace(face) +## print 'auto-constructing type face %s with family=%s, bold=%d, italic=%d' % ( +## face.name, face.familyName, face.bold, face.italic) + return face + else: + #try a brute force search + afm = bruteForceSearchForAFM(faceName) + if afm: + for e in ('.pfb', '.PFB'): + pfb = os.path.splitext(afm)[0] + e + if rl_isfile(pfb): break + assert rl_isfile(pfb), 'file %s not found!' % pfb + face = EmbeddedType1Face(afm, pfb) + registerTypeFace(face) + return face + else: + raise + +def getEncoding(encName): + """Lazily construct known encodings if not found""" + try: + return _encodings[encName] + except KeyError: + if encName in standardEncodings: + enc = Encoding(encName) + registerEncoding(enc) + #print 'auto-constructing encoding %s' % encName + return enc + else: + raise + +def findFontAndRegister(fontName): + '''search for and register a font given its name''' + fontName = str(fontName) + assert type(fontName) is str, 'fontName=%s is not required type str' % ascii(fontName) + #it might have a font-specific encoding e.g. Symbol + # or Dingbats. If not, take the default. + face = getTypeFace(fontName) + if face.requiredEncoding: + font = Font(fontName, fontName, face.requiredEncoding) + else: + font = Font(fontName, fontName, defaultEncoding) + registerFont(font) + return font + +def getFont(fontName): + """Lazily constructs known fonts if not found. + + Names of form 'face-encoding' will be built if + face and encoding are known. Also if the name is + just one of the standard 14, it will make up a font + in the default encoding.""" + try: + return _fonts[fontName] + except KeyError: + return findFontAndRegister(fontName) + +_notdefFont = getFont('ZapfDingbats') +standardT1SubstitutionFonts.extend([getFont('Symbol'),_notdefFont]) + +def getAscentDescent(fontName,fontSize=None): + font = getFont(fontName) + try: + ascent = font.ascent + descent = font.descent + except: + ascent = font.face.ascent + descent = font.face.descent + if fontSize: + norm = fontSize/1000. + return ascent*norm, descent*norm + else: + return ascent, descent + +def getAscent(fontName,fontSize=None): + return getAscentDescent(fontName,fontSize)[0] + +def getDescent(fontName,fontSize=None): + return getAscentDescent(fontName,fontSize)[1] + +def getRegisteredFontNames(): + "Returns what's in there" + reg = list(_fonts.keys()) + reg.sort() + return reg + +def stringWidth(text, fontName, fontSize, encoding='utf8'): + """Compute width of string in points; + not accelerated as fast enough because of instanceStringWidthT1/TTF""" + return getFont(fontName).stringWidth(text, fontSize, encoding=encoding) + +def dumpFontData(): + print('Registered Encodings:') + keys = list(_encodings.keys()) + keys.sort() + for encName in keys: + print(' ',encName) + + print() + print('Registered Typefaces:') + faces = list(_typefaces.keys()) + faces.sort() + for faceName in faces: + print(' ',faceName) + + + print() + print('Registered Fonts:') + k = list(_fonts.keys()) + k.sort() + for key in k: + font = _fonts[key] + print(' %s (%s/%s)' % (font.fontName, font.face.name, font.encoding.name)) + +def test3widths(texts): + # checks all 3 algorithms give same answer, note speed + import time + for fontName in standardFonts[0:1]: +## t0 = time.time() +## for text in texts: +## l1 = stringWidth(text, fontName, 10) +## t1 = time.time() +## print 'fast stringWidth took %0.4f' % (t1 - t0) + + t0 = time.time() + w = getFont(fontName).widths + for text in texts: + l2 = 0 + for ch in text: + l2 = l2 + w[ord(ch)] + t1 = time.time() + print('slow stringWidth took %0.4f' % (t1 - t0)) + + t0 = time.time() + for text in texts: + l3 = getFont(fontName).stringWidth(text, 10) + t1 = time.time() + print('class lookup and stringWidth took %0.4f' % (t1 - t0)) + print() + +def testStringWidthAlgorithms(): + rawdata = open('../../rlextra/rml2pdf/doc/rml_user_guide.prep').read() + print('rawdata length %d' % len(rawdata)) + print('test one huge string...') + test3widths([rawdata]) + print() + words = rawdata.split() + print('test %d shorter strings (average length %0.2f chars)...' % (len(words), 1.0*len(rawdata)/len(words))) + test3widths(words) + + +def test(): + helv = TypeFace('Helvetica') + registerTypeFace(helv) + print(helv.glyphNames[0:30]) + + wombat = TypeFace('Wombat') + print(wombat.glyphNames) + registerTypeFace(wombat) + + dumpFontData() + +#preserve the initial values here +def _reset( + initial_dicts = dict( + _typefaces = _typefaces.copy(), + _encodings = _encodings.copy(), + _fonts = _fonts.copy(), + _dynFaceNames = _dynFaceNames.copy(), + ) + ): + for k,v in initial_dicts.items(): + d=globals()[k] + d.clear() + d.update(v) + rl_codecs.RL_Codecs.reset_dynamic_codecs() + +from reportlab.rl_config import register_reset +register_reset(_reset) +del register_reset + +if __name__=='__main__': + test() + testStringWidthAlgorithms() diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/pdfpattern.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/pdfpattern.py new file mode 100644 index 0000000000000000000000000000000000000000..4cc0898f11cc81ce360919f40ceb813af92326ef --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/pdfpattern.py @@ -0,0 +1,93 @@ +__doc__="""helper for importing pdf structures into a ReportLab generated document +""" +from reportlab.pdfbase.pdfdoc import format, PDFObject, pdfdocEnc +from reportlab.lib.utils import strTypes + +def _patternSequenceCheck(pattern_sequence): + allowedTypes = strTypes if isinstance(strTypes, tuple) else (strTypes,) + allowedTypes = allowedTypes + (PDFObject,PDFPatternIf) + for x in pattern_sequence: + if not isinstance(x,allowedTypes): + if len(x)!=1: + raise ValueError("sequence elts must be strings/bytes/PDFPatternIfs or singletons containing strings: "+ascii(x)) + if not isinstance(x[0],strTypes): + raise ValueError("Singletons must contain strings/bytes or PDFObject instances only: "+ascii(x[0])) + +class PDFPattern(PDFObject): + __RefOnly__ = 1 + def __init__(self, pattern_sequence, **keywordargs): + """ + Description of a kind of PDF object using a pattern. + + Pattern sequence should contain strings, singletons of form [string] or + PDFPatternIf objects. + Strings are literal strings to be used in the object. + Singletons are names of keyword arguments to include. + PDFpatternIf objects allow some conditionality. + Keyword arguments can be non-instances which are substituted directly in string conversion, + or they can be object instances in which case they should be pdfdoc.* style + objects with a x.format(doc) method. + Keyword arguments may be set on initialization or subsequently using __setitem__, before format. + "constant object" instances can also be inserted in the patterns. + """ + _patternSequenceCheck(pattern_sequence) + self.pattern = pattern_sequence + self.arguments = keywordargs + + def __setitem__(self, item, value): + self.arguments[item] = value + + def __getitem__(self, item): + return self.arguments[item] + + def eval(self,L): + arguments = self.arguments + document = self.__document + for x in L: + if isinstance(x,strTypes): + yield pdfdocEnc(x) + elif isinstance(x,PDFObject): + yield x.format(document) + elif isinstance(x,PDFPatternIf): + result = list(self.eval(x.cond)) + cond = result and result[0] + for z in self.eval(x.thenPart if cond else x.elsePart): + yield z + else: + name = x[0] + value = arguments.get(name, None) + if value is None: + raise ValueError("%s value not defined" % ascii(name)) + if isinstance(value,PDFObject): + yield format(value,document) + elif isinstance(value,strTypes): + yield pdfdocEnc(value) + else: + yield pdfdocEnc(str(value)) + + def format(self, document): + self.__document = document + try: + return b"".join(self.eval(self.pattern)) + finally: + del self.__document + + def clone(self): + c = object.__new__(self.__class__) + c.pattern = self.pattern + c.arguments = self.arguments + return c + +class PDFPatternIf: + '''cond will be evaluated as [cond] in PDFpattern eval. + It should evaluate to a list with value 0/1 etc etc. + thenPart is a list to be evaluated if the cond evaulates true, + elsePart is the false sequence. + ''' + def __init__(self,cond,thenPart=[],elsePart=[]): + if not isinstance(cond,list): cond = [cond] + for x in cond, thenPart, elsePart: + _patternSequenceCheck(x) + self.cond = cond + self.thenPart = thenPart + self.elsePart = elsePart diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/pdfutils.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/pdfutils.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0f001fd6f63d2db7a7898c868445c040251e02 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/pdfutils.py @@ -0,0 +1,298 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/pdfbase/pdfutils.py +__version__='3.3.0' +__doc__='' +# pdfutils.py - everything to do with images, streams, +# compression, and some constants + +import os +import binascii +from io import BytesIO + +from reportlab import rl_config +from reportlab.lib.utils import ImageReader, isUnicode +from reportlab.lib.rl_accel import asciiBase85Encode, asciiBase85Decode + +def _chunker(src,dst=[],chunkSize=60): + for i in range(0,len(src),chunkSize): + dst.append(src[i:i+chunkSize]) + return dst + +########################################################## +# +# Image compression helpers. Preprocessing a directory +# of images will offer a vast speedup. +# +########################################################## +_mode2cs = {'RGB':'RGB', 'CMYK': 'CMYK', 'L': 'G'} +_mode2bpp = {'RGB': 3, 'CMYK':4, 'L':1} +def makeA85Image(filename,IMG=None, detectJpeg=False): + import zlib + img = ImageReader(filename) + if IMG is not None: + IMG.append(img) + if detectJpeg and img.jpeg_fh(): + return None + + imgwidth, imgheight = img.getSize() + raw = img.getRGBData() + + code = [] + append = code.append + # this describes what is in the image itself + append('BI') + append('/W %s /H %s /BPC 8 /CS /%s /F [/A85 /Fl]' % (imgwidth, imgheight,_mode2cs[img.mode])) + append('ID') + #use a flate filter and Ascii Base 85 + assert len(raw) == imgwidth * imgheight*_mode2bpp[img.mode], "Wrong amount of data for image" + compressed = zlib.compress(raw) #this bit is very fast... + encoded = asciiBase85Encode(compressed) #...sadly this may not be + + #append in blocks of 60 characters + _chunker(encoded,code) + + append('EI') + return code +def makeRawImage(filename,IMG=None,detectJpeg=False): + import zlib + img = ImageReader(filename) + if IMG is not None: + IMG.append(img) + if detectJpeg and img.jpeg_fh(): + return None + + imgwidth, imgheight = img.getSize() + raw = img.getRGBData() + + code = [] + append = code.append + # this describes what is in the image itself + append('BI') + append('/W %s /H %s /BPC 8 /CS /%s /F [/Fl]' % (imgwidth, imgheight,_mode2cs[img.mode])) + append('ID') + #use a flate filter + assert len(raw) == imgwidth * imgheight*_mode2bpp[img.mode], "Wrong amount of data for image" + compressed = zlib.compress(raw) #this bit is very fast... + + #append in blocks of 60 characters + _chunker(compressed,code) + + append('EI') + return code + +def cacheImageFile(filename, returnInMemory=0, IMG=None): + "Processes image as if for encoding, saves to a file with .a85 extension." + + cachedname = os.path.splitext(filename)[0] + (rl_config.useA85 and '.a85' or '.bin') + if filename==cachedname: + if cachedImageExists(filename): + from reportlab.lib.utils import open_for_read + if returnInMemory: return filter(None,open_for_read(cachedname).read().split('\r\n')) + else: + raise IOError('No such cached image %s' % filename) + else: + if rl_config.useA85: + code = makeA85Image(filename,IMG) + else: + code = makeRawImage(filename,IMG) + if returnInMemory: return code + + #save it to a file + f = open(cachedname,'wb') + f.write('\r\n'.join(code)+'\r\n') + f.close() + if rl_config.verbose: + print('cached image as %s' % cachedname) + + +def preProcessImages(spec): + """Preprocesses one or more image files. + + Accepts either a filespec ('C:\\mydir\\*.jpg') or a list + of image filenames, crunches them all to save time. Run this + to save huge amounts of time when repeatedly building image + documents.""" + + import glob + + if isinstance(spec,str): + filelist = glob.glob(spec) + else: #list or tuple OK + filelist = spec + + for filename in filelist: + if cachedImageExists(filename): + if rl_config.verbose: + print('cached version of %s already exists' % filename) + else: + cacheImageFile(filename) + + +def cachedImageExists(filename): + """Determines if a cached image already exists for a given file. + + Determines if a cached image exists which has the same name + and equal or newer date to the given file.""" + cachedname = os.path.splitext(filename)[0] + (rl_config.useA85 and '.a85' or 'bin') + if os.path.isfile(cachedname): + #see if it is newer + original_date = os.stat(filename)[8] + cached_date = os.stat(cachedname)[8] + if original_date > cached_date: + return 0 + else: + return 1 + else: + return 0 + + +############################################################## +# +# PDF Helper functions +# +############################################################## + +def _normalizeLineEnds(text,desired='\r\n',unlikely='\x00\x01\x02\x03'): + """Normalizes different line end character(s). + + Ensures all instances of CR, LF and CRLF end up as + the specified one.""" + + return (text + .replace('\r\n', unlikely) + .replace('\r', unlikely) + .replace('\n', unlikely) + .replace(unlikely, desired)) + +def _AsciiHexEncode(input): + """Encodes input using ASCII-Hex coding. + + This is a verbose encoding used for binary data within + a PDF file. One byte binary becomes two bytes of ASCII. + Helper function used by images.""" + if isUnicode(input): + input = input.encode('utf-8') + output = BytesIO() + output.write(binascii.b2a_hex(input)) + output.write(b'>') + return output.getvalue() + + +def _AsciiHexDecode(input): + """Decodes input using ASCII-Hex coding. + + Not used except to provide a test of the inverse function.""" + + #strip out all whitespace + if not isUnicode(input): + input = input.decode('utf-8') + stripped = ''.join(input.split()) + assert stripped[-1] == '>', 'Invalid terminator for Ascii Hex Stream' + stripped = stripped[:-1] #chop off terminator + assert len(stripped) % 2 == 0, 'Ascii Hex stream has odd number of bytes' + + return ''.join([chr(int(stripped[i:i+2],16)) for i in range(0,len(stripped),2)]) + +def _wrap(input, columns=60): + "Wraps input at a given column size by inserting \r\n characters." + output = [] + length = len(input) + i = 0 + pos = columns * i + while pos < length: + output.append(input[pos:pos+columns]) + i = i + 1 + pos = columns * i + #avoid HP printer problem + if len(output[-1])==1: + output[-2:] = [output[-2][:-1],output[-2][-1]+output[-1]] + return '\r\n'.join(output) + + +######################################################################### +# +# JPEG processing code - contributed by Eric Johnson +# +######################################################################### + +# Read data from the JPEG file. We should probably be using PIL to +# get this information for us -- but this way is more fun! +# Returns (width, height, color components) as a triple +# This is based on Thomas Merz's code from GhostScript (viewjpeg.ps) +def readJPEGInfo(image): + "Read width, height and number of components from open JPEG file." + + import struct + from reportlab.pdfbase.pdfdoc import PDFError + + #Acceptable JPEG Markers: + # SROF0=baseline, SOF1=extended sequential or SOF2=progressive + validMarkers = [0xC0, 0xC1, 0xC2] + + #JPEG markers without additional parameters + noParamMarkers = \ + [ 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0x01 ] + + #Unsupported JPEG Markers + unsupportedMarkers = \ + [ 0xC3, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF ] + + #read JPEG marker segments until we find SOFn marker or EOF + dpi = (72,72) + done = 0 + while not done: + x = struct.unpack('B', image.read(1)) + if x[0] == 0xFF: #found marker + x = struct.unpack('B', image.read(1)) + #print('marker=%2x' % x[0]) + if x[0] in validMarkers: + image.seek(2, 1) #skip segment length + x = struct.unpack('B', image.read(1)) #data precision + if x[0] != 8: + raise PDFError('JPEG must have 8 bits per component') + y = struct.unpack('BB', image.read(2)) + height = (y[0] << 8) + y[1] + y = struct.unpack('BB', image.read(2)) + width = (y[0] << 8) + y[1] + y = struct.unpack('B', image.read(1)) + color = y[0] + return width, height, color, dpi + elif x[0]==0xE0: + x = struct.unpack('BB', image.read(2)) + n = (x[0] << 8) + x[1] - 2 + x = image.read(n) + y = struct.unpack('BB', x[10:12]) + x = struct.unpack('BB', x[8:10]) + dpi = ((x[0]<<8) + x[1],(y[0]<<8)+y[1]) + elif x[0] in unsupportedMarkers: + raise PDFError('JPEG Unsupported JPEG marker: %0.2x' % x[0]) + elif x[0] not in noParamMarkers: + #skip segments with parameters + #read length and skip the data + x = struct.unpack('BB', image.read(2)) + image.seek( (x[0] << 8) + x[1] - 2, 1) + +class _fusc: + def __init__(self,k, n): + assert k, 'Argument k should be a non empty string' + self._k = k + self._klen = len(k) + self._n = int(n) or 7 + + def encrypt(self,s): + return self.__rotate(asciiBase85Encode(''.join(map(chr,self.__fusc(list(map(ord,s)))))),self._n) + + def decrypt(self,s): + return ''.join(map(chr,self.__fusc(list(map(ord,asciiBase85Decode(self.__rotate(s,-self._n))))))) + + def __rotate(self,s,n): + l = len(s) + if n<0: n = l+n + n %= l + if not n: return s + return s[-n:]+s[:l-n] + + def __fusc(self,s): + slen = len(s) + return list(map(lambda x,y: x ^ y,s,list(map(ord,((int(slen/self._klen)+1)*self._k)[:slen])))) diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/rl_codecs.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/rl_codecs.py new file mode 100644 index 0000000000000000000000000000000000000000..d25890c77a65aa562542b2ed64dceb94af81dab3 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/rl_codecs.py @@ -0,0 +1,1107 @@ +#codecs support +__all__=['RL_Codecs'] +from collections import namedtuple +import codecs +StdCodecData=namedtuple('StdCodecData','exceptions rexceptions') +ExtCodecData=namedtuple('ExtCodecData','baseName exceptions rexceptions') +class RL_Codecs: + __rl_codecs_data = { + 'winansi':StdCodecData({ + 0x007f: 0x2022, # BULLET + 0x0080: 0x20ac, # EURO SIGN + 0x0081: 0x2022, # BULLET + 0x0082: 0x201a, # SINGLE LOW-9 QUOTATION MARK + 0x0083: 0x0192, # LATIN SMALL LETTER F WITH HOOK + 0x0084: 0x201e, # DOUBLE LOW-9 QUOTATION MARK + 0x0085: 0x2026, # HORIZONTAL ELLIPSIS + 0x0086: 0x2020, # DAGGER + 0x0087: 0x2021, # DOUBLE DAGGER + 0x0088: 0x02c6, # MODIFIER LETTER CIRCUMFLEX ACCENT + 0x0089: 0x2030, # PER MILLE SIGN + 0x008a: 0x0160, # LATIN CAPITAL LETTER S WITH CARON + 0x008b: 0x2039, # SINGLE LEFT-POINTING ANGLE QUOTATION MARK + 0x008c: 0x0152, # LATIN CAPITAL LIGATURE OE + 0x008d: 0x2022, # BULLET + 0x008e: 0x017d, # LATIN CAPITAL LETTER Z WITH CARON + 0x008f: 0x2022, # BULLET + 0x0090: 0x2022, # BULLET + 0x0091: 0x2018, # LEFT SINGLE QUOTATION MARK + 0x0092: 0x2019, # RIGHT SINGLE QUOTATION MARK + 0x0093: 0x201c, # LEFT DOUBLE QUOTATION MARK + 0x0094: 0x201d, # RIGHT DOUBLE QUOTATION MARK + 0x0095: 0x2022, # BULLET + 0x0096: 0x2013, # EN DASH + 0x0097: 0x2014, # EM DASH + 0x0098: 0x02dc, # SMALL TILDE + 0x0099: 0x2122, # TRADE MARK SIGN + 0x009a: 0x0161, # LATIN SMALL LETTER S WITH CARON + 0x009b: 0x203a, # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK + 0x009c: 0x0153, # LATIN SMALL LIGATURE OE + 0x009d: 0x2022, # BULLET + 0x009e: 0x017e, # LATIN SMALL LETTER Z WITH CARON + 0x009f: 0x0178, # LATIN CAPITAL LETTER Y WITH DIAERESIS + 0x00a0: 0x0020, # SPACE + }, {0x2022:0x7f,0x20:0x20,0xa0:0x20}), + 'macroman':StdCodecData({ + 0x007f: None, # UNDEFINED + 0x0080: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS + 0x0081: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE + 0x0082: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA + 0x0083: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE + 0x0084: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE + 0x0085: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS + 0x0086: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS + 0x0087: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE + 0x0088: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE + 0x0089: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX + 0x008a: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS + 0x008b: 0x00e3, # LATIN SMALL LETTER A WITH TILDE + 0x008c: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE + 0x008d: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA + 0x008e: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE + 0x008f: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE + 0x0090: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX + 0x0091: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS + 0x0092: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE + 0x0093: 0x00ec, # LATIN SMALL LETTER I WITH GRAVE + 0x0094: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX + 0x0095: 0x00ef, # LATIN SMALL LETTER I WITH DIAERESIS + 0x0096: 0x00f1, # LATIN SMALL LETTER N WITH TILDE + 0x0097: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE + 0x0098: 0x00f2, # LATIN SMALL LETTER O WITH GRAVE + 0x0099: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX + 0x009a: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS + 0x009b: 0x00f5, # LATIN SMALL LETTER O WITH TILDE + 0x009c: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE + 0x009d: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE + 0x009e: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX + 0x009f: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS + 0x00a0: 0x2020, # DAGGER + 0x00a1: 0x00b0, # DEGREE SIGN + 0x00a4: 0x00a7, # SECTION SIGN + 0x00a5: 0x2022, # BULLET + 0x00a6: 0x00b6, # PILCROW SIGN + 0x00a7: 0x00df, # LATIN SMALL LETTER SHARP S + 0x00a8: 0x00ae, # REGISTERED SIGN + 0x00aa: 0x2122, # TRADE MARK SIGN + 0x00ab: 0x00b4, # ACUTE ACCENT + 0x00ac: 0x00a8, # DIAERESIS + 0x00ad: None, # UNDEFINED + 0x00ae: 0x00c6, # LATIN CAPITAL LETTER AE + 0x00af: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE + 0x00b0: None, # UNDEFINED + 0x00b2: None, # UNDEFINED + 0x00b3: None, # UNDEFINED + 0x00b4: 0x00a5, # YEN SIGN + 0x00b6: None, # UNDEFINED + 0x00b7: None, # UNDEFINED + 0x00b8: None, # UNDEFINED + 0x00b9: None, # UNDEFINED + 0x00ba: None, # UNDEFINED + 0x00bb: 0x00aa, # FEMININE ORDINAL INDICATOR + 0x00bc: 0x00ba, # MASCULINE ORDINAL INDICATOR + 0x00bd: None, # UNDEFINED + 0x00be: 0x00e6, # LATIN SMALL LETTER AE + 0x00bf: 0x00f8, # LATIN SMALL LETTER O WITH STROKE + 0x00c0: 0x00bf, # INVERTED QUESTION MARK + 0x00c1: 0x00a1, # INVERTED EXCLAMATION MARK + 0x00c2: 0x00ac, # NOT SIGN + 0x00c3: None, # UNDEFINED + 0x00c4: 0x0192, # LATIN SMALL LETTER F WITH HOOK + 0x00c5: None, # UNDEFINED + 0x00c6: None, # UNDEFINED + 0x00c7: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK + 0x00c8: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK + 0x00c9: 0x2026, # HORIZONTAL ELLIPSIS + 0x00ca: 0x0020, # SPACE + 0x00cb: 0x00c0, # LATIN CAPITAL LETTER A WITH GRAVE + 0x00cc: 0x00c3, # LATIN CAPITAL LETTER A WITH TILDE + 0x00cd: 0x00d5, # LATIN CAPITAL LETTER O WITH TILDE + 0x00ce: 0x0152, # LATIN CAPITAL LIGATURE OE + 0x00cf: 0x0153, # LATIN SMALL LIGATURE OE + 0x00d0: 0x2013, # EN DASH + 0x00d1: 0x2014, # EM DASH + 0x00d2: 0x201c, # LEFT DOUBLE QUOTATION MARK + 0x00d3: 0x201d, # RIGHT DOUBLE QUOTATION MARK + 0x00d4: 0x2018, # LEFT SINGLE QUOTATION MARK + 0x00d5: 0x2019, # RIGHT SINGLE QUOTATION MARK + 0x00d6: 0x00f7, # DIVISION SIGN + 0x00d7: None, # UNDEFINED + 0x00d8: 0x00ff, # LATIN SMALL LETTER Y WITH DIAERESIS + 0x00d9: 0x0178, # LATIN CAPITAL LETTER Y WITH DIAERESIS + 0x00da: 0x2044, # FRACTION SLASH + 0x00db: 0x00a4, # CURRENCY SIGN + 0x00dc: 0x2039, # SINGLE LEFT-POINTING ANGLE QUOTATION MARK + 0x00dd: 0x203a, # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK + 0x00de: 0xfb01, # LATIN SMALL LIGATURE FI + 0x00df: 0xfb02, # LATIN SMALL LIGATURE FL + 0x00e0: 0x2021, # DOUBLE DAGGER + 0x00e1: 0x00b7, # MIDDLE DOT + 0x00e2: 0x201a, # SINGLE LOW-9 QUOTATION MARK + 0x00e3: 0x201e, # DOUBLE LOW-9 QUOTATION MARK + 0x00e4: 0x2030, # PER MILLE SIGN + 0x00e5: 0x00c2, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX + 0x00e6: 0x00ca, # LATIN CAPITAL LETTER E WITH CIRCUMFLEX + 0x00e7: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE + 0x00e8: 0x00cb, # LATIN CAPITAL LETTER E WITH DIAERESIS + 0x00e9: 0x00c8, # LATIN CAPITAL LETTER E WITH GRAVE + 0x00ea: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE + 0x00eb: 0x00ce, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX + 0x00ec: 0x00cf, # LATIN CAPITAL LETTER I WITH DIAERESIS + 0x00ed: 0x00cc, # LATIN CAPITAL LETTER I WITH GRAVE + 0x00ee: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE + 0x00ef: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX + 0x00f0: None, # UNDEFINED + 0x00f1: 0x00d2, # LATIN CAPITAL LETTER O WITH GRAVE + 0x00f2: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE + 0x00f3: 0x00db, # LATIN CAPITAL LETTER U WITH CIRCUMFLEX + 0x00f4: 0x00d9, # LATIN CAPITAL LETTER U WITH GRAVE + 0x00f5: 0x0131, # LATIN SMALL LETTER DOTLESS I + 0x00f6: 0x02c6, # MODIFIER LETTER CIRCUMFLEX ACCENT + 0x00f7: 0x02dc, # SMALL TILDE + 0x00f8: 0x00af, # MACRON + 0x00f9: 0x02d8, # BREVE + 0x00fa: 0x02d9, # DOT ABOVE + 0x00fb: 0x02da, # RING ABOVE + 0x00fc: 0x00b8, # CEDILLA + 0x00fd: 0x02dd, # DOUBLE ACUTE ACCENT + 0x00fe: 0x02db, # OGONEK + 0x00ff: 0x02c7, # CARON + },None), + 'standard':StdCodecData({ + 0x0027: 0x2019, # RIGHT SINGLE QUOTATION MARK + 0x0060: 0x2018, # LEFT SINGLE QUOTATION MARK + 0x007f: None, # UNDEFINED + 0x0080: None, # UNDEFINED + 0x0081: None, # UNDEFINED + 0x0082: None, # UNDEFINED + 0x0083: None, # UNDEFINED + 0x0084: None, # UNDEFINED + 0x0085: None, # UNDEFINED + 0x0086: None, # UNDEFINED + 0x0087: None, # UNDEFINED + 0x0088: None, # UNDEFINED + 0x0089: None, # UNDEFINED + 0x008a: None, # UNDEFINED + 0x008b: None, # UNDEFINED + 0x008c: None, # UNDEFINED + 0x008d: None, # UNDEFINED + 0x008e: None, # UNDEFINED + 0x008f: None, # UNDEFINED + 0x0090: None, # UNDEFINED + 0x0091: None, # UNDEFINED + 0x0092: None, # UNDEFINED + 0x0093: None, # UNDEFINED + 0x0094: None, # UNDEFINED + 0x0095: None, # UNDEFINED + 0x0096: None, # UNDEFINED + 0x0097: None, # UNDEFINED + 0x0098: None, # UNDEFINED + 0x0099: None, # UNDEFINED + 0x009a: None, # UNDEFINED + 0x009b: None, # UNDEFINED + 0x009c: None, # UNDEFINED + 0x009d: None, # UNDEFINED + 0x009e: None, # UNDEFINED + 0x009f: None, # UNDEFINED + 0x00a0: None, # UNDEFINED + 0x00a4: 0x2044, # FRACTION SLASH + 0x00a6: 0x0192, # LATIN SMALL LETTER F WITH HOOK + 0x00a8: 0x00a4, # CURRENCY SIGN + 0x00a9: 0x0027, # APOSTROPHE + 0x00aa: 0x201c, # LEFT DOUBLE QUOTATION MARK + 0x00ac: 0x2039, # SINGLE LEFT-POINTING ANGLE QUOTATION MARK + 0x00ad: 0x203a, # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK + 0x00ae: 0xfb01, # LATIN SMALL LIGATURE FI + 0x00af: 0xfb02, # LATIN SMALL LIGATURE FL + 0x00b0: None, # UNDEFINED + 0x00b1: 0x2013, # EN DASH + 0x00b2: 0x2020, # DAGGER + 0x00b3: 0x2021, # DOUBLE DAGGER + 0x00b4: 0x00b7, # MIDDLE DOT + 0x00b5: None, # UNDEFINED + 0x00b7: 0x2022, # BULLET + 0x00b8: 0x201a, # SINGLE LOW-9 QUOTATION MARK + 0x00b9: 0x201e, # DOUBLE LOW-9 QUOTATION MARK + 0x00ba: 0x201d, # RIGHT DOUBLE QUOTATION MARK + 0x00bc: 0x2026, # HORIZONTAL ELLIPSIS + 0x00bd: 0x2030, # PER MILLE SIGN + 0x00be: None, # UNDEFINED + 0x00c0: None, # UNDEFINED + 0x00c1: 0x0060, # GRAVE ACCENT + 0x00c2: 0x00b4, # ACUTE ACCENT + 0x00c3: 0x02c6, # MODIFIER LETTER CIRCUMFLEX ACCENT + 0x00c4: 0x02dc, # SMALL TILDE + 0x00c5: 0x00af, # MACRON + 0x00c6: 0x02d8, # BREVE + 0x00c7: 0x02d9, # DOT ABOVE + 0x00c8: 0x00a8, # DIAERESIS + 0x00c9: None, # UNDEFINED + 0x00ca: 0x02da, # RING ABOVE + 0x00cb: 0x00b8, # CEDILLA + 0x00cc: None, # UNDEFINED + 0x00cd: 0x02dd, # DOUBLE ACUTE ACCENT + 0x00ce: 0x02db, # OGONEK + 0x00cf: 0x02c7, # CARON + 0x00d0: 0x2014, # EM DASH + 0x00d1: None, # UNDEFINED + 0x00d2: None, # UNDEFINED + 0x00d3: None, # UNDEFINED + 0x00d4: None, # UNDEFINED + 0x00d5: None, # UNDEFINED + 0x00d6: None, # UNDEFINED + 0x00d7: None, # UNDEFINED + 0x00d8: None, # UNDEFINED + 0x00d9: None, # UNDEFINED + 0x00da: None, # UNDEFINED + 0x00db: None, # UNDEFINED + 0x00dc: None, # UNDEFINED + 0x00dd: None, # UNDEFINED + 0x00de: None, # UNDEFINED + 0x00df: None, # UNDEFINED + 0x00e0: None, # UNDEFINED + 0x00e1: 0x00c6, # LATIN CAPITAL LETTER AE + 0x00e2: None, # UNDEFINED + 0x00e3: 0x00aa, # FEMININE ORDINAL INDICATOR + 0x00e4: None, # UNDEFINED + 0x00e5: None, # UNDEFINED + 0x00e6: None, # UNDEFINED + 0x00e7: None, # UNDEFINED + 0x00e8: 0x0141, # LATIN CAPITAL LETTER L WITH STROKE + 0x00e9: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE + 0x00ea: 0x0152, # LATIN CAPITAL LIGATURE OE + 0x00eb: 0x00ba, # MASCULINE ORDINAL INDICATOR + 0x00ec: None, # UNDEFINED + 0x00ed: None, # UNDEFINED + 0x00ee: None, # UNDEFINED + 0x00ef: None, # UNDEFINED + 0x00f0: None, # UNDEFINED + 0x00f1: 0x00e6, # LATIN SMALL LETTER AE + 0x00f2: None, # UNDEFINED + 0x00f3: None, # UNDEFINED + 0x00f4: None, # UNDEFINED + 0x00f5: 0x0131, # LATIN SMALL LETTER DOTLESS I + 0x00f6: None, # UNDEFINED + 0x00f7: None, # UNDEFINED + 0x00f8: 0x0142, # LATIN SMALL LETTER L WITH STROKE + 0x00f9: 0x00f8, # LATIN SMALL LETTER O WITH STROKE + 0x00fa: 0x0153, # LATIN SMALL LIGATURE OE + 0x00fb: 0x00df, # LATIN SMALL LETTER SHARP S + 0x00fc: None, # UNDEFINED + 0x00fd: None, # UNDEFINED + 0x00fe: None, # UNDEFINED + 0x00ff: None, # UNDEFINED + },None), + 'symbol':StdCodecData({ + 0x0022: 0x2200, # FOR ALL + 0x0024: 0x2203, # THERE EXISTS + 0x0027: 0x220b, # CONTAINS AS MEMBER + 0x002a: 0x2217, # ASTERISK OPERATOR + 0x002d: 0x2212, # MINUS SIGN + 0x0040: 0x2245, # APPROXIMATELY EQUAL TO + 0x0041: 0x0391, # GREEK CAPITAL LETTER ALPHA + 0x0042: 0x0392, # GREEK CAPITAL LETTER BETA + 0x0043: 0x03a7, # GREEK CAPITAL LETTER CHI + 0x0044: 0x2206, # INCREMENT + 0x0045: 0x0395, # GREEK CAPITAL LETTER EPSILON + 0x0046: 0x03a6, # GREEK CAPITAL LETTER PHI + 0x0047: 0x0393, # GREEK CAPITAL LETTER GAMMA + 0x0048: 0x0397, # GREEK CAPITAL LETTER ETA + 0x0049: 0x0399, # GREEK CAPITAL LETTER IOTA + 0x004a: 0x03d1, # GREEK THETA SYMBOL + 0x004b: 0x039a, # GREEK CAPITAL LETTER KAPPA + 0x004c: 0x039b, # GREEK CAPITAL LETTER LAMDA + 0x004d: 0x039c, # GREEK CAPITAL LETTER MU + 0x004e: 0x039d, # GREEK CAPITAL LETTER NU + 0x004f: 0x039f, # GREEK CAPITAL LETTER OMICRON + 0x0050: 0x03a0, # GREEK CAPITAL LETTER PI + 0x0051: 0x0398, # GREEK CAPITAL LETTER THETA + 0x0052: 0x03a1, # GREEK CAPITAL LETTER RHO + 0x0053: 0x03a3, # GREEK CAPITAL LETTER SIGMA + 0x0054: 0x03a4, # GREEK CAPITAL LETTER TAU + 0x0055: 0x03a5, # GREEK CAPITAL LETTER UPSILON + 0x0056: 0x03c2, # GREEK SMALL LETTER FINAL SIGMA + 0x0057: 0x2126, # OHM SIGN + 0x0058: 0x039e, # GREEK CAPITAL LETTER XI + 0x0059: 0x03a8, # GREEK CAPITAL LETTER PSI + 0x005a: 0x0396, # GREEK CAPITAL LETTER ZETA + 0x005c: 0x2234, # THEREFORE + 0x005e: 0x22a5, # UP TACK + 0x0060: 0xf8e5, # [unknown unicode name for radicalex] + 0x0061: 0x03b1, # GREEK SMALL LETTER ALPHA + 0x0062: 0x03b2, # GREEK SMALL LETTER BETA + 0x0063: 0x03c7, # GREEK SMALL LETTER CHI + 0x0064: 0x03b4, # GREEK SMALL LETTER DELTA + 0x0065: 0x03b5, # GREEK SMALL LETTER EPSILON + 0x0066: 0x03c6, # GREEK SMALL LETTER PHI + 0x0067: 0x03b3, # GREEK SMALL LETTER GAMMA + 0x0068: 0x03b7, # GREEK SMALL LETTER ETA + 0x0069: 0x03b9, # GREEK SMALL LETTER IOTA + 0x006a: 0x03d5, # GREEK PHI SYMBOL + 0x006b: 0x03ba, # GREEK SMALL LETTER KAPPA + 0x006c: 0x03bb, # GREEK SMALL LETTER LAMDA + 0x006d: 0x00b5, # MICRO SIGN + 0x006e: 0x03bd, # GREEK SMALL LETTER NU + 0x006f: 0x03bf, # GREEK SMALL LETTER OMICRON + 0x0070: 0x03c0, # GREEK SMALL LETTER PI + 0x0071: 0x03b8, # GREEK SMALL LETTER THETA + 0x0072: 0x03c1, # GREEK SMALL LETTER RHO + 0x0073: 0x03c3, # GREEK SMALL LETTER SIGMA + 0x0074: 0x03c4, # GREEK SMALL LETTER TAU + 0x0075: 0x03c5, # GREEK SMALL LETTER UPSILON + 0x0076: 0x03d6, # GREEK PI SYMBOL + 0x0077: 0x03c9, # GREEK SMALL LETTER OMEGA + 0x0078: 0x03be, # GREEK SMALL LETTER XI + 0x0079: 0x03c8, # GREEK SMALL LETTER PSI + 0x007a: 0x03b6, # GREEK SMALL LETTER ZETA + 0x007e: 0x223c, # TILDE OPERATOR + 0x007f: None, # UNDEFINED + 0x0080: None, # UNDEFINED + 0x0081: None, # UNDEFINED + 0x0082: None, # UNDEFINED + 0x0083: None, # UNDEFINED + 0x0084: None, # UNDEFINED + 0x0085: None, # UNDEFINED + 0x0086: None, # UNDEFINED + 0x0087: None, # UNDEFINED + 0x0088: None, # UNDEFINED + 0x0089: None, # UNDEFINED + 0x008a: None, # UNDEFINED + 0x008b: None, # UNDEFINED + 0x008c: None, # UNDEFINED + 0x008d: None, # UNDEFINED + 0x008e: None, # UNDEFINED + 0x008f: None, # UNDEFINED + 0x0090: None, # UNDEFINED + 0x0091: None, # UNDEFINED + 0x0092: None, # UNDEFINED + 0x0093: None, # UNDEFINED + 0x0094: None, # UNDEFINED + 0x0095: None, # UNDEFINED + 0x0096: None, # UNDEFINED + 0x0097: None, # UNDEFINED + 0x0098: None, # UNDEFINED + 0x0099: None, # UNDEFINED + 0x009a: None, # UNDEFINED + 0x009b: None, # UNDEFINED + 0x009c: None, # UNDEFINED + 0x009d: None, # UNDEFINED + 0x009e: None, # UNDEFINED + 0x009f: None, # UNDEFINED + 0x00a0: 0x20ac, # EURO SIGN + 0x00a1: 0x03d2, # GREEK UPSILON WITH HOOK SYMBOL + 0x00a2: 0x2032, # PRIME + 0x00a3: 0x2264, # LESS-THAN OR EQUAL TO + 0x00a4: 0x2044, # FRACTION SLASH + 0x00a5: 0x221e, # INFINITY + 0x00a6: 0x0192, # LATIN SMALL LETTER F WITH HOOK + 0x00a7: 0x2663, # BLACK CLUB SUIT + 0x00a8: 0x2666, # BLACK DIAMOND SUIT + 0x00a9: 0x2665, # BLACK HEART SUIT + 0x00aa: 0x2660, # BLACK SPADE SUIT + 0x00ab: 0x2194, # LEFT RIGHT ARROW + 0x00ac: 0x2190, # LEFTWARDS ARROW + 0x00ad: 0x2191, # UPWARDS ARROW + 0x00ae: 0x2192, # RIGHTWARDS ARROW + 0x00af: 0x2193, # DOWNWARDS ARROW + 0x00b2: 0x2033, # DOUBLE PRIME + 0x00b3: 0x2265, # GREATER-THAN OR EQUAL TO + 0x00b4: 0x00d7, # MULTIPLICATION SIGN + 0x00b5: 0x221d, # PROPORTIONAL TO + 0x00b6: 0x2202, # PARTIAL DIFFERENTIAL + 0x00b7: 0x2022, # BULLET + 0x00b8: 0x00f7, # DIVISION SIGN + 0x00b9: 0x2260, # NOT EQUAL TO + 0x00ba: 0x2261, # IDENTICAL TO + 0x00bb: 0x2248, # ALMOST EQUAL TO + 0x00bc: 0x2026, # HORIZONTAL ELLIPSIS + 0x00bd: 0xf8e6, # [unknown unicode name for arrowvertex] + 0x00be: 0xf8e7, # [unknown unicode name for arrowhorizex] + 0x00bf: 0x21b5, # DOWNWARDS ARROW WITH CORNER LEFTWARDS + 0x00c0: 0x2135, # ALEF SYMBOL + 0x00c1: 0x2111, # BLACK-LETTER CAPITAL I + 0x00c2: 0x211c, # BLACK-LETTER CAPITAL R + 0x00c3: 0x2118, # SCRIPT CAPITAL P + 0x00c4: 0x2297, # CIRCLED TIMES + 0x00c5: 0x2295, # CIRCLED PLUS + 0x00c6: 0x2205, # EMPTY SET + 0x00c7: 0x2229, # INTERSECTION + 0x00c8: 0x222a, # UNION + 0x00c9: 0x2283, # SUPERSET OF + 0x00ca: 0x2287, # SUPERSET OF OR EQUAL TO + 0x00cb: 0x2284, # NOT A SUBSET OF + 0x00cc: 0x2282, # SUBSET OF + 0x00cd: 0x2286, # SUBSET OF OR EQUAL TO + 0x00ce: 0x2208, # ELEMENT OF + 0x00cf: 0x2209, # NOT AN ELEMENT OF + 0x00d0: 0x2220, # ANGLE + 0x00d1: 0x2207, # NABLA + 0x00d2: 0xf6da, # [unknown unicode name for registerserif] + 0x00d3: 0xf6d9, # [unknown unicode name for copyrightserif] + 0x00d4: 0xf6db, # [unknown unicode name for trademarkserif] + 0x00d5: 0x220f, # N-ARY PRODUCT + 0x00d6: 0x221a, # SQUARE ROOT + 0x00d7: 0x22c5, # DOT OPERATOR + 0x00d8: 0x00ac, # NOT SIGN + 0x00d9: 0x2227, # LOGICAL AND + 0x00da: 0x2228, # LOGICAL OR + 0x00db: 0x21d4, # LEFT RIGHT DOUBLE ARROW + 0x00dc: 0x21d0, # LEFTWARDS DOUBLE ARROW + 0x00dd: 0x21d1, # UPWARDS DOUBLE ARROW + 0x00de: 0x21d2, # RIGHTWARDS DOUBLE ARROW + 0x00df: 0x21d3, # DOWNWARDS DOUBLE ARROW + 0x00e0: 0x25ca, # LOZENGE + 0x00e1: 0x2329, # LEFT-POINTING ANGLE BRACKET + 0x00e2: 0xf8e8, # [unknown unicode name for registersans] + 0x00e3: 0xf8e9, # [unknown unicode name for copyrightsans] + 0x00e4: 0xf8ea, # [unknown unicode name for trademarksans] + 0x00e5: 0x2211, # N-ARY SUMMATION + 0x00e6: 0xf8eb, # [unknown unicode name for parenlefttp] + 0x00e7: 0xf8ec, # [unknown unicode name for parenleftex] + 0x00e8: 0xf8ed, # [unknown unicode name for parenleftbt] + 0x00e9: 0xf8ee, # [unknown unicode name for bracketlefttp] + 0x00ea: 0xf8ef, # [unknown unicode name for bracketleftex] + 0x00eb: 0xf8f0, # [unknown unicode name for bracketleftbt] + 0x00ec: 0xf8f1, # [unknown unicode name for bracelefttp] + 0x00ed: 0xf8f2, # [unknown unicode name for braceleftmid] + 0x00ee: 0xf8f3, # [unknown unicode name for braceleftbt] + 0x00ef: 0xf8f4, # [unknown unicode name for braceex] + 0x00f0: None, # UNDEFINED + 0x00f1: 0x232a, # RIGHT-POINTING ANGLE BRACKET + 0x00f2: 0x222b, # INTEGRAL + 0x00f3: 0x2320, # TOP HALF INTEGRAL + 0x00f4: 0xf8f5, # [unknown unicode name for integralex] + 0x00f5: 0x2321, # BOTTOM HALF INTEGRAL + 0x00f6: 0xf8f6, # [unknown unicode name for parenrighttp] + 0x00f7: 0xf8f7, # [unknown unicode name for parenrightex] + 0x00f8: 0xf8f8, # [unknown unicode name for parenrightbt] + 0x00f9: 0xf8f9, # [unknown unicode name for bracketrighttp] + 0x00fa: 0xf8fa, # [unknown unicode name for bracketrightex] + 0x00fb: 0xf8fb, # [unknown unicode name for bracketrightbt] + 0x00fc: 0xf8fc, # [unknown unicode name for bracerighttp] + 0x00fd: 0xf8fd, # [unknown unicode name for bracerightmid] + 0x00fe: 0xf8fe, # [unknown unicode name for bracerightbt] + 0x00ff: None, # UNDEFINED + }, + { + 0x0394:0x0044, # GREEK CAPITAL LETTER DELTA + 0x03a9:0x0057, # GREEK CAPITAL LETTER OMEGA + 0x03bc:0x006d, # GREEK SMALL LETTER MU + } + ), + 'zapfdingbats':StdCodecData({ + 0x0021: 0x2701, # UPPER BLADE SCISSORS + 0x0022: 0x2702, # BLACK SCISSORS + 0x0023: 0x2703, # LOWER BLADE SCISSORS + 0x0024: 0x2704, # WHITE SCISSORS + 0x0025: 0x260e, # BLACK TELEPHONE + 0x0026: 0x2706, # TELEPHONE LOCATION SIGN + 0x0027: 0x2707, # TAPE DRIVE + 0x0028: 0x2708, # AIRPLANE + 0x0029: 0x2709, # ENVELOPE + 0x002a: 0x261b, # BLACK RIGHT POINTING INDEX + 0x002b: 0x261e, # WHITE RIGHT POINTING INDEX + 0x002c: 0x270c, # VICTORY HAND + 0x002d: 0x270d, # WRITING HAND + 0x002e: 0x270e, # LOWER RIGHT PENCIL + 0x002f: 0x270f, # PENCIL + 0x0030: 0x2710, # UPPER RIGHT PENCIL + 0x0031: 0x2711, # WHITE NIB + 0x0032: 0x2712, # BLACK NIB + 0x0033: 0x2713, # CHECK MARK + 0x0034: 0x2714, # HEAVY CHECK MARK + 0x0035: 0x2715, # MULTIPLICATION X + 0x0036: 0x2716, # HEAVY MULTIPLICATION X + 0x0037: 0x2717, # BALLOT X + 0x0038: 0x2718, # HEAVY BALLOT X + 0x0039: 0x2719, # OUTLINED GREEK CROSS + 0x003a: 0x271a, # HEAVY GREEK CROSS + 0x003b: 0x271b, # OPEN CENTRE CROSS + 0x003c: 0x271c, # HEAVY OPEN CENTRE CROSS + 0x003d: 0x271d, # LATIN CROSS + 0x003e: 0x271e, # SHADOWED WHITE LATIN CROSS + 0x003f: 0x271f, # OUTLINED LATIN CROSS + 0x0040: 0x2720, # MALTESE CROSS + 0x0041: 0x2721, # STAR OF DAVID + 0x0042: 0x2722, # FOUR TEARDROP-SPOKED ASTERISK + 0x0043: 0x2723, # FOUR BALLOON-SPOKED ASTERISK + 0x0044: 0x2724, # HEAVY FOUR BALLOON-SPOKED ASTERISK + 0x0045: 0x2725, # FOUR CLUB-SPOKED ASTERISK + 0x0046: 0x2726, # BLACK FOUR POINTED STAR + 0x0047: 0x2727, # WHITE FOUR POINTED STAR + 0x0048: 0x2605, # BLACK STAR + 0x0049: 0x2729, # STRESS OUTLINED WHITE STAR + 0x004a: 0x272a, # CIRCLED WHITE STAR + 0x004b: 0x272b, # OPEN CENTRE BLACK STAR + 0x004c: 0x272c, # BLACK CENTRE WHITE STAR + 0x004d: 0x272d, # OUTLINED BLACK STAR + 0x004e: 0x272e, # HEAVY OUTLINED BLACK STAR + 0x004f: 0x272f, # PINWHEEL STAR + 0x0050: 0x2730, # SHADOWED WHITE STAR + 0x0051: 0x2731, # HEAVY ASTERISK + 0x0052: 0x2732, # OPEN CENTRE ASTERISK + 0x0053: 0x2733, # EIGHT SPOKED ASTERISK + 0x0054: 0x2734, # EIGHT POINTED BLACK STAR + 0x0055: 0x2735, # EIGHT POINTED PINWHEEL STAR + 0x0056: 0x2736, # SIX POINTED BLACK STAR + 0x0057: 0x2737, # EIGHT POINTED RECTILINEAR BLACK STAR + 0x0058: 0x2738, # HEAVY EIGHT POINTED RECTILINEAR BLACK STAR + 0x0059: 0x2739, # TWELVE POINTED BLACK STAR + 0x005a: 0x273a, # SIXTEEN POINTED ASTERISK + 0x005b: 0x273b, # TEARDROP-SPOKED ASTERISK + 0x005c: 0x273c, # OPEN CENTRE TEARDROP-SPOKED ASTERISK + 0x005d: 0x273d, # HEAVY TEARDROP-SPOKED ASTERISK + 0x005e: 0x273e, # SIX PETALLED BLACK AND WHITE FLORETTE + 0x005f: 0x273f, # BLACK FLORETTE + 0x0060: 0x2740, # WHITE FLORETTE + 0x0061: 0x2741, # EIGHT PETALLED OUTLINED BLACK FLORETTE + 0x0062: 0x2742, # CIRCLED OPEN CENTRE EIGHT POINTED STAR + 0x0063: 0x2743, # HEAVY TEARDROP-SPOKED PINWHEEL ASTERISK + 0x0064: 0x2744, # SNOWFLAKE + 0x0065: 0x2745, # TIGHT TRIFOLIATE SNOWFLAKE + 0x0066: 0x2746, # HEAVY CHEVRON SNOWFLAKE + 0x0067: 0x2747, # SPARKLE + 0x0068: 0x2748, # HEAVY SPARKLE + 0x0069: 0x2749, # BALLOON-SPOKED ASTERISK + 0x006a: 0x274a, # EIGHT TEARDROP-SPOKED PROPELLER ASTERISK + 0x006b: 0x274b, # HEAVY EIGHT TEARDROP-SPOKED PROPELLER ASTERISK + 0x006c: 0x25cf, # BLACK CIRCLE + 0x006d: 0x274d, # SHADOWED WHITE CIRCLE + 0x006e: 0x25a0, # BLACK SQUARE + 0x006f: 0x274f, # LOWER RIGHT DROP-SHADOWED WHITE SQUARE + 0x0070: 0x2750, # UPPER RIGHT DROP-SHADOWED WHITE SQUARE + 0x0071: 0x2751, # LOWER RIGHT SHADOWED WHITE SQUARE + 0x0072: 0x2752, # UPPER RIGHT SHADOWED WHITE SQUARE + 0x0073: 0x25b2, # BLACK UP-POINTING TRIANGLE + 0x0074: 0x25bc, # BLACK DOWN-POINTING TRIANGLE + 0x0075: 0x25c6, # BLACK DIAMOND + 0x0076: 0x2756, # BLACK DIAMOND MINUS WHITE X + 0x0077: 0x25d7, # RIGHT HALF BLACK CIRCLE + 0x0078: 0x2758, # LIGHT VERTICAL BAR + 0x0079: 0x2759, # MEDIUM VERTICAL BAR + 0x007a: 0x275a, # HEAVY VERTICAL BAR + 0x007b: 0x275b, # HEAVY SINGLE TURNED COMMA QUOTATION MARK ORNAMENT + 0x007c: 0x275c, # HEAVY SINGLE COMMA QUOTATION MARK ORNAMENT + 0x007d: 0x275d, # HEAVY DOUBLE TURNED COMMA QUOTATION MARK ORNAMENT + 0x007e: 0x275e, # HEAVY DOUBLE COMMA QUOTATION MARK ORNAMENT + 0x007f: None, # UNDEFINED + 0x0080: 0x2768, # MEDIUM LEFT PARENTHESIS ORNAMENT + 0x0081: 0x2769, # MEDIUM RIGHT PARENTHESIS ORNAMENT + 0x0082: 0x276a, # MEDIUM FLATTENED LEFT PARENTHESIS ORNAMENT + 0x0083: 0x276b, # MEDIUM FLATTENED RIGHT PARENTHESIS ORNAMENT + 0x0084: 0x276c, # MEDIUM LEFT-POINTING ANGLE BRACKET ORNAMENT + 0x0085: 0x276d, # MEDIUM RIGHT-POINTING ANGLE BRACKET ORNAMENT + 0x0086: 0x276e, # HEAVY LEFT-POINTING ANGLE QUOTATION MARK ORNAMENT + 0x0087: 0x276f, # HEAVY RIGHT-POINTING ANGLE QUOTATION MARK ORNAMENT + 0x0088: 0x2770, # HEAVY LEFT-POINTING ANGLE BRACKET ORNAMENT + 0x0089: 0x2771, # HEAVY RIGHT-POINTING ANGLE BRACKET ORNAMENT + 0x008a: 0x2772, # LIGHT LEFT TORTOISE SHELL BRACKET ORNAMENT + 0x008b: 0x2773, # LIGHT RIGHT TORTOISE SHELL BRACKET ORNAMENT + 0x008c: 0x2774, # MEDIUM LEFT CURLY BRACKET ORNAMENT + 0x008d: 0x2775, # MEDIUM RIGHT CURLY BRACKET ORNAMENT + 0x008e: None, # UNDEFINED + 0x008f: None, # UNDEFINED + 0x0090: None, # UNDEFINED + 0x0091: None, # UNDEFINED + 0x0092: None, # UNDEFINED + 0x0093: None, # UNDEFINED + 0x0094: None, # UNDEFINED + 0x0095: None, # UNDEFINED + 0x0096: None, # UNDEFINED + 0x0097: None, # UNDEFINED + 0x0098: None, # UNDEFINED + 0x0099: None, # UNDEFINED + 0x009a: None, # UNDEFINED + 0x009b: None, # UNDEFINED + 0x009c: None, # UNDEFINED + 0x009d: None, # UNDEFINED + 0x009e: None, # UNDEFINED + 0x009f: None, # UNDEFINED + 0x00a0: None, # UNDEFINED + 0x00a1: 0x2761, # CURVED STEM PARAGRAPH SIGN ORNAMENT + 0x00a2: 0x2762, # HEAVY EXCLAMATION MARK ORNAMENT + 0x00a3: 0x2763, # HEAVY HEART EXCLAMATION MARK ORNAMENT + 0x00a4: 0x2764, # HEAVY BLACK HEART + 0x00a5: 0x2765, # ROTATED HEAVY BLACK HEART BULLET + 0x00a6: 0x2766, # FLORAL HEART + 0x00a7: 0x2767, # ROTATED FLORAL HEART BULLET + 0x00a8: 0x2663, # BLACK CLUB SUIT + 0x00a9: 0x2666, # BLACK DIAMOND SUIT + 0x00aa: 0x2665, # BLACK HEART SUIT + 0x00ab: 0x2660, # BLACK SPADE SUIT + 0x00ac: 0x2460, # CIRCLED DIGIT ONE + 0x00ad: 0x2461, # CIRCLED DIGIT TWO + 0x00ae: 0x2462, # CIRCLED DIGIT THREE + 0x00af: 0x2463, # CIRCLED DIGIT FOUR + 0x00b0: 0x2464, # CIRCLED DIGIT FIVE + 0x00b1: 0x2465, # CIRCLED DIGIT SIX + 0x00b2: 0x2466, # CIRCLED DIGIT SEVEN + 0x00b3: 0x2467, # CIRCLED DIGIT EIGHT + 0x00b4: 0x2468, # CIRCLED DIGIT NINE + 0x00b5: 0x2469, # CIRCLED NUMBER TEN + 0x00b6: 0x2776, # DINGBAT NEGATIVE CIRCLED DIGIT ONE + 0x00b7: 0x2777, # DINGBAT NEGATIVE CIRCLED DIGIT TWO + 0x00b8: 0x2778, # DINGBAT NEGATIVE CIRCLED DIGIT THREE + 0x00b9: 0x2779, # DINGBAT NEGATIVE CIRCLED DIGIT FOUR + 0x00ba: 0x277a, # DINGBAT NEGATIVE CIRCLED DIGIT FIVE + 0x00bb: 0x277b, # DINGBAT NEGATIVE CIRCLED DIGIT SIX + 0x00bc: 0x277c, # DINGBAT NEGATIVE CIRCLED DIGIT SEVEN + 0x00bd: 0x277d, # DINGBAT NEGATIVE CIRCLED DIGIT EIGHT + 0x00be: 0x277e, # DINGBAT NEGATIVE CIRCLED DIGIT NINE + 0x00bf: 0x277f, # DINGBAT NEGATIVE CIRCLED NUMBER TEN + 0x00c0: 0x2780, # DINGBAT CIRCLED SANS-SERIF DIGIT ONE + 0x00c1: 0x2781, # DINGBAT CIRCLED SANS-SERIF DIGIT TWO + 0x00c2: 0x2782, # DINGBAT CIRCLED SANS-SERIF DIGIT THREE + 0x00c3: 0x2783, # DINGBAT CIRCLED SANS-SERIF DIGIT FOUR + 0x00c4: 0x2784, # DINGBAT CIRCLED SANS-SERIF DIGIT FIVE + 0x00c5: 0x2785, # DINGBAT CIRCLED SANS-SERIF DIGIT SIX + 0x00c6: 0x2786, # DINGBAT CIRCLED SANS-SERIF DIGIT SEVEN + 0x00c7: 0x2787, # DINGBAT CIRCLED SANS-SERIF DIGIT EIGHT + 0x00c8: 0x2788, # DINGBAT CIRCLED SANS-SERIF DIGIT NINE + 0x00c9: 0x2789, # DINGBAT CIRCLED SANS-SERIF NUMBER TEN + 0x00ca: 0x278a, # DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT ONE + 0x00cb: 0x278b, # DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT TWO + 0x00cc: 0x278c, # DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT THREE + 0x00cd: 0x278d, # DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT FOUR + 0x00ce: 0x278e, # DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT FIVE + 0x00cf: 0x278f, # DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT SIX + 0x00d0: 0x2790, # DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT SEVEN + 0x00d1: 0x2791, # DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT EIGHT + 0x00d2: 0x2792, # DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT NINE + 0x00d3: 0x2793, # DINGBAT NEGATIVE CIRCLED SANS-SERIF NUMBER TEN + 0x00d4: 0x2794, # HEAVY WIDE-HEADED RIGHTWARDS ARROW + 0x00d5: 0x2192, # RIGHTWARDS ARROW + 0x00d6: 0x2194, # LEFT RIGHT ARROW + 0x00d7: 0x2195, # UP DOWN ARROW + 0x00d8: 0x2798, # HEAVY SOUTH EAST ARROW + 0x00d9: 0x2799, # HEAVY RIGHTWARDS ARROW + 0x00da: 0x279a, # HEAVY NORTH EAST ARROW + 0x00db: 0x279b, # DRAFTING POINT RIGHTWARDS ARROW + 0x00dc: 0x279c, # HEAVY ROUND-TIPPED RIGHTWARDS ARROW + 0x00dd: 0x279d, # TRIANGLE-HEADED RIGHTWARDS ARROW + 0x00de: 0x279e, # HEAVY TRIANGLE-HEADED RIGHTWARDS ARROW + 0x00df: 0x279f, # DASHED TRIANGLE-HEADED RIGHTWARDS ARROW + 0x00e0: 0x27a0, # HEAVY DASHED TRIANGLE-HEADED RIGHTWARDS ARROW + 0x00e1: 0x27a1, # BLACK RIGHTWARDS ARROW + 0x00e2: 0x27a2, # THREE-D TOP-LIGHTED RIGHTWARDS ARROWHEAD + 0x00e3: 0x27a3, # THREE-D BOTTOM-LIGHTED RIGHTWARDS ARROWHEAD + 0x00e4: 0x27a4, # BLACK RIGHTWARDS ARROWHEAD + 0x00e5: 0x27a5, # HEAVY BLACK CURVED DOWNWARDS AND RIGHTWARDS ARROW + 0x00e6: 0x27a6, # HEAVY BLACK CURVED UPWARDS AND RIGHTWARDS ARROW + 0x00e7: 0x27a7, # SQUAT BLACK RIGHTWARDS ARROW + 0x00e8: 0x27a8, # HEAVY CONCAVE-POINTED BLACK RIGHTWARDS ARROW + 0x00e9: 0x27a9, # RIGHT-SHADED WHITE RIGHTWARDS ARROW + 0x00ea: 0x27aa, # LEFT-SHADED WHITE RIGHTWARDS ARROW + 0x00eb: 0x27ab, # BACK-TILTED SHADOWED WHITE RIGHTWARDS ARROW + 0x00ec: 0x27ac, # FRONT-TILTED SHADOWED WHITE RIGHTWARDS ARROW + 0x00ed: 0x27ad, # HEAVY LOWER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW + 0x00ee: 0x27ae, # HEAVY UPPER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW + 0x00ef: 0x27af, # NOTCHED LOWER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW + 0x00f0: None, # UNDEFINED + 0x00f1: 0x27b1, # NOTCHED UPPER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW + 0x00f2: 0x27b2, # CIRCLED HEAVY WHITE RIGHTWARDS ARROW + 0x00f3: 0x27b3, # WHITE-FEATHERED RIGHTWARDS ARROW + 0x00f4: 0x27b4, # BLACK-FEATHERED SOUTH EAST ARROW + 0x00f5: 0x27b5, # BLACK-FEATHERED RIGHTWARDS ARROW + 0x00f6: 0x27b6, # BLACK-FEATHERED NORTH EAST ARROW + 0x00f7: 0x27b7, # HEAVY BLACK-FEATHERED SOUTH EAST ARROW + 0x00f8: 0x27b8, # HEAVY BLACK-FEATHERED RIGHTWARDS ARROW + 0x00f9: 0x27b9, # HEAVY BLACK-FEATHERED NORTH EAST ARROW + 0x00fa: 0x27ba, # TEARDROP-BARBED RIGHTWARDS ARROW + 0x00fb: 0x27bb, # HEAVY TEARDROP-SHANKED RIGHTWARDS ARROW + 0x00fc: 0x27bc, # WEDGE-TAILED RIGHTWARDS ARROW + 0x00fd: 0x27bd, # HEAVY WEDGE-TAILED RIGHTWARDS ARROW + 0x00fe: 0x27be, # OPEN-OUTLINED RIGHTWARDS ARROW + 0x00ff: None, # UNDEFINED + },None), + 'pdfdoc':StdCodecData({ + #compatibility with pike pdf + 0x0000: 0x0000, #(NULL) U + 0x0001: 0x0001, #(START OF HEADING) U + 0x0002: 0x0002, #(START OF TEXT) U + 0x0003: 0x0003, #(END OF TEXT) U + 0x0004: 0x0004, #(END OF TEXT) U + 0x0005: 0x0005, #(END OF TRANSMISSION) U + 0x0006: 0x0006, #(ACKNOWLEDGE) U + 0x0007: 0x0007, #(BELL) U + 0x0008: 0x0008, #(BACKSPACE) U + 0x000B: 0x000B, #(LINE TABULATION) U + 0x000C: 0x000C, #(FORM FEED) U + 0x000E: 0x000E, #(SHIFT OUT) U + 0x000F: 0x000F, #(SHIFT IN) U + 0x0010: 0x0010, #(DATA LINK ESCAPE) U + 0x0011: 0x0011, #(DEVICE CONTROL ONE) U + 0x0012: 0x0012, #(DEVICE CONTROL TWO) U + 0x0013: 0x0013, #(DEVICE CONTROL THREE) U + 0x0014: 0x0014, #(DEVICE CONTROL FOUR) U + 0x0015: 0x0015, #(NEGATIVE ACKNOWLEDGE) U + 0x0016: 0x0016, #was a typo U+0017 in in PDF SPEC U + 0x0017: 0x0017, #(END OF TRANSMISSION BLOCK) U + 0x007f: 0x007f, # delete pdf spec UNDEFINED + 0x009f: 0x009f, # application program command APC pdf spec UNDEFINED + 0x00ad: 0x00ad, # soft hyphen spec UNDEFINED + + #properly defined by the pdf spec + 0x0009: 0x0009, #(CHARACTER TABULATION) SR + 0x000A: 0x000A, #(LINE FEED) SR + 0x000D: 0x000D, #(CARRIAGE RETURN) SR + 0x0080: 0x2022, # BULLET + 0x0081: 0x2020, # DAGGER + 0x0082: 0x2021, # DOUBLE DAGGER + 0x0083: 0x2026, # HORIZONTAL ELLIPSIS + 0x0084: 0x2014, # EM DASH + 0x0085: 0x2013, # EN DASH + 0x0086: 0x0192, # LATIN SMALL LETTER F WITH HOOK + 0x0087: 0x2044, # FRACTION SLASH + 0x0088: 0x2039, # SINGLE LEFT-POINTING ANGLE QUOTATION MARK + 0x0089: 0x203a, # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK + 0x008a: 0x2212, # MINUS SIGN + 0x008b: 0x2030, # PER MILLE SIGN + 0x008c: 0x201e, # DOUBLE LOW-9 QUOTATION MARK + 0x008d: 0x201c, # LEFT DOUBLE QUOTATION MARK + 0x008e: 0x201d, # RIGHT DOUBLE QUOTATION MARK + 0x008f: 0x2018, # LEFT SINGLE QUOTATION MARK + 0x0090: 0x2019, # RIGHT SINGLE QUOTATION MARK + 0x0091: 0x201a, # SINGLE LOW-9 QUOTATION MARK + 0x0092: 0x2122, # TRADE MARK SIGN + 0x0093: 0xfb01, # LATIN SMALL LIGATURE FI + 0x0094: 0xfb02, # LATIN SMALL LIGATURE FL + 0x0095: 0x0141, # LATIN CAPITAL LETTER L WITH STROKE + 0x0096: 0x0152, # LATIN CAPITAL LIGATURE OE + 0x0097: 0x0160, # LATIN CAPITAL LETTER S WITH CARON + 0x0098: 0x0178, # LATIN CAPITAL LETTER Y WITH DIAERESIS + 0x0099: 0x017d, # LATIN CAPITAL LETTER Z WITH CARON + 0x009a: 0x0131, # LATIN SMALL LETTER DOTLESS I + 0x009b: 0x0142, # LATIN SMALL LETTER L WITH STROKE + 0x009c: 0x0153, # LATIN SMALL LIGATURE OE + 0x009d: 0x0161, # LATIN SMALL LETTER S WITH CARON + 0x009e: 0x017e, # LATIN SMALL LETTER Z WITH CARON + 0x00a0: 0x20ac, # EURO SIGN + 24: 0x02d8, #breve + 25: 0x02c7, #caron + 26: 0x02c6, #circumflex + 27: 0x02d9, #dotaccent + 28: 0x02dd, #hungarumlaut + 29: 0x02db, #ogonek + 30: 0x02da, #ring + 31: 0x02dc, #tilde + },None), + 'macexpert':StdCodecData({ + 0x0021: 0xf721, # [unknown unicode name for exclamsmall] + 0x0022: 0xf6f8, # [unknown unicode name for Hungarumlautsmall] + 0x0023: 0xf7a2, # [unknown unicode name for centoldstyle] + 0x0024: 0xf724, # [unknown unicode name for dollaroldstyle] + 0x0025: 0xf6e4, # [unknown unicode name for dollarsuperior] + 0x0026: 0xf726, # [unknown unicode name for ampersandsmall] + 0x0027: 0xf7b4, # [unknown unicode name for Acutesmall] + 0x0028: 0x207d, # SUPERSCRIPT LEFT PARENTHESIS + 0x0029: 0x207e, # SUPERSCRIPT RIGHT PARENTHESIS + 0x002a: 0x2025, # TWO DOT LEADER + 0x002b: 0x2024, # ONE DOT LEADER + 0x002f: 0x2044, # FRACTION SLASH + 0x0030: 0xf730, # [unknown unicode name for zerooldstyle] + 0x0031: 0xf731, # [unknown unicode name for oneoldstyle] + 0x0032: 0xf732, # [unknown unicode name for twooldstyle] + 0x0033: 0xf733, # [unknown unicode name for threeoldstyle] + 0x0034: 0xf734, # [unknown unicode name for fouroldstyle] + 0x0035: 0xf735, # [unknown unicode name for fiveoldstyle] + 0x0036: 0xf736, # [unknown unicode name for sixoldstyle] + 0x0037: 0xf737, # [unknown unicode name for sevenoldstyle] + 0x0038: 0xf738, # [unknown unicode name for eightoldstyle] + 0x0039: 0xf739, # [unknown unicode name for nineoldstyle] + 0x003c: None, # UNDEFINED + 0x003d: 0xf6de, # [unknown unicode name for threequartersemdash] + 0x003e: None, # UNDEFINED + 0x003f: 0xf73f, # [unknown unicode name for questionsmall] + 0x0040: None, # UNDEFINED + 0x0041: None, # UNDEFINED + 0x0042: None, # UNDEFINED + 0x0043: None, # UNDEFINED + 0x0044: 0xf7f0, # [unknown unicode name for Ethsmall] + 0x0045: None, # UNDEFINED + 0x0046: None, # UNDEFINED + 0x0047: 0x00bc, # VULGAR FRACTION ONE QUARTER + 0x0048: 0x00bd, # VULGAR FRACTION ONE HALF + 0x0049: 0x00be, # VULGAR FRACTION THREE QUARTERS + 0x004a: 0x215b, # VULGAR FRACTION ONE EIGHTH + 0x004b: 0x215c, # VULGAR FRACTION THREE EIGHTHS + 0x004c: 0x215d, # VULGAR FRACTION FIVE EIGHTHS + 0x004d: 0x215e, # VULGAR FRACTION SEVEN EIGHTHS + 0x004e: 0x2153, # VULGAR FRACTION ONE THIRD + 0x004f: 0x2154, # VULGAR FRACTION TWO THIRDS + 0x0050: None, # UNDEFINED + 0x0051: None, # UNDEFINED + 0x0052: None, # UNDEFINED + 0x0053: None, # UNDEFINED + 0x0054: None, # UNDEFINED + 0x0055: None, # UNDEFINED + 0x0056: 0xfb00, # LATIN SMALL LIGATURE FF + 0x0057: 0xfb01, # LATIN SMALL LIGATURE FI + 0x0058: 0xfb02, # LATIN SMALL LIGATURE FL + 0x0059: 0xfb03, # LATIN SMALL LIGATURE FFI + 0x005a: 0xfb04, # LATIN SMALL LIGATURE FFL + 0x005b: 0x208d, # SUBSCRIPT LEFT PARENTHESIS + 0x005c: None, # UNDEFINED + 0x005d: 0x208e, # SUBSCRIPT RIGHT PARENTHESIS + 0x005e: 0xf6f6, # [unknown unicode name for Circumflexsmall] + 0x005f: 0xf6e5, # [unknown unicode name for hypheninferior] + 0x0060: 0xf760, # [unknown unicode name for Gravesmall] + 0x0061: 0xf761, # [unknown unicode name for Asmall] + 0x0062: 0xf762, # [unknown unicode name for Bsmall] + 0x0063: 0xf763, # [unknown unicode name for Csmall] + 0x0064: 0xf764, # [unknown unicode name for Dsmall] + 0x0065: 0xf765, # [unknown unicode name for Esmall] + 0x0066: 0xf766, # [unknown unicode name for Fsmall] + 0x0067: 0xf767, # [unknown unicode name for Gsmall] + 0x0068: 0xf768, # [unknown unicode name for Hsmall] + 0x0069: 0xf769, # [unknown unicode name for Ismall] + 0x006a: 0xf76a, # [unknown unicode name for Jsmall] + 0x006b: 0xf76b, # [unknown unicode name for Ksmall] + 0x006c: 0xf76c, # [unknown unicode name for Lsmall] + 0x006d: 0xf76d, # [unknown unicode name for Msmall] + 0x006e: 0xf76e, # [unknown unicode name for Nsmall] + 0x006f: 0xf76f, # [unknown unicode name for Osmall] + 0x0070: 0xf770, # [unknown unicode name for Psmall] + 0x0071: 0xf771, # [unknown unicode name for Qsmall] + 0x0072: 0xf772, # [unknown unicode name for Rsmall] + 0x0073: 0xf773, # [unknown unicode name for Ssmall] + 0x0074: 0xf774, # [unknown unicode name for Tsmall] + 0x0075: 0xf775, # [unknown unicode name for Usmall] + 0x0076: 0xf776, # [unknown unicode name for Vsmall] + 0x0077: 0xf777, # [unknown unicode name for Wsmall] + 0x0078: 0xf778, # [unknown unicode name for Xsmall] + 0x0079: 0xf779, # [unknown unicode name for Ysmall] + 0x007a: 0xf77a, # [unknown unicode name for Zsmall] + 0x007b: 0x20a1, # COLON SIGN + 0x007c: 0xf6dc, # [unknown unicode name for onefitted] + 0x007d: 0xf6dd, # [unknown unicode name for rupiah] + 0x007e: 0xf6fe, # [unknown unicode name for Tildesmall] + 0x007f: None, # UNDEFINED + 0x0080: None, # UNDEFINED + 0x0081: 0xf6e9, # [unknown unicode name for asuperior] + 0x0082: 0xf6e0, # [unknown unicode name for centsuperior] + 0x0083: None, # UNDEFINED + 0x0084: None, # UNDEFINED + 0x0085: None, # UNDEFINED + 0x0086: None, # UNDEFINED + 0x0087: 0xf7e1, # [unknown unicode name for Aacutesmall] + 0x0088: 0xf7e0, # [unknown unicode name for Agravesmall] + 0x0089: 0xf7e2, # [unknown unicode name for Acircumflexsmall] + 0x008a: 0xf7e4, # [unknown unicode name for Adieresissmall] + 0x008b: 0xf7e3, # [unknown unicode name for Atildesmall] + 0x008c: 0xf7e5, # [unknown unicode name for Aringsmall] + 0x008d: 0xf7e7, # [unknown unicode name for Ccedillasmall] + 0x008e: 0xf7e9, # [unknown unicode name for Eacutesmall] + 0x008f: 0xf7e8, # [unknown unicode name for Egravesmall] + 0x0090: 0xf7ea, # [unknown unicode name for Ecircumflexsmall] + 0x0091: 0xf7eb, # [unknown unicode name for Edieresissmall] + 0x0092: 0xf7ed, # [unknown unicode name for Iacutesmall] + 0x0093: 0xf7ec, # [unknown unicode name for Igravesmall] + 0x0094: 0xf7ee, # [unknown unicode name for Icircumflexsmall] + 0x0095: 0xf7ef, # [unknown unicode name for Idieresissmall] + 0x0096: 0xf7f1, # [unknown unicode name for Ntildesmall] + 0x0097: 0xf7f3, # [unknown unicode name for Oacutesmall] + 0x0098: 0xf7f2, # [unknown unicode name for Ogravesmall] + 0x0099: 0xf7f4, # [unknown unicode name for Ocircumflexsmall] + 0x009a: 0xf7f6, # [unknown unicode name for Odieresissmall] + 0x009b: 0xf7f5, # [unknown unicode name for Otildesmall] + 0x009c: 0xf7fa, # [unknown unicode name for Uacutesmall] + 0x009d: 0xf7f9, # [unknown unicode name for Ugravesmall] + 0x009e: 0xf7fb, # [unknown unicode name for Ucircumflexsmall] + 0x009f: 0xf7fc, # [unknown unicode name for Udieresissmall] + 0x00a0: None, # UNDEFINED + 0x00a1: 0x2078, # SUPERSCRIPT EIGHT + 0x00a2: 0x2084, # SUBSCRIPT FOUR + 0x00a3: 0x2083, # SUBSCRIPT THREE + 0x00a4: 0x2086, # SUBSCRIPT SIX + 0x00a5: 0x2088, # SUBSCRIPT EIGHT + 0x00a6: 0x2087, # SUBSCRIPT SEVEN + 0x00a7: 0xf6fd, # [unknown unicode name for Scaronsmall] + 0x00a8: None, # UNDEFINED + 0x00a9: 0xf6df, # [unknown unicode name for centinferior] + 0x00aa: 0x2082, # SUBSCRIPT TWO + 0x00ab: None, # UNDEFINED + 0x00ac: 0xf7a8, # [unknown unicode name for Dieresissmall] + 0x00ad: None, # UNDEFINED + 0x00ae: 0xf6f5, # [unknown unicode name for Caronsmall] + 0x00af: 0xf6f0, # [unknown unicode name for osuperior] + 0x00b0: 0x2085, # SUBSCRIPT FIVE + 0x00b1: None, # UNDEFINED + 0x00b2: 0xf6e1, # [unknown unicode name for commainferior] + 0x00b3: 0xf6e7, # [unknown unicode name for periodinferior] + 0x00b4: 0xf7fd, # [unknown unicode name for Yacutesmall] + 0x00b5: None, # UNDEFINED + 0x00b6: 0xf6e3, # [unknown unicode name for dollarinferior] + 0x00b7: None, # UNDEFINED + 0x00b8: None, # UNDEFINED + 0x00b9: 0xf7fe, # [unknown unicode name for Thornsmall] + 0x00ba: None, # UNDEFINED + 0x00bb: 0x2089, # SUBSCRIPT NINE + 0x00bc: 0x2080, # SUBSCRIPT ZERO + 0x00bd: 0xf6ff, # [unknown unicode name for Zcaronsmall] + 0x00be: 0xf7e6, # [unknown unicode name for AEsmall] + 0x00bf: 0xf7f8, # [unknown unicode name for Oslashsmall] + 0x00c0: 0xf7bf, # [unknown unicode name for questiondownsmall] + 0x00c1: 0x2081, # SUBSCRIPT ONE + 0x00c2: 0xf6f9, # [unknown unicode name for Lslashsmall] + 0x00c3: None, # UNDEFINED + 0x00c4: None, # UNDEFINED + 0x00c5: None, # UNDEFINED + 0x00c6: None, # UNDEFINED + 0x00c7: None, # UNDEFINED + 0x00c8: None, # UNDEFINED + 0x00c9: 0xf7b8, # [unknown unicode name for Cedillasmall] + 0x00ca: None, # UNDEFINED + 0x00cb: None, # UNDEFINED + 0x00cc: None, # UNDEFINED + 0x00cd: None, # UNDEFINED + 0x00ce: None, # UNDEFINED + 0x00cf: 0xf6fa, # [unknown unicode name for OEsmall] + 0x00d0: 0x2012, # FIGURE DASH + 0x00d1: 0xf6e6, # [unknown unicode name for hyphensuperior] + 0x00d2: None, # UNDEFINED + 0x00d3: None, # UNDEFINED + 0x00d4: None, # UNDEFINED + 0x00d5: None, # UNDEFINED + 0x00d6: 0xf7a1, # [unknown unicode name for exclamdownsmall] + 0x00d7: None, # UNDEFINED + 0x00d8: 0xf7ff, # [unknown unicode name for Ydieresissmall] + 0x00d9: None, # UNDEFINED + 0x00da: 0x00b9, # SUPERSCRIPT ONE + 0x00db: 0x00b2, # SUPERSCRIPT TWO + 0x00dc: 0x00b3, # SUPERSCRIPT THREE + 0x00dd: 0x2074, # SUPERSCRIPT FOUR + 0x00de: 0x2075, # SUPERSCRIPT FIVE + 0x00df: 0x2076, # SUPERSCRIPT SIX + 0x00e0: 0x2077, # SUPERSCRIPT SEVEN + 0x00e1: 0x2079, # SUPERSCRIPT NINE + 0x00e2: 0x2070, # SUPERSCRIPT ZERO + 0x00e3: None, # UNDEFINED + 0x00e4: 0xf6ec, # [unknown unicode name for esuperior] + 0x00e5: 0xf6f1, # [unknown unicode name for rsuperior] + 0x00e6: 0xf6f3, # [unknown unicode name for tsuperior] + 0x00e7: None, # UNDEFINED + 0x00e8: None, # UNDEFINED + 0x00e9: 0xf6ed, # [unknown unicode name for isuperior] + 0x00ea: 0xf6f2, # [unknown unicode name for ssuperior] + 0x00eb: 0xf6eb, # [unknown unicode name for dsuperior] + 0x00ec: None, # UNDEFINED + 0x00ed: None, # UNDEFINED + 0x00ee: None, # UNDEFINED + 0x00ef: None, # UNDEFINED + 0x00f0: None, # UNDEFINED + 0x00f1: 0xf6ee, # [unknown unicode name for lsuperior] + 0x00f2: 0xf6fb, # [unknown unicode name for Ogoneksmall] + 0x00f3: 0xf6f4, # [unknown unicode name for Brevesmall] + 0x00f4: 0xf7af, # [unknown unicode name for Macronsmall] + 0x00f5: 0xf6ea, # [unknown unicode name for bsuperior] + 0x00f6: 0x207f, # SUPERSCRIPT LATIN SMALL LETTER N + 0x00f7: 0xf6ef, # [unknown unicode name for msuperior] + 0x00f8: 0xf6e2, # [unknown unicode name for commasuperior] + 0x00f9: 0xf6e8, # [unknown unicode name for periodsuperior] + 0x00fa: 0xf6f7, # [unknown unicode name for Dotaccentsmall] + 0x00fb: 0xf6fc, # [unknown unicode name for Ringsmall] + 0x00fc: None, # UNDEFINED + 0x00fd: None, # UNDEFINED + 0x00fe: None, # UNDEFINED + 0x00ff: None, # UNDEFINED + },None), + } + __rl_extension_codecs = { + 'extpdfdoc':ExtCodecData('pdfdoc',None,None), + } + #for k,v in __rl_codecs_data.items(): + # __rl_codecs_data[k+'enc'] = __rl_codecs_data[k+'encoding'] = v + #del k,v + + __rl_dynamic_codecs = [] + + def __init__(self): + raise NotImplementedError + + @staticmethod + def _makeCodecInfo(name,encoding_map,decoding_map): + ### Codec APIs + class Codec(codecs.Codec): + def encode(self,input,errors='strict',charmap_encode=codecs.charmap_encode,encoding_map=encoding_map): + return charmap_encode(input,errors,encoding_map) + + def decode(self,input,errors='strict',charmap_decode=codecs.charmap_decode,decoding_map=decoding_map): + return charmap_decode(input,errors,decoding_map) + + class StreamWriter(Codec,codecs.StreamWriter): + pass + + class StreamReader(Codec,codecs.StreamReader): + pass + C = Codec() + return codecs.CodecInfo(C.encode,C.decode,streamreader=StreamReader,streamwriter=StreamWriter,name=name) + + @staticmethod + def _256_exception_codec(name,exceptions,rexceptions,baseRange=range(32,256)): + decoding_map = codecs.make_identity_dict(baseRange) + decoding_map.update(exceptions) + encoding_map = codecs.make_encoding_map(decoding_map) + if rexceptions: encoding_map.update(rexceptions) + return RL_Codecs._makeCodecInfo(name,encoding_map,decoding_map) + + __rl_codecs_cache = {} + + @staticmethod + def __rl_codecs(name,cache=__rl_codecs_cache,data=__rl_codecs_data,extension_codecs=__rl_extension_codecs,_256=True): + try: + return cache[name] + except KeyError: + if name in extension_codecs: + x = extension_codecs[name] + e,r = data[x.baseName] + if x.exceptions: + if e: + e = e.copy() + e.update(x.exceptions) + else: + e = x.exceptions + if x.rexceptions: + if r: + r = r.copy() + r.update(x.rexceptions) + else: + r = x.exceptions + else: + e,r = data[name] + cache[name] = c = RL_Codecs._256_exception_codec(name,e,r) if _256 else RL_Codecs._makeCodecInfo(name, e,r or {}) + return c + + @staticmethod + def _rl_codecs(name): + name = name.lower() + from reportlab.pdfbase.pdfmetrics import standardEncodings + for e in standardEncodings+('ExtPdfdocEncoding',): + e = e[:-8].lower() + if name.startswith(e): return RL_Codecs.__rl_codecs(e) + if name in RL_Codecs.__rl_dynamic_codecs: + return RL_Codecs.__rl_codecs(name,_256=False) + return None + + @staticmethod + def register(): + codecs.register(RL_Codecs._rl_codecs) + + @staticmethod + def add_dynamic_codec(name,exceptions,rexceptions): + name = name.lower() + RL_Codecs.remove_dynamic_codec(name) + RL_Codecs.__rl_codecs_data[name] = (exceptions,rexceptions) + RL_Codecs.__rl_dynamic_codecs.append(name) + + @staticmethod + def remove_dynamic_codec(name): + name = name.lower() + if name in RL_Codecs.__rl_dynamic_codecs: + RL_Codecs.__rl_codecs_data.pop(name,None) + RL_Codecs.__rl_codecs_cache.pop(name,None) + RL_Codecs.__rl_dynamic_codecs.remove(name) + + @staticmethod + def reset_dynamic_codecs(): + map(RL_Codecs.remove_dynamic_codec, RL_Codecs.__rl_dynamic_codecs) diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfbase/ttfonts.py b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/ttfonts.py new file mode 100644 index 0000000000000000000000000000000000000000..eccd3d28b44db5ba0a17e553dbc261994b14fb9a --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfbase/ttfonts.py @@ -0,0 +1,1565 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +__version__ = '$Id$' +__doc__="""TrueType font support + +This defines classes to represent TrueType fonts. They know how to calculate +their own width and how to write themselves into PDF files. They support +subsetting and embedding and can represent all 16-bit Unicode characters. + +Note on dynamic fonts +--------------------- + +Usually a Font in ReportLab corresponds to a fixed set of PDF objects (Font, +FontDescriptor, Encoding). But with dynamic font subsetting a single TTFont +will result in a number of Font/FontDescriptor/Encoding object sets, and the +contents of those will depend on the actual characters used for printing. + +To support dynamic font subsetting a concept of "dynamic font" was introduced. +Dynamic Fonts have a _dynamicFont attribute set to 1. + +Dynamic fonts have the following additional functions:: + + def splitString(self, text, doc): + '''Splits text into a number of chunks, each of which belongs to a + single subset. Returns a list of tuples (subset, string). Use + subset numbers with getSubsetInternalName. Doc is used to identify + a document so that different documents may have different dynamically + constructed subsets.''' + + def getSubsetInternalName(self, subset, doc): + '''Returns the name of a PDF Font object corresponding to a given + subset of this dynamic font. Use this function instead of + PDFDocument.getInternalFontName.''' + +You must never call PDFDocument.getInternalFontName for dynamic fonts. + +If you have a traditional static font, mapping to PDF text output operators +is simple:: + + '%s 14 Tf (%s) Tj' % (getInternalFontName(psfontname), text) + +If you have a dynamic font, use this instead:: + + for subset, chunk in font.splitString(text, doc): + '%s 14 Tf (%s) Tj' % (font.getSubsetInternalName(subset, doc), chunk) + +(Tf is a font setting operator and Tj is a text ouput operator. You should +also escape invalid characters in Tj argument, see TextObject._formatText. +Oh, and that 14 up there is font size.) + +Canvas and TextObject have special support for dynamic fonts. +""" + +from struct import pack, unpack, error as structError +from fnmatch import fnmatch +from reportlab.lib.utils import bytestr, isUnicode, char2int, isStr, isBytes +from reportlab.lib.abag import ABag +from reportlab.pdfbase import pdfmetrics, pdfdoc +from reportlab import rl_config +from reportlab.lib.rl_accel import hex32, add32, calcChecksum, instanceStringWidthTTF, fp_str +from reportlab.rl_config import register_reset, unShapedFontGlob +from collections import namedtuple +from io import BytesIO +import os, time, functools + +try: + import uharfbuzz +except: + uharfbuzz = None + +class TTFError(pdfdoc.PDFError): + "TrueType font exception" + pass + +def SUBSETN(n,table=bytes.maketrans(b'0123456789',b'ABCDEFGIJK')): + return bytes('%6.6d'%n,'ASCII').translate(table) +# +# Helpers +# +def makeToUnicodeCMap(fontname, subset): + """Creates a ToUnicode CMap for a given subset. See Adobe + _PDF_Reference (ISBN 0-201-75839-3) for more information.""" + cmap = [ + "/CIDInit /ProcSet findresource begin", + "12 dict begin", + "begincmap", + "/CIDSystemInfo", + "<< /Registry (%s)" % fontname, + "/Ordering (%s)" % fontname, + "/Supplement 0", + ">> def", + "/CMapName /%s def" % fontname, + "/CMapType 2 def", + "1 begincodespacerange", + "<00> <%02X>" % (len(subset) - 1), + "endcodespacerange", + "%d beginbfchar" % len(subset) + ] + ["<%02X> <%04X>" % (i,v) for i,v in enumerate(subset)] + [ + "endbfchar", + "endcmap", + "CMapName currentdict /CMap defineresource pop", + "end", + "end" + ] + return '\n'.join(cmap) + +def splice(stream, offset, value): + """Splices the given value into stream at the given offset and + returns the resulting stream (the original is unchanged)""" + return stream[:offset] + value + stream[offset + len(value):] + +def _set_ushort(stream, offset, value): + """Writes the given unsigned short value into stream at the given + offset and returns the resulting stream (the original is unchanged)""" + return splice(stream, offset, pack(">H", value)) +# +# TrueType font handling +# + +GF_ARG_1_AND_2_ARE_WORDS = 1 << 0 +GF_ARGS_ARE_XY_VALUES = 1 << 1 +GF_ROUND_XY_TO_GRID = 1 << 2 +GF_WE_HAVE_A_SCALE = 1 << 3 +GF_RESERVED = 1 << 4 +GF_MORE_COMPONENTS = 1 << 5 +GF_WE_HAVE_AN_X_AND_Y_SCALE = 1 << 6 +GF_WE_HAVE_A_TWO_BY_TWO = 1 << 7 +GF_WE_HAVE_INSTRUCTIONS = 1 << 8 +GF_USE_MY_METRICS = 1 << 9 +GF_OVERLAP_COMPOUND = 1 << 10 +GF_SCALED_COMPONENT_OFFSET = 1 << 11 +GF_UNSCALED_COMPONENT_OFFSET = 1 << 12 + + +_cached_ttf_dirs={} +def _ttf_dirs(*roots): + R = _cached_ttf_dirs.get(roots,None) + if R is None: + join = os.path.join + realpath = os.path.realpath + R = [] + aR = R.append + for root in roots: + for r, d, f in os.walk(root,followlinks=True): + s = realpath(r) + if s not in R: aR(s) + for s in d: + s = realpath(join(r,s)) + if s not in R: aR(s) + _cached_ttf_dirs[roots] = R + return R + +def TTFOpenFile(fn): + '''Opens a TTF file possibly after searching TTFSearchPath + returns (filename,file) + ''' + from reportlab.lib.utils import rl_isfile, open_for_read + try: + f = open_for_read(fn,'rb') + return fn, f + except IOError: + import os + if not os.path.isabs(fn): + for D in _ttf_dirs(*rl_config.TTFSearchPath): + tfn = os.path.join(D,fn) + if rl_isfile(tfn): + f = open_for_read(tfn,'rb') + return tfn, f + raise TTFError('Can\'t open file "%s"' % fn) + +class TTFontParser: + "Basic TTF file parser" + ttfVersions = (0x00010000,0x74727565,0x74746366) + ttcVersions = (0x00010000,0x00020000) + fileKind='TTF' + + def __init__(self, file, validate=0,subfontIndex=0): + """Loads and parses a TrueType font file. file can be a filename or a + file object. If validate is set to a false values, skips checksum + validation. This can save time, especially if the font is large. + """ + self.validate = validate + self.readFile(file) + isCollection = self.readHeader() + if isCollection: + self.readTTCHeader() + self.getSubfont(subfontIndex) + else: + if self.validate: self.checksumFile() + self.readTableDirectory() + self.subfontNameX = b'' + + def readTTCHeader(self): + self.ttcVersion = self.read_ulong() + self.fileKind = 'TTC' + self.ttfVersions = self.ttfVersions[:-1] + if self.ttcVersion not in self.ttcVersions: + raise TTFError('"%s" is not a %s file: can\'t read version 0x%8.8x' %(self.filename,self.fileKind,self.ttcVersion)) + self.numSubfonts = self.read_ulong() + self.subfontOffsets = [] + a = self.subfontOffsets.append + for i in range(self.numSubfonts): + a(self.read_ulong()) + + def getSubfont(self,subfontIndex): + if self.fileKind!='TTC': + raise TTFError('"%s" is not a TTC file: use this method' % (self.filename,self.fileKind)) + try: + pos = self.subfontOffsets[subfontIndex] + except IndexError: + raise TTFError('TTC file "%s": bad subfontIndex %s not in [0,%d]' % (self.filename,subfontIndex,self.numSubfonts-1)) + self.seek(pos) + self.readHeader() + self.readTableDirectory() + self.subfontNameX = bytestr('-'+str(subfontIndex)) + + def readTableDirectory(self): + try: + self.numTables = self.read_ushort() + self.searchRange = self.read_ushort() + self.entrySelector = self.read_ushort() + self.rangeShift = self.read_ushort() + + # Read table directory + self.table = {} + self.tables = [] + for n in range(self.numTables): + record = {} + record['tag'] = self.read_tag() + record['checksum'] = self.read_ulong() + record['offset'] = self.read_ulong() + record['length'] = self.read_ulong() + self.tables.append(record) + self.table[record['tag']] = record + except: + raise TTFError('Corrupt %s file "%s" cannot read Table Directory' % (self.fileKind, self.filename)) + if self.validate: self.checksumTables() + + def readHeader(self): + '''read the sfnt header at the current position''' + try: + self.version = version = self.read_ulong() + except: + raise TTFError('"%s" is not a %s file: can\'t read version' %(self.filename,self.fileKind)) + + if version==0x4F54544F: + raise TTFError('%s file "%s": postscript outlines are not supported'%(self.fileKind,self.filename)) + + if version not in self.ttfVersions: + raise TTFError('Not a recognized TrueType font: version=0x%8.8X' % version) + return version==self.ttfVersions[-1] + + def readFile(self,f): + if not hasattr(self,'_ttf_data'): + if hasattr(f,'read'): + self.filename = getattr(f,'name','(ttf)') #good idea Marius + self._ttf_data = f.read() + else: + self.filename, f = TTFOpenFile(f) + self._ttf_data = f.read() + f.close() + self._pos = 0 + + def checksumTables(self): + # Check the checksums for all tables + for t in self.tables: + table = self.get_chunk(t['offset'], t['length']) + checksum = calcChecksum(table) + if t['tag'] == 'head': + adjustment = unpack('>l', table[8:8+4])[0] + checksum = add32(checksum, -adjustment) + xchecksum = t['checksum'] + if xchecksum != checksum: + raise TTFError('TTF file "%s": invalid checksum %s table: %s (expected %s)' % (self.filename,hex32(checksum),t['tag'],hex32(xchecksum))) + + def checksumFile(self): + # Check the checksums for the whole file + checksum = calcChecksum(self._ttf_data) + if 0xB1B0AFBA!=checksum: + raise TTFError('TTF file "%s": invalid checksum %s (expected 0xB1B0AFBA) len: %d &3: %d' % (self.filename,hex32(checksum),len(self._ttf_data),(len(self._ttf_data)&3))) + + def get_table_pos(self, tag): + "Returns the offset and size of a given TTF table." + offset = self.table[tag]['offset'] + length = self.table[tag]['length'] + return (offset, length) + + def seek(self, pos): + "Moves read pointer to a given offset in file." + self._pos = pos + + def skip(self, delta): + "Skip the given number of bytes." + self._pos = self._pos + delta + + def seek_table(self, tag, offset_in_table = 0): + """Moves read pointer to the given offset within a given table and + returns absolute offset of that position in the file.""" + self._pos = self.get_table_pos(tag)[0] + offset_in_table + return self._pos + + def read_tag(self): + "Read a 4-character tag" + self._pos += 4 + return str(self._ttf_data[self._pos - 4:self._pos],'utf8') + + def get_chunk(self, pos, length): + "Return a chunk of raw data at given position" + return bytes(self._ttf_data[pos:pos+length]) + + def read_uint8(self): + self._pos += 1 + return int(self._ttf_data[self._pos-1]) + + def read_ushort(self): + "Reads an unsigned short" + self._pos += 2 + return unpack('>H',self._ttf_data[self._pos-2:self._pos])[0] + + def read_ulong(self): + "Reads an unsigned long" + self._pos += 4 + return unpack('>L',self._ttf_data[self._pos - 4:self._pos])[0] + + def read_short(self): + "Reads a signed short" + self._pos += 2 + try: + return unpack('>h',self._ttf_data[self._pos-2:self._pos])[0] + except structError as error: + raise TTFError(error) + + def get_ushort(self, pos): + "Return an unsigned short at given position" + return unpack('>H',self._ttf_data[pos:pos+2])[0] + + def get_ulong(self, pos): + "Return an unsigned long at given position" + return unpack('>L',self._ttf_data[pos:pos+4])[0] + + def get_table(self, tag): + "Return the given TTF table" + pos, length = self.get_table_pos(tag) + return self._ttf_data[pos:pos+length] + +class TTFontMaker: + "Basic TTF file generator" + + def __init__(self): + "Initializes the generator." + self.tables = {} + + def add(self, tag, data): + "Adds a table to the TTF file." + if tag == 'head': + data = splice(data, 8, b'\0\0\0\0') + self.tables[tag] = data + + def makeStream(self): + "Finishes the generation and returns the TTF file as a string" + stm = BytesIO() + write = stm.write + + tables = self.tables + numTables = len(tables) + searchRange = 1 + entrySelector = 0 + while searchRange * 2 <= numTables: + searchRange = searchRange * 2 + entrySelector = entrySelector + 1 + searchRange = searchRange * 16 + rangeShift = numTables * 16 - searchRange + + # Header + write(pack(">lHHHH", 0x00010000, numTables, searchRange, + entrySelector, rangeShift)) + + # Table directory + offset = 12 + numTables * 16 + wStr = lambda x:write(bytes(tag,'latin1')) + tables_items = list(sorted(tables.items())) + for tag, data in tables_items: + if tag == 'head': + head_start = offset + checksum = calcChecksum(data) + wStr(tag) + write(pack(">LLL", checksum, offset, len(data))) + paddedLength = (len(data)+3)&~3 + offset = offset + paddedLength + + # Table data + for tag, data in tables_items: + data += b"\0\0\0" + write(data[:len(data)&~3]) + + checksum = calcChecksum(stm.getvalue()) + checksum = add32(0xB1B0AFBA, -checksum) + stm.seek(head_start + 8) + write(pack('>L', checksum)) + + return stm.getvalue() + +#this is used in the cmap encoding fmt==2 case +CMapFmt2SubHeader = namedtuple('CMapFmt2SubHeader', 'firstCode entryCount idDelta idRangeOffset') + +class TTFNameBytes(bytes): + '''class used to return named strings''' + def __new__(cls,b,enc='utf8'): + try: + ustr = b.decode(enc) + except: + ustr = b.decode('latin1') + self = bytes.__new__(cls,ustr.encode('utf8')) + self.ustr = ustr + return self + +class TTFontFile(TTFontParser): + "TTF file parser and generator" + _agfnc = 0 + _agfnm = {} + + def __init__(self, file, charInfo=1, validate=0,subfontIndex=0): + """Loads and parses a TrueType font file. + + file can be a filename or a file object. If validate is set to a false + values, skips checksum validation. This can save time, especially if + the font is large. See TTFontFile.extractInfo for more information. + """ + if isStr(subfontIndex): #bytes or unicode + sfi = 0 + __dict__ = self.__dict__.copy() + while True: + TTFontParser.__init__(self, file, validate=validate,subfontIndex=sfi) + numSubfonts = self.numSubfonts = self.read_ulong() + self.extractInfo(charInfo) + if (isBytes(subfontIndex) and subfontIndex==self.name + or subfontIndex==self.name.ustr): #we found it + return + if not sfi: + __dict__.update(dict(_ttf_data=self._ttf_data, filename=self.filename)) + sfi += 1 + if sfi>=numSubfonts: + raise ValueError('cannot find %r subfont %r' % (self.filename, subfontIndex)) + self.__dict__.clear() + self.__dict__.update(__dict__) + else: + TTFontParser.__init__(self, file, validate=validate,subfontIndex=subfontIndex) + self.extractInfo(charInfo) + + def extractInfo(self, charInfo=1): + """ + Extract typographic information from the loaded font file. + + The following attributes will be set:: + + name PostScript font name + flags Font flags + ascent Typographic ascender in 1/1000ths of a point + descent Typographic descender in 1/1000ths of a point + capHeight Cap height in 1/1000ths of a point (0 if not available) + bbox Glyph bounding box [l,t,r,b] in 1/1000ths of a point + _bbox Glyph bounding box [l,t,r,b] in unitsPerEm + unitsPerEm Glyph units per em + italicAngle Italic angle in degrees ccw + stemV stem weight in 1/1000ths of a point (approximate) + + If charInfo is true, the following will also be set:: + + defaultWidth default glyph width in 1/1000ths of a point + charWidths dictionary of character widths for every supported UCS character + code + + This will only work if the font has a Unicode cmap (platform 3, + encoding 1, format 4 or platform 0 any encoding format 4). Setting + charInfo to false avoids this requirement + + """ + # name - Naming table + name_offset = self.seek_table("name") + format = self.read_ushort() + if format != 0: + raise TTFError("Unknown name table format (%d)" % format) + numRecords = self.read_ushort() + string_data_offset = name_offset + self.read_ushort() + names = {1:None,2:None,3:None,4:None,6:None} + K = list(names.keys()) + nameCount = len(names) + for i in range(numRecords): + platformId = self.read_ushort() + encodingId = self.read_ushort() + languageId = self.read_ushort() + nameId = self.read_ushort() + length = self.read_ushort() + offset = self.read_ushort() + if nameId not in K: continue + N = None + if platformId == 3 and encodingId == 1 and languageId == 0x409: # Microsoft, Unicode, US English, PS Name + opos = self._pos + try: + self.seek(string_data_offset + offset) + if length % 2 != 0: + raise TTFError("PostScript name is UTF-16BE string of odd length") + N = TTFNameBytes(self.get_chunk(string_data_offset + offset, length),'utf_16_be') + finally: + self._pos = opos + elif platformId == 1 and encodingId == 0 and languageId == 0: # Macintosh, Roman, English, PS Name + # According to OpenType spec, if PS name exists, it must exist + # both in MS Unicode and Macintosh Roman formats. Apparently, + # you can find live TTF fonts which only have Macintosh format. + N = TTFNameBytes(self.get_chunk(string_data_offset + offset, length),'mac_roman') + if N and names[nameId]==None: + names[nameId] = N + nameCount -= 1 + if nameCount==0: break + if names[6] is not None: + psName = names[6] + elif names[4] is not None: + psName = names[4] + # Fine, one last try before we bail. + elif names[1] is not None: + psName = names[1] + else: + psName = None + + # Don't just assume, check for None since some shoddy fonts cause crashes here... + if not psName: + if rl_config.autoGenerateTTFMissingTTFName: + fn = self.filename + if fn: + bfn = os.path.splitext(os.path.basename(fn))[0] + if not fn: + psName = bytestr('_RL_%s_%s_TTF' % (time.time(), self.__class__._agfnc)) + self.__class__._agfnc += 1 + else: + psName = self._agfnm.get(fn,'') + if not psName: + if bfn: + psName = bytestr('_RL_%s_TTF' % bfn) + else: + psName = bytestr('_RL_%s_%s_TTF' % (time.time(), self.__class__._agfnc)) + self.__class__._agfnc += 1 + self._agfnm[fn] = psName + else: + raise TTFError("Could not find PostScript font name") + + psName = psName.__class__(psName.replace(b" ", b"-")) #Dinu Gherman's fix for font names with spaces + + for c in psName: + if char2int(c)>126 or c in b' [](){}<>/%': + raise TTFError("psName=%r contains invalid character %s" % (psName,ascii(c))) + self.name = psName + self.familyName = names[1] or psName + self.styleName = names[2] or 'Regular' + self.fullName = names[4] or psName + self.uniqueFontID = names[3] or psName + + # head - Font header table + try: + self.seek_table("head") + except: + raise TTFError('head table not found ttf name=%s' % self.name) + ver_maj, ver_min = self.read_ushort(), self.read_ushort() + if ver_maj != 1: + raise TTFError('Unknown head table version %d.%04x' % (ver_maj, ver_min)) + self.fontRevision = self.read_ushort(), self.read_ushort() + + self.skip(4) + magic = self.read_ulong() + if magic != 0x5F0F3CF5: + raise TTFError('Invalid head table magic %04x' % magic) + self.skip(2) + self.unitsPerEm = unitsPerEm = self.read_ushort() + if unitsPerEm==1000: + scale = lambda x: x + else: + _1000mult = 1000 / unitsPerEm + scale = lambda x: x*_1000mult + self._pdfScale = scale + #scale = ((lambda x: x) if unitsPerEm==1000 + #else (lambda x, unitsPerEm=unitsPerEm: x * (1000 / unitsPerEm))) + self.skip(16) + xMin = self.read_short() + yMin = self.read_short() + xMax = self.read_short() + yMax = self.read_short() + self.bbox = list(map(scale, [xMin, yMin, xMax, yMax])) + self.skip(3*2) + indexToLocFormat = self.read_ushort() + glyphDataFormat = self.read_ushort() + + # OS/2 - OS/2 and Windows metrics table + # (needs data from head table) + subsettingAllowed = True + if "OS/2" in self.table: + self.seek_table("OS/2") + version = self.read_ushort() + self.skip(2) + usWeightClass = self.read_ushort() + self.skip(2) + fsType = self.read_ushort() + if fsType==0x0002 or (fsType & 0x0300): + subsettingAllowed = os.path.basename(self.filename) not in rl_config.allowTTFSubsetting + self.skip(58) #11*2 + 10 + 4*4 + 4 + 3*2 + sTypoAscender = self.read_short() + sTypoDescender = self.read_short() + self.ascent = scale(sTypoAscender) # XXX: for some reason it needs to be multiplied by 1.24--1.28 + self.descent = scale(sTypoDescender) + + if version > 1: + self.skip(16) #3*2 + 2*4 + 2 + sCapHeight = self.read_short() + self.capHeight = scale(sCapHeight) + else: + self.capHeight = self.ascent + else: + # Microsoft TTFs require an OS/2 table; Apple ones do not. Try to + # cope. The data is not very important anyway. + usWeightClass = 500 + self.ascent = scale(yMax) + self.descent = scale(yMin) + self.capHeight = self.ascent + + # There's no way to get stemV from a TTF file short of analyzing actual outline data + # This fuzzy formula is taken from pdflib sources, but we could just use 0 here + self.stemV = 50 + int((usWeightClass / 65.0) ** 2) + + # post - PostScript table + # (needs data from OS/2 table) + self.seek_table("post") + ver_maj, ver_min = self.read_ushort(), self.read_ushort() + if ver_maj not in (1, 2, 3, 4): + # Adobe/MS documents 1, 2, 2.5, 3; Apple also has 4. + # From Apple docs it seems that we do not need to care + # about the exact version, so if you get this error, you can + # try to remove this check altogether. + raise TTFError('Unknown post table version %d.%04x' % (ver_maj, ver_min)) + self.italicAngle = self.read_short() + self.read_ushort() / 65536.0 + self.underlinePosition = self.read_short() + self.underlineThickness = self.read_short() + isFixedPitch = self.read_ulong() + + self.flags = FF_SYMBOLIC # All fonts that contain characters + # outside the original Adobe character + # set are considered "symbolic". + if self.italicAngle!= 0: + self.flags = self.flags | FF_ITALIC + if usWeightClass >= 600: # FW_REGULAR == 500, FW_SEMIBOLD == 600 + self.flags = self.flags | FF_FORCEBOLD + if isFixedPitch: + self.flags = self.flags | FF_FIXED + # XXX: FF_SERIF? FF_SCRIPT? FF_ALLCAP? FF_SMALLCAP? + + # hhea - Horizontal header table + self.seek_table("hhea") + ver_maj, ver_min = self.read_ushort(), self.read_ushort() + if ver_maj != 1: + raise TTFError('Unknown hhea table version %d.%04x' % (ver_maj, ver_min)) + self.skip(28) + metricDataFormat = self.read_ushort() + if metricDataFormat != 0: + raise TTFError('Unknown horizontal metric data format (%d)' % metricDataFormat) + numberOfHMetrics = self.read_ushort() + if numberOfHMetrics == 0: + raise TTFError('Number of horizontal metrics is 0') + + # maxp - Maximum profile table + self.seek_table("maxp") + ver_maj, ver_min = self.read_ushort(), self.read_ushort() + if ver_maj != 1: + raise TTFError('Unknown maxp table version %d.%04x' % (ver_maj, ver_min)) + self.numGlyphs = numGlyphs = self.read_ushort() + if not subsettingAllowed: + if self.numGlyphs>0xFF: + raise TTFError('Font does not allow subsetting/embedding (%04X)' % fsType) + else: + self._full_font = True + else: + self._full_font = False + + if not charInfo: + self.charToGlyph = None + self.defaultWidth = None + self.charWidths = None + return + + if glyphDataFormat != 0: + raise TTFError('Unknown glyph data format (%d)' % glyphDataFormat) + + # cmap - Character to glyph index mapping table + cmap_offset = self.seek_table("cmap") + cmapVersion = self.read_ushort() + cmapTableCount = self.read_ushort() + if cmapTableCount==0 and cmapVersion!=0: + cmapTableCount, cmapVersion = cmapVersion, cmapTableCount + encoffs = None + enc = 0 + for n in range(cmapTableCount): + platform = self.read_ushort() + encoding = self.read_ushort() + offset = self.read_ulong() + if platform==3: + enc = 1 + encoffs = offset + elif platform==1 and encoding==0 and enc!=1: + enc = 2 + encoffs = offset + elif platform==1 and encoding==1: + enc = 1 + encoffs = offset + elif platform==0 and encoding!=5: + enc = 1 + encoffs = offset + if encoffs is None: + raise TTFError('could not find a suitable cmap encoding') + encoffs += cmap_offset + self.seek(encoffs) + fmt = self.read_ushort() + self.charToGlyph = charToGlyph = {} + self.glyphToChar = glyphToChar = {} + if fmt in (13,12,10,8): + self.skip(2) #padding + length = self.read_ulong() + lang = self.read_ulong() + else: + length = self.read_ushort() + lang = self.read_ushort() + if fmt==0: + T = [self.read_uint8() for i in range(length-6)] + for unichar in range(min(256,self.numGlyphs,len(T))): + glyph = T[unichar] + charToGlyph[unichar] = glyph + glyphToChar.setdefault(glyph,[]).append(unichar) + elif fmt==4: + limit = encoffs + length + segCount = int(self.read_ushort() / 2.0) + self.skip(6) + endCount = [self.read_ushort() for _ in range(segCount)] + self.skip(2) + startCount = [self.read_ushort() for _ in range(segCount)] + idDelta = [self.read_short() for _ in range(segCount)] + idRangeOffset_start = self._pos + idRangeOffset = [self.read_ushort() for _ in range(segCount)] + + # Now it gets tricky. + for n in range(segCount): + for unichar in range(startCount[n], endCount[n] + 1): + if idRangeOffset[n] == 0: + glyph = (unichar + idDelta[n]) & 0xFFFF + else: + offset = (unichar - startCount[n]) * 2 + idRangeOffset[n] + offset = idRangeOffset_start + 2 * n + offset + if offset >= limit: + # workaround for broken fonts (like Thryomanes) + glyph = 0 + else: + glyph = self.get_ushort(offset) + if glyph != 0: + glyph = (glyph + idDelta[n]) & 0xFFFF + charToGlyph[unichar] = glyph + glyphToChar.setdefault(glyph,[]).append(unichar) + elif fmt==6: + first = self.read_ushort() + count = self.read_ushort() + for glyph in range(first,first+count): + unichar = self.read_ushort() + charToGlyph[unichar] = glyph + glyphToChar.setdefault(glyph,[]).append(unichar) + elif fmt==10: + first = self.read_ulong() + count = self.read_ulong() + for glyph in range(first,first+count): + unichar = self.read_ushort() + charToGlyph[unichar] = glyph + glyphToChar.setdefault(glyph,[]).append(unichar) + elif fmt==12: + segCount = self.read_ulong() + for n in range(segCount): + start = self.read_ulong() + end = self.read_ulong() + inc = self.read_ulong() - start + for unichar in range(start,end+1): + glyph = unichar + inc + charToGlyph[unichar] = glyph + glyphToChar.setdefault(glyph,[]).append(unichar) + elif fmt==13: + segCount = self.read_ulong() + for n in range(segCount): + start = self.read_ulong() + end = self.read_ulong() + gid = self.read_ulong() + for unichar in range(start,end+1): + charToGlyph[unichar] = gid + glyphToChar.setdefault(gid,[]).append(unichar) + elif fmt==2: + T = [self.read_ushort() for i in range(256)] #subheader keys + maxSHK = max(T) + SH = [] + for i in range(maxSHK+1): + firstCode = self.read_ushort() + entryCount = self.read_ushort() + idDelta = self.read_ushort() + idRangeOffset = (self.read_ushort()-(maxSHK-i)*8-2)>>1 + SH.append(CMapFmt2SubHeader(firstCode,entryCount,idDelta,idRangeOffset)) + #number of glyph indexes to read. it is the length of the entire subtable minus that bit we've read so far + entryCount = (length-(self._pos-(cmap_offset+encoffs)))>>1 + glyphs = [self.read_short() for i in range(entryCount)] + last = -1 + for unichar in range(256): + if T[unichar]==0: + #Special case, single byte encoding entry, look unichar up in subhead + if last!=-1: + glyph = 0 + elif (unichar=SH[0].firstCode+SH[0].entryCount or + SH[0].idRangeOffset+(unichar-SH[0].firstCode)>=entryCount): + glyph = 0 + else: + glyph = glyphs[SH[0].idRangeOffset+(unichar-SH[0].firstCode)] + if glyph!=0: + glyph += SH[0].idDelta + #assume the single byte codes are ascii + if glyph!=0 and glyph=entryCount: + glyph = 0 + else: + glyph = glyphs[SH[k].idRangeOffset+j] + if glyph!= 0: + glyph += SH[k].idDelta + if glyph!=0 and glyph 0: "missing character" + glyphMap = [0] # new glyph index -> old glyph index + glyphSet = {0:0} # old glyph index -> new glyph index + codeToGlyph = {} # unicode -> new glyph index + for code in subset: + if code in self.charToGlyph: + originalGlyphIdx = self.charToGlyph[code] + else: + originalGlyphIdx = 0 + if originalGlyphIdx not in glyphSet: + glyphSet[originalGlyphIdx] = len(glyphMap) + glyphMap.append(originalGlyphIdx) + codeToGlyph[code] = glyphSet[originalGlyphIdx] + + # Also include glyphs that are parts of composite glyphs + start = self.get_table_pos('glyf')[0] + n = 0 + while n < len(glyphMap): + originalGlyphIdx = glyphMap[n] + glyphPos = self.glyphPos[originalGlyphIdx] + glyphLen = self.glyphPos[originalGlyphIdx + 1] - glyphPos + n += 1 + if not glyphLen: continue + self.seek(start + glyphPos) + numberOfContours = self.read_short() + if numberOfContours < 0: + # composite glyph + self.skip(8) + flags = GF_MORE_COMPONENTS + while flags & GF_MORE_COMPONENTS: + flags = self.read_ushort() + glyphIdx = self.read_ushort() + if glyphIdx not in glyphSet: + glyphSet[glyphIdx] = len(glyphMap) + glyphMap.append(glyphIdx) + if flags & GF_ARG_1_AND_2_ARE_WORDS: + self.skip(4) + else: + self.skip(2) + if flags & GF_WE_HAVE_A_SCALE: + self.skip(2) + elif flags & GF_WE_HAVE_AN_X_AND_Y_SCALE: + self.skip(4) + elif flags & GF_WE_HAVE_A_TWO_BY_TWO: + self.skip(8) + + + # The following tables are simply copied from the original + for tag in ('name', 'OS/2', 'cvt ', 'fpgm', 'prep'): + try: + output.add(tag, self.get_table(tag)) + except KeyError: + # Apparently some of the tables are optional (cvt, fpgm, prep). + # The lack of the required ones (name, OS/2) would have already + # been caught before. + pass + + # post - PostScript + post = b"\x00\x03\x00\x00" + self.get_table('post')[4:16] + b"\x00" * 16 + output.add('post', post) + + numGlyphs = len(glyphMap) + + # hmtx - Horizontal Metrics + hmtx = [] + for n in range(numGlyphs): + aw, lsb = self.hmetrics[glyphMap[n]] + hmtx.append(int(aw)) + hmtx.append(int(lsb)) + + #work out n as 0 or first aw that's the start of a run + n = len(hmtx)-2 + while n and hmtx[n]==hmtx[n-2]: + n -= 2 + #fails when hmtx[n]!=hmtx[n-2] if there's a run it starts at n+2 + n += 2 + numberOfHMetrics = n>>1 #number of full H Metric pairs + hmtx = hmtx[:n] + hmtx[n+1::2] #full pairs + all the trailing lsb's + + hmtx = pack(*([">%dH" % len(hmtx)] + hmtx)) + output.add('hmtx', hmtx) + + # hhea - Horizontal Header + hhea = self.get_table('hhea') + hhea = _set_ushort(hhea, 34, numberOfHMetrics) + output.add('hhea', hhea) + + # maxp - Maximum Profile + maxp = self.get_table('maxp') + maxp = _set_ushort(maxp, 4, numGlyphs) + output.add('maxp', maxp) + + # cmap - Character to glyph mapping + # XXX maybe use format 0 if possible, not 6? + entryCount = len(subset) + length = 10 + entryCount * 2 + cmap = [0, 1, # version, number of tables + 1, 0, 0,12, # platform, encoding, offset (hi,lo) + 6, length, 0, # format, length, language + 0, + entryCount] + \ + list(map(codeToGlyph.get, subset)) + cmap = pack(*([">%dH" % len(cmap)] + cmap)) + output.add('cmap', cmap) + + # glyf - Glyph data + glyphData = self.get_table('glyf') + offsets = [] + glyf = [] + pos = 0 + for n in range(numGlyphs): + offsets.append(pos) + originalGlyphIdx = glyphMap[n] + glyphPos = self.glyphPos[originalGlyphIdx] + glyphLen = self.glyphPos[originalGlyphIdx + 1] - glyphPos + data = glyphData[glyphPos:glyphPos+glyphLen] + # Fix references in composite glyphs + if glyphLen > 2 and unpack(">h", data[:2])[0] < 0: + # composite glyph + pos_in_glyph = 10 + flags = GF_MORE_COMPONENTS + while flags & GF_MORE_COMPONENTS: + flags = unpack(">H", data[pos_in_glyph:pos_in_glyph+2])[0] + glyphIdx = unpack(">H", data[pos_in_glyph+2:pos_in_glyph+4])[0] + data = _set_ushort(data, pos_in_glyph + 2, glyphSet[glyphIdx]) + pos_in_glyph = pos_in_glyph + 4 + if flags & GF_ARG_1_AND_2_ARE_WORDS: + pos_in_glyph = pos_in_glyph + 4 + else: + pos_in_glyph = pos_in_glyph + 2 + if flags & GF_WE_HAVE_A_SCALE: + pos_in_glyph = pos_in_glyph + 2 + elif flags & GF_WE_HAVE_AN_X_AND_Y_SCALE: + pos_in_glyph = pos_in_glyph + 4 + elif flags & GF_WE_HAVE_A_TWO_BY_TWO: + pos_in_glyph = pos_in_glyph + 8 + glyf.append(data) + pos = pos + glyphLen + if pos % 4 != 0: + padding = 4 - pos % 4 + glyf.append(b'\0' * padding) + pos = pos + padding + offsets.append(pos) + output.add('glyf', b''.join(glyf)) + + # loca - Index to location + loca = [] + if (pos + 1) >> 1 > 0xFFFF: + indexToLocFormat = 1 # long format + for offset in offsets: + loca.append(offset) + loca = pack(*([">%dL" % len(loca)] + loca)) + else: + indexToLocFormat = 0 # short format + for offset in offsets: + loca.append(offset >> 1) + loca = pack(*([">%dH" % len(loca)] + loca)) + output.add('loca', loca) + + # head - Font header + head = self.get_table('head') + head = _set_ushort(head, 50, indexToLocFormat) + output.add('head', head) + + return output.makeStream() + + +# +# TrueType font embedding +# + +# PDF font flags (see PDF Reference Guide table 5.19) +FF_FIXED = 1 << 1-1 +FF_SERIF = 1 << 2-1 +FF_SYMBOLIC = 1 << 3-1 +FF_SCRIPT = 1 << 4-1 +FF_NONSYMBOLIC = 1 << 6-1 +FF_ITALIC = 1 << 7-1 +FF_ALLCAP = 1 << 17-1 +FF_SMALLCAP = 1 << 18-1 +FF_FORCEBOLD = 1 << 19-1 + +class TTFontFace(TTFontFile, pdfmetrics.TypeFace): + """TrueType typeface. + + Conceptually similar to a single byte typeface, but the glyphs are + identified by UCS character codes instead of glyph names.""" + + def __init__(self, filename, validate=0, subfontIndex=0): + "Loads a TrueType font from filename." + pdfmetrics.TypeFace.__init__(self, None) + TTFontFile.__init__(self, filename, validate=validate, subfontIndex=subfontIndex) + + def getCharWidth(self, code): + "Returns the width of character U+" + return self.charWidths.get(code, self.defaultWidth) + + def addSubsetObjects(self, doc, fontname, subset): + """Generate a TrueType font subset and add it to the PDF document. + Returns a PDFReference to the new FontDescriptor object.""" + + fontFile = pdfdoc.PDFStream() + fontFile.content = self.makeSubset(subset) + fontFile.dictionary['Length1'] = len(fontFile.content) + if doc.compression: + fontFile.filters = [pdfdoc.PDFZCompress] + fontFileRef = doc.Reference(fontFile, 'fontFile:%s(%s)' % (self.filename, fontname)) + + flags = self.flags & ~ FF_NONSYMBOLIC + flags = flags | FF_SYMBOLIC + + fontDescriptor = pdfdoc.PDFDictionary({ + 'Type': '/FontDescriptor', + 'Ascent': self.ascent, + 'CapHeight': self.capHeight, + 'Descent': self.descent, + 'Flags': flags, + 'FontBBox': pdfdoc.PDFArray(self.bbox), + 'FontName': pdfdoc.PDFName(fontname), + 'ItalicAngle': self.italicAngle, + 'StemV': self.stemV, + 'FontFile2': fontFileRef, + 'MissingWidth': self.defaultWidth, + }) + return doc.Reference(fontDescriptor, 'fontDescriptor:' + fontname) + +class TTEncoding: + """Encoding for TrueType fonts (always UTF-8). + + TTEncoding does not directly participate in PDF object creation, since + we need a number of different 8-bit encodings for every generated font + subset. TTFont itself cares about that.""" + + def __init__(self): + self.name = "UTF-8" + +class TTFont: + """Represents a TrueType font. + + Its encoding is always UTF-8. + + Note: you cannot use the same TTFont object for different documents + at the same time. + + Example of usage: + + font = ttfonts.TTFont('PostScriptFontName', '/path/to/font.ttf') + pdfmetrics.registerFont(font) + + canvas.setFont('PostScriptFontName', size) + canvas.drawString(x, y, "Some text encoded in UTF-8") + """ + class State: + namePrefix = 'F' + def __init__(self,asciiReadable=None,ttf=None): + A = self.assignments = {} #maps unicode to subset and index + self.nextCode = 0 + self.internalName = None + self.frozen = 0 + face = getattr(ttf,'face',None) + if getattr(face,'_full_font',None): + C = set(face.charToGlyph.keys()) + if 0xa0 in C: C.remove(0xa0) + for n in range(256): + if n in C: + A[n] = n + C.remove(n) + for n in C: + A[n] = n + self.subsets = [[n for n in A]] + self.frozen = True + return + + if asciiReadable is None: + asciiReadable = rl_config.ttfAsciiReadable + + if asciiReadable: + # Let's add the first 128 unicodes to the 0th subset, so ' ' + # always has code 32 (for word spacing to work) and the ASCII + # output is readable + #simple asciiReadable setup + subset0 = list(range(32,128)) #assume we have all of ASCII + charToGlyph = getattr(face,'charToGlyph',None) + if charToGlyph: + for n in subset0: + if n in charToGlyph: + A[n] = n + else: + for n in subset0: + A[n] = n + A[0] = 0 + self.subsets = [32*[0] + subset0] + self.nextCode = 1 #if doing fillin of [1-31] + #self.nextCode = 128 #if not doing fillin + else: + self.subsets = [[0]+[32]*32] + A[0] = 0 + self.nextCode = 1 + A[32] = 32 + + _multiByte = 1 # We want our own stringwidth + _dynamicFont = 1 # We want dynamic subsetting + + def __init__(self, name, filename, validate=0, subfontIndex=0, asciiReadable=None, shapable=True): + """Loads a TrueType font from filename. + + If validate is set to a false values, skips checksum validation. This + can save time, especially if the font is large. + """ + self.fontName = name + self.face = TTFontFace(filename, validate=validate, subfontIndex=subfontIndex) + self.encoding = TTEncoding() + from weakref import WeakKeyDictionary + self.state = WeakKeyDictionary() + if asciiReadable is None: + asciiReadable = rl_config.ttfAsciiReadable + self._asciiReadable = asciiReadable + self.shapable = shapable and not any((fnmatch(name,_) for _ in unShapedFontGlob)) + + def stringWidth(self,text,size,encoding='utf8'): + return instanceStringWidthTTF(self,text,size,encoding) + + def _assignState(self,doc,asciiReadable=None,namePrefix=None): + '''convenience function for those wishing to roll their own state properties''' + if asciiReadable is None: + asciiReadable = self._asciiReadable + try: + state = self.state[doc] + except KeyError: + state = self.state[doc] = TTFont.State(asciiReadable,self) + if namePrefix is not None: + state.namePrefix = namePrefix + return state + + def splitString(self, text, doc, encoding='utf-8'): + """Splits text into a number of chunks, each of which belongs to a + single subset. Returns a list of tuples (subset, string). Use subset + numbers with getSubsetInternalName. Doc is needed for distinguishing + subsets when building different documents at the same time.""" + asciiReadable = self._asciiReadable + try: state = self.state[doc] + except KeyError: state = self.state[doc] = TTFont.State(asciiReadable,self) + _31skip = 31 if asciiReadable and state.nextCode<32 else -256 + curSet = -1 + cur = [] + results = [] + if not isUnicode(text): + text = text.decode('utf-8') # encoding defaults to utf-8 + charToGlyph = self.face.charToGlyph + assignments = state.assignments + subsets = state.subsets + #reserveTTFNotdef = rl_config.reserveTTFNotdef we ignore this now + for code in map(ord,text): + if code==0xa0: code = 32 #map nbsp into space + if code in assignments: + n = assignments[code] + elif code not in charToGlyph: + n = 0 + else: + if state.frozen: + raise pdfdoc.PDFError("Font %s is already frozen, cannot add new character U+%04X" % (self.fontName, code)) + n = state.nextCode + if n&0xFF==32: + # make code 32 always be a space character + if n!=32: subsets[n >> 8].append(32) + state.nextCode += 1 + n = state.nextCode + if n>32: + if not(n&0xFF): + subsets.append([0]) #force code 0 in as notdef + state.nextCode += 1 + n = state.nextCode + subsets[n >> 8].append(code) + else: + if n==_31skip: + #we heve filled in first part of subsets[0] skip past subset[32:127] + #this code will be executed once if asciiReadable + state.nextCode = 127 + subsets[0][n] = code + state.nextCode += 1 + assignments[code] = n + #subsets[n>>8].append(code) + if (n >> 8) != curSet: + if cur: + results.append((curSet,bytes(cur))) + curSet = (n >> 8) + cur = [] + cur.append(n & 0xFF) + if cur: + results.append((curSet,bytes(cur))) + return results + + def getSubsetInternalName(self, subset, doc): + """Returns the name of a PDF Font object corresponding to a given + subset of this dynamic font. Use this function instead of + PDFDocument.getInternalFontName.""" + try: state = self.state[doc] + except KeyError: state = self.state[doc] = TTFont.State(self._asciiReadable) + if subset < 0 or subset >= len(state.subsets): + raise IndexError('Subset %d does not exist in font %s' % (subset, self.fontName)) + if state.internalName is None: + state.internalName = state.namePrefix +repr(len(doc.fontMapping) + 1) + doc.fontMapping[self.fontName] = '/' + state.internalName + doc.delayedFonts.append(self) + return '/%s+%d' % (state.internalName, subset) + + def addObjects(self, doc): + """Makes one or more PDF objects to be added to the document. The + caller supplies the internal name to be used (typically F1, F2, ... in + sequence). + + This method creates a number of Font and FontDescriptor objects. Every + FontDescriptor is a (no more than) 256 character subset of the original + TrueType font.""" + try: state = self.state[doc] + except KeyError: state = self.state[doc] = TTFont.State(self._asciiReadable) + state.frozen = 1 + for n,subset in enumerate(state.subsets): + internalName = self.getSubsetInternalName(n, doc)[1:] + baseFontName = (b''.join((SUBSETN(n),b'+',self.face.name,self.face.subfontNameX))).decode('pdfdoc') + + pdfFont = pdfdoc.PDFTrueTypeFont() + pdfFont.__Comment__ = 'Font %s subset %d' % (self.fontName, n) + pdfFont.Name = internalName + pdfFont.BaseFont = baseFontName + + pdfFont.FirstChar = 0 + pdfFont.LastChar = len(subset) - 1 + + widths = list(map(self.face.getCharWidth, subset)) + pdfFont.Widths = pdfdoc.PDFArray(widths) + + cmapStream = pdfdoc.PDFStream() + cmapStream.content = makeToUnicodeCMap(baseFontName, subset) + if doc.compression: + cmapStream.filters = [pdfdoc.PDFZCompress] + pdfFont.ToUnicode = doc.Reference(cmapStream, 'toUnicodeCMap:' + baseFontName) + + pdfFont.FontDescriptor = self.face.addSubsetObjects(doc, baseFontName, subset) + + # link it in + ref = doc.Reference(pdfFont, internalName) + fontDict = doc.idToObject['BasicFonts'].dict + fontDict[internalName] = pdfFont + del self.state[doc] + + @property + def hbFace(self): + '''return uharbuzz.Face''' + face = getattr(self,'__hbFace__',None) + if not face: + if uharfbuzz is None: + raise ValueError('Cannot import uharfbuzz so shaping is not allowed\nplease pip install uharfbuzz') + blob = uharfbuzz.Blob(self.face._ttf_data) + face = self.__hbFace__ = uharfbuzz.Face(blob) + del blob + self.__hbUnis = {} + self.__hbPrivate = 0xE000 + return face + + def hbFont(self, fontSize=10): + '''return uharfbuzz Font''' + font = uharfbuzz.Font(self.hbFace) + font.ptem = fontSize + self.hbAddPrivate = self.__addPrivate + return font + + def __addPrivate(self, name, gid, advance): + uchar = self.__hbUnis.get(name,None) + if not uchar: + face = self.face + uchar = self.__hbPrivate + while uchar in face.charToGlyph: + uchar += 1 + assert uchar<=0xF800 + self.__hbPrivate = self.__hbUnis[name] = uchar + face.charToGlyph[uchar] = gid + face.glyphToChar.setdefault(gid,[]).append(uchar) + face.charWidths[uchar] = advance + return uchar + + def pdfScale(self,v): + return self.face._pdfScale(v) + + def unregister(self): + if self.fontName in pdfmetrics._fonts: del pdfmetrics._fonts[self.fontName] + if self.face.name in pdfmetrics._dynFaceNames: del pdfmetrics._dynFaceNames[self.face.name] + + @property + def shapable(self): + return bool(self._shapable and uharfbuzz) + + @shapable.setter + def shapable(self,v): + self._shapable = bool(v and uharfbuzz) + +#we only expect to use/see these if uharfbuzz is importable +class ShapedFragWord(list): + '''list class to distinguish frag words that have been shaped''' + pass + +def makeShapedFragWord(w,K=[],V=[]): + klass = w.__class__ + if klass in K: return V[K.index(klass)] + v = ShapedFragWord if klass in (list,ShapedFragWord) else type('ShapedFragWord',(klass,ShapedFragWord),{}) + V.append(v) + K.append(klass) + if len(K)>=127: + K[:] = K[-127:] + V[:] = V[-127:] + return v + +ShapeData = namedtuple('ShapeData','cluster x_advance y_advance x_offset y_offset width') +class ShapeData(ShapeData): + def __repr__(self): + return repr(tuple((map(fp_str,self)))) +_sdGuardL = [ShapeData(-1,0,0,0,0,0)] #for the the end of ShapeData list +_sdSimple = ShapeData(0x7fffffff,0,0,0,0,0) #for added simple chars + +class ShapedStr(str): + def __new__(cls, s, shapeData=None): + self = super().__new__(cls,s) + self.__shapeData__ = shapeData + return self + + def __add__(self,other): + return ShapedStr(super().__add__(other), + shapeData=(self.__shapeData__+other.__shapeData__ if isinstance(other,ShapedStr) + else self.__shapeData__+len(other)*[_sdSimple])) + + def __radd__(self,other): + return ShapedStr(str(other)+str(self), + shapeData=(other.__shapeData__+self.__shapeData__ if isinstance(other,ShapedStr) + else len(other)*[_sdSimple]+self.__shapeData__)) + + def __getitem__(self,i): + s = super().__getitem__(i) + if not s: return s #a simple str + d = self.__shapeData__[i] + return ShapedStr(s,d if isinstance(i,slice) else [d]) + +if not uharfbuzz: + def shapeFragWord(w, features=None): + return w +else: + def shapeFragWord(w, features=dict(kern=True,liga=True,dlig=True), force=False): + '''take a frag word and return a shaped fragword if uharfbuzz makes any changes + if no changes are made return the original word + ''' + if isinstance(w,ShapedFragWord): return w + F = [] + text = '' + specials = {} + for f, s in w[1:]: + if hasattr(f,'cbDefn'): + specials.setdefault(len(text),[]).append(f) + continue + F.extend(len(s)*[f]) + text += s + #if isinstance(text,ShapedStr): breakpoint() + ntext = len(text) + if not F: return w + ttfn = F[0].fontName + ttfs = F[0].fontSize + ttf = pdfmetrics.getFont(ttfn) + try: + hbf = ttf.hbFont(ttfs) + except AttributeError: + return w + ttfs /= 1000 + buf = uharfbuzz.Buffer() + buf.cluster_level = uharfbuzz.BufferClusterLevel.MONOTONE_CHARACTERS + buf.add_str(text) + buf.guess_segment_properties() + infos = buf.glyph_infos + uharfbuzz.shape(hbf, buf, features) + + infos = buf.glyph_infos + positions = buf.glyph_positions + + changed = False + shaped = False + new = makeShapedFragWord(w)([]) + new0 = 0 + nf = None + xpos = 0 + ypos = 0 + shapeDataAppend = [].append + for i,(info,pos) in enumerate(zip(infos,positions)): + gid = info.codepoint + name = hbf.glyph_to_string(gid) + cluster = info.cluster + x_advance = pos.x_advance + x_offset = pos.x_offset + y_advance = pos.y_advance + y_offset = pos.y_offset + f = F[cluster] + if nf is not f: + if nf: + new.append((nf,ShapedStr(ns,shapeData=shapeDataAppend.__self__))) + new0 += newlen + nf = f + ns = '' + newlen = 0 #the new word length + shapeDataAppend = [].append + _ = nf.fontName + if _!=ttfn: + ttfn = _ + ttf = pdfmetrics.getFont(ttfn) + ttfs = nf.fontSize/1000 + try: + uchar = ttf.face.glyphToChar[gid][0] + except KeyError: + uchar = ttf.hbAddPrivate(name, gid, x_advance) + ucharWidth = ttf.face.charWidths[uchar] + uchar = chr(uchar) + ns += uchar + #scale to ensure unitsPerEm == 1000 + x_advance = ttf.pdfScale(x_advance) #fontsize related units + x_offset = ttf.pdfScale(x_offset) + y_advance = ttf.pdfScale(y_advance) #absolute units + y_offset = ttf.pdfScale(y_offset) + if x_advance: newlen += x_advance*ttfs + shaped = shaped or (x_offset!=0 or y_offset!=0 + or i>=ntext + or (text[i]==uchar and x_advance!=ucharWidth)) + changed = changed or shaped or i>=ntext or text[i]!=uchar or force + shapeDataAppend(ShapeData(cluster, x_advance, y_advance, x_offset, y_offset, ucharWidth)) + if nf: #we have at least one frag + new.append((nf,ShapedStr(ns,shapeData=shapeDataAppend.__self__))) + new0 += newlen + if not changed: return w + if not shaped: + if changed: + #make all the tuples simple + new = new.__class__([new[0]] + [tuple(_) for _ in new[1:]]) + else: + return w + if specials: + #now we have to re-add the special cbDefn tuples + #first find the insertion points + S = [] + for k,v in specials.items(): + S.append(((k,k),v)) + for _ in new: + S.append(((_[1].__shapeData__[0].cluster,_[1].__shapeData__[-1].cluster),_)) + new[:] = [_[1] for _ in sorted(S)] + new.insert(0,new0) + return new + +def shapeStr(s,fontName,fontSize, force=False): + return shapeFragWord([pdfmetrics.stringWidth(s,fontName,fontSize), + (ABag(fontName=fontName,fontSize=fontSize),s)],force=force)[1][1] + +def freshTTFont(ttfn, ttfpath,**kwds): + '''return a new instance corrsponding to a ttf path''' + try: + ttf = pdfmetrics.getFont(ttfn) + ttf.unregister() + except: + pass + return TTFont(ttfn,ttfpath,**kwds) + +#preserve the initial values here +def _reset(): + _cached_ttf_dirs.clear() + +register_reset(_reset) +del register_reset diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfgen/__init__.py b/.venv/lib/python3.13/site-packages/reportlab/pdfgen/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d8d012b8930c707eab779740126577989674dfb3 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfgen/__init__.py @@ -0,0 +1,5 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/pdfgen/__init__.py +__version__='3.3.0' +__doc__='''Defines a high-level Canvas interface for creating PDF files''' diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfgen/canvas.py b/.venv/lib/python3.13/site-packages/reportlab/pdfgen/canvas.py new file mode 100644 index 0000000000000000000000000000000000000000..2c7424b61d45848a85f53b5bdb46ad97f70fafe5 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfgen/canvas.py @@ -0,0 +1,2021 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +__version__='3.3.0' +__doc__=""" +The Canvas object is the primary interface for creating PDF files. See +doc/reportlab-userguide.pdf for copious examples. +""" + +__all__ = [ + 'Canvas', + 'ShowBoundaryValue', + ] +ENABLE_TRACKING = 1 # turn this off to do profile testing w/o tracking + +import re +import hashlib +from string import digits +from math import sin, cos, tan, pi +from reportlab import rl_config +from reportlab.pdfbase import pdfdoc +from reportlab.pdfbase import pdfmetrics +from reportlab.pdfbase.ttfonts import ShapedStr, shapeFragWord +from reportlab.pdfgen import pathobject +from reportlab.pdfgen.textobject import PDFTextObject, _PDFColorSetter, bidiShapedText +from reportlab.lib.colors import black, _chooseEnforceColorSpace, Color, CMYKColor, toColor +from reportlab.lib.utils import ImageReader, isSeq, isStr, isUnicode, _digester, asUnicode +from reportlab.lib.abag import ABag +from reportlab.lib.rl_accel import fp_str, escapePDF +from reportlab.lib.boxstuff import aspectRatioFix + +digitPat = re.compile(r'\d') #used in decimal alignment + +# Robert Kern +# Constants for closing paths. +# May be useful if one changes 'arc' and 'rect' to take a +# default argument that tells how to close the path. +# That way we can draw filled shapes. + +FILL_EVEN_ODD = 0 +FILL_NON_ZERO = 1 + #this is used by path-closing routines. + #map stroke, fill, fillmode -> operator + # fillmode: 1 = non-Zero (obviously), 0 = evenOdd +PATH_OPS = {(0, 0, FILL_EVEN_ODD) : 'n', #no op + (0, 0, FILL_NON_ZERO) : 'n', #no op + (1, 0, FILL_EVEN_ODD) : 'S', #stroke only + (1, 0, FILL_NON_ZERO) : 'S', #stroke only + (0, 1, FILL_EVEN_ODD) : 'f*', #Fill only + (0, 1, FILL_NON_ZERO) : 'f', #Fill only + (1, 1, FILL_EVEN_ODD) : 'B*', #Stroke and Fill + (1, 1, FILL_NON_ZERO) : 'B', #Stroke and Fill + } + +def _annFormat(D,color,thickness,dashArray,hradius=0,vradius=0): + from reportlab.pdfbase.pdfdoc import PDFArray + if color and 'C' not in D: + D["C"] = PDFArray([color.red, color.green, color.blue]) + if 'Border' not in D: + border = [hradius,vradius,thickness or 0] + if dashArray: + border.append(PDFArray(dashArray)) + D["Border"] = PDFArray(border) +# BS = PDFDictionary() +# bss = 'S' +# if dashArray: +# BS['D'] = PDFArray(dashArray) +# bss = 'D' +# BS['W'] = thickness or 0 +# BS['S'] = bss +# D['BS'] = BS + +# helpers to guess color space for gradients +def _normalizeColor(aColor): + if isinstance(aColor, CMYKColor): + d = aColor.density + return "DeviceCMYK", tuple(c*d for c in aColor.cmyk()) + elif isinstance(aColor, Color): + return "DeviceRGB", aColor.rgb() + elif isinstance(aColor, (tuple, list)): + l = len(aColor) + if l == 3: + return "DeviceRGB", aColor + elif l == 4: + return "DeviceCMYK", aColor + elif isinstance(aColor, str): + return _normalizeColor(toColor(aColor)) + raise ValueError("Unknown color %r" % aColor) + +def _normalizeColors(colors): + space = None + outcolors = [] + for aColor in colors: + nspace, outcolor = _normalizeColor(aColor) + if space is not None and space != nspace: + raise ValueError("Mismatch in color spaces: %s and %s" % (space, nspace)) + space = nspace + outcolors.append(outcolor) + return space, outcolors + +def _buildColorFunction(colors, positions): + from reportlab.pdfbase.pdfdoc import PDFExponentialFunction, PDFStitchingFunction + if positions is not None and len(positions) != len(colors): + raise ValueError("need to have the same number of colors and positions") + # simplified functions for edge cases + if len(colors) == 1: + # for completeness + return PDFExponentialFunction(N=1, C0=colors[0], C1=colors[0]) + if len(colors) == 2: + if positions is None or (positions[0] == 0 and positions[1] == 1): + return PDFExponentialFunction(N=1, C0=colors[0], C1=colors[1]) + # equally distribute if positions not specified + if positions is None: + nc = len(colors) + positions = [float(x)/(nc-1) for x in range(nc)] + else: + # sort positions and colors in increasing order + poscolors = list(zip(positions, colors)) + poscolors.sort(key=lambda x: x[0]) + # add endpoint positions if not already present + if poscolors[0][0] != 0: + poscolors.insert(0, (0.0, poscolors[0][1])) + if poscolors[-1][0] != 1: + poscolors.append((1.0, poscolors[-1][1])) + positions, colors = list(zip(*poscolors)) # unzip + # build stitching function + functions = [] + bounds = [pos for pos in positions[1:-1]] + encode = [] + lastcolor = colors[0] + for color in colors[1:]: + functions.append(PDFExponentialFunction(N=1, C0=lastcolor, C1=color)) + lastcolor = color + encode.append(0.0) + encode.append(1.0) + return PDFStitchingFunction(functions, bounds, encode, Domain="[0.0 1.0]") + +class ExtGState: + defaults = dict( + CA=1, + ca=1, + OP=False, + op=False, + OPM=0, + BM='Normal', + ) + allowed = dict( + BM = { + 'Normal', 'Multiply', 'Screen', 'Overlay', + 'Darken', 'Lighten', 'ColorDodge', 'ColorBurn', + 'HardLight', 'SoftLight', 'Difference', 'Exclusion', + 'Hue', 'Saturation', 'Color', 'Luminosity', + }, + ) + pdfNameValues = {'BM'} + + @staticmethod + def _boolTransform(v): + return str(v).lower() + + @staticmethod + def _identityTransform(v): + return v + + @staticmethod + def _pdfNameTransform(v): + return '/'+v + + def __init__(self): + self._d = {} + self._c = {} + + def set(self,canv,a,v): + d = self.defaults[a] + if isinstance(d,bool): + v=bool(v) + vTransform = self._boolTransform + elif a in self.pdfNameValues: + if v not in self.allowed[a]: + raise ValueError('ExtGstate[%r] = %r not in allowed values %r' % ( + a,v,self.allowed[a])) + vTransform = self._pdfNameTransform + else: + vTransform = self._identityTransform + if v!=self._d.get(a,d) or (a=='op' and self.getValue('OP')!=d): + self._d[a] = v + t = a,vTransform(v) + if t in self._c: + name = self._c[t] + else: + name = 'gRLs'+str(len(self._c)) + self._c[t] = name + canv._code.append('/%s gs' % name) + + def getValue(self,a): + return self._d.get(a,self.defaults[a]) + + def getState(self): + S = {} + for t,name in self._c.items(): + S[name] = pdfdoc.PDFDictionary(dict((t,))) + return S and pdfdoc.PDFDictionary(S) or None + + def pushCopy(self): + '''the states must be shared across push/pop, but the values not''' + x = self.__class__() + x._d = self._d.copy() + x._c = self._c + return x + +def _gradientExtendStr(extend): + if isinstance(extend,(list,tuple)): + if len(extend)!=2: + raise ValueError('wrong length for extend argument' % extend) + return "[%s %s]" % ['true' if _ else 'false' for _ in extend] + return "[true true]" if extend else "[false false]" + +class ShowBoundaryValue: + def __init__(self,color=(0,0,0),width=0.1,dashArray=None): + self.color = color + self.width = width + self.dashArray = dashArray + + def __bool__(self): + return self.color is not None and self.width>=0 + +class Canvas(_PDFColorSetter): + """This class is the programmer's interface to the PDF file format. Methods + are (or will be) provided here to do just about everything PDF can do. + + The underlying model to the canvas concept is that of a graphics state machine + that at any given point in time has a current font, fill color (for figure + interiors), stroke color (for figure borders), line width and geometric transform, among + many other characteristics. + + Canvas methods generally either draw something (like canvas.line) using the + current state of the canvas or change some component of the canvas + state (like canvas.setFont). The current state can be saved and restored + using the saveState/restoreState methods. + + Objects are "painted" in the order they are drawn so if, for example + two rectangles overlap the last draw will appear "on top". PDF form + objects (supported here) are used to draw complex drawings only once, + for possible repeated use. + + There are other features of canvas which are not visible when printed, + such as outlines and bookmarks which are used for navigating a document + in a viewer. + + Here is a very silly example usage which generates a Hello World pdf document. + + Example:: + + from reportlab.pdfgen import canvas + c = canvas.Canvas("hello.pdf") + from reportlab.lib.units import inch + # move the origin up and to the left + c.translate(inch,inch) + # define a large font + c.setFont("Helvetica", 80) + # choose some colors + c.setStrokeColorRGB(0.2,0.5,0.3) + c.setFillColorRGB(1,0,1) + # draw a rectangle + c.rect(inch,inch,6*inch,9*inch, fill=1) + # make text go straight up + c.rotate(90) + # change color + c.setFillColorRGB(0,0,0.77) + # say hello (note after rotate the y coord needs to be negative!) + c.drawString(3*inch, -3*inch, "Hello World") + c.showPage() + c.save() + + """ + + def __init__(self,filename, + pagesize=None, + bottomup = 1, + pageCompression=None, + invariant = None, + verbosity=0, + encrypt=None, + cropMarks=None, + pdfVersion=None, + enforceColorSpace=None, + initialFontName=None, + initialFontSize=None, + initialLeading=None, + cropBox=None, + artBox=None, + trimBox=None, + bleedBox=None, + lang=None, + **kwds, + ): + """Create a canvas of a given size. etc. + + You may pass a file-like object to filename as an alternative to + a string. + For more information about the encrypt parameter refer to the setEncrypt method. + + Most of the attributes are private - we will use set/get methods + as the preferred interface. Default page size is A4. + cropMarks may be True/False or an object with parameters borderWidth, markColor, markWidth + and markLength + + if enforceColorSpace is in ('cmyk', 'rgb', 'sep','sep_black','sep_cmyk') then one of + the standard _PDFColorSetter callables will be used to enforce appropriate color settings. + If it is a callable then that will be used. + """ + if pagesize is None: pagesize = rl_config.defaultPageSize + if invariant is None: invariant = rl_config.invariant + + self._initialFontName = initialFontName if initialFontName else rl_config.canvas_basefontname + self._initialFontSize = initialFontSize if initialFontSize is not None else 12 + self._initialLeading = initialLeading if initialLeading is not None else self._initialFontSize*1.2 + + self._filename = filename + + self._doc = pdfdoc.PDFDocument(compression=pageCompression, + invariant=invariant, filename=filename, + pdfVersion=pdfVersion or pdfdoc.PDF_VERSION_DEFAULT, + lang=lang + ) + + self._enforceColorSpace = _chooseEnforceColorSpace(enforceColorSpace) + + #this only controls whether it prints 'saved ...' - 0 disables + self._verbosity = verbosity + + #this is called each time a page is output if non-null + self._onPage = None + self._cropMarks = cropMarks + + self._pagesize = pagesize + self._hanging_pagesize = None + self._pageRotation = 0 + #self._currentPageHasImages = 0 + self._pageTransition = None + self._pageDuration = None + self._destinations = {} # dictionary of destinations for cross indexing. + + self.setPageCompression(pageCompression) + self._pageNumber = 1 # keep a count + # when we create a form we need to save operations not in the form + self._codeStack = [] + self._restartAccumulators() # restart all accumulation state (generalized, arw) + self._annotationCount = 0 + + self._outlines = [] # list for a name tree + self._psCommandsBeforePage = [] #for postscript tray/font commands + self._psCommandsAfterPage = [] #for postscript tray/font commands + + #PostScript has the origin at bottom left. It is easy to achieve a top- + #down coord system by translating to the top of the page and setting y + #scale to -1, but then text is inverted. So self.bottomup is used + #to also set the text matrix accordingly. You can now choose your + #drawing coordinates. + self.bottomup = bottomup + self.imageCaching = rl_config.defaultImageCaching + + self._cropBox = cropBox #we don't do semantics for these at all + self._artBox = artBox + self._trimBox = trimBox + self._bleedBox = bleedBox + + self.init_graphics_state() + self._make_preamble() + self.state_stack = [] + + self.setEncrypt(encrypt) + self._namedCB = {} #named callbacks + + def setEncrypt(self, encrypt): + ''' + Set the encryption used for the pdf generated by this canvas. + If encrypt is a string object, it is used as the user password for the pdf. + If encrypt is an instance of reportlab.lib.pdfencrypt.StandardEncryption, this object is + used to encrypt the pdf. This allows more finegrained control over the encryption settings. + ''' + if encrypt: + from reportlab.lib import pdfencrypt + if isStr(encrypt): #encrypt is the password itself + if isUnicode(encrypt): + encrypt = encrypt.encode('utf-8') + encrypt = pdfencrypt.StandardEncryption(encrypt) #now it's the encrypt object + encrypt.setAllPermissions(1) + elif not isinstance(encrypt, pdfencrypt.StandardEncryption): + raise TypeError('Expected string or instance of reportlab.lib.pdfencrypt.StandardEncryption as encrypt parameter but got %r' % encrypt) + self._doc.encrypt = encrypt + else: + try: + del self._doc.encrypt + except AttributeError: + pass + + def init_graphics_state(self): + #initial graphics state, never modify any of these in place + self._x = 0 + self._y = 0 + self._fontname = self._initialFontName + self._fontsize = self._initialFontSize + + self._textMode = 0 #track if between BT/ET + self._leading = self._initialLeading + self._currentMatrix = (1., 0., 0., 1., 0., 0.) + self._fillMode = FILL_EVEN_ODD + + #text state + self._charSpace = 0 + self._wordSpace = 0 + self._horizScale = 100 + self._textRenderMode = 0 + self._rise = 0 + self._textLineMatrix = (1., 0., 0., 1., 0., 0.) + self._textMatrix = (1., 0., 0., 1., 0., 0.) + + # line drawing + self._lineCap = 0 + self._lineJoin = 0 + self._lineDash = None #not done + self._lineWidth = 1 + self._mitreLimit = 0 + + self._fillColorObj = self._strokeColorObj = rl_config.canvas_baseColor or (0,0,0) + self._extgstate = ExtGState() + + def push_state_stack(self): + state = {} + d = self.__dict__ + for name in self.STATE_ATTRIBUTES: + state[name] = d[name] #getattr(self, name) + self.state_stack.append(state) + self._extgstate = self._extgstate.pushCopy() + + def pop_state_stack(self): + self.__dict__.update(self.state_stack.pop()) + + STATE_ATTRIBUTES = """_x _y _fontname _fontsize _textMode _leading _currentMatrix _fillMode + _charSpace _wordSpace _horizScale _textRenderMode _rise _textLineMatrix + _textMatrix _lineCap _lineJoin _lineDash _lineWidth _mitreLimit _fillColorObj + _strokeColorObj _extgstate""".split() + STATE_RANGE = list(range(len(STATE_ATTRIBUTES))) + + #self._addStandardFonts() + + def _make_preamble(self): + P = [].append + if self.bottomup: + P('1 0 0 1 0 0 cm') + else: + P('1 0 0 -1 0 %s cm' % fp_str(self._pagesize[1])) + C = self._code + n = len(C) + if self._fillColorObj != (0,0,0): + self.setFillColor(self._fillColorObj) + if self._strokeColorObj != (0,0,0): + self.setStrokeColor(self._strokeColorObj) + P(' '.join(C[n:])) + del C[n:] + font = pdfmetrics.getFont(self._fontname) + if not font._dynamicFont: + #set an initial font + if font.face.builtIn or not getattr(self,'_drawTextAsPath',False): + P('BT %s 12 Tf 14.4 TL ET' % self._doc.getInternalFontName(self._fontname)) + self._preamble = ' '.join(P.__self__) + + def _escape(self, s): + return escapePDF(s) + + #info functions - non-standard + def setAuthor(self, author): + """identify the author for invisible embedding inside the PDF document. + the author annotation will appear in the the text of the file but will + not automatically be seen when the document is viewed, but is visible + in document properties etc etc.""" + self._doc.setAuthor(author) + + def setDateFormatter(self, dateFormatter): + """accepts a func(yyyy,mm,dd,hh,m,s) used to create embedded formatted date""" + self._doc.setDateFormatter(dateFormatter) + + def addOutlineEntry(self, title, key, level=0, closed=None): + """Adds a new entry to the outline at given level. If LEVEL not specified, + entry goes at the top level. If level specified, it must be + no more than 1 greater than the outline level in the last call. + + The key must be the (unique) name of a bookmark. + the title is the (non-unique) name to be displayed for the entry. + + If closed is set then the entry should show no subsections by default + when displayed. + + Example:: + + c.addOutlineEntry("first section", "section1") + c.addOutlineEntry("introduction", "s1s1", 1, closed=1) + c.addOutlineEntry("body", "s1s2", 1) + c.addOutlineEntry("detail1", "s1s2s1", 2) + c.addOutlineEntry("detail2", "s1s2s2", 2) + c.addOutlineEntry("conclusion", "s1s3", 1) + c.addOutlineEntry("further reading", "s1s3s1", 2) + c.addOutlineEntry("second section", "section1") + c.addOutlineEntry("introduction", "s2s1", 1) + c.addOutlineEntry("body", "s2s2", 1, closed=1) + c.addOutlineEntry("detail1", "s2s2s1", 2) + c.addOutlineEntry("detail2", "s2s2s2", 2) + c.addOutlineEntry("conclusion", "s2s3", 1) + c.addOutlineEntry("further reading", "s2s3s1", 2) + + generated outline looks like:: + + - first section + |- introduction + |- body + | |- detail1 + | |- detail2 + |- conclusion + | |- further reading + - second section + |- introduction + |+ body + |- conclusion + | |- further reading + + Note that the second "body" is closed. + + Note that you can jump from level 5 to level 3 but not + from 3 to 5: instead you need to provide all intervening + levels going down (4 in this case). Note that titles can + collide but keys cannot. + """ + #to be completed + #self._outlines.append(title) + self._doc.outline.addOutlineEntry(key, level, title, closed=closed) + + def setOutlineNames0(self, *nametree): # keep this for now (?) + """nametree should can be a recursive tree like so:: + + c.setOutlineNames( + "chapter1dest", + ("chapter2dest", + ["chapter2section1dest", + "chapter2section2dest", + "chapter2conclusiondest"] + ), # end of chapter2 description + "chapter3dest", + ("chapter4dest", ["c4s1", "c4s2"]) + ) + + each of the string names inside must be bound to a bookmark + before the document is generated. + """ + self._doc.outline.setNames(*((self,)+nametree)) + + def setTitle(self, title): + """write a title into the PDF file that won't automatically display + in the document itself.""" + self._doc.setTitle(title) + + def setSubject(self, subject): + """write a subject into the PDF file that won't automatically display + in the document itself.""" + self._doc.setSubject(subject) + + def setCreator(self, creator): + """write a creator into the PDF file that won't automatically display + in the document itself. This should be used to name the original app + which is passing data into ReportLab, if you wish to name it.""" + self._doc.setCreator(creator) + + def setProducer(self, producer): + """change the default producer value""" + self._doc.setProducer(producer) + + def setKeywords(self, keywords): + """write a list of keywords into the PDF file which shows in document properties. + Either submit a single string or a list/tuple""" + if isinstance(keywords,(list,tuple)): + keywords = ', '.join(keywords) + self._doc.setKeywords(keywords) + + def pageHasData(self): + "Info function - app can call it after showPage to see if it needs a save" + return len(self._code) == 0 + + def showOutline(self): + """Specify that Acrobat Reader should start with the outline tree visible. + showFullScreen() and showOutline() conflict; the one called last + wins.""" + self._doc._catalog.showOutline() + + def showFullScreen0(self): + """Specify that Acrobat Reader should start in full screen mode. + showFullScreen() and showOutline() conflict; the one called last + wins.""" + self._doc._catalog.showFullScreen() + + def _setStrokeAlpha(self,v): + """ + Define the transparency/opacity of strokes. 0 is fully + transparent, 1 is fully opaque. + + Note that calling this function will cause a version 1.4 PDF + to be generated (rather than 1.3). + """ + self._doc.ensureMinPdfVersion('transparency') + self._extgstate.set(self,'CA',v) + + def _setFillAlpha(self,v): + """ + Define the transparency/opacity of non-strokes. 0 is fully + transparent, 1 is fully opaque. + + Note that calling this function will cause a version 1.4 PDF + to be generated (rather than 1.3). + """ + self._doc.ensureMinPdfVersion('transparency') + self._extgstate.set(self,'ca',v) + + def _setStrokeOverprint(self,v): + self._extgstate.set(self,'OP',v) + + def _setFillOverprint(self,v): + self._extgstate.set(self,'op',v) + + def _setOverprintMask(self,v): + self._extgstate.set(self,'OPM',v and 1 or 0) + + def setBlendMode(self, v): + self._extgstate.set(self,'BM',v) + + def _getCmShift(self): + cM = self._cropMarks + if cM: + bleedW = max(0,getattr(cM,'bleedWidth',0)) + bw = max(0,getattr(cM,'borderWidth',36)) + if bleedW: + bw -= bleedW + return bw + + def showPage(self): + """Close the current page and possibly start on a new page.""" + # ensure a space at the end of the stream - Acrobat does + # not mind, but Ghostscript dislikes 'Qendstream' even if + # the length marker finishes after 'Q' + + pageWidth = self._pagesize[0] + pageHeight = self._pagesize[1] + cM = self._cropMarks + code = self._code + if cM: + bw = max(0,getattr(cM,'borderWidth',36)) + if bw: + markLast = getattr(cM,'markLast',1) + ml = min(bw,max(0,getattr(cM,'markLength',18))) + mw = getattr(cM,'markWidth',0.5) + mc = getattr(cM,'markColor',black) + mg = 2*bw-ml + cx0 = len(code) + if ml and mc: + self.saveState() + self.setStrokeColor(mc) + self.setLineWidth(mw) + self.lines([ + (bw,0,bw,ml), + (pageWidth+bw,0,pageWidth+bw,ml), + (bw,pageHeight+mg,bw,pageHeight+2*bw), + (pageWidth+bw,pageHeight+mg,pageWidth+bw,pageHeight+2*bw), + (0,bw,ml,bw), + (pageWidth+mg,bw,pageWidth+2*bw,bw), + (0,pageHeight+bw,ml,pageHeight+bw), + (pageWidth+mg,pageHeight+bw,pageWidth+2*bw,pageHeight+bw), + ]) + self.restoreState() + if markLast: + #if the marks are to be drawn after the content + #save the code we just drew for later use + L = code[cx0:] + del code[cx0:] + cx0 = len(code) + + bleedW = max(0,getattr(cM,'bleedWidth',0)) + self.saveState() + self.translate(bw-bleedW,bw-bleedW) + if bleedW: + #scale everything + self.scale(1+(2.0*bleedW)/pageWidth,1+(2.0*bleedW)/pageHeight) + + #move our translation/expansion code to the beginning + C = code[cx0:] + del code[cx0:] + code[0:0] = C + self.restoreState() + if markLast: + code.extend(L) + pageWidth = 2*bw + pageWidth + pageHeight = 2*bw + pageHeight + + code.append(' ') + page = pdfdoc.PDFPage() + page.pagewidth = pageWidth + page.pageheight = pageHeight + page.Rotate = self._pageRotation + page.hasImages = self._currentPageHasImages + page.setPageTransition(self._pageTransition) + page.setCompression(self._pageCompression) + for box in ('crop','art','bleed','trim'): + size = getattr(self,'_%sBox'%box,None) + if size: + setattr(page,box.capitalize()+'Box',pdfdoc.PDFArray(size)) + if self._pageDuration is not None: + page.Dur = self._pageDuration + + strm = self._psCommandsBeforePage + [self._preamble] + code + self._psCommandsAfterPage + page.setStream(strm) + self._setColorSpace(page) + self._setExtGState(page) + self._setXObjects(page) + self._setShadingUsed(page) + self._setAnnotations(page) + self._doc.addPage(page) + + if self._onPage: self._onPage(self._pageNumber) + self._startPage() + + def _startPage(self): + #now get ready for the next one + if self._hanging_pagesize: + self.setPageSize(self._hanging_pagesize) + self._hanging_pagesize = None + self._pageNumber += 1 + self._restartAccumulators() + self.init_graphics_state() + self.state_stack = [] + + def setPageCallBack(self, func): + """func(pageNum) will be called on each page end. + + This is mainly a hook for progress monitoring. + Call setPageCallback(None) to clear a callback.""" + self._onPage = func + + def _setAnnotations(self,page): + page.Annots = self._annotationrefs + + def _setColorSpace(self,obj): + obj._colorsUsed = self._colorsUsed + + def _setShadingUsed(self, page): + page._shadingUsed = self._shadingUsed + + def _setXObjects(self, thing): + """for pages and forms, define the XObject dictionary for resources, if needed""" + forms = self._formsinuse + if forms: + xobjectsdict = self._doc.xobjDict(forms) + thing.XObjects = xobjectsdict + else: + thing.XObjects = None + + def _bookmarkReference(self, name): + """get a reference to a (possibly undefined, possibly unbound) bookmark""" + d = self._destinations + try: + return d[name] + except: + result = d[name] = pdfdoc.Destination(name) # newly defined, unbound + return result + + def bookmarkPage(self, key, + fit="Fit", + left=None, + top=None, + bottom=None, + right=None, + zoom=None + ): + """ + This creates a bookmark to the current page which can + be referred to with the given key elsewhere. + + PDF offers very fine grained control over how Acrobat + reader is zoomed when people link to this. The default + is to keep the user's current zoom settings. the last + arguments may or may not be needed depending on the + choice of 'fitType'. + + Fit types and the other arguments they use are: + + - XYZ left top zoom - fine grained control. null + or zero for any of the parameters means 'leave + as is', so "0,0,0" will keep the reader's settings. + NB. Adobe Reader appears to prefer "null" to 0's. + + - Fit - entire page fits in window + + - FitH top - top coord at top of window, width scaled + to fit. + + - FitV left - left coord at left of window, height + scaled to fit + + - FitR left bottom right top - scale window to fit + the specified rectangle + + (question: do we support /FitB, FitBH and /FitBV + which are hangovers from version 1.1 / Acrobat 3.0?)""" + dest = self._bookmarkReference(key) + self._doc.inPage() # try to enable page-only features + pageref = self._doc.thisPageRef() + + #None = "null" for PDF + if left is None: + left = "null" + if top is None: + top = "null" + if bottom is None: + bottom = "null" + if right is None: + right = "null" + if zoom is None: + zoom = "null" + + if fit == "XYZ": + dest.xyz(left,top,zoom) + elif fit == "Fit": + dest.fit() + elif fit == "FitH": + dest.fith(top) + elif fit == "FitV": + dest.fitv(left) + elif fit == "FitR": + dest.fitr(left,bottom,right,top) + #Do we need these (version 1.1 / Acrobat 3 versions)? + elif fit == "FitB": + dest.fitb() + elif fit == "FitBH": + dest.fitbh(top) + elif fit == "FitBV": + dest.fitbv(left) + else: + raise ValueError("Unknown Fit type %s" % ascii(fit)) + + dest.setPage(pageref) + return dest + + def bookmarkHorizontalAbsolute(self, key, top, left=0, fit='XYZ', **kw): + """Bind a bookmark (destination) to the current page at a horizontal position. + Note that the yhorizontal of the book mark is with respect to the default + user space (where the origin is at the lower left corner of the page) + and completely ignores any transform (translation, scale, skew, rotation, + etcetera) in effect for the current graphics state. The programmer is + responsible for making sure the bookmark matches an appropriate item on + the page.""" + #This method should probably be deprecated since it is just a sub-set of bookmarkPage + return self.bookmarkPage(key, fit=fit, top=top, left=left, zoom=0) + + def bookmarkHorizontal(self, key, relativeX, relativeY, **kw): + """w.r.t. the current transformation, bookmark this horizontal.""" + (left, top) = self.absolutePosition(relativeX,relativeY) + self.bookmarkHorizontalAbsolute(key, top, left=left, **kw) + + #def _inPage0(self): disallowed! + # """declare a page, enable page features""" + # self._doc.inPage() + + #def _inForm0(self): + # "deprecated in favore of beginForm...endForm" + # self._doc.inForm() + + def doForm(self, name): + """use a form XObj in current operation stream. + + The form should either have been defined previously using + beginForm ... endForm, or may be defined later. If it is not + defined at save time, an exception will be raised. The form + will be drawn within the context of the current graphics + state.""" + self._code.append("/%s Do" % self._doc.getXObjectName(name)) + self._formsinuse.append(name) + + def hasForm(self, name): + """Query whether form XObj really exists yet.""" + return self._doc.hasForm(name) + + ###################################################### + # + # Image routines + # + ###################################################### + def drawInlineImage(self, image, x,y, width=None,height=None, + preserveAspectRatio=False,anchor='c', anchorAtXY=False, showBoundary=False, + extraReturn=None): + """See drawImage, which should normally be used instead... + + drawInlineImage behaves like drawImage, but stores the image content + within the graphics stream for the page. This means that the mask + parameter for transparency is not available. It also means that there + is no saving in file size or time if the same image is reused. + + In theory it allows images to be displayed slightly faster; however, + we doubt if the difference is noticeable to any human user these days. + Only use this if you have studied the PDF specification and know the + implications. + """ + + self._currentPageHasImages = 1 + from reportlab.pdfgen.pdfimages import PDFImage + img_obj = PDFImage(image, x,y, width, height) + img_obj.drawInlineImage(self, + preserveAspectRatio=preserveAspectRatio, + anchor=anchor,anchorAtXY=anchorAtXY,showBoundary=showBoundary, + extraReturn=extraReturn) + return (img_obj.width, img_obj.height) + + def drawImage(self, image, x, y, width=None, height=None, mask=None, + preserveAspectRatio=False, anchor='c', anchorAtXY=False, showBoundary=False, + extraReturn=None): + """Draws the image (ImageReader object or filename) as specified. + + "image" may be an image filename or an ImageReader object. + + x and y define the lower left corner of the image you wish to + draw (or of its bounding box, if using preserveAspectRation below). + + If width and height are not given, the width and height of the + image in pixels is used at a scale of 1 point to 1 pixel. + + If width and height are given, the image will be stretched to fill + the given rectangle bounded by (x, y, x+width, y-height). + + If you supply negative widths and/or heights, it inverts them and adjusts + x and y accordingly. + + The method returns the width and height of the underlying image, since + this is often useful for layout algorithms and saves you work if you have + not specified them yourself. + + The mask parameter supports transparent backgrounds. It takes 6 numbers + and defines the range of RGB values which will be masked out or treated + as transparent. For example with [0,2,40,42,136,139], it will mask out + any pixels with a Red value from 0-2, Green from 40-42 and + Blue from 136-139 (on a scale of 0-255). + + New post version 2.0: drawImage can center an image in a box you + provide, while preserving its aspect ratio. For example, you might + have a fixed square box in your design, and a collection of photos + which might be landscape or portrait that you want to appear within + the box. If preserveAspectRatio is true, your image will appear within + the box specified. + + + If preserveAspectRatio is True, the anchor property can be used to + specify how images should fit into the given box. It should + be set to one of the following values, taken from the points of + the compass (plus 'c' for 'centre'): + + nw n ne + w c e + sw s se + + The default value is 'c' for 'centre'. Thus, if you want your + bitmaps to always be centred and appear at the top of the given box, + set anchor='n'. There are good examples of this in the output + of test_pdfgen_general.py + + Unlike drawInlineImage, this creates 'external images' which + are only stored once in the PDF file but can be drawn many times. + If you give it the same filename twice, even at different locations + and sizes, it will reuse the first occurrence, resulting in a saving + in file size and generation time. If you use ImageReader objects, + it tests whether the image content has changed before deciding + whether to reuse it. + + In general you should use drawImage in preference to drawInlineImage + unless you have read the PDF Spec and understand the tradeoffs.""" + + self._currentPageHasImages = 1 + + # first, generate a unique name/signature for the image. If ANYTHING + # is different, even the mask, this should be different. + if isinstance(image,ImageReader): + rawdata = image.getRGBData() + smask = image._dataA + if mask=='auto' and smask: + mdata = smask.getRGBData() + else: + mdata = str(mask) + if isUnicode(mdata): + mdata = mdata.encode('utf8') + name = _digester(rawdata+mdata) + else: + #filename, use it + s = '%s%s' % (image, mask) + if isUnicode(s): + s = s.encode('utf-8') + name = _digester(s) + + # in the pdf document, this will be prefixed with something to + # say it is an XObject. Does it exist yet? + regName = self._doc.getXObjectName(name) + imgObj = self._doc.idToObject.get(regName, None) + if not imgObj: + #first time seen, create and register the PDFImageXobject + imgObj = pdfdoc.PDFImageXObject(name, image, mask=mask) + imgObj.name = name + self._setXObjects(imgObj) + self._doc.Reference(imgObj, regName) + self._doc.addForm(name, imgObj) + smask = getattr(imgObj,'_smask',None) + if smask: #set up the softmask obtained above + mRegName = self._doc.getXObjectName(smask.name) + mImgObj = self._doc.idToObject.get(mRegName, None) + if not mImgObj: + self._setXObjects(smask) + imgObj.smask = self._doc.Reference(smask,mRegName) + else: + imgObj.smask = pdfdoc.PDFObjectReference(mRegName) + del imgObj._smask + + # ensure we have a size, as PDF will make it 1x1 pixel otherwise! + x,y,width,height,scaled = aspectRatioFix(preserveAspectRatio,anchor,x,y,width,height,imgObj.width,imgObj.height,anchorAtXY) + + # scale and draw + self.saveState() + self.translate(x, y) + self.scale(width, height) + self._code.append("/%s Do" % regName) + self.restoreState() + if showBoundary: + #self.rect(x,y,width,height,stroke=1,fill=0) + self.drawBoundary(showBoundary,x,y,width,height) + + # track what's been used on this page + self._formsinuse.append(name) + if extraReturn: + for k in extraReturn.keys(): + extraReturn[k] = vars()[k] + + return (imgObj.width, imgObj.height) + + def _restartAccumulators(self): + if self._codeStack: + # restore the saved code + self._code, self._formsinuse, self._annotationrefs, self._formData,self._colorsUsed, self._shadingUsed = self._codeStack.pop(-1) + else: + self._code = [] # ready for more... + self._psCommandsAfterPage = [] + self._psCommandsBeforePage = [] + self._currentPageHasImages = 1 # for safety... + self._formsinuse = [] + self._annotationrefs = [] + self._formData = None + self._colorsUsed = {} + self._shadingUsed = {} + + def _pushAccumulators(self): + "when you enter a form, save accumulator info not related to the form for page (if any)" + saved = (self._code, self._formsinuse, self._annotationrefs, self._formData, self._colorsUsed, self._shadingUsed) + self._codeStack.append(saved) + self._code = [] # ready for more... + self._currentPageHasImages = 1 # for safety... + self._formsinuse = [] + self._annotationrefs = [] + self._formData = None + self._colorsUsed = {} + self._shadingUsed = {} + + def _setExtGState(self, obj): + obj.ExtGState = self._extgstate.getState() + + def beginForm(self, name, lowerx=0, lowery=0, upperx=None, uppery=None): + """declare the current graphics stream to be a named form. + A graphics stream can either be a page or a form, not both. + Some operations (like bookmarking) are permitted for pages + but not forms. The form will not automatically be shown in the + document but must be explicitly referenced using doForm in pages + that require the form.""" + self.push_state_stack() + self.init_graphics_state() + if self._code or self._formData: + # save the code that is not in the formf + self._pushAccumulators() + #self._codeStack.append(self._code) + #self._code = [] + self._formData = (name, lowerx, lowery, upperx, uppery) + self._doc.inForm() + #self._inForm0() + + def endForm(self,**extra_attributes): + """emit the current collection of graphics operations as a Form + as declared previously in beginForm.""" + (name, lowerx, lowery, upperx, uppery) = self._formData + #self.makeForm0(name, lowerx, lowery, upperx, uppery) + # fall through! makeForm0 disallowed + #def makeForm0(self, name, lowerx=0, lowery=0, upperx=None, uppery=None): + """Like showpage, but make a form using accumulated operations instead""" + # deprecated in favor or beginForm(...)... endForm() + (w,h) = self._pagesize + if upperx is None: upperx=w + if uppery is None: uppery=h + form = pdfdoc.PDFFormXObject(lowerx=lowerx, lowery=lowery, upperx=upperx, uppery=uppery) + form.compression = self._pageCompression + form.setStreamList([self._preamble] + self._code) # ??? minus preamble (seems to be needed!) + for k, v in extra_attributes.items(): + setattr(form,k,v) + self._setColorSpace(form) + self._setExtGState(form) + self._setXObjects(form) + self._setAnnotations(form) + self._doc.addForm(name, form) + self._restartAccumulators() + self.pop_state_stack() + + def addPostScriptCommand(self, command, position=1): + """Embed literal Postscript in the document. + + With position=0, it goes at very beginning of page stream; + with position=1, at current point; and + with position=2, at very end of page stream. What that does + to the resulting Postscript depends on Adobe's header :-) + + Use with extreme caution, but sometimes needed for printer tray commands. + Acrobat 4.0 will export Postscript to a printer or file containing + the given commands. Adobe Reader 6.0 no longer does as this feature is + deprecated. 5.0, I don't know about (please let us know!). This was + funded by Bob Marshall of Vector.co.uk and tested on a Lexmark 750. + See test_pdfbase_postscript.py for 2 test cases - one will work on + any Postscript device, the other uses a 'setpapertray' command which + will error in Distiller but work on printers supporting it. + """ + #check if we've done this one already... + if isUnicode(command): + rawName = 'PS' + hashlib.md5(command.encode('utf-8'),usedforsecurity=False).hexdigest() + else: + rawName = 'PS' + hashlib.md5(command,usedforsecurity=False).hexdigest() + regName = self._doc.getXObjectName(rawName) + psObj = self._doc.idToObject.get(regName, None) + if not psObj: + #first use of this chunk of Postscript, make an object + psObj = pdfdoc.PDFPostScriptXObject(command + '\n') + self._setXObjects(psObj) + self._doc.Reference(psObj, regName) + self._doc.addForm(rawName, psObj) + if position == 0: + self._psCommandsBeforePage.append("/%s Do" % regName) + elif position==1: + self._code.append("/%s Do" % regName) + else: + self._psCommandsAfterPage.append("/%s Do" % regName) + + self._formsinuse.append(rawName) + + def _absRect(self,rect,relative=0): + if not rect: + w,h = self._pagesize + rect = (0,0,w,h) + elif relative: + lx, ly, ux, uy = rect + xll,yll = self.absolutePosition(lx,ly) + xur,yur = self.absolutePosition(ux, uy) + xul,yul = self.absolutePosition(lx, uy) + xlr,ylr = self.absolutePosition(ux, ly) + xs = xll, xur, xul, xlr + ys = yll, yur, yul, ylr + xmin, ymin = min(xs), min(ys) + xmax, ymax = max(xs), max(ys) + rect = xmin, ymin, xmax, ymax + bw = self._getCmShift() + if bw: + rect = rect[0]+bw,rect[1]+bw,rect[2]+bw,rect[3]+bw + return rect + + def freeTextAnnotation(self, contents, DA, Rect=None, addtopage=1, name=None, relative=0, **kw): + """DA is the default appearance string???""" + Rect = self._absRect(Rect,relative) + self._addAnnotation(pdfdoc.FreeTextAnnotation(Rect, contents, DA, **kw), name, addtopage) + + def textAnnotation(self, contents, Rect=None, addtopage=1, name=None, relative=0, **kw): + """Experimental, but works. + """ + Rect = self._absRect(Rect,relative) + self._addAnnotation(pdfdoc.TextAnnotation(Rect, contents, **kw), name, addtopage) + textAnnotation0 = textAnnotation #deprecated + + def highlightAnnotation(self, contents, Rect, QuadPoints=None, Color=[0.83, 0.89, 0.95], addtopage=1, + name=None, relative=0, **kw): + """ + Allows adding of a highlighted annotation. + + Rect: Mouseover area to show contents of annotation + QuadPoints: List of four x/y points [TOP-LEFT, TOP-RIGHT, BOTTOM-LEFT, BOTTOM-RIGHT] + These points outline the areas to highlight. + You can have multiple groups of four to allow multiple highlighted areas. + Is in the format [x1, y1, x2, y2, x3, y3, x4, y4, x1, y1, x2, y2, x3, y3, x4, y4] etc + QuadPoints defaults to be area inside of passed in Rect + Color: The color of the highlighting. + """ + Rect = self._absRect(Rect, relative) + if not QuadPoints: + QuadPoints = pdfdoc.rect_to_quad(Rect) + self._addAnnotation(pdfdoc.HighlightAnnotation(Rect, contents, QuadPoints, Color, **kw), name, addtopage) + + def inkAnnotation(self, contents, InkList=None, Rect=None, addtopage=1, name=None, relative=0, **kw): + raise NotImplementedError + "Experimental" + Rect = self._absRect(Rect,relative) + if not InkList: + InkList = ((100,100,100,h-100,w-100,h-100,w-100,100),) + self._addAnnotation(pdfdoc.InkAnnotation(Rect, contents, InkList, **kw), name, addtopage) + inkAnnotation0 = inkAnnotation #deprecated + + def linkAbsolute(self, contents, destinationname, Rect=None, addtopage=1, name=None, + thickness=0, color=None, dashArray=None, **kw): + """rectangular link annotation positioned wrt the default user space. + The identified rectangle on the page becomes a "hot link" which + when clicked will send the viewer to the page and position identified + by the destination. + + Rect identifies (lowerx, lowery, upperx, uppery) for lower left + and upperright points of the rectangle. Translations and other transforms + are IGNORED (the rectangular position is given with respect + to the default user space. + destinationname should be the name of a bookmark (which may be defined later + but must be defined before the document is generated). + + You may want to use the keyword argument Border='[0 0 0]' to + suppress the visible rectangle around the during viewing link.""" + return self.linkRect(contents, destinationname, Rect, addtopage, name, relative=0, + thickness=thickness, color=color, dashArray=dashArray, **kw) + + def linkRect(self, contents, destinationname, Rect=None, addtopage=1, name=None, relative=1, + thickness=0, color=None, dashArray=None, **kw): + """rectangular link annotation w.r.t the current user transform. + if the transform is skewed/rotated the absolute rectangle will use the max/min x/y + """ + destination = self._bookmarkReference(destinationname) # permitted to be undefined... must bind later... + Rect = self._absRect(Rect,relative) + kw["Rect"] = Rect + kw["Contents"] = contents + kw["Destination"] = destination + _annFormat(kw,color,thickness,dashArray) + return self._addAnnotation(pdfdoc.LinkAnnotation(**kw), name, addtopage) + + def linkURL(self, url, rect, relative=0, thickness=0, color=None, dashArray=None, kind="URI", **kw): + """Create a rectangular URL 'hotspot' in the given rectangle. + + if relative=1, this is in the current coord system, otherwise + in absolute page space. + The remaining options affect the border appearance; the border is + drawn by Acrobat, not us. Set thickness to zero to hide it. + Any border drawn this way is NOT part of the page stream and + will not show when printed to a Postscript printer or distilled; + it is safest to draw your own.""" + from reportlab.pdfbase.pdfdoc import PDFDictionary, PDFName, PDFArray, PDFString + #tried the documented BS element in the pdf spec but it + #does not work, and Acrobat itself does not appear to use it! + + ann = PDFDictionary(dict=kw) + ann["Type"] = PDFName("Annot") + ann["Subtype"] = PDFName("Link") + ann["Rect"] = PDFArray(self._absRect(rect,relative)) # the whole page for testing + + # the action is a separate dictionary + A = PDFDictionary() + A["Type"] = PDFName("Action") # not needed? + uri = PDFString(url) + A['S'] = PDFName(kind) + if kind=="URI": + A["URI"] = uri + elif kind=='GoToR': + A["F"] = uri + A["D"] = "[ 0 /XYZ null null null ]" + else: + raise ValueError("Unknown linkURI kind '%s'" % kind) + + ann["A"] = A + _annFormat(ann,color,thickness,dashArray) + self._addAnnotation(ann) + + def _addAnnotation(self, annotation, name=None, addtopage=1): + count = self._annotationCount = self._annotationCount+1 + if not name: name="NUMBER"+repr(count) + self._doc.addAnnotation(name, annotation) + if addtopage: + self._annotatePage(name) + + def _annotatePage(self, name): + ref = self._doc.refAnnotation(name) + self._annotationrefs.append(ref) + + def getPageNumber(self): + "get the page number for the current page being generated." + return self._pageNumber + + def save(self): + """Saves and close the PDF document in the file. + If there is current data a ShowPage is executed automatically. + After this operation the canvas must not be used further.""" + if len(self._code): self.showPage() + self._doc.SaveToFile(self._filename, self) + + def getpdfdata(self): + """Returns the PDF data that would normally be written to a file. + If there is current data a ShowPage is executed automatically. + After this operation the canvas must not be used further.""" + if len(self._code): self.showPage() + s = self._doc.GetPDFData(self) + if isUnicode(s): + s = s.encode('utf-8') + return s + + def setPageSize(self, size): + """accepts a 2-tuple in points for paper size for this + and subsequent pages""" + self._pagesize = size + self._make_preamble() + + def setCropBox(self, size, name='crop'): + """accepts a 2-tuple in points for name+'Box' size for this and subsequent pages""" + name = name.lower() + if name.endswith('box'): name = name[:-3] + if name not in ('crop','art','trim','bleed'): + raise ValueError('unknown box name: %r' % name) + setattr(self,'_%sBox' % name, size) + + def setTrimBox(self,size): + self.setCropBox(size,name='trim') + + def setArtBox(self,size): + self.setCropBox(size,name='art') + + def setBleedBox(self,size): + self.setCropBox(size,name='bleed') + + def setPageRotation(self, rot): + """Instruct display device that this page is to be rotated""" + assert rot % 90.0 == 0.0, "Rotation must be a multiple of 90 degrees" + self._pageRotation = rot + + def addLiteral(self, s, escaped=1): + """introduce the literal text of PDF operations s into the current stream. + Only use this if you are an expert in the PDF file format.""" + s = str(s) # make sure its a string + if escaped==0: + s = self._escape(s) # convert to string for safety + self._code.append(s) + + ###################################################################### + # + # coordinate transformations + # + ###################################################################### + def resetTransforms(self): + """I want to draw something (eg, string underlines) w.r.t. the default user space. + Reset the matrix! This should be used usually as follows:: + + canv.saveState() + canv.resetTransforms() + #...draw some stuff in default space coords... + canv.restoreState() # go back! + """ + # we have to adjoin the inverse, since reset is not a basic operation (without save/restore) + (selfa, selfb, selfc, selfd, selfe, selff) = self._currentMatrix + det = selfa*selfd - selfc*selfb + resulta = selfd/det + resultc = -selfc/det + resulte = (selfc*selff - selfd*selfe)/det + resultd = selfa/det + resultb = -selfb/det + resultf = (selfe*selfb - selff*selfa)/det + self.transform(resulta, resultb, resultc, resultd, resulte, resultf) + + def transform(self, a,b,c,d,e,f): + """adjoin a mathematical transform to the current graphics state matrix. + Not recommended for beginners.""" + #How can Python track this? + if ENABLE_TRACKING: + a0,b0,c0,d0,e0,f0 = self._currentMatrix + self._currentMatrix = (a0*a+c0*b, b0*a+d0*b, + a0*c+c0*d, b0*c+d0*d, + a0*e+c0*f+e0, b0*e+d0*f+f0) + if self._code and self._code[-1][-3:]==' cm': + L = self._code[-1].split() + a0, b0, c0, d0, e0, f0 = list(map(float,L[-7:-1])) + s = len(L)>7 and join(L)+ ' %s cm' or '%s cm' + self._code[-1] = s % fp_str(a0*a+c0*b,b0*a+d0*b,a0*c+c0*d,b0*c+d0*d,a0*e+c0*f+e0,b0*e+d0*f+f0) + else: + self._code.append('%s cm' % fp_str(a,b,c,d,e,f)) + + def absolutePosition(self, x, y): + """return the absolute position of x,y in user space w.r.t. default user space""" + if not ENABLE_TRACKING: + raise ValueError("tracking not enabled! (canvas.ENABLE_TRACKING=0)") + (a,b,c,d,e,f) = self._currentMatrix + xp = a*x + c*y + e + yp = b*x + d*y + f + return (xp, yp) + + def translate(self, dx, dy): + """move the origin from the current (0,0) point to the (dx,dy) point + (with respect to the current graphics state).""" + self.transform(1,0,0,1,dx,dy) + + def scale(self, x, y): + """Scale the horizontal dimension by x and the vertical by y + (with respect to the current graphics state). + For example canvas.scale(2.0, 0.5) will make everything short and fat.""" + self.transform(x,0,0,y,0,0) + + def rotate(self, theta): + """Canvas.rotate(theta) + + Rotate the canvas by the angle theta (in degrees).""" + c = cos(theta * pi / 180) + s = sin(theta * pi / 180) + self.transform(c, s, -s, c, 0, 0) + + def skew(self, alpha, beta): + tanAlpha = tan(alpha * pi / 180) + tanBeta = tan(beta * pi / 180) + self.transform(1, tanAlpha, tanBeta, 1, 0, 0) + + ###################################################################### + # + # graphics state management + # + ###################################################################### + + def saveState(self): + """Save the current graphics state to be restored later by restoreState. + + For example: + canvas.setFont("Helvetica", 20) + canvas.saveState() + ... + canvas.setFont("Courier", 9) + ... + canvas.restoreState() + # if the save/restore pairs match then font is Helvetica 20 again. + """ + self.push_state_stack() + self._code.append('q') + + def restoreState(self): + """restore the graphics state to the matching saved state (see saveState).""" + self._code.append('Q') + self.pop_state_stack() + + ############################################################### + # + # Drawing methods. These draw things directly without + # fiddling around with Path objects. We can add any geometry + # methods we wish as long as their meaning is precise and + # they are of general use. + # + # In general there are two patterns. Closed shapes + # have the pattern shape(self, args, stroke=1, fill=0); + # by default they draw an outline only. Line segments come + # in three flavours: line, bezier, arc (which is a segment + # of an elliptical arc, approximated by up to four bezier + # curves, one for each quadrant. + # + # In the case of lines, we provide a 'plural' to unroll + # the inner loop; it is useful for drawing big grids + ################################################################ + + #--------first the line drawing methods----------------------- + + def line(self, x1,y1, x2,y2): + """draw a line segment from (x1,y1) to (x2,y2) (with color, thickness and + other attributes determined by the current graphics state).""" + self._code.append('n %s m %s l S' % (fp_str(x1, y1), fp_str(x2, y2))) + + def lines(self, linelist): + """Like line(), permits many lines to be drawn in one call. + for example for the figure:: + + | + -- -- + | + + crosshairs = [(20,0,20,10), (20,30,20,40), (0,20,10,20), (30,20,40,20)] + canvas.lines(crosshairs) + """ + self._code.append('n') + for (x1,y1,x2,y2) in linelist: + self._code.append('%s m %s l' % (fp_str(x1, y1), fp_str(x2, y2))) + self._code.append('S') + + def cross(self, x, y, size=5, gap=1, text=None, strokeColor=None, strokeWidth=None, fontSize=3): + size *= 0.5 + gap *= 0.5 + crosshairs = [(x,y-size,x,y-gap),(x,y+gap,x,y+size), (x-size,y,x-gap,y),(x+gap,y,x+size,y)] + self.saveState() + if strokeColor: + self.setStrokeColor(strokeColor) + if text: + self.setFillColor(strokeColor) + if strokeWidth: + self.setLineWidth(strokeWidth) + self.lines(crosshairs) + if text: + if fontSize is not None: self.setFontSize(fontSize) + self.drawRightString(x-size, y, text) + self.restoreState() + + def grid(self, xlist, ylist): + """Lays out a grid in current line style. Supply list of + x an y positions.""" + assert len(xlist) > 1, "x coordinate list must have 2+ items" + assert len(ylist) > 1, "y coordinate list must have 2+ items" + lines = [] + y0, y1 = ylist[0], ylist[-1] + x0, x1 = xlist[0], xlist[-1] + for x in xlist: + lines.append((x,y0,x,y1)) + for y in ylist: + lines.append((x0,y,x1,y)) + self.lines(lines) + + def bezier(self, x1, y1, x2, y2, x3, y3, x4, y4): + "Bezier curve with the four given control points" + self._code.append('n %s m %s c S' % + (fp_str(x1, y1), fp_str(x2, y2, x3, y3, x4, y4)) + ) + def arc(self, x1,y1, x2,y2, startAng=0, extent=90): + """Draw a partial ellipse inscribed within the rectangle x1,y1,x2,y2, + starting at startAng degrees and covering extent degrees. Angles + start with 0 to the right (+x) and increase counter-clockwise. + These should have x1 + from reportlab.pdfbase.pdfdoc import PDFAxialShading + colorSpace, ncolors = _normalizeColors(colors) + fcn = _buildColorFunction(ncolors, positions) + shading = PDFAxialShading(x0, y0, x1, y1, Function=fcn, + ColorSpace=colorSpace, Extend=_gradientExtendStr(extend)) + self.shade(shading) + + def radialGradient(self, x, y, radius, colors, positions=None, extend=True): + #this code contributed by Peter Johnson + from reportlab.pdfbase.pdfdoc import PDFRadialShading + colorSpace, ncolors = _normalizeColors(colors) + fcn = _buildColorFunction(ncolors, positions) + shading = PDFRadialShading(x, y, 0.0, x, y, radius, Function=fcn, + ColorSpace=colorSpace, Extend=_gradientExtendStr(extend)) + self.shade(shading) + + ################################################## + # + # Text methods + # + # As with graphics, a separate object ensures that + # everything is bracketed between text operators. + # The methods below are a high-level convenience. + # use PDFTextObject for multi-line text. + ################################################## + + def drawString(self, x, y, text, mode=None, charSpace=0, direction=None, wordSpace=None, shaping=False): + """Draws a string in the current text styles.""" + text, width = bidiShapedText(text,direction,fontName=self._fontname,fontSize=self._fontsize, shaping=shaping) + #we could inline this for speed if needed + t = self.beginText(x, y, direction=direction) + if mode is not None: t.setTextRenderMode(mode) + if charSpace: t.setCharSpace(charSpace) + if wordSpace: t.setWordSpace(wordSpace) + t.textLine(text) + if charSpace: t.setCharSpace(0) + if wordSpace: t.setWordSpace(0) + if mode is not None: t.setTextRenderMode(0) + self.drawText(t) + + def drawRightString(self, x, y, text, mode=None, charSpace=0, direction=None, wordSpace=None, shaping=False): + """Draws a string right-aligned with the x coordinate""" + text, width = bidiShapedText(text,direction,fontName=self._fontname,fontSize=self._fontsize, shaping=shaping) + if charSpace: width += (len(text)-1)*charSpace + if wordSpace: width += (text.count(u' ')+text.count(u'\xa0')-1)*wordSpace + t = self.beginText(x - width, y) + if mode is not None: t.setTextRenderMode(mode) + if charSpace: t.setCharSpace(charSpace) + if wordSpace: t.setWordSpace(wordSpace) + t.textLine(text) + if charSpace: t.setCharSpace(0) + if wordSpace: t.setWordSpace(0) + if mode is not None: t.setTextRenderMode(0) + self.drawText(t) + + def drawCentredString(self, x, y, text, mode=None, charSpace=0, direction=None, wordSpace=None, shaping=False): + """Draws a string centred on the x coordinate. + + We're British, dammit, and proud of our spelling!""" + text, width = bidiShapedText(text,direction,fontName=self._fontname,fontSize=self._fontsize, shaping=shaping) + if charSpace: width += (len(text)-1)*charSpace + if wordSpace: width += (text.count(u' ')+text.count(u'\xa0')-1)*wordSpace + t = self.beginText(x - 0.5*width, y) + if mode is not None: t.setTextRenderMode(mode) + if charSpace: t.setCharSpace(charSpace) + if wordSpace: t.setWordSpace(wordSpace) + t.textLine(text) + if charSpace: t.setCharSpace(0) + if wordSpace: t.setWordSpace(0) + if mode is not None: t.setTextRenderMode(0) + self.drawText(t) + + def drawAlignedString(self, x, y, text, pivotChar=rl_config.decimalSymbol, mode=None, charSpace=0, direction=None, wordSpace=None, shaping=False): + """Draws a string aligned on the first '.' (or other pivot character). + + The centre position of the pivot character will be used as x. + So, you could draw a straight line down through all the decimals in a + column of numbers, and anything without a decimal should be + optically aligned with those that have. + + There is one special rule to help with accounting formatting. Here's + how normal numbers should be aligned on the 'dot'. Look at the + LAST two:: + + 12,345,67 + 987.15 + 42 + -1,234.56 + (456.78) + (456) + 27 inches + 13cm + + Since the last three do not contain a dot, a crude dot-finding + rule would place them wrong. So we test for the special case + where no pivot is found, digits are present, but the last character + is not a digit. We then work back from the end of the string + This case is a tad slower but hopefully rare. + + """ + parts = text.split(pivotChar,1) + pivW = self.stringWidth(pivotChar, self._fontname, self._fontsize) + + if len(parts) == 1 and digitPat.search(text) is not None and text[-1] not in digits: + #we have no decimal but it ends in a bracket, or 'in' or something. + #the cut should be after the last digit. + leftText = parts[0][0:-1] + rightText = parts[0][-1] + #any more? + while leftText[-1] not in digits: + rightText = leftText[-1] + rightText + leftText = leftText[0:-1] + + self.drawRightString(x-0.5*pivW, y, leftText, mode=mode, charSpace=charSpace, + direction=direction, wordSpace=wordSpace, shaping=shaping) + self.drawString(x-0.5*pivW, y, rightText, mode=mode, charSpace=charSpace, + direction=direction, wordSpace=wordSpace, shaping=shaping) + + else: + #normal case + leftText = parts[0] + self.drawRightString(x-0.5*pivW, y, leftText, mode=mode, charSpace=charSpace, + direction=direction, wordSpace=wordSpace, shaping=shaping) + if len(parts) > 1: + rightText = pivotChar + parts[1] + self.drawString(x-0.5*pivW, y, rightText, mode=mode, charSpace=charSpace, + direction=direction, wordSpace=wordSpace, shaping=shaping) + + def getAvailableFonts(self): + """Returns the list of PostScript font names available. + + Standard set now, but may grow in future with font embedding.""" + fontnames = self._doc.getAvailableFonts() + return fontnames + + def listLoadedFonts0(self): + "Convenience function to list all loaded fonts" + names = list(pdfmetrics.widths.keys()) + names.sort() + return names + + def setFont(self, psfontname, size, leading = None): + """Sets the font. If leading not specified, defaults to 1.2 x + font size. Raises a readable exception if an illegal font + is supplied. Font names are case-sensitive! Keeps track + of font name and size for metrics.""" + self._fontname = psfontname + self._fontsize = size + if leading is None: + leading = size * 1.2 + self._leading = leading + font = pdfmetrics.getFont(self._fontname) + if not font._dynamicFont: + if font.face.builtIn or not getattr(self,'_drawTextAsPath',False): + pdffontname = self._doc.getInternalFontName(psfontname) + self._code.append('BT %s %s Tf %s TL ET' % (pdffontname, fp_str(size), fp_str(leading))) + + def setFontSize(self, size=None, leading=None): + '''Sets font size or leading without knowing the font face''' + if size is None: size = self._fontsize + if leading is None: leading = self._leading + self.setFont(self._fontname, size, leading) + + def stringWidth(self, text, fontName=None, fontSize=None): + "gets width of a string in the given font and size" + return pdfmetrics.stringWidth(text, fontName or self._fontname, + (fontSize,self._fontsize)[fontSize is None]) + + # basic graphics modes + + def setLineWidth(self, width): + self._lineWidth = width + self._code.append('%s w' % fp_str(width)) + + def setLineCap(self, mode): + """0=butt,1=round,2=square""" + assert mode in (0,1,2), "Line caps allowed: 0=butt,1=round,2=square" + self._lineCap = mode + self._code.append('%d J' % mode) + + def setLineJoin(self, mode): + """0=mitre, 1=round, 2=bevel""" + assert mode in (0,1,2), "Line Joins allowed: 0=mitre, 1=round, 2=bevel" + self._lineJoin = mode + self._code.append('%d j' % mode) + + def setMiterLimit(self, limit): + self._miterLimit = limit + self._code.append('%s M' % fp_str(limit)) + + def setDash(self, array=[], phase=0): + """Two notations. pass two numbers, or an array and phase""" + reason = '' + if isinstance(array,(int,float)): + array = (array, phase) + phase = 0 + elif not isSeq(array): + reason = 'array should be a sequence of numbers or a number' + bad = [_ for _ in array if not isinstance(_,(int,float)) or _ < 0] + if bad or not isinstance(phase,(int,float)) or phase<0: + reason = 'array & phase should be non-negative numbers' + elif array and sum(array)<=0: + reason = 'dash cycle should be larger than zero' + if reason: + raise ValueError('setDash: array=%r phase=%r\n%s' % (array, phase, reason)) + self._code.append('[%s] %s d' % (fp_str(array), phase)) + + # path stuff - the separate path object builds it + + def beginPath(self): + """Returns a fresh path object. Paths are used to draw + complex figures. The object returned follows the protocol + for a pathobject.PDFPathObject instance""" + return pathobject.PDFPathObject() + + def drawPath(self, aPath, stroke=1, fill=0, fillMode=None): + "Draw the path object in the mode indicated" + if fillMode is None: + fillMode = getattr(aPath,'_fillMode',self._fillMode) + self._code.append(str(aPath.getCode())) + self._strokeAndFill(stroke,fill,fillMode) + + def _strokeAndFill(self,stroke,fill,fillMode=None): + self._code.append(PATH_OPS[stroke, fill, fillMode if fillMode is not None else self._fillMode]) + + def clipPath(self, aPath, stroke=1, fill=0, fillMode=None): + "clip as well as drawing" + if fillMode is None: + fillMode = getattr(aPath,'_fillMode',self._fillMode) + gc = aPath.getCode(); pathops = PATH_OPS[stroke, fill, fillMode] + clip = (fillMode == FILL_EVEN_ODD and ' W* ' or ' W ') + item = "%s%s%s" % (gc, clip, pathops) # ensure string conversion + self._code.append(item) + #self._code.append( aPath.getCode() + # + (self._fillMode == FILL_EVEN_ODD and ' W* ' or ' W ') + # + PATH_OPS[stroke,fill,self._fillMode]) + + def beginText(self, x=0, y=0, direction=None): + """Returns a fresh text object. Text objects are used + to add large amounts of text. See PDFTextObject""" + return PDFTextObject(self, x, y, direction=direction) + + def drawText(self, aTextObject): + """Draws a text object""" + self._code.append(str(aTextObject.getCode())) + + def setPageCompression(self, pageCompression=1): + """Possible values None, 1 or 0 + If None the value from rl_config will be used. + If on, the page data will be compressed, leading to much + smaller files, but takes a little longer to create the files. + This applies to all subsequent pages, or until setPageCompression() + is next called.""" + if pageCompression is None: pageCompression = rl_config.pageCompression + self._pageCompression = pageCompression + self._doc.setCompression(self._pageCompression) + + def setPageDuration(self, duration=None): + """Allows hands-off animation of presentations :-) + + If this is set to a number, in full screen mode, Acrobat Reader + will advance to the next page after this many seconds. The + duration of the transition itself (fade/flicker etc.) is controlled + by the 'duration' argument to setPageTransition; this controls + the time spent looking at the page. This is effective for all + subsequent pages.""" + + self._pageDuration = duration + + def setPageTransition(self, effectname=None, duration=1, + direction=0,dimension='H',motion='I'): + """PDF allows page transition effects for use when giving + presentations. There are six possible effects. You can + just guive the effect name, or supply more advanced options + to refine the way it works. There are three types of extra + argument permitted, and here are the allowed values:: + + direction_arg = [0,90,180,270] + dimension_arg = ['H', 'V'] + motion_arg = ['I','O'] (start at inside or outside) + + This table says which ones take which arguments:: + + PageTransitionEffects = { + 'Split': [direction_arg, motion_arg], + 'Blinds': [dimension_arg], + 'Box': [motion_arg], + 'Wipe' : [direction_arg], + 'Dissolve' : [], + 'Glitter':[direction_arg] + } + + Have fun! + """ + # This builds a Python dictionary with the right arguments + # for the Trans dictionary in the PDFPage object, + # and stores it in the variable _pageTransition. + # showPage later passes this to the setPageTransition method + # of the PDFPage object, which turns it to a PDFDictionary. + self._pageTransition = {} + if not effectname: + return + + #first check each optional argument has an allowed value + if direction in [0,90,180,270]: + direction_arg = ('Di', '/%d' % direction) + else: + raise pdfdoc.PDFError(' directions allowed are 0,90,180,270') + + if dimension in ['H', 'V']: + dimension_arg = ('Dm', '/' + dimension) + else: + raise pdfdoc.PDFError('dimension values allowed are H and V') + + if motion in ['I','O']: + motion_arg = ('M', '/' + motion) + else: + raise pdfdoc.PDFError('motion values allowed are I and O') + + # this says which effects require which argument types from above + PageTransitionEffects = { + 'Split': [direction_arg, motion_arg], + 'Blinds': [dimension_arg], + 'Box': [motion_arg], + 'Wipe' : [direction_arg], + 'Dissolve' : [], + 'Glitter':[direction_arg] + } + + try: + args = PageTransitionEffects[effectname] + except KeyError: + raise pdfdoc.PDFError('Unknown Effect Name "%s"' % effectname) + + # now build the dictionary + transDict = {} + transDict['Type'] = '/Trans' + transDict['D'] = '%d' % duration + transDict['S'] = '/' + effectname + for (key, value) in args: + transDict[key] = value + self._pageTransition = transDict + + def getCurrentPageContent(self): + """Return uncompressed contents of current page buffer. + + This is useful in creating test cases and assertions of what + got drawn, without necessarily saving pages to disk""" + return '\n'.join(self._code) + + def setViewerPreference(self,pref,value): + '''set one of the allowed enbtries in the documents viewer preferences''' + catalog = self._doc.Catalog + VP = getattr(catalog,'ViewerPreferences',None) + if VP is None: + from reportlab.pdfbase.pdfdoc import ViewerPreferencesPDFDictionary + VP = catalog.ViewerPreferences = ViewerPreferencesPDFDictionary() + VP[pref] = value + + def getViewerPreference(self,pref): + '''you'll get an error here if none have been set''' + return self._doc.Catalog.ViewerPreferences[pref] + + def delViewerPreference(self,pref): + '''you'll get an error here if none have been set''' + del self._doc.Catalog.ViewerPreferences[pref] + + def setCatalogEntry(self,key,value): + from reportlab.pdfbase.pdfdoc import PDFDictionary, PDFArray, PDFString + if isStr(value): + value = PDFString(value) + elif isinstance(value,(list,tuple)): + value = PDFArray(value) + elif isinstance(value,dict): + value = PDFDictionary(value) + setattr(self._doc.Catalog,key,value) + + def getCatalogEntry(self,key): + return getattr(self._doc.Catalog,key) + + def delCatalogEntry(self,key): + '''you'll get an error here if it's not been set''' + delattr(self._doc.Catalog,key) + + def addPageLabel(self, pageNum, style=None, start=None, prefix=None): + '''add a PDFPageLabel for pageNum''' + catalog = self._doc.Catalog + PL = getattr(catalog,'PageLabels',None) + if PL is None: + from reportlab.pdfbase.pdfdoc import PDFPageLabels + PL = catalog.PageLabels = PDFPageLabels() + + from reportlab.pdfbase.pdfdoc import PDFPageLabel + PL.addPageLabel(pageNum,PDFPageLabel(style,start,prefix)) + + @property + def acroForm(self): + "get form from canvas, create the form if needed" + try: + return self.AcroForm + except AttributeError: + from reportlab.pdfbase.acroform import AcroForm + self._doc._catalog.AcroForm = self.AcroForm = AcroForm(self) + return self.AcroForm + + def drawBoundary(self,sb,x1,y1,width,height): + "draw a boundary as a rectangle (primarily for debugging)." + ss = isinstance(sb,(str,tuple,list)) or isinstance(sb,Color) + w = -1 + da = None + if ss: + c = toColor(sb,-1) + ss = c != -1 + elif isinstance(sb,ShowBoundaryValue) and sb: + c = toColor(sb.color,-1) + ss = c != -1 + if ss: + w = sb.width + da = sb.dashArray + if ss: + self.saveState() + self.setStrokeColor(c) + if w>=0: self.setLineWidth(w) + if da: self.setDash(da) + self.rect(x1,y1,width,height) + if ss: self.restoreState() + + def setNamedCB(self, name, cb): + self._namedCB[name] = cb + + def getNamedCB(self,name): + return self._namedCB.get(name,None) + +if __name__ == '__main__': + print('For test scripts, look in tests') diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfgen/pathobject.py b/.venv/lib/python3.13/site-packages/reportlab/pdfgen/pathobject.py new file mode 100644 index 0000000000000000000000000000000000000000..fab148e07a07c58cd9b3adbd1a69392de80d06df --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfgen/pathobject.py @@ -0,0 +1,139 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/pdfgen/pathobject.py +__version__='3.3.0' +__doc__=""" +PDFPathObject is an efficient way to draw paths on a Canvas. Do not +instantiate directly, obtain one from the Canvas instead. + +Progress Reports: +8.83, 2000-01-13, gmcm: created from pdfgen.py + +""" + +from reportlab.pdfgen import pdfgeom +from reportlab.lib.rl_accel import fp_str + + +class PDFPathObject: + """Represents a graphic path. There are certain 'modes' to PDF + drawing, and making a separate object to expose Path operations + ensures they are completed with no run-time overhead. Ask + the Canvas for a PDFPath with getNewPathObject(); moveto/lineto/ + curveto wherever you want; add whole shapes; and then add it back + into the canvas with one of the relevant operators. + + Path objects are probably not long, so we pack onto one line + + the code argument allows a canvas to get the operations appended directly so + avoiding the final getCode + """ + def __init__(self,code=None): + self._code = (code,[])[code is None] + self._code_append = self._init_code_append + + def _init_code_append(self,c): + assert c.endswith(' m') or c.endswith(' re'), 'path must start with a moveto or rect' + code_append = self._code.append + code_append('n') + code_append(c) + self._code_append = code_append + + def getCode(self): + "pack onto one line; used internally" + return ' '.join(self._code) + + def moveTo(self, x, y): + self._code_append('%s m' % fp_str(x,y)) + + def lineTo(self, x, y): + self._code_append('%s l' % fp_str(x,y)) + + def curveTo(self, x1, y1, x2, y2, x3, y3): + self._code_append('%s c' % fp_str(x1, y1, x2, y2, x3, y3)) + + def arc(self, x1,y1, x2,y2, startAng=0, extent=90): + """Contributed to piddlePDF by Robert Kern, 28/7/99. + Draw a partial ellipse inscribed within the rectangle x1,y1,x2,y2, + starting at startAng degrees and covering extent degrees. Angles + start with 0 to the right (+x) and increase counter-clockwise. + These should have x1.""" + + self._curves(pdfgeom.bezierArc(x1,y1, x2,y2, startAng, extent)) + + def arcTo(self, x1,y1, x2,y2, startAng=0, extent=90): + """Like arc, but draws a line from the current point to + the start if the start is not the current point.""" + self._curves(pdfgeom.bezierArc(x1,y1, x2,y2, startAng, extent),'lineTo') + + def rect(self, x, y, width, height): + """Adds a rectangle to the path""" + self._code_append('%s re' % fp_str((x, y, width, height))) + + def ellipse(self, x, y, width, height): + """adds an ellipse to the path""" + self._curves(pdfgeom.bezierArc(x, y, x + width,y + height, 0, 360)) + + def _curves(self,curves,initial='moveTo'): + getattr(self,initial)(*curves[0][:2]) + for curve in curves: + self.curveTo(*curve[2:]) + + def circle(self, x_cen, y_cen, r): + """adds a circle to the path""" + x1 = x_cen - r + y1 = y_cen - r + width = height = 2*r + self.ellipse(x1, y1, width, height) + + def roundRect(self, x, y, width, height, radius): + """Draws a rectangle with rounded corners. The corners are + approximately quadrants of a circle, with the given radius.""" + #use a precomputed set of factors for the bezier approximation + #to a circle. There are six relevant points on the x axis and y axis. + #sketch them and it should all make sense! + m = 0.4472 #radius multiplier + xhi = x,x+width + xlo, xhi = min(xhi), max(xhi) + yhi = y,y+height + ylo, yhi = min(yhi), max(yhi) + if isinstance(radius,(list,tuple)): + r = [max(0,r) for r in radius] + if len(r)<4: r += (4-len(r))*[0] + self.moveTo(xlo + r[2], ylo) #start at bottom left + self.lineTo(xhi - r[3], ylo) #bottom row + if r[3]>0: + t = m*r[3] + self.curveTo(xhi - t, ylo, xhi, ylo + t, xhi, ylo + r[3]) #bottom right + self.lineTo(xhi, yhi - r[1]) #right edge + if r[1]>0: + t = m*r[1] + self.curveTo(xhi, yhi - t, xhi - t, yhi, xhi - r[1], yhi) #top right + self.lineTo(xlo + r[0], yhi) #top row + if r[0]>0: + t = m*r[0] + self.curveTo(xlo + t, yhi, xlo, yhi - t, xlo, yhi - r[0]) #top left + self.lineTo(xlo, ylo + r[2]) #left edge + if r[2]>0: + t = m*r[2] + self.curveTo(xlo, ylo + t, xlo + t, ylo, xlo + r[2], ylo) #bottom left + # 4 radii top left top right bittom left bottom right + else: + t = m * radius + self.moveTo(xlo + radius, ylo) + self.lineTo(xhi - radius, ylo) #bottom row + self.curveTo(xhi - t, ylo, xhi, ylo + t, xhi, ylo + radius) #bottom right + self.lineTo(xhi, yhi - radius) #right edge + self.curveTo(xhi, yhi - t, xhi - t, yhi, xhi - radius, yhi) #top right + self.lineTo(xlo + radius, yhi) #top row + self.curveTo(xlo + t, yhi, xlo, yhi - t, xlo, yhi - radius) #top left + self.lineTo(xlo, ylo + radius) #left edge + self.curveTo(xlo, ylo + t, xlo + t, ylo, xlo + radius, ylo) #bottom left + self.close() + + def close(self): + "draws a line back to where it started" + self._code_append('h') diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfgen/pdfgeom.py b/.venv/lib/python3.13/site-packages/reportlab/pdfgen/pdfgeom.py new file mode 100644 index 0000000000000000000000000000000000000000..55f05e4d4cf60af6c459eec566f9d036dbf93040 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfgen/pdfgeom.py @@ -0,0 +1,77 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/pdfgen/pdfgeom.py +__version__='3.3.0' +__doc__=""" +This module includes any mathematical methods needed for PIDDLE. +It should have no dependencies beyond the Python library. + +So far, just Robert Kern's bezierArc. +""" + +from math import sin, cos, pi, ceil + + +def bezierArc(x1,y1, x2,y2, startAng=0, extent=90): + """bezierArc(x1,y1, x2,y2, startAng=0, extent=90) --> List of Bezier +curve control points. + +(x1, y1) and (x2, y2) are the corners of the enclosing rectangle. The +coordinate system has coordinates that increase to the right and down. +Angles, measured in degress, start with 0 to the right (the positive X +axis) and increase counter-clockwise. The arc extends from startAng +to startAng+extent. I.e. startAng=0 and extent=180 yields an openside-down +semi-circle. + +The resulting coordinates are of the form (x1,y1, x2,y2, x3,y3, x4,y4) +such that the curve goes from (x1, y1) to (x4, y4) with (x2, y2) and +(x3, y3) as their respective Bezier control points.""" + + x1,y1, x2,y2 = min(x1,x2), max(y1,y2), max(x1,x2), min(y1,y2) + + if abs(extent) <= 90: + arcList = [startAng] + fragAngle = float(extent) + Nfrag = 1 + else: + arcList = [] + Nfrag = int(ceil(abs(extent)/90.)) + fragAngle = float(extent) / Nfrag + + x_cen = (x1+x2)/2. + y_cen = (y1+y2)/2. + rx = (x2-x1)/2. + ry = (y2-y1)/2. + halfAng = fragAngle * pi / 360. + kappa = abs(4. / 3. * (1. - cos(halfAng)) / sin(halfAng)) + + if fragAngle < 0: + sign = -1 + else: + sign = 1 + + pointList = [] + + for i in range(Nfrag): + theta0 = (startAng + i*fragAngle) * pi / 180. + theta1 = (startAng + (i+1)*fragAngle) *pi / 180. + if fragAngle > 0: + pointList.append((x_cen + rx * cos(theta0), + y_cen - ry * sin(theta0), + x_cen + rx * (cos(theta0) - kappa * sin(theta0)), + y_cen - ry * (sin(theta0) + kappa * cos(theta0)), + x_cen + rx * (cos(theta1) + kappa * sin(theta1)), + y_cen - ry * (sin(theta1) - kappa * cos(theta1)), + x_cen + rx * cos(theta1), + y_cen - ry * sin(theta1))) + else: + pointList.append((x_cen + rx * cos(theta0), + y_cen - ry * sin(theta0), + x_cen + rx * (cos(theta0) + kappa * sin(theta0)), + y_cen - ry * (sin(theta0) - kappa * cos(theta0)), + x_cen + rx * (cos(theta1) - kappa * sin(theta1)), + y_cen - ry * (sin(theta1) + kappa * cos(theta1)), + x_cen + rx * cos(theta1), + y_cen - ry * sin(theta1))) + + return pointList \ No newline at end of file diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfgen/pdfimages.py b/.venv/lib/python3.13/site-packages/reportlab/pdfgen/pdfimages.py new file mode 100644 index 0000000000000000000000000000000000000000..dba35f88d787d73057778f5cc529169fd04b1205 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfgen/pdfimages.py @@ -0,0 +1,215 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/pdfgen/pdfimages.py +__version__='3.3.0' +__doc__=""" +Image functionality sliced out of canvas.py for generalization +""" + +import os +import reportlab +from reportlab import rl_config +from reportlab.pdfbase import pdfutils +from reportlab.pdfbase import pdfdoc +from reportlab.lib.utils import isStr +from reportlab.lib.rl_accel import fp_str, asciiBase85Encode +from reportlab.lib.boxstuff import aspectRatioFix + + +class PDFImage: + """Wrapper around different "image sources". You can make images + from a PIL Image object, a filename (in which case it uses PIL), + an image we previously cached (optimisation, hardly used these + days) or a JPEG (which PDF supports natively).""" + + def __init__(self, image, x,y, width=None, height=None, caching=0): + self.image = image + self.x = x + self.y = y + self.width = width + self.height = height + self.filename = None + self.imageCaching = caching + # the following facts need to be determined, + # whatever the source. Declare what they are + # here for clarity. + self.colorSpace = 'DeviceRGB' + self.bitsPerComponent = 8 + self.filters = [] + self.source = None # JPEG or PIL, set later + self.getImageData() + + def jpg_imagedata(self): + #directly process JPEG files + #open file, needs some error handling!! + fp = open(self.image, 'rb') + try: + result = self._jpg_imagedata(fp) + finally: + fp.close() + return result + + def _jpg_imagedata(self,imageFile): + info = pdfutils.readJPEGInfo(imageFile) + self.source = 'JPEG' + imgwidth, imgheight = info[0], info[1] + if info[2] == 1: + colorSpace = 'DeviceGray' + elif info[2] == 3: + colorSpace = 'DeviceRGB' + else: #maybe should generate an error, is this right for CMYK? + colorSpace = 'DeviceCMYK' + imageFile.seek(0) #reset file pointer + imagedata = [] + #imagedata.append('BI /Width %d /Height /BitsPerComponent 8 /ColorSpace /%s /Filter [/Filter [ /ASCII85Decode /DCTDecode] ID' % (info[0], info[1], colorSpace)) + imagedata.append('BI /W %d /H %d /BPC 8 /CS /%s /F [%s/DCT] ID' % (imgwidth, imgheight, colorSpace, rl_config.useA85 and '/A85 ' or '')) + #write in blocks of (??) 60 characters per line to a list + data = imageFile.read() + if rl_config.useA85: + data = asciiBase85Encode(data) + pdfutils._chunker(data,imagedata) + imagedata.append('EI') + return (imagedata, imgwidth, imgheight) + + def cache_imagedata(self): + image = self.image + if not pdfutils.cachedImageExists(image): + pdfutils.cacheImageFile(image) + + #now we have one cached, slurp it in + cachedname = os.path.splitext(image)[0] + (rl_config.useA85 and '.a85' or '.bin') + imagedata = open(cachedname,'rb').readlines() + #trim off newlines... + imagedata = list(map(str.strip, imagedata)) + return imagedata + + def PIL_imagedata(self): + import zlib + image = self.image + if image.format=='JPEG': + fp=image.fp + fp.seek(0) + return self._jpg_imagedata(fp) + self.source = 'PIL' + + bpc = 8 + # Use the colorSpace in the image + if image.mode == 'CMYK': + myimage = image + colorSpace = 'DeviceCMYK' + bpp = 4 + elif image.mode == '1': + myimage = image + colorSpace = 'DeviceGray' + bpp = 1 + bpc = 1 + elif image.mode == 'L': + myimage = image + colorSpace = 'DeviceGray' + bpp = 1 + else: + myimage = image.convert('RGB') + colorSpace = 'RGB' + bpp = 3 + imgwidth, imgheight = myimage.size + + # this describes what is in the image itself + # *NB* according to the spec you can only use the short form in inline images + imagedata=['BI /W %d /H %d /BPC %d /CS /%s /F [%s/Fl] ID' % (imgwidth, imgheight, bpc, colorSpace, rl_config.useA85 and '/A85 ' or '')] + + #use a flate filter and, optionally, Ascii Base 85 to compress + raw = (myimage.tobytes if hasattr(myimage,'tobytes') else myimage.tostring)() + rowstride = (imgwidth*bpc*bpp+7)>>3 + assert len(raw) == rowstride*imgheight, "Wrong amount of data for image" + data = zlib.compress(raw) #this bit is very fast... + if rl_config.useA85: + data = asciiBase85Encode(data) #...sadly this may not be + #append in blocks of 60 characters + pdfutils._chunker(data,imagedata) + imagedata.append('EI') + return (imagedata, imgwidth, imgheight) + + def non_jpg_imagedata(self,image): + if not self.imageCaching: + imagedata = pdfutils.cacheImageFile(image,returnInMemory=1) + else: + imagedata = self.cache_imagedata() + words = imagedata[1].split() + imgwidth = int(words[1]) + imgheight = int(words[3]) + return imagedata, imgwidth, imgheight + + def getImageData(self,preserveAspectRatio=False): + "Gets data, height, width - whatever type of image" + image = self.image + + if isStr(image): + self.filename = image + if os.path.splitext(image)[1] in ['.jpg', '.JPG', '.jpeg', '.JPEG']: + try: + imagedata, imgwidth, imgheight = self.jpg_imagedata() + except: + imagedata, imgwidth, imgheight = self.non_jpg_imagedata(image) #try for normal kind of image + else: + imagedata, imgwidth, imgheight = self.non_jpg_imagedata(image) + else: + imagedata, imgwidth, imgheight = self.PIL_imagedata() + self.imageData = imagedata + self.imgwidth = imgwidth + self.imgheight = imgheight + self.width = self.width or imgwidth + self.height = self.height or imgheight + + def drawInlineImage(self, canvas, preserveAspectRatio=False,anchor='sw', anchorAtXY=False, + showBoundary=False, extraReturn=None): + """Draw an Image into the specified rectangle. If width and + height are omitted, they are calculated from the image size. + Also allow file names as well as images. This allows a + caching mechanism""" + width = self.width + height = self.height + if width<1e-6 or height<1e-6: return False + x,y,self.width,self.height, scaled = aspectRatioFix(preserveAspectRatio,anchor,self.x,self.y,width,height,self.imgwidth,self.imgheight,anchorAtXY) + # this says where and how big to draw it + if not canvas.bottomup: y = y+height + canvas._code.append('q %s 0 0 %s cm' % (fp_str(self.width), fp_str(self.height, x, y))) + width = self.width + height = self.height + # self._code.extend(imagedata) if >=python-1.5.2 + for line in self.imageData: + canvas._code.append(line) + canvas._code.append('Q') + if showBoundary: + canvas.drawBoundary(showBoundary,x,y,width,height) + if extraReturn: + for k in extraReturn.keys(): + extraReturn[k] = vars()[k] + return True + + def format(self, document): + """Allow it to be used within pdfdoc framework. This only + defines how it is stored, not how it is drawn later.""" + + dict = pdfdoc.PDFDictionary() + dict['Type'] = '/XObject' + dict['Subtype'] = '/Image' + dict['Width'] = self.width + dict['Height'] = self.height + dict['BitsPerComponent'] = 8 + dict['ColorSpace'] = pdfdoc.PDFName(self.colorSpace) + content = '\n'.join(self.imageData[3:-1]) + '\n' + strm = pdfdoc.PDFStream(dictionary=dict, content=content) + return strm.format(document) + +if __name__=='__main__': + srcfile = os.path.join( + os.path.dirname(reportlab.__file__), + 'test', + 'pythonpowered.gif' + ) + assert os.path.isfile(srcfile), 'image not found' + pdfdoc.LongFormat = 1 + img = PDFImage(srcfile, 100, 100) + doc = pdfdoc.PDFDocument() + print('source=',img.source) + print(img.format(doc)) diff --git a/.venv/lib/python3.13/site-packages/reportlab/pdfgen/textobject.py b/.venv/lib/python3.13/site-packages/reportlab/pdfgen/textobject.py new file mode 100644 index 0000000000000000000000000000000000000000..1908040a0c196c113ba837bfb66382165273ed59 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/pdfgen/textobject.py @@ -0,0 +1,751 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/pdfgen/textobject.py +__version__='3.3.0' +__doc__=""" +PDFTextObject is an efficient way to add text to a Canvas. Do not +instantiate directly, obtain one from the Canvas instead. + +Progress Reports: +8.83, 2000-01-13, gmcm: created from pdfgen.py +""" +from reportlab.lib.colors import Color, CMYKColor, CMYKColorSep, toColor +from reportlab.lib.utils import isBytes, isStr, asUnicode +from reportlab.lib.rl_accel import fp_str +from reportlab.pdfbase.pdfmetrics import getFont as pdfmetrics_getFont, stringWidth as pdfmetrics_stringWidth, unicode2T1 as pdfmetrics_unicode2T1 +from reportlab.pdfbase.ttfonts import ShapedStr, ShapeData, _sdGuardL, shapeStr +from itertools import groupby +from operator import itemgetter + +#this is to handle the optionality of rlbidi +try: + import rlbidi + log2vis = rlbidi.log2vis + class BidiStr(str): + '''A str with indices visual __bidiV__, logical __bidiL__''' + def __new__(cls, s, bidiV=-1, bidiL=-1): + self = super().__new__(cls,s) + self.__bidiV__ = bidiV + self.__bidiL__ = bidiL + return self + isBidiStr = lambda _: isinstance(_,BidiStr) + class BidiList(list): + '''A list with indices visual __bidiV__, logical __bidiL__''' + def __init__(self, L, bidiV=-1, bidiL=-1): + super().__init__(L) + self.__bidiV__ = bidiV + self.__bidiL__ = bidiL + def __repr__(self): + return f'{self.__class__.__name__}({super().__repr__()},{self.__bidiV__},{self.__bidiL__})' + isBidiList = lambda _: isinstance(_,BidiList) + def bidiText(text,direction): + if direction: direction = direction.upper() + return log2vis(text, direction,clean=True) if direction in ('LTR','RTL') else text + from reportlab.lib.utils import KlassStore + from copy import deepcopy + _bidiKS = KlassStore() + def innerBidiStrWrap(s, bidiV=-1, bidiL=-1): + if isinstance(s,BidiStr): return s + if type(s) is str: + klass = BidiStr + else: + sklassName = s.__class__.__name__ + klassName = f'BidiIndexed{sklassName}' + if klassName not in _bidiKS: + NS=dict(BidiStr=BidiStr,klassName=klassName,klass=s.__class__,deepcopy=deepcopy) + exec( f'''class {klassName}(klass,BidiStr):\n''' + '''\tdef __new__(cls,s,bidiV=-1,bidiL=-1):\n''' + '''\t\tself = super(cls,cls).__new__(cls,s)\n''' + '''\t\tif hasattr(s,'__dict__'): self.__dict__=deepcopy(s.__dict__)\n''' + '''\t\tself.__bidiV__ = bidiV\n''' + '''\t\tself.__bidiL__ = bidiL\n''' + '''\t\treturn self\n''', + NS) + _bidiKS.add(klassName,NS[klassName]) + klass = _bidiKS[klassName] + return klass(s,bidiV=bidiV,bidiL=bidiL) + def bidiStrWrap(s, orig): + if not isinstance(orig,BidiStr): return s + return innerBidiStrWrap(s,orig.__bidiV__,orig.__bidiL__) + def bidiListWrap(L, orig): + if not isinstance(orig,(BidiList,BidiIndex)) or isinstance(L,BidiList): return L + if type(L) is list: + klass = BidiList + else: + lklassName = L.__class__.__name__ + klassName = f'BidiIndexed{lklassName}' + if klassName not in _bidiKS: + NS=dict(BidiList=BidiList,klassName=klassName,klass=L.__class__,deepcopy=deepcopy) + exec( f'''class {klassName}(klass,BidiList):\n''' + '''\tdef __init__(self,L,bidiV=-1,bidiL=-1):\n''' + '''\t\tklass.__init__(self,L)\n''' + '''\t\tif hasattr(L,'__dict__'): self.__dict__=deepcopy(L.__dict__)\n''' + '''\t\tself.__bidiV__ = bidiV\n''' + '''\t\tself.__bidiL__ = bidiL\n''', + NS) + _bidiKS.add(klassName,NS[klassName]) + klass = _bidiKS[klassName] + return klass(L,orig.__bidiV__,orig.__bidiL__) + #return _bidiKS[klassName](L,orig.__bidiV__,orig.__bidiL__) + class BidiIndex: + def __init__(self,bidiV=-1,bidiL=-1): + self.__bidiV__ = bidiV + self.__bidiL__ = bidiL + import re + wordpat = re.compile(r'[^ ]+',re.M) + del re + def bidiWordList(words,direction='RTL', clean=True, wx=False): + '''takes words (list of strings) returns bidi associated lists + if wx is True then the V2L index only is returned + ''' + if direction: direction = direction.upper() + if direction not in ('LTR','RTL'): return words + if not isinstance(words,(list,tuple)): + raise ValueError('bidiWordList argument words should be a list or tuple of strings') + raw = ' '.join(words) + V2L = [] + bidi = log2vis(raw, base_direction=direction, clean=clean, positions_V_to_L=V2L) + + VMAP = {} + for i, m in enumerate(wordpat.finditer(bidi)): + t = (m.group(0), i) + start, end = m.span() + for j in range(start,end): + VMAP[V2L[j]] = t + + res = [].append + #create result by assigning a V word to a raw one + for w, m in enumerate(wordpat.finditer(raw)): + for j in range(*m.span()): + if j in VMAP: + s, i = VMAP[j] + res(i if wx else BidiStr(s,i,w)) + break + else: + #we seem to have a raw word that doesn't appear in bidi + pass + return res.__self__ + def bidiShapedText(text, direction='RTL', clean=True, fontName='Helvetica', fontSize=10, shaping=False): + '''return shaped/bidi text and width; assumes text is aways in logical order''' + text = asUnicode(text) + if shaping: + font = pdfmetrics_getFont(fontName) + if not font.shapable: shaping = False + if direction: direction = direction.upper() + if direction in ('RTL','LTR'): + if shaping: + w = text.lstrip() + bL = len(text) - len(w) + text = w.rstrip() + bR = len(w) - len(text) + LW = [text[slice(*m.span())] for m in wordpat.finditer(text)] #logical words + VX = bidiWordList(LW,direction=direction,wx=True) #visual order + SW = [shapeStr(LW[i],fontName,fontSize) for i in VX] #shaped words in visual order + if len(VX)>1 and VX[0]>VX[-1]: + bL, bR = bR, bL + text = shapeStr(bL*' ',fontName,fontSize, force=True) + for w in SW: + if not hasattr(w,'__shapeData__'): w = shapeStr(w,fontName,fontSize,force=True) + if w is not SW[0]: text += shapeStr(' ',fontName,fontSize, force=True) + text += w + if bR: + text += shapeStr(bR*' ',fontName,fontSize) + else: + text = log2vis(text,base_direction=direction,clean=clean) + else: + if shaping: + text = shapeStr(text, fontName, fontSize) + width = (sum((_.x_advance for _ in text.__shapeData__))*fontSize/1000 if isinstance(text,ShapedStr) + else pdfmetrics_stringWidth(text, fontName, fontSize)) + return text, width + def bidiFragWord(w,direction=None,bidiV=-1,bidiL=-1, clean=True): + if direction not in ('RTL','LTR'): return w + text = '' + cbd = [].append + fL = [].append + for i, (f, s) in enumerate(w[1:]): + if hasattr(f,'cbDefn'): + cbd(i) + else: + for u in s: + fL(i) + text += u + if len(text)<=1: return w #nothing to bidi + fL = fL.__self__ + V2L = [] + bidi = log2vis(text, base_direction=direction, clean=clean, positions_V_to_L=V2L) + fsL = [(w[1+k][0],''.join((ks[1] for ks in g))) for k, g in groupby(((fL[V2L[i]],v) for i,v in enumerate(bidi)),key=itemgetter(0))] + bfw = [sum((pdfmetrics_stringWidth(s,f.fontName,f.fontSize) for f,s in fsL))] + fsL + cbd = cbd.__self__ + if cbd: + if V2L[0]>V2L[-1]: + #reversed + for i in sorted(cbd): + fs = w[i+1] + bfw.insert(len(w)-i,fs) + bfw[0] += getattr(fs,'width',0) + else: + for i in reversed(sorted(cbd)): + fs = w[i+1] + bfw.insert(i+1,fs) + bfw[0] += getattr(fs,'width',0) + bfw = w.__class__(bfw) + return bidiListWrap(bfw, BidiIndex(bidiV,bidiL)) + rtlSupport = True +except: + import warnings + _rlbidiMsg = 'rlbidi is not installed - RTL/LTR not supported' + def log2vis(*args,**kwds): + raise ValueError(_rlbidiMsg) + isBidiStr = isBidiList = lambda _: False + BidiStr = str + BidiList = list + def bidiText(*args,**kwds): + direction = kwds.pop('direction',None) + if direction: direction = direction.upper() + if direction in ('LTR','RTL'): + warnings.warn(_rlbidiMsg,stacklevel=0) + return args[0] + def bidiShapedText(text, direction='RTL', clean=True, fontName='Helvetica', fontSize=10, shaping=False): + return bidiText(text,direction), pdfmetrics_stringWidth(text,fontName,fontSize) + bidiWordList = bidiStrWrap = bidiListWrap = bidiFragWord = innerBidiStrWrap = BidiIndex = bidiText + rtlSupport = False + +class _PDFColorSetter: + '''Abstracts the color setting operations; used in Canvas and Textobject + asseumes we have a _code object''' + def _checkSeparation(self,cmyk): + if isinstance(cmyk,CMYKColorSep): + name,sname = self._doc.addColor(cmyk) + if name not in self._colorsUsed: + self._colorsUsed[name] = sname + return name + + #if this is set to a callable(color) --> color it can be used to check color setting + #see eg _enforceCMYK/_enforceRGB + _enforceColorSpace = None + + def setFillColorCMYK(self, c, m, y, k, alpha=None): + """set the fill color useing negative color values + (cyan, magenta, yellow and darkness value). + Takes 4 arguments between 0.0 and 1.0""" + self.setFillColor((c,m,y,k),alpha=alpha) + + def setStrokeColorCMYK(self, c, m, y, k, alpha=None): + """set the stroke color useing negative color values + (cyan, magenta, yellow and darkness value). + Takes 4 arguments between 0.0 and 1.0""" + self.setStrokeColor((c,m,y,k),alpha=alpha) + + def setFillColorRGB(self, r, g, b, alpha=None): + """Set the fill color using positive color description + (Red,Green,Blue). Takes 3 arguments between 0.0 and 1.0""" + self.setFillColor((r,g,b),alpha=alpha) + + def setStrokeColorRGB(self, r, g, b, alpha=None): + """Set the stroke color using positive color description + (Red,Green,Blue). Takes 3 arguments between 0.0 and 1.0""" + self.setStrokeColor((r,g,b),alpha=alpha) + + def setFillColor(self, aColor, alpha=None): + """Takes a color object, allowing colors to be referred to by name""" + if self._enforceColorSpace: + aColor = self._enforceColorSpace(aColor) + if isinstance(aColor, CMYKColor): + d = aColor.density + c,m,y,k = (d*aColor.cyan, d*aColor.magenta, d*aColor.yellow, d*aColor.black) + self._fillColorObj = aColor + name = self._checkSeparation(aColor) + if name: + self._code.append('/%s cs %s scn' % (name,fp_str(d))) + else: + self._code.append('%s k' % fp_str(c, m, y, k)) + elif isinstance(aColor, Color): + rgb = (aColor.red, aColor.green, aColor.blue) + self._fillColorObj = aColor + self._code.append('%s rg' % fp_str(rgb) ) + elif isinstance(aColor,(tuple,list)): + l = len(aColor) + if l==3: + self._fillColorObj = aColor + self._code.append('%s rg' % fp_str(aColor) ) + elif l==4: + self._fillColorObj = aColor + self._code.append('%s k' % fp_str(aColor)) + else: + raise ValueError('Unknown color %r' % aColor) + elif isStr(aColor): + self.setFillColor(toColor(aColor)) + else: + raise ValueError('Unknown color %r' % aColor) + if alpha is not None: + self.setFillAlpha(alpha) + elif getattr(aColor, 'alpha', None) is not None: + self.setFillAlpha(aColor.alpha) + + def setStrokeColor(self, aColor, alpha=None): + """Takes a color object, allowing colors to be referred to by name""" + if self._enforceColorSpace: + aColor = self._enforceColorSpace(aColor) + if isinstance(aColor, CMYKColor): + d = aColor.density + c,m,y,k = (d*aColor.cyan, d*aColor.magenta, d*aColor.yellow, d*aColor.black) + self._strokeColorObj = aColor + name = self._checkSeparation(aColor) + if name: + self._code.append('/%s CS %s SCN' % (name,fp_str(d))) + else: + self._code.append('%s K' % fp_str(c, m, y, k)) + elif isinstance(aColor, Color): + rgb = (aColor.red, aColor.green, aColor.blue) + self._strokeColorObj = aColor + self._code.append('%s RG' % fp_str(rgb) ) + elif isinstance(aColor,(tuple,list)): + l = len(aColor) + if l==3: + self._strokeColorObj = aColor + self._code.append('%s RG' % fp_str(aColor) ) + elif l==4: + self._strokeColorObj = aColor + self._code.append('%s K' % fp_str(aColor)) + else: + raise ValueError('Unknown color %r' % aColor) + elif isStr(aColor): + self.setStrokeColor(toColor(aColor)) + else: + raise ValueError('Unknown color %r' % aColor) + if alpha is not None: + self.setStrokeAlpha(alpha) + elif getattr(aColor, 'alpha', None) is not None: + self.setStrokeAlpha(aColor.alpha) + + def setFillGray(self, gray, alpha=None): + """Sets the gray level; 0.0=black, 1.0=white""" + self._fillColorObj = (gray, gray, gray) + self._code.append('%s g' % fp_str(gray)) + if alpha is not None: + self.setFillAlpha(alpha) + + def setStrokeGray(self, gray, alpha=None): + """Sets the gray level; 0.0=black, 1.0=white""" + self._strokeColorObj = (gray, gray, gray) + self._code.append('%s G' % fp_str(gray)) + if alpha is not None: + self.setFillAlpha(alpha) + + def setStrokeAlpha(self,a): + if not (isinstance(a,(float,int)) and 0<=a<=1): + raise ValueError('setStrokeAlpha invalid value %r' % a) + getattr(self,'_setStrokeAlpha',lambda x: None)(a) + + def setFillAlpha(self,a): + if not (isinstance(a,(float,int)) and 0<=a<=1): + raise ValueError('setFillAlpha invalid value %r' % a) + getattr(self,'_setFillAlpha',lambda x: None)(a) + + def setStrokeOverprint(self,a): + getattr(self,'_setStrokeOverprint',lambda x: None)(a) + + def setFillOverprint(self,a): + getattr(self,'_setFillOverprint',lambda x: None)(a) + + def setOverprintMask(self,a): + getattr(self,'_setOverprintMask',lambda x: None)(a) + +class PDFTextObject(_PDFColorSetter): + """PDF logically separates text and graphics drawing; text + operations need to be bracketed between BT (Begin text) and + ET operators. This class ensures text operations are + properly encapusalted. Ask the canvas for a text object + with beginText(x, y). Do not construct one directly. + Do not use multiple text objects in parallel; PDF is + not multi-threaded! + + It keeps track of x and y coordinates relative to its origin.""" + + def __init__(self, canvas, x=0,y=0, direction=None): + self._code = ['BT'] #no point in [] then append RGB + self._canvas = canvas #canvas sets this so it has access to size info + self._fontname = self._canvas._fontname + self._fontsize = self._canvas._fontsize + self._leading = self._canvas._leading + self._doc = self._canvas._doc + self._colorsUsed = self._canvas._colorsUsed + self._enforceColorSpace = getattr(canvas,'_enforceColorSpace',None) + font = pdfmetrics_getFont(self._fontname) + self._curSubset = -1 + self.direction = direction + self.setTextOrigin(x, y) + self._textRenderMode = 0 + self._clipping = 0 + self._rise = 0 + + def getCode(self): + "pack onto one line; used internally" + self._code.append('ET') + if self._clipping: + self._code.append('%d Tr' % (self._textRenderMode^4)) + return ' '.join(self._code) + + def setTextOrigin(self, x, y): + if self._canvas.bottomup: + self._code.append('1 0 0 1 %s Tm' % fp_str(x, y)) #bottom up + else: + self._code.append('1 0 0 -1 %s Tm' % fp_str(x, y)) #top down + + # The current cursor position is at the text origin + self._x0 = self._x = x + self._y0 = self._y = y + + def setTextTransform(self, a, b, c, d, e, f): + "Like setTextOrigin, but does rotation, scaling etc." + if not self._canvas.bottomup: + c = -c #reverse bottom row of the 2D Transform + d = -d + self._code.append('%s Tm' % fp_str(a, b, c, d, e, f)) + + # The current cursor position is at the text origin Note that + # we aren't keeping track of all the transform on these + # coordinates: they are relative to the rotations/sheers + # defined in the matrix. + self._x0 = self._x = e + self._y0 = self._y = f + + def moveCursor(self, dx, dy): + """Starts a new line at an offset dx,dy from the start of the + current line. This does not move the cursor relative to the + current position, and it changes the current offset of every + future line drawn (i.e. if you next do a textLine() call, it + will move the cursor to a position one line lower than the + position specificied in this call. """ + + # Check if we have a previous move cursor call, and combine + # them if possible. + if self._code and self._code[-1].endswith(' Td'): + L = self._code[-1].split() + if len(L)==3: + del self._code[-1] + else: + self._code[-1] = ''.join(L[:-4]) + + # Work out the last movement + lastDx = float(L[-3]) + lastDy = float(L[-2]) + + # Combine the two movement + dx += lastDx + dy -= lastDy + + # We will soon add the movement to the line origin, so if + # we've already done this for lastDx, lastDy, remove it + # first (so it will be right when added back again). + self._x0 -= lastDx + self._y0 -= lastDy + + # Output the move text cursor call. + self._code.append('%s Td' % fp_str(dx, -dy)) + + # Keep track of the new line offsets and the cursor position + self._x0 += dx + self._y0 += dy + self._x = self._x0 + self._y = self._y0 + + def setXPos(self, dx): + """Starts a new line dx away from the start of the + current line - NOT from the current point! So if + you call it in mid-sentence, watch out.""" + self.moveCursor(dx,0) + + def getCursor(self): + """Returns current text position relative to the last origin.""" + return (self._x, self._y) + + def getStartOfLine(self): + """Returns a tuple giving the text position of the start of the + current line.""" + return (self._x0, self._y0) + + def getX(self): + """Returns current x position relative to the last origin.""" + return self._x + + def getY(self): + """Returns current y position relative to the last origin.""" + return self._y + + def _setFont(self, psfontname, size): + """Sets the font and fontSize + Raises a readable exception if an illegal font + is supplied. Font names are case-sensitive! Keeps track + of font anme and size for metrics.""" + self._fontname = psfontname + self._fontsize = size + font = pdfmetrics_getFont(self._fontname) + + if font._dynamicFont: + self._curSubset = -1 + else: + pdffontname = self._canvas._doc.getInternalFontName(psfontname) + self._code.append('%s %s Tf' % (pdffontname, fp_str(size))) + + def setFont(self, psfontname, size, leading = None): + """Sets the font. If leading not specified, defaults to 1.2 x + font size. Raises a readable exception if an illegal font + is supplied. Font names are case-sensitive! Keeps track + of font anme and size for metrics.""" + self._fontname = psfontname + self._fontsize = size + if leading is None: + leading = size * 1.2 + self._leading = leading + font = pdfmetrics_getFont(self._fontname) + if font._dynamicFont: + self._curSubset = -1 + else: + pdffontname = self._canvas._doc.getInternalFontName(psfontname) + self._code.append('%s %s Tf %s TL' % (pdffontname, fp_str(size), fp_str(leading))) + + def setCharSpace(self, charSpace): + """Adjusts inter-character spacing""" + self._charSpace = charSpace + self._code.append('%s Tc' % fp_str(charSpace)) + + def setWordSpace(self, wordSpace): + """Adjust inter-word spacing. This can be used + to flush-justify text - you get the width of the + words, and add some space between them.""" + self._wordSpace = wordSpace + self._code.append('%s Tw' % fp_str(wordSpace)) + + def setHorizScale(self, horizScale): + "Stretches text out horizontally" + self._horizScale = 100 + horizScale + self._code.append('%s Tz' % fp_str(horizScale)) + + def setLeading(self, leading): + "How far to move down at the end of a line." + self._leading = leading + self._code.append('%s TL' % fp_str(leading)) + + def setTextRenderMode(self, mode): + """Set the text rendering mode. + + 0 = Fill text + 1 = Stroke text + 2 = Fill then stroke + 3 = Invisible + 4 = Fill text and add to clipping path + 5 = Stroke text and add to clipping path + 6 = Fill then stroke and add to clipping path + 7 = Add to clipping path + + after we start clipping we mustn't change the mode back until after the ET + """ + + assert mode in (0,1,2,3,4,5,6,7), "mode must be in (0,1,2,3,4,5,6,7)" + if (mode & 4)!=self._clipping: + mode |= 4 + self._clipping = mode & 4 + if self._textRenderMode!=mode: + self._textRenderMode = mode + self._code.append('%d Tr' % mode) + + def setRise(self, rise): + "Move text baseline up or down to allow superscript/subscripts" + v = f'{fp_str(rise)} Ts' + if self._code[-1].endswith(' Ts'): #optimize out r0 Ts r1 Ts + #reverse previous changes + self._y += self._rise + self._code[-1] = v + else: + self._rise = rise + self._y -= rise + self._code.append(v) + + def _formatText(self, text): + "Generates PDF text output operator(s)" + #if log2vis and self.direction in ('LTR','RTL'): + # # Use pyfribidi to write the text in the correct visual order. + # text = log2vis(text, self.direction) + canv = self._canvas + font = pdfmetrics_getFont(self._fontname) + state = (self._code, self._x, self._y) + try: + self._code = [] + R = self._code.append + if font._dynamicFont: + canv_escape = canv._escape + tmpl = None + r0 = self._rise + #it's a truetype font + if font.shapable and isinstance(text,ShapedStr): + sd0 = 0 + r0 = self._rise + shapeData = text.__shapeData__ + fontsize = self._fontsize + for subset, t in font.splitString(text, canv._doc): + cluster = None + if subset!=self._curSubset: + if not tmpl: + tmpl = f'{fp_str(fontsize)} Tf {fp_str(self._leading)} TL' + R(f'{font.getSubsetInternalName(subset, canv._doc)} {tmpl}') + self._curSubset = subset + sd1 = sd0 + len(t) + SD = shapeData[sd0:sd1] + _sdGuardL + sd0 = sd1 + for i, sd in enumerate(SD): + r = r0 + fontsize*sd.y_offset/1000 + if cluster is None or sd.cluster<0 or r!=self._rise: + if cluster is not None: + #end current cluster + A = [v for v in ((('(%s)' % canv_escape(b''.join(g))) if k else fp_str(sum(g))) + for k, g in groupby(filter(None,A.__self__),lambda x: isinstance(x,bytes))) if v!='0'] + if len(A)==1 and A[0].startswith('('): + R(f'{A[0]} Tj') + else: + R(f'[{" ".join(A)}] TJ') + + if self._rise!=r0: self.setRise(r0) + if sd.cluster<0: break + + #begin new cluster + if r!=self._rise: self.setRise(r) + cluster = sd.cluster + A = [].append + + #we assume that both harfbuzz and pdf positions are correct + A(-sd.x_offset) #adjust using harfbuzz offset + A(bytes(chr(t[i]).encode('latin1'))) + #A(sd.x_offset) #remove the harfbuzz adjustment + #we assume the harfbuzz position is correct, but we will have + # 1<----O------| + # 1-----O ---->|--------------A--------->2 + # + # 1<----O------|<....(W-O).....><...x...>2 + # 1--------------------W-------> + # + # W - O + x = A ==> x = A-W+O + A(sd.width - sd.x_advance + sd.x_offset) + if self._rise!=r0: self.setRise(r0) + else: + for subset, t in font.splitString(text, canv._doc): + if subset!=self._curSubset: + if not tmpl: + tmpl = f'{fp_str(self._fontsize)} Tf {fp_str(self._leading)} TL' + R(f'{font.getSubsetInternalName(subset, canv._doc)} {tmpl}') + self._curSubset = subset + R(f'({canv_escape(t)}) Tj') + elif font._multiByte: + #all the fonts should really work like this - let them know more about PDF... + R("%s %s Tf %s TL" % ( + canv._doc.getInternalFontName(font.fontName), + fp_str(self._fontsize), + fp_str(self._leading) + )) + R("(%s) Tj" % font.formatForPdf(text)) + else: + #convert to T1 coding + fc = font + if isBytes(text): + try: + text = text.decode('utf8') + except UnicodeDecodeError as e: + i,j = e.args[2:4] + raise UnicodeDecodeError(*(e.args[:4]+('%s\n%s-->%s<--%s' % (e.args[4],text[max(i-10,0):i],text[i:j],text[j:j+10]),))) + + canv_escape = canv._escape + for f, t in pdfmetrics_unicode2T1(text,[font]+font.substitutionFonts): + if f!=fc: + R("%s %s Tf %s TL" % (canv._doc.getInternalFontName(f.fontName), fp_str(self._fontsize), fp_str(self._leading))) + fc = f + R(f'({canv_escape(t)}) Tj') + if font!=fc: + R("%s %s Tf %s TL" % (canv._doc.getInternalFontName(self._fontname), fp_str(self._fontsize), fp_str(self._leading))) + finally: + self._code, self._x, self._y = state + return ' '.join(R.__self__) + + def _shapedTextOut(self, text, dx, dy): + add = self._code.append + canv = self._canvas + font = pdfmetrics_getFont(self._fontname) + canv_escape = canv._escape + for subset, t in font.splitString(text, canv._doc): + if subset!=self._curSubset: + pdffontname = font.getSubsetInternalName(subset, canv._doc) + R.append("%s %s Tf %s TL" % (pdffontname, fp_str(self._fontsize), fp_str(self._leading))) + self._curSubset = subset + if dy: + print(f'{dy} -->',end='') + dy = (dy / font.face.unitsPerEm) * self._fontsize + print(f'{dy}') + add(f'{fp_str(dy)} Ts') + if dx: + add(f'[{fp_str(font.pdfScale(dx))} ({canv_escape(t)})] TJ') + if dy: + add(f'{fp_str(-dy)} Ts') + + + def _textOut(self, text, TStar=0): + "prints string at current point, ignores text cursor" + self._code.append('%s%s' % (self._formatText(text), (TStar and ' T*' or ''))) + + def textOut(self, text): + """prints string at current point, text cursor moves across.""" + self._x = self._x + self._canvas.stringWidth(text, self._fontname, self._fontsize) + self._code.append(self._formatText(text)) + + def textLine(self, text=''): + """prints string at current point, text cursor moves down. + Can work with no argument to simply move the cursor down.""" + # Update the coordinates of the cursor + self._x = self._x0 + if self._canvas.bottomup: + self._y = self._y - self._leading + else: + self._y = self._y + self._leading + + # Update the location of the start of the line + # self._x0 is unchanged + self._y0 = self._y + + # Output the text followed by a PDF newline command + self._code.append('%s T*' % self._formatText(text)) + + def textLines(self, stuff, trim=1): + """prints multi-line or newlined strings, moving down. One + comon use is to quote a multi-line block in your Python code; + since this may be indented, by default it trims whitespace + off each line and from the beginning; set trim=0 to preserve + whitespace.""" + if isStr(stuff): + lines = asUnicode(stuff).strip().split(u'\n') + if trim==1: + lines = [s.strip() for s in lines] + elif isinstance(stuff,(tuple,list)): + lines = stuff + else: + assert 1==0, "argument to textlines must be string,, list or tuple" + + # Output each line one at a time. This used to be a long-hand + # copy of the textLine code, now called as a method. + for line in lines: + self.textLine(line) + + def __nonzero__(self): + 'PDFTextObject is true if it has something done after the init' + return self._code != ['BT'] + + def _setFillAlpha(self,v): + self._canvas._doc.ensureMinPdfVersion('transparency') + self._canvas._extgstate.set(self,'ca',v) + + def _setStrokeOverprint(self,v): + self._canvas._extgstate.set(self,'OP',v) + + def _setFillOverprint(self,v): + self._canvas._extgstate.set(self,'op',v) + + def _setOverprintMask(self,v): + self._canvas._extgstate.set(self,'OPM',v and 1 or 0) diff --git a/.venv/lib/python3.13/site-packages/reportlab/platypus/__init__.py b/.venv/lib/python3.13/site-packages/reportlab/platypus/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c051b8ca8542ef918e3ac978e2f35b3e0f2451fa --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/platypus/__init__.py @@ -0,0 +1,14 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/platypus/__init__.py +__version__='3.5.20' +__doc__='''Page Layout and Typography Using Scripts" - higher-level framework for flowing documents''' + +from .flowables import * +from .frames import * +from .multicol import * +from .paragraph import * +from .paraparser import * +from .tables import * +from .doctemplate import * +from .xpreformatted import * diff --git a/.venv/lib/python3.13/site-packages/reportlab/platypus/doctemplate.py b/.venv/lib/python3.13/site-packages/reportlab/platypus/doctemplate.py new file mode 100644 index 0000000000000000000000000000000000000000..1901f08566b7a111069296c7e1fae4bf1b3e95d7 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/platypus/doctemplate.py @@ -0,0 +1,1408 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/platypus/doctemplate.py +__all__ = ( + 'ActionFlowable', + 'BaseDocTemplate', + 'CurrentFrameFlowable', + 'FrameActionFlowable', + 'FrameBreak', + 'Indenter', + 'IndexingFlowable', + 'LayoutError', + 'LCActionFlowable', + 'NextFrameFlowable', + 'NextPageTemplate', + 'NotAtTopPageBreak', + 'NullActionFlowable', + 'PageAccumulator', + 'PageBegin', + 'PageTemplate', + 'SimpleDocTemplate', + ) +__version__='3.5.20' + +__doc__=""" +This module contains the core structure of platypus. + +rlatypus constructs documents. Document styles are determined by DocumentTemplates. + +Each DocumentTemplate contains one or more PageTemplates which defines the look of the +pages of the document. + +Each PageTemplate has a procedure for drawing the "non-flowing" part of the page +(for example the header, footer, page number, fixed logo graphic, watermark, etcetera) and +a set of Frames which enclose the flowing part of the page (for example the paragraphs, +tables, or non-fixed diagrams of the text). + +A document is built when a DocumentTemplate is fed a sequence of Flowables. +The action of the build consumes the flowables in order and places them onto +frames on pages as space allows. When a frame runs out of space the next frame +of the page is used. If no frame remains a new page is created. A new page +can also be created if a page break is forced. + +The special invisible flowable NextPageTemplate can be used to specify +the page template for the next page (which by default is the one being used +for the current frame). +""" + +from reportlab.platypus.flowables import * +from reportlab.platypus.flowables import _ContainerSpace +from reportlab.lib.units import inch +from reportlab.lib import rl_safe_eval +from reportlab.platypus.paragraph import Paragraph +from reportlab.platypus.frames import Frame +from reportlab.rl_config import defaultPageSize, verbose, invariant +import reportlab.lib.sequencer +from reportlab.pdfgen import canvas +from reportlab.lib.utils import isSeq, encode_label, decode_label, annotateException, strTypes + +try: + set +except NameError: + from sets import Set as set + +import sys +import logging +logger = logging.getLogger("reportlab.platypus") + +class LayoutError(Exception): + pass + +def _fSizeString(f): + #used to get size during error messages + w=getattr(f,'width',None) + if w is None: + w=getattr(f,'_width',None) + + h=getattr(f,'height',None) + if h is None: + h=getattr(f,'_height',None) + #tables in particular may have some nasty large culprit + if hasattr(f, '_culprit'): + c = ', %s, ' % f._culprit() + else: + c = '' + if w is not None or h is not None: + if w is None: w='???' + if h is None: h='???' + return '(%s x %s)%s' % (w,h,c) + return '' + +def _doNothing(canvas, doc): + "Dummy callback for onPage" + pass + +class PTCycle(list): + def __new__(cls,*args,**kwds): + self = list.__new__(cls,*args,**kwds) + self._restart = 0 + self._idx = 0 + return self + + @property + def next_value(self): + v = self[self._idx] + self._idx += 1 + if self._idx>=len(self): + self._idx = self._restart + return v + + @property + def peek(self): + return self[self._idx] + +class IndexingFlowable(Flowable): + """Abstract interface definition for flowables which might + hold references to other pages or themselves be targets + of cross-references. XRefStart, XRefDest, Table of Contents, + Indexes etc.""" + def isIndexing(self): + return 1 + + def isSatisfied(self): + return 1 + + def notify(self, kind, stuff): + """This will be called by the framework wherever 'stuff' happens. + 'kind' will be a value that can be used to decide whether to + pay attention or not.""" + pass + + def beforeBuild(self): + """Called by multiBuild before it starts; use this to clear + old contents""" + pass + + def afterBuild(self): + """Called after build ends but before isSatisfied""" + pass + +class ActionFlowable(Flowable): + '''This Flowable is never drawn, it can be used for data driven controls + For example to change a page template (from one column to two, for example) + use NextPageTemplate which creates an ActionFlowable. + ''' + def __init__(self,action=()): + #must call super init to ensure it has a width and height (of zero), + #as in some cases the packer might get called on it... + Flowable.__init__(self) + if not isSeq(action): + action = (action,) + self.action = tuple(action) + + def apply(self,doc): + ''' + This is called by the doc.build processing to allow the instance to + implement its behaviour + ''' + action = self.action[0] + args = tuple(self.action[1:]) + arn = 'handle_'+action + if arn=="handle_nextPageTemplate" and args[0]=='main': + pass + try: + getattr(doc,arn)(*args) + except AttributeError as aerr: + if aerr.args[0]==arn: + raise NotImplementedError("Can't handle ActionFlowable(%s)" % action) + else: + raise + except: + annotateException("\nhandle_%s args=%s"%(action,ascii(args))) + + def __call__(self): + return self + + def identity(self, maxLen=None): + return "ActionFlowable: %s%s" % (str(self.action),self._frameName()) + +class NullActionFlowable(ActionFlowable): + '''an ActionFlowable that does nothing''' + def apply(self,doc): + pass + +class LCActionFlowable(ActionFlowable): + locChanger = 1 #we cause a frame or page change + + def wrap(self, availWidth, availHeight): + '''Should never be called.''' + raise NotImplementedError('%s.wrap should never be called' % self.__class__.__name__) + + def draw(self): + '''Should never be called.''' + raise NotImplementedError('%s.draw should never be called' % self.__class__.__name__) + +class NextFrameFlowable(ActionFlowable): + locChanger = 1 #we cause a frame or page change + def __init__(self,ix,resume=0): + ActionFlowable.__init__(self,('nextFrame',ix,resume)) + +class CurrentFrameFlowable(LCActionFlowable): + def __init__(self,ix,resume=0): + ActionFlowable.__init__(self,('currentFrame',ix,resume)) + +class NullActionFlowable(ActionFlowable): + def apply(self,doc): + pass + +class _FrameBreak(LCActionFlowable): + ''' + A special ActionFlowable that allows setting doc._nextFrameIndex + + eg story.append(FrameBreak('mySpecialFrame')) + ''' + def __call__(self,ix=None,resume=0): + r = self.__class__(self.action+(resume,)) + r._ix = ix + return r + + def apply(self,doc): + if getattr(self,'_ix',None): + doc.handle_nextFrame(self._ix) + ActionFlowable.apply(self,doc) + +FrameBreak = _FrameBreak('frameEnd') +PageBegin = LCActionFlowable('pageBegin') + +def _evalMeasurement(n): + if isinstance(n,str): + from reportlab.platypus.paraparser import _num + n = _num(n) + if isSeq(n): n = n[1] + return n + +class FrameActionFlowable(Flowable): + _fixedWidth = _fixedHeight = 1 + def __init__(self,*arg,**kw): + raise NotImplementedError('%s.__init__ should never be called for abstract Class'%self.__class__.__name__) + + def frameAction(self,frame): + raise NotImplementedError('%s.frameAction should never be called for abstract Class'%self.__class__.__name__) + +class Indenter(FrameActionFlowable): + """Increases or decreases left and right margins of frame. + + This allows one to have a 'context-sensitive' indentation + and makes nested lists way easier. + """ + _ZEROSIZE=True + width=0 + height=0 + def __init__(self, left=0, right=0): + self.left = _evalMeasurement(left) + self.right = _evalMeasurement(right) + + def frameAction(self, frame): + frame._leftExtraIndent += self.left + frame._rightExtraIndent += self.right + +class NotAtTopPageBreak(FrameActionFlowable): + locChanger = 1 #we cause a frame or page change + def __init__(self,nextTemplate=None): + self.nextTemplate = nextTemplate + + def frameAction(self,frame): + if not frame._atTop: + frame.add_generated_content(PageBreak(nextTemplate=self.nextTemplate)) + +class NextPageTemplate(ActionFlowable): + locChanger = 1 #we cause a frame or page change + """When you get to the next page, use the template specified (change to two column, for example) """ + def __init__(self,pt): + ActionFlowable.__init__(self,('nextPageTemplate',pt)) + +class PageTemplate: + """ + essentially a list of Frames and an onPage routine to call at the start + of a page when this is selected. onPageEnd gets called at the end. + derived classes can also implement beforeDrawPage and afterDrawPage if they want + """ + def __init__(self,id=None,frames=[],onPage=_doNothing, onPageEnd=_doNothing, + pagesize=None, autoNextPageTemplate=None, + cropBox=None, + artBox=None, + trimBox=None, + bleedBox=None, + ): + frames = frames or [] + if not isSeq(frames): frames = [frames] + assert [x for x in frames if not isinstance(x,Frame)]==[], "frames argument error" + self.id = id + self.frames = frames + self.onPage = onPage + self.onPageEnd = onPageEnd + self.pagesize = pagesize + self.autoNextPageTemplate = autoNextPageTemplate + self.cropBox = cropBox + self.artBox = artBox + self.trimBox = trimBox + self.bleedBox = bleedBox + + def beforeDrawPage(self,canv,doc): + """Override this if you want additional functionality or prefer + a class based page routine. Called before any flowables for + this page are processed.""" + pass + + def checkPageSize(self,canv,doc): + """This gets called by the template framework + If canv size != template size then the canv size is set to + the template size or if that's not available to the + doc size. + """ + #### NEVER EVER EVER COMPARE FLOATS FOR EQUALITY + #RGB converting pagesizes to ints means we are accurate to one point + #RGB I suggest we should be aiming a little better + cp = None + dp = None + sp = None + if canv._pagesize: cp = list(map(int, canv._pagesize)) + if self.pagesize: sp = list(map(int, self.pagesize)) + if doc.pagesize: dp = list(map(int, doc.pagesize)) + if cp!=sp: + if sp: + canv.setPageSize(self.pagesize) + elif cp!=dp: + canv.setPageSize(doc.pagesize) + for box in 'crop','art','trim','bleed': + size = getattr(self,box+'Box',None) + if size: + canv.setCropBox(size,name=box) + + def afterDrawPage(self, canv, doc): + """This is called after the last flowable for the page has + been processed. You might use this if the page header or + footer needed knowledge of what flowables were drawn on + this page.""" + pass + +def _addGeneratedContent(flowables,frame): + S = getattr(frame,'_generated_content',None) + if S: + flowables[0:0] = S + del frame._generated_content + +class onDrawStr(str): + def __new__(cls,value,onDraw,label,kind=None): + self = str.__new__(cls,value) + self.onDraw = onDraw + self.kind = kind + self.label = label + return self + + def __getnewargs__(self): + return str(self),self.onDraw,self.label,self.kind + +class PageAccumulator: + '''gadget to accumulate information in a page + and then allow it to be interrogated at the end + of the page''' + _count = 0 + def __init__(self,name=None): + if name is None: + name = self.__class__.__name__+str(self.__class__._count) + self.__class__._count += 1 + self.name = name + self.data = [] + + def reset(self): + self.data[:] = [] + + def add(self,*args): + self.data.append(args) + + def onDrawText(self,*args): + return '' % (self.name,encode_label(args)) + + def __call__(self,canv,kind,label): + self.add(*decode_label(label)) + + def attachToPageTemplate(self,pt): + if pt.onPage: + def onPage(canv,doc,oop=pt.onPage): + self.onPage(canv,doc) + oop(canv,doc) + else: + def onPage(canv,doc): + self.onPage(canv,doc) + pt.onPage = onPage + if pt.onPageEnd: + def onPageEnd(canv,doc,oop=pt.onPageEnd): + self.onPageEnd(canv,doc) + oop(canv,doc) + else: + def onPageEnd(canv,doc): + self.onPageEnd(canv,doc) + pt.onPageEnd = onPageEnd + + def onPage(self,canv,doc): + '''this will be called at the start of the page''' + canv.setNamedCB(self.name,self) #push ourselves onto the canvas + self.reset() + + def onPageEnd(self,canv,doc): + '''this will be called at the end of a page''' + self.pageEndAction(canv,doc) + try: + delattr(canv,self.name) + except: + pass + self.reset() + + def pageEndAction(self,canv,doc): + '''this should be overridden to do something useful''' + pass + + def onDrawStr(self,value,*args): + return onDrawStr(value,self,encode_label(args)) + +def _ktAllow(f): + '''return true if allowed in containers like KeepTogether''' + return not (isinstance(f,(_ContainerSpace,DocIf,DocWhile)) or getattr(f,'locChanger',False)) + +class BaseDocTemplate: + """ + First attempt at defining a document template class. + + The basic idea is simple. + + 1) The document has a list of data associated with it + this data should derive from flowables. We'll have + special classes like PageBreak, FrameBreak to do things + like forcing a page end etc. + + 2) The document has one or more page templates. + + 3) Each page template has one or more frames. + + 4) The document class provides base methods for handling the + story events and some reasonable methods for getting the + story flowables into the frames. + + 5) The document instances can override the base handler routines. + + Most of the methods for this class are not called directly by the user, + but in some advanced usages they may need to be overridden via subclassing. + + EXCEPTION: doctemplate.build(...) must be called for most reasonable uses + since it builds a document using the page template. + + Each document template builds exactly one document into a file specified + by the filename argument on initialization. + + Possible keyword arguments for the initialization: + + - pageTemplates: A list of templates. Must be nonempty. Names + assigned to the templates are used for referring to them so no two used + templates should have the same name. For example you might want one template + for a title page, one for a section first page, one for a first page of + a chapter and two more for the interior of a chapter on odd and even pages. + If this argument is omitted then at least one pageTemplate should be provided + using the addPageTemplates method before the document is built. + - pageSize: a 2-tuple or a size constant from reportlab/lib/pagesizes.pu. + Used by the SimpleDocTemplate subclass which does NOT accept a list of + pageTemplates but makes one for you; ignored when using pageTemplates. + + - showBoundary: if set draw a box around the frame boundaries. + - leftMargin: + - rightMargin: + - topMargin: + - bottomMargin: Margin sizes in points (default 1 inch). These margins may be + overridden by the pageTemplates. They are primarily of interest for the + SimpleDocumentTemplate subclass. + + - allowSplitting: If set flowables (eg, paragraphs) may be split across frames or pages + (default: 1) + - title: Internal title for document (does not automatically display on any page) + - author: Internal author for document (does not automatically display on any page) + """ + _initArgs = { 'pagesize':defaultPageSize, + 'pageTemplates':[], + 'showBoundary':0, + 'leftMargin':inch, + 'rightMargin':inch, + 'topMargin':inch, + 'bottomMargin':inch, + 'allowSplitting':1, + 'title':None, + 'author':None, + 'subject':None, + 'creator':None, + 'producer':None, + 'keywords':[], + 'invariant':None, + 'pageCompression':None, + '_pageBreakQuick':1, + 'rotation':0, + '_debug':0, + 'encrypt': None, + 'cropMarks': None, + 'enforceColorSpace': None, + 'displayDocTitle': None, + 'lang': None, + 'initialFontName': None, + 'initialFontSize': None, + 'initialLeading': None, + 'cropBox': None, + 'artBox': None, + 'trimBox': None, + 'bleedBox': None, + 'keepTogetherClass': KeepTogether, + 'hideToolbar': None, + 'hideMenubar': None, + 'hideWindowUI': None, + 'fitWindow': None, + 'centerWindow': None, + 'nonFullScreenPageMode': None, + 'direction': None, + 'viewArea': None, + 'viewClip': None, + 'printArea': None, + 'printClip': None, + 'printScaling': None, + 'duplex': None, + } + _invalidInitArgs = () + _firstPageTemplateIndex = 0 + + def __init__(self, filename, **kw): + """create a document template bound to a filename (see class documentation for keyword arguments)""" + self.filename = filename + self._nameSpace = dict(doc=self) + self._lifetimes = {} + + for k in self._initArgs.keys(): + if k not in kw: + v = self._initArgs[k] + else: + if k in self._invalidInitArgs: + raise ValueError("Invalid argument %s" % k) + v = kw[k] + setattr(self,k,v) + + p = self.pageTemplates + self.pageTemplates = [] + self.addPageTemplates(p) + + # facility to assist multi-build and cross-referencing. + # various hooks can put things into here - key is what + # you want, value is a page number. This can then be + # passed to indexing flowables. + self._pageRefs = {} + self._indexingFlowables = [] + + #callback facility for progress monitoring + self._onPage = None + self._onProgress = None + self._flowableCount = 0 # so we know how far to go + + #infinite loop detection if we start doing lots of empty pages + self._curPageFlowableCount = 0 + self._emptyPages = 0 + self._emptyPagesAllowed = 10 + + #context sensitive margins - set by story, not from outside + self._leftExtraIndent = 0.0 + self._rightExtraIndent = 0.0 + self._topFlowables = [] + self._pageTopFlowables = [] + self._frameBGs = [] + + self._calc() + self.afterInit() + + def _calc(self): + self._rightMargin = self.pagesize[0] - self.rightMargin + self._topMargin = self.pagesize[1] - self.topMargin + self.width = self._rightMargin - self.leftMargin + self.height = self._topMargin - self.bottomMargin + + def setPageCallBack(self, func): + 'Simple progress monitor - func(pageNo) called on each new page' + self._onPage = func + + def setProgressCallBack(self, func): + '''Cleverer progress monitor - func(typ, value) called regularly''' + self._onProgress = func + + def clean_hanging(self): + 'handle internal postponed actions' + while len(self._hanging): + self.handle_flowable(self._hanging) + + def addPageTemplates(self,pageTemplates): + 'add one or a sequence of pageTemplates' + if not isSeq(pageTemplates): + pageTemplates = [pageTemplates] + #this test below fails due to inconsistent imports! + #assert filter(lambda x: not isinstance(x,PageTemplate), pageTemplates)==[], "pageTemplates argument error" + for t in pageTemplates: + self.pageTemplates.append(t) + + def handle_documentBegin(self): + '''implement actions at beginning of document''' + self._hanging = [PageBegin] + if isinstance(self._firstPageTemplateIndex,list): + self.handle_nextPageTemplate(self._firstPageTemplateIndex) + self._setPageTemplate() + else: + self.pageTemplate = self.pageTemplates[self._firstPageTemplateIndex] + self.page = 0 + self.beforeDocument() + + def handle_pageBegin(self): + """Perform actions required at beginning of page. + shouldn't normally be called directly""" + self.page += 1 + if self._debug: logger.debug("beginning page %d" % self.page) + self.pageTemplate.beforeDrawPage(self.canv,self) + self.pageTemplate.checkPageSize(self.canv,self) + self.pageTemplate.onPage(self.canv,self) + for f in self.pageTemplate.frames: f._reset() + self.beforePage() + #keep a count of flowables added to this page. zero indicates bad stuff + self._curPageFlowableCount = 0 + if hasattr(self,'_nextFrameIndex'): + del self._nextFrameIndex + self.frame = self.pageTemplate.frames[0] + self.frame._debug = self._debug + self.handle_frameBegin(pageTopFlowables=self._pageTopFlowables) + + def _setPageTemplate(self): + if hasattr(self,'_nextPageTemplateCycle'): + #they are cycling through pages'; we keep the index + self.pageTemplate = self._nextPageTemplateCycle.next_value + elif hasattr(self,'_nextPageTemplateIndex'): + self.pageTemplate = self.pageTemplates[self._nextPageTemplateIndex] + del self._nextPageTemplateIndex + elif self.pageTemplate.autoNextPageTemplate: + self.handle_nextPageTemplate(self.pageTemplate.autoNextPageTemplate) + self.pageTemplate = self.pageTemplates[self._nextPageTemplateIndex] + + def _samePT(self,npt): + if isSeq(npt): + return getattr(self,'_nextPageTemplateCycle',[]) + if isinstance(npt,strTypes): + return npt == (self.pageTemplates[self._nextPageTemplateIndex].id if hasattr(self,'_nextPageTemplateIndex') else self.pageTemplate.id) + if isinstance(npt,int) and 0<=npt= self._emptyPagesAllowed: + if 1: + ident = "More than %d pages generated without content - halting layout. Likely that a flowable is too large for any frame." % self._emptyPagesAllowed + #leave to keep apart from the raise + raise LayoutError(ident) + else: + pass #attempt to restore to good state + else: + if self._onProgress: + self._onProgress('PAGE', self.canv.getPageNumber()) + self.pageTemplate.afterDrawPage(self.canv, self) + self.pageTemplate.onPageEnd(self.canv, self) + self.afterPage() + if self._debug: logger.debug("ending page %d" % self.page) + self.canv.setPageRotation(getattr(self.pageTemplate,'rotation',self.rotation)) + self.canv.showPage() + self._setPageTemplate() + if self._emptyPages==0: + pass #store good state here + self._hanging.append(PageBegin) + + def handle_pageBreak(self,slow=None): + '''some might choose not to end all the frames''' + if self._pageBreakQuick and not slow: + self.handle_pageEnd() + else: + n = len(self._hanging) + while len(self._hanging)==n: + self.handle_frameEnd() + + def handle_frameBegin(self,resume=0,pageTopFlowables=None): + '''What to do at the beginning of a frame''' + f = self.frame + if f._atTop: + boundary = self.frame.showBoundary or self.showBoundary + if boundary: + self.frame.drawBoundary(self.canv,boundary) + f._leftExtraIndent = self._leftExtraIndent + f._rightExtraIndent = self._rightExtraIndent + f._frameBGs = self._frameBGs + if pageTopFlowables: + self._hanging.extend(pageTopFlowables) + if self._topFlowables: + self._hanging.extend(self._topFlowables) + + def handle_frameEnd(self,resume=0): + ''' Handles the semantics of the end of a frame. This includes the selection of + the next frame or if this is the last frame then invoke pageEnd. + ''' + self._removeVars(('frame',)) + self._leftExtraIndent = self.frame._leftExtraIndent + self._rightExtraIndent = self.frame._rightExtraIndent + self._frameBGs = self.frame._frameBGs + + if hasattr(self,'_nextFrameIndex'): + self.frame = self.pageTemplate.frames[self._nextFrameIndex] + self.frame._debug = self._debug + del self._nextFrameIndex + self.handle_frameBegin(resume) + else: + f = self.frame + if hasattr(f,'lastFrame') or f is self.pageTemplate.frames[-1]: + self.handle_pageEnd() + self.frame = None + else: + self.frame = self.pageTemplate.frames[self.pageTemplate.frames.index(f) + 1] + self.frame._debug = self._debug + self.handle_frameBegin() + + def handle_nextPageTemplate(self,pt): + '''On endPage change to the page template with name or index pt''' + if isinstance(pt,strTypes): + if hasattr(self, '_nextPageTemplateCycle'): del self._nextPageTemplateCycle + for t in self.pageTemplates: + if t.id == pt: + self._nextPageTemplateIndex = self.pageTemplates.index(t) + return + raise ValueError("can't find template('%s')"%pt) + elif isinstance(pt,int): + if hasattr(self, '_nextPageTemplateCycle'): del self._nextPageTemplateCycle + self._nextPageTemplateIndex = pt + elif isSeq(pt): + #used for alternating left/right pages + #collect the refs to the template objects, complain if any are bad + c = PTCycle() + for ptn in pt: + found = 0 + if ptn=='*': #special case name used to short circuit the iteration + c._restart = len(c) + continue + for t in self.pageTemplates: + if t.id == ptn: + c.append(t) + found = 1 + if not found: + raise ValueError("Cannot find page template called %s" % ptn) + if not c: + raise ValueError("No valid page templates in cycle") + elif c._restart>len(c): + raise ValueError("Invalid cycle restart position") + + #ensure we start on the first one + self._nextPageTemplateCycle = c + else: + raise TypeError("argument pt should be string or integer or list") + + def _peekNextPageTemplate(self,pt): + if isinstance(pt,strTypes): + for t in self.pageTemplates: + if t.id == pt: + return t + raise ValueError("can't find template('%s')"%pt) + elif isinstance(pt,int): + self.pageTemplates[pt] + elif isSeq(pt): + #used for alternating left/right pages + #collect the refs to the template objects, complain if any are bad + c = PTCycle() + for ptn in pt: + found = 0 + if ptn=='*': #special case name used to short circuit the iteration + c._restart = len(c) + continue + for t in self.pageTemplates: + if t.id == ptn: + c.append(t) + found = 1 + if not found: + raise ValueError("Cannot find page template called %s" % ptn) + if not c: + raise ValueError("No valid page templates in cycle") + elif c._restart>len(c): + raise ValueError("Invalid cycle restart position") + return c.peek + else: + raise TypeError("argument pt should be string or integer or list") + + def _peekNextFrame(self): + '''intended to be used by extreme flowables''' + if hasattr(self,'_nextFrameIndex'): + return self.pageTemplate.frames[self._nextFrameIndex] + f = self.frame + if hasattr(f,'lastFrame') or f is self.pageTemplate.frames[-1]: + if hasattr(self,'_nextPageTemplateCycle'): + #they are cycling through pages'; we keep the index + pageTemplate = self._nextPageTemplateCycle.peek + elif hasattr(self,'_nextPageTemplateIndex'): + pageTemplate = self.pageTemplates[self._nextPageTemplateIndex] + elif self.pageTemplate.autoNextPageTemplate: + pageTemplate = self._peekNextPageTemplate(self.pageTemplate.autoNextPageTemplate) + else: + pageTemplate = self.pageTemplate + return pageTemplate.frames[0] + else: + return self.pageTemplate.frames[self.pageTemplate.frames.index(f) + 1] + + def handle_nextFrame(self,fx,resume=0): + '''On endFrame change to the frame with name or index fx''' + if isinstance(fx,strTypes): + for f in self.pageTemplate.frames: + if f.id == fx: + self._nextFrameIndex = self.pageTemplate.frames.index(f) + return + raise ValueError("can't find frame('%s') in %r(%s) which has frames %r"%(fx,self.pageTemplate,self.pageTemplate.id,[(f,f.id) for f in self.pageTemplate.frames])) + elif isinstance(fx,int): + self._nextFrameIndex = fx + else: + raise TypeError("argument fx should be string or integer") + + def handle_currentFrame(self,fx,resume=0): + '''change to the frame with name or index fx''' + self.handle_nextFrame(fx,resume) + self.handle_frameEnd(resume) + + def handle_breakBefore(self, flowables): + '''preprocessing step to allow pageBreakBefore and frameBreakBefore attributes''' + first = flowables[0] + # if we insert a page break before, we'll process that, see it again, + # and go in an infinite loop. So we need to set a flag on the object + # saying 'skip me'. This should be unset on the next pass + if hasattr(first, '_skipMeNextTime'): + delattr(first, '_skipMeNextTime') + return + # this could all be made much quicker by putting the attributes + # in to the flowables with a defult value of 0 + if hasattr(first,'pageBreakBefore') and first.pageBreakBefore == 1: + first._skipMeNextTime = 1 + first.insert(0, PageBreak()) + return + if hasattr(first,'style') and hasattr(first.style, 'pageBreakBefore') and first.style.pageBreakBefore == 1: + first._skipMeNextTime = 1 + flowables.insert(0, PageBreak()) + return + if hasattr(first,'frameBreakBefore') and first.frameBreakBefore == 1: + first._skipMeNextTime = 1 + flowables.insert(0, FrameBreak()) + return + if hasattr(first,'style') and hasattr(first.style, 'frameBreakBefore') and first.style.frameBreakBefore == 1: + first._skipMeNextTime = 1 + flowables.insert(0, FrameBreak()) + return + + def handle_keepWithNext(self, flowables): + "implements keepWithNext" + i = 0 + n = len(flowables) + while i maxPasses: + raise IndexError("Index entries not resolved after %d passes" % maxPasses) + + #work through any edits + while mbe: + e = mbe.pop(0) + e[0](*e[1:]) + + del self._multiBuildEdits + if verbose: print('saved') + return passes + + #these are pure virtuals override in derived classes + #NB these get called at suitable places by the base class + #so if you derive and override the handle_xxx methods + #it's up to you to ensure that they maintain the needed consistency + def afterInit(self): + """This is called after initialisation of the base class.""" + pass + + def beforeDocument(self): + """This is called before any processing is + done on the document.""" + pass + + def beforePage(self): + """This is called at the beginning of page + processing, and immediately before the + beforeDrawPage method of the current page + template.""" + pass + + def afterPage(self): + """This is called after page processing, and + immediately after the afterDrawPage method + of the current page template.""" + pass + + def filterFlowables(self,flowables): + '''called to filter flowables at the start of the main handle_flowable method. + Upon return if flowables[0] has been set to None it is discarded and the main + method returns. + ''' + pass + + def afterFlowable(self, flowable): + '''called after a flowable has been rendered''' + pass + + _allowedLifetimes = 'page','frame','build','forever' + def docAssign(self,var,expr,lifetime): + if not isinstance(expr,strTypes): expr=str(expr) + expr=expr.strip() + var=var.strip() + self.docExec('%s=(%s)'%(var.strip(),expr.strip()),lifetime) + + def docExec(self,stmt,lifetime): + stmt=stmt.strip() + NS=self._nameSpace + K0=list(NS.keys()) + try: + if lifetime not in self._allowedLifetimes: + raise ValueError('bad lifetime %r not in %r'%(lifetime,self._allowedLifetimes)) + rl_safe_eval.rl_safe_exec(stmt.strip(),{},NS) + except: + K1 = [k for k in NS if k not in K0] #the added keys we need to delete + for k in K1: + del NS[k] + annotateException('\ndocExec %s lifetime=%r failed!\n' % (stmt,lifetime)) + self._addVars([k for k in NS.keys() if k not in K0],lifetime) + + def _addVars(self,vars,lifetime): + '''add namespace variables to lifetimes lists''' + LT=self._lifetimes + for var in vars: + for v in LT.values(): + if var in v: + v.remove(var) + LT.setdefault(lifetime,set([])).add(var) + + def _removeVars(self,lifetimes): + '''remove namespace variables for with lifetime in lifetimes''' + LT=self._lifetimes + NS=self._nameSpace + for lifetime in lifetimes: + for k in LT.setdefault(lifetime,[]): + try: + del NS[k] + except KeyError: + pass + del LT[lifetime] + + def docEval(self,expr): + try: + return rl_safe_eval.rl_safe_eval(expr.strip(),{},self._nameSpace) + except: + annotateException('\ndocEval %s failed!\n' % expr) + + def __repr__(self): + return (f'<{self.__class__.__module__}.{self.__class__.__name__} object at 0x?hidden?>' if invariant + else super().__repr__()) + +class SimpleDocTemplate(BaseDocTemplate): + """A special case document template that will handle many simple documents. + See documentation for BaseDocTemplate. No pageTemplates are required + for this special case. A page templates are inferred from the + margin information and the onFirstPage, onLaterPages arguments to the build method. + + A document which has all pages with the same look except for the first + page may can be built using this special approach. + """ + _invalidInitArgs = ('pageTemplates',) + + def handle_pageBegin(self): + '''override base method to add a change of page template after the firstpage. + ''' + self._handle_pageBegin() + self._handle_nextPageTemplate('Later') + + def build(self,flowables,onFirstPage=_doNothing, onLaterPages=_doNothing, canvasmaker=canvas.Canvas): + """build the document using the flowables. Annotate the first page using the onFirstPage + function and later pages using the onLaterPages function. The onXXX pages should follow + the signature + + def myOnFirstPage(canvas, document): + # do annotations and modify the document + ... + + The functions can do things like draw logos, page numbers, + footers, etcetera. They can use external variables to vary + the look (for example providing page numbering or section names). + """ + self._calc() #in case we changed margins sizes etc + frameT = Frame(self.leftMargin, self.bottomMargin, self.width, self.height, id='normal') + self.addPageTemplates([PageTemplate(id='First',frames=frameT, onPage=onFirstPage,pagesize=self.pagesize), + PageTemplate(id='Later',frames=frameT, onPage=onLaterPages,pagesize=self.pagesize)]) + if onFirstPage is _doNothing and hasattr(self,'onFirstPage'): + self.pageTemplates[0].beforeDrawPage = self.onFirstPage + if onLaterPages is _doNothing and hasattr(self,'onLaterPages'): + self.pageTemplates[1].beforeDrawPage = self.onLaterPages + BaseDocTemplate.build(self,flowables, canvasmaker=canvasmaker) + +def progressCB(typ, value): + """Example prototype for progress monitoring. + + This aims to provide info about what is going on + during a big job. It should enable, for example, a reasonably + smooth progress bar to be drawn. We design the argument + signature to be predictable and conducive to programming in + other (type safe) languages. If set, this will be called + repeatedly with pairs of values. The first is a string + indicating the type of call; the second is a numeric value. + + typ 'STARTING', value = 0 + typ 'SIZE_EST', value = numeric estimate of job size + typ 'PASS', value = number of this rendering pass + typ 'PROGRESS', value = number between 0 and SIZE_EST + typ 'PAGE', value = page number of page + type 'FINISHED', value = 0 + + The sequence is + STARTING - always called once + SIZE_EST - always called once + PROGRESS - called often + PAGE - called often when page is emitted + FINISHED - called when really, really finished + + some juggling is needed to accurately estimate numbers of + pages in pageDrawing mode. + + NOTE: the SIZE_EST is a guess. It is possible that the + PROGRESS value may slightly exceed it, or may even step + back a little on rare occasions. The only way to be + really accurate would be to do two passes, and I don't + want to take that performance hit. + """ + print('PROGRESS MONITOR: %-10s %d' % (typ, value)) + +if __name__ == '__main__': + from reportlab.lib.styles import _baseFontName, _baseFontNameB + def myFirstPage(canvas, doc): + from reportlab.lib.colors import red + PAGE_HEIGHT = canvas._pagesize[1] + canvas.saveState() + canvas.setStrokeColor(red) + canvas.setLineWidth(5) + canvas.line(66,72,66,PAGE_HEIGHT-72) + canvas.setFont(_baseFontNameB,24) + canvas.drawString(108, PAGE_HEIGHT-108, "TABLE OF CONTENTS DEMO") + canvas.setFont(_baseFontName,12) + canvas.drawString(4 * inch, 0.75 * inch, "First Page") + canvas.restoreState() + + def myLaterPages(canvas, doc): + from reportlab.lib.colors import red + PAGE_HEIGHT = canvas._pagesize[1] + canvas.saveState() + canvas.setStrokeColor(red) + canvas.setLineWidth(5) + canvas.line(66,72,66,PAGE_HEIGHT-72) + canvas.setFont(_baseFontName,12) + canvas.drawString(4 * inch, 0.75 * inch, "Page %d" % doc.page) + canvas.restoreState() + + def run(): + objects_to_draw = [] + from reportlab.lib.styles import ParagraphStyle + #from paragraph import Paragraph + from reportlab.platypus.doctemplate import SimpleDocTemplate + + #need a style + normal = ParagraphStyle('normal') + normal.firstLineIndent = 18 + normal.spaceBefore = 6 + from reportlab.lib.randomtext import randomText + import random + for i in range(15): + height = 0.5 + (2*random.random()) + box = XBox(6 * inch, height * inch, 'Box Number %d' % i) + objects_to_draw.append(box) + para = Paragraph(randomText(), normal) + objects_to_draw.append(para) + + SimpleDocTemplate('doctemplate.pdf').build(objects_to_draw, + onFirstPage=myFirstPage,onLaterPages=myLaterPages) + + run() diff --git a/.venv/lib/python3.13/site-packages/reportlab/platypus/figures.py b/.venv/lib/python3.13/site-packages/reportlab/platypus/figures.py new file mode 100644 index 0000000000000000000000000000000000000000..33e870e45842d4bbabdc9e4219b06e51757fe100 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/platypus/figures.py @@ -0,0 +1,420 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/platypus/figures.py +"""This includes some demos of platypus for use in the API proposal""" +__version__='3.3.0' + +import os + +from reportlab.lib import colors +from reportlab.pdfgen.canvas import Canvas +from reportlab.lib.styles import ParagraphStyle +from reportlab.lib.utils import recursiveImport, strTypes +from reportlab.platypus import Frame +from reportlab.platypus import Flowable +from reportlab.platypus import Paragraph +from reportlab.lib.units import inch +from reportlab.lib.enums import TA_LEFT, TA_RIGHT, TA_CENTER +from reportlab.lib.validators import isColor +from reportlab.lib.colors import toColor +from reportlab.lib.styles import _baseFontName, _baseFontNameI + +captionStyle = ParagraphStyle('Caption', fontName=_baseFontNameI, fontSize=10, alignment=TA_CENTER) + +class Figure(Flowable): + def __init__(self, width, height, caption="", + captionFont=_baseFontNameI, captionSize=12, + background=None, + captionTextColor=toColor('black'), + captionBackColor=None, + border=None, + spaceBefore=12, + spaceAfter=12, + captionGap=None, + captionAlign='centre', + captionPosition='bottom', + hAlign='CENTER', + ): + Flowable.__init__(self) + self.width = width + self.figureHeight = height + self.caption = caption + self.captionFont = captionFont + self.captionSize = captionSize + self.captionTextColor = captionTextColor + self.captionBackColor = captionBackColor + self.captionGap = captionGap or 0.5*captionSize + self.captionAlign = captionAlign + self.captionPosition = captionPosition + self._captionData = None + self.captionHeight = 0 # work out later + self.background = background + self.border = border + self.spaceBefore = spaceBefore + self.spaceAfter = spaceAfter + self.hAlign=hAlign + self._getCaptionPara() #Larry Meyn's fix - otherwise they all get the number of the last chapter. + + def _getCaptionPara(self): + caption = self.caption + captionFont = self.captionFont + captionSize = self.captionSize + captionTextColor = self.captionTextColor + captionBackColor = self.captionBackColor + captionAlign = self.captionAlign + captionPosition = self.captionPosition + if self._captionData!=(caption,captionFont,captionSize,captionTextColor,captionBackColor,captionAlign,captionPosition): + self._captionData = (caption,captionFont,captionSize,captionTextColor,captionBackColor,captionAlign,captionPosition) + if isinstance(caption,Paragraph): + self.captionPara = caption + elif isinstance(caption,strTypes): + self.captionStyle = ParagraphStyle( + 'Caption', + fontName=captionFont, + fontSize=captionSize, + leading=1.2*captionSize, + textColor = captionTextColor, + backColor = captionBackColor, + #seems to be getting ignored + spaceBefore=self.captionGap, + alignment=TA_LEFT if captionAlign=='left' else TA_RIGHT if captionAlign=='right' else TA_CENTER, + ) + #must build paragraph now to get sequencing in synch with rest of story + self.captionPara = Paragraph(self.caption, self.captionStyle) + else: + raise ValueError('Figure caption of type %r is not a string or Paragraph' % type(caption)) + + def wrap(self, availWidth, availHeight): + # try to get the caption aligned + if self.caption: + self._getCaptionPara() + w, h = self.captionPara.wrap(self.width, availHeight - self.figureHeight) + self.captionHeight = h + self.captionGap + self.height = self.captionHeight + self.figureHeight + if w>self.width: self.width = w + else: + self.height = self.figureHeight + if self.hAlign in ('CENTER','CENTRE',TA_CENTER): + self.dx = 0.5 * (availWidth - self.width) + elif self.hAlign in ('RIGHT',TA_RIGHT): + self.dx = availWidth - self.width + else: + self.dx = 0 + return (self.width, self.height) + + def draw(self): + self.canv.translate(self.dx, 0) + if self.caption and self.captionPosition=='bottom': + self.canv.translate(0, self.captionHeight) + if self.background: + self.drawBackground() + if self.border: + self.drawBorder() + self.canv.saveState() + self.drawFigure() + self.canv.restoreState() + if self.caption: + if self.captionPosition=='bottom': + self.canv.translate(0, -self.captionHeight) + else: + self.canv.translate(0, self.figureHeight+self.captionGap) + self._getCaptionPara() + self.drawCaption() + + def drawBorder(self): + self.canv.drawBoundary(self.border,0,0,self.width, self.figureHeight) + + def _doBackground(self, color): + self.canv.saveState() + self.canv.setFillColor(self.background) + self.canv.rect(0, 0, self.width, self.figureHeight, fill=1) + self.canv.restoreState() + + def drawBackground(self): + """For use when using a figure on a differently coloured background. + Allows you to specify a colour to be used as a background for the figure.""" + if isColor(self.background): + self._doBackground(self.background) + else: + try: + c = toColor(self.background) + self._doBackground(c) + except: + pass + + def drawCaption(self): + self.captionPara.drawOn(self.canv, 0, 0) + + def drawFigure(self): + pass + +def drawPage(canvas,x, y, width, height): + #draws something which looks like a page + pth = canvas.beginPath() + corner = 0.05*width + + # shaded backdrop offset a little + canvas.setFillColorRGB(0.5,0.5,0.5) + canvas.rect(x + corner, y - corner, width, height, stroke=0, fill=1) + + #'sheet of paper' in light yellow + canvas.setFillColorRGB(1,1,0.9) + canvas.setLineWidth(0) + canvas.rect(x, y, width, height, stroke=1, fill=1) + + #reset + canvas.setFillColorRGB(0,0,0) + canvas.setStrokeColorRGB(0,0,0) + +class PageFigure(Figure): + """Shows a blank page in a frame, and draws on that. Used in + illustrations of how PLATYPUS works.""" + def __init__(self, background=None): + Figure.__init__(self, 3*inch, 3*inch) + self.caption = 'Figure 1 - a blank page' + self.captionStyle = captionStyle + self.background = background + + def drawVirtualPage(self): + pass + + def drawFigure(self): + drawPage(self.canv, 0.625*inch, 0.25*inch, 1.75*inch, 2.5*inch) + self.canv.translate(0.625*inch, 0.25*inch) + self.canv.scale(1.75/8.27, 2.5/11.69) + self.drawVirtualPage() + +class PlatPropFigure1(PageFigure): + """This shows a page with a frame on it""" + def __init__(self): + PageFigure.__init__(self) + self.caption = "Figure 1 - a page with a simple frame" + def drawVirtualPage(self): + demo1(self.canv) + +class FlexFigure(Figure): + """Base for a figure class with a caption. Can grow or shrink in proportion""" + def __init__(self, width, height, caption, background=None, + captionFont='Helvetica-Oblique',captionSize=8, + captionTextColor=colors.black, + shrinkToFit=1, + growToFit=1, + spaceBefore=12, + spaceAfter=12, + captionGap=9, + captionAlign='centre', + captionPosition='top', + scaleFactor=None, + hAlign='CENTER', + border=1, + ): + Figure.__init__(self, width, height, caption, + captionFont=captionFont, + captionSize=captionSize, + background=None, + captionTextColor=captionTextColor, + spaceBefore = spaceBefore, + spaceAfter = spaceAfter, + captionGap=captionGap, + captionAlign=captionAlign, + captionPosition=captionPosition, + hAlign=hAlign, + border=border, + ) + self.shrinkToFit = shrinkToFit #if set and wrap is too tight, shrinks + self.growToFit = growToFit #if set and wrap is too small, grows + self.scaleFactor = scaleFactor + self._scaleFactor = None + self.background = background + + def _scale(self,availWidth,availHeight): + "Rescale to fit according to the rules, but only once" + if self._scaleFactor is None or self.width>availWidth or self.height>availHeight: + w, h = Figure.wrap(self, availWidth, availHeight) + captionHeight = h - self.figureHeight + if self.scaleFactor is None: + #scale factor None means auto + self._scaleFactor = min(availWidth/self.width,(availHeight-captionHeight)/self.figureHeight) + else: #they provided a factor + self._scaleFactor = self.scaleFactor + if self._scaleFactor<1 and self.shrinkToFit: + self.width = self.width * self._scaleFactor - 0.0001 + self.figureHeight = self.figureHeight * self._scaleFactor + elif self._scaleFactor>1 and self.growToFit: + self.width = self.width*self._scaleFactor - 0.0001 + self.figureHeight = self.figureHeight * self._scaleFactor + + def wrap(self, availWidth, availHeight): + self._scale(availWidth,availHeight) + return Figure.wrap(self, availWidth, availHeight) + + def split(self, availWidth, availHeight): + self._scale(availWidth,availHeight) + return Figure.split(self, availWidth, availHeight) + +class ImageFigure(FlexFigure): + """Image with a caption below it""" + def __init__(self, filename, caption, background=None,scaleFactor=None,hAlign='CENTER',border=None): + assert os.path.isfile(filename), 'image file %s not found' % filename + from reportlab.lib.utils import ImageReader + w, h = ImageReader(filename).getSize() + self.filename = filename + FlexFigure.__init__(self, w, h, caption, background,scaleFactor=scaleFactor,hAlign=hAlign,border=border) + + def drawFigure(self): + self.canv.drawImage(self.filename, + 0, 0,self.width, self.figureHeight) + +class DrawingFigure(FlexFigure): + """Drawing with a caption below it. Clunky, scaling fails.""" + def __init__(self, modulename, classname, caption, baseDir=None, background=None): + module = recursiveImport(modulename, baseDir) + klass = getattr(module, classname) + self.drawing = klass() + FlexFigure.__init__(self, + self.drawing.width, + self.drawing.height, + caption, + background) + self.growToFit = 1 + + def drawFigure(self): + self.canv.scale(self._scaleFactor, self._scaleFactor) + self.drawing.drawOn(self.canv, 0, 0) + +try: + from rlextra.pageCatcher.pageCatcher import restoreForms, storeForms, storeFormsInMemory, restoreFormsInMemory + _hasPageCatcher = 1 +except ImportError: + _hasPageCatcher = 0 +if _hasPageCatcher: + #################################################################### + # + # PageCatcher plugins + # These let you use our PageCatcher product to add figures + # to other documents easily. + #################################################################### + class PageCatcherCachingMixIn: + "Helper functions to cache pages for figures" + + def getFormName(self, pdfFileName, pageNo): + #naming scheme works within a directory only + dirname, filename = os.path.split(pdfFileName) + root, ext = os.path.splitext(filename) + return '%s_page%d' % (root, pageNo) + + def needsProcessing(self, pdfFileName, pageNo): + "returns 1 if no forms or form is older" + formName = self.getFormName(pdfFileName, pageNo) + if os.path.exists(formName + '.frm'): + formModTime = os.stat(formName + '.frm')[8] + pdfModTime = os.stat(pdfFileName)[8] + return (pdfModTime > formModTime) + else: + return 1 + + def processPDF(self, pdfFileName, pageNo): + formName = self.getFormName(pdfFileName, pageNo) + storeForms(pdfFileName, formName + '.frm', + prefix= formName + '_', + pagenumbers=[pageNo]) + #print 'stored %s.frm' % formName + return formName + '.frm' + + class cachePageCatcherFigureNonA4(FlexFigure, PageCatcherCachingMixIn): + """PageCatcher page with a caption below it. Size to be supplied.""" + # This should merge with PageFigure into one class that reuses + # form information to determine the page orientation... + def __init__(self, filename, pageNo, caption, width, height, background=None): + self.dirname, self.filename = os.path.split(filename) + if self.dirname == '': + self.dirname = os.curdir + self.pageNo = pageNo + self.formName = self.getFormName(self.filename, self.pageNo) + '_' + str(pageNo) + FlexFigure.__init__(self, width, height, caption, background) + + def drawFigure(self): + self.canv.saveState() + if not self.canv.hasForm(self.formName): + restorePath = self.dirname + os.sep + self.filename + #does the form file exist? if not, generate it. + formFileName = self.getFormName(restorePath, self.pageNo) + '.frm' + if self.needsProcessing(restorePath, self.pageNo): + #print 'preprocessing PDF %s page %s' % (restorePath, self.pageNo) + self.processPDF(restorePath, self.pageNo) + names = restoreForms(formFileName, self.canv) + self.canv.scale(self._scaleFactor, self._scaleFactor) + self.canv.doForm(self.formName) + self.canv.restoreState() + + class cachePageCatcherFigure(cachePageCatcherFigureNonA4): + """PageCatcher page with a caption below it. Presumes A4, Portrait. + This needs our commercial PageCatcher product, or you'll get a blank.""" + def __init__(self, filename, pageNo, caption, width=595, height=842, background=None): + cachePageCatcherFigureNonA4.__init__(self, filename, pageNo, caption, width, height, background=background) + + class PageCatcherFigureNonA4(FlexFigure): + """PageCatcher page with a caption below it. Size to be supplied.""" + # This should merge with PageFigure into one class that reuses + # form information to determine the page orientation... + _cache = {} + def __init__(self, filename, pageNo, caption, width, height, background=None, caching=None): + fn = self.filename = filename + self.pageNo = pageNo + fn = fn.replace(os.sep,'_').replace('/','_').replace('\\','_').replace('-','_').replace(':','_') + self.prefix = fn.replace('.','_')+'_'+str(pageNo)+'_' + self.formName = self.prefix + str(pageNo) + self.caching = caching + FlexFigure.__init__(self, width, height, caption, background) + + def drawFigure(self): + if not self.canv.hasForm(self.formName): + if self.filename in self._cache: + f,data = self._cache[self.filename] + else: + f = open(self.filename,'rb') + pdf = f.read() + f.close() + f, data = storeFormsInMemory(pdf, pagenumbers=[self.pageNo], prefix=self.prefix) + if self.caching=='memory': + self._cache[self.filename] = f, data + f = restoreFormsInMemory(data, self.canv) + self.canv.saveState() + self.canv.scale(self._scaleFactor, self._scaleFactor) + self.canv.doForm(self.formName) + self.canv.restoreState() + + class PageCatcherFigure(PageCatcherFigureNonA4): + """PageCatcher page with a caption below it. Presumes A4, Portrait. + This needs our commercial PageCatcher product, or you'll get a blank.""" + def __init__(self, filename, pageNo, caption, width=595, height=842, background=None, caching=None): + PageCatcherFigureNonA4.__init__(self, filename, pageNo, caption, width, height, background=background, caching=caching) + +def demo1(canvas): + frame = Frame( + 2*inch, # x + 4*inch, # y at bottom + 4*inch, # width + 5*inch, # height + showBoundary = 1 # helps us see what's going on + ) + bodyStyle = ParagraphStyle('Body', fontName=_baseFontName, fontSize=24, leading=28, spaceBefore=6) + para1 = Paragraph('Spam spam spam spam. ' * 5, bodyStyle) + para2 = Paragraph('Eggs eggs eggs. ' * 5, bodyStyle) + mydata = [para1, para2] + + #this does the packing and drawing. The frame will consume + #items from the front of the list as it prints them + frame.addFromList(mydata,canvas) + +def test1(): + c = Canvas('figures.pdf') + f = Frame(inch, inch, 6*inch, 9*inch, showBoundary=1) + v = PlatPropFigure1() + v.captionTextColor = toColor('blue') + v.captionBackColor = toColor('lightyellow') + f.addFromList([v],c) + c.save() + +if __name__ == '__main__': + test1() diff --git a/.venv/lib/python3.13/site-packages/reportlab/platypus/flowables.py b/.venv/lib/python3.13/site-packages/reportlab/platypus/flowables.py new file mode 100644 index 0000000000000000000000000000000000000000..6310993b5d9549f3f912254b126cfdf815d90b62 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/reportlab/platypus/flowables.py @@ -0,0 +1,2663 @@ +#Copyright ReportLab Europe Ltd. 2000-2017 +#see license.txt for license details +#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/platypus/flowables.py +__version__='3.3.0' +__doc__=""" +A flowable is a "floating element" in a document whose exact position is determined by the +other elements that precede it, such as a paragraph, a diagram interspersed between paragraphs, +a section header, etcetera. Examples of non-flowables include page numbering annotations, +headers, footers, fixed diagrams or logos, among others. + +Flowables are defined here as objects which know how to determine their size and which +can draw themselves onto a page with respect to a relative "origin" position determined +at a higher level. The object's draw() method should assume that (0,0) corresponds to the +bottom left corner of the enclosing rectangle that will contain the object. The attributes +vAlign and hAlign may be used by 'packers' as hints as to how the object should be placed. + +Some Flowables also know how to "split themselves". For example a +long paragraph might split itself between one page and the next. + +Packers should set the canv attribute during wrap, split & draw operations to allow +the flowable to work out sizes etc in the proper context. + +The "text" of a document usually consists mainly of a sequence of flowables which +flow into a document from top to bottom (with column and page breaks controlled by +higher level components). +""" +import os +from copy import deepcopy, copy +from reportlab.lib.colors import gray, lightgrey +from reportlab.lib.rl_accel import fp_str +from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT +from reportlab.lib.styles import _baseFontName +from reportlab.lib.utils import strTypes, rl_safe_exec, annotateException +from reportlab.lib.abag import ABag +from reportlab.pdfbase import pdfutils +from reportlab.pdfbase.pdfmetrics import stringWidth +from reportlab.rl_config import _FUZZ, overlapAttachedSpace, ignoreContainerActions, listWrapOnFakeWidth + +__all__ = '''AnchorFlowable BalancedColumns BulletDrawer CallerMacro CondPageBreak DDIndenter DocAssert + DocAssign DocExec DocIf DocPara DocWhile FailOnDraw FailOnWrap Flowable FrameBG FrameSplitter + HRFlowable Image ImageAndFlowables KeepInFrame KeepTogether LIIndenter ListFlowable ListItem + Macro NullDraw PTOContainer PageBreak PageBreakIfNotEmpty ParagraphAndImage Preformatted + SetPageTopFlowables SetTopFlowables SlowPageBreak Spacer TopPadder TraceInfo UseUpSpace XBox + splitLine splitLines PlacedStory'''.split() + +class TraceInfo: + "Holder for info about where an object originated" + def __init__(self): + self.srcFile = '(unknown)' + self.startLineNo = -1 + self.startLinePos = -1 + self.endLineNo = -1 + self.endLinePos = -1 + +############################################################# +# Flowable Objects - a base class and a few examples. +# One is just a box to get some metrics. We also have +# a paragraph, an image and a special 'page break' +# object which fills the space. +############################################################# +class Flowable: + """Abstract base class for things to be drawn. Key concepts: + + 1. It knows its size + 2. It draws in its own coordinate system (this requires the + base API to provide a translate() function. + + """ + _fixedWidth = 0 #assume wrap results depend on arguments? + _fixedHeight = 0 + + def __init__(self): + self.width = 0 + self.height = 0 + self.wrapped = 0 + + #these are hints to packers/frames as to how the floable should be positioned + self.hAlign = 'LEFT' #CENTER/CENTRE or RIGHT + self.vAlign = 'BOTTOM' #MIDDLE or TOP + + #optional holder for trace info + self._traceInfo = None + self._showBoundary = None + + #many flowables handle text and must be processed in the + #absence of a canvas. tagging them with their encoding + #helps us to get conversions right. Use Python codec names. + self.encoding = None + + def _drawOn(self,canv): + '''ensure canv is set on and then draw''' + self.canv = canv + self.draw()#this is the bit you overload + del self.canv + + def _hAlignAdjust(self,x,sW=0): + if sW and hasattr(self,'hAlign'): + a = self.hAlign + if a in ('CENTER','CENTRE', TA_CENTER): + x += 0.5*sW + elif a in ('RIGHT',TA_RIGHT): + x += sW + elif a not in ('LEFT',TA_LEFT): + raise ValueError("Bad hAlign value "+str(a)) + return x + + def drawOn(self, canvas, x, y, _sW=0): + "Tell it to draw itself on the canvas. Do not override" + x = self._hAlignAdjust(x,_sW) + canvas.saveState() + canvas.translate(x, y) + self._drawOn(canvas) + if hasattr(self, '_showBoundary') and self._showBoundary: + #diagnostic tool support + canvas.setStrokeColor(gray) + canvas.rect(0,0,self.width, self.height) + canvas.restoreState() + + def wrapOn(self, canv, aW, aH): + '''intended for use by packers allows setting the canvas on + during the actual wrap''' + self.canv = canv + w, h = self.wrap(aW,aH) + del self.canv + return w, h + + def wrap(self, availWidth, availHeight): + """This will be called by the enclosing frame before objects + are asked their size, drawn or whatever. It returns the + size actually used.""" + return (self.width, self.height) + + def minWidth(self): + """This should return the minimum required width""" + return getattr(self,'_minWidth',self.width) + + def splitOn(self, canv, aW, aH): + '''intended for use by packers allows setting the canvas on + during the actual split''' + self.canv = canv + S = self.split(aW,aH) + del self.canv + return S + + def split(self, availWidth, availheight): + """This will be called by more sophisticated frames when + wrap fails. Stupid flowables should return []. Clever flowables + should split themselves and return a list of flowables. + If they decide that nothing useful can be fitted in the + available space (e.g. if you have a table and not enough + space for the first row), also return []""" + return [] + + def getKeepWithNext(self): + """returns boolean determining whether the next flowable should stay with this one""" + if hasattr(self,'keepWithNext'): return self.keepWithNext + elif hasattr(self,'style') and hasattr(self.style,'keepWithNext'): return self.style.keepWithNext + else: return 0 + + def getSpaceAfter(self): + """returns how much space should follow this item if another item follows on the same page.""" + if hasattr(self,'spaceAfter'): return self.spaceAfter + elif hasattr(self,'style') and hasattr(self.style,'spaceAfter'): return self.style.spaceAfter + else: return 0 + + def getSpaceBefore(self): + """returns how much space should precede this item if another item precedess on the same page.""" + if hasattr(self,'spaceBefore'): return self.spaceBefore + elif hasattr(self,'style') and hasattr(self.style,'spaceBefore'): return self.style.spaceBefore + else: return 0 + + def isIndexing(self): + """Hook for IndexingFlowables - things which have cross references""" + return 0 + + def identity(self, maxLen=None): + ''' + This method should attempt to return a string that can be used to identify + a particular flowable uniquely. The result can then be used for debugging + and or error printouts + ''' + if hasattr(self, 'getPlainText'): + r = self.getPlainText(identify=1) + elif hasattr(self, 'text'): + r = str(self.text) + else: + r = '...' + if r and maxLen: + r = r[:maxLen] + return "<%s at %s%s>%s" % (self.__class__.__name__, hex(id(self)), self._frameName(), r) + + @property + def _doctemplate(self): + return getattr(getattr(self,'canv',None),'_doctemplate',None) + + def _doctemplateAttr(self,a): + return getattr(self._doctemplate,a,None) + + def _frameName(self): + f = getattr(self,'_frame',None) + if not f: f = self._doctemplateAttr('frame') + if f and f.id: return ' frame=%s' % f.id + return '' + +class XBox(Flowable): + """Example flowable - a box with an x through it and a caption. + This has a known size, so does not need to respond to wrap().""" + def __init__(self, width, height, text = 'A Box'): + Flowable.__init__(self) + self.width = width + self.height = height + self.text = text + + def __repr__(self): + return "XBox(w=%s, h=%s, t=%s)" % (self.width, self.height, self.text) + + def draw(self): + self.canv.rect(0, 0, self.width, self.height) + self.canv.line(0, 0, self.width, self.height) + self.canv.line(0, self.height, self.width, 0) + + #centre the text + self.canv.setFont(_baseFontName,12) + self.canv.drawCentredString(0.5*self.width, 0.5*self.height, self.text) + +def _trimEmptyLines(lines): + #don't want the first or last to be empty + while len(lines) and lines[0].strip() == '': + lines = lines[1:] + while len(lines) and lines[-1].strip() == '': + lines = lines[:-1] + return lines + +def _dedenter(text,dedent=0): + ''' + tidy up text - carefully, it is probably code. If people want to + indent code within a source script, you can supply an arg to dedent + and it will chop off that many character, otherwise it leaves + left edge intact. + ''' + lines = text.split('\n') + if dedent>0: + templines = _trimEmptyLines(lines) + lines = [] + for line in templines: + line = line[dedent:].rstrip() + lines.append(line) + else: + lines = _trimEmptyLines(lines) + + return lines + +SPLIT_CHARS = "[{( ,.;:/\\-" + +def splitLines(lines, maximum_length, split_characters, new_line_characters): + if split_characters is None: + split_characters = SPLIT_CHARS + if new_line_characters is None: + new_line_characters = "" + # Return a table of lines + lines_splitted = [] + for line in lines: + if len(line) > maximum_length: + splitLine(line, lines_splitted, maximum_length, \ + split_characters, new_line_characters) + else: + lines_splitted.append(line) + return lines_splitted + +def splitLine(line_to_split, lines_splitted, maximum_length, \ +split_characters, new_line_characters): + # Used to implement the characters added + #at the beginning of each new line created + first_line = True + + # Check if the text can be splitted + while line_to_split and len(line_to_split)>0: + + # Index of the character where we can split + split_index = 0 + + # Check if the line length still exceeds the maximum length + if len(line_to_split) <= maximum_length: + # Return the remaining of the line + split_index = len(line_to_split) + else: + # Iterate for each character of the line + for line_index in range(maximum_length): + # Check if the character is in the list + # of allowed characters to split on + if line_to_split[line_index] in split_characters: + split_index = line_index + 1 + + # If the end of the line was reached + # with no character to split on + if split_index==0: + split_index = line_index + 1 + + if first_line: + lines_splitted.append(line_to_split[0:split_index]) + first_line = False + maximum_length -= len(new_line_characters) + else: + lines_splitted.append(new_line_characters + \ + line_to_split[0:split_index]) + + # Remaining text to split + line_to_split = line_to_split[split_index:] + +class Preformatted(Flowable): + """This is like the HTML
 tag.
+    It attempts to display text exactly as you typed it in a fixed width "typewriter" font.
+    By default the line breaks are exactly where you put them, and it will not be wrapped.
+    You can optionally define a maximum line length and the code will be wrapped; and
+    extra characters to be inserted at the beginning of each wrapped line (e.g. '> ').
+    """
+    def __init__(self, text, style, bulletText = None, dedent=0, maxLineLength=None, splitChars=None, newLineChars=""):
+        """text is the text to display. If dedent is set then common leading space
+        will be chopped off the front (for example if the entire text is indented
+        6 spaces or more then each line will have 6 spaces removed from the front).
+        """
+        self.style = style
+        self.bulletText = bulletText
+        self.lines = _dedenter(text,dedent)
+        if text and maxLineLength:
+            self.lines = splitLines(
+                                self.lines,
+                                maxLineLength,
+                                splitChars,
+                                newLineChars
+                        )
+
+    def __repr__(self):
+        bT = self.bulletText
+        H = "Preformatted("
+        if bT is not None:
+            H = "Preformatted(bulletText=%s," % repr(bT)
+        return "%s'''\\ \n%s''')" % (H, '\n'.join(self.lines))
+
+    def wrap(self, availWidth, availHeight):
+        self.width = availWidth
+        self.height = self.style.leading*len(self.lines)
+        return (self.width, self.height)
+
+    def minWidth(self):
+        style = self.style
+        fontSize = style.fontSize
+        fontName = style.fontName
+        return max([stringWidth(line,fontName,fontSize) for line in self.lines])
+
+    def split(self, availWidth, availHeight):
+        #returns two Preformatted objects
+
+        #not sure why they can be called with a negative height
+        if availHeight < self.style.leading:
+            return []
+
+        linesThatFit = int(availHeight * 1.0 / self.style.leading)
+
+        text1 = '\n'.join(self.lines[0:linesThatFit])
+        text2 = '\n'.join(self.lines[linesThatFit:])
+        style = self.style
+        if style.firstLineIndent != 0:
+            style = deepcopy(style)
+            style.firstLineIndent = 0
+        return [Preformatted(text1, self.style), Preformatted(text2, style)]
+
+    def draw(self):
+        #call another method for historical reasons.  Besides, I
+        #suspect I will be playing with alternate drawing routines
+        #so not doing it here makes it easier to switch.
+
+        cur_x = self.style.leftIndent
+        cur_y = self.height - self.style.fontSize
+        self.canv.addLiteral('%PreformattedPara')
+        if self.style.textColor:
+            self.canv.setFillColor(self.style.textColor)
+        tx = self.canv.beginText(cur_x, cur_y)
+        #set up the font etc.
+        tx.setFont( self.style.fontName,
+                    self.style.fontSize,
+                    self.style.leading)
+
+        for text in self.lines:
+            tx.textLine(text)
+        self.canv.drawText(tx)
+
+class Image(Flowable):
+    """an image (digital picture).  Formats supported by PIL/Java 1.4 (the Python/Java Imaging Library
+       are supported. Images as flowables may be aligned horizontally in the
+       frame with the hAlign parameter - accepted values are 'CENTER',
+       'LEFT' or 'RIGHT' with 'CENTER' being the default.
+       We allow for two kinds of lazyness to allow for many images in a document
+       which could lead to file handle starvation.
+       lazy=1 don't open image until required.
+       lazy=2 open image when required then shut it.
+    """
+    _fixedWidth = 1
+    _fixedHeight = 1
+    def __init__(self, filename, width=None, height=None, kind='direct',
+                 mask="auto", lazy=1, hAlign='CENTER', useDPI=False):
+        """If size to draw at not specified, get it from the image."""
+        self.hAlign = hAlign
+        self._mask = mask
+        fp = hasattr(filename,'read')
+        self._drawing = None
+        if fp:
+            self._file = filename
+            self.filename = repr(filename)
+        elif hasattr(filename,'_renderPy'):
+            self._drawing = filename
+            self.filename=repr(filename)
+            self._file = None
+            self._img = None
+            fp = True
+        else:
+            self._file = self.filename = filename
+        self._dpi = useDPI
+        if not fp and os.path.splitext(filename)[1] in ['.jpg', '.JPG', '.jpeg', '.JPEG']:
+            # if it is a JPEG, will be inlined within the file -
+            # but we still need to know its size now
+            from reportlab.lib.utils import open_for_read
+            f = open_for_read(filename, 'b')
+            try:
+                try:
+                    info = pdfutils.readJPEGInfo(f)
+                except:
+                    #couldn't read as a JPEG, try like normal
+                    self._setup(width,height,kind,lazy)
+                    return
+            finally:
+                f.close()
+            self.imageWidth = info[0]
+            self.imageHeight = info[1]
+            if useDPI:
+                self._dpi = info[3]
+            self._img = None
+            self._setup(width,height,kind,0)
+        elif fp:
+            self._setup(width,height,kind,0)
+        else:
+            self._setup(width,height,kind,lazy)
+
+    def _dpiAdjust(self):
+        dpi = self._dpi
+        if dpi:
+            if dpi[0]!=72: self.imageWidth *= 72.0 / dpi[0]
+            if dpi[1]!=72: self.imageHeight *= 72.0 / dpi[1]
+
+    def _setup(self,width,height,kind,lazy):
+        self._lazy = lazy
+        self._width = width
+        self._height = height
+        self._kind = kind
+        if lazy<=0: self._setup_inner()
+
+    def _setup_inner(self):
+        width = self._width
+        height = self._height
+        kind = self._kind
+        img = self._img
+        if img:
+            self.imageWidth, self.imageHeight = img.getSize()
+            if self._dpi and hasattr(img,'_image'):
+                self._dpi = img._image.info.get('dpi',(72,72))
+        elif self._drawing:
+            self.imageWidth, self.imageHeight = self._drawing.width,self._drawing.height
+            self._dpi = False
+        self._dpiAdjust()
+        if self._lazy>=2: del self._img
+        if kind in ['direct','absolute']:
+            self.drawWidth = width or self.imageWidth
+            self.drawHeight = height or self.imageHeight
+        elif kind in ['percentage','%']:
+            self.drawWidth = self.imageWidth*width*0.01
+            self.drawHeight = self.imageHeight*height*0.01
+        elif kind in ['bound','proportional']:
+            factor = min(float(width)/self.imageWidth,float(height)/self.imageHeight)
+            self.drawWidth = self.imageWidth*factor
+            self.drawHeight = self.imageHeight*factor
+
+    def _restrictSize(self,aW,aH):
+        if self.drawWidth>aW+_FUZZ or self.drawHeight>aH+_FUZZ:
+            self._oldDrawSize = self.drawWidth, self.drawHeight
+            factor = min(float(aW)/self.drawWidth,float(aH)/self.drawHeight)
+            self.drawWidth *= factor
+            self.drawHeight *= factor
+        return self.drawWidth, self.drawHeight
+
+    def _unRestrictSize(self):
+        dwh = getattr(self,'_oldDrawSize',None)
+        if dwh:
+            self.drawWidth, self.drawHeight = dwh
+
+    def __getattr__(self,a):
+        if a=='_img':
+            from reportlab.lib.utils import ImageReader  #this may raise an error
+            self._img = ImageReader(self._file)
+            if not isinstance(self._file,strTypes):
+                self._file = None
+                if self._lazy>=2: self._lazy = 1    #here we're assuming we cannot read again
+            return self._img
+        elif a in ('drawWidth','drawHeight','imageWidth','imageHeight'):
+            self._setup_inner()
+            return self.__dict__[a]
+        raise AttributeError(".%s" % (id(self),a))
+
+    def wrap(self, availWidth, availHeight):
+        #the caller may decide it does not fit.
+        return self.drawWidth, self.drawHeight
+
+    def draw(self):
+        dx = getattr(self,'_offs_x',0)
+        dy = getattr(self,'_offs_y',0)
+        d = self._drawing
+        if d:
+            sx = self.drawWidth / float(self.imageWidth)
+            sy = self.drawHeight / float(self.imageHeight)
+            otrans = d.transform
+            try:
+                d.scale(sx,sy)
+                d.drawOn(self.canv,dx,dy)
+            finally:
+                d.transform = otrans
+        else:
+            lazy = self._lazy
+            if lazy>=2: self._lazy = 1
+            self.canv.drawImage(    self._img or self.filename,
+                                    dx,
+                                    dy,
+                                    self.drawWidth,
+                                    self.drawHeight,
+                                    mask=self._mask,
+                                    )
+            if lazy>=2:
+                self._img = self._file = None
+                self._lazy = lazy
+
+    def identity(self,maxLen=None):
+        r = Flowable.identity(self,maxLen)
+        if r[-4:]=='>...' and isinstance(self.filename,str):
+            r = "%s filename=%s>" % (r[:-4],self.filename)
+        return r
+
+class NullDraw(Flowable):
+    def draw(self):
+        pass
+
+class Spacer(NullDraw):
+    """A spacer just takes up space and doesn't draw anything - it guarantees
+       a gap between objects."""
+    _fixedWidth = 1
+    _fixedHeight = 1
+    def __init__(self, width, height, isGlue=False):
+        self.width = width
+        if isGlue:
+            self.height = 1e-4
+            self.spacebefore = height
+        self.height = height
+
+    def __repr__(self):
+        return "%s(%s, %s)" % (self.__class__.__name__,self.width, self.height)
+
+class UseUpSpace(NullDraw):
+    def __init__(self):
+        pass
+
+    def __repr__(self):
+        return "%s()" % self.__class__.__name__
+
+    def wrap(self, availWidth, availHeight):
+        self.width = availWidth
+        self.height = availHeight
+        return (availWidth,availHeight-1e-8)  #step back a point
+
+class PageBreak(UseUpSpace):
+    locChanger=1
+    """Move on to the next page in the document.
+       This works by consuming all remaining space in the frame!"""
+    def __init__(self,nextTemplate=None):
+        self.nextTemplate = nextTemplate
+
+    def __repr__(self):
+        return "%s(%s)" % (self.__class__.__name__,repr(self.nextTemplate) if self.nextTemplate else '')
+
+class SlowPageBreak(PageBreak):
+    pass
+
+class PageBreakIfNotEmpty(PageBreak):
+    pass
+
+class CondPageBreak(Spacer):
+    locChanger=1
+    """use up a frame if not enough vertical space effectively CondFrameBreak"""
+    def __init__(self, height):
+        self.height = height
+
+    def __repr__(self):
+        return "CondPageBreak(%s)" %(self.height,)
+
+    def wrap(self, availWidth, availHeight):
+        if availHeightaH and (not self._maxHeight or aH>self._maxHeight)
+        C1 = (self._H0>aH) or C0 and atTop
+        if C0 or C1:
+            fb = False
+            panf = self._doctemplateAttr('_peekNextFrame')
+            if cf and panf:
+                nf = panf()
+                nAW = nf._width
+                nAH = nf._height
+            if C0 and not (self.splitAtTop and atTop):
+                fb = not (atTop and cf and nf and cAW>=nAW and cAH>=nAH)
+            elif nf and nAW>=cf._width and nAH>=self._H:
+                fb = True
+
+            S.insert(0,(self.FrameBreak if fb else self.NullActionFlowable)())
+        return S
+
+    def identity(self, maxLen=None):
+        msg = "<%s at %s%s> containing :%s" % (self.__class__.__name__,hex(id(self)),self._frameName(),"\n".join([f.identity() for f in self._content]))
+        if maxLen:
+            return msg[0:maxLen]
+        else:
+            return msg
+
+class KeepTogetherSplitAtTop(KeepTogether):
+    '''
+    Same as KeepTogether, but it will split content immediately if it cannot
+    fit at the top of a frame.
+    '''
+    splitAtTop = True
+
+class Macro(Flowable):
+    """This is not actually drawn (i.e. it has zero height)
+    but is executed when it would fit in the frame.  Allows direct
+    access to the canvas through the object 'canvas'"""
+    def __init__(self, command):
+        self.command = command
+    def __repr__(self):
+        return "Macro(%s)" % repr(self.command)
+    def wrap(self, availWidth, availHeight):
+        return (0,0)
+    def draw(self):
+        rl_safe_exec(self.command, g=None, l={'canvas':self.canv})
+
+def _nullCallable(*args,**kwds):
+    pass
+
+class CallerMacro(Flowable):
+    '''
+    like Macro, but with callable command(s)
+    drawCallable(self)
+    wrapCallable(self,aW,aH)
+    '''
+    def __init__(self, drawCallable=None, wrapCallable=None):
+        self._drawCallable = drawCallable or _nullCallable
+        self._wrapCallable = wrapCallable or _nullCallable
+    def __repr__(self):
+        return "CallerMacro(%r,%r)" % (self._drawCallable,self._wrapCallable)
+    def wrap(self, aW, aH):
+        self._wrapCallable(self,aW,aH)
+        return (0,0)
+    def draw(self):
+        self._drawCallable(self)
+
+class ParagraphAndImage(Flowable):
+    '''combine a Paragraph and an Image'''
+    def __init__(self,P,I,xpad=3,ypad=3,side='right'):
+        self.P = P
+        self.I = I
+        self.xpad = xpad
+        self.ypad = ypad
+        self._side = side
+
+    def getSpaceBefore(self):
+        return max(self.P.getSpaceBefore(),self.I.getSpaceBefore())
+
+    def getSpaceAfter(self):
+        return max(self.P.getSpaceAfter(),self.I.getSpaceAfter())
+
+    def wrap(self,availWidth,availHeight):
+        wI, hI = self.I.wrap(availWidth,availHeight)
+        self.wI = wI
+        self.hI = hI
+        # work out widths array for breaking
+        self.width = availWidth
+        P = self.P
+        style = P.style
+        xpad = self.xpad
+        ypad = self.ypad
+        leading = style.leading
+        leftIndent = style.leftIndent
+        later_widths = availWidth - leftIndent - style.rightIndent
+        intermediate_widths = later_widths - xpad - wI
+        first_line_width = intermediate_widths - style.firstLineIndent
+        P.width = 0
+        nIW = int((hI+ypad)/(leading*1.0))
+        P.blPara = P.breakLines([first_line_width] + nIW*[intermediate_widths]+[later_widths])
+        if self._side=='left':
+            self._offsets = [wI+xpad]*(1+nIW)+[0]
+        P.height = len(P.blPara.lines)*leading
+        self.height = max(hI,P.height)
+        return (self.width, self.height)
+
+    def split(self,availWidth, availHeight):
+        P, wI, hI, ypad = self.P, self.wI, self.hI, self.ypad
+        if hI+ypad>availHeight or len(P.frags)<=0: return []
+        S = P.split(availWidth,availHeight)
+        if not S: return S
+        P = self.P = S[0]
+        del S[0]
+        style = P.style
+        P.height = len(self.P.blPara.lines)*style.leading
+        self.height = max(hI,P.height)
+        return [self]+S
+
+    def draw(self):
+        canv = self.canv
+        if self._side=='left':
+            self.I.drawOn(canv,0,self.height-self.hI-self.ypad)
+            self.P._offsets = self._offsets
+            try:
+                self.P.drawOn(canv,0,0)
+            finally:
+                del self.P._offsets
+        else:
+            self.I.drawOn(canv,self.width-self.wI-self.xpad,self.height-self.hI-self.ypad)
+            self.P.drawOn(canv,0,0)
+
+class FailOnWrap(NullDraw):
+    def wrap(self, availWidth, availHeight):
+        raise ValueError("FailOnWrap flowable wrapped and failing as ordered!")
+
+class FailOnDraw(Flowable):
+    def wrap(self, availWidth, availHeight):
+        return 0,0
+
+    def draw(self):
+        raise ValueError("FailOnDraw flowable drawn, and failing as ordered!")
+
+class HRFlowable(Flowable):
+    '''Like the hr tag'''
+    def __init__(self,
+            width="80%",
+            thickness=1,
+            lineCap='round',
+            color=lightgrey,
+            spaceBefore=1, spaceAfter=1,
+            hAlign='CENTER', vAlign='BOTTOM',
+            dash=None):
+        Flowable.__init__(self)
+        self.width = width
+        self.lineWidth = thickness
+        self.lineCap=lineCap
+        self.spaceBefore = spaceBefore
+        self.spaceAfter = spaceAfter
+        self.color = color
+        self.hAlign = hAlign
+        self.vAlign = vAlign
+        self.dash = dash
+
+    def __repr__(self):
+        return "HRFlowable(width=%s, height=%s)" % (self.width, self.height)
+
+    def wrap(self, availWidth, availHeight):
+        w = self.width
+        if isinstance(w,strTypes):
+            w = w.strip()
+            if w.endswith('%'): w = availWidth*float(w[:-1])*0.01
+            else: w = float(w)
+        w = min(w,availWidth)
+        self._width = w
+        return w, self.lineWidth
+
+    def draw(self):
+        canv = self.canv
+        canv.saveState()
+        canv.setLineWidth(self.lineWidth)
+        canv.setLineCap({'butt':0,'round':1, 'square': 2}[self.lineCap.lower()])
+        canv.setStrokeColor(self.color)
+        if self.dash: canv.setDash(self.dash)
+        canv.line(0, 0, self._width, self.height)
+        canv.restoreState()
+
+class _PTOInfo:
+    def __init__(self,trailer,header):
+        self.trailer = _flowableSublist(trailer)
+        self.header = _flowableSublist(header)
+
+def cdeepcopy(obj):
+    if hasattr(obj,'deepcopy'):
+        return obj.deepcopy()
+    else:
+        return deepcopy(obj)
+
+class _Container(_ContainerSpace):  #Abstract some common container like behaviour
+    def drawOn(self, canv, x, y, _sW=0, scale=1.0, content=None, aW=None):
+        '''we simulate being added to a frame'''
+        from reportlab.platypus.doctemplate import ActionFlowable, Indenter
+        x0 = x
+        y0 = y
+        pS = 0
+        if aW is None: aW = self.width
+        aW *= scale
+        if content is None:
+            content = self._content
+        x = self._hAlignAdjust(x,_sW*scale)
+        y += self.height*scale
+        yt = y
+        frame = getattr(self,'_frame',None)
+        for c in content:
+            if not ignoreContainerActions and isinstance(c,ActionFlowable):
+                c.apply(canv._doctemplate)
+                continue
+            if isinstance(c,Indenter):
+                x += c.left*scale
+                aW -= (c.left+c.right)*scale
+                continue
+            w, h = c.wrapOn(canv,aW,0xfffffff)
+            if h<_FUZZ and not getattr(c,'_ZEROSIZE',None): continue
+            if yt!=y:
+                s = c.getSpaceBefore()
+                if not getattr(c,'_SPACETRANSFER',False):
+                    h += max(s-pS,0)
+            y -= h
+            s = c.getSpaceAfter()
+            if getattr(c,'_SPACETRANSFER',False):
+                s = pS
+            pS = s
+            fbg = getattr(frame,'_frameBGs',None)
+            if fbg and fbg[-1].active:
+                bg = fbg[-1]
+                fbgl = bg.left
+                fbgr = bg.right
+                bgm = bg.start
+                fbw = scale*(frame._width-fbgl-fbgr)
+                fbx = x0+scale*(fbgl-frame._leftPadding)
+                fbh = y + h + pS
+                fby = max(y0,y-pS)
+                fbh = max(0,fbh-fby)
+                bg.render(canv,frame,fbx,fby,fbw,fbh)
+            c._frame = frame
+            c.drawOn(canv,x,y,_sW=aW-w)
+            if c is not content[-1] and not getattr(c,'_SPACETRANSFER',None):
+                y -= pS
+            del c._frame
+
+    def copyContent(self,content=None):
+        C = [].append
+        for c in (content or self._content):
+            C(cdeepcopy(c))
+        self._content = C.__self__
+
+class PTOContainer(_Container,Flowable):
+    '''PTOContainer(contentList,trailerList,headerList)
+
+    A container for flowables decorated with trailer & header lists.
+    If the split operation would be called then the trailer and header
+    lists are injected before and after the split. This allows specialist
+    "please turn over" and "continued from previous" like behaviours.'''
+    def __init__(self,content,trailer=None,header=None):
+        I = _PTOInfo(trailer,header)
+        self._content = C = []
+        for _ in _flowableSublist(content):
+            if isinstance(_,PTOContainer):
+                C.extend(_._content)
+            else:
+                C.append(_)
+                if not hasattr(_,'_ptoinfo'): _._ptoinfo = I
+
+    def wrap(self,availWidth,availHeight):
+        self.width, self.height = _listWrapOn(self._content,availWidth,self.canv)
+        return self.width,self.height
+
+    def split(self, availWidth, availHeight):
+        from reportlab.platypus.doctemplate import Indenter
+        if availHeight<0: return []
+        canv = self.canv
+        C = self._content
+        x = i = H = pS = hx = 0
+        n = len(C)
+        I2W = {}
+        dLeft = dRight = 0
+        for x in range(n):
+            c = C[x]
+            I = c._ptoinfo
+            if I not in I2W.keys():
+                T = I.trailer
+                Hdr = I.header
+                tW, tH = _listWrapOn(T, availWidth, self.canv)
+                if len(T):  #trailer may have no content
+                    tSB = T[0].getSpaceBefore()
+                else:
+                    tSB = 0
+                I2W[I] = T,tW,tH,tSB
+            else:
+                T,tW,tH,tSB = I2W[I]
+            _, h = c.wrapOn(canv,availWidth,0xfffffff)
+            if isinstance(c,Indenter):
+                dw = c.left+c.right
+                dLeft += c.left
+                dRight += c.right
+                availWidth -= dw
+                pS = 0
+                hx = 0
+            else:
+                if x:
+                    hx = max(c.getSpaceBefore()-pS,0)
+                    h += hx
+                pS = c.getSpaceAfter()
+            H += h+pS
+            tHS = tH+max(tSB,pS)
+            if H+tHS>=availHeight-_FUZZ: break
+            i += 1
+
+        #first retract last thing we tried
+        H -= (h+pS)
+
+        #attempt a sub split on the last one we have
+        aH = (availHeight-H-tHS-hx)*0.99999
+        if aH>=0.05*availHeight:
+            SS = c.splitOn(canv,availWidth,aH)
+        else:
+            SS = []
+
+        if abs(dLeft)+abs(dRight)>1e-8:
+            R1I = [Indenter(-dLeft,-dRight)]
+            R2I = [Indenter(dLeft,dRight)]
+        else:
+            R1I = R2I = []
+
+        if not SS:
+            j = i
+            while i>1 and C[i-1].getKeepWithNext():
+                i -= 1
+                C[i].keepWithNext = 0
+
+            if i==1 and C[0].getKeepWithNext():
+                #robin's black sheep
+                i = j
+                C[0].keepWithNext = 0
+
+        F = [UseUpSpace()]
+
+        if len(SS)>1:
+            R1 = C[:i]+SS[:1]+R1I+T+F
+            R2 = Hdr+R2I+SS[1:]+C[i+1:]
+        elif not i:
+            return []
+        else:
+            R1 = C[:i]+R1I+T+F
+            R2 = Hdr+R2I+C[i:]
+        T =  R1 + [PTOContainer(R2,[copy(x) for x in I.trailer],[copy(x) for x in I.header])]
+        return T
+
+#utility functions used by KeepInFrame
+def _hmodel(s0,s1,h0,h1):
+    # calculate the parameters in the model
+    # h = a/s**2 + b/s
+    a11 = 1./s0**2
+    a12 = 1./s0
+    a21 = 1./s1**2
+    a22 = 1./s1
+    det = a11*a22-a12*a21
+    b11 = a22/det
+    b12 = -a12/det
+    b21 = -a21/det
+    b22 = a11/det
+    a = b11*h0+b12*h1
+    b = b21*h0+b22*h1
+    return a,b
+
+def _qsolve(h,ab):
+    '''solve the model v = a/s**2 + b/s for an s which gives us v==h'''
+    a,b = ab
+    if abs(a)<=_FUZZ:
+        return b/h
+    t = 0.5*b/a
+    from math import sqrt
+    f = -h/a
+    r = t*t-f
+    if r<0: return None
+    r = sqrt(r)
+    if t>=0:
+        s1 = -t - r
+    else:
+        s1 = -t + r
+    s2 = f/s1
+    return max(1./s1, 1./s2)
+
+class KeepInFrame(_Container,Flowable):
+    def __init__(self, maxWidth, maxHeight, content=[], mergeSpace=1, mode='shrink', name='',hAlign='LEFT',vAlign='BOTTOM', fakeWidth=None):
+        '''mode describes the action to take when overflowing
+            error       raise an error in the normal way
+            continue    ignore ie just draw it and report maxWidth, maxHeight
+            shrink      shrinkToFit
+            truncate    fit as much as possible
+            set fakeWidth to False to make _listWrapOn do the 'right' thing
+        '''
+        self.name = name
+        self.maxWidth = maxWidth
+        self.maxHeight = maxHeight
+        self.mode = mode
+        assert mode in ('error','overflow','shrink','truncate'), '%s invalid mode value %s' % (self.identity(),mode)
+        assert maxHeight>=0,  '%s invalid maxHeight value %s' % (self.identity(),maxHeight)
+        if mergeSpace is None: mergeSpace = overlapAttachedSpace
+        self.mergespace = mergeSpace
+        self._content = content or []
+        self.vAlign = vAlign
+        self.hAlign = hAlign
+        self.fakeWidth = fakeWidth
+
+    def _getAvailableWidth(self):
+        return self.maxWidth - self._leftExtraIndent - self._rightExtraIndent
+
+    def identity(self, maxLen=None):
+        return "<%s at %s%s%s> size=%sx%s" % (self.__class__.__name__, hex(id(self)), self._frameName(),
+                getattr(self,'name','') and (' name="%s"'% getattr(self,'name','')) or '',
+                getattr(self,'maxWidth','') and (' maxWidth=%s'%fp_str(getattr(self,'maxWidth',0))) or '',
+                getattr(self,'maxHeight','')and (' maxHeight=%s' % fp_str(getattr(self,'maxHeight')))or '')
+
+    def wrap(self,availWidth,availHeight):
+        from reportlab.platypus.doctemplate import LayoutError
+        mode = self.mode
+        maxWidth = float(min(self.maxWidth or availWidth,availWidth))
+        maxHeight = float(min(self.maxHeight or availHeight,availHeight))
+        fakeWidth = self.fakeWidth
+        W, H = _listWrapOn(self._content,maxWidth,self.canv, fakeWidth=fakeWidth)
+        if (mode=='error' and (W>maxWidth+_FUZZ or H>maxHeight+_FUZZ)):
+            ident = 'content %sx%s too large for %s' % (W,H,self.identity(30))
+            #leave to keep apart from the raise
+            raise LayoutError(ident)
+        elif W<=maxWidth+_FUZZ and H<=maxHeight+_FUZZ:
+            self.width = W-_FUZZ      #we take what we get
+            self.height = H-_FUZZ
+        elif mode in ('overflow','truncate'):   #we lie
+            self.width = min(maxWidth,W)-_FUZZ
+            self.height = min(maxHeight,H)-_FUZZ
+        else:
+            def func(x):
+                x = float(x)
+                W, H = _listWrapOn(self._content,x*maxWidth,self.canv, fakeWidth=fakeWidth)
+                W /= x
+                H /= x
+                return W, H
+            W0 = W
+            H0 = H
+            s0 = 1
+            if W>maxWidth+_FUZZ:
+                #squeeze out the excess width and or Height
+                s1 = W/maxWidth     #linear model
+                W, H = func(s1)
+                if H<=maxHeight+_FUZZ:
+                    self.width = W-_FUZZ
+                    self.height = H-_FUZZ
+                    self._scale = s1
+                    return W,H
+                s0 = s1
+                H0 = H
+                W0 = W
+            s1 = H/maxHeight
+            W, H = func(s1)
+            self.width = W-_FUZZ
+            self.height = H-_FUZZ
+            self._scale = s1
+            if H=maxHeight+_FUZZ:
+                #the standard case W should be OK, H is short we want
+                #to find the smallest s with H<=maxHeight
+                H1 = H
+                for f in 0, 0.01, 0.05, 0.10, 0.15:
+                    #apply the quadratic model
+                    s = _qsolve(maxHeight*(1-f),_hmodel(s0,s1,H0,H1))
+                    W, H = func(s)
+                    if H<=maxHeight+_FUZZ and W<=maxWidth+_FUZZ:
+                        self.width = W-_FUZZ
+                        self.height = H-_FUZZ
+                        self._scale = s
+                        break
+
+        return self.width, self.height
+
+    def drawOn(self, canv, x, y, _sW=0):
+        scale = getattr(self,'_scale',1.0)
+        truncate = self.mode=='truncate'
+        ss = scale!=1.0 or truncate
+        if ss:
+            canv.saveState()
+            if truncate:
+                p = canv.beginPath()
+                p.rect(x, y, self.width,self.height)
+                canv.clipPath(p,stroke=0)
+            else:
+                canv.translate(x,y)
+                x=y=0
+                canv.scale(1.0/scale, 1.0/scale)
+        _Container.drawOn(self, canv, x, y, _sW=_sW, scale=scale)
+        if ss: canv.restoreState()
+
+class PlacedStory(Flowable):
+    _ZEROSIZE=1
+    _SPACETRANSFER = True
+    _anchors = ('nw','n','ne','w','c','e','sw','s','se')
+    def __init__(self, x, y, maxWidth, maxHeight, content=[], mergeSpace=1, mode='shrink',
+                        name='', anchor='sw', fakeWidth=None, hAlign='LEFT',vAlign='BOTTOM',
+                        showBoundary=None, origin='page'):
+        self.kif = KeepInFrame(maxWidth, maxHeight, content=content, mergeSpace=mergeSpace,
+                         mode=mode, name=name,hAlign=hAlign,vAlign=vAlign, fakeWidth=None)
+        self.x = x
+        self.y = y
+        self.anchor = anchor
+        self.w = None
+        self.h = None
+        self.sb = showBoundary
+        self.origin = origin
+
+    def wrap(self,_aW,_aH):
+        #_aW & _aH are ignored
+        if self.w is None:
+            self.kif.canv = getattr(self,'canv')
+            self.w, self.h = self.kif.wrap(self.kif.maxWidth,self.kif.maxHeight)
+            del self.kif.canv
+        return 0,0
+
+    def drawOn(self, canv, lx, ly, _sW=0):
+        #we ignore _x and _y infavour of our own
+        if self.w is None: self.wrap(0,0)
+        origin = self.origin
+        if origin=='page':
+            dx = dy = 0
+        elif origin=='local':
+            dx = lx
+            dy = ly
+        elif origin=='frame':
+            _ = getattr(self,'_frame',None)
+            if not _: _ = self._doctemplateAttr('frame')
+            dx = _.x1
+            dy = _.y1
+        else:
+            raise ValueError(f'PlacedStory invalid {origin=} not in "page", "frame" or "local"')
+
+        anchor = self.anchor
+        if anchor not in self._anchors:
+            raise ValueError(f'PlacedStory invalid {anchor=} not in {self._anchors}')
+        if anchor in ('nw','n','ne'):
+            dy -= self.h
+        elif anchor in ('w','c','e'):
+            dy -= self.h / 2
+        if anchor in ('n','c','s'):
+            dx -= self.w/2
+        elif anchor in ('ne','e','se'):
+            dx -= self.w
+        x = self.x + dx
+        y = self.y + dy
+
+        self.kif.drawOn(canv,x,y)
+        if self.sb: canv.drawBoundary(self.sb,x,y,self.w,self.h)
+
+class _FindSplitterMixin:
+    def _findSplit(self,canv,availWidth,availHeight,mergeSpace=1,obj=None,content=None,paraFix=True):
+        '''return max width, required height for a list of flowables F'''
+        W = 0
+        H = 0
+        pS = sB = 0
+        atTop = 1
+        if isinstance(self,ListFlowable):
+            F = self._getContent() if hasattr(self,'_flowables') else self._list_content
+        else:
+            F = self._getContent(content)
+        for i,f in enumerate(F):
+            if hasattr(f,'frameAction'):
+                from reportlab.platypus.doctemplate import Indenter
+                if isinstance(f,Indenter):
+                    availWidth -= f.left+f.right
+                continue
+            w,h = f.wrapOn(canv,availWidth,0xfffffff)
+            if w<=_FUZZ or h<=_FUZZ: continue
+            W = max(W,w)
+            if not atTop:
+                s = f.getSpaceBefore()
+                if mergeSpace: s = max(s-pS,0)
+                H += s
+            else:
+                if obj is not None: obj._spaceBefore = f.getSpaceBefore()
+                atTop = 0
+            if H>=availHeight or w>availWidth:
+                return W, availHeight, F[:i],F[i:]
+            H += h
+            if H>availHeight:
+                aH = availHeight-(H-h)
+                if paraFix:
+                    from reportlab.platypus.paragraph import Paragraph
+                    if isinstance(f,(Paragraph,Preformatted)):
+                        leading = f.style.leading
+                        nH = leading*int(aH/float(leading))+_FUZZ
+                        if nH_FUZZ:
+            W,H0,self._C0,self._C1 = self._findSplit(canv,iW,aH)
+        else:
+            W = availWidth
+            H0 = 0
+        if W>iW+_FUZZ:
+            self._C0 = []
+            self._C1 = self._content
+        aH = self._aH = max(aH,H0)
+        self.width = availWidth
+        if not self._C1:
+            self.height = aH
+        else:
+            W1,H1 = _listWrapOn(self._C1,availWidth,canv)
+            self.height = aH+H1
+        return self.width, self.height
+
+    def split(self,availWidth, availHeight):
+        if hasattr(self,'_wrapArgs'):
+            I = self._I
+            if self._wrapArgs!=(availWidth,availHeight) or getattr(I,'_oldDrawSize',None) is not None:
+                self._reset()
+                I._unRestrictSize()
+        W,H=self.wrap(availWidth,availHeight)
+        if self._aH>availHeight: return []
+        C1 = self._C1
+        if C1:
+            S = C1[0].split(availWidth,availHeight-self._aH)
+            if not S:
+                _C1 = []
+            else:
+                _C1 = [S[0]]
+                C1 = S[1:]+C1[1:]
+        else:
+            _C1 = []
+        return [ImageAndFlowables(
+                    self._I,
+                    self._C0+_C1,
+                    imageLeftPadding=self._ilpad,
+                    imageRightPadding=self._irpad,
+                    imageTopPadding=self._itpad,
+                    imageBottomPadding=self._ibpad,
+                    imageSide=self._side, imageHref=self.imageHref)
+                    ]+C1
+
+    def drawOn(self, canv, x, y, _sW=0):
+        if self._side=='left':
+            Ix = x + self._ilpad
+            Fx = Ix+ self._irpad + self._wI
+        else:
+            Ix = x + self.width-self._wI-self._irpad
+            Fx = x
+        self._I.drawOn(canv,Ix,y+self.height-self._itpad-self._hI)
+
+        if self.imageHref:
+            canv.linkURL(self.imageHref, (Ix, y+self.height-self._itpad-self._hI, Ix + self._wI, y+self.height), relative=1)
+
+        if self._C0:
+            _Container.drawOn(self, canv, Fx, y, content=self._C0, aW=self._iW)
+        if self._C1:
+            aW, aH = self._wrapArgs
+            _Container.drawOn(self, canv, x, y-self._aH,content=self._C1, aW=aW)
+
+class _AbsRect(NullDraw):
+    _ZEROSIZE=1
+    _SPACETRANSFER = True
+    def __init__(self,x,y,width,height,strokeWidth=0,strokeColor=None,fillColor=None,strokeDashArray=None):
+        self._x = x
+        self._y = y
+        self._width = width
+        self._height = height
+        self._strokeColor = strokeColor
+        self._fillColor = fillColor
+        self._strokeWidth = strokeWidth
+        self._strokeDashArray = strokeDashArray
+
+    def wrap(self, availWidth, availHeight):
+        return 0,0
+
+    def drawOn(self, canv, x, y, _sW=0):
+        if self._width>_FUZZ and self._height>_FUZZ:
+            st = self._strokeColor and self._strokeWidth is not None and self._strokeWidth>=0
+            if st or self._fillColor:
+                canv.saveState()
+                if st:
+                    canv.setStrokeColor(self._strokeColor)
+                    canv.setLineWidth(self._strokeWidth)
+                if self._fillColor:
+                    canv.setFillColor(self._fillColor)
+                canv.rect(self._x,self._y,self._width,self._height,stroke=1 if st else 0, fill=1 if self._fillColor else 0)
+                canv.restoreState()
+
+class _ExtendBG(NullDraw):
+    _ZEROSIZE=1
+    _SPACETRANSFER = True
+    def __init__(self,y,height,bg,frame):
+        self._y = y
+        self._height = height
+        self._bg = bg
+
+    def wrap(self, availWidth, availHeight):
+        return 0,0
+
+    def frameAction(self, frame):
+        bg = self._bg
+        fby = self._y
+        fbh = self._height
+        fbgl = bg.left
+        fbw = frame._width - fbgl - bg.right
+        fbx = frame._x1 - fbgl
+        canv = self.canv
+        pn = canv.getPageNumber()
+        bg.render(canv,frame,fbx,fby,fbw,fbh)
+
+class _AbsLine(NullDraw):
+    _ZEROSIZE=1
+    _SPACETRANSFER = True
+    def __init__(self,x,y,x1,y1,strokeWidth=0,strokeColor=None,strokeDashArray=None):
+        self._x = x
+        self._y = y
+        self._x1 = x1
+        self._y1 = y1
+        self._strokeColor = strokeColor
+        self._strokeWidth = strokeWidth
+        self._strokeDashArray = strokeDashArray
+
+    def wrap(self, availWidth, availHeight):
+        return 0,0
+
+    def drawOn(self, canv, x, y, _sW=0):
+        if self._strokeColor and self._strokeWidth is not None and self._strokeWidth>=0:
+            canv.saveState()
+            canv.setStrokeColor(self._strokeColor)
+            canv.setLineWidth(self._strokeWidth)
+            canv.line(self._x,self._y,self._x1,self._y1)
+            canv.restoreState()
+
+class BalancedColumns(_FindSplitterMixin,NullDraw):
+    '''combine a list of flowables and an Image'''
+    def __init__(self, F, nCols=2, needed=72, spaceBefore=0, spaceAfter=0, showBoundary=None,
+            leftPadding=None, innerPadding=None, rightPadding=None, topPadding=None, bottomPadding=None,
+            name='', endSlack=0.1,
+            boxStrokeColor=None,
+            boxStrokeWidth=0,
+            boxFillColor=None,
+            boxMargin=None,
+            vLinesStrokeColor=None,
+            vLinesStrokeWidth=None,
+            ):
+        self.name = name or 'BalancedColumns-%d' % id(self)
+        if nCols <2:
+            raise ValueError('nCols should be at least 2 not %r in %s' % (nCols,self.identitity()))
+        self._content = _flowableSublist(F)
+        self._nCols = nCols
+        self.spaceAfter = spaceAfter
+        self._leftPadding = leftPadding
+        self._innerPadding = innerPadding
+        self._rightPadding = rightPadding
+        self._topPadding = topPadding
+        self._bottomPadding = bottomPadding
+        self.spaceBefore = spaceBefore
+        self._needed = needed - _FUZZ
+        self.showBoundary = showBoundary
+        self.endSlack = endSlack    #what we might allow as a lastcolumn overrun
+        self._boxStrokeColor = boxStrokeColor
+        self._boxStrokeWidth = boxStrokeWidth
+        self._boxFillColor = boxFillColor
+        self._boxMargin = boxMargin
+        self._vLinesStrokeColor = vLinesStrokeColor
+        self._vLinesStrokeWidth = vLinesStrokeWidth
+
+    def identity(self, maxLen=None):
+        return "<%s nCols=%r at %s%s%s>" % (self.__class__.__name__, self._nCols, hex(id(self)), self._frameName(),
+                getattr(self,'name','') and (' name="%s"'% getattr(self,'name','')) or '',
+                )
+
+    def getSpaceAfter(self):
+        return self.spaceAfter
+
+    def getSpaceBefore(self):
+        return self.spaceBefore
+
+    def _generated_content(self,aW,aH):
+        G = []
+        frame = self._frame
+        from reportlab.platypus.doctemplate import LayoutError, ActionFlowable, Indenter
+        from reportlab.platypus.frames import Frame
+        from reportlab.platypus.doctemplate import FrameBreak
+        lpad = frame._leftPadding if self._leftPadding is None else self._leftPadding
+        rpad = frame._rightPadding if self._rightPadding is None else self._rightPadding
+        tpad = frame._topPadding if self._topPadding is None else self._topPadding
+        bpad = frame._bottomPadding if self._bottomPadding is None else self._bottomPadding
+        leftExtraIndent = frame._leftExtraIndent
+        rightExtraIndent = frame._rightExtraIndent
+        gap = max(lpad,rpad) if self._innerPadding is None else self._innerPadding
+        hgap = gap*0.5
+        canv = self.canv
+        nCols = self._nCols
+        cw = (aW - gap*(nCols-1) - lpad - rpad)/float(nCols)
+        aH0 = aH
+        aH -= tpad + bpad
+        W,H0,_C0,C2 = self._findSplit(canv,cw,nCols*aH,paraFix=False)
+        if not _C0:
+            raise ValueError(
+                    "%s cannot make initial split aW=%r aH=%r ie cw=%r ah=%r\ncontent=%s" % (
+                        self.identity(),aW,aH,cw,nCols*aH,
+                        [f.__class__.__name__ for f in self._content],
+                        ))
+        _fres = {}
+        def splitFunc(ah,endSlack=0):
+            if ah not in _fres:
+                c = []
+                w = 0
+                h = 0
+                cn = None
+                icheck = nCols-2 if endSlack else -1
+                for i in range(nCols):
+                    wi, hi, c0, c1 = self._findSplit(canv,cw,ah,content=cn,paraFix=False)
+                    w = max(w,wi)
+                    h = max(h,hi)
+                    c.append(c0)
+                    if i==icheck:
+                        wc, hc, cc0, cc1 = self._findSplit(canv,cw,2*ah,content=c1,paraFix=False)
+                        if hc<=(1+endSlack)*ah:
+                            c.append(c1)
+                            h = ah-1e-6
+                            cn = []
+                            break
+                    cn = c1
+                _fres[ah] = ah+100000*int(cn!=[]),cn==[],(w,h,c,cn)
+            return _fres[ah][2]
+
+        endSlack = 0
+        if C2:
+            H = aH
+        else:
+            #we are short so use H0 to figure out what to use
+            import math
+
+            def func(ah):
+                splitFunc(ah)
+                return _fres[ah][0]
+
+            def gss(f, a, b, tol=1, gr=(math.sqrt(5) + 1) / 2):
+                c = b - (b - a) / gr
+                d = a + (b - a) / gr
+                while abs(a - b) > tol:
+                    if f(c) < f(d):
+                        b = d
+                    else:
+                        a = c
+
+                    # we recompute both c and d here to avoid loss of precision which may lead to incorrect results or infinite loop
+                    c = b - (b - a) / gr
+                    d = a + (b - a) / gr
+
+                F = [(x,tf,v) for x,tf,v in _fres.values() if tf]
+                if F:
+                    F.sort()
+                    return F[0][2]
+                return None
+
+            H = min(int(H0/float(nCols)+self.spaceAfter*0.4),aH)
+            splitFunc(H)
+            if not _fres[H][1]:
+                H = gss(func,H,aH)
+                if H:
+                    W, H0, _C0, C2 = H
+                    H = H0
+                    endSlack = False
+                else:
+                    H = aH
+                    endSlack = self.endSlack
+            else:
+                H1 = H0/float(nCols)
+                splitFunc(H1)
+                if not _fres[H1][1]:
+                    H = gss(func,H,aH)
+                    if H:
+                        W, H0, _C0, C2 = H
+                        H = H0
+                        endSlack = False
+                    else:
+                        H = aH
+                        endSlack = self.endSlack
+            assert not C2, "unexpected non-empty C2"
+        W1, H1, C, C1 = splitFunc(H, endSlack)
+        _fres.clear()
+        if C[0]==[] and C[1]==[] and C1:
+            #no split situation
+            C, C1 = [C1,C[1]], C[0]
+
+        x1 = frame._x1
+        y1 = frame._y1
+        fw = frame._width
+        ftop = y1+bpad+tpad+aH
+        fh = H1 + bpad + tpad
+        y2 = ftop - fh
+        dx = aW / float(nCols)
+        if leftExtraIndent or rightExtraIndent:
+            indenter0 = Indenter(-leftExtraIndent,-rightExtraIndent)
+            indenter1 = Indenter(leftExtraIndent,rightExtraIndent)
+        else:
+            indenter0 = indenter1 = None
+
+        showBoundary=self.showBoundary if self.showBoundary is not None else frame.showBoundary
+        obx = x1+leftExtraIndent+frame._leftPadding
+        F = [Frame(obx+i*dx,y2,dx,fh,
+                leftPadding=lpad if not i else hgap, bottomPadding=bpad,
+                rightPadding=rpad if i==nCols-1 else hgap, topPadding=tpad,
+                id='%s-%d' %(self.name,i),
+                showBoundary=showBoundary,
+                overlapAttachedSpace=frame._oASpace,
+                _debug=frame._debug) for i in range(nCols)]
+
+        #we are going to modify the current template
+        T=self._doctemplateAttr('pageTemplate')
+        if T is None:
+            raise LayoutError('%s used in non-doctemplate environment' % self.identity())
+
+        BGs = getattr(frame,'_frameBGs',None)
+        xbg = bg = BGs[-1] if BGs else None
+
+        class TAction(ActionFlowable):
+            '''a special Action flowable that sets stuff on the doc template T'''
+            def __init__(self, bgs=[],F=[],f=None):
+                Flowable.__init__(self)
+                self.bgs = bgs
+                self.F = F
+                self.f = f
+
+            def apply(self,doc,T=T):
+                T.frames = self.F
+                frame._frameBGs = self.bgs
+                doc.handle_currentFrame(self.f.id)
+                frame._frameBGs = self.bgs
+
+        if bg:
+            #G.append(Spacer(1e-5,1e-5))
+            #G[-1].__id__ = 'spacer0'
+            xbg = _ExtendBG(y2,fh,bg,frame)
+            G.append(xbg)
+
+        oldFrames = T.frames
+        G.append(TAction([],F,F[0]))
+        if indenter0: G.append(indenter0)
+        doBox = (self._boxStrokeColor and self._boxStrokeWidth and self._boxStrokeWidth>=0) or self._boxFillColor
+        doVLines = self._vLinesStrokeColor and self._vLinesStrokeWidth and self._vLinesStrokeWidth>=0
+        if doBox or doVLines:
+            obm = self._boxMargin
+            if not obm: obm = (0,0,0,0)
+            if len(obm)==1:
+                obmt = obml = obmr = obmb = obm[0]
+            elif len(obm)==2:
+                obmt = obmb = obm[0]
+                obml = obmr = obm[1]
+            elif len(obm)==3:
+                obmt = obm[0]
+                obml = obmr = obm[1]
+                obmb = obm[2]
+            elif len(obm)==4:
+                obmt = obm[0]
+                obmr = obm[1]
+                obmb = obm[2]
+                obml = obm[3]
+            else:
+                raise ValueError('Invalid value %s for boxMargin' % repr(obm))
+            obx1 = obx - obml
+            obx2 = F[-1]._x1+F[-1]._width + obmr
+            oby2 = y2-obmb
+            obh = fh+obmt+obmb
+            oby1 = oby2+obh
+            if doBox:
+                box = _AbsRect(obx1,oby2, obx2-obx1, obh,
+                        fillColor=self._boxFillColor,
+                        strokeColor=self._boxStrokeColor,
+                        strokeWidth=self._boxStrokeWidth,
+                        )
+            if doVLines:
+                vLines = []
+                for i in range(1,nCols):
+                    vlx = 0.5*(F[i]._x1 + F[i-1]._x1+F[i-1]._width)
+                    vLines.append(_AbsLine(vlx,oby2,vlx,oby1,strokeWidth=self._vLinesStrokeWidth,strokeColor=self._vLinesStrokeColor))
+        else:
+            oby1 = ftop
+            oby2 = y2
+
+        if doBox: G.append(box)
+        if doVLines: G.extend(vLines)
+        sa = self.getSpaceAfter()
+        for i in range(nCols):
+            Ci = C[i]
+            if Ci:
+                Ci = KeepInFrame(W1,H1,Ci,mode='shrink')
+                sa = max(sa,Ci.getSpaceAfter())
+                G.append(Ci)
+            if i!=nCols-1:
+                G.append(FrameBreak)
+        G.append(TAction(BGs,oldFrames,frame))
+        if xbg:
+            if C1: sa = 0
+            xbg._y = min(y2,oby2) - sa
+            xbg._height = max(ftop,oby1) - xbg._y
+        if indenter1: G.append(indenter1)
+        if C1:
+            G.append(
+                BalancedColumns(C1, nCols=nCols,
+                    needed=self._needed, spaceBefore=self.spaceBefore, spaceAfter=self.spaceAfter,
+                    showBoundary=self.showBoundary,
+                    leftPadding=self._leftPadding,
+                    innerPadding=self._innerPadding,
+                    rightPadding=self._rightPadding,
+                    topPadding=self._topPadding,
+                    bottomPadding=self._bottomPadding,
+                    name=self.name+'-1', endSlack=self.endSlack,
+                    boxStrokeColor=self._boxStrokeColor,
+                    boxStrokeWidth=self._boxStrokeWidth,
+                    boxFillColor=self._boxFillColor,
+                    boxMargin=self._boxMargin,
+                    vLinesStrokeColor=self._vLinesStrokeColor,
+                    vLinesStrokeWidth=self._vLinesStrokeWidth,
+                    )
+                )
+        return fh, G
+
+    def wrap(self,aW,aH):
+        #here's where we mess with everything
+        self_frame = getattr(self,'_frame',None)
+        if aH_FUZZ and abs(fbh)>_FUZZ:
+            pn = canv.getPageNumber()
+            if self.fid==id(frame) and self.cid==id(canv) and self.pn==pn:
+                ox,oy,ow,oh = self.getDims(canv)
+                self.setDims(canv,ox,fby,ow,oh+oy-fby)
+            else:
+                canv.saveState()
+                fbgc = self.fillColor
+                if fbgc:
+                    canv.setFillColor(fbgc)
+                sw = self.strokeWidth
+                sc = None if sw is None or sw<0 else self.strokeColor
+                if sc:
+                    canv.setStrokeColor(sc)
+                    canv.setLineWidth(sw)
+                    da = self.strokeDashArray
+                    if da:
+                        canv.setDash(da)
+                self.fid = id(frame)
+                self.cid = id(canv)
+                self.pn = pn
+                self.codePos = len(canv._code)
+                canv.rect(fbx,fby,fbw,fbh,stroke=1 if sc else 0,fill=1 if fbgc else 0)
+                canv.restoreState()
+
+class FrameBG(AnchorFlowable):
+    """Start or stop coloring the frame background
+    left & right are distances from the edge of the frame to start stop colouring.
+    if start in ('frame','frame-permanent') then the background is filled from here to the bottom of the frame and immediately discarded
+    for the frame case.
+    """
+    _ZEROSIZE=1
+    def __init__(self, color=None, left=0, right=0, start=True, strokeWidth=None, strokeColor=None, strokeDashArray=None):
+        Spacer.__init__(self,0,0)
+        self.start = start
+        if start:
+            from reportlab.platypus.doctemplate import _evalMeasurement
+            self.left = _evalMeasurement(left)
+            self.right = _evalMeasurement(right)
+            self.color = color
+            self.strokeWidth = strokeWidth
+            self.strokeColor = strokeColor
+            self.strokeDashArray = strokeDashArray
+
+    def __repr__(self):
+        return "%s(%s)" % (self.__class__.__name__,', '.join(['%s=%r' % (i,getattr(self,i,None)) for i in 'start color left right'.split()]))
+
+    def draw(self):
+        frame = getattr(self,'_frame',None)
+        if frame is None: return
+        if self.start:
+            sc = self.strokeColor
+            sw = self.strokeWidth
+            sw = -1 if sw is None else sw
+            frame._frameBGs.append(
+                        _FBGBag(left=self.left,
+                                right=self.right,
+                                fillColor=self.color,
+                                start=self.start if self.start in ('frame','frame-permanent') else None,
+                                strokeColor=self.strokeColor,
+                                strokeWidth=self.strokeWidth,
+                                strokeDashArray=self.strokeDashArray,
+                                fid = 0,
+                                cid = 0,
+                                pn = -1,
+                                codePos = None,
+                                active=True,
+                                ))
+        elif frame._frameBGs:
+            frame._frameBGs.pop()
+
+class FrameSplitter(NullDraw):
+    '''When encountered this flowable should either switch directly to nextTemplate
+    if remaining space in the current frame is less than gap+required or it should
+    temporarily modify the current template to have the frames from nextTemplate
+    that are listed in nextFrames and switch to the first of those frames.
+    '''
+    _ZEROSIZE=1
+    def __init__(self, nextTemplate, nextFrames=[], gap=10, required=72, adjustHeight=True):
+        self.nextTemplate = nextTemplate
+        self.nextFrames = nextFrames or []
+        self.gap = gap
+        self.required = required
+        self.adjustHeight = adjustHeight
+
+    def wrap(self,aW,aH):
+        frame = self._frame
+        from reportlab.platypus.doctemplate import NextPageTemplate,CurrentFrameFlowable,LayoutError
+        G=[NextPageTemplate(self.nextTemplate)]
+        if aH1 and hasattr(f,'blPara'):
+            cnl = len(f.blPara.lines)
+            nnl = len(S[0].blPara.lines)
+            #avoid 1/2 line widow when justified else avoid 1 line widow
+            if ((getattr(getattr(f,'style',None),'alignment',None)==4 and nnl>=(cnl-2)) 
+                    or nnl==(cnl-1)):
+                S = []
+        return [
+                LIIndenter(s,
+                        leftIndent=self._leftIndent,
+                        rightIndent=self._rightIndent,
+                        bullet = (s is S[0] and self._bullet or None),
+                        ) for s in S
+                ] if S else []
+
+    def drawOn(self, canv, x, y, _sW=0):
+        if self._bullet:
+            self._bullet.drawOn(self,canv,x,y,0)
+        self._flowable.drawOn(canv,x+self._leftIndent,y,max(0,_sW-self._leftIndent-self._rightIndent))
+
+from reportlab.lib.styles import ListStyle
+class ListItem:
+    def __init__(self,
+                    flowables,  #the initial flowables
+                    style=None,
+                    #leftIndent=18,
+                    #rightIndent=0,
+                    #spaceBefore=None,
+                    #spaceAfter=None,
+                    #bulletType='1',
+                    #bulletColor='black',
+                    #bulletFontName='Helvetica',
+                    #bulletFontSize=12,
+                    #bulletOffsetY=0,
+                    #bulletDedent='auto',
+                    #bulletDir='ltr',
+                    #bulletFormat=None,
+                    **kwds
+                    ):
+        if not isinstance(flowables,(list,tuple)):
+            flowables = (flowables,)
+        self._flowables = flowables
+        params = self._params = {}
+
+        if style:
+            if not isinstance(style,ListStyle):
+                raise ValueError('%s style argument (%r) not a ListStyle' % (self.__class__.__name__,style))
+            self._style = style
+
+        for k in ListStyle.defaults:
+            if k in kwds:
+                v = kwds.get(k)
+            elif style:
+                v = getattr(style,k)
+            else:
+                continue
+            params[k] = v
+
+        for k in ('value', 'spaceBefore','spaceAfter'):
+            v = kwds.get(k,getattr(style,k,None))
+            if v is not None:
+                params[k] = v
+
+class _LIParams:
+    def __init__(self,flowable,params,value,first):
+        self.flowable = flowable
+        self.params = params
+        self.value = value
+        self.first= first
+
+class ListFlowable(_Container,Flowable,_FindSplitterMixin):
+    _numberStyles = '1aAiI'
+    def __init__(self,
+                    flowables,  #the initial flowables
+                    start=None,
+                    style=None,
+                    #leftIndent=18,
+                    #rightIndent=0,
+                    #spaceBefore=None,
+                    #spaceAfter=None,
+                    #bulletType='1',
+                    #bulletColor='black',
+                    #bulletFontName='Helvetica',
+                    #bulletFontSize=12,
+                    #bulletOffsetY=0,
+                    #bulletDedent='auto',
+                    #bulletDir='ltr',
+                    #bulletFormat=None,
+                    **kwds
+                    ):
+        self._flowables = flowables
+
+        if style:
+            if not isinstance(style,ListStyle):
+                raise ValueError('%s style argument not a ListStyle' % self.__class__.__name__)
+            self.style = style
+
+        for k,v in ListStyle.defaults.items():
+            setattr(self,'_'+k,kwds.get(k,getattr(style,k,v)))
+
+        for k in ('spaceBefore','spaceAfter'):
+            v = kwds.get(k,getattr(style,k,None))
+            if v is not None:
+                setattr(self,k,v)
+
+        auto = False
+        if start is None:
+            start = getattr(self,'_start',None)
+            if start is None:
+                if self._bulletType=='bullet':
+                    start = 'bulletchar'
+                    auto = True
+                else:
+                    start = self._bulletType
+                    auto = True
+        if self._bulletType!='bullet':
+            if auto:
+                for v in start:
+                    if v not in self._numberStyles:
+                        raise ValueError('invalid start=%r or bullettype=%r' % (start,self._bulletType))
+            else:
+                for v in self._bulletType:
+                    if v not in self._numberStyles:
+                        raise ValueError('invalid bullettype=%r' % self._bulletType)
+        self._start = start
+        self._auto = auto or isinstance(start,(list,tuple))
+
+        self._list_content = None
+        self._dims = None
+        self._caption = kwds.pop('caption',None)
+
+    @property
+    def _content(self):
+        if self._list_content is None:
+            self._list_content = self._getContent()
+            del self._flowables
+        return self._list_content
+
+    def wrap(self,aW,aH):
+        if self._dims!=aW:
+            self.width, self.height = _listWrapOn(self._content,aW,self.canv)
+            self._dims = aW
+        return self.width,self.height
+
+    def split(self,aW,aH):
+        return self._content
+
+    def _flowablesIter(self):
+        for f in self._flowables:
+            if isinstance(f,(list,tuple)):
+                if f:
+                    for i, z in enumerate(f):
+                        yield i==0 and not isinstance(z,LIIndenter), z
+            elif isinstance(f,ListItem):
+                params = f._params
+                if not params:
+                    #meerkat simples just a list like object
+                    for i, z in enumerate(f._flowables):
+                        if isinstance(z,LIIndenter):
+                            raise ValueError('LIIndenter not allowed in ListItem')
+                        yield i==0, z
+                else:
+                    params = params.copy()
+                    value = params.pop('value',None)
+                    spaceBefore = params.pop('spaceBefore',None)
+                    spaceAfter = params.pop('spaceAfter',None)
+                    n = len(f._flowables) - 1
+                    for i, z in enumerate(f._flowables):
+                        P = params.copy()
+                        if not i and spaceBefore is not None:
+                            P['spaceBefore'] = spaceBefore
+                        if i==n and spaceAfter is not None:
+                            P['spaceAfter'] = spaceAfter
+                        if i: value=None
+                        yield 0, _LIParams(z,P,value,i==0)
+            else:
+                yield not isinstance(f,LIIndenter), f
+
+    def _makeLIIndenter(self,flowable, bullet, params=None):
+        if params:
+            leftIndent = params.get('leftIndent',self._leftIndent)
+            rightIndent = params.get('rightIndent',self._rightIndent)
+            spaceBefore = params.get('spaceBefore',None)
+            spaceAfter = params.get('spaceAfter',None)
+            return LIIndenter(flowable,leftIndent,rightIndent,bullet,spaceBefore=spaceBefore,spaceAfter=spaceAfter)
+        else:
+            return LIIndenter(flowable,self._leftIndent,self._rightIndent,bullet)
+
+    def _makeBullet(self,value,params=None):
+        if params is None:
+            def getp(a):
+                return getattr(self,'_'+a)
+        else:
+            style = getattr(params,'style',None)
+            def getp(a):
+                if a in params: return params[a]
+                if style and a in style.__dict__: return getattr(self,a)
+                return getattr(self,'_'+a)
+
+        return BulletDrawer(
+                    value=value,
+                    bulletAlign=getp('bulletAlign'),
+                    bulletType=getp('bulletType'),
+                    bulletColor=getp('bulletColor'),
+                    bulletFontName=getp('bulletFontName'),
+                    bulletFontSize=getp('bulletFontSize'),
+                    bulletOffsetY=getp('bulletOffsetY'),
+                    bulletDedent=getp('calcBulletDedent'),
+                    bulletDir=getp('bulletDir'),
+                    bulletFormat=getp('bulletFormat'),
+                    )
+
+    def _getContent(self):
+        bt = self._bulletType
+        value = self._start
+        if isinstance(value,(list,tuple)):
+            values = value
+            value = values[0]
+        else:
+            values = [value]
+        autov = values[0]
+        inc = int(bt in '1aAiI')
+        if inc:
+            try:
+                value = int(value)
+            except:
+                value = 1
+
+        bd = self._bulletDedent
+        if bd=='auto':
+            align = self._bulletAlign
+            dir = self._bulletDir
+            if dir=='ltr' and align=='left':
+                bd = self._leftIndent
+            elif align=='right':
+                bd = self._rightIndent
+            else:
+                #we need to work out the maximum width of any of the labels
+                tvalue = value
+                maxW = 0
+                for d,f in self._flowablesIter():
+                    if d:
+                        maxW = max(maxW,_computeBulletWidth(self,tvalue))
+                        if inc: tvalue += inc
+                    elif isinstance(f,LIIndenter):
+                        b = f._bullet
+                        if b:
+                            if b.bulletType==bt:
+                                maxW = max(maxW,_computeBulletWidth(b,b.value))
+                                tvalue = int(b.value)
+                        else:
+                            maxW = max(maxW,_computeBulletWidth(self,tvalue))
+                        if inc: tvalue += inc
+                if dir=='ltr':
+                    if align=='right':
+                        bd = self._leftIndent - maxW
+                    else:
+                        bd = self._leftIndent - maxW*0.5
+                elif align=='left':
+                    bd = self._rightIndent - maxW
+                else:
+                    bd = self._rightIndent - maxW*0.5
+
+        self._calcBulletDedent = bd
+
+        S = []
+        aS = S.append
+        i=0
+        for d,f in self._flowablesIter():
+            if isinstance(f,ListFlowable):
+                fstart = f._start
+                if isinstance(fstart,(list,tuple)):
+                    fstart = fstart[0]
+                if fstart in values:
+                    #my kind of ListFlowable
+                    if f._auto:
+                        autov = values.index(autov)+1
+                        f._start = values[autov:]+values[:autov]
+                        autov = f._start[0]
+                        if inc: f._bulletType = autov
+                    else:
+                        autov = fstart
+            fparams = {}
+            if not i:
+                i += 1
+                spaceBefore = getattr(self,'spaceBefore',None)
+                if spaceBefore is not None:
+                    fparams['spaceBefore'] = spaceBefore
+            if d:
+                aS(self._makeLIIndenter(f,bullet=self._makeBullet(value),params=fparams))
+                if inc: value += inc
+            elif isinstance(f,LIIndenter):
+                b = f._bullet
+                if b:
+                    if b.bulletType!=bt:
+                        raise ValueError('Included LIIndenter bulletType=%s != OrderedList bulletType=%s' % (b.bulletType,bt))
+                    value = int(b.value)
+                else:
+                    f._bullet = self._makeBullet(value,params=getattr(f,'params',None))
+                if fparams:
+                    f.__dict__['spaceBefore'] = max(f.__dict__.get('spaceBefore',0),spaceBefore)
+                aS(f)
+                if inc: value += inc
+            elif isinstance(f,_LIParams):
+                fparams.update(f.params)
+                z = self._makeLIIndenter(f.flowable,bullet=None,params=fparams)
+                if f.first:
+                    if f.value is not None:
+                        value = f.value
+                        if inc: value = int(value)
+                    z._bullet = self._makeBullet(value,f.params)
+                    if inc: value += inc
+                aS(z)
+            else:
+                aS(self._makeLIIndenter(f,bullet=None,params=fparams))
+
+        spaceAfter = getattr(self,'spaceAfter',None)
+        if spaceAfter is not None:
+            f=S[-1]
+            f.__dict__['spaceAfter'] = max(f.__dict__.get('spaceAfter',0),spaceAfter)
+
+        if self._caption: S.insert(0,self._caption)
+
+        return S
+
+class TopPadder(Flowable):
+    '''wrap a single flowable so that its first bit will be
+    padded to fill out the space so that it appears at the
+    bottom of its frame'''
+    def __init__(self,f):
+        self.__dict__['_TopPadder__f'] = f
+
+    def wrap(self,aW,aH):
+        w,h = self.__f.wrap(aW,aH)
+        self.__dict__['_TopPadder__dh'] = aH-h
+        return w,h
+
+    def split(self,aW,aH):
+        S = self.__f.split(aW,aH)
+        if len(S)>1:
+            S[0] = TopPadder(S[0])
+        return S
+
+    def drawOn(self, canvas, x, y, _sW=0):
+        self.__f.drawOn(canvas,x,y-max(0,self.__dh-1e-8),_sW)
+
+    def __setattr__(self,a,v):
+        setattr(self.__f,a,v)
+
+    def __getattr__(self,a):
+        return getattr(self.__f,a)
+
+    def __delattr__(self,a):
+        delattr(self.__f,a)
+
+class DocAssign(NullDraw):
+    '''At wrap time this flowable evaluates var=expr in the doctemplate namespace'''
+    _ZEROSIZE=1
+    def __init__(self,var,expr,life='forever'):
+        Flowable.__init__(self)
+        self.args = var,expr,life
+
+    def funcWrap(self,aW,aH):
+        NS=self._doctemplateAttr('_nameSpace')
+        NS.update(dict(availableWidth=aW,availableHeight=aH))
+        try:
+            return self.func()
+        finally:
+            for k in 'availableWidth','availableHeight':
+                try:
+                    del NS[k]
+                except:
+                    pass
+
+    def func(self):
+        return self._doctemplateAttr('d'+self.__class__.__name__[1:])(*self.args)
+
+    def wrap(self,aW,aH):
+        self.funcWrap(aW,aH)
+        return 0,0
+
+class DocExec(DocAssign):
+    '''at wrap time exec stmt in doc._nameSpace'''
+    def __init__(self,stmt,lifetime='forever'):
+        Flowable.__init__(self)
+        self.args=stmt,lifetime
+
+class DocPara(DocAssign):
+    '''at wrap time create a paragraph with the value of expr as text
+    if format is specified it should use %(__expr__)s for string interpolation
+    of the expression expr (if any). It may also use %(name)s interpolations
+    for other variables in the namespace.
+    suitable defaults will be used if style and klass are None
+    '''
+    def __init__(self,expr,format=None,style=None,klass=None,escape=True):
+        Flowable.__init__(self)
+        self.expr=expr
+        self.format=format
+        self.style=style
+        self.klass=klass
+        self.escape=escape
+
+    def func(self):
+        expr = self.expr
+        if expr:
+            if not isinstance(expr,str): expr = str(expr)
+            return self._doctemplateAttr('docEval')(expr)
+
+    def add_content(self,*args):
+        self._doctemplateAttr('frame').add_generated_content(*args)
+
+    def get_value(self,aW,aH):
+        value = self.funcWrap(aW,aH)
+        if self.format:
+            NS=self._doctemplateAttr('_nameSpace').copy()
+            NS.update(dict(availableWidth=aW,availableHeight=aH))
+            NS['__expr__'] = value
+            value = self.format % NS
+        else:
+            value = str(value)
+        return value
+
+    def wrap(self,aW,aH):
+        value = self.get_value(aW,aH)
+        P = self.klass
+        if not P:
+            from reportlab.platypus.paragraph import Paragraph as P
+        style = self.style
+        if not style:
+            from reportlab.lib.styles import getSampleStyleSheet
+            style=getSampleStyleSheet()['Code']
+        if self.escape:
+            from xml.sax.saxutils import escape
+            value=escape(value)
+        self.add_content(P(value,style=style))
+        return 0,0
+
+class DocAssert(DocPara):
+    def __init__(self,cond,format=None):
+        Flowable.__init__(self)
+        self.expr=cond
+        self.format=format
+
+    def funcWrap(self,aW,aH):
+        self._cond = DocPara.funcWrap(self,aW,aH)
+        return self._cond
+
+    def wrap(self,aW,aH):
+        value = self.get_value(aW,aH)
+        if not bool(self._cond):
+            raise AssertionError(value)
+        return 0,0
+
+class DocIf(DocPara):
+    def __init__(self,cond,thenBlock,elseBlock=[]):
+        Flowable.__init__(self)
+        self.expr = cond
+        self.blocks = elseBlock or [],thenBlock
+
+    def checkBlock(self,block):
+        if not isinstance(block,(list,tuple)):
+            block = (block,)
+        return block
+
+    def wrap(self,aW,aH):
+        self.add_content(*self.checkBlock(self.blocks[int(bool(self.funcWrap(aW,aH)))]))
+        return 0,0
+
+class DocWhile(DocIf):
+    def __init__(self,cond,whileBlock):
+        Flowable.__init__(self)
+        self.expr = cond
+        self.block = self.checkBlock(whileBlock)
+
+    def wrap(self,aW,aH):
+        if bool(self.funcWrap(aW,aH)):
+            self.add_content(*(list(self.block)+[self]))
+        return 0,0
+
+class SetTopFlowables(NullDraw):
+    _ZEROZSIZE = 1
+    def __init__(self,F,show=False):
+        self._F = F
+        self._show = show
+
+    def wrap(self,aW,aH):
+        doc = getattr(getattr(self,'canv',None),'_doctemplate',None)
+        if doc:
+            doc._topFlowables = self._F
+            if self._show and self._F:
+                doc.frame._generated_content = self._F
+        return 0,0
+
+class SetPageTopFlowables(NullDraw):
+    _ZEROZSIZE = 1
+    def __init__(self,F,show=False):
+        self._F = F
+        self._show = show
+
+    def wrap(self,aW,aH):
+        doc = getattr(getattr(self,'canv',None),'_doctemplate',None)
+        if doc:
+            doc._pageTopFlowables = self._F
+            if self._show and self._F:
+                doc.frame._generated_content = self._F
+        return 0,0
diff --git a/.venv/lib/python3.13/site-packages/reportlab/platypus/frames.py b/.venv/lib/python3.13/site-packages/reportlab/platypus/frames.py
new file mode 100644
index 0000000000000000000000000000000000000000..f74c0e325add901cb6b4bee26f2c95dc54613d55
--- /dev/null
+++ b/.venv/lib/python3.13/site-packages/reportlab/platypus/frames.py
@@ -0,0 +1,268 @@
+#Copyright ReportLab Europe Ltd. 2000-2017
+#see license.txt for license details
+#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/platypus/frames.py
+
+__version__='3.5.14'
+
+__doc__="""A frame is a container for content on a page.
+"""
+
+__all__ = (
+            'Frame',
+            )
+
+import logging
+logger = logging.getLogger('reportlab.platypus')
+
+_geomAttr=('x1', 'y1', 'width', 'height', 'leftPadding', 'bottomPadding', 'rightPadding', 'topPadding')
+from reportlab import rl_config
+_FUZZ=rl_config._FUZZ
+
+class Frame:
+    '''
+    A Frame is a piece of space in a document that is filled by the
+    "flowables" in the story.  For example in a book like document most
+    pages have the text paragraphs in one or two frames.  For generality
+    a page might have several frames (for example for 3 column text or
+    for text that wraps around a graphic).
+
+    After creation a Frame is not usually manipulated directly by the
+    applications program -- it is used internally by the platypus modules.
+
+    Here is a diagramatid abstraction for the definitional part of a Frame::
+
+                width                    x2,y2
+        +---------------------------------+
+        | l  top padding                r | h
+        | e +-------------------------+ i | e
+        | f |                         | g | i
+        | t |                         | h | g
+        |   |                         | t | h
+        | p |                         |   | t
+        | a |                         | p |
+        | d |                         | a |
+        |   |                         | d |
+        |   +-------------------------+   |
+        |    bottom padding               |
+        +---------------------------------+
+        (x1,y1) <-- lower left corner
+
+    NOTE!! Frames are stateful objects.  No single frame should be used in
+    two documents at the same time (especially in the presence of multithreading.
+    '''
+    def __init__(self, x1, y1, width,height, leftPadding=6, bottomPadding=6,
+            rightPadding=6, topPadding=6, id=None, showBoundary=0,
+            overlapAttachedSpace=None,_debug=None):
+        self.id = id
+        self._debug = _debug
+
+        #these say where it goes on the page
+        self.__dict__['_x1'] = x1
+        self.__dict__['_y1'] = y1
+        self.__dict__['_width'] = width
+        self.__dict__['_height'] = height
+
+        #these create some padding.
+        self.__dict__['_leftPadding'] = leftPadding
+        self.__dict__['_bottomPadding'] = bottomPadding
+        self.__dict__['_rightPadding'] = rightPadding
+        self.__dict__['_topPadding'] = topPadding
+
+        # if we want a boundary to be shown
+        self.showBoundary = showBoundary
+
+        if overlapAttachedSpace is None: overlapAttachedSpace = rl_config.overlapAttachedSpace
+        self._oASpace = overlapAttachedSpace
+        self._geom()
+        self._reset()
+
+    def __getattr__(self,a):
+        if a in _geomAttr: return self.__dict__['_'+a]
+        raise AttributeError(a)
+
+    def __setattr__(self,a,v):
+        if a in _geomAttr:
+            self.__dict__['_'+a] = v
+            self._geom()
+        else:
+            self.__dict__[a] = v
+
+    def _saveGeom(self, **kwds):
+        if not self.__dict__.setdefault('_savedGeom',{}):
+            for ga in _geomAttr:
+                ga = '_'+ga
+                self.__dict__['_savedGeom'][ga] = self.__dict__[ga]
+        for k,v in kwds.items():
+            setattr(self,k,v)
+
+    def _restoreGeom(self):
+        if self.__dict__.get('_savedGeom',None):
+            for ga in _geomAttr:
+                ga = '_'+ga
+                self.__dict__[ga] = self.__dict__[ga]['_savedGeom']
+                del self.__dict__['_savedGeom']
+            self._geom()
+
+    def _geom(self):
+        self._x2 = self._x1 + self._width
+        self._y2 = self._y1 + self._height
+        #efficiency
+        self._y1p = self._y1 + self._bottomPadding
+        #work out the available space
+        self._aW = self._x2 - self._x1 - self._leftPadding - self._rightPadding
+        self._aH = self._y2 - self._y1p - self._topPadding
+
+    def _reset(self):
+        self._restoreGeom()
+        #drawing starts at top left
+        self._x = self._x1 + self._leftPadding
+        self._y = self._y2 - self._topPadding
+        self._atTop = 1
+        self._prevASpace = 0
+
+        # these two should NOT be set on a frame.
+        # they are used when Indenter flowables want
+        # to adjust edges e.g. to do nested lists
+        self._leftExtraIndent = 0.0
+        self._rightExtraIndent = 0.0
+
+    def _getAvailableWidth(self):
+        return self._aW - self._leftExtraIndent - self._rightExtraIndent
+
+    def _add(self, flowable, canv, trySplit=0):
+        """ Draws the flowable at the current position.
+        Returns 1 if successful, 0 if it would not fit.
+        Raises a LayoutError if the object is too wide,
+        or if it is too high for a totally empty frame,
+        to avoid infinite loops"""
+        flowable._frame = self
+        flowable.canv = canv #so they can use stringWidth etc
+        try:
+            if getattr(flowable,'frameAction',None):
+                flowable.frameAction(self)
+                return 1
+
+            y = self._y
+            p = self._y1p
+            s = 0
+            aW = self._getAvailableWidth()
+            zeroSize = getattr(flowable,'_ZEROSIZE',False)
+            if not self._atTop:
+                s =flowable.getSpaceBefore()
+                if self._oASpace:
+                    if getattr(flowable,'_SPACETRANSFER',False) or zeroSize:
+                        s = self._prevASpace
+                    s = max(s-self._prevASpace,0)
+            h = y - p - s
+            if h>0 or zeroSize:
+                w, h = flowable.wrap(aW, h)
+            else:
+                return 0
+
+            h += s
+            y -= h
+
+            if y < p-_FUZZ:
+                if not rl_config.allowTableBoundsErrors and ((h>self._aH or w>aW) and not trySplit):
+                    from reportlab.platypus.doctemplate import LayoutError
+                    raise LayoutError("Flowable %s (%sx%s points) too large for frame (%sx%s points)." % (
+                        flowable.__class__, w,h, aW,self._aH))
+                return 0
+            else:
+                #now we can draw it, and update the current point.
+                sa = flowable.getSpaceAfter()
+                fbg = getattr(self,'_frameBGs',None)
+                if fbg and fbg[-1].active:
+                    bg = fbg[-1]
+                    fbgl = bg.left
+                    fbgr = bg.right
+                    bgm = bg.start
+                    fbw = self._width-fbgl-fbgr
+                    fbx = self._x1+fbgl
+                    if not bgm:
+                        fbh = y + h + sa
+                        fby = max(p,y-sa)
+                        fbh = max(0,fbh-fby)
+                    else:
+                        fbh = y + h - s
+                        att = fbh>=self._y2 - self._topPadding
+                        if bgm=='frame' or bgm=='frame-permanent' or (att and bgm=='frame-permanent-1'):
+                            #first time or att top use
+                            fbh = max(0,(self._y2 if att else fbh)-self._y1)
+                            fby = self._y1
+                            if bgm=='frame-permanent':
+                                fbg[-1].start = 'frame-permanent-1'
+                        else:
+                            fby = fbw = fbh = 0
+                    bg.render(canv,self,fbx,fby,fbw,fbh)
+                    if bgm=='frame':
+                        fbg.pop()
+
+                flowable.drawOn(canv, self._x + self._leftExtraIndent, y, _sW=aW-w)
+                flowable.canv=canv
+                if self._debug: logger.debug('drew %s' % flowable.identity())
+                y -= sa
+                if self._oASpace:
+                    if getattr(flowable,'_SPACETRANSFER',False):
+                        sa = self._prevASpace
+                    self._prevASpace = sa
+                if y!=self._y: self._atTop = 0
+                self._y = y
+                return 1
+        finally:
+            #sometimes canv/_frame aren't still on the flowable
+            for a in ('canv', '_frame'):
+                if hasattr(flowable,a):
+                    delattr(flowable,a)
+
+    add = _add
+
+    def split(self,flowable,canv):
+        '''Ask the flowable to split using up the available space.'''
+        y = self._y
+        p = self._y1p
+        s = 0
+        if not self._atTop:
+            s = flowable.getSpaceBefore()
+            if self._oASpace:
+                s = max(s-self._prevASpace,0)
+        h = y-p-s
+        if h<=0 and not getattr(flowable,'_ZEROSIZE',False):
+            return []
+        flowable._frame = self                  #some flowables might need these
+        flowable.canv = canv
+        try:
+            r = flowable.split(self._aW, h)
+        finally:
+            #sometimes canv/_frame aren't still on the flowable
+            for a in ('canv', '_frame'):
+                if hasattr(flowable,a):
+                    delattr(flowable,a)
+        return r
+
+    def drawBoundary(self, canv, __boundary__=None):
+        canv.drawBoundary(__boundary__ or self.showBoundary, self._x1, self._y1,
+                                self._x2 - self._x1, self._y2 - self._y1)
+
+    def addFromList(self, drawlist, canv):
+        """Consumes objects from the front of the list until the
+        frame is full.  If it cannot fit one object, raises
+        an exception."""
+
+        if self._debug: logger.debug("enter Frame.addFromlist() for frame %s" % self.id)
+        if self.showBoundary:
+            self.drawBoundary(canv)
+
+        while len(drawlist) > 0:
+            head = drawlist[0]
+            if self.add(head,canv,trySplit=0):
+                del drawlist[0]
+            else:
+                #leave it in the list for later
+                break
+
+    def add_generated_content(self,*C):
+        self.__dict__.setdefault('_generated_content',[]).extend(C)
+
+    def _aSpaceString(self):
+        return '(%s x %s%s)' % (self._getAvailableWidth(),self._aH,self._atTop and '*' or '')
diff --git a/.venv/lib/python3.13/site-packages/reportlab/platypus/multicol.py b/.venv/lib/python3.13/site-packages/reportlab/platypus/multicol.py
new file mode 100644
index 0000000000000000000000000000000000000000..a213978b8bac4496e330345a60bc83793d7f67c4
--- /dev/null
+++ b/.venv/lib/python3.13/site-packages/reportlab/platypus/multicol.py
@@ -0,0 +1,111 @@
+__all__ = '''MultiCol'''.split()
+from reportlab.lib.utils import strTypes
+from .flowables import Flowable, _Container, _FindSplitterMixin, _listWrapOn
+
+class MultiCol(_Container,_FindSplitterMixin,Flowable):
+	def __init__(self,contents,widths, minHeightNeeded=36, spaceBefore=None, spaceAfter=None):
+		if len(contents)!=len(widths):
+			raise ValueError('%r len(contents)=%d not the same as len(widths)=%d' % (self,len(contents),len(widths)))
+		self.contents = contents
+		self.widths = widths
+		self.minHeightNeeded = minHeightNeeded
+		self._spaceBefore = spaceBefore
+		self._spaceAfter = spaceAfter
+		self._naW = None
+
+	def nWidths(self,aW):
+		if aW==self._naW: return self._nW
+		nW = [].append
+		widths = self.widths
+		s = 0.0
+		for i,w in enumerate(widths):
+			if isinstance(w,strTypes):
+				w=w.strip()
+				pc = w.endswith('%')
+				if pc: w=w[:-1]
+				try:
+					w = float(w)
+				except:
+					raise ValueError('%s: nWidths failed with value %r' % (self,widths[i]))
+				if pc: w = w*0.01*aW
+			elif not isinstance(w,(float,int)):
+				raise ValueError('%s: nWidths failed with value %r' % (self,widths[i]))
+
+			s += w
+			nW(w)
+
+		self._naW = aW
+		s = aW / s
+		self._nW = [w*s for w in nW.__self__]
+		return self._nW
+
+	def wrap(self,aW,aH):
+		widths = self.nWidths(aW)
+		w = h = 0.0
+		canv = self.canv
+		h = 0
+		for faW,F in zip(widths,self.contents):
+			if not F:
+				fW = faW
+				fH = 0
+			else:
+				fW,fH = _listWrapOn(F,faW,canv)
+			h = max(h,fH)
+			w += fW
+		self.width = w
+		self.height = h
+		return w, h
+
+	def split(self,aW,aH):
+		if aH
+        
  • first one
  • +
  • second one
  • + + + +Also
      (default) or
        ,
          . + +- Numberred lists (ala html):: + +
            +
          1. first one
          2. +
          3. second one
          4. +
          + +Also
            (default) or
              ,
                . + +- Display lists (ala HTML): + +For example + +
                +
                frogs
                Little green slimy things. Delicious with garlic
                +
                kittens
                cute, furry, not edible
                +
                bunnies
                cute, furry,. Delicious with garlic
                +
                + +ALSO the following additional internal paragraph markup tags are supported + +underlined text + +hyperlinked text +hyperlinked text + +Go to the end (go to document internal destination) +Go to the beginning + +This is the document start + (define document destination inside paragraph, color is optional) + +""" +from reportlab.pdfbase.pdfmetrics import stringWidth +from reportlab.lib.rl_accel import fp_str +from reportlab.platypus.flowables import Flowable +from reportlab.lib import colors +from reportlab.lib.styles import _baseFontName + +# SET THIS TO CAUSE A VIEWING BUG WITH ACROREAD 3 (for at least one input) +# CAUSEERROR = 0 + +debug = 0 + +DUMPPROGRAM = 0 + +TOOSMALLSPACE = 1e-5 + +from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT, TA_JUSTIFY + +# indent changes effect the next line +# align changes effect the current line + +# need to fix spacing questions... if ends with space then space may be inserted + +# NEGATIVE SPACE SHOULD NEVER BE EXPANDED (IN JUSTIFICATION, EG) + +class paragraphEngine: + # text origin of 0,0 is upper left corner + def __init__(self, program = None): + from reportlab.lib.colors import black + if program is None: + program = [] + self.lineOpHandlers = [] # for handling underlining and hyperlinking, etc + self.program = program + self.indent = self.rightIndent = 0.0 + self.baseindent = 0.0 # adjust this to add more indentation for bullets, eg + self.fontName = "Helvetica" + self.fontSize = 10 + self.leading = 12 + self.fontColor = black + self.x = self.y = self.rise = 0.0 + from reportlab.lib.enums import TA_LEFT + self.alignment = TA_LEFT + self.textStateStack = [] + + TEXT_STATE_VARIABLES = ("indent", "rightIndent", "fontName", "fontSize", + "leading", "fontColor", "lineOpHandlers", "rise", + "alignment") + #"textStateStack") + + def pushTextState(self): + state = [] + for var in self.TEXT_STATE_VARIABLES: + val = getattr(self, var) + state.append(val) + #self.textStateStack.append(state) + self.textStateStack = self.textStateStack+[state] # fresh copy + #print "push", self.textStateStack + #print "push", len(self.textStateStack), state + return state + + def popTextState(self): + state = self.textStateStack[-1] + self.textStateStack = self.textStateStack[:-1] + #print "pop", self.textStateStack + state = state[:] # copy for destruction + #print "pop", len(self.textStateStack), state + #print "handlers before", self.lineOpHandlers + for var in self.TEXT_STATE_VARIABLES: + val = state[0] + del state[0] + setattr(self, var, val) + + def format(self, maxwidth, maxheight, program, leading=0): + "return program with line operations added if at least one line fits" + # note: a generated formatted segment should not be formatted again + startstate = self.__dict__.copy() + #remainder = self.cleanProgram(program) + remainder = program[:] + #program1 = remainder[:] # debug only + lineprogram = [] + #if maxheight=self.leading and remainder: + #print "getting line with statestack", len(self.textStateStack) + #heightremaining = heightremaining - self.leading + indent = self.indent + rightIndent = self.rightIndent + linewidth = maxwidth - indent - rightIndent + beforelinestate = self.__dict__.copy() + if linewidthleading: + heightremaining = heightremaining-leading + else: + room = 0 + #self.resetState(beforelinestate) + self.__dict__.update(beforelinestate) + break # no room for this line +## if debug: +## print "line", line +## if lineIsFull: print "is full" +## else: print "is partially full" +## print "consumes", cursor, "elements" +## print "covers", currentLength, "of", maxwidth + alignment = self.alignment # last declared alignment for this line used + # recompute linewidth using the used indent + #linewidth = maxwidth - usedIndent - rightIndent + remainder = remainder[cursor:] + if not remainder: + # trim off the extra end of line + del line[-1] + # do justification if any + #line = self.shrinkWrap(line + if alignment==TA_LEFT: + #if debug: + # print "ALIGN LEFT" + if justStrings: + line = stringLine(line, currentLength) + else: + line = self.shrinkWrap(line) + pass + elif alignment==TA_CENTER: + #if debug: + # print "ALIGN CENTER" + if justStrings: + line = stringLine(line, currentLength) + else: + line = self.shrinkWrap(line) + line = self.centerAlign(line, currentLength, maxLength) + elif alignment==TA_RIGHT: + #if debug: + # print "ALIGN RIGHT" + if justStrings: + line = stringLine(line, currentLength) + else: + line = self.shrinkWrap(line) + line = self.rightAlign(line, currentLength, maxLength) + elif alignment==TA_JUSTIFY: + #if debug: + # print "JUSTIFY" + if remainder and lineIsFull: + if justStrings: + line = simpleJustifyAlign(line, currentLength, maxLength) + else: + line = self.justifyAlign(line, currentLength, maxLength) + else: + if justStrings: + line = stringLine(line, currentLength) + else: + line = self.shrinkWrap(line) + if debug: + print("no justify because line is not full or end of para") + else: + raise ValueError("bad alignment "+repr(alignment)) + if not justStrings: + line = self.cleanProgram(line) + lineprogram.extend(line) + laststate = self.__dict__.copy() + #self.resetState(startstate) + self.__dict__.update(startstate) + heightused = maxheight - heightremaining + return (lineprogram, remainder, laststate, heightused) + + def getState(self): + # inlined + return self.__dict__.copy() + + def resetState(self, state): + # primarily inlined + self.__dict__.update(state) + +## def sizeOfWord(self, word): +## inlineThisFunctionForEfficiency +## return float(stringWidth(word, self.fontName, self.fontSize)) + + def fitLine(self, program, totalLength): + "fit words (and other things) onto a line" + # assuming word lengths and spaces have not been yet added + # fit words onto a line up to maxlength, adding spaces and respecting extra space + from reportlab.pdfbase.pdfmetrics import stringWidth + usedIndent = self.indent + maxLength = totalLength - usedIndent - self.rightIndent + done = 0 + line = [] + cursor = 0 + lineIsFull = 0 + currentLength = 0 + maxcursor = len(program) + needspace = 0 + first = 1 + terminated = None + fontName = self.fontName + fontSize = self.fontSize + spacewidth = stringWidth(" ", fontName, fontSize) #self.sizeOfWord(" ") + justStrings = 1 + while not done and cursormaxLength and not first: # always do at least one thing + # this word won't fit + #if debug: + # print "WORD", opcode, "wont fit, width", width, "fullwidth", fullwidth + # print " currentLength", currentLength, "newlength", newlength, "maxLength", maxLength + done = 1 + lineIsFull = 1 + else: + # fit the word: add a space then the word + if lastneedspace: + line.append( spacewidth ) # expandable space: positive + if opcode: + line.append( opcode ) + if abs(width)>TOOSMALLSPACE: + line.append( -width ) # non expanding space: negative + currentLength = newlength + #print line + #stop + first = 0 + elif isinstance(opcode,float): + justStrings = 0 + aopcode = abs(opcode) # negative means non expanding + if aopcode>TOOSMALLSPACE: + nextLength = currentLength+aopcode + if nextLength>maxLength and not first: # always do at least one thing + #if debug: print "EXPLICIT spacer won't fit", maxLength, nextLength, opcode + done = 1 + else: + if aopcode>TOOSMALLSPACE: + currentLength = nextLength + line.append(opcode) + first = 0 + elif isinstance(opcode,tuple): + justStrings = 0 + indicator = opcode[0] + #line.append(opcode) + if indicator=="nextLine": + # advance to nextLine + #(i, endallmarks) = opcode + line.append(opcode) + cursor += 1 # consume this element + terminated = done = 1 + #if debug: + # print "nextLine encountered" + elif indicator=="color": + # change fill color + oldcolor = self.fontColor + (i, colorname) = opcode + #print "opcode", opcode + if isinstance(colorname,str): + color = self.fontColor = getattr(colors, colorname) + else: + color = self.fontColor = colorname # assume its something sensible :) + line.append(opcode) + elif indicator=="face": + # change font face + (i, fontname) = opcode + fontName = self.fontName = fontname + spacewidth = stringWidth(" ", fontName, fontSize) #self.sizeOfWord(" ") + line.append(opcode) + elif indicator=="size": + # change font size + (i, fontsize) = opcode + size = abs(float(fontsize)) + if isinstance(fontsize,str): + if fontsize[:1]=="+": + fontSize = self.fontSize = self.fontSize + size + elif fontsize[:1]=="-": + fontSize = self.fontSize = self.fontSize - size + else: + fontSize = self.fontSize = size + else: + fontSize = self.fontSize = size + spacewidth = stringWidth(" ", fontName, fontSize) #self.sizeOfWord(" ") + line.append(opcode) + elif indicator=="leading": + # change font leading + (i, leading) = opcode + self.leading = leading + line.append(opcode) + elif indicator=="indent": + # increase the indent + (i, increment) = opcode + indent = self.indent = self.indent + increment + if first: + usedIndent = max(indent, usedIndent) + maxLength = totalLength - usedIndent - self.rightIndent + line.append(opcode) + elif indicator=="push": + self.pushTextState() + line.append(opcode) + elif indicator=="pop": + try: + self.popTextState() + except: +## print "stack fault near", cursor +## for i in program[max(0, cursor-10):cursor+10]: +## if i==cursor: +## print "***>>>", +## print i + raise + fontName = self.fontName + fontSize = self.fontSize + spacewidth = stringWidth(" ", fontName, fontSize) #self.sizeOfWord(" ") + line.append(opcode) + elif indicator=="bullet": + (i, bullet, indent, font, size) = opcode + # adjust for base indent (only at format time -- only execute once) + indent = indent + self.baseindent + opcode = (i, bullet, indent, font, size) + if not first: + raise ValueError("bullet not at beginning of line") + bulletwidth = float(stringWidth(bullet, font, size)) + spacewidth = float(stringWidth(" ", font, size)) + bulletmin = indent+spacewidth+bulletwidth + # decrease the line size to allow bullet + usedIndent = max(bulletmin, usedIndent) + if first: + maxLength = totalLength - usedIndent - self.rightIndent + line.append(opcode) + elif indicator=="rightIndent": + # increase the right indent + (i, increment) = opcode + self.rightIndent = self.rightIndent+increment + if first: + maxLength = totalLength - usedIndent - self.rightIndent + line.append(opcode) + elif indicator=="rise": + (i, rise) = opcode + newrise = self.rise = self.rise+rise + line.append(opcode) + elif indicator=="align": + (i, alignment) = opcode + #if debug: + # print "SETTING ALIGNMENT", alignment + self.alignment = alignment + line.append(opcode) + elif indicator=="lineOperation": + (i, handler) = opcode + line.append(opcode) + self.lineOpHandlers = self.lineOpHandlers + [handler] # fresh copy + elif indicator=="endLineOperation": + (i, handler) = opcode + h = self.lineOpHandlers[:] # fresh copy + h.remove(handler) + self.lineOpHandlers = h + line.append(opcode) + + else: + raise ValueError("at format time don't understand indicator "+repr(indicator)) + else: + raise ValueError("op must be string, float, instance, or tuple "+repr(opcode)) + if not done: + cursor += 1 + #first = 0 +## if debug: +## if done: +## print "DONE FLAG IS SET" +## if cursor>=maxcursor: +## print "AT END OF PROGRAM" + if not terminated: + line.append( ("nextLine", 0) ) + #print "fitline", line + return (lineIsFull, line, cursor, currentLength, usedIndent, maxLength, justStrings) + + def centerAlign(self, line, lineLength, maxLength): + diff = maxLength-lineLength + shift = diff/2.0 + if shift>TOOSMALLSPACE: + return self.insertShift(line, shift) + return line + + def rightAlign(self, line, lineLength, maxLength): + shift = maxLength-lineLength + #die + if shift>TOOSMALLSPACE: + return self.insertShift(line, shift) + return line + + def insertShift(self, line, shift): + # insert shift just before first visible element in line + result = [] + first = 1 + for e in line: + if first and (isinstance(e,str) or hasattr(e,'width')): + result.append(shift) + first = 0 + result.append(e) + return result + + def justifyAlign(self, line, lineLength, maxLength): + diff = maxLength-lineLength + # count EXPANDABLE SPACES AFTER THE FIRST VISIBLE + spacecount = 0 + visible = 0 + first = 1 + for e in line: + if isinstance(e,float) and e>TOOSMALLSPACE and visible: + spacecount += 1 + elif first and (isinstance(e,str) or hasattr(e,'width')): + visible = 1 + first = 0 + #if debug: print "diff is", diff, "wordcount", wordcount #; die + if spacecount<1: + return line + shift = diff/float(spacecount) + if shift<=TOOSMALLSPACE: + #if debug: print "shift too small", shift + return line + first = 1 + visible = 0 + result = [] + cursor = 0 + nline = len(line) + while cursorTOOSMALLSPACE and visible: + expanded = e+shift + result[-1] = expanded + cursor += 1 + return result + +## if not first: +## #if debug: print "shifting", shift, e +## #result.append(shift) +## # add the shift in result before any start markers before e +## insertplace = len(result)-1 +## done = 0 +## myshift = shift +## while insertplace>0 and not done: +## beforeplace = insertplace-1 +## beforething = result[beforeplace] +## if isinstance(beforething,tuple): +## indicator = beforething[0] +## if indicator=="endLineOperation": +## done = 1 +## elif debug: +## print "adding shift before", beforething +## elif isinstance(beforething,float): +## myshift += beforething +## del result[beforeplace] +## else: +## done = 1 +## if not done: +## insertplace = beforeplace +## result.insert(insertplace, myshift) +## first = 0 +## cursor += 1 +## return result + + def shrinkWrap(self, line): + # for non justified text, collapse adjacent text/shift's into single operations + result = [] + index = 0 + maxindex = len(line) + while index0: + thefloats = -thefloats + if nexte<0 and thefloats>0: + nexte = -nexte + thefloats += nexte + elif isinstance(nexte,str): + thestrings.append(nexte) + index += 1 + if index0: + last = -last + if e<0 and last>0: + e = -e + last = float(last)+e + else: + if abs(last)>TOOSMALLSPACE: + result.append(last) + result.append(e) + last = 0 + if last: + result.append(last) + # now go backwards and delete all floats occurring after all visible elements +## count = len(result)-1 +## done = 0 +## while count>0 and not done: +## e = result[count] +## if hasattr(e,'width') or isinstance(e,str): +## done = 1 +## elif isinstance(e,float): +## del result[count] +## count = count-1 + # move end operations left and start operations left up to visibles + change = 1 + rline = list(range(len(result)-1)) + while change: + #print line + change = 0 + for index in rline: + nextindex = index+1 + this = result[index] + next = result[nextindex] + doswap = 0 + # don't swap visibles + if isinstance(this,str) or \ + isinstance(next,str) or \ + hasattr(this,'width') or hasattr(next,'width'): + doswap = 0 + # only swap two tuples if the second one is an end operation and the first is something else + elif isinstance(this,tuple): + thisindicator = this[0] + if isinstance(next,tuple): + nextindicator = next[0] + doswap = 0 + if (nextindicator=="endLineOperation" and thisindicator!="endLineOperation" + and thisindicator!="lineOperation"): + doswap = 1 # swap nonend!=end + elif isinstance(next,float): + if thisindicator=="lineOperation": + doswap = 1 # begin != space + if doswap: + #print "swap", line[index],line[nextindex] + result[index] = next + result[nextindex] = this + change = 1 + return result + + def runOpCodes(self, program, canvas, textobject): + "render the line(s)" + + escape = canvas._escape + code = textobject._code + startstate = self.__dict__.copy() + font = None + size = None + # be sure to set them before using them (done lazily below) + #textobject.setFont(self.fontName, self.fontSize) + textobject.setFillColor(self.fontColor) + xstart = self.x + thislineindent = self.indent + thislinerightIndent = self.rightIndent + indented = 0 + for opcode in program: + if isinstance(opcode,str) or hasattr(opcode,'width'): + if not indented: + if abs(thislineindent)>TOOSMALLSPACE: + #if debug: print "INDENTING", thislineindent + #textobject.moveCursor(thislineindent, 0) + code.append('%s Td' % fp_str(thislineindent, 0)) + self.x += thislineindent + for handler in self.lineOpHandlers: + #handler.end_at(x, y, self, canvas, textobject) # finish, eg, underlining this line + handler.start_at(self.x, self.y, self, canvas, textobject) # start underlining the next + indented = 1 + # lazily set font (don't do it again if not needed) + if font!=self.fontName or size!=self.fontSize: + font = self.fontName + size = self.fontSize + textobject.setFont(font, size) + if isinstance(opcode,str): + textobject.textOut(opcode) + else: + # drawable thing + opcode.execute(self, textobject, canvas) + elif isinstance(opcode,float): + # use abs value (ignore expandable marking) + opcode = abs(opcode) + if opcode>TOOSMALLSPACE: + #textobject.moveCursor(opcode, 0) + code.append('%s Td' % fp_str(opcode, 0)) + self.x += opcode + elif isinstance(opcode,tuple): + indicator = opcode[0] + if indicator=="nextLine": + # advance to nextLine + (i, endallmarks) = opcode + x = self.x + y = self.y + newy = self.y = self.y-self.leading + newx = self.x = xstart + thislineindent = self.indent + thislinerightIndent = self.rightIndent + indented = 0 + for handler in self.lineOpHandlers: + handler.end_at(x, y, self, canvas, textobject) # finish, eg, underlining this line + #handler.start_at(newx, newy, self, canvas, textobject)) # start underlining the next + textobject.setTextOrigin(newx, newy) + elif indicator=="color": + # change fill color + oldcolor = self.fontColor + (i, colorname) = opcode + #print "opcode", opcode + if isinstance(colorname,str): + color = self.fontColor = getattr(colors, colorname) + else: + color = self.fontColor = colorname # assume its something sensible :) + #if debug: + # print color.red, color.green, color.blue + # print dir(color) + #print "color is", color + #from reportlab.lib.colors import green + #if color is green: print "color is green" + if color!=oldcolor: + textobject.setFillColor(color) + elif indicator=="face": + # change font face + (i, fontname) = opcode + self.fontName = fontname + #textobject.setFont(self.fontName, self.fontSize) + elif indicator=="size": + # change font size + (i, fontsize) = opcode + size = abs(float(fontsize)) + if isinstance(fontsize,str): + if fontsize[:1]=="+": + self.fontSize += size + elif fontsize[:1]=="-": + self.fontSize -= size + else: + self.fontSize = size + else: + self.fontSize = size + fontSize = self.fontSize + textobject.setFont(self.fontName, self.fontSize) + elif indicator=="leading": + # change font leading + (i, leading) = opcode + self.leading = leading + elif indicator=="indent": + # increase the indent + (i, increment) = opcode + indent = self.indent = self.indent + increment + thislineindent = max(thislineindent, indent) + elif indicator=="push": + self.pushTextState() + elif indicator=="pop": + oldcolor = self.fontColor + oldfont = self.fontName + oldsize = self.fontSize + self.popTextState() + #if CAUSEERROR or oldfont!=self.fontName or oldsize!=self.fontSize: + # textobject.setFont(self.fontName, self.fontSize) + if oldcolor!=self.fontColor: + textobject.setFillColor(self.fontColor) + elif indicator=="wordSpacing": + (i, ws) = opcode + textobject.setWordSpace(ws) + elif indicator=="bullet": + (i, bullet, indent, font, size) = opcode + if abs(self.x-xstart)>TOOSMALLSPACE: + raise ValueError("bullet not at beginning of line") + bulletwidth = float(stringWidth(bullet, font, size)) + spacewidth = float(stringWidth(" ", font, size)) + bulletmin = indent+spacewidth+bulletwidth + # decrease the line size to allow bullet as needed + if bulletmin > thislineindent: + #if debug: print "BULLET IS BIG", bullet, bulletmin, thislineindent + thislineindent = bulletmin + textobject.moveCursor(indent, 0) + textobject.setFont(font, size) + textobject.textOut(bullet) + textobject.moveCursor(-indent, 0) + #textobject.textOut("M") + textobject.setFont(self.fontName, self.fontSize) + elif indicator=="rightIndent": + # increase the right indent + (i, increment) = opcode + self.rightIndent = self.rightIndent+increment + elif indicator=="rise": + (i, rise) = opcode + newrise = self.rise = self.rise+rise + textobject.setRise(newrise) + elif indicator=="align": + (i, alignment) = opcode + self.alignment = alignment + elif indicator=="lineOperation": + (i, handler) = opcode + handler.start_at(self.x, self.y, self, canvas, textobject) + #self.lineOpHandlers.append(handler) + #if debug: print "adding", handler, self.lineOpHandlers + self.lineOpHandlers = self.lineOpHandlers + [handler] # fresh copy! + elif indicator=="endLineOperation": + (i, handler) = opcode + handler.end_at(self.x, self.y, self, canvas, textobject) + newh = self.lineOpHandlers = self.lineOpHandlers[:] # fresh copy + #if debug: print "removing", handler, self.lineOpHandlers + if handler in newh: + self.lineOpHandlers.remove(handler) + else: + pass + #print "WARNING: HANDLER", handler, "NOT IN", newh + else: + raise ValueError("don't understand indicator "+repr(indicator)) + else: + raise ValueError("op must be string float or tuple "+repr(opcode)) + laststate = self.__dict__.copy() + #self.resetState(startstate) + self.__dict__.update(startstate) + return laststate + +def stringLine(line, length): + "simple case: line with just strings and spacings which can be ignored" + + strings = [] + for x in line: + if isinstance(x,str): + strings.append(x) + text = ' '.join(strings) + result = [text, float(length)] + nextlinemark = ("nextLine", 0) + if line and line[-1]==nextlinemark: + result.append( nextlinemark ) + return result + +def simpleJustifyAlign(line, currentLength, maxLength): + "simple justification with only strings" + + strings = [] + for x in line[:-1]: + if isinstance(x,str): + strings.append(x) + nspaces = len(strings)-1 + slack = maxLength-currentLength + text = ' '.join(strings) + if nspaces>0 and slack>0: + wordspacing = slack/float(nspaces) + result = [("wordSpacing", wordspacing), text, maxLength, ("wordSpacing", 0)] + else: + result = [text, currentLength, ("nextLine", 0)] + nextlinemark = ("nextLine", 0) + if line and line[-1]==nextlinemark: + result.append( nextlinemark ) + return result + +from reportlab.lib.colors import black + +def readBool(text): + if text.upper() in ("Y", "YES", "TRUE", "1"): + return 1 + elif text.upper() in ("N", "NO", "FALSE", "0"): + return 0 + else: + raise ValueError("true/false attribute has illegal value '%s'" % text) + +def readAlignment(text): + up = text.upper() + if up == 'LEFT': + return TA_LEFT + elif up == 'RIGHT': + return TA_RIGHT + elif up in ['CENTER', 'CENTRE']: + return TA_CENTER + elif up == 'JUSTIFY': + return TA_JUSTIFY + +def readLength(text): + """Read a dimension measurement: accept "3in", "5cm", + "72 pt" and so on.""" + text = text.strip() + try: + return float(text) + except ValueError: + text = text.lower() + numberText, units = text[:-2],text[-2:] + numberText = numberText.strip() + try: + number = float(numberText) + except ValueError: + raise ValueError("invalid length attribute '%s'" % text) + try: + multiplier = { + 'in':72, + 'cm':28.3464566929, #72/2.54; is this accurate? + 'mm':2.83464566929, + 'pt':1 + }[units] + except KeyError: + raise ValueError("invalid length attribute '%s'" % text) + + return number * multiplier + +def lengthSequence(s, converter=readLength): + """from "(2, 1)" or "2,1" return [2,1], for example""" + s = s.strip() + if s[:1]=="(" and s[-1:]==")": + s = s[1:-1] + sl = s.split(',') + sl = [s.strip() for s in sl] + sl = [converter(s) for s in sl] + return sl + + +def readColor(text): + """Read color names or tuples, RGB or CMYK, and return a Color object.""" + if not text: + return None + from reportlab.lib import colors + from string import letters + if text[0] in letters: + return colors.__dict__[text] + tup = lengthSequence(text) + + msg = "Color tuple must have 3 (or 4) elements for RGB (or CMYC)." + assert 3 <= len(tup) <= 4, msg + msg = "Color tuple must have all elements <= 1.0." + for i in range(len(tup)): + assert tup[i] <= 1.0, msg + + if len(tup) == 3: + colClass = colors.Color + elif len(tup) == 4: + colClass = colors.CMYKColor + return colClass(*tup) + +class StyleAttributeConverters: + fontSize=[readLength] + leading=[readLength] + leftIndent=[readLength] + rightIndent=[readLength] + firstLineIndent=[readLength] + alignment=[readAlignment] + spaceBefore=[readLength] + spaceAfter=[readLength] + bulletFontSize=[readLength] + bulletIndent=[readLength] + textColor=[readColor] + backColor=[readColor] + +class SimpleStyle: + "simplified paragraph style without all the fancy stuff" + name = "basic" + fontName=_baseFontName + fontSize=10 + leading=12 + leftIndent=0 + rightIndent=0 + firstLineIndent=0 + alignment=TA_LEFT + spaceBefore=0 + spaceAfter=0 + bulletFontName=_baseFontName + bulletFontSize=10 + bulletIndent=0 + textColor=black + backColor=None + + def __init__(self, name, parent=None, **kw): + mydict = self.__dict__ + if parent: + for a,b in parent.__dict__.items(): + mydict[a]=b + for a,b in kw.items(): + mydict[a] = b + + def addAttributes(self, dictionary): + for key in dictionary.keys(): + value = dictionary[key] + if value is not None: + if hasattr(StyleAttributeConverters, key): + converter = getattr(StyleAttributeConverters, key)[0] + value = converter(value) + setattr(self, key, value) + + +DEFAULT_ALIASES = { + "h1.defaultStyle": "Heading1", + "h2.defaultStyle": "Heading2", + "h3.defaultStyle": "Heading3", + "h4.defaultStyle": "Heading4", + "h5.defaultStyle": "Heading5", + "h6.defaultStyle": "Heading6", + "title.defaultStyle": "Title", + "subtitle.defaultStyle": "SubTitle", + "para.defaultStyle": "Normal", + "pre.defaultStyle": "Code", + "ul.defaultStyle": "UnorderedList", + "ol.defaultStyle": "OrderedList", + "li.defaultStyle": "Definition", + } + +class FastPara(Flowable): + "paragraph with no special features (not even a single ampersand!)" + + def __init__(self, style, simpletext): + #if debug: + # print "FAST", id(self) + if "&" in simpletext: + raise ValueError("no ampersands please!") + self.style = style + self.simpletext = simpletext + self.lines = None + + def wrap(self, availableWidth, availableHeight): + simpletext = self.simpletext + self.availableWidth = availableWidth + style = self.style + text = self.simpletext + rightIndent = style.rightIndent + leftIndent = style.leftIndent + leading = style.leading + font = style.fontName + size = style.fontSize + firstindent = style.firstLineIndent + #textcolor = style.textColor + words = simpletext.split() + lines = [] + from reportlab.pdfbase.pdfmetrics import stringWidth + spacewidth = stringWidth(" ", font, size) + currentline = [] + currentlength = 0 + firstmaxlength = availableWidth - rightIndent - firstindent + maxlength = availableWidth - rightIndent - leftIndent + if maxlengthavailableHeight: + done = 1 + if currentlength and not done: + lines.append( (' '.join(currentline), currentlength, len(currentline) )) + heightused = heightused+leading + self.lines = lines + self.height = heightused + remainder = self.remainder = ' '.join(words[cursor:]) + #print "lines", lines + #print "remainder is", remainder + else: + remainder = None + heightused = self.height + lines = self.lines + if remainder: + result = (availableWidth, availableHeight+leading) # need to split + else: + result = (availableWidth, heightused) + #if debug: print "wrap is", (availableWidth, availableHeight), result, len(lines) + return result + + def split(self, availableWidth, availableHeight): + style = self.style + leading = style.leading + if availableHeight1: + # patch from doug@pennatus.com, 9 Nov 2002, no extraspace on last line + textobject.setWordSpace((basicWidth-length)/(nwords-1.0)) + else: + textobject.setWordSpace(0.0) + textobject.setTextOrigin(x,y) + textobject.textOut(text) + y = y-leading + c.drawText(textobject) + + def getSpaceBefore(self): + #if debug: + # print "got space before", self.spaceBefore + return self.style.spaceBefore + + def getSpaceAfter(self): + #print "got space after", self.spaceAfter + return self.style.spaceAfter + +def defaultContext(): + result = {} + from reportlab.lib.styles import getSampleStyleSheet + styles = getSampleStyleSheet() + for stylenamekey, stylenamevalue in DEFAULT_ALIASES.items(): + result[stylenamekey] = styles[stylenamevalue] + return result + +def buildContext(stylesheet=None): + result = {} + from reportlab.lib.styles import getSampleStyleSheet + if stylesheet is not None: + # Copy styles with the same name as aliases + for stylenamekey, stylenamevalue in DEFAULT_ALIASES.items(): + if stylenamekey in stylesheet: + result[stylenamekey] = stylesheet[stylenamekey] + # Then make aliases + for stylenamekey, stylenamevalue in DEFAULT_ALIASES.items(): + if stylenamevalue in stylesheet: + result[stylenamekey] = stylesheet[stylenamevalue] + + styles = getSampleStyleSheet() + # Then, fill in defaults if they were not filled yet. + for stylenamekey, stylenamevalue in DEFAULT_ALIASES.items(): + if stylenamekey not in result and stylenamevalue in styles: + result[stylenamekey] = styles[stylenamevalue] + return result + +class Para(Flowable): + + spaceBefore = 0 + spaceAfter = 0 + + def __init__(self, style, parsedText=None, bulletText=None, state=None, context=None, baseindent=0): + #print id(self), "para", parsedText + self.baseindent = baseindent + self.context = buildContext(context) + self.parsedText = parsedText + self.bulletText = bulletText + self.style1 = style # make sure Flowable doesn't use this unless wanted! call it style1 NOT style + #self.spaceBefore = self.spaceAfter = 0 + self.program = [] # program before layout + self.formattedProgram = [] # after layout + self.remainder = None # follow on paragraph if any + self.state = state # initial formatting state (for completions) + if not state: + self.spaceBefore = style.spaceBefore + self.spaceAfter = style.spaceAfter + #self.spaceBefore = "invalid value" + #if hasattr(self, "spaceBefore") and debug: + # print "spaceBefore is", self.spaceBefore, self.parsedText + self.bold = 0 + self.italic = 0 + self.face = style.fontName + self.size = style.fontSize + + def getSpaceBefore(self): + #if debug: + # print "got space before", self.spaceBefore + return self.spaceBefore + + def getSpaceAfter(self): + #print "got space after", self.spaceAfter + return self.spaceAfter + + def wrap(self, availableWidth, availableHeight): + if debug: + print("WRAPPING", id(self), availableWidth, availableHeight) + print(" ", self.formattedProgram) + print(" ", self.program) + self.availableHeight = availableHeight + self.myengine = p = paragraphEngine() + p.baseindent = self.baseindent # for shifting bullets as needed + parsedText = self.parsedText + formattedProgram = self.formattedProgram + state = self.state + if state: + leading = state["leading"] + else: + leading = self.style1.leading + program = self.program + self.cansplit = 1 # until proven otherwise + if state: + p.resetState(state) + p.x = 0 + p.y = 0 + needatleast = state["leading"] + else: + needatleast = self.style1.leading + if availableHeight<=needatleast: + self.cansplit = 0 + #if debug: + # print "CANNOT COMPILE, NEED AT LEAST", needatleast, 'AVAILABLE', availableHeight + return (availableHeight+1, availableWidth) # cannot split + if parsedText is None and program is None: + raise ValueError("need parsedText for formatting") + if not program: + self.program = program = self.compileProgram(parsedText) + if not self.formattedProgram: + (formattedProgram, remainder, \ + laststate, heightused) = p.format(availableWidth, availableHeight, program, leading) + self.formattedProgram = formattedProgram + self.height = heightused + self.laststate = laststate + self.remainderProgram = remainder + else: + heightused = self.height + remainder = None + # too big if there is a remainder + if remainder: + # lie about the height: it must be split anyway + #if debug: + # print "I need to split", self.formattedProgram + # print "heightused", heightused, "available", availableHeight, "remainder", len(remainder) + height = availableHeight + 1 + #print "laststate is", laststate + #print "saving remainder", remainder + self.remainder = Para(self.style1, parsedText=None, bulletText=None, \ + state=laststate, context=self.context) + self.remainder.program = remainder + self.remainder.spaceAfter = self.spaceAfter + self.spaceAfter = 0 + else: + self.remainder = None # no extra + height = heightused + if height>availableHeight: + height = availableHeight-0.1 + #if debug: + # print "giving height", height, "of", availableHeight, self.parsedText + result = (availableWidth, height) + if debug: + (w, h) = result + if abs(availableHeight-h)<0.2: + print("exact match???" + repr(availableHeight, h)) + print("wrap is", (availableWidth, availableHeight), result) + return result + + def split(self, availableWidth, availableHeight): + #if debug: + # print "SPLITTING", id(self), availableWidth, availableHeight + if availableHeight<=0 or not self.cansplit: + #if debug: + # print "cannot split", availableWidth, "too small" + return [] # wrap failed to find a split + self.availableHeight = availableHeight + formattedProgram = self.formattedProgram + #print "formattedProgram is", formattedProgram + if formattedProgram is None: + raise ValueError("must call wrap before split") + elif not formattedProgram: + # no first line in self: fail to split + return [] + remainder = self.remainder + if remainder: + #print "SPLITTING" + result= [self, remainder] + else: + result= [self] + #if debug: print "split is", result + return result + + def draw(self): + p = self.myengine #paragraphEngine() + formattedProgram = self.formattedProgram + if formattedProgram is None: + raise ValueError("must call wrap before draw") + state = self.state + laststate = self.laststate + if state: + p.resetState(state) + p.x = 0 + p.y = 0 + c = self.canv + #if debug: + # print id(self), "page number", c.getPageNumber() + height = self.height + if state: + leading = state["leading"] + else: + leading = self.style1.leading + #if debug: + # c.rect(0,0,-1, height-self.size, fill=1, stroke=1) + c.translate(0, height-self.size) + t = c.beginText() + #t.setTextOrigin(0,0) + if DUMPPROGRAM or debug: + print("="*44, "now running program") + for x in formattedProgram: + print(x) + print("-"*44) + laststate = p.runOpCodes(formattedProgram, c, t) + #print laststate["x"], laststate["y"] + c.drawText(t) + + def compileProgram(self, parsedText, program=None): + style = self.style1 + # standard parameters + #program = self.program + if program is None: + program = [] + a = program.append + fn = style.fontName + # add style information if there was no initial state + a( ("face", fn ) ) + from reportlab.lib.fonts import ps2tt + (self.face, self.bold, self.italic) = ps2tt(fn) + a( ("size", style.fontSize ) ) + self.size = style.fontSize + a( ("align", style.alignment ) ) + a( ("indent", style.leftIndent ) ) + if style.firstLineIndent: + a( ("indent", style.firstLineIndent ) ) # must be undone later + a( ("rightIndent", style.rightIndent ) ) + a( ("leading", style.leading) ) + if style.textColor: + a( ("color", style.textColor) ) + #a( ("nextLine", 0) ) # clear for next line + if self.bulletText: + self.do_bullet(self.bulletText, program) + self.compileComponent(parsedText, program) + # now look for a place where to insert the unindent after the first line + if style.firstLineIndent: + count = 0 + for x in program: + count += 1 + if isinstance(x,str) or hasattr(x,'width'): + break + program.insert( count, ("indent", -style.firstLineIndent ) ) # defaults to end if no visibles + #print "="*8, id(self), "program is" + #for x in program: + # print x +## print "="*11 +## # check pushes and pops +## stackcount = 0 +## dump = 0 +## for x in program: +## if dump: +## print "dump:", x +## if isinstance(x,tuple): +## i = x[0] +## if i=="push": +## stackcount += 1 +## print " "*stackcount, "push", stackcount +## if i=="pop": +## stackcount = stackcount-1 +## print " "*stackcount, "pop", stackcount +## if stackcount<0: +## dump=1 +## print "STACK UNDERFLOW!" +## if dump: stop + return program + + def linearize(self, program = None, parsedText=None): + #print "LINEARIZING", self + #program = self.program = [] + if parsedText is None: + parsedText = self.parsedText + style = self.style1 + if program is None: + program = [] + program.append( ("push",) ) + if style.spaceBefore: + program.append( ("leading", style.spaceBefore+style.leading) ) + else: + program.append( ("leading", style.leading) ) + program.append( ("nextLine", 0) ) + program = self.compileProgram(parsedText, program=program) + program.append( ("pop",) ) + # go to old margin + program.append( ("push",) ) + if style.spaceAfter: + program.append( ("leading", style.spaceAfter) ) + else: + program.append( ("leading", 0) ) + program.append( ("nextLine", 0) ) + program.append( ("pop",) ) + + def compileComponent(self, parsedText, program): + #program = self.program + if isinstance(parsedText,str): + # handle special characters here... + # short cut + if parsedText: + stext = parsedText.strip() + if not stext: + program.append(" ") # contract whitespace to single space + else: + handleSpecialCharacters(self, parsedText, program) + elif isinstance(parsedText,list): + for e in parsedText: + self.compileComponent(e, program) + elif isinstance(parsedText,tuple): + (tagname, attdict, content, extra) = parsedText + if not attdict: + attdict = {} + compilername = "compile_"+tagname + compiler = getattr(self, compilername, None) + if compiler is not None: + compiler(attdict, content, extra, program) + else: + # just pass the tag through + if debug: + L = [ "<" + tagname ] + a = L.append + if not attdict: attdict = {} + for k, v in attdict.items(): + a(" %s=%s" % (k,v)) + if content: + a(">") + a(str(content)) + a("" % tagname) + else: + a("/>") + t = ''.join(L) + handleSpecialCharacters(self, t, program) + else: + raise ValueError("don't know how to handle tag " + repr(tagname)) + + def shiftfont(self, program, face=None, bold=None, italic=None): + oldface = self.face + oldbold = self.bold + olditalic = self.italic + oldfontinfo = (oldface, oldbold, olditalic) + if face is None: face = oldface + if bold is None: bold = oldbold + if italic is None: italic = olditalic + self.face = face + self.bold = bold + self.italic = italic + from reportlab.lib.fonts import tt2ps + font = tt2ps(face,bold,italic) + oldfont = tt2ps(oldface,oldbold,olditalic) + if font!=oldfont: + program.append( ("face", font ) ) + return oldfontinfo + + def compile_(self, attdict, content, extra, program): + # "anonymous" tag: just do the content + for e in content: + self.compileComponent(e, program) + #compile_para = compile_ # at least for now... + + def compile_pageNumber(self, attdict, content, extra, program): + program.append(PageNumberObject()) + + def compile_b(self, attdict, content, extra, program): + (f,b,i) = self.shiftfont(program, bold=1) + for e in content: + self.compileComponent(e, program) + self.shiftfont(program, bold=b) + + def compile_i(self, attdict, content, extra, program): + (f,b,i) = self.shiftfont(program, italic=1) + for e in content: + self.compileComponent(e, program) + self.shiftfont(program, italic=i) + + def compile_u(self, attdict, content, extra, program): + # XXXX must eventually add things like alternative colors + #program = self.program + program.append( ('lineOperation', UNDERLINE) ) + for e in content: + self.compileComponent(e, program) + program.append( ('endLineOperation', UNDERLINE) ) + + def compile_sub(self, attdict, content, extra, program): + size = self.size + self.size = newsize = size * 0.7 + rise = size*0.5 + #program = self.program + program.append( ('size', newsize) ) + self.size = size + program.append( ('rise', -rise) ) + for e in content: + self.compileComponent(e, program) + program.append( ('size', size) ) + program.append( ('rise', rise) ) + + def compile_ul(self, attdict, content, extra, program, tagname="ul"): + # by transformation + #print "compile", tagname, attdict + atts = attdict.copy() + bulletmaker = bulletMaker(tagname, atts, self.context) + # now do each element as a separate paragraph + for e in content: + if isinstance(e,str): + if e.strip(): + raise ValueError("don't expect CDATA between list elements") + elif isinstance(e,tuple): + (tagname, attdict1, content1, extra) = e + if tagname!="li": + raise ValueError("don't expect %s inside list" % repr(tagname)) + newatts = atts.copy() + if attdict1: + newatts.update(attdict1) + bulletmaker.makeBullet(newatts) + self.compile_para(newatts, content1, extra, program) + + def compile_ol(self, attdict, content, extra, program): + return self.compile_ul(attdict, content, extra, program, tagname="ol") + + def compile_dl(self, attdict, content, extra, program): + # by transformation + #print "compile", tagname, attdict + atts = attdict.copy() + # by transformation + #print "compile", tagname, attdict + atts = attdict.copy() + bulletmaker = bulletMaker("dl", atts, self.context) + # now do each element as a separate paragraph + contentcopy = list(content) # copy for destruction + bullet = "" + while contentcopy: + e = contentcopy[0] + del contentcopy[0] + if isinstance(e,str): + if e.strip(): + raise ValueError("don't expect CDATA between list elements") + elif not contentcopy: + break # done at ending whitespace + else: + continue # ignore intermediate whitespace + elif isinstance(e,tuple): + (tagname, attdict1, content1, extra) = e + if tagname!="dd" and tagname!="dt": + raise ValueError("don't expect %s here inside list, expect 'dd' or 'dt'" % \ + repr(tagname)) + if tagname=="dt": + if bullet: + raise ValueError("dt will not be displayed unless followed by a dd: "+repr(bullet)) + if content1: + self.compile_para(attdict1, content1, extra, program) + # raise ValueError, \ + # "only simple strings supported in dd content currently: "+repr(content1) + elif tagname=="dd": + newatts = atts.copy() + if attdict1: + newatts.update(attdict1) + bulletmaker.makeBullet(newatts, bl=bullet) + self.compile_para(newatts, content1, extra, program) + bullet = "" # don't use this bullet again + if bullet: + raise ValueError("dt will not be displayed unless followed by a dd"+repr(bullet)) + + def compile_super(self, attdict, content, extra, program): + size = self.size + self.size = newsize = size * 0.7 + rise = size*0.5 + #program = self.program + program.append( ('size', newsize) ) + program.append( ('rise', rise) ) + for e in content: + self.compileComponent(e, program) + program.append( ('size', size) ) + self.size = size + program.append( ('rise', -rise) ) + + def compile_font(self, attdict, content, extra, program): + #program = self.program + program.append( ("push",) ) # store current data + if "face" in attdict: + face = attdict["face"] + from reportlab.lib.fonts import tt2ps + try: + font = tt2ps(face,self.bold,self.italic) + except: + font = face # better work! + program.append( ("face", font ) ) + if "color" in attdict: + colorname = attdict["color"] + program.append( ("color", colorname) ) + if "size" in attdict: + #size = float(attdict["size"]) # really should convert int, cm etc here! + size = attdict["size"] + program.append( ("size", size) ) + for e in content: + self.compileComponent(e, program) + program.append( ("pop",) ) # restore as before + + def compile_a(self, attdict, content, extra, program): + url = attdict["href"] + colorname = attdict.get("color", "blue") + #program = self.program + Link = HotLink(url) + program.append( ("push",) ) # store current data + program.append( ("color", colorname) ) + program.append( ('lineOperation', Link) ) + program.append( ('lineOperation', UNDERLINE) ) + for e in content: + self.compileComponent(e, program) + program.append( ('endLineOperation', UNDERLINE) ) + program.append( ('endLineOperation', Link) ) + program.append( ("pop",) ) # restore as before + + def compile_link(self, attdict, content, extra, program): + dest = attdict["destination"] + colorname = attdict.get("color", None) + #program = self.program + Link = InternalLink(dest) + program.append( ("push",) ) # store current data + if colorname: + program.append( ("color", colorname) ) + program.append( ('lineOperation', Link) ) + program.append( ('lineOperation', UNDERLINE) ) + for e in content: + self.compileComponent(e, program) + program.append( ('endLineOperation', UNDERLINE) ) + program.append( ('endLineOperation', Link) ) + program.append( ("pop",) ) # restore as before + + def compile_setLink(self, attdict, content, extra, program): + dest = attdict["destination"] + colorname = attdict.get("color", "blue") + #program = self.program + Link = DefDestination(dest) + program.append( ("push",) ) # store current data + if colorname: + program.append( ("color", colorname) ) + program.append( ('lineOperation', Link) ) + if colorname: + program.append( ('lineOperation', UNDERLINE) ) + for e in content: + self.compileComponent(e, program) + if colorname: + program.append( ('endLineOperation', UNDERLINE) ) + program.append( ('endLineOperation', Link) ) + program.append( ("pop",) ) # restore as before + + #def compile_p(self, attdict, content, extra, program): + # # have to be careful about base indent here! + # not finished + + def compile_bullet(self, attdict, content, extra, program): + ### eventually should allow things like images and graphics in bullets too XXXX + if len(content)!=1 or not isinstance(content[0],str): + raise ValueError("content for bullet must be a single string") + text = content[0] + self.do_bullet(text, program) + + def do_bullet(self, text, program): + style = self.style1 + #program = self.program + indent = style.bulletIndent + self.baseindent + font = style.bulletFontName + size = style.bulletFontSize + program.append( ("bullet", text, indent, font, size) ) + + def compile_tt(self, attdict, content, extra, program): + (f,b,i) = self.shiftfont(program, face="Courier") + for e in content: + self.compileComponent(e, program) + self.shiftfont(program, face=f) + + def compile_greek(self, attdict, content, extra, program): + self.compile_font({"face": "symbol"}, content, extra, program) + + def compile_evalString(self, attdict, content, extra, program): + program.append( EvalStringObject(attdict, content, extra, self.context) ) + + def compile_name(self, attdict, content, extra, program): + program.append( NameObject(attdict, content, extra, self.context) ) + + def compile_getName(self, attdict, content, extra, program): + program.append( GetNameObject(attdict, content, extra, self.context) ) + + def compile_seq(self, attdict, content, extra, program): + program.append( SeqObject(attdict, content, extra, self.context) ) + + def compile_seqReset(self, attdict, content, extra, program): + program.append( SeqResetObject(attdict, content, extra, self.context) ) + + def compile_seqDefault(self, attdict, content, extra, program): + program.append( SeqDefaultObject(attdict, content, extra, self.context) ) + + def compile_para(self, attdict, content, extra, program, stylename = "para.defaultStyle"): + if attdict is None: + attdict = {} + context = self.context + stylename = attdict.get("style", stylename) + style = context[stylename] + newstyle = SimpleStyle(name="rml2pdf internal embedded style", parent=style) + newstyle.addAttributes(attdict) + bulletText = attdict.get("bulletText", None) + mystyle = self.style1 + thepara = Para(newstyle, content, context=context, bulletText=bulletText) + # possible ref loop on context, break later + # now compile it and add it to the program + mybaseindent = self.baseindent + self.baseindent = thepara.baseindent = mystyle.leftIndent + self.baseindent + thepara.linearize(program=program) + program.append( ("nextLine", 0) ) + self.baseindent = mybaseindent + +class bulletMaker: + def __init__(self, tagname, atts, context): + self.tagname = tagname + #print "context is", context + style = "li.defaultStyle" + self.style = style = atts.get("style", style) + typ = {"ul": "disc", "ol": "1", "dl": None}[tagname] + #print tagname, "bulletmaker type is", typ + self.typ =typ = atts.get("type", typ) + #print tagname, "bulletmaker type is", typ + if "leftIndent" not in atts: + # get the style so you can choose an indent length + thestyle = context[style] + from reportlab.pdfbase.pdfmetrics import stringWidth + size = thestyle.fontSize + indent = stringWidth("XXX", "Courier", size) + atts["leftIndent"] = str(indent) + self.count = 0 + self._first = 1 + + def makeBullet(self, atts, bl=None): + if not self._first: + # forget space before for non-first elements + atts["spaceBefore"] = "0" + else: + self._first = 0 + typ = self.typ + tagname = self.tagname + if bl is None: + if tagname=="ul": + if typ=="disc": bl = chr(109) + elif typ=="circle": bl = chr(108) + elif typ=="square": bl = chr(110) + else: + raise ValueError("unordered list type %s not implemented" % repr(typ)) + if "bulletFontName" not in atts: + atts["bulletFontName"] = "ZapfDingbats" + elif tagname=="ol": + if 'value' in atts: + self.count = int(atts['value']) + else: + self.count += 1 + if typ=="1": bl = str(self.count) + elif typ=="a": + theord = ord("a")+self.count-1 + bl = chr(theord) + elif typ=="A": + theord = ord("A")+self.count-1 + bl = chr(theord) + else: + raise ValueError("ordered bullet type %s not implemented" % repr(typ)) + else: + raise ValueError("bad tagname "+repr(tagname)) + if "bulletText" not in atts: + atts["bulletText"] = bl + if "style" not in atts: + atts["style"] = self.style + +class EvalStringObject: + "this will only work if rml2pdf is present" + + tagname = "evalString" + + def __init__(self, attdict, content, extra, context): + if not attdict: + attdict = {} + self.attdict = attdict + self.content = content + self.context = context + self.extra = extra + + def getOp(self, tuple, engine): + from rlextra.rml2pdf.rml2pdf import Controller + #print "tuple", tuple + op = self.op = Controller.processTuple(tuple, self.context, {}) + return op + + def width(self, engine): + from reportlab.pdfbase.pdfmetrics import stringWidth + content = self.content + if not content: + content = [] + tuple = (self.tagname, self.attdict, content, self.extra) + op = self.op = self.getOp(tuple, engine) + #print op.__class__ + #print op.pcontent + #print self + s = str(op) + return stringWidth(s, engine.fontName, engine.fontSize) + + def execute(self, engine, textobject, canvas): + textobject.textOut(str(self.op)) + +class SeqObject(EvalStringObject): + + def getOp(self, tuple, engine): + from reportlab.lib.sequencer import getSequencer + globalsequencer = getSequencer() + attr = self.attdict + #if it has a template, use that; otherwise try for id; + #otherwise take default sequence + if 'template' in attr: + templ = attr['template'] + op = self.op = templ % globalsequencer + return op + elif 'id' in attr: + id = attr['id'] + else: + id = None + op = self.op = globalsequencer.nextf(id) + return op + +class NameObject(EvalStringObject): + tagname = "name" + def execute(self, engine, textobject, canvas): + pass # name doesn't produce any output + +class SeqDefaultObject(NameObject): + + def getOp(self, tuple, engine): + from reportlab.lib.sequencer import getSequencer + globalsequencer = getSequencer() + attr = self.attdict + try: + default = attr['id'] + except KeyError: + default = None + globalsequencer.setDefaultCounter(default) + self.op = "" + return "" + +class SeqResetObject(NameObject): + + def getOp(self, tuple, engine): + from reportlab.lib.sequencer import getSequencer + globalsequencer = getSequencer() + attr = self.attdict + try: + id = attr['id'] + except KeyError: + id = None + try: + base = int(attr['base']) + except: + base=0 + globalsequencer.reset(id, base) + self.op = "" + return "" + +class GetNameObject(EvalStringObject): + tagname = "getName" + +class PageNumberObject: + + def __init__(self, example="XXX"): + self.example = example # XXX SHOULD ADD THE ABILITY TO PASS IN EXAMPLES + + def width(self, engine): + from reportlab.pdfbase.pdfmetrics import stringWidth + return stringWidth(self.example, engine.fontName, engine.fontSize) + + def execute(self, engine, textobject, canvas): + n = canvas.getPageNumber() + textobject.textOut(str(n)) + +### this should be moved into rml2pdf +def EmbedInRml2pdf(): + "make the para the default para implementation in rml2pdf" + from rlextra.rml2pdf.rml2pdf import MapNode, Controller # may not need to use superclass? + global paraMapper, theParaMapper, ulMapper + + class paraMapper(MapNode): + #stylename = "para.defaultStyle" + def translate(self, nodetuple, controller, context, overrides): + (tagname, attdict, content, extra) = nodetuple + stylename = tagname+".defaultStyle" + stylename = attdict.get("style", stylename) + style = context[stylename] + mystyle = SimpleStyle(name="rml2pdf internal style", parent=style) + mystyle.addAttributes(attdict) + bulletText = attdict.get("bulletText", None) + # can we use the fast implementation? + result = None + if not bulletText and len(content)==1: + text = content[0] + if isinstance(text,str) and "&" not in text: + result = FastPara(mystyle, text) + if result is None: + result = Para(mystyle, content, context=context, bulletText=bulletText) # possible ref loop on context, break later + return result + + theParaMapper = paraMapper() + + class ulMapper(MapNode): + # wrap in a default para and let the para do it + def translate(self, nodetuple, controller, context, overrides): + thepara = ("para", {}, [nodetuple], None) + return theParaMapper.translate(thepara, controller, context, overrides) + + # override rml2pdf interpreters (should be moved to rml2pdf) + theListMapper = ulMapper() + Controller["ul"] = theListMapper + Controller["ol"] = theListMapper + Controller["dl"] = theListMapper + Controller["para"] = theParaMapper + Controller["h1"] = theParaMapper + Controller["h2"] = theParaMapper + Controller["h3"] = theParaMapper + Controller["title"] = theParaMapper + +def handleSpecialCharacters(engine, text, program=None): + from reportlab.platypus.paraparser import greeks + from string import whitespace + standard={'lt':'<', 'gt':'>', 'amp':'&'} + # add space prefix if space here + if text[0:1] in whitespace: + program.append(" ") + #print "handling", repr(text) + # shortcut + if 0 and "&" not in text: + result = [] + for x in text.split(): + result.append(x+" ") + if result: + last = result[-1] + if text[-1:] not in whitespace: + result[-1] = last.strip() + program.extend(result) + return program + if program is None: + program = [] + amptext = text.split("&") + first = 1 + lastfrag = amptext[-1] + for fragment in amptext: + if not first: + # check for special chars + semi = fragment.find(";") + if semi>0: + name = fragment[:semi] + if name[0]=='#': + try: + if name[1] == 'x': + n = int(name[2:], 16) + else: + n = int(name[1:]) + except ValueError: + n = -1 + if n>=0: + fragment = chr(n)+fragment[semi+1:] + else: + fragment = "&"+fragment + elif name in standard: + s = standard[name] + if isinstance(fragment,bytes): + s = s.decode('utf8') + fragment = s+fragment[semi+1:] + elif name in greeks: + s = greeks[name] + if isinstance(fragment,bytes): + s = s.decode('utf8') + fragment = s+fragment[semi+1:] + else: + # add back the & + fragment = "&"+fragment + else: + # add back the & + fragment = "&"+fragment + # add white separated components of fragment followed by space + sfragment = fragment.split() + for w in sfragment[:-1]: + program.append(w+" ") + # does the last one need a space? + if sfragment and fragment: + # reader 3 used to go nuts if you don't special case the last frag, but it's fixed? + if fragment[-1] in whitespace: # or fragment==lastfrag: + program.append( sfragment[-1]+" " ) + else: + last = sfragment[-1].strip() + if last: + #print "last is", repr(last) + program.append( last ) + first = 0 + #print "HANDLED", program + return program + +def Paragraph(text, style, bulletText=None, frags=None, context=None): + """ Paragraph(text, style, bulletText=None) + intended to be like a platypus Paragraph but better. + """ + # if there is no & or < in text then use the fast paragraph + if "&" not in text and "<" not in text: + return FastPara(style, simpletext=text) + else: + # use the fully featured one. + from reportlab.lib import rparsexml + parsedpara = rparsexml.parsexmlSimple(text,entityReplacer=None) + return Para(style, parsedText=parsedpara, bulletText=bulletText, state=None, context=context) + +class UnderLineHandler: + def __init__(self, color=None): + self.color = color + def start_at(self, x,y, para, canvas, textobject): + self.xStart = x + self.yStart = y + def end_at(self, x, y, para, canvas, textobject): + offset = para.fontSize/8.0 + canvas.saveState() + color = self.color + if self.color is None: + color = para.fontColor + canvas.setStrokeColor(color) + canvas.line(self.xStart, self.yStart-offset, x,y-offset) + canvas.restoreState() + +UNDERLINE = UnderLineHandler() + +class HotLink(UnderLineHandler): + + def __init__(self, url): + self.url = url + + def end_at(self, x, y, para, canvas, textobject): + fontsize = para.fontSize + rect = [self.xStart, self.yStart, x,y+fontsize] + if debug: + print("LINKING RECTANGLE", rect) + #canvas.rect(self.xStart, self.yStart, x-self.xStart,y+fontsize-self.yStart, stroke=1) + self.link(rect, canvas) + + def link(self, rect, canvas): + canvas.linkURL(self.url, rect, relative=1) + +class InternalLink(HotLink): + + def link(self, rect, canvas): + destinationname = self.url + contents = "" + canvas.linkRect(contents, destinationname, rect, Border="[0 0 0]") + +class DefDestination(HotLink): + + defined = 0 + + def link(self, rect, canvas): + destinationname = self.url + if not self.defined: + [x, y, x1, y1] = rect + canvas.bookmarkHorizontal(destinationname, x, y1) # use the upper y + self.defined = 1 + +def splitspace(text): + # split on spacing but include spaces at element ends + stext = text.split() + result = [] + for e in stext: + result.append(e+" ") + return result + + +testparagraph = """ +This is Text. +This is bold text. +This is Text. +This is italic text. + +
                  +
                • this is an element at 1 +more text and even more text & on and on and so forth +more text and even more text and on & on and so forth +more text and even more text and on and on & so forth +more text and even more text and on and on and so forth +more text and even more text and on and on and so forth --> +more text monospaced and back to normal + +
                    +
                  • this is an element at 2 + +more text and even more text and on and on and so forth +more text and even more text and on and on and so forth + +
                      +
                    • this is an element at 3 + +more text and even more text and on and on and so forth + + +
                      +
                      frogs
                      Little green slimy things. Delicious with garlic
                      +
                      kittens
                      cute, furry, not edible
                      +
                      bunnies
                      cute, furry,. Delicious with garlic
                      +
                      + +more text and even more text and on and on and so forth + +
                        +
                      • this is an element at 4 +more text and even more text and on and on and so forth +
                      • +
                      • this is an element at4 +more text and even more text and on and on and so forth +
                      • +
                      +more text and even more text and on and on and so forth +more text and even more text and on and on and so forth + +
                    • +
                    +more text and even more text and on and on and so forth +more text and even more text and on and on and so forth +
                  • +
                  +UNDERLINED more text and even more text and on and on and so forth +more text and even more text and on and on and so forth + +
                    +
                  1. first element of the alpha list + +
                      +
                    • first element of the square unnumberred list
                    • + +
                    • second element of the unnumberred list
                    • + +
                    • third element of the unnumberred list + third element of the unnumberred list + third element of the unnumberred list + third element of the unnumberred list + third element of the unnumberred list + third element of the unnumberred list + third element of the unnumberred list +
                    • + +
                    • fourth element of the unnumberred list
                    • + +
                    + +
                  2. + +
                  3. second element of the alpha list
                  4. + +
                  5. third element of the alpha list + third element of the unnumberred list &#33; --> ! + third element of the unnumberred list &#8704; --> ∀ + third element of the unnumberred list &exist; --> ∃ + third element of the unnumberred list + third element of the unnumberred list + third element of the unnumberred list +
                  6. + +
                  7. fourth element of the alpha list
                  8. + +
                  + + +
                • +
                +""" + +testparagraph1 = """ +goto www.reportlab.com. + + + +Red letter. thisisareallylongword andsoisthis andthisislonger +justified text paragraph example with a pound sign \xc2\xa3 +justified text paragraph example +justified text paragraph example + + + +Green letter. +centered text paragraph example +centered text paragraph example +centered text paragraph example + + +Blue letter. +right justified text paragraph example +right justified text paragraph example +right justified text paragraph example + + +Yellow letter. +left justified text paragraph example +left justified text paragraph example +left justified text paragraph example + + +""" + +def test2(canv,testpara): + #print test_program; return + from reportlab.lib.units import inch + from reportlab.lib.styles import ParagraphStyle + from reportlab.lib import rparsexml + parsedpara = rparsexml.parsexmlSimple(testpara,entityReplacer=None) + S = ParagraphStyle("Normal", None) + P = Para(S, parsedpara) + (w, h) = P.wrap(5*inch, 10*inch) + print("wrapped as", (h,w)) + canv.saveState() + canv.translate(1*inch, 1*inch) + canv.rect(0,0,5*inch,10*inch, fill=0, stroke=1) + P.canv = canv + canv.saveState() + P.draw() + canv.restoreState() + canv.setStrokeColorRGB(1, 0, 0) + #canv.translate(0, 3*inch) + canv.rect(0,0,w,h, fill=0, stroke=1) + canv.restoreState() + canv.showPage() + +testlink = HotLink("http://www.reportlab.com") + +test_program = [ + ('push',), + ('indent', 100), + ('rightIndent', 200), + ('bullet', 'very long bullet', 50, 'Courier', 14), + ('align', TA_CENTER), + ('face', _baseFontName), + ('size', 12), + ('leading', 14), + ] + splitspace("This is the first segment of the first paragraph.") + [ + ('lineOperation', testlink), + ]+splitspace("HOTLINK This is the first segment of the first paragraph. This is the first segment of the first paragraph. This is the first segment of the first paragraph. This is the first segment of the first paragraph. ") + [ + ('endLineOperation', testlink), + ('nextLine', 0), + ('align', TA_LEFT), + ('bullet', 'Bullet', 10, 'Courier', 8), + ('face', _baseFontName), + ('size', 12), + ('leading', 14), + ] + splitspace("This is the SECOND!!! segment of the first paragraph. This is the first segment of the first paragraph. This is the first segment of the first paragraph. This is the first segment of the first paragraph. This is the first segment of the first paragraph. ") + [ + ('nextLine', 0), + ('align', TA_JUSTIFY), + ('bullet', 'Bullet not quite as long this time', 50, 'Courier', 8), + ('face', "Helvetica-Oblique"), + ('size', 12), + ('leading', 14), + ('push',), + ('color', 'red'), + ] + splitspace("This is the THIRD!!! segment of the first paragraph." + ) + [ + ('lineOperation', UNDERLINE), + ] + splitspace("This is the first segment of the first paragraph. This is the first segment of the first paragraph. This is the first segment of the first paragraph. This is the first segment of the first paragraph. ") + [ + ('endLineOperation', UNDERLINE), + ('rise', 5), + "raised ", "text ", + ('rise', -10), + "lowered ", "text ", + ('rise', 5), + "normal ", "text ", + ('pop',), + ('indent', 100), + ('rightIndent', 50), + ('nextLine', 0), + ('align', TA_RIGHT), + ('bullet', 'O', 50, 'Courier', 14), + ('face', "Helvetica"), + ('size', 12), + ('leading', 14), + ] + splitspace("And this is the remainder of the paragraph indented further. a a a a a a a a And this is the remainder of the paragraph indented further. a a a a a a a a And this is the remainder of the paragraph indented further. a a a a a a a a And this is the remainder of the paragraph indented further. a a a a a a a a And this is the remainder of the paragraph indented further. a a a a a a a a And this is the remainder of the paragraph indented further. a a a a a a a a And this is the remainder of the paragraph indented further. a a a a a a a a ") + [ + ('pop',), + ('nextLine', 0),] + +def test(): + from pprint import pprint + #print test_program; return + from reportlab.pdfgen import canvas + from reportlab.lib.units import inch + fn = "paratest0.pdf" + c = canvas.Canvas(fn) + test2(c,testparagraph) + test2(c,testparagraph1) + if 1: + remainder = test_program + test_program + test_program + laststate = {} + while remainder: + print("NEW PAGE") + c.translate(inch, 8*inch) + t = c.beginText() + t.setTextOrigin(0,0) + p = paragraphEngine() + p.resetState(laststate) + p.x = 0 + p.y = 0 + maxwidth = 7*inch + maxheight = 500 + (formattedprogram, remainder, laststate, height) = p.format(maxwidth, maxheight, remainder) + if debug: + pprint( formattedprogram )#; return + laststate = p.runOpCodes(formattedprogram, c, t) + c.drawText(t) + c.showPage() + print("="*30, "x=", laststate["x"], "y=", laststate["y"]) + c.save() + print(fn) + +if __name__=="__main__": + test()