php 에서 pdf 파일로 다운로드 하는 방법은 몇가지가 있는데 그중 컴포저를 설치 했을 경우의 예시를 들어 본다. 아래와 같이 tecnickcom/tcpdf 로 컴포저를 설치하고 적용 방법은 아래에 3가지 경우로 예시를 메모해 본다.
보통은 window.print() 로 날리면 해당 화면이 출력하기 모듈이 뜨면서 거기서 pdf 로 바로 다운로드가 가능한데 pdf 로 바로 다운이 되어야 하는 경우는 아래와 같이 수정을 해야 한다.
composer require tecnickcom/tcpdf
1. tcpdf 를 사용해서 $pdf 로 생성하는 방법
<?php
require_once('vendor/autoload.php');
$pdf = new TCPDF();
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Your Name');
$pdf->SetTitle('견적서');
$pdf->SetSubject('견적서 예제');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
$pdf->AddPage();
$pdf->SetFont('helvetica', 'B', 20);
$pdf->Cell(0, 10, '견적서', 0, 1, 'C');
$pdf->Ln(10);
$tableData = [
['항목', '수량', '단가', '합계'],
['상품 A', '2', '50000', '100000'],
['상품 B', '1', '30000', '30000'],
['상품 C', '3', '20000', '60000'],
];
$pdf->SetFont('helvetica', 'B', 12);
$pdf->SetFillColor(200, 220, 255);
$pdf->Cell(40, 10, $tableData[0][0], 1, 0, 'C', 1);
$pdf->Cell(40, 10, $tableData[0][1], 1, 0, 'C', 1);
$pdf->Cell(40, 10, $tableData[0][2], 1, 0, 'C', 1);
$pdf->Cell(40, 10, $tableData[0][3], 1, 1, 'C', 1);
$pdf->SetFont('helvetica', '', 12);
$pdf->SetFillColor(255, 255, 255);
foreach ($tableData as $key => $row) {
if ($key > 0) {
$pdf->Cell(40, 10, $row[0], 1, 0, 'C', 1);
$pdf->Cell(40, 10, $row[1], 1, 0, 'C', 1);
$pdf->Cell(40, 10, $row[2], 1, 0, 'C', 1);
$pdf->Cell(40, 10, $row[3], 1, 1, 'C', 1);
}
}
$pdf->Ln(10);
$imageFile = 'path/to/your/seal.png';
$pdf->Image($imageFile, 150, 250, 40, 40, 'PNG', '', '', false, 300, '', false, false, 0, false, false, false);
$pdf->Output('견적서.pdf', 'D');
?>
2. html 태그를 css 파일을 적용해서 중간에 추가 하는 경우
<?php
require_once('vendor/autoload.php');
$pdf = new TCPDF();
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Your Name');
$pdf->SetTitle('견적서');
$pdf->SetSubject('견적서 예제');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
$pdf->AddPage();
$css = file_get_contents('path/to/styles.css');
$html = '
<style>' . $css . '</style>
<h1>견적서</h1>
<table>
<thead>
<tr>
<th>항목</th>
<th>수량</th>
<th>단가</th>
<th>합계</th>
</tr>
</thead>
<tbody>
<tr>
<td>상품 A</td>
<td>2</td>
<td>50000</td>
<td>100000</td>
</tr>
<tr>
<td>상품 B</td>
<td>1</td>
<td>30000</td>
<td>30000</td>
</tr>
<tr>
<td>상품 C</td>
<td>3</td>
<td>20000</td>
<td>60000</td>
</tr>
</tbody>
</table>
<br>
<img src="path/to/your/seal.png" alt="직인" width="100" height="100" style="float:right;">
';
$pdf->writeHTML($html, true, false, true, false, '');
$pdf->Output('견적서.pdf', 'D');
?>
3. html 코드가 있는 php 파일을 include 해서 적용하는 방법
<?php
require_once('vendor/autoload.php');
$pdf = new TCPDF();
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Your Name');
$pdf->SetTitle('견적서');
$pdf->SetSubject('견적서 예제');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
$pdf->AddPage();
ob_start();
include('aa.php');
$html = ob_get_clean();
$pdf->writeHTML($html, true, false, true, false, '');
$pdf->Output('견적서.pdf', 'D');
?>
각 상황에 맞게 사용하는 것이 좋겠다. 컴포저 설치시에는 실서버와 동일한 php 버전에서 컴포저를 설치해야 버전 이슈가 없는 점은 참고해야 한다.