diff --git a/DotNET/Endpoint Examples/JSON Payload/tdm-reserved-pdf.cs b/DotNET/Endpoint Examples/JSON Payload/tdm-reserved-pdf.cs new file mode 100644 index 0000000..9066c9e --- /dev/null +++ b/DotNET/Endpoint Examples/JSON Payload/tdm-reserved-pdf.cs @@ -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 "); + 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); + } + } + } + } + } +} diff --git a/DotNET/Endpoint Examples/Multipart Payload/tdm-reserved-pdf.cs b/DotNET/Endpoint Examples/Multipart Payload/tdm-reserved-pdf.cs new file mode 100644 index 0000000..631bfba --- /dev/null +++ b/DotNET/Endpoint Examples/Multipart Payload/tdm-reserved-pdf.cs @@ -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 `. + * + * 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 "); + 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); + } + } + } +} diff --git a/DotNET/Program.cs b/DotNET/Program.cs index c87fc39..9cb4b9e 100644 --- a/DotNET/Program.cs +++ b/DotNET/Program.cs @@ -16,6 +16,7 @@ static void PrintUsage() Console.Error.WriteLine(" pdf Convert file to PDF"); Console.Error.WriteLine(" pdfa Convert to PDF/A"); Console.Error.WriteLine(" pdfx Convert to PDF/X"); + Console.Error.WriteLine(" tdm-reserved-pdf Apply TDM rights metadata"); Console.Error.WriteLine(" png|jpg|gif|bmp Convert to image format"); Console.Error.WriteLine(" word|excel|powerpoint|tif Convert to Office/TIFF"); Console.Error.WriteLine(" Info / Extract:"); @@ -67,6 +68,7 @@ static void PrintUsage() Console.Error.WriteLine(" rasterized-pdf-multipart Rasterize PDF"); Console.Error.WriteLine(" pdfa-multipart Convert to PDF/A"); Console.Error.WriteLine(" pdfx-multipart Convert to PDF/X"); + Console.Error.WriteLine(" tdm-reserved-pdf-multipart Apply TDM rights metadata"); Console.Error.WriteLine(" png-multipart|jpg-multipart|gif-multipart|bmp-multipart|tif-multipart Convert to image"); Console.Error.WriteLine(" word-multipart|excel-multipart|powerpoint-multipart Convert Office"); Console.Error.WriteLine(" Info / Extract:"); @@ -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; diff --git a/Java/Endpoint Examples/JSON Payload/TDMReservedPDF.java b/Java/Endpoint Examples/JSON Payload/TDMReservedPDF.java new file mode 100644 index 0000000..0bb0d36 --- /dev/null +++ b/Java/Endpoint Examples/JSON Payload/TDMReservedPDF.java @@ -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 ""; + } +} diff --git a/Java/Endpoint Examples/Multipart Payload/TDMReservedPDF.java b/Java/Endpoint Examples/Multipart Payload/TDMReservedPDF.java new file mode 100644 index 0000000..900011b --- /dev/null +++ b/Java/Endpoint Examples/Multipart Payload/TDMReservedPDF.java @@ -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); + } +} diff --git a/JavaScript/Endpoint Examples/JSON Payload/tdm-reserved-pdf.js b/JavaScript/Endpoint Examples/JSON Payload/tdm-reserved-pdf.js new file mode 100644 index 0000000..f2c9c2d --- /dev/null +++ b/JavaScript/Endpoint Examples/JSON Payload/tdm-reserved-pdf.js @@ -0,0 +1,56 @@ +var axios = require("axios"); +var fs = require("fs"); + +// This sample uploads a PDF and applies TDM rights metadata. + +// By default, we use the US-based API service. This is the primary endpoint for global use. +var apiUrl = "https://api.pdfrest.com"; + +/* For GDPR compliance and enhanced performance for European users, you can switch to the EU-based service by uncommenting the URL below. + * For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work + */ +//var apiUrl = "https://eu-api.pdfrest.com"; + +var uploadData = fs.createReadStream("/path/to/file"); + +var uploadConfig = { + method: "post", + maxBodyLength: Infinity, + url: apiUrl + "/upload", + headers: { + "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", // Replace with your API key + "Content-Filename": "filename.pdf", + "Content-Type": "application/octet-stream", + }, + data: uploadData, // set the data to be sent with the request +}; + +// send request and handle response or error +axios(uploadConfig) + .then(function (upload_response) { + console.log(JSON.stringify(upload_response.data)); + var uploadedId = upload_response.data.files[0].id; + + var tdmReservedPdfConfig = { + method: "post", + maxBodyLength: Infinity, + url: apiUrl + "/tdm-reserved-pdf", + headers: { + "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", // Replace with your API key + "Content-Type": "application/json", + }, + data: { id: uploadedId, policy: "https://example.com/tdm-policy" }, // set the data to be sent with the request + }; + + // send request and handle response or error + axios(tdmReservedPdfConfig) + .then(function (tdmReservedPdfResponse) { + console.log(JSON.stringify(tdmReservedPdfResponse.data)); + }) + .catch(function (error) { + console.log(error); + }); + }) + .catch(function (error) { + console.log(error); + }); diff --git a/JavaScript/Endpoint Examples/Multipart Payload/tdm-reserved-pdf.js b/JavaScript/Endpoint Examples/Multipart Payload/tdm-reserved-pdf.js new file mode 100644 index 0000000..3fd0ffa --- /dev/null +++ b/JavaScript/Endpoint Examples/Multipart Payload/tdm-reserved-pdf.js @@ -0,0 +1,41 @@ +// This request demonstrates how to apply TDM rights metadata to a PDF. +var axios = require('axios'); +var FormData = require('form-data'); +var fs = require('fs'); + +// By default, we use the US-based API service. This is the primary endpoint for global use. +var apiUrl = "https://api.pdfrest.com"; + +/* For GDPR compliance and enhanced performance for European users, you can switch to the EU-based service by uncommenting the URL below. + * For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work + */ +//var apiUrl = "https://eu-api.pdfrest.com"; + +// Create a new form data object and append the PDF file and TDM policy to it. +var tdmReservedPdfData = new FormData(); +tdmReservedPdfData.append('file', fs.createReadStream('/path/to/file')); +tdmReservedPdfData.append('policy', 'https://example.com/tdm-policy'); +tdmReservedPdfData.append('output', 'pdfrest_tdm_reserved_pdf'); + +// define configuration options for axios request +var tdmReservedPdfConfig = { + method: 'post', + maxBodyLength: Infinity, // set maximum length of the request body + url: apiUrl + '/tdm-reserved-pdf', + headers: { + 'Api-Key': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', // Replace with your API key + ...tdmReservedPdfData.getHeaders() // set headers for the request + }, + data : tdmReservedPdfData // set the data to be sent with the request +}; + +// send request and handle response or error +axios(tdmReservedPdfConfig) +.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. diff --git a/PHP/Endpoint Examples/JSON Payload/tdm-reserved-pdf.php b/PHP/Endpoint Examples/JSON Payload/tdm-reserved-pdf.php new file mode 100644 index 0000000..ac76970 --- /dev/null +++ b/PHP/Endpoint Examples/JSON Payload/tdm-reserved-pdf.php @@ -0,0 +1,41 @@ + false]); +$upload_headers = [ + 'api-key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', + 'content-filename' => 'filename.pdf', + 'Content-Type' => 'application/octet-stream' +]; +$upload_body = file_get_contents('/path/to/file'); +$upload_request = new Request('POST', $apiUrl.'/upload', $upload_headers, $upload_body); +$upload_res = $upload_client->sendAsync($upload_request)->wait(); +echo $upload_res->getBody() . PHP_EOL; + +$upload_response_json = json_decode($upload_res->getBody()); + +$uploaded_id = $upload_response_json->{'files'}[0]->{'id'}; + +echo "Successfully uploaded with an id of: " . $uploaded_id . PHP_EOL; + +$tdm_reserved_pdf_client = new Client(['http_errors' => false]); +$tdm_reserved_pdf_headers = [ + 'api-key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', + 'Content-Type' => 'application/json' +]; +$tdm_reserved_pdf_body = '{"id":"'.$uploaded_id.'", "policy":"https://example.com/tdm-policy"}'; +$tdm_reserved_pdf_request = new Request('POST', $apiUrl.'/tdm-reserved-pdf', $tdm_reserved_pdf_headers, $tdm_reserved_pdf_body); +$tdm_reserved_pdf_res = $tdm_reserved_pdf_client->sendAsync($tdm_reserved_pdf_request)->wait(); +echo $tdm_reserved_pdf_res->getBody() . PHP_EOL; diff --git a/PHP/Endpoint Examples/Multipart Payload/tdm-reserved-pdf.php b/PHP/Endpoint Examples/Multipart Payload/tdm-reserved-pdf.php new file mode 100644 index 0000000..66bd8fa --- /dev/null +++ b/PHP/Endpoint Examples/Multipart Payload/tdm-reserved-pdf.php @@ -0,0 +1,47 @@ + 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' // Set the API key in the headers for authentication. +]; + +$options = [ + 'multipart' => [ + [ + 'name' => 'file', // Specify the field name for the file. + 'contents' => Utils::tryFopen('/path/to/file', 'r'), // Open the file specified by the '/path/to/file' for reading. + 'filename' => '/path/to/file', // Set the filename for the file to be processed, in this case, '/path/to/file'. + 'headers' => [ + 'Content-Type' => '' // Set the Content-Type header for the file. + ] + ], + [ + 'name' => 'policy', // Specify the field name for the policy string. + 'contents' => 'https://example.com/tdm-policy' // Set a dummy URL policy value. + ], + [ + 'name' => 'output', // Specify the field name for the output option. + 'contents' => 'pdfrest_tdm_reserved_pdf' // Set the value for the output option. + ] + ] +]; + +$request = new Request('POST', $apiUrl.'/tdm-reserved-pdf', $headers); // Create a new HTTP POST request with the API endpoint and headers. + +$res = $client->sendAsync($request, $options)->wait(); // Send the asynchronous request and wait for the response. + +echo $res->getBody(); // Output the response body, which contains the PDF with TDM rights metadata. diff --git a/Python/Endpoint Examples/JSON Payload/tdm-reserved-pdf.py b/Python/Endpoint Examples/JSON Payload/tdm-reserved-pdf.py new file mode 100644 index 0000000..1a1daca --- /dev/null +++ b/Python/Endpoint Examples/JSON Payload/tdm-reserved-pdf.py @@ -0,0 +1,48 @@ +import requests +import json + +# This sample uploads a PDF and applies TDM rights metadata. + +# By default, we use the US-based API service. This is the primary endpoint for global use. +api_url = "https://api.pdfrest.com" + +# For GDPR compliance and enhanced performance for European users, you can switch to the EU-based service by uncommenting the URL below. +# For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work +#api_url = "https://eu-api.pdfrest.com" + +with open('/path/to/file', 'rb') as f: + upload_data = f.read() + +print("Uploading file...") +upload_response = requests.post(url=api_url+'/upload', + data=upload_data, + headers={'Content-Type': 'application/octet-stream', 'Content-Filename': 'file.pdf', "API-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"}) + +print("Upload response status code: " + str(upload_response.status_code)) + +if upload_response.ok: + upload_response_json = upload_response.json() + print(json.dumps(upload_response_json, indent = 2)) + + + uploaded_id = upload_response_json['files'][0]['id'] + tdm_reserved_pdf_data = { "id" : uploaded_id, "policy": "https://example.com/tdm-policy" } + print(json.dumps(tdm_reserved_pdf_data, indent = 2)) + + + print("Applying TDM rights metadata...") + tdm_reserved_pdf_response = requests.post(url=api_url+'/tdm-reserved-pdf', + data=json.dumps(tdm_reserved_pdf_data), + headers={'Content-Type': 'application/json', "API-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"}) + + + + print("Processing response status code: " + str(tdm_reserved_pdf_response.status_code)) + if tdm_reserved_pdf_response.ok: + tdm_reserved_pdf_response_json = tdm_reserved_pdf_response.json() + print(json.dumps(tdm_reserved_pdf_response_json, indent = 2)) + + else: + print(tdm_reserved_pdf_response.text) +else: + print(upload_response.text) diff --git a/Python/Endpoint Examples/Multipart Payload/tdm-reserved-pdf.py b/Python/Endpoint Examples/Multipart Payload/tdm-reserved-pdf.py new file mode 100644 index 0000000..36622bd --- /dev/null +++ b/Python/Endpoint Examples/Multipart Payload/tdm-reserved-pdf.py @@ -0,0 +1,44 @@ +from requests_toolbelt import MultipartEncoder +import requests +import json + +# This sample applies metadata on a PDF declaring Text and Data Mining (TDM) rights. + +# By default, we use the US-based API service. This is the primary endpoint for global use. +api_url = "https://api.pdfrest.com" + +# For GDPR compliance and enhanced performance for European users, you can switch to the EU-based service by uncommenting the URL below. +# For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work +#api_url = "https://eu-api.pdfrest.com" + +tdm_reserved_pdf_endpoint_url = api_url+'/tdm-reserved-pdf' + +# The /tdm-reserved-pdf endpoint can take a single PDF file or id as input. +mp_encoder_tdm_reserved_pdf = MultipartEncoder( + fields={ + 'file': ('file_name.pdf', open('/path/to/file', 'rb'), 'application/pdf'), + 'policy': 'https://example.com/tdm-policy', + 'output' : 'example_tdm_reserved_pdf_out' + } +) + +# Let's set the headers that the tdm-reserved-pdf endpoint expects. +# Since MultipartEncoder is used, the 'Content-Type' header gets set to 'multipart/form-data' via the content_type attribute below. +headers = { + 'Accept': 'application/json', + 'Content-Type': mp_encoder_tdm_reserved_pdf.content_type, + 'Api-Key': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' # place your api key here +} + +print("Sending POST request to tdm-reserved-pdf endpoint...") +response = requests.post(tdm_reserved_pdf_endpoint_url, data=mp_encoder_tdm_reserved_pdf, headers=headers) + +print("Response status code: " + str(response.status_code)) + +if response.ok: + response_json = response.json() + print(json.dumps(response_json, indent = 2)) +else: + print(response.text) + +# If you would like to download the file instead of getting the JSON response, please see the 'get-resource-id-endpoint.py' sample. diff --git a/cURL/Endpoint Examples/JSON Payload/tdm-reserved-pdf.sh b/cURL/Endpoint Examples/JSON Payload/tdm-reserved-pdf.sh new file mode 100755 index 0000000..74e312c --- /dev/null +++ b/cURL/Endpoint Examples/JSON Payload/tdm-reserved-pdf.sh @@ -0,0 +1,22 @@ +#!/bin/sh + +# By default, we use the US-based API service. This is the primary endpoint for global use. +API_URL="https://api.pdfrest.com" + +# For GDPR compliance and enhanced performance for European users, you can switch to the EU-based service by uncommenting the URL below. +# For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work +# API_URL="https://eu-api.pdfrest.com" + +# This request uploads a PDF and applies metadata declaring TDM rights. +UPLOAD_ID=$(curl --location "$API_URL/upload" \ +--header 'Api-Key: xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' \ +--header 'content-filename: filename.pdf' \ +--data-binary '@/path/to/file' \ + | jq -r '.files.[0].id') + +echo "File successfully uploaded with an ID of: $UPLOAD_ID" + +curl "$API_URL/tdm-reserved-pdf" \ +--header 'Api-Key: xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' \ +--header 'Content-Type: application/json' \ +--data-raw "{ \"id\": \"$UPLOAD_ID\", \"policy\": \"https://example.com/tdm-policy\"}" | jq -r '.' diff --git a/cURL/Endpoint Examples/Multipart Payload/tdm-reserved-pdf.sh b/cURL/Endpoint Examples/Multipart Payload/tdm-reserved-pdf.sh new file mode 100755 index 0000000..75e11e5 --- /dev/null +++ b/cURL/Endpoint Examples/Multipart Payload/tdm-reserved-pdf.sh @@ -0,0 +1,15 @@ +# By default, we use the US-based API service. This is the primary endpoint for global use. +API_URL="https://api.pdfrest.com" + +# For GDPR compliance and enhanced performance for European users, you can switch to the EU-based service by uncommenting the URL below. +# For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work +# API_URL="https://eu-api.pdfrest.com" + +# This request applies metadata declaring Text and Data Mining (TDM) rights. +curl -X POST "$API_URL/tdm-reserved-pdf" \ + -H "Accept: application/json" \ + -H "Content-Type: multipart/form-data" \ + -H "Api-Key: xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" \ + -F "file=@/path/to/file" \ + -F "output=example_tdm_reserved_pdf_out" \ + -F "policy=https://example.com/tdm-policy" \