How to convert any document into a Thumbnail PNG Image in Python
Creating thumbnail images from documents is actually quite a bit more complicated of a task than you might at first think. The document’s format must first be determined, then its contents rendered over a white background, the pages split, and then there’s image resizing and aspect ratios. Man, what a mess. But there is hope! Hope in the form of an API that has already solved all of these problems and will handle all of your thumbnail needs with no complaints and very little effort on your part.
We begin with installation; use this command.
pip install cloudmersive-convert-api-client
Now call convert_document_autodetect_to_thumbnail. You may optionally specify the size, as well as file extension, which comes into play as an insurance policy for unsupported files that are not directly imported (such as byte arrays and memory streams).
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 that’s it! Talk about simple.