[Python] 纯文本查看 复制代码
# -*- coding: utf-8 -*-
import tkinter as tk
from tkinter import filedialog
from PyPDF2 import PdfReader, PdfWriter
import os
def select_input_folder():
folder_path = filedialog.askdirectory()
input_folder_entry.delete(0, tk.END)
input_folder_entry.insert(0, folder_path)
def select_output_folder():
folder_path = filedialog.askdirectory()
output_folder_entry.delete(0, tk.END)
output_folder_entry.insert(0, folder_path)
def delete_pages():
input_folder = input_folder_entry.get()
output_folder = output_folder_entry.get()
# 创建输出文件夹
os.makedirs(output_folder, exist_ok=True)
# 获取输入文件夹中的所有PDF文件
pdf_files = [f for f in os.listdir(input_folder) if f.endswith('.pdf')]
# 遍历每个PDF文件进行转换
for file_name in pdf_files:
input_file = os.path.join(input_folder, file_name)
output_file = os.path.join(output_folder, file_name)
try:
# 打开PDF文件
with open(input_file, 'rb') as file:
reader = PdfReader(file)
total_pages = len(reader.pages)
# 指定要删除的页面
page_to_remove = int(page_to_remove_entry.get())
# 创建一个新的PDF写入对象
writer = PdfWriter()
# 复制除要删除的页面外的所有页面到新的PDF文件中
for page_num in range(total_pages):
if page_num != page_to_remove - 1:
writer.add_page(reader.pages[page_num])
# 保存新的PDF文件
with open(output_file, 'wb') as output:
writer.write(output)
except Exception as e:
error_log_text.insert(tk.END, f"转换失败:{file_name}\n")
error_log_text.insert(tk.END, f"错误信息:{str(e)}\n\n")
error_log_text.insert(tk.END, "转换完成!")
# 创建主窗口
window = tk.Tk()
window.title("PDF页面删除工具")
# 输入文件夹选择部分
input_folder_label = tk.Label(window, text="输入文件夹:")
input_folder_label.grid(row=0, column=0, padx=10, pady=10, sticky=tk.W)
input_folder_entry = tk.Entry(window, width=40)
input_folder_entry.grid(row=0, column=1, padx=10, pady=10)
input_folder_button = tk.Button(window, text="选择文件夹", command=select_input_folder)
input_folder_button.grid(row=0, column=2, padx=10, pady=10)
# 输出文件夹选择部分
output_folder_label = tk.Label(window, text="输出文件夹:")
output_folder_label.grid(row=1, column=0, padx=10, pady=10, sticky=tk.W)
output_folder_entry = tk.Entry(window, width=40)
output_folder_entry.grid(row=1, column=1, padx=10, pady=10)
output_folder_button = tk.Button(window, text="选择文件夹", command=select_output_folder)
output_folder_button.grid(row=1, column=2, padx=10, pady=10)
# 删除页面部分
page_to_remove_label = tk.Label(window, text="要删除的页面:")
page_to_remove_label.grid(row=2, column=0, padx=10, pady=10, sticky=tk.W)
page_to_remove_entry = tk.Entry(window, width=40)
page_to_remove_entry.grid(row=2, column=1, padx=10, pady=10)
# 删除按钮
delete_button = tk.Button(window, text="运行", command=delete_pages)
delete_button.grid(row=3, column=0, columnspan=3, padx=10, pady=10)
# 错误日志文本框
error_log_text = tk.Text(window, width=60, height=10)
error_log_text.grid(row=4, column=0, columnspan=3, padx=10, pady=10)
# 启动窗口
window.mainloop()