Blame Raw
permissionBRICK · 9f53616a · · 55 lines (1.7 KB)
1 contributor
1from docx import Document
2from docx.enum.style import WD_STYLE_TYPE
3from docx.oxml.ns import qn
4from docx.shared import Pt, RGBColor
5
6
7def 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
14def 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
23def 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
31doc = Document()
32styles = doc.styles
33
34normal = styles["Normal"]
35style_paragraph(normal, "Times New Roman", 12)
36
37title = styles["Title"]
38style_paragraph(title, "Times New Roman", 22, bold=True, space_after=12)
39
40heading1 = styles["Heading 1"]
41style_paragraph(heading1, "Times New Roman", 18, bold=True, space_before=18, space_after=10)
42
43heading2 = styles["Heading 2"]
44style_paragraph(heading2, "Times New Roman", 16, bold=True, space_before=14, space_after=8)
45
46heading3 = styles["Heading 3"]
47style_paragraph(heading3, "Times New Roman", 14, bold=True, space_before=12, space_after=6)
48
49if "First Paragraph" not in [style.name for style in styles]:
50 styles.add_style("First Paragraph", WD_STYLE_TYPE.PARAGRAPH)
51
52first_paragraph = styles["First Paragraph"]
53style_paragraph(first_paragraph, "Times New Roman", 12)
54
55doc.save("reference.docx")