Search code examples
python-docx

Python-Docx Is it possible to remove textwrapping around picture?


I´m using run.add_picture() to add a image to my document, but it comes with a 0,30cm spacing around it. I want to remove it so there is no spacing between the text and the image, but I don´t know how to clear this spacing.

Here is the code:

from docx import Document
doc = Document()
doc.add_picture('icon.png')
doc.save('test.docx')

Solution

  • If I understand correctly, you want to insert a floating image instead of an inline one. The code you showed inserts an inline one:

    from docx import Document
    doc = Document()
    doc.add_picture('icon.png')
    doc.save('test.docx')
    

    However, if you first create the paragraph you want to insert the picture, you can add it in a specific run:

    from docx import Document
    doc = Document()
    par = doc.add_paragraph('test text 2\n')
    r = par.add_run()
    r.add_picture(r'icon.png')
    r.add_break()
    r.add_text('\n continue with text after image.')
    doc.save('test.docx')