Sign in

How to convert a DOCX document into a Thumbnail PNG Image in Python

Creating a custom thumbnail for a DOCX page has never been an easier task for all you Python users out there. We will be skipping the lengthy process of rendering documents, converting them into images, resizing, and several other steps that I won’t mention. This means getting straight to real results that you can implement into your project in a couple minutes. How, you ask? Cloudmersive has an API for that.

So let’s install that API’s client with the following command.

pip install cloudmersive-convert-api-client

Now we can call convert_document_autodetect_to_thumbnail, which is simple if you follow our lovely example here:

from __future__ import print_functionimport timeimport cloudmersive_convert_api_clientfrom cloudmersive_convert_api_client.rest 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.ConvertDocumentApi(cloudmersive_convert_api_client.ApiClient(configuration))input_file = '/path/to/file' # file | Input file to perform the operation on.max_width = 56 # int | Optional; Maximum width of the output thumbnail - final image will be as large as possible while less than or equal to this width. Default is 128. (optional)max_height = 56 # int | Optional; Maximum height of the output thumbnail - final image will be as large as possible while less than or equal to this width. Default is 128. (optional)extension = 'extension_example' # str | Optional; Specify the file extension of the inputFile. This will improve the response time in most cases. Also allows unsupported files without extensions to still return a corresponding generic icon. (optional)try:# Convert File to Thumbnail Imageapi_response = api_instance.convert_document_autodetect_to_thumbnail(input_file, max_width=max_width, max_height=max_height, extension=extension)pprint(api_response)except ApiException as e:print("Exception when calling ConvertDocumentApi->convert_document_autodetect_to_thumbnail: %s\n" % e)

And your results await. Super easy.

Image for post
Image for post

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store