Code With Python
39K subscribers
843 photos
24 videos
22 files
747 links
This channel delivers clear, practical content for developers, covering Python, Django, Data Structures, Algorithms, and DSA – perfect for learning, coding, and mastering key programming skills.
Admin: @HusseinSheikho || @Hussein_Sheikho
Download Telegram
📚 Learn to Code by Solving Problems (2022)

1⃣ Join Channel Download:
https://t.me/+MhmkscCzIYQ2MmM8

2⃣ Download Book: https://t.me/c/1854405158/45

💬 Tags: #code #python

USEFUL CHANNELS FOR YOU
❤‍🔥91👍1
💀 How to encrypt a PDF with a password using Python

Ready Python script: takes a regular PDF and creates a password-protected copy.

📦 Library installation
pip install PyPDF2


⌨️ Code
from __future__ import annotations
from pathlib import Path
from typing import Union

from PyPDF2 import PdfReader, PdfWriter

PDFPath = Union[str, Path]


def encrypt_pdf(input_path: PDFPath, output_path: PDFPath, password: str) -> Path:
    """
    Encrypts a PDF file with a password and saves it to output_path.
    Returns the path to the encrypted file.
    """
    in_path = Path(input_path)
    out_path = Path(output_path)

    reader = PdfReader(in_path)
    writer = PdfWriter()

    for page in reader.pages:
        writer.add_page(page)

    writer.encrypt(password)

    with out_path.open("wb") as f:
        writer.write(f)

    return out_path


def encrypt_with_suffix(input_path: PDFPath, password: str, suffix: str = "_encrypted") -> Path:
    """
    Creates an encrypted copy next to the original file.
    For example: secret.pdf → secret_encrypted.pdf
    """
    in_path = Path(input_path)
    output_path = in_path.with_name(f"{in_path.stem}{suffix}{in_path.suffix}")
    return encrypt_pdf(in_path, output_path, password)


if __name__ == "__main__":
    pdf_file = "secret.pdf"
    pdf_password = "pythontoday"

    encrypted_path = encrypt_with_suffix(pdf_file, pdf_password)
    print(f"Encrypted file created: {encrypted_path}")


💡 Where it will be useful

🟢send a document to a client with the password via a separate channel;
🟢store important PDFs in encrypted form;
🟢integrate encryption into your service/bot/admin panel.

#python #code #tipsandtricks

https://t.me/DataScience4 🌟
Please open Telegram to view this post
VIEW IN TELEGRAM
4👍1👎1