How to Insert an Image into a DOCX File in Python

While on your DOCX editing journey, you may need to add an image into the document. If so, you can open up the file for editing with our Begin Editing function, and use the following function to insert the image. Executing this quick and easy process will take the pain out of editing, and provide you with a quality result.

Before we get started, you want to make sure you have the information for the following request configuration ready to go:

{
"InputFileBytes": "string",
"InputFileUrl": "string",
"ParagraphToInsert": {
"ParagraphIndex": 0,
"Path": "string",
"ContentRuns": [
{
"RunIndex": 0,
"Path": "string",
"TextItems": [
{
"TextIndex": 0,
"Path": "string",
"TextContent": "string"
}
],
"Bold": true,
"Italic": true,
"Underline": "string",
"FontFamily": "string",
"FontSize": "string"
}
],
"StyleID": "string"
},
"InsertPlacement": "string",
"InsertPath": "string"
}

Now, we can run this command to install the SDK:

pip install cloudmersive-convert-api-client

Then, we can call the function:

from __future__ import print_function
import time
import cloudmersive_convert_api_client
from cloudmersive_convert_api_client.rest import ApiException
from pprint import pprint
# Configure API key authorization: Apikey
configuration = cloudmersive_convert_api_client.Configuration()
configuration.api_key['Apikey'] = 'YOUR_API_KEY'
# create an instance of the API class
api_instance = cloudmersive_convert_api_client.EditDocumentApi(cloudmersive_convert_api_client.ApiClient(configuration))
req_config = cloudmersive_convert_api_client.InsertDocxInsertParagraphRequest() # InsertDocxInsertParagraphRequest | Document input request
try:
# Insert a new paragraph into a Word DOCX document
api_response = api_instance.edit_document_docx_insert_paragraph(req_config)
pprint(api_response)
except ApiException as e:
print("Exception when calling EditDocumentApi->edit_document_docx_insert_paragraph: %s\n" % e)

This will successfully add the image to your Word document, and return your edited URL. If you have other editing operations to perform, you can move on to those. Alternatively, if you have no further changes, you can use the Finish Editing API to solidify your changes and download your updated document.

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.