from docx import Document from docx.enum.style import WD_STYLE_TYPE from docx.oxml.ns import qn from docx.shared import Pt, RGBColor def set_font(font, name: str, size_pt: int, *, bold: bool = False): font.name = name font.size = Pt(size_pt) font.bold = bold font.color.rgb = RGBColor(0x00, 0x00, 0x00) def set_run_fonts(style, name: str): r_pr = style.element.get_or_add_rPr() r_fonts = r_pr.get_or_add_rFonts() r_fonts.set(qn("w:ascii"), name) r_fonts.set(qn("w:hAnsi"), name) r_fonts.set(qn("w:eastAsia"), name) r_fonts.set(qn("w:cs"), name) def style_paragraph(style, name: str, size_pt: int, *, bold: bool = False, space_before: int = 0, space_after: int = 0): set_font(style.font, name, size_pt, bold=bold) set_run_fonts(style, name) fmt = style.paragraph_format fmt.space_before = Pt(space_before) fmt.space_after = Pt(space_after) doc = Document() styles = doc.styles normal = styles["Normal"] style_paragraph(normal, "Times New Roman", 12) title = styles["Title"] style_paragraph(title, "Times New Roman", 22, bold=True, space_after=12) heading1 = styles["Heading 1"] style_paragraph(heading1, "Times New Roman", 18, bold=True, space_before=18, space_after=10) heading2 = styles["Heading 2"] style_paragraph(heading2, "Times New Roman", 16, bold=True, space_before=14, space_after=8) heading3 = styles["Heading 3"] style_paragraph(heading3, "Times New Roman", 14, bold=True, space_before=12, space_after=6) if "First Paragraph" not in [style.name for style in styles]: styles.add_style("First Paragraph", WD_STYLE_TYPE.PARAGRAPH) first_paragraph = styles["First Paragraph"] style_paragraph(first_paragraph, "Times New Roman", 12) doc.save("reference.docx")