Python docx库文本对齐 [英] Python docx library text align
问题描述
我正在使用python docx库来操作word文档.但是我找不到该库的文档页面中的一条线与中心对齐.我也找不到Google.
I am using python docx library to manipulate a word document. However I can't find how to align a line to the center in the documents page of that library. I can't find by google either.
from docx import Document
document = Document()
p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True
如何在docx中对齐文本?
How can I align the text in docx?
推荐答案
使用新版本的python-docx 0.7 http://python-docx.readthedocs.org/en/latest/dev/analysis/features/par-alignment.html
With the new version of python-docx 0.7 https://github.com/python-openxml/python-docx/commit/158f2121bcd2c58b258dec1b83f8fef15316de19 Add feature #51: Paragraph.alignment (read/write) Now it is possible to align a paragraph as here: http://python-docx.readthedocs.org/en/latest/dev/analysis/features/par-alignment.html
paragraph = document.add_paragraph("This is a text")
paragraph.alignment = 0 # for left, 1 for center, 2 right, 3 justify ....
根据评论进行编辑
实际上,左为0,中为1,右为2
actually it is 0 for left, 1 for center, 2 for right
从评论中编辑2
您不应该像这样对魔术数字进行硬编码.使用WD_ALIGN_PARAGRAPH.CENTER
获取正确的居中等值.为此,请使用以下导入
You shouldn't hard code magic numbers like this. Use WD_ALIGN_PARAGRAPH.CENTER
to get the correct value for centering, etc. To do this use the following import
from docx.enum.text import WD_ALIGN_PARAGRAPH
这篇关于Python docx库文本对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!