Skip to main content
Practice

Inserting and Styling Images in Your Document

When working on a document, there are times when you need to insert images to help convey the content more intuitively.

Using python-docx, you can programmatically insert images into a document and adjust their size and position.

In this lesson, we will learn how to insert and resize images in your document.


Inserting an Image

To insert an image into your document, use the add_picture() method.

This method takes the file path as an argument and adds the image to the document.

Inserting an Image
doc.add_picture('image.png')

The code above inserts the 'image.png' file into the document.

The image file path can be specified using a relative path or an absolute path.


Resizing an Image

After inserting an image, you can use the Inches or Cm classes to resize it.

This is useful for adjusting the width or height of an image to the desired size.

Resizing an Image
from docx.shared import Inches

doc.add_picture('image.png', width=Inches(2))

The code above sets the width of the image to 2 inches when inserting it into the document.

If the height is not specified, it will be automatically adjusted to maintain the aspect ratio.

Adjusting Both Width and Height of an Image
doc.add_picture('image.png', width=Inches(2), height=Inches(3))

This example sets the width to 2 inches and the height to 3 inches when inserting the image.


Can We Precisely Adjust the Image Position?

With python-docx, you cannot precisely position an image in terms of how far from the top or left it should appear.

Therefore, if precise image positioning is needed, it is best to insert the image programmatically first and then manually adjust its position by opening the Word file.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.