How to Apply TDM Reservations to PDF in .NET with C#

Learn how to use C# with pdfRest TDM Reserve PDF API to protect documents from AI data mining.
Share this page

Why Use TDM Reserve PDF with C#?

The pdfRest TDM Reserve PDF API Tool provides .NET developers with a robust method to shield digital documents from automated scraping bots. This tutorial demonstrates how to construct and send an API call to the TDM Reserve endpoint using C#. By utilizing this endpoint, you can automatically inject compliant TDMRep metadata into your PDFs, effectively telling AI training models and web crawlers to bypass your proprietary content.

For example, a financial services enterprise might use a C# application to generate and distribute proprietary market analysis reports to their premium clients. To ensure these highly valuable insights aren't scraped and summarized by third-party AI tools, the development team can implement the TDM Reserve API as a final step in their document generation pipeline. This guarantees every outgoing report is embedded with a machine-readable "Do Not Mine" directive, securing the firm's competitive advantage and intellectual property.

TDM Reserve PDF with C# Code Example

/*
 * 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);
            }
        }
    }
}

Source: GitHub

Breaking Down the Code

The code begins by checking if the input arguments are valid:

if (args == null || args.Length < 1)
{
    Console.Error.WriteLine("tdm-reserved-pdf-multipart requires ");
    Environment.Exit(1);
    return;
}

This ensures that a file path is provided as an argument. If not, it exits with an error message.

Next, it verifies the existence of the specified file:

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

This step is crucial to avoid processing a non-existent file.

The code then retrieves the API key from environment variables:

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;
}

Without a valid API key, the request cannot be authenticated.

The base URL for the API is set, with an option to override it:

var baseUrl = Environment.GetEnvironmentVariable("PDFREST_URL") ?? "https://api.pdfrest.com";

This allows for regional API endpoint customization.

The code constructs an HTTP POST request with multipart form data:

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);
}

This snippet sends the PDF file along with a policy URL to the API, receiving a JSON response with the result.

Beyond the Tutorial

In this tutorial, you learned how to make a multipart API call to the pdfRest TDM Reserve PDF endpoint using C#. This process involves setting up environment variables, preparing the file and policy data, and handling the API response. To explore more, you can demo all of the pdfRest API Tools in the API Lab. For further details, refer to the API Reference Guide.

Note: This is an example of a multipart API call. Code samples using JSON payloads can be found at GitHub.

Generate a self-service API Key now!
Create your FREE API Key to start processing PDFs in seconds, only possible with pdfRest.