检测文件夹中多个PDF的内容类型

时间:2018-09-11 23:06:25

标签: python pdf automation pypdf2

到目前为止,我正在anaconda平台中使用PyPDF2在20000+ pdfs中放置水印。该代码适用于大多数PDF文件,但是其中一些文件的内容是报告中扫描效果不佳的图像。

我想知道python中是否有工具或其他可以分析PDF内容并确定PDF是图像还是带有文本字符的pdf文件的工具。这将使我知道哪些文件存在此缺陷,并将它们放置在其他文件夹中。

谢谢

我添加了我的代码。

import PyPDF2 #this library requires to be installed
import os


if __name__ == "__main__":


    ROOT_PATH = "."
    #STAMP_PATH = "." + "/stamped/"
    TEMPLATE_PATH = "."
    
    STAMP_PATH = "."
        
    
    count = 0
    
    for dirName, subdirList, fileList in os.walk(ROOT_PATH):
        
        files=[]

        print('Found directory: %s' % dirName)
        for fileName in fileList:

            if fileName.find('.pdf') > 0:
                count += 1

                print('\tHandling %s - %s  %s' % (count, dirName, fileName))

                files.append(fileName)


#=======================main code part ==========================================                
                file= open(fileName,'rb')
                reader = PyPDF2.PdfFileReader(file)
                page= reader.getPage(0)
                
                
                water = open(TEMPLATE_PATH + 'StampTemplate1109.pdf','rb')
                reader2 = PyPDF2.PdfFileReader(water)
                waterpage = reader2.getPage(0)
                
                #command to merge parent PDF first page with PDF watermark page
                page.mergeTranslatedPage(waterpage, 0, -20, expand=True)
                
                
                writer =PyPDF2.PdfFileWriter()
                writer.addPage(page)
                
                #add rest of PDF pages
                for pageNum in range(1, reader.numPages): # this will give length of book
                 pageObj = reader.getPage(pageNum)
                 writer.addPage(pageObj)
                 
                #return the parent PDF file with the watermark 
                # here we are writing so 'wb' is for write binary
                resultFile = open(STAMP_PATH + 'Reviewed ' + fileName,'wb')
                
                writer.write(resultFile)
                file.close()
                resultFile.close()
#==============================================================================                

    print "TOTAL OF %s PROCESSED" % count 

1 个答案:

答案 0 :(得分:0)

由于您已经在使用PyPDF2,因此您可能想使用PageObject.extractText函数来查看在PDF的每一页上是否有文本。如果您从页面中得到一个空字符串,则可能是图像。