| 1 | from docx import Document |
| 2 | from docx.enum.style import WD_STYLE_TYPE |
| 3 | from docx.oxml.ns import qn |
| 4 | from docx.shared import Pt, RGBColor |
| 5 | |
| 6 | |
| 7 | def set_font(font, name: str, size_pt: int, *, bold: bool = False): |
| 8 | font.name = name |
| 9 | font.size = Pt(size_pt) |
| 10 | font.bold = bold |
| 11 | font.color.rgb = RGBColor(0x00, 0x00, 0x00) |
| 12 | |
| 13 | |
| 14 | def set_run_fonts(style, name: str): |
| 15 | r_pr = style.element.get_or_add_rPr() |
| 16 | r_fonts = r_pr.get_or_add_rFonts() |
| 17 | r_fonts.set(qn("w:ascii"), name) |
| 18 | r_fonts.set(qn("w:hAnsi"), name) |
| 19 | r_fonts.set(qn("w:eastAsia"), name) |
| 20 | r_fonts.set(qn("w:cs"), name) |
| 21 | |
| 22 | |
| 23 | def style_paragraph(style, name: str, size_pt: int, *, bold: bool = False, space_before: int = 0, space_after: int = 0): |
| 24 | set_font(style.font, name, size_pt, bold=bold) |
| 25 | set_run_fonts(style, name) |
| 26 | fmt = style.paragraph_format |
| 27 | fmt.space_before = Pt(space_before) |
| 28 | fmt.space_after = Pt(space_after) |
| 29 | |
| 30 | |
| 31 | doc = Document() |
| 32 | styles = doc.styles |
| 33 | |
| 34 | normal = styles["Normal"] |
| 35 | style_paragraph(normal, "Times New Roman", 12) |
| 36 | |
| 37 | title = styles["Title"] |
| 38 | style_paragraph(title, "Times New Roman", 22, bold=True, space_after=12) |
| 39 | |
| 40 | heading1 = styles["Heading 1"] |
| 41 | style_paragraph(heading1, "Times New Roman", 18, bold=True, space_before=18, space_after=10) |
| 42 | |
| 43 | heading2 = styles["Heading 2"] |
| 44 | style_paragraph(heading2, "Times New Roman", 16, bold=True, space_before=14, space_after=8) |
| 45 | |
| 46 | heading3 = styles["Heading 3"] |
| 47 | style_paragraph(heading3, "Times New Roman", 14, bold=True, space_before=12, space_after=6) |
| 48 | |
| 49 | if "First Paragraph" not in [style.name for style in styles]: |
| 50 | styles.add_style("First Paragraph", WD_STYLE_TYPE.PARAGRAPH) |
| 51 | |
| 52 | first_paragraph = styles["First Paragraph"] |
| 53 | style_paragraph(first_paragraph, "Times New Roman", 12) |
| 54 | |
| 55 | doc.save("reference.docx") |