Skip to content

Commit 96a7d46

Browse files
committed
1.6
2 parents a60568f + 41fa8ee commit 96a7d46

12 files changed

+448
-35
lines changed

GETTING-STARTED.md

Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
#### 1. Install the ConvertAPI library
2+
3+
Go to [ConvertAPI Java client](https://github.com/ConvertAPI/convertapi-java) page and download JAR file.
4+
Place JAR in to your project library directory.
5+
6+
7+
#### 2.a. Simple conversion methods
8+
9+
```java
10+
import com.convertapi.*;
11+
12+
Config.setDefaultSecret("your-api-secret");
13+
14+
// Simplified file to file conversion example
15+
ConvertApi.convertFile("test.docx", "/tmp/result.pdf");
16+
17+
// Simplified web site to pdf conversion example
18+
ConvertApi.convertUrl("http://example.com", "/tmp/example.pdf");
19+
20+
// Simplified remote file to local file conversion example
21+
ConvertApi.convertRemoteFile("https://cdn.convertapi.com/cara/testfiles/document.docx", "/tmp/demo.pdf");
22+
```
23+
24+
25+
#### 2.b. Convert local file
26+
27+
```java
28+
import com.convertapi.*;
29+
30+
Config.setDefaultSecret("your-api-secret");
31+
32+
//Set input and output formats and pass file parameter.
33+
//Word to PDF API. Read more https://www.convertapi.com/docx-to-pdf
34+
ConvertApi.convert("docx", "pdf",
35+
new Param("file", Paths.get("test.docx"))
36+
).get().saveFile(Paths.get("/tmp")).get();
37+
```
38+
39+
40+
#### 2.c. Convert remote file and set additional parameters
41+
42+
```java
43+
import com.convertapi.*;
44+
45+
Config.setDefaultSecret("your-api-secret");
46+
47+
//Set input and output formats and pass file parameter.
48+
//PowerPoint to PNG API. Read more https://www.convertapi.com/pptx-to-png
49+
ConvertApi.convert("pdf", "png",
50+
new Param("file", "https://cdn.convertapi.com/cara/testfiles/presentation.pptx"),
51+
new Param("scaleimage", "true"),
52+
new Param("scaleproportions", "true"),
53+
new Param("imageheight", 300)
54+
).get().saveFile(Paths.get("/tmp")).get();
55+
```
56+
57+
58+
#### 2.d. Convert from a stream
59+
60+
```java
61+
import com.convertapi.*;
62+
63+
Config.setDefaultSecret("your-api-secret");
64+
65+
// Create stream from HTML string
66+
String streamContent = "<!DOCTYPE html><html><body><h1>My First Heading</h1><p>My first paragraph.</p></body></html>";
67+
InputStream stream = new ByteArrayInputStream(streamContent.getBytes());
68+
69+
// Html to PDF API. Read more https://www.convertapi.com/html-to-pdf
70+
CompletableFuture<ConversionResult> result = ConvertApi.convert("html", "pdf",
71+
new Param("file", stream, "test.html")
72+
);
73+
74+
// PDF as stream
75+
InputStream resultStream = result.get().asStream().get();
76+
```
77+
78+
79+
#### 2.e. Conversions chaining
80+
81+
```java
82+
// Split PDF document and merge first and last pages to new PDF
83+
import com.convertapi.*;
84+
85+
Config.setDefaultSecret("your-api-secret");
86+
87+
// Set input and output formats and pass file parameter.
88+
// Split PDF API. Read more https://www.convertapi.com/pdf-to-split
89+
CompletableFuture<ConversionResult> splitResult = ConvertApi.convert("pdf", "split",
90+
new Param("file", Paths.get("test.pdf"))
91+
);
92+
93+
// Get result of the first conversion and use it in Merge conversion.
94+
// Chains are executed on server without moving files.
95+
// Merge PDF API. Read more https://www.convertapi.com/pdf-to-merge
96+
CompletableFuture<ConversionResult> mergeResult = ConvertApi.convert("pdf", "merge",
97+
new Param("files", splitResult, 0),
98+
new Param("files", splitResult, -1)
99+
);
100+
101+
mergeResult.get().saveFile(Paths.get("/tmp")).get();
102+
```
103+
104+
105+
#### 3. Read account status
106+
107+
```java
108+
import com.convertapi.*;
109+
import com.convertapi.model.*;
110+
111+
Config.setDefaultSecret("your-api-secret");
112+
113+
// Read full account data
114+
User user = ConvertApi.getUser();
115+
116+
// Find out how much seconds left
117+
int secondsLeft = user.SecondsLeft;
118+
```
119+
120+
121+
#### 4. Exception handling (asynchronous)
122+
123+
```java
124+
import com.convertapi.*;
125+
126+
Config.setDefaultSecret("your-api-secret");
127+
128+
// Creating an exception
129+
CompletableFuture<ConversionResult> resultFuture = ConvertApi.convert("pdf", "pptx",
130+
new Param("file", Paths.get("test-files/test.pdf")),
131+
new Param("AutoRotate","WrongParameter")
132+
).exceptionally(t -> {
133+
// Handling and exception
134+
System.out.println("Error message: " + t.getMessage());
135+
return null;
136+
});
137+
138+
ConversionResult result = resultFuture.get();
139+
// Saving file if there was no exception
140+
if (result != null) {
141+
result.saveFile(Paths.get("/tmp")).get();
142+
}
143+
```
144+
145+
146+
#### 5. Supported file formats, conversions and actions
147+
148+
https://www.convertapi.com/doc/supported-formats
149+
150+
#### 6. GitHub
151+
152+
https://github.com/ConvertAPI/convertapi-java

convertapi.iml

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<module type="JAVA_MODULE" version="4">
3+
<component name="NewModuleRootManager" inherit-compiler-output="true">
4+
<exclude-output />
5+
<content url="file://$MODULE_DIR$">
6+
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
7+
<excludeFolder url="file://$MODULE_DIR$/.idea" />
8+
<excludeFolder url="file://$MODULE_DIR$/lib" />
9+
<excludeFolder url="file://$MODULE_DIR$/src/com/convertapi/examples" />
10+
</content>
11+
<orderEntry type="inheritedJdk" />
12+
<orderEntry type="sourceFolder" forTests="false" />
13+
<orderEntry type="library" exported="" name="lib" level="project" />
14+
</component>
15+
</module>

src/com/convertapi/ConversionException.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
package com.convertapi;
22

3-
class ConversionException extends RuntimeException {
3+
public class ConversionException extends RuntimeException {
44
private final int httpStatusCode;
55

66
public ConversionException(String message, int httpStatusCode){

src/com/convertapi/ConversionResult.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import com.convertapi.model.ConversionResponse;
44
import com.convertapi.model.ConversionResponseFile;
55

6+
import java.io.InputStream;
67
import java.nio.file.Files;
78
import java.nio.file.Path;
89
import java.util.ArrayList;
@@ -41,7 +42,11 @@ public ConversionResultFile getFile(int index) {
4142
return new ConversionResultFile(response.Files[index]);
4243
}
4344

44-
public CompletableFuture<Path> saveFile(Path file) {
45+
public CompletableFuture<InputStream> asStream() {
46+
return getFile(0).asStream();
47+
}
48+
49+
public CompletableFuture<Path> saveFile(Path file) {
4550
return getFile(0).saveFile(file);
4651
}
4752

src/com/convertapi/ConvertApi.java

Lines changed: 69 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.convertapi;
22

33
import com.convertapi.model.ConversionResponse;
4+
import com.convertapi.model.RemoteUploadResponse;
45
import com.convertapi.model.User;
56
import com.google.gson.Gson;
67
import okhttp3.HttpUrl;
@@ -107,29 +108,89 @@ public static User getUser(Config config) {
107108
}
108109

109110
@SuppressWarnings("unused")
110-
public static CompletableFuture<ConversionResult> convert(Path fromFile, String toFormat) throws IOException {
111-
return convert(fromFile, toFormat, Config.defaults().getSecret());
111+
public static CompletableFuture<ConversionResult> convertFile(Path fromFile, String toFormat, Param... params) throws IOException {
112+
return convertFile(fromFile, toFormat, Config.defaults().getSecret(), params);
112113
}
113114

114-
public static CompletableFuture<ConversionResult> convert(Path fromFile, String toFormat, String secret) throws IOException {
115-
return convert(getFileExtension(fromFile), toFormat, new Param[]{new Param("file", fromFile)}, Config.defaults(secret));
115+
public static CompletableFuture<ConversionResult> convertFile(Path fromFile, String toFormat, String secret, Param... params) throws IOException {
116+
Param[] fileParam = new Param[]{new Param("file", fromFile)};
117+
return convert(getFileExtension(fromFile), toFormat, Param.concat(fileParam, params), Config.defaults(secret));
116118
}
117119

118120
@SuppressWarnings("unused")
119-
public static void convert(String fromPathToFile, String toPathToFile) {
120-
convert(fromPathToFile, toPathToFile, Config.defaults().getSecret());
121+
public static void convertFile(String fromPathToFile, String toPathToFile) {
122+
convertFile(fromPathToFile, toPathToFile, Config.defaults().getSecret());
121123
}
122124

123-
public static void convert(String fromPathToFile, String toPathToFile, String secret) {
125+
public static void convertFile(String fromPathToFile, String toPathToFile, String secret, Param... params) {
124126
try {
125127
Path fromPath = Paths.get(fromPathToFile);
126128
Path toPath = Paths.get(toPathToFile);
127-
convert(fromPath, getFileExtension(toPath), secret).get().saveFile(toPath).get();
129+
convertFile(fromPath, getFileExtension(toPath), secret, params).get().saveFile(toPath).get();
128130
} catch (IOException | ExecutionException | InterruptedException e) {
129131
throw new RuntimeException(e);
130132
}
131133
}
132134

135+
public static List<Path> convertFileToDir(String fromPathToFile, String toFormat, String outputDirectory, Param... params) {
136+
return convertFileToDir(fromPathToFile, toFormat, outputDirectory, Config.defaults().getSecret(), params);
137+
}
138+
139+
public static List<Path> convertFileToDir(String fromPathToFile, String toFormat, String outputDirectory, String secret, Param... params) {
140+
try {
141+
Path fromPath = Paths.get(fromPathToFile);
142+
Path toPath = Paths.get(outputDirectory);
143+
return convertFile(fromPath, toFormat, secret, params).get().saveFilesSync(toPath);
144+
} catch (IOException | ExecutionException | InterruptedException e) {
145+
throw new RuntimeException(e);
146+
}
147+
}
148+
149+
public static Path convertUrl(String url, String toPathToFile, Param... params) {
150+
return convertUrl(url, toPathToFile, Config.defaults().getSecret(), params);
151+
}
152+
153+
public static Path convertUrl(String url, String toPathToFile, String secret, Param... params) {
154+
try {
155+
Path toPath = Paths.get(toPathToFile);
156+
Param[] urlParam = new Param[]{new Param("url", url)};
157+
return convert("web", getFileExtension(toPath), Param.concat(urlParam, params), Config.defaults(secret)).get().saveFile(toPath).get();
158+
} catch (ExecutionException | InterruptedException e) {
159+
throw new RuntimeException(e);
160+
}
161+
}
162+
163+
public static Path convertRemoteFile(String url, String toPathToFile, Param... params) {
164+
return convertRemoteFile(url, toPathToFile, Config.defaults().getSecret(), params);
165+
}
166+
167+
public static Path convertRemoteFile(String url, String toPathToFile, String secret, Param... params) {
168+
RemoteUploadResponse response = Http.remoteUpload(url, Config.defaults(secret));
169+
try {
170+
Path toPath = Paths.get(toPathToFile);
171+
return convert(response.FileExt, getFileExtension(toPath), new Param[]{
172+
new Param("file", response.FileId)
173+
}, Config.defaults(secret)).get().saveFile(toPath).get();
174+
} catch (ExecutionException | InterruptedException e) {
175+
throw new RuntimeException(e);
176+
}
177+
}
178+
179+
public static List<Path> convertRemoteFileToDir(String url, String toFormat, String outputDirectory, Param... params) {
180+
return convertRemoteFileToDir(url, toFormat, outputDirectory, Config.defaults().getSecret(), params);
181+
}
182+
183+
public static List<Path> convertRemoteFileToDir(String url, String toFormat, String outputDirectory, String secret, Param... params) {
184+
RemoteUploadResponse response = Http.remoteUpload(url, Config.defaults(secret));
185+
try {
186+
Path toPath = Paths.get(outputDirectory);
187+
Param[] fileParam = new Param[]{new Param("file", response.FileId)};
188+
return convert(response.FileExt, toFormat, Param.concat(fileParam, params), Config.defaults(secret)).get().saveFilesSync(toPath);
189+
} catch (ExecutionException | InterruptedException e) {
190+
throw new RuntimeException(e);
191+
}
192+
}
193+
133194
private static String getFileExtension(Path path) {
134195
String name = path.getFileName().toString();
135196
return name.substring(name.lastIndexOf(".") + 1);

src/com/convertapi/Http.java

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
package com.convertapi;
22

3-
import okhttp3.HttpUrl;
4-
import okhttp3.OkHttpClient;
5-
import okhttp3.Request;
6-
import okhttp3.Response;
3+
import com.convertapi.model.RemoteUploadResponse;
4+
import com.google.gson.Gson;
5+
import okhttp3.*;
76

87
import java.io.IOException;
98
import java.io.InputStream;
@@ -59,7 +58,34 @@ static CompletableFuture<Void> requestDelete(String url) {
5958
}
6059

6160
static Request.Builder getRequestBuilder() {
62-
String agent = String.format("ConvertAPI-Java/%.1f (%s)", 1.5, System.getProperty("os.name"));
61+
String agent = String.format("ConvertAPI-Java/%.1f (%s)", 1.6, System.getProperty("os.name"));
6362
return new Request.Builder().header("User-Agent", agent);
6463
}
64+
65+
static RemoteUploadResponse remoteUpload(String urlToFile, Config config) {
66+
HttpUrl url = Http.getUrlBuilder(config)
67+
.addPathSegment("upload-from-url")
68+
.addQueryParameter("url", urlToFile)
69+
.build();
70+
71+
Request request = Http.getRequestBuilder()
72+
.url(url)
73+
.method("POST", RequestBody.create(null, ""))
74+
.addHeader("Accept", "application/json")
75+
.build();
76+
77+
String bodyString;
78+
try {
79+
Response response = Http.getClient().newCall(request).execute();
80+
//noinspection ConstantConditions
81+
bodyString = response.body().string();
82+
if (response.code() != 200) {
83+
throw new ConversionException(bodyString, response.code());
84+
}
85+
} catch (IOException e) {
86+
throw new RuntimeException(e);
87+
}
88+
89+
return new Gson().fromJson(bodyString, RemoteUploadResponse.class);
90+
}
6591
}

0 commit comments

Comments
 (0)