Search code examples
pythonimagereplacedocx

Replace image in Word docx format


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?


Solution

  • So, this worked for me using docxtpl and a template I modified in MS Word:

    Right click the image in MS Word, Select "View Alt Text":

    enter image description here

    Write "replace_me" as the Alt Text. Save and close.

    Then:

    from docxtpl import DocxTemplate
    
    tpl = DocxTemplate("sometemplate.docx")
    tpl.replace_pic("replace_me", "yourimage.png")
    

    Definitely worked on MS Word for Mac 2022, Version 16.69 (23010700).