5

我正在使用 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 中的文本?

4

2 回答 2

12

使用新版本的 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

你不应该像这样硬编码幻数。用于WD_ALIGN_PARAGRAPH.CENTER获得正确的居中值等。为此,请使用以下导入

from docx.enum.text import WD_ALIGN_PARAGRAPH 
于 2014-07-01T10:26:25.640 回答
3
p = document.add_paragraph('A plain paragraph having some ',style='BodyText', breakbefore=False, jc='left')# @param string jc: Paragraph alignment, possible values:left, center, right, both (justified), ...

如需参考,请参阅 def 段落中的此参考阅读文档

于 2014-06-04T07:35:23.800 回答