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( 'w3wiki' , 0 ) # Adding paragraph with spacing doc.add_heading( 'Paragraph Spacing: Para-1 [With Spacing]' , 3 ) para = doc.add_paragraph( 'w3wiki 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( 'w3wiki is a Computer Science portal for geeks.' ) # Now save the document to a location doc.save( 'gfg.docx' ) |
Output:
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 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.