1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
|
# generators/pdf_generator.py
from reportlab.lib.pagesizes import letter, A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch, cm
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Image
from reportlab.lib import colors
from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT
from io import BytesIO
import matplotlib.pyplot as plt
from core.base import DocumentGenerator, DocumentConfig, OutputFormat
class PDFGenerator(DocumentGenerator):
"""Generatore PDF avanzato con ReportLab"""
def __init__(self, config: DocumentConfig):
super().__init__(config)
self.doc = None
self.story = []
self.styles = getSampleStyleSheet()
self._create_custom_styles()
def _create_custom_styles(self):
"""Crea stili personalizzati per il documento"""
# Titolo principale
self.styles.add(ParagraphStyle(
name='CustomTitle',
parent=self.styles['Heading1'],
fontSize=24,
spaceAfter=30,
textColor=colors.HexColor('#2C3E50'),
alignment=TA_CENTER
))
# Sottotitolo
self.styles.add(ParagraphStyle(
name='CustomSubtitle',
parent=self.styles['Heading2'],
fontSize=16,
spaceAfter=20,
textColor=colors.HexColor('#34495E'),
leftIndent=0.5*inch
))
# Paragrafo con indentazione
self.styles.add(ParagraphStyle(
name='IndentedParagraph',
parent=self.styles['Normal'],
leftIndent=0.5*inch,
spaceAfter=12
))
def generate(self) -> Path:
"""Genera il documento PDF"""
try:
# Inizializza documento
self.doc = SimpleDocTemplate(
str(self.config.output_path),
pagesize=A4,
rightMargin=2*cm,
leftMargin=2*cm,
topMargin=2*cm,
bottomMargin=2*cm
)
# Costruisci contenuto
self._build_content()
# Genera PDF
self.doc.build(self.story)
self.logger.info(f"PDF generato: {self.config.output_path}")
return self.config.output_path
except Exception as e:
self.logger.error(f"Errore generazione PDF: {e}")
raise
def _build_content(self):
"""Costruisce il contenuto del documento"""
data = self.config.data
# Header con logo se presente
if 'logo_path' in data:
self._add_logo(data['logo_path'])
# Titolo documento
if 'title' in data:
title = Paragraph(data['title'], self.styles['CustomTitle'])
self.story.append(title)
self.story.append(Spacer(1, 20))
# Sottotitolo
if 'subtitle' in data:
subtitle = Paragraph(data['subtitle'], self.styles['CustomSubtitle'])
self.story.append(subtitle)
self.story.append(Spacer(1, 15))
# Sezioni del documento
if 'sections' in data:
for section in data['sections']:
self._add_section(section)
# Tabelle se presenti
if 'tables' in data:
for table_data in data['tables']:
self._add_table(table_data)
# Grafici se presenti
if 'charts' in data:
for chart_data in data['charts']:
self._add_chart(chart_data)
def _add_logo(self, logo_path: str):
"""Aggiunge logo al documento"""
try:
logo = Image(logo_path, width=2*inch, height=1*inch)
logo.hAlign = 'CENTER'
self.story.append(logo)
self.story.append(Spacer(1, 20))
except Exception as e:
self.logger.warning(f"Impossibile caricare logo: {e}")
def _add_section(self, section: dict):
"""Aggiunge una sezione al documento"""
# Titolo sezione
if 'title' in section:
section_title = Paragraph(section['title'], self.styles['Heading2'])
self.story.append(section_title)
self.story.append(Spacer(1, 10))
# Contenuto sezione
if 'content' in section:
for paragraph in section['content']:
p = Paragraph(paragraph, self.styles['IndentedParagraph'])
self.story.append(p)
self.story.append(Spacer(1, 15))
def _add_table(self, table_data: dict):
"""Aggiunge tabella formattata"""
data_table = table_data.get('data', [])
if not data_table:
return
# Crea tabella
table = Table(data_table)
# Applica stile
table_style = [
('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#3498DB')),
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
('ALIGN', (0, 0), (-1, -1), 'CENTER'),
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
('FONTSIZE', (0, 0), (-1, 0), 12),
('BOTTOMPADDING', (0, 0), (-1, 0), 12),
('BACKGROUND', (0, 1), (-1, -1), colors.beige),
('GRID', (0, 0), (-1, -1), 1, colors.black)
]
table.setStyle(TableStyle(table_style))
# Titolo tabella
if 'title' in table_data:
table_title = Paragraph(table_data['title'], self.styles['Heading3'])
self.story.append(table_title)
self.story.append(Spacer(1, 10))
self.story.append(table)
self.story.append(Spacer(1, 20))
def _add_chart(self, chart_data: dict):
"""Aggiunge grafico generato con matplotlib"""
try:
# Genera grafico in memoria
fig, ax = plt.subplots(figsize=(8, 6))
chart_type = chart_data.get('type', 'bar')
if chart_type == 'bar':
ax.bar(chart_data['labels'], chart_data['values'])
elif chart_type == 'line':
ax.plot(chart_data['labels'], chart_data['values'])
elif chart_type == 'pie':
ax.pie(chart_data['values'], labels=chart_data['labels'], autopct='%1.1f%%')
ax.set_title(chart_data.get('title', 'Grafico'))
# Salva in BytesIO
img_buffer = BytesIO()
plt.savefig(img_buffer, format='png', dpi=150, bbox_inches='tight')
img_buffer.seek(0)
plt.close()
# Aggiungi al documento
chart_img = Image(img_buffer, width=6*inch, height=4*inch)
chart_img.hAlign = 'CENTER'
self.story.append(chart_img)
self.story.append(Spacer(1, 20))
except Exception as e:
self.logger.error(f"Errore generazione grafico: {e}")
def validate_template(self, template_path: Path) -> bool:
"""Valida template PDF (placeholder per future implementazioni)"""
return template_path.exists() and template_path.suffix in ['.json', '.yaml']
# Registra il generatore
from core.base import DocumentFactory
DocumentFactory.register_generator(OutputFormat.PDF, PDFGenerator)
|