Try it live: PDF Compress → API Tester — send a real request from your browser.
POST /v2/pdf/compress
A new and improved compression API - our 1st version 2 PDF.co endpoint!
Attributes
Attributes are case-sensitive and should be inside JSON for POST request. for example:
{ "url": "https://example.com/file1.pdf" }| Attribute | Type | Required | Default | Description |
|---|---|---|---|---|
url | string | Yes | - | URL to the source file url attribute |
config | object | No | - | Configuration options. By default this object is pre-defined to give typical options for optimization. |
httpusername | string | No | - | HTTP auth user name if required to access source URL. |
httppassword | string | No | - | HTTP auth password if required to access source URL. |
pages | string | No | all pages | Specify page indices as comma-separated values or ranges to process (e.g. “0, 1, 2-” or “1, 2, 3-7”). The first-page index is 0. Use ”!” before a number for inverted page numbers (e.g. “!0” for the last page). If not specified, the default configuration processes all pages. The input must be in string format. |
password | string | No | - | Password for the PDF file. |
async | boolean | No | 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 & Callbacks |
name | string | No | - | File name for the generated output, the input must be in string format. |
expiration | integer | No | 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. |
profiles | object | No | - | See Profiles for more information. |
outputDataFormat | string | No | - | If you require your output as base64 format, set this to base64 |
JPEGQuality | integer | No | 25 | Controls JPEG compression quality from 1 (worst quality, smallest size) to 100 (best quality, largest size). |
config
The config object defines granular settings for the compression process as follows:
| Attribute | Description | Required |
|---|---|---|
images | Contains key/value pairs to define how images should be compressed. | Yes |
save | Contains key/value pairs to define how saving should be performed. | Yes |
config.images
Image compression options. Each key defines how to treat certain image types in the document. In this way you can target color, grayscale or monochrome images with different approaches.
Each key above takes the same bundle of key/value pairs as follows:
Downsample & Compression object
config.images.color, config.images.grayscale & config.images.monochrome all utlize this object schema.
Downsample object
Here you can choose the target ppi / threshold ppi or skip downsampling if you want. The threshold ppi is the limit for which to start downsizing from and the downsample ppi is the target ppi to meet.Example: If the threshold ppi (
threshold_ppi) is 400 and downsample ppi (downsample_ppi) is 250, it will reduce the resolution to 250 ppi for any images with resolution equal or higher than 400 ppi.| Key | Type | Description |
|---|---|---|
skip | boolean. Default isfalse. | Boolean to indicate whether to skip downsizing. |
downsample_ppi | number | The target PPI. Default is150forcolorandgrayscale,300formonochrome. |
threshold_ppi | number | The threshold PPI. Default is225forcolorandgrayscale,450formonochrome. |
Compression object
Here you can choose different compression options for each image type:color, grayscale or monochrome.
| Key | Type | Description |
|---|---|---|
skip | boolean. Default isfalse. | Boolean to indicate whether to skip compressing. |
compression_format | string | Available algorithms arejpeg,jpeg2000,CCITTGroup4,CCITTGroup3,zip. |
compression_params | object | An object which contains the quality settings. |
Compression parameters object
Depending on what you have set for thecompression_format algorithm you have different options.
jpeg: can choose qualityjpeg2000: can choose quality and layers
| Key | Type | Description |
|---|---|---|
quality | number | The quality setting for the image,0~100. Default is60. |
"compression_format": "jpeg",
"compression_params": {
"quality": 60
}
--- | --- | --- |
| quality_mode | string. Either “rates” or “dB” depending on the units you want to use to specify image quality. Default is “rates”. | String used to define quality mode for JPEG2000. |
| quality_layers | number[]. A sequence of numbers, each of which represents either an approximate size reduction (if quality mode is “rates”) or a signal to noise ratio value in decibels. If not specified, defaults to a single layer of full quality. Default is[30]ifquality_modeis “rates”. Default is[38.0,34.0,30.0]ifquality_modeis “dB”. | An array of numbers for the layers. |
Example
"compression_format": "jpeg2000",
"compression_params": {
"quality_mode": "dB",
"quality_layers": [38.0, 34.0, 31.0]
}
config.save
Contains one key for use with garbage collection to free up space that has been allocated to objects no longer needed.
| Key | Type | Description |
|---|---|---|
garbage | number | Garbage collection option. |
config.save.garbage
| Value | Description |
|---|---|
0 | none |
1 | remove unused (unreferenced) objects. |
2 | in addition to 1, compact the xref table. |
3 | in addition to 2, merge duplicate objects. |
4(default) | in addition to 3, check stream objects for duplication. |
"save": {
"garbage": 4
}
The default config object
The defaultconfig is set to match the standard configuration for image optimization by Adobe Acrobat Pro and is defined as follows:
{
"images": {
"color": {
"skip": false,
"downsample": {
"skip": false,
"downsample_ppi": 150,
"threshold_ppi": 225
},
"compression": {
"skip": false,
"compression_format": "jpeg",
"compression_params": {
"quality": 60
}
}
},
"grayscale": {
"skip": false,
"downsample": {
"skip": false,
"downsample_ppi": 150,
"threshold_ppi": 225
},
"compression": {
"skip": false,
"compression_format": "jpeg",
"compression_params": {
"quality": 60
}
}
},
"monochrome": {
"skip": false,
"downsample": {
"skip": false,
"downsample_ppi": 300,
"threshold_ppi": 450
},
"compression": {
"skip": false,
"compression_format": "ccitt_g4",
"compression_params": {}
}
}
},
"save": {
"garbage": 4
}
}
Query parameters
No query parameters accepted.Responses
| Parameter | Type | Description |
|---|---|---|
pageCount | integer | Number of pages in the PDF document. |
error | boolean | Indicates whether an error occurred (false means success) |
status | string | Status code of the request (200, 404, 500, etc.). For more information, see Response Codes. |
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 |
url | string | Direct URL to the final PDF file stored in S3. |
name | string | Name of the output file |
outputLinkValidTill | string | Timestamp indicating when the output link will expire |
Example Payload
To see the request size limits, please refer to the Request Size Limits.
{
"url": "https://pdfco-test-files.s3.us-west-2.amazonaws.com/pdf-compress/sample.pdf",
"async": false,
"config": {
"images": {
"color": {
"skip": false,
"downsample": {
"skip": false,
"downsample_ppi": 150,
"threshold_ppi": 225
},
"compression": {
"skip": false,
"compression_format": "jpeg",
"compression_params": {
"quality": 60
}
}
},
"grayscale": {
"skip": false,
"downsample": {
"skip": false,
"downsample_ppi": 150,
"threshold_ppi": 225
},
"compression": {
"skip": false,
"compression_format": "jpeg",
"compression_params": {
"quality": 60
}
}
},
"monochrome": {
"skip": false,
"downsample": {
"skip": false,
"downsample_ppi": 300,
"threshold_ppi": 450
},
"compression": {
"skip": false,
"compression_format": "ccitt_g4",
"compression_params": {}
}
}
},
"save": {
"garbage": 4
}
}
}
Example Response
To see the main response codes, please refer to the Response Codes page.
{
"pageCount": 2,
"error": false,
"status": 200,
"credits": 70,
"remainingCredits": 999860,
"duration": 8768,
"url": "https://pdf-temp-files-stage.s3.amazonaws.com/Q5LRG3405GT14GNBBP8N58IXIUKF6NJO/compress-test-file.pdf?response-content-type=application%2Foctet-stream&response-content-disposition=attachment%3B%20filename%3D%22compress-test-file.pdf%22&AWSAccessKeyId=ASIASXN3AR4TZVP6G2PQ&Signature=h2Ffqd3OBDzaVmEPxJ%2BmTdbLMsI%3D&x-amz-security-token=IQoJb3JpZ2luX2VjEO%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEaCXVzLXdlc3QtMiJIMEYCIQDgXKbzaSp%2FaJrC3SWlRorreN9x%2BbkJ%2BgEHAaOVV7E8ygIhANXdm4YRa9qLMdI2r3qS%2FJzW4qBMTiQQ5tNyxumuDeBkKv4CCEgQABoMMTg3NzYwMTUyMzU5IgySpYVqM8WXbK4IUxUq2wLnZiRWas5oBdBpcNHBtF9dScpq0bVYoBwJRnw0lsLsCMLhutefsj9CGr9ErvwxrYmmDIrZ4vC%2FWJ3y%2Bu6d5tN1CR%2BvjpAcLzS9S0g35ISj3CpJBf6MIQh1VAi0jdBxqHRtnwyePGTGTdNKjyiWAbhTt291muIFdqNLFwEtajiJp3%2FgbeZV1Lz1D64ZmI%2FF8z8uiwIkuSC7B9yMK47nXavLUE4grcV4FIBi72KLYu3Ox4fW3dvgHQ0fidQbuyx25YLg2UytBrdrGVUJNcFaYPisP76dqJXZABYtGShEnx%2FLUvltnRKXDAnbJWF8JvpL7RNmTy9Os5juXjL2q6pI2NGPQWG9Z49CFbiBoDnQbqedbTIx%2F8klYHfe7X84V2fHVSu%2BvvOcP02nd9%2F8zyN%2FUxxausV5bH4rB5Jf925CYa42T5UQ7549bmXfh9zTfCO2ieDEOPhae8mmZ7VMJjDC%2BOC%2BBjqdASP%2BO3P0TicxozEfw9RDPChcqE2yXP2VuEqJV37063fojqHFE1eVPYDjdpMo2OTskboP6PiRL9obIzgBgA4BhTZmQegcOXNEkB57FjGLnoqrRt092FOuqAa0uws1U8DJz6yjlbgxh5bCB6NLtsTJT02MB%2B7O2Bw3j2ILZefWUAELaI9FSkLzSsyHKtWtj2I90oLYomZUb8NkvW5YXkg%3D&Expires=1742228055",
"name": "compress-test-file.pdf",
"outputLinkValidTill": "2025-03-17T16:14:15.296664+00:00"
}
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.Code Samples
- CURL (Simple use case)
- CURL (Defining configuration options)
- JavaScript/Node.js
- Python
- C#
- Java
- PHP
curl --location 'https://api.pdf.co/v2/pdf/compress' \
--header 'Content-Type: application/json' \
--header 'x-api-key: *******************' \
--data '{
"async": false,
"url": "https://pdfco-test-files.s3.us-west-2.amazonaws.com/pdf-compress/sample.pdf"
}'
curl --location 'https://api.pdf.co/v2/pdf/compress' \n--header 'Content-Type: application/json' \n--header 'x-api-key: *******************' \n--data '{\n "async": false,\n "url": "https://pdfco-test-files.s3.us-west-2.amazonaws.com/pdf-compress/sample.pdf",\n "config": {\n "images": {\n "color": {\n "skip": false,\n "downsample": {\n "skip": false,\n "downsample_ppi": 150,\n "threshold_ppi": 225\n },\n "compression": {\n "skip": false,\n "compression_format": "jpeg",\n "compression_params": {\n "quality": 50\n }\n }\n },\n "grayscale": {\n "skip": false,\n "downsample": {\n "skip": false,\n "downsample_ppi": 150,\n "threshold_ppi": 225\n },\n "compression": {\n "skip": false,\n "compression_format": "jpeg2000",\n "compression_params": {\n "quality_mode": "dB",\n "quality_layers": [36.0]\n }\n }\n },\n "monochrome": {\n "skip": false,\n "downsample": {\n "skip": false,\n "downsample_ppi": 300,\n "threshold_ppi": 450\n },\n "compression": {\n "skip": false,\n "compression_format": "ccitt_g4",\n "compression_params": {}\n }\n }\n },\n "save": {\n "garbage": 4\n }\n }\n}'
/*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);
});
});
}
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 compressPDF(apiKey, uploadedFileUrl, password, destinationFile) {
// Prepare request to `Compress PDF` API endpoint
var queryPath = `/v2/pdf/compress`;
// 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!`);
if (data.error == false) {
checkIfJobIsCompleted(data.jobId, data.url, destinationFile);
}
else {
// Service reported error
console.log("readBarcodes(): " + data.message);
}
});
})
.on("error", (e) => {
// Request error
console.log("readBarcodes(): " + e);
});
// Write request data
postRequest.write(jsonPayload);
postRequest.end();
}
function checkIfJobIsCompleted(jobId, resultFileUrl, destinationFile) {
let queryPath = `/v1/job/check`;
// JSON payload for api request
let jsonPayload = JSON.stringify({
jobid: jobId
});
let reqOptions = {
host: "api.pdf.co",
path: queryPath,
method: "POST",
headers: {
"x-api-key": API_KEY,
"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(`Checking Job #${jobId}, Status: ${data.status}, Time: ${new Date().toLocaleString()}`);
if (data.status == "working") {
// Check again after 3 seconds
setTimeout(function () { checkIfJobIsCompleted(jobId, resultFileUrl, destinationFile); }, 3000);
}
else if (data.status == "success") {
// Download PDF file
var file = fs.createWriteStream(destinationFile);
https.get(resultFileUrl, (response2) => {
response2.pipe(file)
.on("close", () => {
console.log(`Generated PDF file saved as "${destinationFile}" file.`);
});
});
}
else {
console.log(`Operation ended with status: "${data.status}".`);
}
})
});
// Write request data
postRequest.write(jsonPayload);
postRequest.end();
}
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/v2"
# Direct URL of source PDF file.
# You can also upload your own file into PDF.co and use it as url. Check "Upload File" samples for code snippets: https://github.com/pdfdotco/pdf-co-api-samples/tree/master/File%20Upload/
SourceFileURL = "https://pdfco-test-files.s3.us-west-2.amazonaws.com/pdf-compress/sample.pdf"
# PDF document password. Leave empty for unprotected documents.
Password = ""
# Destination PDF file name
DestinationFile = ".\\result.pdf"
# (!) Make asynchronous job
Async = True
def main(args = None):
compressePDF(SourceFileURL, DestinationFile)
def compressePDF(uploadedFileUrl, destinationFile):
"""Compress PDF using PDF.co Web API"""
# Prepare requests params as JSON
# See documentation: https://docs.pdf.co
parameters = {}
parameters["async"] = Async
parameters["name"] = os.path.basename(destinationFile)
parameters["password"] = Password
parameters["url"] = uploadedFileUrl
# Prepare URL for 'Compress PDF' API request
url = "{}/pdf/compress".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
resultFileUrl = 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":
# Download result file
r = requests.get(resultFileUrl, stream=True)
if (r.status_code == 200):
with open(destinationFile, 'wb') as file:
for chunk in r:
file.write(chunk)
print(f"Result file saved as \"{destinationFile}\" file.")
else:
print(f"Request error: {response.status_code} {response.reason}")
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
if __name__ == '__main__':
main()
using System;
using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;
using System.Threading;
using System.Collections.Generic;
using Newtonsoft.Json;
// Cloud API asynchronous "Compress PDF" job example.
// Allows to avoid timeout errors when processing huge or scanned PDF documents.
namespace PDFcoApiExample
{
class Program
{
// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co
const String API_KEY = "***********************************";
// Direct URL of source PDF file.
// You can also upload your own file into PDF.co and use it as url. Check "Upload File" samples for code snippets: https://github.com/pdfdotco/pdf-co-api-samples/tree/master/File%20Upload/
const string SourceFileUrl = "https://pdfco-test-files.s3.us-west-2.amazonaws.com/pdf-compress/sample.pdf";
// PDF document password. Leave empty for unprotected documents.
const string Password = "";
// Destination PDF file name
const string DestinationFile = @".\result.pdf";
// (!) Make asynchronous job
const bool Async = 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);
// URL for `Compress PDF` API call
string url = "https://api.pdf.co/v2/pdf/compress";
// Prepare requests params as JSON
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("name", Path.GetFileName(DestinationFile));
parameters.Add("password", Password);
parameters.Add("url", SourceFileUrl);
parameters.Add("async", Async);
// Convert dictionary of params to JSON
string jsonPayload = JsonConvert.SerializeObject(parameters);
try
{
// Execute POST request with JSON payload
string response = webClient.UploadString(url, jsonPayload);
// Parse JSON response
JObject json = JObject.Parse(response);
if (json["error"].ToObject<bool>() == false)
{
// Asynchronous job ID
string jobId = json["jobId"].ToString();
// URL of generated PDF file that will available after the job completion
string resultFileUrl = json["url"].ToString();
// 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.
do
{
string status = CheckJobStatus(jobId); // Possible statuses: "working", "failed", "aborted", "success".
// Display timestamp and status (for demo purposes)
Console.WriteLine(DateTime.Now.ToLongTimeString() + ": " + status);
if (status == "success")
{
// Download PDF file
webClient.DownloadFile(resultFileUrl, DestinationFile);
Console.WriteLine("Generated PDF file saved as \"{0}\" file.", DestinationFile);
break;
}
else if (status == "working")
{
// Pause for a few seconds
Thread.Sleep(3000);
}
else
{
Console.WriteLine(status);
break;
}
}
while (true);
}
else
{
Console.WriteLine(json["message"].ToString());
}
}
catch (WebException e)
{
Console.WriteLine(e.ToString());
}
webClient.Dispose();
Console.WriteLine();
Console.WriteLine("Press any key...");
Console.ReadKey();
}
static string CheckJobStatus(string jobId)
{
using (WebClient webClient = new WebClient())
{
// Set API Key
webClient.Headers.Add("x-api-key", API_KEY);
string url = "https://api.pdf.co/v1/job/check?jobid=" + jobId;
string response = webClient.DownloadString(url);
JObject json = JObject.Parse(response);
return Convert.ToString(json["status"]);
}
}
}
}
package com.company;
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 = "***********************************";
// Direct URL of source PDF file.
// You can also upload your own file into PDF.co and use it as url. Check "Upload File" samples for code snippets: https://github.com/pdfdotco/pdf-co-api-samples/tree/master/File%20Upload/
final static String SourceFileUrl = "https://pdfco-test-files.s3.us-west-2.amazonaws.com/pdf-compress/sample.pdf";
// PDF document password. Leave empty for unprotected documents.
final static String Password = "";
// Destination PDF file name
final static Path DestinationFile = Paths.get(".\\result.pdf");
public static void main(String[] args) throws IOException
{
// Create HTTP client instance
OkHttpClient webClient = new OkHttpClient();
// Prepare URL for `Compress PDF` API call
String query = "https://api.pdf.co/v2/pdf/compress";
// 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("{\"name\": \"%s\", \"password\": \"%s\", \"url\": \"%s\"}",
DestinationFile.getFileName(),
Password,
SourceFileUrl);
// 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)
{
// Get URL of generated PDF file
String resultFileUrl = json.get("url").getAsString();
// Download PDF file
downloadFile(webClient, resultFileUrl, DestinationFile.toFile());
System.out.printf("Generated PDF file saved as \"%s\" file.", DestinationFile.toString());
}
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 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
// Cloud API asynchronous "Compress PDF" job example.
// Allows to avoid timeout errors when processing huge or scanned PDF documents.
// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co
$apiKey = "***********************************";
// Direct URL of source PDF file. Check another example if you need to upload a local file to the cloud.
// You can also upload your own file into PDF.co and use it as url. Check "Upload File" samples for code snippets: https://github.com/pdfdotco/pdf-co-api-samples/tree/master/File%20Upload/
$sourceFileUrl = "https://pdfco-test-files.s3.us-west-2.amazonaws.com/pdf-compress/sample.pdf";
// PDF document password. Leave empty for unprotected documents.
$password = "";
// Prepare URL for `Compress PDF` API call
$url = "https://api.pdf.co/v2/pdf/compress";
// Prepare requests params
$parameters = array();
$parameters["password"] = $password;
$parameters["url"] = $sourceFileUrl;
$parameters["async"] = true; // (!) Make asynchronous job
// Create Json payload
$data = json_encode($parameters);
// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey, "Content-type: application/json"));
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
// Execute request
$result = curl_exec($curl);
if (curl_errno($curl) == 0)
{
$status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($status_code == 200)
{
$json = json_decode($result, true);
if (!isset($json["error"]) || $json["error"] == false)
{
// URL of generated PDF file that will available after the job completion
$resultFileUrl = $json["url"];
// Asynchronous job ID
$jobId = $json["jobId"];
// Check the job status in a loop
do
{
$status = CheckJobStatus($jobId, $apiKey); // Possible statuses: "working", "failed", "aborted", "success".
// Display timestamp and status (for demo purposes)
echo "<p>" . date(DATE_RFC2822) . ": " . $status . "</p>";
if ($status == "success")
{
// Display link to the file with conversion results
echo "<div><h2>Conversion Result:</h2><a href='" . $resultFileUrl . "' target='_blank'>" . $resultFileUrl . "</a></div>";
break;
}
else if ($status == "working")
{
// Pause for a few seconds
sleep(3);
}
else
{
echo $status . "<br/>";
break;
}
}
while (true);
}
else
{
// Display service reported error
echo "<p>Error: " . $json["message"] . "</p>";
}
}
else
{
// Display request error
echo "<p>Status code: " . $status_code . "</p>";
echo "<p>" . $result . "</p>";
}
}
else
{
// Display CURL error
echo "Error: " . curl_error($curl);
}
// Cleanup
curl_close($curl);
function CheckJobStatus($jobId, $apiKey)
{
$status = null;
// Create URL
$url = "https://api.pdf.co/v1/job/check";
// Prepare requests params
$parameters = array();
$parameters["jobid"] = $jobId;
// Create Json payload
$data = json_encode($parameters);
// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey, "Content-type: application/json"));
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
// Execute request
$result = curl_exec($curl);
if (curl_errno($curl) == 0)
{
$status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($status_code == 200)
{
$json = json_decode($result, true);
if (!isset($json["error"]) || $json["error"] == false)
{
$status = $json["status"];
}
else
{
// Display service reported error
echo "<p>Error: " . $json["message"] . "</p>";
}
}
else
{
// Display request error
echo "<p>Status code: " . $status_code . "</p>";
echo "<p>" . $result . "</p>";
}
}
else
{
// Display CURL error
echo "Error: " . curl_error($curl);
}
// Cleanup
curl_close($curl);
return $status;
}
?>
</body>
</html>