python-docx: run.add_picture() won't insert the image into the document

I’m trying to editing an existing Word document (.docx). Everything works well and I can easily add images at the end of the document with : document.add_picture("my_picture.png") .

My problem is presented when I try to get a specific paragraph and add a picture inside a new run.

ex. document.paragraphs[20].add_run().add_picture("my_picture.png")

The command executes correctly, but then when I open the saved word document no image is present at the paragraph n.20.

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 4
  • Comments: 17 (5 by maintainers)

Most upvoted comments

Hi @maxcavalli as a rule one should avoid introducing a new issue on an old thread. Please start a new issue for this 😃

Post the before-repair and after-repair XML and let’s have a look:

paragraph = document.paragraphs[20]
run = paragraph.add_run()
picture = run.add_picture("my_picture.png")
print(paragraph._p.xml)

Then after the repair:

paragraph = document.paragraphs[20]
print(paragraph._p.xml)

My guess is that microsoft changed the image XML in a way that python-docx hasn’t been able to handle. Its saying there’s an error and a docx file is also a zipfile full of xml files.