Search code examples
python-3.xpython-docx

Add a set of images after a specific text in a word file with Python docx


I have a set of images in a folder and I am trying to insert them into a word file. Each image has a number as an indicator and I want to insert them right after a specific tag I put in the document. The thing is Pyton's docx is only adding the images at the end of the document.

This is the portion of the code where I add the images:

for par in doc.paragraphs:
   tag='[First set of images]')
   if tag in par.text:
       doc.add_picture(alt_file+'\\'+imgs[1],width=Cm(22.51))
       doc.save(docs[1])enter code here

Solution

  • If the number is in a paragraph by itself, you can add a picture in a run following the text (but still in the same paragraph) like this:

    if tag in paragraph.text:
        run = paragraph.add_run()
        run.add_picture("image.png", ...)
    

    The details of the Run.add_picture() call are in the API documentation here:
    https://python-docx.readthedocs.io/en/latest/api/text.html#run-objects