import os
import sys
import os
from PyPDF2 import PdfFileReader, PdfFileWriter
import time
DIR = "C:\\Users\\pc\\Desktop\ New folder (4)"
# Gets the maximum recursion depth
print(sys.getrecursionlimit())
sys.setrecursionlimit(2000)
def get_file_list(file_path):
dir_list = os.listdir(file_path)
if not dir_list:
return
else:
# Be careful , Use here lambda expression , Arrange the files in ascending order according to the last modification time
# os.path.getmtime() The function is to get the last modification time of the file
# os.path.getctime() The function is to get the last creation time of the file
dir_list = sorted(dir_list, key=lambda x: os.path.getmtime(os.path.join(file_path, x)))
# print(dir_list)
return dir_list
# Merge all under the same directory PDF file
def MergePDF(filepath, outfile):
output = PdfFileWriter()
outputPages = 0
pdf_fileName = get_file_list(DIR)
if pdf_fileName:
for pdf_file in pdf_fileName:
print(" route :%s" % pdf_file)
# Read source PDF file
# input = PdfFileReader(open(pdf_file, "rb"))
try:
input = PdfFileReader(open(os.path.join(filepath, pdf_file), "rb"))
except:
pass
# Get the source PDF The total number of pages in the file
pageCount = input.getNumPages()
outputPages += pageCount
print(" the number of pages :%d" % pageCount)
title = pdf_file[:-4]
print(title)
# Separately page Add to output output in
for iPage in range(pageCount):
output.addPage(input.getPage(iPage))
output.addBookmark(title=pdf_file[:-4], pagenum=outputPages - pageCount)
print(" Total combined pages :%d." % outputPages)
# Write to target PDF file
outputStream = open(os.path.join(filepath, outfile), "wb")
output.write(outputStream)
outputStream.close()
print("PDF File merge complete !")
else:
print(" There is nothing to merge PDF file !")
MergePDF("C:\\Users\\pc\\Desktop\\ New folder (4)", ' test .pdf')