Add Images to Word File using Python

Here I am going to show an example how you can add images to word file in Python programming language. Generally you write headings, paragraphs, etc. to describe an event or something in the word file. To explain better pictorially about the same thing you need to insert or add images.

python-docx is a Python library for creating and updating Microsoft Word (.docx) files. I am going to use Python based python-docx module to insert images into the word (docx) file.

Prerequisites

Python 3.9.1, python-docx 0.8.10 (pip install python-docx)

Insert Images

Now I am going to write a Python script which will add images to the word file. I am adding two images to the word file. You can add as many images as you want.

I have imported the required packages from the docx module. The function add_picture() actually inserts the image to the docx file. The first parameter is mandatory and takes the full path of the image file. The second optional parameter is the width and third optional parameter is height of the image.

If you do not specify any width or height then it will take the original image’s width and height.

If you want to insert a particular image or picture at a particular page then you need to use add_page_break() function otherwise multiple pictures would be inserted into a single page if they are fit to be inserted.

Finally I saved the docx file using save() function. The output file is stored in the same path as the Python script as I have not specified any path for the output docx file.

from docx import Document
from docx.shared import Inches

document = Document()

document.add_picture('computer.jpg', width=Inches(6))

#document.add_page_break()

document.add_picture('sample.jpg')

#write to docx
document.save('images.docx')

Testing the Application

Now executing the above script will give you the following output. If you uncomment the line (remove #) for #document.add_page_break() then you will see each image is inserted into two different page of the docx file.

add images to word file in python

That’s all about how to insert or add images into word (docx) file.

Source Code

Download

Leave a Reply

Your email address will not be published. Required fields are marked *