Search code examples
pythonpython-3.xdocxpython-docx

How to change font styles in python docx for a sentence


How do we apply a font name, size, etc to add_run() in python docx.
I have tried the following but it doesn’t work.

run = Document().add_paragraph().add_run()
font = run.font
font.name = “MS Gothic”
Document().add_paragraph().add_run(“Some random text”)

Solution

  • For per sentence try the below:

    import docx
    document = docx.Document()
    run = document.add_paragraph().add_run()
    '''Apply style'''
    style = document.styles['Normal']
    font = style.font
    font.name = 'MS Gothic'
    font.size = docx.shared.Pt(15)
    paragraph = document.add_paragraph('Some text\n')
    '''Add another sentence to the paragraph'''
    sentence = paragraph.add_run('A new line that should have a different font')
    '''Then format the sentence'''
    sentence.font.name = 'Arial'
    sentence.font.size = docx.shared.Pt(10)