ReKx
ReKx

Reputation: 1066

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”)

Upvotes: 4

Views: 13777

Answers (2)

Pieter du Toit
Pieter du Toit

Reputation: 126

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) 

Upvotes: 10

Pieter du Toit
Pieter du Toit

Reputation: 126

This was answered before and you can check it out here, you have to apply a style. I've tested the below and it seems to work.

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)
document.add_paragraph('Some text').add_run()

Upvotes: 1

Related Questions