Skip to content

Commit 9671577

Browse files
Standardize C# examples with environment variables and enhanced error handling
- Added headers to new examples, documenting purpose, setup, usage, and output. - Replaced hardcoded file paths, API keys, and URLs with environment variables. - Enhanced input validation, error handling, and exception messages across samples. - Updated `merge-different-file-types` and `pdf-multipart` examples for clarity and alignment with guidelines.
1 parent 7441b6f commit 9671577

3 files changed

Lines changed: 198 additions & 111 deletions

File tree

Lines changed: 126 additions & 92 deletions
Original file line numberDiff line numberDiff line change
@@ -1,96 +1,130 @@
1+
/*
2+
* What this sample does:
3+
* - Converts two different file types to PDF via multipart, then merges them.
4+
* - Routed from Program.cs as: `dotnet run -- merge-different-file-types <imageFile> <pptFile>`.
5+
*
6+
* Setup (environment):
7+
* - Copy .env.example to .env
8+
* - Set PDFREST_API_KEY=your_api_key_here
9+
* - Optional: set PDFREST_URL to override the API region. For EU/GDPR compliance and proximity, use:
10+
* PDFREST_URL=https://eu-api.pdfrest.com
11+
* For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
12+
*
13+
* Usage:
14+
* dotnet run -- merge-different-file-types image.png slides.pptx
15+
*
16+
* Output:
17+
* - Prints JSON responses for the two pdf conversions and the final merge.
18+
*/
19+
120
using Newtonsoft.Json.Linq;
221
using System.Text;
322

