docx_create.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. #!/usr/bin/env python3
  2. # MIT License. Part of the Hermes docx skill.
  3. """Create a .docx document from a JSON spec.
  4. Usage: docx_create.py spec.json output.docx
  5. Run with --help for the spec format summary.
  6. Spec (JSON object):
  7. {
  8. "page": {"width_mm": 210, "height_mm": 297,
  9. "margins_mm": {"top": 25, "bottom": 25, "left": 20, "right": 20}},
  10. "header": "text shown in page header",
  11. "footer": "text shown in page footer",
  12. "styles": [{"name": "MyStyle", "base": "Normal", "font": "Arial",
  13. "size_pt": 12, "bold": true, "color": "1F4E79"}],
  14. "blocks": [
  15. {"type": "heading", "text": "Title", "level": 1},
  16. {"type": "paragraph", "style": "MyStyle", "runs": [
  17. {"text": "plain "}, {"text": "bold", "bold": true},
  18. {"text": " italic", "italic": true},
  19. {"text": " under", "underline": true}]},
  20. {"type": "paragraph", "text": "shortcut: single plain run"},
  21. {"type": "bullet_list", "items": ["a", "b"]},
  22. {"type": "numbered_list", "items": ["one", "two"]},
  23. {"type": "table", "header": ["Col1", "Col2"],
  24. "rows": [["1", "2"]], "style": "Light Grid Accent 1",
  25. "header_bold": true},
  26. {"type": "image", "path": "pic.png", "width_mm": 60},
  27. {"type": "page_break"},
  28. {"type": "toc"}
  29. ]
  30. }
  31. Extras: `"footer_page_numbers": true` at the top level adds a
  32. "Page X of Y" footer built from PAGE/NUMPAGES fields, and a `toc` block
  33. inserts a Table of Contents field. Field results are computed by
  34. Word/LibreOffice when the file is opened, not by python-docx.
  35. """
  36. from __future__ import annotations
  37. import argparse
  38. import json
  39. import sys
  40. from docx import Document
  41. from docx.enum.style import WD_STYLE_TYPE
  42. from docx.enum.text import WD_BREAK
  43. from docx.shared import Mm, Pt, RGBColor
  44. def apply_page(doc, page: dict) -> None:
  45. section = doc.sections[0]
  46. if "width_mm" in page:
  47. section.page_width = Mm(page["width_mm"])
  48. if "height_mm" in page:
  49. section.page_height = Mm(page["height_mm"])
  50. m = page.get("margins_mm", {})
  51. for side in ("top", "bottom", "left", "right"):
  52. if side in m:
  53. setattr(section, f"{side}_margin", Mm(m[side]))
  54. def add_styles(doc, styles: list) -> None:
  55. for s in styles:
  56. style = doc.styles.add_style(s["name"], WD_STYLE_TYPE.PARAGRAPH)
  57. if s.get("base"):
  58. style.base_style = doc.styles[s["base"]]
  59. font = style.font
  60. if s.get("font"):
  61. font.name = s["font"]
  62. if s.get("size_pt"):
  63. font.size = Pt(s["size_pt"])
  64. if s.get("bold") is not None:
  65. font.bold = s["bold"]
  66. if s.get("italic") is not None:
  67. font.italic = s["italic"]
  68. if s.get("color"):
  69. font.color.rgb = RGBColor.from_string(s["color"])
  70. def add_runs(para, block: dict) -> None:
  71. runs = block.get("runs")
  72. if runs is None:
  73. runs = [{"text": block.get("text", "")}]
  74. for r in runs:
  75. run = para.add_run(r.get("text", ""))
  76. if r.get("bold"):
  77. run.bold = True
  78. if r.get("italic"):
  79. run.italic = True
  80. if r.get("underline"):
  81. run.underline = True
  82. def add_block(doc, block: dict) -> None:
  83. btype = block["type"]
  84. if btype == "heading":
  85. doc.add_heading(block.get("text", ""), level=block.get("level", 1))
  86. elif btype == "paragraph":
  87. para = doc.add_paragraph(style=block.get("style"))
  88. add_runs(para, block)
  89. elif btype == "bullet_list":
  90. for item in block.get("items", []):
  91. doc.add_paragraph(item, style="List Bullet")
  92. elif btype == "numbered_list":
  93. for item in block.get("items", []):
  94. doc.add_paragraph(item, style="List Number")
  95. elif btype == "table":
  96. header = block.get("header", [])
  97. rows = block.get("rows", [])
  98. ncols = len(header) if header else (len(rows[0]) if rows else 1)
  99. table = doc.add_table(rows=0, cols=ncols)
  100. table.style = block.get("style", "Table Grid")
  101. if header:
  102. cells = table.add_row().cells
  103. for i, text in enumerate(header):
  104. cells[i].text = str(text)
  105. if block.get("header_bold", True):
  106. for para in cells[i].paragraphs:
  107. for run in para.runs:
  108. run.bold = True
  109. for row in rows:
  110. cells = table.add_row().cells
  111. for i, text in enumerate(row):
  112. cells[i].text = str(text)
  113. elif btype == "image":
  114. width = Mm(block["width_mm"]) if block.get("width_mm") else None
  115. doc.add_picture(block["path"], width=width)
  116. elif btype == "page_break":
  117. doc.add_paragraph().add_run().add_break(WD_BREAK.PAGE)
  118. elif btype == "toc":
  119. from docx_edit import _add_field
  120. para = doc.add_paragraph()
  121. _add_field(para, r' TOC \o "1-3" \h \z \u ',
  122. "Table of contents - open in Word/LibreOffice and "
  123. "update fields to populate.")
  124. else:
  125. raise ValueError(f"unknown block type: {btype}")
  126. def main() -> int:
  127. ap = argparse.ArgumentParser(
  128. description="Create a .docx from a JSON spec.",
  129. epilog="See the module docstring (top of this file) for the spec format.")
  130. ap.add_argument("spec", help="path to JSON spec file")
  131. ap.add_argument("output", help="path of .docx to write")
  132. args = ap.parse_args()
  133. with open(args.spec, encoding="utf-8") as f:
  134. spec = json.load(f)
  135. doc = Document()
  136. if spec.get("page"):
  137. apply_page(doc, spec["page"])
  138. if spec.get("styles"):
  139. add_styles(doc, spec["styles"])
  140. if spec.get("header"):
  141. doc.sections[0].header.paragraphs[0].text = spec["header"]
  142. if spec.get("footer"):
  143. doc.sections[0].footer.paragraphs[0].text = spec["footer"]
  144. for block in spec.get("blocks", []):
  145. add_block(doc, block)
  146. if spec.get("footer_page_numbers"):
  147. from docx_edit import _add_field
  148. para = doc.sections[0].footer.paragraphs[0]
  149. para.add_run("Page ")
  150. _add_field(para, " PAGE ", "1")
  151. para.add_run(" of ")
  152. _add_field(para, " NUMPAGES ", "1")
  153. doc.save(args.output)
  154. print(json.dumps({"ok": True, "output": args.output,
  155. "blocks": len(spec.get("blocks", []))}))
  156. return 0
  157. if __name__ == "__main__":
  158. sys.exit(main())