Fit text string to cell in FPDF

May 19th, 2011 by paul Leave a reply »

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');
...
Advertisement

1 comment

  1. Matt says:

    Like the solution.

    I’m looking for a code template to generate a nice looking certificate.

    Need to add a company logo, candidate name, date, course centre.
    Otherwise simple.
    Any ideas where I can get it?

Leave a Reply