python 打开pdf文件_Python3检验pdf文件是否有效
【基本原理】
利用PyPDF2的PdfFileReader模塊打開pdf文件,如果不拋異常,就認為此pdf文件有效。有時打開并不拋出異常,但是有這種警告:UserWarning: startxref on same line as offset [pdf.py:1680]。這種情況pdf多半也是壞的,可進一步通過頁數判斷。但walker在測試中發現,對于正常pdf文件,進一步通過頁數判斷時有時會拋出異常。
【情形一】
pdf文件在磁盤上。import traceback
from PyPDF2 import PdfFileReader
#參數為pdf文件全路徑名
def isValidPDF_pathfile(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
【情形二】
pdf是來自網絡的bytes數據。由于PdfFileReader的參數為文件名或文件對象,所以需要做一下轉換。
方法一:import traceback, tempfile
from PyPDF2 import PdfFileReader
#參數為bytes類型數據。利用臨時文件。
def isValidPDF_bytes(pdfBytes):
bValid = True
try:
fp = tempfile.TemporaryFile()
fp.write(pdfBytes)
reader = PdfFileReader(fp)
fp.close()
if reader.getNumPages() < 1: #進一步通過頁數判斷。
bValid = False
except:
bValid = False
print('*' + traceback.format_exc())
return bValid
方法二:import io, traceback
from PyPDF2 import PdfFileReader
#參數為bytes類型數據。利用BytesIO轉換。
def isValidPDF_bytes(pdfBytes):
bValid = True
try:
b = io.BytesIO(pdfBytes)
reader = PdfFileReader(b)
if reader.getNumPages() < 1: #進一步通過頁數判斷。
bValid = False
except:
bValid = False
print('*' + traceback.format_exc())
return bValid
還可以利用PDFlib判斷:import os
from PDFlib.PDFlib import PDFlib
from PDFlib.PDFlib import PDFlibException
def isValidPdf(pathfile):
p = PDFlib()
p.set_option("license=xxxxxx-xxxxxx-xxxxxx-xxxxxx-xxxxxx")
p.set_option("errorpolicy=return");
indoc = p.open_pdi_document(pathfile, 'repair=none');
print('indoc:' + str(indoc))
print('pathfile size:' + str(os.path.getsize(pathfile)) + 'B')
bValid = False
if (indoc == -1):
print('*' + p.get_errmsg())
bValid = False
else:
pageNumber = p.pcos_get_number(indoc, "length:pages")
print('pageNumber:' + str(pageNumber))
if pageNumber < 1: #頁數為0
bValid = False
else:
bValid = True
if bValid:
p.close_pdi_document(indoc)
return bValid
*** updated * 2018-12-12 ***# encoding: utf-8
# author: walker
# date: 2018-12-12
# summary: 直接用 PDF 文件內容判斷 PDF 的正確性和完整性,適用于判斷下載的 PDF
import re
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
【相關閱讀】
*** walker ***
總結
以上是生活随笔為你收集整理的python 打开pdf文件_Python3检验pdf文件是否有效的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 快速运行python虚拟环境_快速入门P
- 下一篇: python三维模型_python三维模