The Wayback Machine - https://web.archive.org/web/20240905174223/https://www.geeksforgeeks.org/paragraph-formatting-in-python-docx-module/
Open In App

Paragraph Formatting In Python .docx Module

Last Updated : 09 Jan, 2023
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 users 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.

Line Spacing

To set the line spacing between the text in the paragraph we make use of the paragraph_format along with line_spacing. It is used to set the space between each line in the paragraph.

Syntax: para.paragraph_format.line_spacing = Length

Parameter: Length: It is the length of the space to be left between the lines. It takes length as an input. It can be defined either with an absolute distance value or with a relative distance value of the line-height. If the input is in pt, inches or cm then it considered them as an absolute value and if the input is in float then it is considered as a relative value.

Example 1: Setting the line spacing with absolute distance value.

Python3




# Import docx NOT python-docx
import docx
from docx.shared import Inches
 
# Create an instance of a word document
doc = docx.Document()
 
# Add a Title to the document
doc.add_heading('GeeksForGeeks', 0)
 
# Adding paragraph with spacing
doc.add_heading('Line Spacing: Para-1 [With Spacing]', 3)
para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes etc.')
# Adding linspace of 0.5 inches in the paragraph
para.paragraph_format.line_spacing = Inches(0.5)
 
# Adding paragraph without spacing
doc.add_heading('Line Spacing: Para-2 [Without Spacing]', 3)
doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes etc.')
 
# Now save the document to a location
doc.save('gfg.docx')


Output:

Example 2: Setting the line spacing with relative value.

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 spacing
doc.add_heading('Line Spacing: Para-1 [With Spacing]', 3)
para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes etc.')
# Adding line space in the paragraph
para.paragraph_format.line_spacing = 1.75
 
# Adding paragraph without spacing
doc.add_heading('Line Spacing: Para-2 [Without Spacing]', 3)
doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes etc.')
 
# Now save the document to a location
doc.save('gfg.docx')


Output:

Paragraph Spacing

To apply paragraph spacing to the paragraphs in the Word document we make use of .paragraph_format along with .space_before and .space_after. It specifies the space to be left before and after the paragraph respectively. It can only take the positive value as input, if we give any negative value it will give range error.

Sr. No.

Spacing

Description

1.

.space_before

It adds space before the paragraph in the word document.

2.

.space_after

It adds space after the paragraph in the word document.

Example 3: Adding paragraph with and without spacing in a Word document.

Python3




# Import docx NOT python-docx
import docx
from docx.shared import Inches
 
# Create an instance of a word document
doc = docx.Document()
 
# Add a Title to the document
doc.add_heading('GeeksForGeeks', 0)
 
# Adding paragraph with spacing
doc.add_heading('Paragraph Spacing: Para-1 [With Spacing]', 3)
para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.')
# Adding space before and after of the paragraph
para.paragraph_format.space_before = Inches(0.25)
para.paragraph_format.space_after = Inches(0.25)
 
# Adding paragraph without spacing
doc.add_heading('Paragraph Spacing: Para-2 [Without Spacing]', 3)
doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.')
 
# Now save the document to a location
doc.save('gfg.docx')


Output:

Horizontal Alignment

To set the horizontal alignment in the text we will use the .paragraph_format.alignment method. It is used along with WD_PARAGRAPH_ALIGNMENT to set the alignment of the paragraph. You have to import WD_PARAGRAPH_ALIGNMENT from the docx.enum.text before using it:

from docx.enum.text import WD_ALIGN_PARAGRAPH

Syntax: para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.[Alignment]

Parameter: 

Alignment: It is used to set the alignment. You can set the alignment to any of the left, Center, right, or fully justified.

Various alignments are described below:

Sr. No.

Alignment Name

Description

1.

CENTER

It sets the alignment to Center.

2.

LEFT

It sets the alignment to left.

3.

RIGHT

It sets the alignment to right.

4.

JUSTIFY

It sets the alignment to justify.

5.

DISTRIBUTE

It sets the characters in such a way that they fill the entire width of the paragraph.

Example 1: Adding paragraphs with different Horizontal Alignments.

Python3




# Import docx NOT python-docx
import docx
from docx.enum.text import WD_ALIGN_PARAGRAPH
 
# Create an instance of a word document
doc = docx.Document()
 
# Add a Title to the document
doc.add_heading('GeeksForGeeks', 0)
 
# Adding paragraph with alignment Center
doc.add_heading('Alignment: Center', 3)
para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.')
para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
 
# Adding paragraph with alignment Left
doc.add_heading('Alignment: Left', 3)
para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.')
para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.LEFT
 
