LEVEL 54 QUEST
PDF 리포트 자동 생성
TCPDF/FPDF를 활용한 월간 리포트 PDF 생성, 차트 이미지 삽입, 크론 자동 발송 시스템을 구현합니다.
TCPDF 라이브러리 설치 및 기본 사용법
TCPDF vs FPDF
PHP에서 PDF를 생성하는 대표 라이브러리로 TCPDF와 FPDF가 있습니다. TCPDF는 한글 지원이 뛰어나고 HTML을 직접 렌더링할 수 있어 SaaS 리포트 생성에 적합합니다. Composer로 간편하게 설치할 수 있습니다.
| 비교 항목 | TCPDF | FPDF |
|---|---|---|
| 한글 지원 | 기본 지원 (UTF-8) | 별도 폰트 설정 필요 |
| HTML 렌더링 | writeHTML() 지원 | 미지원 |
| 이미지 삽입 | 다양한 형식 지원 | JPG/PNG만 지원 |
| 파일 크기 | 큼 (~10MB) | 가벼움 (~80KB) |
| 설치 | composer require tecnickcom/tcpdf | composer require setasign/fpdf |
# Composer로 TCPDF 설치
$ composer require tecnickcom/tcpdf
// 기본 PDF 생성 예시
<?php
require_once 'vendor/autoload.php';
$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8');
// 문서 정보 설정
$pdf->SetCreator('SaaS Admin');
$pdf->SetAuthor('DevFoil SaaS');
$pdf->SetTitle('월간 사용 리포트');
// 헤더/푸터 비활성화 (커스텀 구현)
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
// 한글 폰트 설정
$pdf->SetFont('cid0jp', '', 12);
// 새 페이지 추가
$pdf->AddPage();
$pdf->Cell(0, 10, '월간 사용 리포트', 0, 1, 'C');
// PDF 출력
$pdf->Output('report.pdf', 'F'); // 'F'=파일저장, 'D'=다운로드, 'I'=브라우저
월간 리포트 PDF 템플릿 구현
// ReportGenerator.php - 월간 리포트 생성 클래스
class ReportGenerator {
private $pdf;
private $pdo;
public function __construct($pdo) {
$this->pdo = $pdo;
$this->pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8');
$this->pdf->setPrintHeader(false);
$this->pdf->setPrintFooter(false);
$this->pdf->SetAutoPageBreak(true, 15);
}
/**
* 커버 페이지 생성
*/
private function addCoverPage($customerName, $reportMonth) {
$this->pdf->AddPage();
// 배경색
$this->pdf->SetFillColor(15, 23, 42);
$this->pdf->Rect(0, 0, 210, 297, 'F');
// 제목
$this->pdf->SetTextColor(248, 250, 252);
$this->pdf->SetFont('cid0jp', 'B', 28);
$this->pdf->SetY(100);
$this->pdf->Cell(0, 15, '월간 사용 리포트', 0, 1, 'C');
// 고객명 & 날짜
$this->pdf->SetFont('cid0jp', '', 16);
$this->pdf->SetTextColor(148, 163, 184);
$this->pdf->Cell(0, 12, $customerName, 0, 1, 'C');
$this->pdf->Cell(0, 10, $reportMonth, 0, 1, 'C');
}
/**
* KPI 요약 페이지
*/
private function addKPISummary($data) {
$this->pdf->AddPage();
$this->pdf->SetFont('cid0jp', 'B', 20);
$this->pdf->SetTextColor(30, 41, 59);
$this->pdf->Cell(0, 12, '핵심 지표 요약', 0, 1);
$this->pdf->Ln(5);
// KPI 카드를 HTML로 렌더링
$html = '
<table cellpadding="10">
<tr>
<td bgcolor="#eff6ff" width="50%">
<b>총 API 호출</b><br>
<span style="font-size:24px; color:#3b82f6;">'
. number_format($data['total_calls'])
. '</span></td>
<td bgcolor="#f0fdf4" width="50%">
<b>성공률</b><br>
<span style="font-size:24px; color:#10b981;">'
. $data['success_rate']
. '%</span></td>
</tr>
<tr>
<td bgcolor="#fefce8" width="50%">
<b>평균 응답시간</b><br>
<span style="font-size:24px; color:#f59e0b;">'
. $data['avg_response']
. 'ms</span></td>
<td bgcolor="#fdf2f8" width="50%">
<b>사용량 대비 한도</b><br>
<span style="font-size:24px; color:#ec4899;">'
. $data['usage_percent']
. '%</span></td>
</tr>
</table>';
$this->pdf->writeHTML($html, true, false, true);
}
/**
* 사용량 상세 테이블 페이지
*/
private function addUsageTable($dailyData) {
$this->pdf->AddPage();
$this->pdf->SetFont('cid0jp', 'B', 20);
$this->pdf->Cell(0, 12, '일별 사용량 상세', 0, 1);
$this->pdf->Ln(5);
$html = '<table border="1" cellpadding="5">
<tr bgcolor="#f1f5f9">
<th width="25%"><b>날짜</b></th>
<th width="20%"><b>호출수</b></th>
<th width="20%"><b>에러수</b></th>
<th width="15%"><b>에러율</b></th>
<th width="20%"><b>평균응답(ms)</b></th>
</tr>';
foreach ($dailyData as $row) {
$errorRate = $row['total_calls'] > 0
? round($row['errors'] / $row['total_calls'] * 100, 1)
: 0;
$bgColor = $errorRate > 5 ? 'bgcolor="#fef2f2"' : '';
$html .= "<tr {$bgColor}>
<td>{$row['log_date']}</td>
<td align='right'>" . number_format($row['total_calls']) . "</td>
<td align='right'>{$row['errors']}</td>
<td align='right'>{$errorRate}%</td>
<td align='right'>{$row['avg_ms']}ms</td>
</tr>";
}
$html .= '</table>';
$this->pdf->writeHTML($html, true, false, true);
}
/**
* 리포트 생성 실행
*/
public function generate($customerId, $month) {
$customer = $this->getCustomerInfo($customerId);
$kpiData = $this->getKPIData($customerId, $month);
$dailyData = $this->getDailyData($customerId, $month);
$this->addCoverPage($customer['company_name'], $month);
$this->addKPISummary($kpiData);
$this->addUsageTable($dailyData);
$filename = "reports/report_{$customerId}_{$month}.pdf";
$this->pdf->Output($filename, 'F');
return $filename;
}
}
🔒
여기까지는 미리보기입니다
PDF 리포트 자동 생성
무료 가입하면 이어서 볼 수 있고, 강의를 완료할 때마다 XP와 레벨이 쌓입니다.
Google로 3초 만에 시작 →🧵 Threads로 시작무료 공개 강의 둘러보기 (Lv.1~3)무료 가입하면 이어서 볼 수 있고, 강의를 완료할 때마다 XP와 레벨이 쌓입니다.