Replace image in Word docx format

Viewed 902

I'm attempting to replace an image in a Word 2019 .docx file using the following code in Python:

from docxtpl import DocxTemplate
tpl = DocxTemplate("C:\\temp\\replace_picture_tpl.docx")
context = {}
tpl.replace_pic('Sample.png','C:\\temp\\NewImage.png')
tpl.render(context)
tpl.save("C:\\temp\\TestOutput.docx")

I get the error ValueError: Picture Sample.png not found in the docx template. I created the document by inserting a random .png file into a blank Word document and saving it. I have double checked and confirmed that it is a .docx file. I then used the code above to attempt to change the picture, which didn't work. I looked around online for a couple of days and haven't been able to find anything to help yet. I've gone through the docxtpl templates and sample code and it seems like the code references a "descr" tag to locate 'Sample.png'. However when I view the replace_picture_tpl.docx XML file, the image doesn't have this tag. Any suggestions?

1 Answers

Open template in MS Word or LibreOffice, click by you image to replace, click right button and selec properies. In dialog window find tag "Description" and put here you tag. Scrennshot from LibreOffice Writer.

enter image description here

For Ryan M : Before delete my answer try to read and understand question! Yes question about how to do this in Python, but autor can't do it in python, because he don't set "description" in template DOCX document. And he asking how to do it! He don't ask how generate DOCX template by python!

Related