### C# Setup for PDF Generation API Source: https://docs.pdf.co/api-reference/pdf-from-html/template-id This C# code provides the basic setup for interacting with the PDF.co API, including API key and namespace declarations. It serves as a starting point for implementing PDF generation functionalities. ```csharp using System; using System.Collections.Generic; using System.IO; using System.Net; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace PDFcoApiExample { class Program { // The authentication key (API Key). // Get your own by registering at https://app.pdf.co const String API_KEY = "***********************************"; static void Main(string[] args) { // --TemplateID-- /* Please follow below steps to create your own HTML Template and get "templateId". 1. Add new html template in app.pdf.co/templates/html 2. Copy paste your html template code into this new template. Sample HTML templates can be found at "https://github.com/pdfdotco/pdf-co-api-samples/tree/master/PDF%20from%20HTML%20template/TEMPLATES-SAMPLES" 3. Save this new template 4. Copy it’s ID to clipboard 5. Now set ID of the template into “templateId” parameter */ ``` -------------------------------- ### Compress PDF using Node.js Source: https://docs.pdf.co/api-reference/pdf-compress This Node.js example shows how to compress a PDF file by first uploading it to pdf.co and then processing it. Ensure you have the 'request' module installed (`npm install request`) and replace '***********************************' with your API key. ```javascript /*jshint esversion: 6 */ var https = require("https"); var path = require("path"); var fs = require("fs"); // `request` module is required for file upload. // Use "npm install request" command to install. var request = require("request"); // The authentication key (API Key). // Get your own by registering at https://app.pdf.co const API_KEY = "***********************************"; // Source PDF file const SourceFile = "./sample.pdf"; // PDF document password. Leave empty for unprotected documents. const Password = ""; // Destination PDF file name const DestinationFile = "./result.pdf"; // 1. RETRIEVE PRESIGNED URL TO UPLOAD FILE. getPresignedUrl(API_KEY, SourceFile) .then(([uploadUrl, uploadedFileUrl]) => { // 2. UPLOAD THE FILE TO CLOUD. uploadFile(API_KEY, SourceFile, uploadUrl) .then(() => { // 3. COMPRESS UPLOADED PDF FILE compressPDF(API_KEY, uploadedFileUrl, Password, DestinationFile); }) .catch(e => { console.log(e); }); }) .catch(e => { console.log(e); }); function getPresignedUrl(apiKey, localFile) { return new Promise(resolve => { // Prepare request to `Get Presigned URL` API endpoint let queryPath = `/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name=${path.basename(SourceFile)}`; let reqOptions = { host: "api.pdf.co", path: encodeURI(queryPath), headers: { "x-api-key": API_KEY } }; // Send request https.get(reqOptions, (response) => { response.on("data", (d) => { let data = JSON.parse(d); if (data.error == false) { // Return presigned url we received resolve([data.presignedUrl, data.url]); } else { // Service reported error console.log("getPresignedUrl(): " + data.message); } }); }) .on("error", (e) => { // Request error console.log("getPresignedUrl(): " + e); }); }); } ``` -------------------------------- ### Python PDF.co API Setup Source: https://docs.pdf.co/api-reference/pdf-change-text-searchable/searchable Initializes the necessary libraries and configuration for interacting with the PDF.co Web API in Python. Ensure you have the 'requests' library installed. ```python import os import requests # pip install requests # The authentication key (API Key). # Get your own by registering at https://app.pdf.co API_KEY = "******************************************" # Base URL for PDF.co Web API requests BASE_URL = "https://api.pdf.co/v1" ``` -------------------------------- ### C# Profile Example Source: https://docs.pdf.co/api-reference/profiles Example of setting 'profiles' parameter with TrimSpaces and PreserveFormattingOnTextExtraction in C#. ```json { "profiles": "'TrimSpaces': 'True' , 'PreserveFormattingOnTextExtraction': 'True'" } ``` -------------------------------- ### Java SDK Example Source: https://docs.pdf.co/api-reference/pdf-from-html/convert Example of how to use the PDF.co Java SDK to convert HTML to PDF. ```APIDOC ## Convert HTML to PDF (Java) ### Description This code sample demonstrates how to convert an HTML string to a PDF file using the PDF.co API with Java. ### Method POST ### Endpoint https://api.pdf.co/v1/pdf/convert/from/html ### Parameters #### Request Body - **html** (string) - Required - The HTML content to convert. - **name** (string) - Optional - The name of the output PDF file. - **margins** (string) - Optional - CSS-style margins (e.g., "5px 5px 5px 5px"). - **paperSize** (string) - Optional - Paper size (e.g., "Letter", "A4"). - **orientation** (string) - Optional - Page orientation ("Portrait" or "Landscape"). - **printBackground** (boolean) - Optional - Whether to print background colors and images (defaults to true). - **async** (boolean) - Optional - Whether to process the request asynchronously. - **header** (string) - Optional - HTML content for the header. - **footer** (string) - Optional - HTML content for the footer. ### Request Example ```json { "html": "

