吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1678|回复: 46
收起左侧

[Windows] PDF批量合并

  [复制链接]
MXDZRB 发表于 2025-3-31 15:29


[Python] 纯文本查看 复制代码
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import os
import threading
from queue import Queue
try:
    from PyPDF2 import PdfMerger
except ModuleNotFoundError:
    import sys
    sys.exit("Error: PyPDF2 模块未安装,请运行 'pip install PyPDF2' 进行安装")
 
class PDFMergerApp:
    def __init__(self):
        self.window = tk.Tk()
        self.window.title('📄 PDF合并打印软件')
        self.window.geometry('700x450')
        self.window.configure(bg='#F8FAFC')
         
        # 创建现代风格按钮
        self.button_style = {
            'background': '#4F46E5',
            'foreground': 'white',
            'borderwidth': 0,
            'relief': 'flat',
            'font': ('微软雅黑', 12, 'bold'),
            'padx': 30,
            'pady': 15
        }
         
        # 主容器框架,添加圆角和阴影效果
        main_frame = tk.Frame(self.window, bg='#FFFFFF')
        main_frame.grid_columnconfigure(0, weight=1)
        main_frame.grid_rowconfigure(1, weight=1)
        main_frame.pack(expand=True, fill='both', padx=35, pady=30)
         
        # 标题标签
        title_label = tk.Label(
            main_frame,
            text='PDF文件合并工具',
            font=('微软雅黑', 20, 'bold'),
            fg='#1E293B',
            bg='#FFFFFF',
            pady=20
        )
        title_label.grid(row=0, column=0, sticky='ew')
         
        # 文件选择按钮容器
        button_frame = tk.Frame(main_frame, bg='#FFFFFF', padx=20)
        button_frame.grid(row=1, column=0, sticky='ew')
        button_frame.grid_columnconfigure(0, weight=1)
         
        # 文件选择按钮
        select_button = tk.Button(
            button_frame,
            text='🖇️ 选择并合并PDF文件',
            command=self.select_and_merge_pdfs,
            cursor='hand2',
            **self.button_style
        )
        select_button.grid(row=0, column=0, pady=(25,35), sticky='ew')
         
        # 状态标签
        self.status_label = tk.Label(main_frame,
                                   text='准备就绪',
                                   font=('微软雅黑', 11),
                                   fg='#64748B',
                                   bg='#FFFFFF',
                                   padx=15,
                                   pady=12)
        self.status_label.grid(row=2, column=0, pady=(5,15), sticky='ew')
         
        # 配置悬停效果
        select_button.bind('<Enter>', lambda e: select_button.config(background='#4338CA'))
        select_button.bind('<Leave>', lambda e: select_button.config(background='#4F46E5'))
         
        # 设置窗口图标
        try:
            self.window.iconbitmap('pdf_icon.ico')
        except:
            pass
         
        # 用于线程间通信
        self.queue = Queue()
 
    def update_progress(self):
        try:
            while not self.queue.empty():
                msg = self.queue.get_nowait()
                if msg.startswith('status:'):
                    self.status_label['text'] = msg.split(':')[1]
                elif msg.startswith('error:'):
                    messagebox.showerror('错误', f'处理PDF时出错:{msg.split(":", 1)[1]}')
                elif msg == 'done':
                    return
        except Queue.Empty:
            pass
        self.window.after(50, self.update_progress)
 
    def merge_pdfs_thread(self, files):
        try:
            merger = PdfMerger(strict=False)
            total_files = len(files)
             
            for i, pdf_file in enumerate(files, 1):
                with open(pdf_file, 'rb') as pdf:
                    merger.append(fileobj=pdf, import_outline=False)
                self.queue.put(f'status:正在处理: {os.path.basename(pdf_file)}')
 
             
            output_path = os.path.join(os.path.dirname(files[0]), 'merged_output.pdf')
            self.queue.put('status:正在保存文件...')
            with open(output_path, 'wb') as output:
                merger.write(fileobj=output)
            merger.close()
             
            self.queue.put('status:完成!')
 
            os.startfile(output_path)
             
        except Exception as e:
            self.queue.put(f'error:{str(e)}')
        finally:
            self.queue.put('done')
     
    def select_and_merge_pdfs(self):
        # 打开文件选择对话框
        files = filedialog.askopenfilenames(
            title='选择PDF文件',
            filetypes=[('PDF files', '*.pdf')]
        )
         
        if files:
            # 重置状态
            self.status_label['text'] = '准备处理...'
             
            # 启动处理线程
            thread = threading.Thread(target=self.merge_pdfs_thread, args=(files,))
            thread.daemon = True
            thread.start()
             
            # 启动进度更新
            self.window.after(100, self.update_progress)
 
    def run(self):
        self.window.mainloop()
 
if __name__ == '__main__':
    app = PDFMergerApp()
    app.run()
image.png

免费评分

参与人数 4吾爱币 +3 热心值 +4 收起 理由
dogox + 1 + 1 我很赞同!
mu12138 + 1 + 1 热心回复!
bosxie + 1 + 1 谢谢@Thanks!
wuai5211314 + 1 感谢分享!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

manglang 发表于 2025-3-31 16:38
输出文件名是固定的,每次都要改名才能处理下一个项目,不如以时间为文件名,这样就不怕重名了。
[Python] 纯文本查看 复制代码
1
2
3
4
5
now = datetime.datetime.now()
 timestamp = now.strftime("%Y-%m-%d_%H-%M-%S")
filename = f"{timestamp}_合并.pdf"
output_path = os.path.join(os.path.dirname(files[0]), (f'{filename}'))
self.queue.put('status: 保存文件......')
 楼主| MXDZRB 发表于 2025-4-1 14:39
ecaven 发表于 2025-4-1 10:48
有没有两个pdf文件的页面交叉合并的功能,比如双面打印的文件但扫描仪只能单面扫描,是否可以合成一个pdf?

PDFsam Basic(PDF 拆分和合并): 这是最推荐的免费、开源、跨平台(Windows, macOS, Linux)的工具之一。

它有一个专门的功能叫做 "" (交替合并 或 交叉合并)。替代混音

操作方法:打开 PDFsam Basic -> 选择 “Alternate Mix” 模块 -> 分别添加你的奇数页PDF文件和偶数页PDF文件 -

优点: 免费、功能强大、专门为此类任务设计、相对安全(文件在本地处理)。
jsyxp 发表于 2025-3-31 15:36
ziyouzizai 发表于 2025-3-31 15:40
感谢分享
JKBOX 发表于 2025-3-31 15:41
方法不错 值得借鉴
wuai5211314 发表于 2025-3-31 15:44
感谢分享!
zhangchuan123 发表于 2025-3-31 15:46
大哥,你这个批量合并,小白完全看不懂呀,来个安装下载链接
pleny 发表于 2025-3-31 15:53
能开发个PDF排版的,这样可以自制小尺寸阅读的电纸书。
taochangpeng 发表于 2025-3-31 15:58
有点深奥,表示看不明白,还是要支持楼主
http88 发表于 2025-3-31 16:01
都是好工具好辅助啊  谢谢!
briskelf 发表于 2025-3-31 16:12
感谢大神分享
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2025-4-7 04:00

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表