-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinvert.py
More file actions
50 lines (41 loc) · 1.6 KB
/
invert.py
File metadata and controls
50 lines (41 loc) · 1.6 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
from pdf2image import convert_from_path
from PIL import ImageOps
import img2pdf
import os
import sys
import tempfile
def invert_color(filepath, output_path):
try:
# Create temporary directory
with tempfile.TemporaryDirectory() as temp_dir:
images = convert_from_path(filepath)
temp_files = []
for idx, img in enumerate(images):
inverted_img = ImageOps.invert(img.convert('RGB'))
temp_path = os.path.join(temp_dir, f"page_{idx}.jpeg")
inverted_img.save(temp_path, "JPEG")
temp_files.append(temp_path)
with open(output_path, "wb") as f:
f.write(img2pdf.convert(temp_files))
except Exception as e:
print(f"Error processing {filepath}: {str(e)}")
raise
def dir(in_dir):
if not os.path.isdir(in_dir):
print("Invalid directory")
return
for filename in os.listdir(in_dir):
if filename.lower().endswith(".pdf"):
input_path = os.path.join(in_dir, filename)
output_name = f"{os.path.splitext(filename)[0]}-inv.pdf"
output_path = os.path.join(in_dir, output_name)
# Skip if output already exists
if os.path.exists(output_path):
print(f"Skipping {filename} - output exists")
continue
invert_color(input_path, output_path)
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python invert.py /path/to/directory")
else:
dir(sys.argv[1])