pdf是电子书,文档经常会用的格式,除了下载各种阅读器以外,我们也可以用Python批量处理大量PDF文件。本文用到了pypdf2,pdfminer.six,pdf2image来做常规处理。
5 from PyPDF2 import PdfFileReader
6
7 def extract_information(pdf_path,filename):
8 try:
9 with open(pdf_path, 'rb') as f:
10 pdf = PdfFileReader(f)
11 information = pdf.getDocumentInfo()
12 number_of_pages = pdf.getNumPages()
13
14 title=filename.split('.pdf')[0]
15 if information.title is not None and len(information.title)>0:
16 title=information.title
17 print(f"{title} page : {number_of_pages}")
18 except Exception as e:
19 pass
pdfminer.six 可以取出文本
8 from io import StringIO
9 from pdfminer.layout import LAParams
10 from pdfminer.high_level import extract_text_to_fp
16 def get_text(path):
17 output_string = StringIO()
18 with open(path, 'rb') as fin:
19 extract_text_to_fp(fin, output_string)
20 print(output_string.getvalue().strip())
pdf2image 可以提出所有页面存为图片,但因为IO的性能问题。作者提出最好用SSD硬盘和多线程。
6 from pdf2image import convert_from_path
12 def get_cover(path,filename):
13 images=convert_from_path(path)
14 images[0].save(filename+'.jpg')
上面的代码把封面(第一页)取了出来,保存为图片
我们可以用Python自带的文件处理功能,结合上面的三个函数,批量处理books目录下的大量pdf文件。
38 if __name__ == '__main__':
39 book_folder=os.path.join(Path.home(),'books')
40 for pdf in os.listdir(book_folder):
41 if pdf.endswith('.pdf'):
42 path=os.path.join(book_folder,pdf)
43 title,page=extract_information(path,pdf)
44 if page>0 and page<50:
45 get_text(path)
46 get_cover(path,pdf)