Python批量加密pdf

1次阅读
没有评论

人狠话不多,兰州连接包含源码和打包好的单文件程序

https://abpyu.lanzoul.com/irEuG1rh84qj

import tkinter as tk
from tkinter import filedialog, messagebox
import os
import configparser
import PyPDF2

# 读取配置文件
config = configparser.ConfigParser()
config.read('config.ini')
last_password = config.get('Settings', 'LastPassword', fallback='')

# GUI窗口
root = tk.Tk()
root.title('PDF加密工具')

# 选择包含PDF文件的文件夹的函数
def select_pdf_folder():
dir_path = filedialog.askdirectory()
if dir_path:
entry_pdf_path.delete(0, tk.END)
entry_pdf_path.insert(0, dir_path)

# 选择保存路径的函数
def select_save_path():
dir_path = filedialog.askdirectory()
if dir_path:
entry_save_path.delete(0, tk.END)
entry_save_path.insert(0, dir_path)

# 加密文件夹内的所有PDF文件的函数
def encrypt_pdfs():
pdf_folder = entry_pdf_path.get()
save_path = entry_save_path.get()
password = entry_password.get()

if not pdf_folder or not save_path or not password:
messagebox.showerror('错误', '请填写所有字段')
return

# 确保节存在,如果不存在则创建
if not config.has_section('Settings'):
config.add_section('Settings')

# 更新配置文件
config.set('Settings', 'LastPassword', password)
with open('config.ini', 'w') as config_file:
config.write(config_file)

# 遍历文件夹中的所有PDF文件
for filename in os.listdir(pdf_folder):
if filename.lower().endswith('.pdf'):
pdf_path = os.path.join(pdf_folder, filename)
with open(pdf_path, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
pdf_writer = PyPDF2.PdfWriter()

for page in pdf_reader.pages:
pdf_writer.add_page(page)

pdf_writer.encrypt(password)

new_file_path = os.path.join(save_path, filename)
with open(new_file_path, 'wb') as new_file:
pdf_writer.write(new_file)

messagebox.showinfo('完成', '所有PDF文件已加密')

# GUI布局
label_pdf_path = tk.Label(root, text='PDF源文件夹:')
label_pdf_path.grid(row=0, column=0, sticky='e')

entry_pdf_path = tk.Entry(root, width=50)
entry_pdf_path.grid(row=0, column=1, padx=5, pady=5)

button_browse_pdf = tk.Button(root, text='浏览', command=select_pdf_folder)
button_browse_pdf.grid(row=0, column=2, padx=5, pady=5)

label_save_path = tk.Label(root, text='保存PDF路径:')
label_save_path.grid(row=1, column=0, sticky='e')

entry_save_path = tk.Entry(root, width=50)
entry_save_path.grid(row=1, column=1, padx=5, pady=5)

button_browse_save = tk.Button(root, text='浏览', command=select_save_path)
button_browse_save.grid(row=1, column=2, padx=5, pady=5)

label_password = tk.Label(root, text='设置密码:')
label_password.grid(row=2, column=0, sticky='e')

entry_password = tk.Entry(root, show='', width=50)
entry_password.insert(0, last_password)
entry_password.grid(row=2, column=1, padx=5, pady=5)

button_encrypt = tk.Button(root, text='加密', command=encrypt_pdfs)
button_encrypt.grid(row=3, column=1, padx=5, pady=10)

# 运行GUI
root.mainloop()

正文完
 0
116博客
版权声明:本篇文章由 116博客 于2024-11-27发表,共计2437字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码