JINSI YA KUTUMIA DATABASE KUTENGENEZA PDF

Katika somo hili utajifunza jinsi ambavyo tutatengeneza PDF kutokana na data ambazo zipo kwenye PDF. 

 

Katika somo hili tutatumia data za faili la html ambalo tumelitumia katika somo lililopita. Hivyo basi tutatengeneza database yenye jina la pdf kisha tutaweka table yenye jina content, ambayo ina field 5 ambazo ni id, summary, content, autor, title. Baada ya hapo ndipo tutaweka data zetu.

 

Hatuwa ya kwanza:

Tengeneza database yenye jina pdf. Kisha tengeneza table iite content kisha weka filed hizo nilizotaja hapo juu. Unaweza kutuia code hizo hapo chini kutengeneza table hiyo.

CREATE TABLE `content` (

 `id` int(11) NOT NULL,

 `title` varchar(255) NOT NULL,

 `summary` varchar(255) NOT NULL,

 `content` text NOT NULL,

 `author` varchar(255) NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

 

ALTER TABLE `content`

 ADD PRIMARY KEY (`id`);

ALTER TABLE `content`

 MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

 

Hatuwa ya pili

Baada ya hapo tutaingiza data zetu za html ambazo tumezitumia katika somo lililopita. Unaweza kingiza tu kawaida ama ukatumia code nitakazokupa hapo jini.

INSERT INTO `content` (`id`, `title`, `summary`, `content`, `author`)

VALUES 

   (NULL, 'Mafunzo ya PDF',

       'Hapa utajifunza jinsi y akutengeneza PDF kwa kutumia data zilizopo kwenye database',

       '<!DOCTYPE html>

       <html lang="en">

       <head>

           <meta charset="UTF-8">

           <meta name="viewport" content="width=device-width, initial-scale=1.0">

           <title>Short Story</title>

           <style>

               body {

                   font-family: Arial, sans-serif;

                   line-height: 1.6;

                   margin: 0;

                   padding: 20px;

                   background-color: #f4f4f4;

               }

               h1 {

                   text-align: center;

                   color: #333;

               }

               p {

                   max-width: 800px;

                   margin: 0 auto 20px;

                   color: #555;

               }

           </style>

       </head>

       <body>

           <h1>The Enchanted Forest</h1>

           <p>Once upon a time, in a land far away, there was an enchanted forest where magical creatures lived in harmony. The forest was filled with towering trees, whose leaves shimmered with a golden hue. Every morning, the forest would come alive with the songs of birds and the chatter of woodland creatures.</p>

           <p>In the heart of this forest lived a young elf named Elara. Elara was known throughout the land for her kind heart and her ability to communicate with animals. She spent her days exploring the forest, helping any creature in need, and learning the secrets of the ancient woods.</p>

           <p>One day, while wandering through a particularly dense part of the forest, Elara stumbled upon a hidden glade. In the center of the glade was a crystal-clear pond, and next to the pond stood a majestic unicorn with a mane that sparkled like diamonds. The unicorn introduced himself as Orion, the guardian of the forest.</p>

           <p>Orion told Elara about a great danger that was approaching the forest. A dark sorcerer had discovered the forest\'s location and intended to drain its magic for his own evil purposes. The only way to save the forest was to find the ancient Tree of Life and awaken its power.</p>

           <p>Determined to save her home, Elara set off on a perilous journey. She faced many challenges along the way, including crossing a treacherous river, outsmarting a cunning fox, and navigating through a maze of thorns. But with the help of her animal friends, she overcame every obstacle.</p>

           <p>Finally, after days of travel, Elara found the Tree of Life. It was a magnificent tree with branches that reached the sky and roots that dug deep into the earth. Elara placed her hands on the trunk and spoke the ancient words of awakening. The tree began to glow with a brilliant light, and its magic spread throughout the forest, banishing the sorcerer\'s dark influence.</p>

           <p>The forest was saved, and its inhabitants rejoiced. Elara became a hero, and her bond with the forest grew even stronger. From that day on, the enchanted forest thrived, and its magic remained protected for generations to come.</p>

       </body>

       </html>',

       'Bongoclass'

   );

 

Hatuwa ya tatu

Baada ya hapo hatuwa hyo sasa ni kusoma hizo data kwenye faililetu la php. Tutatumia fail lilelile la indexphp. Kwanza tutaanza na kufuta code za html kwenye lile faili. Hivyo basi code zetu zitaonekana hivi:-

<?php

require 'vendor/autoload.php';

$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

$pdf->setCreator('Bongoclass');

$pdf->setAuthor('Rajabu');

$pdf->setTitle('Mafunzo ya ICT');

$pdf->setSubject('Kutengeneza PDF');

$pdf->setKeywords('ICT, PDF, bongoclass');

$pdf->setHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' Mafunzo', PDF_HEADER_STRING, array(0,64,255), array(0,64,128));

