Maximizing font size in FPDF
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!
Related posts:
February 10th, 2011 at 12:19 pm
Thanks for this function. Exactly what i was looking for. (we print a document with a fixed window size for comments)