PDF Rotate Pages#

/pdf/edit/rotate#

Rotates selected pages inside a PDF file.

  • Method: POST

  • Endpoint: /v1/pdf/edit/rotate

Attributes#

Note

Attributes are case-sensitive and should be inside JSON for POST request, for example:

{
    "url": "https://example.com/file1.pdf"
}

Attribute

Description

Required

url

URL to the source file. 1

yes

angle

Angle in degrees. Supported values 90, 180, and 270.

no

httpusername

HTTP auth user name if required to access source url.

no

httppassword

HTTP auth password if required to access source url.

no

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.

no

async

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 to check the status of the process and retrieve the output while you can proceed with other tasks.

no

profiles

Use this parameter to set additional configurations for fine-tuning and extra options. Explore the Profiles section for more.

no

Query parameters#

No query parameters accepted.

Payload 3#

{
    "url": "https://pdfco-test-files.s3.us-west-2.amazonaws.com/pdf-optimize/sample.pdf",
    "name": "result.pdf",
    "angle": 90,
    "pages": "0-2,4"
}

Response 2#

{
    "url": "https://pdf-temp-files.s3.us-west-2.amazonaws.com/2EK4QYIZU1XUEUH853VTSK47NPLXCUYX/result.pdf?X-Amz-Expires=3600&X-Amz-Security-Token=FwoGZXIvYXdzEFsaDC5Vfgoi83YzdW9HXiKCAYBVHK096wqoUyu8Ckq8jEhV1DBv9VzHY1EcPWvfG3L2YrFa8QC5ZMr3UhFEn4%2B%2B2u6e%2FcdZd%2FXbdVaI45yNE%2Btz28UHMVxCQUClj9kCHrMyJ4W1%2BlnDgLi9JUHt7SkIvV9Lj7GLDBOXy22KCND86HdtPg0uT%2FNQtcjJm%2F34cISImKYov63NlQYyKG%2BEO%2FQLP%2BzJuugBdSLcKUOTL52dnc1l82ye1u5kYvTlbfPMdisU1tY%3D&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=ASIA4NRRSZPHESTCUXXF/20220623/us-west-2/s3/aws4_request&X-Amz-Date=20220623T135902Z&X-Amz-SignedHeaders=host&X-Amz-Signature=78f2fe7f22ebd1fc2c329a855c7582f9deb09c0c5045281b9b2420a5afb792cf",
    "fileSize": 1064923,
    "pageCount": 4,
    "error": false,
    "status": 200,
    "name": "result.pdf",
    "credits": 28,
    "duration": 245,
    "remainingCredits": 98194839
}

CURL#

curl --location --request POST 'https://api.pdf.co/v1/pdf/edit/rotate' \
--header 'x-api-key: *******************' \
--header 'Content-Type: application/json' \
--data-raw '{
    "url": "https://pdfco-test-files.s3.us-west-2.amazonaws.com/pdf-optimize/sample.pdf",
    "name": "result.pdf",
    "angle": 90,
    "pages": "0-2,4"
}'


/pdf/edit/rotate/auto#

Uses AI to automatically fix the rotation of pages inside scanned PDF based on text analysis. To change text language change the lang parameter (eng by default).

  • Method: POST

  • Endpoint: /v1/pdf/edit/rotate/auto

Attributes#

Note

Attributes are case-sensitive and should be inside JSON for POST request, for example:

{
    "url": "https://example.com/file1.pdf"
}

Attribute

Description

Required

url

URL to the source file. 1

yes

lang

Set the language for OCR (text from image) to use for scanned PDF, PNG, and JPG documents input when extracting text. The default is eng. Other languages are also supported: deu, spa, chi_sim, jpn, and many others, see Language Support. You can also use 2 languages simultaneously like this: eng+deu or jpn+kor (any combination).

no

httpusername

HTTP auth user name if required to access source url.

no

httppassword

HTTP auth password if required to access source url.

no

async

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 to check the status of the process and retrieve the output while you can proceed with other tasks.

no

profiles

Use this parameter to set additional configurations for fine-tuning and extra options. Explore the Profiles section for more.

no

Query parameters#

No query parameters accepted.

Payload 3#

{
    "url": "https://pdfco-test-files.s3.us-west-2.amazonaws.com/pdf-fix-rotation/rotated_pages.pdf",
    "name": "result.pdf"
}

