-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpdf_generator.py
More file actions
206 lines (178 loc) · 7.2 KB
/
pdf_generator.py
File metadata and controls
206 lines (178 loc) · 7.2 KB
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
import io
from reportlab.lib.pagesizes import letter, A4, legal
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer, Image
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_RIGHT
import pandas as pd
from template_manager import TemplateManager
from datetime import datetime
class PDFGenerator:
def __init__(self, template_name="default", include_images=True, preserve_formatting=True, page_size="A4"):
self.template_name = template_name
self.include_images = include_images
self.preserve_formatting = preserve_formatting
self.page_size = self._get_page_size(page_size)
self.template_manager = TemplateManager()
self.styles = getSampleStyleSheet()
self._setup_custom_styles()
def _get_page_size(self, size_name):
"""Convert page size name to reportlab page size"""
sizes = {
"A4": A4,
"Letter": letter,
"Legal": legal
}
return sizes.get(size_name, A4)
def _setup_custom_styles(self):
"""Setup custom paragraph styles"""
# Title style
self.styles.add(ParagraphStyle(
name='CustomTitle',
parent=self.styles['Heading1'],
fontSize=18,
spaceAfter=30,
alignment=TA_CENTER,
textColor=colors.darkblue
))
# Header style
self.styles.add(ParagraphStyle(
name='CustomHeader',
parent=self.styles['Heading2'],
fontSize=14,
spaceAfter=12,
textColor=colors.darkblue
))
# Normal style with spacing
self.styles.add(ParagraphStyle(
name='CustomNormal',
parent=self.styles['Normal'],
fontSize=10,
spaceAfter=6
))
def generate_pdf(self, data_df):
"""Generate PDF from data using the selected template"""
buffer = io.BytesIO()
# Create document
doc = SimpleDocTemplate(
buffer,
pagesize=self.page_size,
rightMargin=72,
leftMargin=72,
topMargin=72,
bottomMargin=18
)
# Build story (content)
story = []
# Add title
title = Paragraph("Bank Operations Verification Report", self.styles['CustomTitle'])
story.append(title)
story.append(Spacer(1, 12))
# Add generation info
generation_info = f"Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}<br/>"
generation_info += f"Template: {self.template_name}<br/>"
generation_info += f"Records: {len(data_df)}"
info_para = Paragraph(generation_info, self.styles['CustomNormal'])
story.append(info_para)
story.append(Spacer(1, 20))
# Add data summary
summary_header = Paragraph("Data Summary", self.styles['CustomHeader'])
story.append(summary_header)
# Create summary table
summary_data = [
['Metric', 'Value'],
['Total Records', str(len(data_df))],
['Columns', str(len(data_df.columns))],
['Data Types', ', '.join(data_df.dtypes.astype(str).unique())]
]
summary_table = Table(summary_data, colWidths=[2*inch, 3*inch])
summary_table.setStyle(TableStyle([
('BACKGROUND', (0, 0), (-1, 0), colors.grey),
('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)
]))
story.append(summary_table)
story.append(Spacer(1, 20))
# Add main data table
data_header = Paragraph("Detailed Data", self.styles['CustomHeader'])
story.append(data_header)
# Prepare data for table
table_data = []
# Add headers
headers = list(data_df.columns)
table_data.append(headers)
# Add data rows (limit to prevent overly large PDFs)
max_rows = min(len(data_df), 50) # Limit to 50 rows for performance
for i in range(max_rows):
row = []
for col in data_df.columns:
value = str(data_df.iloc[i][col])
# Truncate long values
if len(value) > 30:
value = value[:27] + "..."
row.append(value)
table_data.append(row)
# Add truncation notice if needed
if len(data_df) > max_rows:
truncation_notice = Paragraph(
f"Note: Only showing first {max_rows} rows of {len(data_df)} total records.",
self.styles['CustomNormal']
)
story.append(truncation_notice)
story.append(Spacer(1, 10))
# Calculate column widths
page_width = self.page_size[0] - 144 # Account for margins
num_cols = len(headers)
col_width = page_width / num_cols
col_widths = [col_width] * num_cols
# Create main data table
main_table = Table(table_data, colWidths=col_widths, repeatRows=1)
# Style the main table
table_style = [
('BACKGROUND', (0, 0), (-1, 0), colors.darkblue),
('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), 10),
('BOTTOMPADDING', (0, 0), (-1, 0), 12),
('FONTSIZE', (0, 1), (-1, -1), 8),
('GRID', (0, 0), (-1, -1), 1, colors.black)
]
# Alternate row colors
for i in range(1, len(table_data)):
if i % 2 == 0:
table_style.append(('BACKGROUND', (0, i), (-1, i), colors.lightgrey))
else:
table_style.append(('BACKGROUND', (0, i), (-1, i), colors.white))
main_table.setStyle(TableStyle(table_style))
story.append(main_table)
# Add footer
story.append(Spacer(1, 30))
footer = Paragraph(
"This report was automatically generated by the PDF Export System.",
self.styles['CustomNormal']
)
story.append(footer)
# Build PDF
doc.build(story)
buffer.seek(0)
return buffer
def _format_value(self, value):
"""Format value for display in PDF"""
if pd.isna(value):
return "N/A"
elif isinstance(value, (int, float)):
if isinstance(value, float) and value.is_integer():
return str(int(value))
elif isinstance(value, float):
return f"{value:.2f}"
else:
return str(value)
else:
return str(value)