Generate dan save file PDF menggunakan DOMPDF di Codeigniter

Feb

Generate dan save file PDF menggunakan DOMPDF di Codeigniter

Di sini kita akan coba membuat file pdf di codeigniter menggunakan library DOMPDF. Proses yang akan kita buat adalah nantinya aplikasi mengenerate file pdf dan menyimpan file pdf tsb di server untuk bisa di download oleh user.

1. Install DOMPDF di composer

Buka file composer.json di root folder codeigniter Anda, pada bagian required tambahkan baris “dompdf/dompdf”: “dev-master”, lalu buka terminal dan ketik “composer update

2. Buat file GeneratePDF.php

Buat file GeneratePDF.php di folder application/libraries. tuliskan kode berikut :

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

use Dompdf\Adapter\CPDF;
use Dompdf\Dompdf;
use Dompdf\Exception;

class Createpdf
{

public function generate($html, $filename=”, $stream=TRUE, $paper = ‘A4’, $orientation = “portrait”)
{
define(‘DOMPDF_ENABLE_AUTOLOAD’, false);
$dompdf = new DOMPDF();
$dompdf->loadHtml($html);
$dompdf->setPaper($paper, $orientation);
$dompdf->render();
if ($stream) { $dompdf->stream($filename, array(“Attachment” => 0)); } else { return $dompdf->output(); }
}

public function save($html, $filename=”, $paper = ‘A4’, $orientation = “portrait”)
{
define(‘DOMPDF_ENABLE_AUTOLOAD’, false);
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->setPaper($paper, $orientation);
$dompdf->render();
$output = $dompdf->output();
file_put_contents($_SERVER[“DOCUMENT_ROOT”].’/dn/’.$filename, $output);
}

3. Buat file controller

defined(‘BASEPATH’) OR exit(‘No direct script access allowed’);
require FCPATH.’/vendor/autoload.php’;
class Goodsdelivery extends CI_Controller
{
public function __construct()
{
parent::__construct();
}

public function index($slug)
{
$rec = $this->m_model->getBySlug($slug);
if($rec==null) redirect(‘notfound’);
$this->load->library(‘createpdf’);
$data = array(
‘rec’ => $rec,
‘est_date’ => date(),
);
$html = $this->load->view(‘report/dn’, $data, true);

$filename = ‘Delivery Note.pdf’;

$this->createpdf->save($html, $filename, ‘A4’, ‘portrait’);
}

Setelah semua file selesai dibuat, jalankan aplikasi. dari kode di atas, file PDF akan di save di folder “report/dn”.

Leave a Reply

Your email address will not be published. Required fields are marked *