Php PDF: Generate Database Table Mysql Ke Pdf Report

 Author : hadinug, 03 December, 2014, Komentar

Pada tutorial sebelumnya kami telah menuliskan bagaimana membuat file PDF dengan javascript on the fly. Nah kali ini kita akan membuat laporan dari sebuah table yang lanhsung di generate ke file PDF. Penasaran bukan!!!, ikuti langkah-langkahnya secara bertaha dibawah ini:


Download Librari PHP FPDF

Pada tutorial kali ini kita menggunakan FPDF, untuk megenerate sebuah source program menjadi file PDF. SIlahkan download di http://fpdf.de/ 



Database

Karna pada tutorial kali ini kita menggunakan isi dari sebuah table dan menjadikan nya sebuah laporan dalam bentuk file PDF, maka kita harus membuat database terlebih dahulu:

CREATE DATABASE `example_karyawan` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `example_karyawan`; 

DROP TABLE IF EXISTS `karyawan`;

CREATE TABLE `karyawan` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nip` varchar(50) DEFAULT NULL,
  `nama` varchar(10) DEFAULT NULL,
  `alamat` varchar(50) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  `url` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

/*Data for the table `karyawan` */

insert  into `karyawan`(`id`,`nip`,`nama`,`alamat`,`email`,`url`) values (1,'0111500382','Jojon','Jalan Ciledug Raya No 90, Petukangan Utara, Jakart','jojon@gmail.com','http://www.jojon.net'),(2,'0111500383','Ponikem','Jalan Ciledug Raya No 91, Petukangan Utara, Jakart','achmatim@gmail.com','http://www.ponikem.net'),(3,'0111500384','Omas','Jalan Ciledug Raya No 92, Petukangan Utara, Jakart','omas@gmail.com','http://www.omas.com');


Conection Mysql dan Generate data from table

Berikut sintak sederhana coneksi ke mysql database. Jika anda ingin pelajari lebih silahkan coba tutorial berikut:

// simple conection to mysql
try {
    mysql_connect('localhost', 'root', '');
    mysql_select_db('example_karyawan');
} catch (Exception $exc) {
    echo $exc->getTraceAsString();
}
// generate query from table
$query = mysql_query("SELECT * FROM karyawan");
$data = array();
while ($row = mysql_fetch_array($query)) {
    $data[] = array(
        'nip' => $row['nip'],
        'nama' => $row['nama'],
        'alamat' => $row['alamat'],
        'email' => $row['email'],
        'url' => $row['url'] 
    );
}


Atur Header dan Option

Agara tampilan laporan PDF lebih menarik, mari kita coba menambahkan sebauh setingan sederhana:

//header
$this->SetFont("", "B", 10);
$this->MultiCell(0, 12, 'PT. ILC (Indonesia Lawak Club)');
$this->Cell(0, 1, " ", "B");
$this->Ln(20);
$this->SetFont("", "B", 12);
$this->SetX($left);
$this->Cell(0, 10, 'LAPORAN DATA KARYAWAN', 0, 1, 'C');
$this->Ln(20);


//Untuk option

//pilihan
$options = array(
    'filename' => '', //nama file penyimpanan, kosongkan jika output ke browser
    'destinationfile' => '', //I=inline browser (default), F=local file, D=download
    'paper_size' => 'A4', //paper size: F4, A3, A4, A5, Letter, Legal
    'orientation' => 'L' //orientation: P=portrait, L=landscape
);


Instasiasi class PDF dan generate Laporan

$tabel = new FPDF_AutoWrapTable($data, $options);
$tabel->printPDF();

Masih bingung?, sama saya juga bingung, dari pada kita sama-sama bingung, mari kita lihat full source code nya dan lihat demo serta download contoh nya dibawah ini:

/**
 * @author twitter@hadinug1
 * @website http://hadinug.net
 * @email achmatim@gmail.com
 */
require_once("fpdf17/fpdf.php");

class FPDF_AutoWrapTable extends FPDF {

    private $data = array();
    private $options = array(
        'filename' => '',
        'destinationfile' => '',
        'paper_size' => 'F4',
        'orientation' => 'P'
    );

    function __construct($data = array(), $options = array()) {
        parent::__construct();
        $this->data = $data;
        $this->options = $options;
    }

    public function rptDetailData() {
        //
        $border = 0;
        $this->AddPage();
        $this->SetAutoPageBreak(true, 60);
        $this->AliasNbPages();
        $left = 25;

        //header
        $this->SetFont("", "B", 10);
        $this->MultiCell(0, 12, 'PT. ILC (Indonesia Lawak Club)');
        $this->Cell(0, 1, " ", "B");
        $this->Ln(20);
        $this->SetFont("", "B", 12);
        $this->SetX($left);
        $this->Cell(0, 10, 'LAPORAN DATA KARYAWAN', 0, 1, 'C');
        $this->Ln(20);


        $h = 18;
        $left = 40;
        $top = 80;
        #tableheader
        $this->SetFillColor(200, 200, 200);
        $left = $this->GetX();
        $this->Cell(50, $h, 'NO', 1, 0, 'L', true);
        $this->SetX($left += 25);
        $this->Cell(100, $h, 'NIP', 1, 0, 'C', true);
        $this->SetX($left += 100);
        $this->Cell(160, $h, 'NAMA', 1, 0, 'C', true);
        $this->SetX($left += 160);
        $this->Cell(300, $h, 'ALAMAT', 1, 0, 'C', true);
        $this->SetX($left += 300);
        $this->Cell(100, $h, 'EMAIL', 1, 0, 'C', true);
        $this->SetX($left += 100);
        $this->Cell(100, $h, 'WEBSITE', 1, 1, 'C', true);
        //$this->Ln(20);

        $this->SetFont('Arial', '', 9);
        $this->SetWidths(array(25, 100, 160, 300, 100, 100));
        $this->SetAligns(array('C', 'L', 'L', 'L', 'L', 'L'));
        $no = 1;
        $this->SetFillColor(255);
        foreach ($this->data as $baris) {
            $this->Row(
                    array($no++,
                        $baris['nip'],
                        $baris['nama'],
                        $baris['alamat'],
                        $baris['email'],
                        $baris['url']
            ));
        }
    }

    public function printPDF() {

        if ($this->options['paper_size'] == "F4") {
            $a = 8.3 * 72; //1 inch = 72 pt
            $b = 13.0 * 72;
            $this->FPDF($this->options['orientation'], "pt", array($a, $b));
        } else {
            $this->FPDF($this->options['orientation'], "pt", $this->options['paper_size']);
        }

        $this->SetAutoPageBreak(false);
        $this->AliasNbPages();
        $this->SetFont("helvetica", "B", 10);
        //$this->AddPage();

        $this->rptDetailData();

        $this->Output($this->options['filename'], $this->options['destinationfile']);
    }

    private $widths;
    private $aligns;

    function SetWidths($w) {
        //Set the array of column widths
        $this->widths = $w;
    }

    function SetAligns($a) {
        //Set the array of column alignments
        $this->aligns = $a;
    }

    function Row($data) {
        //Calculate the height of the row
        $nb = 0;
        for ($i = 0; $i < count($data); $i++)
            $nb = max($nb, $this->NbLines($this->widths[$i], $data[$i]));
        $h = 18 * $nb;
        //Issue a page break first if needed
        $this->CheckPageBreak($h);
        //Draw the cells of the row
        for ($i = 0; $i < count($data); $i++) {
            $w = $this->widths[$i];
            $a = isset($this->aligns[$i]) ? $this->aligns[$i] : 'L';
            //Save the current position
            $x = $this->GetX();
            $y = $this->GetY();
            //Draw the border
            $this->Rect($x, $y, $w, $h);
            //Print the text
            $this->MultiCell($w, 18, $data[$i], 0, $a);
            //Put the position to the right of the cell
            $this->SetXY($x + $w, $y);
        }
        //Go to the next line
        $this->Ln($h);
    }

    function CheckPageBreak($h) {
        //If the height h would cause an overflow, add a new page immediately
        if ($this->GetY() + $h > $this->PageBreakTrigger)
            $this->AddPage($this->CurOrientation);
    }

    function NbLines($w, $txt) {
        //Computes the number of lines a MultiCell of width w will take
        $cw = &$this->CurrentFont['cw'];
        if ($w == 0)
            $w = $this->w - $this->rMargin - $this->x;
        $wmax = ($w - 1 * $this->cMargin) * 1000 / $this->FontSize;
        $s = str_replace("r", '', $txt);
        $nb = strlen($s);
        if ($nb > 0 and $s[$nb - 1] == "n")
            $nb--;
        $sep = -1;
        $i = 0;
        $j = 0;
        $l = 0;
        $nl = 1;
        while ($i < $nb) {
            $c = $s[$i];
            if ($c == "n") {
                $i++;
                $sep = -1;
                $j = $i;
                $l = 0;
                $nl++;
                continue;
            }
            if ($c == ' ')
                $sep = $i;
            $l+=$cw[$c];
            if ($l > $wmax) {
                if ($sep == -1) {
                    if ($i == $j)
                        $i++;
                }
                else
                    $i = $sep + 1;
                $sep = -1;
                $j = $i;
                $l = 0;
                $nl++;
            }
            else
                $i++;
        }
        return $nl;
    }

}

//end of class
//pilihan
$options = array(
    'filename' => '', //nama file penyimpanan, kosongkan jika output ke browser
    'destinationfile' => '', //I=inline browser (default), F=local file, D=download
    'paper_size' => 'A4', //paper size: F4, A3, A4, A5, Letter, Legal
    'orientation' => 'L' //orientation: P=portrait, L=landscape
);

// simple conection to mysql
try {
    mysql_connect('localhost', 'root', '');
    mysql_select_db('example_karyawan');
} catch (Exception $exc) {
    echo $exc->getTraceAsString();
}
// generate query from table
$query = mysql_query("SELECT * FROM karyawan");
$data = array();
while ($row = mysql_fetch_array($query)) {
    $data[] = array(
        'nip' => $row['nip'],
        'nama' => $row['nama'],
        'alamat' => $row['alamat'],
        'email' => $row['email'],
        'url' => $row['url'] 
    );
}


$tabel = new FPDF_AutoWrapTable($data, $options);
$tabel->printPDF(); 


download dan demo

 
Bagikan halaman ke sosial media
 
Tags :   fpdf    pdftable    pdf       

Tentang Penulis

writer hadinug
Web Developer di PT. Yafii Solusi Internasional

Link: http://ysi.co.id

   Komentar Anda