Ethscriptions commited on
Commit
8319975
·
verified ·
1 Parent(s): cd91a84

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +168 -189
app.py CHANGED
@@ -7,121 +7,87 @@ import base64
7
  import matplotlib.gridspec as gridspec
8
  import math
9
  from matplotlib.backends.backend_pdf import PdfPages
10
- import matplotlib.font_manager as fm # 新增导入
11
- import os # 新增导入
12
 
13
- # --- 全局常量 ---
14
  SPLIT_TIME = "17:30"
15
  BUSINESS_START = "09:30"
16
  BUSINESS_END = "01:30"
17
- BORDER_COLOR = 'grey'
18
  DATE_COLOR = '#A9A9A9'
19
- FONT_PATH = 'SimHei.ttf' # 字体文件路径
20
-
21
- # --- 字体设置 ---
22
- FONT_BOLD = None
23
- FONT_REGULAR = None
24
- FONT_WARNING_ISSUED = False
25
-
26
- def get_font_properties():
27
- """加载字体文件并返回 FontProperties 对象"""
28
- global FONT_BOLD, FONT_REGULAR, FONT_WARNING_ISSUED
29
- if FONT_BOLD is None: # 只加载一次
30
- if os.path.exists(FONT_PATH):
31
- try:
32
- FONT_BOLD = fm.FontProperties(fname=FONT_PATH, weight='bold')
33
- FONT_REGULAR = fm.FontProperties(fname=FONT_PATH, weight='normal')
34
- except Exception as e:
35
- if not FONT_WARNING_ISSUED:
36
- st.warning(f"加载字体 '{FONT_PATH}' 失败: {e}. 将使用默认字体。")
37
- FONT_WARNING_ISSUED = True
38
- else:
39
- if not FONT_WARNING_ISSUED:
40
- st.warning(f"字体文件 '{FONT_PATH}' 未找到。请将其放置在代码同目录下。将使用默认字体。")
41
- FONT_WARNING_ISSUED = True
42
-
43
- def get_font_args(style='regular'):
44
- """根据请求的样式返回字体参数字典"""
45
- get_font_properties() # 确保字体已加载
46
- if style == 'bold' and FONT_BOLD:
47
- return {'fontproperties': FONT_BOLD}
48
- if style == 'regular' and FONT_REGULAR:
49
- return {'fontproperties': FONT_REGULAR}
50
- # Fallback
51
- return {'fontfamily': 'sans-serif', 'weight': 'bold' if style == 'bold' else 'normal'}
52
-
53
 
54
  def process_schedule(file):
55
  """处理上传的 Excel 文件,生成排序和分组后的打印内容"""
56
  try:
57
  # 读取 Excel,跳过前 8 行
58
  df = pd.read_excel(file, skiprows=8)
59
-
60
  # 提取所需列 (G9, H9, J9)
61
  df = df.iloc[:, [6, 7, 9]] # G, H, J 列
62
  df.columns = ['Hall', 'StartTime', 'EndTime']
63
-
64
  # 清理数据
65
  df = df.dropna(subset=['Hall', 'StartTime', 'EndTime'])
66
-
67
- # 转换影厅格式为 "#号" 格式
68
- df['Hall'] = df['Hall'].str.extract(r'(\d+)号').astype(str) + ' '
69
-
70
  # 保存原始时间字符串用于诊断
71
  df['original_end'] = df['EndTime']
72
-
73
  # 转换时间为 datetime 对象
74
  base_date = datetime.today().date()
75
  df['StartTime'] = pd.to_datetime(df['StartTime'])
76
  df['EndTime'] = pd.to_datetime(df['EndTime'])
77
-
78
  # 设置基准时间
79
  business_start = datetime.strptime(f"{base_date} {BUSINESS_START}", "%Y-%m-%d %H:%M")
80
  business_end = datetime.strptime(f"{base_date} {BUSINESS_END}", "%Y-%m-%d %H:%M")
81
-
82
  # 处理跨天情况
83
  if business_end < business_start:
84
  business_end += timedelta(days=1)
85
-
86
  # 标准化所有时间到同一天
87
  for idx, row in df.iterrows():
88
  end_time = row['EndTime']
89
  if end_time.hour < 9:
90
  df.at[idx, 'EndTime'] = end_time + timedelta(days=1)
91
-
92
  if row['StartTime'].hour >= 21 and end_time.hour < 9:
93
  df.at[idx, 'EndTime'] = end_time + timedelta(days=1)
94
-
95
  # 筛选营业时间内的场次
96
  df['time_for_comparison'] = df['EndTime'].apply(
97
  lambda x: datetime.combine(base_date, x.time())
98
  )
99
-
100
  df.loc[df['time_for_comparison'].dt.hour < 9, 'time_for_comparison'] += timedelta(days=1)
101
-
102
  valid_times = (
103
  ((df['time_for_comparison'] >= datetime.combine(base_date, business_start.time())) &
104
  (df['time_for_comparison'] <= datetime.combine(base_date + timedelta(days=1), business_end.time())))
105
  )
106
-
107
  df = df[valid_times]
108
-
109
  # 按散场时间排序
110
  df = df.sort_values('EndTime')
111
-
112
  # 分割数据
113
- split_time = datetime.strptime(f"{base_date} {SPLIT_TIME}", "%Y-%m-%d %H:%M")
114
- split_time_for_comparison = df['time_for_comparison'].apply(
115
- lambda x: datetime.combine(base_date, split_time.time())
116
- )
117
-
118
- part1 = df[df['time_for_comparison'] <= split_time_for_comparison].copy()
119
- part2 = df[df['time_for_comparison'] > split_time_for_comparison].copy()
120
-
121
  # 格式化时间显示
122
  for part in [part1, part2]:
123
- part['EndTime'] = part['EndTime'].dt.strftime('%-H:%M')
124
-
 
 
 
 
125
  # 关键修改:精确读取C6单元格
126
  date_df = pd.read_excel(
127
  file,
@@ -131,7 +97,7 @@ def process_schedule(file):
131
  header=None # 无表头
132
  )
133
  date_cell = date_df.iloc[0, 0]
134
-
135
  try:
136
  # 处理不同日期格式
137
  if isinstance(date_cell, str):
@@ -140,167 +106,178 @@ def process_schedule(file):
140
  date_str = pd.to_datetime(date_cell).strftime('%Y-%m-%d')
141
  except:
142
  date_str = datetime.today().strftime('%Y-%m-%d')
143
-
144
  return part1[['Hall', 'EndTime']], part2[['Hall', 'EndTime']], date_str
145
-
146
  except Exception as e:
147
  st.error(f"处理文件时出错: {str(e)}")
148
  return None, None, None
149
 
 
150
  def create_print_layout(data, title, date_str):
151
- """创建基于精确表格布局的打印页面 (PNG 和 PDF)"""
152
  if data.empty:
153
  return None
154
 
155
- # --- 1. 布局和尺寸计算 ---
156
- A5_WIDTH_IN, A5_HEIGHT_IN = 5.83, 8.27
157
- DPI = 300
158
- MARGIN = 0.25 # 页边距 (英寸)
159
- HEADER_HEIGHT_IN = 0.3 # 日期标题栏高度 (英寸)
160
-
161
- content_width = A5_WIDTH_IN - (2 * MARGIN)
162
- content_height = A5_HEIGHT_IN - (2 * MARGIN)
163
-
164
- total_items = len(data)
165
- num_cols = 3
166
- num_rows = math.ceil(total_items / num_cols)
167
-
168
- grid_height = content_height - HEADER_HEIGHT_IN
169
- cell_width = content_width / num_cols
170
- cell_height = grid_height / num_rows if num_rows > 0 else 0
171
-
172
- # --- 2. 动态字体大小计算 ---
173
- def calculate_font_size(fig):
174
- # 使用一个典型的宽字符串来估算
175
- sample_text = "8 88:88"
176
- target_width = cell_width * 0.9 # 目标宽度为单元格宽度的90%
177
-
178
- # 用初始字号10来测量
179
- initial_fontsize = 10
180
- t = fig.text(0.5, 0.5, sample_text, fontsize=initial_fontsize, **get_font_args('bold'))
181
- # 渲染并获取边界框(以英寸为单位)
182
- bbox = t.get_window_extent(renderer=fig.canvas.get_renderer())
183
- text_width_in = bbox.width / fig.get_dpi()
184
- t.remove() # 移除临时文本
185
 