Response 2#

{
    "url": "https://pdf-temp-files.s3.us-west-2.amazonaws.com/HQ86WA7MFED1Q7C843NDSKVRW5AFVTMP/result.pdf?X-Amz-Expires=3600&X-Amz-Security-Token=FwoGZXIvYXdzEFwaDD6ndEhlfId4KouQ8yKCASr8amowIV2tLAi%2BhjnlVi%2FNYjf8ZJ3MqgKWsYVm5dQ8fQx7hceGdmtqhB6OH8t9xdacbMEcoMIpQr1BcSSfu2ZFfGFBDaHNpaSTfPXhkNnQaZFOi5KFozZiPBP9xPoSCV%2Fj%2BLIrDsOF%2Fb89i1Nd4OJFoXnfhjf03ZHJ%2BNCQEC%2BbePsovsjNlQYyKIV1qb1wGdwgJ%2ByibJ5x%2BQGoG4x2ebnEGTQkKBf4zobYT9Uv6FVQ%2FJg%3D&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=ASIA4NRRSZPHB3D5EZ56/20220623/us-west-2/s3/aws4_request&X-Amz-Date=20220623T141005Z&X-Amz-SignedHeaders=host&X-Amz-Signature=351ad45980cad0d3f634f7b784d5445b9c4e1ad2244912f56ea065209d73bb30",
    "fileSize": 455115,
    "pageCount": 3,
    "error": false,
    "status": 200,
    "name": "result.pdf",
    "credits": 84,
    "duration": 6002,
    "remainingCredits": 98194629
}

CURL#

curl --location --request POST 'https://api.pdf.co/v1/pdf/edit/rotate/auto' \
--header 'x-api-key: *******************' \
--header 'Content-Type: application/json' \
--data-raw '{
    "url": "https://pdfco-test-files.s3.us-west-2.amazonaws.com/pdf-fix-rotation/rotated_pages.pdf",
    "name": "result.pdf"
}'


Code samples (/pdf/edit/rotate)#

var https = require("https");
var path = require("path");
var fs = require("fs");


// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co
const 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/bytescout/pdf-co-api-samples/tree/master/File%20Upload/
const SourceFileUrl = "https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/pdf-optimize/sample.pdf";

// Angle in degrees. Supported values are 90, 180, 270.
const Angle = 90;

// Comma-separated list of page indices (or ranges) to process. Example: '0,3-5,7-'. For ALL pages just leave this param empty
const Pages = "0-2,4";

// Destination PDF file name
const DestinationFile = "./result.pdf";

// Prepare request to `Rotate PDF` API endpoint
var queryPath = `/v1/pdf/edit/rotate`;

// JSON payload for api request
var jsonPayload = JSON.stringify({
    url: SourceFileUrl, name: path.basename(DestinationFile), angle: Angle, pages: Pages, async: true
});

var reqOptions = {
    host: "api.pdf.co",
    method: "POST",
    path: queryPath,
    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) => {
        // Parse JSON response
        var data = JSON.parse(d);
        if (data.error == false) {
            console.log(`Job #${data.jobId} has been created!`);
            checkIfJobIsCompleted(data.jobId, data.url);
        }
        else {
            // Service reported error
            console.log(data.message);
        }
    });
}).on("error", (e) => {
    // Request error
    console.log(e);
});

// Write request data
postRequest.write(jsonPayload);
postRequest.end();

function checkIfJobIsCompleted(jobId, resultFileUrl) {
    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); }, 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/v1"

# 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/bytescout/pdf-co-api-samples/tree/master/File%20Upload/
SourceFileURL = "https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/pdf-optimize/sample.pdf"

# Angle in degrees. Supported values are 90, 180, 270.
Angle = 90

# Comma-separated list of page indices (or ranges) to process. Example: '0,3-5,7-'. For ALL pages just leave this param empty
Pages = "0-2,4"

# Destination PDF file name
DestinationFile = ".\\result.pdf"

# (!) Make asynchronous job
Async = True


def main(args = None):
    rotatePDF(SourceFileURL, DestinationFile)


