Implementing a class error and returning 0 text

Viewed 40

I hope this finds you well. I am struggling a bit and I have two questions. First, I am trying to implement a class and it returns a code similar to <main. object at 0x02C08790> when I am trying to implement the class. I have referenced other comments and do not quite understand. My second question is when I run the code below it states that there is no items in the pdf I saved earlier. I think I am passing the document incorrectly but I am unsure. I have tested each code separately and the both work independently but not together. Any help is greatly appreciated.

import os
from pdfminer3.layout import LAParams, LTTextBox
from pdfminer3.pdfpage import PDFPage
from pdfminer3.pdfinterp import PDFResourceManager
from pdfminer3.pdfinterp import PDFPageInterpreter
from pdfminer3.converter import PDFPageAggregator
from pdfminer3.converter import TextConverter
import io

import PyPDF2
from PyPDF2 import PdfFileMerger, PdfFileReader
import pandas as pd


class Transform:
    # method for extracting data and merging it into one pdf

    def __init__(self):
        try:
            source_dir = os.getcwd()
            merger = PdfFileMerger()
            for item in os.listdir(source_dir):
                if item.endswith("pdf"):
                    merger.append(item)
        except Exception:
            print("unable to collect")
        finally:
            merger.write("test.pdf")
            merger.close()

#running that method extract
    def extract(self):
        resource_manager = PDFResourceManager()
        fake_file_handle = io.StringIO()
        converter = TextConverter(resource_manager, fake_file_handle, laparams=LAParams())
        page_interpreter = PDFPageInterpreter(resource_manager, converter)

        with open('test.pdf', 'rb') as fh:
            for page in PDFPage.get_pages(fh,
                                          caching=True,
                                          check_extractable=True):
                page_interpreter.process_page(page)

            text = fake_file_handle.getvalue()

        # close open handles
        converter.close()
        fake_file_handle.close()

print(Transform)
1 Answers

I expect your code should merge all pdf in current dir into test.pdf plus print text of this merged pdf. It needs just two corrections, first replace

print(Transform)

with

print(Transform().extract())

Transform by itself is a class, you need to create (instantiate) object out of it, using Transform(). Then you may call some methods on it like .extract(), this runs method-function defined in that class. You may read about classes and objects here.

Second, add

return text

as last line in def extract(self) function body. This return is necessary so that extract returns text it has extracted from pdf, otherwise it does some work, but doesn't return any result in the original code.

You may Run full corrected code here.

Related