The Wayback Machine - https://web.archive.org/web/20240907032600/https://www.geeksforgeeks.org/working-with-text-in-python-docx-module/
Open In App

Working With Text In Python .docx Module

Last Updated : 03 Jan, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Font Size

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-docx
import docx
from docx.shared import Pt
  
# Create an instance of a word document
doc = docx.Document()
  
# Add a Title to the document 
doc.add_heading('GeeksForGeeks', 0)
  
# Adding paragraph with Increased font size
doc.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 font
para.font.size = Pt(12)
  
# Adding paragraph with normal font size
doc.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:

Font Colour

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-docx
import docx
from docx.shared import RGBColor
  
# Create an instance of a word document
doc = 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:

Font Style

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-docx
import docx
  
# Create an instance of a word document
doc = docx.Document()
  
# Add a Title to the document 
doc.add_heading('GeeksForGeeks', 0)
  
# Adding paragraph with new font Style
doc.add_heading('Font Style: Roboto', 3)
para = doc.add_paragraph().add_run(
    'GeeksforGeeks is a Computer Science portal for geeks.')
# Setting new font style
para.font.name = 'Roboto'
  
# Adding paragraph with default font Style
doc.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:

Bold Text

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-docx
import docx
  
# Create an instance of a word document
doc = docx.Document()
  
# Add a Title to the document
doc.add_heading('GeeksForGeeks', 0)
  
# Creating paragraph
para = doc.add_paragraph()
  
# Adding content to paragraph
bold_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 true
bold_para.bold = True
  
# Now save the document to a location
doc.save('gfg.docx')


Output:

Document gfg.docx

Example 2: Applying bold to a specific word or phrase.

Python3




# Import docx NOT python-docx
import docx
  
# Create an instance of a word document
doc = docx.Document()
  
# Add a Title to the document
doc.add_heading('GeeksForGeeks', 0)
  
# Creating paragraph with some content
para = doc.add_paragraph(
    '''GeeksforGeeks is a Computer Science portal for geeks.''')
  
# Adding more content to paragraph and Setting bold to true
para.add_run(
    ''' It contains well written, well thought and well-explained ''').bold = True
  
# Adding more content to paragraph
para.add_run('''computer science and programming articles, quizzes etc.''')
  
# Now save the document to a location
doc.save('gfg.docx')


Output:

Document gfg.docx

Italics Text

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-docx
import docx
  
# Create an instance of a word document
doc = docx.Document()
  
# Add a Title to the document
doc.add_heading('GeeksForGeeks', 0)
  
# Creating paragraph
para = doc.add_paragraph()
  
# Adding content to paragraph
italic_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 true
italic_para.italic = True
  
# Now save the document to a location
doc.save('gfg.docx')


Output:

Document gfg.docx

Example 4: Applying italics to a specific word or phrase.

Python3




# Import docx NOT python-docx
import docx
  
# Create an instance of a word document
doc = docx.Document()
  
# Add a Title to the document
doc.add_heading('GeeksForGeeks', 0)
  
# Creating paragraph with some content
para = doc.add_paragraph(
    '''GeeksforGeeks is a Computer Science portal for geeks.''')
  
# Adding more content to paragraph and applying italics to true
para.add_run(
    ''' It contains well written, well thought and well-explained ''').italic = True
  
# Adding more content to paragraph
para.add_run('''computer science and programming articles, quizzes etc.''')
  
# Now save the document to a location
doc.save('gfg.docx')


Output:

Document gfg.docx

Underlined Text

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-docx
import docx
  
# Create an instance of a word document
doc = docx.Document()
  
# Add a Title to the document
doc.add_heading('GeeksForGeeks', 0)
  
# Creating paragraph
para = doc.add_paragraph()
  
# Adding content to paragraph
underline_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 true
underline_para.underline = True
  
# Now save the document to a location
doc.save('gfg.docx')


Output:

Document gfg.docx

Example 6: Applying underline to a specific word or phrase.

Python3




# Import docx NOT python-docx
import docx
  
# Create an instance of a word document
doc = docx.Document()
  
# Add a Title to the document
doc.add_heading('GeeksForGeeks', 0)
  
# Creating paragraph with some content
para = doc.add_paragraph(
    '''GeeksforGeeks is a Computer Science portal for geeks.''')
  
# Adding more content to paragraph and applying underline to them
para.add_run(
    ''' It contains well written, well thought and well-explained ''').underline = True
  
# Adding more content to paragraph
para.add_run('''computer science and programming articles, quizzes etc.''')
  
# Now save the document to a location
doc.save('gfg.docx')


Output:

Document gfg.docx



Similar Reads

