How to Change PDF Password with Python

Learn how to replace a PDF password with a new one using pdfRest Encrypt PDF API Tool with Python
Share this page

Why Change PDF Password with Python?

The pdfRest Encrypt PDF API Tool empowers you to efficiently update passwords on existing PDFs directly with Python. This eliminates the need for manual re-encryption, saving you time and minimizing errors.

Strengthen passwords, grant access to new team members, or comply with data security regulations – the Encrypt PDF API automates the process, ensuring both enhanced security and streamlined collaboration within your Python workflows.

Change PDF Password with Python Code Example

from requests_toolbelt import MultipartEncoder
import requests
import json

encrypted_pdf_endpoint_url = 'https://api.pdfrest.com/encrypted-pdf'

# The /encrypted-pdf endpoint can take a single PDF file or id as input.
# This sample demonstrates encryption of a PDF with the password 'password'.
mp_encoder_encryptedPdf = MultipartEncoder(
    fields={
        'file': ('file_name.pdf', open('/path/to/file', 'rb'), 'application/pdf'),
        'output' : 'example_encryptedPdf_out',
        'current_open_password': 'currpassword',
        'new_open_password': 'newpassword',
    }
)

# Let's set the headers that the encrypted-pdf endpoint expects.
# Since MultipartEncoder is used, the 'Content-Type' header gets set to 'multipart/form-data' via the content_type attribute below.
headers = {
    'Accept': 'application/json',
    'Content-Type': mp_encoder_encryptedPdf.content_type,
    'Api-Key': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' # place your api key here
}

print("Sending POST request to encrypted-pdf endpoint...")
response = requests.post(encrypted_pdf_endpoint_url, data=mp_encoder_encryptedPdf, headers=headers)

print("Response status code: " + str(response.status_code))

if response.ok:
    response_json = response.json()
    print(json.dumps(response_json, indent = 2))
else:
    print(response.text)

# If you would like to download the file instead of getting the JSON response, please see the 'get-resource-id-endpoint.py' sample.

The provided code is sourced from the pdf-rest-api-samples repository on GitHub.

Breaking Down the Code

The code begins by importing the necessary libraries: MultipartEncoder from requests_toolbelt, requests, and json. The MultipartEncoder is used for creating multipart/form-data payloads, which is the required format for file uploads.

from requests_toolbelt import MultipartEncoder
import requests
import json

The endpoint URL is defined as a string, representing the API endpoint to which the POST request will be sent.

encrypted_pdf_endpoint_url = 'https://api.pdfrest.com/encrypted-pdf'

The MultipartEncoder is then configured with the fields needed for the request: the file to encrypt, the desired output name, the current password, and the new password for opening the PDF.

mp_encoder_encryptedPdf = MultipartEncoder(
    fields={
        'file': ('file_name.pdf', open('/path/to/file', 'rb'), 'application/pdf'),
        'output' : 'example_encryptedPdf_out',
        'current_open_password': 'currpassword',
        'new_open_password': 'newpassword',
    }
)

Headers are set up to include the expected 'Accept' and 'Content-Type', as well as the 'Api-Key' which should be replaced with your actual API key.

headers = {
    'Accept': 'application/json',
    'Content-Type': mp_encoder_encryptedPdf.content_type,
    'Api-Key': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' # place your api key here
}

The POST request is sent using the requests.post method with the specified URL, data payload, and headers. The response is then checked for success, and the JSON response is printed if available, otherwise the error text is displayed.

response = requests.post(encrypted_pdf_endpoint_url, data=mp_encoder_encryptedPdf, headers=headers)

Beyond the Tutorial

By following the above steps, you have learned how to make an API call to change a PDF password using Python. This process can be integrated into larger workflows to automate the protection of sensitive documents. To explore and demo all of the pdfRest API Tools, visit the API Lab. For further information and detailed API documentation, refer to the API Reference Guide.

Note: This is an example of a multipart API call. Code samples using JSON payloads for the same operation can be found at pdf-rest-api-samples.

Generate a self-service API Key now!
Create your FREE API Key to start processing PDFs in seconds, only possible with pdfRest.