Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CPlusPlus/Endpoint Examples/JSON Payload/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,8 @@ if (cpr_FOUND AND nlohmann_json_FOUND)
add_executable(summarized_pdf_text_json summarized_pdf_text.cpp)
target_link_libraries(summarized_pdf_text_json PRIVATE cpr::cpr nlohmann_json::nlohmann_json)
target_compile_features(summarized_pdf_text_json PRIVATE cxx_std_20)

add_executable(translated_pdf_text_json translated_pdf_text.cpp)
target_link_libraries(translated_pdf_text_json PRIVATE cpr::cpr nlohmann_json::nlohmann_json)
target_compile_features(translated_pdf_text_json PRIVATE cxx_std_20)
endif()
142 changes: 142 additions & 0 deletions CPlusPlus/Endpoint Examples/JSON Payload/translated_pdf_text.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
/*
* What this sample does:
* - Uploads a PDF via /upload, then calls /translated-pdf-text with a JSON payload
* referencing the uploaded resource id (two-step JSON flow).
*
* Setup (environment):
* - Set PDFREST_API_KEY=your_api_key_here
* - Optional: set PDFREST_URL to override the API region. For EU/GDPR, use:
* PDFREST_URL=https://eu-api.pdfrest.com
* More info: https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
*
* Usage:
* ./translated_pdf_text_json /path/to/input.pdf
*
* Output:
* - Prints JSON responses to stdout. Non-2xx responses print a concise
* error to stderr and exit non-zero.
*/

#include <cpr/cpr.h>
#include <nlohmann/json.hpp>

#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <optional>
#include <string>

namespace fs = std::filesystem;
using json = nlohmann::json;

static std::string rtrim_slashes(std::string s) {
while (!s.empty() && (s.back() == '/' || s.back() == '\\')) {
s.pop_back();
}
return s;
}

static void load_dotenv_if_present(const fs::path &path) {
std::ifstream f(path);
if (!f.is_open()) return;
std::string line;
while (std::getline(f, line)) {
if (line.empty() || line[0] == '#') continue;
auto pos = line.find('=');
if (pos == std::string::npos) continue;
std::string key = line.substr(0, pos);
std::string val = line.substr(pos + 1);
auto trim = [](std::string &s) {
size_t start = s.find_first_not_of(" \t\r\n");
size_t end = s.find_last_not_of(" \t\r\n");
if (start == std::string::npos) { s.clear(); return; }
s = s.substr(start, end - start + 1);
};
trim(key);
trim(val);
if (key.empty()) continue;
#ifdef _WIN32
_putenv_s(key.c_str(), val.c_str());
#else
if (std::getenv(key.c_str()) == nullptr) setenv(key.c_str(), val.c_str(), 0);
#endif
}
}

static void load_env() {
const fs::path here = fs::current_path();
load_dotenv_if_present(here / ".env");
if (fs::exists(here.parent_path())) {
load_dotenv_if_present(here.parent_path() / ".env");
}
}

