public ResponseEntity<byte[]> exportResource(int lessonPlanId) {
try {
// 获取课程计划
LessonPlan lessonPlan = lessonPlanService.selectById(lessonPlanId);
if (lessonPlan == null) {
log.error("课程计划不存在: lessonPlanId={}", lessonPlanId);
return ResponseEntity.badRequest().body(null); // 课程计划不存在
}
// 记录内容
log.info("课程计划标题: {}", lessonPlan.getTitle());
log.info("课程计划内容: {}", lessonPlan.getContent());
// 创建 PDF 文件流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter writer = new PdfWriter(baos);
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf);
// 设置支持中文的字体
PdfFont font = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H");
document.setFont(font);
// 添加课程计划标题和内容
document.add(new Paragraph("课程计划: " + lessonPlan.getTitle()).setFont(font));
document.add(new Paragraph("内容: " + lessonPlan.getContent()).setFont(font));
// 关闭文档
document.close();
// 设置 HTTP 头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
headers.setContentDispositionFormData("attachment", "lesson_plan_" + lessonPlanId + ".pdf");
// 返回文件流
return ResponseEntity.ok()
.headers(headers)
.body(baos.toByteArray());
} catch (Exception e) {
log.error("生成 PDF 失败: lessonPlanId={}, 错误: {}", lessonPlanId, e.getMessage());
e.printStackTrace();
return ResponseEntity.status(500).body(null); // 服务器错误
}
}
04-04
2540