4-
/* In this sample, we will show how to merge different file types together as
5-
* discussed in https://pdfrest.com/solutions/merge-multiple-types-of-files-together/.
6-
First, we will upload an image file to the /pdf route and capture the output ID.
7-
* Next, we will upload a PowerPoint file to the /pdf route and capture its output
8-
* ID. Finally, we will pass both IDs to the /merged-pdf route to combine both inputs
9-
* into a single PDF.
10-
*
11-
* Note that there is nothing special about an image and a PowerPoint file, and
12-
* this sample could be easily used to convert and combine any two file types
13-
* that the /pdf route takes as inputs.
14-
*/
15-
16-
var apiKey = "xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; // Your API key here
17-
18-
using (var httpClient = new HttpClient { BaseAddress = new Uri("https://api.pdfrest.com") })
23+
namespace Samples.ComplexFlowExamples
1924
{
20-
// Begin first PDF conversion
21-
using var imageRequest = new HttpRequestMessage(HttpMethod.Post, "pdf");
22-
23-
imageRequest.Headers.TryAddWithoutValidation("Api-Key", apiKey);
24-
imageRequest.Headers.Accept.Add(new("application/json"));
25-
var imageMultipartContent = new MultipartFormDataContent();
26-
27-
var imageByteArray = File.ReadAllBytes("/path/to/file.png");
28-
var imageByteAryContent = new ByteArrayContent(imageByteArray);
29-
imageMultipartContent.Add(imageByteAryContent, "file", "file.png");
30-
imageByteAryContent.Headers.TryAddWithoutValidation("Content-Type", "image/x-png");
31-
32-
imageRequest.Content = imageMultipartContent;
33-
var imageResponse = await httpClient.SendAsync(imageRequest);
34-
35-
var imageResult = await imageResponse.Content.ReadAsStringAsync();
36-
Console.WriteLine("Image to PDF response received.");
37-
Console.WriteLine(imageResult);
38-
39-
dynamic imageResponseData = JObject.Parse(imageResult);
40-
string imageID = imageResponseData.outputId;
41-
42-
// Begin second PDF conversion
43-
using var powerpointRequest = new HttpRequestMessage(HttpMethod.Post, "pdf");
44-
45-
powerpointRequest.Headers.TryAddWithoutValidation("Api-Key", apiKey);
46-
powerpointRequest.Headers.Accept.Add(new("application/json"));
47-
var powerpointMultipartContent = new MultipartFormDataContent();
48-
49-
var powerpointByteArray = File.ReadAllBytes("/path/to/file.ppt");
50-
var powerpointByteAryContent = new ByteArrayContent(powerpointByteArray);
51-
powerpointMultipartContent.Add(powerpointByteAryContent, "file", "file.ppt");
52-
powerpointByteAryContent.Headers.TryAddWithoutValidation("Content-Type", "application/vnd.ms-powerpoint");
53-
54-
powerpointRequest.Content = powerpointMultipartContent;
55-
var powerpointResponse = await httpClient.SendAsync(powerpointRequest);
56-
57-
var powerpointResult = await powerpointResponse.Content.ReadAsStringAsync();
58-
Console.WriteLine("powerpoint to PDF response received.");
59-
Console.WriteLine(powerpointResult);
60-
61-
dynamic powerpointResponseData = JObject.Parse(powerpointResult);
62-
string powerpointID = powerpointResponseData.outputId;
63-
64-
// Begin file merge
65-
using var request = new HttpRequestMessage(HttpMethod.Post, "merged-pdf");
66-
67-
request.Headers.TryAddWithoutValidation("Api-Key", apiKey);
68-
request.Headers.Accept.Add(new("application/json"));
69-
var multipartContent = new MultipartFormDataContent();
70-
71-
72-
var imageByteArrayID = new ByteArrayContent(Encoding.UTF8.GetBytes(imageID));
73-
multipartContent.Add(imageByteArrayID, "id[]");
74-
75-
var byteArrayOption = new ByteArrayContent(Encoding.UTF8.GetBytes("id"));
76-
multipartContent.Add(byteArrayOption, "type[]");
77-
var byteArrayOption2 = new ByteArrayContent(Encoding.UTF8.GetBytes("all"));
78-
multipartContent.Add(byteArrayOption2, "pages[]");
79-
80-
81-
var powerpointByteArrayID = new ByteArrayContent(Encoding.UTF8.GetBytes(powerpointID));
82-
multipartContent.Add(powerpointByteArrayID, "id[]");
83-
84-
var byteArrayOption3 = new ByteArrayContent(Encoding.UTF8.GetBytes("id"));
85-
multipartContent.Add(byteArrayOption3, "type[]");
86-
var byteArrayOption4 = new ByteArrayContent(Encoding.UTF8.GetBytes("all"));
87-
multipartContent.Add(byteArrayOption4, "pages[]");
88-
89-
request.Content = multipartContent;
90-
var response = await httpClient.SendAsync(request);
91-
92-
var apiResult = await response.Content.ReadAsStringAsync();
93-
94-
Console.WriteLine("Merge response received.");
95-
Console.WriteLine(apiResult);
96-
}
25+
public static class MergeDifferentFileTypes
26+
{
27+
public static async Task Execute(string[] args)
28+
{
29+
if (args == null || args.Length < 2)
30+
{
31+
Console.Error.WriteLine("merge-different-file-types requires <imageFile> <pptFile>");
32+
Environment.Exit(1);
33+
return;
34+
}
35+
36+
var imagePath = args[0];
37+
var pptPath = args[1];
38+
if (!File.Exists(imagePath) || !File.Exists(pptPath))
39+
{
40+
Console.Error.WriteLine("One or more input files not found.");
41+
Environment.Exit(1);
42+
return;
43+
}
44+
45+
var apiKey = Environment.GetEnvironmentVariable("PDFREST_API_KEY");
46+
if (string.IsNullOrWhiteSpace(apiKey))
47+
{
48+
Console.Error.WriteLine("Missing required environment variable: PDFREST_API_KEY");
49+
Environment.Exit(1);
50+
return;
51+
}
52+
53+
var baseUrl = Environment.GetEnvironmentVariable("PDFREST_URL") ?? "https://api.pdfrest.com";
54+
55+
using (var httpClient = new HttpClient { BaseAddress = new Uri(baseUrl) })
56+
{
57+
// Begin first PDF conversion
58+
using var imageRequest = new HttpRequestMessage(HttpMethod.Post, "pdf");
59+
imageRequest.Headers.TryAddWithoutValidation("Api-Key", apiKey);
60+
imageRequest.Headers.Accept.Add(new("application/json"));
61+
var imageMultipartContent = new MultipartFormDataContent();
62+
63+
var imageByteArray = File.ReadAllBytes(imagePath);
64+
var imageByteAryContent = new ByteArrayContent(imageByteArray);
65+
imageMultipartContent.Add(imageByteAryContent, "file", Path.GetFileName(imagePath));
66+
imageByteAryContent.Headers.TryAddWithoutValidation("Content-Type", "application/octet-stream");
67+
68+
imageRequest.Content = imageMultipartContent;
69+
var imageResponse = await httpClient.SendAsync(imageRequest);
70+
71+
var imageResult = await imageResponse.Content.ReadAsStringAsync();
72+
Console.WriteLine("Image to PDF response received.");
73+
Console.WriteLine(imageResult);
74+
75+
dynamic imageResponseData = JObject.Parse(imageResult);
76+
string imageID = imageResponseData.outputId;
77+
78+
// Begin second PDF conversion
79+
using var powerpointRequest = new HttpRequestMessage(HttpMethod.Post, "pdf");
80+
powerpointRequest.Headers.TryAddWithoutValidation("Api-Key", apiKey);
81+
powerpointRequest.Headers.Accept.Add(new("application/json"));
82+
var powerpointMultipartContent = new MultipartFormDataContent();
83+
84+
var powerpointByteArray = File.ReadAllBytes(pptPath);
85+
var powerpointByteAryContent = new ByteArrayContent(powerpointByteArray);
86+
powerpointMultipartContent.Add(powerpointByteAryContent, "file", Path.GetFileName(pptPath));
87+
powerpointByteAryContent.Headers.TryAddWithoutValidation("Content-Type", "application/octet-stream");
88+
89+
powerpointRequest.Content = powerpointMultipartContent;
90+
var powerpointResponse = await httpClient.SendAsync(powerpointRequest);
91+
92+
var powerpointResult = await powerpointResponse.Content.ReadAsStringAsync();
93+
Console.WriteLine("powerpoint to PDF response received.");
94+
Console.WriteLine(powerpointResult);
95+
96+
dynamic powerpointResponseData = JObject.Parse(powerpointResult);
97+
string powerpointID = powerpointResponseData.outputId;
98+
99+
// Begin file merge
100+
using var request = new HttpRequestMessage(HttpMethod.Post, "merged-pdf");
101+
request.Headers.TryAddWithoutValidation("Api-Key", apiKey);
102+
request.Headers.Accept.Add(new("application/json"));
103+
var multipartContent = new MultipartFormDataContent();
104+
105+
var imageByteArrayID = new ByteArrayContent(Encoding.UTF8.GetBytes(imageID));
106+
multipartContent.Add(imageByteArrayID, "id[]");
107+
108+
var byteArrayOption = new ByteArrayContent(Encoding.UTF8.GetBytes("id"));
109+
multipartContent.Add(byteArrayOption, "type[]");
110+
var byteArrayOption2 = new ByteArrayContent(Encoding.UTF8.GetBytes("all"));
111+
multipartContent.Add(byteArrayOption2, "pages[]");
112+
113+
var powerpointByteArrayID = new ByteArrayContent(Encoding.UTF8.GetBytes(powerpointID));
114+
multipartContent.Add(powerpointByteArrayID, "id[]");
115+
116+
var byteArrayOption3 = new ByteArrayContent(Encoding.UTF8.GetBytes("id"));
117+
multipartContent.Add(byteArrayOption3, "type[]");
118+
var byteArrayOption4 = new ByteArrayContent(Encoding.UTF8.GetBytes("all"));
119+
multipartContent.Add(byteArrayOption4, "pages[]");
120+
121+
request.Content = multipartContent;
122+
var response = await httpClient.SendAsync(request);
123+
var apiResult = await response.Content.ReadAsStringAsync();
124+
125+
Console.WriteLine("Merge response received.");
126+
Console.WriteLine(apiResult);
127+
}
128+
}
129+
}
130+
}
Lines changed: 71 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,82 @@
1+
/*
2+
* What this sample does:
3+
* - Calls the pdf endpoint using multipart/form-data to convert an input file to PDF.
4+
* - Routed from Program.cs as: `dotnet run -- pdf-multipart <inputFile>`.
5+
*
6+
* Setup (environment):
7+
* - Copy .env.example to .env
8+
* - Set PDFREST_API_KEY=your_api_key_here
9+
* - Optional: set PDFREST_URL to override the API region. For EU/GDPR compliance and proximity, use:
10+
* PDFREST_URL=https://eu-api.pdfrest.com
11+
* For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
12+
*
13+
* Usage:
14+
* dotnet run -- pdf-multipart /path/to/input.html
15+
* dotnet run -- pdf-multipart /path/to/input.docx
16+
*
17+
* Output:
18+
* - Prints the JSON response from the API. On HTTP errors, prints server response body.
19+
*/
20+
121
using System.Text;
222