186
- # 根据宽度比例调整字体大小
187
- if text_width_in > 0:
188
- scale_factor = target_width / text_width_in
189
- return initial_fontsize * scale_factor
190
- return initial_fontsize # 备用
191
-
192
- # --- 3. 数据准备 (Z字形排序) ---
193
- data_values = data.values.tolist()
194
- while len(data_values) % num_cols != 0:
195
- data_values.append(['', ''])
196
-
197
- rows_per_col_layout = math.ceil(len(data_values) / num_cols)
198
- sorted_data = [['', '']] * len(data_values)
199
- for i, item in enumerate(data_values):
200
- if item[0] and item[1]:
201
- row_in_col = i % rows_per_col_layout
202
- col_idx = i // rows_per_col_layout
203
- new_index = row_in_col * num_cols + col_idx
204
- if new_index < len(sorted_data):
205
- sorted_data[new_index] = item
206
-
207
- # --- 4. 绘图 ---
208
- fig = plt.figure(figsize=(A5_WIDTH_IN, A5_HEIGHT_IN), dpi=DPI)
209
- final_fontsize = calculate_font_size(fig)
210
- index_fontsize = final_fontsize * 0.35
211
- date_fontsize = final_fontsize * 0.5
212
-
213
- # 绘制日期头
214
- header_ax = fig.add_axes([MARGIN / A5_WIDTH_IN, (A5_HEIGHT_IN - MARGIN - HEADER_HEIGHT_IN) / A5_HEIGHT_IN, content_width / A5_WIDTH_IN, HEADER_HEIGHT_IN / A5_HEIGHT_IN])
215
- header_ax.text(0.01, 0.5, f"{date_str} {title}",
216
- fontsize=date_fontsize,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217
  color=DATE_COLOR,
 
218
  ha='left',
219
  va='center',
220
- transform=header_ax.transAxes,
221
- **get_font_args('bold'))
222
- header_ax.set_axis_off()
223
-
224
- # 绘制每个单元格
225
- for idx, (hall, end_time) in enumerate(sorted_data):
226
- if hall and end_time:
227
- row_grid = idx // num_cols
228
- col_grid = idx % num_cols
229
-
230
- # 计算单元格的绝对位置(从左下角开始,单位:英寸)
231
- x_pos_in = MARGIN + (col_grid * cell_width)
232
- y_pos_in = MARGIN + ( (num_rows - 1 - row_grid) * cell_height )
233
-
234
- # 转换为 Figure 的相对坐标 [left, bottom, width, height]
235
- ax_rect = [x_pos_in / A5_WIDTH_IN, y_pos_in / A5_HEIGHT_IN, cell_width / A5_WIDTH_IN, cell_height / A5_HEIGHT_IN]
236
- ax = fig.add_axes(ax_rect)
237
-
238
- # 绘制主要文本
239
- display_text = f"{hall}{end_time}"
240
- ax.text(0.5, 0.5, display_text,
241
- fontsize=final_fontsize,
242
- ha='center',
243
- va='center',
244
- transform=ax.transAxes,
245
- **get_font_args('bold'))
246
-
247
- # 绘制左上角序号
248
- ax.text(0.08, 0.92, str(idx + 1),
249
- fontsize=index_fontsize,
250
- color=BORDER_COLOR,
251
- ha='left',
252
- va='top',
253
- transform=ax.transAxes,
254
- **get_font_args('regular'))
255
-
256
- # 设置边框为灰色点状虚线
257
- for spine in ax.spines.values():
258
- spine.set_color(BORDER_COLOR)
259
- spine.set_linestyle(':')
260
- spine.set_linewidth(1)
261
-
262
- ax.set_xticks([])
263
- ax.set_yticks([])
264
-
265
- # --- 5. 保存到内存 ---
266
- # 保存 PNG
267
  png_buffer = io.BytesIO()
