[Python] python-docx header set anchor "to page"

Discussão em 'Python' iniciado por Stack, Abril 14, 2025.

  1. Stack

    Stack Membro Participativo

    Problem: put a logo image at top left position of the page.

    I've tried the following to accomplish the same but it doesn't work as expected:

    from docx import Document
    from docx.shared import Mm, Pt
    from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
    doc = Document()

    # A4 vertical
    section = doc.sections[0]
    section.page_height = Mm(297)
    section.page_width = Mm(210)

    # tried to remove margin to position logo
    section.top_margin = Mm(0)
    section.bottom_margin = Mm(0)
    section.left_margin = Mm(0)
    section.right_margin = Mm(0)

    # placed logo but still got a left margin
    header = section.header
    p = header.paragraphs[0]
    p.paragraph_format.space_before = 0
    p.paragraph_format.space_after = 0
    p.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT
    p.add_run().add_picture("logo.png", width=Mm(210))

    # restored margins for next content but trigger a break of the page
    section.top_margin = Mm(20)
    section.bottom_margin = Mm(20)
    section.left_margin = Mm(25)
    section.right_margin = Mm(20)


    Manually editing the generated docx file I've found out that with image properties anchor to page it would fix.

    But this option seems missing in docx code.

    Continue reading...

Compartilhe esta Página