import json from docx import Document from docx.shared import Pt, RGBColor, Cm from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.oxml.ns import qn from docx.oxml import OxmlElement def add_divider(doc): p = doc.add_paragraph() pPr = p._p.get_or_add_pPr() pBdr = OxmlElement('w:pBdr') bottom = OxmlElement('w:bottom') bottom.set(qn('w:val'), 'single') bottom.set(qn('w:sz'), '4') bottom.set(qn('w:space'), '1') bottom.set(qn('w:color'), 'B0C4DE') pBdr.append(bottom) pPr.append(pBdr) p.paragraph_format.space_after = Pt(4) with open('modules.json', encoding='utf-8') as f: modules = json.load(f) with open('title.txt', encoding='utf-8') as f: lines = f.read().splitlines() main_title, sub_title, note_text = lines[0], lines[1], lines[2] doc = Document() for section in doc.sections: section.top_margin = Cm(2.5) section.bottom_margin = Cm(2.5) section.left_margin = Cm(3) section.right_margin = Cm(3) t = doc.add_heading(level=0) t.alignment = WD_ALIGN_PARAGRAPH.CENTER r = t.add_run(main_title) r.font.size = Pt(22) r.font.color.rgb = RGBColor(0x0d, 0x2a, 0x6e) s = doc.add_paragraph() s.alignment = WD_ALIGN_PARAGRAPH.CENTER sr = s.add_run(sub_title) sr.font.size = Pt(13) sr.font.color.rgb = RGBColor(0x55, 0x77, 0x99) doc.add_paragraph() add_divider(doc) for module in modules: h = doc.add_heading(level=1) h.alignment = WD_ALIGN_PARAGRAPH.LEFT hr = h.add_run(module['title']) hr.font.size = Pt(15) hr.font.bold = True hr.font.color.rgb = RGBColor(0x1e, 0x40, 0x7e) h.paragraph_format.space_before = Pt(14) h.paragraph_format.space_after = Pt(4) p = doc.add_paragraph() p.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY pr = p.add_run(module['content']) pr.font.size = Pt(11) pr.font.color.rgb = RGBColor(0x22, 0x22, 0x22) p.paragraph_format.first_line_indent = Pt(22) p.paragraph_format.line_spacing = Pt(22) p.paragraph_format.space_after = Pt(6) add_divider(doc) doc.add_paragraph() np = doc.add_paragraph() np.alignment = WD_ALIGN_PARAGRAPH.LEFT nr = np.add_run(note_text) nr.font.size = Pt(9) nr.font.color.rgb = RGBColor(0x99, 0x99, 0x99) nr.font.italic = True outfile = '实验室安全智能监测与管控中心-可视化大屏模块说明.docx' doc.save(outfile) print('Saved:', outfile)