Skip to content

Commit

Permalink
Merge pull request #81 from datalogics-cgreen/pdfcloud-4165-text
Browse files Browse the repository at this point in the history
Add Add Text code samples
  • Loading branch information
datalogics-dliang authored Oct 25, 2024
2 parents bbd4177 + c7bc4e3 commit b1e8869
Show file tree
Hide file tree
Showing 12 changed files with 581 additions and 0 deletions.
67 changes: 67 additions & 0 deletions DotNET/Endpoint Examples/JSON Payload/pdf-with-added-text.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text;

using (var httpClient = new HttpClient { BaseAddress = new Uri("https://api.pdfrest.com") })
{
using (var uploadRequest = new HttpRequestMessage(HttpMethod.Post, "upload"))
{
uploadRequest.Headers.TryAddWithoutValidation("Api-Key", "xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
uploadRequest.Headers.Accept.Add(new("application/json"));

var uploadByteArray = File.ReadAllBytes("/path/to/file");
var uploadByteAryContent = new ByteArrayContent(uploadByteArray);
uploadByteAryContent.Headers.TryAddWithoutValidation("Content-Type", "application/octet-stream");
uploadByteAryContent.Headers.TryAddWithoutValidation("Content-Filename", "filename.pdf");


uploadRequest.Content = uploadByteAryContent;
var uploadResponse = await httpClient.SendAsync(uploadRequest);

var uploadResult = await uploadResponse.Content.ReadAsStringAsync();

Console.WriteLine("Upload response received.");
Console.WriteLine(uploadResult);

JObject uploadResultJson = JObject.Parse(uploadResult);
var uploadedID = uploadResultJson["files"][0]["id"];
using (var addedTextRequest = new HttpRequestMessage(HttpMethod.Post, "pdf-with-added-text"))
{
addedTextRequest.Headers.TryAddWithoutValidation("Api-Key", "xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
addedTextRequest.Headers.Accept.Add(new("application/json"));

addedTextRequest.Headers.TryAddWithoutValidation("Content-Type", "application/json");

var text_option_array = new JArray();
var text_options = new JObject
{
["font"] = "Times New Roman",
["max_width"] = "175",
["opacity"] = "1",
["page"] = "1",
["rotation"] = "0",
["text"] = "sample text in PDF",
["text_color_rgb"] = "0,0,0",
["text_size"] = "30",
["x"] = "72",
["y"] = "144"
};
text_option_array.Add(text_options);

JObject parameterJson = new JObject
{
["id"] = uploadedID,
["text_objects"] = JsonConvert.SerializeObject(text_option_array),
};

addedTextRequest.Content = new StringContent(parameterJson.ToString(), Encoding.UTF8, "application/json"); ;
var addedTextResponse = await httpClient.SendAsync(addedTextRequest);

var addedTextResult = await addedTextResponse.Content.ReadAsStringAsync();

Console.WriteLine("Processing response received.");
Console.WriteLine(addedTextResult);
}
}
}
45 changes: 45 additions & 0 deletions DotNET/Endpoint Examples/Multipart Payload/pdf-with-added-text.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text;

using (var httpClient = new HttpClient { BaseAddress = new Uri("https://api.pdfrest.com") })
{
using (var request = new HttpRequestMessage(HttpMethod.Post, "pdf-with-added-text"))
{
request.Headers.TryAddWithoutValidation("Api-Key", "xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
request.Headers.Accept.Add(new("application/json"));
var multipartContent = new MultipartFormDataContent();

var byteArray = File.ReadAllBytes("/path/to/file");
var byteAryContent = new ByteArrayContent(byteArray);
multipartContent.Add(byteAryContent, "file", "file_name");
byteAryContent.Headers.TryAddWithoutValidation("Content-Type", "application/pdf");

var text_option_array = new JArray();
var text_options = new JObject
{
["font"] = "Times New Roman",
["max_width"] = "175",
["opacity"] = "1",
["page"] = "1",
["rotation"] = "0",
["text"] = "sample text in PDF",
["text_color_rgb"] = "0,0,0",
["text_size"] = "30",
["x"] = "72",
["y"] = "144"
};
text_option_array.Add(text_options);
var byteArrayOption = new ByteArrayContent(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(text_option_array)));
multipartContent.Add(byteArrayOption, "text_objects");


request.Content = multipartContent;
var response = await httpClient.SendAsync(request);

var apiResult = await response.Content.ReadAsStringAsync();

Console.WriteLine("API response received.");
Console.WriteLine(apiResult);
}
}
100 changes: 100 additions & 0 deletions Java/Endpoint Examples/JSON Payload/PDFWithAddedText.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import io.github.cdimascio.dotenv.Dotenv;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONObject;

public class PDFWithAddedText {

// Specify the path to your file here, or as the first argument when running the program.
private static final String DEFAULT_FILE_PATH = "/path/to/file";

// Specify your API key here, or in the environment variable PDFREST_API_KEY.
// You can also put the environment variable in a .env file.
private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

public static void main(String[] args) {
File inputFile;
if (args.length > 0) {
inputFile = new File(args[0]);
} else {
inputFile = new File(DEFAULT_FILE_PATH);
}
final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();

String uploadString = uploadFile(inputFile);
JSONObject uploadJSON = new JSONObject(uploadString);
if (uploadJSON.has("error")) {
System.out.println("Error during upload: " + uploadString);
return;
}
JSONArray fileArray = uploadJSON.getJSONArray("files");

JSONObject fileObject = fileArray.getJSONObject(0);

String uploadedID = fileObject.get("id").toString();

String textOptions =
"[{\\\"font\\\":\\\"Times New Roman\\\",\\\"max_width\\\":\\\"175\\\",\\\"opacity\\\":\\\"1\\\",\\\"page\\\":\\\"1\\\",\\\"rotation\\\":\\\"0\\\",\\\"text\\\":\\\"sample text in PDF\\\",\\\"text_color_rgb\\\":\\\"0,0,0\\\",\\\"text_size\\\":\\\"30\\\",\\\"x\\\":\\\"72\\\",\\\"y\\\":\\\"144\\\"}]";

String JSONString =
String.format("{\"id\":\"%s\", \"text_objects\":\"%s\"}", uploadedID, textOptions);

final RequestBody requestBody =
RequestBody.create(JSONString, MediaType.parse("application/json"));

Request request =
new Request.Builder()
.header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
.url("https://api.pdfrest.com/pdf-with-added-text")
.post(requestBody)
.build();
try {
OkHttpClient client =
new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();

Response response = client.newCall(request).execute();
System.out.println("Processing Result code " + response.code());
if (response.body() != null) {
System.out.println(prettyJson(response.body().string()));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}

private static String prettyJson(String json) {
// https://stackoverflow.com/a/9583835/11996393
return new JSONObject(json).toString(4);
}

// This function is just a copy of the 'Upload.java' file to upload a binary file
private static String uploadFile(File inputFile) {

final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();

final RequestBody requestBody =
RequestBody.create(inputFile, MediaType.parse("application/pdf"));

Request request =
new Request.Builder()
.header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
.header("Content-Filename", "File.pdf")
.url("https://api.pdfrest.com/upload")
.post(requestBody)
.build();
try {
OkHttpClient client = new OkHttpClient().newBuilder().build();
Response response = client.newCall(request).execute();
System.out.println("Upload Result code " + response.code());
if (response.body() != null) {
return response.body().string();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return "";
}
}
62 changes: 62 additions & 0 deletions Java/Endpoint Examples/Multipart Payload/PDFWithAddedText.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import io.github.cdimascio.dotenv.Dotenv;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.*;
import org.json.JSONObject;

public class PDFWithAddedText {

// Specify the path to your file here, or as the first argument when running the program.
private static final String DEFAULT_FILE_PATH = "/path/to/file";

// Specify your API key here, or in the environment variable PDFREST_API_KEY.
// You can also put the environment variable in a .env file.
private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

public static void main(String[] args) {
File inputFile;
if (args.length > 0) {
inputFile = new File(args[0]);
} else {
inputFile = new File(DEFAULT_FILE_PATH);
}

final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();

final String text_options =
"[{\"font\":\"Times New Roman\",\"max_width\":\"175\",\"opacity\":\"1\",\"page\":\"1\",\"rotation\":\"0\",\"text\":\"sample text in PDF\",\"text_color_rgb\":\"0,0,0\",\"text_size\":\"30\",\"x\":\"72\",\"y\":\"144\"}]";
final RequestBody inputFileRequestBody =
RequestBody.create(inputFile, MediaType.parse("application/pdf"));
RequestBody requestBody =
new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", inputFile.getName(), inputFileRequestBody)
.addFormDataPart("text_objects", text_options)
.addFormDataPart("output", "pdfrest_added_text")
.build();
Request request =
new Request.Builder()
.header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
.url("https://api.pdfrest.com/pdf-with-added-text")
.post(requestBody)
.build();
try {
OkHttpClient client =
new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();

Response response = client.newCall(request).execute();
System.out.println("Result code " + response.code());
if (response.body() != null) {
System.out.println(prettyJson(response.body().string()));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}

private static String prettyJson(String json) {
// https://stackoverflow.com/a/9583835/11996393
return new JSONObject(json).toString(4);
}
}
64 changes: 64 additions & 0 deletions JavaScript/Endpoint Examples/JSON Payload/pdf-with-added-text.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
var axios = require("axios");
var FormData = require("form-data");
var fs = require("fs");

var upload_data = fs.createReadStream("/path/to/file");

var upload_config = {
method: "post",
maxBodyLength: Infinity,
url: "https://api.pdfrest.com/upload",
headers: {
"Api-Key": "xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", // Replace with your API key
"Content-Filename": "filename.pdf",
"Content-Type": "application/octet-stream",
},
data: upload_data, // set the data to be sent with the request
};

// send request and handle response or error
axios(upload_config)
.then(function (upload_response) {
console.log(JSON.stringify(upload_response.data));
var uploaded_id = upload_response.data.files[0].id;

var text_option_array = [];
var text_options = {
"font":"Times New Roman",
"max_width":"175",
"opacity":"1",
"page":"1",
"rotation":"0",
"text":"sample text in PDF",
"text_color_rgb":"0,0,0",
"text_size":"30",
"x":"72",
"y":"144"
};
text_option_array.push(text_options);
var add_text_config = {
method: "post",
maxBodyLength: Infinity,
url: "https://api.pdfrest.com/pdf-with-added-text",
headers: {
"Api-Key": "xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", // Replace with your API key
"Content-Type": "application/json",
},
data: {
id: uploaded_id,
text_objects: JSON.stringify(text_option_array),
}, // set the data to be sent with the request
};

// send request and handle response or error
axios(add_text_config)
.then(function (add_text_response) {
console.log(JSON.stringify(add_text_response.data));
})
.catch(function (error) {
console.log(error);
});
})
.catch(function (error) {
console.log(error);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* This request demonstrates how to add text to a PDF.
* Horizontal and vertical offsets of the text are measured in PDF units. (1 inch = 72 PDF units)
*/
var axios = require('axios');
var FormData = require('form-data');
var fs = require('fs');

// Create a new form data instance and append the PDF file and parameters to it
var data = new FormData();
data.append('file', fs.createReadStream('/path/to/file'));
var text_option_array = [];
var text_options = {
"font":"Times New Roman",
"max_width":"175",
"opacity":"1",
"page":"1",
"rotation":"0",
"text":"sample text in PDF",
"text_color_rgb":"0,0,0",
"text_size":"30",
"x":"72",
"y":"144"
};
text_option_array.push(text_options);
data.append('text_objects', JSON.stringify(text_option_array));
data.append('output', 'pdfrest_pdf_with_added_text');

// define configuration options for axios request
var config = {
method: 'post',
maxBodyLength: Infinity, // set maximum length of the request body
url: 'https://api.pdfrest.com/pdf-with-added-text',
headers: {
'Api-Key': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', // Replace with your API key
...data.getHeaders() // set headers for the request
},
data : data // set the data to be sent with the request
};

// send request and handle response or error
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});

// If you would like to download the file instead of getting the JSON response, please see the 'get-resource-id-endpoint.js' sample.
Loading

0 comments on commit b1e8869

Please sign in to comment.