Skip to content

trading_agent.attachments.pdf_text_reader

Reads the text of a PDF, page by page, with pypdf.

A scanned PDF holds pictures of pages and no text, so it reads as empty; the store then tells the desk so, and the user can send the pages as pictures instead.

Typical usage example:

extracted = PdfTextReader().read(Path('annual_report.pdf'))

PdfTextReader

Bases: TextReader

Reads a PDF's text layer.

read

read(path)

Reads every page's text, each under a page heading.

Parameters:

Name Type Description Default
path Path

The PDF.

required

Returns:

Type Description
ExtractedText

The text and the number of pages.

Raises:

Type Description
TextReadError

The file is damaged, is not a PDF, or needs a password.

Source code in src/trading_agent/attachments/pdf_text_reader.py
def read(self, path: Path) -> text_reader.ExtractedText:
    """Reads every page's text, each under a page heading.

    Args:
        path (Path): The PDF.

    Returns:
        text_reader.ExtractedText: The text and the number of pages.

    Raises:
        TextReadError: The file is damaged, is not a PDF, or needs a password.
    """
    reader = self._open(path)
    pages = []
    try:
        for number, page in enumerate(reader.pages, start=1):
            page_text = page.extract_text() or ''
            pages.append(f'--- Page {number} ---\n{page_text.strip()}')
    except _PYPDF_ERRORS as error:
        raise text_reader.TextReadError(
            f'the PDF cannot be read ({type(error).__name__}: {error})'
        ) from error
    return text_reader.ExtractedText(
        text='\n\n'.join(pages),
        page_count=len(pages),
    )