python 删除pdf页面_使用PyPDF2库对pdf文件进行指定页面删除操作

平台: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文件

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值