Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 101 additions & 0 deletions DotNET/Endpoint Examples/JSON Payload/tdm-reserved-pdf.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@

/*
* What this sample does:
* - Called from Program.cs to upload a file, then apply TDM rights metadata via JSON flow.
*
* Setup (environment):
* - Copy .env.example to .env
* - Set PDFREST_API_KEY=your_api_key_here
* - Optional: set PDFREST_URL to override the API region. For EU/GDPR compliance and proximity, use:
* PDFREST_URL=https://eu-api.pdfrest.com
* For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
*
* Usage:
* dotnet run -- tdm-reserved-pdf /path/to/input.pdf
*
* Output:
* - Prints JSON responses; non-2xx results exit non-zero.
*/
using Newtonsoft.Json.Linq;
using System.Text;

namespace Samples.EndpointExamples.JsonPayload
{
public static class TdmReservedPdf
{
public static async Task Execute(string[] args)
{
if (args == null || args.Length < 1)
{
Console.Error.WriteLine("tdm-reserved-pdf requires <inputFile>");
Environment.Exit(1);
return;
}

var inputPath = args[0];
if (!File.Exists(inputPath))
{
Console.Error.WriteLine($"File not found: {inputPath}");
Environment.Exit(1);
return;
}

var apiKey = Environment.GetEnvironmentVariable("PDFREST_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey))
{
Console.Error.WriteLine("Missing required environment variable: PDFREST_API_KEY");
Environment.Exit(1);
return;
}
var baseUrl = Environment.GetEnvironmentVariable("PDFREST_URL") ?? "https://api.pdfrest.com";

using (var httpClient = new HttpClient { BaseAddress = new Uri(baseUrl) })
{
using (var uploadRequest = new HttpRequestMessage(HttpMethod.Post, "upload"))
{
uploadRequest.Headers.TryAddWithoutValidation("Api-Key", apiKey);
uploadRequest.Headers.Accept.Add(new("application/json"));

var uploadByteArray = File.ReadAllBytes(inputPath);
var uploadByteAryContent = new ByteArrayContent(uploadByteArray);
uploadByteAryContent.Headers.TryAddWithoutValidation("Content-Type", "application/octet-stream");
uploadByteAryContent.Headers.TryAddWithoutValidation("Content-Filename", Path.GetFileName(inputPath));


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 tdmReservedPdfRequest = new HttpRequestMessage(HttpMethod.Post, "tdm-reserved-pdf"))
{
tdmReservedPdfRequest.Headers.TryAddWithoutValidation("Api-Key", apiKey);
tdmReservedPdfRequest.Headers.Accept.Add(new("application/json"));

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


JObject parameterJson = new JObject
{
["id"] = uploadedId,
["policy"] = "https://example.com/tdm-policy",
};

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

var tdmReservedPdfResult = await tdmReservedPdfResponse.Content.ReadAsStringAsync();

Console.WriteLine("TDM metadata response received.");
Console.WriteLine(tdmReservedPdfResult);
}
}
}
}
}
}
74 changes: 74 additions & 0 deletions DotNET/Endpoint Examples/Multipart Payload/tdm-reserved-pdf.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* What this sample does:
* - Applies TDM rights metadata to a PDF via multipart/form-data.
* - Routed from Program.cs as: `dotnet run -- tdm-reserved-pdf-multipart <inputFile>`.
*
* Setup (environment):
* - Copy .env.example to .env
* - Set PDFREST_API_KEY=your_api_key_here
* - Optional: set PDFREST_URL to override the API region. For EU/GDPR compliance and proximity, use:
* PDFREST_URL=https://eu-api.pdfrest.com
* For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
*
* Usage:
* dotnet run -- tdm-reserved-pdf-multipart /path/to/input.pdf
*
* Output:
* - Prints the JSON response. Validation errors (args/env) exit non-zero.
*/

using System.Text;

