Encrypt & Decrypt PDFs - Python Sample Code

Sample code for using Apryse SDK to read encrypted (password protected) documents, secure a document with encryption, or remove encryption. Samples provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby, Go and VB. Learn more about our Server SDK.

1#---------------------------------------------------------------------------------------
2# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
3# Consult LICENSE.txt regarding license information.
4#---------------------------------------------------------------------------------------
5
6import site
7site.addsitedir("../../../PDFNetC/Lib")
8import sys
9from PDFNetPython import *
10
11sys.path.append("../../LicenseKey/PYTHON")
12from LicenseKey import *
13
14#---------------------------------------------------------------------------------------
15# This sample shows encryption support in PDFNet. The sample reads an encrypted document and
16# sets a new SecurityHandler. The sample also illustrates how password protection can
17# be removed from an existing PDF document.
18#---------------------------------------------------------------------------------------
19
20def main():
21 PDFNet.Initialize(LicenseKey)
22
23 # Relative path to the folder containing the test files.
24 input_path = "../../TestFiles/"
25 output_path = "../../TestFiles/Output/"
26
27 # Example 1:
28 # secure a PDF document with password protection and adjust permissions
29
30 # Open the test file
31 print("Securing an existing document...")
32
33 doc = PDFDoc(input_path + "fish.pdf")
34 doc.InitSecurityHandler()
35
36 # Perform some operation on the document. In this case we use low level SDF API
37 # to replace the content stream of the first page with contents of file 'my_stream.txt'
38 if True: # Optional
39 print("Replacing the content stream, use Flate compression...")
40
41 # Get the page dictionary using the following path: trailer/Root/Pages/Kids/0
42 page_dict = (doc.GetTrailer().Get("Root").Value()
43 .Get("Pages").Value()
44 .Get("Kids").Value()
45 .GetAt(0))
46
47 # Embed a custom stream (file mystream.txt) using Flate compression.
48 embed_file = MappedFile(input_path + "my_stream.txt")
49 mystm = FilterReader(embed_file)
50 page_dict.Put("Contents", doc.CreateIndirectStream(mystm, FlateEncode(Filter())))
51
52 # encrypt the document
53
54 # Apply a new security handler with given security settings.
55 # In order to open saved PDF you will need a user password 'test'.
56 new_handler = SecurityHandler()
57
58 # Set a new password required to open a document
59 user_password = "test"
60 new_handler.ChangeUserPassword(user_password)
61
62 # Set permissions
63 new_handler.SetPermission(SecurityHandler.e_print, True)
64 new_handler.SetPermission(SecurityHandler.e_extract_content, False)
65
66 # Note: document takes the ownership of new_handler.
67 doc.SetSecurityHandler(new_handler)
68
69 # save the changes.
70 print("Saving modified file...")
71 doc.Save(output_path + "secured.pdf", 0)
72 doc.Close()
73
74 # Example 2:
75 # Opens an encrypted PDF document and removes its security.
76
77 doc = PDFDoc(output_path + "secured.pdf")
78
79 # If the document is encrypted prompt for the password
80 if not doc.InitSecurityHandler():
81 success = False
82 print("The password is: test")
83 count = 0
84 while count < 3:
85 print("A password required to open the document.")
86 if sys.version_info.major >= 3:
87 password = input("Please enter the password: \n")
88 else:
89 password = raw_input("Please enter the password: \n")
90
91 if doc.InitStdSecurityHandler(password, len(password)):
92 success = True
93 print("The password is correct.")
94 break
95 elif count < 3:
96 print("The password is incorrect, please try again")
97 count = count + 1
98
99 if not success:
100 print("Document authentication error....")
101 return
102
103 hdlr = doc.GetSecurityHandler()
104 print("Document Open Password: " + str(hdlr.IsUserPasswordRequired()))
105 print("Permissions Password: " + str(hdlr.IsMasterPasswordRequired()))
106 print(("Permissions: "
107 + "\n\tHas 'owner' permissions: " + str(hdlr.GetPermission(SecurityHandler.e_owner))
108 + "\n\tOpen and decrypt the document: " + str(hdlr.GetPermission(SecurityHandler.e_doc_open))
109 + "\n\tAllow content extraction: " + str(hdlr.GetPermission(SecurityHandler.e_extract_content))
110 + "\n\tAllow full document editing: " + str(hdlr.GetPermission(SecurityHandler.e_doc_modify) )
111 + "\n\tAllow printing: " + str(hdlr.GetPermission(SecurityHandler.e_print))
112 + "\n\tAllow high resolution printing: " + str(hdlr.GetPermission(SecurityHandler.e_print_high))
113 + "\n\tAllow annotation editing: " + str(hdlr.GetPermission(SecurityHandler.e_mod_annot))
114 + "\n\tAllow form fill: " + str(hdlr.GetPermission(SecurityHandler.e_fill_forms))
115 + "\n\tAllow content extraction for accessibility: " + str(hdlr.GetPermission(SecurityHandler.e_access_support))
116 + "\n\tAllow document assembly: " + str(hdlr.GetPermission(SecurityHandler.e_assemble_doc))))
117
118 # remove all security on the document
119 doc.RemoveSecurity()
120 doc.Save(output_path + "not_secured.pdf", 0)
121 doc.Close()
122
123 # Example 3:
124 # Encrypt/Decrypt a PDF using PDFTron custom security handler
125 print("-------------------------------------------------")
126 print("Encrypt a document using PDFTron Custom Security handler with a custom id and password...")
127 doc = PDFDoc(input_path + "BusinessCardTemplate.pdf")
128
129 # Create PDFTron custom security handler with a custom id. Replace this with your own integer
130 custom_id = 123456789
131 custom_handler = PDFTronCustomSecurityHandler(custom_id)
132
133 # Add a password to the custom security handler
134 password = "test"
135 custom_handler.ChangeUserPassword(password)
136
137 # Save the encrypted document
138 doc.SetSecurityHandler(custom_handler)
139 doc.Save(output_path + "BusinessCardTemplate_enc.pdf", 0)
140 doc.Close()
141
142 print("Decrypt the PDFTron custom security encrypted document above...")
143 # Register the PDFTron Custom Security handler with the same custom id used in encryption
144 PDFNet.AddPDFTronCustomHandler(custom_id)
145
146 doc_enc = PDFDoc(output_path + "BusinessCardTemplate_enc.pdf")
147 doc_enc.InitStdSecurityHandler(password)
148 doc_enc.RemoveSecurity()
149 # Save the decrypted document
150 doc_enc.Save(output_path + "BusinessCardTemplate_enc_dec.pdf", 0)
151 doc_enc.Close()
152 PDFNet.Terminate()
153 print("Done. Result saved in BusinessCardTemplate_enc_dec.pdf")
154 print("-------------------------------------------------");
155 print("Test completed.")
156
157if __name__ == '__main__':
158 main()

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales