diff --git a/DotNET/Complex Flow Examples/refry-pdf.cs b/DotNET/Complex Flow Examples/refry-pdf.cs new file mode 100644 index 0000000..54e3e13 --- /dev/null +++ b/DotNET/Complex Flow Examples/refry-pdf.cs @@ -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 [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 [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()!, jobOptionsPath); + var finalId = finalPdf["outputId"]!.Value()!; + + 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 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 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 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); + } +} diff --git a/DotNET/Endpoint Examples/JSON Payload/pdf-from-email.cs b/DotNET/Endpoint Examples/JSON Payload/pdf-from-email.cs new file mode 100644 index 0000000..2d7bd3f --- /dev/null +++ b/DotNET/Endpoint Examples/JSON Payload/pdf-from-email.cs @@ -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 + */ +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 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()!; + } +} diff --git a/DotNET/Endpoint Examples/JSON Payload/pdf-from-postscript.cs b/DotNET/Endpoint Examples/JSON Payload/pdf-from-postscript.cs new file mode 100644 index 0000000..4a2c57a --- /dev/null +++ b/DotNET/Endpoint Examples/JSON Payload/pdf-from-postscript.cs @@ -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 + */ +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 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()!; + } +} diff --git a/DotNET/Endpoint Examples/JSON Payload/postscript.cs b/DotNET/Endpoint Examples/JSON Payload/postscript.cs new file mode 100644 index 0000000..6b86024 --- /dev/null +++ b/DotNET/Endpoint Examples/JSON Payload/postscript.cs @@ -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 + */ +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 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()!; + } +} diff --git a/DotNET/Endpoint Examples/Multipart Payload/pdf-from-email.cs b/DotNET/Endpoint Examples/Multipart Payload/pdf-from-email.cs new file mode 100644 index 0000000..fa4a2ac --- /dev/null +++ b/DotNET/Endpoint Examples/Multipart Payload/pdf-from-email.cs @@ -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 + */ +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; + } +} diff --git a/DotNET/Endpoint Examples/Multipart Payload/pdf-from-postscript.cs b/DotNET/Endpoint Examples/Multipart Payload/pdf-from-postscript.cs new file mode 100644 index 0000000..ab8e43f --- /dev/null +++ b/DotNET/Endpoint Examples/Multipart Payload/pdf-from-postscript.cs @@ -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 + */ +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; + } +} diff --git a/DotNET/Endpoint Examples/Multipart Payload/postscript.cs b/DotNET/Endpoint Examples/Multipart Payload/postscript.cs new file mode 100644 index 0000000..e54f774 --- /dev/null +++ b/DotNET/Endpoint Examples/Multipart Payload/postscript.cs @@ -0,0 +1,48 @@ +/* + * 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-multipart + */ +using System.Net.Http.Headers; + +namespace Samples.EndpointExamples.MultipartPayload; + +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")); + using var form = new MultipartFormDataContent(); + var inputContent = new ByteArrayContent(await File.ReadAllBytesAsync(inputPath)); + inputContent.Headers.ContentType = new MediaTypeHeaderValue("application/pdf"); + form.Add(inputContent, "file", Path.GetFileName(inputPath)); + form.Add(new StringContent("3"), "ps_level"); + form.Add(new StringContent("all"), "page_range"); + form.Add(new StringContent("false"), "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("postscript_from_pdf"), "output"); + var response = await client.PostAsync("postscript", form); + var result = await response.Content.ReadAsStringAsync(); + Console.WriteLine(result); + if (!response.IsSuccessStatusCode) Environment.ExitCode = 1; + } +} diff --git a/DotNET/Program.cs b/DotNET/Program.cs index e8b732a..a902f20 100644 --- a/DotNET/Program.cs +++ b/DotNET/Program.cs @@ -14,6 +14,9 @@ static void PrintUsage() Console.Error.WriteLine(" markdown-json Convert PDF to Markdown"); Console.Error.WriteLine(" rasterized-pdf Rasterize PDF pages"); Console.Error.WriteLine(" pdf Convert file to PDF"); + Console.Error.WriteLine(" pdf-from-email Convert Email (.eml) to PDF"); + Console.Error.WriteLine(" pdf-from-postscript Convert PostScript to PDF"); + Console.Error.WriteLine(" postscript Convert PDF to PostScript"); Console.Error.WriteLine(" pdf-from-markdown|csv|json|xml|text Structured input to PDF"); Console.Error.WriteLine(" pdfa Convert to PDF/A"); Console.Error.WriteLine(" pdfx Convert to PDF/X"); @@ -67,6 +70,9 @@ static void PrintUsage() Console.Error.WriteLine("Multipart Payload (multipart/form-data):"); Console.Error.WriteLine(" Conversions:"); Console.Error.WriteLine(" pdf-multipart Convert to PDF"); + Console.Error.WriteLine(" pdf-from-email-multipart Convert Email (.eml) to PDF"); + Console.Error.WriteLine(" pdf-from-postscript-multipart Convert PostScript to PDF"); + Console.Error.WriteLine(" postscript-multipart Convert PDF to PostScript"); Console.Error.WriteLine(" pdf-from-markdown|csv|json|xml|text-multipart Structured input to PDF"); Console.Error.WriteLine(" markdown-multipart Convert to Markdown"); Console.Error.WriteLine(" rasterized-pdf-multipart Rasterize PDF"); @@ -128,6 +134,7 @@ static void PrintUsage() Console.Error.WriteLine(" protected-watermark Watermark then restrict"); Console.Error.WriteLine(" redact-preview-and-finalize Preview then apply redactions\n"); Console.Error.WriteLine(" create-invoice-from-structured-data Generate invoice from JSON and CSV\n"); + Console.Error.WriteLine(" refry-pdf [outputPdf] Convert PDF to PostScript and back\n"); Console.Error.WriteLine("Environment (.env supported):"); Console.Error.WriteLine(" PDFREST_API_KEY=... Required API key"); @@ -166,6 +173,15 @@ static void PrintUsage() case "pdf-multipart": await Samples.EndpointExamples.MultipartPayload.Pdf.Execute(rest); break; + case "pdf-from-email": + await Samples.EndpointExamples.JsonPayload.PdfFromEmail.Execute(rest); + break; + case "pdf-from-postscript": + await Samples.EndpointExamples.JsonPayload.PdfFromPostscript.Execute(rest); + break; + case "postscript": + await Samples.EndpointExamples.JsonPayload.Postscript.Execute(rest); + break; case "pdf-from-markdown": await Samples.EndpointExamples.JsonPayload.PdfFromMarkdown.Execute(rest); break; @@ -181,6 +197,15 @@ static void PrintUsage() case "pdf-from-text": await Samples.EndpointExamples.JsonPayload.PdfFromText.Execute(rest); break; + case "pdf-from-email-multipart": + await Samples.EndpointExamples.MultipartPayload.PdfFromEmail.Execute(rest); + break; + case "pdf-from-postscript-multipart": + await Samples.EndpointExamples.MultipartPayload.PdfFromPostscript.Execute(rest); + break; + case "postscript-multipart": + await Samples.EndpointExamples.MultipartPayload.Postscript.Execute(rest); + break; case "pdf-from-markdown-multipart": await Samples.EndpointExamples.MultipartPayload.PdfFromMarkdown.Execute(rest); break; @@ -254,6 +279,9 @@ static void PrintUsage() case "create-invoice-from-structured-data": await Samples.ComplexFlowExamples.CreateInvoiceFromStructuredData.Execute(rest); break; + case "refry-pdf": + await Samples.ComplexFlowExamples.RefryPdf.Execute(rest); + break; case "extracted-text": await Samples.EndpointExamples.JsonPayload.ExtractedText.Execute(rest); break; diff --git a/Java/Complex Flow Examples/RefryPdf.java b/Java/Complex Flow Examples/RefryPdf.java new file mode 100644 index 0000000..02b5da6 --- /dev/null +++ b/Java/Complex Flow Examples/RefryPdf.java @@ -0,0 +1,119 @@ +import io.github.cdimascio.dotenv.Dotenv; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.concurrent.TimeUnit; +import okhttp3.MediaType; +import okhttp3.MultipartBody; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import org.json.JSONObject; + +/* + * Refry a PDF by converting it to PostScript and back to PDF. + * + * PDF refrying is the common name for a PDF -> PostScript -> PDF roundtrip. + * Some print, prepress, and legacy production workflows use it to rebuild, + * flatten, or normalize page content for downstream systems. The process is + * intentionally lossy and may remove tags, forms, layers, annotations, + * transparency, metadata, and editability. Use this workflow when a downstream + * system requires rebuilt page content or a PostScript-based interchange file. + * + * 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. + * + * Run: java RefryPdf [outputPdf] + */ +public class RefryPdf { + private static final String DEFAULT_API_URL = "https://api.pdfrest.com"; + private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; + private static final OkHttpClient CLIENT = + new OkHttpClient.Builder().readTimeout(120, TimeUnit.SECONDS).build(); + + public static void main(String[] args) throws IOException { + File inputFile = new File(args.length > 0 ? args[0] : "/path/to/sample.pdf"); + File jobOptionsFile = new File(args.length > 1 ? args[1] : "/path/to/custom.joboptions"); + Path outputPath = args.length > 2 ? Path.of(args[2]) : Path.of("refried.pdf"); + + Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load(); + String apiUrl = dotenv.get("PDFREST_URL", DEFAULT_API_URL).replaceAll("/$", ""); + String apiKey = dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY); + + JSONObject postscript = + postMultipart( + apiUrl, + apiKey, + "postscript", + new MultipartBody.Builder() + .setType(MultipartBody.FORM) + .addFormDataPart( + "file", + inputFile.getName(), + RequestBody.create(inputFile, MediaType.parse("application/pdf"))) + .addFormDataPart("ps_level", "3") + .addFormDataPart("page_range", "all") + .addFormDataPart("binary_output", "true") + .addFormDataPart("scale", "1") + .addFormDataPart("rotate", "false") + .addFormDataPart("shrink_to_fit", "true") + .addFormDataPart("print_annotations", "true") + .addFormDataPart("output", "refry_intermediate") + .build()); + + JSONObject finalPdf = + postMultipart( + apiUrl, + apiKey, + "pdf", + new MultipartBody.Builder() + .setType(MultipartBody.FORM) + .addFormDataPart("id", postscript.getString("outputId")) + .addFormDataPart( + "job_options", + jobOptionsFile.getName(), + RequestBody.create(jobOptionsFile, MediaType.parse("application/octet-stream"))) + .addFormDataPart("output", "refried") + .build()); + + Request downloadRequest = + new Request.Builder() + .url(apiUrl + "/resource/" + finalPdf.getString("outputId") + "?format=file") + .header("Api-Key", apiKey) + .build(); + try (Response response = CLIENT.newCall(downloadRequest).execute()) { + if (!response.isSuccessful() || response.body() == null) { + throw new IOException("resource download failed: " + response.code()); + } + Files.write(outputPath, response.body().bytes()); + } + + System.out.println(finalPdf.toString(2)); + System.out.println("Created " + outputPath.toAbsolutePath()); + } + + private static JSONObject postMultipart( + String apiUrl, String apiKey, String endpoint, RequestBody body) throws IOException { + Request request = + new Request.Builder() + .url(apiUrl + "/" + endpoint) + .header("Api-Key", apiKey) + .header("Accept", "application/json") + .post(body) + .build(); + try (Response response = CLIENT.newCall(request).execute()) { + String text = response.body() == null ? "" : response.body().string(); + System.out.println(endpoint + ": " + response.code()); + if (!response.isSuccessful()) { + throw new IOException(endpoint + " failed: " + text); + } + return new JSONObject(text); + } + } +} diff --git a/Java/Endpoint Examples/JSON Payload/PdfFromEmail.java b/Java/Endpoint Examples/JSON Payload/PdfFromEmail.java new file mode 100644 index 0000000..d45035b --- /dev/null +++ b/Java/Endpoint Examples/JSON Payload/PdfFromEmail.java @@ -0,0 +1,58 @@ +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 PdfFromEmail { + // 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, replace the URL above + // with https://eu-api.pdfrest.com. For more information, visit + // https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work. + private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; + + // Converts an Email (.eml) file to PDF. The JSON request uses the resource ID + // returned after uploading the Email file. + public static void main(String[] args) throws IOException { + File inputFile = new File(args.length > 0 ? args[0] : "/path/to/sample.eml"); + Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load(); + String apiKey = dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY); + String inputId = upload(inputFile, apiKey); + JSONObject payload = new JSONObject().put("id", inputId).put("output", "pdf_from_email"); + Request request = + new Request.Builder() + .url(API_URL + "/pdf") + .header("Api-Key", apiKey) + .post(RequestBody.create(payload.toString(), MediaType.parse("application/json"))) + .build(); + send(request); + } + + private static void send(Request request) throws IOException { + OkHttpClient client = new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).build(); + try (Response response = client.newCall(request).execute()) { + System.out.println("Result code " + response.code()); + if (response.body() != null) System.out.println(response.body().string()); + if (!response.isSuccessful()) System.exit(1); + } + } + + private static String upload(File file, String apiKey) throws IOException { + Request request = + new Request.Builder() + .url(API_URL + "/upload") + .header("Api-Key", apiKey) + .header("Content-Filename", file.getName()) + .post(RequestBody.create(file, MediaType.parse("application/octet-stream"))) + .build(); + OkHttpClient client = new OkHttpClient(); + try (Response response = client.newCall(request).execute()) { + String body = response.body() == null ? "{}" : response.body().string(); + if (!response.isSuccessful()) throw new IOException(body); + return new JSONObject(body).getJSONArray("files").getJSONObject(0).getString("id"); + } + } +} diff --git a/Java/Endpoint Examples/JSON Payload/PdfFromPostscript.java b/Java/Endpoint Examples/JSON Payload/PdfFromPostscript.java new file mode 100644 index 0000000..c296c0f --- /dev/null +++ b/Java/Endpoint Examples/JSON Payload/PdfFromPostscript.java @@ -0,0 +1,71 @@ +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 PdfFromPostscript { + // 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, replace the URL above + // with https://eu-api.pdfrest.com. For more information, visit + // https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work. + private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; + + /* This sample 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. + */ + public static void main(String[] args) throws IOException { + File inputFile = new File(args.length > 0 ? args[0] : "/path/to/sample.ps"); + File jobOptionsFile = new File(args.length > 1 ? args[1] : "/path/to/custom.joboptions"); + Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load(); + String apiKey = dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY); + String inputId = upload(inputFile, apiKey); + String jobOptionsId = upload(jobOptionsFile, apiKey); + JSONObject payload = + new JSONObject() + .put("id", inputId) + .put("job_options_id", jobOptionsId) + .put("output", "pdf_from_postscript"); + Request request = + new Request.Builder() + .url(API_URL + "/pdf") + .header("Api-Key", apiKey) + .post(RequestBody.create(payload.toString(), MediaType.parse("application/json"))) + .build(); + send(request); + } + + private static void send(Request request) throws IOException { + OkHttpClient client = new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).build(); + try (Response response = client.newCall(request).execute()) { + System.out.println("Result code " + response.code()); + if (response.body() != null) System.out.println(response.body().string()); + if (!response.isSuccessful()) System.exit(1); + } + } + + private static String upload(File file, String apiKey) throws IOException { + Request request = + new Request.Builder() + .url(API_URL + "/upload") + .header("Api-Key", apiKey) + .header("Content-Filename", file.getName()) + .post(RequestBody.create(file, MediaType.parse("application/octet-stream"))) + .build(); + OkHttpClient client = new OkHttpClient(); + try (Response response = client.newCall(request).execute()) { + String body = response.body() == null ? "{}" : response.body().string(); + if (!response.isSuccessful()) throw new IOException(body); + return new JSONObject(body).getJSONArray("files").getJSONObject(0).getString("id"); + } + } +} diff --git a/Java/Endpoint Examples/JSON Payload/Postscript.java b/Java/Endpoint Examples/JSON Payload/Postscript.java new file mode 100644 index 0000000..f155027 --- /dev/null +++ b/Java/Endpoint Examples/JSON Payload/Postscript.java @@ -0,0 +1,73 @@ +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 Postscript { + // 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, replace the URL above + // with https://eu-api.pdfrest.com. For more information, visit + // https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work. + private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; + + /* This sample uploads a PDF, then converts it through the JSON /postscript flow. + * Pairing this endpoint with /pdf creates a PDF -> PostScript -> PDF workflow commonly + * called PDF refrying. Some print and prepress workflows use it to rebuild, flatten, + * or normalize page content, but the lossy roundtrip can discard PDF-specific features. + * These settings request Level 3, text-safe output, all pages at original scale, + * shrink-to-fit without rotation, and printable annotations. + */ + public static void main(String[] args) throws IOException { + File inputFile = new File(args.length > 0 ? args[0] : "/path/to/sample.pdf"); + Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load(); + String apiKey = dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY); + String inputId = upload(inputFile, apiKey); + JSONObject payload = + new JSONObject() + .put("id", inputId) + .put("ps_level", 3) + .put("page_range", "all") + .put("binary_output", false) + .put("scale", 1) + .put("rotate", false) + .put("shrink_to_fit", true) + .put("print_annotations", true) + .put("output", "postscript_from_pdf"); + Request request = + new Request.Builder() + .url(API_URL + "/postscript") + .header("Api-Key", apiKey) + .post(RequestBody.create(payload.toString(), MediaType.parse("application/json"))) + .build(); + send(request); + } + + private static void send(Request request) throws IOException { + OkHttpClient client = new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).build(); + try (Response response = client.newCall(request).execute()) { + System.out.println("Result code " + response.code()); + if (response.body() != null) System.out.println(response.body().string()); + if (!response.isSuccessful()) System.exit(1); + } + } + + private static String upload(File file, String apiKey) throws IOException { + Request request = + new Request.Builder() + .url(API_URL + "/upload") + .header("Api-Key", apiKey) + .header("Content-Filename", file.getName()) + .post(RequestBody.create(file, MediaType.parse("application/octet-stream"))) + .build(); + OkHttpClient client = new OkHttpClient(); + try (Response response = client.newCall(request).execute()) { + String body = response.body() == null ? "{}" : response.body().string(); + if (!response.isSuccessful()) throw new IOException(body); + return new JSONObject(body).getJSONArray("files").getJSONObject(0).getString("id"); + } + } +} diff --git a/Java/Endpoint Examples/Multipart Payload/PdfFromEmail.java b/Java/Endpoint Examples/Multipart Payload/PdfFromEmail.java new file mode 100644 index 0000000..f3e1e97 --- /dev/null +++ b/Java/Endpoint Examples/Multipart Payload/PdfFromEmail.java @@ -0,0 +1,47 @@ +import io.github.cdimascio.dotenv.Dotenv; +import java.io.File; +import java.io.IOException; +import java.util.concurrent.TimeUnit; +import okhttp3.*; + +public class PdfFromEmail { + // 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, replace the URL above + // with https://eu-api.pdfrest.com. For more information, visit + // https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work. + private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; + + // Converts an Email (.eml) file to PDF by sending the file directly in a + // multipart request. + public static void main(String[] args) throws IOException { + File inputFile = new File(args.length > 0 ? args[0] : "/path/to/sample.eml"); + Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load(); + String apiKey = dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY); + MultipartBody.Builder form = + new MultipartBody.Builder() + .setType(MultipartBody.FORM) + .addFormDataPart( + "file", + inputFile.getName(), + RequestBody.create(inputFile, MediaType.parse("message/rfc822"))) + .addFormDataPart("output", "pdf_from_email"); + Request request = + new Request.Builder() + .url(API_URL + "/pdf") + .header("Api-Key", apiKey) + .post(form.build()) + .build(); + send(request); + } + + private static void send(Request request) throws IOException { + OkHttpClient client = new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).build(); + try (Response response = client.newCall(request).execute()) { + System.out.println("Result code " + response.code()); + if (response.body() != null) System.out.println(response.body().string()); + if (!response.isSuccessful()) System.exit(1); + } + } +} diff --git a/Java/Endpoint Examples/Multipart Payload/PdfFromPostscript.java b/Java/Endpoint Examples/Multipart Payload/PdfFromPostscript.java new file mode 100644 index 0000000..925d107 --- /dev/null +++ b/Java/Endpoint Examples/Multipart Payload/PdfFromPostscript.java @@ -0,0 +1,59 @@ +import io.github.cdimascio.dotenv.Dotenv; +import java.io.File; +import java.io.IOException; +import java.util.concurrent.TimeUnit; +import okhttp3.*; + +public class PdfFromPostscript { + // 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, replace the URL above + // with https://eu-api.pdfrest.com. For more information, visit + // https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work. + private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; + + /* This sample 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. + */ + public static void main(String[] args) throws IOException { + File inputFile = new File(args.length > 0 ? args[0] : "/path/to/sample.ps"); + File jobOptionsFile = new File(args.length > 1 ? args[1] : "/path/to/custom.joboptions"); + Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load(); + String apiKey = dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY); + MultipartBody.Builder form = + new MultipartBody.Builder() + .setType(MultipartBody.FORM) + .addFormDataPart( + "file", + inputFile.getName(), + RequestBody.create(inputFile, MediaType.parse("application/postscript"))) + .addFormDataPart( + "job_options", + jobOptionsFile.getName(), + RequestBody.create(jobOptionsFile, MediaType.parse("application/octet-stream"))) + .addFormDataPart("output", "pdf_from_postscript"); + Request request = + new Request.Builder() + .url(API_URL + "/pdf") + .header("Api-Key", apiKey) + .post(form.build()) + .build(); + send(request); + } + + private static void send(Request request) throws IOException { + OkHttpClient client = new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).build(); + try (Response response = client.newCall(request).execute()) { + System.out.println("Result code " + response.code()); + if (response.body() != null) System.out.println(response.body().string()); + if (!response.isSuccessful()) System.exit(1); + } + } +} diff --git a/Java/Endpoint Examples/Multipart Payload/Postscript.java b/Java/Endpoint Examples/Multipart Payload/Postscript.java new file mode 100644 index 0000000..ea4081c --- /dev/null +++ b/Java/Endpoint Examples/Multipart Payload/Postscript.java @@ -0,0 +1,59 @@ +import io.github.cdimascio.dotenv.Dotenv; +import java.io.File; +import java.io.IOException; +import java.util.concurrent.TimeUnit; +import okhttp3.*; + +public class Postscript { + // 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, replace the URL above + // with https://eu-api.pdfrest.com. For more information, visit + // https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work. + private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; + + /* This sample converts PDF to PostScript through /postscript. Pairing this endpoint + * with /pdf creates a PDF -> PostScript -> PDF workflow commonly called PDF refrying. + * Some print and prepress workflows use it to rebuild, flatten, or normalize page + * content, but the lossy roundtrip can discard PDF-specific features. These settings + * request Level 3, text-safe output, all pages at original scale, shrink-to-fit without + * rotation, and printable annotations. + */ + public static void main(String[] args) throws IOException { + File inputFile = new File(args.length > 0 ? args[0] : "/path/to/sample.pdf"); + Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load(); + String apiKey = dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY); + MultipartBody.Builder form = + new MultipartBody.Builder() + .setType(MultipartBody.FORM) + .addFormDataPart( + "file", + inputFile.getName(), + RequestBody.create(inputFile, MediaType.parse("application/pdf"))) + .addFormDataPart("ps_level", "3") + .addFormDataPart("page_range", "all") + .addFormDataPart("binary_output", "false") + .addFormDataPart("scale", "1") + .addFormDataPart("rotate", "false") + .addFormDataPart("shrink_to_fit", "true") + .addFormDataPart("print_annotations", "true") + .addFormDataPart("output", "postscript_from_pdf"); + Request request = + new Request.Builder() + .url(API_URL + "/postscript") + .header("Api-Key", apiKey) + .post(form.build()) + .build(); + send(request); + } + + private static void send(Request request) throws IOException { + OkHttpClient client = new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).build(); + try (Response response = client.newCall(request).execute()) { + System.out.println("Result code " + response.code()); + if (response.body() != null) System.out.println(response.body().string()); + if (!response.isSuccessful()) System.exit(1); + } + } +} diff --git a/JavaScript/Complex Flow Examples/refry-pdf.js b/JavaScript/Complex Flow Examples/refry-pdf.js new file mode 100644 index 0000000..a80f42c --- /dev/null +++ b/JavaScript/Complex Flow Examples/refry-pdf.js @@ -0,0 +1,81 @@ +/** + * Refry a PDF by converting it to PostScript and back to PDF. + * + * PDF refrying is the common name for a PDF -> PostScript -> PDF roundtrip. + * Some print, prepress, and legacy production workflows use it to rebuild or + * normalize page content, flatten certain PDF constructs, or prepare a file + * for downstream systems. The process is intentionally lossy and may remove + * tags, forms, layers, annotations, transparency, metadata, and editability. + * Use this workflow when a downstream system requires rebuilt page content or + * a PostScript-based interchange file. + * + * 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. + * + * Run: node refry-pdf.js [outputPdf] + */ +const axios = require("axios"); +const FormData = require("form-data"); +const fs = require("fs"); +const path = require("path"); + +const apiUrl = (process.env.PDFREST_URL || "https://api.pdfrest.com").replace(/\/$/, ""); +const apiKey = process.env.PDFREST_API_KEY || "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; +const inputPath = process.argv[2] || "/path/to/sample.pdf"; +const jobOptionsPath = process.argv[3] || "/path/to/custom.joboptions"; +const outputPath = process.argv[4] || path.join(__dirname, "refried.pdf"); + +async function postMultipart(endpoint, fields) { + const form = new FormData(); + for (const field of fields) { + if (field.path) { + form.append(field.name, fs.createReadStream(field.path), { + filename: path.basename(field.path), + contentType: field.contentType, + }); + } else { + form.append(field.name, field.value); + } + } + const response = await axios.post(`${apiUrl}/${endpoint}`, form, { + headers: { Accept: "application/json", "Api-Key": apiKey, ...form.getHeaders() }, + maxBodyLength: Infinity, + }); + console.log(`${endpoint}: ${response.status}`); + return response.data; +} + +async function main() { + const postscript = await postMultipart("postscript", [ + { name: "file", path: inputPath, contentType: "application/pdf" }, + { name: "ps_level", value: "3" }, + { name: "page_range", value: "all" }, + { name: "binary_output", value: "true" }, + { name: "scale", value: "1" }, + { name: "rotate", value: "false" }, + { name: "shrink_to_fit", value: "true" }, + { name: "print_annotations", value: "true" }, + { name: "output", value: "refry_intermediate" }, + ]); + const finalPdf = await postMultipart("pdf", [ + { name: "id", value: postscript.outputId }, + { name: "job_options", path: jobOptionsPath, contentType: "application/octet-stream" }, + { name: "output", value: "refried" }, + ]); + const download = await axios.get(`${apiUrl}/resource/${finalPdf.outputId}?format=file`, { + headers: { "Api-Key": apiKey }, + responseType: "arraybuffer", + }); + fs.writeFileSync(outputPath, download.data); + console.log(JSON.stringify(finalPdf, null, 2)); + console.log(`Created ${outputPath}`); +} + +main().catch((error) => { + console.error(error.response ? error.response.data : error.message); + process.exitCode = 1; +}); diff --git a/JavaScript/Endpoint Examples/JSON Payload/pdf-from-email.js b/JavaScript/Endpoint Examples/JSON Payload/pdf-from-email.js new file mode 100644 index 0000000..6c2bf43 --- /dev/null +++ b/JavaScript/Endpoint Examples/JSON Payload/pdf-from-email.js @@ -0,0 +1,27 @@ +var axios = require("axios"); +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"; + +// This sample converts an Email (.eml) file to PDF. It uploads the Email file +// first, then calls /pdf with its resource ID. +var inputPath = "/path/to/sample.eml"; +async function upload(path) { + var response = await axios.post(apiUrl + "/upload", fs.createReadStream(path), { headers: { "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "Content-Type": "application/octet-stream", "Content-Filename": path.split("/").pop() }, maxBodyLength: Infinity }); + return response.data.files[0].id; +} + +async function main() { + var inputId = await upload(inputPath); + var payload = { id: inputId, output: "pdf_from_email" }; + var response = await axios.post(apiUrl + "/pdf", payload, { headers: { "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "Content-Type": "application/json" } }); + console.log(JSON.stringify(response.data, null, 2)); +} + +main().catch((error) => { console.error(error.response ? error.response.data : error.message); process.exitCode = 1; }); diff --git a/JavaScript/Endpoint Examples/JSON Payload/pdf-from-postscript.js b/JavaScript/Endpoint Examples/JSON Payload/pdf-from-postscript.js new file mode 100644 index 0000000..b8dd439 --- /dev/null +++ b/JavaScript/Endpoint Examples/JSON Payload/pdf-from-postscript.js @@ -0,0 +1,36 @@ +var axios = require("axios"); +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"; + +/* This sample converts a PostScript (.ps) file 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. + * Pairing this /pdf call with /postscript creates a PDF -> PostScript -> PDF workflow + * commonly called PDF refrying. Some print and prepress workflows use it to rebuild or + * normalize page content, but the lossy roundtrip can discard PDF-specific features. + */ +var inputPath = "/path/to/sample.ps"; +var jobOptionsPath = "/path/to/custom.joboptions"; +async function upload(path) { + var response = await axios.post(apiUrl + "/upload", fs.createReadStream(path), { headers: { "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "Content-Type": "application/octet-stream", "Content-Filename": path.split("/").pop() }, maxBodyLength: Infinity }); + return response.data.files[0].id; +} + +async function main() { + var inputId = await upload(inputPath); + var jobOptionsId = await upload(jobOptionsPath); + var payload = { id: inputId, job_options_id: jobOptionsId, output: "pdf_from_postscript" }; + var response = await axios.post(apiUrl + "/pdf", payload, { headers: { "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "Content-Type": "application/json" } }); + console.log(JSON.stringify(response.data, null, 2)); +} + +main().catch((error) => { console.error(error.response ? error.response.data : error.message); process.exitCode = 1; }); diff --git a/JavaScript/Endpoint Examples/JSON Payload/postscript.js b/JavaScript/Endpoint Examples/JSON Payload/postscript.js new file mode 100644 index 0000000..ac6d868 --- /dev/null +++ b/JavaScript/Endpoint Examples/JSON Payload/postscript.js @@ -0,0 +1,32 @@ +var axios = require("axios"); +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"; + +/* This sample uploads a PDF, then converts it through the JSON /postscript flow. + * Pairing this endpoint with /pdf creates a PDF -> PostScript -> PDF workflow commonly + * called PDF refrying. Some print and prepress workflows use it to rebuild, flatten, or + * normalize page content, but the lossy roundtrip can discard PDF-specific features. + * These settings request Level 3, text-safe output, all pages at original scale, + * shrink-to-fit without rotation, and printable annotations. + */ +var inputPath = "/path/to/sample.pdf"; +async function upload(path) { + var response = await axios.post(apiUrl + "/upload", fs.createReadStream(path), { headers: { "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "Content-Type": "application/octet-stream", "Content-Filename": path.split("/").pop() }, maxBodyLength: Infinity }); + return response.data.files[0].id; +} + +async function main() { + var inputId = await upload(inputPath); + var payload = { 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" }; + var response = await axios.post(apiUrl + "/postscript", payload, { headers: { "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "Content-Type": "application/json" } }); + console.log(JSON.stringify(response.data, null, 2)); +} + +main().catch((error) => { console.error(error.response ? error.response.data : error.message); process.exitCode = 1; }); diff --git a/JavaScript/Endpoint Examples/Multipart Payload/pdf-from-email.js b/JavaScript/Endpoint Examples/Multipart Payload/pdf-from-email.js new file mode 100644 index 0000000..84eb77f --- /dev/null +++ b/JavaScript/Endpoint Examples/Multipart Payload/pdf-from-email.js @@ -0,0 +1,22 @@ +var axios = require("axios"); +var fs = require("fs"); +var FormData = require("form-data"); + +// 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"; + +// This sample converts an Email (.eml) file to PDF by sending it directly in a +// multipart /pdf request. +var inputPath = "/path/to/sample.eml"; +var form = new FormData(); +form.append("file", fs.createReadStream(inputPath), { contentType: "message/rfc822" }); +form.append("output", "pdf_from_email"); + +axios.post(apiUrl + "/pdf", form, { headers: { "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", ...form.getHeaders() }, maxBodyLength: Infinity }) +.then((response) => { console.log(JSON.stringify(response.data, null, 2)); }) +.catch((error) => { console.error(error.response ? error.response.data : error.message); process.exitCode = 1; }); diff --git a/JavaScript/Endpoint Examples/Multipart Payload/pdf-from-postscript.js b/JavaScript/Endpoint Examples/Multipart Payload/pdf-from-postscript.js new file mode 100644 index 0000000..ee470b1 --- /dev/null +++ b/JavaScript/Endpoint Examples/Multipart Payload/pdf-from-postscript.js @@ -0,0 +1,31 @@ +var axios = require("axios"); +var fs = require("fs"); +var FormData = require("form-data"); + +// 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"; + +/* This sample converts a PostScript (.ps) file 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. + * Pairing this /pdf call with /postscript creates a PDF -> PostScript -> PDF workflow + * commonly called PDF refrying. Some print and prepress workflows use it to rebuild or + * normalize page content, but the lossy roundtrip can discard PDF-specific features. + */ +var inputPath = "/path/to/sample.ps"; +var jobOptionsPath = "/path/to/custom.joboptions"; +var form = new FormData(); +form.append("file", fs.createReadStream(inputPath), { contentType: "application/postscript" }); +form.append("job_options", fs.createReadStream(jobOptionsPath), { contentType: "application/octet-stream" }); +form.append("output", "pdf_from_postscript"); + +axios.post(apiUrl + "/pdf", form, { headers: { "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", ...form.getHeaders() }, maxBodyLength: Infinity }) +.then((response) => { console.log(JSON.stringify(response.data, null, 2)); }) +.catch((error) => { console.error(error.response ? error.response.data : error.message); process.exitCode = 1; }); diff --git a/JavaScript/Endpoint Examples/Multipart Payload/postscript.js b/JavaScript/Endpoint Examples/Multipart Payload/postscript.js new file mode 100644 index 0000000..abda8c8 --- /dev/null +++ b/JavaScript/Endpoint Examples/Multipart Payload/postscript.js @@ -0,0 +1,34 @@ +var axios = require("axios"); +var fs = require("fs"); +var FormData = require("form-data"); + +// 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"; + +/* This sample converts PDF to PostScript through multipart /postscript. + * Pairing this endpoint with /pdf creates a PDF -> PostScript -> PDF workflow commonly + * called PDF refrying. Some print and prepress workflows use it to rebuild, flatten, or + * normalize page content, but the lossy roundtrip can discard PDF-specific features. + * These settings request Level 3, text-safe output, all pages at original scale, + * shrink-to-fit without rotation, and printable annotations. + */ +var inputPath = "/path/to/sample.pdf"; +var form = new FormData(); +form.append("file", fs.createReadStream(inputPath), { contentType: "application/pdf" }); +form.append("ps_level", "3"); +form.append("page_range", "all"); +form.append("binary_output", "false"); +form.append("scale", "1"); +form.append("rotate", "false"); +form.append("shrink_to_fit", "true"); +form.append("print_annotations", "true"); +form.append("output", "postscript_from_pdf"); + +axios.post(apiUrl + "/postscript", form, { headers: { "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", ...form.getHeaders() }, maxBodyLength: Infinity }) +.then((response) => { console.log(JSON.stringify(response.data, null, 2)); }) +.catch((error) => { console.error(error.response ? error.response.data : error.message); process.exitCode = 1; }); diff --git a/PHP/Complex Flow Examples/refry-pdf.php b/PHP/Complex Flow Examples/refry-pdf.php new file mode 100644 index 0000000..51b9c68 --- /dev/null +++ b/PHP/Complex Flow Examples/refry-pdf.php @@ -0,0 +1,65 @@ + PostScript -> PDF roundtrip. + * Some print, prepress, and legacy production workflows use it to rebuild or + * normalize page content, flatten certain PDF constructs, or prepare a file + * for downstream systems. The process is intentionally lossy and may remove + * tags, forms, layers, annotations, transparency, metadata, and editability. + * Use this workflow when a downstream system requires rebuilt page content or + * a PostScript-based interchange file. + * + * 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. + * + * Run: php refry-pdf.php [outputPdf] + */ + +require 'vendor/autoload.php'; + +use GuzzleHttp\Client; +use GuzzleHttp\Psr7\Utils; + +$apiUrl = rtrim(getenv('PDFREST_URL') ?: 'https://api.pdfrest.com', '/'); +$apiKey = getenv('PDFREST_API_KEY') ?: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'; +$inputPath = $argv[1] ?? '/path/to/sample.pdf'; +$jobOptionsPath = $argv[2] ?? '/path/to/custom.joboptions'; +$outputPath = $argv[3] ?? __DIR__ . '/refried.pdf'; +$client = new Client(['http_errors' => true]); + +function postMultipart(Client $client, string $url, string $apiKey, array $parts): array +{ + $response = $client->post($url, [ + 'headers' => ['Accept' => 'application/json', 'Api-Key' => $apiKey], + 'multipart' => $parts, + ]); + echo basename($url) . ': ' . $response->getStatusCode() . PHP_EOL; + return json_decode($response->getBody(), true, 512, JSON_THROW_ON_ERROR); +} + +$postscript = postMultipart($client, $apiUrl . '/postscript', $apiKey, [ + ['name' => 'file', 'contents' => Utils::tryFopen($inputPath, 'r'), 'filename' => basename($inputPath), 'headers' => ['Content-Type' => 'application/pdf']], + ['name' => 'ps_level', 'contents' => '3'], + ['name' => 'page_range', 'contents' => 'all'], + ['name' => 'binary_output', 'contents' => 'true'], + ['name' => 'scale', 'contents' => '1'], + ['name' => 'rotate', 'contents' => 'false'], + ['name' => 'shrink_to_fit', 'contents' => 'true'], + ['name' => 'print_annotations', 'contents' => 'true'], + ['name' => 'output', 'contents' => 'refry_intermediate'], +]); + +$finalPdf = postMultipart($client, $apiUrl . '/pdf', $apiKey, [ + ['name' => 'id', 'contents' => $postscript['outputId']], + ['name' => 'job_options', 'contents' => Utils::tryFopen($jobOptionsPath, 'r'), 'filename' => basename($jobOptionsPath), 'headers' => ['Content-Type' => 'application/octet-stream']], + ['name' => 'output', 'contents' => 'refried'], +]); + +$download = $client->get($apiUrl . '/resource/' . rawurlencode($finalPdf['outputId']) . '?format=file', ['headers' => ['Api-Key' => $apiKey]]); +file_put_contents($outputPath, $download->getBody()->getContents()); +echo json_encode($finalPdf, JSON_PRETTY_PRINT) . PHP_EOL; +echo "Created $outputPath" . PHP_EOL; diff --git a/PHP/Endpoint Examples/JSON Payload/pdf-from-email.php b/PHP/Endpoint Examples/JSON Payload/pdf-from-email.php new file mode 100644 index 0000000..5cc49e8 --- /dev/null +++ b/PHP/Endpoint Examples/JSON Payload/pdf-from-email.php @@ -0,0 +1,27 @@ + false]); +$upload = function (string $path) use ($client, $apiUrl): string { + $response = $client->post($apiUrl . '/upload', ['headers' => ['Api-Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', 'Content-Type' => 'application/octet-stream', 'Content-Filename' => basename($path)], 'body' => Utils::tryFopen($path, 'r')]); + $body = json_decode((string) $response->getBody(), true); + return $body['files'][0]['id']; +}; +$inputId = $upload($inputPath); +$payload = ['id' => $inputId, 'output' => 'pdf_from_email']; +$response = $client->post($apiUrl . '/pdf', ['headers' => ['Api-Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', 'Content-Type' => 'application/json', 'Accept' => 'application/json'], 'json' => $payload]); +echo $response->getBody(); diff --git a/PHP/Endpoint Examples/JSON Payload/pdf-from-postscript.php b/PHP/Endpoint Examples/JSON Payload/pdf-from-postscript.php new file mode 100644 index 0000000..af2853f --- /dev/null +++ b/PHP/Endpoint Examples/JSON Payload/pdf-from-postscript.php @@ -0,0 +1,36 @@ + PostScript -> PDF workflow + * commonly called PDF refrying. Some print and prepress workflows use it to rebuild or + * normalize page content, but the lossy roundtrip can discard PDF-specific features. + */ +$inputPath = '/path/to/sample.ps'; +$jobOptionsPath = '/path/to/custom.joboptions'; +$client = new Client(['http_errors' => false]); +$upload = function (string $path) use ($client, $apiUrl): string { + $response = $client->post($apiUrl . '/upload', ['headers' => ['Api-Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', 'Content-Type' => 'application/octet-stream', 'Content-Filename' => basename($path)], 'body' => Utils::tryFopen($path, 'r')]); + $body = json_decode((string) $response->getBody(), true); + return $body['files'][0]['id']; +}; +$inputId = $upload($inputPath); +$jobOptionsId = $upload($jobOptionsPath); +$payload = ['id' => $inputId, 'job_options_id' => $jobOptionsId, 'output' => 'pdf_from_postscript']; +$response = $client->post($apiUrl . '/pdf', ['headers' => ['Api-Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', 'Content-Type' => 'application/json', 'Accept' => 'application/json'], 'json' => $payload]); +echo $response->getBody(); diff --git a/PHP/Endpoint Examples/JSON Payload/postscript.php b/PHP/Endpoint Examples/JSON Payload/postscript.php new file mode 100644 index 0000000..04fe224 --- /dev/null +++ b/PHP/Endpoint Examples/JSON Payload/postscript.php @@ -0,0 +1,42 @@ + PostScript -> PDF workflow commonly + * called PDF refrying. Some print and prepress workflows use it to rebuild, flatten, or + * normalize page content, but the lossy roundtrip can discard PDF-specific features. + * These settings request Level 3, text-safe output, all pages at original scale, + * shrink-to-fit without rotation, and printable annotations. + */ +$inputPath = '/path/to/sample.pdf'; +$client = new Client(['http_errors' => false]); +$upload = function (string $path) use ($client, $apiUrl): string { + $response = $client->post($apiUrl . '/upload', ['headers' => ['Api-Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', 'Content-Type' => 'application/octet-stream', 'Content-Filename' => basename($path)], 'body' => Utils::tryFopen($path, 'r')]); + $body = json_decode((string) $response->getBody(), true); + return $body['files'][0]['id']; +}; +$inputId = $upload($inputPath); +$payload = [ + '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', +]; +$response = $client->post($apiUrl . '/postscript', ['headers' => ['Api-Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', 'Content-Type' => 'application/json', 'Accept' => 'application/json'], 'json' => $payload]); +echo $response->getBody(); diff --git a/PHP/Endpoint Examples/Multipart Payload/pdf-from-email.php b/PHP/Endpoint Examples/Multipart Payload/pdf-from-email.php new file mode 100644 index 0000000..c8b7945 --- /dev/null +++ b/PHP/Endpoint Examples/Multipart Payload/pdf-from-email.php @@ -0,0 +1,23 @@ + 'file', 'contents' => Utils::tryFopen($inputPath, 'r'), 'filename' => basename($inputPath), 'headers' => ['Content-Type' => 'message/rfc822']], + ['name' => 'output', 'contents' => 'pdf_from_email'], +]; +$response = (new Client())->post($apiUrl . '/pdf', ['headers' => ['Api-Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', 'Accept' => 'application/json'], 'multipart' => $multipart]); +echo $response->getBody(); diff --git a/PHP/Endpoint Examples/Multipart Payload/pdf-from-postscript.php b/PHP/Endpoint Examples/Multipart Payload/pdf-from-postscript.php new file mode 100644 index 0000000..3a3f8c9 --- /dev/null +++ b/PHP/Endpoint Examples/Multipart Payload/pdf-from-postscript.php @@ -0,0 +1,32 @@ + PostScript -> PDF workflow + * commonly called PDF refrying. Some print and prepress workflows use it to rebuild or + * normalize page content, but the lossy roundtrip can discard PDF-specific features. + */ +$inputPath = '/path/to/sample.ps'; +$jobOptionsPath = '/path/to/custom.joboptions'; +$multipart = [ + ['name' => 'file', 'contents' => Utils::tryFopen($inputPath, 'r'), 'filename' => basename($inputPath), 'headers' => ['Content-Type' => 'application/postscript']], + ['name' => 'job_options', 'contents' => Utils::tryFopen($jobOptionsPath, 'r'), 'filename' => basename($jobOptionsPath), 'headers' => ['Content-Type' => 'application/octet-stream']], + ['name' => 'output', 'contents' => 'pdf_from_postscript'], +]; +$response = (new Client())->post($apiUrl . '/pdf', ['headers' => ['Api-Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', 'Accept' => 'application/json'], 'multipart' => $multipart]); +echo $response->getBody(); diff --git a/PHP/Endpoint Examples/Multipart Payload/postscript.php b/PHP/Endpoint Examples/Multipart Payload/postscript.php new file mode 100644 index 0000000..153d064 --- /dev/null +++ b/PHP/Endpoint Examples/Multipart Payload/postscript.php @@ -0,0 +1,35 @@ + PostScript -> PDF workflow commonly + * called PDF refrying. Some print and prepress workflows use it to rebuild, flatten, or + * normalize page content, but the lossy roundtrip can discard PDF-specific features. + * These settings request Level 3, text-safe output, all pages at original scale, + * shrink-to-fit without rotation, and printable annotations. + */ +$inputPath = '/path/to/sample.pdf'; +$multipart = [ + ['name' => 'file', 'contents' => Utils::tryFopen($inputPath, 'r'), 'filename' => basename($inputPath), 'headers' => ['Content-Type' => 'application/pdf']], + ['name' => 'ps_level', 'contents' => '3'], + ['name' => 'page_range', 'contents' => 'all'], + ['name' => 'binary_output', 'contents' => 'false'], + ['name' => 'scale', 'contents' => '1'], + ['name' => 'rotate', 'contents' => 'false'], + ['name' => 'shrink_to_fit', 'contents' => 'true'], + ['name' => 'print_annotations', 'contents' => 'true'], + ['name' => 'output', 'contents' => 'postscript_from_pdf'], +]; +$response = (new Client())->post($apiUrl . '/postscript', ['headers' => ['Api-Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', 'Accept' => 'application/json'], 'multipart' => $multipart]); +echo $response->getBody(); diff --git a/Python/Complex Flow Examples/refry-pdf.py b/Python/Complex Flow Examples/refry-pdf.py new file mode 100644 index 0000000..ce86b4b --- /dev/null +++ b/Python/Complex Flow Examples/refry-pdf.py @@ -0,0 +1,97 @@ +"""Refry a PDF by converting it to PostScript and back to PDF. + +PDF refrying is the common name for a PDF -> PostScript -> PDF roundtrip. +Some print, prepress, and legacy production workflows use it to rebuild or +normalize page content, flatten certain PDF constructs, or prepare a file for +downstream systems. The process is intentionally lossy and may remove tags, +forms, layers, annotations, transparency, metadata, and editability. Use this +workflow when a downstream system requires rebuilt page content or a +PostScript-based interchange file. + +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. + +Run: python3 refry-pdf.py [outputPdf] +""" + +import json +import os +import sys +from pathlib import Path + +import requests +from requests_toolbelt import MultipartEncoder + + +API_URL = os.getenv("PDFREST_URL", "https://api.pdfrest.com").rstrip("/") +API_KEY = os.getenv("PDFREST_API_KEY", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx") +INPUT_PATH = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("/path/to/sample.pdf") +JOB_OPTIONS_PATH = ( + Path(sys.argv[2]) if len(sys.argv) > 2 else Path("/path/to/custom.joboptions") +) +OUTPUT_PATH = Path(__file__).with_name("refried.pdf") +if len(sys.argv) > 3: + OUTPUT_PATH = Path(sys.argv[3]) + + +def post_multipart(endpoint, fields): + """Send a multipart request and return its JSON response.""" + form = MultipartEncoder(fields=fields) + response = requests.post( + f"{API_URL}/{endpoint}", + data=form, + headers={ + "Accept": "application/json", + "Content-Type": form.content_type, + "Api-Key": API_KEY, + }, + timeout=120, + ) + print(f"{endpoint}: {response.status_code}") + if not response.ok: + raise RuntimeError(f"{endpoint} failed: {response.text}") + return response.json() + + +with INPUT_PATH.open("rb") as input_file: + postscript = post_multipart( + "postscript", + { + "file": (INPUT_PATH.name, input_file, "application/pdf"), + "ps_level": "3", + "page_range": "all", + "binary_output": "true", + "scale": "1", + "rotate": "false", + "shrink_to_fit": "true", + "print_annotations": "true", + "output": "refry_intermediate", + }, + ) + +with JOB_OPTIONS_PATH.open("rb") as job_options_file: + final_pdf = post_multipart( + "pdf", + { + "id": postscript["outputId"], + "job_options": ( + JOB_OPTIONS_PATH.name, + job_options_file, + "application/octet-stream", + ), + "output": "refried", + }, + ) + +download = requests.get( + f"{API_URL}/resource/{final_pdf['outputId']}?format=file", + headers={"Api-Key": API_KEY}, + timeout=120, +) +download.raise_for_status() +OUTPUT_PATH.write_bytes(download.content) +print(json.dumps(final_pdf, indent=2)) +print(f"Created {OUTPUT_PATH}") diff --git a/Python/Endpoint Examples/JSON Payload/pdf-from-email.py b/Python/Endpoint Examples/JSON Payload/pdf-from-email.py new file mode 100644 index 0000000..2dba5ce --- /dev/null +++ b/Python/Endpoint Examples/JSON Payload/pdf-from-email.py @@ -0,0 +1,44 @@ +import json +import os +import requests + +# 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 sample converts an Email (.eml) file to PDF. It uploads the Email file +# first, then calls /pdf with its resource ID. +input_path = "/path/to/sample.eml" + +def upload(path): + with open(path, "rb") as source: + response = requests.post(api_url + "/upload", data=source, headers={ + "Content-Type": "application/octet-stream", + "Content-Filename": os.path.basename(path), + "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", + }) + if not response.ok: + print(response.text) + raise SystemExit(1) + return response.json()["files"][0]["id"] + +input_id = upload(input_path) +payload = { + "id": input_id, + "output": "pdf_from_email", +} +response = requests.post(api_url + "/pdf", json=payload, headers={ + "Accept": "application/json", + "Content-Type": "application/json", + "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", +}) + +print("Response status code: " + str(response.status_code)) +if response.ok: + print(json.dumps(response.json(), indent=2)) +else: + print(response.text) + raise SystemExit(1) diff --git a/Python/Endpoint Examples/JSON Payload/pdf-from-postscript.py b/Python/Endpoint Examples/JSON Payload/pdf-from-postscript.py new file mode 100644 index 0000000..184a942 --- /dev/null +++ b/Python/Endpoint Examples/JSON Payload/pdf-from-postscript.py @@ -0,0 +1,53 @@ +import json +import os +import requests + +# 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 sample converts a PostScript (.ps) file 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. +# Pairing this /pdf call with /postscript creates a PDF -> PostScript -> PDF workflow +# commonly called PDF refrying. Some print and prepress workflows use it to rebuild or +# normalize page content, but the lossy roundtrip can discard PDF-specific features. +input_path = "/path/to/sample.ps" +job_options_path = "/path/to/custom.joboptions" + +def upload(path): + with open(path, "rb") as source: + response = requests.post(api_url + "/upload", data=source, headers={ + "Content-Type": "application/octet-stream", + "Content-Filename": os.path.basename(path), + "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", + }) + if not response.ok: + print(response.text) + raise SystemExit(1) + return response.json()["files"][0]["id"] + +input_id = upload(input_path) +job_options_id = upload(job_options_path) +payload = { + "id": input_id, + "job_options_id": job_options_id, + "output": "pdf_from_postscript", +} +response = requests.post(api_url + "/pdf", json=payload, headers={ + "Accept": "application/json", + "Content-Type": "application/json", + "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", +}) + +print("Response status code: " + str(response.status_code)) +if response.ok: + print(json.dumps(response.json(), indent=2)) +else: + print(response.text) + raise SystemExit(1) diff --git a/Python/Endpoint Examples/JSON Payload/postscript.py b/Python/Endpoint Examples/JSON Payload/postscript.py new file mode 100644 index 0000000..1e2668f --- /dev/null +++ b/Python/Endpoint Examples/JSON Payload/postscript.py @@ -0,0 +1,55 @@ +import json +import os +import requests + +# 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 sample uploads a PDF, then converts it through the JSON /postscript flow. +# Pairing this endpoint with /pdf creates a PDF -> PostScript -> PDF workflow commonly +# called PDF refrying. Some print and prepress workflows use it to rebuild, flatten, or +# normalize page content, but the lossy roundtrip can discard PDF-specific features. +# These settings request Level 3, text-safe output, all pages at original scale, +# shrink-to-fit without rotation, and printable annotations. +input_path = "/path/to/sample.pdf" + +def upload(path): + with open(path, "rb") as source: + response = requests.post(api_url + "/upload", data=source, headers={ + "Content-Type": "application/octet-stream", + "Content-Filename": os.path.basename(path), + "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", + }) + if not response.ok: + print(response.text) + raise SystemExit(1) + return response.json()["files"][0]["id"] + +input_id = upload(input_path) +payload = { + "id": input_id, + "ps_level": 3, + "page_range": "all", + "binary_output": False, + "scale": 1, + "rotate": False, + "shrink_to_fit": True, + "print_annotations": True, + "output": "postscript_from_pdf", +} +response = requests.post(api_url + "/postscript", json=payload, headers={ + "Accept": "application/json", + "Content-Type": "application/json", + "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", +}) + +print("Response status code: " + str(response.status_code)) +if response.ok: + print(json.dumps(response.json(), indent=2)) +else: + print(response.text) + raise SystemExit(1) diff --git a/Python/Endpoint Examples/Multipart Payload/pdf-from-email.py b/Python/Endpoint Examples/Multipart Payload/pdf-from-email.py new file mode 100644 index 0000000..697f122 --- /dev/null +++ b/Python/Endpoint Examples/Multipart Payload/pdf-from-email.py @@ -0,0 +1,34 @@ +import json +import os +import requests + +# 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 sample converts an Email (.eml) file to PDF by sending it directly in a +# multipart /pdf request. +input_path = "/path/to/sample.eml" + +from requests_toolbelt import MultipartEncoder +with open(input_path, "rb") as input_file: + fields = { + "file": (os.path.basename(input_path), input_file, "message/rfc822"), + "output": "pdf_from_email", + } + form = MultipartEncoder(fields=fields) + response = requests.post(api_url + "/pdf", data=form, headers={ + "Accept": "application/json", + "Content-Type": form.content_type, + "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", + }) + +print("Response status code: " + str(response.status_code)) +if response.ok: + print(json.dumps(response.json(), indent=2)) +else: + print(response.text) + raise SystemExit(1) diff --git a/Python/Endpoint Examples/Multipart Payload/pdf-from-postscript.py b/Python/Endpoint Examples/Multipart Payload/pdf-from-postscript.py new file mode 100644 index 0000000..98658e6 --- /dev/null +++ b/Python/Endpoint Examples/Multipart Payload/pdf-from-postscript.py @@ -0,0 +1,46 @@ +import json +import os +import requests + +# 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 sample converts a PostScript (.ps) file 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. +# Pairing this /pdf call with /postscript creates a PDF -> PostScript -> PDF workflow +# commonly called PDF refrying. Some print and prepress workflows use it to rebuild or +# normalize page content, but the lossy roundtrip can discard PDF-specific features. +input_path = "/path/to/sample.ps" +job_options_path = "/path/to/custom.joboptions" + +from requests_toolbelt import MultipartEncoder +with open(input_path, "rb") as input_file, open(job_options_path, "rb") as job_options_file: + fields = { + "file": (os.path.basename(input_path), input_file, "application/postscript"), + "job_options": ( + os.path.basename(job_options_path), + job_options_file, + "application/octet-stream", + ), + "output": "pdf_from_postscript", + } + form = MultipartEncoder(fields=fields) + response = requests.post(api_url + "/pdf", data=form, headers={ + "Accept": "application/json", + "Content-Type": form.content_type, + "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", + }) + +print("Response status code: " + str(response.status_code)) +if response.ok: + print(json.dumps(response.json(), indent=2)) +else: + print(response.text) + raise SystemExit(1) diff --git a/Python/Endpoint Examples/Multipart Payload/postscript.py b/Python/Endpoint Examples/Multipart Payload/postscript.py new file mode 100644 index 0000000..3051970 --- /dev/null +++ b/Python/Endpoint Examples/Multipart Payload/postscript.py @@ -0,0 +1,45 @@ +import json +import os +import requests + +# 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 sample converts PDF to PostScript through multipart /postscript. +# Pairing this endpoint with /pdf creates a PDF -> PostScript -> PDF workflow commonly +# called PDF refrying. Some print and prepress workflows use it to rebuild, flatten, or +# normalize page content, but the lossy roundtrip can discard PDF-specific features. +# These settings request Level 3, text-safe output, all pages at original scale, +# shrink-to-fit without rotation, and printable annotations. +input_path = "/path/to/sample.pdf" + +from requests_toolbelt import MultipartEncoder +with open(input_path, "rb") as input_file: + fields = { + "file": (os.path.basename(input_path), input_file, "application/pdf"), + "ps_level": "3", + "page_range": "all", + "binary_output": "false", + "scale": "1", + "rotate": "false", + "shrink_to_fit": "true", + "print_annotations": "true", + "output": "postscript_from_pdf", + } + form = MultipartEncoder(fields=fields) + response = requests.post(api_url + "/postscript", data=form, headers={ + "Accept": "application/json", + "Content-Type": form.content_type, + "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", + }) + +print("Response status code: " + str(response.status_code)) +if response.ok: + print(json.dumps(response.json(), indent=2)) +else: + print(response.text) + raise SystemExit(1) diff --git a/cURL/Complex Flow Examples/refry-pdf.sh b/cURL/Complex Flow Examples/refry-pdf.sh new file mode 100644 index 0000000..68c617d --- /dev/null +++ b/cURL/Complex Flow Examples/refry-pdf.sh @@ -0,0 +1,60 @@ +#!/bin/sh + +# Refry a PDF by converting it to PostScript and back to PDF. +# +# PDF refrying is the common name for a PDF -> PostScript -> PDF roundtrip. +# Some print, prepress, and legacy production workflows use it to rebuild or +# normalize page content, flatten certain PDF constructs, or prepare a file +# for downstream systems. The process is intentionally lossy and may remove +# tags, forms, layers, annotations, transparency, metadata, and editability. +# Use this workflow when a downstream system requires rebuilt page content or +# a PostScript-based interchange file. +# +# 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. +# +# Run: sh refry-pdf.sh [outputPdf] + +set -eu + +SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +API_URL="${PDFREST_URL:-https://api.pdfrest.com}" +API_KEY="${PDFREST_API_KEY:-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}" +INPUT_PATH="${1:-/path/to/sample.pdf}" +JOB_OPTIONS_PATH="${2:-/path/to/custom.joboptions}" +OUTPUT_PATH="${3:-$SCRIPT_DIR/refried.pdf}" + +POSTSCRIPT_RESPONSE=$(curl --fail-with-body --silent --show-error --location "$API_URL/postscript" \ + --header 'Accept: application/json' \ + --header 'Content-Type: multipart/form-data' \ + --header "Api-Key: $API_KEY" \ + --form "file=@$INPUT_PATH;type=application/pdf" \ + --form 'ps_level=3' \ + --form 'page_range=all' \ + --form 'binary_output=true' \ + --form 'scale=1' \ + --form 'rotate=false' \ + --form 'shrink_to_fit=true' \ + --form 'print_annotations=true' \ + --form 'output=refry_intermediate') +POSTSCRIPT_ID=$(printf '%s' "$POSTSCRIPT_RESPONSE" | jq -r '.outputId') + +FINAL_RESPONSE=$(curl --fail-with-body --silent --show-error --location "$API_URL/pdf" \ + --header 'Accept: application/json' \ + --header 'Content-Type: multipart/form-data' \ + --header "Api-Key: $API_KEY" \ + --form "id=$POSTSCRIPT_ID" \ + --form "job_options=@$JOB_OPTIONS_PATH;type=application/octet-stream" \ + --form 'output=refried') +FINAL_ID=$(printf '%s' "$FINAL_RESPONSE" | jq -r '.outputId') + +curl --fail-with-body --silent --show-error --location \ + "$API_URL/resource/$FINAL_ID?format=file" \ + --header "Api-Key: $API_KEY" \ + --output "$OUTPUT_PATH" +printf '%s\n' "$FINAL_RESPONSE" | jq . +echo "Created $OUTPUT_PATH" diff --git a/cURL/Endpoint Examples/JSON Payload/pdf-from-email.sh b/cURL/Endpoint Examples/JSON Payload/pdf-from-email.sh new file mode 100644 index 0000000..301337f --- /dev/null +++ b/cURL/Endpoint Examples/JSON Payload/pdf-from-email.sh @@ -0,0 +1,26 @@ +#!/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 sample converts an Email (.eml) file to PDF. It uploads the Email file +# first, then calls /pdf with its resource ID. +INPUT_PATH="/path/to/sample.eml" + +INPUT_ID=$(curl --silent --show-error --location "$API_URL/upload" \ + --header "Api-Key: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" \ + --header "Content-Filename: $(basename "$INPUT_PATH")" \ + --header "Content-Type: application/octet-stream" \ + --data-binary "@$INPUT_PATH" | jq -r ".files[0].id") +if [ -z "$INPUT_ID" ] || [ "$INPUT_ID" = "null" ]; then echo "Input upload failed" >&2; exit 1; fi +PAYLOAD=$(jq -n --arg id "$INPUT_ID" \ + '{"id": $id, "output": "pdf_from_email"}') +curl --location "$API_URL/pdf" \ + --header "Accept: application/json" \ + --header "Content-Type: application/json" \ + --header "Api-Key: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" \ + --data "$PAYLOAD" diff --git a/cURL/Endpoint Examples/JSON Payload/pdf-from-postscript.sh b/cURL/Endpoint Examples/JSON Payload/pdf-from-postscript.sh new file mode 100644 index 0000000..dbada4d --- /dev/null +++ b/cURL/Endpoint Examples/JSON Payload/pdf-from-postscript.sh @@ -0,0 +1,39 @@ +#!/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 sample converts a PostScript (.ps) file 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. +# Pairing this /pdf call with /postscript creates a PDF -> PostScript -> PDF workflow +# commonly called PDF refrying. Some print and prepress workflows use it to rebuild or +# normalize page content, but the lossy roundtrip can discard PDF-specific features. +INPUT_PATH="/path/to/sample.ps" +JOB_OPTIONS_PATH="/path/to/custom.joboptions" + +INPUT_ID=$(curl --silent --show-error --location "$API_URL/upload" \ + --header "Api-Key: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" \ + --header "Content-Filename: $(basename "$INPUT_PATH")" \ + --header "Content-Type: application/octet-stream" \ + --data-binary "@$INPUT_PATH" | jq -r ".files[0].id") +if [ -z "$INPUT_ID" ] || [ "$INPUT_ID" = "null" ]; then echo "PostScript upload failed" >&2; exit 1; fi +JOB_OPTIONS_ID=$(curl --silent --show-error --location "$API_URL/upload" \ + --header "Api-Key: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" \ + --header "Content-Filename: $(basename "$JOB_OPTIONS_PATH")" \ + --header "Content-Type: application/octet-stream" \ + --data-binary "@$JOB_OPTIONS_PATH" | jq -r ".files[0].id") +if [ -z "$JOB_OPTIONS_ID" ] || [ "$JOB_OPTIONS_ID" = "null" ]; then echo "Job options upload failed" >&2; exit 1; fi +PAYLOAD=$(jq -n --arg id "$INPUT_ID" --arg job_options_id "$JOB_OPTIONS_ID" \ + '{"id": $id, "job_options_id": $job_options_id, "output": "pdf_from_postscript"}') +curl --location "$API_URL/pdf" \ + --header "Accept: application/json" \ + --header "Content-Type: application/json" \ + --header "Api-Key: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" \ + --data "$PAYLOAD" diff --git a/cURL/Endpoint Examples/JSON Payload/postscript.sh b/cURL/Endpoint Examples/JSON Payload/postscript.sh new file mode 100644 index 0000000..1b924a4 --- /dev/null +++ b/cURL/Endpoint Examples/JSON Payload/postscript.sh @@ -0,0 +1,32 @@ +#!/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 sample uploads a PDF, then converts it through the JSON /postscript flow. +# Pairing this endpoint with /pdf creates a PDF -> PostScript -> PDF workflow commonly +# called PDF refrying. Some print and prepress workflows use it to rebuild, flatten, or +# normalize page content, but the lossy roundtrip can discard PDF-specific features. +# These settings request Level 3, text-safe output, all pages at original scale, +# shrink-to-fit without rotation, and printable annotations. +INPUT_PATH="/path/to/sample.pdf" + +INPUT_ID=$(curl --silent --show-error --location "$API_URL/upload" \ + --header "Api-Key: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" \ + --header "Content-Filename: $(basename "$INPUT_PATH")" \ + --header "Content-Type: application/octet-stream" \ + --data-binary "@$INPUT_PATH" | jq -r ".files[0].id") +if [ -z "$INPUT_ID" ] || [ "$INPUT_ID" = "null" ]; then echo "PDF upload failed" >&2; exit 1; fi +PAYLOAD=$(jq -n --arg id "$INPUT_ID" \ + '{"id": $id, "ps_level": 3, "page_range": "all", "binary_output": false, + "scale": 1, "rotate": false, "shrink_to_fit": true, + "print_annotations": true, "output": "postscript_from_pdf"}') +curl --location "$API_URL/postscript" \ + --header "Accept: application/json" \ + --header "Content-Type: application/json" \ + --header "Api-Key: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" \ + --data "$PAYLOAD" diff --git a/cURL/Endpoint Examples/Multipart Payload/pdf-from-email.sh b/cURL/Endpoint Examples/Multipart Payload/pdf-from-email.sh new file mode 100644 index 0000000..3a7121b --- /dev/null +++ b/cURL/Endpoint Examples/Multipart Payload/pdf-from-email.sh @@ -0,0 +1,19 @@ +#!/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 sample converts an Email (.eml) file to PDF by sending it directly in a +# multipart /pdf request. +INPUT_PATH="/path/to/sample.eml" + +curl --location "$API_URL/pdf" \ + --header "Accept: application/json" \ + --header "Content-Type: multipart/form-data" \ + --header "Api-Key: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" \ + --form "file=@$INPUT_PATH;type=message/rfc822" \ + --form "output=pdf_from_email" diff --git a/cURL/Endpoint Examples/Multipart Payload/pdf-from-postscript.sh b/cURL/Endpoint Examples/Multipart Payload/pdf-from-postscript.sh new file mode 100644 index 0000000..b2c0efc --- /dev/null +++ b/cURL/Endpoint Examples/Multipart Payload/pdf-from-postscript.sh @@ -0,0 +1,27 @@ +#!/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 sample converts a PostScript (.ps) file 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. +# Pairing this /pdf call with /postscript creates a PDF -> PostScript -> PDF workflow +# commonly called PDF refrying. Some print and prepress workflows use it to rebuild or +# normalize page content, but the lossy roundtrip can discard PDF-specific features. +INPUT_PATH="/path/to/sample.ps" +JOB_OPTIONS_PATH="/path/to/custom.joboptions" + +curl --location "$API_URL/pdf" \ + --header "Accept: application/json" \ + --header "Content-Type: multipart/form-data" \ + --header "Api-Key: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" \ + --form "file=@$INPUT_PATH;type=application/postscript" \ + --form "job_options=@$JOB_OPTIONS_PATH;type=application/octet-stream" \ + --form "output=pdf_from_postscript" diff --git a/cURL/Endpoint Examples/Multipart Payload/postscript.sh b/cURL/Endpoint Examples/Multipart Payload/postscript.sh new file mode 100644 index 0000000..1d97107 --- /dev/null +++ b/cURL/Endpoint Examples/Multipart Payload/postscript.sh @@ -0,0 +1,30 @@ +#!/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 sample converts PDF to PostScript through multipart /postscript. +# Pairing this endpoint with /pdf creates a PDF -> PostScript -> PDF workflow commonly +# called PDF refrying. Some print and prepress workflows use it to rebuild, flatten, or +# normalize page content, but the lossy roundtrip can discard PDF-specific features. +# These settings request Level 3, text-safe output, all pages at original scale, +# shrink-to-fit without rotation, and printable annotations. +INPUT_PATH="/path/to/sample.pdf" + +curl --location "$API_URL/postscript" \ + --header "Accept: application/json" \ + --header "Content-Type: multipart/form-data" \ + --header "Api-Key: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" \ + --form "file=@$INPUT_PATH;type=application/pdf" \ + --form "ps_level=3" \ + --form "page_range=all" \ + --form "binary_output=false" \ + --form "scale=1" \ + --form "rotate=false" \ + --form "shrink_to_fit=true" \ + --form "print_annotations=true" \ + --form "output=postscript_from_pdf"