这是以前的一个python小程序。假如文件夹下有5个PDF文件,他们的名字分别是:
hello
world
nihao
shijie
thankyou
把他们合并到成一个jieshao.pdf文件,并且用上面5个文件的名字来作为jieshao.pdf的书签。
:::info
这个函数会遍历要求目录下的所有文件,将以 .pdf 结尾的所有pdf合并成一个新的pdf,并保存在 file_dir 目录下
:::
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 import osimport os.pathfrom PyPDF2 import PdfFileReader, PdfFileWriterimport timedef getFileName (filepath ): list1=[] for root, dirs, files in os.walk(filepath, topdown=False ): for name in files: if name.endswith(".pdf" ): list1.append(os.path.join(root, name)) return list1 def MergePDF (filepath, outfile ): output = PdfFileWriter() outputPages = 0 pdf_fileName = getFileName(filepath) for each_file in pdf_fileName: print ("adding %s" % each_file) input = PdfFileReader(open (each_file, "rb" )) if input .isEncrypted == True : input .decrypt("map" ) pageCount = input .getNumPages() outputPages += pageCount print ("%s has %d pages" % (each_file, pageCount)) for iPage in range (pageCount): output.addPage(input .getPage(iPage)) x=outputPages-pageCount output.addBookmark( title=each_file.split("\\" )[-1 ]+str (x+1 )+'-' +str (x+pageCount),pagenum=x) print ("All Pages Number: " + str (outputPages)) outputStream = open (os.path.join(filepath, outfile), "wb" ) output.write(outputStream) outputStream.close() print ("finished" ) if __name__ == '__main__' : time1 = time.time() file_dir =r'C:\Users\frankelin\Documents\湖南醴陵旅游' out = u"jieshao.pdf" MergePDF(file_dir, out) time2 = time.time() print (u'总共耗时: %.4f s' % (time2 - time1))