I need to quickly change the margins of many docx documents. I checked python-docx and I do not find a way to access/modify the page layout (in particular the margins) properties. Is there a way?
Asked
Active
Viewed 1.9k times
19
-
2Margins are controlled by [Section objects](http://python-docx.readthedocs.org/en/latest/api/section.html#sections-objects). See [Working With Sections](http://python-docx.readthedocs.org/en/latest/user/sections.html) for more details. I think you can just enumerate the sections in the doc and change the margin properties. – tdelaney Oct 02 '15 at 20:38
-
Totally true @tdelaney, somehow I has misread this part of the documentation. Thanks for pointing this out! – XAnguera Oct 02 '15 at 21:41
2 Answers
38
Thanks to @tdelaney for pointing out the page where it clearly indicated the solution. I am just posting here the code I used in case anyone else is confused as I initially was:
#Open the document
document = Document(args.inputFile)
#changing the page margins
sections = document.sections
for section in sections:
section.top_margin = Cm(margin)
section.bottom_margin = Cm(margin)
section.left_margin = Cm(margin)
section.right_margin = Cm(margin)
document.save(args.outputFile)

XAnguera
- 1,157
- 1
- 11
- 25
-
Is there any method to change the Left and Right margin of only the Header and Footer and NOT the whole page/section? – Slick Slime Jul 24 '19 at 07:41
-
-
@Steve It's probably the output of `argparse`, which is storing the values passed in from the command line. – Anthony May 07 '20 at 12:45
-
15
import docx
from docx.shared import Inches, Cm
doc = docx.Document()
sections = doc.sections
for section in sections:
section.top_margin = Cm(0.5)
section.bottom_margin = Cm(0.5)
section.left_margin = Cm(1)
section.right_margin = Cm(1)
Here's the code that i used please include from docx.shared import Inches, Cm

Siddharth Rajput
- 151
- 1
- 2