Saturday, 1 October 2016

How to Generate Dynamic PDF File using TCPDF in PHP



Hello friends in this video we are going to discuss how can we create pdf file from html data using TCPDF class in php. This is my new video in PHP Advance Video tutorial series. In this video we will show how can we generate pdf file from html table data by using TCPDF libraries. This is the best library for creating pdf file from html data in php programming language, this is because it is build by php language. This is the one of the best library for creating pdf, this is because in this library we can generate pdf file from html data. So most of the developer use this library for generating pdf document in their project. This is the official site of TCPDF library and here you can see that it is now one of the world's most active Open Source projects, used daily by millions of users and included in thousands of Content Management system and Web applications. You can download TCPDF library from here - https://sourceforge.net/projects/tcpdf/


Source Code


Database


 --  
 -- Table structure for table `tbl_employee`  
 --  
 CREATE TABLE IF NOT EXISTS `tbl_employee` (  
  `id` int(11) NOT NULL AUTO_INCREMENT,  
  `name` varchar(50) NOT NULL,  
  `address` text NOT NULL,  
  `gender` varchar(10) NOT NULL,  
  `designation` varchar(100) NOT NULL,  
  `age` int(11) NOT NULL,  
  PRIMARY KEY (`id`)  
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=22 ;  
 --  
 -- Dumping data for table `tbl_employee`  
 --  
 INSERT INTO `tbl_employee` (`id`, `name`, `address`, `gender`, `designation`, `age`) VALUES  
 (1, 'Bruce Tom', '656 Edsel Road\r\nSherman Oaks, CA 91403', 'Male', 'Driver', 36),  
 (5, 'Clara Gilliam', '63 Woodridge Lane\r\nMemphis, TN 38138', 'Female', 'Programmer', 24),  
 (6, 'Barbra K. Hurley', '1241 Canis Heights Drive\r\nLos Angeles, CA 90017', 'Female', 'Service technician', 26),  
 (7, 'Antonio J. Forbes', '403 Snyder Avenue\r\nCharlotte, NC 28208', 'Male', 'Faller', 32),  
 (8, 'Charles D. Horst', '1636 Walnut Hill Drive\r\nCincinnati, OH 45202', 'Male', 'Financial investigator', 29),  
 (9, 'Beau L. Clayton', '3588 Karen Lane\r\nLouisville, KY 40223', 'Male', 'Extractive metallurgical engin', 33),  
 (10, 'Ramona W. Burns', '2170 Ocala Street\r\nOrlando, FL 32801', 'Female', 'Electronic typesetting machine operator', 27),  
 (11, 'Jennifer A. Morrison', '2135 Lakeland Terrace\r\nPlymouth, MI 48170', 'Female', 'Rigging chaser', 29),  
 (12, 'Susan M. Juarez', '3177 Horseshoe Lane\r\nNorristown, PA 19403', 'Female', 'Control and valve installer', 25),  
 (13, 'Ellan D. Downie', '384 Flynn Street\r\nStrongsville, OH 44136', 'Female', 'Education and training manager', 26),  
 (14, 'Larry T. Williamson', '1424 Andell Road\r\nBrentwood, TN 37027', 'Male', 'Teaching assistant', 30),  
 (15, 'Lauren M. Reynolds', '4798 Echo Lane\r\nKentwood, MI 49512', 'Female', 'Internet developer', 22),  
 (16, 'Joseph L. Judge', '3717 Junkins Avenue\r\nMoultrie, GA 31768', 'Male', 'Refrigeration mechanic', 35),  
 (17, 'Eric C. Lavelle', '1120 Whitetail Lane\r\nDallas, TX 75207', 'Male', 'Model', 21),  
 (18, 'Cheryl T. Smithers', '1203 Abia Martin Drive\r\nCommack, NY 11725', 'Female', 'Personal banker', 23),  
 (19, 'Tonia J. Diaz', '4724 Rocky Road\r\nPhiladelphia, PA 19107', 'Female', 'Facilitator', 29),  
 (20, 'Stephanie P. Lederman', '2117 Larry Street\r\nWaukesha, WI 53186', 'Female', 'Mental health aide', 27),  
 (21, 'Edward F. Sanchez', '2313 Elliott Street\r\nManchester, NH 03101', 'Male', 'Marine oiler', 28);  


index.php



 <?php  
 function fetch_data()  
 {  
      $output = '';  
      $connect = mysqli_connect("localhost", "root", "", "testing");  
      $sql = "SELECT * FROM tbl_employee ORDER BY id ASC";  
      $result = mysqli_query($connect, $sql);  
      while($row = mysqli_fetch_array($result))  
      {       
      $output .= '<tr>  
                          <td>'.$row["id"].'</td>  
                          <td>'.$row["name"].'</td>  
                          <td>'.$row["gender"].'</td>  
                          <td>'.$row["designation"].'</td>  
                          <td>'.$row["age"].'</td>  
                     </tr>  
                          ';  
      }  
      return $output;  
 }  
 if(isset($_POST["create_pdf"]))  
 {  
      require_once('tcpdf/tcpdf.php');  
      $obj_pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);  
      $obj_pdf->SetCreator(PDF_CREATOR);  
      $obj_pdf->SetTitle("Export HTML Table data to PDF using TCPDF in PHP");  
      $obj_pdf->SetHeaderData('', '', PDF_HEADER_TITLE, PDF_HEADER_STRING);  
      $obj_pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));  
      $obj_pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));  
      $obj_pdf->SetDefaultMonospacedFont('helvetica');  
      $obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER);  
      $obj_pdf->SetMargins(PDF_MARGIN_LEFT, '5', PDF_MARGIN_RIGHT);  
      $obj_pdf->setPrintHeader(false);  
      $obj_pdf->setPrintFooter(false);  
      $obj_pdf->SetAutoPageBreak(TRUE, 10);  
      $obj_pdf->SetFont('helvetica', '', 12);  
      $obj_pdf->AddPage();  
      $content = '';  
      $content .= '  
      <h3 align="center">Export HTML Table data to PDF using TCPDF in PHP</h3><br /><br />  
      <table border="1" cellspacing="0" cellpadding="5">  
           <tr>  
                <th width="5%">ID</th>  
                <th width="30%">Name</th>  
                <th width="10%">Gender</th>  
                <th width="45%">Designation</th>  
                <th width="10%">Age</th>  
           </tr>  
      ';  
      $content .= fetch_data();  
      $content .= '</table>';  
      $obj_pdf->writeHTML($content);  
      $obj_pdf->Output('sample.pdf', 'I');  
 }  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | Export HTML Table data to PDF using TCPDF in PHP</title>  
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />            
      </head>  
      <body>  
           <br /><br />  
           <div class="container" style="width:700px;">  
                <h3 align="center">Export HTML Table data to PDF using TCPDF in PHP</h3><br />  
                <div class="table-responsive">  
                     <table class="table table-bordered">  
                          <tr>  
                               <th width="5%">ID</th>  
                               <th width="30%">Name</th>  
                               <th width="10%">Gender</th>  
                               <th width="45%">Designation</th>  
                               <th width="10%">Age</th>  
                          </tr>  
                     <?php  
                     echo fetch_data();  
                     ?>  
                     </table>  
                     <br />  
                     <form method="post">  
                          <input type="submit" name="create_pdf" class="btn btn-danger" value="Create PDF" />  
                     </form>  
                </div>  
           </div>  
      </body>  
 </html>  

