如何使用Python将课表二维数组生成PDF或图片格式文件
推荐采用「动态生成HTML课表→直接合并导出为PDF」的方案,可直接复用你已有的HTML样式逻辑,不需要额外做图片转码,实现成本最低。
第一步:安装依赖库
使用weasyprint完成HTML转PDF,无需额外安装全局工具,执行以下命令安装:
pip install weasyprint
第二步:核心实现代码
from weasyprint import HTML # 你的课表原始数据,这里仅放示例,可替换为自己生成的完整数据 schedule_data = { "CS-3B": [['', '', 'DS ', '', 'COaAL '], ['', 'COaAL ', '', 'DS ', 'OOP '], ['DS-L ', 'DS-L ', 'OOP-L ', 'OOP-L ', 'FoM '], ['COaAL-L ', 'COaAL-L ', 'OOP ', '', ''], ['', 'FoM ', 'DE ', '', 'DE ']], "CS-1D": [['PF-L ', 'PF-L ', 'ECaC-L ', 'ItIaCT ECaC-L ', 'ItIaCT '], ['IS ', 'AP ', 'ECaC-L ', 'ECaC-L ', ''], ['PF ', 'PF ', '', 'ECaC ', ''], ['CaAG ', 'ECaC ', 'ECaC ', '', 'IS '], ['', 'CaAG ', '', 'ECaC ', 'AP ']] # 剩余班级数据自行补全即可 } # 固定配置 days = ["周一", "周二", "周三", "周四", "周五"] periods = ["I", "II", "III", "IV", "V"] # 公共CSS样式,可自行修改调整样式 common_css = """ <style> .center { text-align: center; } td { height: 75px; width: 150px; border: 1px solid #000; } h1 { page-break-before: always; /* 每个班级课表单独占一页 */ } h1:first-child { page-break-before: avoid; /* 第一个班级不需要前置分页 */ } table { border-collapse: collapse; margin: 0 auto; } </style> """ # 生成单个班级的HTML课表 def generate_class_html(class_name, schedule): html_parts = [f'<h1 class="center">{class_name}</h1>'] html_parts.append('<table><thead><tr><td class="center"><b>时段/日期</b></td>') # 拼接表头 for p in periods: html_parts.append(f'<td class="center"><b>{p}</b></td>') html_parts.append('</tr></thead><tbody>') # 遍历每天的课表 for day_idx, day_schedule in enumerate(schedule): html_parts.append(f'<tr><td class="center"><b>{days[day_idx]}</b></td>') period_idx = 0 while period_idx < 5: current_course = day_schedule[period_idx].strip() # 空时段直接渲染空单元格 if not current_course: html_parts.append('<td class="center"></td>') period_idx += 1 continue # 判断是否为连续实验课,需要合并单元格 colspan = 1 if current_course.endswith('-L') and period_idx + 1 < 5: next_course = day_schedule[period_idx+1].strip() if next_course == current_course: colspan = 2 # 处理同时段多门课,自动加水平分隔线 course_list = current_course.split() course_content = '<hr>'.join(course_list) html_parts.append(f'<td class="center" colspan="{colspan}">{course_content}</td>') period_idx += colspan html_parts.append('</tr>') html_parts.append('</tbody></table>') return ''.join(html_parts) # 拼接完整HTML内容 full_html = ['<!DOCTYPE html><html><head>', common_css, '</head><body>'] for class_name, sch in schedule_data.items(): full_html.append(generate_class_html(class_name, sch)) full_html.append('</body></html>') full_html_str = ''.join(full_html) # 导出为PDF HTML(string=full_html_str).write_pdf('所有班级课表.pdf')
功能说明
- 自动识别连续的-L结尾实验课,合并对应单元格,不会重复渲染被合并的时段
- 自动识别同一时段的多门课程,自动添加水平分隔线拆分单元格
- 每个班级的课表单独占PDF的一页,可直接打印
- 样式可通过修改CSS代码自定义,比如调整单元格大小、边框样式、字体等
如果确实需要生成单张图片,只需要额外安装imgkit库,把每个班级的HTML单独转成PNG图片即可,逻辑和转PDF完全一致。
内容的提问来源于stack exchange,提问作者Awais Shahid
相关产品推荐
相关产品推荐

