Creating Password-Protected PDFs with Python ReportLab



We'll start with a simple example of creating a single password-protected PDF and then move on to generating multiple PDFs with unique passwords for each file.

Creating a Single Password-Protected PDF 🔝

Creating a Secure PDF with Python ReportLab: Step-by-Step Guide Part-1
from reportlab.pdfgen import canvas
from reportlab.lib import pdfencrypt
pw=pdfencrypt.StandardEncryption('test')
my_path='D:\\testing\\my_pdf\\my_pdf.pdf'# file path
c = canvas.Canvas(my_path,bottomup=0,encrypt=pw)
c.drawString(50,200,"Hello World") # write text in page 
c.showPage() # saves current page
c.save() # stores the file and close  the canvas
Let's break down the code step by step.
  1. Import the necessary modules:
    from reportlab.pdfgen import canvas
    from reportlab.lib import pdfencrypt
  2. Define the password for the PDF:
    pw=pdfencrypt.StandardEncryption('test')
  3. Specify the file path where the PDF will be saved:
    my_path='D:\\testing\\my_pdf\\my_pdf.pdf'
  4. Create the canvas object with the specified file path and encryption:
    c = canvas.Canvas(my_path,bottomup=0,encrypt=pw)
  5. Draw the text "Hello World" on the PDF canvas:
    c.drawString(50,200,"Hello World")
  6. Save the current page:
    c.showPage()
  7. Store the file and close the canvas:
    c.save()

This script will create a single PDF file named my_pdf.pdf at the specified location, protected with the password test.

Creating multiple Password-Protected PDFs 🔝

Creating Multiple Password-Protected PDFs from data sets using Python ReportLab Part II

This example uses a list of data to create multiple PDFs, each protected with a unique password of its own.

from reportlab.pdfgen import canvas
from datetime import datetime
from reportlab.lib import pdfencrypt

path='D:\\testing\\my_pdf\\my_pdf_'# file path

l1 = [(1, 'John Deo', 'Four', 75, 'female','2010-02-25'),
      (2, 'Max Ruin', 'Three', 85, 'male','2010-12-12'),
      (3, 'Arnold', 'Three', 55, 'male','2011-03-31')]  # Data to be used
for rows in l1:
    f=rows[0] # first column or id as file name
    my_path=path+str(f)+'.pdf' # Path with file name

    dt=datetime.strptime(rows[5],'%Y-%m-%d') # date object
    str_dt=datetime.strftime(dt,'%b') # Month part only like Jan, Feb , Mar
    str_name=rows[1][0:3] # first 3 chars of the name
    str_pw=(str_name+str_dt).lower() # johfeb maxdec arnmar

    pw=pdfencrypt.StandardEncryption(str_pw)
    c = canvas.Canvas(my_path,bottomup=0,encrypt=pw)
    my_data=str(rows[0]) + ','+ rows[1] + ','+ rows[2]+ ','+ str(rows[3])+ ','+ rows[4] 
    c.drawString(50,200,my_data) # write text in page 

    c.showPage() # saves current page
    c.save() # stores the file and close  the canvas
Let's break down the code step by step.
  1. Import the necessary modules:
    from reportlab.pdfgen import canvas
    from datetime import datetime
    from reportlab.lib import pdfencrypt
  2. Define the file path where the PDFs will be saved:
    path='D:\\testing\\my_pdf\\my_pdf_'
  3. Create a list of tuples containing the data for each PDF:
    l1 = [
      (1, 'John Deo', 'Four', 75, 'female','2010-02-25'),
      (2, 'Max Ruin', 'Three', 85, 'male','2010-12-12'),
      (3, 'Arnold', 'Three', 55, 'male','2011-03-31')
    ]
  4. Loop through each row in the list:
    for rows in l1:
  5. Extract the first column (ID) to use as the file name:
    f=rows[0]
  6. Generate the full file path with the file name:
    my_path=path+str(f)+'.pdf'
    Here str() is used to convert integer to String.
  7. Convert the date string to a date object and extract the month:
    dt=datetime.strptime(rows[5],'%Y-%m-%d')
    str_dt=datetime.strftime(dt,'%b')
    strptime() : Returns date object from input string with format details.
    strftime() : Returns the string by using format by taking date object as input .
  8. Create a password using the first three characters of the name and the month:
    str_name=rows[1][0:3]
    str_pw=(str_name+str_dt).lower()
    lower() : Change all to lower case letters
  9. Initialize the encryption object with the generated password:
    pw=pdfencrypt.StandardEncryption(str_pw)
  10. Create the canvas object with the specified file path and encryption:
    c = canvas.Canvas(my_path,bottomup=0,encrypt=pw)
  11. Prepare the data string to be written to the PDF:
    my_data=str(rows[0]) + ','+ rows[1] + ','+ rows[2]+ ','+ str(rows[3])+ ','+ rows[4]
  12. Draw the data string on the PDF canvas:
    c.drawString(50,200,my_data)
  13. Save the current page:
    c.showPage()
  14. Store the file and close the canvas:
    c.save()

