PDF作为可移植文档格式(Portable Document Format),在日常生活中经常接触到,最近处理一些数据更是频繁接触一些需要批量处理pdf文件的需求,因此便想整理一下自己实践的用Python处理PDF格式数据的笔记。本文会保持更新。
PDF处理的高频需求有:读取、写入、格式转换(pdf提取文本写入txt、根据url写入pdf等)
、批处理(多个pdf合并为1个、切分pdf)等等。
查了下相关资料,Python操作PDF的库有(只是应用的话肯定不至于造轮子从二进制数据开始读):pdfminer、pdfminer3k、PyPDF、PyPDF2、pdf2htmlex、pdf2image、pdf2xlsx等。
### 用pdf2合并和切分PDF
比较几个库之后打算先从PyPDF2快速实现一些功能。其官方文档为[PyPDF2 Documentation](https://pythonhosted.org/PyPDF2/),根据文档,PDF2库包含了 PdfFileReader PdfFileMerger PageObject PdfFileWriter 四个常用的主要的调用类,意思也很明确。
先用`pip install PyPDF2`安装库。
#### 批量合并pdf
```python
import os
from PyPDF2 import PdfFileReader, PdfFileWriter #导入需要的类(库)
wp='D:/doc_of_pdf/' #work_path
#合并同一个文件夹下的pdf文件
flst=[] #获得pdf文件路径
for root, dirs, files in os.walk(wp):
flst=files
flst=[wp+f for f in flst]
out_pdf=PdfFileWriter()
for pf in flst:
in_pdf=PdfFileReader(open(pf, 'rb')) #二进制打开
page_count=in_pdf.getNumPages() #输入pdf的页数
for pc in range(page_count):
out_pdf.addPage(in_pdf.getPage(pc)) #逐页循环
with open(wp+'合并笔记_1-3章.pdf','wb') as wf:
out_pdf.write(wf)
#out_pdf.getNumPages()
```
#### 切分pdf为多个pdf
```python
#将一个pdf文件根据一定规则切分为多个
sc_pdf=PdfFileReader(open(flst[0], 'rb')) #对第一章笔记进行处理
count_sc=sc_pdf.getNumPages()
#每7页切分为1个PDF文件
out_pdf=PdfFileWriter() #用以输出pdf
for c in range(count_sc):
if c%7==0 and c>0:
with open(wp+'切分_{0}.pdf'.format(c),'wb') as wf:
out_pdf.write(wf)
out_pdf=PdfFileWriter() #重建一个空对象
else:
out_pdf.addPage(sc_pdf.getPage(c))
```
通过上面的实践,可以看到实现这几个需求高频使用到的方法就是新建一个Reader或Writer对象,通过`.getNumPages()`获取一共的页码,通过`.getPage(page)`获取特定页,`.addPage()`写入页码。
to be continue…
ps:文章同步于jianshu
## 参考资料