45 lines
1.4 KiB
Python
45 lines
1.4 KiB
Python
from pdf2image import convert_from_path
|
|
from PIL import Image
|
|
import os,time
|
|
|
|
|
|
def compress_pdf_images(input_pdf, output_pdf, quality=50):
|
|
# Convert PDF pages to images
|
|
images = convert_from_path(input_pdf)
|
|
|
|
# Compress images
|
|
compressed_images = []
|
|
for image in images:
|
|
image = image.convert("RGB")
|
|
image.save("temp.jpg", "JPEG", quality=quality)
|
|
compressed_images.append(Image.open("temp.jpg"))
|
|
image.close()
|
|
Image.close()
|
|
|
|
for attempt in range(5):
|
|
retry_delay=3
|
|
try:
|
|
# Your code that might fail
|
|
os.remove("temp.jpg")
|
|
print("Success:", result)
|
|
break # Exit the loop if successful
|
|
except Exception as e:
|
|
print(f"Attempt {attempt + 1} failed:", e)
|
|
if attempt < 5 - 1:
|
|
print(f"Retrying in {retry_delay} seconds...")
|
|
time.sleep(retry_delay)
|
|
else:
|
|
print("Max retries reached. Exiting.")
|
|
|
|
|
|
# Save compressed images as a new PDF
|
|
compressed_images[0].save(output_pdf, save_all=True, append_images=compressed_images[1:])
|
|
|
|
|
|
|
|
|
|
# Usage
|
|
inputpdf=r"u:\Dropbox\!!!Days\Downloads Z230\Dokumentace\a.pdf"
|
|
outputpdf=r"u:\Dropbox\!!!Days\Downloads Z230\Dokumentace\aconverted.pdf"
|
|
# Usage
|
|
compress_pdf_images(inputpdf, outputpdf, quality=50) |