How to Convert a Document to PDF using JavaScript

Cloudmersive
2 min readAug 18, 2022

--

Easily transferrable, flexible, secure… the list of reasons why PDFs are such a popular file format goes on and on and on. With that in mind, it should be as easy to convert documents to PDF in your code as it is to click the “export PDF” button in another application — and thankfully, there’s an API for that. Our Document to PDF conversion API will automatically detect the input file type (include all major office document formats & over 100 image format types) and convert it to PDF format with zero additional hassle. The best part? You can take advantage of this API in just a few simple steps by using the ready-to-run code examples provided below to structure your API call. Other than that, you’ll just need a Cloudmersive API key, which you can easily obtain by registering a free account on our website.

We can structure this API call in two different ways with JavaScript. The first way uses the XHR feature that JavaScript has built-in. Use the below code examples to go that route:

var data = new FormData();
data.append("inputFile", fileInput.files[0], "file");

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function() {
if(this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://api.cloudmersive.com/convert/autodetect/to/pdf");xhr.setRequestHeader("Apikey", "YOUR-API-KEY-HERE");xhr.send(data);

Alternatively, you can first install the jQuery library using the below command:

bower install jquery

And then include the following code to structure your call:

var form = new FormData();
form.append("inputFile", fileInput.files[0], "file");
var settings = {
"url": "https://api.cloudmersive.com/convert/autodetect/to/pdf",
"method": "POST",
"timeout": 0,
"headers": {
"Content-Type": "multipart/form-data",
"Apikey": "YOUR-API-KEY-HERE"
},
"processData": false,
"mimeType": "multipart/form-data",
"contentType": false,
"data": form
};
$.ajax(settings).done(function (response) {
console.log(response);
});

After that, you’re all set — no more code required. Nice and easy.

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

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

No responses yet