51 comments:

  1. I am having this error "TCPDF ERROR: Some data has already been output, can't send PDF file"

    ReplyDelete
    Replies
    1. Add this ob_end_clean(); before this $obj_pdf->Output('sample.pdf', 'I');

      Delete
    2. Add this ob_end_clean(); before this $obj_pdf->Output('sample.pdf', 'I');

      Delete
    3. You can download TCPDF library from here - https://sourceforge.net/projects/tcpdf/

      Delete
    4. Download the TCPDF file

      Delete
    5. Please...
      Did someone fond solution about this?

      Delete
    6. Write Code before Output pdf line then it will solve:
      ob_end_clean();
      $obj_pdf->Output('sample.pdf', 'I');

      Delete
    7. put the code above, before

      Delete
  2. I am having the same error, what is the solutions to this

    ReplyDelete
    Replies
    1. Add this ob_end_clean(); before this $obj_pdf->Output('sample.pdf', 'I');

      Delete
    2. You can download TCPDF library from here - https://sourceforge.net/projects/tcpdf/

      Delete
    3. i also got same error but the solution is there.....just add the below code at the top of the page then its working fine...the code is-


      Delete
    4. you need to download the TCPDF files so i am sharing that link https://github.com/tecnickcom/TCPDF here u can download

      Delete
  3. I am having the same error, what is the solutions to this

    ReplyDelete
    Replies
    1. Add this ob_end_clean(); before this $obj_pdf->Output('sample.pdf', 'I');

      Delete
    2. You can download TCPDF library from here - https://sourceforge.net/projects/tcpdf/

      Delete
  4. Thank you!! It works perfect

    ReplyDelete
  5. thank you so much it is really working you are great

    ReplyDelete
  6. Many thanks. This is the only working lesson in the network, which really helped me to make a beautiful account for the payment for the order for Joomla!

    ReplyDelete
  7. Many thanks. This is the only working lesson in the network, which really helped me to make a beautiful account for the payment for the order for Joomla!

    ReplyDelete
  8. i have error what shoud i do

    ReplyDelete
  9. Notice: Undefined offset: 0 in C:\xampp\htdocs\job\HTML\tcpdf\tcpdf.php on line 17155

    Notice: Undefined offset: 0 in C:\xampp\htdocs\job\HTML\tcpdf\tcpdf.php on line 17522

    Notice: Undefined offset: 0 in C:\xampp\htdocs\job\HTML\tcpdf\tcpdf.php on line 17522

    Notice: Undefined offset: 0 in C:\xampp\htdocs\job\HTML\tcpdf\tcpdf.php on line 17975

    Notice: Undefined offset: 0 in C:\xampp\htdocs\job\HTML\tcpdf\tcpdf.php on line 18273

    Notice: Undefined offset: 0 in C:\xampp\htdocs\job\HTML\tcpdf\tcpdf.php on line 17975

    Notice: Undefined offset: 0 in C:\xampp\htdocs\job\HTML\tcpdf\tcpdf.php on line 17522

    Notice: Undefined offset: 0 in C:\xampp\htdocs\job\HTML\tcpdf\tcpdf.php on line 18282

    Notice: Undefined offset: 0 in C:\xampp\htdocs\job\HTML\tcpdf\tcpdf.php on line 18284

    Notice: Undefined offset: 0 in C:\xampp\htdocs\job\HTML\tcpdf\tcpdf.php on line 17522
    TCPDF ERROR: Wrong page number on setPage() function: 0

    ReplyDelete
  10. Hi,thank you very much for the tutorial.

    Solution to the error is to add ob_end_clean(); before $obj_pdf->Output('sample.pdf', 'I');

    It should be like such:

    ob_end_clean();
    $obj_pdf->Output('sample.pdf', 'I');

    ReplyDelete
  11. hi. thanks for the tutorial. but can i request for a tutorial the same as this one but the input and output are NOT in a table? just plain text from a text area tag. thank you so much! your answer will be helpful to my project that i am developing now as my requirement to graduate.

    ReplyDelete
  12. Use ob_start(); at the beginning

    ReplyDelete

  13. ( ! ) Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\wamp\www\login\pdf.php on line 34
    Call Stack
    # Time Memory Function Location
    1 0.0019 389512 {main}( ) ..\pdf.php:0
    2 3.0282 396928 fetch_data( ) ..\pdf.php:102
    3 6.0960 404072 mysqli_fetch_array ( ) ..\pdf.php:34



    I am having the same error, what is the solutions to this

    ReplyDelete
    Replies
    1. There must be something error with your query.

      Delete
  14. please help sir i have some error in line 22 tcpdf/tcpdf.php please help

    neeleshverma38@gmail.com

    ReplyDelete
    Replies
    1. i think you can write tcpdf.php only. I had did it & success..dont forget to insert tcpdf file together in ur system folder.

      Delete
  15. TCPDF ERROR: Some data has already been output, can't send PDF file

    ReplyDelete
    Replies
    1. what the solution for this? I had this problem also

      Delete
    2. try this. it worked for me
      ob_end_clean(); $obj_pdf->Output('sample.pdf', 'I');

      Delete

  16. ( ! ) Warning: require_once(tcpdf.php): failed to open stream: No such file or directory in C:\wamp64\www\pdf\index.php on line 23
    Call Stack
    # Time Memory Function Location
    1 0.0001 405128 {main}( ) ...\index.php:0

    ( ! ) Fatal error: require_once(): Failed opening required 'tcpdf.php' (include_path='.;C:\php\pear') in C:\wamp64\www\pdf\index.php on line 23
    Call Stack
    # Time Memory Function Location
    1 0.0001 405128 {main}( ) ...\index.php:0

    ReplyDelete
  17. Thank you so much.This tutorial is help full for me.

    ReplyDelete
  18. for any one still facing TCPDF ERROR : some data has already been output,cant send pdf file i have found the solution all you need to do is add ob_end_clean(); above the $obj_pdf->Output('sample.pdf', 'I');

    ReplyDelete
  19. how do I change the page orientation of my PDF generated file

    ReplyDelete
  20. How do I change the page orientation of the generated PDF file?

    ReplyDelete
  21. TCPDF ERROR: Some data has already been output, can't send PDF file

    getting this error while executing the program

    ReplyDelete
  22. how can i repeat the table header in every page?

    ReplyDelete
  23. I have same error Some data has already been output, can't send PDF file and

    Warning: "continue" targeting switch is equivalent to "break"

    ReplyDelete
  24. Having these errors, can u plz help me out to resolve this.
    Fatal error: Uncaught Error: Class 'PHPUnit\Framework\TestCase' not found in C:\xampp\htdocs\logistic_comp\tcpdf\test\tcpdf.php:31 Stack trace: #0 C:\xampp\htdocs\logistic_comp\pdf-gen.php(25): require_once() #1 {main} thrown in C:\xampp\htdocs\logistic_comp\tcpdf\test\tcpdf.php

    ReplyDelete
  25. having these errors. Can u plz help me out????
    Fatal error: Uncaught Error: Class 'PHPUnit\Framework\TestCase' not found in C:\xampp\htdocs\logistic_comp\tcpdf\test\tcpdf.php:31 Stack trace: #0 C:\xampp\htdocs\logistic_comp\pdf-gen.php(25): require_once() #1 {main} thrown in C:\xampp\htdocs\logistic_comp\tcpdf\test\tcpdf.php

    ReplyDelete
  26. if i insert hindi inside table it is not showing in frontend....

    it showing " ??????? ". sir please help.
    i want to download pdf file with hindi font also

    ReplyDelete
  27. how to add header and footer this code

    ReplyDelete