Skip to content
Closed
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
117 changes: 117 additions & 0 deletions DotNET/Complex Flow Examples/refry-pdf.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
/*
* What this sample does:
* - Converts PDF to PostScript and then converts the PostScript back to PDF.
* - This PDF -> PostScript -> PDF roundtrip is commonly called PDF refrying.
* - Some print, prepress, and legacy production workflows use it to rebuild,
* flatten, or normalize page content for downstream systems.
* - Refrying is intentionally lossy and may remove tags, forms, layers,
* annotations, transparency, metadata, and editability.
* - The PostScript-to-PDF step uses a custom .joboptions profile in this
* sample. A .joboptions file contains Adobe Distiller-compatible conversion
* settings; it is optional, and default settings are used when omitted.
* - pdfRest applies the profile with Datalogics PDF Converter SDK. Datalogics
* maintains the SDK in partnership with Adobe, using the same Adobe
* technology that powers Distiller.
*
* 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
*
* Usage:
* dotnet run -- refry-pdf <pdf> <jobOptions> [outputPdf]
*
* Output:
* - Prints each API result and downloads refried.pdf unless outputPdf is set.
*/

using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;

namespace Samples.ComplexFlowExamples;

public static class RefryPdf
{
public static async Task Execute(string[] args)
{
if (args.Length < 2)
{
throw new ArgumentException("refry-pdf requires <pdf> <jobOptions> [outputPdf]");
}

var inputPath = args[0];
var jobOptionsPath = args[1];
var outputPath = args.Length > 2 ? args[2] : Path.Combine("Complex Flow Examples", "refried.pdf");
var apiKey = Environment.GetEnvironmentVariable("PDFREST_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey))
{
throw new InvalidOperationException("Missing PDFREST_API_KEY");
}

var baseUrl = (Environment.GetEnvironmentVariable("PDFREST_URL") ?? "https://api.pdfrest.com").TrimEnd('/');
using var client = new HttpClient(new HttpClientHandler { UseCookies = false })
{
BaseAddress = new Uri(baseUrl),
Timeout = TimeSpan.FromMinutes(2),
};
client.DefaultRequestHeaders.TryAddWithoutValidation("Api-Key", apiKey);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var postscript = await ConvertToPostscript(client, inputPath);
var finalPdf = await ConvertToPdf(client, postscript["outputId"]!.Value<string>()!, jobOptionsPath);
var finalId = finalPdf["outputId"]!.Value<string>()!;

var bytes = await client.GetByteArrayAsync($"resource/{Uri.EscapeDataString(finalId)}?format=file");
await File.WriteAllBytesAsync(outputPath, bytes);
Console.WriteLine(finalPdf.ToString());
Console.WriteLine($"Created {Path.GetFullPath(outputPath)}");
}

private static async Task<JObject> ConvertToPostscript(HttpClient client, string inputPath)
{
using var form = new MultipartFormDataContent();
var input = new ByteArrayContent(await File.ReadAllBytesAsync(inputPath));
input.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
form.Add(input, "file", Path.GetFileName(inputPath));
form.Add(new StringContent("3"), "ps_level");
form.Add(new StringContent("all"), "page_range");
form.Add(new StringContent("true"), "binary_output");
form.Add(new StringContent("1"), "scale");
form.Add(new StringContent("false"), "rotate");
form.Add(new StringContent("true"), "shrink_to_fit");
form.Add(new StringContent("true"), "print_annotations");
form.Add(new StringContent("refry_intermediate"), "output");
return await Post(client, "postscript", form);
}

private static async Task<JObject> ConvertToPdf(
HttpClient client,
string postscriptId,
string jobOptionsPath)
{
using var form = new MultipartFormDataContent();
form.Add(new StringContent(postscriptId), "id");
var jobOptions = new ByteArrayContent(await File.ReadAllBytesAsync(jobOptionsPath));
jobOptions.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
form.Add(jobOptions, "job_options", Path.GetFileName(jobOptionsPath));
form.Add(new StringContent("refried"), "output");
return await Post(client, "pdf", form);
}

private static async Task<JObject> Post(
HttpClient client,
string endpoint,
HttpContent content)
{
using var response = await client.PostAsync(endpoint, content);
var text = await response.Content.ReadAsStringAsync();
Console.WriteLine($"{endpoint}: {(int)response.StatusCode}");
if (!response.IsSuccessStatusCode)
{
throw new InvalidOperationException($"{endpoint} failed: {text}");
}

return JObject.Parse(text);
}
}
50 changes: 50 additions & 0 deletions DotNET/Endpoint Examples/JSON Payload/pdf-from-email.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* What this sample does:
* - Converts an Email (.eml) file to PDF through the /pdf endpoint.
* - Uploads the Email file first, then passes its resource ID in the JSON request.
*
* Setup (environment):
* - Set PDFREST_API_KEY=your_api_key_here
* - Optional: set PDFREST_URL to override the API region.
*
* Usage:
* dotnet run -- pdf-from-email <inputFile>
*/
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;
using System.Text;

namespace Samples.EndpointExamples.JsonPayload;

public static class PdfFromEmail
{
public static async Task Execute(string[] args)
{
var inputPath = args.Length > 0 ? args[0] : "/path/to/sample.eml";
var apiKey = Environment.GetEnvironmentVariable("PDFREST_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException("Missing PDFREST_API_KEY");
var baseUrl = Environment.GetEnvironmentVariable("PDFREST_URL") ?? "https://api.pdfrest.com";
using var client = new HttpClient { BaseAddress = new Uri(baseUrl) };
client.DefaultRequestHeaders.TryAddWithoutValidation("Api-Key", apiKey);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var inputId = await UploadAsync(client, inputPath);
var payload = new JObject { ["id"] = inputId, ["output"] = "pdf_from_email" };
using var content = new StringContent(payload.ToString(), Encoding.UTF8, "application/json");
var response = await client.PostAsync("pdf", content);
var result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
if (!response.IsSuccessStatusCode) Environment.ExitCode = 1;
}

private static async Task<string> UploadAsync(HttpClient client, string path)
{
using var content = new ByteArrayContent(await File.ReadAllBytesAsync(path));
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
using var request = new HttpRequestMessage(HttpMethod.Post, "upload") { Content = content };
request.Headers.Add("Content-Filename", Path.GetFileName(path));
var response = await client.SendAsync(request);
var result = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode) throw new InvalidOperationException(result);
return JObject.Parse(result)["files"]![0]!["id"]!.Value<string>()!;
}
}
63 changes: 63 additions & 0 deletions DotNET/Endpoint Examples/JSON Payload/pdf-from-postscript.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* What this sample does:
* - Converts PostScript to PDF with a custom .joboptions profile.
* - A .joboptions file contains Adobe Distiller-compatible conversion settings.
* The profile is optional; omit job_options to use default settings.
* - pdfRest applies a supplied profile with Datalogics PDF Converter SDK.
* Datalogics maintains the SDK in partnership with Adobe, using the same
* Adobe technology that powers Distiller.
* - Pair with /postscript for PDF refrying: PDF -> PostScript -> PDF. Some print and
* prepress workflows use this lossy roundtrip to rebuild or normalize page content.
*
* Setup (environment):
* - Set PDFREST_API_KEY=your_api_key_here
* - Optional: set PDFREST_URL to override the API region.
*
* Usage:
* dotnet run -- pdf-from-postscript <postscriptFile> <jobOptionsFile>
*/
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;
using System.Text;

namespace Samples.EndpointExamples.JsonPayload;

public static class PdfFromPostscript
{
public static async Task Execute(string[] args)
{
var inputPath = args.Length > 0 ? args[0] : "/path/to/sample.ps";
var jobOptionsPath = args.Length > 1 ? args[1] : "/path/to/custom.joboptions";
var apiKey = Environment.GetEnvironmentVariable("PDFREST_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException("Missing PDFREST_API_KEY");
var baseUrl = Environment.GetEnvironmentVariable("PDFREST_URL") ?? "https://api.pdfrest.com";
using var client = new HttpClient { BaseAddress = new Uri(baseUrl) };
client.DefaultRequestHeaders.TryAddWithoutValidation("Api-Key", apiKey);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var inputId = await UploadAsync(client, inputPath);
var jobOptionsId = await UploadAsync(client, jobOptionsPath);
var payload = new JObject
{
["id"] = inputId,
["job_options_id"] = jobOptionsId,
["output"] = "pdf_from_postscript",
};
using var content = new StringContent(payload.ToString(), Encoding.UTF8, "application/json");
var response = await client.PostAsync("pdf", content);
var result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
if (!response.IsSuccessStatusCode) Environment.ExitCode = 1;
}

private static async Task<string> UploadAsync(HttpClient client, string path)
{
using var content = new ByteArrayContent(await File.ReadAllBytesAsync(path));
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
using var request = new HttpRequestMessage(HttpMethod.Post, "upload") { Content = content };
request.Headers.Add("Content-Filename", Path.GetFileName(path));
var response = await client.SendAsync(request);
var result = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode) throw new InvalidOperationException(result);
return JObject.Parse(result)["files"]![0]!["id"]!.Value<string>()!;
}
}
64 changes: 64 additions & 0 deletions DotNET/Endpoint Examples/JSON Payload/postscript.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* What this sample does:
* - Converts PDF to PostScript through the /postscript endpoint.
* - Pair with /pdf for PDF refrying: PDF -> PostScript -> PDF. Some print and prepress
* workflows use this lossy roundtrip to rebuild, flatten, or normalize page content.
* - Requests Level 3, text-safe output, all pages at original scale, shrink-to-fit
* without rotation, and printable annotations.
*
* Setup (environment):
* - Set PDFREST_API_KEY=your_api_key_here
* - Optional: set PDFREST_URL to override the API region.
*
* Usage:
* dotnet run -- postscript <inputFile>
*/
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;
using System.Text;

namespace Samples.EndpointExamples.JsonPayload;

public static class Postscript
{
public static async Task Execute(string[] args)
{
var inputPath = args.Length > 0 ? args[0] : "/path/to/sample.pdf";
var apiKey = Environment.GetEnvironmentVariable("PDFREST_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException("Missing PDFREST_API_KEY");
var baseUrl = Environment.GetEnvironmentVariable("PDFREST_URL") ?? "https://api.pdfrest.com";
using var client = new HttpClient { BaseAddress = new Uri(baseUrl) };
client.DefaultRequestHeaders.TryAddWithoutValidation("Api-Key", apiKey);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var inputId = await UploadAsync(client, inputPath);
var payload = new JObject
{
["id"] = inputId,
["ps_level"] = 3,
["page_range"] = "all",
["binary_output"] = false,
["scale"] = 1,
["rotate"] = false,
["shrink_to_fit"] = true,
["print_annotations"] = true,
["output"] = "postscript_from_pdf",
};
using var content = new StringContent(payload.ToString(), Encoding.UTF8, "application/json");
var response = await client.PostAsync("postscript", content);
var result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
if (!response.IsSuccessStatusCode) Environment.ExitCode = 1;
}

private static async Task<string> UploadAsync(HttpClient client, string path)
{
using var content = new ByteArrayContent(await File.ReadAllBytesAsync(path));
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
using var request = new HttpRequestMessage(HttpMethod.Post, "upload") { Content = content };
request.Headers.Add("Content-Filename", Path.GetFileName(path));
var response = await client.SendAsync(request);
var result = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode) throw new InvalidOperationException(result);
return JObject.Parse(result)["files"]![0]!["id"]!.Value<string>()!;
}
}
38 changes: 38 additions & 0 deletions DotNET/Endpoint Examples/Multipart Payload/pdf-from-email.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* What this sample does:
* - Converts an Email (.eml) file to PDF through the /pdf endpoint.
* - Sends the Email file directly in a multipart request.
*
* Setup (environment):
* - Set PDFREST_API_KEY=your_api_key_here
* - Optional: set PDFREST_URL to override the API region.
*
* Usage:
* dotnet run -- pdf-from-email-multipart <inputFile>
*/
using System.Net.Http.Headers;

namespace Samples.EndpointExamples.MultipartPayload;

public static class PdfFromEmail
{
public static async Task Execute(string[] args)
{
var inputPath = args.Length > 0 ? args[0] : "/path/to/sample.eml";
var apiKey = Environment.GetEnvironmentVariable("PDFREST_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException("Missing PDFREST_API_KEY");
var baseUrl = Environment.GetEnvironmentVariable("PDFREST_URL") ?? "https://api.pdfrest.com";
using var client = new HttpClient { BaseAddress = new Uri(baseUrl) };
client.DefaultRequestHeaders.TryAddWithoutValidation("Api-Key", apiKey);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using var form = new MultipartFormDataContent();
var inputContent = new ByteArrayContent(await File.ReadAllBytesAsync(inputPath));
inputContent.Headers.ContentType = new MediaTypeHeaderValue("message/rfc822");
form.Add(inputContent, "file", Path.GetFileName(inputPath));
form.Add(new StringContent("pdf_from_email"), "output");
var response = await client.PostAsync("pdf", form);
var result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
if (!response.IsSuccessStatusCode) Environment.ExitCode = 1;
}
}
48 changes: 48 additions & 0 deletions DotNET/Endpoint Examples/Multipart Payload/pdf-from-postscript.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* What this sample does:
* - Converts PostScript to PDF with a custom .joboptions profile.
* - A .joboptions file contains Adobe Distiller-compatible conversion settings.
* The profile is optional; omit job_options to use default settings.
* - pdfRest applies a supplied profile with Datalogics PDF Converter SDK.
* Datalogics maintains the SDK in partnership with Adobe, using the same
* Adobe technology that powers Distiller.
* - Pair with /postscript for PDF refrying: PDF -> PostScript -> PDF. Some print and
* prepress workflows use this lossy roundtrip to rebuild or normalize page content.
*
* Setup (environment):
* - Set PDFREST_API_KEY=your_api_key_here
* - Optional: set PDFREST_URL to override the API region.
*
* Usage:
* dotnet run -- pdf-from-postscript-multipart <postscriptFile> <jobOptionsFile>
*/
using System.Net.Http.Headers;

namespace Samples.EndpointExamples.MultipartPayload;

public static class PdfFromPostscript
{
public static async Task Execute(string[] args)
{
var inputPath = args.Length > 0 ? args[0] : "/path/to/sample.ps";
var jobOptionsPath = args.Length > 1 ? args[1] : "/path/to/custom.joboptions";
var apiKey = Environment.GetEnvironmentVariable("PDFREST_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException("Missing PDFREST_API_KEY");
var baseUrl = Environment.GetEnvironmentVariable("PDFREST_URL") ?? "https://api.pdfrest.com";
using var client = new HttpClient { BaseAddress = new Uri(baseUrl) };
client.DefaultRequestHeaders.TryAddWithoutValidation("Api-Key", apiKey);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using var form = new MultipartFormDataContent();
var inputContent = new ByteArrayContent(await File.ReadAllBytesAsync(inputPath));
inputContent.Headers.ContentType = new MediaTypeHeaderValue("application/postscript");
form.Add(inputContent, "file", Path.GetFileName(inputPath));
var jobOptionsContent = new ByteArrayContent(await File.ReadAllBytesAsync(jobOptionsPath));
jobOptionsContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
form.Add(jobOptionsContent, "job_options", Path.GetFileName(jobOptionsPath));
form.Add(new StringContent("pdf_from_postscript"), "output");
var response = await client.PostAsync("pdf", form);
var result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
if (!response.IsSuccessStatusCode) Environment.ExitCode = 1;
}
}
Loading
Loading