How to Convert a PDF Document to Text using JavaScript

Cloudmersive
2 min readAug 18, 2022

--

The contents of a PDF document often contain formatting carried over things like PowerPoint presentations, HTML code, and more — which means the pure text within that document is often buried under complex, inaccessible layers. That’s why it’s handy to have a way to convert PDFs directly to text — a service provided easily & efficiently by our PDF to Text conversion API. This API will simply take a PDF input and return an output of all the text included within the PDF, and it offers one optional formatting mode which allows you to specify how whitespace should be handled during the conversion (default option is ‘preserveWhitespace’). Using this API is as easy as the conversion itself — just copy & paste ready-to-run code examples included below, and authenticate using your Cloudmersive API key (you can get one for free by registering a free account on our website).

You can structure your API call using the XHR request capability in JavaScript by copying the below code examples:

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/pdf/to/txt");
xhr.setRequestHeader("textFormattingMode", "<string>");
xhr.setRequestHeader("Apikey", "YOUR-API-KEY-HERE");xhr.send(data);

And to use jQuery, first install the library by running the below command:

bower install jquery

Then use the below code examples:

var form = new FormData();
form.append("inputFile", fileInput.files[0], "file");
var settings = {
"url": "https://api.cloudmersive.com/convert/pdf/to/txt",
"method": "POST",
"timeout": 0,
"headers": {
"textFormattingMode": "<string>",
"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);
});

Once you include your API key and pass through the required parameters, you’re good to go. Note that your free account comes with a limit of 800 API calls per month and zero additional commitments, but you can easily upgrade to more extensive coverage at any time.

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

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

No responses yet