__main__.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # SPDX-FileCopyrightText: 2024 geisserml <geisserml@gmail.com>
  2. # SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
  3. import sys
  4. import argparse
  5. import importlib
  6. from pypdfium2.version import PYPDFIUM_INFO, PDFIUM_INFO
  7. from pypdfium2._cli._parsers import setup_logging
  8. from pypdfium2_raw.bindings import _libs_info
  9. pdfium_path = _libs_info["pdfium"]["path"]
  10. SubCommands = {
  11. "arrange": "rearrange/merge documents",
  12. "attachments": "list/extract/edit embedded files",
  13. "extract-images": "extract images",
  14. "extract-text": "extract text",
  15. "imgtopdf": "convert images to PDF",
  16. "pageobjects": "print info on page objects",
  17. "pdfinfo": "print info on document and pages",
  18. "render": "rasterize pages",
  19. "tile": "tile pages (N-up)",
  20. "toc": "print table of contents",
  21. }
  22. CmdToModule = {n: importlib.import_module(f"pypdfium2._cli.{n.replace('-', '_')}") for n in SubCommands}
  23. def get_parser():
  24. main_parser = argparse.ArgumentParser(
  25. prog = "pypdfium2",
  26. formatter_class = argparse.RawTextHelpFormatter,
  27. description = "Command line interface to the pypdfium2 library (Python binding to PDFium)",
  28. )
  29. main_parser.add_argument(
  30. "--version", "-v",
  31. action = "version",
  32. version = f"pypdfium2 {PYPDFIUM_INFO}\n" f"pdfium {PDFIUM_INFO} at {pdfium_path}"
  33. )
  34. subparsers = main_parser.add_subparsers(dest="subcommand")
  35. for name, help in SubCommands.items():
  36. subparser = subparsers.add_parser(name, description=help, help=help)
  37. CmdToModule[name].attach(subparser)
  38. return main_parser
  39. def api_main(raw_args=sys.argv[1:]):
  40. parser = get_parser()
  41. args = parser.parse_args(raw_args)
  42. if not args.subcommand:
  43. parser.print_help()
  44. return
  45. CmdToModule[args.subcommand].main(args)
  46. def cli_main():
  47. setup_logging()
  48. api_main()
  49. if __name__ == "__main__":
  50. cli_main()