blib/lib/Excel/Template/Element/Cell/AutoSize.pm untested

filter: Statementstmt 0.0% 0 / 44 Branchbran 0.0% 0 / 10 Conditioncond 0.0% 0 / 8 MC/DCmcdc 0.0% 0 / 4 Subroutinesub 0.0% 0 / 6 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 74 CC 6 SCAR 31.7
CC
6
Cov
0%
render
42.0
BEGIN
2.0
BEGIN
2.0
CRAP 23.8
1 package Excel::Template::Element::Cell::AutoSize;
2 $VERSION = '0.04';
3 use strict;
4
5 BEGIN {
6 use Excel::Template::Element::Cell;
7 use Font::TTFMetrics;
8 use vars qw(@ISA);
9
10 @ISA = qw(Excel::Template::Element::Cell);
11
12 Excel::Template::Factory::register(name => 'CELLAUTOSIZE', class => 'Excel::Template::Element::Cell::AutoSize', isa => 'CELL');
13 }
14
15 sub render
16 {
17 my $self = shift;
18 my ($context) = @_;
19
20 my $font_path = $ENV{'FONT_PATH'} || die "Environment variable FONT_PATH not set\n";
21 my $font_name = lc($context->active_format->{'_font'});
22 $font_name .= 'bd' if $context->active_format->{'_bold'} == 700;
23 my $font_size = $context->active_format->{'_size'};
24
25 my $font_found = 0;
26 foreach my $path (split(':', $font_path)){
27 $font_found = 1 if -e "$path/$font_name.ttf";
28 $font_path = $path if $font_found;
29 last if $font_found;
30 }
31
32 my $font = Font::TTFMetrics->new("$font_path/$font_name.ttf") || die "Font $font_name not found\n";
33
34 my $dpi = 96;
35 my $units_per_em = $font->get_units_per_em();
36 my $text = $self->get_text($context) || ' ';
37 my $font_width = $font->string_width($text);
38
39 #The following expression is from the TTFMetrics docs.
40 my $pixel_width = $font_width *$font_size *$dpi /(72 *$units_per_em);
41
42 #The following expression is from the Spreadsheet::WriteExcel internals.
43 my $cell_width = (($pixel_width -5) /7) + 1; # For cell widths > 1
44
45 #Set larger column width if $cell_text_length is greater than current max for column
46 my $max_width_key = '_COL_WIDTH_' . $context->get($self, 'COL');
47 #Initialize current max column width if this is our first access of this column
48 $context->active_worksheet->{$max_width_key} = $context->active_worksheet->{$max_width_key} || 0;
49
50 #print $font_name . "," . $context->active_format->{'_bold'} . "\n";
51 if ($cell_width > $context->active_worksheet->{$max_width_key}){
52 $context->active_worksheet->{$max_width_key} = $cell_width;
53 $context->active_worksheet->set_column($context->get($self, 'COL'), $context->get($self, 'COL'), $cell_width);
54 }
55 $context->active_worksheet->write(
56 (map { $context->get($self, $_) } qw(ROW COL)),
57 $self->get_text($context),
58 $context->active_format,
59 );
60
61 return 1;
62 }
63
64 1;
65 __END__