Skip to content

Commit efd47ce

Browse files
Merge pull request #125 from datalogics-cgreen/tdm-samples
PDFCLOUD-5791 Add TDM samples
2 parents d48ff71 + 4f294db commit efd47ce

13 files changed

Lines changed: 670 additions & 0 deletions

File tree

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
2+
/*
3+
* What this sample does:
4+
* - Called from Program.cs to upload a file, then apply TDM rights metadata via JSON flow.
5+
*
6+
* Setup (environment):
7+
* - Copy .env.example to .env
8+
* - Set PDFREST_API_KEY=your_api_key_here
9+
* - Optional: set PDFREST_URL to override the API region. For EU/GDPR compliance and proximity, use:
10+
* PDFREST_URL=https://eu-api.pdfrest.com
11+
* For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
12+
*
13+
* Usage:
14+
* dotnet run -- tdm-reserved-pdf /path/to/input.pdf
15+
*
16+
* Output:
17+
* - Prints JSON responses; non-2xx results exit non-zero.
18+
*/
19+
using Newtonsoft.Json.Linq;
20+
using System.Text;
21+
22+
namespace Samples.EndpointExamples.JsonPayload
23+
{
24+
public static class TdmReservedPdf
25+
{
26+
public static async Task Execute(string[] args)
27+
{
28+
if (args == null || args.Length < 1)
29+
{
30+
Console.Error.WriteLine("tdm-reserved-pdf requires <inputFile>");
31+
Environment.Exit(1);
32+
return;
33+
}
34+
35+
var inputPath = args[0];
36+
if (!File.Exists(inputPath))
37+
{
38+
Console.Error.WriteLine($"File not found: {inputPath}");
39+
Environment.Exit(1);
40+
return;
41+
}
42+
43+
var apiKey = Environment.GetEnvironmentVariable("PDFREST_API_KEY");
44+
if (string.IsNullOrWhiteSpace(apiKey))
45+
{
46+
Console.Error.WriteLine("Missing required environment variable: PDFREST_API_KEY");
47+
Environment.Exit(1);
48+
return;
49+
}
50+
var baseUrl = Environment.GetEnvironmentVariable("PDFREST_URL") ?? "https://api.pdfrest.com";
51+
52+
using (var httpClient = new HttpClient { BaseAddress = new Uri(baseUrl) })
53+
{
54+
using (var uploadRequest = new HttpRequestMessage(HttpMethod.Post, "upload"))
55+
{
56+
uploadRequest.Headers.TryAddWithoutValidation("Api-Key", apiKey);
57+
uploadRequest.Headers.Accept.Add(new("application/json"));
58+
59+
var uploadByteArray = File.ReadAllBytes(inputPath);
60+
var uploadByteAryContent = new ByteArrayContent(uploadByteArray);
61+
uploadByteAryContent.Headers.TryAddWithoutValidation("Content-Type", "application/octet-stream");
62+
uploadByteAryContent.Headers.TryAddWithoutValidation("Content-Filename", Path.GetFileName(inputPath));
63+
64+
65+
uploadRequest.Content = uploadByteAryContent;
66+
var uploadResponse = await httpClient.SendAsync(uploadRequest);
67+
68+
var uploadResult = await uploadResponse.Content.ReadAsStringAsync();
69+
70+
Console.WriteLine("Upload response received.");
71+
Console.WriteLine(uploadResult);
72+
73+
JObject uploadResultJson = JObject.Parse(uploadResult);
74+
var uploadedId = uploadResultJson["files"][0]["id"];
75+
using (var tdmReservedPdfRequest = new HttpRequestMessage(HttpMethod.Post, "tdm-reserved-pdf"))
76+
{
77+
tdmReservedPdfRequest.Headers.TryAddWithoutValidation("Api-Key", apiKey);
78+
tdmReservedPdfRequest.Headers.Accept.Add(new("application/json"));
79+
80+
tdmReservedPdfRequest.Headers.TryAddWithoutValidation("Content-Type", "application/json");
81+
82+
83+
JObject parameterJson = new JObject
84+
{
85+
["id"] = uploadedId,
86+
["policy"] = "https://example.com/tdm-policy",
87+
};
88+
89+
tdmReservedPdfRequest.Content = new StringContent(parameterJson.ToString(), Encoding.UTF8, "application/json"); ;
90+
var tdmReservedPdfResponse = await httpClient.SendAsync(tdmReservedPdfRequest);
91+
92+
var tdmReservedPdfResult = await tdmReservedPdfResponse.Content.ReadAsStringAsync();
93+
94+
Console.WriteLine("TDM metadata response received.");
95+
Console.WriteLine(tdmReservedPdfResult);
96+
}
97+
}
98+
}
99+
}
100+
}
101+
}
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/*
2+
* What this sample does:
3+
* - Applies TDM rights metadata to a PDF via multipart/form-data.
4+
* - Routed from Program.cs as: `dotnet run -- tdm-reserved-pdf-multipart <inputFile>`.
5+
*
6+
* Setup (environment):
7+
* - Copy .env.example to .env
8+
* - Set PDFREST_API_KEY=your_api_key_here
9+
* - Optional: set PDFREST_URL to override the API region. For EU/GDPR compliance and proximity, use:
10+
* PDFREST_URL=https://eu-api.pdfrest.com
11+
* For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
12+
*
13+
* Usage:
14+
* dotnet run -- tdm-reserved-pdf-multipart /path/to/input.pdf
15+
*
16+
* Output:
17+
* - Prints the JSON response. Validation errors (args/env) exit non-zero.
18+
*/
19+
20+
using System.Text;
21+
22+
namespace Samples.EndpointExamples.MultipartPayload
23+
{
24+
public static class TdmReservedPdf
25+
{
26+
public static async Task Execute(string[] args)
27+
{
28+
if (args == null || args.Length < 1)
29+
{
30+
Console.Error.WriteLine("tdm-reserved-pdf-multipart requires <inputFile>");
31+
Environment.Exit(1);
32+
return;
33+
}
34+
var inputPath = args[0];
35+
if (!File.Exists(inputPath))
36+
{
37+
Console.Error.WriteLine($"File not found: {inputPath}");
38+
Environment.Exit(1);
39+
return;
40+
}
41+
var apiKey = Environment.GetEnvironmentVariable("PDFREST_API_KEY");
42+
if (string.IsNullOrWhiteSpace(apiKey))
43+
{
44+
Console.Error.WriteLine("Missing required environment variable: PDFREST_API_KEY");
45+
Environment.Exit(1);
46+
return;
47+
}
48+
var baseUrl = Environment.GetEnvironmentVariable("PDFREST_URL") ?? "https://api.pdfrest.com";
49+
50+
using (var httpClient = new HttpClient { BaseAddress = new Uri(baseUrl) })
51+
using (var tdmReservedPdfRequest = new HttpRequestMessage(HttpMethod.Post, "tdm-reserved-pdf"))
52+
{
53+
tdmReservedPdfRequest.Headers.TryAddWithoutValidation("Api-Key", apiKey);
54+
tdmReservedPdfRequest.Headers.Accept.Add(new("application/json"));
55+
var multipartContent = new MultipartFormDataContent();
56+
57+
var byteArray = File.ReadAllBytes(inputPath);
58+
var byteAryContent = new ByteArrayContent(byteArray);
59+
multipartContent.Add(byteAryContent, "file", Path.GetFileName(inputPath));
60+
byteAryContent.Headers.TryAddWithoutValidation("Content-Type", "application/octet-stream");
61+
62+
var policyValue = new ByteArrayContent(Encoding.UTF8.GetBytes("https://example.com/tdm-policy"));
63+
multipartContent.Add(policyValue, "policy");
64+
65+
tdmReservedPdfRequest.Content = multipartContent;
66+
var response = await httpClient.SendAsync(tdmReservedPdfRequest);
67+
var apiResult = await response.Content.ReadAsStringAsync();
68+
69+
Console.WriteLine("TDM metadata response received.");
70+
Console.WriteLine(apiResult);
71+
}
72+
}
73+
}
74+
}

