在pythondocx中更改页边距格式

2024-06-11 04:48:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Python的PythonDocx模块制作多页边距

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')

问题是我不能添加新的页边距,程序只使用我写的最后一页边距。如何仅为一个段落创建唯一的页边空白


Tags: frommarginimportaddptformatstylesection
1条回答
网友
1楼 · 发布于 2024-06-11 04:48:41

页边距适用于,该节通常是共享某些页面格式(如页眉、页脚和页边距)的块项目序列(段落和/或表格)

我认为您要查找的是缩进,它适用于单个段落。其设置为: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

相关问题 更多 >