268
- fig.savefig(png_buffer, format='png', pad_inches=0)
 
269
  png_buffer.seek(0)
270
  png_base64 = base64.b64encode(png_buffer.getvalue()).decode()
271
-
272
- # 保存 PDF
 
273
  pdf_buffer = io.BytesIO()
274
- fig.savefig(pdf_buffer, format='pdf', pad_inches=0)
 
 
275
  pdf_buffer.seek(0)
276
  pdf_base64 = base64.b64encode(pdf_buffer.getvalue()).decode()
277
-
278
- plt.close(fig)
279
 
280
  return {
281
  'png': f'data:image/png;base64,{png_base64}',
282
  'pdf': f'data:application/pdf;base64,{pdf_base64}'
283
  }
284
 
 
285
  def display_pdf(base64_pdf):
286
- """Streamlit中嵌入显示PDF"""
287
  pdf_display = f'<iframe src="{base64_pdf}" width="100%" height="800" type="application/pdf"></iframe>'
288
  return pdf_display
289
 
290
- # --- Streamlit 界面 ---
291
  st.set_page_config(page_title="散厅时间快捷打印", layout="wide")
292
  st.title("散厅时间快捷打印")
293
 
294
- # 检查并加载字体,如有需要会显示警告
295
- get_font_properties()
296
-
297
  uploaded_file = st.file_uploader("上传【放映场次核对表.xls】文件", type=["xls"])
298
 
299
  if uploaded_file:
300
  part1, part2, date_str = process_schedule(uploaded_file)
301
 
302
  if part1 is not None and part2 is not None:
303
- # 生成包含 PNG PDF 的字典
304
  part1_output = create_print_layout(part1, "A", date_str)
305
  part2_output = create_print_layout(part2, "C", date_str)
306
 
@@ -309,6 +286,7 @@ if uploaded_file:
309
  with col1:
310
  st.subheader("白班散场预览(时间 ≤ 17:30)")
311
  if part1_output:
 
312
  tab1_1, tab1_2 = st.tabs(["PDF 预览", "PNG 预览"])
313
  with tab1_1:
314
  st.markdown(display_pdf(part1_output['pdf']), unsafe_allow_html=True)
@@ -320,6 +298,7 @@ if uploaded_file:
320
  with col2:
321
  st.subheader("夜班散场预览(时间 > 17:30)")
322
  if part2_output:
 
323
  tab2_1, tab2_2 = st.tabs(["PDF 预览", "PNG 预览"])
324
  with tab2_1:
325
  st.markdown(display_pdf(part2_output['pdf']), unsafe_allow_html=True)
 
7
  import matplotlib.gridspec as gridspec
8
  import math
9
  from matplotlib.backends.backend_pdf import PdfPages
10
+ # The 'FancyBboxPatch' is no longer needed for the new border style.
 
11
 
 
12
  SPLIT_TIME = "17:30"
13
  BUSINESS_START = "09:30"
14
  BUSINESS_END = "01:30"
15
+ BORDER_COLOR = 'gray' # Changed to gray for the new style
16
  DATE_COLOR = '#A9A9A9'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  def process_schedule(file):
19
  """处理上传的 Excel 文件,生成排序和分组后的打印内容"""
20
  try:
21
  # 读取 Excel,跳过前 8 行
22
  df = pd.read_excel(file, skiprows=8)
23
+
24
  # 提取所需列 (G9, H9, J9)
25
  df = df.iloc[:, [6, 7, 9]] # G, H, J 列
26
  df.columns = ['Hall', 'StartTime', 'EndTime']
27
+
28
  # 清理数据
29
  df = df.dropna(subset=['Hall', 'StartTime', 'EndTime'])