Working with Highlighted Text in Python .docx Module
Prerequisites: docx 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 co
5 min read
Working with Page Orientations and Pagination Properties - Python .docx Module
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 pytho
4 min read
Working with Lists - Python .docx Module
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 pytho
4 min read
Working with Headers And Footers in Python .docx Module
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 objects. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-
6 min read
Working with Documents - Python .docx Module
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 pytho
2 min read
Working with Titles and Heading - Python docx Module
Prerequisites: docx 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. Python
2 min read
Working with Images - Python .docx Module
Prerequisites: docx Word documents contain formatted text wrapped within three object levels. 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. Python doc
2 min read
Working with Page Break - Python .docx Module
Prerequisites: docx Word documents contain formatted text wrapped within three object levels. 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. Python doc
2 min read
Working with Tables - Python .docx Module
Prerequisites: docx Word documents contain formatted text wrapped within three object levels. 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. Python doc
3 min read
Working with Paragraphs in Python .docx Module
Prerequisites: docx 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 co
4 min read
Convert Docx to Pdf using docx2pdf Module in Python
Tired of having to use online docx to PDF converters with crappy interfaces and conversion limits? Then, look no further than your friendly neighborhood language python's docx2pdf module. This module is a hidden gem among the many modules for the python language. This module can be used to convert files singly or in bulk using the command line or a
2 min read
Paragraph Formatting In Python .docx Module
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 pytho
9 min read
How to Install python-docx on Linux?
Word documents include formatted text wrapped in three object levels: Run objects at the lowest level, Paragraph objects at the intermediate level, and Document objects at the top level. As a result, we are unable to work with these documents using standard text editors. However, we may use the Python-Docx package to manage these word documents in
2 min read
Python Docx - How to Number Headings?
Python-docx is a powerful library for creating and manipulating Word documents (.docx) in Python. It's widely used for automating the generation of reports, invoices, and other document-based tasks. One of the common requirements when creating structured documents is the need to set heading numbers to maintain a hierarchical structure and improve r
3 min read
Working with XlsxWriter module - Python
XlsxWriter is a Python module that provides various methods to work with Excel using Python. It can be used to read, write, applying formulas. Also, it supports features such as formatting, images, charts, page setup, auto filters, conditional formatting, and many others. This tutorial aims at providing knowledge about the XlsxWriter module from ba
12 min read
twitter-text-python (ttp) module - Python
twitter-text-python is a Tweet parser and formatter for Python. Amongst many things, the tasks that can be performed by this module are : reply : The username of the handle to which the tweet is being replied to. users : All the usernames mentioned in the tweet. tags : All the hashtags mentioned in the tweet. urls : All the URLs mentioned in the tw
3 min read
Python Text To Speech | pyttsx module
pyttsx is a cross-platform text to speech library which is platform independent. The major advantage of using this library for text-to-speech conversion is that it works offline. However, pyttsx supports only Python 2.x. Hence, we will see pyttsx3 which is modified to work on both Python 2.x and Python 3.x with the same code. Use this command for I
2 min read
Pygame - Working with Text
In this article, we will see how to play with texts using the Pygame module. We will be dealing here with initializing the font, rendering the text, editing the text using the keyboard, and adding a blinking cursor note. Installation To install this module type the below command in the terminal. pip install pygameFont Initialization Now we can proc
5 min read
Convert Text and Text File to PDF using Python
PDFs are one of the most important and widely used digital media. PDF stands for Portable Document Format. It uses .pdf extension. It is used to present and exchange documents reliably, independent of software, hardware, or operating system. Converting a given text or a text file to PDF (Portable Document Format) is one of the basic requirements in
3 min read
Convert Text Image to Hand Written Text Image using Python
In this article, we are going to see how to convert text images to handwritten text images using PyWhatkit, Pillow, and Tesseract in Python. Module needed: Pytesseract: Sometimes known as Python-tesseract, is a Python-based optical character recognition (OCR) program. It can read and recognize text in photos, license plates, and other documents. To
2 min read
Python: Convert Speech to text and text to Speech
Speech Recognition is an important feature in several applications used such as home automation, artificial intelligence, etc. This article aims to provide an introduction on how to make use of the SpeechRecognition and pyttsx3 library of Python.Installation required: Python Speech Recognition module: pip install speechrecognitionPyAudio: Use the f
3 min read
How to Set Text of Tkinter Text Widget With a Button?
Prerequisite: Python GUI – tkinter Text Widget is used where a user wants to insert multi-line text fields. In this article, we are going to learn the approaches to set the text inside the text fields of the text widget with the help of a button. Approach: Using insert and delete methodImport the Tkinter module.Create a GUI window.Create our text w
2 min read
How to wrap text within Tkinter Text Box?
In this article, we will see that how can we wrap the text in the TKinter Text-Box using the Tkinter module Called textWrap Module. The textwrap module can be used for wrapping and formatting plain text. This module provides formatting of the text by adjusting the line breaks in the input paragraph. Example 1: Firstly We will import the Tkinter Lib
2 min read
MySQL-Connector-Python module in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
2 min read
Python calendar module : formatmonth() method
Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. class calendar.TextCalendar(firstweekday=0) can be used to generate plain text
2 min read
Python | Writing to an excel file using openpyxl module
Prerequisite : Reading an excel file using openpyxl Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files. The openpyxl module allows Python program to read and modify Excel files. For example, user might have to go through thousands of rows and pick out few handful information to make small changes b
3 min read
Stack and Queue in Python using queue Module
A simple python List can act as queue and stack as well. Queue mechanism is used widely and for many purposes in daily life. A queue follows FIFO rule(First In First Out) and is used in programming for sorting and for many more things. Python provides Class queue as a module which has to be generally created in languages such as C/C++ and Java. 1.
3 min read
PyMsgBox module in Python
PyMsgBox is simple, cross-platform, purely implemented in Python for message boxes as JavaScript has. It uses Python's built-in Tkinter module for its GUI. Installation This module does not built-in Python. To install it type the below command in the terminal. pip install PyMsgBox There are four functions in PyMsgBox, which follow JavaScript’s mess
2 min read
uniform() method in Python Random module
uniform() is a method specified in the random library in Python 3. Nowadays, in general, day-day tasks, there's always the need to generate random numbers in a range. Normal programming constructs require a method more than just one word to achieve this particular task. In python, there's an inbuilt method, "uniform()" which performs this task with
2 min read
mode() function in Python statistics module
The mode of a set of data values is the value that appears most often. It is the value at which the data is most likely to be sampled. A mode of a continuous probability distribution is often considered to be any value x at which its probability density function has a local maximum value, so any peak is a mode.Python is very robust when it comes to
5 min read
Practice Tags :