__main__.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # SPDX-FileCopyrightText: 2026 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
  9. SubCommands = {
  10. "arrange": "Rearrange/merge documents",
  11. "attachments": "List/extract/edit embedded files",
  12. "extract-images": "Extract images",
  13. "extract-text": "Extract text",
  14. "imgtopdf": "Convert images to PDF",
  15. "pageobjects": "Print info on pageobjects",
  16. "pdfinfo": "Print info on document and pages",
  17. "render": "Rasterize pages",
  18. "tile": "Tile pages (N-up)",
  19. "toc": "Print table of contents",
  20. }
  21. CmdToModule = {n: importlib.import_module(f"pypdfium2._cli.{n.replace('-', '_')}") for n in SubCommands}
  22. def get_parser():
  23. main_parser = argparse.ArgumentParser(
  24. prog = "pypdfium2",
  25. formatter_class = argparse.RawTextHelpFormatter,
  26. description = "Command line interface to the pypdfium2 library (Python binding to PDFium)",
  27. )
  28. main_parser.add_argument(
  29. "--version", "-v",
  30. action = "version",
  31. version = f"pypdfium2 {PYPDFIUM_INFO}\n" f"pdfium {PDFIUM_INFO} at {_libs['pdfium']._name}"
  32. )
  33. subparsers = main_parser.add_subparsers(dest="subcommand")
  34. for name, help in SubCommands.items():
  35. mod = CmdToModule[name]
  36. desc = getattr(mod, "PARSER_DESC", None)
  37. desc = (help + "\n\n" + desc) if desc else help
  38. subparser = subparsers.add_parser(
  39. name, help=help, description=desc,
  40. formatter_class=argparse.RawTextHelpFormatter,
  41. )
  42. mod.attach(subparser)
  43. return main_parser
  44. def api_main(raw_args=sys.argv[1:]):
  45. parser = get_parser()
  46. args = parser.parse_args(raw_args)
  47. if not args.subcommand:
  48. parser.print_help()
  49. return
  50. CmdToModule[args.subcommand].main(args)
  51. def cli_main():
  52. setup_logging()
  53. api_main()
  54. if __name__ == "__main__":
  55. cli_main()