更改 python-docx 中的边距格式

Changing margin formatting in python-docx

我正在尝试使用 Python 的 python-docx 模块制作多个页边距。

from docx import Document
from docx.enum.style import WD_STYLE_TYPE
from docx.shared import Mm, Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT

worddoc = Document()

section = worddoc.sections[0]
section.page_height = Mm(297)
section.page_width = Mm(210)

section.left_margin = Mm(30.4)
section.right_margin = Mm(14.4)
section.top_margin = Mm(18.4)
section.bottom_margin = Mm(9.4)


paragraph = worddoc.add_paragraph('Left Indent Test')

paragraph.style = worddoc.styles.add_style('Style1', WD_STYLE_TYPE.PARAGRAPH)

p2 = worddoc.add_paragraph('another margin')

p2.style = worddoc.styles.add_style('Style2', WD_STYLE_TYPE.PARAGRAPH)



font = p2.style.font
font.name = 'Times New Roman'
font.size = Pt(19)
file_format = p2.paragraph_format
file_format.space_before = Pt(0)
file_format.space_after = Pt(0)


sect = worddoc.sections[0]
sect.left_margin = Mm(110.4)
sect.right_margin = Mm(14.4)

# flux = worddoc.add_paragraph('normal text with default margin')

worddoc.save('left_indent.docx')

问题是我无法添加新的边距,程序只使用我写的最后一个边距。如何只为一个段落制作独特的边距?

margin 适用于 section,它通常是一系列块项目(段落 and/or 表)共享某些 页面 格式,例如页眉、页脚和边距。

我认为您要找的是 indent,它适用于单个段落。其设置是:Paragraph.paragraph_format.left_indent 并且它是右侧缩进和独特的第一行缩进的同伴。

from docx import Document
from docx.shared import Mm

document = Document()
paragraph = document.add_paragraph('Left Indent Test')
paragraph.paragraph_format.left_indent = Mm(30.4)
paragraph.paragraph_format.right_indent = Mm(14.4)

这些设置在此处的文档中进行了描述:
https://python-docx.readthedocs.io/en/latest/api/text.html#docx.text.parfmt.ParagraphFormat