import os
import sys
import os
from PyPDF2 import PdfFileReader, PdfFileWriter
import time
DIR = "C:\\Users\\pc\\Desktop\新建文件夾 (4)"
#獲取最大遞歸深度
print(sys.getrecursionlimit())
sys.setrecursionlimit(2000)
def get_file_list(file_path):
dir_list = os.listdir(file_path)
if not dir_list:
return
else:
# 注意,這裡使用lambda表達式,將文件按照最後修改時間順序升序排列
# os.path.getmtime() 函數是獲取文件最後修改時間
# os.path.getctime() 函數是獲取文件最後創建時間
dir_list = sorted(dir_list, key=lambda x: os.path.getmtime(os.path.join(file_path, x)))
# print(dir_list)
return dir_list
# 合並同一目錄下的所有PDF文件
def MergePDF(filepath, outfile):
output = PdfFileWriter()
outputPages = 0
pdf_fileName = get_file_list(DIR)
if pdf_fileName:
for pdf_file in pdf_fileName:
print("路徑:%s" % pdf_file)
# 讀取源PDF文件
# input = PdfFileReader(open(pdf_file, "rb"))
try:
input = PdfFileReader(open(os.path.join(filepath, pdf_file), "rb"))
except:
pass
# 獲得源PDF文件中頁面總數
pageCount = input.getNumPages()
outputPages += pageCount
print("頁數:%d" % pageCount)
title = pdf_file[:-4]
print(title)
# 分別將page添加到輸出output中
for iPage in range(pageCount):
output.addPage(input.getPage(iPage))
output.addBookmark(title=pdf_file[:-4], pagenum=outputPages - pageCount)
print("合並後的總頁數:%d." % outputPages)
# 寫入到目標PDF文件
outputStream = open(os.path.join(filepath, outfile), "wb")
output.write(outputStream)
outputStream.close()
print("PDF文件合並完成!")
else:
print("沒有可以合並的PDF文件!")
MergePDF("C:\\Users\\pc\\Desktop\\新建文件夾 (4)", '測試.pdf')