class SessionDocTemplate
A custom ReportLab document template that extends BaseDocTemplate to add session information (conversation ID and exchange number) in the footer of each page.
/tf/active/vicechatdev/e-ink-llm/pdf_generator.py
18 - 67
moderate
Purpose
This class creates PDF documents with customized footers containing session tracking information. It's designed for generating PDF reports from conversational AI interactions, displaying page numbers on the left and session metadata on the right of each page footer. The template automatically manages page layout with appropriate margins to accommodate the footer.
Source Code
class SessionDocTemplate(BaseDocTemplate):
"""Custom document template with session info in footer"""
def __init__(self, filename, conversation_id=None, exchange_number=None, **kwargs):
super().__init__(filename, **kwargs)
self.conversation_id = conversation_id
self.exchange_number = exchange_number
# Create frame for main content (leaving space for footer)
main_frame = Frame(
self.leftMargin, self.bottomMargin + 0.5*inch,
self.width, self.height - 0.5*inch,
id='main'
)
# Create page template
main_template = PageTemplate(
id='main',
frames=[main_frame],
onPage=self.add_session_footer
)
self.addPageTemplates([main_template])
def add_session_footer(self, canvas, doc):
"""Add session information to page footer"""
canvas.saveState()
# Set footer style
canvas.setFont('Helvetica', 8)
canvas.setFillColor(colors.grey)
# Left side: page number
page_text = f"Page {doc.page}"
canvas.drawString(doc.leftMargin, doc.bottomMargin, page_text)
# Right side: session info
if self.conversation_id and self.exchange_number:
session_text = f"Session: {self.conversation_id} | Exchange #{self.exchange_number}"
elif self.conversation_id:
session_text = f"Session: {self.conversation_id}"
else:
session_text = "E-Ink LLM Assistant"
# Calculate position for right-aligned text
text_width = canvas.stringWidth(session_text, 'Helvetica', 8)
x_position = doc.width + doc.leftMargin - text_width
canvas.drawString(x_position, doc.bottomMargin, session_text)
canvas.restoreState()
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
BaseDocTemplate | - |
Parameter Details
filename: The path/filename where the PDF document will be saved. Can be a string path or file-like object.
conversation_id: Optional identifier for the conversation session. Used to track which conversation this document belongs to. Displayed in the footer as 'Session: {conversation_id}'.
exchange_number: Optional number indicating which exchange in the conversation this document represents. Displayed in footer as 'Exchange #{exchange_number}'.
**kwargs: Additional keyword arguments passed to the parent BaseDocTemplate class, such as pagesize, leftMargin, rightMargin, topMargin, bottomMargin, etc.
Return Value
Instantiation returns a SessionDocTemplate object that can be used to build PDF documents. The object inherits all methods from BaseDocTemplate, primarily the build() method which takes a list of flowables (Paragraph, Spacer, Image, etc.) and generates the PDF file.
Class Interface
Methods
__init__(self, filename, conversation_id=None, exchange_number=None, **kwargs)
Purpose: Initializes the document template with session tracking information and sets up the page layout with footer space
Parameters:
filename: Path where the PDF will be savedconversation_id: Optional conversation identifier for footer displayexchange_number: Optional exchange number for footer display**kwargs: Additional arguments passed to BaseDocTemplate (pagesize, margins, etc.)
Returns: None (constructor)
add_session_footer(self, canvas, doc)
Purpose: Callback method that adds session information and page numbers to the footer of each page during PDF generation
Parameters:
canvas: ReportLab canvas object for drawing on the pagedoc: Document object containing page information and dimensions
Returns: None (modifies canvas in-place)
build(self, flowables, **kwargs)
Purpose: Inherited from BaseDocTemplate. Builds the PDF document from a list of flowables (Paragraph, Spacer, Image, etc.)
Parameters:
flowables: List of ReportLab flowable objects to render in the document**kwargs: Additional build options
Returns: None (writes PDF to file)
Attributes
| Name | Type | Description | Scope |
|---|---|---|---|
conversation_id |
Optional[str] | Stores the conversation identifier to be displayed in the footer | instance |
exchange_number |
Optional[int] | Stores the exchange number to be displayed in the footer | instance |
leftMargin |
float | Inherited from BaseDocTemplate. Left margin of the page in points | instance |
rightMargin |
float | Inherited from BaseDocTemplate. Right margin of the page in points | instance |
topMargin |
float | Inherited from BaseDocTemplate. Top margin of the page in points | instance |
bottomMargin |
float | Inherited from BaseDocTemplate. Bottom margin of the page in points | instance |
width |
float | Inherited from BaseDocTemplate. Width of the content area in points | instance |
height |
float | Inherited from BaseDocTemplate. Height of the content area in points | instance |
page |
int | Inherited from BaseDocTemplate. Current page number during document generation | instance |
Dependencies
reportlab
Required Imports
from reportlab.platypus.doctemplate import BaseDocTemplate
from reportlab.platypus.doctemplate import PageTemplate
from reportlab.platypus.frames import Frame
from reportlab.lib import colors
from reportlab.lib.units import inch
Usage Example
from reportlab.platypus.doctemplate import BaseDocTemplate
from reportlab.platypus.doctemplate import PageTemplate
from reportlab.platypus.frames import Frame
from reportlab.lib import colors
from reportlab.lib.units import inch
from reportlab.platypus import Paragraph
from reportlab.lib.styles import getSampleStyleSheet
# Instantiate the template
doc = SessionDocTemplate(
'output.pdf',
conversation_id='conv_12345',
exchange_number=3
)
# Create content
styles = getSampleStyleSheet()
story = [
Paragraph('This is a test document', styles['Title']),
Paragraph('Content goes here', styles['Normal'])
]
# Build the PDF
doc.build(story)
# Example without session info
doc2 = SessionDocTemplate('simple.pdf')
doc2.build(story)
Best Practices
- Always call the build() method with a list of flowables to generate the actual PDF file
- The conversation_id and exchange_number are optional but recommended for tracking multi-exchange conversations
- The template reserves 0.5 inches at the bottom for the footer, ensure your content fits within the remaining space
- Use standard ReportLab flowables (Paragraph, Spacer, Image, etc.) to populate the document
- The footer is automatically added to every page via the onPage callback mechanism
- If neither conversation_id nor exchange_number is provided, the footer displays 'E-Ink LLM Assistant' as default text
- The class modifies the document's frame to leave space for the footer, so manual frame adjustments are not needed
- Session information is rendered in grey color at 8pt Helvetica font for subtle appearance
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class HybridSessionDocTemplate 87.1% similar
-
class SessionDetector 56.9% similar
-
class ConversationTimelineGenerator 55.9% similar
-
class SessionInfo 55.2% similar
-
function export_to_pdf_v1 54.9% similar