In [22]:
import pyPdf

In [2]:
mypdf = "../../data/ExampleTest.pdf"

In [8]:
input1 = pyPdf.PdfFileReader(file(mypdf, "rb"))
content = ""
for i in range(0, input1.getNumPages()):
    content += input1.getPage(i).extractText() + " \n"
    content = " ".join(content.replace(u"\xa0-2", u" ").strip().split())
print(content)


FERNANDEZ LOPEZ MCETXANIZ BENEITEZOIERMédico:25943278ENDOCRINOLOGIAServicio:Diagnóstico:HIPOGONADISMOPARAMETRORESULTADOApellidos: Nombre: ________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________Edad: Observ.:62110701Nº Petición:19/05/2014Nº S.S.:480094652053Fecha extracción-inicio ensayo:Destino:MENDARO CONSULTASCentro:MENDARO HOSPITALNº Lab_NºHª: Pº Dr. Begiristain, s/n.20014 Donostia-San Sebastián. Gipuzkoa.España. Tfno. 943007038. Fax.943007063VALOR DE REFERENCIA LABORATORIO HOSPITAL UNIVERSITARIO DONOSTIA UNIDADES DONOSTIA UNIBERTSITATE OSPITALEKO LABORATEGIA F.Nacimiento:15/09/1988HospitalOspitalea_____________________________Donostia1049470CIC:*62110701*HombreSexo:1494183TIS:BIOQUIMICA- GENERALBioquímica generalSrm-Pla-Creatinina1.15mg/dL[ .70 - 1.20 ]Filtrado glomerular estimado77mL/min/1.73 m²MDRD-4Por encima de 60 el cálculo de la estimación del filtrado no es válido para alertar de enfermedad renal crónica.Srm-Pla-Glucosa88mg/dL[ 70 - 110 ]Srm-Colesterol182mg/dL[ 120 - 220 ]Deseable: [ < 200 ]Enzimas sueroSrm-Pla-ALT(GPT)17U/L[ 0 - 41 ]BIOQUIMICA-HORMONAS-MARCADORESHormonasSrm-Folitropina (FSH) 1.4U/LHombres: Mujeres:F.folicular: F.ovulatoria: F.luteinica: Postmenopausia: Niños: [ 1.7 - 11 ][ 3.9 - 10 ][ 6.6 - 52 ][ 2.3 - 8 ][ 26.5 - 139 ][ 0 - 4 ]Srm-Lutropina (LH) 1.7U/LHombres: Mujeres:F.folicular: F.ovulatoria: F.luteinica: Postmenopausia: Niños: [ 0.5 - 6 ][ 1.7 - 7.2 ][ 13 - 52 ][ 0.6 - 10 ][ 20 - 65 ][ 0.3 - 1 ]Srm-Prolactina20.1ng/mL*[ 4 - 15.2 ]Srm-Testosterona total1.64ng/mL*Hombres: Mujeres: Niños: [ 2.4 - 10.7 ][ 0.06 - 0.86 ][ 0 - 0.3 ]Pág. 1 de 262110701Petición:ETXANIZ BENEITEZApellidos:____________________________________________________________________________________________________________________Nombre:OIERSrm-SHBG24.4nmol/L[ 11.4 - 52.3 ]36.3pg/mL[ 66 - 216 ]*Srm-Testosterona libre calculadaHEMATOLOGIA-MORFOLOGIAHemogramaSan-Hematíes5.490*10e6/uL[ 4.3 - 5.6 ]San-Hemoglobina15.4g/dL[ 13 - 17 ]San-Hematocrito45.6%[ 40 - 50 ]San-V.C.M.83.1fL[ 80 - 97 ]San-H.C.M.28.1pg[ 27 - 33 ]San-C.H.C.M.33.8g/dL[ 32 - 36 ]San-A.D.E.15.3%C.V.[ 11.5 - 15.6 ]San-Plaquetas312*10e3/µL[ 140 - 400 ]San-Leucocitos8.17*10e3/µL[ 3.8 - 10 ]FórmulaSan-Neutrófilos46.4%[ 40 - 75 ]San-Neutrófilos3.79*10e3/µL[ 1.6 - 7.5 ]San-Linfocitos37.9%[ 19 - 48 ]San-Linfocitos3.10*10e3/uL[ 0.9 - 3.5 ]San-Monocitos13.20%[ 3.5 - 12 ]*San-Monocitos1.08*10e3/µL[ 0.2 - 0.9 ]*San-Eosinófilos1.700%[ 0.5 - 7 ]San-Eosinófilos0.14*10e3/µL[ 0.02 - 0.6 ]San-Basófilos0.700%[ 0 - 1.5 ]San-Basófilos0.06*10e3/µL[ 0 - 0.2 ]San-Granulocitos inmad.0.10%[ 0 - 0.5 ]San-Granulocitos inmad.0.01*10e3/µL[ 0 - 0.03 ]San-Granulocitos inmad. : Valores normales en embarazadas: 0,1-2,1 % Granulocitos inmaduros incluye metamielocitos, mielocitos y promielocitos. Cifras > 2% indican desviación izquierda(infección, tto. con G-CSF, hemopatía...)-San-Eritroblastos 0.0%[ 0 - 0 ]San-Eritroblastos0.000*10e3/µL[ 0 - 0 ]Validadores finales:5/8/2014Fecha edición informe:Este informe no podrá reproducirse parcialmente sin aprobación escrita del LHUD. Se conserva registro informático del método seguido en cada parámetro.Jefe del Servicio de Bioquímica:Jefe de Servicio de Hematología:Jefe del Servicio de Microbiología:M. Araiz RamirezE. Pérez TralleroA. Garrido Chercoles________________________________________________________________________________________________________________________________________Pág. 2 de 2