# Adding paragraph with alignment Right
doc.add_heading('Alignment: Right', 3)
para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.')
para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.RIGHT
 
# Adding paragraph with alignment Justify
doc.add_heading('Alignment: Justify', 3)
para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.')
para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
 
# Adding paragraph with alignment Distribute
doc.add_heading('Alignment: Distribute', 3)
para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.')
para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.DISTRIBUTE
 
# Now save the document to a location
doc.save('gfg.docx')


Output:

Indentations

To set the indentation in the text we will use the .paragraph_format method. To apply indentation we use left_indent and right_indent with the .paragraph_format and set the value of the indentation. You have to specify indentation with a length value i.e inches, pt or cm. You can also give a negative value as indentation which will cause the paragraph to overlap with the margin by the value specified.

Sr. No.

Indentation

Description

1.

left_indent

It sets the left indentation of the paragraph in the word file.

2.

right_indent

It sets the right indentation of the paragraph in the word file.

Syntax:

  • For the left indentation: para.paragraph_format.left_indent = size
  • For the right indentation: para.paragraph_format.right_indent = size

Parameter: 

size: It is the value by which we want indentation on our paragraph. It can be in inches, pt or cm… etc.

Example 2: Setting left and right indentation of the paragraph.

Python3




# Import docx NOT python-docx
import docx
from docx.shared import Inches
 
# Create an instance of a word document
doc = docx.Document()
 
# Add a Title to the document
doc.add_heading('GeeksForGeeks', 0)
 
# Adding paragraph with left Indentation
doc.add_heading('Indentation: Left', 3)
para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal \
for geeks. It contains well written, well thought and well-explained \
computer science and programming articles, quizzes etc.')
para.paragraph_format.left_indent = Inches(0.5)
 
# Adding paragraph with right Indentation
doc.add_heading('Indentation: Right', 3)
para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal\
for geeks. It contains well written, well thought and well-explained\
computer science and programming articles, quizzes etc.')
para.paragraph_format.right_indent = Inches(0.5)
 
# Now save the document to a location
doc.save('gfg.docx')


Output:

Example 3: Setting a negative value for the left and right indentation of the paragraph.

Python3




# Import docx NOT python-docx
import docx
from docx.shared import Inches
 
# Create an instance of a word document
doc = docx.Document()
 
# Add a Title to the document
doc.add_heading('GeeksForGeeks', 0)
 
# Adding paragraph with negative left Indentation
doc.add_heading('Indentation: Left', 3)
para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal \
for geeks. It contains well written, well thought and well-explained\
computer science and programming articles, quizzes etc.')
para.paragraph_format.left_indent = Inches(-0.5)
 
# Adding paragraph with negative right Indentation
doc.add_heading('Indentation: Right', 3)
para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal\
for geeks. It contains well written, well thought and well-explained\
computer science and programming articles, quizzes etc.')
para.paragraph_format.right_indent = Inches(-0.5)
 
# Now save the document to a location
doc.save('gfg.docx')


Output:

You can also set indentation only for the first line of the paragraph by using .paragraph_format along with  .first_line_indent property. It specifies the indentation length between the first line and the other lines.

Syntax: para.paragraph_format. first_line_indent = Length

Parameters: 

Length: It is the length to be left as indentation at the first line. A positive value will cause the line to indent while the negative value will cause hanging indentation.

Example 4: Giving positive indentation value as input for the first-line indentation.

Python3




# Import docx NOT python-docx
import docx
from docx.shared import Inches
 
# Create an instance of a word document
doc = docx.Document()
 
# Add a Title to the document
doc.add_heading('GeeksForGeeks', 0)
 
# Adding paragraph with only first line Indented
doc.add_heading('Indentation: First Line', 3)
para = doc.add_paragraph('GeeksforGeeks is a Computer Science\
portal for geeks. It contains well written, well thought and \
well-explained computer science and programming articles, quizzes etc.')
 
# Causing First Line Indentation
para.paragraph_format. first_line_indent = Inches(0.5)
 
# Now save the document to a location
doc.save('gfg.docx')


Output:

Example 5: Giving negative indentation value as input for the first-line indentation.

Python3




# Import docx NOT python-docx
import docx
from docx.shared import Inches
 
# Create an instance of a word document
doc = docx.Document()
 
# Add a Title to the document
doc.add_heading('GeeksForGeeks', 0)
 
# Adding paragraph with only first line Indented
doc.add_heading('Indentation: First Line', 3)
para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes etc.')
 
# Causing First Line Indentation
para.paragraph_format. first_line_indent = Inches(-0.5)
 
# Now save the document to a location
doc.save('gfg.docx')


Output:



