pdftotext Python Library

repository·master·Indexed 21 days ago

https://github.com/jalan/pdftotext

A simple Python library for extracting text from PDF files by leveraging the Poppler C++ library. It provides the pdftotext.PDF class to load PDF files, handle password protection, and iterate over pages to extract text content.

Tokens
547
Snippets
3
Records
4
Agent score
27%

What's inside pdftotext

  1. Install OS dependencies

    master

    The library requires system-level dependencies (specifically Poppler and build tools) to compile. Install the appropriate package for your operating system:

    Debian, Ubuntu, and friends:

    sudo apt install build-essential libpoppler-cpp-dev pkg-config python3-dev

    Fedora, Red Hat, and friends:

    sudo yum install gcc-c++ pkgconfig poppler-cpp-devel python3-devel

    macOS:

    brew install pkg-config poppler python
  2. Iterate over PDF pages and extract text

    master

    The pdftotext.PDF object behaves like a collection of pages. You can determine the total page count using len(), iterate over pages in a loop, or access specific pages using integer indexing.

    import pdftotext
    
    with open("lorem_ipsum.pdf", "rb") as f:
        pdf = pdftotext.PDF(f)
    
    # Get total page count
    print(len(pdf))
    
    # Iterate over all pages
    for page in pdf:
        print(page)
    
    # Access individual pages by index
    print(pdf[0])
    print(pdf[1])
    
    # Extract all text into a single string
    full_text = "\n\n".join(pdf)
    print(full_text)
  3. Load a PDF with pdftotext.PDF()

    master

    To extract text from a PDF, open the file in binary mode (rb) and pass the file object to pdftotext.PDF(). If the PDF is password-protected, provide the password as the second argument to the constructor.

    import pdftotext
    
    # Load an unprotected PDF
    with open("lorem_ipsum.pdf", "rb") as f:
        pdf = pdftotext.PDF(f)
    
    # Load a password-protected PDF
    with open("secure.pdf", "rb") as f:
        pdf = pdftotext.PDF(f, "secret")