[Python] Inserting images into a .docx file in Python

Discussão em 'Python' iniciado por Stack, Dezembro 1, 2024.

  1. Stack

    Stack Membro Participativo

    There is a task of generating reports in docx from PDF, I can not defeat the insertion of an image. The image needs to be inserted with specific parameters. Problems arose with the position and text fairing. The most successful attempts didn't change the fairing, and the image was inserted at the end or in a new paragraph.

    I need the upper border of the image at the level of a certain line, the picture itself was at the left edge of the document, and the text flowed around the image around the frame.

    I tried this

    par = doc.paragraphs[2]
    par.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT
    run = paragraph.add_run()
    run.add_picture(img_path, width=Cm(5))


    And this one

    par = doc.paragraphs[2]
    run = par.add_run()
    run.add_picture(img_path)
    run_element = run._r

    anchor = OxmlElement('wp:anchor')
    anchor.set('wrapText', 'bothSides')
    anchor.set('distT', '0')
    anchor.set('distB', '0')
    anchor.set('distL', '0')
    anchor.set('distR', '0')

    extent = OxmlElement('wp:extent')
    extent.set('cx', '3000000')
    extent.set('cy', '2000000')
    anchor.append(extent)

    run_element.append(anchor)


    The text gets into the document in the following way, and I don't want to change the docx-python lib that turns it into the desired form.

    search_text = 'text'
    index = find_paragraph_index(doc, search_text)
    doc.paragraphs[3]._element.addnext(doc.add_paragraph()._element)
    doc.paragraphs[4].add_run(doc.paragraphs[index+1].text+":"+" "+doc.paragraphs[index + 2].text)
    doc.paragraphs[index + 1].clear()


    The final result should be something like this. Maybe someone has encountered something like this or knows a solution. Thanks in advance.

    [Example][​IMG]

    Continue reading...

Compartilhe esta Página