3-
using (var httpClient = new HttpClient { BaseAddress = new Uri("https://api.pdfrest.com") })
23+
namespace Samples.EndpointExamples.MultipartPayload
424
{
5-
using (var request = new HttpRequestMessage(HttpMethod.Post, "pdf"))
25+
public static class Pdf
626
{
7-
request.Headers.TryAddWithoutValidation("Api-Key", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
8-
request.Headers.Accept.Add(new("application/json"));
9-
var multipartContent = new MultipartFormDataContent();
27+
public static async Task Execute(string[] args)
28+
{
29+
if (args == null || args.Length < 1)
30+
{
31+
Console.Error.WriteLine("pdf-multipart requires <inputFile>");
32+
Environment.Exit(1);
33+
return;
34+
}
35+
36+
var inputPath = args[0];
37+
if (!File.Exists(inputPath))
38+
{
39+
Console.Error.WriteLine($"File not found: {inputPath}");
40+
Environment.Exit(1);
41+
return;
42+
}
43+
44+
var apiKey = Environment.GetEnvironmentVariable("PDFREST_API_KEY");
45+
if (string.IsNullOrWhiteSpace(apiKey))
46+
{
47+
Console.Error.WriteLine("Missing required environment variable: PDFREST_API_KEY");
48+
Environment.Exit(1);
49+
return;
50+
}
51+
52+
var baseUrl = Environment.GetEnvironmentVariable("PDFREST_URL") ?? "https://api.pdfrest.com";
53+
54+
using (var httpClient = new HttpClient { BaseAddress = new Uri(baseUrl) })
55+
using (var request = new HttpRequestMessage(HttpMethod.Post, "pdf"))
56+
{
57+
request.Headers.TryAddWithoutValidation("Api-Key", apiKey);
58+
request.Headers.Accept.Add(new("application/json"));
59+
60+
var multipartContent = new MultipartFormDataContent();
1061

11-
var byteArray = File.ReadAllBytes("/path/to/file");
12-
var byteAryContent = new ByteArrayContent(byteArray);
13-
multipartContent.Add(byteAryContent, "file", "file_name");
14-
byteAryContent.Headers.TryAddWithoutValidation("Content-Type", "text/html");
62+
var byteArray = File.ReadAllBytes(inputPath);
63+
var byteAryContent = new ByteArrayContent(byteArray);
64+
multipartContent.Add(byteAryContent, "file", Path.GetFileName(inputPath));
65+
byteAryContent.Headers.TryAddWithoutValidation("Content-Type", "application/octet-stream");
1566

16-
var byteArrayOption = new ByteArrayContent(Encoding.UTF8.GetBytes("A4"));
17-
multipartContent.Add(byteArrayOption, "page_size");
67+
var byteArrayOption = new ByteArrayContent(Encoding.UTF8.GetBytes("A4"));
68+
multipartContent.Add(byteArrayOption, "page_size");
1869

19-
var byteArrayOption2 = new ByteArrayContent(Encoding.UTF8.GetBytes("output.pdf"));
20-
multipartContent.Add(byteArrayOption2, "output");
21-
request.Content = multipartContent;
22-
var response = await httpClient.SendAsync(request);
70+
var byteArrayOption2 = new ByteArrayContent(Encoding.UTF8.GetBytes("output.pdf"));
71+
multipartContent.Add(byteArrayOption2, "output");
2372

24-
var apiResult = await response.Content.ReadAsStringAsync();
73+
request.Content = multipartContent;
74+
var response = await httpClient.SendAsync(request);
75+
var apiResult = await response.Content.ReadAsStringAsync();
2576

26-
Console.WriteLine("API response received.");
27-
Console.WriteLine(apiResult);
77+
Console.WriteLine("API response received.");
78+
Console.WriteLine(apiResult);
79+
}
80+
}
2881
}
2982
}

DotNET/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ static void PrintUsage()
1111
Console.Error.WriteLine("Commands:");
1212
Console.Error.WriteLine(" markdown-json <inputFile> Upload then convert to Markdown (JSON two-step)");
1313
Console.Error.WriteLine(" rasterized-pdf <inputFile> Upload then rasterize PDF (JSON two-step)");
14-
Console.Error.WriteLine(" pdf-multipart <inputFile> [ct] Convert to PDF via multipart (optional content-type)");
14+
Console.Error.WriteLine(" pdf-multipart <inputFile> Convert to PDF via multipart");
1515
Console.Error.WriteLine(" merge-different-file-types <imageFile> <pptFile> Convert then merge (complex flow)");
1616
Console.Error.WriteLine(" extracted-text <inputFile> Upload then extract text (JSON two-step)");
1717
Console.Error.WriteLine(" extracted-images <inputFile> Upload then extract images (JSON two-step)");

0 commit comments

Comments
 (0)