Programming, tutorials, mechatronics, operating systems, and other tech stuff

PHP FPDF Use text wrapping in table with MultiCell Table

60 comments
When we make a table in pdf using PHP FPDF library, basically we build it individually cell by cell. It is of course not as convenience as making a table using xml language such as HTML table. And the major drawbacks of using Cells is it's not able to wrap or break text as it overflow the defined cell width.

MultiCell

However, there is a method in FPDF library called MultiCell which allows us to make a Cell that wraps it's content, in short, it will break the text and make a new line when the text exceed it's width, thus multiplies it's height accordingly. But it doesn't works the same way with Cell, especially the positioning as the height varies according to it's content.

To make a table using MultiCell, we need to find out how much lines needed in a row as every cell in a row should have same height. And then we need to define where to put next cell, we can do this by calculating current cell position and offset it with it's dimension.

Don't want the math? FPDF MultiCell Table Class to the rescue.

FPDF Founder, Olivier Plathey have provided a FPDF extension class to make table from MultiCell named PDF_MC_Table. You can copy it from here :
https://github.com/gemul/fpdf-multicell-table/blob/master/pdf_mc_table.php

To use it, change the main fpdf.php file path to your FPDF library directory.
<?php
//call main fpdf file
require('fpdf18/fpdf.php');
//create new class extending fpdf class
class PDF_MC_Table extends FPDF {
...

Then in your script, include the pdf_mc_table.php file, not fpdf.php file.

<?php
//include pdf_mc_table.php, not fpdf17/fpdf.php
include('pdf_mc_table.php');
...

Next, create a new object from PDF_MC_Table Class.

...
//make new object
$pdf = new PDF_MC_Table();
...

From this point onward, you can use $pdf to build your pdf structure as usual. It doesn't change any functionaly of FPDF but instead it does add new ones.

Build the pdf table with MultiCell.

Like usual, you can add pages, use cell to build your content, and finally call Output() to render your pdf. Please read Generate Printable Invoice in PHP using FPDF library for more information.
And when it comes to make a multicell table, you need to:
  1. Set Font

    This is important to calculate length of the text.
    ...
    //add page, set font
    $pdf->AddPage();
    $pdf->SetFont('Arial','',14);
    ...
    
  2. Define the columns width.

    The column width is defined in array manner using SetWidths() method. The number of element should match the number of column.
    ...
    //set width for each column (6 columns)
    $pdf->SetWidths(Array(20,40,40,30,20,40));
    ...
    
  3. Set the line height.

    Use SetLineHeight() to define line height. This height will be used globally in our table. What we need to define here is height of line, not the row height. For example, if we define the line height to 5, and the cell with greatest line number in a row require 3 lines, then the height of the entire row will be 5 * 3 = 15.
    ...
    //set line height. This is the height of each lines, not rows.
    $pdf->SetLineHeight(5);
    ...
    
  4. Set the columns alignment (optional).

    This is optional. The default alginment of the cell is Left. You can define column alignment using SetAligns() method in array manner, with 'L' or empty string for Left (default), 'R' for Right, 'C' for Center, 'J' for justified. Also note that even if you only want to change only one column, you need to define all of them because number of array elements should match the number of columns.
    For example, when we want to make second column right aligned and third column centered, we use:
    ...
    //set alignment
    $pdf->SetAligns(Array('','R','C','','',''));
    ...
    
  5. Make the table header with standard Cell.

    To make it look like a proper table, add a table heading using standard cell with same number of columns and same widths for each cell respectively. Make the font bold if you like, or change the fill color to distinct it from table body. In this example, i will only make it bold.
    ...
    
    //add table heading using standard cells
    //set font to bold
    $pdf->SetFont('Arial','B',14);
    $pdf->Cell(20,5,"ID",1,0);
    $pdf->Cell(40,5,"First Name",1,0);
    $pdf->Cell(40,5,"Last Name",1,0);
    $pdf->Cell(30,5,"Email",1,0);
    $pdf->Cell(20,5,"Gender",1,0);
    $pdf->Cell(40,5,"Address",1,0);
    //add a new line
    $pdf->Ln();
    //reset font
    $pdf->SetFont('Arial','',14);
    ...
    
