Create online PDF converter using JS

Kostas, Developer

Most documents are processed digitally in this technology age, and converting files to PDF has become a daily task. There are plenty of PDF converters online, and we thought it would be fun to show you how to make one using our ConvertAPI JS library. The same can be achieved using any programming language, but we will use JS for this project, so you only need basic web development skills to follow along. If you to jump straight into the code without reading the whole article, you can find a working demo on CodeSandbox.

We don't use any JS or CSS compilers to keep things simple. We want to make the example as environment-independent as possible. We wrote some HTML and CSS code to display our converter without going into detail as this is not directly related to our service - you can choose your own styling and design. The fun part is in JavaScript. Let's get into it!

The ConvertAPI JavaScript Library

We provide SDKs for the most popular programming languages. You don't need to write plain HTTP requests to our endpoints. Before coding our JavaScript engine, we'll need to import the ConvertAPI JS library into our project. There are a couple of ways to achieve this:

  1. Install the package using NPM. Simply run this line from a console: npm i convertapi-js. This is a preferred and most reliable way to manage external resources; however, it requires a module loader or a bundler. You can integrate our library into a TypeScript project as well.
  2. Load the library from our CDN <script src="https://unpkg.com/convertapi-js/lib/convertapi.js"></script>. In this example, we will use the latter approach. However, we encourage you to use NPM in your production-grade projects.

Endpoint Authentication

Once you have the library loaded, you'll want to sign up for a free account and grab your API secret. There are a couple of ways to authenticate the API requests using our JS library:

  1. Authenticate requests using the API secret: let convertApi = ConvertApi.auth({secret: 'your-api-secret'}). It is the simplest way that we will use in our example, but please note that the secret key will be exposed to the client-side and might be considered unsafe to use in your production environment. You can generate a new secret at any time if you notice any suspicious activity. You can find and manage the API secret in your dashboard.
  2. Authenticate requests using Authentication Token: let convertApi = ConvertApi.auth({token: '<YOUR_TOKEN>'});. This is considered a safer method because each token can have a maximum request count and a lifetime in seconds. It would be best for a client-side-based application to create a new token for every conversion request. However, it would help if you had some backend infrastructure to generate your tokens as it requires you to use an API Secret. Tokens are created using the /token endpoint or generated manually in your control panel.

You can read more about authentication methods in our documentation.

Let's start coding...

We will create a simple document converter that accepts a predefined set of document types and converts it to a PDF right away. However, if the uploaded document is a PDF, we will show a dialog with the destination format selection. Let's create an index.html, index.js, and style.css files for our project. Once we have our HTML + CSS ready, we can connect things up in our index.js file.

For the sake of simplicity, let's say we only want to accept these document types:

// Accepted document types
const documentTypes = [
  "pdf",
  "doc",
  "docx",
  "odt",
  "xls",
  "xlsx",
  "ppt",
  "pptx",
  "key",
  "numbers",
  "slides",
  "odt",
  "txt",
  "rtf",
  "jpeg",
  "png"
];

Let's write a file upload function that will handle the selected file. We will check if the file is valid, then show the destination format selection dialog or instantly convert it to a PDF.

// File upload function
function uploadFile(file, destination = 'pdf') {
  // get file extension
  const extension = file.name.split(".").pop();
  // get file size
  const fileSize = file.size;
  // If uploaded document is PDF and destination is not set
  if(extension == 'pdf' && !workArea.classList.contains('work-area--Select-destination')) {
    // show destination selection dialog
    ...
  } else {
    // Check if file is valid
    if (fileValidate(extension, fileSize)) {
      // manage our front-end view
	  ...
      // Attempt to convert a file
      convertFile(file, extension, destination);
    }
    else {
      // in case an invalid file was uploaded - reset form
      location.reload();
    }
  }
}

Having a predefined list of document types, we can implement a simple file validation function that gets called upon file upload. In this example we will check whether the file has a valid extension and validate the maximum file size (let's say 2MB for the demo purposes, however there is no such limit on our endpoints):

// File validation function
function fileValidate(fileType, fileSize) {
  // File type validation
  let isDocument = documentTypes.filter((type) => fileType.indexOf(type) !== -1);
  // If uploaded file is a valid document
  if (isDocument.length !== 0) {
    // Check if file size is 2MB or less
    if (fileSize <= 2000000) {
      return true;
    } else {
      // Show the file size validation error
      return alert('Max file size is 2 MB');
    };
  } else {
      // Show the file type validation error
    return alert(`Please make sure to upload a document. Supported formats are:\r\n.${[...documentTypes].join(', .')}.`);
  };
};

Once the uploaded file is validated, we can finally convert it. In this simple example, we only pass a single parameter containing a file we want to convert. Each conversion has multiple advanced properties. If you want to find out what each conversion is capable of, please find the conversion on our live demo page, or by calling our converter's https://v2.convertapi.com/info endpoint. For the sake of brevity we will apply the conversion with the default parameters. So our conversion function looks like this:

function convertFile(file, extension, destination) {
    // Initialize ConvertAPI with your secret key
    let convertApi = ConvertApi.auth({secret: 'your-api-secret'});
    // Create conversion parameters object
    let params = convertApi.createParams();
    // set uploaded file as one of the parameters 
    params.add('file', file);
    // execute the conversion
    convertApi.convert(extension, destination, params).then(x => {
      let result = x.dto;
      // check if success
      if(result.Files) {
        // show result download
		...
      } else {
        // handle error
        loadingText.textContent = `Ooops! ${result.Message}`;
        ...
      }
    }, (error) => {
      // Throw a network-related error here
      throw(error);
    });
}

And that's all it takes to get our converter going! You can find the whole project source code on GitHub.

Creating a dynamic converter

Our REST API service supports more than 500+ file formats. All of them can be found in our documentation. They can also be fetched dynamically using a simple GET request:

[GET]
https://v2.convertapi.com/info

This endpoint returns a complete list of available converters and their required and optional parameters. Using this endpoint, you can implement a dynamic converter that can handle all file types supported by our service. We are constantly improving our API and introducing new conversions from time to time. Therefore, if you want to make the most of our service, we encourage you to use this dynamic approach. Keep in mind that some converters require extra parameters to complete the conversion. For example, PDF -> ENCRYPT conversion requires the user to set a password, while PDF -> WATERMARK requires a watermark text or an image overlay. Suppose you want to see the PDF to ENCRYPT converter parameters:

[GET]
https://v2.convertapi.com/info/pdf/to/encrypt

As you can see, it returns the same result as the /info endpoint but is filtered by a specific conversion. This JSON contains all properties and their data types. Based on this information, it is possible to create a neat form for the end-users to adjust the conversion based on their needs.

Conclusion

In this quick example, we demonstrated how simple it is to create your own document converter using a ConvertAPI JS library. You can find full project source on GitHub and a working demo hosted on CodeSandbox. There are more advanced JS examples in our GitHub's examples folder.

You can create a similar document converter using Python, Node JS, DotNet, Java, PHP and other programming languages. Feel free to tweak the code snippets based on your needs and create your superb document converter!