Python PDF Protect Multiple Files

Abaixo você encontra os procedimentos para configuração e o código-fonte em Python desenvolvido para proteger vários arquivos PDF em lote, adicionando senhas de usuário e proprietário em todos os documentos de um diretório.


Procedimento Operacional Padrão (POP)

1. Criar o ambiente virtual (venv) no Windows

Ainda não criou o seu ambiente localhost? Veja no link abaixo como fazer.


2. Instalar as bibliotecas Python

Com o ambiente virtual ativado, instale a biblioteca externa pypdf necessária para a manipulação e criptografia dos arquivos PDF:

pip install pypdf

3. Como configurar o script


Código-Fonte

# REQUEST LIB PYTHON
import os
from pathlib import Path
from pypdf import PdfReader, PdfWriter

def protect_files(
    input_dir: str,
    output_dir: str,
    psw_user: str,
    psw_owner: str,
):
    """
    Protects all PDFs in input directory and saves to output directory.

    Args:
        input_dir (str): Path to folder with original PDFs.
        output_dir (str): Path to folder for protected PDFs.
        psw_user (str): User password (open document).
        psw_owner (str): Owner password (permissions).
    """
    input_path = Path(input_dir)
    output_path = Path(output_dir)

    # Create output directory if it doesn't exist
    output_path.mkdir(parents=True, exist_ok=True)

    pdfs_processed = 0
    for file in input_path.glob("*.pdf"):
        try:
            print(f"Processing: {file.name}")

            # Read PDF
            reader = PdfReader(file)
            writer = PdfWriter()

            # Copy all pages
            for page in reader.pages:
                writer.add_page(page)

            writer.encrypt(
                user_password=psw_user, owner_password=psw_owner, algorithm="AES-256"
            )

            # Output name: original-psw.pdf
            # output_filename = file.stem + "-psw.pdf"
            output_filename = file.stem + ".pdf"
            output_filepath = output_path / output_filename

            # Save
            with open(output_filepath, "wb") as f:
                writer.write(f)

            pdfs_processed += 1
            print(f"✓ Saved: {output_filename}")

        except Exception as e:
            print(f"✗ Error in {file.name}: {str(e)}")

    print(f"\nSuccess! {pdfs_processed} PDFs protected.")


# Usage
if __name__ == "__main__":
    protect_files(
        input_dir=r"C:\test\pdf",
        output_dir=r"C:\test\pdf",
        psw_user="psw123",
        psw_owner="psw456",
    )