    Add a new line after that and do not forget to change the font back to normal.
  6. Write each row with Row() method.

    Then write the data row by row with Row() method also in array manners. The class will take care of the math.
    ...
    //loop the data
    foreach($data as $item){
     //write data using Row() method containing array of values.
     $pdf->Row(Array(
      $item['id'],
      $item['first_name'],
      $item['last_name'],
      $item['email'],
      $item['gender'],
      $item['address'],
     ));
     
    }
    ...
    
That's it. And don't forget to call $pdf->Output(); method to see the result.

And always keep in mind to never output anything in your script, so no empty line before "<?php", no echo, var_dump(), print() whatsoever. Even an error report or php warning will break your pdf file thus make it a corrupted pdf.

Except when you want to debug your code, you can freely output anything but comment out $pdf->Output(); line to prevent pdf render.

Known limitations.

However, as far as i know, there are some limitation in this method which is:
  1. Borders.
    Because the border is drawn using Rect() behind the scene, you may need some tweaking if you wish to change its style, color or size.

Further explanation and tutorial video.

For further explanation on how this class works behind the scene, please watch my tutorial video on youtube here :
https://youtu.be/pELrw9P5ywM
Also check out my PHP PDF Video Tutorial playlist here:
https://www.youtube.com/playlist?list=PLHCU7DCP4jhxnxV4Ub4YDqWiZ061t183c

60 comments :


  1. Howdy, would you mind letting me know which web host you’re utilizing? I’ve loaded your blog in 3 completely different web browsers, and I must say this blog loads a lot quicker than most. Can you suggest a good internet hosting provider at a reasonable price?
    Best AWS Amazon Web Services Training in Chennai | Best AWS Training and Certification for Solution Architect in Chennai
    Amazon Web Services Training in Tambaram, Chennai|Best AWS Training in Tambaram, Chennai

    ReplyDelete
  2. This is a nice article here with some useful tips for those who are not used-to comment that frequently. Thanks for this helpful information I agree with all points you have given to us. I will follow all of them.
    Data science training in Bangalore | Data Science Training institute in Bangalore

    ReplyDelete
  3. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    Selenium Training in Electronic City

    ReplyDelete
  4. Post is very useful. Thank you, this useful information.

    Learn Best Cognos Training in Bangalore from Experts. Softgen Infotech offers the Best Cognos Training in Bangalore.100% Placement Assistance, Live Classroom Sessions, Only Technical Profiles, 24x7 Lab Infrastructure Support.

    ReplyDelete
  5. Data Science is the future of Artificial Intelligence. Therefore, it is very important to understand what is Data Science and how can it add value to your business.
    Best Institute for Data Science in Mumbai which includes classroom and online training. Along with Classroom training, we also conduct online training using state-of-the-art technologies to ensure the wonderful experience of online interactive learning. Best Institute for Data Science

    ReplyDelete
  6. Data Science is the future of Artificial Intelligence. Therefore, it is very important to understand what is Data Science and how can it add value to your business.
    Data Science institute in Mumbai which includes classroom and online training. Along with Classroom training, we also conduct online training using state-of-the-art technologies to ensure the wonderful experience of online interactive learning. Data Science institute in Mumbai

    ReplyDelete
  7. Data Science is the future of Artificial Intelligence. Therefore, it is very important to understand what is Data Science and how can it add value to your business.
    Best institute for Data Science in Bangalore which includes classroom and online training. Along with Classroom training, we also conduct online training using state-of-the-art technologies to ensure the wonderful experience of online interactive learning. Best institute for Data Science in Bangalore

    ReplyDelete
  8. Nice blog,I understood the topic very clearly,And want to study more like this.
    Data Scientist Course

