How to Convert HTML Strings to PNG Screenshots in Node.js
By rending our HTML code through a remote web service, we can easily screenshot static web content.
Using the below code, we can easily take advantage of a free API that renders and screenshots our HTML strings with full support for HTML5, JavaScript, CSS, and other advanced features.
In our request parameters, we can optionally specify how much extra loading wait our HTML code might need, and we can also customize the height and width of our resulting screenshot.
{
"Html": "string",
"ExtraLoadingWait": 0,
"ScreenshotWidth": 0,
"ScreenshotHeight": 0
}
To install the SDK, we can either run the following command:
npm install cloudmersive-convert-api-client --save
Or add the following snippet to our package.json:
"dependencies": {
"cloudmersive-convert-api-client": "^2.6.3"
}
After that, we can copy the below ready-to-run code examples into our file, and we can authorize our requests with a free-tier API key (this can be obtained on the Cloudmersive website):
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.ConvertWebApi();
var input = new CloudmersiveConvertApiClient.HtmlToPngRequest(); // HtmlToPngRequest | HTML to PNG request parameters
var callback = function(error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
apiInstance.convertWebHtmlToPng(input, callback);