def rotatePDF(uploadedFileUrl, destinationFile):
    """Rotate PDF using PDF.co Web API"""

    # Prepare requests params as JSON
    # See documentation: https://developer.pdf.co/
    parameters = {}
    parameters["url"] = uploadedFileUrl
    parameters["name"] = os.path.basename(destinationFile)
    parameters["angle"] = Angle
    parameters["pages"] = Pages
    parameters["async"] = Async

    # Prepare URL for 'Rotate PDF' API request
    url = "{}/pdf/edit/rotate".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 "Rotate PDF" job example.
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/bytescout/pdf-co-api-samples/tree/master/File%20Upload/
    const string SourceFileUrl = "https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/pdf-optimize/sample.pdf";

    // Angle in degrees. Supported values are 90, 180, 270.
    const int Angle = 90;

    // Comma-separated list of page indices (or ranges) to process. Example: '0,3-5,7-'. For ALL pages just leave this param empty
    const string Pages = "0-2,4";

    // 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 `Rotate PDF` API call
      string url = "https://api.pdf.co/v1/pdf/edit/rotate";

      // Prepare requests params as JSON
      Dictionary<string, object> parameters = new Dictionary<string, object>();
      parameters.Add("url", SourceFileUrl);
      parameters.Add("name", Path.GetFileName(DestinationFile));
      parameters.Add("angle", Angle);
      parameters.Add("pages", Pages);
      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/bytescout/pdf-co-api-samples/tree/master/File%20Upload/
    final static String SourceFileUrl = "https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/pdf-optimize/sample.pdf";

    // Angle in degrees. Supported values are 90, 180, 270.
    final static Integer Angle = 90;

    // Comma-separated list of page indices (or ranges) to process. Example: '0,3-5,7-'. For ALL pages just leave this param empty
    final static String Pages = "0-2,4";

    // 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 `Rotate PDF` API call
        String query = "https://api.pdf.co/v1/pdf/edit/rotate";

        // 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("{\"url\": \"%s\", \"name\": \"%s\", \"angle\": \"%d\", \"pages\": \"%s\"}",
                SourceFileUrl,
                DestinationFile.getFileName(),
                Angle,
                Pages);

        // 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();
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Cloud API asynchronous "Optimize PDF" job example (allows to avoid timeout errors).</title>
</head>
<body>

<?php

// Cloud API asynchronous "Optimize 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/bytescout/pdf-co-api-samples/tree/master/File%20Upload/
$sourceFileUrl = "https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/pdf-optimize/sample.pdf";

// Angle in degrees. Supported values are 90, 180, 270.
$angle = 90;

// Comma-separated list of page indices (or ranges) to process. Example: '0,3-5,7-'. For ALL pages just leave this param empty
$pages = "0-2,4";


// Prepare URL for `Rotate PDF` API call
$url = "https://api.pdf.co/v1/pdf/edit/rotate";

// Prepare requests params
$parameters = array();
$parameters["url"] = $sourceFileUrl;
$parameters["angle"] = $angle;
$parameters["pages"] = $pages;
$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>

Code samples (/pdf/edit/rotate/auto)#

var https = require("https");
var path = require("path");
var fs = require("fs");

// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co
const 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/bytescout/pdf-co-api-samples/tree/master/File%20Upload/
const SourceFileUrl = "https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/pdf-fix-rotation/rotated_pages.pdf";

// Destination PDF file name
const DestinationFile = "./result.pdf";


// Prepare request to `Rotate PDF` API endpoint
var queryPath = `/v1/pdf/edit/rotate/auto`;

// JSON payload for api request
var jsonPayload = JSON.stringify({
    url: SourceFileUrl, name: path.basename(DestinationFile), angle: Angle, pages: Pages
});

var reqOptions = {
    host: "api.pdf.co",
    method: "POST",
    path: queryPath,
    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) => {
        // Parse JSON response
        var data = JSON.parse(d);
        if (data.error == false) {
            // Download PDF file
            var file = fs.createWriteStream(DestinationFile);
            https.get(data.url, (response2) => {
                response2.pipe(file)
                    .on("close", () => {
                        console.log(`Generated PDF file saved as "${DestinationFile}" file.`);
                    });
            });
        }
        else {
            // Service reported error
            console.log(data.message);
        }
    });
}).on("error", (e) => {
    // Request error
    console.log(e);
});

// Write request data
postRequest.write(jsonPayload);
postRequest.end();
import os
import requests # pip install requests

# The authentication key (API Key).
# Get your own by registering at https://app.pdf.co
API_KEY = "******************************************"

