Add / Remove PDF Password & Security#

Add password and security limitations to PDF or remove existing limits and password from existing PDF files.

/pdf/security/add#

Add security to a PDF.

  • Method: POST

  • Endpoint: /v1/pdf/security/add

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

ownerPassword

The main owner password that is used for document encryption and for setting/removing restrictions.

yes

userPassword

The optional user password will be asked for viewing and printing document.

no

encryptionAlgorithm

Encryption algorithm. Valid values: RC4_40bit, RC4_128bit, AES_128bit, AES_256bit. AES_128bit or higher is recommended.

no

allowAccessibilitySupport

Allow or prohibit content extraction for accessibility needs. Note: this restriction applies when userPassword (if any) is entered. See note.

no

allowAssemblyDocument

Allow or prohibit assembling the document. Note: this restriction applies when userPassword (if any) is entered. See note.

no

allowPrintDocument

Allow or prohibit printing PDF document. Note: this restriction applies when userPassword (if any) is entered. See note.

no

allowFillForms

Allow or prohibit the filling of interactive form fields (including signature fields) in the PDF documents. See note.

no

allowModifyDocument

Allow or prohibit modification of PDF document. See note.

no

allowContentExtraction

Allow or prohibit copying content from PDF document. See note.

no

allowModifyAnnotations

Allow or prohibit interacting with text annotations and forms in PDF document. See note.

no

printQuality

Allowed printing quality. Valid values: HighResolution, LowResolution. See note.

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

name

File name for the generated output, the input must be in string format.

no

expiration

Set the expiration time for the output link in minutes (default is 60 i.e 60 minutes or 1 hour), 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.

no

profiles

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

no

Note

This restriction applies when userPassword (if any) is entered. This restriction does not apply if the user enters Owner Password. Default: false.

Query parameters#

No query parameters accepted.

Payload#

{
    "url": "https://pdfco-test-files.s3.us-west-2.amazonaws.com/pdf-merge/sample1.pdf",
    "ownerPassword": "12345",
    "userPassword": "54321",
    "EncryptionAlgorithm": "AES_128bit",
    "AllowPrintDocument": false,
    "AllowFillForms": false,
    "AllowModifyDocument": false,
    "AllowContentExtraction": false,
    "AllowModifyAnnotations": false,
    "PrintQuality": "LowResolution",
    "name": "output-protected.pdf",
    "async": false
}

Response 2#

{
    "url": "https://pdf-temp-files.s3.amazonaws.com/eaa441ade38548b8a3a96d8014c4f463/sample1.pdf",
    "pageCount": 1,
    "error": false,
    "status": 200,
    "name": "sample1.pdf",
    "remainingCredits": 616208,
    "credits": 14
}

CURL#

curl --location --request POST 'https://api.pdf.co/v1/pdf/security/add' \
--header 'x-api-key: ' \
--data-raw '{
    "url": "https://pdfco-test-files.s3.us-west-2.amazonaws.com/pdf-merge/sample1.pdf",
    "ownerPassword": "12345",
    "userPassword": "54321",
    "EncryptionAlgorithm": "AES_128bit",
    "AllowPrintDocument": false,
    "AllowFillForms": false,
    "AllowModifyDocument": false,
    "AllowContentExtraction": false,
    "AllowModifyAnnotations": false,
    "PrintQuality": "LowResolution",
    "name": "output-protected.pdf",
    "async": false
}'


/pdf/security/remove#

Add security to a PDF.

  • Method: POST

  • Endpoint: /v1/pdf/security/remove

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

password

The owner/user password to open files and remove security features.

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

name

File name for the generated output, the input must be in string format.

no

expiration

Set the expiration time for the output link in minutes (default is 60 i.e 60 minutes or 1 hour), 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.

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#

{
    "url": "https://pdfco-test-files.s3.us-west-2.amazonaws.com/pdf-security/ProtectedPDFFile.pdf",
    "password": "admin@123",
    "name": "unprotected",
    "async": false
}

Response 2#

{
    "url": "https://pdf-temp-files.s3.amazonaws.com/9f2a754f76db46ac93781b3d2c6694c3/ProtectedPDFFile.pdf",
    "pageCount": 1,
    "error": false,
    "status": 200,
    "name": "ProtectedPDFFile.pdf",
    "remainingCredits": 616187,
    "credits": 21
}

CURL#

