我使用pdfminer使用python从pdf文件中提取数据。我想提取pdf中存在的所有数据,无论它是图像,文本还是其他任何内容。我们可以在一行(或两个,如果需要,没有太多工作)这样做。任何帮助表示赞赏。提前致谢
答案 0 :(得分:7)
不,你不能。 Pdfminer很强大,但它的水平相当低。我们可以在一行(或两个,如果需要,没有太多工作)这样做。
不幸的是,文档并不完全详尽。由于Denis Papathanasiou的一些代码,我能够找到自己的方式。代码在his blog中讨论,您可以在此处找到来源:layout_scanner.py
另见this answer,我在其中提供了更多细节。
答案 1 :(得分:2)
对于Python 3:
pip install pdfminer.six
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from io import StringIO
def convert_pdf_to_txt(path, codec='utf-8'):
rsrcmgr = PDFResourceManager()
retstr = StringIO()
laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
fp = open(path, 'rb')
interpreter = PDFPageInterpreter(rsrcmgr, device)
password = ""
maxpages = 0
caching = True
pagenos=set()
for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):
interpreter.process_page(page)
text = retstr.getvalue()
fp.close()
device.close()
retstr.close()
return text
答案 2 :(得分:0)
对于python3,还有另外一个:pip install pdfminer3k
from pdfminer.pdfinterp import PDFResourceManager, process_pdf
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from io import StringIO
import time
from functools import wraps
def fn_timer(function)://this is for calculating the run time(function)
@wraps(function)
def function_timer(*args, **kwargs):
t0 = time.time()
result = function(*args, **kwargs)
t1 = time.time()
print ("Total time running %s: %s seconds" %
('test', str(t1-t0))
)
return result
return function_timer
@fn_timer
def convert_pdf(path, pages):
rsrcmgr = PDFResourceManager()
retstr = StringIO()
laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, laparams=laparams)
fp = open(path, 'rb')
process_pdf(rsrcmgr, device, fp,pages)
fp.close()
device.close()
str = retstr.getvalue()
retstr.close()
return str
file = r'M:\a.pdf'
print(convert_pdf(file,[1,]))