Fit text string to cell in FPDF

Something I really hate (and am not very good at thoroughly testing) is ensuring that a layout I’ve designed will nicely fit user data of any length. Of course you can easily wrap all text outputting on a webpage or a dynamically generated PDF in a truncate() method, however this crude method isn’t always sufficient.

Today, I was auto generating a PDF certificate (using the PHP PDF generation library: FPDF) and needed the company name and URL to fit nicely on the page. I used FPDF’s handy function  GetStringWidth() to acheive a nice little solution to ensuring the string fit on one line of the PDF.

	$my_string = 'This is my variable length string!';
	$font_size = 14;
	$decrement_step = 0.1;
	$line_width = 160; // Line width (approx) in mm
	$pdf->SetFont('Verdana', 'B', $font_size);
	while($pdf->GetStringWidth($my_string) > $line_width) {
		$pdf->SetFontSize($font_size -= $decrement_step);
	$pdf->Cell($line_width, 10, $my_string, 0, 1, 'C');

The above code slowly makes the string shorter until it fits the right length. I hope that helps!

comments powered by Disqus