To align a heading to the left using ReportLab, you need to modify the paragraph style's alignment property. Here's how to do it:
1. For Existing Heading Styles
Modify the alignment property of the heading style directly:
python
from reportlab.lib.styles import getSampleStyleSheet
styles = getSampleStyleSheet()
# Modify existing h1 style to left-align
styles['Heading1'].alignment = 0 # 0=left, 1=center, 2=right, 4=justify
# Use the modified style
heading_style = styles['Heading1']
2. Create a Custom Left-Aligned Style
Create a new style based on an existing one with left alignment:
python
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
styles = getSampleStyleSheet()
# Create custom left-aligned heading style
left_heading_style = ParagraphStyle(
name='LeftHeading1',
parent=styles['Heading1'],
alignment=0, # Left alignment
# Optional additional overrides:
spaceAfter=12, # Add space after heading
fontName='Helvetica-Bold',
fontSize=16
)
# Use in your story
story.append(Paragraph("My Left-Aligned Heading", left_heading_style))
3. In Your Two-Column Example
Here's how to integrate this into the two-column flow example:
python
# ... [previous setup code] ...
# Create left-aligned heading style
styles = getSampleStyleSheet()
left_heading_style = ParagraphStyle(
name='LeftHeading1',
parent=styles['Heading1'],
alignment=0 # Left align
)
story = []
# Add left-aligned heading
story.append(Paragraph("My Left-Aligned Document Title", left_heading_style))
story.append(Spacer(1, 0.3 * inch))
# Continue with your content...
for i in range(10):
story.append(Paragraph(lorem.paragraph(), styles['Normal']))
story.append(Spacer(1, 0.2 * inch))
# ... [rest of the code] ...
Key Points:
-
Alignment Values:
0 = Left (default)
1 = Center
2 = Right
4 = Justify
-
Best Practices:
- Create custom styles instead of modifying base styles directly
- Use
parent to inherit properties from existing styles
- Set
spaceAfter for proper spacing after headings
- Apply to all heading levels consistently (Heading1, Heading2, etc.)
-
In Two-Column Layout:
- The heading will appear in the first column (left frame)
- To create a full-width heading above columns, you'd need to:
- Create a separate top frame
- Use a table spanning both columns
- Use a different page template for the first page
Example of a full-width heading using a table:
python
from reportlab.platypus import Table
# Full-width heading table
heading_table = Table([
[Paragraph("Full-Width Left-Aligned Heading", left_heading_style)]
], colWidths=[usable_width]) # usable_width = total columns width + gutter
story.append(heading_table)
story.append(Spacer(1, 0.3 * inch))
This gives you flexible control over heading alignment while maintaining the two-column text flow.