TypeError: a bytes-like object is required, not 'str' --> Python Conversion from PDF to XML

Viewed 189

I have a code which should convert a PDF to XML . But When i ran the code , it is showing me error.

TypeError: a bytes-like object is required, not 'str'

but as am new , i don know what i should do , I tried some of the solution from Browser , but not worked.

Can anyone please help me

from io import BytesIO

import pdfminer.converter
from pdfminer.layout import LAParams
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage


def get_xml_py2(file_path):
    in_fp = BytesIO()
    lstRtn = []
    with open(file_path, 'rb') as x:
        in_fp.write(x.read())

    laparams = LAParams(all_texts=True)
    rsrcmgr = PDFResourceManager()

    for page in PDFPage.get_pages(in_fp):
        outfp = BytesIO()
        device = pdfminer.converter.XMLConverter(rsrcmgr, outfp, laparams=laparams)
        interpreter = PDFPageInterpreter(rsrcmgr, device)
        interpreter.process_page(page)
        lstRtn.append(outfp.getvalue())
        device.close()
        outfp.close()

        in_fp.close()

    return lstRtn

if __name__ == '__main__':
    text = get_xml_py2('Sample.pdf')
1 Answers

You're using BytesIO in a place that wants StringIO. So import StringIO and change outfp to outfp=StringIO()

Also remove device.close(), outfp.close(), in_fp.close() from the for loop.

Your resulting code will be

from io import BytesIO, StringIO
import pdfminer.converter
from pdfminer.layout import LAParams
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage

def get_xml_py2(file_path):
    in_fp = BytesIO()
    lstRtn = []
    with open(file_path, 'rb') as x:
        in_fp.write(x.read())

    laparams = LAParams(all_texts=True)
    rsrcmgr = PDFResourceManager()
    outfp = StringIO()
    device = pdfminer.converter.XMLConverter(rsrcmgr, outfp, laparams=laparams)
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    for page in PDFPage.get_pages(in_fp):
        interpreter.process_page(page)
        lstRtn.append(outfp.getvalue())
    device.close()
    outfp.close()
    in_fp.close()
    return lstRtn

I removed some assignment from the loop cause i don't think they should be in the it.

Related