At work, I use the excellent FPDF library to write PDF files. But I couldn’t find any way to automatically make the text as large as possible to fit into a given space. So I wrote the following function to stick into the FPDF class. It’ll take a given text string and a width, incrementally set the font size higher and higher until it over-runs the space, then gives you the right size to just fit into the width.
/** * Function to maximize the text size based on a given text string and width * * returns the calculated text size */ function SetMaxFontSize($text, $maxWidth, $step = 1, $fontMin = 1) { // prevent stupidity if ($maxWidth < 0) { $maxWidth = 1; } if ($step < 0) { $step = 1; } if ($fontMin < 0) { $fontMin = 1; } $fontSize = $fontMin; $text_width = 1; while($text_width < $maxWidth) { $this->SetFontSize($fontSize); $text_width=$this->GetStringWidth($text); $fontSize += $step; // larger step is faster, smaller step is more accurate } $fontSize -= ($step * 2); // this is the biggest you can get without going over $this->SetFontSize($fontSize); return $fontSize; }
Here’s how I’m calling it in my PDF-generating script.
// you have to set the font first (at least once someplace in the script), or else FPDF throws an error $pdf->SetFont($fontName,'',1); // make the text as big as possible without overflowing $pdf->SetMaxFontSize($text, BOX_WIDTH, 2, 1);
The third and fourth parameters in the function are the step size (larger step is faster, smaller step is more accurate) and the beginning font size value. They’re both optional.
Hope this helps someone!
Thanks for this function. Exactly what i was looking for. (we print a document with a fixed window size for comments)
Hi,
Thanks so much for this… it was exactly what I was looking for on a time budget as well… I added a maxSize to it and took 20pts off the maxWidth to allow for the default padding in a multicell and it’s perfect!
Thanks!
Any idea how I can return the text size? I’m trying to print flowing text equally spaced at different sizes underneath each other. If I know the text size (or height) I can adjust the positioning for the next line.
You can call the method like this:
“`
$fontSize = $pdf->SetMaxFontSize($text, BOX_WIDTH, 2, 1);
“`
Then use $fontSize however you want.
Thanks Curtis, I bet you never thought you would get a query after so long!
Very useful function
Cheers
Matt