File size: 1,274 Bytes
afa96cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

import fitz  # fitz is the internal name for PyMuPDF


def load_pdf(file_path):
    """
    Opens a PDF and extracts text from every page.

    Input  : file_path → path to the PDF file on disk
    Output : list of dicts, one per page, like:
             [
               {"page_num": 1, "text": "Introduction to AI..."},
               {"page_num": 2, "text": "Chapter 1 begins here..."},
             ]
    """

    doc = fitz.open(file_path)  # open the PDF file
    pages = []                  # empty list to collect results

    for page_num in range(len(doc)):    # loop through every page
        page = doc[page_num]            # get the current page object
        text = page.get_text()          # extract all text from this page
        text = text.strip()             # remove extra spaces at start and end

        # only keep the page if it actually has text
        # some PDF pages are just images or blank — we skip those
        if text:
            pages.append({
                "page_num": page_num + 1,  # page numbers start from 1, not 0
                "text": text               # the actual text content
            })

    doc.close()  # always close the file when done
    print(f"Loaded {len(pages)} pages from the PDF.")
    return pages