static std::optional<std::string> read_file_to_string(const fs::path &p) {
std::ifstream in(p, std::ios::binary);
if (!in) return std::nullopt;
std::string data((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
return data;
}

int main(int argc, char *argv[]) {
load_env();
if (argc < 2) {
std::cerr << "Usage: translated_pdf_text_json <input.pdf>\n";
return 1;
}
fs::path input_path(argv[1]);
if (!fs::exists(input_path)) {
std::cerr << "File not found: " << input_path << "\n";
return 1;
}

const char *api_key_c = std::getenv("PDFREST_API_KEY");
if (api_key_c == nullptr || std::string(api_key_c).empty()) {
std::cerr << "Missing required environment variable: PDFREST_API_KEY\n";
return 1;
}
std::string api_key = api_key_c;

const char *base_url_c = std::getenv("PDFREST_URL");
std::string base_url = base_url_c && std::string(base_url_c).size() ? base_url_c : std::string("https://api.pdfrest.com");
base_url = rtrim_slashes(base_url);

auto maybe_data = read_file_to_string(input_path);
if (!maybe_data) {
std::cerr << "Failed to read input file: " << input_path << "\n";
return 1;
}
std::string body = std::move(*maybe_data);

cpr::Header headers{{"Api-Key", api_key}, {"Accept", "application/json"}, {"Content-Type", "application/octet-stream"}, {"Content-Filename", input_path.filename().string()}};
auto res = cpr::Post(cpr::Url{base_url + "/upload"}, headers, cpr::Body{body});
if (res.error || res.status_code < 200 || res.status_code >= 300) {
std::cerr << "Upload failed (status " << res.status_code << "): " << res.error.message << "\n" << res.text << "\n";
return 1;
}
std::cout << res.text << "\n";

std::string uploaded_id;
try {
auto j = json::parse(res.text);
uploaded_id = j.at("files").at(0).at("id").get<std::string>();
} catch (const std::exception &e) {
std::cerr << "Failed to parse upload id: " << e.what() << "\n";
return 1;
}

// Translates text to American English. Format the output_language as a 2-3 character ISO 639 code,
// optionally with a region/script (e.g., 'en', 'es', 'zh-Hant', 'eng-US').
json payload = { {"id", uploaded_id}, {"output_language", "en-US"} };

cpr::Header tr_headers{{"Api-Key", api_key}, {"Accept", "application/json"}, {"Content-Type", "application/json"}};
auto tr_res = cpr::Post(cpr::Url{base_url + "/translated-pdf-text"}, tr_headers, cpr::Body{payload.dump()});
if (tr_res.error || tr_res.status_code < 200 || tr_res.status_code >= 300) {
std::cerr << "Translate failed (status " << tr_res.status_code << "): " << tr_res.error.message << "\n" << tr_res.text << "\n";
return 1;
}
std::cout << tr_res.text << "\n";
return 0;
}

4 changes: 4 additions & 0 deletions CPlusPlus/Endpoint Examples/Multipart Payload/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,8 @@ if (cpr_FOUND)
add_executable(summarized_pdf_text_multipart summarized_pdf_text.cpp)
target_link_libraries(summarized_pdf_text_multipart PRIVATE cpr::cpr)
target_compile_features(summarized_pdf_text_multipart PRIVATE cxx_std_20)

add_executable(translated_pdf_text_multipart translated_pdf_text.cpp)
target_link_libraries(translated_pdf_text_multipart PRIVATE cpr::cpr)
target_compile_features(translated_pdf_text_multipart PRIVATE cxx_std_20)
endif()
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/*
* What this sample does:
* - Translates PDF text content via multipart/form-data (file + options).
*
* Setup (environment):
* - Copy .env.example to .env
* - Set PDFREST_API_KEY=your_api_key_here
* - Optional: set PDFREST_URL to override the API region. For EU/GDPR compliance and proximity, use:
* PDFREST_URL=https://eu-api.pdfrest.com
* For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
*
* Usage:
* ./translated_pdf_text_multipart /path/to/input.pdf
*
* Output:
* - Prints the JSON response to stdout; non-2xx exits with concise error.
*/

#include <cpr/cpr.h>
#include <filesystem>
#include <iostream>
#include <fstream>
#include <cstdlib>

namespace fs = std::filesystem;

static std::string rtrim_slashes(std::string s) {
while (!s.empty() && (s.back() == '/' || s.back() == '\\')) s.pop_back();
return s;
}

static void load_dotenv_if_present(const fs::path &path) {
std::ifstream f(path);
if (!f.is_open()) return;
std::string line;
while (std::getline(f, line)) {
if (line.empty() || line[0] == '#') continue;
auto p = line.find('=');
if (p == std::string::npos) continue;
std::string k = line.substr(0, p);
std::string v = line.substr(p + 1);
auto trim = [](std::string &s) { size_t b = s.find_first_not_of(" \t\r\n"), e = s.find_last_not_of(" \t\r\n"); if (b == std::string::npos) { s.clear(); return; } s = s.substr(b, e - b + 1); };
trim(k); trim(v);
#ifdef _WIN32
_putenv_s(k.c_str(), v.c_str());
#else
if (!std::getenv(k.c_str())) setenv(k.c_str(), v.c_str(), 0);
#endif
}
}

static void load_env() {
auto here = fs::current_path();
load_dotenv_if_present(here / ".env");
if (fs::exists(here.parent_path())) load_dotenv_if_present(here.parent_path() / ".env");
}

int main(int argc, char **argv) {
load_env();
if (argc < 2) { std::cerr << "Usage: translated_pdf_text_multipart <input.pdf>\n"; return 1; }
fs::path input = argv[1];
if (!fs::exists(input)) { std::cerr << "File not found: " << input << "\n"; return 1; }
const char *key = getenv("PDFREST_API_KEY");
if (!key || !*key) { std::cerr << "Missing PDFREST_API_KEY\n"; return 1; }
std::string base = getenv("PDFREST_URL") ? getenv("PDFREST_URL") : "https://api.pdfrest.com";
base = rtrim_slashes(base);

cpr::Header hdr{{"Api-Key", key}, {"Accept", "application/json"}};
cpr::Multipart mp{
{"file", cpr::File{input.string()}},
// Translates text to American English. Format the output_language as a 2-3 character ISO 639 code,
// optionally with a region/script (e.g., 'en', 'es', 'zh-Hant', 'eng-US').
{"output_language", "en-US"}
};
auto res = cpr::Post(cpr::Url{base + "/translated-pdf-text"}, hdr, mp);
if (res.error || res.status_code < 200 || res.status_code >= 300) {
std::cerr << "Request failed (" << res.status_code << ")\n" << res.error.message << "\n" << res.text << "\n";
return 1;
}
std::cout << res.text << "\n";
return 0;
}

97 changes: 97 additions & 0 deletions DotNET/Endpoint Examples/JSON Payload/translated-pdf-text.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/*
* What this sample does:
* - Implements a command callable from Program.cs that uploads a file and
* then translates the content in the file via the JSON two-step flow.
* - Routes `dotnet run -- translated-pdf-text <inputFile>` to this module.
*
* Setup (environment):
* - Copy .env.example to .env
* - Set PDFREST_API_KEY=your_api_key_here
* - Optional: set PDFREST_URL to override the API region. For EU/GDPR compliance and proximity, use:
* PDFREST_URL=https://eu-api.pdfrest.com
* For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
*/

using Newtonsoft.Json.Linq;
using System.Text;

namespace Samples.EndpointExamples.JsonPayload
{
public static class TranslatedPdfText
{
public static async Task Execute(string[] args)
{
if (args == null || args.Length < 1)
{
Console.Error.WriteLine("translated-pdf-text requires <inputFile>");
Environment.Exit(1);
return;
}

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

var apiKey = Environment.GetEnvironmentVariable("PDFREST_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey))
{
Console.Error.WriteLine("Missing required environment variable: PDFREST_API_KEY");
Environment.Exit(1);
return;
}

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

using (var httpClient = new HttpClient { BaseAddress = new Uri(baseUrl) })
{
using (var uploadRequest = new HttpRequestMessage(HttpMethod.Post, "upload"))
{
uploadRequest.Headers.TryAddWithoutValidation("Api-Key", apiKey);
uploadRequest.Headers.Accept.Add(new("application/json"));

var uploadByteArray = File.ReadAllBytes(inputPath);
var uploadByteAryContent = new ByteArrayContent(uploadByteArray);
uploadByteAryContent.Headers.TryAddWithoutValidation("Content-Type", "application/octet-stream");
uploadByteAryContent.Headers.TryAddWithoutValidation("Content-Filename", Path.GetFileName(inputPath));

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 translateRequest = new HttpRequestMessage(HttpMethod.Post, "translated-pdf-text"))
{
translateRequest.Headers.TryAddWithoutValidation("Api-Key", apiKey);
translateRequest.Headers.Accept.Add(new("application/json"));
translateRequest.Headers.TryAddWithoutValidation("Content-Type", "application/json");

JObject parameterJson = new JObject
{
["id"] = uploadedID,
// Translates text to American English. Format the output_language as a 2-3 character ISO 639 code, optionally with a region/script (e.g., 'en', 'es', 'zh-Hant', 'eng-US').
["output_language"] = "en-US"
};

translateRequest.Content = new StringContent(parameterJson.ToString(), Encoding.UTF8, "application/json");
var translateResponse = await httpClient.SendAsync(translateRequest);

var translateResult = await translateResponse.Content.ReadAsStringAsync();

Console.WriteLine("Processing response received.");
Console.WriteLine(translateResult);
}
}
}
}
}
}

Loading