DotNET/Program.cs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ static void PrintUsage()
1616
Console.Error.WriteLine(" pdf <file> Convert file to PDF");
1717
Console.Error.WriteLine(" pdfa <file> Convert to PDF/A");
1818
Console.Error.WriteLine(" pdfx <file> Convert to PDF/X");
19+
Console.Error.WriteLine(" tdm-reserved-pdf <pdf> Apply TDM rights metadata");
1920
Console.Error.WriteLine(" png|jpg|gif|bmp <file> Convert to image format");
2021
Console.Error.WriteLine(" word|excel|powerpoint|tif <file> Convert to Office/TIFF");
2122
Console.Error.WriteLine(" Info / Extract:");
@@ -67,6 +68,7 @@ static void PrintUsage()
6768
Console.Error.WriteLine(" rasterized-pdf-multipart <pdf> Rasterize PDF");
6869
Console.Error.WriteLine(" pdfa-multipart <file> Convert to PDF/A");
6970
Console.Error.WriteLine(" pdfx-multipart <file> Convert to PDF/X");
71+
Console.Error.WriteLine(" tdm-reserved-pdf-multipart <pdf> Apply TDM rights metadata");
7072
Console.Error.WriteLine(" png-multipart|jpg-multipart|gif-multipart|bmp-multipart|tif-multipart <file> Convert to image");
7173
Console.Error.WriteLine(" word-multipart|excel-multipart|powerpoint-multipart <file> Convert Office");
7274
Console.Error.WriteLine(" Info / Extract:");
@@ -290,12 +292,18 @@ static void PrintUsage()
290292
case "pdfx-multipart":
291293
await Samples.EndpointExamples.MultipartPayload.Pdfx.Execute(rest);
292294
break;
295+
case "tdm-reserved-pdf-multipart":
296+
await Samples.EndpointExamples.MultipartPayload.TdmReservedPdf.Execute(rest);
297+
break;
293298
case "pdfa":
294299
await Samples.EndpointExamples.JsonPayload.Pdfa.Execute(rest);
295300
break;
296301
case "pdfx":
297302
await Samples.EndpointExamples.JsonPayload.Pdfx.Execute(rest);
298303
break;
304+
case "tdm-reserved-pdf":
305+
await Samples.EndpointExamples.JsonPayload.TdmReservedPdf.Execute(rest);
306+
break;
299307
case "excel":
300308
await Samples.EndpointExamples.JsonPayload.Excel.Execute(rest);
301309
break;
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
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 TDMReservedPDF {
10+
11+
// By default, we use the US-based API service. This is the primary endpoint for global use.
12+
private static final String API_URL = "https://api.pdfrest.com";
13+
14+
// For GDPR compliance and enhanced performance for European users, you can switch to the EU-based
15+
// service by commenting out the URL above and uncommenting the URL below.
16+
// For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
17+
// private static final String API_URL = "https://eu-api.pdfrest.com";
18+
19+
// Specify the path to your file here, or as the first argument when running the program.
20+
private static final String DEFAULT_FILE_PATH = "/path/to/file.pdf";
21+
22+
// Specify your API key here, or in the environment variable PDFREST_API_KEY.
23+
// You can also put the environment variable in a .env file.
24+
private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
25+
26+
public static void main(String[] args) {
27+
File inputFile;
28+
if (args.length > 0) {
29+
inputFile = new File(args[0]);
30+
} else {
31+
inputFile = new File(DEFAULT_FILE_PATH);
32+
}
33+
final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();
34+
35+
String uploadString = uploadFile(inputFile);
36+
JSONObject uploadJSON = new JSONObject(uploadString);
37+
if (uploadJSON.has("error")) {
38+
System.out.println("Error during upload: " + uploadString);
39+
return;
40+
}
41+
JSONArray fileArray = uploadJSON.getJSONArray("files");
42+
43+
JSONObject fileObject = fileArray.getJSONObject(0);
44+
45+
String uploadedId = fileObject.get("id").toString();
46+
47+
String tdmReservedPdfJson =
48+
String.format("{\"id\":\"%s\", \"policy\":\"https://example.com/tdm-policy\"}", uploadedId);
49+
50+
final RequestBody requestBody =
51+
RequestBody.create(tdmReservedPdfJson, MediaType.parse("application/json"));
52+
53+
Request request =
54+
new Request.Builder()
55+
.header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
56+
.url(API_URL + "/tdm-reserved-pdf")
57+
.post(requestBody)
58+
.build();
59+
try {
60+
OkHttpClient client =
61+
new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();
62+
63+
Response response = client.newCall(request).execute();
64+
System.out.println("TDM metadata Result code " + response.code());
65+
if (response.body() != null) {
66+
System.out.println(prettyJson(response.body().string()));
67+
}
68+
} catch (IOException e) {
69+
throw new RuntimeException(e);
70+
}
71+
}
72+
73+
private static String prettyJson(String json) {
74+
// https://stackoverflow.com/a/9583835/11996393
75+
return new JSONObject(json).toString(4);
76+
}
77+
78+
// This function is just a copy of the 'Upload.java' file to upload a binary file
79+
private static String uploadFile(File inputFile) {
80+
81+
final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();
82+
83+
final RequestBody requestBody =
84+
RequestBody.create(inputFile, MediaType.parse("application/pdf"));
85+
86+
Request request =
87+
new Request.Builder()
88+
.header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
89+
.header("Content-Filename", "File.pdf")
90+
.url(API_URL + "/upload")
91+
.post(requestBody)
92+
.build();
93+
try {
94+
OkHttpClient client = new OkHttpClient().newBuilder().build();
95+
Response response = client.newCall(request).execute();
96+
System.out.println("Upload Result code " + response.code());
97+
if (response.body() != null) {
98+
return response.body().string();
99+
}
100+
} catch (IOException e) {
101+
throw new RuntimeException(e);
102+
}
103+
return "";
104+
}
105+
}
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
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.JSONObject;
7+
8+
public class TDMReservedPDF {
9+
10+
// By default, we use the US-based API service. This is the primary endpoint for global use.
11+
private static final String API_URL = "https://api.pdfrest.com";
12+
13+
// For GDPR compliance and enhanced performance for European users, you can switch to the EU-based
14+
// service by commenting out the URL above and uncommenting the URL below.
15+
// For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
16+
// private static final String API_URL = "https://eu-api.pdfrest.com";
17+
18+
// Specify the path to your file here, or as the first argument when running the program.
19+
private static final String DEFAULT_FILE_PATH = "/path/to/file.pdf";
20+
21+
// Specify your API key here, or in the environment variable PDFREST_API_KEY.
22+
// You can also put the environment variable in a .env file.
23+
private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
24+
25+
public static void main(String[] args) {
26+
File inputFile;
27+
if (args.length > 0) {
28+
inputFile = new File(args[0]);
29+
} else {
30+
inputFile = new File(DEFAULT_FILE_PATH);
31+
}
32+
33+
final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();
34+
35+
final RequestBody inputFileRequestBody =
36+
RequestBody.create(inputFile, MediaType.parse("application/pdf"));
37+
RequestBody requestBody =
38+
new MultipartBody.Builder()
39+
.setType(MultipartBody.FORM)
40+
.addFormDataPart("file", inputFile.getName(), inputFileRequestBody)
41+
.addFormDataPart("policy", "https://example.com/tdm-policy")
42+
.addFormDataPart("output", "pdfrest_tdm_reserved_pdf")
43+
.build();
44+
Request request =
45+
new Request.Builder()
46+
.header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
47+
.url(API_URL + "/tdm-reserved-pdf")
48+
.post(requestBody)
49+
.build();
50+
try {
51+
OkHttpClient client =
52+
new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();
53+
54+
Response response = client.newCall(request).execute();
55+
System.out.println("TDM metadata result code " + response.code());
56+
if (response.body() != null) {
57+
System.out.println(prettyJson(response.body().string()));
58+
}
59+
} catch (IOException e) {
60+
throw new RuntimeException(e);
61+
}
62+
}
63+
64+
private static String prettyJson(String json) {
65+
// https://stackoverflow.com/a/9583835/11996393
66+
return new JSONObject(json).toString(4);
67+
}
68+
}

0 commit comments

Comments
 (0)