function add_table_to_pdf_v1
Adds a formatted table to a PDF document story with proper text wrapping, styling, and header formatting using ReportLab's platypus components.
/tf/active/vicechatdev/vice_ai/new_app.py
4174 - 4226
moderate
Purpose
This function is designed to convert structured table data into a ReportLab Table object and add it to a PDF document story. It handles text wrapping for cell content, applies distinct styling for header and regular rows, and ensures proper formatting with grey headers and white text. The function is typically used as part of a larger PDF generation workflow where tables need to be embedded in documents.
Source Code
def add_table_to_pdf(story, table_data):
"""Add a table to PDF document with proper formatting and text wrapping"""
if not table_data:
logger.info("No table data provided for PDF")
return
from reportlab.platypus import Paragraph, Table, TableStyle
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib import colors
logger.info(f"Processing PDF table with {len(table_data)} rows")
# Get styles for table cells
table_styles = getSampleStyleSheet()
cell_style = ParagraphStyle(
'TableCell',
parent=table_styles['Normal'],
fontSize=9,
wordWrap='CJK'
)
header_style = ParagraphStyle(
'TableHeader',
parent=table_styles['Normal'],
fontSize=9,
textColor=colors.black,
wordWrap='CJK',
fontName='Helvetica-Bold'
)
# Convert table data to reportlab format
pdf_table_data = []
for row_data in table_data:
row_cells = []
style = header_style if row_data['type'] == 'header' else cell_style
for cell_content in row_data['cells']:
# Wrap cell content in Paragraph for text wrapping
cell_para = Paragraph(str(cell_content), style)
row_cells.append(cell_para)
pdf_table_data.append(row_cells)
if pdf_table_data:
# Create table
table = Table(pdf_table_data)
# Apply table styling
table.setStyle(TableStyle([
('BACKGROUND', (0, 0), (-1, 0), colors.grey),
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
('ALIGN', (0, 0), (-1, -1), 'LEFT'),
]))
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
story |
- | - | positional_or_keyword |
table_data |
- | - | positional_or_keyword |
Parameter Details
story: A ReportLab story list (typically from SimpleDocTemplate) that accumulates PDF elements. The function appends the formatted table to this list. Expected to be a list-like object that accepts platypus flowables.
table_data: A list of dictionaries where each dictionary represents a table row. Each row dictionary must contain: 'type' (string: 'header' or regular row indicator) and 'cells' (list of cell content values). If empty or None, the function returns early without adding anything to the story.
Return Value
Returns None. The function modifies the 'story' parameter in-place by appending the formatted table. If table_data is empty or None, it returns early without modification.
Dependencies
reportlablogging
Required Imports
from reportlab.platypus import Paragraph, Table, TableStyle
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib import colors
import logging
Conditional/Optional Imports
These imports are only needed under specific conditions:
from reportlab.platypus import Paragraph, Table, TableStyle
Condition: imported inside the function only when table_data is provided
Required (conditional)from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
Condition: imported inside the function only when table_data is provided
Required (conditional)from reportlab.lib import colors
Condition: imported inside the function only when table_data is provided
Required (conditional)Usage Example
from reportlab.platypus import SimpleDocTemplate
from io import BytesIO
import logging
# Setup logger
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
# Create PDF document
buffer = BytesIO()
doc = SimpleDocTemplate(buffer)
story = []
# Prepare table data
table_data = [
{'type': 'header', 'cells': ['Name', 'Age', 'City']},
{'type': 'row', 'cells': ['John Doe', '30', 'New York']},
{'type': 'row', 'cells': ['Jane Smith', '25', 'Los Angeles']}
]
# Add table to PDF
add_table_to_pdf(story, table_data)
# Build PDF
doc.build(story)
pdf_bytes = buffer.getvalue()
Best Practices
- Ensure table_data is properly structured with 'type' and 'cells' keys in each row dictionary
- The function uses lazy imports for ReportLab components, which are only loaded when table_data is provided
- Cell content is automatically converted to strings, so any data type can be passed in the cells list
- The function modifies the story list in-place, so ensure you pass a mutable list object
- Header rows should have type='header' to receive bold formatting and grey background
- The function logs the number of rows being processed, useful for debugging large tables
- Text wrapping is enabled with 'CJK' mode, which supports Chinese, Japanese, and Korean characters
- Font size is set to 9pt for both headers and cells to ensure readability in PDF format
- The table is not explicitly appended to the story in the provided code - ensure the calling code handles this or the function should be modified to include story.append(table)
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function add_table_to_pdf 92.8% similar
-
function add_formatted_content_to_pdf_v1 75.9% similar
-
function add_formatted_content_to_pdf 75.4% similar
-
function add_table_to_word 70.3% similar
-
function add_table_to_word_v1 68.6% similar