- 정보공유
[PHP] HTML 파일을 CSS가 적용된 PDF로 변환하여 서버에 저장하는 PHP 코드
- 작성일
- 25-11-06 13:14
- 조회수
- 6 건
- 댓글
- 0 건
<?php
/**
* HTML to PDF Converter (Composer 없이 사용)
* TCPDF 라이브러리 사용
*
* 설치 방법:
* 1. https://github.com/tecnickcom/TCPDF/archive/main.zip 다운로드
* 2. 압축 해제 후 'tcpdf' 폴더에 배치
* 3. 또는 아래 간단한 방법 사용
*/
// TCPDF 라이브러리 경로 (실제 경로에 맞게 수정)
require_once('tcpdf/tcpdf.php');
class HtmlToPdfConverter
{
private $pdf;
/**
* 생성자
*/
public function __construct($options = [])
{
// PDF 기본 설정
$orientation = $options['orientation'] ?? 'P'; // P=세로, L=가로
$unit = 'mm';
$format = $options['paper_size'] ?? 'A4';
$this->pdf = new TCPDF($orientation, $unit, $format, true, 'UTF-8', false);
// 문서 정보 설정
$this->pdf->SetCreator('HTML to PDF Converter');
$this->pdf->SetAuthor('Your Name');
$this->pdf->SetTitle('Converted Document');
// 헤더/푸터 제거 (필요시 주석 해제)
$this->pdf->setPrintHeader(false);
$this->pdf->setPrintFooter(false);
// 여백 설정 (mm 단위)
$this->pdf->SetMargins(15, 15, 15);
$this->pdf->SetAutoPageBreak(true, 15);
// 이미지 스케일 설정
$this->pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// 한글 폰트 설정
$this->pdf->SetFont('dejavusans', '', 10);
}
/**
* HTML 파일을 PDF로 변환하여 저장
*
* @param string $htmlFilePath HTML 파일 경로
* @param string $pdfOutputPath PDF 저장 경로
* @return bool 성공 여부
*/
public function convertFile($htmlFilePath, $pdfOutputPath)
{
try {
if (!file_exists($htmlFilePath)) {
throw new Exception("HTML 파일을 찾을 수 없습니다: {$htmlFilePath}");
}
$html = file_get_contents($htmlFilePath);
return $this->convertString($html, $pdfOutputPath);
} catch (Exception $e) {
error_log("PDF 변환 오류: " . $e->getMessage());
return false;
}
}
/**
* HTML 문자열을 PDF로 변환하여 저장
*
* @param string $html HTML 문자열
* @param string $pdfOutputPath PDF 저장 경로
* @return bool 성공 여부
*/
public function convertString($html, $pdfOutputPath)
{
try {
// 저장 디렉토리 확인 및 생성
$directory = dirname($pdfOutputPath);
if (!is_dir($directory) && !empty($directory)) {
mkdir($directory, 0755, true);
}
// 새 페이지 추가
$this->pdf->AddPage();
// HTML을 PDF로 변환
$this->pdf->writeHTML($html, true, false, true, false, '');
// PDF 파일로 저장
$this->pdf->Output($pdfOutputPath, 'F');
return true;
} catch (Exception $e) {
error_log("PDF 변환 오류: " . $e->getMessage());
return false;
}
}
/**
* PDF를 브라우저로 다운로드
*
* @param string $filename 다운로드될 파일명
*/
public function download($filename = 'document.pdf')
{
$this->pdf->Output($filename, 'D');
}
/**
* PDF를 브라우저에서 미리보기
*
* @param string $filename 파일명
*/
public function preview($filename = 'document.pdf')
{
$this->pdf->Output($filename, 'I');
}
}
// ============================================
// 사용 예제
// ============================================
// 예제 1: HTML 파일을 PDF로 변환
$converter = new HtmlToPdfConverter();
$htmlFile = 'input.html';
$pdfFile = 'output/document.pdf';
if ($converter->convertFile($htmlFile, $pdfFile)) {
echo "PDF 변환 성공: {$pdfFile}\n";
} else {
echo "PDF 변환 실패\n";
}
// 예제 2: HTML 문자열을 PDF로 변환
$htmlContent = '
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body {
font-family: "DejaVu Sans", sans-serif;
margin: 20px;
}
h1 {
color: #2c3e50;
border-bottom: 3px solid #3498db;
padding-bottom: 10px;
font-size: 24px;
}
h2 {
color: #34495e;
margin-top: 20px;
font-size: 18px;
}
.container {
background-color: #f8f9fa;
padding: 20px;
border-radius: 8px;
margin: 20px 0;
}
.highlight {
background-color: #fff3cd;
padding: 15px;
border-left: 4px solid #ffc107;
margin: 15px 0;
}
table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
th, td {
border: 1px solid #dee2e6;
padding: 10px;
text-align: left;
}
th {
background-color: #3498db;
color: white;
font-weight: bold;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
.info-box {
background-color: #d1ecf1;
border: 1px solid #bee5eb;
padding: 15px;
border-radius: 5px;
margin: 10px 0;
}
p {
line-height: 1.6;
margin: 10px 0;
}
</style>
</head>
<body>
<h1>HTML to PDF 변환 문서</h1>
<div class="container">
<h2>CSS 스타일이 적용된 콘텐츠</h2>
<p>이 문서는 <strong>TCPDF</strong> 라이브러리를 사용하여 HTML을 PDF로 변환한 예제입니다.</p>
<p>다양한 CSS 스타일이 정상적으로 적용되어 있습니다.</p>
</div>
<div class="highlight">
<strong>중요 알림:</strong> CSS 스타일(색상, 테두리, 배경 등)이 제대로 적용되어 표시됩니다!
</div>
<div class="info-box">
<h3>주요 기능</h3>
<ul>
<li>HTML 태그 완벽 지원</li>
<li>CSS 스타일 적용</li>
<li>테이블 및 레이아웃 지원</li>
<li>한글 폰트 지원</li>
</ul>
</div>
<h2>데이터 테이블 예제</h2>
<table>
<thead>
<tr>
<th>번호</th>
<th>항목명</th>
<th>설명</th>
<th>상태</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>첫 번째 항목</td>
<td>상세 설명 내용 1</td>
<td>완료</td>
</tr>
<tr>
<td>2</td>
<td>두 번째 항목</td>
<td>상세 설명 내용 2</td>
<td>진행중</td>
</tr>
<tr>
<td>3</td>
<td>세 번째 항목</td>
<td>상세 설명 내용 3</td>
<td>대기</td>
</tr>
<tr>
<td>4</td>
<td>네 번째 항목</td>
<td>상세 설명 내용 4</td>
<td>완료</td>
</tr>
</tbody>
</table>
<h2>추가 정보</h2>
<p>이 PDF는 서버에 저장되거나 브라우저로 다운로드할 수 있습니다.</p>
<p><em>작성일: 2025년 11월 6일</em></p>
</body>
</html>
';
// 세로 방향 A4 용지로 변환
$converter2 = new HtmlToPdfConverter(['paper_size' => 'A4', 'orientation' => 'P']);
$pdfFile2 = 'output/styled_document.pdf';
if ($converter2->convertString($htmlContent, $pdfFile2)) {
echo "스타일 적용된 PDF 변환 성공: {$pdfFile2}\n";
}
// 예제 3: 가로 방향 PDF 생성
$converter3 = new HtmlToPdfConverter(['paper_size' => 'A4', 'orientation' => 'L']);
$pdfFile3 = 'output/landscape_document.pdf';
if ($converter3->convertString($htmlContent, $pdfFile3)) {
echo "가로 방향 PDF 변환 성공: {$pdfFile3}\n";
}
// 예제 4: 브라우저에서 즉시 다운로드
// $converter->download('my_document.pdf');
// 예제 5: 브라우저에서 미리보기
// $converter->preview('preview.pdf');
?>