[Python] Replace image in Word docx format

Discussão em 'Python' iniciado por Stack, Fevereiro 21, 2025.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página