This script will generate three password-protected PDF files, each containing data from the corresponding row in the list. The password for each PDF is generated using the first three characters of the name and the month from the date.

File name and Passwords as per the above code.

Filename Password
my_pdf_1.pdf johfeb
my_pdf_2.pdf maxdec
my_pdf_3.pdf arnmar

The logic behind creation of password for each file

The unique password for each PDF file is generated by combining the first three characters of the name and the abbreviated month part of the date, both converted to lowercase.

Specifically, the date string from the data is parsed to extract the month, which is then abbreviated to its three-letter form (e.g., "Feb" for February). At the same time, the first three characters of the person's name are extracted. These two parts are concatenated and converted to lowercase to form the password.

For example, the name "John Deo" and date "2010-02-25" produce the password "johfeb".

This logic ensures that each file has a unique, yet easily reproducible, password based on the individual's name and the month of the date provided in the data.
dt=datetime.strptime(rows[5],'%Y-%m-%d') # date object
str_dt=datetime.strftime(dt,'%b') # Month part only like Jan, Feb , Mar
str_name=rows[1][0:3] # first 3 chars of the name
str_pw=(str_name+str_dt).lower() # johfeb maxdec arnmar

Restricting Editing and Printing Permissions in PDFs 🔝

How to set User and Master level password for different activities in PDF file in Reportlab Part-III

With the PDF security handler, we can specify two types of passwords for a document:

  • Owner Password: Also referred to as the 'master password' or 'security password'.
  • User Password: Also referred to as the 'open password'.

Providing either of these passwords will allow the PDF file to be opened, decrypted, and displayed on the screen.

  • When the owner password is provided, the file is opened with full permissions, allowing us to perform any action, including changing security settings and passwords or re-encrypting the file with a new password.
  • When the user password is provided, the file opens in a restricted mode. These restrictions, set during the file's encryption, control our ability to:
  • Modify the document's content.
  • Copy text and graphics from the document.
  • Add or modify text annotations and interactive form fields.
  • Print the document.

Steps to Restrict Permissions

  1. Import the necessary modules:
    from reportlab.pdfgen import canvas
    from reportlab.lib import pdfencrypt
  2. Define the permissions using StandardEncryption:
    pw=pdfencrypt.StandardEncryption(userPassword='xyz', 
                                      ownerPassword='abc',
                                      canPrint=False, 
                                      canModify=False, 
                                      canCopy=False, 
                                      canAnnotate=False)
    • userPassword='xyz': Sets the user password for opening the PDF.
    • ownerPassword='abc': Sets the owner password, which can override restrictions.
    • canPrint=False: Restricts printing (set to True to allow).
    • canModify=False: Restricts modifying the document (set to True to allow).
    • canCopy=False: Restricts copying text and graphics (set to True to allow).
    • canAnnotate=False: Restricts adding or modifying annotations (set to True to allow).
  3. Define the file path where the restricted PDF will be saved:
    my_path='D:\\testing\\my_pdf\\my_pdf.pdf'
  4. Create the canvas object with the specified file path and encryption:
    c = canvas.Canvas(my_path, bottomup=0, encrypt=pw)
  5. Add content to the PDF:
    c.drawString(50, 200, "this is protected")
  6. Save the current page and the canvas:
    c.showPage()
    c.save()

By following these steps, you can create PDFs with specific restrictions on printing, modifying, copying, and annotating using Python ReportLab. This ensures that your documents are protected according to your requirements.

Here is the complete Python code:
from reportlab.pdfgen import canvas
from reportlab.lib import pdfencrypt

pw = pdfencrypt.StandardEncryption(userPassword='xyz', 
                                   ownerPassword='abc',
                                   canPrint=False, 
                                   canModify=False, 
                                   canCopy=False, 
                                   canAnnotate=False)
                                   
my_path = 'D:\\testing\\my_pdf\\my_pdf.pdf'  # pdf file path
c = canvas.Canvas(my_path, bottomup=0, encrypt=pw)  # canvas
c.drawString(50, 200, "this is protected")  # write text in page
c.showPage()  # saves current page
c.save()  # stores the file and closes the canvas




Questions 🔝


PDF Table from different data sources to PDF file
Bar charts in PDF Line charts in PDF Pie Charts Paragraph
Python

Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer