image

PHP somo la 71: Jinsi ya kutengeneza PDF kwa kutumia PHP na library ya tcpdf

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:-

  1. TCPDF
  2. FPDF
  3. DOMPDF

 

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.:-

  1. Kwa kutumia composer
  2. Kwa kudownload library yenyewe moja kwa moja.

 

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:-

  1. Orientatation: inaweza kuwa potrait ambayo huwakilishwa kwa p ama landscape ambayo huwakilishwa kwa l
  2. Unit ambayo inakuwa kwenye milimita 
  3. Format ambayo inaweza kuwa A4 ama A3 n.k
  4. Unicode inaweza kuwa true ama false
  5. Ecoding hapa utaweka encoding unayotumia inaweza kuwa UTF-8 ambayoni universe
  6. Diskcache hii inaweza kuwa false ama true. 

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:-

  1. Mtengenezaji - creator mfano Bongoclass

   $pdf->setCreator(PDF_CREATOR)

  1. Muandishi - Author mfano Rajabu

$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.

 

  1. Header na footer

// 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));

 

  1. Spacing

// set default monospaced font

$pdf->setDefaultMonospacedFont(PDF_FONT_MONOSPACED);

 

  1. Margin

// set margins

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

$pdf->setHeaderMargin(PDF_MARGIN_HEADER);

$pdf->setFooterMargin(PDF_MARGIN_FOOTER);

 

  1. Page break

// set auto page breaks

$pdf->setAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

 

  1. Image scale

// set image scale factor

$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

 

  1. Language

// 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:-

  1. Kwanza tutaanza na ku set sebsetting kuwa default kwa kuweka true. Hata hiyounaweza kuset false ilikuwa na control zaidi. Vyema ukarejea documentation ya TCPDF ili kuwa na uwelewa zaidi juu ya unachokifanya

      $pdf->setFontSubsetting(true);


 

  1. Baada ya hapo utakwend aku set font, ambayo kuna family, size, style fontfile na subset. Kipengele hiki kinahitajika uwe na uwelewa juu ya word docment kama microsoft wod inavyotumika kuset fot za doc

$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.


 





           

Je! umeipenda hii post?
Ndio            Hapana            Save post

Rajabu Tarehe 2024-06-24 19:48:21 Topic: PHP Main: Masomo File: Download PDF     Share On Facebook or Whatsapp Imesomwa mara 187


Sponsored links
👉1 Kitau cha Fiqh     👉2 Sira ya Mtume Muhammad (s.a.w)     👉3 Madrasa kiganjani     👉4 kitabu cha Simulizi     👉5 Kitabu cha Afya     👉6 Simulizi za Hadithi Audio    

Post zifazofanana:-

PHP somo la 53: class inheritance kwenye PHP Object Oriented Programming
Katika somo hili utakwenda kujifunza kuhusu class inheritance kwenye object oriented programming. Soma Zaidi...

PHP - somo la 40: Jinsi ya kutumia htaccess file kubadilisha muonekano wa link
Katika somo hili uatakwenda kujifunza jinsi ya kutumia htaccess ili kubadili muonekano wa link ya website ama blog ili kuifanya iwe rafiki zaidi. Soma Zaidi...

PHP BLOG - somo la 12: Jinsi ya kutumia prepared statement kwenye kusoma post za blog
Katika somo hili tutakwenda kutumia prepared ststement kwenye ku fetch data kutoka kwenye database. Soma Zaidi...

PHP somo la 83: Server Variables
Katika somo hili utakwend akujifunza kuhusu server variables Soma Zaidi...

PHP somo la 75: Content-Type Header
Katika somo hili utakwenda kujifunza kuhusu content-type header. Soma Zaidi...

PHP somo la 87: Jinsi ya kuangalia error wakati wa ku decode na ku encode json data
Katika somo hili utakwenda kujifunza jisni ya kudhibiti error ambazo zinaweza kutokea wakati wa ku encode na ku decoe json data Soma Zaidi...

PHP - somo la 4: Aina za data zinazotumika kwenye PHP
Katika somo hili utakwenda kujifunza aina za data ambazo hutumika kwenye PHP Soma Zaidi...

PHP somo la 76: Aina za cache header
Katika somo hili utakwenda kujifunza kuhusu Aina za cache header Soma Zaidi...

PHP - somo la 36: Jinsi ya ku upload taarifa za mafaili kwenye database kw akutumia PHP
katika somo hili utajfunza kukusanya taarifa za mafaili. kisha ku upload hayo mafaili. kisha kuandika hizo taarifa za mafaii kwenye database Soma Zaidi...

PHP - somo la 2: sheria za uandishi wa code za PHP
Katika somo hili utajifunza kuhusu syntax za PHP Soma Zaidi...

PHP somo la 54: class constant kwenye php
Katika somo hili utakwenda kujifunza jinsi ya kutumia constatnt kwenye class. Soma Zaidi...

PHP - somo la 13: Jinsi ya kuunganisha database na website
Katika somo hili utajifunza jinsi ya ku connect database, kwa kutumia php Soma Zaidi...