In [10]:
import PyPDF2

In [19]:
pdf = PyPDF2.PdfFileReader(open(mypdf, "rb"))
#pdf.getPage(0)

In [1]:
from StringIO import StringIO

def getPDFContent(path):
    content = ""
    pdf = pyPdf.PdfFileReader(file(path,"rb"))
    for i in range(0, pdf.getNumPages()):
        content += pdf.getPage(i).extractText() + " \n"
        content = " ".join(content.replace(u"\xa0-2", u" ").strip().split())
    return(content)

pdfContent = StringIO(getPDFContent(mypdf))
for buf in pdfContent:
    print(buf)


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-f52bc49e706f> in <module>()
      9     return(content)
     10 
---> 11 pdfContent = StringIO(getPDFContent(mypdf))
     12 for buf in pdfContent:
     13     print(buf)

NameError: name 'mypdf' is not defined

In [27]:
from pdfminer.pdfdocument import PDFDocument, PDFNoOutlines
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LAParams, LTTextBox, LTTextLine, LTFigure, LTImage

In [15]:
f = open(mypdf, "rb")
parser = PDFParser(f)
document = PDFDocument(parser)
rsc = PDFResourceManager()
laparams = LAParams() 
device = PDFPageAggregator(rsc, laparams=laparams)
interpreter = PDFPageInterpreter(rsc, device)
for page in PDFPage.create_pages(document):
    interpreter.process_page(page)
    layout = device.get_result()
    print(layout.analyze)
print(layout)


<bound method LTPage.analyze of <LTPage(1) 0.000,0.000,561.100,817.800 rotate=0>>
<bound method LTPage.analyze of <LTPage(2) 0.000,0.000,561.100,817.800 rotate=0>>
<LTPage(2) 0.000,0.000,561.100,817.800 rotate=0>

In [39]:
def with_pdf (pdf_doc, pdf_pwd, fn, *args):
    """Open the pdf document, and apply the function, returning the results"""
    result = None
    try:
        fp = open(pdf_doc, 'rb')
        parser = PDFParser(fp)
        doc = PDFDocument(parser)
        parser.set_document(doc)
        doc.initialize(pdf_pwd)
        if doc.is_extractable:
            result = fn(doc, *args)
        fp.close()
    except IOError:
        pass
    return result

'''
def _parse_pages (doc):
    rsrcmgr = PDFResourceManager()
    laparams = LAParams()
    device = PDFPageAggregator(rsrcmgr, laparams=laparams)
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    for page in PDFPage.create_pages(doc):
        interpreter.process_page(page)
        layout = device.get_result()
        for level,title,dest,a,se in doc.get_outlines():
            print("{} {}".format(level, title))
            
'''

def _parse_toc(doc):
    toc = []
    try:
        outlines = doc.get_outlines()
        for(level, title, dest, a, se) in outlines:
            toc.append((level,title))
    except PDFNoOutlines:
        pass
    return toc


def get_pages (pdf_doc, pdf_pwd=''):
    """Process each of the pages in this pdf file"""
    with_pdf(pdf_doc, pdf_pwd, _parse_pages)

def get_toc (pdf_doc, pdf_pwd=''):
    """Return the table of contents (toc), if any, for this pdf file"""
    return with_pdf(pdf_doc, pdf_pwd, _parse_toc)

get_pages(mypdf)


---------------------------------------------------------------------------
PDFNoOutlines                             Traceback (most recent call last)
<ipython-input-39-4c88cdc1dfad> in <module>()
     37     return with_pdf(pdf_doc, pdf_pwd, _parse_toc)
     38 
---> 39 get_pages(mypdf)

<ipython-input-39-4c88cdc1dfad> in get_pages(pdf_doc, pdf_pwd)
     31 def get_pages (pdf_doc, pdf_pwd=''):
     32     """Process each of the pages in this pdf file"""
