build_doc.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import json
  2. from docx import Document
  3. from docx.shared import Pt, RGBColor, Cm
  4. from docx.enum.text import WD_ALIGN_PARAGRAPH
  5. from docx.oxml.ns import qn
  6. from docx.oxml import OxmlElement
  7. def add_divider(doc):
  8. p = doc.add_paragraph()
  9. pPr = p._p.get_or_add_pPr()
  10. pBdr = OxmlElement('w:pBdr')
  11. bottom = OxmlElement('w:bottom')
  12. bottom.set(qn('w:val'), 'single')
  13. bottom.set(qn('w:sz'), '4')
  14. bottom.set(qn('w:space'), '1')
  15. bottom.set(qn('w:color'), 'B0C4DE')
  16. pBdr.append(bottom)
  17. pPr.append(pBdr)
  18. p.paragraph_format.space_after = Pt(4)
  19. with open('modules.json', encoding='utf-8') as f:
  20. modules = json.load(f)
  21. with open('title.txt', encoding='utf-8') as f:
  22. lines = f.read().splitlines()
  23. main_title, sub_title, note_text = lines[0], lines[1], lines[2]
  24. doc = Document()
  25. for section in doc.sections:
  26. section.top_margin = Cm(2.5)
  27. section.bottom_margin = Cm(2.5)
  28. section.left_margin = Cm(3)
  29. section.right_margin = Cm(3)
  30. t = doc.add_heading(level=0)
  31. t.alignment = WD_ALIGN_PARAGRAPH.CENTER
  32. r = t.add_run(main_title)
  33. r.font.size = Pt(22)
  34. r.font.color.rgb = RGBColor(0x0d, 0x2a, 0x6e)
  35. s = doc.add_paragraph()
  36. s.alignment = WD_ALIGN_PARAGRAPH.CENTER
  37. sr = s.add_run(sub_title)
  38. sr.font.size = Pt(13)
  39. sr.font.color.rgb = RGBColor(0x55, 0x77, 0x99)
  40. doc.add_paragraph()
  41. add_divider(doc)
  42. for module in modules:
  43. h = doc.add_heading(level=1)
  44. h.alignment = WD_ALIGN_PARAGRAPH.LEFT
  45. hr = h.add_run(module['title'])
  46. hr.font.size = Pt(15)
  47. hr.font.bold = True
  48. hr.font.color.rgb = RGBColor(0x1e, 0x40, 0x7e)
  49. h.paragraph_format.space_before = Pt(14)
  50. h.paragraph_format.space_after = Pt(4)
  51. p = doc.add_paragraph()
  52. p.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
  53. pr = p.add_run(module['content'])
  54. pr.font.size = Pt(11)
  55. pr.font.color.rgb = RGBColor(0x22, 0x22, 0x22)
  56. p.paragraph_format.first_line_indent = Pt(22)
  57. p.paragraph_format.line_spacing = Pt(22)
  58. p.paragraph_format.space_after = Pt(6)
  59. add_divider(doc)
  60. doc.add_paragraph()
  61. np = doc.add_paragraph()
  62. np.alignment = WD_ALIGN_PARAGRAPH.LEFT
  63. nr = np.add_run(note_text)
  64. nr.font.size = Pt(9)
  65. nr.font.color.rgb = RGBColor(0x99, 0x99, 0x99)
  66. nr.font.italic = True
  67. outfile = '实验室安全智能监测与管控中心-可视化大屏模块说明.docx'
  68. doc.save(outfile)
  69. print('Saved:', outfile)