Search code examples
phpwhile-looptcpdfsubstr

Using GetStringWidth in TCPDF to short a string


I'm using TCPDF to print a Barcode sheet label. Each label has a barcode and some text underneath. Evreything seems to work fine, but somtimes the text is to long and 'invade' the next label/next line.

I'm trying to check the length of the string - and short it if needed:

$label_w = ($page_w-$right_mar-$left_mar)/$Col;
$text_width = $pdf->GetStringWidth($exploded_line[2]);
while ($text_width>$label_w-15) // "-15" because the text location
    {
        $exploded_line[2]=substr($exploded_line[2],0,-1);
        $text_width = $pdf->GetStringWidth($exploded_line[2]);
    }

The text that going into the loop just continue shrinking until only the first letter left...

At first I thought that the problem is that my While condition isn't stopping for some reason. Then I tried changing it to simple if - BUT the problem isn't gone...

if ($text_width>$label_w-15)
    {
        $exploded_line[2]=substr($exploded_line[2],0,-1);
        $text_width = $pdf->GetStringWidth($exploded_line[2]);
    }

Any suggestions? Thanks.


Solution

  • OK, finally I got it. The problem was really in the substr function. I'm using UTF-8, so I had to use mb_substr...

    $exploded_line[2]=mb_substr($exploded_line[2],0,-1,"utf-8");
    

    This is working as expected. Thanks anyway.