有没有人有一个简单的方法来计算一个页面上的一个文本将以特定的字体和大小消耗多少点? (容易=代码计算量最小的代码). Zend_Pdf似乎没有这样做的功能,除了一些非常昂贵的调用每个字符getGlyphForCharacter(),getUnitsPerEm()和getWidthsForGlyph().
我正在每个页面上生成一个多页的PDF表格,并且需要在列中包装文本.创建它已经花了几秒钟时间,我不希望它花费太多时间,或者我不得不开始搞乱后台任务或进度条.
我想出的唯一解决方案是预先计算每个字体使用的每个字符的宽度(以点为单位),然后将它们添加到每个字符串上.仍然相当昂贵.
我错过了什么吗?还是有更简单的东西?
谢谢!
有一种方法来准确计算宽度,而不是使用
Gorilla3D’s worst case algorithm.
请尝试此代码从http://devzone.zend.com/article/2525-Zend_Pdf-tutorial#comments-2535
我在我的应用程序中使用它来计算右对齐文本的偏移量,它的作用
- /**
- * Returns the total width in points of the string using the specified font and
- * size.
- *
- * This is not the most efficient way to perform this calculation. I'm
- * concentrating optimization efforts on the upcoming layout manager class.
- * Similar calculations exist inside the layout manager class,but widths are
- * generally calculated only after determining line fragments.
- *
- * @link http://devzone.zend.com/article/2525-Zend_Pdf-tutorial#comments-2535
- * @param string $string
- * @param Zend_Pdf_Resource_Font $font
- * @param float $fontSize Font size in points
- * @return float
- */
- 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;
- }
关于表演,我没有在剧本中集中精力,但是我可以想象它的速度很慢.如果可能,我建议将PDF写入磁盘,所以重复的视图非常快,缓存/硬编码数据也是可能的.