---> 33     with_pdf(pdf_doc, pdf_pwd, _parse_pages)
     34 
     35 def get_toc (pdf_doc, pdf_pwd=''):

<ipython-input-39-4c88cdc1dfad> in with_pdf(pdf_doc, pdf_pwd, fn, *args)
      8         parser.set_document(doc)
      9         if doc.is_extractable:
---> 10             result = fn(doc, *args)
     11         else:
     12             print("doc is not extractable")

<ipython-input-39-4c88cdc1dfad> in _parse_pages(doc)
     25         interpreter.process_page(page)
     26         layout = device.get_result()
---> 27         for level,title,dest,a,se in doc.get_outlines():
     28             print("{} {}".format(level, title))
     29 

/home/oier/.virtualenvs/analisis2/local/lib/python2.7/site-packages/pdfminer/pdfdocument.pyc in get_outlines(self)
    688     def get_outlines(self):
    689         if 'Outlines' not in self.catalog:
--> 690             raise PDFNoOutlines
    691 
    692         def search(entry, level):

PDFNoOutlines: 

In [17]:
import sys
import os
from binascii import b2a_hex
###
### pdf-miner requirements
###
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument, PDFNoOutlines
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LAParams, LTTextBox, LTTextLine, LTFigure, LTImage, LTChar

def with_pdf (pdf_doc, fn, pdf_pwd, *args):
    """Open the pdf document, and apply the function, returning the results"""
    result = None
    try:
        # open the pdf file
        fp = open(pdf_doc, 'rb')
        # create a parser object associated with the file object
        parser = PDFParser(fp)
        # create a PDFDocument object that stores the document structure
        doc = PDFDocument(parser, pdf_pwd)
        # connect the parser and document objects
        parser.set_document(doc)
        # supply the password for initialization
        #doc.initialize(pdf_pwd)
        if doc.is_extractable:
            # apply the function and return the result
            result = fn(doc, *args)
        # close the pdf file
        fp.close()
    except IOError:
        # the file doesn't exist or similar problem
        pass
    return result

###
### Table of Contents
###
def _parse_toc (doc):
    """With an open PDFDocument object, get the table of contents (toc) data
    [this is a higher-order function to be passed to with_pdf()]"""
    toc = []
    try:
        outlines = doc.get_outlines()
        for (level,title,dest,a,se) in outlines:
            toc.append( (level, title) )
    except PDFNoOutlines:
        print("NO OUTLINES")
    return toc

def get_toc (pdf_doc, pdf_pwd=''):
    """Return the table of contents (toc), if any, for this pdf file"""
    return with_pdf(pdf_doc, _parse_toc, pdf_pwd)
###
### Extracting Images
###
def write_file (folder, filename, filedata, flags='w'):
    """Write the file data to the folder and filename combination
    (flags: 'w' for write text, 'wb' for write binary, use 'a' instead of 'w' for append)"""
    result = False
    if os.path.isdir(folder):
        try:
            file_obj = open(os.path.join(folder, filename), flags)
            file_obj.write(filedata)
            file_obj.close()
            result = True
        except IOError:
            pass
    return result

def determine_image_type (stream_first_4_bytes):
    """Find out the image file type based on the magic number comparison of the first 4 (or 2) bytes"""
    file_type = None
    bytes_as_hex = b2a_hex(stream_first_4_bytes)
    if bytes_as_hex.startswith('ffd8'):
        file_type = '.jpeg'
    elif bytes_as_hex == '89504e47':
        file_type = '.png'
    elif bytes_as_hex == '47494638':
        file_type = '.gif'
    elif bytes_as_hex.startswith('424d'):
        file_type = '.bmp'
    return file_type

def save_image (lt_image, page_number, images_folder):
    """Try to save the image data from this LTImage object, and return the file name, if successful"""
    result = None
    if lt_image.stream:
        file_stream = lt_image.stream.get_rawdata()
    if file_stream:
        file_ext = determine_image_type(file_stream[0:4])
    if file_ext:
        file_name = ''.join([str(page_number), '_', lt_image.name, file_ext])
    if write_file(images_folder, file_name, file_stream, flags='wb'):
        result = file_name
    return result
###
### Extracting Text
###
def to_bytestring (s, enc='utf-8'):
    """Convert the given unicode string to a bytestring, using the standard encoding,
    unless it's already a bytestring"""
    if s:
        if isinstance(s, str):
            return s
        else:
            return s.encode(enc)
        
