平台:win10家庭版,python 3.7,PyPDF2
思维过程:
方法一:将pdf文件通过拆分为单页,放入一个文件夹,再删除其中不要的文件,最后再把剩余的文件进行合并为一个pdf文件
第一步:使用原文件路径创建新文件夹,用于存放拆分后的单页文件
defnewdir(self,path):
self.new=os.path.splitext(path)[0]if not os.path.isdir(self.new): #使用os.path.isdir判断文件夹是否存在,
os.mkdir(self.new)
View Code
第二步:生成单页文件,并存放到新建的文件夹
1 defpdfsplt(self,path):2 ifos.path.isfile(path):3 file_1 = open(path,"rb")4 file_reader = PyPDF2.PdfFileReader(file_1, strict=False) #使用strict关闭错误提示
5 #使用for循环读取每一页并将其写入新pdf文件,文件以页码命名
6 for page inrange(0,file_reader.getNumPages()):7 file_write =PyPDF2.PdfFileWriter()8 pageobj =file_reader.getPage(page)9 file_write.addPage(pageobj)10 output = str(self.new) + "\\" + str(int(page+1)) + ".pdf"
11 with open(output,"wb") as output_pdf:12 file_write.write(output_pdf)13 file_1.close()14 else:15 print("文件不存在!")16 time.sleep(3)17 exit()
View Code
第三步:删除文件夹中不要的文件
1 defpdfremove(self,number):2 for pag innumber:3 filename = str(self.new) + "\\" + str(pag) + ".pdf"
4 ifos.path.isfile(filename):5 os.unlink(filename)6 else:7 print("请确认要删除的页码%s是否正确!!"%pag)
View Code
第四步:把剩余文件合并为一个pdf文件