Pergunta

Eu tenho uma grade de dados que quero exportar para RTF, PDF etc. usando vários conversores/geradores PHP (e não perfeitos).

O que mais estou perdendo é a tabela HTML Ajuste automático das larguras da coluna com base nos comprimentos das cordas nas células (as cordas contêm quebras de linha que complicam um pouco as coisas, como devem ser preservadas).

Preciso de um algoritmo que, dado o conteúdo das células (texto simples), uma largura total da tabela e uma largura média de um caractere retornariam uma largura para cada coluna. Eu não gostaria de reinventar a roda se algo já estivesse disponível.

Claro que não pode ser perfeito se a fonte for uma largura variável, mas uma aproximação se sairia bem. Ou talvez possa ter uma tabela configurável com larguras para cada caractere.

Qualquer dica seria apreciada.

Foi útil?

Solução

Esta não é fácil.

No PhPexcel, quando uma célula está definida como AutoWidth, usamos a função da biblioteca 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;

É muito intensivo, especialmente ao trabalhar com grandes planilhas, por isso também temos um método alternativo (aproximação)

// 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;
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top