curl --location --request POST 'https://api.pdf.co/v1/pdf/security/remove' \
--header 'x-api-key: ' \
--data-raw '{
    "url": "https://pdfco-test-files.s3.us-west-2.amazonaws.com/pdf-security/ProtectedPDFFile.pdf",
    "password": "admin@123",
    "name": "unprotected",
    "async": false
}'


Code samples#

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.
const SourceFileUrl = "https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/pdf-merge/sample1.pdf";

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

// Passwords to protect PDF document
// The owner password will be required for document modification.
// The user password only allows to view and print the document.
const OwnerPassword = "123456";
const UserPassword = "654321";

// Encryption algorithm.
// Valid values: "RC4_40bit", "RC4_128bit", "AES_128bit", "AES_256bit".
const EncryptionAlgorithm = "AES_128bit";

// Allow or prohibit content extraction for accessibility needs.
const AllowAccessibilitySupport = true;

// Allow or prohibit assembling the document.
const AllowAssemblyDocument = true;

// Allow or prohibit printing PDF document.
const AllowPrintDocument = true;

// Allow or prohibit filling of interactive form fields (including signature fields) in PDF document.
const AllowFillForms = true;

// Allow or prohibit modification of PDF document.
const AllowModifyDocument = true;

// Allow or prohibit copying content from PDF document.
const AllowContentExtraction = true;

// Allow or prohibit interacting with text annotations and forms in PDF document.
const AllowModifyAnnotations = true;

// Allowed printing quality.
// Valid values: "HighResolution", "LowResolution"
const PrintQuality = "HighResolution";

// Runs processing asynchronously.
// Returns Use JobId that you may use with /job/check to check state of the processing (possible states: working, failed, aborted and success).
const async = false;


// Prepare request to `PDF Security` API endpoint
var queryPath = `/v1/pdf/security/add`;

// JSON payload for api request
var jsonPayload = JSON.stringify({
    name: path.basename(DestinationFile),
    url: SourceFileUrl,
    ownerPassword: OwnerPassword,
    userPassword: UserPassword,
    encryptionAlgorithm: EncryptionAlgorithm,
    allowAccessibilitySupport: AllowAccessibilitySupport,
    allowAssemblyDocument: AllowAssemblyDocument,
    allowPrintDocument: AllowPrintDocument,
    allowFillForms: AllowFillForms,
    allowModifyDocument: AllowModifyDocument,
    allowContentExtraction: AllowContentExtraction,
    allowModifyAnnotations: AllowModifyAnnotations,
    printQuality: PrintQuality,
    async: async
});

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.
SourceFileURL = "https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/pdf-merge/sample1.pdf"

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

# Passwords to protect PDF document
# The owner password will be required for document modification.
# The user password only allows to view and print the document.
OwnerPassword = "123456"
UserPassword = "654321"

# Encryption algorithm.
# Valid values: "RC4_40bit", "RC4_128bit", "AES_128bit", "AES_256bit".
EncryptionAlgorithm = "AES_128bit"

# Allow or prohibit content extraction for accessibility needs.
AllowAccessibilitySupport = True

# Allow or prohibit assembling the document.
AllowAssemblyDocument = True

# Allow or prohibit printing PDF document.
AllowPrintDocument = True

# Allow or prohibit filling of interactive form fields (including signature fields) in PDF document.
AllowFillForms = True

# Allow or prohibit modification of PDF document.
AllowModifyDocument = True

# Allow or prohibit copying content from PDF document.
AllowContentExtraction = True

# Allow or prohibit interacting with text annotations and forms in PDF document.
AllowModifyAnnotations = True

# Allowed printing quality.
# Valid values: "HighResolution", "LowResolution"
PrintQuality = "HighResolution"

# Runs processing asynchronously.
# Returns Use JobId that you may use with /job/check to check state of the processing (possible states: working, failed, aborted and success).
Async = False

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


