Sample request
CURL
curl --location --request POST 'https://api.pdf.co/v1/pdf/split' \
--header 'Content-Type: application/json' \
--header 'x-api-key: *******************' \
--data-raw '{
"url": "https://pdfco-test-files.s3.us-west-2.amazonaws.com/pdf-split/sample.pdf",
"pages": "1-2,3-",
"inline": true,
"name": "result.pdf",
"async": false
}'
import os
import requests # pip install requests
import time
import datetime
# 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"
# Source PDF file
SourceFile = ".\\sample.pdf"
# Comma-separated list of page numbers (or ranges) to process. Example: '1,3-5,7-'.
Pages = "1-2,3-"
# (!) Make asynchronous job
Async = True
def main(args = None):
uploadedFileUrl = uploadFile(SourceFile)
if (uploadedFileUrl != None):
splitPDF(uploadedFileUrl)
def splitPDF(uploadedFileUrl):
"""Split PDF using PDF.co Web API"""
# Prepare requests params as JSON
# See documentation: https://developer.pdf.co/
parameters = {}
parameters["async"] = Async
parameters["pages"] = Pages
parameters["url"] = uploadedFileUrl
# Prepare URL for 'Split PDF' API request
url = "{}/pdf/split".format(BASE_URL)
# Execute request and get response as JSON
response = requests.post(url, data=parameters, headers={ "x-api-key": API_KEY })
if (response.status_code == 200):
json = response.json()
if json["error"] == False:
# Asynchronous job ID
jobId = json["jobId"]
# URL of the result file
resultFilePlaceholder = json["url"]
# Check the job status in a loop.
# If you don't want to pause the main thread you can rework the code
# to use a separate thread for the status checking and completion.
while True:
status = checkJobStatus(jobId) # Possible statuses: "working", "failed", "aborted", "success".
# Display timestamp and status (for demo purposes)
print(datetime.datetime.now().strftime("%H:%M.%S") + ": " + status)
if status == "success":
resJsonImgFiles = requests.get(resultFilePlaceholder)
# Download generated PDF files
part = 1
for resultFileUrl in resJsonImgFiles.json():
# Download Result File
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":
# Pause for a few seconds
time.sleep(3)
else:
print(status)
break
else:
# Show service reported error
print(json["message"])
else:
print(f"Request error: {response.status_code} {response.reason}")
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 = response.json()
return json["status"]
else:
print(f"Request error: {response.status_code} {response.reason}")
return None
def uploadFile(fileName):
"""Uploads file to the cloud"""
# 1. RETRIEVE PRESIGNED URL TO UPLOAD FILE.
# Prepare URL for 'Get Presigned URL' API request
url = "{}/file/upload/get-presigned-url?contenttype=application/octet-stream&name={}".format(
BASE_URL, os.path.basename(fileName))
# Execute request and get response as JSON
response = requests.get(url, headers={ "x-api-key": API_KEY })
if (response.status_code == 200):
json = response.json()
if json["error"] == False:
# URL to use for file upload
uploadUrl = json["presignedUrl"]
# URL for future reference
uploadedFileUrl = json["url"]
# 2. UPLOAD FILE TO CLOUD.
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:
# Show service reported error
print(json["message"])
else:
print(f"Request error: {response.status_code} {response.reason}")
return None
if __name__ == '__main__':
main()
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";
// Comma-separated list of page numbers (or ranges) to process. Example: '1,3-5,7-'.
const string Pages = "1-2,3-";
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<bool>() == 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
webClient.Headers.Remove("content-type");
// 3. SPLIT UPLOADED PDF
// URL for `Split PDF` API call
var url = "https://api.pdf.co/v1/pdf/split";
// Prepare requests params as JSON
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("pages", Pages);
parameters.Add("url", uploadedFileUrl);
// 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<bool>() == false)
{
// Download generated PDF files
int part = 1;
foreach (JToken token in json["urls"])
{
string resultFileUrl = token.ToString();
string localFileName = String.Format(@".\part{0}.pdf", part);
webClient.DownloadFile(resultFileUrl, localFileName);
Console.WriteLine("Downloaded \"{0}\".", localFileName);
part++;
}
}
else
{
Console.WriteLine(json["message"].ToString());
}
}
else
{
Console.WriteLine(json["message"].ToString());
}
}
catch (WebException e)
{
Console.WriteLine(e.ToString());
}
webClient.Dispose();
Console.WriteLine();
Console.WriteLine("Press any key...");
Console.ReadKey();
}
}
}
package com.company;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import okhttp3.*;
import java.io.*;
import java.net.*;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main
{
// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co
final static String API_KEY = "***********************************";
// Source PDF file to split
final static Path SourceFile = Paths.get(".\\sample.pdf");
// Comma-separated list of page numbers (or ranges) to process. Example: '1,3-5,7-'.
final static String Pages = "1-2,3-";
public static void main(String[] args) throws IOException
{
// Create HTTP client instance
OkHttpClient webClient = new OkHttpClient();
// 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 = String.format(
"https://api.pdf.co/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name=%s",
SourceFile.getFileName());
// Prepare request
Request request = new Request.Builder()
.url(query)
.addHeader("x-api-key", API_KEY) // (!) Set API Key
.build();
// Execute request
Response response = webClient.newCall(request).execute();
if (response.code() == 200)
{
// Parse JSON response
JsonObject json = new JsonParser().parse(response.body().string()).getAsJsonObject();
boolean error = json.get("error").getAsBoolean();
if (!error)
{
// Get URL to use for the file upload
String uploadUrl = json.get("presignedUrl").getAsString();
// Get URL of uploaded file to use with later API calls
String uploadedFileUrl = json.get("url").getAsString();
// 2. UPLOAD THE FILE TO CLOUD.
if (uploadFile(webClient, API_KEY, uploadUrl, SourceFile))
{
// 3. SPLIT UPLOADED PDF
SplitPdf(webClient, API_KEY, Pages, uploadedFileUrl);
}
}
else
{
// Display service reported error
System.out.println(json.get("message").getAsString());
}
}
else
{
// Display request error
System.out.println(response.code() + " " + response.message());
}
}
public static void SplitPdf(OkHttpClient webClient, String apiKey, String pages, String uploadedFileUrl) throws IOException
{
// Prepare URL for `Split PDF` API call
String query = "https://api.pdf.co/v1/pdf/split";
// Make correctly escaped (encoded) URL
URL url = null;
try
{
url = new URI(null, query, null).toURL();
}
catch (URISyntaxException e)
{
e.printStackTrace();
}
// Create JSON payload
String jsonPayload = String.format("{\"pages\": \"%s\", \"url\": \"%s\"}",
pages,
uploadedFileUrl);
// Prepare request body
RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonPayload);
// Prepare request
Request request = new Request.Builder()
.url(url)
.addHeader("x-api-key", API_KEY) // (!) Set API Key
.addHeader("Content-Type", "application/json")
.post(body)
.build();
// Execute request
Response response = webClient.newCall(request).execute();
if (response.code() == 200)
{
// Parse JSON response
JsonObject json = new JsonParser().parse(response.body().string()).getAsJsonObject();
boolean error = json.get("error").getAsBoolean();
if (!error)
{
// Download generated PDF files
JsonArray urls = json.get("urls").getAsJsonArray();
int part = 1;
for (JsonElement element: urls)
{
String resultFileUrl = element.getAsString();
String localFileName = String.format(".\\part%s.pdf", part);
downloadFile(webClient, resultFileUrl, Paths.get(localFileName).toFile());
System.out.println(String.format("Splitted part saved as \"%s\".", localFileName));
part++;
}
}
else
{
// Display service reported error
System.out.println(json.get("message").getAsString());
}
}
else
{
// Display request error
System.out.println(response.code() + " " + response.message());
}
}
public static boolean uploadFile(OkHttpClient webClient, String apiKey, String url, Path sourceFile) throws IOException
{
// Prepare request body
RequestBody body = RequestBody.create(MediaType.parse("application/octet-stream"), sourceFile.toFile());
// Prepare request
Request request = new Request.Builder()
.url(url)
.addHeader("x-api-key", apiKey) // (!) Set API Key
.addHeader("content-type", "application/octet-stream")
.put(body)
.build();
// Execute request
Response response = webClient.newCall(request).execute();
return (response.code() == 200);
}
public static void downloadFile(OkHttpClient webClient, String url, File destinationFile) throws IOException
{
// Prepare request
Request request = new Request.Builder()
.url(url)
.build();
// Execute request
Response response = webClient.newCall(request).execute();
byte[] fileBytes = response.body().bytes();
// Save downloaded bytes to file
OutputStream output = new FileOutputStream(destinationFile);
output.write(fileBytes);
output.flush();
output.close();
response.close();
}
}
<?php
// Note: For input files larger than 200 KB, we recommend using async mode by setting the "async" parameter to true.
// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co
$API_KEY = "***********************************";
// Source PDF file to split
$SourceFile = "./sample.pdf";
// Comma-separated list of page numbers (or ranges) to process. Example: '1,3-5,7-'.
$Pages = "1-2,3-";
// 1. RETRIEVE THE PRESIGNED URL TO UPLOAD THE FILE.
// * If you already have the direct PDF file link, go to the step 3.
$presignedUrls = getPresignedUrl($API_KEY, $SourceFile);
if ($presignedUrls !== null) {
list($uploadUrl, $uploadedFileUrl) = $presignedUrls;
// 2. UPLOAD THE FILE TO CLOUD.
if (uploadFile($API_KEY, $SourceFile, $uploadUrl)) {
// 3. SPLIT UPLOADED PDF
splitPdf($API_KEY, $uploadedFileUrl, $Pages);
}
}
function getPresignedUrl($apiKey, $localFile)
{
// Prepare URL for `Get Presigned URL` API call
$url = "https://api.pdf.co/v1/file/upload/get-presigned-url"
. "?contenttype=application/octet-stream"
. "&name=" . urlencode(basename($localFile));
// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Execute request
$result = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlError = curl_error($curl);
curl_close($curl);
if ($result === false) {
// Display CURL error
echo "getPresignedUrl(): " . $curlError . PHP_EOL;
return null;
}
if ($statusCode != 200) {
// Display request error
echo "getPresignedUrl(): request error " . $statusCode . PHP_EOL . $result . PHP_EOL;
return null;
}
$json = json_decode($result, true);
if (!empty($json["error"])) {
// Display service reported error
echo "getPresignedUrl(): " . $json["message"] . PHP_EOL;
return null;
}
// Return the URL to use for the file upload, and the URL of the uploaded
// file to use with later API calls
return array($json["presignedUrl"], $json["url"]);
}
function uploadFile($apiKey, $localFile, $uploadUrl)
{
$fileHandle = fopen($localFile, "rb");
if ($fileHandle === false) {
echo "uploadFile(): unable to open " . $localFile . PHP_EOL;
return false;
}
// Create request. The presigned URL expects a raw PUT of the file bytes.
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $uploadUrl);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey, "content-type: application/octet-stream"));
curl_setopt($curl, CURLOPT_PUT, true);
curl_setopt($curl, CURLOPT_INFILE, $fileHandle);
curl_setopt($curl, CURLOPT_INFILESIZE, filesize($localFile));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Execute request
$result = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlError = curl_error($curl);
curl_close($curl);
fclose($fileHandle);
if ($result === false) {
// Display CURL error
echo "uploadFile(): " . $curlError . PHP_EOL;
return false;
}
if ($statusCode != 200) {
// Display request error
echo "uploadFile(): request error " . $statusCode . PHP_EOL . $result . PHP_EOL;
return false;
}
return true;
}
function splitPdf($apiKey, $uploadedFileUrl, $pages)
{
// Prepare URL for `Split PDF` API call
$url = "https://api.pdf.co/v1/pdf/split";
// Prepare requests params
$parameters = array();
$parameters["pages"] = $pages;
$parameters["url"] = $uploadedFileUrl;
// Create Json payload
$data = json_encode($parameters);
// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey, "Content-Type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Execute request
$result = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlError = curl_error($curl);
curl_close($curl);
if ($result === false) {
// Display CURL error
echo "splitPdf(): " . $curlError . PHP_EOL;
return;
}
if ($statusCode != 200) {
// Display request error
echo "splitPdf(): request error " . $statusCode . PHP_EOL . $result . PHP_EOL;
return;
}
$json = json_decode($result, true);
if (!empty($json["error"])) {
// Display service reported error
echo "splitPdf(): " . $json["message"] . PHP_EOL;
return;
}
// Download generated PDF files
$part = 1;
foreach ($json["urls"] as $resultFileUrl) {
$destinationFile = "./part" . $part . ".pdf";
if (downloadFile($resultFileUrl, $destinationFile)) {
echo "Downloaded \"" . $destinationFile . "\"." . PHP_EOL;
}
$part++;
}
}
function downloadFile($url, $destinationFile)
{
// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
// Execute request
$result = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlError = curl_error($curl);
curl_close($curl);
if ($result === false) {
// Display CURL error
echo "downloadFile(): " . $curlError . PHP_EOL;
return false;
}
if ($statusCode != 200) {
// Display request error
echo "downloadFile(): request error " . $statusCode . PHP_EOL . $result . PHP_EOL;
return false;
}
// Write the file only after a successful response so failures leave no file behind
if (file_put_contents($destinationFile, $result) === false) {
echo "downloadFile(): unable to create " . $destinationFile . PHP_EOL;
return false;
}
return true;
}
?>
{
"urls": [
"https://pdf-temp-files.s3.amazonaws.com/1e9a7f2c46834160903276716424382b/result_page1-2.pdf",
"https://pdf-temp-files.s3.amazonaws.com/c976b9f89a2e460786a3d5c0deeeef67/result_page3-4.pdf"
],
"pageCount": 4,
"error": false,
"status": 200,
"name": "result.pdf",
"remainingCredits": 98441
}
{
"error": true,
"status": 400,
"message": "Bad request. Typically due to bad input parameters or unreachable input URLs (e.g., access restrictions like login or password)."
}
{
"status": "error",
"errorCode": 401,
"error": true,
"message": "Please provide your API key as \"x-api-key\" header parameter for GET or POST request or as username (\"curl -u <apikey>\") or as url parameter (not recommended). Get your API key at https://app.pdf.co/account"
}
{
"status": "error",
"errorCode": 402,
"error": true,
"message": "Not enough credits, subscription expired or metered use is not allowed. Please review credits on your account at https://app.pdf.co/subscriptions"
}
{
"error": true,
"status": 403,
"message": "Access forbidden for input URL."
}
{
"error": true,
"status": 404,
"message": "The requested resource could not be found."
}
{
"error": true,
"status": 408,
"message": "The server timed out waiting for the request."
}
{
"error": true,
"message": "Too many requests. Your current limit is <limit> requests per minute. Please try again later"
}
{
"error": true,
"status": 441,
"message": "Invalid Password. Password protected document."
}
{
"error": true,
"status": 442,
"message": "Input document is damaged or of incorrect type."
}
{
"error": true,
"status": 443,
"message": "Permissions. The operation is prohibited by document security settings."
}
{
"error": true,
"status": 444,
"message": "Profiles parsing error. Please ensure that the configuration is supported."
}
{
"error": true,
"status": 445,
"message": "Timeout error. For large documents, use asynchronous mode (async=true) and check status via /job/check."
}
{
"error": true,
"status": 446,
"message": "Some files required for conversion are missing."
}
{
"error": true,
"status": 449,
"message": "Invalid index range. Page index is out of range."
}
{
"error": true,
"status": 450,
"message": "Invalid page range specified."
}
{
"error": true,
"status": 452,
"message": "Invalid URL."
}
{
"error": true,
"status": 454,
"message": "Invalid parameters."
}
{
"error": true,
"status": 500,
"message": "Something went wrong. Please try again or contact support."
}
CURL
curl --location --request POST 'https://api.pdf.co/v1/pdf/split' \
--header 'Content-Type: application/json' \
--header 'x-api-key: *******************' \
--data-raw '{
"url": "https://pdfco-test-files.s3.us-west-2.amazonaws.com/pdf-split/sample.pdf",
"pages": "1-2,3-",
"inline": true,
"name": "result.pdf",
"async": false
}'
import os
import requests # pip install requests
import time
import datetime
# 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"
# Source PDF file
SourceFile = ".\\sample.pdf"
# Comma-separated list of page numbers (or ranges) to process. Example: '1,3-5,7-'.
Pages = "1-2,3-"
# (!) Make asynchronous job
Async = True
def main(args = None):
uploadedFileUrl = uploadFile(SourceFile)
if (uploadedFileUrl != None):
splitPDF(uploadedFileUrl)
def splitPDF(uploadedFileUrl):
"""Split PDF using PDF.co Web API"""
# Prepare requests params as JSON
# See documentation: https://developer.pdf.co/
parameters = {}
parameters["async"] = Async
parameters["pages"] = Pages
parameters["url"] = uploadedFileUrl
# Prepare URL for 'Split PDF' API request
url = "{}/pdf/split".format(BASE_URL)
# Execute request and get response as JSON
response = requests.post(url, data=parameters, headers={ "x-api-key": API_KEY })
if (response.status_code == 200):
json = response.json()
if json["error"] == False:
# Asynchronous job ID
jobId = json["jobId"]
# URL of the result file
resultFilePlaceholder = json["url"]
# Check the job status in a loop.
# If you don't want to pause the main thread you can rework the code
# to use a separate thread for the status checking and completion.
while True:
status = checkJobStatus(jobId) # Possible statuses: "working", "failed", "aborted", "success".
# Display timestamp and status (for demo purposes)
print(datetime.datetime.now().strftime("%H:%M.%S") + ": " + status)
if status == "success":
resJsonImgFiles = requests.get(resultFilePlaceholder)
# Download generated PDF files
part = 1
for resultFileUrl in resJsonImgFiles.json():
# Download Result File
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":
# Pause for a few seconds
time.sleep(3)
else:
print(status)
break
else:
# Show service reported error
print(json["message"])
else:
print(f"Request error: {response.status_code} {response.reason}")
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 = response.json()
return json["status"]
else:
print(f"Request error: {response.status_code} {response.reason}")
return None
def uploadFile(fileName):
"""Uploads file to the cloud"""
# 1. RETRIEVE PRESIGNED URL TO UPLOAD FILE.
# Prepare URL for 'Get Presigned URL' API request
url = "{}/file/upload/get-presigned-url?contenttype=application/octet-stream&name={}".format(
BASE_URL, os.path.basename(fileName))
# Execute request and get response as JSON
response = requests.get(url, headers={ "x-api-key": API_KEY })
if (response.status_code == 200):
json = response.json()
if json["error"] == False:
# URL to use for file upload
uploadUrl = json["presignedUrl"]
# URL for future reference
uploadedFileUrl = json["url"]
# 2. UPLOAD FILE TO CLOUD.
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:
# Show service reported error
print(json["message"])
else:
print(f"Request error: {response.status_code} {response.reason}")
return None
if __name__ == '__main__':
main()
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";
// Comma-separated list of page numbers (or ranges) to process. Example: '1,3-5,7-'.
const string Pages = "1-2,3-";
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<bool>() == 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
webClient.Headers.Remove("content-type");
// 3. SPLIT UPLOADED PDF
// URL for `Split PDF` API call
var url = "https://api.pdf.co/v1/pdf/split";
// Prepare requests params as JSON
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("pages", Pages);
parameters.Add("url", uploadedFileUrl);
// 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<bool>() == false)
{
// Download generated PDF files
int part = 1;
foreach (JToken token in json["urls"])
{
string resultFileUrl = token.ToString();
string localFileName = String.Format(@".\part{0}.pdf", part);
webClient.DownloadFile(resultFileUrl, localFileName);
Console.WriteLine("Downloaded \"{0}\".", localFileName);
part++;
}
}
else
{
Console.WriteLine(json["message"].ToString());
}
}
else
{
Console.WriteLine(json["message"].ToString());
}
}
catch (WebException e)
{
Console.WriteLine(e.ToString());
}
webClient.Dispose();
Console.WriteLine();
Console.WriteLine("Press any key...");
Console.ReadKey();
}
}
}
package com.company;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import okhttp3.*;
import java.io.*;
import java.net.*;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main
{
// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co
final static String API_KEY = "***********************************";
// Source PDF file to split
final static Path SourceFile = Paths.get(".\\sample.pdf");
// Comma-separated list of page numbers (or ranges) to process. Example: '1,3-5,7-'.
final static String Pages = "1-2,3-";
public static void main(String[] args) throws IOException
{
// Create HTTP client instance
OkHttpClient webClient = new OkHttpClient();
// 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 = String.format(
"https://api.pdf.co/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name=%s",
SourceFile.getFileName());
// Prepare request
Request request = new Request.Builder()
.url(query)
.addHeader("x-api-key", API_KEY) // (!) Set API Key
.build();
// Execute request
Response response = webClient.newCall(request).execute();
if (response.code() == 200)
{
// Parse JSON response
JsonObject json = new JsonParser().parse(response.body().string()).getAsJsonObject();
boolean error = json.get("error").getAsBoolean();
if (!error)
{
// Get URL to use for the file upload
String uploadUrl = json.get("presignedUrl").getAsString();
// Get URL of uploaded file to use with later API calls
String uploadedFileUrl = json.get("url").getAsString();
// 2. UPLOAD THE FILE TO CLOUD.
if (uploadFile(webClient, API_KEY, uploadUrl, SourceFile))
{
// 3. SPLIT UPLOADED PDF
SplitPdf(webClient, API_KEY, Pages, uploadedFileUrl);
}
}
else
{
// Display service reported error
System.out.println(json.get("message").getAsString());
}
}
else
{
// Display request error
System.out.println(response.code() + " " + response.message());
}
}
public static void SplitPdf(OkHttpClient webClient, String apiKey, String pages, String uploadedFileUrl) throws IOException
{
// Prepare URL for `Split PDF` API call
String query = "https://api.pdf.co/v1/pdf/split";
// Make correctly escaped (encoded) URL
URL url = null;
try
{
url = new URI(null, query, null).toURL();
}
catch (URISyntaxException e)
{
e.printStackTrace();
}
// Create JSON payload
String jsonPayload = String.format("{\"pages\": \"%s\", \"url\": \"%s\"}",
pages,
uploadedFileUrl);
// Prepare request body
RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonPayload);
// Prepare request
Request request = new Request.Builder()
.url(url)
.addHeader("x-api-key", API_KEY) // (!) Set API Key
.addHeader("Content-Type", "application/json")
.post(body)
.build();
// Execute request
Response response = webClient.newCall(request).execute();
if (response.code() == 200)
{
// Parse JSON response
JsonObject json = new JsonParser().parse(response.body().string()).getAsJsonObject();
boolean error = json.get("error").getAsBoolean();
if (!error)
{
// Download generated PDF files
JsonArray urls = json.get("urls").getAsJsonArray();
int part = 1;
for (JsonElement element: urls)
{
String resultFileUrl = element.getAsString();
String localFileName = String.format(".\\part%s.pdf", part);
downloadFile(webClient, resultFileUrl, Paths.get(localFileName).toFile());
System.out.println(String.format("Splitted part saved as \"%s\".", localFileName));
part++;
}
}
else
{
// Display service reported error
System.out.println(json.get("message").getAsString());
}
}
else
{
// Display request error
System.out.println(response.code() + " " + response.message());
}
}
public static boolean uploadFile(OkHttpClient webClient, String apiKey, String url, Path sourceFile) throws IOException
{
// Prepare request body
RequestBody body = RequestBody.create(MediaType.parse("application/octet-stream"), sourceFile.toFile());
// Prepare request
Request request = new Request.Builder()
.url(url)
.addHeader("x-api-key", apiKey) // (!) Set API Key
.addHeader("content-type", "application/octet-stream")
.put(body)
.build();
// Execute request
Response response = webClient.newCall(request).execute();
return (response.code() == 200);
}
public static void downloadFile(OkHttpClient webClient, String url, File destinationFile) throws IOException
{
// Prepare request
Request request = new Request.Builder()
.url(url)
.build();
// Execute request
Response response = webClient.newCall(request).execute();
byte[] fileBytes = response.body().bytes();
// Save downloaded bytes to file
OutputStream output = new FileOutputStream(destinationFile);
output.write(fileBytes);
output.flush();
output.close();
response.close();
}
}
<?php
// Note: For input files larger than 200 KB, we recommend using async mode by setting the "async" parameter to true.
// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co
$API_KEY = "***********************************";
// Source PDF file to split
$SourceFile = "./sample.pdf";
// Comma-separated list of page numbers (or ranges) to process. Example: '1,3-5,7-'.
$Pages = "1-2,3-";
// 1. RETRIEVE THE PRESIGNED URL TO UPLOAD THE FILE.
// * If you already have the direct PDF file link, go to the step 3.
$presignedUrls = getPresignedUrl($API_KEY, $SourceFile);
if ($presignedUrls !== null) {
list($uploadUrl, $uploadedFileUrl) = $presignedUrls;
// 2. UPLOAD THE FILE TO CLOUD.
if (uploadFile($API_KEY, $SourceFile, $uploadUrl)) {
// 3. SPLIT UPLOADED PDF
splitPdf($API_KEY, $uploadedFileUrl, $Pages);
}
}
function getPresignedUrl($apiKey, $localFile)
{
// Prepare URL for `Get Presigned URL` API call
$url = "https://api.pdf.co/v1/file/upload/get-presigned-url"
. "?contenttype=application/octet-stream"
. "&name=" . urlencode(basename($localFile));
// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Execute request
$result = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlError = curl_error($curl);
curl_close($curl);
if ($result === false) {
// Display CURL error
echo "getPresignedUrl(): " . $curlError . PHP_EOL;
return null;
}
if ($statusCode != 200) {
// Display request error
echo "getPresignedUrl(): request error " . $statusCode . PHP_EOL . $result . PHP_EOL;
return null;
}
$json = json_decode($result, true);
if (!empty($json["error"])) {
// Display service reported error
echo "getPresignedUrl(): " . $json["message"] . PHP_EOL;
return null;
}
// Return the URL to use for the file upload, and the URL of the uploaded
// file to use with later API calls
return array($json["presignedUrl"], $json["url"]);
}
function uploadFile($apiKey, $localFile, $uploadUrl)
{
$fileHandle = fopen($localFile, "rb");
if ($fileHandle === false) {
echo "uploadFile(): unable to open " . $localFile . PHP_EOL;
return false;
}
// Create request. The presigned URL expects a raw PUT of the file bytes.
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $uploadUrl);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey, "content-type: application/octet-stream"));
curl_setopt($curl, CURLOPT_PUT, true);
curl_setopt($curl, CURLOPT_INFILE, $fileHandle);
curl_setopt($curl, CURLOPT_INFILESIZE, filesize($localFile));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Execute request
$result = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlError = curl_error($curl);
curl_close($curl);
fclose($fileHandle);
if ($result === false) {
// Display CURL error
echo "uploadFile(): " . $curlError . PHP_EOL;
return false;
}
if ($statusCode != 200) {
// Display request error
echo "uploadFile(): request error " . $statusCode . PHP_EOL . $result . PHP_EOL;
return false;
}
return true;
}
function splitPdf($apiKey, $uploadedFileUrl, $pages)
{
// Prepare URL for `Split PDF` API call
$url = "https://api.pdf.co/v1/pdf/split";
// Prepare requests params
$parameters = array();
$parameters["pages"] = $pages;
$parameters["url"] = $uploadedFileUrl;
// Create Json payload
$data = json_encode($parameters);
// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey, "Content-Type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Execute request
$result = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlError = curl_error($curl);
curl_close($curl);
if ($result === false) {
// Display CURL error
echo "splitPdf(): " . $curlError . PHP_EOL;
return;
}
if ($statusCode != 200) {
// Display request error
echo "splitPdf(): request error " . $statusCode . PHP_EOL . $result . PHP_EOL;
return;
}
$json = json_decode($result, true);
if (!empty($json["error"])) {
// Display service reported error
echo "splitPdf(): " . $json["message"] . PHP_EOL;
return;
}
// Download generated PDF files
$part = 1;
foreach ($json["urls"] as $resultFileUrl) {
$destinationFile = "./part" . $part . ".pdf";
if (downloadFile($resultFileUrl, $destinationFile)) {
echo "Downloaded \"" . $destinationFile . "\"." . PHP_EOL;
}
$part++;
}
}
function downloadFile($url, $destinationFile)
{
// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
// Execute request
$result = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlError = curl_error($curl);
curl_close($curl);
if ($result === false) {
// Display CURL error
echo "downloadFile(): " . $curlError . PHP_EOL;
return false;
}
if ($statusCode != 200) {
// Display request error
echo "downloadFile(): request error " . $statusCode . PHP_EOL . $result . PHP_EOL;
return false;
}
// Write the file only after a successful response so failures leave no file behind
if (file_put_contents($destinationFile, $result) === false) {
echo "downloadFile(): unable to create " . $destinationFile . PHP_EOL;
return false;
}
return true;
}
?>
{
"urls": [
"https://pdf-temp-files.s3.amazonaws.com/1e9a7f2c46834160903276716424382b/result_page1-2.pdf",
"https://pdf-temp-files.s3.amazonaws.com/c976b9f89a2e460786a3d5c0deeeef67/result_page3-4.pdf"
],
"pageCount": 4,
"error": false,
"status": 200,
"name": "result.pdf",
"remainingCredits": 98441
}
{
"error": true,
"status": 400,
"message": "Bad request. Typically due to bad input parameters or unreachable input URLs (e.g., access restrictions like login or password)."
}
{
"status": "error",
"errorCode": 401,
"error": true,
"message": "Please provide your API key as \"x-api-key\" header parameter for GET or POST request or as username (\"curl -u <apikey>\") or as url parameter (not recommended). Get your API key at https://app.pdf.co/account"
}
{
"status": "error",
"errorCode": 402,
"error": true,
"message": "Not enough credits, subscription expired or metered use is not allowed. Please review credits on your account at https://app.pdf.co/subscriptions"
}
{
"error": true,
"status": 403,
"message": "Access forbidden for input URL."
}
{
"error": true,
"status": 404,
"message": "The requested resource could not be found."
}
{
"error": true,
"status": 408,
"message": "The server timed out waiting for the request."
}
{
"error": true,
"message": "Too many requests. Your current limit is <limit> requests per minute. Please try again later"
}
{
"error": true,
"status": 441,
"message": "Invalid Password. Password protected document."
}
{
"error": true,
"status": 442,
"message": "Input document is damaged or of incorrect type."
}
{
"error": true,
"status": 443,
"message": "Permissions. The operation is prohibited by document security settings."
}
{
"error": true,
"status": 444,
"message": "Profiles parsing error. Please ensure that the configuration is supported."
}
{
"error": true,
"status": 445,
"message": "Timeout error. For large documents, use asynchronous mode (async=true) and check status via /job/check."
}
{
"error": true,
"status": 446,
"message": "Some files required for conversion are missing."
}
{
"error": true,
"status": 449,
"message": "Invalid index range. Page index is out of range."
}
{
"error": true,
"status": 450,
"message": "Invalid page range specified."
}
{
"error": true,
"status": 452,
"message": "Invalid URL."
}
{
"error": true,
"status": 454,
"message": "Invalid parameters."
}
{
"error": true,
"status": 500,
"message": "Something went wrong. Please try again or contact support."
}
PDF Split
Split PDF
Split a PDF into multiple files by specifying page numbers or page ranges to keep in each output.
Sample request
CURL
curl --location --request POST 'https://api.pdf.co/v1/pdf/split' \
--header 'Content-Type: application/json' \
--header 'x-api-key: *******************' \
--data-raw '{
"url": "https://pdfco-test-files.s3.us-west-2.amazonaws.com/pdf-split/sample.pdf",
"pages": "1-2,3-",
"inline": true,
"name": "result.pdf",
"async": false
}'
import os
import requests # pip install requests
import time
import datetime
# 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"
# Source PDF file
SourceFile = ".\\sample.pdf"
# Comma-separated list of page numbers (or ranges) to process. Example: '1,3-5,7-'.
Pages = "1-2,3-"
# (!) Make asynchronous job
Async = True
def main(args = None):
uploadedFileUrl = uploadFile(SourceFile)
if (uploadedFileUrl != None):
splitPDF(uploadedFileUrl)
def splitPDF(uploadedFileUrl):
"""Split PDF using PDF.co Web API"""
# Prepare requests params as JSON
# See documentation: https://developer.pdf.co/
parameters = {}
parameters["async"] = Async
parameters["pages"] = Pages
parameters["url"] = uploadedFileUrl
# Prepare URL for 'Split PDF' API request
url = "{}/pdf/split".format(BASE_URL)
# Execute request and get response as JSON
response = requests.post(url, data=parameters, headers={ "x-api-key": API_KEY })
if (response.status_code == 200):
json = response.json()
if json["error"] == False:
# Asynchronous job ID
jobId = json["jobId"]
# URL of the result file
resultFilePlaceholder = json["url"]
# Check the job status in a loop.
# If you don't want to pause the main thread you can rework the code
# to use a separate thread for the status checking and completion.
while True:
status = checkJobStatus(jobId) # Possible statuses: "working", "failed", "aborted", "success".
# Display timestamp and status (for demo purposes)
print(datetime.datetime.now().strftime("%H:%M.%S") + ": " + status)
if status == "success":
resJsonImgFiles = requests.get(resultFilePlaceholder)
# Download generated PDF files
part = 1
for resultFileUrl in resJsonImgFiles.json():
# Download Result File
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":
# Pause for a few seconds
time.sleep(3)
else:
print(status)
break
else:
# Show service reported error
print(json["message"])
else:
print(f"Request error: {response.status_code} {response.reason}")
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 = response.json()
return json["status"]
else:
print(f"Request error: {response.status_code} {response.reason}")
return None
def uploadFile(fileName):
"""Uploads file to the cloud"""
# 1. RETRIEVE PRESIGNED URL TO UPLOAD FILE.
# Prepare URL for 'Get Presigned URL' API request
url = "{}/file/upload/get-presigned-url?contenttype=application/octet-stream&name={}".format(
BASE_URL, os.path.basename(fileName))
# Execute request and get response as JSON
response = requests.get(url, headers={ "x-api-key": API_KEY })
if (response.status_code == 200):
json = response.json()
if json["error"] == False:
# URL to use for file upload
uploadUrl = json["presignedUrl"]
# URL for future reference
uploadedFileUrl = json["url"]
# 2. UPLOAD FILE TO CLOUD.
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:
# Show service reported error
print(json["message"])
else:
print(f"Request error: {response.status_code} {response.reason}")
return None
if __name__ == '__main__':
main()
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";
// Comma-separated list of page numbers (or ranges) to process. Example: '1,3-5,7-'.
const string Pages = "1-2,3-";
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<bool>() == 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
webClient.Headers.Remove("content-type");
// 3. SPLIT UPLOADED PDF
// URL for `Split PDF` API call
var url = "https://api.pdf.co/v1/pdf/split";
// Prepare requests params as JSON
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("pages", Pages);
parameters.Add("url", uploadedFileUrl);
// 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<bool>() == false)
{
// Download generated PDF files
int part = 1;
foreach (JToken token in json["urls"])
{
string resultFileUrl = token.ToString();
string localFileName = String.Format(@".\part{0}.pdf", part);
webClient.DownloadFile(resultFileUrl, localFileName);
Console.WriteLine("Downloaded \"{0}\".", localFileName);
part++;
}
}
else
{
Console.WriteLine(json["message"].ToString());
}
}
else
{
Console.WriteLine(json["message"].ToString());
}
}
catch (WebException e)
{
Console.WriteLine(e.ToString());
}
webClient.Dispose();
Console.WriteLine();
Console.WriteLine("Press any key...");
Console.ReadKey();
}
}
}
package com.company;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import okhttp3.*;
import java.io.*;
import java.net.*;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main
{
// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co
final static String API_KEY = "***********************************";
// Source PDF file to split
final static Path SourceFile = Paths.get(".\\sample.pdf");
// Comma-separated list of page numbers (or ranges) to process. Example: '1,3-5,7-'.
final static String Pages = "1-2,3-";
public static void main(String[] args) throws IOException
{
// Create HTTP client instance
OkHttpClient webClient = new OkHttpClient();
// 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 = String.format(
"https://api.pdf.co/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name=%s",
SourceFile.getFileName());
// Prepare request
Request request = new Request.Builder()
.url(query)
.addHeader("x-api-key", API_KEY) // (!) Set API Key
.build();
// Execute request
Response response = webClient.newCall(request).execute();
if (response.code() == 200)
{
// Parse JSON response
JsonObject json = new JsonParser().parse(response.body().string()).getAsJsonObject();
boolean error = json.get("error").getAsBoolean();
if (!error)
{
// Get URL to use for the file upload
String uploadUrl = json.get("presignedUrl").getAsString();
// Get URL of uploaded file to use with later API calls
String uploadedFileUrl = json.get("url").getAsString();
// 2. UPLOAD THE FILE TO CLOUD.
if (uploadFile(webClient, API_KEY, uploadUrl, SourceFile))
{
// 3. SPLIT UPLOADED PDF
SplitPdf(webClient, API_KEY, Pages, uploadedFileUrl);
}
}
else
{
// Display service reported error
System.out.println(json.get("message").getAsString());
}
}
else
{
// Display request error
System.out.println(response.code() + " " + response.message());
}
}
public static void SplitPdf(OkHttpClient webClient, String apiKey, String pages, String uploadedFileUrl) throws IOException
{
// Prepare URL for `Split PDF` API call
String query = "https://api.pdf.co/v1/pdf/split";
// Make correctly escaped (encoded) URL
URL url = null;
try
{
url = new URI(null, query, null).toURL();
}
catch (URISyntaxException e)
{
e.printStackTrace();
}
// Create JSON payload
String jsonPayload = String.format("{\"pages\": \"%s\", \"url\": \"%s\"}",
pages,
uploadedFileUrl);
// Prepare request body
RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonPayload);
// Prepare request
Request request = new Request.Builder()
.url(url)
.addHeader("x-api-key", API_KEY) // (!) Set API Key
.addHeader("Content-Type", "application/json")
.post(body)
.build();
// Execute request
Response response = webClient.newCall(request).execute();
if (response.code() == 200)
{
// Parse JSON response
JsonObject json = new JsonParser().parse(response.body().string()).getAsJsonObject();
boolean error = json.get("error").getAsBoolean();
if (!error)
{
// Download generated PDF files
JsonArray urls = json.get("urls").getAsJsonArray();
int part = 1;
for (JsonElement element: urls)
{
String resultFileUrl = element.getAsString();
String localFileName = String.format(".\\part%s.pdf", part);
downloadFile(webClient, resultFileUrl, Paths.get(localFileName).toFile());
System.out.println(String.format("Splitted part saved as \"%s\".", localFileName));
part++;
}
}
else
{
// Display service reported error
System.out.println(json.get("message").getAsString());
}
}
else
{
// Display request error
System.out.println(response.code() + " " + response.message());
}
}
public static boolean uploadFile(OkHttpClient webClient, String apiKey, String url, Path sourceFile) throws IOException
{
// Prepare request body
RequestBody body = RequestBody.create(MediaType.parse("application/octet-stream"), sourceFile.toFile());
// Prepare request
Request request = new Request.Builder()
.url(url)
.addHeader("x-api-key", apiKey) // (!) Set API Key
.addHeader("content-type", "application/octet-stream")
.put(body)
.build();
// Execute request
Response response = webClient.newCall(request).execute();
return (response.code() == 200);
}
public static void downloadFile(OkHttpClient webClient, String url, File destinationFile) throws IOException
{
// Prepare request
Request request = new Request.Builder()
.url(url)
.build();
// Execute request
Response response = webClient.newCall(request).execute();
byte[] fileBytes = response.body().bytes();
// Save downloaded bytes to file
OutputStream output = new FileOutputStream(destinationFile);
output.write(fileBytes);
output.flush();
output.close();
response.close();
}
}
<?php
// Note: For input files larger than 200 KB, we recommend using async mode by setting the "async" parameter to true.
// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co
$API_KEY = "***********************************";
// Source PDF file to split
$SourceFile = "./sample.pdf";
// Comma-separated list of page numbers (or ranges) to process. Example: '1,3-5,7-'.
$Pages = "1-2,3-";
// 1. RETRIEVE THE PRESIGNED URL TO UPLOAD THE FILE.
// * If you already have the direct PDF file link, go to the step 3.
$presignedUrls = getPresignedUrl($API_KEY, $SourceFile);
if ($presignedUrls !== null) {
list($uploadUrl, $uploadedFileUrl) = $presignedUrls;
// 2. UPLOAD THE FILE TO CLOUD.
if (uploadFile($API_KEY, $SourceFile, $uploadUrl)) {
// 3. SPLIT UPLOADED PDF
splitPdf($API_KEY, $uploadedFileUrl, $Pages);
}
}
function getPresignedUrl($apiKey, $localFile)
{
// Prepare URL for `Get Presigned URL` API call
$url = "https://api.pdf.co/v1/file/upload/get-presigned-url"
. "?contenttype=application/octet-stream"
. "&name=" . urlencode(basename($localFile));
// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Execute request
$result = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlError = curl_error($curl);
curl_close($curl);
if ($result === false) {
// Display CURL error
echo "getPresignedUrl(): " . $curlError . PHP_EOL;
return null;
}
if ($statusCode != 200) {
// Display request error
echo "getPresignedUrl(): request error " . $statusCode . PHP_EOL . $result . PHP_EOL;
return null;
}
$json = json_decode($result, true);
if (!empty($json["error"])) {
// Display service reported error
echo "getPresignedUrl(): " . $json["message"] . PHP_EOL;
return null;
}
// Return the URL to use for the file upload, and the URL of the uploaded
// file to use with later API calls
return array($json["presignedUrl"], $json["url"]);
}
function uploadFile($apiKey, $localFile, $uploadUrl)
{
$fileHandle = fopen($localFile, "rb");
if ($fileHandle === false) {
echo "uploadFile(): unable to open " . $localFile . PHP_EOL;
return false;
}
// Create request. The presigned URL expects a raw PUT of the file bytes.
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $uploadUrl);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey, "content-type: application/octet-stream"));
curl_setopt($curl, CURLOPT_PUT, true);
curl_setopt($curl, CURLOPT_INFILE, $fileHandle);
curl_setopt($curl, CURLOPT_INFILESIZE, filesize($localFile));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Execute request
$result = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlError = curl_error($curl);
curl_close($curl);
fclose($fileHandle);
if ($result === false) {
// Display CURL error
echo "uploadFile(): " . $curlError . PHP_EOL;
return false;
}
if ($statusCode != 200) {
// Display request error
echo "uploadFile(): request error " . $statusCode . PHP_EOL . $result . PHP_EOL;
return false;
}
return true;
}
function splitPdf($apiKey, $uploadedFileUrl, $pages)
{
// Prepare URL for `Split PDF` API call
$url = "https://api.pdf.co/v1/pdf/split";
// Prepare requests params
$parameters = array();
$parameters["pages"] = $pages;
$parameters["url"] = $uploadedFileUrl;
// Create Json payload
$data = json_encode($parameters);
// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey, "Content-Type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Execute request
$result = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlError = curl_error($curl);
curl_close($curl);
if ($result === false) {
// Display CURL error
echo "splitPdf(): " . $curlError . PHP_EOL;
return;
}
if ($statusCode != 200) {
// Display request error
echo "splitPdf(): request error " . $statusCode . PHP_EOL . $result . PHP_EOL;
return;
}
$json = json_decode($result, true);
if (!empty($json["error"])) {
// Display service reported error
echo "splitPdf(): " . $json["message"] . PHP_EOL;
return;
}
// Download generated PDF files
$part = 1;
foreach ($json["urls"] as $resultFileUrl) {
$destinationFile = "./part" . $part . ".pdf";
if (downloadFile($resultFileUrl, $destinationFile)) {
echo "Downloaded \"" . $destinationFile . "\"." . PHP_EOL;
}
$part++;
}
}
function downloadFile($url, $destinationFile)
{
// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
// Execute request
$result = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlError = curl_error($curl);
curl_close($curl);
if ($result === false) {
// Display CURL error
echo "downloadFile(): " . $curlError . PHP_EOL;
return false;
}
if ($statusCode != 200) {
// Display request error
echo "downloadFile(): request error " . $statusCode . PHP_EOL . $result . PHP_EOL;
return false;
}
// Write the file only after a successful response so failures leave no file behind
if (file_put_contents($destinationFile, $result) === false) {
echo "downloadFile(): unable to create " . $destinationFile . PHP_EOL;
return false;
}
return true;
}
?>
{
"urls": [
"https://pdf-temp-files.s3.amazonaws.com/1e9a7f2c46834160903276716424382b/result_page1-2.pdf",
"https://pdf-temp-files.s3.amazonaws.com/c976b9f89a2e460786a3d5c0deeeef67/result_page3-4.pdf"
],
"pageCount": 4,
"error": false,
"status": 200,
"name": "result.pdf",
"remainingCredits": 98441
}
{
"error": true,
"status": 400,
"message": "Bad request. Typically due to bad input parameters or unreachable input URLs (e.g., access restrictions like login or password)."
}
{
"status": "error",
"errorCode": 401,
"error": true,
"message": "Please provide your API key as \"x-api-key\" header parameter for GET or POST request or as username (\"curl -u <apikey>\") or as url parameter (not recommended). Get your API key at https://app.pdf.co/account"
}
{
"status": "error",
"errorCode": 402,
"error": true,
"message": "Not enough credits, subscription expired or metered use is not allowed. Please review credits on your account at https://app.pdf.co/subscriptions"
}
{
"error": true,
"status": 403,
"message": "Access forbidden for input URL."
}
{
"error": true,
"status": 404,
"message": "The requested resource could not be found."
}
{
"error": true,
"status": 408,
"message": "The server timed out waiting for the request."
}
{
"error": true,
"message": "Too many requests. Your current limit is <limit> requests per minute. Please try again later"
}
{
"error": true,
"status": 441,
"message": "Invalid Password. Password protected document."
}
{
"error": true,
"status": 442,
"message": "Input document is damaged or of incorrect type."
}
{
"error": true,
"status": 443,
"message": "Permissions. The operation is prohibited by document security settings."
}
{
"error": true,
"status": 444,
"message": "Profiles parsing error. Please ensure that the configuration is supported."
}
{
"error": true,
"status": 445,
"message": "Timeout error. For large documents, use asynchronous mode (async=true) and check status via /job/check."
}
{
"error": true,
"status": 446,
"message": "Some files required for conversion are missing."
}
{
"error": true,
"status": 449,
"message": "Invalid index range. Page index is out of range."
}
{
"error": true,
"status": 450,
"message": "Invalid page range specified."
}
{
"error": true,
"status": 452,
"message": "Invalid URL."
}
{
"error": true,
"status": 454,
"message": "Invalid parameters."
}
{
"error": true,
"status": 500,
"message": "Something went wrong. Please try again or contact support."
}
CURL
curl --location --request POST 'https://api.pdf.co/v1/pdf/split' \
--header 'Content-Type: application/json' \
--header 'x-api-key: *******************' \
--data-raw '{
"url": "https://pdfco-test-files.s3.us-west-2.amazonaws.com/pdf-split/sample.pdf",
"pages": "1-2,3-",
"inline": true,
"name": "result.pdf",
"async": false
}'
import os
import requests # pip install requests
import time
import datetime
# 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"
# Source PDF file
SourceFile = ".\\sample.pdf"
# Comma-separated list of page numbers (or ranges) to process. Example: '1,3-5,7-'.
Pages = "1-2,3-"
# (!) Make asynchronous job
Async = True
def main(args = None):
uploadedFileUrl = uploadFile(SourceFile)
if (uploadedFileUrl != None):
splitPDF(uploadedFileUrl)
def splitPDF(uploadedFileUrl):
"""Split PDF using PDF.co Web API"""
# Prepare requests params as JSON
# See documentation: https://developer.pdf.co/
parameters = {}
parameters["async"] = Async
parameters["pages"] = Pages
parameters["url"] = uploadedFileUrl
# Prepare URL for 'Split PDF' API request
url = "{}/pdf/split".format(BASE_URL)
# Execute request and get response as JSON
response = requests.post(url, data=parameters, headers={ "x-api-key": API_KEY })
if (response.status_code == 200):
json = response.json()
if json["error"] == False:
# Asynchronous job ID
jobId = json["jobId"]
# URL of the result file
resultFilePlaceholder = json["url"]
# Check the job status in a loop.
# If you don't want to pause the main thread you can rework the code
# to use a separate thread for the status checking and completion.
while True:
status = checkJobStatus(jobId) # Possible statuses: "working", "failed", "aborted", "success".
# Display timestamp and status (for demo purposes)
print(datetime.datetime.now().strftime("%H:%M.%S") + ": " + status)
if status == "success":
resJsonImgFiles = requests.get(resultFilePlaceholder)
# Download generated PDF files
part = 1
for resultFileUrl in resJsonImgFiles.json():
# Download Result File
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":
# Pause for a few seconds
time.sleep(3)
else:
print(status)
break
else:
# Show service reported error
print(json["message"])
else:
print(f"Request error: {response.status_code} {response.reason}")
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 = response.json()
return json["status"]
else:
print(f"Request error: {response.status_code} {response.reason}")
return None
def uploadFile(fileName):
"""Uploads file to the cloud"""
# 1. RETRIEVE PRESIGNED URL TO UPLOAD FILE.
# Prepare URL for 'Get Presigned URL' API request
url = "{}/file/upload/get-presigned-url?contenttype=application/octet-stream&name={}".format(
BASE_URL, os.path.basename(fileName))
# Execute request and get response as JSON
response = requests.get(url, headers={ "x-api-key": API_KEY })
if (response.status_code == 200):
json = response.json()
if json["error"] == False:
# URL to use for file upload
uploadUrl = json["presignedUrl"]
# URL for future reference
uploadedFileUrl = json["url"]
# 2. UPLOAD FILE TO CLOUD.
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:
# Show service reported error
print(json["message"])
else:
print(f"Request error: {response.status_code} {response.reason}")
return None
if __name__ == '__main__':
main()
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";
// Comma-separated list of page numbers (or ranges) to process. Example: '1,3-5,7-'.
const string Pages = "1-2,3-";
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<bool>() == 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
webClient.Headers.Remove("content-type");
// 3. SPLIT UPLOADED PDF
// URL for `Split PDF` API call
var url = "https://api.pdf.co/v1/pdf/split";
// Prepare requests params as JSON
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("pages", Pages);
parameters.Add("url", uploadedFileUrl);
// 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<bool>() == false)
{
// Download generated PDF files
int part = 1;
foreach (JToken token in json["urls"])
{
string resultFileUrl = token.ToString();
string localFileName = String.Format(@".\part{0}.pdf", part);
webClient.DownloadFile(resultFileUrl, localFileName);
Console.WriteLine("Downloaded \"{0}\".", localFileName);
part++;
}
}
else
{
Console.WriteLine(json["message"].ToString());
}
}
else
{
Console.WriteLine(json["message"].ToString());
}
}
catch (WebException e)
{
Console.WriteLine(e.ToString());
}
webClient.Dispose();
Console.WriteLine();
Console.WriteLine("Press any key...");
Console.ReadKey();
}
}
}
package com.company;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import okhttp3.*;
import java.io.*;
import java.net.*;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main
{
// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co
final static String API_KEY = "***********************************";
// Source PDF file to split
final static Path SourceFile = Paths.get(".\\sample.pdf");
// Comma-separated list of page numbers (or ranges) to process. Example: '1,3-5,7-'.
final static String Pages = "1-2,3-";
public static void main(String[] args) throws IOException
{
// Create HTTP client instance
OkHttpClient webClient = new OkHttpClient();
// 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 = String.format(
"https://api.pdf.co/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name=%s",
SourceFile.getFileName());
// Prepare request
Request request = new Request.Builder()
.url(query)
.addHeader("x-api-key", API_KEY) // (!) Set API Key
.build();
// Execute request
Response response = webClient.newCall(request).execute();
if (response.code() == 200)
{
// Parse JSON response
JsonObject json = new JsonParser().parse(response.body().string()).getAsJsonObject();
boolean error = json.get("error").getAsBoolean();
if (!error)
{
// Get URL to use for the file upload
String uploadUrl = json.get("presignedUrl").getAsString();
// Get URL of uploaded file to use with later API calls
String uploadedFileUrl = json.get("url").getAsString();
// 2. UPLOAD THE FILE TO CLOUD.
if (uploadFile(webClient, API_KEY, uploadUrl, SourceFile))
{
// 3. SPLIT UPLOADED PDF
SplitPdf(webClient, API_KEY, Pages, uploadedFileUrl);
}
}
else
{
// Display service reported error
System.out.println(json.get("message").getAsString());
}
}
else
{
// Display request error
System.out.println(response.code() + " " + response.message());
}
}
public static void SplitPdf(OkHttpClient webClient, String apiKey, String pages, String uploadedFileUrl) throws IOException
{
// Prepare URL for `Split PDF` API call
String query = "https://api.pdf.co/v1/pdf/split";
// Make correctly escaped (encoded) URL
URL url = null;
try
{
url = new URI(null, query, null).toURL();
}
catch (URISyntaxException e)
{
e.printStackTrace();
}
// Create JSON payload
String jsonPayload = String.format("{\"pages\": \"%s\", \"url\": \"%s\"}",
pages,
uploadedFileUrl);
// Prepare request body
RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonPayload);
// Prepare request
Request request = new Request.Builder()
.url(url)
.addHeader("x-api-key", API_KEY) // (!) Set API Key
.addHeader("Content-Type", "application/json")
.post(body)
.build();
// Execute request
Response response = webClient.newCall(request).execute();
if (response.code() == 200)
{
// Parse JSON response
JsonObject json = new JsonParser().parse(response.body().string()).getAsJsonObject();
boolean error = json.get("error").getAsBoolean();
if (!error)
{
// Download generated PDF files
JsonArray urls = json.get("urls").getAsJsonArray();
int part = 1;
for (JsonElement element: urls)
{
String resultFileUrl = element.getAsString();
String localFileName = String.format(".\\part%s.pdf", part);
downloadFile(webClient, resultFileUrl, Paths.get(localFileName).toFile());
System.out.println(String.format("Splitted part saved as \"%s\".", localFileName));
part++;
}
}
else
{
// Display service reported error
System.out.println(json.get("message").getAsString());
}
}
else
{
// Display request error
System.out.println(response.code() + " " + response.message());
}
}
public static boolean uploadFile(OkHttpClient webClient, String apiKey, String url, Path sourceFile) throws IOException
{
// Prepare request body
RequestBody body = RequestBody.create(MediaType.parse("application/octet-stream"), sourceFile.toFile());
// Prepare request
Request request = new Request.Builder()
.url(url)
.addHeader("x-api-key", apiKey) // (!) Set API Key
.addHeader("content-type", "application/octet-stream")
.put(body)
.build();
// Execute request
Response response = webClient.newCall(request).execute();
return (response.code() == 200);
}
public static void downloadFile(OkHttpClient webClient, String url, File destinationFile) throws IOException
{
// Prepare request
Request request = new Request.Builder()
.url(url)
.build();
// Execute request
Response response = webClient.newCall(request).execute();
byte[] fileBytes = response.body().bytes();
// Save downloaded bytes to file
OutputStream output = new FileOutputStream(destinationFile);
output.write(fileBytes);
output.flush();
output.close();
response.close();
}
}
<?php
// Note: For input files larger than 200 KB, we recommend using async mode by setting the "async" parameter to true.
// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co
$API_KEY = "***********************************";
// Source PDF file to split
$SourceFile = "./sample.pdf";
// Comma-separated list of page numbers (or ranges) to process. Example: '1,3-5,7-'.
$Pages = "1-2,3-";
// 1. RETRIEVE THE PRESIGNED URL TO UPLOAD THE FILE.
// * If you already have the direct PDF file link, go to the step 3.
$presignedUrls = getPresignedUrl($API_KEY, $SourceFile);
if ($presignedUrls !== null) {
list($uploadUrl, $uploadedFileUrl) = $presignedUrls;
// 2. UPLOAD THE FILE TO CLOUD.
if (uploadFile($API_KEY, $SourceFile, $uploadUrl)) {
// 3. SPLIT UPLOADED PDF
splitPdf($API_KEY, $uploadedFileUrl, $Pages);
}
}
function getPresignedUrl($apiKey, $localFile)
{
// Prepare URL for `Get Presigned URL` API call
$url = "https://api.pdf.co/v1/file/upload/get-presigned-url"
. "?contenttype=application/octet-stream"
. "&name=" . urlencode(basename($localFile));
// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Execute request
$result = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlError = curl_error($curl);
curl_close($curl);
if ($result === false) {
// Display CURL error
echo "getPresignedUrl(): " . $curlError . PHP_EOL;
return null;
}
if ($statusCode != 200) {
// Display request error
echo "getPresignedUrl(): request error " . $statusCode . PHP_EOL . $result . PHP_EOL;
return null;
}
$json = json_decode($result, true);
if (!empty($json["error"])) {
// Display service reported error
echo "getPresignedUrl(): " . $json["message"] . PHP_EOL;
return null;
}
// Return the URL to use for the file upload, and the URL of the uploaded
// file to use with later API calls
return array($json["presignedUrl"], $json["url"]);
}
function uploadFile($apiKey, $localFile, $uploadUrl)
{
$fileHandle = fopen($localFile, "rb");
if ($fileHandle === false) {
echo "uploadFile(): unable to open " . $localFile . PHP_EOL;
return false;
}
// Create request. The presigned URL expects a raw PUT of the file bytes.
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $uploadUrl);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey, "content-type: application/octet-stream"));
curl_setopt($curl, CURLOPT_PUT, true);
curl_setopt($curl, CURLOPT_INFILE, $fileHandle);
curl_setopt($curl, CURLOPT_INFILESIZE, filesize($localFile));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Execute request
$result = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlError = curl_error($curl);
curl_close($curl);
fclose($fileHandle);
if ($result === false) {
// Display CURL error
echo "uploadFile(): " . $curlError . PHP_EOL;
return false;
}
if ($statusCode != 200) {
// Display request error
echo "uploadFile(): request error " . $statusCode . PHP_EOL . $result . PHP_EOL;
return false;
}
return true;
}
function splitPdf($apiKey, $uploadedFileUrl, $pages)
{
// Prepare URL for `Split PDF` API call
$url = "https://api.pdf.co/v1/pdf/split";
// Prepare requests params
$parameters = array();
$parameters["pages"] = $pages;
$parameters["url"] = $uploadedFileUrl;
// Create Json payload
$data = json_encode($parameters);
// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey, "Content-Type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Execute request
$result = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlError = curl_error($curl);
curl_close($curl);
if ($result === false) {
// Display CURL error
echo "splitPdf(): " . $curlError . PHP_EOL;
return;
}
if ($statusCode != 200) {
// Display request error
echo "splitPdf(): request error " . $statusCode . PHP_EOL . $result . PHP_EOL;
return;
}
$json = json_decode($result, true);
if (!empty($json["error"])) {
// Display service reported error
echo "splitPdf(): " . $json["message"] . PHP_EOL;
return;
}
// Download generated PDF files
$part = 1;
foreach ($json["urls"] as $resultFileUrl) {
$destinationFile = "./part" . $part . ".pdf";
if (downloadFile($resultFileUrl, $destinationFile)) {
echo "Downloaded \"" . $destinationFile . "\"." . PHP_EOL;
}
$part++;
}
}
function downloadFile($url, $destinationFile)
{
// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
// Execute request
$result = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlError = curl_error($curl);
curl_close($curl);
if ($result === false) {
// Display CURL error
echo "downloadFile(): " . $curlError . PHP_EOL;
return false;
}
if ($statusCode != 200) {
// Display request error
echo "downloadFile(): request error " . $statusCode . PHP_EOL . $result . PHP_EOL;
return false;
}
// Write the file only after a successful response so failures leave no file behind
if (file_put_contents($destinationFile, $result) === false) {
echo "downloadFile(): unable to create " . $destinationFile . PHP_EOL;
return false;
}
return true;
}
?>
{
"urls": [
"https://pdf-temp-files.s3.amazonaws.com/1e9a7f2c46834160903276716424382b/result_page1-2.pdf",
"https://pdf-temp-files.s3.amazonaws.com/c976b9f89a2e460786a3d5c0deeeef67/result_page3-4.pdf"
],
"pageCount": 4,
"error": false,
"status": 200,
"name": "result.pdf",
"remainingCredits": 98441
}
{
"error": true,
"status": 400,
"message": "Bad request. Typically due to bad input parameters or unreachable input URLs (e.g., access restrictions like login or password)."
}
{
"status": "error",
"errorCode": 401,
"error": true,
"message": "Please provide your API key as \"x-api-key\" header parameter for GET or POST request or as username (\"curl -u <apikey>\") or as url parameter (not recommended). Get your API key at https://app.pdf.co/account"
}
{
"status": "error",
"errorCode": 402,
"error": true,
"message": "Not enough credits, subscription expired or metered use is not allowed. Please review credits on your account at https://app.pdf.co/subscriptions"
}
{
"error": true,
"status": 403,
"message": "Access forbidden for input URL."
}
{
"error": true,
"status": 404,
"message": "The requested resource could not be found."
}
{
"error": true,
"status": 408,
"message": "The server timed out waiting for the request."
}
{
"error": true,
"message": "Too many requests. Your current limit is <limit> requests per minute. Please try again later"
}
{
"error": true,
"status": 441,
"message": "Invalid Password. Password protected document."
}
{
"error": true,
"status": 442,
"message": "Input document is damaged or of incorrect type."
}
{
"error": true,
"status": 443,
"message": "Permissions. The operation is prohibited by document security settings."
}
{
"error": true,
"status": 444,
"message": "Profiles parsing error. Please ensure that the configuration is supported."
}
{
"error": true,
"status": 445,
"message": "Timeout error. For large documents, use asynchronous mode (async=true) and check status via /job/check."
}
{
"error": true,
"status": 446,
"message": "Some files required for conversion are missing."
}
{
"error": true,
"status": 449,
"message": "Invalid index range. Page index is out of range."
}
{
"error": true,
"status": 450,
"message": "Invalid page range specified."
}
{
"error": true,
"status": 452,
"message": "Invalid URL."
}
{
"error": true,
"status": 454,
"message": "Invalid parameters."
}
{
"error": true,
"status": 500,
"message": "Something went wrong. Please try again or contact support."
}
Try it live: Split PDF → API Tester — send a real request from your browser.
POST /v1/pdf/split
When splitting a document the pages parameter controls which
pages to split out into individual documents. The page limit should not exceed the number of pages in the document - for example, you cannot split a 100 page document into 200 individual documents, however you can split it into 100 individual documents.The
pages parameter is 1-based, meaning the first page is 1 and not 0.Request body
Attributes are case-sensitive and should be inside JSON for POST request. for example:
{ "url": "https://example.com/file1.pdf" } No query parameters accepted.To see the request size limits, please refer to the Request Size Limits.
string
required
URL to the source file
url attributestring
The callback URL (or Webhook) used to receive the POST data. see Webhooks & Callbacks. This is only applicable when
async is set to true.string
HTTP auth user name if required to access source URL.
string
HTTP auth password if required to access source URL.
string
default:"all pages"
Specify pages as comma-separated page numbers and ranges to process (e.g. “1, 2, 5-10” or “3-” for page 3 to the end). The first-page index is 1. Use ”!” before a number for inverted page numbers (e.g. “!1” for the last page). Use ”*” to split all pages individually. If omitted, all pages are split. The input must be in string format.
boolean
default:"false"
Set
async to true for long processes to run in the background, API will then return a jobId which you can use with the Background Job Check endpoint. Also see Webhooks & Callbacksboolean
default:"false"
For asynchronous requests, set to
true to include the result URLs in the completed job response. The initial response still includes a URL to the JSON file containing the split PDF URLs.string
File name for the generated output, the input must be in string format.
boolean
default:"false"
Defines whether the page range is appended to the output filename. When set to
true, the output filename remains exactly as specified in the name parameter. When set to false (default), the filename automatically includes the page range of the extracted pages for each output file.integer
default:"60"
Set the expiration time for the output link in minutes. After this specified duration, any generated output file(s) will be automatically deleted from PDF.co Temporary Files Storage. The maximum duration for link expiration varies based on your current subscription plan. To store permanent input files (e.g. re-usable images, pdf templates, documents) consider using PDF.co Built-In Files Storage.
Show profiles properties
Show profiles properties
| Setting | Type | Description |
|---|---|---|
outputDataFormat | string | If you require your output as base64 format, set this to base64 |
DataEncryptionAlgorithm | string | Controls the encryption algorithm used for data encryption. See User-Controlled Encryption for more information. The available algorithms are: AES128, AES192, AES256. |
DataEncryptionKey | string | Controls the encryption key used for data encryption. See User-Controlled Encryption for more information. |
DataEncryptionIV | string | Controls the encryption IV used for data encryption. See User-Controlled Encryption for more information. |
DataDecryptionAlgorithm | string | Controls the decryption algorithm used for data decryption. See User-Controlled Encryption for more information. The available algorithms are: AES128, AES192, AES256. |
DataDecryptionKey | string | Controls the decryption key used for data decryption. See User-Controlled Encryption for more information. |
DataDecryptionIV | string | Controls the decryption IV used for data decryption. See User-Controlled Encryption for more information. |
Responses
Synchronous response
{
"urls": [
"https://pdf-temp-files.s3.amazonaws.com/1e9a7f2c46834160903276716424382b/result_page1-2.pdf",
"https://pdf-temp-files.s3.amazonaws.com/c976b9f89a2e460786a3d5c0deeeef67/result_page3-4.pdf"
],
"pageCount": 4,
"error": false,
"status": 200,
"name": "result.pdf",
"remainingCredits": 98441
}
| Field | Type | Description |
|---|---|---|
urls | array[string] | List of URLs to the generated PDF files stored in S3, normally one for each split part. |
url | string | Present only in the initial response when async is true; URL to the JSON file containing the split PDF URLs. |
outputLinkValidTill | string | Timestamp indicating when the output link will expire |
pageCount | integer | Number of pages in the PDF document. |
error | boolean | Indicates whether an error occurred (false means success) |
status | integer or string | The numeric status code of the operation, or the string "error"; when it is "error", the numeric code is in errorCode. The 429 rate-limit response has no status field. In all cases, rely on the HTTP status code of the response. |
name | string | Name of the output file |
credits | integer | Number of credits consumed by the request |
remainingCredits | integer | Number of credits remaining in the account |
duration | integer | Time taken for the operation in milliseconds |
jobId | string | Present in the initial response when async is true. |
jobId and a reserved URL that should be used only after the job succeeds. Poll it via Background Job Check. Errors return error: true with a status code and message. See the response examples and Response Codes.
The reserved url points to a JSON file containing the split PDF URLs. With inline: true, the completed job response includes the result URL list.
Inconsistent URL Encoding in cURL Output: When using cURL to make API requests, the output JSON may show URL characters encoded as Unicode escape sequences. For example, the ampersand character (
&) may appear as \u0026 in the cURL output. This is normal JSON encoding behavior and does not affect the validity of the URL. The URL will function correctly when used, as JSON parsers automatically decode these escape sequences. If you’re parsing the response programmatically, your JSON parser will handle this conversion automatically.Was this page helpful?