Katika somo hili utakwenda kujifunza jinsi ya ku generate PDF automatik kutoka kwenye php code , html, javascript na css.
PHP PDF KWA KUTUMIA TCPDF
Karibu tena kwenye course mpya ya PHP PDF. Katika course hii utakwenda kujifunzajinsi ya kutengeneza PDF kwa kutumia PHP. katika somo hili utakwenda kujifunza jinsi ya kutumia library ya TCPDF kwa ajili ya kutengeneza PDF.
Kuna library nyingi ambazo hutumika kutengeneza PDF kwa kutumia PHP. Kwa mfano:-
Katika course hii tutakwenda kutumia library ya TCPDF. Kwakuwa library zote hizi zinafanana ufanyaji wa kazi, unaweza kutumia course hii kuweza kutumia library nyinginezo.
1. Jinsi ya ku install library ya TCPDF:
Kuna njia kuu 2 za ku install library za PHP.:-
Jinsi ya kutumia composer:
Kwanza download composer kwenye system yako. Ingia https://getcomposer.org/ kisha download.njia rahisi download composer.exe https://getcomposer.org/Composer-Setup.exe kisha fuata maelekezo kuinstall.
Utatakiwa ku select version ya PHP unayotumia. PHP utaipata kwenye faili lako la locahost. Mfano kama unatumia xamp ingia kwenye faili la xamp. Kisha bofya PHP, kisha bofya php.exe. Baada ya hapo utaweza kuendelea na maelekezo.
Baada ya hapo utatakiwa ku instal composer kwenye project yako kwa ku install
Tumia command composer init kisa fata maelekezo.kwa mfano utajaza packagename, description, athor, katika minimal stability weka stable, package type weka library na katikalicense weka MIT. Pia utaulizwa kama unahitaki kuweka Dependencies hapo utaweka yes kisha utajaza TCPDF. Kisha utachaguwa namba ya toleo unalolitaka. Angalia video hii tumekuwekea hatuwa kwa hatuwa jinsi ya ku install composer
https://www.youtube.com/watch?v=aeZ4p1DuRHE
Baada ya hapo uta install library yetu ya tcpdf kwa kuandika composer require tecnickcom/tcpdf kisha fata maelekezo. Makaumefuata video nilioelekeza hapo juu utaweza ku downloadmoja kwa moja.
Bila ya kutumia composer
Kaa umepata changamoto juu ya ku install composer basi itakubidi ku download library nzima kutoka github bofya link hii https://github.com/tecnickcom/tcpdf
Jisnis ya kutumia library ya TCPDF
Kwanza tutakwenda kutengeneza file tutaliita index.php kwenye file hili ndipo tutakwenda kufanyia mazoezi yetu ya kuanzia.
Kama unatumia composer anza na kuweka mstari huu wa code kwa ajili ya ku include library ya TCPDF
require 'vendor/autoload.php';
Na kama hutumii composer yaani umesha download folder lalibrary kutoka github, basi utaweza ku include kwa kutumia mstari huu wa code
require_once('TCPDF-main/tcpdf.php');
Hatuwa inayofuata ni kutengeneza object ya PDF kwa kutumia TCPDF class. Na hapa ndiomwanzo wa kutengeneza pdf
$pdf = new TCPDF()
Ndani ya hii class kuna taarifa tunatakiwa kuziweka kwenye tcpdf_config.php filehili linapatikana kwenye folda la config kwenye library ya tcpdf. Utazikuta tayari zimeshajazwa ila kama unataka ku set unavyotaka wewe unaruhusiwa..
Taarifa hizi utazijazakwenye config Taarifa hizo ni kama:-
Zipo taarifa nyingine unaweza ku set zote utaset kwenye faili hilo la config.sasa wacha tuone taarifa zote kwa pamoja zinavyokuwa
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
Code hizo hapo juu zitatuwezesha kutengeneza PDF. sasa hatuw ainayofuata ni kuweka taarifa muhimu kuhusu hilo PDF tulilolitengeneza. Taarifa hizoni kama:-
$pdf->setCreator(PDF_CREATOR)
$pdf->setAuthor('Rajabu');
C. ichwa cha habar - title Mfano Mafunzo ya ICT
$pdf->setTitle('Mafunzo ya ICT');
D. Maada - subject Mfano kutengeneza pdf
$pdf->setSubject('Kutengeneza PDF');
E. Maneno maalumu - keyword mfano ICT, PDF, Bongoclass
$pdf->setKeywords('ICT, PDF, bongoclass');
Code hizo zinawezakuonekana hivi:-
$pdf->setCreator('Bongoclass');
$pdf->setAuthor('Rajabu');
$pdf->setTitle('Mafunzo ya ICT');
$pdf->setSubject('Kutengeneza PDF');
$pdf->setKeywords('ICT, PDF, bongoclass');
Taarifa hizo hapo juu unaweza kuziona kwenye PDF kaa utaangalia properties. Mfano
Hatuwa nayofuata n u set heade footerna margn. Hz n taarfa muhmu sana wenye muoneano na mpanglo wa fal la PDF. taarfa hz pa unaweza uzset wenye confg fle. Hata hvyo so lazma unaweza uzacha ama zlvyo.
// set default header data
$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));
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->setDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->setMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->setHeaderMargin(PDF_MARGIN_HEADER);
$pdf->setFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->setAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
Taarifa hizo zote zipo kwenye header information. Unaweza kuziita metadata kama zile za kwenye html hata hivyo sio kitu kimoja. Hizi zinasaidia kuweza kupangilia uuondo mzima wa hiyo PDF unayoitengeneza.
Hatuwa inayofuata ni ku set font. Pia unaweza uacha kama palivyo ama unaweza kuset font kulingana na mahitaji yako. Yenyewetutaiweka katika hatuwa kuu 3 ambazo ni:-
$pdf->setFontSubsetting(true);
$pdf->setFont('dejavusans', '', 14, '', true);
Hatuwa inayofuata ni ku addpage kwa kutumia $pdf->AddPage();Hii itakuwezesha kuadd page endapo maudhui ni mengi.
Hatuwa inayofuata utakwenda ku set shadow. Hapa unawezakuwacha kama palivyo . vinginevyo rejea documentation ya library kuwa na ujuzi zaidi
// set text shadow effect
$pdf->setTextShadow(array('enabled'=>true, 'depth_w'=>0.2, 'depth_h'=>0.2, 'color'=>array(196,196,196), 'opacity'=>1, 'blend_mode'=>'Normal'));
Hatuwa inayofuata sasani ni kuwekamaudhui ya PDF yetu. Hapa ndipo tuankwend akuweka content. Jambo la kujuwa nikuwa failila PDF contentzake zinaanzia kwenye <<<EOD na kuishia kwenye EOD
Sasa tuseme tuna code za html ambazo tutataka kuzipadili kuwa pdf file.
Hvyo bas tutawea code zetu ndan ya <<<EOD na EOD
$content = <<<EOD
//code za html weka hapa
EOD;
Mfano:
$content = <<<EOD
<!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>
EOD;
Sasa hatuwa inayofuata ni kuandika hayo maudhui kwenye PDF document. Kufanya hivyo tutatumia method ya
$pdf->writeHTMLCell();
Mfano:
// Print text using writeHTMLCell()
$pdf->writeHTMLCell(0, 0, '', '', $content, 0, 1, 0, true, '', true);
Mwisho tutamaliza kwa kuweka jina la pdf tunayoitengeneza. Tutafanya hivyo kwa kutumia method ya $pdf->Output()
Mfano:
$pdf->Output('Mafunzo_somola_1.pdf', 'I');
Mpaka kufikia hapo tumemaliza kutengeneza PDF yetu. Hapo kama uta run code utaona pdf litatengeneza. Code zote zitaweza kuonekana kama hapochini:-
<?php
require_once('TCPDF-main/tcpdf.php');
require 'vendor/autoload.php';
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->setCreator('Bongoclass');
$pdf->setAuthor('Rajabu');
$pdf->setTitle('Mafunzo ya ICT');
$pdf->setSubject('Kutengeneza PDF');
$pdf->setKeywords('ICT, PDF, bongoclass');
// set default header data
$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));
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->setDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->setMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->setHeaderMargin(PDF_MARGIN_HEADER);
$pdf->setFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->setAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// set default font subsetting mode
$pdf->setFontSubsetting(true);
// Set font
// dejavusans is a UTF-8 Unicode font, if you only need to
// print standard ASCII chars, you can use core fonts like
// helvetica or times to reduce file size.
$pdf->setFont('dejavusans', '', 14, '', true);
// Add a page
// This method has several options, check the source code documentation for more information.
$pdf->AddPage();
// set text shadow effect
$pdf->setTextShadow(array('enabled'=>true, 'depth_w'=>0.2, 'depth_h'=>0.2, 'color'=>array(196,196,196), 'opacity'=>1, 'blend_mode'=>'Normal'));
// Set some content to print
$content = <<<EOD
<!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>
EOD;
// Print text using writeHTMLCell()
$pdf->writeHTMLCell(0, 0, '', '', $content, 0, 1, 0, true, '', true);
// ---------------------------------------------------------
// Close and output PDF document
// This method has several options, check the source code documentation for more information.
$pdf->Output('Mafunzo_somola_1.pdf', 'I');
Sasa hapo PDF yako utaona kuna baadhi ya maneno hujuwi yametoka wapo mfano hayo hapo kwenye picha hap chini
Hayo utakwenda kuyaset kwenye tcpdf_config.phpkule kwenye config folder.
Mfano:
Unaweza kubadili hizi line mbuli za codede
define ('PDF_HEADER_TITLE', 'MAFUNZO YA ICT');
define ('PDF_HEADER_STRING', "Bongoclass - www.bongoclass.com");
Mwisho:
Tukutane somo linalofuata tutakwenda kujifunza kutengeneza pdf file kwa kutumia data kutoka kwenye database.
Jifunze zaidi, na wasiliana nasi ukiwa na App yetu. Bofya link hapo chini kuweza kuipakua.
Download NowFaili la env ni moja kati ya mafaili ambayo ni muhimu kwa usalama wa project. Fili hili hutumika kuhifadhi data za siri
Soma Zaidi...Katika somo hili utakwenda kujifunza kuhusu condition statements if, ifelse na switch case. Hata utajifunza jnsi ya kuziandika na zinavyofanya kazi
Soma Zaidi...Katika somo hili utakwenda kujifunza kuhusu Aina za cache header
Soma Zaidi...Katika somo hili utakwenda kujifunza kuhusu class inheritance kwenye object oriented programming.
Soma Zaidi...Haya ni mabo ya kuzingatia unapo encode ama ku decode data za json
Soma Zaidi...Katika somo hili utakwenda kujifunza jinsi ya kusoma data kwenye database kwa kutumia PDO.
Soma Zaidi...Katika soko hili takwenda kujufunza jinsi ya kutuma sms kwa kutumia PHP. Hii itasaidia kama unataka kutuma OTP yaqni Onetime password
Soma Zaidi...Katika somo hili utakwenda kujifunza concept ya traits kwenye OOP. hii itakusaidia ku solve baadhi ya changamoto zinazotokana na inheritance
Soma Zaidi...Katika somo hili utajifunza jinsi ya kutuma email kwa kutumia email() function ya PHP. Hii ni njia rahisi zaidi ya kutuma email. Ila hufanya kazi kwenye hosting.
Soma Zaidi...Katika somo hili utakwenda kujifunza kuhusu Maana ya JSON na sheria za kuandika faili la json
Soma Zaidi...