Similar Reads

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
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 Text 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 python-d
8 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
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
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
{{ form.as_p }} - Render Django Forms as paragraph
Django forms are an advanced set of HTML forms that can be created using python and support all features of HTML forms in a pythonic way. Rendering Django Forms in the template may seem messy at times but with proper knowledge of Django Forms and attributes of fields, one can easily create excellent Form with all powerful features. In this article,
2 min read
PYGLET – Selecting Paragraph in Caret
In this article we will see how we can select paragraph in caret in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or can be set to fill an ent
2 min read
PYGLET – Getting Paragraph End Position in Formatted Document
In this article, we will see how we can get the end position of the given paragraph in the formatted document in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia, etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as
3 min read
PYGLET – Getting Paragraph Start Position in Formatted Document
In this article, we will see how we can get the start position of the given paragraph in the formatted document in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia, etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear
3 min read
PYGLET – Setting Paragraph Style of Formatted Document
In this article we will see how we can set style to the specific paragraph in the formatted document in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating
2 min read
How to extract paragraph from a website and save it as a text file?
Perquisites: Beautiful soupUrllib Scraping is an essential technique which helps us to retrieve useful data from a URL or a html file that can be used in another manner. The given article shows how to extract paragraph from a URL and save it as a text file. Modules Needed bs4: Beautiful Soup(bs4) is a Python library used for getting data from HTML
2 min read
Count the number of paragraph tag using BeautifulSoup
Sometimes, while extracting data from an HTML webpage, do you want to know how many paragraph tags are used in a given HTML document? Don't worry we will discuss about this in this article. Syntax:print(len(soup.find_all("p")))Approach: Step 1: First, import the libraries, BeautifulSoup, and os. from bs4 import BeautifulSoup as bs import os Step 2:
2 min read
JSON Formatting in Python
JSON (JavaScript Object Notation) is a popular data format that is used for exchanging data between applications. It is a lightweight format that is easy for humans to read and write, and easy for machines to parse and generate. Python Format JSON Javascript Object Notation abbreviated as JSON is a lightweight data interchange format. It encodes Py
3 min read
Python code formatting using Black
Writing well-formatted code is very important, small programs are easy to understand but as programs get complex they get harder and harder to understand. At some point, you can’t even understand the code written by you. To avoid this, it is needed to write code in a readable format. Here Black comes into play, Black ensures code quality. What is B
3 min read
Formatting Axes in Python-Matplotlib
Matplotlib is a python library for creating static, animated and interactive data visualizations. Note: For more information, refer to Introduction to Matplotlib What is Axes? This is what you think of as 'plot'. It is the region of the image that contains the data space. The Axes contains two or three-axis(in case of 3D) objects which take care of
4 min read
Formatting containers using format() in Python
Let us see how to format containers that were accessed through __getitem__ or getattr() using the format() method in Python. Accessing containers that support __getitem__a) For Dictionaries C/C++ Code # creating a dictionary founder = {'Apple': 'Steve Jobs', 'Microsoft': 'Bill Gates'} # formatting print('{f[Microsoft]} {f[Apple]}'.format(f = founde
1 min read
Hover Text and Formatting in Python-Plotly
Prerequisites: Python Plotly In this article, we will explore how to Hover Text and Formatting in Python. It is a useful approach to Hover Text and Formatting as it allows to reveal a large amount of data about complex information. One of the most deceptively-powerful features of data visualization is the ability for a viewer to quickly analyze a s
2 min read
Python Modulo String Formatting
In Python, a string of required formatting can be achieved by different methods. Some of them are; 1) Using % 2) Using {} 3) Using Template Strings In this article the formatting using % is discussed. The formatting using % is similar to that of 'printf' in C programming language. %d - integer %f - float %s - string %x - hexadecimal %o - octal The
2 min read
Formatting Dates in Python
In different regions of the world, different types of date formats are used and for that reason usually, programming languages provide a number of date formats for the developed to deal with. In Python, it is dealt with by using a liberty called DateTime. It consists of classes and methods that can be used to work with data and time values. Require
5 min read
Python DateTime Formatting with Pendulum
Effective date and time management is essential in many applications. Compared to the default datetime module, Pendulum is a Python library that offers a more user-friendly and intuitive interface for manipulating dates. In this article, we will learn about datetime formatting with Pendulum in Python. Python DateTime Formatting with PendulumBelow,
3 min read
Python | Output Formatting
In Python, there are several ways to present the output of a program. Data can be printed in a human-readable form, or written to a file for future use, or even in some other specified form. Users often want more control over the formatting of output than simply printing space-separated values. Output Formatting in PythonThere are several ways to f
7 min read
Practice Tags :