How to Encrypt and Password-Protect a PDF File in Python
While PDF format has numerous intrinsic security benefits, two important security elements — encryption and password protection — require a few extra steps to enable.
Thankfully, the below API solution will make it easy to build rapid PDF encryption and custom password-protection features directly into your Python workflows, using only a few lines of compact code in the process. You’ll be able to easily secure your PDF files at scale before processing and sharing them with various stakeholders. This API solution will allow you to configure user (reader) and owner (creator) passwords, as well as set a specific encryption key length (such as 128-bit RC4 encryption).
To call this API, your first step is to install the SDK by running the below command:
pip install cloudmersive-convert-api-client
After that, add the imports and call the function:
from __future__ import print_function
import time
import cloudmersive_convert_api_client
from cloudmersive_convert_api_client.rest import ApiException
from pprint import pprint
# Configure API key authorization: Apikey
configuration = cloudmersive_convert_api_client.Configuration()
configuration.api_key['Apikey'] = 'YOUR_API_KEY'
# create an instance of the API class
api_instance = cloudmersive_convert_api_client.EditPdfApi(cloudmersive_convert_api_client.ApiClient(configuration))
input_file = '/path/to/inputfile' # file | Input file to perform the operation on.
user_password = 'user_password_example' # str | Password of a user (reader) of the PDF file (optional)
owner_password = 'owner_password_example' # str | Password of a owner (creator/editor) of the PDF file (optional)
encryption_key_length = 'encryption_key_length_example' # str | Possible values are \"128\" (128-bit RC4 encryption) and \"256\" (256-bit AES encryption). Default is 256. (optional)
try:
# Encrypt and password-protect a PDF
api_response = api_instance.edit_pdf_encrypt(input_file, user_password=user_password, owner_password=owner_password, encryption_key_length=encryption_key_length)
pprint(api_response)
except ApiException as e:
print("Exception when calling EditPdfApi->edit_pdf_encrypt: %s\n" % e)
In addition to password and encryption customization details, you’ll need a Cloudmersive API key to complete your call; you can get one by visiting our website and registering a free account (this yields a limit of 800 API calls per month with no commitments).