Create pdfquery
Browse filesa tool to search through documents saved as pdf
- tools/pdfquery +37 -0
tools/pdfquery
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" first install pypdf using pip install pypdf"""
|
| 2 |
+
import pypdf
|
| 3 |
+
|
| 4 |
+
def search_word_in_pdf(pdf_path, search_word):
|
| 5 |
+
"""
|
| 6 |
+
Searches for a specific word in a PDF file and prints the pages where it's found.
|
| 7 |
+
"""
|
| 8 |
+
# Open the PDF file
|
| 9 |
+
with open(pdf_path, 'rb') as file:
|
| 10 |
+
# Create a PDF reader object
|
| 11 |
+
reader = pypdf.PdfReader(file)
|
| 12 |
+
|
| 13 |
+
# Track if the word was found at all
|
| 14 |
+
found_matches = False
|
| 15 |
+
|
| 16 |
+
print(f"Searching for '{search_word}' in '{pdf_path}'...\n")
|
| 17 |
+
|
| 18 |
+
# Loop through each page (0-indexed, so we add 1 for actual page number)
|
| 19 |
+
for page_num, page in enumerate(reader.pages, start=1):
|
| 20 |
+
# Extract text from the page
|
| 21 |
+
text = page.extract_text()
|
| 22 |
+
|
| 23 |
+
# Perform case-insensitive search
|
| 24 |
+
if text and search_word.lower() in text.lower():
|
| 25 |
+
print(f"✅ Found on Page {page_num}")
|
| 26 |
+
found_matches = True
|
| 27 |
+
|
| 28 |
+
if not found_matches:
|
| 29 |
+
print("❌ Word not found in the document.")
|
| 30 |
+
|
| 31 |
+
# Example Usage
|
| 32 |
+
if __name__ == "__main__":
|
| 33 |
+
# Replace with your actual PDF file path and target word
|
| 34 |
+
pdf_file = "sample.pdf"
|
| 35 |
+
word_to_find = "invoice"
|
| 36 |
+
|
| 37 |
+
search_word_in_pdf(pdf_file, word_to_find)
|