import os from pypdf import PdfWriter def merge_pdfs_in_current_folder(): # 自動取得這個 python 腳本所在的資料夾路徑 current_dir = os.path.dirname(os.path.abspath(__file__)) output_filename = "output.pdf" output_path = os.path.join(current_dir, output_filename) # 使用新版的 PdfWriter 來進行合併 merger = PdfWriter() pdf_files = [] # 找出同層目錄下所有 .pdf 檔案 for file in os.listdir(current_dir): # 確保是 PDF 檔,且排除掉我們要輸出的 output.pdf 本身 if file.lower().endswith('.pdf') and file != output_filename: pdf_files.append(file) # 依檔案名稱排序 (例如 1.pdf, 2.pdf) pdf_files.sort() if not pdf_files: print("在同層目錄中找不到任何可以合併的 PDF 檔案。") return print("發現以下 PDF 檔案,準備進行合併:") for file in pdf_files: print(f"- {file}") # 逐一將 PDF 檔案加入合併器 for file in pdf_files: full_path = os.path.join(current_dir, file) try: merger.append(full_path) except Exception as e: print(f"讀取檔案 {file} 時發生錯誤: {e}") # 寫入合併後的檔案 try: with open(output_path, "wb") as fout: merger.write(fout) print(f"\n合併完成!已成功輸出至:\n{output_path}") except Exception as e: print(f"\n儲存檔案時發生錯誤: {e}") merger.close() if __name__ == "__main__": merge_pdfs_in_current_folder()