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!

This entry was posted on Tuesday, June 22nd, 2010 at 9:27 am and is filed under Programming, Work. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

5 Responses to “Maximizing font size in FPDF”

  1. Mordy GNo Gravatar Says:

    Thanks for this function. Exactly what i was looking for. (we print a document with a fixed window size for comments)

  2. HelenNo Gravatar Says:

    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!

  3. Matt PorterNo Gravatar Says:

    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.

  4. Curtis GibbyNo Gravatar Says:

    You can call the method like this:

    “`
    $fontSize = $pdf->SetMaxFontSize($text, BOX_WIDTH, 2, 1);
    “`

    Then use $fontSize however you want.

  5. Matt PorterNo Gravatar Says:

    Thanks Curtis, I bet you never thought you would get a query after so long!

    Very useful function

    Cheers

    Matt

Leave a Reply