练手代码之使用Python实现合并PDF文件

如果你有合并PDF的需要,你会怎么办

我们无所不能的程序员会选择写一个Python代码来实现(谁会这么无聊?是我),如果真的有PDF操作需要,我推荐你使用PDF Expert这个软件哈~

话不多说直接上代码:

import os
import PyPDF2
from tkinter import Tk
from tkinter.filedialog import askopenfilenames

def combine_pdfs(input_files, output_file):
    pdf_merger = PyPDF2.PdfMerger()
    
    try:
        for file_path in input_files:
            if not os.path.exists(file_path):
                raise FileNotFoundError(f"The file {file_path} does not exist.")
            with open(file_path, 'rb') as f:
                pdf_merger.append(f)
        
        output_dir = os.path.dirname(output_file)
        if output_dir and not os.path.exists(output_dir):
            os.makedirs(output_dir)
        
        with open(output_file, 'wb') as f:
            pdf_merger.write(f)
        print("合并成功")
    except Exception as e:
        print("合并PDF时出现错误:", str(e))
        raise

def get_file_paths():
    Tk().withdraw() # 不显示Tkinter的根窗口
    file_paths = askopenfilenames(filetypes=[("PDF files", "*.pdf")])
    return file_paths

input_files = get_file_paths()

if len(input_files) < 2:
    print("请选择至少两个PDF文件进行合并。")
else:
    # 组合文件命名
    output_file = "combined_pdfs.pdf"
    try:
        combine_pdfs(input_files, output_file)
    except FileNotFoundError as e:
        print(e)

运行之后弹窗选择两个PDF文件即可,会自动输出在根目录 

 

练手代码之使用Python实现合并PDF文件_第1张图片

结束

By the way,我的博客:https://wcowin.work/ 

欢迎来撩~

你可能感兴趣的:(Python,python,pdf,前端)