🔍 Code Extractor

function add_formatted_content_to_pdf_v1

Maturity: 47

Converts processed markdown elements into formatted PDF content by adding paragraphs, headers, lists, and tables to a ReportLab story object with appropriate styling.

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
4126 - 4158
Complexity:
moderate

Purpose

This function serves as a PDF content builder that takes structured markdown elements and renders them into a PDF document using ReportLab. It handles different content types (headers, paragraphs, lists, tables) and applies custom styling to each element type. The function is designed to work as part of a larger PDF generation pipeline where markdown content needs to be converted to professionally formatted PDF output.

Source Code

def add_formatted_content_to_pdf(story, elements, styles):
    """Add processed markdown elements to PDF with proper formatting"""
    from reportlab.platypus import Paragraph, Spacer
    
    for element in elements:
        if element['type'] == 'header':
            level = min(element['level'], 3)  # Use appropriate heading styles
            if level == 1:
                style_name = 'CustomHeading1'
            elif level == 2:
                style_name = 'CustomHeading2'
            else:
                style_name = 'CustomHeading3'
            story.append(Paragraph(element['content'], styles[style_name]))
            story.append(Spacer(1, 12))
            
        elif element['type'] == 'paragraph':
            formatted_text = convert_markdown_to_html(element['content'])
            story.append(Paragraph(formatted_text, styles['Normal']))
            story.append(Spacer(1, 6))
            
        elif element['type'] in ['list_item', 'numbered_list_item', 'bullet', 'numbered']:
            if element['type'] in ['list_item', 'bullet']:
                bullet = '• '
            else:
                bullet = '1. '
            formatted_text = bullet + convert_markdown_to_html(element['content'])
            story.append(Paragraph(formatted_text, styles['Normal']))
            
        elif element['type'] == 'table':
            logger.info(f"Adding table to PDF with {len(element['content'])} rows")
            add_table_to_pdf(story, element['content'])
            story.append(Spacer(1, 12))

Parameters

Name Type Default Kind
story - - positional_or_keyword
elements - - positional_or_keyword
styles - - positional_or_keyword

Parameter Details

story: A ReportLab story list (typically from SimpleDocTemplate) that accumulates flowable elements (Paragraphs, Spacers, Tables) to be rendered into the final PDF document. This list is modified in-place.

elements: A list of dictionaries where each dictionary represents a markdown element with keys 'type' (string indicating element type: 'header', 'paragraph', 'list_item', 'numbered_list_item', 'bullet', 'numbered', 'table'), 'content' (the text/data content), and optionally 'level' (for headers, indicating h1-h6 level).

styles: A dictionary or ReportLab StyleSheet object containing predefined paragraph styles including 'CustomHeading1', 'CustomHeading2', 'CustomHeading3', and 'Normal'. These styles define font, size, spacing, and other formatting properties.

Return Value

This function returns None. It modifies the 'story' parameter in-place by appending ReportLab flowable objects (Paragraph, Spacer, Table) to it.

Dependencies

  • reportlab

Required Imports

from reportlab.platypus import Paragraph, Spacer

Conditional/Optional Imports

These imports are only needed under specific conditions:

from reportlab.platypus import Paragraph, Spacer

Condition: imported inside the function, always required when function executes

Required (conditional)

Usage Example

from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.pagesizes import letter
from io import BytesIO

# Setup
buffer = BytesIO()
doc = SimpleDocTemplate(buffer, pagesize=letter)
story = []
styles = getSampleStyleSheet()
styles.add(ParagraphStyle(name='CustomHeading1', fontSize=18, spaceAfter=12))
styles.add(ParagraphStyle(name='CustomHeading2', fontSize=14, spaceAfter=10))
styles.add(ParagraphStyle(name='CustomHeading3', fontSize=12, spaceAfter=8))

# Define elements
elements = [
    {'type': 'header', 'level': 1, 'content': 'Main Title'},
    {'type': 'paragraph', 'content': 'This is a **bold** paragraph.'},
    {'type': 'bullet', 'content': 'First bullet point'},
    {'type': 'numbered', 'content': 'First numbered item'},
    {'type': 'table', 'content': [['Header1', 'Header2'], ['Data1', 'Data2']]}
]

# Use function
add_formatted_content_to_pdf(story, elements, styles)
doc.build(story)

Best Practices

  • Ensure the 'story' list is initialized before calling this function
  • Verify that all required custom styles ('CustomHeading1', 'CustomHeading2', 'CustomHeading3', 'Normal') exist in the styles parameter before calling
  • The function depends on external helper functions 'convert_markdown_to_html' and 'add_table_to_pdf' which must be defined in the same module
  • Header levels are capped at 3 to prevent style lookup errors; levels 4-6 will use CustomHeading3 style
  • The function modifies the story parameter in-place, so no return value needs to be captured
  • Ensure 'logger' is properly configured if you want to capture table addition logs
  • List items use hardcoded bullets ('•' for unordered, '1.' for numbered) which may need customization for complex list structures
  • Table content should be properly formatted as a 2D list structure before passing to this function

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function add_formatted_content_to_pdf 95.7% similar

    Processes markdown elements and adds them to a PDF document story with appropriate formatting, handling headers, paragraphs, lists, and tables.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function add_table_to_pdf_v1 75.9% similar

    Adds a formatted table to a PDF document story with proper text wrapping, styling, and header formatting using ReportLab's platypus components.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function add_table_to_pdf 75.7% similar

    Adds a formatted table to a ReportLab PDF document with automatic text wrapping, column width calculation, and alternating row colors.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function add_formatted_content_to_word_v1 74.5% similar

    Converts processed markdown elements into formatted content within a Microsoft Word document, handling headers, paragraphs, lists, tables, and code blocks with appropriate styling.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function export_to_pdf_v1 73.2% similar

    Converts a document object with sections and references into a formatted PDF file using ReportLab, supporting multiple heading levels, text content with markdown/HTML processing, and reference management.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
← Back to Browse