Repository navigation
Expand file tree
/
Copy pathpdftextfinder.py
More file actions
130 lines (103 loc) · 4.51 KB
/
Copy pathpdftextfinder.py
File metadata and controls
130 lines (103 loc) · 4.51 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# -*- coding: utf-8 -*-
"""PDFTextFinder
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1IInjyMsV0CHzHBlPWw7q2kdrW_TjiHrX
"""
!pip install pymupdf -q
import fitz
from google.colab import files
import os
import io
def highlight_text_in_pdf_colab(pdf_content, original_filename, search_text):
if not search_text:
print("Search text cannot be empty.")
return None, None, 0
try:
doc = fitz.open(stream=pdf_content, filetype="pdf")
except Exception as e:
print(f"Error opening PDF from content: {e}")
return None, None, 0
total_found = 0
found_on_pages = []
print(f"\nSearching for '{search_text}' (case-insensitive) in '{original_filename}'...")
search_flags = 8
for page_num in range(len(doc)):
page = doc.load_page(page_num)
text_instances = page.search_for(search_text, flags=search_flags)
if text_instances:
num_on_page = len(text_instances)
total_found += num_on_page
found_on_pages.append(page_num + 1)
print(f" Found {num_on_page} instance(s) on page {page_num + 1}")
for inst in text_instances:
highlight = page.add_highlight_annot(inst)
highlight.update()
if total_found > 0:
base, ext = os.path.splitext(original_filename)
output_filename = f"{base}_highlighted{ext}"
try:
output_pdf_bytes = doc.tobytes(garbage=4, deflate=True)
print(f"\nSuccessfully highlighted {total_found} instance(s).")
print(f"Output will be named: {output_filename}")
if found_on_pages:
print(f"Text found on pages: {', '.join(map(str, found_on_pages))}")
doc.close()
return output_filename, output_pdf_bytes, total_found
except Exception as e:
print(f"Error preparing highlighted PDF for download: {e}")
doc.close()
return None, None, total_found
else:
print(f"\nNo instances of '{search_text}' found in the PDF.")
doc.close()
return None, None, 0
def upload_pdf_colab():
"""Uploads a PDF file in Google Colab and returns its name and content."""
print("Please upload your PDF file:")
uploaded = files.upload()
if not uploaded:
print("No file uploaded.")
return None, None
filename = list(uploaded.keys())[0]
content = uploaded[filename]
if not filename.lower().endswith(".pdf"):
print(f"'{filename}' does not appear to be a PDF file. Please upload a .pdf file.")
files.uploaded.clear()
return None, None
print(f"Uploaded '{filename}' ({len(content)} bytes)")
return filename, content
def main_colab():
print("PDF Text Highlighter")
print("----------------------------------------")
original_filename, pdf_content = upload_pdf_colab()
if not original_filename or not pdf_content:
print("PDF upload failed or was cancelled. Exiting.")
return
search_query = input("Enter the string to find and highlight (case-insensitive): ")
if not search_query.strip():
print("Search string cannot be empty. Exiting.")
return
output_filename, output_pdf_bytes, count = highlight_text_in_pdf_colab(
pdf_content, original_filename, search_query
)
if output_filename and output_pdf_bytes and count > 0:
print(f"\nOffering '{output_filename}' for download...")
try:
with open(output_filename, "wb") as f:
f.write(output_pdf_bytes)
files.download(output_filename)
print(f"If download doesn't start automatically, check your browser's download permissions for this site.")
except Exception as e:
print(f"Could not initiate download: {e}")
print("The highlighted PDF was processed but could not be offered for download automatically.")
print(f"You might find the file '{output_filename}' in the Colab file browser (left panel).")
elif count == 0:
print("No changes made as no text was found.")
else:
print("An error occurred during highlighting or saving the PDF, or no text was found to highlight.")
if __name__ == "__main__" and 'google.colab' in str(get_ipython()):
main_colab()
elif __name__ == "__main__":
print("This script is intended to be run in a Google Colab environment for file upload/download features.")
print("If running locally, please use a version with local file dialogs.")