#!/usr/bin/env python3
"""
Table with Images Example - HTML Output
This example demonstrates creating HTML tables with images:
- Creating HTML tables programmatically
- Embedding images in table cells
- Book catalog / product showcase tables
- Styled tables with CSS
- Mixed content (images and text) in cells
Generates standalone HTML files with embedded images (base64).
"""
import sys
from pathlib import Path
import base64
from typing import Dict, List, Tuple
# Add pyWebLayout to path
sys.path.insert(0, str(Path(__file__).parent.parent))
def image_to_base64(image_path: Path) -> str:
"""Convert image file to base64 string for HTML embedding."""
with open(image_path, 'rb') as img_file:
img_data = img_file.read()
return base64.b64encode(img_data).decode('utf-8')
def create_html_header(title: str) -> str:
"""Create HTML document header with CSS styles."""
return f"""
{title}
{title}
"""
def create_html_footer() -> str:
"""Create HTML document footer."""
return """
"""
def create_book_catalog_html(cover_images: Dict[str, str]) -> str:
"""Create HTML for book catalog table with cover images."""
books = [
("cover 1.png", "The Great Adventure", "John Smith", "$19.99"),
("cover 2.png", "Mystery of the Ages", "Jane Doe", "$24.99"),
("cover 3.png", "Science Today", "Dr. Brown", "$29.99"),
("cover 4.png", "Art & Design", "M. Artist", "$34.99"),
]
html = '\n'
html += '
Book Catalog
\n'
html += '
\n'
html += ' \n'
html += ' \n'
html += ' | Cover | \n'
html += ' Title | \n'
html += ' Author | \n'
html += ' Price | \n'
html += '
\n'
html += ' \n'
html += ' \n'
for cover_file, title, author, price in books:
html += ' \n'
# Cover cell
html += ' \n'
if cover_file in cover_images:
html += f' \n'
html += ' | \n'
# Title cell
html += f' {title} | \n'
# Author cell
html += f' {author} | \n'
# Price cell
html += f' {price} | \n'
html += '
\n'
html += ' \n'
html += '
\n'
html += '
\n'
return html
def create_product_showcase_html(cover_images: Dict[str, str]) -> str:
"""Create HTML for product showcase table."""
products = [
("cover 1.png", "Premium Edition - Hardcover with gold embossing"),
("cover 2.png", "Collector's Item - Limited print run"),
]
html = '\n'
html += '
Product Showcase
\n'
html += '
\n'
html += ' \n'
html += ' \n'
html += ' | Product | \n'
html += ' Description | \n'
html += '
\n'
html += ' \n'
html += ' \n'
for cover_file, description in products:
html += ' \n'
# Product cell with image
html += ' \n'
if cover_file in cover_images:
html += f' \n'
html += ' | \n'
# Description cell
html += f' {description} | \n'
html += '
\n'
html += ' \n'
html += '
\n'
html += '
\n'
return html
def main():
"""Generate HTML tables with images."""
print("Table with Images Example - HTML Version")
print("=" * 50)
# Load cover images and convert to base64
print("\n Loading and encoding cover images...")
cover_images = {}
data_path = Path(__file__).parent.parent / "tests" / "data"
for i in range(1, 5):
cover_path = data_path / f"cover {i}.png"
if cover_path.exists():
try:
cover_images[f"cover {i}.png"] = image_to_base64(cover_path)
print(f" ā Loaded and encoded cover {i}.png")
except Exception as e:
print(f" ā Failed to load cover {i}.png: {e}")
if not cover_images:
print(" ā No cover images found!")
return
# Generate HTML content
print("\n Generating HTML tables...")
html_content = create_html_header("Table with Images - HTML Example")
print(" - Creating book catalog table...")
html_content += create_book_catalog_html(cover_images)
print(" - Creating product showcase table...")
html_content += create_product_showcase_html(cover_images)
html_content += create_html_footer()
# Save HTML output
output_dir = Path("docs/html")
output_dir.mkdir(parents=True, exist_ok=True)
output_path = output_dir / "example_05_table_with_images.html"
with open(output_path, 'w', encoding='utf-8') as f:
f.write(html_content)
print(f"\nā Example completed!")
print(f" Output saved to: {output_path}")
print(f" Used {len(cover_images)} cover images (embedded as base64)")
print(f" Open the file in a web browser to view the tables")
return output_path
if __name__ == "__main__":
main()