Hello World

", "name": "result.pdf" } ``` ### Response #### Success Response (200) - **error** (boolean) - Indicates if an error occurred. - **message** (string) - A message describing the result or error. - **url** (string) - The URL of the generated PDF file if successful. #### Response Example ```json { "error": false, "message": "", "url": "https://cdn.pdf.co/pdf/result.pdf" } ``` ``` -------------------------------- ### Upload PDF and Find Text (C#) Source: https://docs.pdf.co/api-reference/pdf-find/basic This C# example shows how to upload a PDF and search for text using regular expressions. It covers getting a presigned URL, uploading the file, and then calling the PDF Text Search API. ```csharp using System; using System.Collections.Generic; using System.IO; using System.Net; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace PDFcoApiExample { class Program { // The authentication key (API Key). // Get your own by registering at https://app.pdf.co const String API_KEY = "*********************************"; // Source PDF file const string SourceFile = @".\sample.pdf"; // Comma-separated list of page indices (or ranges) to process. Leave empty for all pages. Example: '0,2-5,7-'. const string Pages = ""; // PDF document password. Leave empty for unprotected documents. const string Password = ""; // Search string. const string SearchString = @"\d{1,}\.\d\d"; // Regular expression to find numbers like '100.00' // Note: do not use `+` char in regex, but use `{1,}` instead. // `+` char is valid for URL and will not be escaped, and it will become a space char on the server side. // Enable regular expressions (Regex) const bool RegexSearch = true; static void Main(string[] args) { // Create standard .NET web client instance WebClient webClient = new WebClient(); // Set API Key webClient.Headers.Add("x-api-key", API_KEY); // 1. RETRIEVE THE PRESIGNED URL TO UPLOAD THE FILE. // * If you already have a direct file URL, skip to the step 3. // Prepare URL for `Get Presigned URL` API call string query = Uri.EscapeUriString(string.Format( "https://api.pdf.co/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name={0}", Path.GetFileName(SourceFile))); try { // Execute request string response = webClient.DownloadString(query); // Parse JSON response JObject json = JObject.Parse(response); if (json["error"].ToObject() == false) { // Get URL to use for the file upload string uploadUrl = json["presignedUrl"].ToString(); string uploadedFileUrl = json["url"].ToString(); // 2. UPLOAD THE FILE TO CLOUD. webClient.Headers.Add("content-type", "application/octet-stream"); webClient.UploadFile(uploadUrl, "PUT", SourceFile); // You can use UploadData() instead if your file is byte[] or Stream // 3. MAKE UPLOADED PDF FILE SEARCHABLE // URL for `PDF Text Search` API call // See documentation: https://docs.pdf.co string url = "https://api.pdf.co/v1/pdf/find"; // Prepare requests params as JSON Dictionary parameters = new Dictionary(); parameters.Add("password", Password); parameters.Add("pages", Pages); parameters.Add("url", uploadedFileUrl); parameters.Add("searchString", SearchString); parameters.Add("regexSearch", RegexSearch); ``` -------------------------------- ### C# SDK Example Source: https://docs.pdf.co/api-reference/pdf-split/by-text-search-or-barcode This C# code snippet shows how to set up the WebClient, add the API key, and prepare for making requests to the PDF.co API for splitting PDF documents. ```APIDOC ## C# SDK Example ### Description This C# code snippet shows how to set up the WebClient, add the API key, and prepare for making requests to the PDF.co API for splitting PDF documents. ### Method POST ### Endpoint `/pdf/split/by/text_search_or_barcode` ### Parameters #### Query Parameters - **name** (string) - Required - The name of the file to be processed. - **url** (string) - Required - The URL of the file to be processed. - **searchString** (string) - Optional - The text string to search for within the PDF to determine split points. - **barcodeType** (string) - Optional - The type of barcode to search for (e.g., "All", "QR", "Code128", "PDF417"). - **pages** (string) - Optional - Specifies the pages to process (e.g., "1-10", "1,3,5"). - **inline** (boolean) - Optional - If true, the result will be returned directly in the response; otherwise, a URL will be provided. - **async** (boolean) - Optional - If true, the request will be processed asynchronously. ### Request Example ```csharp using System; using System.Collections.Generic; using System.IO; using System.Net; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace PDFcoApiExample { class Program { // The authentication key (API Key). // Get your own by registering at https://app.pdf.co const String API_KEY = "***********************************"; // Source PDF file to split const string SourceFile = @".\sample.pdf"; static void Main(string[] args) { // Create standard .NET web client instance WebClient webClient = new WebClient(); // Set API Key webClient.Headers.Add("x-api-key", API_KEY); // ... (rest of the C# code for uploading, splitting, and downloading would go here) } } } ``` ``` -------------------------------- ### Example File Download URL Source: https://docs.pdf.co/api-reference/file-download An example of a complete URL for downloading a file using a specific filetoken. ```text https://api.pdf.co/v1/file/download/a1d30e75adf5eaa................. ``` -------------------------------- ### Example JSON Response for Upload URL GET Source: https://docs.pdf.co/api-reference/file-upload/upload-url-get This is a typical JSON response when successfully uploading a file from a URL using the GET method. It includes the direct URL to the file, expiration timestamp, status, and credit information. ```json { "url": "https://pdf-temp-files.s3.amazonaws.com/97415d1c45a04b29ac42c8dc01883316/sample.pdf", "error": false, "status": 200, "name": "sample.pdf", "remainingCredits": 77765 } ``` -------------------------------- ### Retrieve a Specific Template Source: https://docs.pdf.co/api-reference/documentparser/templates-id This example demonstrates how to retrieve details for a specific document parser template using its ID via a GET request. ```APIDOC ## GET /pdf/documentparser/templates/{id} ### Description Retrieves the details of a specific document parser template. ### Method GET ### Endpoint /pdf/documentparser/templates/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the template to retrieve. #### Request Example ```bash curl --location --request GET 'https://api.pdf.co/v1/pdf/documentparser/templates/1' \ --header 'Content-Type: application/json' \ --header 'x-api-key: {{x-api-key}}' \ --data-raw '' ``` ### Response #### Success Response (200) - **templateId** (integer) - The ID of the template. - **name** (string) - The name of the template. - **template** (string) - The template configuration in YAML format. - **createdDate** (string) - The date and time when the template was created. #### Response Example ```json { "templateId": 1, "name": "Invoice Template", "template": "field1:\n type: text\n regex: \"\\d+\"", "createdDate": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Python SDK Example Source: https://docs.pdf.co/api-reference/pdf-split/by-text-search-or-barcode This Python code demonstrates how to upload a file, initiate a split job based on text search or barcode, check the job status, and download the resulting PDF files. ```APIDOC ## Python SDK Example ### Description This Python code demonstrates how to upload a file, initiate a split job based on text search or barcode, check the job status, and download the resulting PDF files. ### Method POST ### Endpoint `/pdf/split/by/text_search_or_barcode` ### Parameters #### Query Parameters - **name** (string) - Required - The name of the file to be processed. - **url** (string) - Required - The URL of the file to be processed. - **searchString** (string) - Optional - The text string to search for within the PDF to determine split points. - **barcodeType** (string) - Optional - The type of barcode to search for (e.g., "All", "QR", "Code128", "PDF417"). - **pages** (string) - Optional - Specifies the pages to process (e.g., "1-10", "1,3,5"). - **inline** (boolean) - Optional - If true, the result will be returned directly in the response; otherwise, a URL will be provided. - **async** (boolean) - Optional - If true, the request will be processed asynchronously. ### Request Example ```python import requests import time import os import datetime # Define your API Key and Base URL API_KEY = "YOUR_API_KEY" BASE_URL = "https://api.pdf.co/v1" def uploadFile(fileName): """Uploads file to the cloud""" url = f"{BASE_URL}/file/upload/get-presigned-url?contenttype=application/octet-stream&name={os.path.basename(fileName)}" response = requests.get(url, headers={ "x-api-key": API_KEY }) if response.status_code == 200: json_data = response.json() if not json_data["error"]: uploadUrl = json_data["presignedUrl"] uploadedFileUrl = json_data["url"] with open(fileName, 'rb') as file: requests.put(uploadUrl, data=file, headers={ "x-api-key": API_KEY, "content-type": "application/octet-stream" }) return uploadedFileUrl else: print(json_data["message"]) else: print(f"Request error: {response.status_code} {response.reason}") return None def checkJobStatus(jobId): """Checks server job status""" url = f"{BASE_URL}/job/check?jobid={jobId}" response = requests.get(url, headers={ "x-api-key": API_KEY }) if response.status_code == 200: json_data = response.json() return json_data["status"] else: print(f"Request error: {response.status_code} {response.reason}") return None def main(): # Upload the source file sourceFileName = "sample.pdf" uploadedFileUrl = uploadFile(sourceFileName) if uploadedFileUrl: # Define parameters for splitting parameters = { "name": os.path.basename(sourceFileName), "url": uploadedFileUrl, "searchString": "Invoice", # Example: Split by text "Invoice" # "barcodeType": "QR", # Example: Or split by QR code "async": True } # Execute request to split PDF split_url = f"{BASE_URL}/pdf/split/by/text_search_or_barcode" response = requests.post(split_url, data=parameters, headers={ "x-api-key": API_KEY }) if response.status_code == 200: json_data = response.json() if not json_data["error"]: jobId = json_data["jobId"] resultFilePlaceholder = json_data["url"] # Check the job status in a loop while True: status = checkJobStatus(jobId) print(f"{datetime.datetime.now().strftime('%H:%M.%S')}: {status}") if status == "success": resJsonImgFiles = requests.get(resultFilePlaceholder) part = 1 for resultFileUrl in resJsonImgFiles.json(): r = requests.get(resultFileUrl, stream=True) localFileUrl = f"Page{part}.pdf" if r.status_code == 200: with open(localFileUrl, 'wb') as file: for chunk in r: file.write(chunk) print(f"Result file saved as \"{localFileUrl}\" file.") else: print(f"Request error: {response.status_code} {response.reason}") part = part + 1 break elif status == "working": time.sleep(3) else: print(status) break else: print(json_data["message"]) else: print(f"Request error: {response.status_code} {response.reason}") if __name__ == '__main__': main() ``` ``` -------------------------------- ### Check Background Job Status with Python Source: https://docs.pdf.co/api-reference/background-job-check This Python script uses the 'requests' library to check the status of a background job via the PDF.co API. It sends a GET request with the job ID and API key. Ensure you have the 'requests' library installed (`pip install requests`). ```python import os import requests # pip install requests # The authentication key (API Key). # Get your own by registering at https://app.pdf.co API_KEY = "******************************************" jobId = "******************************************" # Base URL for PDF.co Web API requests BASE_URL = "https://api.pdf.co/v1" url = f"{BASE_URL}/job/check?jobid={jobId}" response = requests.get(url, headers={ "x-api-key": API_KEY }) if (response.status_code == 200): json = response.json() return json["status"] else: print(f"Request error: {response.status_code} {response.reason}") ``` -------------------------------- ### Download File using CURL Source: https://docs.pdf.co/api-reference/file-download This example demonstrates how to download a file using a CURL command. Replace YOUR_FILETOKEN_HERE with your actual file token and ******************* with your API key. ```APIDOC ## GET /file/download/{fileToken} ### Description Downloads a file from PDF.co storage using its file token. ### Method GET ### Endpoint https://api.pdf.co/v1/file/download/YOUR_FILETOKEN_HERE ### Headers - **x-api-key** (string) - Required - Your PDF.co API key. ### Output Saves the downloaded file as `downloaded-file.pdf` in the current directory. ``` -------------------------------- ### C#: PDF Split Setup Source: https://docs.pdf.co/api-reference/pdf-split/by-text-search-or-barcode This C# code snippet sets up the necessary using directives, namespace, and constants for interacting with the PDF.co API, including the API key and source file path. ```csharp using System; using System.Collections.Generic; using System.IO; using System.Net; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace PDFcoApiExample { class Program { // The authentication key (API Key). // Get your own by registering at https://app.pdf.co const String API_KEY = "***********************************"; // Source PDF file to split const string SourceFile = @".\sample.pdf"; static void Main(string[] args) { // Create standard .NET web client instance WebClient webClient = new WebClient(); // Set API Key webClient.Headers.Add("x-api-key", API_KEY); ``` -------------------------------- ### Split PDF using Text Search (JavaScript/Node.js) Source: https://docs.pdf.co/api-reference/pdf-split/by-text-search-or-barcode This JavaScript code demonstrates how to split a PDF file using text search. It includes functions for getting a presigned URL, uploading the file, and then splitting it. Make sure to install the 'request' module using 'npm install request'. ```javascript var https = require("https"); var path = require("path"); var fs = require("fs"); // `request` module is required for file upload. // Use "npm install request" command to install. var request = require("request"); // The authentication key (API Key). // Get your own by registering at https://app.pdf.co const API_KEY = "***********************************"; // Source PDF file to split const SourceFile = "./sample.pdf"; // Split Search String const SplitText = "invoice number"; // 1. RETRIEVE PRESIGNED URL TO UPLOAD FILE. getPresignedUrl(API_KEY, SourceFile) .then(([uploadUrl, uploadedFileUrl]) => { // 2. UPLOAD THE FILE TO CLOUD. uploadFile(API_KEY, SourceFile, uploadUrl) .then(() => { // 3. SPLIT UPLOADED PDF splitPdf(API_KEY, uploadedFileUrl, SplitText); }) .catch(e => { console.log(e); }); }) .catch(e => { console.log(e); }); function getPresignedUrl(apiKey, localFile) { return new Promise(resolve => { // Prepare request to `Get Presigned URL` API endpoint let queryPath = `/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name=${path.basename(SourceFile)}`; let reqOptions = { host: "api.pdf.co", path: encodeURI(queryPath), headers: { "x-api-key": API_KEY } }; // Send request https.get(reqOptions, (response) => { response.on("data", (d) => { let data = JSON.parse(d); if (data.error == false) { // Return presigned url we received resolve([data.presignedUrl, data.url]); } else { // Service reported error console.log("getPresignedUrl(): " + data.message); } }); }) .on("error", (e) => { // Request error console.log("getPresignedUrl(): " + e); }); }); } function uploadFile(apiKey, localFile, uploadUrl) { return new Promise(resolve => { fs.readFile(SourceFile, (err, data) => { request({ method: "PUT", url: uploadUrl, body: data, headers: { "Content-Type": "application/octet-stream" } }, (err, res, body) => { if (!err) { resolve(); } else { console.log("uploadFile() request error: " + err); } }); }); }); } function splitPdf(apiKey, uploadedFileUrl, splitText) { // Prepare request to `Split PDF By Text` API endpoint var queryPath = `/v1/pdf/split2`; // JSON payload for api request var jsonPayload = JSON.stringify({ searchString: splitText, url: uploadedFileUrl, async: true }); ``` -------------------------------- ### Get PDF Info using JavaScript (Node.js) Source: https://docs.pdf.co/api-reference/pdf-info-reader This JavaScript code demonstrates how to upload a PDF file and then retrieve its information using the pdf.co API. It requires the 'request' module for file uploads. Make sure to install it using 'npm install request'. Replace '***********************************' with your API key. ```javascript var https = require("https"); var path = require("path"); var fs = require("fs"); // `request` module is required for file upload. // Use "npm install request" command to install. var request = require("request"); // The authentication key (API Key). // Get your own by registering at https://app.pdf.co const API_KEY = "***********************************"; // Source PDF file to get information const SourceFile = "./sample.pdf"; // 1. RETRIEVE THE PRESIGNED URL TO UPLOAD THE FILE. getPresignedUrl(API_KEY, SourceFile) .then(([uploadUrl, uploadedFileUrl]) => { // 2. UPLOAD THE FILE TO CLOUD. uploadFile(API_KEY, SourceFile, uploadUrl) .then(() => { // 3. GET INFORMATION FROM UPLOADED FILE getPdfInfo(API_KEY, uploadedFileUrl); }) .catch(e => { console.log(e); }); }) .catch(e => { console.log(e); }); function getPresignedUrl(apiKey, localFile) { return new Promise(resolve => { // Prepare request to `Get Presigned URL` API endpoint let queryPath = `/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name=${path.basename(SourceFile)}`; let reqOptions = { host: "api.pdf.co", path: encodeURI(queryPath), headers: { "x-api-key": API_KEY } }; // Send request https.get(reqOptions, (response) => { response.on("data", (d) => { let data = JSON.parse(d); if (data.error == false) { // Return presigned url we received resolve([data.presignedUrl, data.url]); } else { // Service reported error console.log("getPresignedUrl(): " + data.message); } }); }) .on("error", (e) => { // Request error console.log("getPresignedUrl(): " + e); }); }); } function uploadFile(apiKey, localFile, uploadUrl) { return new Promise(resolve => { fs.readFile(SourceFile, (err, data) => { request({ method: "PUT", url: uploadUrl, body: data, headers: { "Content-Type": "application/octet-stream" } }, (err, res, body) => { if (!err) { resolve(); } else { console.log("uploadFile() request error: " + e); } }); }); }); } function getPdfInfo(apiKey, uploadedFileUrl) { // Prepare URL for `PDF Info` API call var queryPath = `/v1/pdf/info`; // JSON payload for api request var jsonPayload = JSON.stringify({ url: uploadedFileUrl }); var reqOptions = { host: "api.pdf.co", method: "POST", path: queryPath, headers: { "x-api-key": apiKey, "Content-Type": "application/json", "Content-Length": Buffer.byteLength(jsonPayload, 'utf8') } }; // Send request var postRequest = https.request(reqOptions, (response) => { response.on("data", (d) => { response.setEncoding("utf8"); // Parse JSON response let data = JSON.parse(d); if (data.error == false) { // Display PDF document information for (var key in data.info) { console.log(`${key}: ${data.info[key]}`); } } else { // Service reported error console.log("getPdfInfo(): " + data.message); } }); }) .on("error", (e) => { // Request error console.log("getPdfInfo(): " + e); }); // Write request data postRequest.write(jsonPayload); postRequest.end(); } ``` -------------------------------- ### Download File using C# Source: https://docs.pdf.co/api-reference/file-download This C# example demonstrates how to download a file using the PDF.co API. It sets up a WebClient to handle the download process. Replace YOUR_FILETOKEN_HERE and your API key. ```APIDOC ## GET /file/download/{fileToken} ### Description Downloads a file from PDF.co storage using its file token via C#. ### Method GET ### Endpoint https://api.pdf.co/v1/file/download/YOUR_FILETOKEN_HERE ### Headers - **x-api-key** (string) - Required - Your PDF.co API key. ### Output Saves the downloaded file as `downloaded-file.pdf` in the current directory. ``` -------------------------------- ### Optimize PDF using JavaScript (Node.js) Source: https://docs.pdf.co/api-reference/pdf-optimize This JavaScript code demonstrates how to optimize a PDF file using the pdf.co API in a Node.js environment. It includes steps for getting a presigned URL, uploading the file, and then optimizing it. Make sure to install the 'request' module using 'npm install request'. ```javascript /*jshint esversion: 6 */ var https = require("https"); var path = require("path"); var fs = require("fs"); // `request` module is required for file upload. // Use "npm install request" command to install. var request = require("request"); // The authentication key (API Key). // Get your own by registering at https://app.pdf.co const API_KEY = "***********************************"; // Source PDF file const SourceFile = "./sample.pdf"; // PDF document password. Leave empty for unprotected documents. const Password = ""; // Destination PDF file name const DestinationFile = "./result.pdf"; // 1. RETRIEVE PRESIGNED URL TO UPLOAD FILE. getPresignedUrl(API_KEY, SourceFile) .then(([uploadUrl, uploadedFileUrl]) => { // 2. UPLOAD THE FILE TO CLOUD. uploadFile(API_KEY, SourceFile, uploadUrl) .then(() => { // 3. OPTIMIZE UPLOADED PDF FILE optimizePdf(API_KEY, uploadedFileUrl, Password, DestinationFile); }) .catch(e => { console.log(e); }); }) .catch(e => { console.log(e); }); function getPresignedUrl(apiKey, localFile) { return new Promise(resolve => { // Prepare request to `Get Presigned URL` API endpoint let queryPath = `/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name=${path.basename(SourceFile)}`; let reqOptions = { host: "api.pdf.co", path: encodeURI(queryPath), headers: { "x-api-key": API_KEY } }; // Send request https.get(reqOptions, (response) => { response.on("data", (d) => { let data = JSON.parse(d); if (data.error == false) { // Return presigned url we received resolve([data.presignedUrl, data.url]); } else { // Service reported error console.log("getPresignedUrl(): " + data.message); } }); }) .on("error", (e) => { // Request error console.log("getPresignedUrl(): " + e); }); }); } function uploadFile(apiKey, localFile, uploadUrl) { return new Promise(resolve => { fs.readFile(SourceFile, (err, data) => { request({ method: "PUT", url: uploadUrl, body: data, headers: { "Content-Type": "application/octet-stream" } }, (err, res, body) => { if (!err) { resolve(); } else { console.log("uploadFile() request error: " + e); } }); }); }); } function optimizePdf(apiKey, uploadedFileUrl, password, destinationFile) { // Prepare request to `Optimize PDF` API endpoint var queryPath = `/v1/pdf/optimize`; // JSON payload for api request var jsonPayload = JSON.stringify({ name: path.basename(destinationFile), password: password, url: uploadedFileUrl, async: true }); var reqOptions = { host: "api.pdf.co", method: "POST", path: queryPath, headers: { "x-api-key": apiKey, "Content-Type": "application/json", "Content-Length": Buffer.byteLength(jsonPayload, 'utf8') } }; // Send request var postRequest = https.request(reqOptions, (response) => { response.on("data", (d) => { response.setEncoding("utf8"); // Parse JSON response let data = JSON.parse(d); console.log(`Job #${data.jobId} has been created!`); ``` -------------------------------- ### CURL - Defining Configuration Options Source: https://docs.pdf.co/api-reference/pdf-compress An advanced example showing how to compress a PDF with detailed configuration options for image processing and saving. ```APIDOC ## POST /v2/pdf/compress (with config) ### Description Compresses a PDF file from a given URL with advanced configuration options for image processing and saving. ### Method POST ### Endpoint https://api.pdf.co/v2/pdf/compress ### Parameters #### Request Body - **async** (boolean) - Optional - If true, the operation will be performed asynchronously. - **url** (string) - Required - The URL of the PDF file to compress. - **config** (object) - Optional - Configuration object for compression settings. - **images** (object) - Settings for image compression. - **color** (object) - Settings for color images. - **skip** (boolean) - If true, skip color image processing. - **downsample** (object) - Downsampling settings for color images. - **skip** (boolean) - If true, skip downsampling. - **downsample_ppi** (integer) - Target PPI for downsampling. - **threshold_ppi** (integer) - PPI threshold for downsampling. - **compression** (object) - Compression settings for color images. - **skip** (boolean) - If true, skip compression. - **compression_format** (string) - Compression format (e.g., 'jpeg', 'jpeg2000'). - **compression_params** (object) - Parameters for the chosen compression format. - **quality** (integer) - JPEG quality (0-100). - **quality_mode** (string) - JPEG2000 quality mode ('dB', 'layers'). - **quality_layers** (array) - JPEG2000 quality layers. - **grayscale** (object) - Settings for grayscale images (similar structure to color images). - **monochrome** (object) - Settings for monochrome images. - **skip** (boolean) - If true, skip monochrome image processing. - **downsample** (object) - Downsampling settings for monochrome images. - **skip** (boolean) - If true, skip downsampling. - **downsample_ppi** (integer) - Target PPI for downsampling. - **threshold_ppi** (integer) - PPI threshold for downsampling. - **compression** (object) - Compression settings for monochrome images. - **skip** (boolean) - If true, skip compression. - **compression_format** (string) - Compression format (e.g., 'ccitt_g4'). - **compression_params** (object) - Parameters for the chosen compression format. - **save** (object) - Settings for saving the PDF. - **garbage** (integer) - Value to control garbage collection during save. ### Request Example ```json { "async": false, "url": "https://pdfco-test-files.s3.us-west-2.amazonaws.com/pdf-compress/sample.pdf", "config": { "images": { "color": { "skip": false, "downsample": { "skip": false, "downsample_ppi": 150, "threshold_ppi": 225 }, "compression": { "skip": false, "compression_format": "jpeg", "compression_params": { "quality": 50 } } }, "grayscale": { "skip": false, "downsample": { "skip": false, "downsample_ppi": 150, "threshold_ppi": 225 }, "compression": { "skip": false, "compression_format": "jpeg2000", "compression_params": { "quality_mode": "dB", "quality_layers": [36.0] } } }, "monochrome": { "skip": false, "downsample": { "skip": false, "downsample_ppi": 300, "threshold_ppi": 450 }, "compression": { "skip": false, "compression_format": "ccitt_g4", "compression_params": {} } } }, "save": { "garbage": 4 } } } ``` ### Response #### Success Response (200) - **status** (string) - The status of the operation. - **name** (string) - The name of the compressed file. - **downloadUrl** (string) - The URL to download the compressed PDF. - **error** (boolean) - Indicates if an error occurred. - **message** (string) - A message describing the result of the operation. - **remainingCredits** (integer) - The number of remaining credits for the account. #### Response Example ```json { "error": false, "message": "", "remainingCredits": 100, "name": "result.pdf", "downloadUrl": "https://pdfco-test-files.s3.us-west-2.amazonaws.com/result.pdf" } ``` ``` -------------------------------- ### C# PDF Text Search Example Source: https://docs.pdf.co/api-reference/pdf-find Use this C# code to upload a PDF and search for text using regular expressions. Ensure you have the Newtonsoft.Json library installed. ```csharp using System; using System.Collections.Generic; using System.IO; using System.Net; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace PDFcoApiExample { class Program { // The authentication key (API Key). // Get your own by registering at https://app.pdf.co const String API_KEY = "*********************************"; // Source PDF file const string SourceFile = @".\sample.pdf"; // Comma-separated list of page indices (or ranges) to process. Leave empty for all pages. Example: '0,2-5,7-'. const string Pages = ""; // PDF document password. Leave empty for unprotected documents. const string Password = ""; // Search string. const string SearchString = @"\d{1,}\.\d\d"; // Regular expression to find numbers like '100.00' // Note: do not use `+` char in regex, but use `{1,}` instead. // `+` char is valid for URL and will not be escaped, and it will become a space char on the server side. // Enable regular expressions (Regex) const bool RegexSearch = true; static void Main(string[] args) { // Create standard .NET web client instance WebClient webClient = new WebClient(); // Set API Key webClient.Headers.Add("x-api-key", API_KEY); // 1. RETRIEVE THE PRESIGNED URL TO UPLOAD THE FILE. // * If you already have a direct file URL, skip to the step 3. // Prepare URL for `Get Presigned URL` API call string query = Uri.EscapeUriString(string.Format( "https://api.pdf.co/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name={0}", Path.GetFileName(SourceFile))); try { // Execute request string response = webClient.DownloadString(query); // Parse JSON response JObject json = JObject.Parse(response); if (json["error"].ToObject() == false) { // Get URL to use for the file upload string uploadUrl = json["presignedUrl"].ToString(); string uploadedFileUrl = json["url"].ToString(); // 2. UPLOAD THE FILE TO CLOUD. webClient.Headers.Add("content-type", "application/octet-stream"); webClient.UploadFile(uploadUrl, "PUT", SourceFile); // You can use UploadData() instead if your file is byte[] or Stream // 3. MAKE UPLOADED PDF FILE SEARCHABLE // URL for `PDF Text Search` API call // See documentation: https://docs.pdf.co string url = "https://api.pdf.co/v1/pdf/find"; // Prepare requests params as JSON Dictionary parameters = new Dictionary(); parameters.Add("password", Password); parameters.Add("pages", Pages); parameters.Add("url", uploadedFileUrl); parameters.Add("searchString", SearchString); parameters.Add("regexSearch", RegexSearch); // Convert dictionary of params to JSON string jsonPayload = JsonConvert.SerializeObject(parameters); // Execute POST request with JSON payload response = webClient.UploadString(url, jsonPayload); // Parse JSON response json = JObject.Parse(response); if (json["error"].ToObject() == false) { foreach (JToken item in json["body"]) { Console.WriteLine($"Found text \"{item["text"]}\" at coordinates {item["left"]}, {item["top"]}"); } } else { Console.WriteLine(json["message"].ToString()); } } else { Console.WriteLine(json["message"].ToString()); } } catch (WebException ex) { Console.WriteLine(ex.ToString()); } webClient.Dispose(); Console.WriteLine(); Console.WriteLine("Press any key..."); Console.ReadKey(); } } } ``` -------------------------------- ### Account Balance Response Example Source: https://docs.pdf.co/api-reference/account-balance-info This is an example of a successful response from the account balance endpoint, showing the number of remaining credits. ```json { "remainingCredits": 99795868 } ``` -------------------------------- ### Make PDF Searchable using JavaScript (Node.js) Source: https://docs.pdf.co/api-reference/pdf-change-text-searchable/searchable This JavaScript code snippet shows how to make a PDF searchable using the pdf.co API. It includes functions to get a presigned URL for uploading, upload the file, and then make the PDF searchable. Ensure you have the 'request' module installed (`npm install request`). ```javascript var https = require("https"); var path = require("path"); var fs = require("fs"); // `request` module is required for file upload. // Use "npm install request" command to install. var request = require("request"); // The authentication key (API Key). // Get your own by registering at https://app.pdf.co const API_KEY = "***********************************"; // Source PDF file const SourceFile = "./sample.pdf"; // Comma-separated list of page indices (or ranges) to process. Leave empty for all pages. Example: '0,2-5,7-'. const Pages = ""; // PDF document password. Leave empty for unprotected documents. const Password = ""; // OCR language. "eng", "fra", "deu", "spa" supported currently. Let us know if you need more. const Language = "eng"; // Destination PDF file name const DestinationFile = "./result.pdf"; // 1. RETRIEVE PRESIGNED URL TO UPLOAD FILE. getPresignedUrl(API_KEY, SourceFile) .then(([uploadUrl, uploadedFileUrl]) => { // 2. UPLOAD THE FILE TO CLOUD. uploadFile(API_KEY, SourceFile, uploadUrl) .then(() => { // 3. MAKE UPLOADED PDF FILE SEARCHABLE makePdfSearchable(API_KEY, uploadedFileUrl, Password, Pages, Language, DestinationFile); }) .catch(e => { console.log(e); }); }) .catch(e => { console.log(e); }); function getPresignedUrl(apiKey, localFile) { return new Promise(resolve => { // Prepare request to `Get Presigned URL` API endpoint let queryPath = `/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name=${path.basename(SourceFile)}`; let reqOptions = { host: "api.pdf.co", path: encodeURI(queryPath), headers: { "x-api-key": API_KEY } }; // Send request https.get(reqOptions, (response) => { response.on("data", (d) => { let data = JSON.parse(d); if (data.error == false) { // Return presigned url we received resolve([data.presignedUrl, data.url]); } else { // Service reported error console.log("getPresignedUrl(): " + data.message); } }); }) .on("error", (e) => { // Request error console.log("getPresignedUrl(): " + e); }); }); } ```