How to Append an Image to an HTML Document from a URL in Node.js
If we’re making a quick change to our HTML file, we don’t always need to make that edit manually. Performing our action programmatically can save us time and increase our productivity in the long run.
Using the below code, we can take advantage of a free API that allows us to automatically append a new image from a URL to the bottom of an existing HTML file. We can specify CSS styling for our image in the input request, and our response will contain our original HTML code plus the appended image.
To use this API for free, we’ll just need a free-tier API key. This will allow a limit of 800 API calls per month with no commitment — perfect for getting new projects off the ground.
We can begin structuring our API call by installing the SDK. To do that, we can either run the following command:
npm install cloudmersive-convert-api-client --save
Or we can add the following snippet to our package.json:
"dependencies": {
"cloudmersive-convert-api-client": "^2.6.3"
}
Finally, we can include the below code in our file, configure our reqeust parameters, and call the function:
var CloudmersiveConvertApiClient = require('cloudmersive-convert-api-client');
var defaultClient = CloudmersiveConvertApiClient.ApiClient.instance;
// Configure API key authorization: Apikey
var Apikey = defaultClient.authentications['Apikey'];
Apikey.apiKey = 'YOUR API KEY';
var apiInstance = new CloudmersiveConvertApiClient.EditHtmlApi();
var imageUrl = "imageUrl_example"; // String | The URL for the image.
var opts = {
'inputFile': Buffer.from(fs.readFileSync("C:\\temp\\inputfile").buffer), // File | Optional: Input file to perform the operation on.
'inputFileUrl': "inputFileUrl_example", // String | Optional: URL of a file to operate on as input.
'cssStyle': "cssStyle_example" // String | Optional: CSS style for the image.
};
var callback = function(error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
apiInstance.editHtmlHtmlAppendImageFromUrl(imageUrl, opts, callback);
Now we can easily add new images to the bottom of our HTML documents without any manual intervention. Easy!