unsupported.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
  2. # SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
  3. __all__ = ("PdfUnspHandler", )
  4. import atexit
  5. import logging
  6. import pypdfium2.raw as pdfium_c
  7. import pypdfium2.internal as pdfium_i
  8. lib_logger = logging.getLogger("pypdfium2")
  9. class PdfUnspHandler:
  10. """
  11. Unsupported feature handler helper class.
  12. Attributes:
  13. handlers (dict[str, typing.Callable]):
  14. A dictionary of named handler functions to be called with an unsupported code (:attr:`FPDF_UNSP_*`) when PDFium detects an unsupported feature.
  15. """
  16. def __init__(self):
  17. self.handlers = {}
  18. self._config = None
  19. def __call__(self, _, type):
  20. for handler in self.handlers.values():
  21. handler(type)
  22. def setup(self, add_default=True):
  23. """
  24. Attach the handler to PDFium, and register an exit function to keep the object alive for the rest of the session.
  25. Parameters:
  26. add_default (bool):
  27. If True, add a default callback that will log unsupported features as warning.
  28. """
  29. self._config = pdfium_c.UNSUPPORT_INFO(version=1)
  30. pdfium_i.set_callback(self._config, "FSDK_UnSupport_Handler", self)
  31. pdfium_c.FSDK_SetUnSpObjProcessHandler(self._config)
  32. atexit.register(self._keep)
  33. if add_default:
  34. self.handlers["default"] = PdfUnspHandler._default
  35. def _keep(self):
  36. id(self.handlers)
  37. id(self._config)
  38. @staticmethod
  39. def _default(type):
  40. lib_logger.warning(f"Unsupported PDF feature: {pdfium_i.UnsupportedInfoToStr.get(type)}")