Reputation: 41
I am trying to make multiple margins using Python's python-docx module.
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')
The problem is I can't add new margin and program uses only last margin I wrote. How to make unique margin only for one paragraph?
Upvotes: 1
Views: 2507
Reputation: 28883
margin applies to a section, which in general is a sequence of block items (paragraphs and/or tables) that share certain page formatting, like headers, footers, and margins.
I think what you're looking for is indent, which applies to an individual paragraph. The setting for that is: Paragraph.paragraph_format.left_indent
and it's companions for right-side indent and distinct first-line 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)
These settings are described in the documentation here:
https://python-docx.readthedocs.io/en/latest/api/text.html#docx.text.parfmt.ParagraphFormat
Upvotes: 2