python docx paragraph alignment
Python'spython-docx
Library is a library for creating and updating Microsoft Word documents.
It provides rich features including but not limited to adding text, pictures, tables, etc.
When working with documents, the alignment of paragraphs is an important formatting option.
python-docx
In the library, paragraph alignment can be passedParagraph
The object'salignment
Properties to set.
Some common alignment methods
-
WD_PARAGRAPH_ALIGNMENT.LEFT
: Left alignment, this is the default alignment. -
WD_PARAGRAPH_ALIGNMENT.RIGHT
: Right aligned. -
WD_PARAGRAPH_ALIGNMENT.CENTER
: Align in the center. -
WD_PARAGRAPH_ALIGNMENT.JUSTIFY
: Align both ends, also known as full alignment or justice alignment, the left and right edges of the text are aligned. -
WD_PARAGRAPH_ALIGNMENT.JUSTIFY_LOW
: Similar to the two ends aligned, but the last line will be left aligned. -
WD_PARAGRAPH_ALIGNMENT.JUSTIFY_MED
: Similar to the two ends aligned, but the last line will be slightly dispersed to fit the page width. -
WD_PARAGRAPH_ALIGNMENT.JUSTIFY_HIGH
: Similar to the two ends aligned, but the last line will be more scattered.
Sample code
Show how topython-docx
Set the alignment method of paragraphs in:
from docx import Document from import WD_PARAGRAPH_ALIGNMENT # Create a new Word documentdoc = Document() # Add a new paragraphp = doc.add_paragraph('This is a left-aligned piece of text. ') # Set the alignment of paragraphs to center alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # Add another paragraph and set to right-alignp2 = doc.add_paragraph('This is a right-aligned piece of text. ') = WD_PARAGRAPH_ALIGNMENT.RIGHT # Add the third paragraph and set it to align both endsp3 = doc.add_paragraph('This is a piece of text that is aligned at both ends. ') = WD_PARAGRAPH_ALIGNMENT.JUSTIFY # Save the document('')
- In this code, we first import the necessary modules and then create a new Word document.
- Next, we add three paragraphs and set their alignment separately.
- Finally, we save the document as
。
Please note:
python-docx
Library is not a standard library for Python
Therefore, before using it, you need to use the package management tool firstpip
Come to install
pip install python-docx
usepython-docx
When you are library, you can also set other properties of the paragraph
Such as indentation, line spacing, font style, etc., to meet different document editing needs
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.