Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I apply both bold and italics in python-docx?

I'm working on making a dictionary. I'm using python-docx to put it into MS Word. I can easily make it bold, or italics, but can't seem to figure out how to do both. Here's the basics:

import docx

word = 'Dictionary'

doc = docx.Document()
p = doc.add_paragraph()
p.add_run(word).bold = True

doc.save('test.docx')

I have tried p.add_run(word).bold.italic = True, but receive a 'NoneType' error, which I understand.

I have also tried p.bold = True and p.italic = True before and after the add_run, but lose formatting all together.

Word's find/replace is a simple solution, but I'd prefer to do it in the code if I can.

like image 823
mightyoscar Avatar asked Sep 26 '16 18:09

mightyoscar


People also ask

How do you make text bold and italic in Python?

formated text in python? (bold, italic, etc.) Tricker red = '\033[91m' green = '\033[92m' blue = '\033[94m' bold = '\033[1m' italics = '\033[3m' underline = '\033[4m' end = '\033[0m' print (red + underline + 'Test!... Test! ' + end) something like this?

How do I make text bold in Python docx?

To set the text to bold you have to set it true. To highlight a specific word the bold needs to be set True along with its add_run() statement. Example 1: Applying bold to a complete paragraph.

How do you type in bold and italics?

To make text bold, select and highlight the text first. Then hold down Ctrl (the control key) on the keyboard and press B on the keyboard. To make text italic, select and highlight the text first. Then hold down Ctrl (the control key) on the keyboard and then press the I on the keyboard.


1 Answers

The add_run method will return a new instance of Run each time it is called. You need create a single instance and then apply italic and bold

import docx

word = 'Dictionary'

doc = docx.Document()
p = doc.add_paragraph()

runner = p.add_run(word)
runner.bold = True
runner.italic = True

doc.save('test.docx')
like image 187
Wondercricket Avatar answered Sep 27 '22 17:09

Wondercricket