我正在使用 python docx 库来操作 word 文档。但是我找不到如何在该库的文档页面中将一条线与中心对齐。我也无法通过谷歌找到。
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 中的文本?
最佳答案
随着新版python-docx 0.7 https://github.com/python-openxml/python-docx/commit/158f2121bcd2c58b258dec1b83f8fef15316de19 添加功能 #51:Paragraph.alignment(读/写) 现在可以按此处对齐段落: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
从评论中编辑 2
你不应该像这样硬编码魔数(Magic Number)。使用 WD_ALIGN_PARAGRAPH.CENTER
获取正确的居中值等。为此,请使用以下导入
from docx.enum.text import WD_ALIGN_PARAGRAPH
关于Python docx 库文本对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24031011/