平台:win10家庭版,python 3.7,PyPDF2

思维过程:

方法一:将pdf文件通过拆分为单页,放入一个文件夹,再删除其中不要的文件,最后再把剩余的文件进行合并为一个pdf文件

第一步:使用原文件路径创建新文件夹,用于存放拆分后的单页文件

def newdir(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 def pdfsplt(self,path):
 2                     if os.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 in range(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 def pdfremove(self,number):
2     for pag in number:
3         filename = str(self.new) + "\\" + str(pag) + ".pdf"
4         if os.path.isfile(filename):
5             os.unlink(filename)
6         else:
7             print("请确认要删除的页码%s是否正确!!"%pag)

View Code

  第四步:把剩余文件合并为一个pdf文件

 1 def pdfmerge(self):
 2     file_list = [int(os.path.splitext(x)[0]) for x in os.listdir(self.new)]  #读取新建文件夹下的所有文件并提取文件名转为数字
 3     file_write = PyPDF2.PdfFileWriter() #先创建一个新的pdf对象
 4     for page in sorted(file_list):
 5         pathstr = str(self.new) + "\\" + str(page) + ".pdf"
 6         file_1 = open(pathstr,"rb")
 7         file_reader = PyPDF2.PdfFileReader(file_1, strict=False)  # 使用strict关闭错误提示
 8         pageobj = file_reader.getPage(0)
 9         file_write.addPage(pageobj)
10         output = str(self.new) + "_new.pdf"
11         with open(output, "wb") as output_pdf:
12             file_write.write(output_pdf)
13             print("第%s页完成"%page)
14         file_1.close()

View Code

  第五步:删除其中的缓存文件夹

1 def rmdir(self):
2     if os.path.isdir(self.new):
3         shutil.rmtree(self.new)

View Code

方法一的完整代码:

 1 import PyPDF2
 2 import os,time,shutil,sys
 3 import threading
 4
 5 class mypdf(object):
 6     def __init__(self,path,number):
 7         self.newdir(path)
 8         self.pdfsplt(path)
 9         self.pdfremove(number)
10         self.pdfmerge()
11         self.rmdir()
12         pass
13
14     #用于创建一个独立的文件夹,存放缓存数据
15     def newdir(self,path):
16         self.new = os.path.splitext(path)[0]
17         if not os.path.isdir(self.new): #使用os.path.isdir判断文件夹是否存在,
18             os.mkdir(self.new)
19
20     #将每一页生成独立文件,存放到缓存文件夹
21     def pdfsplt(self,path):
22         if os.path.isfile(path):
23             file_1 = open(path,"rb")
24             file_reader = PyPDF2.PdfFileReader(file_1, strict=False)  #使用strict关闭错误提示
25             #使用for循环读取每一页并将其写入新pdf文件,文件以页码命名
26             for page in range(0,file_reader.getNumPages()):
27                 file_write = PyPDF2.PdfFileWriter()
28                 pageobj = file_reader.getPage(page)
29                 file_write.addPage(pageobj)
30                 output = str(self.new) + "\\" + str(int(page+1)) + ".pdf"
31                 with open(output,"wb") as output_pdf:
32                     file_write.write(output_pdf)
33             file_1.close()
34         else:
35             print("文件不存在!")
36             time.sleep(3)
37             exit()
38
39     #删除缓存文件夹中的不要的页
40     def pdfremove(self,number):
41         for pag in number:
42             filename = str(self.new) + "\\" + str(pag) + ".pdf"
43             if os.path.isfile(filename):
44                 os.unlink(filename)
45             else:
46                 print("请确认要删除的页码%s是否正确!!"%pag)
47
48     #将缓存文件夹中的剩余文件合进行合并
49     def pdfmerge(self):
50         file_list = [int(os.path.splitext(x)[0]) for x in os.listdir(self.new)]  #读取新建文件夹下的所有文件并提取文件名转为数字
51         file_write = PyPDF2.PdfFileWriter() #先创建一个新的pdf对象
52         for page in sorted(file_list):
53             pathstr = str(self.new) + "\\" + str(page) + ".pdf"
54             file_1 = open(pathstr,"rb")
55             file_reader = PyPDF2.PdfFileReader(file_1, strict=False)  # 使用strict关闭错误提示
56             pageobj = file_reader.getPage(0)
57             file_write.addPage(pageobj)
58             output = str(self.new) + "_new.pdf"
59             with open(output, "wb") as output_pdf:
60                 file_write.write(output_pdf)
61                 print("第%s页完成"%page)
62             file_1.close()
63
64     def rmdir(self):
65         if os.path.isdir(self.new):
66             shutil.rmtree(self.new)
67
68 if __name__ == "__main__":
69     #通过第一个参数获取待处理的文件,第二个参数到以后为删除的页码
70     path = sys.argv[1]
71     number = sys.argv[2:]
72     mypdf = mypdf(path,number)
73     def f(path,number):
74         mypdf(path,number)
75     threading.Thread(target=f,args=[path,number])

View Code

方法二:在写入新文件时使用if判断进行筛选出不要的页面

想法一、将读取与写入同时处理。使用if判断筛选不要的页面

 1 def pdfsplt(self,path,number):
 2         print(number,type(number))
 3         if os.path.isfile(path):
 4             file_1 = open(path,"rb")
 5             file_reader = PyPDF2.PdfFileReader(file_1, strict=False)  #使用strict关闭错误提示
 6             file_write = PyPDF2.PdfFileWriter()
 7             #使用for循环读取每一页并将其写入新pdf文件,文件以页码命名
 8             for page in range(0,file_reader.getNumPages()):
 9                 if page not in number:
10                     pageobj = file_reader.getPage(page)
11                     file_write.addPage(pageobj)
12                     output = str(self.new) + "_new.pdf"
13                     with open(output,"wb") as output_pdf:
14                         file_write.write(output_pdf)
15             file_1.close()
16         else:
17             print("文件不存在!")
18             time.sleep(3)
19             exit()

View Code

想法二、将数据先全部放入内存,最后在写入,来提高速度:

 1 def pdfsplt(self,path,number):
 2         print(number,type(number))
 3         if os.path.isfile(path):
 4             file_1 = open(path,"rb")
 5             file_reader = PyPDF2.PdfFileReader(file_1, strict=False)  #使用strict关闭错误提示
 6             file_write = PyPDF2.PdfFileWriter()
 7             #使用for循环读取每一页并将其写入新pdf文件,文件以页码命名
 8             for page in range(0,file_reader.getNumPages()):
 9                 if page not in number:
10                     pageobj = file_reader.getPage(page)
11                     file_write.addPage(pageobj)
12             output = str(self.new) + "_new.pdf"
13             with open(output,"wb") as output_pdf: #将内容全部放入内存,最后写入,提高处理速度
14                 file_write.write(output_pdf)
15             file_1.close()
16         else:
17             print("文件不存在!")
18             time.sleep(3)
19             exit()

View Code

方法二的完整代码:

 1 import PyPDF2
 2 import os,time,shutil,sys
 3 import threading
 4
 5 class mypdf(object):
 6     def __init__(self,path,number):
 7         self.new = os.path.splitext(path)[0] #获取文件的路径
 8         self.pdfsplt(path,number)
 9         pass
10
11  #循环每一页读入内存,最后写入文件
12     def pdfsplt(self,path,number):
13         print(number,type(number))
14         if os.path.isfile(path):
15             file_1 = open(path,"rb")
16             file_reader = PyPDF2.PdfFileReader(file_1, strict=False)  #使用strict关闭错误提示
17             file_write = PyPDF2.PdfFileWriter()
18             #使用for循环读取每一页并将其写入新pdf文件,文件以页码命名
19             for page in range(0,file_reader.getNumPages()):
20                 if page not in number:
21                     pageobj = file_reader.getPage(page)
22                     file_write.addPage(pageobj)
23             output = str(self.new) + "_new.pdf"
24             with open(output,"wb") as output_pdf: #将内容全部放入内存,最后写入,提高处理速度
25                 file_write.write(output_pdf)
26             file_1.close()
27         else:
28             print("文件不存在!")
29             time.sleep(3)
30             exit()
31
32 if __name__ == "__main__":
33     #通过第一个参数获取待处理的文件,第二个参数到以后为删除的页码
34     path = sys.argv[1]
35     number = sys.argv[2:]
36     number = list(map(int, number))
37     mypdf = mypdf(path,number)
38     def f(path,number):
39         mypdf(path,number)
40     threading.Thread(target=f,args=[path,number])

View Code

两种方法的比较:

 

方法一

方法二中的第一种想法

方法二中的第二种想法

运行速度

较慢

代码量

65行

34行

34行

缺点:

方法一在处理扫描的pdf文件时,运行速度太慢,不能实现范围性的删除。

方法二不能实现范围性的删除

转载于:https://www.cnblogs.com/NINOMIYA1360/p/11013010.html

使用PyPDF2库对pdf文件进行指定页面删除操作相关推荐

  1. python读取pdf文档书签 bookmark_Python利用PyPDF2库获取PDF文件总页码实例

    Python中可以利用PyPDF2库来获取该pdf文件的总页码,可以根据下面的方法一步步进行下去: 1.首先,要安装PyPDF2库,利用以下命令即可: pip install PyPDF2 2.接着, ...

  2. python读取扫描形成的pdf_Python利用PyPDF2库获取PDF文件总页码实例

    Python中可以利用PyPDF2库来获取该pdf文件的总页码,可以根据下面的方法一步步进行下去: 1.首先,要安装PyPDF2库,利用以下命令即可: pip install PyPDF2 2.接着, ...

  3. Python利用PyPDF2库获取PDF文件总页码

    Python中可以利用PyPDF2库来获取该pdf文件的总页码,可以根据下面的方法一步步进行下去: 1.首先,要安装PyPDF2库,利用以下命令即可: pip install PyPDF2 2.接着, ...

  4. python常用库 自动化办公类 —— PyPDF2(处理pdf文件)

    python常用库 自动化办公类 -- PyPDF2(处理pdf文件) 摘要 PyPDF库的安装 PyPDF库的常用功能 文字提取 合并pdf文件 旋转pdf页面 pdf文件加密 摘要 本文主要介绍了 ...

  5. 使用iText库创建PDF文件

    前言 译文连接:http://howtodoinjava.com/apache-commons/create-pdf-files-in-java-itext-tutorial/ 对于excel文件的读 ...

  6. 利用python中pdfplumber库提取PDF文件中文字

    pdfplumber库中提供了一个extract_text()方法来帮助我们提取PDF文件中的文字.我们只需要使用pdfplumber中的open()方法打开我们希望提取文字的PDF文件,然后对所需提 ...

  7. PDF文件如何添加页面或插入其他PDF页面

    在处理PDF文件的时候如果要在文档中添加插入一个页面,或者是插入其他pdf文件页面的话该怎样操作?编辑PDF文件是否像office文档那样操作简单?下面就来讲下PDF文件怎么添加页面的. ​ 因为PD ...

  8. PDF文件如何旋转页面,来教你这两种方法

    PDF文件如何旋转页面呢?很多在用PDF文件的人都知道,PDF文件是一种不能直接编辑的文件,具有比较好的安全性,没有办法直接编辑,就不用说旋转页面了,想要给PDF文件旋转页面可以使用专业的PDF编辑软 ...

  9. PDF文件怎么旋转页面

    有的PDF文件打开后会有文档页面反过来的情况,那么怎么对PDF文档页面进行旋转?想要对PDF文档页面进行旋转,那么利用PDF编辑器http://bianji.xjpdf.com/进行旋转是一种不错的选 ...

最新文章

  1. sublime text 3 中改变.vue文件的颜色
  2. Java的call by value_call by value or reference ?
  3. 每日一博 - 延时任务的多种实现方式解读
  4. 并不对劲的bzoj2038:p1494:[国家集训队]小Z的袜子
  5. java 找出list中相同数据_Java获取List中相同的数据
  6. Java集合框架:ArrayList
  7. 你胆敢不加break试试?
  8. 11.Pipelines
  9. 汇编语言:实现大小写字母转换
  10. WPF中路由事件的传播
  11. Bootstrap3 滚动监听插件的方法
  12. ORACLE数据库常见问题诊断方法 ---(常见错误篇)
  13. InstallShield 12 制作安装包
  14. 服务器正在运行由于另一个程序,关于 服务器正在运行中,由于另一个程序正在运行中,此操作没法完成 问题的解决...
  15. 无锡python培训班,无锡Python+人工智能培训
  16. 企业网上下单订货管理软件源码搭建功能介绍|移讯云订货通订单管理系统
  17. tushare pro 版本获取股票历史数据
  18. 转载一篇ps更换背景色
  19. 海康威视py和c++调用全(超精髓,亲测)
  20. 韦东山ARM第一期总结

热门文章

  1. 腾讯内部转岗_腾讯微博即将关停,网友:竟然还活着?
  2. el-tooltip位置不灵活_要提高步伐移动的灵活性,注意这5点,加以改正,步伐不再沉重...
  3. PowerBI功能发布时间线
  4. 第3讲 | 浅说区块链共识机制
  5. 七牛云上传截图后的base64位遇到的问题总结
  6. Eclipse汉化插件
  7. 从输入URL到页面加载完成的过程中都发生了什么事情?
  8. asp.net mvc 依赖缓存启动项配置
  9. Python:使用threading模块实现多线程编程三[threading.Thread类的重要函数]
  10. 网络安装Citrix XenServer