使用pdfminer水平读取pdf文件

时间:2014-10-29 14:44:27

标签: python pdf extract pdfminer

我想用pdfminer(版本20140328)提取pdf。

这是提取pdf的代码:

import sys
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.converter import XMLConverter, HTMLConverter, TextConverter
from pdfminer.layout import LAParams
from cStringIO import StringIO
import urllib2

def pdf_to_string(data):
    fp = StringIO(data)
    rsrcmgr = PDFResourceManager()
    retstr = StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
    # Create a PDF interpreter object.
    interpreter = PDFPageInterpreter(rsrcmgr, device)

    # Process each page contained in the document.
    for page in PDFPage.get_pages(fp):
        interpreter.process_page(page)
        data =  retstr.getvalue()

    return data

pdf_url="http://www.consilium.europa.eu/uedocs/cms_data/docs/pressdata/en/ecofin/140836.pdf"
file_object = urllib2.urlopen(urllib2.Request(pdf_url)).read()
string=pdf_to_string(file_object)

这是pdf的截图: enter image description here

问题是pdfminer没有水平读取(人然后位置)但是在列中(所有人都是他们各自的位置):

Belgium: 
Mr Koen GEENS 

Bulgaria: 
Mr Petar CHOBANOV 

Czech Republic: 
Mr Radek URBAN 


Minister for Finance, with responsibility for the Civil 
Service 

Minister for Finance 

Deputy Minister for Finance 

如何让pdfminer水平阅读文字?

1 个答案:

答案 0 :(得分:0)

我找到了一个使用 pdftotext 的工作解决方案:

import tempfile, subprocess

def pdf_to_string(file_object):
    pdfData = file_object.read()
    tf = tempfile.NamedTemporaryFile()
    tf.write(pdfData)
    tf.seek(0)
    outputTf = tempfile.NamedTemporaryFile()

    if (len(pdfData) > 0) :
        out, err = subprocess.Popen(["pdftotext", "-layout", tf.name, outputTf.name ]).communicate()
        return outputTf.read()
    else :
        return None

pdf_file="files/2014_1.pdf"
file_object = file(pdf_file, 'rb')
print pdf_to_string(file_object)

这会产生正确的输出,人名然后位置:)。

<强>解决!