@@ -0,0 +1,318 @@
|
||||
#!/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"""<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{title}</title>
|
||||
<style>
|
||||
body {{
|
||||
font-family: 'DejaVu Sans', Arial, sans-serif;
|
||||
background-color: #f0f0f0;
|
||||
padding: 20px;
|
||||
margin: 0;
|
||||
}}
|
||||
|
||||
.container {{
|
||||
max-width: 1400px;
|
||||
margin: 0 auto;
|
||||
background-color: white;
|
||||
padding: 30px;
|
||||
border: 2px solid #b4b4b4;
|
||||
border-radius: 5px;
|
||||
}}
|
||||
|
||||
h1 {{
|
||||
color: #323296;
|
||||
font-size: 24px;
|
||||
margin-bottom: 30px;
|
||||
text-align: center;
|
||||
}}
|
||||
|
||||
.table-container {{
|
||||
margin-bottom: 40px;
|
||||
}}
|
||||
|
||||
.table-title {{
|
||||
font-size: 18px;
|
||||
font-weight: bold;
|
||||
margin-bottom: 15px;
|
||||
color: #333;
|
||||
}}
|
||||
|
||||
/* Blue style table */
|
||||
table.style-blue {{
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
border: 1px solid #646464;
|
||||
margin-bottom: 20px;
|
||||
}}
|
||||
|
||||
table.style-blue th {{
|
||||
background-color: #4682b4;
|
||||
color: white;
|
||||
padding: 10px;
|
||||
text-align: left;
|
||||
font-size: 12px;
|
||||
border: 1px solid #646464;
|
||||
}}
|
||||
|
||||
table.style-blue td {{
|
||||
padding: 10px;
|
||||
border: 1px solid #646464;
|
||||
font-size: 11px;
|
||||
}}
|
||||
|
||||
table.style-blue tr:nth-child(even) {{
|
||||
background-color: #f5f8fa;
|
||||
}}
|
||||
|
||||
table.style-blue tr:nth-child(odd) {{
|
||||
background-color: white;
|
||||
}}
|
||||
|
||||
/* Green style table */
|
||||
table.style-green {{
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
border: 2px solid #3c783c;
|
||||
margin-bottom: 20px;
|
||||
}}
|
||||
|
||||
table.style-green th {{
|
||||
background-color: #90ee90;
|
||||
color: #333;
|
||||
padding: 12px;
|
||||
text-align: left;
|
||||
font-size: 12px;
|
||||
border: 2px solid #3c783c;
|
||||
}}
|
||||
|
||||
table.style-green td {{
|
||||
padding: 12px;
|
||||
border: 2px solid #3c783c;
|
||||
font-size: 10px;
|
||||
}}
|
||||
|
||||
table.style-green tr:nth-child(even) {{
|
||||
background-color: #f0fff0;
|
||||
}}
|
||||
|
||||
table.style-green tr:nth-child(odd) {{
|
||||
background-color: white;
|
||||
}}
|
||||
|
||||
.cover-image {{
|
||||
max-width: 100px;
|
||||
height: auto;
|
||||
display: block;
|
||||
}}
|
||||
|
||||
.product-image {{
|
||||
max-width: 120px;
|
||||
height: auto;
|
||||
display: block;
|
||||
}}
|
||||
|
||||
.price {{
|
||||
font-weight: bold;
|
||||
}}
|
||||
|
||||
.footer {{
|
||||
margin-top: 40px;
|
||||
text-align: center;
|
||||
color: #666;
|
||||
font-size: 12px;
|
||||
}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h1>{title}</h1>
|
||||
"""
|
||||
|
||||
|
||||
def create_html_footer() -> str:
|
||||
"""Create HTML document footer."""
|
||||
return """
|
||||
<div class="footer">
|
||||
Generated by pyWebLayout - Table with Images Example (HTML Version)
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
|
||||
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 = '<div class="table-container">\n'
|
||||
html += ' <div class="table-title">Book Catalog</div>\n'
|
||||
html += ' <table class="style-blue">\n'
|
||||
html += ' <thead>\n'
|
||||
html += ' <tr>\n'
|
||||
html += ' <th>Cover</th>\n'
|
||||
html += ' <th>Title</th>\n'
|
||||
html += ' <th>Author</th>\n'
|
||||
html += ' <th>Price</th>\n'
|
||||
html += ' </tr>\n'
|
||||
html += ' </thead>\n'
|
||||
html += ' <tbody>\n'
|
||||
|
||||
for cover_file, title, author, price in books:
|
||||
html += ' <tr>\n'
|
||||
|
||||
# Cover cell
|
||||
html += ' <td>\n'
|
||||
if cover_file in cover_images:
|
||||
html += f' <img src="data:image/png;base64,{cover_images[cover_file]}" alt="{title}" class="cover-image">\n'
|
||||
html += ' </td>\n'
|
||||
|
||||
# Title cell
|
||||
html += f' <td>{title}</td>\n'
|
||||
|
||||
# Author cell
|
||||
html += f' <td>{author}</td>\n'
|
||||
|
||||
# Price cell
|
||||
html += f' <td class="price">{price}</td>\n'
|
||||
|
||||
html += ' </tr>\n'
|
||||
|
||||
html += ' </tbody>\n'
|
||||
html += ' </table>\n'
|
||||
html += '</div>\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 = '<div class="table-container">\n'
|
||||
html += ' <div class="table-title">Product Showcase</div>\n'
|
||||
html += ' <table class="style-green">\n'
|
||||
html += ' <thead>\n'
|
||||
html += ' <tr>\n'
|
||||
html += ' <th>Product</th>\n'
|
||||
html += ' <th>Description</th>\n'
|
||||
html += ' </tr>\n'
|
||||
html += ' </thead>\n'
|
||||
html += ' <tbody>\n'
|
||||
|
||||
for cover_file, description in products:
|
||||
html += ' <tr>\n'
|
||||
|
||||
# Product cell with image
|
||||
html += ' <td>\n'
|
||||
if cover_file in cover_images:
|
||||
html += f' <img src="data:image/png;base64,{cover_images[cover_file]}" alt="Product cover" class="product-image">\n'
|
||||
html += ' </td>\n'
|
||||
|
||||
# Description cell
|
||||
html += f' <td>{description}</td>\n'
|
||||
|
||||
html += ' </tr>\n'
|
||||
|
||||
html += ' </tbody>\n'
|
||||
html += ' </table>\n'
|
||||
html += '</div>\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()
|
||||
@@ -0,0 +1,273 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
HTML Table with Images Example - End-to-End Rendering
|
||||
|
||||
This example demonstrates the complete pipeline:
|
||||
1. HTML table source with <img> tags in cells
|
||||
2. parse_html_string() converts HTML → Abstract document structure
|
||||
3. DocumentLayouter handles all layout and rendering
|
||||
|
||||
No custom rendering code needed - DocumentLayouter handles everything!
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from PIL import Image
|
||||
|
||||
# Add pyWebLayout to path
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent))
|
||||
|
||||
from pyWebLayout.io.readers.html_extraction import parse_html_string
|
||||
from pyWebLayout.concrete.page import Page
|
||||
from pyWebLayout.style.page_style import PageStyle
|
||||
from pyWebLayout.layout.document_layouter import DocumentLayouter
|
||||
from pyWebLayout.concrete.table import TableStyle
|
||||
from pyWebLayout.style import Font
|
||||
|
||||
|
||||
def create_book_catalog_html():
|
||||
"""Create HTML for a book catalog table with actual <img> tags."""
|
||||
# Get base path for images - use absolute paths for the img src
|
||||
data_path = Path(__file__).parent.parent / "tests" / "data"
|
||||
|
||||
html = f"""
|
||||
<html>
|
||||
<body>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Cover</th>
|
||||
<th>Title</th>
|
||||
<th>Author</th>
|
||||
<th>Price</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><img src="{data_path / 'cover 1.png'}" alt="The Great Adventure" /></td>
|
||||
<td>The Great Adventure</td>
|
||||
<td>John Smith</td>
|
||||
<td><b>$19.99</b></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><img src="{data_path / 'cover 2.png'}" alt="Mystery of the Ages" /></td>
|
||||
<td>Mystery of the Ages</td>
|
||||
<td>Jane Doe</td>
|
||||
<td><b>$24.99</b></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><img src="{data_path / 'cover 3.png'}" alt="Science Today" /></td>
|
||||
<td>Science Today</td>
|
||||
<td>Dr. Brown</td>
|
||||
<td><b>$29.99</b></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><img src="{data_path / 'cover 4.png'}" alt="Art & Design" /></td>
|
||||
<td>Art & Design</td>
|
||||
<td>M. Artist</td>
|
||||
<td><b>$34.99</b></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
return html
|
||||
|
||||
|
||||
def create_product_showcase_html():
|
||||
"""Create HTML for a product showcase table with images."""
|
||||
data_path = Path(__file__).parent.parent / "tests" / "data"
|
||||
|
||||
html = f"""
|
||||
<html>
|
||||
<body>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Product</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><img src="{data_path / 'cover 1.png'}" alt="Premium Edition" /></td>
|
||||
<td>Premium Edition - Hardcover with gold embossing</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><img src="{data_path / 'cover 2.png'}" alt="Collector's Item" /></td>
|
||||
<td>Collector's Item - Limited print run</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
return html
|
||||
|
||||
|
||||
def render_html_with_layouter(html_string: str, title: str,
|
||||
table_style: TableStyle,
|
||||
page_size=(600, 500)):
|
||||
"""
|
||||
Render HTML using DocumentLayouter - the proper way!
|
||||
|
||||
This function demonstrates the correct usage:
|
||||
1. Parse HTML → Abstract blocks
|
||||
2. Create Page
|
||||
3. Create DocumentLayouter
|
||||
4. Layout all blocks using layouter
|
||||
|
||||
Args:
|
||||
html_string: HTML source containing table with <img> tags
|
||||
title: Title for the output (for logging)
|
||||
table_style: Table styling configuration
|
||||
page_size: Page dimensions
|
||||
|
||||
Returns:
|
||||
PIL Image with rendered content
|
||||
"""
|
||||
print(f"\n Processing '{title}'...")
|
||||
|
||||
# Step 1: Parse HTML to abstract blocks
|
||||
print(" 1. Parsing HTML → Abstract blocks...")
|
||||
base_font = Font(font_size=11)
|
||||
blocks = parse_html_string(html_string, base_font=base_font)
|
||||
print(f" → Parsed {len(blocks)} blocks")
|
||||
|
||||
# Step 2: Create page
|
||||
print(" 2. Creating page...")
|
||||
page_style = PageStyle(
|
||||
border_width=2,
|
||||
border_color=(180, 180, 180),
|
||||
padding=(20, 20, 20, 20),
|
||||
background_color=(255, 255, 255)
|
||||
)
|
||||
page = Page(size=page_size, style=page_style)
|
||||
|
||||
# Step 3: Create DocumentLayouter
|
||||
print(" 3. Creating DocumentLayouter...")
|
||||
layouter = DocumentLayouter(page)
|
||||
|
||||
# Step 4: Layout all blocks using the layouter
|
||||
print(" 4. Laying out all blocks...")
|
||||
for block in blocks:
|
||||
# For tables, we can pass a custom style
|
||||
from pyWebLayout.abstract.block import Table
|
||||
if isinstance(block, Table):
|
||||
success = layouter.layout_table(block, style=table_style)
|
||||
else:
|
||||
# For other blocks (paragraphs, headings, images), use layout_document
|
||||
success = layouter.layout_document([block])
|
||||
|
||||
if not success:
|
||||
print(f" ⚠ Warning: Block {type(block).__name__} didn't fit on page")
|
||||
|
||||
print(f" ✓ Layout complete!")
|
||||
|
||||
# Step 5: Get the rendered canvas
|
||||
# Note: Tables render directly onto page._canvas
|
||||
# We access page.draw to ensure canvas is initialized
|
||||
print(" 5. Getting rendered canvas...")
|
||||
_ = page.draw # Ensure canvas exists
|
||||
return page._canvas
|
||||
|
||||
|
||||
def main():
|
||||
"""Demonstrate end-to-end HTML table with images rendering using DocumentLayouter."""
|
||||
print("HTML Table with Images Example - DocumentLayouter")
|
||||
print("=" * 60)
|
||||
print("\nThis example demonstrates:")
|
||||
print(" 1. HTML with <img> tags inside <td> cells")
|
||||
print(" 2. parse_html_string() automatically handles images")
|
||||
print(" 3. DocumentLayouter handles all layout and rendering")
|
||||
print(" 4. NO manual TableRenderer or custom rendering code!")
|
||||
|
||||
# Verify images exist
|
||||
print("\n Checking for cover images...")
|
||||
data_path = Path(__file__).parent.parent / "tests" / "data"
|
||||
cover_count = 0
|
||||
for i in range(1, 5):
|
||||
cover_path = data_path / f"cover {i}.png"
|
||||
if cover_path.exists():
|
||||
cover_count += 1
|
||||
print(f" ✓ Found cover {i}.png")
|
||||
|
||||
if cover_count == 0:
|
||||
print(" ✗ No cover images found! This example requires cover images.")
|
||||
return
|
||||
|
||||
# Create HTML sources with <img> tags
|
||||
print("\n Creating HTML sources with <img> tags...")
|
||||
print(" - Book catalog HTML")
|
||||
book_html = create_book_catalog_html()
|
||||
|
||||
print(" - Product showcase HTML")
|
||||
product_html = create_product_showcase_html()
|
||||
|
||||
# Define table styles
|
||||
book_style = TableStyle(
|
||||
border_width=1,
|
||||
border_color=(100, 100, 100),
|
||||
cell_padding=(8, 10, 8, 10),
|
||||
header_bg_color=(70, 130, 180),
|
||||
cell_bg_color=(255, 255, 255),
|
||||
alternate_row_color=(245, 248, 250)
|
||||
)
|
||||
|
||||
product_style = TableStyle(
|
||||
border_width=2,
|
||||
border_color=(60, 120, 60),
|
||||
cell_padding=(10, 12, 10, 12),
|
||||
header_bg_color=(144, 238, 144),
|
||||
cell_bg_color=(255, 255, 255),
|
||||
alternate_row_color=(240, 255, 240)
|
||||
)
|
||||
|
||||
# Render using DocumentLayouter - the proper way!
|
||||
print("\n Rendering with DocumentLayouter (HTML → Abstract → Layout → PNG)...")
|
||||
|
||||
book_image = render_html_with_layouter(
|
||||
book_html,
|
||||
"Book Catalog",
|
||||
book_style,
|
||||
page_size=(700, 600)
|
||||
)
|
||||
|
||||
product_image = render_html_with_layouter(
|
||||
product_html,
|
||||
"Product Showcase",
|
||||
product_style,
|
||||
page_size=(600, 350)
|
||||
)
|
||||
|
||||
# Combine images side by side
|
||||
print("\n Combining output images...")
|
||||
padding = 20
|
||||
total_width = book_image.size[0] + product_image.size[0] + padding * 3
|
||||
total_height = max(book_image.size[1], product_image.size[1]) + padding * 2
|
||||
|
||||
combined = Image.new('RGB', (total_width, total_height), (240, 240, 240))
|
||||
combined.paste(book_image, (padding, padding))
|
||||
combined.paste(product_image, (book_image.size[0] + padding * 2, padding))
|
||||
|
||||
# Save output
|
||||
output_dir = Path("docs/images")
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
output_path = output_dir / "example_06_html_table_with_images.png"
|
||||
combined.save(output_path)
|
||||
|
||||
print(f"\n✓ Example completed!")
|
||||
print(f" Output saved to: {output_path}")
|
||||
print(f" Image size: {combined.size[0]}x{combined.size[1]} pixels")
|
||||
print(f"\nThe complete pipeline:")
|
||||
print(f" 1. HTML with <img> tags → parse_html_string() → Abstract blocks")
|
||||
print(f" 2. Abstract blocks → DocumentLayouter → Concrete objects")
|
||||
print(f" 3. Page.render() → PNG output")
|
||||
print(f"\n ✓ Using DocumentLayouter - NO custom rendering code!")
|
||||
|
||||
return combined
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user