程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Use Python to sort and merge PDF by PDF creation time, and add bookmarks

編輯:Python
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')

 


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved