> ## Documentation Index
> Fetch the complete documentation index at: https://developer.pdf.co/llms.txt
> Use this file to discover all available pages before exploring further.

# PDF to JPG

> PDF to high quality JPEG image conversion. High quality rendering. Also works great for thumbnail generation and previews.

## Common Use Cases

* Generate thumbnail previews of PDF pages for a document library or gallery
* Convert scanned paperwork into images for display in a web app
* Create shareable image versions of a PDF page for social media or email
* Extract individual pages as images for further processing (e.g. OCR, image editing)

<Note>
  **Try it live:** [PDF to JPG → API Tester](/api-tester/pdf-to-image/jpg) — send a real request from your browser.
</Note>

## `POST /v1/pdf/convert/to/jpg`

## Request body

<Note>Attributes are case-sensitive and should be inside JSON for POST request. for example: `{ "url": "https://example.com/file1.pdf" }` *No query parameters accepted.*</Note>

<Note>To see the request size limits, please refer to the [Request Size Limits](/api/url-input-and-request-limits#pdf-co-request-size).</Note>

<ParamField body="url" type="string" required>
  URL to the source file [`url` attribute](/api/url-input-and-request-limits#supported-file-sources)
</ParamField>

<ParamField body="callback" type="string">
  The callback URL (or Webhook) used to receive the POST data. see [Webhooks & Callbacks](/api/webhooks). This is only applicable when `async` is set to `true`.
</ParamField>

<ParamField body="httpusername" type="string">
  HTTP auth user name if required to access source URL.
</ParamField>

<ParamField body="httppassword" type="string">
  HTTP auth password if required to access source URL.
</ParamField>

<ParamField body="pages" type="string" default="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.
</ParamField>

<ParamField body="rect" type="string">
  Defines coordinates for extraction. Use`PDF Edit Add Helper`to get or measure PDF coordinates. The format is `{x} {y} {width} {height}`.
</ParamField>

<ParamField body="inline" type="boolean" default="false">
  Set to true to return results inside the response. Otherwise, the endpoint will return a URL to the output file generated.
</ParamField>

<ParamField body="password" type="string">
  Password for the PDF file.
</ParamField>

<ParamField body="async" type="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](/api/job-check). Also see [Webhooks & Callbacks](/api/webhooks)
</ParamField>

<ParamField body="name" type="string">
  File name for the generated output, the input must be in string format.
</ParamField>

<ParamField body="expiration" type="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](/api/file-upload/overview). 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](https://app.pdf.co/tools/files).
</ParamField>

<ParamField body="profiles" type="string">
  Pass profile settings as a JSON-encoded string. See [Profiles](/api/profiles) for more information.
</ParamField>

<Expandable title="profiles properties">
  | Setting | Type | Description |
  | - | - | - |
  | `outputDataFormat` | string | If you require your output as `base64` format, set this to `base64` |
  | `RotationAngle` | integer | Use manual rotation to handle PDFs with vertically drawn text. Normally, OCR automatically detects page rotation in PDFs and extracts text accurately. However, in some cases, the PDF might not have an actual rotated page  ---  Rather, the text itself is drawn vertically. In such scenarios, auto-detection may fail. You can use this parameter to manually set the page rotation. The available angles are: `0`, `1`, `2`, `3`. |
  | `RenderTextObjects` | boolean (default `true`) | Controls whether to render text objects in the PDF document. When set to true, it will render all text objects in the PDF document. Set to false to skip over text objects during rendering. See [Disable Text Layer](#disable-text-layer) for more information. |
  | `RenderImageObjects` | boolean (default `true`) | Render image objects or not |
  | `RenderVectorObjects` | boolean (default `true`) | Render vector objects or not |
  | `RenderCurveVectorObjects` | boolean (default `true`) | Render curve vector objects or not |
  | `TextSmoothingMode` | string | Controls text smoothing mode. Available options: `HighSpeed`, `HighQuality`. |
  | `VectorSmoothingMode` | string | Controls vector smoothing mode. Available options: `HighSpeed`, `HighQuality`. |
  | `ImageInterpolationMode` | string | Controls image interpolation mode. Available options: `HighSpeed`, `HighQuality`. |
  | `JPEGQuality` | integer (default `80`) | Range from `0` (lowest) to `100` (highest), default is `80`. See [profiles.JPEGQuality](#profiles-jpegquality) |
  | `TIFFCompression` | string | Controls TIFF compression. Available options: `None`, `LZW`, `CCITT3`, `CCITT4`, `RLE`. |
  | `RotateFlipType` | string | Controls rotation and flip type. Available options: `RotateNoneFlipNone`, `Rotate90FlipNone`, `Rotate180FlipNone`, `Rotate270FlipNone`, `RotateNoneFlipX`, `Rotate90FlipX`, `Rotate180FlipX`, `Rotate270FlipX`, `RotateNoneFlipY`, `Rotate90FlipY`, `Rotate180FlipY`, `Rotate270FlipY`, `RotateNoneFlipXY`, `Rotate90FlipXY`, `Rotate180FlipXY`, `Rotate270FlipXY`. |
  | `ImageBitsPerPixel` | string | Controls image bits per pixel. Available options: `BPP1`, `BPP8`, `BPP24`, `BPP32`. |
  | `OneBitConversionAlgorithm` | string | Controls one-bit conversion algorithm. Available options: `BayerOrderedDithering`, `OtsuThreshold`. |
  | `FontHintingMode` | string | Controls font hinting mode. Available options: `Default`, `Stronger`. |
  | `ResolutionOverride` | float | Overrides the default resolution. Specified in DPI. |
  | `NightMode` | boolean (default `false`) | Enables night mode rendering. |
  | `RenderingResolution` | integer (default `120`) | See [Set Image Resolution](#set-image-resolution) for more information. |
  | `DataEncryptionAlgorithm` | string | Controls the encryption algorithm used for data encryption. See [User-Controlled Encryption](/knowledgebase/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](/knowledgebase/user-controlled-encryption) for more information. |
  | `DataEncryptionIV` | string | Controls the encryption IV used for data encryption. See [User-Controlled Encryption](/knowledgebase/user-controlled-encryption) for more information. |
  | `DataDecryptionAlgorithm` | string | Controls the decryption algorithm used for data decryption. See [User-Controlled Encryption](/knowledgebase/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](/knowledgebase/user-controlled-encryption) for more information. |
  | `DataDecryptionIV` | string | Controls the decryption IV used for data decryption. See [User-Controlled Encryption](/knowledgebase/user-controlled-encryption) for more information. |
</Expandable>

### Disable Text Layer

We can turn off the text layer for our render as follows:

```json theme={null}
{
 "profiles": "{\"RenderTextObjects\": false}"
}
```

### Set Image Resolution

By default the screen resolution is 120 DPI. To change the rendering resolution, please use:

```json theme={null}
{
 "profiles": "{\"RenderingResolution\": 300}"
}
```

### `JPEGQuality`

To set image quality (from `0` (lowest) to `100` (highest), default is `80`) please use:

```
{
 "profiles": "{\"JPEGQuality\": 75}"
}
```

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

Profiles section for more.

```json theme={null}
{
 "profiles": "{\"RenderTextObjects\": false, \"RenderVectorObjects\": true, \"RenderImageObjects\": true}"
}
```

### `OCRImagePreprocessingFilters`

To set image preprocessing filters, please use:

```json theme={null}
{
 "profiles": "{\"OCRImagePreprocessingFilters.AddGrayscale()\": [], \"OCRImagePreprocessingFilters.AddGammaCorrection()\": [1.4]}"
}
```

## Responses

```json Synchronous response theme={null}
{
  "urls": [
    "https://pdf-temp-files.s3.amazonaws.com/c15b8d82e0034d01a73eac719d69349b/sample.jpg",
    "https://pdf-temp-files.s3.amazonaws.com/152d2fe414b645e38f81a49e5dafa85b/sample.jpg"
  ],
  "pageCount": 2,
  "error": false,
  "status": 200,
  "name": "sample.jpg",
  "duration": 1121,
  "remainingCredits": 98722216,
  "credits": 24
}
```

| Field | Type | Description |
| - | - | - |
| `urls` | array\[string] | List of URLs to the generated JPEG images stored in S3, typically one image per converted page. |
| `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 | Status code of the request (200, 404, 500, etc.). For more information, see [Response Codes](/api/response-codes). |
| `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`. |

An asynchronous request returns a `jobId` and a reserved URL that should be used only after the job succeeds. Poll it via [Background Job Check](/api/job-check). Errors return `error: true` with a status code and message. See the response examples and [Response Codes](/api/response-codes).

<Note>
  **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.
</Note>

<div id="code-samples" />

<Panel>
  **Sample request**

  <RequestExample dropdown>
    ```bash CURL theme={null}
    curl --location --request POST 'https://api.pdf.co/v1/pdf/convert/to/jpg' \
    --header 'x-api-key: *******************' \
    --header 'Content-Type: application/json' \
    --data-raw '{
    "url": "https://pdfco-test-files.s3.us-west-2.amazonaws.com/pdf-to-image/sample.pdf",
    "inline": true,
    "pages": "0-",
    "async": false
    }'
    ```

    ```javascript JavaScript/Node.js theme={null}
    var https = require("https");
    var path = require("path");
    var fs = require("fs");

    // `request` module is required for file upload.
    // Use "npm install request" command to install.
    var request = require("request");

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


    // Source PDF file
    const SourceFile = "./sample.pdf";
    // Comma-separated list of page indices (or ranges) to process. Leave empty for all pages. Example: '0,2-5,7-'.
    const Pages = "";
    // PDF document password. Leave empty for unprotected documents.
    const Password = "";


    // 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. CONVERT UPLOADED PDF FILE TO IMAGE
                    convertPDFToImage(API_KEY, uploadedFileUrl, Password, Pages, "jpg");
                })
                .catch(e => {
                    console.log(e);
                });
        })
        .catch(e => {
            console.log(e);
        });


    function getPresignedUrl(apiKey, localFile) {
        return new Promise(resolve => {
            // Prepare request to `Get Presigned URL` API endpoint
            let queryPath = `/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name=${path.basename(SourceFile)}`;
            let reqOptions = {
                host: "api.pdf.co",
                path: encodeURI(queryPath),
                headers: { "x-api-key": API_KEY }
            };
            // Send request
            https.get(reqOptions, (response) => {
                response.on("data", (d) => {
                    let data = JSON.parse(d);
                    if (data.error == false) {
                        // Return presigned url we received
                        resolve([data.presignedUrl, data.url]);
                    }
                    else {
                        // Service reported error
                        console.log("getPresignedUrl(): " + data.message);
                    }
                });
            })
                .on("error", (e) => {
                    // Request error
                    console.log("getPresignedUrl(): " + e);
                });
        });
    }

    function uploadFile(apiKey, localFile, uploadUrl) {
        return new Promise(resolve => {
            fs.readFile(SourceFile, (err, data) => {
                request({
                    method: "PUT",
                    url: uploadUrl,
                    body: data,
                    headers: {
                        "Content-Type": "application/octet-stream"
                    }
                }, (err, res, body) => {
                    if (!err) {
                        resolve();
                    }
                    else {
                        console.log("uploadFile() request error: " + err);
                    }
                });
            });
        });
    }

    // `imageType` should correspond to the API we want to use,
    // i.e. /v1/pdf/convert/to/jpg, /v1/pdf/convert/to/png, /v1/pdf/convert/to/webp or /v1/pdf/convert/to/tiff
    // we just take the last part of the path, the file extension
    function convertPDFToImage(apiKey, uploadedFileUrl, password, pages, imageType) {
        // Prepare URL for PDF to Image API call
        var queryPath = `/v1/pdf/convert/to/${imageType}`;

        // JSON payload for api request
        var jsonPayload = JSON.stringify({
            password: password, pages: pages, url: uploadedFileUrl
        });

        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) => {
                response.setEncoding("utf8");
                // Parse JSON response
                let data = JSON.parse(d);
                if (data.error == false) {
                    // Download generated image files
                    var page = 1;
                    data.urls.forEach((url) => {
                        var localFileName = `./page${page}.${imageType}`;
                        var file = fs.createWriteStream(localFileName);
                        https.get(url, (response2) => {
                            response2.pipe(file)
                                .on("close", () => {
                                    console.log(`Generated image file saved as "${localFileName}" file.`);
                                });
                        });
                        page++;
                    }, this);
                }
                else {
                    // Service reported error
                    console.log("convertPDFToImage(): " + data.message);
                }
            });
        })
            .on("error", (e) => {
                // Request error
                console.log("convertPDFToImage(): " + e);
            });

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

    }
    ```

    ```python Python theme={null}
    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"

    # Source PDF file
    SourceFile = ".\\sample.pdf"
    # Comma-separated list of page indices (or ranges) to process. Leave empty for all pages. Example: '0,2-5,7-'.
    Pages = ""
    # PDF document password. Leave empty for unprotected documents.
    Password = ""

    def main(args = None):
        uploadedFileUrl = uploadFile(SourceFile)
        if (uploadedFileUrl != None):
            convertPDFToImage(uploadedFileUrl, "jpg")


    def convertPDFToImage(uploadedFileUrl, imageType):
        """Converts PDF To Image using PDF.co Web API"""

        # Prepare requests params as JSON
        # See documentation: https://developer.pdf.co/api/pdf-to-image/jpg
        parameters = {}
        parameters["password"] = Password
        parameters["pages"] = Pages
        parameters["url"] = uploadedFileUrl

        # Prepare URL for PDF To Image API request
        url = "{}/pdf/convert/to/{}".format(BASE_URL, imageType)

        # 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:

                # Download generated JPG files
                part = 1

                for resultFileUrl in json["urls"]:
                    # Download Result File
                    r = requests.get(resultFileUrl, stream=True)

                    localFileUrl = f"Page{part}.{imageType}"

                    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
            else:
                # Show service reported error
                print(json["message"])
        else:
            print(f"Request error: {response.status_code} {response.reason}")


    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()
    ```

    ```csharp C# theme={null}
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Net;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;

    namespace PDFcoApiExample
    {
      class Program
      {
        // The authentication key (API Key).
        // Get your own by registering at https://app.pdf.co
        const String API_KEY = "***********************************";

        // Source PDF file
        const string SourceFile = @".\sample.pdf";
        // Comma-separated list of page indices (or ranges) to process. Leave empty for all pages. Example: '0,2-5,7-'.
        const string Pages = "";
        // PDF document password. Leave empty for unprotected documents.
        const string Password = "";

        const string imageType = "jpg";

        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 the 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();
              // Get URL of uploaded file to use with later API calls
              string uploadedFileUrl = json["url"].ToString();

              // 2. UPLOAD THE FILE TO CLOUD.

              webClient.Headers.Add("content-type", "application/octet-stream");
              webClient.UploadFile(uploadUrl, "PUT", SourceFile); // You can use UploadData() instead if your file is byte[] or Stream

              // 3. CONVERT UPLOADED PDF FILE TO IMAGE

              // Prepare URL for PDF To Image API call
              string url = String.Format(@"https://api.pdf.co/v1/pdf/convert/to/{0}", imageType);


              // Prepare requests params as JSON
              Dictionary<string, object> parameters = new Dictionary<string, object>();
              parameters.Add("password", Password);
              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 JPEG files
                int page = 1;
                foreach (JToken token in json["urls"])
                {
                  string resultFileUrl = token.ToString();
                  string localFileName = String.Format(@".\page{0}.{1}", page, imageType);

                  webClient.DownloadFile(resultFileUrl, localFileName);

                  Console.WriteLine("Downloaded \"{0}\".", localFileName);
                  page++;
                }
              }
              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();
        }
      }
    }
    ```

    ```java Java theme={null}
    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
        final static Path SourceFile = Paths.get(".\\sample.pdf");
        // Comma-separated list of page indices (or ranges) to process. Leave empty for all pages. Example: '0,2-5,7-'.
        final static String Pages = "";
        // PDF document password. Leave empty for unprotected documents.
        final static String Password = "";


        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. CONVERT UPLOADED PDF FILE TO IMAGE

                        PDFToImage(webClient, API_KEY, Password, Pages, uploadedFileUrl, "jpg");
                    }
                }
                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 PDFToImage(OkHttpClient webClient, String apiKey, String password, String pages, String uploadedFileUrl, String imageType) throws IOException
        {
            // Prepare URL for PDF To Image API call
            String query = String.format("https://api.pdf.co/v1/pdf/convert/to/%s", imageType);

            // 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("{\"password\": \"%s\", \"pages\": \"%s\", \"url\": \"%s\"}",
                    password,
                    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 JPEG files
                    JsonArray urls = json.get("urls").getAsJsonArray();

                    int page = 1;
                    for (JsonElement element: urls)
                    {
                        String resultFileUrl = element.getAsString();
                        String localFileName = String.format(".\\page%s.%s", page, imageType);

                        downloadFile(webClient, resultFileUrl, Paths.get(localFileName).toFile());

                        System.out.println(String.format("Downloaded \"%s\".", localFileName));
                        page++;
                    }
                }
                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 PHP theme={null}
    <?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
    $SourceFile = "./sample.pdf";
    // Comma-separated list of page indices (or ranges) to process. Leave empty for all pages. Example: '0,2-5,7-'.
    $Pages = "";
    // PDF document password. Leave empty for unprotected documents.
    $Password = "";


    // 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. CONVERT UPLOADED PDF FILE TO JPG
            convertPdfToJpg($API_KEY, $uploadedFileUrl, $Password, $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 convertPdfToJpg($apiKey, $uploadedFileUrl, $password, $pages)
    {
        // Prepare URL for `PDF To JPG` API call
        $url = "https://api.pdf.co/v1/pdf/convert/to/jpg";

        // Prepare requests params
        $parameters = array();
        $parameters["password"] = $password;
        $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 "convertPdfToJpg(): " . $curlError . PHP_EOL;
            return;
        }

        if ($statusCode != 200) {
            // Display request error
            echo "convertPdfToJpg(): request error " . $statusCode . PHP_EOL . $result . PHP_EOL;
            return;
        }

        $json = json_decode($result, true);

        if (!empty($json["error"])) {
            // Display service reported error
            echo "convertPdfToJpg(): " . $json["message"] . PHP_EOL;
            return;
        }

        // Download generated JPG files
        $page = 1;

        foreach ($json["urls"] as $resultFileUrl) {
            $destinationFile = "./page" . $page . ".jpg";

            if (downloadFile($resultFileUrl, $destinationFile)) {
                echo "Downloaded \"" . $destinationFile . "\"." . PHP_EOL;
            }

            $page++;
        }
    }

    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;
    }

    ?>
    ```
  </RequestExample>

  <ResponseExample>
    ```json 200 theme={null}
    {
      "urls": [
        "https://pdf-temp-files.s3.amazonaws.com/c15b8d82e0034d01a73eac719d69349b/sample.jpg",
        "https://pdf-temp-files.s3.amazonaws.com/152d2fe414b645e38f81a49e5dafa85b/sample.jpg"
      ],
      "pageCount": 2,
      "error": false,
      "status": 200,
      "name": "sample.jpg",
      "duration": 1121,
      "remainingCredits": 98722216,
      "credits": 24
    }
    ```

    ```json 400 theme={null}
    {
      "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)."
    }
    ```

    ```json 401 theme={null}
    {
      "error": true,
      "status": 401,
      "message": "Unauthorized. Authentication is required and has failed or has not yet been provided."
    }
    ```

    ```json 402 theme={null}
    {
      "error": true,
      "status": 402,
      "message": "Not enough credits."
    }
    ```

    ```json 403 theme={null}
    {
      "error": true,
      "status": 403,
      "message": "Access forbidden for input URL."
    }
    ```

    ```json 404 theme={null}
    {
      "error": true,
      "status": 404,
      "message": "The requested resource could not be found."
    }
    ```

    ```json 408 theme={null}
    {
      "error": true,
      "status": 408,
      "message": "The server timed out waiting for the request."
    }
    ```

    ```json 429 theme={null}
    {
      "error": true,
      "status": 429,
      "message": "Too many requests in a given time period."
    }
    ```

    ```json 441 theme={null}
    {
      "error": true,
      "status": 441,
      "message": "Invalid Password. Password protected document."
    }
    ```

    ```json 442 theme={null}
    {
      "error": true,
      "status": 442,
      "message": "Input document is damaged or of incorrect type."
    }
    ```

    ```json 443 theme={null}
    {
      "error": true,
      "status": 443,
      "message": "Permissions. The operation is prohibited by document security settings."
    }
    ```

    ```json 444 theme={null}
    {
      "error": true,
      "status": 444,
      "message": "Profiles parsing error. Please ensure that the configuration is supported."
    }
    ```

    ```json 445 theme={null}
    {
      "error": true,
      "status": 445,
      "message": "Timeout error. For large documents, use asynchronous mode (async=true) and check status via /job/check."
    }
    ```

    ```json 446 theme={null}
    {
      "error": true,
      "status": 446,
      "message": "Some files required for conversion are missing."
    }
    ```

    ```json 448 theme={null}
    {
      "error": true,
      "status": 448,
      "message": "Invalid URL or HTML. Ensure the provided URL is valid and accessible."
    }
    ```

    ```json 449 theme={null}
    {
      "error": true,
      "status": 449,
      "message": "Invalid index range. Page index is out of range."
    }
    ```

    ```json 450 theme={null}
    {
      "error": true,
      "status": 450,
      "message": "Invalid page range specified."
    }
    ```

    ```json 452 theme={null}
    {
      "error": true,
      "status": 452,
      "message": "Invalid URL."
    }
    ```

    ```json 454 theme={null}
    {
      "error": true,
      "status": 454,
      "message": "Invalid parameters."
    }
    ```

    ```json 500 theme={null}
    {
      "error": true,
      "status": 500,
      "message": "Something went wrong. Please try again or contact support."
    }
    ```
  </ResponseExample>
</Panel>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.