How to convert any document into a Thumbnail PNG Image in Node.JS

Cloudmersive
2 min readMay 28, 2020

--

Thumbnails are a great way to improve your user experience, but they can be deceptively difficult to create in an automated fashion. You first have to convert the document into a PDF, then rasterize it as an image, convert this into a PNG, and finally resize it to a thumbnail. Now repeat this setup for each type of document that you would like to support as well as create logic for determining the input file’s format. This whole process takes a huge amount of time. Instead, let’s look at a quick alternative that will provide the same results but require virtually no effort whatsoever.

We are going to use an API to achieve our results, so let’s use npm install for our client files.

npm install cloudmersive-convert-api-client --save

Now we are going to call convertDocumentAutodetectToThumbnail, as seen below.

var CloudmersiveConvertApiClient = require('cloudmersive-convert-api-client');var defaultClient = CloudmersiveConvertApiClient.ApiClient.instance;// Configure API key authorization: Apikeyvar Apikey = defaultClient.authentications['Apikey'];Apikey.apiKey = 'YOUR API KEY';// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)//Apikey.apiKeyPrefix = 'Token';var apiInstance = new CloudmersiveConvertApiClient.ConvertDocumentApi();var inputFile = "/path/to/file"; // File | Input file to perform the operation on.var opts = {'maxWidth': 56, // Number | 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.'maxHeight': 56, // Number | 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.'extension': "extension_example" // String | 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.};var callback = function(error, data, response) {if (error) {console.error(error);} else {console.log('API called successfully. Returned data: ' + data);}};apiInstance.convertDocumentAutodetectToThumbnail(inputFile, opts, callback);

You may optionally customize the size of the resulting image, as well as enter an extension for files that do not have one. The API will automatically detect the file’s format and return a thumbnail for the first page. If you would like additional pages and a higher degree of customization, there is also an advanced version of this function that is object based.

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

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

No responses yet