namespace Samples.EndpointExamples.MultipartPayload
{
public static class TdmReservedPdf
{
public static async Task Execute(string[] args)
{
if (args == null || args.Length < 1)
{
Console.Error.WriteLine("tdm-reserved-pdf-multipart requires <inputFile>");
Environment.Exit(1);
return;
}
var inputPath = args[0];
if (!File.Exists(inputPath))
{
Console.Error.WriteLine($"File not found: {inputPath}");
Environment.Exit(1);
return;
}
var apiKey = Environment.GetEnvironmentVariable("PDFREST_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey))
{
Console.Error.WriteLine("Missing required environment variable: PDFREST_API_KEY");
Environment.Exit(1);
return;
}
var baseUrl = Environment.GetEnvironmentVariable("PDFREST_URL") ?? "https://api.pdfrest.com";

using (var httpClient = new HttpClient { BaseAddress = new Uri(baseUrl) })
using (var tdmReservedPdfRequest = new HttpRequestMessage(HttpMethod.Post, "tdm-reserved-pdf"))
{
tdmReservedPdfRequest.Headers.TryAddWithoutValidation("Api-Key", apiKey);
tdmReservedPdfRequest.Headers.Accept.Add(new("application/json"));
var multipartContent = new MultipartFormDataContent();

var byteArray = File.ReadAllBytes(inputPath);
var byteAryContent = new ByteArrayContent(byteArray);
multipartContent.Add(byteAryContent, "file", Path.GetFileName(inputPath));
byteAryContent.Headers.TryAddWithoutValidation("Content-Type", "application/octet-stream");

var policyValue = new ByteArrayContent(Encoding.UTF8.GetBytes("https://example.com/tdm-policy"));
multipartContent.Add(policyValue, "policy");

tdmReservedPdfRequest.Content = multipartContent;
var response = await httpClient.SendAsync(tdmReservedPdfRequest);
var apiResult = await response.Content.ReadAsStringAsync();

Console.WriteLine("TDM metadata response received.");
Console.WriteLine(apiResult);
}
}
}
}
8 changes: 8 additions & 0 deletions DotNET/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ static void PrintUsage()
Console.Error.WriteLine(" pdf <file> Convert file to PDF");
Console.Error.WriteLine(" pdfa <file> Convert to PDF/A");
Console.Error.WriteLine(" pdfx <file> Convert to PDF/X");
Console.Error.WriteLine(" tdm-reserved-pdf <pdf> Apply TDM rights metadata");
Console.Error.WriteLine(" png|jpg|gif|bmp <file> Convert to image format");
Console.Error.WriteLine(" word|excel|powerpoint|tif <file> Convert to Office/TIFF");
Console.Error.WriteLine(" Info / Extract:");
Expand Down Expand Up @@ -67,6 +68,7 @@ static void PrintUsage()
Console.Error.WriteLine(" rasterized-pdf-multipart <pdf> Rasterize PDF");
Console.Error.WriteLine(" pdfa-multipart <file> Convert to PDF/A");
Console.Error.WriteLine(" pdfx-multipart <file> Convert to PDF/X");
Console.Error.WriteLine(" tdm-reserved-pdf-multipart <pdf> Apply TDM rights metadata");
Console.Error.WriteLine(" png-multipart|jpg-multipart|gif-multipart|bmp-multipart|tif-multipart <file> Convert to image");
Console.Error.WriteLine(" word-multipart|excel-multipart|powerpoint-multipart <file> Convert Office");
Console.Error.WriteLine(" Info / Extract:");
Expand Down Expand Up @@ -290,12 +292,18 @@ static void PrintUsage()
case "pdfx-multipart":
await Samples.EndpointExamples.MultipartPayload.Pdfx.Execute(rest);
break;
case "tdm-reserved-pdf-multipart":
await Samples.EndpointExamples.MultipartPayload.TdmReservedPdf.Execute(rest);
break;
case "pdfa":
await Samples.EndpointExamples.JsonPayload.Pdfa.Execute(rest);
break;
case "pdfx":
await Samples.EndpointExamples.JsonPayload.Pdfx.Execute(rest);
break;
case "tdm-reserved-pdf":
await Samples.EndpointExamples.JsonPayload.TdmReservedPdf.Execute(rest);
break;
case "excel":
await Samples.EndpointExamples.JsonPayload.Excel.Execute(rest);
break;
Expand Down
105 changes: 105 additions & 0 deletions Java/Endpoint Examples/JSON Payload/TDMReservedPDF.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
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 TDMReservedPDF {

// By default, we use the US-based API service. This is the primary endpoint for global use.
private static final String API_URL = "https://api.pdfrest.com";

// For GDPR compliance and enhanced performance for European users, you can switch to the EU-based
// service by commenting out the URL above and uncommenting the URL below.
// For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
// private static final String API_URL = "https://eu-api.pdfrest.com";

// 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.pdf";

// 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 tdmReservedPdfJson =
String.format("{\"id\":\"%s\", \"policy\":\"https://example.com/tdm-policy\"}", uploadedId);

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

Request request =
new Request.Builder()
.header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
.url(API_URL + "/tdm-reserved-pdf")
.post(requestBody)
.build();
try {
OkHttpClient client =
new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();

Response response = client.newCall(request).execute();
System.out.println("TDM metadata 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(API_URL + "/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 "";
}
}
68 changes: 68 additions & 0 deletions Java/Endpoint Examples/Multipart Payload/TDMReservedPDF.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
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 TDMReservedPDF {

// By default, we use the US-based API service. This is the primary endpoint for global use.
private static final String API_URL = "https://api.pdfrest.com";

// For GDPR compliance and enhanced performance for European users, you can switch to the EU-based
// service by commenting out the URL above and uncommenting the URL below.
// For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
// private static final String API_URL = "https://eu-api.pdfrest.com";

// 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.pdf";

// 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 RequestBody inputFileRequestBody =
RequestBody.create(inputFile, MediaType.parse("application/pdf"));
RequestBody requestBody =
new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", inputFile.getName(), inputFileRequestBody)
.addFormDataPart("policy", "https://example.com/tdm-policy")
.addFormDataPart("output", "pdfrest_tdm_reserved_pdf")
.build();
Request request =
new Request.Builder()
.header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
.url(API_URL + "/tdm-reserved-pdf")
.post(requestBody)
.build();
try {
OkHttpClient client =
new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();

Response response = client.newCall(request).execute();
System.out.println("TDM metadata 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);
}
}
Loading
Loading