def update_page_text_hash (h, lt_obj, pct=0.2):
    """Use the bbox x0,x1 values within pct% to produce lists of associated text within the hash"""
    x0 = lt_obj.bbox[0]
    x1 = lt_obj.bbox[2]
    key_found = False
    for k, v in h.items():
        hash_x0 = k[0]
        if x0 >= (hash_x0 * (1.0-pct)) and (hash_x0 * (1.0+pct)) >= x0:
            hash_x1 = k[1]
            if x1 >= (hash_x1 * (1.0-pct)) and (hash_x1 * (1.0+pct)) >= x1:
# the text inside this LT* object was positioned at the same
# width as a prior series of text, so it belongs together
                key_found = True
                v.append(to_bytestring(lt_obj.get_text()))
                h[k] = v
    if not key_found:
# the text, based on width, is a new series,
# so it gets its own series (entry in the hash)
        h[(x0,x1)] = [to_bytestring(lt_obj.get_text())]
    return h

def parse_lt_objs (lt_objs, page_number, images_folder, text=[]):
    """Iterate through the list of LT* objects and capture the text or image data contained in each"""
    text_content = []
    page_text = {} # k=(x0, x1) of the bbox, v=list of text strings within that bbox width (physical column)
    for lt_obj in lt_objs:
        if isinstance(lt_obj, LTTextBox) or isinstance(lt_obj, LTTextLine):
            # text, so arrange is logically based on its column width
            page_text = update_page_text_hash(page_text, lt_obj)
        elif isinstance(lt_obj, LTImage):
            # an image, so save it to the designated folder, and note its place in the text
            saved_file = save_image(lt_obj, page_number, images_folder)
            if saved_file:
                # use html style <img /> tag to mark the position of the image within the text
                text_content.append('<img src="'+os.path.join(images_folder, saved_file)+'" />')
            else:
                print >> sys.stderr, "error saving image on page", page_number, lt_obj.__repr__
        elif isinstance(lt_obj, LTFigure):
            # LTFigure objects are containers for other LT* objects, so recurse through the children
            text_content.append(parse_lt_objs(lt_obj, page_number, images_folder, text_content))
    for k, v in sorted([(key,value) for (key,value) in page_text.items()]):
        # sort the page_text hash by the keys (x0,x1 values of the bbox),
        # which produces a top-down, left-to-right sequence of related columns
        text_content.append(''.join(v))
    return '\n'.join(text_content)
###
### Processing Pages
###
def _parse_pages (doc, images_folder):
    """With an open PDFDocument object, get the pages and parse each one
    [this is a higher-order function to be passed to with_pdf()]"""
    rsrcmgr = PDFResourceManager()
    laparams = LAParams()
    device = PDFPageAggregator(rsrcmgr, laparams=laparams)
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    text_content = []
    for i, page in enumerate(PDFPage.create_pages(doc)):
        interpreter.process_page(page)
        # receive the LTPage object for this page
        layout = device.get_result()
        # layout is an LTPage object which may contain child objects like LTTextBox, LTFigure, LTImage, etc.
        text_content.append(parse_lt_objs(layout, (i+1), images_folder))
    return text_content

def get_pages (pdf_doc, pdf_pwd='', images_folder='/tmp'):
    """Process each of the pages in this pdf file and return a list of strings representing the text found in each page"""
    return with_pdf(pdf_doc, _parse_pages, pdf_pwd, *tuple([images_folder]))

In [18]:
toc = get_toc(mypdf)
toc


NO OUTLINES
Out[18]:
[]

In [13]:
get_pages(mypdf)


---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-13-5b711c2f213e> in <module>()
----> 1 get_pages(mypdf)

<ipython-input-12-0cc7fe5f3615> in get_pages(pdf_doc, pdf_pwd, images_folder)
    175 def get_pages (pdf_doc, pdf_pwd='', images_folder='/tmp'):
    176     """Process each of the pages in this pdf file and return a list of strings representing the text found in each page"""
--> 177     return with_pdf(pdf_doc, _parse_pages, pdf_pwd, *tuple([images_folder]))

<ipython-input-12-0cc7fe5f3615> in with_pdf(pdf_doc, fn, pdf_pwd, *args)
     28         if doc.is_extractable:
     29             # apply the function and return the result
---> 30             result = fn(doc, *args)
     31         # close the pdf file
     32         fp.close()

<ipython-input-12-0cc7fe5f3615> in _parse_pages(doc, images_folder)
    170         layout = device.get_result()
    171         # layout is an LTPage object which may contain child objects like LTTextBox, LTFigure, LTImage, etc.
--> 172         text_content.append(parse_lt_objs(layout, (i+1), images_folder))
    173     return text_content
    174 

<ipython-input-12-0cc7fe5f3615> in parse_lt_objs(lt_objs, page_number, images_folder, text)
    153         # which produces a top-down, left-to-right sequence of related columns
    154         text_content.append(''.join(v))
--> 155     return '\n'.join(text_content)
    156 ###
    157 ### Processing Pages

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 5: ordinal not in range(128)