userPyGeo
userPyGeo

Reputation: 3971

Python-docx find and replace image in table

How do I find an existing image in MS document table and replace it with a new one? With this code am able to find table cell/location of an image and add new image, but it doesn't replace the old image.

from docx import Document
from docx.shared import Inches


doc = docx.Document('myWordDoc.docx')

tables = doc.tables

# Find existing image and remove it then add new image

img = tables[0].rows[0].cells[0].add_paragraph()
r = img.add_run()
r.add_picture('/tmp/foo.jpg', width=Inches(2.5))

Is this possible with python-docx module or any other module?

Upvotes: 7

Views: 8097

Answers (2)

Farhan Hai Khan
Farhan Hai Khan

Reputation: 808

Perhaps try using https://github.com/khanfarhan10/PythonCertificateGenerator/blob/main/ImageReplacer.py and suit the code to yourself!

All file manipulations are performed using python ZipFile.

Upvotes: 2

Michael Larsson
Michael Larsson

Reputation: 197

I replaced your 3 last lines of code:

img = tables[0].rows[0].cells[0].add_paragraph()
r = img.add_run()
r.add_picture('/tmp/foo.jpg', width=Inches(2.5))

With something like this

#This seams to clear the content in my cell
tables[0].rows[0].cells[0]._element.clear_content()

#Then when the image is inserted to the cell it is not placed one linefeed down.
img = tables[0].rows[0].cells[0].add_paragraph().add_run().add_picture('Image.png', width=Inches(0.4))

It seams to work for me, but a big thanks for your question it put me on the right track, It was not only hard to remove the image, when I added the new image it was a line feed down. But my code, that is a bit compact fixed both of the problems.

Thanks!

Upvotes: 5

Related Questions