    ReplyDelete
  9. I really appreciate this post. I’ve been looking all over for this! Thank goodness I found it on Bing. You’ve made my day! Thx again!

    Selenium Training in Electronic City

    ReplyDelete
  10. Thanks for the informative article. This is one of the best resources I have found in quite some time. Nicely written and great info. I really cannot thank you enough for sharing.
    Microsoft Azure Training in Electronic City

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. Great post! I am actually getting ready to across this information, It’s very helpful for this blog. Also great with all of the valuable information you have Keep up the good work you are doing well.
    CRS Info Solutions Salesforce Training   

    ReplyDelete
  13. Nice post I have been searching for a useful post like this on salesforce course details, it is highly helpful for me and I have a great experience with this   
    Salesforce Training India 

    ReplyDelete
  14. I have been searching for a useful post like this on salesforce course details, it is highly helpful for me and I have a great experience with this Salesforce Training who are providing certification and job assistance. Salesforce training in Noida

    ReplyDelete
  15. wonderful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article resolved my all queries.
    Data Science Course

    ReplyDelete
  16. I like viewing web sites which comprehend the price of delivering the excellent useful resource free of charge. I truly adored reading your posting. Thank you!

    data science course

    ReplyDelete
  17. If you are looking for a job oriented practical based workday course syllabus curriculum at Workday training institutes in India then you are arrived at the right place called Workday training institutes in ameerpet because this institute is quite popular for this wonderful course not just in Workday training institutes in Jaipur and also proving job assistance for Workday training institutes in Pune.

    ReplyDelete
  18. This comment has been removed by the author.

    ReplyDelete
  19. This comment has been removed by the author.

    ReplyDelete
  20. This comment has been removed by the author.

    ReplyDelete
  21. Attend The Data Science Courses From ExcelR. Practical Data Science Courses Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Science Courses.
    Data Science Courses

    ReplyDelete
  22. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
    Correlation vs Covariance
    Simple linear regression

    ReplyDelete
  23. Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.You can also check my articles as well.

    Data Science In Banglore With Placements
    Data Science Course In Bangalore
    Data Science Training In Bangalore
    Best Data Science Courses In Bangalore
    Data Science Institute In Bangalore

    Thank you..

    ReplyDelete
  24. This post is great. I reallly admire your post. Your post was awesome.
    data science course in Hyderabad

    ReplyDelete
  25. I have to search sites with relevant information on given topic and provide them to teacher our opinion and the article.

    data science interview questions

    ReplyDelete
  26. This Was An Amazing ! I Haven't Seen This Type of Blog Ever ! Thankyou For Sharing, data science online course

    ReplyDelete
  27. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
    Correlation vs Covariance
    Simple linear regression
    data science interview questions

    ReplyDelete
  28. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    workday studio online training
    best workday studio online training
    top workday studio online training

    ReplyDelete
  29. Thanks for sharing great information. I like your blog and highly recommend. We also offer best data science training in Hyderabaddata scientist courses

    ReplyDelete
  30. Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.
    sap training in chennai

    sap training in tambaram

    azure training in chennai

    azure training in tambaram

    cyber security course in chennai

    cyber security course in tambaram

    ethical hacking course in chennai

    ethical hacking course in tambaram

    ReplyDelete
  31. It's very useful blog post with informative and insightful content and i had good experience with this information. We, at the CRS info solutions ,help candidates in acquiring certificates, master interview questions, and prepare brilliant resumes.Find top Salesforce admin interview questions in 2020.
    These Salesforce developer interview questions are highly helpful in 2020. You can read these Salesforce lightning interview questions and Salesforce integration interview questions which are prepared by industry experts.

    ReplyDelete
  32. Thanks for a marvelous posting! I seriously enjoyed reading it, you are
    a great author.I will be sure to bookmark your blog and will often come back in the future.
    I want to encourage yourself to continue your great job, have a
    nice weekend!
    angular js training in chennai

    angular js training in velachery

    full stack training in chennai

