How to insert an image into a Word DOCX document in Python

We are about to set a speed record for implementing image insertion for Microsoft Word DOCX files. Ready? Go!

First, let’s get pip install working on our client:

pip install cloudmersive-convert-api-client

The example code below will demonstrate how to go about using the edit_document_docx_insert_image function. Notice we call it from an API instance.

from __future__ import print_functionimport timeimport cloudmersive_convert_api_clientfrom import ApiExceptionfrom pprint import pprint# Configure API key authorization: Apikeyconfiguration = cloudmersive_convert_api_client.Configuration()configuration.api_key['Apikey'] = 'YOUR_API_KEY'# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed# configuration.api_key_prefix['Apikey'] = 'Bearer'# create an instance of the API classapi_instance = cloudmersive_convert_api_client.EditDocumentApi(cloudmersive_convert_api_client.ApiClient(configuration))req_config = cloudmersive_convert_api_client.DocxInsertImageRequest() # DocxInsertImageRequest | Document input requesttry:# Insert image into a Word DOCX documentapi_response = api_instance.edit_document_docx_insert_image(req_config)pprint(api_response)except ApiException as e:print("Exception when calling EditDocumentApi->edit_document_docx_insert_image: %s\n" % e)

We shall then provide said function with a DocxInsertImageRequest, which consists of the following parameters:

"InputDocumentFileBytes": "string",
"InputDocumentFileUrl": "string",
"InputImageFileBytes": "string",
"InputImageFileUrl": "string",
"ImageToAdd": {
"Path": "string",
"ImageName": "string",
"ImageId": 0,
"ImageDescription": "string",
"ImageWidth": 0,
"ImageHeight": 0,
"XOffset": 0,
"YOffset": 0,
"ImageDataEmbedId": "string",
"ImageDataContentType": "string",
"ImageInternalFileName": "string",
"ImageContentsURL": "string",
"InlineWithText": true
"InsertPlacement": "string",
"InsertPath": "string",
"WidthInEMUs": 0,
"HeightInEMUs": 0

Now run the code, and you’re done!

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