report_teacher_weekly_stats_pdf.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /**
  3. * 生成「老师组卷 + 学情分析」周报 PDF(与 report_teacher_weekly_stats.php 同源数据)
  4. *
  5. * 用法:
  6. * php scripts/report_teacher_weekly_stats_pdf.php
  7. * php scripts/report_teacher_weekly_stats_pdf.php /path/to/out.pdf
  8. */
  9. use League\CommonMark\Environment\Environment;
  10. use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension;
  11. use League\CommonMark\Extension\GithubFlavoredMarkdownExtension;
  12. use League\CommonMark\MarkdownConverter;
  13. require __DIR__ . '/../vendor/autoload.php';
  14. ob_start();
  15. require __DIR__ . '/report_teacher_weekly_stats.php';
  16. $markdown = ob_get_clean();
  17. $env = new Environment([
  18. 'html_input' => 'allow',
  19. 'allow_unsafe_links' => false,
  20. ]);
  21. $env->addExtension(new CommonMarkCoreExtension());
  22. $env->addExtension(new GithubFlavoredMarkdownExtension());
  23. $converter = new MarkdownConverter($env);
  24. $bodyHtml = $converter->convert($markdown)->getContent();
  25. $css = <<<'CSS'
  26. <style>
  27. body { font-family: 'DejaVu Sans', sans-serif; font-size: 10pt; color: #111; }
  28. h2 { font-size: 14pt; margin: 0 0 8px 0; }
  29. h3 { font-size: 11pt; margin: 16px 0 8px 0; }
  30. blockquote { margin: 0 0 10px 0; padding: 6px 10px; background: #f9fafb; border-left: 3px solid #d1d5db; font-size: 9pt; color: #4b5563; }
  31. table { border-collapse: collapse; width: 100%; margin: 8px 0 12px 0; }
  32. th, td { border: 1px solid #d1d5db; padding: 4px 6px; vertical-align: top; }
  33. th { background: #f3f4f6; font-weight: 600; }
  34. </style>
  35. CSS;
  36. $html = '<!DOCTYPE html><html><head><meta charset="UTF-8">'.$css.'</head><body>'.$bodyHtml.'</body></html>';
  37. $defaultOut = storage_path('app/reports/teacher-weekly-stats-'.date('Y-m-d_His').'.pdf');
  38. $outPath = $argv[1] ?? $defaultOut;
  39. $dir = dirname($outPath);
  40. if (! is_dir($dir)) {
  41. mkdir($dir, 0755, true);
  42. }
  43. $mpdf = new \Mpdf\Mpdf([
  44. 'mode' => 'utf-8',
  45. 'format' => 'A4',
  46. 'margin_top' => 14,
  47. 'margin_bottom' => 14,
  48. 'margin_left' => 12,
  49. 'margin_right' => 12,
  50. 'default_font' => 'dejavusans',
  51. ]);
  52. $mpdf->WriteHTML($html);
  53. $mpdf->Output($outPath, \Mpdf\Output\Destination::FILE);
  54. $mdPath = preg_replace('/\.pdf$/i', '.md', $outPath);
  55. file_put_contents($mdPath, $markdown);
  56. fwrite(STDERR, "PDF: {$outPath}\nMD: {$mdPath}\n");