4

さまざまな (完全ではない) PHP コンバーター/ジェネレーターを使用して、RTF、PDF などにエクスポートしたいデータのグリッドがあります。

私が最も欠けているのは、セル内の文字列の長さに基づいた HTML テーブルの列幅の自動調整です (文字列には改行が含まれているため、保持する必要があるため、少し複雑になります)。

セルの内容 (プレーン テキスト)、テーブルの合計幅、および文字の平均幅を考慮して、各列の幅を返すアルゴリズムが必要です。何かがすでに利用可能である場合、私は車輪を再発明したくありません.

もちろん、フォントが可変幅の場合は完全ではありませんが、概算で問題ありません。または、各文字の幅を設定可能なテーブルを持つこともできます。

ヒントをいただければ幸いです。

4

1 に答える 1

2

これは簡単なことではありません。

PHPExcel では、セルが自動幅に設定されている場合、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;
于 2010-06-16T09:00:30.497 に答える