# Base URL for PDF.co Web API requests
BASE_URL = "https://api.pdf.co/v1"

# 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/bytescout/pdf-co-api-samples/tree/master/File%20Upload/
SourceFileURL = "https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/pdf-fix-rotation/rotated_pages.pdf"

# Destination PDF file name
DestinationFile = ".\\result.pdf"

def main(args = None):
    rotatePDF(SourceFileURL, DestinationFile)


def rotatePDF(uploadedFileUrl, destinationFile):
    """Auto Rotate PDF using PDF.co Web API"""

    # Prepare requests params as JSON
    # See documentation: https://developer.pdf.co/
    parameters = {}
    parameters["url"] = uploadedFileUrl
    parameters["name"] = os.path.basename(destinationFile)

    # Prepare URL for 'Auto Rotate PDF' API request
    url = "{}/pdf/edit/rotate/auto".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:
            #  Get URL of result file
            resultFileUrl = json["url"]
            # 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}")
        else:
            # Show service reported error
            print(json["message"])
    else:
        print(f"Request error: {response.status_code} {response.reason}")

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 = "*********************************";

    // 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/bytescout/pdf-co-api-samples/tree/master/File%20Upload/
    const string SourceFileUrl = "https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/pdf-fix-rotation/rotated_pages.pdf";

    // Destination PDF file name
    const string DestinationFile = @".\result.pdf";

    static void Main(string[] args)
    {
      // Create standard .NET web client instance
      WebClient webClient = new WebClient();

      // Set API Key
      webClient.Headers.Add("x-api-key", API_KEY);

      // URL for `Auto Rotate PDF` API call
      string url = "https://api.pdf.co/v1/pdf/edit/rotate/auto";

      // Prepare requests params as JSON
      Dictionary<string, object> parameters = new Dictionary<string, object>();
      parameters.Add("url", SourceFileUrl);
      parameters.Add("name", Path.GetFileName(DestinationFile));

      // 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)
        {
          // Get URL of generated PDF file
          string resultFileUrl = json["url"].ToString();

          // Download PDF file
          webClient.DownloadFile(resultFileUrl, DestinationFile);

          Console.WriteLine("Generated PDF file saved as \"{0}\" file.", DestinationFile);
        }
        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.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/bytescout/pdf-co-api-samples/tree/master/File%20Upload/
    final static String SourceFileUrl = "https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/pdf-fix-rotation/rotated_pages.pdf";

    // 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 `Rotate PDF` API call
        String query = "https://api.pdf.co/v1/pdf/edit/rotate/auto";

        // 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("{\"url\": \"%s\", \"name\": \"%s\"}",
                SourceFileUrl,
                DestinationFile.getFileName());

        // 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();
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Cloud API asynchronous "Optimize PDF" job example (allows to avoid timeout errors).</title>
</head>
<body>

<?php

// Cloud API asynchronous "Optimize 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/bytescout/pdf-co-api-samples/tree/master/File%20Upload/
$sourceFileUrl = "https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/pdf-fix-rotation/rotated_pages.pdf";

// Prepare URL for `Rotate PDF` API call
$url = "https://api.pdf.co/v1/pdf/edit/rotate/auto";

// Prepare requests params
$parameters = array();
$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>

On Github#

Footnotes

1(1,2)

Supports publicly accessible links from any source, including Google Drive, Dropbox, and PDF.co Built-In Files Storage. To upload files via the API, check out the File Upload section. Note: If you experience intermittent Access Denied or Too Many Requests errors, please try adding cache: to enable built-in URL caching (e.g., cache:https://example.com/file1.pdf). For data security, you have the option to encrypt output files and decrypt input files. Learn more about user-controlled data encryption.

2(1,2)

Main response codes as follows:

Code

Description

200

Success

400

Bad request. Typically happens because of bad input parameters, or because the input URLs can’t be reached, possibly due to access restrictions like needing a login or password.

401

Unauthorized

402

Not enough credits

445

Timeout error. To process large documents or files please use asynchronous mode (set the async parameter to true) and then check status using the /job/check endpoint. If a file contains many pages then specify a page range using the pages parameter. The number of pages of the document can be obtained using the /pdf/info endpoint.

3(1,2)

PDF.co Request size: API requests do not support request sizes of more than 4 megabytes in size. Please ensure that request sizes do not exceed this limit.