Paragraph Formatting In Python .docx Module

Paragraph Formatting In Python .docx Module

The python-docx module provides extensive capabilities for formatting paragraphs in Word documents. Here's a guide on paragraph formatting using this module:

1. Installation:

If you haven't installed python-docx, do so using pip:

pip install python-docx 

2. Basic Formatting:

Start by importing the required packages and creating a document:

from docx import Document doc = Document() 

3. Add a Paragraph and Format:

a) Alignment:

from docx.enum.text import WD_PARAGRAPH_ALIGNMENT para = doc.add_paragraph("This is centered text.") para.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER 

b) Line Spacing:

# Set line spacing to 1.5 para = doc.add_paragraph("This is text with line spacing of 1.5.") para.paragraph_format.line_spacing = 1.5 

c) Space Before and After Paragraph:

para = doc.add_paragraph("This has space before and after.") para.paragraph_format.space_before = Pt(12) # 12 points space before para.paragraph_format.space_after = Pt(12) # 12 points space after 

d) Indentation:

para = doc.add_paragraph("This text is indented.") para.paragraph_format.left_indent = Inches(0.5) # Indent text 0.5 inches from the left 

e) Keep Together, Keep with Next, and Page Break Before:

para = doc.add_paragraph("This is text with formatting options.") para.paragraph_format.keep_together = True # Keep entire paragraph on one page para.paragraph_format.keep_with_next = True # Do not break page after this paragraph para.paragraph_format.page_break_before = True # Start this paragraph on a new page 

f) Bullets and Numbering:

# Add bullet points para = doc.add_paragraph("Bullet 1", style='ListBullet') para = doc.add_paragraph("Bullet 2", style='ListBullet') # Add numbering para = doc.add_paragraph("Number 1", style='ListNumber') para = doc.add_paragraph("Number 2", style='ListNumber') 

For the Pt and Inches functions, you need to import them:

from docx.shared import Pt, Inches 

4. Save the Document:

doc.save("formatted_paragraph.docx") 

This is just an overview of paragraph formatting. The python-docx library provides more comprehensive formatting options that you can explore in detail in its official documentation.


More Tags

qtablewidget browser-tab kendo-datepicker publish blazor multitasking compass-geolocation frontend iphone-x aspnetboilerplate

More Programming Guides

Other Guides

More Programming Examples