office_to_pdf.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import os
  2. import subprocess
  3. import platform
  4. from pathlib import Path
  5. class ConvertToPdfError(Exception):
  6. def __init__(self, msg):
  7. self.msg = msg
  8. super().__init__(self.msg)
  9. # Chinese font list
  10. REQUIRED_CHS_FONTS = ['SimSun', 'Microsoft YaHei', 'Noto Sans CJK SC']
  11. def check_fonts_installed():
  12. """Check if required Chinese fonts are installed."""
  13. system_type = platform.system()
  14. if system_type == 'Windows':
  15. # Windows: check fonts via registry or system font folder
  16. font_dir = Path("C:/Windows/Fonts")
  17. installed_fonts = [f.name for f in font_dir.glob("*.ttf")]
  18. if any(font for font in REQUIRED_CHS_FONTS if any(font in f for f in installed_fonts)):
  19. return True
  20. raise EnvironmentError(
  21. f"Missing Chinese font. Please install at least one of: {', '.join(REQUIRED_CHS_FONTS)}"
  22. )
  23. else:
  24. # Linux/macOS: use fc-list
  25. try:
  26. output = subprocess.check_output(['fc-list', ':lang=zh'], encoding='utf-8')
  27. for font in REQUIRED_CHS_FONTS:
  28. if font in output:
  29. return True
  30. raise EnvironmentError(
  31. f"Missing Chinese font. Please install at least one of: {', '.join(REQUIRED_CHS_FONTS)}"
  32. )
  33. except Exception as e:
  34. raise EnvironmentError(f"Font detection failed. Please install 'fontconfig' and fonts: {str(e)}")
  35. def get_soffice_command():
  36. """Return the path to LibreOffice's soffice executable depending on the platform."""
  37. if platform.system() == 'Windows':
  38. possible_paths = [
  39. Path("C:/Program Files/LibreOffice/program/soffice.exe"),
  40. Path("C:/Program Files (x86)/LibreOffice/program/soffice.exe")
  41. ]
  42. for path in possible_paths:
  43. if path.exists():
  44. return str(path)
  45. raise ConvertToPdfError(
  46. "LibreOffice not found. Please install LibreOffice and ensure soffice.exe is located in a standard path."
  47. )
  48. else:
  49. return 'soffice' # Assume it's in PATH on Linux/macOS
  50. def convert_file_to_pdf(input_path, output_dir):
  51. """Convert a single document (ppt, doc, etc.) to PDF."""
  52. if not os.path.isfile(input_path):
  53. raise FileNotFoundError(f"The input file {input_path} does not exist.")
  54. os.makedirs(output_dir, exist_ok=True)
  55. check_fonts_installed()
  56. soffice_cmd = get_soffice_command()
  57. cmd = [
  58. soffice_cmd,
  59. '--headless',
  60. '--norestore',
  61. '--invisible',
  62. '--convert-to', 'pdf',
  63. '--outdir', str(output_dir),
  64. str(input_path)
  65. ]
  66. process = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  67. if process.returncode != 0:
  68. raise ConvertToPdfError(f"LibreOffice convert failed: {process.stderr.decode()}")