Working With Text In Python .docx Module - GeeksforGeeks

03 Jan, 2021
Prerequisite: Working with .docx module
Word documents contain formatted text wrapped within three object levels. The Lowest level-run objects, middle level-paragraph objects, and highest level-document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. Pip command to install this module is:
pip install python-docx
Python docx module allows user to manipulate docs by either manipulating the existing one or creating a new empty document and manipulating it. It is a powerful tool as it helps you to manipulate the document to a very large extend. You can also manipulate the font size, colour and its style using this module.
To increase/decrease the font size of the text you have to first create a paragraph object then you have to use add_run() method to add content. You can directly use add_paragraph() method to add paragraph but if you want to increase/decrease the font size of the text you have to use add_run() as all the block-level formatting is done by using add_paragraph() method while all the character-level formatting is done by using add_run().
Now to set a new font size we will use .font.size method. This is the method of the font object and is used to set the new font size of the text.
Syntax: para.font.size = Length
Parameter: 
Length: It defines the size of the font. It can be in inches, pt or cm.
Example 1: Setting the font size of the text in a paragraph.
Python3
# Import docx NOT python-docximport docxfrom docx.shared import Pt  # Create an instance of a word documentdoc = docx.Document()  # Add a Title to the document doc.add_heading('GeeksForGeeks', 0)  # Adding paragraph with Increased font sizedoc.add_heading('Increased Font Size Paragraph:', 3)para = doc.add_paragraph().add_run(    'GeeksforGeeks is a Computer Science portal for geeks.')# Increasing size of the fontpara.font.size = Pt(12)  # Adding paragraph with normal font sizedoc.add_heading('Normal Font Size Paragraph:', 3)doc.add_paragraph(    'GeeksforGeeks is a Computer Science portal for geeks.')  # Now save the document to a location doc.save('gfg.docx')
Output:
To apply a font colour to the text you have to first create a paragraph object then you have to use add_run() method to add content. You can directly use add_paragraph() method to add paragraph but if you want to apply a font colour to a text you have to use add_run() as all the block-level formatting is done by using add_paragraph() method while all the character-level formatting is done by using add_run().
To set the colour to the font we will make us of the RGBColor() object which takes hexadecimal input of the colour and sets the same colour to the text.
Syntax: para.font.color.rgb = RGBColor([RGB Colour Value in  Hexadecimal])
Parameter:
RGB Colour Value: It is the hexadecimal value of the colour you want to set. It is given in the form of R, G, B as input.
Note: You have to add ‘from docx.shared import RGBColor‘ import statement before calling RGBColor() function in your code.
Example 2: Adding colour to the text in the paragraph.
Python3
# Import docx NOT python-docximport docxfrom docx.shared import RGBColor  # Create an instance of a word documentdoc = docx.Document()  # Add a Title to the document doc.add_heading('GeeksForGeeks', 0)  # Adding paragraph doc.add_heading('Font Colour:', 3)para = doc.add_paragraph().add_run(    'GeeksforGeeks is a Computer Science portal for geeks.')  # Adding forest green colour to the text# RGBColor(R, G, B)para.font.color.rgb = RGBColor(0x22, 0x8b, 0x22)  # Now save the document to a location doc.save('gfg.docx')
Output:
To set a new font style for the text you have to first create a paragraph object then you have to use add_run() method to add content. You can directly use add_paragraph() method to add paragraph but if you want to set a new font style of the text you have to use add_run() as all the block-level formatting is done by using add_paragraph() method while all the character-level formatting is done by using add_run().
Now to set a new font name we will use .font.name method. This is the method of the font object and is used to set the new font name for the text.
Syntax: para.font.name = String s
Parameter:
String s: It is the name of the new font style. If you give any random name as input string then default style is adopted for the text.
Example 3: Setting a new font name for a paragraph.
Python3
# Import docx NOT python-docximport docx  # Create an instance of a word documentdoc = docx.Document()  # Add a Title to the document doc.add_heading('GeeksForGeeks', 0)  # Adding paragraph with new font Styledoc.add_heading('Font Style: Roboto', 3)para = doc.add_paragraph().add_run(    'GeeksforGeeks is a Computer Science portal for geeks.')# Setting new font stylepara.font.name = 'Roboto'  # Adding paragraph with default font Styledoc.add_heading('Font Style: Default [Cambria]', 3)doc.add_paragraph(    'GeeksforGeeks is a Computer Science portal for geeks.')  # Now save the document to a location doc.save('gfg.docx')
Output:
To set the text to bold you have to set it true.
doc.bold = True
To highlight a specific word the bold needs to be set True along with its add_run() statement.
add_run(" text ").bold=True
Example 1: Applying bold to a complete paragraph.
Python3
# Import docx NOT python-docximport docx  # Create an instance of a word documentdoc = docx.Document()  # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0)  # Creating paragraphpara = doc.add_paragraph()  # Adding content to paragraphbold_para = para.add_run(    '''GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes etc.''')  # Setting bold to truebold_para.bold = True  # Now save the document to a locationdoc.save('gfg.docx')
Output:
Document gfg.docx
Example 2: Applying bold to a specific word or phrase.
Python3
# Import docx NOT python-docximport docx  # Create an instance of a word documentdoc = docx.Document()  # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0)  # Creating paragraph with some contentpara = doc.add_paragraph(    '''GeeksforGeeks is a Computer Science portal for geeks.''')  # Adding more content to paragraph and Setting bold to truepara.add_run(    ''' It contains well written, well thought and well-explained ''').bold = True  # Adding more content to paragraphpara.add_run('''computer science and programming articles, quizzes etc.''')  # Now save the document to a locationdoc.save('gfg.docx')
Output:
Document gfg.docx
To set the text to italics you have to set it true.
doc.italic = True
To make some specific word(s) italics, it needs to be set True along with its add_run() statement.
add_run(" text ").italic=True
Example 3: Applying italics to a complete paragraph.
Python3
# Import docx NOT python-docximport docx  # Create an instance of a word documentdoc = docx.Document()  # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0)  # Creating paragraphpara = doc.add_paragraph()  # Adding content to paragraphitalic_para = para.add_run(    '''GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes etc.''')  # Applying italics to trueitalic_para.italic = True  # Now save the document to a locationdoc.save('gfg.docx')
Output:
Document gfg.docx
Example 4: Applying italics to a specific word or phrase.
Python3
# Import docx NOT python-docximport docx  # Create an instance of a word documentdoc = docx.Document()  # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0)  # Creating paragraph with some contentpara = doc.add_paragraph(    '''GeeksforGeeks is a Computer Science portal for geeks.''')  # Adding more content to paragraph and applying italics to truepara.add_run(    ''' It contains well written, well thought and well-explained ''').italic = True  # Adding more content to paragraphpara.add_run('''computer science and programming articles, quizzes etc.''')  # Now save the document to a locationdoc.save('gfg.docx')
Output:
Document gfg.docx
To apply to underline to a text you have to set it true.
doc.underline = True
To underline a specific part, underline needs to set a True along with its add_run() function
add_run("text").underline=True
Example 5: Applying underline to a complete paragraph.
Python3
# Import docx NOT python-docximport docx  # Create an instance of a word documentdoc = docx.Document()  # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0)  # Creating paragraphpara = doc.add_paragraph()  # Adding content to paragraphunderline_para = para.add_run(    '''GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes etc.''')  # Applying undeline to trueunderline_para.underline = True  # Now save the document to a locationdoc.save('gfg.docx')
Output:
Document gfg.docx
Example 6: Applying underline to a specific word or phrase.
Python3
# Import docx NOT python-docximport docx  # Create an instance of a word documentdoc = docx.Document()  # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0)  # Creating paragraph with some contentpara = doc.add_paragraph(    '''GeeksforGeeks is a Computer Science portal for geeks.''')  # Adding more content to paragraph and applying underline to thempara.add_run(    ''' It contains well written, well thought and well-explained ''').underline = True  # Adding more content to paragraphpara.add_run('''computer science and programming articles, quizzes etc.''')  # Now save the document to a locationdoc.save('gfg.docx')
Output:
Document gfg.docx
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()