我有数据的一个网格,我想出口到RTF,PDF等使用各种(而不是完美的)PHP转换器/发生器。

我所缺少的是大多数基于字符串的在细胞中的长度列宽的HTML表自动调整(字符串包含换行符,其复杂的事情一点,因为它们应该被保留)。

我需要一种算法,考虑到细胞(纯文本),表中的总宽度和字符的平均宽度的内容,将返回一个宽度为每个列。我不想重新发明轮子,如果事情已经可用。

当然,如果字体是可变的宽度,但是近似会做就好它不能是完美的。或者它可以具有与宽度为每个字符可配置的表。

任何暗示,将不胜感激。

有帮助吗?

解决方案

这是不容易的。

在PHPExcel,当小区被设置为autowidth,我们使用GD库imagettfbbox()函数

// font size should really be supplied in pixels in GD2,
// but since GD2 seems to assume 72dpi, pixels and points are the same
$fontFile = self::getTrueTypeFontFileFromFont($font);
$textBox = imagettfbbox($font->getSize(), $rotation, $fontFile, $text);

// Get corners positions
$lowerLeftCornerX  = $textBox[0];
$lowerLeftCornerY  = $textBox[1];
$lowerRightCornerX = $textBox[2];
$lowerRightCornerY = $textBox[3];
$upperRightCornerX = $textBox[4];
$upperRightCornerY = $textBox[5];
$upperLeftCornerX  = $textBox[6];
$upperLeftCornerY  = $textBox[7];

// Consider the rotation when calculating the width
$textWidth = max($lowerRightCornerX - $upperLeftCornerX, $upperRightCornerX - $lowerLeftCornerX);

return $textWidth;

这是非常密集的,虽然,特别是大型工作表中工作时,因此我们还具有替代的(近似)方法

// Calculate column width in pixels. We assume fixed glyph width. Result varies with font name and size.
switch ($fontName) {
    case 'Calibri':
        // value 8.26 was found via interpolation by inspecting real Excel files with Calibri 11 font.
        $columnWidth = (int) (8.26 * PHPExcel_Shared_String::CountCharacters($columnText));
        $columnWidth = $columnWidth * $fontSize / 11; // extrapolate from font size
        break;

    case 'Arial':
        // value 7 was found via interpolation by inspecting real Excel files with Arial 10 font.
        $columnWidth = (int) (7 * PHPExcel_Shared_String::CountCharacters($columnText));
        $columnWidth = $columnWidth * $fontSize / 10; // extrapolate from font size
        break;

    case 'Verdana':
        // value 8 was found via interpolation by inspecting real Excel files with Verdana 10 font.
        $columnWidth = (int) (8 * PHPExcel_Shared_String::CountCharacters($columnText));
        $columnWidth = $columnWidth * $fontSize / 10; // extrapolate from font size
        break;

    default:
        // just assume Calibri
        $columnWidth = (int) (8.26 * PHPExcel_Shared_String::CountCharacters($columnText));
        $columnWidth = $columnWidth * $fontSize / 11; // extrapolate from font size
        break;
}

// Calculate approximate rotated column width
if ($rotation !== 0) {
    if ($rotation == -165) {
        // stacked text
        $columnWidth = 4; // approximation
    } else {
        // rotated text
        $columnWidth = $columnWidth * cos(deg2rad($rotation))
                        + $fontSize * abs(sin(deg2rad($rotation))) / 5; // approximation
    }
}

// pixel width is an integer
$columnWidth = (int) $columnWidth;
return $columnWidth;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top