Search code examples
pythonpython-3.xdocxdoc

How do I change font size in a docx file python


I am trying to create a Finance Log, however I canot change the font size from one size to another without the entire font size of all the text changing.

I want "Finance Log" and "Created On..." to be in 48 and "Log Begins:" to be in 24.

Tstyle = doc.styles['Normal']
font = Tstyle.font
font.name = "Nunito Sans"
font.size = Pt(48)
Title = doc.add_paragraph()
TRun = Title.add_run("Finance Log")
TRun.bold = True
CurrentDate= datetime.datetime.now()
FormattedDate= CurrentDate.strftime('%d-%m-%Y')
FCreated = Title.add_run("\nFile Created On "+FormattedDate)
Fstyle = doc.styles['Heading 1']
font = Fstyle.font
font.name = "Nunito Sans"
font.size = Pt(24)
FLog = doc.add_paragraph()
FinanceTitle = FLog.add_run("Log Begins:")
doc.save(path_to_docx)

I have tried multiple things such as creating a new style, setting the new style to a heading etc...

I am aware of Set paragraph font in python-docx however I could not resolve the problem from this


Solution

  • I canot change the font size from one size to another without the entire font size of all the text changing.

    That's because you're changing the underlying font size of the style objects:

    Tstyle = doc.styles['Normal']
    font = Tstyle.font  # << this line assigns font = doc.styles['Normal'].font
    

    So, you're not working with some generic "font" property, you're working with the font that belongs to the named style "Normal". And so:

    font.name = "Nunito Sans"
    font.size = Pt(48)  # << this line changes the font size of doc.styles['Normal']
    

    Untested, but try something like:

    TStyle, FStyle = doc.styles['Normal'], doc.styles['Heading 1']
    for style in (TStyle, FStyle):
        style.font.name = "Nunito Sans"
    TStyle.font.size = Pt(48)
    FStyle.font.size = Pt(24)
    
    
    Title = doc.add_paragraph()
    Title.style = TStyle
    TRun = Title.add_run("Finance Log")
    TRun.bold = True
    
    FCreated = Title.add_run("\nFile Created On {0}".format(datetime.datetime.now().strftime('%d-%m-%y')))
    
    FLog = doc.add_paragraph()
    FLog.style = FStyle
    FinanceTitle = FLog.add_run("Log Begins:")
    doc.save(path_to_docx)