Beginner10 min read

Extract text and page numbers from a PDF

Read a sample handbook page by page and identify which pages need optical character recognition.

Get the sample handbook

The fictional handbook has four pages. The first three contain embedded text. The last page is a scan. Save the PDF and script in a new working folder. Use a Python 3 virtual environment and install pypdf.

Download pdf_pages.py
View pdf_pages.py
import argparse
from io import BytesIO
from pathlib import Path

from pypdf import PdfReader
from pypdf.errors import PdfReadError


def extract_pages(data):
    reader = PdfReader(BytesIO(data))
    if reader.is_encrypted:
        raise ValueError("Use a PDF you can open without a password for this exercise.")
    return [(number, page.extract_text().strip())
            for number, page in enumerate(reader.pages, start=1)]


def main():
    parser = argparse.ArgumentParser(description="Inspect a PDF's embedded text by page.")
    parser.add_argument("pdf", type=Path)
    parser.add_argument("--page", type=int)
    args = parser.parse_args()

    try:
        pages = extract_pages(args.pdf.read_bytes())
        if args.page is not None:
            if not 1 <= args.page <= len(pages):
                raise ValueError(f"Choose a page from 1 to {len(pages)}.")
            number, text = pages[args.page - 1]
            print(f"Page {number}\n{text or '(no embedded text)'}")
        else:
            for number, text in pages:
                message = f"{len(text)} characters" if text else "no embedded text"
                print(f"Page {number}: {message}")
    except (OSError, ValueError, PdfReadError) as error:
        raise SystemExit(str(error)) from None


if __name__ == "__main__":
    main()
python -m pip install "pypdf==7.1.0"
python pdf_pages.py library-handbook.pdf
python pdf_pages.py library-handbook.pdf --page 2

Use the Python executable in your environment. On systems where python is unavailable, use python3 or your Windows environment’s python.exe.

Check the text layer

You’re ready when

The script lists pages 1 to 3 with character counts and page 4 with “no embedded text.” Page 2 contains equipment reference EQ-314. Open page 2 in a PDF reader and check the extracted text against the document.

The page number here is the page’s one-based position in the file. Some documents use printed page labels that begin at a different number. Include the file name and make it clear which numbering scheme your citations use.

Try the scanned page

Open page 4 and read the notice in the PDF viewer. It is visible because the page contains an image. Export that page as an image and follow the OCR lesson to recover the words. Save OCR output with the original page number if you later add it to an index.

Check the order and spacing in PDFs with tables or columns. Extraction can place lines in an order that differs from the page’s reading order.

Check your understanding

What should you record when an image-only page gives zero extracted characters?

Record the page as needing OCR or as skipped. Preserve its original position in either case.

Sources

Search the guide