docx_to_pdf.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import argparse
  2. import shutil
  3. import subprocess
  4. import sys
  5. import tempfile
  6. from pathlib import Path
  7. from typing import Optional, Sequence
  8. def find_tool(*names: str) -> Optional[str]:
  9. for name in names:
  10. resolved = shutil.which(name)
  11. if resolved:
  12. return resolved
  13. return None
  14. def run_checked(command: Sequence[str]) -> None:
  15. try:
  16. subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  17. except subprocess.CalledProcessError as exc:
  18. stderr = exc.stderr.decode("utf-8", errors="replace").strip()
  19. detail = f"{' '.join(command)} exited with status {exc.returncode}"
  20. if stderr:
  21. detail = f"{detail}: {stderr}"
  22. raise RuntimeError(detail) from exc
  23. def convert_to_pdf(input_path: Path, output_path: Path) -> None:
  24. office = find_tool("soffice", "libreoffice")
  25. if not office:
  26. raise RuntimeError("Missing LibreOffice executable (soffice/libreoffice)")
  27. output_path.parent.mkdir(parents=True, exist_ok=True)
  28. temp_pdf = output_path.parent / f"{input_path.stem}.pdf"
  29. if temp_pdf.exists():
  30. temp_pdf.unlink()
  31. if output_path.exists() and output_path != temp_pdf:
  32. output_path.unlink()
  33. with tempfile.TemporaryDirectory(prefix="docx-lo-profile-") as profile_dir:
  34. command = [
  35. office,
  36. f"-env:UserInstallation=file://{profile_dir}",
  37. "--headless",
  38. "--invisible",
  39. "--norestore",
  40. "--convert-to",
  41. "pdf",
  42. "--outdir",
  43. str(output_path.parent),
  44. str(input_path),
  45. ]
  46. run_checked(command)
  47. if not temp_pdf.exists():
  48. raise RuntimeError(f"LibreOffice did not produce {temp_pdf.name}")
  49. if temp_pdf != output_path:
  50. temp_pdf.replace(output_path)
  51. def main() -> int:
  52. parser = argparse.ArgumentParser(description="Convert a DOCX file into a rendered PDF via LibreOffice.")
  53. parser.add_argument("--input", required=True, help="Path to the input .docx file")
  54. parser.add_argument("--output", required=True, help="Path to the output .pdf file")
  55. args = parser.parse_args()
  56. input_path = Path(args.input).expanduser().resolve()
  57. output_path = Path(args.output).expanduser().resolve()
  58. if not input_path.exists():
  59. raise RuntimeError(f"Input file does not exist: {input_path}")
  60. if input_path.suffix.lower() != ".docx":
  61. raise RuntimeError("docx_to_pdf.py currently supports .docx only")
  62. convert_to_pdf(input_path, output_path)
  63. print(f"Wrote {output_path}")
  64. return 0
  65. if __name__ == "__main__":
  66. try:
  67. raise SystemExit(main())
  68. except Exception as exc: # pragma: no cover - CLI error path
  69. print(f"docx_to_pdf.py failed: {exc}", file=sys.stderr)
  70. raise SystemExit(1)