13

I am trying to Wrap a text in the Cell using FPDF. here is my code.

<?php
require('fpdf.php');

$pdf = new FPDF();

$pdf->AddPage();
$pdf->SetFont('Arial','',16);
$pdf->Cell(20,7,'Hi1',1);
$pdf->Cell(20,7,'Hi2',1);
$pdf->Cell(20,7,'Hi3',1);

$pdf->Ln();

$pdf->Cell(20,7,'Hi4',1);
$pdf->Cell(20,7,'Hi5(xtra)',1);
$pdf->Cell(20,7,'Hi5',1);

$pdf->Output();
?>

The output for this code looks like this enter image description here

Now I want to Wrap that Xtra text which is there into the Cell. The xtra text should go into the second line. How should I do that.

when I use MultiCell for that line $pdf->MultiCell( 20, 7, 'Hi5(xtra)', 1); It is changing into the following.. enter image description here

I have tried the Answer mentioned by Log1c It came out this way enter image description here

Jay
  • 477
  • 3
  • 7
  • 20

8 Answers8

20

Use MultiCell() instead Cell()

Change this:

$pdf->Cell(20,7,'Hi5(xtra)',1);

To:

$pdf->MultiCell( 20, 7, 'Hi5(xtra)', 1);

The MultiCell() is used for print text with multiple lines.

EDIT:

I can see that MultiCell(), breaks the line so new cell will be placed below current position.

In such case you can calculate x and y co-ordinate and calculate new position and set position after outputting every cell.

<?php
require('fpdf.php');

$pdf = new FPDF();

$pdf->AddPage();

$start_x=$pdf->GetX(); //initial x (start of column position)
$current_y = $pdf->GetY();
$current_x = $pdf->GetX();

$cell_width = 20;  //define cell width
$cell_height=7;    //define cell height

$pdf->SetFont('Arial','',16);

$pdf->MultiCell($cell_width,$cell_height,'Hi1',1); //print one cell value
$current_x+=$cell_width;                           //calculate position for next cell
$pdf->SetXY($current_x, $current_y);               //set position for next cell to print

$pdf->MultiCell($cell_width,$cell_height,'Hi2',1); //printing next cell
$current_x+=$cell_width;                           //re-calculate position for next cell
$pdf->SetXY($current_x, $current_y);               //set position for next cell

$pdf->MultiCell($cell_width,$cell_height,'Hi3',1);
$current_x+=$cell_width;

$pdf->Ln();
$current_x=$start_x;                       //set x to start_x (beginning of line)
$current_y+=$cell_height;                  //increase y by cell_height to print on next line

$pdf->SetXY($current_x, $current_y);

$pdf->MultiCell($cell_width,$cell_height,'Hi4',1);
$current_x+=$cell_width;
$pdf->SetXY($current_x, $current_y);

$pdf->MultiCell($cell_width,$cell_height,'Hi5(xtra)',1);
$current_x+=$cell_width;
$pdf->SetXY($current_x, $current_y);

$pdf->MultiCell($cell_width,$cell_height,'Hi5',1);
$current_x+=$cell_width;
$pdf->SetXY($current_x, $current_y);

$pdf->Output();
?>
Ravi Dhoriya ツ
  • 4,435
  • 8
  • 37
  • 48
  • when i have used the multicell I am getting it as above - I have edit my question Please check. Hi5 is going into 3rd row. which is not what i want. – Jay May 08 '14 at 13:04
  • Not sure, but try changing all `Cell()` to `MultiCell()` – Ravi Dhoriya ツ May 08 '14 at 13:07
  • No its not working all are going into next line. Ideally it has created 6 rows and only one column. – Jay May 08 '14 at 13:10
  • Yes I have tried. I will edit my question and add the picture please check. The main cell "Hi5(Xtra) is going into the next row but along with that I want other two cell "Hi4" and "Hi5" also to extend. – Jay May 08 '14 at 14:49
  • because those are separate cells and not a same row internally. – Ravi Dhoriya ツ May 09 '14 at 06:48
4