$pdf->setFooterData(array(0,64,0), array(0,64,128));

$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));

$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

$pdf->setDefaultMonospacedFont(PDF_FONT_MONOSPACED);

$pdf->setMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);

$pdf->setHeaderMargin(PDF_MARGIN_HEADER);

$pdf->setFooterMargin(PDF_MARGIN_FOOTER);

$pdf->setAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {

   require_once(dirname(__FILE__).'/lang/eng.php');

   $pdf->setLanguageArray($l);

}

$pdf->setFontSubsetting(true);

$pdf->setFont('dejavusans', '', 14, '', true);

$pdf->AddPage();

$pdf->setTextShadow(array('enabled'=>true, 'depth_w'=>0.2, 'depth_h'=>0.2, 'color'=>array(196,196,196), 'opacity'=>1, 'blend_mode'=>'Normal'));

$content = <<<EOD

 

EOD;

$pdf->writeHTMLCell(0, 0, '', '', $content, 0, 1, 0, true, '', true);

$pdf->Output('Mafunzo_somola_1.pdf', 'I');

 

Hatuwa ya nne

Juu kabisa ya hizi code kabla ya kuanza kutumia tcpdf library tutakwenda kuandika code kwa ajli ya kusoma data zetu kutoka kwenye database.

 

Code zote ztaoneana hv:

<?php

 

// Database configuration

global $l;

$servername = "localhost";

$username = "root";

$password = "123456";

$dbname = "pdf";

 

try {

   // Create a new PDO instance

   $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

   // Set the PDO error mode to exception

   $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

 

   // Prepare the SQL statement

   $stmt = $conn->prepare("SELECT id, title, summary, content, author FROM content");

 

   // Execute the statement

   $stmt->execute();

 

   // Fetch all the results

   $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

 

   // Display the results

   foreach ($results as $row) {

       //PDF contents variables

       $ttle = $row["title"];

       $summary = $row["summary"];

       $content = $row["content"];

       $author = $row["author"];

 

       require 'vendor/autoload.php';

       $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

       $pdf->setCreator('Bongoclass');

       $pdf->setAuthor($author);

       $pdf->setTitle($ttle);

       $pdf->setSubject('Kutengeneza PDF');

       $pdf->setKeywords('ICT, PDF, bongoclass');

       $pdf->setHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE . ' Mafunzo', PDF_HEADER_STRING, array(0, 64, 255), array(0, 64, 128));

       $pdf->setFooterData(array(0, 64, 0), array(0, 64, 128));

       $pdf->setHeaderFont(array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));

       $pdf->setFooterFont(array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

       $pdf->setDefaultMonospacedFont(PDF_FONT_MONOSPACED);

       $pdf->setMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);

       $pdf->setHeaderMargin(PDF_MARGIN_HEADER);

       $pdf->setFooterMargin(PDF_MARGIN_FOOTER);

       $pdf->setAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

       $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

       if (@file_exists(dirname(__FILE__) . '/lang/eng.php')) {

           require_once(dirname(__FILE__) . '/lang/eng.php');

           $pdf->setLanguageArray($l);

       }

       $pdf->setFontSubsetting(true);

       $pdf->setFont('dejavusans', '', 14, '', true);

       $pdf->AddPage();

       $pdf->setTextShadow(array('enabled' => true, 'depth_w' => 0.2, 'depth_h' => 0.2, 'color' => array(196, 196, 196), 'opacity' => 1, 'blend_mode' => 'Normal'));

       $content = <<<EOD

$summary

$content

Makala hii imeandikwa na $author

 

EOD;

       $pdf->writeHTMLCell(0, 0, '', '', $content, 0, 1, 0, true, '', true);

       $pdf->Output('Mafunzo_somola_1.pdf', 'I');

   }

} catch (PDOException $e) {

   echo "Error: " . $e->getMessage();

}

 

Mwsho:

Huu ndo mwsho wa somo hili tukutane katika mfululizo wa masomo mengine. Pia angalia kwenye mifano kwenye library hii kuna kifano zaidi ya 100 unaweza kuitumia.