/** * Calculate an (approximate) OpenXML column width, based on font size and text contained * * @param int $fontSize Font size (in pixels or points) * @param bool $fontSizeInPixels Is the font size specified in pixels (true) or in points (false) ? * @param string $cellText Text to calculate width * @param int $rotation Rotation angle * @return int Column width */ public static function calculateColumnWidth(Style_Font $font, $cellText = '', $rotation = 0, Style_Font $defaultFont = null) { // If it is rich text, use plain text if ($cellText instanceof RichText) { $cellText = $cellText->getPlainText(); } // Special case if there are one or more newline characters ("\n") if (strpos($cellText, "\n") !== false) { $lineTexts = explode("\n", $cellText); $lineWitdhs = array(); foreach ($lineTexts as $lineText) { $lineWidths[] = self::calculateColumnWidth($font, $lineText, $rotation = 0, $defaultFont); } return max($lineWidths); // width of longest line in cell } // Try to get the exact text width in pixels try { // If autosize method is set to 'approx', use approximation if (self::$autoSizeMethod == self::AUTOSIZE_METHOD_APPROX) { throw new Exception('AutoSize method is set to approx'); } // Width of text in pixels excl. padding $columnWidth = self::getTextWidthPixelsExact($cellText, $font, $rotation); // Excel adds some padding, use 1.07 of the width of an 'n' glyph $columnWidth += ceil(self::getTextWidthPixelsExact('0', $font, 0) * 1.07); // pixels incl. padding } catch (Exception $e) { // Width of text in pixels excl. padding, approximation $columnWidth = self::getTextWidthPixelsApprox($cellText, $font, $rotation); // Excel adds some padding, just use approx width of 'n' glyph $columnWidth += self::getTextWidthPixelsApprox('n', $font, 0); } // Convert from pixel width to column width $columnWidth = Shared_Drawing::pixelsToCellDimension($columnWidth, $defaultFont); // Return return round($columnWidth, 6); }