CodeIgniter3

23. [CodeIgniter3] Dompdf를 사용하여 HTML을 PDF로 변환하기

drizzle0925 2022. 1. 7. 12:49
728x90

PDF는 웹 애플리케이션에서 아카이브를 만드는 데 가장 많이 활용됩니다.

PDF 레코드는 문서의 정보 팩을 다운로드하는 간단하고 사용하기 쉬운 접근 방식을 제공합니다.

웹사이트 페이지 콘텐츠를 다운로드하기 전에 내용을 HTML에서 PDF로 변경해야 합니다.

HTMl에서 PDF로의 변경은 PHP 라이브러리를 활용하여 효과적으로 수행할 수 있습니다.

 

 

Dompdf는 HTML 콘텐츠에서 PDF를 만드는데 도움이 되는 PHP 라이브러리입니다. Dompdf를 사용하여 PHP에서 HTML을 PDF로 변경하는 것은 어려운 일입니다. 응용 프로그램이 CodeIgniter와 함께 작동하는 경우 Dompdf를 사용하여 PDF를 생성하기 위해 PDF 라이브러리를 만들어야 합니다. HTML을 PDF로 변경하고 CodeIgniter에서 Dompdf를 활용하여 PDF를 생성하는 방법에 대해서 알아보겠습니다.

 

Database

아래 쿼리를 이용하여 `tbl_users` 테이블을 생성합니다.

CREATE TABLE IF NOT EXISTS `tbl_users` (
  `UserID` int NOT NULL primary key auto_increment,
  `Name` varchar(250) NOT NULL,
  `Address` text NOT NULL,
  `City` varchar(250) NOT NULL,
  `PostalCode` varchar(30) NOT NULL,
  `Country` varchar(100) NOT NULL,
  `images` varchar(255) NOT NULL 
);

 

 

Dompdf 라이브러리 다운로드

dompdf 라이브러리를 사용하기 위해서는 아래 사이트에서 라이브러리를 다운로드하아야 합니다.

https://github.com/dompdf/dompdf/releases

 

Releases · dompdf/dompdf

HTML to PDF converter for PHP. Contribute to dompdf/dompdf development by creating an account on GitHub.

github.com

 

빨간색으로 체크된 부분을 클릭하여 라이브러리를 다운로드합니다.

 

다운로드한 파일은 application/libraries 폴더에서 압축 해제합니다.

 

Library

application/libraries/Pdf.php 파일을 만들고 아래 코드를 입력합니다.

<?php 
if(!defined('BASEPATH')) exit('No direct script access allowed');

require_once dirname(__FILE__).'/dompdf/autoload.inc.php';

use Dompdf\Dompdf;

class Pdf
{
    public function __construct()
    {
        require_once dirname(__FILE__).'/dompdf/autoload.inc.php';
        $pdf = new DOMPDF();
        $CI =& get_instance();
        $CI->dompdf = $pdf;
    }
}
?>

 

Controller

application/controllers/PdfController.php 파일을 만들고 아래 코드를 입력합니다.

<?php 
defined('BASEPATH') OR exit('No direct script access allowed');

class PdfController extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('PdfModel');
        $this->load->library('pdf');
    }

    public function index()
    {
        $data['customer_data'] = $this->PdfModel->showRecord();
        $this->load->view('htmltopdf', $data);
    }

    public function details()
    {
        if($this->uri->segment(3))
        {
            $customer_id = $this->uri->segment(3);
            $data['customer_details'] = $this->PdfModel->show_single_details($customer_id);
            $this->load->view('htmltopdf', $data);
        }
    }

    public function pdfdetails()
    {
        if($this->uri->segment(3))
        {
            $customer_id = $this->uri->segment(3);
            $html_content = '<h3 align="center">Generate PDF using Dompdf</h3>';
            $html_content .= $this->PdfModel->show_single_details($customer_id);
            $this->dompdf->loadHtml($html_content);
            $this->dompdf->set_option('isRemoteEnabled', TRUE);
            $this->dompdf->render();
            $this->dompdf->stream("".$customer_id.".pdf", array("Attachment"=>0));
        }
    }
}
?>

 

Model

application/models/PdfModel.php 파일을 만들고 아래 코드를 입력합니다.

<?php 
defined('BASEPATH') or exit('No direct script access allowed');

class PdfModel extends CI_Model
{
    public function showRecord()
    {
        return $this->db->get('tbl_users');
    }

    public function show_single_details($customer_id)
    {
        $this->db->where('UserID', $customer_id);
        $data = $this->db->get('tbl_users');
        $output = '<table width="100%" cellspacing="5" cellpadding="5">';
        foreach($data->result() as $row)
        {
            $output .= '
            <tr>
                <td width="25%"><img src="'.base_url().'images/'.$row->images.'" /></td>
                <td width="75%">
                    <p><b>Name: </b>'.$row->Name.'</p>
                    <p><b>Address: </b>'.$row->Address.'</p>
                    <p><b>City: </b>'.$row->City.'</p>
                    <p><b>Postal Code: </b>'.$row->PostalCode.'</p>
                    <p><b>Country: </b>'.$row->Country.'</p>
                </td>
            </tr>
            ';
        }
        $output .= '</table>';
        return $output;
    }
}
?>

 

View

application/views/htmltopdf.php 파일을 만들고 아래 코드를 입력합니다.

<!DOCTYPE html>
<html lang="ko">
<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>Generate PDF using Dompdf</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</head>
<body>
    <div class="container box">
        <h2 class="text-center text-primary">Generate PDF using Dompdf</h2>
        <br />
        <?php 
        if(isset($customer_data))
        {
        ?>
            <table class="table table-bordered table-striped">
                <tr>
                    <td>ID</td>
                    <td>Name</td>
                    <td>View</td>
                    <td>View in PDF</td>
                </tr>
                <?php 
                foreach($customer_data->result() as $row)
                {
                    echo '
                    <tr>
                        <td>'.$row->UserID.'</td>
                        <td>'.$row->Name.'</td>
                        <td><a href="'.base_url().'pdfcontroller/details/'.$row->UserID.'">View</a></td>
                        <td><a href="'.base_url().'pdfcontroller/pdfdetails/'.$row->UserID.'">View in PDF</a></td>
                    </tr>
                    ';
                }
                ?>
            </table>
        <?php
        }
        if(isset($customer_details))
        {
            echo $customer_details;
        }
        ?>
    </div>
</body>
</html>

 

아래 URL로 이동합니다.

localhost/pdfcontroller/

 

테스트를 위해 데이터를 추가합니다.

아래 쿼리를 실행합니다.

INSERT INTO tbl_users(Name,Address,City,PostalCode,Country,images) VALUES('minji','gangnam','seoul','11053','korea','minji.jpeg');

 

 

images/minji.jpeg 파일을 저장합니다.

 

아래 URL로 이동합니다.

localhost/pdfcontroller/

 

View를 클릭하면 아래와 같습니다.

 

View in PDF를 클릭하면 아래와 같습니다.

 

Github : https://github.com/jun0925/study/commit/b9a072afbc557151afcaae31792177a49aef9436

728x90