_library_scope.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. # SPDX-FileCopyrightText: 2024 geisserml <geisserml@gmail.com>
  2. # SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
  3. import atexit
  4. import os, sys
  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:
  10. print("Initialize PDFium (auto)", file=sys.stderr)
  11. # PDFium init API may change in the future: https://crbug.com/pdfium/1446
  12. # NOTE Technically, FPDF_InitLibrary() would be sufficient for our purposes, but since it's formally marked for deprecation, don't use it to be on the safe side. Also, avoid experimental config versions that might not be promoted to stable.
  13. config = pdfium_c.FPDF_LIBRARY_CONFIG(
  14. version = 2,
  15. m_pUserFontPaths = None,
  16. m_pIsolate = None,
  17. m_v8EmbedderSlot = 0,
  18. # m_pPlatform = None, # v3
  19. # m_RendererType = pdfium_c.FPDF_RENDERERTYPE_AGG, # v4
  20. )
  21. pdfium_c.FPDF_InitLibraryWithConfig(config)
  22. pdfium_i.LIBRARY_AVAILABLE.value = True
  23. def destroy_lib():
  24. assert pdfium_i.LIBRARY_AVAILABLE
  25. if pdfium_i.DEBUG_AUTOCLOSE:
  26. # use os.write() rather than print() to avoid "reentrant call" exceptions on shutdown (see https://stackoverflow.com/q/75367828/15547292)
  27. os.write(sys.stderr.fileno(), b"Destroy PDFium (auto)\n")
  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)