30
+
31
+ # 转换影厅格式为 "#" 格式 (移除末尾空格)
32
+ df['Hall'] = df['Hall'].str.extract(r'(\d+)号').astype(str)
33
+
34
  # 保存原始时间字符串用于诊断
35
  df['original_end'] = df['EndTime']
36
+
37
  # 转换时间为 datetime 对象
38
  base_date = datetime.today().date()
39
  df['StartTime'] = pd.to_datetime(df['StartTime'])
40
  df['EndTime'] = pd.to_datetime(df['EndTime'])
41
+
42
  # 设置基准时间
43
  business_start = datetime.strptime(f"{base_date} {BUSINESS_START}", "%Y-%m-%d %H:%M")
44
  business_end = datetime.strptime(f"{base_date} {BUSINESS_END}", "%Y-%m-%d %H:%M")
45
+
46
  # 处理跨天情况
47
  if business_end < business_start:
48
  business_end += timedelta(days=1)
49
+
50
  # 标准化所有时间到同一天
51
  for idx, row in df.iterrows():
52
  end_time = row['EndTime']
53
  if end_time.hour < 9:
54
  df.at[idx, 'EndTime'] = end_time + timedelta(days=1)
55
+
56
  if row['StartTime'].hour >= 21 and end_time.hour < 9:
57
  df.at[idx, 'EndTime'] = end_time + timedelta(days=1)
58
+
59
  # 筛选营业时间内的场次
60
  df['time_for_comparison'] = df['EndTime'].apply(
61
  lambda x: datetime.combine(base_date, x.time())
62
  )
63
+
64
  df.loc[df['time_for_comparison'].dt.hour < 9, 'time_for_comparison'] += timedelta(days=1)
65
+
66
  valid_times = (
67
  ((df['time_for_comparison'] >= datetime.combine(base_date, business_start.time())) &
68
  (df['time_for_comparison'] <= datetime.combine(base_date + timedelta(days=1), business_end.time())))
69
  )
70
+
71
  df = df[valid_times]
72
+
73
  # 按散场时间排序
74
  df = df.sort_values('EndTime')
75
+
76
  # 分割数据
77
+ split_time_obj = datetime.strptime(SPLIT_TIME, "%H:%M").time()
78
+ split_datetime = datetime.combine(base_date, split_time_obj)
79
+
80
+ part1 = df[df['time_for_comparison'] <= split_datetime].copy()
81
+ part2 = df[df['time_for_comparison'] > split_datetime].copy()
82
+
 
 
83
  # 格式化时间显示
84
  for part in [part1, part2]:
85
+ # Use '%-H' for 24-hour format without leading zero on Linux/macOS
86
+ # Use '%#H' on Windows. A more cross-platform way is to format and remove later.
87
+ # Let's stick to '%H:%M' for universal 24-hour format e.g., "09:30"
88
+ part['EndTime'] = part['EndTime'].dt.strftime('%H:%M')
89
+
90
+
91
  # 关键修改:精确读取C6单元格
92
  date_df = pd.read_excel(
93
  file,
 
97
  header=None # 无表头
98
  )
99
  date_cell = date_df.iloc[0, 0]
100
+
101
  try:
102
  # 处理不同日期格式
103
  if isinstance(date_cell, str):
 
106
  date_str = pd.to_datetime(date_cell).strftime('%Y-%m-%d')
107
  except:
108
  date_str = datetime.today().strftime('%Y-%m-%d')
109
+
110
  return part1[['Hall', 'EndTime']], part2[['Hall', 'EndTime']], date_str
111
+
112
  except Exception as e:
113
  st.error(f"处理文件时出错: {str(e)}")
114
  return None, None, None
115
 
116
+
117
  def create_print_layout(data, title, date_str):
118
+ """创建打印布局 (PNG 和 PDF)"""
119
  if data.empty:
120
  return None
121
 
