医院Web开发实战:PDF报告生成背后的那些坑
引言
为什么PDF报告生成这么难?
我踩过的三个大坑
坑一:字体兼容性问题
坑二:表格数据对齐问题
坑三:图片嵌入导致的性能问题
我的实战代码模板
/*** 生成医疗PDF报告的核心函数* @param array $reportData 报告数据* @param array $images 图片数据(可空)* @return string PDF文件路径*/functiongenerateMedicalPDF($reportData, $images = []) {// 1. 初始化PDF生成器$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);// 2. 设置字体(解决坑一)$pdf->SetFont('stsongstdlight', '', 12);// 3. 生成文字内容$pdf->AddPage();$pdf->writeHTML($this->buildReportHTML($reportData));// 4. 处理图片(解决坑三)if(!empty($images)) {foreach($images as $img) {$compressedImg = $this->compressMedicalImage($img);$pdf->Image($compressedImg['clipath'], 15, $pdf->GetY(), 180, 0, '', '', 'T', false, 300, '', false, false, 0, false, false, false);$pdf->Ln(10);}}// 5. 输出PDF$filename = '/tmp/report_' . time() . '.pdf';$pdf->Output($filename, 'F');return $filename;}/*** 构建报告HTML内容,处理表格对齐(解决坑二)*/functionbuildReportHTML($data) {$html = '<h2>' . $data['title'] . '</h2>';// 固定列宽的表格设计$html .= '<table style="width:100%; border-collapse:collapse;">';$html .= '<tr><th style="width:30%; text-align:left;">项目</th>';$html .= '<th style="width:20%; text-align:right;">数值</th>';$html .= '<th style="width:30%; text-align:left;">单位</th>';$html .= '<th style="width:20%; text-align:left;">参考范围</th></tr>';foreach($data['items'] as $item) {$html .= '<tr>';$html .= '<td style="width:30%;">' . $item['name'] . '</td>';$html .= '<td style="width:20%; text-align:right;">' . $item['value'] . '</Elev>';$html .= '<td style="width:30%;">' . $item['unit'] . '</td>';$html .= '<td style="width:20%;">' . $item['range'] . '</td>';$html .= '</tr>';}$html .= '</table>';return $html;}
总结与建议
后续计划
|
话题 |
预计发布时间 |
|
预约挂号系统的并发锁处理 |
4月1日 |
|
微信支付对账的自动化方案 |
4月8日 |
|
小程序海报生成的技术优化 |
4月15日 |
夜雨聆风