Add an image in a specific position in the document (.docx)? Add an image in a specific position in the document (.docx)? python python

Add an image in a specific position in the document (.docx)?


Quoting the python-docx documentation:

The Document.add_picture() method adds a specified picture to the end of the document in a paragraph of its own. However, by digging a little deeper into the API you can place text on either side of the picture in its paragraph, or both.

When we "dig a little deeper", we discover the Run.add_picture() API.

Here is an example of its use:

from docx import Documentfrom docx.shared import Inchesdocument = Document()p = document.add_paragraph()r = p.add_run()r.add_text('Good Morning every body,This is my ')r.add_picture('/tmp/foo.jpg')r.add_text(' do you like it?')document.save('demo.docx')


well, I don't know if this will apply to you but here is what I've done to set an image in a specific spot to a docx document:I created a base docx document (template document). In this file, I've inserted some tables without borders, to be used as placeholders for images. When creating the document, first I open the template, and update the file creating the images inside the tables. So the code itself is not much different from your original code, the only difference is that I'm creating the paragraph and image inside a specific table.

from docx import Documentfrom docx.shared import Inchesdoc = Document('addImage.docx')tables = doc.tablesp = tables[0].rows[0].cells[0].add_paragraph()r = p.add_run()r.add_picture('resized.png',width=Inches(4.0), height=Inches(.7))p = tables[1].rows[0].cells[0].add_paragraph()r = p.add_run()r.add_picture('teste.png',width=Inches(4.0), height=Inches(.7))doc.save('addImage.docx')


Here's my solution. It has the advantage on the first proposition that it surrounds the picture with a title (with style Header 1) and a section for additional comments. Note that you have to do the insertions in the reverse order they appear in the Word document.

This snippet is particularly useful if you want to programmatically insert pictures in an existing document.

from docx import Documentfrom docx.shared import Inches# ------- initial code -------document = Document()p = document.add_paragraph()r = p.add_run()r.add_text('Good Morning every body,This is my ')picPath = 'D:/Development/Python/aa.png'r.add_picture(picPath)r.add_text(' do you like it?')document.save('demo.docx')# ------- improved code -------document = Document()p = document.add_paragraph('Picture bullet section', 'List Bullet')p = p.insert_paragraph_before('')r = p.add_run()r.add_picture(picPath)p = p.insert_paragraph_before('My picture title', 'Heading 1')document.save('demo_better.docx')