Working with Images – Python .docx Module
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
doc = docx.Document()
doc.add_heading( 'GeeksForGeeks' , 0 )
doc.add_heading( 'Image in Native Size:' , 3 )
doc.add_picture( 'logo.png' )
doc.save( 'gfg.docx' )
|
Output:
gfg.docx
Example 2: Adding an image in a defined size in a word document.
Python3
import docx
from docx.shared import Inches
doc = docx.Document()
doc.add_heading( 'GeeksForGeeks' , 0 )
doc.add_heading( 'Image with Defined Size:' , 3 )
doc.add_picture( 'logo.png' , width = Inches( 2 ), height = Inches( 2 ))
doc.save( 'gfg.docx' )
|
Output:
gfg.docx
Last Updated :
21 Nov, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...