Working with Images – Python .docx Module
Word documents contain formatted text wrapped within three object levels. Lowest level- run objects, middle level- paragraph objects and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module.
Python docx module allows user to manipulate docs by either manipulating the existing one or creating a new empty document and manipulating it. It is a powerful tool as it helps you to manipulate the document to a very large extend. To add an image in a word document we use add_picture() method. This method is used to add an image in your Word document whenever called.
Syntax: doc.add_picture(image_path, width=None, height=None)
- image_path: It is a string containing the path of the image to be added.
- width: It sets the width of the image to be added in the document.
- height: It sets the height of the image to be added in the document.
In the function given above, height and width are not specified then the image appears in its native size.
Pip command to install this module is:
pip install python-docx
- Import module
- Create docx object
- Declare add_picture() method wherever image is required to be inserted, along with the path to that image and dimensions(optional).
- Save document.
Example 1: Adding an image in native size in a word document.
Example 2: Adding an image in a defined size in a word document.
Please Login to comment...