Pregunta

Tengo una cuadrícula de datos que desea exportar a RTF, PDF, etc. utilizando diversas (y no perfectos) PHP / generadores convertidores.

Lo que más falta es la tabla HTML ajuste automático del ancho de las columnas en base a las longitudes de las cadenas en las células (cadenas contienen saltos de línea, que complicar las cosas un poco, ya que deben ser preservados).

I necesita un algoritmo que, dado el contenido de las células (texto sin formato), una anchura total de la mesa y una anchura media de un carácter, volvería una anchura para cada columna. No me gustaría que reinventar la rueda si algo está ya disponible.

Por supuesto que no puede ser perfecto si la fuente es de anchura variable, pero una aproximación haría muy bien. O tal vez podría tener una tabla configurable con anchuras para cada personaje.

Cualquier indicio sería apreciada.

¿Fue útil?

Solución

Esto no es una tarea fácil.

En PHPExcel, cuando una célula se establece en ANCHO AUTO, se utiliza la función de 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;

Es aunque muy intensa, sobre todo cuando se trabaja con grandes hojas de trabajo, por lo que también tenemos un método alternativo (aproximación)

// 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 bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top