Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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”)
like image 598
ReKx Avatar asked Jan 28 '23 23:01

ReKx


1 Answers

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) 
like image 197
Pieter du Toit Avatar answered Jan 30 '23 11:01

Pieter du Toit