    full stack training in velachery

    php training in chennai

    php training in velachery

    photoshop training in chennai

    photoshop training in velachery


    ReplyDelete
  33. Hi
    How do I get to put a header color?

    ReplyDelete
  34. Found your post interesting to read. I cant wait to see your post soon. Good Luck for the upcoming update. This article is really very interesting and effective, data sciecne course in hyderabad

    ReplyDelete
  35. This is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.

    Simple Linear Regression

    Correlation vs Covariance

    ReplyDelete
  36. Amazing Article ! I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
    Simple Linear Regression
    Correlation vs covariance
    data science interview questions
    KNN Algorithm
    Logistic Regression explained

    ReplyDelete
  37. I am really enjoying reading your well written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work. data science training in Hyderabad

    ReplyDelete
  38. Very nice blogs!!! i have to learning for lot of information for this sites…Sharing for wonderful information.Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing, data sciecne course in hyderabad

    ReplyDelete
  39. Crypto-currency as a modern form of the digital asset has received a worldwide acclaim for easy and faster financial transactions and its awareness among people have allowed them to take more interest in the field thus opening up new and advanced ways of making payments. Crypto.com Referral Code with the growing demand of this global phenomenon more,new traders and business owners are now willing to invest in this currency platform despite its fluctuating prices however it is quite difficult to choose the best one when the market is full. In the list of crypto-currencies bit-coins is one of the oldest and more popular Crypto.com Referral Code for the last few years. It is basically used for trading goods and services and has become the part of the so-called computerized block-chain system allowing anyone to use it thus increasing the craze among the public, Crypto.com Referral Code.

    Common people who are willing to purchase BTC can use an online wallet system for buying them safely in exchange of cash or credit cards and in a comfortable way from the thousands of BTC foundations around the world and keep them as assets for the future. Due to its popularity, many corporate investors are now accepting them as cross-border payments and the rise is unstoppable. With the advent of the internet and mobile devices,information gathering has become quite easy as a result the BTC financial transactions are accessible and its price is set in accordance with people’s choice and preferences thus leading to a profitable investment with Crypto.com Referral Code Code. Recent surveys have also proved that instability is good for BTC exchange as if there is instability and political unrest in the country due to which banks suffer then investing in BTC can surely be a better option. Again bit-coin transaction fees are pretty cheaper and a more convenient technology for making contracts thus attracting the crowd. The BTC can also be converted into different fiat currencies and is used for trading of securities, for land titles, document stamping, public rewards and vice versa.

    Another advanced block-chain project is Ethereumor the ETH which has served much more than just a digital form of crypto-currency Crypto.com Referral Code and its popularity in the last few decades have allowed billions of people to hold wallets for them. With the ease of the online world,the ETH have allowed the retailers and business organizations to accept them for trading purposes, therefore, can serve as the future of the financial system.

    ReplyDelete
  40. Our full Lace Front Wigs are all hand made with a lace cap. They are manufactured with thin lace sewn on top of the cap. Individual hairs are then sewn onto the thin lace. Each lace wig has lace all around the unit which will need to be cut prior to securing the wig to your head. You will need to cut along the hairline around your entire head. By doing so, you will be able to wear your hair anyway you like. You can even style ponytails, up-dos, etc. Once the Lace Wigs is successfully applied, it will appear that all the hair is growing directly from your head!

    Lace front wigs are hand-made with lace front cap & machine weft at back. Lace front wigs are manufactured with a thin lace that extends from ear to ear across the hairline. When you receive the wig, the lace will be quite long in the front. Cut and style according to your preference, as you will need to apply adhesive along the front of the wig. Once the wig is applied, you will still have Lace Wigs with a very natural appearance.
    TeamWigz Provide the Best Lace Front Wigs and Lace Wigs in Johannesburg and South Africa.

    ReplyDelete
  41. This is an opportunity to identify them, and make their liberation part of the overall programme of change. Salesforce training in Hyderabad

    ReplyDelete