Skip to content

Instantly share code, notes, and snippets.

@xu-li
Last active April 4, 2018 06:11
Show Gist options
  • Save xu-li/422cb1466840e78cb037d2a77731a306 to your computer and use it in GitHub Desktop.
Save xu-li/422cb1466840e78cb037d2a77731a306 to your computer and use it in GitHub Desktop.
FPDF::fillText, fillText in a rectangular area
<?php
/**
* Fill text in a rectangular area
*
* It will automatically decrease font size if it exceeds the boundary.
* It also takes cMargin into consideration.
*
* @see FPDF::Cell()
*
* @param string $text
* @param number $x
* @param number $y
* @param number $w
* @param number $h
* @param string $align
* @param string $link
*/
public function fillText($text, $x, $y, $w, $h, $align = 'C', $link = '')
{
// remove margins
$width_without_margin = $w - 2 * $this->cMargin;
// save the old font size so that we can revert it back
$old_font_size = $font_size = $this->FontSizePt;
// get the initial text width
$text_width = $this->GetStringWidth($text);
// only decrease font size if it exceeds the boundary
if ($text_width > $width_without_margin) {
do {
$font_size--;
$this->SetFontSize($font_size);
$text_width = $this->GetStringWidth($text);
} while ($text_width > $width_without_margin);
// adjust x
if ($align == 'R') {
$x = $x + $w - $text_width - 2 * $this->cMargin;
} else if ($align == 'C') {
$x = $x + $w / 2 - $text_width / 2 - $this->cMargin;
}
$w = $text_width + 2 * $this->cMargin;
}
// draw text
$this->SetXY($x, $y);
// $this->Cell($w, $h, $text, 1, 0, $align, false, $link);
$this->Cell($w, $h, $text, 0, 0, $align, false, $link);
// revert back
$this->SetFontSize($old_font_size);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment