Giter Club home page Giter Club logo

convertapi-java's Introduction

ConvertAPI Java Client

Convert your files with our online file conversion API

The ConvertAPI helps converting various file formats. Creating PDF and Images from various sources like Word, Excel, Powerpoint, images, web pages or raw HTML codes. Merge, Encrypt, Split, Repair and Decrypt PDF files. And many others files manipulations. In just few minutes you can integrate it into your application and use it easily.

The ConvertAPI-Java library makes it easier to use the Convert API from your Java 8 projects without having to build your own API calls. You can get your free API secret at https://www.convertapi.com/a

Installation

Maven

Add the following dependency to your pom.xml:

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

Usage

Configuration

You can get your secret at https://www.convertapi.com/a

Config.setDefaultSecret("your-api-secret");
// or token authentication
Config.setDefaultToken("your-token");
Config.setDefaultApiKey("your-api-key");

File conversion

Example to convert DOCX file to PDF. All supported formats and options can be found here.

CompletableFuture<ConversionResult> result = ConvertApi.convert("docx", "pdf", new Param("file", Paths.get("test.docx")));

// save to file
result.get().saveFile(Paths.get("my_file.pdf")).get();

Other result operations:

// save all result files to folder
result.get().saveFiles(Paths.get("/tmp"));

// get result file
ConversionResultFile file = result.get().getFile(0);

// get conversion cost
Integer cost = result.get().conversionCost();

Convert file url

CompletableFuture<ConversionResult> result = ConvertApi.convert("pptx", "pdf",
    new Param("file", "https://cdn.convertapi.com/cara/testfiles/presentation.pptx")
);

Additional conversion parameters

ConvertAPI accepts extra conversion parameters depending on converted formats. All conversion parameters and explanations can be found here.

CompletableFuture<ConversionResult> result = ConvertApi.convert("pdf", "jpg",
        new Param("file", Paths.get("test.pdf")),
        new Param("scaleimage", "true"),
        new Param("scaleproportions", "true"),
        new Param("imageheight", 300)
);

User information

You can always check the remaining conversions amount and other account information by fetching user information.

User user = ConvertApi.getUser();
int conversionsTotal = user.ConversionsTotal;
int conversionsConsumed = user.ConversionsConsumed;

Alternative domain

Create Config instance with the alternative domain and provide it in convert method. Dedicated to the region domain list.

Config config = new Config(secret, "https", "eu-v2.convertapi.com", 0, httpClientBuilder);

More examples

You can find more advanced examples in the examples folder.

Converting your first file, full example:

ConvertAPI is designed to make converting file super easy, the following snippet shows how easy it is to get started. Let's convert WORD DOCX file to PDF:

import com.convertapi.ConvertApi;

public class SimpleConversion {
    public static void main(String[] args) {
        ConvertApi.convert("source.docx", "result.pdf", "your-api-secret");
    }
}

This is the bare-minimum to convert a file using the ConvertAPI client, but you can do a great deal more with the ConvertAPI Java library. Take special note that you should replace your-api-secret with the secret you obtained in item two of the pre-requisites.

Issues & Comments

Please leave all comments, bugs, requests, and issues on the Issues page. We'll respond to your request ASAP!

License

The ConvertAPI Java Library is licensed under the MIT license. Refer to the LICENSE file for more information.

convertapi-java's People

Contributors

dependabot[bot] avatar jonas-jasas avatar jonasjasas avatar kmozsi avatar kostas-jonauskas avatar lakshmikantdeshpande avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

convertapi-java's Issues

java.nio.file is not generally available on Android

Thanks for making this source available. I wish to use it on Android, but java.nio.file was not added until the latest released version, Android 8.x. Supporting only the latest release of Android is not a viable option for most developers.

I don't want to fork this unnecessarily, so I'm first wondering if you've considered making the API work on Android as well?

Add ability to supply executor to client

We'd like to be able to pass an Executor to the convert methods so that we can have better control of async operations. Right now your client calls CompletableFutures.supplyAsync(() -> {/*code*/}) which uses the ForkJoinPool.commonPool().

Limitation on byte size (inputstream)

Hello,
I am trying to pass an inputstream to Param() but i am always getting : "expected 1024 bytes but received 8192".
Here how i am trying to use:

try (InputStream inputStream = fileData.getBody(InputStream.class)) {
String documentId = documentService.compressDocument( owner, titleString, new Origin(OriginType.WIDERSPRUCH, caseId), fileData.getFileName(), fileData.getMediaType().getType() + "/" + fileData.getMediaType().getSubtype(), inputStream, documentType);
return Response.ok(new Success(documentId)).build();
}
Here i am receiving the file as inputPart then i am converting it to inputstream, then i am passing these parameters to convert function like the following : InputStream resultStream = convertService.convert("pdf", "compress", inputStream, filename);

Close OkHttpClient responses

When using client this is logged to console all the time:

Jun 18, 2021 9:20:40 AM okhttp3.internal.platform.Platform log
WARNING: A connection to https://v2.convertapi.com/ was leaked. Did you forget to close a response body? To see where this was allocated, set the OkHttpClient logger level to FINE: Logger.getLogger(OkHttpClient.class.getName()).setLevel(Level.FINE);

Convertapi 2.2 to 2.9 - Error: java.lang.NoClassDefFoundError: Could not initialize class com.convertapi.client.Http

Hello,
I am using Netbeans IDE 15 and JDK14. When I changed com.convertapi.client from 2.2 to 2.9, I started getting the error "java.lang.NoClassDefFoundError: Could not initialize class com.convertapi.client.Http" and the connection was not opening.

