Wrapping text for Zend Pdf
June 4, 2008 12:40 pm PHP, Zend FrameworkA common issue in Zend_Pdf is to wrap text in a box. I’ve found partial solutions such as wrapping text each 80 characters for instance but the line width can vary regarding the font and the character width. Since we can’t rely on the character count unless using a monospaced font, we have to wrap text on the real box width.
In partial solutions, I’ve found a function which computes the real width of a string according to the font and the font size. By aggregating every chunks, I’ve made my getWrappedText() method which returns a string with the correct \n :
protected function getWrappedText($string, Zend_Pdf_Style $style,$max_width)
{
$wrappedText = '' ;
$lines = explode("\n",$string) ;
foreach($lines as $line) {
$words = explode(' ',$line) ;
$word_count = count($words) ;
$i = 0 ;
$wrappedLine = '' ;
while($i < $word_count)
{
/* if adding a new word isn't wider than $max_width,
we add the word */
if($this->widthForStringUsingFontSize($wrappedLine.' '.$words[$i]
,$style->getFont()
, $style->getFontSize()) < $max_width) {
if(!empty($wrappedLine)) {
$wrappedLine .= ' ' ;
}
$wrappedLine .= $words[$i] ;
} else {
$wrappedText .= $wrappedLine."\n" ;
$wrappedLine = $words[$i] ;
}
$i++ ;
}
$wrappedText .= $wrappedLine."\n" ;
}
return $wrappedText ;
}
/**
* found here, not sure of the author :
* http://devzone.zend.com/article/2525-Zend_Pdf-tutorial#comments-2535
*/
protected function widthForStringUsingFontSize($string, $font, $fontSize)
{
$drawingString = iconv('UTF-8', 'UTF-16BE//IGNORE', $string);
$characters = array();
for ($i = 0; $i < strlen($drawingString); $i++) {
$characters[] = (ord($drawingString[$i++]) << 8 ) | ord($drawingString[$i]);
}
$glyphs = $font->glyphNumbersForCharacters($characters);
$widths = $font->widthsForGlyphs($glyphs);
$stringWidth = (array_sum($widths) / $font->getUnitsPerEm()) * $fontSize;
return $stringWidth;
}
then you can draw the text easily :
$y = 700;
$lines = explode("\n",$this->getWrappedText($text,$style_text,400)) ;
foreach($lines as $line)
{
$page2->drawText($line, 140, $y);
$y-=15;
}