def protectPDF(uploadedFileUrl, destinationFile):
    """Protect PDF using PDF.co Web API"""

    # Prepare requests params as JSON
    # See documentation: https://developer.pdf.co
    parameters = {"name": os.path.basename(destinationFile), "url": uploadedFileUrl, "ownerPassword": OwnerPassword,
                  "userPassword": UserPassword, "encryptionAlgorithm": EncryptionAlgorithm,
                  "allowAccessibilitySupport": AllowAccessibilitySupport,
                  "allowAssemblyDocument": AllowAssemblyDocument, "allowPrintDocument": AllowPrintDocument,
                  "allowFillForms": AllowFillForms, "allowModifyDocument": AllowModifyDocument,
                  "allowContentExtraction": AllowContentExtraction, "allowModifyAnnotations": AllowModifyAnnotations,
                  "printQuality": PrintQuality, "async": Async}

    # Serializing json
    import json
    json_object = json.dumps(parameters, indent=4)

    # Prepare URL for 'PDF Security' API request
    url = "{}/pdf/security/add".format(BASE_URL)

    # Execute request and get response as JSON
    response = requests.post(url, data=json_object, headers={"x-api-key": API_KEY})
    if (response.status_code == 200):
        jsonResp = response.json()

        if jsonResp["error"] == False:
            #  Get URL of result file
            resultFileUrl = jsonResp["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(jsonResp["message"])
    else:
        print(f"Request error: {response.status_code} {response.reason}")

if __name__ == '__main__':
    main()
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ByteScoutWebApiExample
{
    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";

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

        // Passwords to protect PDF document
        // The owner password will be required for document modification.
        // The user password only allows to view and print the document.
        const string OwnerPassword = "123456";
        const string UserPassword = "654321";

        // Encryption algorithm.
        // Valid values: "RC4_40bit", "RC4_128bit", "AES_128bit", "AES_256bit".
        const string EncryptionAlgorithm = "AES_128bit";

        // Allow or prohibit content extraction for accessibility needs.
        const bool AllowAccessibilitySupport = true;

        // Allow or prohibit assembling the document.
        const bool AllowAssemblyDocument = true;

        // Allow or prohibit printing PDF document.
        const bool AllowPrintDocument = true;

        // Allow or prohibit filling of interactive form fields (including signature fields) in PDF document.
        const bool AllowFillForms = true;

        // Allow or prohibit modification of PDF document.
        const bool AllowModifyDocument = true;

        // Allow or prohibit copying content from PDF document.
        const bool AllowContentExtraction = true;

        // Allow or prohibit interacting with text annotations and forms in PDF document.
        const bool AllowModifyAnnotations = true;

        // Allowed printing quality.
        // Valid values: "HighResolution", "LowResolution"
        const string PrintQuality = "HighResolution";


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


            // Upload file to the cloud
            string uploadedFileUrl = UploadFile(SourceFile);


            // PROTECT UPLOADED PDF DOCUMENT

            // Prepare requests params as JSON
            // See documentation: https://developer.pdf.co/
            Dictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("name", Path.GetFileName(DestinationFile));
            parameters.Add("url", uploadedFileUrl);
            parameters.Add("ownerPassword", OwnerPassword);
            parameters.Add("userPassword", UserPassword);
            parameters.Add("encryptionAlgorithm", EncryptionAlgorithm);
            parameters.Add("allowAccessibilitySupport", AllowAccessibilitySupport.ToString());
            parameters.Add("allowAssemblyDocument", AllowAssemblyDocument.ToString());
            parameters.Add("allowPrintDocument", AllowPrintDocument.ToString());
            parameters.Add("allowFillForms", AllowFillForms.ToString());
            parameters.Add("allowModifyDocument", AllowModifyDocument.ToString());
            parameters.Add("allowContentExtraction", AllowContentExtraction.ToString());
            parameters.Add("allowModifyAnnotations", AllowModifyAnnotations.ToString());
            parameters.Add("printQuality", PrintQuality);
            // Convert dictionary of params to JSON
            string jsonPayload = JsonConvert.SerializeObject(parameters);

            try
            {
                // URL of "PDF Security" endpoint
                string url = "https://api.pdf.co/v1/pdf/security/add";

                // 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 generated 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();
        }

        /// <summary>
        /// Uploads file to the cloud and return URL of uploaded file to use in further API calls.
        /// </summary>
        /// <param name="file">Source file name (path).</param>
        /// <returns>URL of uploaded file</returns>
        static string UploadFile(string file)
        {
            // Create standard .NET web client instance
            WebClient webClient = new WebClient();

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

            try
            {
                // 1. RETRIEVE THE PRESIGNED URL TO UPLOAD THE FILE.
                // * If you already have a direct file URL, skip to the step 3.

                // Prepare URL for `Get Presigned URL` API call
                string query = Uri.EscapeUriString(string.Format(
                    "https://api.pdf.co/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name={0}",
                    Path.GetFileName(file)));

                // 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", file); // You can use UploadData() instead if your file is in byte[] or Stream

                    return uploadedFileUrl;
                }
                else
                {
                    // Display service reported error
                    Console.WriteLine(json["message"].ToString());
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            finally
            {
                webClient.Dispose();
            }

            return null;
        }
    }
}
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.
    final static String SourceFileUrl = "https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/pdf-merge/sample1.pdf";

    // Destination PDF file name
    final static Path DestinationFile = Paths.get(".\\protected.pdf");

    // Passwords to protect PDF document
    // The owner password will be required for document modification.
    // The user password only allows to view and print the document.
    final static String OwnerPassword = "123456";
    final static String UserPassword = "654321";

    // Encryption algorithm.
    // Valid values: "RC4_40bit", "RC4_128bit", "AES_128bit", "AES_256bit".
    final static String EncryptionAlgorithm = "AES_128bit";

    // Allow or prohibit content extraction for accessibility needs.
    final static boolean AllowAccessibilitySupport = true;

    // Allow or prohibit assembling the document.
    final static boolean AllowAssemblyDocument = true;

    // Allow or prohibit printing PDF document.
    final static boolean AllowPrintDocument = true;

    // Allow or prohibit filling of interactive form fields (including signature fields) in PDF document.
    final static boolean AllowFillForms = true;

    // Allow or prohibit modification of PDF document.
    final static boolean AllowModifyDocument = true;

    // Allow or prohibit copying content from PDF document.
    final static boolean AllowContentExtraction = true;

    // Allow or prohibit interacting with text annotations and forms in PDF document.
    final static boolean AllowModifyAnnotations = true;

    // Allowed printing quality.
    // Valid values: "HighResolution", "LowResolution"
    final static String PrintQuality = "HighResolution";

    // Runs processing asynchronously.
    // Returns Use JobId that you may use with /job/check to check state of the processing (possible states: working, failed, aborted and success).
    final static boolean async = false;


    public static void main(String[] args) throws IOException
    {
        // Create HTTP client instance
        OkHttpClient webClient = new OkHttpClient();

        // Prepare URL for `PDF Security` API call
        String query = "https://api.pdf.co/v1/pdf/security/add";

        // 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("{\n" +
                        "    \"name\": \"%s\",\n" +
                        "    \"url\": \"%s\",\n" +
                        "    \"ownerPassword\": \"%s\",\n" +
                        "    \"userPassword\": \"%s\",\n" +
                        "    \"EncryptionAlgorithm\": \"%s\",\n" +
                        "    \"AllowAccessibilitySupport\": %s,\n" +
                        "    \"AllowAssemblyDocument\": %s,\n" +
                        "    \"AllowPrintDocument\": %s,\n" +
                        "    \"AllowFillForms\": %s,\n" +
                        "    \"AllowModifyDocument\": %s,\n" +
                        "    \"AllowContentExtraction\": %s,\n" +
                        "    \"AllowModifyAnnotations\": %s,\n" +
                        "    \"PrintQuality\": \"%s\",\n" +
                        "    \"async\": %s\n" +
                        "}",
                DestinationFile.getFileName(), SourceFileUrl, OwnerPassword, UserPassword, EncryptionAlgorithm,
                Boolean.toString(AllowAccessibilitySupport), Boolean.toString(AllowAssemblyDocument), Boolean.toString(AllowPrintDocument),
                Boolean.toString(AllowFillForms), Boolean.toString(AllowModifyDocument), Boolean.toString(AllowContentExtraction),
                Boolean.toString(AllowModifyAnnotations),PrintQuality, Boolean.toString(async)
        );

        // 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

  // Note: If you have input files large than 200kb we highly recommend to check "async" mode example.

  // Get submitted form data
  $apiKey = $_POST["apiKey"]; // The authentication key (API Key). Get your own by registering at https://app.pdf.co


  // 1. RETRIEVE THE PRESIGNED URL TO UPLOAD THE FILE.
  // * If you already have the direct PDF file link, go to the step 3.

  // Create URL
  $url = "https://api.pdf.co/v1/file/upload/get-presigned-url" .
      "?name=" . urlencode($_FILES["file"]["name"]) .
      "&contenttype=application/octet-stream";

  // Create request
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey));
  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  // 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);

          // Get URL to use for the file upload
          $uploadFileUrl = $json["presignedUrl"];
          // Get URL of uploaded file to use with later API calls
          $uploadedFileUrl = $json["url"];

          // 2. UPLOAD THE FILE TO CLOUD.

          $localFile = $_FILES["file"]["tmp_name"];
          $fileHandle = fopen($localFile, "r");

          curl_setopt($curl, CURLOPT_URL, $uploadFileUrl);
          curl_setopt($curl, CURLOPT_HTTPHEADER, array("content-type: application/octet-stream"));
          curl_setopt($curl, CURLOPT_PUT, true);
          curl_setopt($curl, CURLOPT_INFILE, $fileHandle);
          curl_setopt($curl, CURLOPT_INFILESIZE, filesize($localFile));

          // Execute request
          curl_exec($curl);

          fclose($fileHandle);

          if (curl_errno($curl) == 0)
          {
              $status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

              if ($status_code == 200)
              {
                  // 3. PROTECT PDF FILE

                  ProtectPdf($apiKey, $uploadedFileUrl);
              }
              else
              {
                  // Display request error
                  echo "<p>Status code: " . $status_code . "</p>";
                  echo "<p>" . $result . "</p>";
              }
          }
          else
          {
              // Display CURL error
              echo "Error: " . curl_error($curl);
          }
      }
      else
      {
          // Display service reported error
          echo "<p>Status code: " . $status_code . "</p>";
          echo "<p>" . $result . "</p>";
      }

      curl_close($curl);
  }
  else
  {
      // Display CURL error
      echo "Error: " . curl_error($curl);
  }

  function ProtectPdf($apiKey, $uploadedFileUrl)
  {
      // Passwords to protect PDF document
      // The owner password will be required for document modification.
      // The user password only allows to view and print the document.
      $OwnerPassword = "123456";
      $UserPassword = "654321";

      // Encryption algorithm.
      // Valid values: "RC4_40bit", "RC4_128bit", "AES_128bit", "AES_256bit".
      $EncryptionAlgorithm = "AES_128bit";

      // Allow or prohibit content extraction for accessibility needs.
      $AllowAccessibilitySupport = true;

      // Allow or prohibit assembling the document.
      $AllowAssemblyDocument = true;

      // Allow or prohibit printing PDF document.
      $AllowPrintDocument = true;

      // Allow or prohibit filling of interactive form fields (including signature fields) in PDF document.
      $AllowFillForms = true;

      // Allow or prohibit modification of PDF document.
      $AllowModifyDocument = true;

      // Allow or prohibit copying content from PDF document.
      $AllowContentExtraction = true;

      // Allow or prohibit interacting with text annotations and forms in PDF document.
      $AllowModifyAnnotations = true;

      // Allowed printing quality.
      // Valid values: "HighResolution", "LowResolution"
      $PrintQuality = "HighResolution";

      // Prepare URL for `PDF Security` API call
      $url = "https://api.pdf.co/v1/pdf/security/add";

      // Prepare requests params
      $parameters = array();
      $parameters["name"] = "result.pdf";
      $parameters["url"] = $uploadedFileUrl;
      $parameters["ownerPassword"] = $OwnerPassword;
      $parameters["userPassword"] = $UserPassword;
      $parameters["encryptionAlgorithm"] = $EncryptionAlgorithm;
      $parameters["allowAccessibilitySupport"] = $AllowAccessibilitySupport;
      $parameters["allowAssemblyDocument"] = $AllowAssemblyDocument;
      $parameters["allowPrintDocument"] = $AllowPrintDocument;
      $parameters["allowFillForms"] = $AllowFillForms;
      $parameters["allowModifyDocument"] = $AllowModifyDocument;
      $parameters["allowContentExtraction"] = $AllowContentExtraction;
      $parameters["allowModifyAnnotations"] = $AllowModifyAnnotations;
      $parameters["printQuality"] = $PrintQuality;

      // 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)
              {
                  $resultFileUrl = $json["url"];

                  // Display link to the result file
                  echo "<div><h2>Conversion Result:</h2><a href='" . $resultFileUrl . "' target='_blank'>" . $resultFileUrl . "</a></div>";
              }
              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);
  }

?>

On Github#

Footnotes

1(1,2)

Supports links from 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 to add 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.