from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from PIL import Image
import time

# Function to read HTML file and replace placeholders
def generate_html_content(template_path, name, title, phone):
    with open(template_path, 'r') as file:
        html_content = file.read()
        html_content = html_content.replace('{{ name }}', name)
        html_content = html_content.replace('{{ title }}', title)
        html_content = html_content.replace('{{ phone }}', phone)
        return html_content

# Signature data
signatures = [
    { 'name': 'John Doe', 'title': 'Software Engineer', 'phone': '(123) 456-7890' },
    # Add more signatures as needed
]

template_path = 'signature_template.html'

# Set up Selenium with headless Chromium
chromium_options = Options()
chromium_options.add_argument("--headless")
chromium_options.add_argument("--disable-gpu")
chromium_options.add_argument("--window-size=420,600")  # Adjust the height as needed

# Use the ChromeDriverManager to install and manage the ChromiumDriver
chromium_service = Service(ChromeDriverManager(chrome_type="chromium").install())

# Initialize the WebDriver with Chromium
driver = webdriver.Chrome(service=chromium_service, options=chromium_options)

# Generate images for each signature
for signature in signatures:
    html_content = generate_html_content(template_path, signature['name'], signature['title'], signature['phone'])
    temp_html_path = f"{signature['name'].replace(' ', '_')}_temp.html"

    with open(temp_html_path, 'w') as temp_file:
        temp_file.write(html_content)

    driver.get(f"file://{temp_html_path}")

    time.sleep(2)  # Wait for the page to load completely

    screenshot_path = f"{signature['name'].replace(' ', '_')}_signature.png"
    driver.save_screenshot(screenshot_path)

    # Optionally, crop the image to remove any unnecessary white space
    image = Image.open(screenshot_path)
    cropped_image = image.crop(image.getbbox())
    cropped_image.save(screenshot_path)

    print(f"Generated image for {signature['name']}")

driver.quit()
