Slick Slime
Slick Slime

Reputation: 693

python-docx Change header left margin only

I am using python-docx library to add an image to header and footer of a .docx file.

By default, there is a left margin to both Header-Footer as well as the Page.

In order to change the left margin of Header-Footer to 0 if I use section.left_margin = 0 this sets the margin of whole page to 0. But I only want to change the left margin of Header-Footer to 0.

So: How can I change the left margin of only the Header and Footer using python-docx or any other library.

Current Document Image - if I simply add Image to header and footer that has same width as section's width:

enter image description here

Document Image if I also do section.left_margin = 0:

enter image description here

What I actually want:

enter image description here

Upvotes: 0

Views: 2438

Answers (1)

scanny
scanny

Reputation: 28883

As Cindy mentions in her comment: You can't change header margins, because page margins are an attribute of the section and therefore apply to both headers and the body. What you can do is change paragraph indents, and there are at least two approaches here.

  1. Change left indent to a negative value:

    from docx.shared import Inches
    
    header = section.header
    paragraph = header.paragraphs[0]
    paragraph.paragraph_format.left_indent = -Inches(1.0)
    
  2. Change right indent such that right_indent + right_margin = left_margin:

    paragraph.paragraph_format.right_indent = Inches(0.5)
    

Note that this indentation must be applied to all paragraphs in the header you want aligned this way; indentation is paragraph-by-paragraph.

Upvotes: 3

Related Questions