当前位置:   article > 正文

用Python处理PDF

out_pdf.addpage(

本文转载自蛰虫始航 ,详情可以扫描下方二维码: 

640?wx_fmt=png

PDF作为可移植文档格式(Portable Document Format),在日常生活中经常接触到,最近处理一些数据更是频繁接触一些需要批量处理pdf文件的需求,因此便想整理一下自己实践的用Python处理PDF格式数据的笔记。本文会保持更新。PDF处理的高频需求有:读取、写入、格式转换(pdf提取文本写入txt、根据url写入pdf等) 、批处理(多个pdf合并为1个、切分pdf)等等。查了下相关资料,Python操作PDF的库有(只是应用的话肯定不至于造轮子从二进制数据开始读):pdfminer、pdfminer3k、PyPDF、PyPDF2、pdf2htmlex、pdf2image、pdf2xlsx等。

640?wx_fmt=png
可用的pdf库

用pdf2合并和切分PDF

比较几个库之后打算先从PyPDF2快速实现一些功能。其官方文档为PyPDF2 Documentation[1],根据文档,PDF2库包含了 PdfFileReader PdfFileMerger PageObject PdfFileWriter 四个常用的主要的调用类,意思也很明确。先用pip install PyPDF2安装库。

批量合并pdf
  1. import os
  2. from PyPDF2 import PdfFileReader, PdfFileWriter #导入需要的类(库)
  3. wp='D:/doc_of_pdf/' #work_path
  4. #合并同一个文件夹下的pdf文件
  5. flst=[] #获得pdf文件路径
  6. for root, dirs, files in os.walk(wp):
  7. flst=files
  8. flst=[wp+f for f in flst]
  9. out_pdf=PdfFileWriter()
  10. for pf in flst:
  11. in_pdf=PdfFileReader(open(pf, 'rb')) #二进制打开
  12. page_count=in_pdf.getNumPages() #输入pdf的页数
  13. for pc in range(page_count):
  14. out_pdf.addPage(in_pdf.getPage(pc)) #逐页循环
  15. with open(wp+'合并笔记_1-3章.pdf','wb') as wf:
  16. out_pdf.write(wf)
  17. #out_pdf.getNumPages()

640?wx_fmt=png
执行前后对比

切分pdf为多个pdf
  1. #将一个pdf文件根据一定规则切分为多个
  2. sc_pdf=PdfFileReader(open(flst[0], 'rb')) #对第一章笔记进行处理
  3. count_sc=sc_pdf.getNumPages()
  4. #每7页切分为1PDF文件
  5. out_pdf=PdfFileWriter() #用以输出pdf
  6. for c in range(count_sc):
  7. if c%7==0 and c>0:
  8. with open(wp+'切分_{0}.pdf'.format(c),'wb') as wf:
  9. out_pdf.write(wf)
  10. out_pdf=PdfFileWriter() #重建一个空对象
  11. else:
  12. out_pdf.addPage(sc_pdf.getPage(c))

640?wx_fmt=png
切分测试结果截图

通过上面的实践,可以看到实现这几个需求高频使用到的方法就是新建一个Reader或Writer对象,通过.getNumPages()获取一共的页码,通过.getPage(page)获取特定页,.addPage()写入页码。

图片转PDF

  1. #单张图片转pdf
  2. from PIL import Image
  3. from PyPDF2 import PdfFileReader, PdfFileWriter
  4. img = Image.open('D:/docOfStu/pypdf2-mindmap-01.JPG')
  5. img.save('D:/docOfStu/pypdf2-mindmap-01.pdf', 'PDF') #通过PIL库保存为pdf格式
  6. #多张图片转pdf
  7. ilst=['D:/docOfStu/pypdf2-mindmap-01.jpg','D:/docOfStu/pypdf2-mindmap-02.jpg'] #图片列表
  8. # for root, dirs, files in os.walk(wpt): ilst=files #也可以通过os.walk(wpt) 读取文件夹wpt下所有图片
  9. out_pdf=PdfFileWriter()
  10. for f in ilst:
  11. img = Image.open(f)
  12. fw=f.replace('.jpg','.pdf')
  13. img.save(fw)
  14. out_pdf.appendPagesFromReader(PdfFileReader(open(fw,'rb'))) #也可拆这句为 sc_pdf=PdfFileReader(open(fw,'rb')); out_pdf.addPage(sc_pdf.getPage(0))
  15. out_pdf.write(open('D:/docOfStu/pypdf2-mindmap-04.pdf','wb'))

640?wx_fmt=png
图片转pdf对比效果

页面处理

过滤pdf中的的特定页面,只保留特定页面;另一方面,给pdf文件添加特定页面;

 
 

代码同步更新于:https://github.com/QLWeilcf/ Stack_lcf/blob/master/pdfProccWithpy.ipynb

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/51701
推荐阅读
相关标签
  

闽ICP备14008679号