Document and file conversion library for Java

Shanika Wickramasinghe

As a developer, you will encounter many scenarios where you will need to convert a file from one type to another. In one instance, you might need to convert a PNG image into a more web-friendly WebP format to improve page load times. In another instance, you would have to convert a DOCX file into a PDF to resolve compatibility issues.

On such occasions, you may have realized that converting file types can be quite a hassle. It can cost your company time, money, and resources. However, with ConvertAPI, you can easily convert file types, ensuring your projects are fast and efficient!

ConvertAPI supports conversion among over 200 file formats, including popular ones like MS Office, Web, PDF, and more. Our service simplifies the coding process by providing you with a code snippet that you can insert into your code in any programming language to make it work. It's that easy!

This article is for Java developers. In this article, we'll show you how easy it is to convert files between different formats using ConvertAPI.

Prerequisites

To start working with ConvertAPI, you first need to sign up. We offer a generous trial package that allows you to try out 250 file conversions. Once you sign up, you will receive your API secret, which is required for file conversions in your project.

Your API Secret and API key

Next, We assume you have already installed Java and Maven on your machine. If not, you can easily download and install them from their official websites provided below. Java Download Maven Download

We also assume you have a working Java project. However, for demonstration purposes, Let’s create a new Maven project with the following command.

mvn archetype:generate “-DgroupId=com.example” “-DartifactId=convertapi-example” “-DarchetypeArtifactId=maven-archetype-quickstart” “-DinteractiveMode=false”

Executing this command will generate a simple Maven project with a pom.xml file.

Next, to use the ConvertAPI SDK in your project, you need to include the following dependency in your pom.xml file.

<dependency>
	<groupId>com.convertapi.client</groupId>
	<artifactId>convertapi</artifactId>
	<version>2.10</version>
</dependency>

Next, run the following command to install dependencies and build the project.
mvn clean install

In the next section, we will write our code. So let’s get to it!

Converting DOCX to PDF

In this tutorial, We’ll show you how to convert DOCX files to PDF format using a very simple code snippet. To make things easy, you can use our demo tool, which will provide you with the necessary code snippet once you input the required information.

Let's see how it works. First, choose the type of conversion you need. For this example, let’s go with 'DOCX to PDF'.

Select DOCX to PDF API converter tool

If you only need a straightforward conversion, select the programming language of your project. Our tool will provide you with the code snippet with default configurations.

DOCX to PDF converting code snippet for Java Language

However, if you want further customizations, you can select them from the advanced properties. It will show you all the customization options available for that particular conversion.

Selecting advanced properties

For this example tutorial, Let’s set ConvertMarkups, ConvertTags, and ConvertBookmarks to True.

setting ConvertMarkups, ConvertTags, and ConvertBookmarks to True in advanced properties

This will make the necessary changes in the code snippet to make the conversions.

Config.setDefaultSecret("your-api-secret");
ConvertApi.convert("docx", "pdf",
	new  Param("File", Paths.get("/path/to/my_file.docx")),
	new  Param("ConvertMarkups", "true"),
	new  Param("ConvertTags", "true"),
	new  Param("ConvertBookmarks", "true")
).get().saveFilesSync(Paths.get("/path/to/result/dir"));

Let’s go ahead and add this code snippet with relevant imports to a project. Next, we’ll have a DOCX file called 'example' in the project folder, convert it to PDF, and save it in the results folder.

package com.example;

import java.nio.file.Paths;
import com.convertapi.client.Config;
import com.convertapi.client.ConvertApi;
import com.convertapi.client.Param;


public class App
{
    public static void main( String[] args )
    {
        Config.setDefaultSecret("your-api-secret");


        try {
            ConvertApi.convert("docx", "pdf",
                new Param("File", Paths.get("D:\\Code samples\\Java\\Converter API examples\\convertapi-example\\example.docx")),
                new Param("ConvertMarkups", "true"),
                new Param("ConvertTags", "true"),
                new Param("ConvertBookmarks", "true")
            ).get().saveFilesSync(Paths.get("D:\\Code samples\\Java\\Converter API examples\\convertapi-example\\result"));


            System.out.println("Conversion completed successfully!");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error during conversion: " + e.getMessage());
        }
    }
}
  

Let's compile the project and execute it with the following commands.

mvn clean compile mvn exec:java -Dexec.mainClass=com.example.App

After executing these commands, you will find a PDF file in the results folder.

Folder structure after runnign the above command which shows the PDF is created by running the above code

Happy with the result? Let’s try out another example.

Converting PNG to PDF

In this example, We'll show you how to convert a PNG to PDF. As we mentioned earlier, you need to select the appropriate tool for this conversion. Then, you need to determine the type of parameters you want to define for the conversion using advanced properties.

Let’s have the resulting PDF to be in A4 size and landscape orientation. Moreover, let’s add a color space of RGB to it.

After selecting all the properties to define for the conversion, you’ll be able to see the following code snippet.

Config.setDefaultSecret("your-api-secret");
ConvertApi.convert("png", "pdf",
   new Param("File", Paths.get("/path/to/my_file.png")),
   new Param("PageSize", "a4"),
   new Param("PageOrientation", "landscape"),
   new Param("ColorSpace", "rgb")
).get().saveFilesSync(Paths.get("/path/to/result/dir"));

Let’s include it in the project and run the code as we did in the above example. Here’s the final code.

package com.example;


import java.nio.file.Paths;
import com.convertapi.client.Config;
import com.convertapi.client.ConvertApi;
import com.convertapi.client.Param;

public class App
{
    public static void main( String[] args )
    {
        Config.setDefaultSecret("your-api-secret");
        try {
            ConvertApi.convert("png", "pdf",
                    new Param("File", Paths.get("D:\\Code samples\\Java\\Converter API examples\\convertapi-example\\example1.png")),
                    new Param("PageSize", "a4"),
                    new Param("PageOrientation", "landscape"),
                    new Param("ColorSpace", "rgb")
            ).get().saveFilesSync(Paths.get("D:\\Code samples\\Java\\Converter API examples\\convertapi-example\\result"));


            System.out.println("Conversion completed successfully!");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error during conversion: " + e.getMessage());
        }
    }
}

After compiling the code and running it with the following commands, you’ll get a PDF file from the input PNG image.

mvn clean compile mvn exec:java -Dexec.mainClass=com.example.App

Folder structure after running the above command which shows the PDF is created by running the above code

Key Takeaways

With the use of ConvertAPI tools, conversion has never been easier! Our service streamlines the integration of code snippets, simplifying the developer's role. So yes, it's a cheat code (pun intended).

And it's not just limited to Java; ConvertAPI offers SDK libraries for various programming languages like Python, Ruby, C#, JavaScript - you name it.

In the unlikely event of a conversion failure, if you require assistance solving the problem, you can zip the files that are failing and upload them to your dashboard's Issue Tracker section, and we'll provide you with the solution to continue your development!