Skip to content

Commit 3367842

Browse files
Merge pull request #99 from datalogics-jacksonm/pdfcloud-4898-markdown-samples
PDFCLOUD-4898 | Add PDF to Markdown code samples
2 parents b066939 + 98dd047 commit 3367842

13 files changed

Lines changed: 478 additions & 1 deletion

File tree

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
using Newtonsoft.Json.Linq;
2+
using System.Text;
3+
4+
using (var httpClient = new HttpClient { BaseAddress = new Uri("https://api.pdfrest.com") })
5+
{
6+
using (var uploadRequest = new HttpRequestMessage(HttpMethod.Post, "upload"))
7+
{
8+
uploadRequest.Headers.TryAddWithoutValidation("Api-Key", "xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
9+
uploadRequest.Headers.Accept.Add(new("application/json"));
10+
11+
var uploadByteArray = File.ReadAllBytes("/path/to/file");
12+
var uploadByteAryContent = new ByteArrayContent(uploadByteArray);
13+
uploadByteAryContent.Headers.TryAddWithoutValidation("Content-Type", "application/octet-stream");
14+
uploadByteAryContent.Headers.TryAddWithoutValidation("Content-Filename", "filename.pdf");
15+
16+
uploadRequest.Content = uploadByteAryContent;
17+
var uploadResponse = await httpClient.SendAsync(uploadRequest);
18+
19+
var uploadResult = await uploadResponse.Content.ReadAsStringAsync();
20+
21+
Console.WriteLine("Upload response received.");
22+
Console.WriteLine(uploadResult);
23+
24+
JObject uploadResultJson = JObject.Parse(uploadResult);
25+
var uploadedID = uploadResultJson["files"][0]["id"];
26+
using (var markdownRequest = new HttpRequestMessage(HttpMethod.Post, "markdown"))
27+
{
28+
markdownRequest.Headers.TryAddWithoutValidation("Api-Key", "xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
29+
markdownRequest.Headers.Accept.Add(new("application/json"));
30+
markdownRequest.Headers.TryAddWithoutValidation("Content-Type", "application/json");
31+
32+
JObject parameterJson = new JObject
33+
{
34+
["id"] = uploadedID,
35+
};
36+
37+
markdownRequest.Content = new StringContent(parameterJson.ToString(), Encoding.UTF8, "application/json");
38+
var markdownResponse = await httpClient.SendAsync(markdownRequest);
39+
40+
var markdownResult = await markdownResponse.Content.ReadAsStringAsync();
41+
42+
Console.WriteLine("Markdown response received.");
43+
Console.WriteLine(markdownResult);
44+
}
45+
}
46+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
using System.Text;
2+
3+
using (var httpClient = new HttpClient { BaseAddress = new Uri("https://api.pdfrest.com") })
4+
{
5+
using (var request = new HttpRequestMessage(HttpMethod.Post, "markdown"))
6+
{
7+
request.Headers.TryAddWithoutValidation("Api-Key", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
8+
request.Headers.Accept.Add(new("application/json"));
9+
var multipartContent = new MultipartFormDataContent();
10+
11+
var byteArray = File.ReadAllBytes("/path/to/file");
12+
var byteAryContent = new ByteArrayContent(byteArray);
13+
multipartContent.Add(byteAryContent, "file", "file_name");
14+
byteAryContent.Headers.TryAddWithoutValidation("Content-Type", "application/pdf");
15+
16+
var byteArrayOption = new ByteArrayContent(Encoding.UTF8.GetBytes("on"));
17+
multipartContent.Add(byteArrayOption, "page_break_comments");
18+
19+
request.Content = multipartContent;
20+
var response = await httpClient.SendAsync(request);
21+
22+
var apiResult = await response.Content.ReadAsStringAsync();
23+
24+
Console.WriteLine("Markdown API response received.");
25+
Console.WriteLine(apiResult);
26+
}
27+
}
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
import io.github.cdimascio.dotenv.Dotenv;
2+
import java.io.File;
3+
import java.io.IOException;
4+
import java.util.concurrent.TimeUnit;
5+
import okhttp3.*;
6+
import org.json.JSONArray;
7+
import org.json.JSONObject;
8+
9+
public class Markdown {
10+
11+
// Specify the path to your file here, or as the first argument when running the program.
12+
private static final String DEFAULT_FILE_PATH = "/path/to/file.pdf";
13+
14+
// Specify your API key here, or in the environment variable PDFREST_API_KEY.
15+
// You can also put the environment variable in a .env file.
16+
private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
17+
18+
public static void main(String[] args) {
19+
File inputFile;
20+
if (args.length > 0) {
21+
inputFile = new File(args[0]);
22+
} else {
23+
inputFile = new File(DEFAULT_FILE_PATH);
24+
}
25+
final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();
26+
27+
String uploadString = uploadFile(inputFile);
28+
JSONObject uploadJSON = new JSONObject(uploadString);
29+
if (uploadJSON.has("error")) {
30+
System.out.println("Error during upload: " + uploadString);
31+
return;
32+
}
33+
JSONArray fileArray = uploadJSON.getJSONArray("files");
34+
JSONObject fileObject = fileArray.getJSONObject(0);
35+
String uploadedID = fileObject.get("id").toString();
36+
37+
String JSONString =
38+
String.format("{\"id\":\"%s\", \"page_break_comments\":\"on\"}", uploadedID);
39+
final RequestBody requestBody =
40+
RequestBody.create(JSONString, MediaType.parse("application/json"));
41+
42+
Request request =
43+
new Request.Builder()
44+
.header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
45+
.url("https://api.pdfrest.com/markdown")
46+
.post(requestBody)
47+
.build();
48+
try {
49+
OkHttpClient client =
50+
new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();
51+
52+
Response response = client.newCall(request).execute();
53+
System.out.println("Markdown Result code " + response.code());
54+
if (response.body() != null) {
55+
System.out.println(prettyJson(response.body().string()));
56+
}
57+
} catch (IOException e) {
58+
throw new RuntimeException(e);
59+
}
60+
}
61+
62+
private static String prettyJson(String json) {
63+
// https://stackoverflow.com/a/9583835/11996393
64+
return new JSONObject(json).toString(4);
65+
}
66+
67+
// This function is just a copy of the 'Upload.java' file to upload a binary file
68+
private static String uploadFile(File inputFile) {
69+
final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();
70+
final RequestBody requestBody =
71+
RequestBody.create(inputFile, MediaType.parse("application/pdf"));
72+
73+
Request request =
74+
new Request.Builder()
75+
.header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
76+
.header("Content-Filename", "File.pdf")
77+
.url("https://api.pdfrest.com/upload")
78+
.post(requestBody)
79+
.build();
80+
try {
81+
OkHttpClient client = new OkHttpClient().newBuilder().build();
82+
Response response = client.newCall(request).execute();
83+
System.out.println("Upload Result code " + response.code());
84+
if (response.body() != null) {
85+
return response.body().string();
86+
}
87+
} catch (IOException e) {
88+
throw new RuntimeException(e);
89+
}
90+
return "";
91+
}
92+
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import io.github.cdimascio.dotenv.Dotenv;
2+
import java.io.File;
3+
import java.io.IOException;
4+
import okhttp3.MediaType;
5+
import okhttp3.MultipartBody;
6+
import okhttp3.OkHttpClient;
7+
import okhttp3.Request;
8+
import okhttp3.RequestBody;
9+
import okhttp3.Response;
10+
import org.json.JSONObject;
11+
12+
public class Markdown {
13+
14+
// Specify the path to your file here, or as the first argument when running the program.
15+
private static final String DEFAULT_FILE_PATH = "/path/to/file.pdf";
16+
17+
// Specify your API key here, or in the environment variable PDFREST_API_KEY.
18+
// You can also put the environment variable in a .env file.
19+
private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
20+
21+
public static void main(String[] args) {
22+
File inputFile;
23+
if (args.length > 0) {
24+
inputFile = new File(args[0]);
25+
} else {
26+
inputFile = new File(DEFAULT_FILE_PATH);
27+
}
28+
29+
final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();
30+
31+
final RequestBody inputFileRequestBody =
32+
RequestBody.create(inputFile, MediaType.parse("application/pdf"));
33+
RequestBody requestBody =
34+
new MultipartBody.Builder()
35+
.setType(MultipartBody.FORM)
36+
.addFormDataPart("file", inputFile.getName(), inputFileRequestBody)
37+
.addFormDataPart("page_break_comments", "on")
38+
.build();
39+
Request request =
40+
new Request.Builder()
41+
.header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
42+
.url("https://api.pdfrest.com/markdown")
43+
.post(requestBody)
44+
.build();
45+
try {
46+
OkHttpClient client = new OkHttpClient().newBuilder().build();
47+
Response response = client.newCall(request).execute();
48+
System.out.println("Result code " + response.code());
49+
if (response.body() != null) {
50+
System.out.println(prettyJson(response.body().string()));
51+
}
52+
} catch (IOException e) {
53+
throw new RuntimeException(e);
54+
}
55+
}
56+
57+
private static String prettyJson(String json) {
58+
// https://stackoverflow.com/a/9583835/11996393
59+
return new JSONObject(json).toString(4);
60+
}
61+
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
var axios = require("axios");
2+
var fs = require("fs");
3+
4+
var upload_data = fs.createReadStream("/path/to/file.pdf");
5+
6+
var upload_config = {
7+
method: "post",
8+
maxBodyLength: Infinity,
9+
url: "https://api.pdfrest.com/upload",
10+
headers: {
11+
"Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", // Replace with your API key
12+
"Content-Filename": "filename.pdf",
13+
"Content-Type": "application/octet-stream",
14+
},
15+
data: upload_data,
16+
};
17+
18+
// Send upload request
19+
axios(upload_config)
20+
.then(function (upload_response) {
21+
console.log("Upload response:");
22+
console.log(JSON.stringify(upload_response.data, null, 2));
23+
24+
var uploaded_id = upload_response.data.files[0].id;
25+
26+
var markdown_config = {
27+
method: "post",
28+
maxBodyLength: Infinity,
29+
url: "https://api.pdfrest.com/markdown",
30+
headers: {
31+
"Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", // Replace with your API key
32+
"Content-Type": "application/json",
33+
},
34+
data: {
35+
id: uploaded_id,
36+
page_break_comments: "on"
37+
},
38+
};
39+
40+
// Send markdown request
41+
axios(markdown_config)
42+
.then(function (markdown_response) {
43+
console.log("Markdown response:");
44+
console.log(JSON.stringify(markdown_response.data, null, 2));
45+
})
46+
.catch(function (error) {
47+
console.error("Markdown request error:");
48+
console.error(error.response?.data || error.message);
49+
});
50+
})
51+
.catch(function (error) {
52+
console.error("Upload request error:");
53+
console.error(error.response?.data || error.message);
54+
});
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// This request demonstrates how to generate markdown from a PDF document.
2+
var axios = require("axios");
3+
var FormData = require("form-data");
4+
var fs = require("fs");
5+
6+
// Create a new form data instance and append the PDF file and parameters to it
7+
var data = new FormData();
8+
data.append("file", fs.createReadStream("/path/to/file"));
9+
data.append("page_break_comments", "on");
10+
11+
// define configuration options for axios request
12+
var config = {
13+
method: "post",
14+
maxBodyLength: Infinity, // set maximum length of the request body
15+
url: "https://api.pdfrest.com/markdown",
16+
headers: {
17+
"Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", // Replace with your API key
18+
...data.getHeaders(), // set headers for the request
19+
},
20+
data: data, // set the data to be sent with the request
21+
};
22+
23+
// send request and handle response or error
24+
axios(config)
25+
.then(function (response) {
26+
console.log(JSON.stringify(response.data));
27+
})
28+
.catch(function (error) {
29+
console.log(error);
30+
});
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<?php
2+
require 'vendor/autoload.php'; // Require the autoload file to load Guzzle HTTP client.
3+
4+
use GuzzleHttp\Client; // Import the Guzzle HTTP client namespace.
5+
use GuzzleHttp\Psr7\Request; // Import the PSR-7 Request class.
6+
use GuzzleHttp\Psr7\Utils; // Import the PSR-7 Utils class for working with streams.
7+
8+
$upload_client = new Client(['http_errors' => false]);
9+
$upload_headers = [
10+
'api-key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
11+
'content-filename' => 'filename.pdf',
12+
'Content-Type' => 'application/octet-stream'
13+
];
14+
$upload_body = file_get_contents('/path/to/file');
15+
$upload_request = new Request('POST', 'https://api.pdfrest.com/upload', $upload_headers, $upload_body);
16+
$upload_res = $upload_client->sendAsync($upload_request)->wait();
17+
echo $upload_res->getBody() . PHP_EOL;
18+
19+
$upload_response_json = json_decode($upload_res->getBody());
20+
21+
$uploaded_id = $upload_response_json->{'files'}[0]->{'id'};
22+
23+
echo "Successfully uploaded with an id of: " . $uploaded_id . PHP_EOL;
24+
25+
$markdown_client = new Client(['http_errors' => false]);
26+
$markdown_headers = [
27+
'api-key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
28+
'Content-Type' => 'application/json'
29+
];
30+
$markdown_body = '{"id":"'.$uploaded_id.'","page_break_comments":"on"}';
31+
$markdown_request = new Request('POST', 'https://api.pdfrest.com/markdown', $markdown_headers, $markdown_body);
32+
$markdown_res = $markdown_client->sendAsync($markdown_request)->wait();
33+
echo $markdown_res->getBody() . PHP_EOL;
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?php
2+
require 'vendor/autoload.php'; // Require the autoload file to load Guzzle HTTP client.
3+
4+
use GuzzleHttp\Client; // Import the Guzzle HTTP client namespace.
5+
use GuzzleHttp\Psr7\Request; // Import the PSR-7 Request class.
6+
use GuzzleHttp\Psr7\Utils; // Import the PSR-7 Utils class for working with streams.
7+
8+
$client = new Client(); // Create a new instance of the Guzzle HTTP client.
9+
10+
$headers = [
11+
'Api-Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' // Set the API key in the headers for authentication.
12+
];
13+
14+
$options = [
15+
'multipart' => [
16+
[
17+
'name' => 'file', // Specify the field name for the file.
18+
'contents' => Utils::tryFopen('/path/to/file', 'r'), // Open the file specified by '/path/to/file' for reading.
19+
'filename' => '/path/to/file', // Set the filename for the file to be processed, in this case, '/path/to/file'.
20+
'headers' => [
21+
'Content-Type' => 'application/pdf' // Set the Content-Type header for the file.
22+
]
23+
],
24+
[
25+
'name' => 'page_break_comments', // Specify the field name for the page_break_comments option.
26+
'contents' => 'on' // Set the value for the page_break_comments option (in this case, 'on').
27+
]
28+
]
29+
];
30+
31+
$request = new Request('POST', 'https://api.pdfrest.com/markdown', $headers); // Create a new HTTP POST request with the updated /markdown endpoint and headers.
32+
33+
$res = $client->sendAsync($request, $options)->wait(); // Send the asynchronous request and wait for the response.
34+
35+
echo $res->getBody(); // Output the response body, which contains the generated markdown from the document.

0 commit comments

Comments
 (0)