# encoding: utf-8
# author:
# date:
# summary: 直接用 PDF 文件内容判断 PDF 的正确性和完整性,适用于判断下载的 PDF
#做成 exe:pyinstaller -F -c checkpdf.py
import re
import os
import sys
from PyPDF2 import PdfFileReader
#参数为pdf文件全路径名
def isValidPDF_pathfile2(pathfile):
bValid = True
try:
#PdfFileReader(open(pathfile, 'rb'))
reader = PdfFileReader(pathfile)
if reader.getNumPages() < 1: #进一步通过页数判断。
bValid = False
except:
bValid = False
#print('*' + traceback.format_exc())
return bValid
def isValidPDF_pathfile(pathfile):
r"""
直接用文件内容判断头尾,
参数为pdf文件全路径名
"""
content = ''
with open(pathfile, mode='rb') as f:
content = f.read()
partBegin = content[0:20]
if partBegin.find(rb'%PDF-1.') < 0:
print('Error: not find %PDF-1.')
return False
idx = content.rfind(rb'%%EOF')
if idx < 0:
print('Error: not find %%EOF')
return False
partEnd = content[(0 if idx-100 < 0 else idx-100) : idx + 5]
if not re.search(rb'startxref\s+\d+\s+%%EOF$', partEnd):
print('Error: not find startxref')
return False
return True
filter=[".pdf"] #设置过滤后的文件类型 当然可以设置多个类型
def all_path(dirname):
result = []#所有的文件
for maindir, subdir, file_name_list in os.walk(dirname):
# print("1:",maindir) #当前主目录
# print("2:",subdir) #当前主目录下的所有目录
# print("3:",file_name_list) #当前主目录下的所有文件
for filename in file_name_list:
apath = os.path.join(maindir, filename)#合并成一个完整路径
ext = os.path.splitext(apath)[1] # 获取文件后缀 [0]获取的是除了文件名以外的内容
if ext in filter:
result.append(apath)
return result
if __name__ == '__main__':
root_path = "./"
if len(sys.argv) >= 2:
root_path = sys.argv[1]
print(root_path)
dir_or_files = all_path(root_path)
with open(os.path.join(root_path,"result.txt"), "w") as fp:
for dir_file in dir_or_files:
#获取目录或者文件的路径
#dir_file_path = os.path.join(root_path,dir_file)
print(dir_file)
if isValidPDF_pathfile(dir_file):
if isValidPDF_pathfile2(dir_file):
print("OK")
#fp.write("OK \t"+dir_file+"\r\n")
else:
print("ERROR2")
fp.write("ERROR\t"+dir_file+"\r\n")
else:
print("ERROR")
fp.write("ERROR\t"+dir_file+"\r\n")
附 做成 exe:pyinstaller -F -c checkpdf.py
这是因为默认安装的Pyinstaller是3.31版本 不支持最新出的Python3.7 可以安装pyinstaller 3.4版本 支持Python3.7
pip install https://github.com/pyinstaller/pyinstaller/archive/develop.tar.gz
命令 | 介绍 |
---|---|
-F,-onefile | 产生单个的可执行文件 |
-D,--onedir | 产生一个目录(包含多个文件)作为可执行程序 |
-a,--ascii | 不包含 Unicode 字符集支持 |
-d,--debug | 产生 debug 版本的可执行文件 |
-w,--windowed,--noconsolc | 指定程序运行时不显示命令行窗口(仅对 Windows 有效) |
-c,--nowindowed,--console | 指定使用命令行窗口运行程序(仅对 Windows 有效) |
-o DIR,--out=DIR | 指定 spec 文件的生成目录。如果没有指定,则默认使用当前目录来生成 spec 文件 |
-p DIR,--path=DIR | 设置 Python 导入模块的路径(和设置 PYTHONPATH 环境变量的作用相似)。也可使用路径分隔符(Windows 使用分号,Linux 使用冒号)来分隔多个路径 |
-n NAME,--name=NAME | 指定项目(产生的 spec)名字。如果省略该选项,那么第一个脚本的主文件名将作为 spec 的名字 |
检测pdf是否有效参考的:https://blog.51cto.com/walkerqt/1683680
pyinstaller参考:
https://note.youdao.com/ynoteshare1/index.html?id=2d95b5572ce8953ae0acce9496b355ca&type=note