how to encrypt a pdf file in python

Solutions on MaxInterview for how to encrypt a pdf file in python by the best coders in the world

showing results for - "how to encrypt a pdf file in python"
Nathael
25 Oct 2019
1import PyPDF2
2import os
3import argparse
4 
5 
6def set_password(input_file, user_pass, owner_pass):
7    """
8    Function creates new temporary pdf file with same content,
9    assigns given password to pdf and rename it with original file.
10    """
11    # temporary output file with name same as input file but prepended
12    # by "temp_", inside same direcory as input file.
13    path, filename = os.path.split(input_file)
14    output_file = os.path.join(path, "temp_" + filename)
15 
16    output = PyPDF2.PdfFileWriter()
17 
18    input_stream = PyPDF2.PdfFileReader(open(input_file, "rb"))
19 
20    for i in range(0, input_stream.getNumPages()):
21        output.addPage(input_stream.getPage(i))
22 
23    outputStream = open(output_file, "wb")
24 
25    # Set user and owner password to pdf file
26    output.encrypt(user_pass, owner_pass, use_128bit=True)
27    output.write(outputStream)
28    outputStream.close()
29 
30    # Rename temporary output file with original filename, this
31    # will automatically delete temporary file
32    os.rename(output_file, input_file)
33 
34 
35def main():
36    parser = argparse.ArgumentParser()
37    parser.add_argument('-i', '--input_pdf', required=True,
38                        help='Input pdf file')
39    parser.add_argument('-p', '--user_password', required=True,
40                        help='output CSV file')
41    parser.add_argument('-o', '--owner_password', default=None,
42                        help='Owner Password')
43    args = parser.parse_args()
44    set_password(args.input_pdf, args.user_password, args.owner_password)
45 
46if __name__ == "__main__":
47    main()
48