import os
import subprocess

def compress_pdf(input_path):
    try:
        temp_output_path = input_path.replace(".pdf", "_temp.pdf")
        subprocess.run([
            'C:\\Program Files\\gs\\gs10.03.1\\bin\\gswin64c.exe',  # Usar la ruta completa de Ghostscript
            '-sDEVICE=pdfwrite',
            '-dCompatibilityLevel=1.4',
            '-dPDFSETTINGS=/screen',  # Puedes ajustar esto a /ebook o /printer
            '-dNOPAUSE',
            '-dQUIET',
            '-dBATCH',
            '-dDownsampleColorImages=true',
            '-dColorImageResolution=72',  # Ajusta esta resolución según sea necesario
            f'-sOutputFile={temp_output_path}',
            input_path
        ], check=True)
        os.replace(temp_output_path, input_path)
    except subprocess.CalledProcessError as e:
        print(f"Error compressing {input_path}: {e}")

def compress_pdfs_in_directory(directory):
    for filename in os.listdir(directory):
        if filename.endswith(".pdf"):
            input_path = os.path.join(directory, filename)
            compress_pdf(input_path)
            print(f"Compressed {filename} and replaced original file")

if __name__ == "__main__":
    # Obtener el directorio donde está guardado el script
    script_directory = os.path.dirname(os.path.abspath(__file__))
    compress_pdfs_in_directory(script_directory)

    # Pausar la consola para ver los mensajes
    input("Presiona Enter para salir...")