As a solution, I added the below jar in maven.

 <dependency>
         <groupId>org.jetbrains.kotlin</groupId>
         <artifactId>kotlin-stdlib</artifactId>
         <version>1.3.70</version>
     </dependency>

When I added this jar it worked fine.

"InvalidParameters":{"Timeout":["The field Timeout must be between 10 and 1200."]}

Getting the error "InvalidParameters":{"Timeout":["The field Timeout must be between 10 and 1200."]}, when running the sample conversion as below:

System.out.println("Converting WEB to PDF");
CompletableFuture result = ConvertApi.convert("web", "pdf",
new Param("url", "https://en.wikipedia.org/wiki/Data_conversion"),
new Param("filename", "web-example")
);

    Path tmpDir = Paths.get(System.getProperty("java.io.tmpdir"));
    CompletableFuture<Path> pdfFile = result.get().saveFile(tmpDir);

    System.out.println("PDF file saved to: " + pdfFile.get().toString());

Note: This is the code snippet from the examples provided by you.

System.console() is null when using an IDE

This error is triggered when trying to execute any logic by using any IDE(Idea, Eclipse, etc)

E.G. Execute UserInformation.java by using Idea/Eclipse and the following error will be triggered and no logic is being executed.

Caused by: java.lang.NullPointerException
	at com.convertapi.client.Http.getRequestBuilder(Http.java:62)
	at com.convertapi.client.Param.lambda$upload$1(Param.java:98)

Possible fix:


    static Request.Builder getRequestBuilder() {
        if (System.console() == null) {
            System.out.printf("VERSIJA: %s", Http.class.getPackage().getImplementationVersion());
        } else {
            System.console().printf("VERSIJA: %s", Http.class.getPackage().getImplementationVersion());
        }
        String agent = String.format("ConvertAPI-Java/%.1f (%s)", Http.class.getPackage().getImplementationVersion(), System.getProperty("os.name"));
        return new Request.Builder().header("User-Agent", agent);
    }

error on local file IllegalFormatConversionException

this is the full kotlin code

@RequiresApi(Build.VERSION_CODES.Q)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    when(requestCode){
        SELECT_REQUEST -> {
            val input = data!!.data
            val folder: File? = Environment.getExternalStoragePublicDirectory("${Environment.DIRECTORY_DOWNLOADS}/pptToPdf/")
            Config.setDefaultSecret("SECRET_CODE")
            ConvertApi.convert("pptx", "pdf",
                    Param("file", Paths.get(getFilePath(input!!)))
            ).get().saveFile(Paths.get(folder!!.path)).get()

        }
        else -> return
    }
}

@RequiresApi(Build.VERSION_CODES.Q)
private fun getFilePath(uri: Uri):String{
    val path = uri.path
            val filename = path!!.substring(path.lastIndexOf("/") + 1)
    val file = File(externalCacheDir, filename)
    file.createNewFile()
    FileOutputStream(file).use { outputStream ->
        contentResolver.openInputStream(uri).use { inputStream ->
            if (inputStream != null) {
                FileUtils.copy(inputStream, outputStream)
            }
            outputStream.flush()
        }
    }
    return file.path
}

AND THE ERROR IS

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.chavhan.pdfconverterfromoffice, PID: 5828
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1002, result=-1, data=Intent { dat=content://com.android.externalstorage.documents/document/primary:Download/pptexamples.ppt flg=0x1 }} to activity {com.chavhan.pdfconverterfromoffice/com.chavhan.pdfconverterfromoffice.MainActivity}: java.util.concurrent.ExecutionException: java.util.IllegalFormatConversionException: f != java.lang.String
at android.app.ActivityThread.deliverResults(ActivityThread.java:4845)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4886)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.util.concurrent.ExecutionException: java.util.IllegalFormatConversionException: f != java.lang.String
at java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:361)
at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1923)
at com.chavhan.pdfconverterfromoffice.MainActivity.onActivityResult(MainActivity.kt:120)
at android.app.Activity.dispatchActivityResult(Activity.java:8110)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4838)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4886) 
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:7356) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 
Caused by: java.util.IllegalFormatConversionException: f != java.lang.String
at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4403)
at java.util.Formatter$FormatSpecifier.printFloat(Formatter.java:2898)
at java.util.Formatter$FormatSpecifier.print(Formatter.java:2845)
at java.util.Formatter.format(Formatter.java:2524)
at java.util.Formatter.format(Formatter.java:2459)
at java.lang.String.format(String.java:2870)
at com.convertapi.client.Http.getRequestBuilder(Http.java:61)
at com.convertapi.client.ConvertApi.lambda$convert$0(ConvertApi.java:73)
at com.convertapi.client.-$$Lambda$ConvertApi$DHu1fqnXgXGPutW81zP_QKRvc6Y.get(Unknown Source:8)
at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1627)
at java.util.concurrent.CompletableFuture$AsyncSupply.exec(CompletableFuture.java:1619)
at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:285)
at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1155)
at java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1993)
at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1941)
at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)

Is there an example of working with IO streams over File/Path?

So I have a case where I have no file system representation of the document and only have either an IO stream or byte[] on hand to work with. I seem to struggle to find an example for my case, can someone pinpoint it please or let me know how can one work with IO streams or byte arrays?

Add user agent header

Add user agent header in such format

User-Agent: "convertapi-java-{LibraryVersion}"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.