1

What I want to do is insert an image into a specific location in an existing Word document using Python. I've looked at various libraries to do this; I'm using the docx-mailmerge package to insert text and tables using Word merge fields, but unfortunately image merging is just a TODO/wishlist feature. python-docx meanwhile allows image insertion, but only at the end of a document, not in specific places.

Is there another library that does this, or a good trick to accomplish it?

dasboth
  • 216
  • 3
  • 12

1 Answers1

2

Fiddling around with the underlying API (and thanks to this SO answer) I hacked my way to success:

  1. add a placeholder in your Word document where the image should go, something like a single line that says [ChartImage1]
  2. find the paragraph object in the document that contains that text
  3. replace the text of that paragraph with an empty string
  4. add a run, and inside that add your image

So something like:

document = Document("template.docx")
image_paras = [i for i, p in enumerate(document.paragraphs) if "[ChartImage1]" in p.text]
p = document.paragraphs[image_paras[0]]
p.text = ""
r = p.add_run()
r.add_picture("path/to/image.png")
document.save("my_doc.docx")
dasboth
  • 216
  • 3
  • 12