Prerequisites: docx
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)
Parameters:
- 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.
Installation
Pip command to install this module is:
pip install python-docx
Approach
- 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.
Python3
# Import docx NOT python-docx import docx # Create an instance of a word document doc = docx.Document() # Add a Title to the document doc.add_heading( 'GeeksForGeeks' , 0 ) # Image in its native size doc.add_heading( 'Image in Native Size:' , 3 ) doc.add_picture( 'logo.png' ) # Now save the document to a location doc.save( 'gfg.docx' ) |
Output:
Example 2: Adding an image in a defined size in a word document.
Python3
# Import docx NOT python-docx import docx from docx.shared import Inches # Create an instance of a word document doc = docx.Document() # Add a Title to the document doc.add_heading( 'GeeksForGeeks' , 0 ) # Image with defined size doc.add_heading( 'Image with Defined Size:' , 3 ) doc.add_picture( 'logo.png' , width = Inches( 2 ), height = Inches( 2 )) # Now save the document to a location doc.save( 'gfg.docx' ) |
Output: