How to Easily Convert Common Documents to PDF in Nodejs
What could be easier than calling a single free API to convert multiple unique document formats to PDF?
We can take advantage of the below ready-to-run Nodejs code examples to make conversions from a wide range of common document types (Word, Excel, PowerPoint, HTML, and 100+ image formats) to PDF.
It’s extremely easy to integrate this API into our Nodejs application. We just need to install the SDK and call a single, low-code function which autodetects our input file type and then asks the underlying service to make a high-fidelity conversion.
We’ll receive the encoding for our new PDF in the API response, and we can write that output to a new PDF file.
Let’s first install the client SDK. We can run this command to install via NPM install:
npm install cloudmersive-convert-api-client --save
Alternatively, we can just add this snippet to our package.json:
"dependencies": {
"cloudmersive-convert-api-client": "^2.6.3"
}
Next, we should quickly turn our attention to API call authorization. We’ll need a free API key to authorize our requests, and that’ll allow us to make up to 800 API calls per month with zero commitments.
We can paste our API key into the authorization variable, and we can then make the request using a file path:
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.convertDocumentAutodetectToPdf(inputFile, callback);
That’s all the code we’ll need! Now we can easily make quick API calls to convert a wide range of common document types to PDF with zero hassle.