HTMLviewer2_API / app.py
tomo2chin2's picture
Update app.py
630fc7d verified
raw
history blame
2.12 kB
import gradio as gr
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from PIL import Image
from io import BytesIO
import tempfile
import time
import os
def render_fullpage_screenshot_with_margin(html_code):
# 1) HTMLコードを一時ファイルに保存
tmp_file = tempfile.NamedTemporaryFile(suffix=".html", delete=False)
tmp_path = tmp_file.name
tmp_file.write(html_code.encode('utf-8'))
tmp_file.close()
# 2) ヘッドレスChrome(Chromium)起動オプション
options = Options()
options.add_argument("--headless")
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--force-device-scale-factor=1")
try:
driver = webdriver.Chrome(options=options)
# 3) まずはある程度のウィンドウサイズでページを開く
driver.set_window_size(1200, 800)
driver.get("file://" + tmp_path)
# 4) ページのロード完了を待機
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.TAG_NAME, "body"))
)
time.sleep(2) # フォントや外部リソース読み込み安定化
# 5) スクロールバーを非表示にし、背景を白に統一(必要に応じて変更)
driver.execute_script("""
document.documentElement.style.overflow = 'hidden';
document.body.style.overflow = 'hidden';
document.documentElement.style.backgroundColor = 'white';
document.body.style.backgroundColor = 'white';
""")
# 6) ページ全体の幅・高さを取得(bodyとdocumentElement両方を比較)
scroll_width = driver.execute_script(
"return Math.max(document.body.scrollWidth, document.documentElement.scrollWidth)"
)
scroll_height = driver.execute_script(
"return Math.max(document.body