Solution for Python Docx’s run.add_picture() doesn’t work the first time, but works every time after. Why is that?
is Given Below:
I’ve encountered a bug when using python docx. It seems that whenever I use the run.add_picture() method, it doesn’t work the first time (it just produces a run that’s bold and italicized, but doesn’t include the intended picture).
But it works every time after. Is there a known reason why this happens? And is there a fix for it?
This is what I mean as an example. When I run the following code:
paragraph.add_run().add_picture(path, height = height) paragraph.add_run().add_picture(path, height = height) paragraph.add_run().add_picture(path, height = height)
The first line of code doesn’t work, but the second and third do. I see two of the same pictures, instead of 3.
I don’t think it’s an issue with the rest of my code, because again, it works every time except the first time. It almost feels like that first line of code NEEDS to be executed in order for the .add_picture() method to work later.
It seems that my issue is the base document I’m using.
Here is some minimal code on when this problem occurs.
from docx import Document document = Document("Base Document.docx") document._body.clear_content() run = document.add_paragraph().add_run() run.add_picture("Capture.JPG") run.add_picture("Capture.JPG") run.add_picture("Capture.JPG") document.save('demo.docx')
When I leave out the “Base Document.docx” argument inside Document(), this problem doesn’t occur. The thing about Base Document.docx though is that it’s a completely empty word document. I just applied some styles on some text in the document, but deleted them right after, so that the styles could be used while programming, as per documentation. I don’t know what else I could have (accidently) done on Base Document.docx that is causing this issue. Any ideas?
Update 2: Resolved. Just created a new “Base Document.docx”
I’m still curious what the issue was with the first “Base Document.docx”