I dont think Multicell is the solution for this.Problems in using multicell.

  • line breaks enter image description here

  • overlaps with next row enter image description here

  • More over we cant able predict how much height a cell may goes? eg: if first cell text length is 50 and the second text lenght is 100 then its height differs so we cant able to create as a table row.

    Even the above answer helps to solve only the break of line but not overlap problem.

Here i came with a new solution for this.a new function vcell() uses only cell in it to make the expected output successfully.

<?php
require('fpdf.php');
class ConductPDF extends FPDF {
function vcell($c_width,$c_height,$x_axis,$text){
$w_w=$c_height/3;
$w_w_1=$w_w+2;
$w_w1=$w_w+$w_w+$w_w+3;
$len=strlen($text);// check the length of the cell and splits the text into 7 character each and saves in a array 

$lengthToSplit = 7;
if($len>$lengthToSplit){
$w_text=str_split($text,$lengthToSplit);
$this->SetX($x_axis);
$this->Cell($c_width,$w_w_1,$w_text[0],'','','');
if(isset($w_text[1])) {
    $this->SetX($x_axis);
    $this->Cell($c_width,$w_w1,$w_text[1],'','','');
}
$this->SetX($x_axis);
$this->Cell($c_width,$c_height,'','LTRB',0,'L',0);
}
else{
    $this->SetX($x_axis);
    $this->Cell($c_width,$c_height,$text,'LTRB',0,'L',0);}
    }
 }
$pdf = new ConductPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','',16);
$pdf->Ln();
$x_axis=$pdf->getx();
$c_width=20;// cell width 
$c_height=6;// cell height
$text="aim success ";// content 
$pdf->vcell($c_width,$c_height,$x_axis,'Hi1');// pass all values inside the cell 
$x_axis=$pdf->getx();// now get current pdf x axis value
$pdf->vcell($c_width,$c_height,$x_axis,'Hi2');
$x_axis=$pdf->getx();
$pdf->vcell($c_width,$c_height,$x_axis,'Hi3');
$pdf->Ln();
$x_axis=$pdf->getx();
$c_width=20;
$c_height=12;
$text="aim success ";
$pdf->vcell($c_width,$c_height,$x_axis,'Hi4');
$x_axis=$pdf->getx();
$pdf->vcell($c_width,$c_height,$x_axis,'Hi5(xtra)');
$x_axis=$pdf->getx();
$pdf->vcell($c_width,$c_height,$x_axis,'Hi5');
$pdf->Ln();
$x_axis=$pdf->getx();
$c_width=20;
$c_height=12;
$text="All the best";
$pdf->vcell($c_width,$c_height,$x_axis,'Hai');
$x_axis=$pdf->getx();
$pdf->vcell($c_width,$c_height,$x_axis,'VICKY');
$x_axis=$pdf->getx();
$pdf->vcell($c_width,$c_height,$x_axis,$text);
$pdf->Ln();
$x_axis=$pdf->getx();
$c_width=20;
$c_height=6;
$text="Good";
$pdf->vcell($c_width,$c_height,$x_axis,'Hai');
$x_axis=$pdf->getx();
$pdf->vcell($c_width,$c_height,$x_axis,'vignesh');
$x_axis=$pdf->getx();
$pdf->vcell($c_width,$c_height,$x_axis,$text);
$pdf->Output();
?>

enter image description here

Function explanation:

function vcell($c_width,$c_height,$x_axis,$text){
$w_w=$c_height/3;
$w_w_1=$w_w+2;
$w_w1=$w_w+$w_w+$w_w+3;
// $w_w2=$w_w+$w_w+$w_w+$w_w+3;// for 3 rows wrap
$len=strlen($text);// check the length of the cell and splits the text into 7 character each and saves in a array 
if($len>7){
$w_text=str_split($text,7);// splits the text into length of 7 and saves in a array since we need wrap cell of two cell we took $w_text[0], $w_text[1] alone.
// if we need wrap cell of 3 row then we can go for    $w_text[0],$w_text[1],$w_text[2]
$this->SetX($x_axis);
$this->Cell($c_width,$w_w_1,$w_text[0],'','','');
$this->SetX($x_axis);
$this->Cell($c_width,$w_w1,$w_text[1],'','','');
//$this->SetX($x_axis);
// $this->Cell($c_width,$w_w2,$w_text[2],'','','');// for 3 rows wrap but increase the $c_height it is very important.
$this->SetX($x_axis);
$this->Cell($c_width,$c_height,'','LTRB',0,'L',0);
}
else{
    $this->SetX($x_axis);
    $this->Cell($c_width,$c_height,$text,'LTRB',0,'L',0);}
    } 