122
+ # --- A5 Paper Dimensions in inches for precise layout ---
123
+ A5_WIDTH_IN = 5.83
124
+ A5_HEIGHT_IN = 8.27
125
+ NUM_COLS = 3
126
+
127
+ # --- Create Figures for PNG and PDF ---
128
+ png_fig = plt.figure(figsize=(A5_WIDTH_IN, A5_HEIGHT_IN), dpi=300)
129
+ pdf_fig = plt.figure(figsize=(A5_WIDTH_IN, A5_HEIGHT_IN), dpi=300)
130
+
131
+ # --- Internal drawing function to apply changes to both figures ---
132
+ def process_figure(fig):
133
+ plt.rcParams['font.family'] = 'sans-serif'
134
+ plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']
135
+
136
+ total_items = len(data)
137
+ if total_items == 0:
138
+ plt.close(fig)
139
+ return
140
+
141
+ # --- 1. Redesign Print Layout ---
142
+ # Calculate number of rows needed
143
+ num_rows = math.ceil(total_items / NUM_COLS)
 
 
 
 
 
 
 
 
144
 
145
+ # Remove all padding from the figure edges
146
+ fig.subplots_adjust(left=0, right=1, top=0.95, bottom=0)
147
+
148
+ # Create a grid with no space between cells. A small top row for the date.
149
+ gs = gridspec.GridSpec(
150
+ num_rows + 1,
151
+ NUM_COLS,
152
+ hspace=0,
153
+ wspace=0,
154
+ height_ratios=[0.3] + [1] * num_rows, # Make date row shorter
155
+ figure=fig
156
+ )
157
+
158
+ data_values = data.values.tolist()
159
+
160
+ # Pad data with empty values to make it a multiple of NUM_COLS
161
+ while len(data_values) % NUM_COLS != 0:
162
+ data_values.append(['', ''])
163
+
164
+ # --- Sort data column-first (Z-pattern) ---
165
+ rows_per_col_layout = math.ceil(len(data_values) / NUM_COLS)
166
+ sorted_data = [['', '']] * len(data_values)
167
+ for i, item in enumerate(data_values):
168
+ if item[0] and item[1]:
169
+ row_in_col = i % rows_per_col_layout
170
+ col_idx = i // rows_per_col_layout
171
+ new_index = row_in_col * NUM_COLS + col_idx
172
+ if new_index < len(sorted_data):
173
+ sorted_data[new_index] = item
174
+
175
+ # --- Dynamic Font Size Calculation ---
176
+ def get_dynamic_fontsize(text, cell_width_inches):
177
+ if not text:
178
+ return 1
179
+ # This factor is empirical, adjusts font size to fill ~90% of cell width
180
+ # A lower factor (e.g., 0.5) results in larger text.
181
+ ASPECT_RATIO_FACTOR = 0.55
182
+ num_chars = len(text)
183
+ # Formula: (target_width_points) / (num_characters * aspect_ratio)
184
+ fontsize = (cell_width_inches * 0.9 * 72) / (num_chars * ASPECT_RATIO_FACTOR)
185
+ return max(10, fontsize) # Return at least size 10
186
+
187
+ cell_width_inches = A5_WIDTH_IN / NUM_COLS
188
+
189
+ # --- Draw each data cell ---
190
+ for idx, (hall, end_time) in enumerate(sorted_data):
191
+ if hall and end_time:
192
+ row_grid = idx // NUM_COLS + 1 # +1 to skip date row
193
+ col_grid = idx % NUM_COLS
194
+
195
+ ax = fig.add_subplot(gs[row_grid, col_grid])
196
+
197
+ display_text = f"{hall} {end_time}"
198
+
199
+ # Calculate optimal font size
200
+ fontsize = get_dynamic_fontsize(display_text, cell_width_inches)
201
+
202
+ ax.text(0.5, 0.5, display_text,
203
+ fontsize=fontsize,
204
+ fontweight='bold',
205
+ ha='center',
206
+ va='center',
207
+ transform=ax.transAxes)
208
+
209
+ # --- 2. Change Cell Border ---
210
+ # Set a dotted gray border
211
+ for spine in ax.spines.values():
212
+ spine.set_visible(True)
213
+ spine.set_linestyle((0, (1, 2))) # Dotted line: (0, (on, off))
214
+ spine.set_edgecolor(BORDER_COLOR)
215
+ spine.set_linewidth(1.5)
216
+
217
+ ax.set_xticks([])
218
+ ax.set_yticks([])
219
+ ax.set_facecolor('none')
220
+
221
+ # --- Add date and title information to the top row ---
222
+ ax_date = fig.add_subplot(gs[0, :])
223
+ ax_date.text(0.01, 0.5, f"{date_str} {title}",
224
+ fontsize=12,
225
  color=DATE_COLOR,
226
+ fontweight='bold',
227
  ha='left',
228
  va='center',
229
+ transform=ax_date.transAxes)
230
+
231
+ # Hide the border for the date cell
232
+ for spine in ax_date.spines.values():
233
+ spine.set_visible(False)
234
+ ax_date.set_xticks([])
235
+ ax_date.set_yticks([])
236
+ ax_date.set_facecolor('none')
237
+
238
+ # Process both the PNG and PDF figures with the new layout
239
+ process_figure(png_fig)
240
+ process_figure(pdf_fig)
241
+
242
+ # --- Save PNG ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
  png_buffer = io.BytesIO()
