How to Convert HTML Documents to PNG Screenshots in Node.js

Cloudmersive
2 min readOct 6, 2023

--

Taking screenshots of our HTML documents gives us the flexibility to store static iterations of our web pages in development.

Using the ready-to-run Node.js code examples below, we can take advantage of a free API that allows us to quickly convert our HTML documents into a fully rendered PNG screenshot. We’ll get one PNG screenshot for each page of our HTML document, and we’ll also get full support for all our JavaScript/CSS/Image elements and other complex behaviors.

We can begin structuring our API call by first installing the SDK. Let’s either run the below command to install the SDK:

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

Or let’s add the below snippet into our package.json:

  "dependencies": {
"cloudmersive-convert-api-client": "^2.6.3"
}

After that, let’s copy the below code into our file, and then let’s authorize our request with a free-tier API key (we can get one by registering a free account 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.ConvertDocumentApi();

var inputFile = Buffer.from(fs.readFileSync("C:\\temp\\inputfile").buffer); // File | Input file to perform the operation on.


var callback = function(error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
apiInstance.convertDocumentHtmlToPng(inputFile, callback);

We’ll receive the encoding for our PNG file in the API response.

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

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

No responses yet