_library_scope.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. # SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
  2. # SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
  3. import sys
  4. import atexit
  5. import pypdfium2.raw as pdfium_c
  6. import pypdfium2.internal as pdfium_i
  7. def init_lib():
  8. assert not pdfium_i.LIBRARY_AVAILABLE
  9. if pdfium_i.DEBUG_AUTOCLOSE: # pragma: no cover
  10. # FIXME not shown on auto-init, because DEBUG_AUTOCLOSE can only be set on the caller side after pypdfium2 has been imported...
  11. print("Initialize PDFium", file=sys.stderr)
  12. # PDFium init API may change in the future: https://crbug.com/pdfium/1446
  13. # NOTE Technically, FPDF_InitLibrary() would be sufficient for our purposes, but pdfium docs say "This will be deprecated in the future", so don't use it to be on the safe side. Also, avoid experimental config versions that might not be promoted to stable.
  14. config = pdfium_c.FPDF_LIBRARY_CONFIG(
  15. version = 2,
  16. m_pUserFontPaths = None,
  17. m_pIsolate = None,
  18. m_v8EmbedderSlot = 0,
  19. # m_pPlatform = None, # v3
  20. # m_RendererType = pdfium_c.FPDF_RENDERERTYPE_AGG, # v4
  21. )
  22. pdfium_c.FPDF_InitLibraryWithConfig(config)
  23. pdfium_i.LIBRARY_AVAILABLE.value = True
  24. def destroy_lib(): # pragma: no cover
  25. assert pdfium_i.LIBRARY_AVAILABLE
  26. if pdfium_i.DEBUG_AUTOCLOSE:
  27. pdfium_i._safe_debug("Destroy PDFium")
  28. pdfium_c.FPDF_DestroyLibrary()
  29. pdfium_i.LIBRARY_AVAILABLE.value = False
  30. # Load pdfium
  31. init_lib()
  32. # Register an exit handler that will free pdfium
  33. # Trust in Python to call exit handlers only after all objects have been finalized
  34. atexit.register(destroy_lib)