Community
  • 1
  • 1
Vigneswaran S
  • 2,039
  • 1
  • 20
  • 32
  • This is a really great solution Vigneswaran. Thank you. What does "w_w" represent? width_width? – JeremyCanfield May 10 '16 at 21:30
  • 1
    @JeremyCanfield: it a height . $w_w=$c_height/3; example:if you want to wrap a word with 3 line.and the cell height is 9 so 9/3=3. first w_w line will be echo in height 3 and next line is echoed in height 6 and next line will be in height 9. – Vigneswaran S May 13 '16 at 09:43
  • suppose You don't know whether cell is enough or not, how exactly are you proposing that if it needed to divide automatically..? For the first raw you hard coded height as 6 and for the 2nd raw you hard coded height as 12. What if this needed to decide automatically? – Chanaka Karunarathne Nov 21 '16 at 11:46
  • @ChanakaSuranga : I have given a idea, find a function which creates height automatically based on character count. then your problem solved :). Find automatically and pass it. – Vigneswaran S Dec 05 '16 at 10:26
2

i try this all solution but its break table row look. so i try this solution and its help me so much,

$pdf=new PDF_MC_Table();
$pdf->AddPage();
$pdf->SetFont('Arial','',14);
//Table with 20 rows and 4 columns
$pdf->SetWidths(array(30,50,30,40));
srand(microtime()*1000000);
for($i=0;$i<20;$i++)
    $pdf->Row(array("test","test testtesttesttest ","test","test testtesttesttest "));
$pdf->Output();

reference: FPDF

Dave
  • 3,073
  • 7
  • 20
  • 33
1

This automatically wrap the text into the cell by striking the font size :

class FPDF_CellFit extends FPDF
{
    //Cell with horizontal scaling if text is too wide
    function CellFit($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='', $scale=false, $force=true)
    {
        //Get string width
        $str_width=$this->GetStringWidth($txt);

        //Calculate ratio to fit cell
        if($w==0)
            $w = $this->w-$this->rMargin-$this->x;
        $ratio = ($w-$this->cMargin*2)/$str_width;

        $fit = ($ratio < 1 || ($ratio > 1 && $force));
        if ($fit)
        {
            if ($scale)
            {
                //Calculate horizontal scaling
                $horiz_scale=$ratio*100.0;
                //Set horizontal scaling
                $this->_out(sprintf('BT %.2F Tz ET',$horiz_scale));
            }
            else
            {
                //Calculate character spacing in points
                $char_space=($w-$this->cMargin*2-$str_width)/max(strlen($txt)-1,1)*$this->k;
                //Set character spacing
                $this->_out(sprintf('BT %.2F Tc ET',$char_space));
            }
            //Override user alignment (since text will fill up cell)
            $align='';
        }

        //Pass on to Cell method
        $this->Cell($w,$h,$txt,$border,$ln,$align,$fill,$link);

        //Reset character spacing/horizontal scaling
        if ($fit)
            $this->_out('BT '.($scale ? '100 Tz' : '0 Tc').' ET');
    }

    //Cell with horizontal scaling only if necessary
    function CellFitScale($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='')
    {
        $this->CellFit($w,$h,$txt,$border,$ln,$align,$fill,$link,true,false);
    }

    //Cell with horizontal scaling always
    function CellFitScaleForce($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='')
    {
        $this->CellFit($w,$h,$txt,$border,$ln,$align,$fill,$link,true,true);
    }

    //Cell with character spacing only if necessary
    function CellFitSpace($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='')
    {
        $this->CellFit($w,$h,$txt,$border,$ln,$align,$fill,$link,false,false);
    }

