A quick way to encrypt PDFs

Carrying on with this week’s PDF escapades, spent some time picking through the docs and the forum and have come up with a really simple, reusable pattern for encrypting PDFs from a FileLoader.

I clocked some posts in which people had previously struggled with this and it has nearly driven me to distraction the last couple of days as it just wouldn’t make sense at first.

  1. Place a FileLoader on your form. Add a datatable with two columns: file(Media object) and filename (String). Create a secret called ‘file’ and generate a value for it.

  2. In your form code:

def file_loader_1_change(self, file, **event_args):
    """This method is called when a new file is loaded into this FileLoader"""
  1. In your server module:
import PyPDF2
from PyPDF2 import PdfFileWriter, PdfFileReader
import anvil.media
import io
from io import BytesIO

def processdata(file):
  name_file = file.name
  app_tables.files.add_row(file=file, filename=name_file)
  row = app_tables.file.get(filename=name_file)
  pdf_bytes = row['file'].get_bytes()
  file1 = io.BytesIO(pdf_bytes)
  pdfReader = PyPDF2.PdfFileReader(file1)

  pdfWriter = PyPDF2.PdfFileWriter()
  for pagenum in range(pdfReader.numPages):
    pageobj = pdfReader.getPage(pagenum)
  password = anvil.secrets.get_secret('file')
  pdfWriter.encrypt(user_pwd=password, owner_pwd=None,use_128bit=True)
  out_file = io.BytesIO()
  filename = "enc-"+name_file
  out_file_media = anvil.BlobMedia("application/pdf", out_file.read(), name=filename)


That’s it, an encrypted PDF stored in your database for later use. Hope another Anvil user finds this useful in some way.