From c8f4eefa3760a7939b6f21c4a0774dce5a493a70 Mon Sep 17 00:00:00 2001 From: Taylor Smith Date: Wed, 22 Jan 2025 11:27:59 -0600 Subject: [PATCH] Add samples for rasterized-pdf endpoint --- .../JSON Payload/rasterized-pdf.cs | 50 ++++++++++ .../Multipart Payload/rasterized-pdf.cs | 25 +++++ .../JSON Payload/RasterizedPdf.java | 96 +++++++++++++++++++ .../Multipart Payload/RasterizedPdf.java | 59 ++++++++++++ .../JSON Payload/rasterized-pdf.js | 47 +++++++++ .../Multipart Payload/rasterized-pdf.js | 32 +++++++ .../JSON Payload/rasterized-pdf.php | 33 +++++++ .../Multipart Payload/rasterized-pdf.php | 35 +++++++ .../JSON Payload/rasterized-pdf.py | 39 ++++++++ .../Multipart Payload/rasterized-pdf.py | 34 +++++++ .../JSON Payload/rasterized-pdf.sh | 14 +++ .../Multipart Payload/rasterized-pdf.sh | 6 ++ 12 files changed, 470 insertions(+) create mode 100644 DotNET/Endpoint Examples/JSON Payload/rasterized-pdf.cs create mode 100644 DotNET/Endpoint Examples/Multipart Payload/rasterized-pdf.cs create mode 100644 Java/Endpoint Examples/JSON Payload/RasterizedPdf.java create mode 100644 Java/Endpoint Examples/Multipart Payload/RasterizedPdf.java create mode 100644 JavaScript/Endpoint Examples/JSON Payload/rasterized-pdf.js create mode 100644 JavaScript/Endpoint Examples/Multipart Payload/rasterized-pdf.js create mode 100644 PHP/Endpoint Examples/JSON Payload/rasterized-pdf.php create mode 100644 PHP/Endpoint Examples/Multipart Payload/rasterized-pdf.php create mode 100644 Python/Endpoint Examples/JSON Payload/rasterized-pdf.py create mode 100644 Python/Endpoint Examples/Multipart Payload/rasterized-pdf.py create mode 100755 cURL/Endpoint Examples/JSON Payload/rasterized-pdf.sh create mode 100755 cURL/Endpoint Examples/Multipart Payload/rasterized-pdf.sh diff --git a/DotNET/Endpoint Examples/JSON Payload/rasterized-pdf.cs b/DotNET/Endpoint Examples/JSON Payload/rasterized-pdf.cs new file mode 100644 index 0000000..3eb6c72 --- /dev/null +++ b/DotNET/Endpoint Examples/JSON Payload/rasterized-pdf.cs @@ -0,0 +1,50 @@ + +using Newtonsoft.Json.Linq; +using System.Text; + +using (var httpClient = new HttpClient { BaseAddress = new Uri("https://api.pdfrest.com") }) +{ + using (var uploadRequest = new HttpRequestMessage(HttpMethod.Post, "upload")) + { + uploadRequest.Headers.TryAddWithoutValidation("Api-Key", "xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"); + uploadRequest.Headers.Accept.Add(new("application/json")); + + var uploadByteArray = File.ReadAllBytes("/path/to/file"); + var uploadByteAryContent = new ByteArrayContent(uploadByteArray); + uploadByteAryContent.Headers.TryAddWithoutValidation("Content-Type", "application/octet-stream"); + uploadByteAryContent.Headers.TryAddWithoutValidation("Content-Filename", "filename.pdf"); + + + uploadRequest.Content = uploadByteAryContent; + var uploadResponse = await httpClient.SendAsync(uploadRequest); + + var uploadResult = await uploadResponse.Content.ReadAsStringAsync(); + + Console.WriteLine("Upload response received."); + Console.WriteLine(uploadResult); + + JObject uploadResultJson = JObject.Parse(uploadResult); + var uploadedID = uploadResultJson["files"][0]["id"]; + using (var rasterizeRequest = new HttpRequestMessage(HttpMethod.Post, "rasterized-pdf")) + { + rasterizeRequest.Headers.TryAddWithoutValidation("Api-Key", "xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"); + rasterizeRequest.Headers.Accept.Add(new("application/json")); + + rasterizeRequest.Headers.TryAddWithoutValidation("Content-Type", "application/json"); + + + JObject parameterJson = new JObject + { + ["id"] = uploadedID, + }; + + rasterizeRequest.Content = new StringContent(parameterJson.ToString(), Encoding.UTF8, "application/json"); ; + var rasterizeResponse = await httpClient.SendAsync(rasterizeRequest); + + var rasterizeResult = await rasterizeResponse.Content.ReadAsStringAsync(); + + Console.WriteLine("Processing response received."); + Console.WriteLine(rasterizeResult); + } + } +} diff --git a/DotNET/Endpoint Examples/Multipart Payload/rasterized-pdf.cs b/DotNET/Endpoint Examples/Multipart Payload/rasterized-pdf.cs new file mode 100644 index 0000000..bf503b5 --- /dev/null +++ b/DotNET/Endpoint Examples/Multipart Payload/rasterized-pdf.cs @@ -0,0 +1,25 @@ +using System.Text; + +using (var httpClient = new HttpClient { BaseAddress = new Uri("https://api.pdfrest.com") }) +{ + using (var request = new HttpRequestMessage(HttpMethod.Post, "rasterized-pdf")) + { + request.Headers.TryAddWithoutValidation("Api-Key", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"); + request.Headers.Accept.Add(new("application/json")); + var multipartContent = new MultipartFormDataContent(); + + var byteArray = File.ReadAllBytes("/path/to/file"); + var byteAryContent = new ByteArrayContent(byteArray); + multipartContent.Add(byteAryContent, "file", "file_name"); + byteAryContent.Headers.TryAddWithoutValidation("Content-Type", "application/pdf"); + + + request.Content = multipartContent; + var response = await httpClient.SendAsync(request); + + var apiResult = await response.Content.ReadAsStringAsync(); + + Console.WriteLine("API response received."); + Console.WriteLine(apiResult); + } +} diff --git a/Java/Endpoint Examples/JSON Payload/RasterizedPdf.java b/Java/Endpoint Examples/JSON Payload/RasterizedPdf.java new file mode 100644 index 0000000..6fffa62 --- /dev/null +++ b/Java/Endpoint Examples/JSON Payload/RasterizedPdf.java @@ -0,0 +1,96 @@ +import io.github.cdimascio.dotenv.Dotenv; +import java.io.File; +import java.io.IOException; +import java.util.concurrent.TimeUnit; +import okhttp3.*; +import org.json.JSONArray; +import org.json.JSONObject; + +public class RasterizedPdf { + + // Specify the path to your file here, or as the first argument when running the program. + private static final String DEFAULT_FILE_PATH = "/path/to/file.pdf"; + + // Specify your API key here, or in the environment variable PDFREST_API_KEY. + // You can also put the environment variable in a .env file. + private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; + + public static void main(String[] args) { + File inputFile; + if (args.length > 0) { + inputFile = new File(args[0]); + } else { + inputFile = new File(DEFAULT_FILE_PATH); + } + final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load(); + + String uploadString = uploadFile(inputFile); + JSONObject uploadJSON = new JSONObject(uploadString); + if (uploadJSON.has("error")) { + System.out.println("Error during upload: " + uploadString); + return; + } + JSONArray fileArray = uploadJSON.getJSONArray("files"); + + JSONObject fileObject = fileArray.getJSONObject(0); + + String uploadedID = fileObject.get("id").toString(); + + String JSONString = String.format("{\"id\":\"%s\"}", uploadedID); + + final RequestBody requestBody = + RequestBody.create(JSONString, MediaType.parse("application/json")); + + Request request = + new Request.Builder() + .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY)) + .url("https://api.pdfrest.com/rasterized-pdf") + .post(requestBody) + .build(); + try { + OkHttpClient client = + new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build(); + + Response response = client.newCall(request).execute(); + System.out.println("Processing Result code " + response.code()); + if (response.body() != null) { + System.out.println(prettyJson(response.body().string())); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private static String prettyJson(String json) { + // https://stackoverflow.com/a/9583835/11996393 + return new JSONObject(json).toString(4); + } + + // This function is just a copy of the 'Upload.java' file to upload a binary file + private static String uploadFile(File inputFile) { + + final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load(); + + final RequestBody requestBody = + RequestBody.create(inputFile, MediaType.parse("application/pdf")); + + Request request = + new Request.Builder() + .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY)) + .header("Content-Filename", "File.pdf") + .url("https://api.pdfrest.com/upload") + .post(requestBody) + .build(); + try { + OkHttpClient client = new OkHttpClient().newBuilder().build(); + Response response = client.newCall(request).execute(); + System.out.println("Upload Result code " + response.code()); + if (response.body() != null) { + return response.body().string(); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + return ""; + } +} diff --git a/Java/Endpoint Examples/Multipart Payload/RasterizedPdf.java b/Java/Endpoint Examples/Multipart Payload/RasterizedPdf.java new file mode 100644 index 0000000..dea861f --- /dev/null +++ b/Java/Endpoint Examples/Multipart Payload/RasterizedPdf.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.*; +import org.json.JSONObject; + +public class RasterizedPdf { + + // Specify the path to your file here, or as the first argument when running the program. + private static final String DEFAULT_FILE_PATH = "/path/to/file.pdf"; + + // Specify your API key here, or in the environment variable PDFREST_API_KEY. + // You can also put the environment variable in a .env file. + private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; + + public static void main(String[] args) { + File inputFile; + if (args.length > 0) { + inputFile = new File(args[0]); + } else { + inputFile = new File(DEFAULT_FILE_PATH); + } + + final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load(); + + final RequestBody inputFileRequestBody = + RequestBody.create(inputFile, MediaType.parse("application/pdf")); + RequestBody requestBody = + new MultipartBody.Builder() + .setType(MultipartBody.FORM) + .addFormDataPart("file", inputFile.getName(), inputFileRequestBody) + .addFormDataPart("output", "pdfrest_rasterized") + .build(); + Request request = + new Request.Builder() + .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY)) + .url("https://api.pdfrest.com/rasterized-pdf") + .post(requestBody) + .build(); + try { + OkHttpClient client = + new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build(); + + Response response = client.newCall(request).execute(); + System.out.println("Result code " + response.code()); + if (response.body() != null) { + System.out.println(prettyJson(response.body().string())); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private static String prettyJson(String json) { + // https://stackoverflow.com/a/9583835/11996393 + return new JSONObject(json).toString(4); + } +} diff --git a/JavaScript/Endpoint Examples/JSON Payload/rasterized-pdf.js b/JavaScript/Endpoint Examples/JSON Payload/rasterized-pdf.js new file mode 100644 index 0000000..7a28800 --- /dev/null +++ b/JavaScript/Endpoint Examples/JSON Payload/rasterized-pdf.js @@ -0,0 +1,47 @@ +var axios = require("axios"); +var FormData = require("form-data"); +var fs = require("fs"); + +var upload_data = fs.createReadStream("/path/to/file"); + +var upload_config = { + method: "post", + maxBodyLength: Infinity, + url: "https://api.pdfrest.com/upload", + headers: { + "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", // Replace with your API key + "Content-Filename": "filename.pdf", + "Content-Type": "application/octet-stream", + }, + data: upload_data, // set the data to be sent with the request +}; + +// send request and handle response or error +axios(upload_config) + .then(function (upload_response) { + console.log(JSON.stringify(upload_response.data)); + var uploaded_id = upload_response.data.files[0].id; + + var rasterize_config = { + method: "post", + maxBodyLength: Infinity, + url: "https://api.pdfrest.com/rasterized-pdf", + headers: { + "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", // Replace with your API key + "Content-Type": "application/json", + }, + data: { id: uploaded_id }, // set the data to be sent with the request + }; + + // send request and handle response or error + axios(rasterize_config) + .then(function (rasterize_response) { + console.log(JSON.stringify(rasterize_response.data)); + }) + .catch(function (error) { + console.log(error); + }); + }) + .catch(function (error) { + console.log(error); + }); diff --git a/JavaScript/Endpoint Examples/Multipart Payload/rasterized-pdf.js b/JavaScript/Endpoint Examples/Multipart Payload/rasterized-pdf.js new file mode 100644 index 0000000..454cfa9 --- /dev/null +++ b/JavaScript/Endpoint Examples/Multipart Payload/rasterized-pdf.js @@ -0,0 +1,32 @@ +// This request demonstrates how to rasterize a PDF file. +var axios = require("axios"); +var FormData = require("form-data"); +var fs = require("fs"); + +// Create a new form data instance and append the file and parameters to it +var data = new FormData(); +data.append("file", fs.createReadStream("/path/to/file")); +data.append("output", "pdfrest_rasterized"); + +// define configuration options for axios request +var config = { + method: "post", + maxBodyLength: Infinity, // set maximum length of the request body + url: "https://api.pdfrest.com/rasterized-pdf", + headers: { + "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", // Replace with your API key + ...data.getHeaders(), // set headers for the request + }, + data: data, // set the data to be sent with the request +}; + +// send request and handle response or error +axios(config) + .then(function (response) { + console.log(JSON.stringify(response.data)); + }) + .catch(function (error) { + console.log(error); + }); + +// If you would like to download the file instead of getting the JSON response, please see the 'get-resource-id-endpoint.js' sample. diff --git a/PHP/Endpoint Examples/JSON Payload/rasterized-pdf.php b/PHP/Endpoint Examples/JSON Payload/rasterized-pdf.php new file mode 100644 index 0000000..1db075f --- /dev/null +++ b/PHP/Endpoint Examples/JSON Payload/rasterized-pdf.php @@ -0,0 +1,33 @@ + false]); +$upload_headers = [ + 'api-key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', + 'content-filename' => 'filename.pdf', + 'Content-Type' => 'application/octet-stream' +]; +$upload_body = file_get_contents('/path/to/file'); +$upload_request = new Request('POST', 'https://api.pdfrest.com/upload', $upload_headers, $upload_body); +$upload_res = $upload_client->sendAsync($upload_request)->wait(); +echo $upload_res->getBody() . PHP_EOL; + +$upload_response_json = json_decode($upload_res->getBody()); + +$uploaded_id = $upload_response_json->{'files'}[0]->{'id'}; + +echo "Successfully uploaded with an id of: " . $uploaded_id . PHP_EOL; + +$rasterize_client = new Client(['http_errors' => false]); +$rasterize_headers = [ + 'api-key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', + 'Content-Type' => 'application/json' +]; +$rasterize_body = '{"id":"'.$uploaded_id.'"}'; +$rasterize_request = new Request('POST', 'https://api.pdfrest.com/rasterized-pdf', $rasterize_headers, $rasterize_body); +$rasterize_res = $rasterize_client->sendAsync($rasterize_request)->wait(); +echo $rasterize_res->getBody() . PHP_EOL; diff --git a/PHP/Endpoint Examples/Multipart Payload/rasterized-pdf.php b/PHP/Endpoint Examples/Multipart Payload/rasterized-pdf.php new file mode 100644 index 0000000..25b8ff6 --- /dev/null +++ b/PHP/Endpoint Examples/Multipart Payload/rasterized-pdf.php @@ -0,0 +1,35 @@ + 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' // Set the API key in the headers for authentication. +]; + +$options = [ + 'multipart' => [ + [ + 'name' => 'file', // Specify the field name for the file. + 'contents' => Utils::tryFopen('/path/to/file', 'r'), // Open the file specified by the '/path/to/file' for reading. + 'filename' => 'filename.pdf', // Set the filename for the file to be converted, in this case, '/path/to/file'. + 'headers' => [ + 'Content-Type' => '' // Set the Content-Type header for the file. + ] + ], + [ + 'name' => 'output', // Specify the field name for the output option. + 'contents' => 'pdfrest_rasterize' // Set the value for the output option (in this case, 'pdfrest_rasterize'). + ] + ] +]; + +$request = new Request('POST', 'https://api.pdfrest.com/rasterized-pdf', $headers); // Create a new HTTP POST request with the API endpoint and headers. + +$res = $client->sendAsync($request, $options)->wait(); // Send the asynchronous request and wait for the response. + +echo $res->getBody(); // Output the response body, which contains the rasterized PDF. diff --git a/Python/Endpoint Examples/JSON Payload/rasterized-pdf.py b/Python/Endpoint Examples/JSON Payload/rasterized-pdf.py new file mode 100644 index 0000000..01d63e3 --- /dev/null +++ b/Python/Endpoint Examples/JSON Payload/rasterized-pdf.py @@ -0,0 +1,39 @@ +import requests +import json + +with open('/path/to/file', 'rb') as f: + upload_data = f.read() + +print("Uploading file...") +upload_response = requests.post(url='https://api.pdfrest.com/upload', + data=upload_data, + headers={'Content-Type': 'application/octet-stream', 'Content-Filename': 'file.pdf', "API-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"}) + +print("Upload response status code: " + str(upload_response.status_code)) + +if upload_response.ok: + upload_response_json = upload_response.json() + print(json.dumps(upload_response_json, indent = 2)) + + + uploaded_id = upload_response_json['files'][0]['id'] + rasterize_data = { "id" : uploaded_id } + print(json.dumps(rasterize_data, indent = 2)) + + + print("Processing file...") + rasterize_response = requests.post(url='https://api.pdfrest.com/rasterized-pdf', + data=json.dumps(rasterize_data), + headers={'Content-Type': 'application/json', "API-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"}) + + + + print("Processing response status code: " + str(rasterize_response.status_code)) + if rasterize_response.ok: + rasterize_response_json = rasterize_response.json() + print(json.dumps(rasterize_response_json, indent = 2)) + + else: + print(rasterize_response.text) +else: + print(upload_response.text) diff --git a/Python/Endpoint Examples/Multipart Payload/rasterized-pdf.py b/Python/Endpoint Examples/Multipart Payload/rasterized-pdf.py new file mode 100644 index 0000000..eb64edd --- /dev/null +++ b/Python/Endpoint Examples/Multipart Payload/rasterized-pdf.py @@ -0,0 +1,34 @@ +from requests_toolbelt import MultipartEncoder +import requests +import json + +rasterize_endpoint_url = 'https://api.pdfrest.com/rasterized-pdf' + +# The /rasterized endpoint can take a single PDF file or id as input and turn it into a rasterized PDF file. +mp_encoder_rasterize = MultipartEncoder( + fields={ + 'file': ('file_name.pdf', open('/path/to/file', 'rb'), 'application/pdf'), + 'output' : 'example_rasterize_out', + } +) + +# Let's set the headers that the rasterized-pdf endpoint expects. +# Since MultipartEncoder is used, the 'Content-Type' header gets set to 'multipart/form-data' via the content_type attribute below. +headers = { + 'Accept': 'application/json', + 'Content-Type': mp_encoder_rasterize.content_type, + 'Api-Key': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' # place your api key here +} + +print("Sending POST request to rasterized-pdf endpoint...") +response = requests.post(rasterize_endpoint_url, data=mp_encoder_rasterize, headers=headers) + +print("Response status code: " + str(response.status_code)) + +if response.ok: + response_json = response.json() + print(json.dumps(response_json, indent = 2)) +else: + print(response.text) + +# If you would like to download the file instead of getting the JSON response, please see the 'get-resource-id-endpoint.py' sample. diff --git a/cURL/Endpoint Examples/JSON Payload/rasterized-pdf.sh b/cURL/Endpoint Examples/JSON Payload/rasterized-pdf.sh new file mode 100755 index 0000000..6546d77 --- /dev/null +++ b/cURL/Endpoint Examples/JSON Payload/rasterized-pdf.sh @@ -0,0 +1,14 @@ +#!/bin/sh + +UPLOAD_ID=$(curl --location 'https://api.pdfrest.com/upload' \ +--header 'Api-Key: xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' \ +--header 'content-filename: filename.pdf' \ +--data-binary '@/path/to/file' \ + | jq -r '.files.[0].id') + +echo "File successfully uploaded with an ID of: $UPLOAD_ID" + +curl 'https://api.pdfrest.com/rasterized-pdf' \ +--header 'Api-Key: xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' \ +--header 'Content-Type: application/json' \ +--data-raw "{ \"id\": \"$UPLOAD_ID\"}" | jq -r '.' diff --git a/cURL/Endpoint Examples/Multipart Payload/rasterized-pdf.sh b/cURL/Endpoint Examples/Multipart Payload/rasterized-pdf.sh new file mode 100755 index 0000000..a95f333 --- /dev/null +++ b/cURL/Endpoint Examples/Multipart Payload/rasterized-pdf.sh @@ -0,0 +1,6 @@ +curl -X POST "https://api.pdfrest.com/rasterized-pdf" \ + -H "Accept: application/json" \ + -H "Content-Type: multipart/form-data" \ + -H "Api-Key: xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" \ + -F "file=@/path/to/file" \ + -F "output=example_out"