Search code examples
pythonpython-3.xpython-docx

Header and footer top and bottom margin


I have a s cript that generates a docx file, everything is ok with the exception that the header and footer are not align to top and bottom.

I have

        mydoc = docx.Document()
        section_g = mydoc.sections
        section_h = mydoc.sections[0]
        header = section_h.header
        header_para = header.paragraphs[0]
        footer = section_h.footer
        footer_para = footer.paragraphs[0]


        for section in section_g:
            section.top_margin = Cm(0)
            section.bottom_margin = Cm(0)
            section.left_margin = Cm(0)
            section.right_margin = Cm(0)

This works great for the rest of the document but the header and footer top and left margin is not 0.

What am i missing? thanks


Solution

  • Have a look at the API documentation for Section.header_distance and .footer_distance here: https://python-docx.readthedocs.io/en/latest/api/section.html#docx.section.Section.header_distance

    I think this is the setting you're after. Basically it determines the space between the top or bottom of the page and the header or footer respectively. By adjusting these values in conjunction with the top and bottom margin values you can adjust where the header and footer start and where the "body" text begins and ends vertically.