Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify docx page margins with python-docx

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?

like image 866
XAnguera Avatar asked Oct 02 '15 19:10

XAnguera


Video Answer


2 Answers

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)
like image 55
XAnguera Avatar answered Sep 18 '22 20:09

XAnguera


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

like image 26
Siddharth Rajput Avatar answered Sep 21 '22 20:09

Siddharth Rajput