244
+ # Use pad_inches=0 because we handled margins with subplots_adjust
245
+ png_fig.savefig(png_buffer, format='png', pad_inches=0)
246
  png_buffer.seek(0)
247
  png_base64 = base64.b64encode(png_buffer.getvalue()).decode()
248
+ plt.close(png_fig)
249
+
250
+ # --- Save PDF ---
251
  pdf_buffer = io.BytesIO()
252
+ with PdfPages(pdf_buffer) as pdf:
253
+ # Use pad_inches=0 for PDF as well
254
+ pdf.savefig(pdf_fig, pad_inches=0)
255
  pdf_buffer.seek(0)
256
  pdf_base64 = base64.b64encode(pdf_buffer.getvalue()).decode()
257
+ plt.close(pdf_fig)
 
258
 
259
  return {
260
  'png': f'data:image/png;base64,{png_base64}',
261
  'pdf': f'data:application/pdf;base64,{pdf_base64}'
262
  }
263
 
264
+ # --- PDF display function ---
265
  def display_pdf(base64_pdf):
266
+ """Embeds PDF in Streamlit for display"""
267
  pdf_display = f'<iframe src="{base64_pdf}" width="100%" height="800" type="application/pdf"></iframe>'
268
  return pdf_display
269
 
270
+ # Streamlit UI
271
  st.set_page_config(page_title="散厅时间快捷打印", layout="wide")
272
  st.title("散厅时间快捷打印")
273
 
 
 
 
274
  uploaded_file = st.file_uploader("上传【放映场次核对表.xls】文件", type=["xls"])
275
 
276
  if uploaded_file:
277
  part1, part2, date_str = process_schedule(uploaded_file)
278
 
279
  if part1 is not None and part2 is not None:
280
+ # Generate outputs containing both PNG and PDF data
281
  part1_output = create_print_layout(part1, "A", date_str)
282
  part2_output = create_print_layout(part2, "C", date_str)
283
 
 
286
  with col1:
287
  st.subheader("白班散场预览(时间 ≤ 17:30)")
288
  if part1_output:
289
+ # Use tabs to show both PDF and PNG previews
290
  tab1_1, tab1_2 = st.tabs(["PDF 预览", "PNG 预览"])
291
  with tab1_1:
292
  st.markdown(display_pdf(part1_output['pdf']), unsafe_allow_html=True)
 
298
  with col2:
299
  st.subheader("夜班散场预览(时间 > 17:30)")
300
  if part2_output:
301
+ # Use tabs to show both PDF and PNG previews
302
  tab2_1, tab2_2 = st.tabs(["PDF 预览", "PNG 预览"])
303
  with tab2_1:
304
  st.markdown(display_pdf(part2_output['pdf']), unsafe_allow_html=True)