import tempfile import time from selenium import webdriver from PIL import Image import os import subprocess import json import chromedriver_autoinstaller from selenium.webdriver.chrome.service import Service as ChromeService from selenium.webdriver.chrome.options import Options chrome_path = "/tmp/chrome-extract/opt/google/chrome/google-chrome" # Function to install and configure Chrome without sudo def setup_chrome(): chrome_url = "https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb" chrome_deb_path = "/tmp/google-chrome-stable_current_amd64.deb" subprocess.run(["wget", chrome_url, "-O", chrome_deb_path]) extract_dir = "/tmp/chrome-extract" os.makedirs(extract_dir, exist_ok=True) # Extract Chrome browser files subprocess.run(["ar", "x", chrome_deb_path], cwd=extract_dir) data_tar_path = os.path.join(extract_dir, "data.tar.xz") subprocess.run(["tar", "xf", data_tar_path], cwd=extract_dir) # Set Chrome browser path os.environ["CHROME_BINARY"] = chrome_path # Add Chrome path to system PATH os.environ["PATH"] = f"{os.path.dirname(chrome_path)}:{os.environ['PATH']}" # Install ChromeDriver chromedriver_autoinstaller.install() #return chrome_path # Function to convert HTML content to an image def html_to_image(html_content): # Save HTML content in a temporary file with tempfile.NamedTemporaryFile(delete=False, suffix='.html') as html_file: html_file.write(html_content.encode('utf-8')) html_file_path = html_file.name options = Options() options.binary_location = chrome_path options.add_argument("--headless") # For headless mode options.add_argument("--no-sandbox") options.add_argument("--disable-dev-shm-usage") # Start the Chrome browser driver = webdriver.Chrome(service=ChromeService(), options=options) # Load the HTML file driver.get(f'file://{html_file_path}') # Wait for the page to load time.sleep(2) # Get the page dimensions width = driver.execute_script("return document.body.scrollWidth") height = driver.execute_script("return document.body.scrollHeight") # Resize window to the page size driver.set_window_size(width, height) # Capture screenshot and save as a PNG file screenshot_path = tempfile.NamedTemporaryFile(delete=False, suffix='.png').name driver.save_screenshot(screenshot_path) # Close the browser driver.quit() return screenshot_path def render_abc(abc_string): abc_string = json.dumps(abc_string) print("in render_abc") html_template = f"""
""" screenshot_path = html_to_image(html_template) return screenshot_path #return html_template # Initialize the environment #chrome_path = setup_chrome() # Example of how to call the function html_content = """ ABCJS Example
""" #screenshot_path = html_to_image(html_content, chrome_path) #print(f"Screenshot saved at: {screenshot_path}")