hdfg 发表于 2015-8-12 08:59:22

Python3检验pdf文件是否有效

【基本原理】

  利用PyPDF2的PdfFileReader模块打开pdf文件,如果不抛异常,就认为此pdf文件有效。
【情形一】
  pdf文件在磁盘上。   

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import traceback
from PyPDF2 import PdfFileReader   

#参数为pdf文件全路径名
def isValidPDF_pathfile(pathfile):
    bValid = True
    try:
      #PdfFileReader(open(pathfile, 'rb'))
      PdfFileReader(pathfile)
    except:
      bValid = False
      print('*' + traceback.format_exc())
         
    return bValid




【情形二】
  pdf是来自网络的bytes数据。由于PdfFileReader的参数为文件名或文件对象,所以需要做一下转换。
方法一:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import traceback, tempfile
from PyPDF2 import PdfFileReader   

#参数为bytes类型数据。利用临时文件。
def isValidPDF_bytes(pdfBytes):
    bValid = True
    try:
      fp = tempfile.TemporaryFile()
      fp.write(pdfBytes)
      PdfFileReader(fp)
      fp.close()
    except:
      bValid = False
      print('*' + traceback.format_exc())
         
    return bValid




方法二:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import io, traceback
from PyPDF2 import PdfFileReader   

#参数为bytes类型数据。利用BytesIO转换。
def isValidPDF_bytes(pdfBytes):
    bValid = True
    try:
      b = io.BytesIO(pdfBytes)
      PdfFileReader(b)
    except:
      bValid = False
      print('*' + traceback.format_exc())
         
    return bValid





参考文档:
1、The PdfFileReader Class
2、tempfile — Generate temporary files and directories
3、io — Core tools for working with streams

*** walker ***

页: [1]
查看完整版本: Python3检验pdf文件是否有效