    //Cell with character spacing always
    function CellFitSpaceForce($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='')
    {
        //Same as calling CellFit directly
        $this->CellFit($w,$h,$txt,$border,$ln,$align,$fill,$link,false,true);
    }
}


$text="dfshsdbfhbsdhfbhsdbfkbfkbfkbdf";
   $this->CellFitScale(50,10,'  '.$text,1,0,'',0);//long text
0

I have faced the same problem and try to find a way of whether is a cell enough or not for the text and divide height by amount of line and use result as for the particular cell height. But, it only make code very complex. then I switch to a library called html2pdf. It creates html table which no any above mentioned conflict, And that page convert to pdf file. Use html2pdf library.. it is the easiest way of creating pdf with automatically divided cell. you can download it here and there are many guides in the internet.

Chanaka Karunarathne
  • 1,936
  • 2
  • 16
  • 14
0

Try this: You can pass column widths, column alignments, fills and links as arrays. if width is a number, it will be the width of the whole table.

<?php
require('fpdf.php');
class PDF extends FPDF{
    function plot_table($widths, $lineheight, $table, $border=1, $aligns=array(), $fills=array(), $links=array()){
        $func = function($text, $c_width){
            $len=strlen($text);
            $twidth = $this->GetStringWidth($text);
            $split = floor($c_width * $len / $twidth);
            $w_text = explode( "\n", wordwrap( $text, $split, "\n", true));
            return $w_text;
        };
        foreach ($table as $line){
            $line = array_map($func, $line, $widths);
            $maxlines = max(array_map("count", $line));
            foreach ($line as $key => $cell){
                $x_axis = $this->getx();
                $height = $lineheight * $maxlines / count($cell);
                $len = count($line);
                $width = (isset($widths[$key]) === TRUE ? $widths[$key] : $widths / count($line));
                $align = (isset($aligns[$key]) === TRUE ? $aligns[$key] : '');
                $fill = (isset($fills[$key]) === TRUE ? $fills[$key] : false);
                $link = (isset($links[$key]) === TRUE ? $links[$key] : '');
                foreach ($cell as $textline){
                    $this->cell($widths[$key],$height,$textline,0,0,$align,$fill,$link);
                    $height += 2 * $lineheight * $maxlines / count($cell);
                    $this->SetX($x_axis);
                }
                if($key == $len - 1){
                    $lbreak=1;
                }
                else{
                    $lbreak = 0;
                }
                $this->cell($widths[$key],$lineheight * $maxlines, '',$border,$lbreak);
            }
        }
    }
}
$pdf = new PDF('P','mm','A4');
$lineheight = 8;
$fontsize = 12;
$pdf->SetFont('Arial','',$fontsize);
$pdf->SetAutoPageBreak(true , 30);
$pdf->SetMargins(20, 1, 20);
$pdf->AddPage();

$table = array(array('Hi1', 'Hi2', 'Hi3'), array('Hi4', 'Hi5 (xtra)', 'Hi6'), array('Hi7', 'Hi8', 'Hi9'));
$widths = array(11,11,11);
$pdf->plot_table($widths, $lineheight, $table);
$pdf->Output('Table.pdf', 'I');
return;

Should draw this:FPDF table

0

<?php 
require "fpdf.php";

