Created
May 1, 2022 18:22
-
-
Save yashrathi-git/6509aca46bedb1ea8879c9e50f97e389 to your computer and use it in GitHub Desktop.
Inverts pdf colors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pdf2image | |
from PIL import ImageOps | |
import img2pdf | |
import os | |
import sys | |
from pathlib import Path | |
from random import randint | |
def invert_color(filepath): | |
print("Converting to images...") | |
images = pdf2image.convert_from_path(filepath) | |
idx_counter = [] | |
temp_dir_path = Path(f"temp_{randint(1000000, 9999999)}") | |
temp_dir_path.mkdir(exist_ok=True) | |
try: | |
print("Inverting colors...") | |
for idx, i in enumerate(images): | |
temp_fp = str(temp_dir_path / f"temp_{idx}.jpeg") | |
idx_counter.append(temp_fp) | |
i = ImageOps.invert(i) | |
i.save(temp_fp) | |
print("Saving output to output.pdf...") | |
with open("output.pdf", "wb") as f: | |
f.write(img2pdf.convert(idx_counter)) | |
finally: | |
print("Deleting temp directory...") | |
for fp in idx_counter: | |
os.remove(fp) | |
temp_dir_path.rmdir() | |
print("Done!") | |
# | |
if __name__ == "__main__": | |
args = sys.argv | |
fp = args[-1] | |
if not fp.endswith("pdf"): | |
print("USAGE: python3 script.py <filepath>") | |
exit(1) | |
invert_color(filepath=fp) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment