728x90

php 에서도 가능하고 npm 으로도 설치가 가능해서 vue 나 react 에서도 가능한 스크립트다. 

 

상단에 아래와 같이 스크립트 url 을 추가해 주고 인쇄 되어야 하는 content 같은 div 아이디 값을 지정해 주고 .save 를 주면 pdf 로 다운로드가 가능하다. pdf 다운로드는 실제 변환되는 걸로 코딩을 하려면 무척 시간이 많이 걸리고 css 스타일도 inline 으로 밖아야 해서 코드도 무척 길어 지는데 아래와 같은 스크립트는 특정 div 만도 가능해서 좋은거 같다. 

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>

 

pdf 다운로드 기능이 필요 하다면 참고해 보면 좋겠다.

var element = document.getElementById('content'); // PDF로 변환할 HTML 요소
html2pdf()
    .from(element)
    .save('document.pdf'); // 저장할 파일 이름

 

npm install html2pdf.js

 

728x90
728x90

php 에서 pdf 파일로 다운로드 하는 방법은 몇가지가 있는데 그중 컴포저를 설치 했을 경우의 예시를 들어 본다. 아래와 같이 tecnickcom/tcpdf 로 컴포저를 설치하고 적용 방법은 아래에 3가지 경우로 예시를 메모해 본다. 

 

 

보통은 window.print() 로 날리면 해당 화면이 출력하기 모듈이 뜨면서 거기서 pdf 로 바로 다운로드가 가능한데 pdf 로 바로 다운이 되어야 하는 경우는 아래와 같이 수정을 해야 한다.  

composer require tecnickcom/tcpdf

 

1. tcpdf 를 사용해서 $pdf 로 생성하는 방법 

<?php
require_once('vendor/autoload.php');

// PDF 문서 생성
$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 파일 다운로드
$pdf->Output('견적서.pdf', 'D');
?>

 

2. html 태그를 css 파일을 적용해서 중간에 추가 하는 경우

<?php
require_once('vendor/autoload.php');

// PDF 문서 생성
$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 파일 포함
$css = file_get_contents('path/to/styles.css'); // 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;">
';

// HTML 콘텐츠 출력
$pdf->writeHTML($html, true, false, true, false, '');

// PDF 파일 다운로드
$pdf->Output('견적서.pdf', 'D');
?>

 

3. html 코드가 있는 php 파일을 include 해서 적용하는 방법

<?php
require_once('vendor/autoload.php');

// PDF 문서 생성
$pdf = new TCPDF();

// 문서 정보 설정
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Your Name');
$pdf->SetTitle('견적서');
$pdf->SetSubject('견적서 예제');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');

// 페이지 추가
$pdf->AddPage();

// HTML 파일 포함
ob_start(); // 출력 버퍼링 시작
include('aa.php'); // aa.php 파일 포함
$html = ob_get_clean(); // 버퍼 내용을 변수로 저장하고 버퍼 비우기

// HTML 콘텐츠 출력
$pdf->writeHTML($html, true, false, true, false, '');

// PDF 파일 다운로드
$pdf->Output('견적서.pdf', 'D');
?>

 

각 상황에 맞게 사용하는 것이 좋겠다. 컴포저 설치시에는 실서버와 동일한 php 버전에서 컴포저를 설치해야 버전 이슈가 없는 점은 참고해야 한다. 

728x90
728x90

php 에서 작업을 하다 보면 예전에는 엑셀 다운로드가 많았지만 요즘에는 pdf 로 다운 받기를 원한다.  tcpdf 사이트에서 무료로 다은 받을 수 있지만 한글이 깨지는 오류가 있다. 한글 폰트가 있어야지만 한글이 깨지지 않기 때문에 nanumbarungothicyethangul.php 파일과 폰트를 다운로드 해서 설정해주고 아래와 같이 코딩해주면 html 코드 그대로 pdf 파일로 다운로드가 가능하다. 

 

 

단 css 파일에 정의된 스타일은 사용이 되지 않고 태그 자체에 style 을 하드코딩으로 해주어야 한다. 그래서 테이블 코딩으로 하는것이 레이아웃이 깨지거나 하지 않아서 해당 출력물은 테이블 코딩을 별도로 진행하는 것이 좋다. 

<?php
	require_once "./tcpdf/tcpdf_import.php";  

/**
 * 헤더 변경을 위한 class 상속 후 재 정의
 */
class MYPDF extends TCPDF {

    //Page header
    public function Header() {
        // Logo
        $image_file = K_PATH_IMAGES.'logo_example.jpg';
        $this->Image($image_file, 10, 10, 15, '', 'PNG', '', 'T', false, 300, '', false, false, 0, false, false, false);
        // Set font
        $this->SetFont('helvetica', 'B', 15);

        // Title
        //$this->Cell(0, 15, 'www.example.com', 0, false, 'C', 0, '', 0, false, 'M', 'M');
    }
}

$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, "UTF-8", false);
$pdf->SetCreator(PDF_CREATOR);

// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);

// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

$pdf->SetFont('nanumbarungothicyethangul', '', 12);
$pdf->AddPage();
//$pdf->writeHTMLCell(0, 0, "", "", $html, 0, 1, 0, true, "", true);










include $_SERVER["DOCUMENT_ROOT"]."/include/dbopen.php";
$sql = " select * from dual";

ob_start();
?>

<!doctype html>
<html><head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge"/> 
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>PDF 다운로드 예제</title>
</head>
<body>

<style type="text/css">
.table th, .table td {
    padding: 10px 16px;
    font-size: 15px;
    border: 1px solid #cccccc;
}	
</style>
				<p style="text-align:center; margin-bottom:50px; font-size:30px;">견적서</p>
 
                <table class="table">
                  <colgroup><col width="10%"><col width="10%"><col width="50%"><col></colgroup>
                  <tr>
                    <th style="padding: 10px 16px; font-size: 15px; border: 1px solid #cccccc;"rowspan="2">확인란</th>
                    <td rowspan="2">
                      <img src="도메인경로부터/img/img_confirm.png" style="width:80px;">
                    </td>                        
                    <td>데이터 내용 </td>
                  </tr>
                </table>
  
            </div>

</body>
</html>
<?php
$pdfData = ob_get_contents();
ob_end_clean();
 

// 테이블을 출력할 때 사용하는 방법
$pdf -> writeHTML($pdfData, true, false, false, false, '');

$pdf->Output(getcwd()."/example_test_01.pdf", "FI");

?>
728x90

+ Recent posts