render_docx_pages.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  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. command_text = " ".join(command)
  20. detail = f"{command_text} exited with status {exc.returncode}"
  21. if stderr:
  22. detail = f"{detail}: {stderr}"
  23. raise RuntimeError(detail) from exc
  24. def convert_to_pdf(input_path: Path, output_dir: Path) -> Path:
  25. office = find_tool("soffice", "libreoffice")
  26. if not office:
  27. raise RuntimeError("Missing LibreOffice executable (soffice/libreoffice)")
  28. with tempfile.TemporaryDirectory(prefix="docx-lo-profile-") as profile_dir:
  29. command = [
  30. office,
  31. f"-env:UserInstallation=file://{profile_dir}",
  32. "--headless",
  33. "--invisible",
  34. "--norestore",
  35. "--convert-to",
  36. "pdf",
  37. "--outdir",
  38. str(output_dir),
  39. str(input_path),
  40. ]
  41. run_checked(command)
  42. pdf_path = output_dir / f"{input_path.stem}.pdf"
  43. if not pdf_path.exists():
  44. raise RuntimeError(f"LibreOffice did not produce {pdf_path.name}")
  45. return pdf_path
  46. def normalize_rendered_pages(render_dir: Path) -> None:
  47. generated = sorted(render_dir.glob("page-*.png"))
  48. if not generated:
  49. raise RuntimeError("Render command finished without producing any page PNGs")
  50. for index, image_path in enumerate(generated, start=1):
  51. target = render_dir / f"page-{index}.png"
  52. if image_path != target:
  53. image_path.replace(target)
  54. def clear_output_pages(output_dir: Path) -> None:
  55. for image_path in output_dir.glob("page-*.png"):
  56. image_path.unlink()
  57. def publish_rendered_pages(render_dir: Path, output_dir: Path) -> None:
  58. clear_output_pages(output_dir)
  59. generated = sorted(render_dir.glob("page-*.png"))
  60. if not generated:
  61. raise RuntimeError("No rendered page PNGs were available to publish")
  62. for image_path in generated:
  63. image_path.replace(output_dir / image_path.name)
  64. def render_pdf_pages(pdf_path: Path, render_dir: Path, dpi: int) -> None:
  65. pdftoppm = find_tool("pdftoppm")
  66. if not pdftoppm:
  67. raise RuntimeError("Missing pdftoppm")
  68. prefix = render_dir / "page"
  69. command = [
  70. pdftoppm,
  71. "-r",
  72. str(dpi),
  73. "-png",
  74. str(pdf_path),
  75. str(prefix),
  76. ]
  77. run_checked(command)
  78. normalize_rendered_pages(render_dir)
  79. def render_full_fidelity(input_path: Path, output_dir: Path, dpi: int) -> None:
  80. with tempfile.TemporaryDirectory(prefix="docx-render-") as temp_dir:
  81. render_dir = Path(temp_dir)
  82. pdf_path = convert_to_pdf(input_path, render_dir)
  83. render_pdf_pages(pdf_path, render_dir, dpi)
  84. publish_rendered_pages(render_dir, output_dir)
  85. def main() -> int:
  86. parser = argparse.ArgumentParser(description="Render a Word-style document into page PNGs.")
  87. parser.add_argument("input_path", help="Path to the input .docx/.doc/.rtf/.odt file")
  88. parser.add_argument(
  89. "--output-dir",
  90. required=True,
  91. help="Directory for rendered page images",
  92. )
  93. parser.add_argument(
  94. "--dpi",
  95. type=int,
  96. default=150,
  97. help="Rasterization DPI for generated PNG pages when pdftoppm is available",
  98. )
  99. args = parser.parse_args()
  100. input_path = Path(args.input_path).expanduser().resolve()
  101. output_dir = Path(args.output_dir).expanduser().resolve()
  102. output_dir.mkdir(parents=True, exist_ok=True)
  103. if not input_path.exists():
  104. raise RuntimeError(f"Input file does not exist: {input_path}")
  105. office = find_tool("soffice", "libreoffice")
  106. pdftoppm = find_tool("pdftoppm")
  107. if not office:
  108. raise RuntimeError("Missing LibreOffice executable (soffice/libreoffice)")
  109. if not pdftoppm:
  110. raise RuntimeError("Missing pdftoppm; full-fidelity page rendering cannot proceed")
  111. render_full_fidelity(input_path, output_dir, args.dpi)
  112. print(f"Rendered {input_path.name} to {output_dir} using libreoffice+pdftoppm")
  113. return 0
  114. if __name__ == "__main__":
  115. try:
  116. raise SystemExit(main())
  117. except Exception as exc: # pragma: no cover - CLI error path
  118. print(f"render_docx_pages.py failed: {exc}", file=sys.stderr)
  119. raise SystemExit(1)