用Tkinter制作一个用于合并PDF文件的小程序

需要安装PyPDF2库,具体原代码如下:

python 复制代码
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 29 14:44:20 2024

@author: YBK
"""

import PyPDF2
import os
import tkinter as tk 
import windnd

 
pdf_files = []
def dragged_files(files):    
    if len(files) > 1:
        for item in files:
            pdf_files.append(item.decode('gbk'))
        message.config(text='当前拖放的文件路径为:\n' + '\n'.join((file for file in pdf_files)))        
    else:
        pdf_files.append(files[0].decode('gbk'))
        message.config(text='当前拖放的文件路径为:\n' + '\n'.join((file for file in pdf_files))) 
   
def is_pdf_file(file_path):
    # 使用os.path.splitext()分割文件路径和扩展名
    _, file_extension = os.path.splitext(file_path)
    # 检查扩展名是否为.pdf(注意扩展名包含点号)
    return file_extension.lower() == '.pdf'

def on_button_click():
    global pdf_files
    print("生成合并的PDF文件!")
    output_path = os.path.dirname(pdf_files[0])
    output_path = os.path.join(output_path,'mergedpdf.pdf')
    print(output_path)
    merge_pdfs(pdf_files, output_path)
    message.config(text='合成成功,当前合成PDF的文件路径为:\n' + output_path)
 
def on_button_click0():
    global pdf_files
    pdf_files = []
    message.config(text='当前拖放的文件路径为:\n' + '\n'.join((file for file in pdf_files)))
    print("清空列表")

def merge_pdfs(pdf_list, output_path):
    merger = PyPDF2.PdfMerger()    
    for pdf in pdf_list:
        if is_pdf_file(pdf):
            with open(pdf, 'rb') as f:
                merger.append(f)    
    with open(output_path, 'wb') as f:
        merger.write(f)

if __name__ == '__main__':
    rootWindow = tk.Tk()
    rootWindow.title("按顺序拖拉PDF文件进行合并")
    rootWindow.geometry("400x520")
    message = tk.Message(rootWindow, width=400, text="当前未拖放PDF文件,请拖放文件到这里...")
    message.grid(row=0,columnspan=2)
    button0 = tk.Button(rootWindow, text="清空文件列表", command=on_button_click0)
    button = tk.Button(rootWindow, text="提交进行合并", command=on_button_click)
    # 放置按钮在主窗口上
    button0.grid(row=1,column=0)
    button.grid(row=1,column=1)
    windnd.hook_dropfiles(rootWindow, func=dragged_files,)
    rootWindow.mainloop()

运行界面:

非常实用,提高办公效率。因为现在Wps合并PDF文件需要会员,还是自己开发一个。

相关推荐
腾马科技6 小时前
新版saas餐饮外卖小程序源码/微信/支付宝/抖音/扫码点餐/DIY装修/美团代付/全开源
微信小程序·小程序·点餐小程序
郑叔敲代码10 小时前
帝国cms 微信小程序的登录逻辑
微信小程序·小程序·notepad++
CodeCraft Studio11 小时前
CAD文件处理控件Aspose.CAD教程:在 Python 中将 SVG 转换为 PDF
开发语言·python·pdf·svg·cad·aspose·aspose.cad
lifallen12 小时前
从Apache Doris 学习 HyperLogLog
java·大数据·数据仓库·算法·apache
DolphinScheduler社区13 小时前
# 3.1.8<3.2.0<3.3.1,Apache DolphinScheduler集群升级避坑指南
java·大数据·开源·apache·任务调度·海豚调度
棋子一名14 小时前
跑马灯组件 Vue2/Vue3/uni-app/微信小程序
微信小程序·小程序·uni-app·vue·js
无衣 秦风15 小时前
vue3+hubuilderX开发微信小程序使用elliptic生成ECDH密钥对遇到的问题
微信小程序·小程序
游戏开发爱好者815 小时前
BShare HTTPS 集成与排查实战,从 SDK 接入到 iOS 真机调试(bshare https、签名、回调、抓包)
android·ios·小程序·https·uni-app·iphone·webview
2501_9160088915 小时前
iOS 26 系统流畅度实战指南|流畅体验检测|滑动顺畅对比
android·macos·ios·小程序·uni-app·cocoa·iphone
流***陌16 小时前
陪诊就医小程序中健康档案的精细化管理设计方案
小程序