Codeigniter chuyển nội dung html thành pdf – convert html to pdf

0
376

Codeigniter chuyển nội dung html thành pdf – convert html to pdf. Có rất nhiều thư viện giúp thực hiện convert html to pdf. Quá trình sử dụng cá nhân nhantam cũng đã dùng tới 5,6 thư viện khác nhau, từ mpdf, html2pdf, phpwkhtmltopdf. Nhantam cảm thấy khá hài lòng với phpwkhtmltopdf, thư viện code php rất nhẹ bởi nó được hỗ trợ thêm từ file thực thi được cài đặt vào hệ điều hành bao gồm cả Windows và Linux.

1. Cài đặt

Để sử dụng phpwkhtmltopdf chúng ta cần cài đặt các bước như sau:

  • wkhtmltopdf: Thư viện thực thi để tạo tệp pdf từ tệp html: Mở webite wkhtmltopdf bạn chọn file cho hệ thống cần thực thi: Windows, MacOS, Ubunti, CentOs, …vv. https://wkhtmltopdf.org/downloads.html
  • phpwkhtmltopdf: Thư viện php để xử lý việc tạo tệp html sau đó thực thi wkhtmltopdf cli (commandline). Sử dụng composer để download thư viên PHP.
composer require mikehaertl/phpwkhtmltopdf

2. Cấu hình với Codeigniter

  1. Cài đặt wkhtmltopdf
  2. Sử dụng composer để downlaod thư viện PHP phpwkhtmltopdf
  3. Tạo file WKPDF.php trong thư viện của Codeigniter (application/libraries/)
  4. Tạo file config phpwkhtmltopdf.php trong thư mục config của Codeigniter (application/config/)
  5. Cập nhật file cấu hình phpwkhtmltopdf.php để phù hợp với ứng dụng code của bạn.

3. Cách sử dụng Controller

$this->load->library('WKPDF');
$pdf_content = "<h1>Hello World!</h1>";

$pdf_path_file = FCPATH."/file.pdf";

if (!$this->wkpdf->generate($pdf_content, $pdf_path_file, true)) {
    echo $this->wkpdf->getError();
}

3.1 file config

application/config/phpwkhtmltopdf.php

<?php
/**
 * phpwkhtmltopdf config
 * @link https://gist.github.com/DykiSA/1b768c3e296a983a0b398b2b3a08a07d
 * @source https://github.com/mikehaertl/phpwkhtmltopdf
 */

$config['phpwkhtmltopdf'] = array(
            'binary' => 'C:\Program Files (x86)\wkhtmltopdf\bin\wkhtmltopdf', /* path to the wkhtmltopdf executable - đường dẫn file thực thi được cài vào hệ điều hành Windows, nếu chạy trên Linux các bạn khai báo lại đường dẫn */
            'tmpDir'  => APPPATH . '../temp/', /* path to store generated temp files */
            'encoding' => 'UTF-8',
            'page-size' => 'A5',


            'no-outline', // Make Chrome not complain
            'margin-top'    => 0,
            'margin-right'  => 1,
            'margin-bottom' => 0,
            'margin-left'   => 1,

            'user-style-sheet' => FCPATH.'/assets/css/pdf.css', //Có thể khai báo css định dạng cho pdf

            "orientation" => "landscape",

            'ignoreWarnings' => true,
            'commandOptions' => array(
                'useExec' => true,      // Can help on Windows systems
                'procEnv' => array(
                    // Check the output of 'locale -a' on your system to find supported languages
                    'LANG' => 'vi-VN.utf-8', // Vietnamese
                ),
            ),
        )

3.2 file thư viện

appliction/libraries/WKPDF.php

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

use mikehaertl\wkhtmlto\Pdf as HtmlToPDF;

/**
 * A simple codeigniter library to help setup phpwkhtmltopdf
 * @link https://gist.github.com/DykiSA/
 */

class WKPDF
{
    private $CI;
    private $error;
    private $options;
    
    /**
     * intialize the class WKPDF
     * @param array $options      override options for phpwkhtmltopdf
     */
    public function __construct($options = [])
    {
        $this->CI =& get_instance();

        $this->initialize($options);
    }

    /**
     * initialize the library
     * @param array $options      override options for phpwkhtmltopdf
     */
    public function initialize($options = []) {
        // get options
        $this->CI->load->config('phpwkhtmltopdf');
        $this->options = $this->CI->config->item('phpwkhtmltopdf');

        if (is_array($options) && !empty($options)) {
            $this->options = array_merge($this->options, $options);
        }
    }
    
    /**
     * generating html
     * @param string $content       content of the pdf file
     * @param string $filename      will be shown as downloaded file
     * @param bool   $is_download   download = true/false
     * @return bool                 true if sucess otherwise false
     */
    public function generate($content, $filename, $is_download)
    {
        // clear error messgae
        $this->error = null;
        // init phpwkhtmltopdf
        $pdf = new HtmlToPDF($this->options);
        // add content
        $pdf->addPage($content);
        // generate pdf
        $is_success = false;
        if ($is_download) {
            $is_success = $pdf->send($filename);
        } else {
            $is_success = $pdf->send();
        }
        
        if (!$is_success) {
            // update error message
            $this->error = $pdf->getError();
        }
        return $is_success;
    }

    /**
     * get error message from last action
     * @return string       error message
     */
    public function getError()
    {
        return $this->error;
    }
    
}

Tham khảo thêm tại link: https://gist.github.com/DykiSA/1b768c3e296a983a0b398b2b3a08a07d

Chúc các bạn thành công

nhantam
Lập trình phần mềm trên nền web tại Panpic

BÌNH LUẬN

Vui lòng nhập bình luận của bạn
Vui lòng nhập tên của bạn ở đây

38 + = 40