Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to password protect PDF file using Python?

We will use python library PyPDF2 to set Password to Pdf File.

To install PyPDF2:

sudo pip install pypdf2

We are using encrypt function of PyPDF2.

encrypt(user_password, owner_password=None, use_128bit=True)

  • user_password  – The “user password” allows opening and reading the PDF file with the restrictions .
  • owner_password – The “owner password”  have no restrictions. By default, the owner password is the same as the user password.
  • use_128bit  – Decides which encryption to use128bit or 40bit.

import PyPDF2
import os
import argparse

def set_password(input_file, user_pass, owner_pass):
    Function creates new temporary pdf file with same content,
    assigns given password to pdf and rename it with original file.
    # temporary output file with name same as input file but prepended
    # by "temp_", inside same direcory as input file.
    path, filename = os.path.split(input_file)
    output_file = os.path.join(path, "temp_" + filename)

    output = PyPDF2.PdfFileWriter()

    input_stream = PyPDF2.PdfFileReader(open(input_file, "rb"))

    for i in range(0, input_stream.getNumPages()):

    outputStream = open(output_file, "wb")

    # Set user and owner password to pdf file
    output.encrypt(user_pass, owner_pass, use_128bit=True)

    # Rename temporary output file with original filename, this
    # will automatically delete temporary file
    os.rename(output_file, input_file)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', '--input_pdf', required=True,
                        help='Input pdf file')
    parser.add_argument('-p', '--user_password', required=True,
                        help='output CSV file')
    parser.add_argument('-o', '--owner_password', default=None,
                        help='Owner Password')
    args = parser.parse_args()
    set_password(args.input_pdf, args.user_password, args.owner_password)

if __name__ == "__main__":

If you have any queries, please comment!

The post How to password Protect Pdf File using Python? appeared first on Gaurav Vichare.

This post first appeared on Gaurav Vichare -, please read the originial post: here

Share the post

How to password protect PDF file using Python?


Subscribe to Gaurav Vichare -

Get updates delivered right to your inbox!

Thank you for your subscription