$db = new PDO("mysql:host=localhost;dbname=coba","root");
$id="";
class myPDF extends FPDF{
    function header(){
        $this->image('adw1.png',15,10);
  $this->image('huawei.png',235,13);
        $this->SetFont('Times','B',14);
        $this->Cell(276,10,'Berita Acara Barang Keluar',0,0,'C');
        $this->Ln();  
        $this->SetFont('Times','B',12);
        $this->Cell(276,10,'PT ADYAWINSA WEST JAVA',0,0,'C');
        $this->Ln(20);
  $this->SetFont('Times','',10);
        $this->Cell(276,-15,'JL. RUMAH SAKIT NO 108',0,0,'C');
        $this->Ln(5);
  $this->Line(10,36,287,36);
  $this->SetLineWidth(0);
  $this->Line(10,37,287,37);
  $this->Ln(5);
  $this->SetFont('Times','B',8);
  $this->Cell(8,10,'No',1,0,'C');
  $this->Cell(20,10,'Tgl Keluar',1,0,'C');
  $this->Cell(30,10,'Nama Receiver',1,0,'C');
  $this->Cell(60,10,'Nama Barang',1,0,'C');
  $this->Cell(15,10,'Bom Code',1,0,'C');
  $this->Cell(35,10,'Site Name',1,0,'C');
  $this->Cell(20,10,'Site ID',1,0,'C');
        $this->Cell(10,10,'Qty',1,0,'C');
  $this->Cell(10,10,'Unit',1,0,'C');
  $this->Cell(20,10,'Material Type',1,0,'C');
  $this->Cell(20,10,'Nama Project',1,0,'C');
  $this->Cell(30,10,'Keterangan',1,0,'C');
        $this->Ln();
    }
    function footer(){
        $this->SetY(-15);
        $this->SetFont('Arial','',8);
        $this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');
  $this->SetY(140);
        $this->SetFont('Arial','',10);
        $this->Cell(100,10,'Receiver',0,0,'C');
  $this->SetY(140);
        $this->SetFont('Arial','',10);
        $this->Cell(0,10,'Verified By',0,0,'C');
  $this->SetY(140);
        $this->SetFont('Arial','',10);
        $this->Cell(450,10,'Approved By',0,0,'C');
  $this->SetY(160);
        $this->SetFont('Arial','',10);
        $this->Cell(100,10,'(.........................)',0,0,'C');
  $this->SetY(160);
        $this->SetFont('Arial','',10);
        $this->Cell(0,10,'(.........................)',0,0,'C');
  $this->SetY(160);
        $this->SetFont('Arial','',10);
        $this->Cell(450,10,'(.........................)',0,0,'C');
    }
    function viewTable($db){
  $no=1;
  $id = $_GET['bk_id'];
        $this->SetFont('Times','',6);
        $stmt = $db->query("SELECT tgl_keluar, nama_karyawan, barang_nama, bom_code, site_name, site_id, qty, barang_kategori, material_type, nama_project, keterangan from barang_keluar INNER JOIN bk_detail ON barang_keluar.bk_id = bk_detail.bk_id where barang_keluar.bk_id = '$id'");
  while($data = $stmt->fetch(PDO::FETCH_OBJ))
  {
   $this->Cell(8,10,$no++,1,0,'C');
   $this->Cell(20,10,$data->tgl_keluar,1,0,'C');
   $this->Cell(30,10,$data->nama_karyawan,1,0,'C');
   $this->Cell(60,10,$data->barang_nama,1,0,'C');
   $this->Cell(15,10,$data->bom_code,1,0,'C');
   $this->Cell(35,10,$data->site_name,1,0,'C');
   $this->Cell(20,10,$data->site_id,1,0,'C');
            $this->Cell(10,10,$data->qty,1,0,'C');
   $this->Cell(10,10,$data->barang_kategori,1,0,'C');
   $this->Cell(20,10,$data->material_type,1,0,'C');
   $this->Cell(20,10,$data->nama_project,1,0,'C');
   $this->Cell(30,10,$data->keterangan,1,0,'C');
   $this->Ln();
           
        }
 }
}
$pdf = new myPDF();
$pdf->SetAutoPageBreak(true,70);
$pdf->AliasNbPages();
$pdf->AddPage('L','A4',0);
$pdf->viewTable($db);
$pdf->Output();;
-1

you shoud use space between words, if it will be no space string it will remain as is ... try the following

<?php
require('fpdf.php');

$pdf = new FPDF();

$pdf->AddPage();
$pdf->SetFont('Arial','',16);
$pdf->Cell(20,7,'Hi1',1);
$pdf->Cell(20,7,'Hi2',1);
$pdf->Cell(20,7,'Hi3',1);

$pdf->Ln();

$pdf->Cell(20,7,'Hi4',1);
$pdf->Cell(20,7,'Hi5 (xtra)',1);
$pdf->Cell(20,7,'Hi5',1);

$pdf->Output();
?>

enjoy :)

Anri
  • 1,706
  • 2
  • 17
  • 36