File Coverage

blib/lib/PDF/Table/ColumnWidth.pm
Criterion Covered Total %
statement 66 154 42.8
branch 11 56 19.6
condition 1 18 5.5
subroutine 5 6 83.3
pod 0 2 0.0
total 83 236 35.1


line stmt bran cond sub pod time code
1             package PDF::Table::ColumnWidth;
2              
3 4     4   24 use strict;
  4         6  
  4         95  
4 4     4   16 use warnings;
  4         5  
  4         76  
5              
6 4     4   16 use Carp;
  4         6  
  4         176  
7 4     4   19 use List::Util qw[min max]; # core
  4         5  
  4         5468  
8              
9             our $VERSION = '1.004'; # VERSION
10             our $LAST_UPDATE = '1.003'; # manually update whenever code is changed
11              
12             ###################################################################
13             # calculate the column widths
14             # minimum: any specified min_w, increased to longest word in column
15             # maximum: largest total length of content, reduced to any spec. max_w
16             # maximum must be at least as large as minimum
17             # TBD: rules and borders? currently overlay cells. consider
18             # expanding h and w by width of rules and borders. would involve
19             # mucking with cell background fill dimensions? remember that
20             # rule widths could vary by cell. perhaps could just increase cell
21             # dimensions (and padding) by rule widths, and continue to overlay?
22             # expand min widths to fill to desired total width, try not to
23             # exceed maximum widths
24             # NOTE: this routine is called directly from t/PDF-Table.t
25             ###################################################################
26              
27             sub CalcColumnWidths {
28 13     13 0 1220 my $avail_width = shift; # specified table width
29 13         20 my $col_min_width = shift; # content-driven min widths (longest word) and
30             # optional min_w
31 13         16 my $col_max_content = shift; # content-driven max widths
32 13         17 my $max_w = shift; # -1 unless optional max_w for column
33              
34 13         15 my $min_width = 0; # calculate minimum overall table width needed
35 13         15 my $calc_widths ; # each column's calculated width
36              
37 13         20 my $num_cols = scalar(@$max_w);
38             # total requested minimum width (min_w property) plus min for content
39             # also initialize result calc_widths to min_width
40 13         49 for (my $j = 0; $j < scalar $num_cols; $j++) {
41             # min_w requested minimum AND longest word
42 36         56 $calc_widths->[$j] = $col_min_width->[$j];
43             # overall table minimum width
44 36         62 $min_width += $calc_widths->[$j];
45             }
46              
47             # minimum possible width for each column results in wider table?
48 13 50       29 if ($avail_width < $min_width) {
49 0         0 carp "!!! Warning !!!\n Table width expanded from $avail_width to $min_width\n";
50 0         0 $avail_width = $min_width;
51             }
52              
53             # Calculate how much can be added to every column to fit the available width
54             # Allow columns to expand to max_w before applying extra space equally.
55             # @max is SMALLER of max_w (if given) and content length, but at least as
56             # large as $col_min_width
57 13         20 my (@max, @natural, @indices);
58              
59             # @max = absolute widest this column can be
60             # initially max_w if given (>0), else table width
61 13         27 for (my $col=0; $col<$num_cols; $col++) {
62 36         58 $max[$col] = $avail_width;
63 36 50       53 if ($max_w->[$col] > 0) {
64 0         0 $max[$col] = min($max[$col], $max_w->[$col]);
65             }
66 36         90 $max[$col] = max($max[$col], $col_min_width->[$col]);
67             }
68              
69             # @natural = width fraction of avail_width, based only on content size
70             # ($col_max_content), before any limits applied
71 13         23 my $sum_content_size = 0;
72 13         28 for (my $col=0; $col<$num_cols; $col++) {
73 36         54 $sum_content_size += $col_max_content->[$col];
74             }
75 13         23 $sum_content_size /= $avail_width;
76 13         25 for (my $col=0; $col<$num_cols; $col++) {
77 36         75 $natural[$col] = $col_max_content->[$col]/$sum_content_size;
78             }
79              
80             # loop to adjust sizes, after setting size to natural
81             #my $old_total_delta = -1;
82 13         15 my $total_delta = 0;
83 13         20 my $again = 1;
84 13         25 for (my $col=0; $col<$num_cols; $col++) {
85 36         57 $calc_widths->[$col] = $natural[$col];
86             }
87              
88 13         31 while ($again) {
89 14         18 $again = 0;
90              
91             # let expand to satisfy min be offset by contract to satisfy max
92             # note that $total_delta adjusted from previous loop, not restarted
93 14         30 for (my $col = 0; $col < $num_cols; $col++) {
94 39 100       175 if ($calc_widths->[$col] < $col_min_width->[$col]) {
    50          
95 3         6 $total_delta += $col_min_width->[$col] - $calc_widths->[$col];
96 3         6 $calc_widths->[$col] = $col_min_width->[$col];
97             } elsif ($calc_widths->[$col] > $max[$col]) {
98 0         0 $total_delta -= $calc_widths->[$col] - $max[$col];
99 0         0 $calc_widths->[$col] = $max[$col];
100             }
101             }
102             # total_delta within +/-.1% of avail_width? we're done!
103 14 100       36 if (abs($total_delta) <= 0.001*$avail_width) { last; }
  13         24  
104              
105 1         3 my $change_amt;
106 1 50       2 if ($total_delta > 0) {
107             # net was we expanded more to satisfy min, so reduce any column
108             # not at min, proportional to content (natural)
109 1         3 @indices = ();
110             # @indices lists all columns NOT already at min
111 1         2 $sum_content_size = 0;
112 1         3 for (my $col=0; $col<$num_cols; $col++) {
113 3 100       5 if ($calc_widths->[$col] == $col_min_width->[$col]) { next; }
  2         4  
114 1         2 push @indices, $col;
115 1         3 $sum_content_size += $col_max_content->[$col];
116             }
117 1 50 33     6 if (!scalar @indices || $sum_content_size <= 0) {
118             # everyone at min but need to reduce... should NOT see this
119 0         0 carp "Problem... need to reduce column widths, but all already at minimum!";
120 0         0 last;
121             }
122 1         2 my $max_reduce_size;
123 1         1 $sum_content_size /= $total_delta;
124 1         3 foreach my $col (@indices) {
125 1         2 $max_reduce_size = $calc_widths->[$col] - $col_min_width->[$col];
126             # change amount is positive
127 1         2 $change_amt = $col_max_content->[$col]/$sum_content_size;
128 1         12 $change_amt = min($change_amt, $max_reduce_size);
129 1         9 $calc_widths->[$col] -= $change_amt;
130 1         3 $total_delta -= $change_amt;
131 1         4 $again = 1;
132             }
133              
134             } else { # total_delta < 0
135             # net was we contracted more to satisfy max, so expand any column
136             # not at max, proportional to content (natural)
137 0         0 @indices = ();
138             # @indices lists all columns NOT already at max
139 0         0 $sum_content_size = 0;
140 0         0 for (my $col=0; $col<$num_cols; $col++) {
141 0 0       0 if ($calc_widths->[$col] == $max[$col]) { next; }
  0         0  
142 0         0 push @indices, $col;
143 0         0 $sum_content_size += $col_max_content->[$col];
144             }
145 0 0 0     0 if (!scalar @indices || $sum_content_size <= 0) {
146             # everyone at max but need to increase... should NOT see this
147 0         0 carp "Problem... need to increase column widths, but all already at maximum!";
148 0         0 last;
149             }
150 0         0 my $max_increase_size;
151 0         0 $sum_content_size /= $total_delta;
152 0         0 foreach my $col (@indices) {
153 0         0 $max_increase_size = $max[$col] - $calc_widths->[$col];
154             # change amount is positive
155 0         0 $change_amt = -$col_max_content->[$col]/$sum_content_size;
156 0         0 $change_amt = min($change_amt, $max_increase_size);
157 0         0 $calc_widths->[$col] += $change_amt;
158 0         0 $total_delta += $change_amt;
159 0         0 $again = 1;
160             }
161              
162             } # if-elsif to handle decrease or increase by total_delta
163              
164             } # while($again) loop
165              
166 13         61 return ($calc_widths, $avail_width);
167             } # End of CalcColumnWidths()
168              
169             ###################################################################
170             # set the column widths per 'size' string
171             # width = available width of table (points)
172             # size = string describing each column's width
173             # NvalUnit for each, where Nval is a positive number
174             # (default 1) and Unit is an optional unit or float
175             # specifier. Nval, or Unit, or both must be given for
176             # each column.
177             # If Unit not given, the number is assumed to be Points
178             # (1/72 inch). Permitted units are cm, mm, in, em, ex, pt
179             # (any case).
180             # returned values are array of column widths (points) and
181             # total width (points), increased if necessary
182             ###################################################################
183              
184             sub SetColumnWidths {
185 0     0 0   my $avail_width = shift; # specified table width
186 0           my $size = shift; # width specifications
187 0           my $em_size = shift; # size of em in points
188 0           my $ex_size = shift; # size of ex in points
189              
190 0           my @colspecs = split /\s+/, $size;
191 0 0         if (!scalar @colspecs) {
192 0           die "!! Error !!\nNo column width specifications found in size '$size'!\n";
193             }
194              
195 0           my ($calc_widths, $float_widths, $number, $unit);
196 0           for (my $col=0; $col
197 0 0         if ($colspecs[$col] =~ m#^([\d.]+)([*a-z]+)$#i) {
    0          
    0          
198             # it appears to be NvalUnit in $1, $2
199 0           $number = $1;
200 0           $unit = $2;
201             } elsif ($colspecs[$col] =~ m#^([\d.]+)$#) {
202             # found just Nval in $1
203 0           $number = $1;
204 0           $unit = 'pt';
205             } elsif ($colspecs[$col] =~ m#^([*a-z]+)$#i) {
206             # found just Unit in $1
207 0           $number = 1;
208 0           $unit = $1;
209             # it is discouraged, but legal, for e.g., 'in' => 1 inch
210             } else {
211             # unable to disassemble this entry, including negative numbers
212 0           carp "!! Warning !!\nUnable to decode column $col entry '$colspecs[$col]', using '*' instead\n";
213 0           $number = 1;
214 0           $unit = '*';
215             }
216              
217             # see if legal number \d+, \d+., \d+.\d+, .\d+
218 0 0 0       if ($number =~ m#^\d+$# ||
      0        
      0        
219             $number =~ m#^\d+\.$# ||
220             $number =~ m#^\d+\.\d+$# ||
221             $number =~ m#^\.\d+$#) {
222             # valid number, use $number
223             } else {
224             # invalid number format, replace by 1
225             # can detect multiple decimal points, but no check for range
226 0           carp "!! Warning !!\nInvalid number '$number' in column $col, using '1' instead.\n";
227 0           $number = 1;
228             }
229              
230             # see if legal unit *, pt, in, cm, mm, em, ex
231             # if so, convert to points, add to calc_widths array
232 0 0         if ($unit =~ m#^\*$#) {
    0          
    0          
    0          
    0          
    0          
    0          
233 0           $calc_widths->[$col] = -1; # mark as floating for now
234 0           $float_widths->[$col] = $number;
235             } elsif ($unit =~ m#^pt$#i) {
236 0           $calc_widths->[$col] = $number;
237 0           $float_widths->[$col] = -1;
238             } elsif ($unit =~ m#^in$#i) {
239 0           $calc_widths->[$col] = $number * 72;
240 0           $float_widths->[$col] = -1;
241             } elsif ($unit =~ m#^cm$#i) {
242 0           $calc_widths->[$col] = $number * 72 / 2.54;
243 0           $float_widths->[$col] = -1;
244             } elsif ($unit =~ m#^mm$#i) {
245 0           $calc_widths->[$col] = $number * 72 / 25.4;
246 0           $float_widths->[$col] = -1;
247             } elsif ($unit =~ m#^em$#i) {
248 0           $calc_widths->[$col] = $number * $em_size;
249 0           $float_widths->[$col] = -1;
250             } elsif ($unit =~ m#^ex$#i) {
251 0           $calc_widths->[$col] = $number * $ex_size;
252 0           $float_widths->[$col] = -1;
253             } else {
254             # invalid unit, replace by mm
255 0           carp "!! Warning !!\nInvalid unit '$unit' in column $col, using 'mm' instead.\n";
256 0           $unit = 'mm';
257 0           $calc_widths->[$col] = $number * 72 / 25.4;
258 0           $float_widths->[$col] = -1;
259             }
260             } # loop through columns $col
261              
262             # calc_widths -1 need updating from float_widths
263             # first need to calculate available space to allocate (if < 1 pt, increase
264             # width with warning). divide by sum of float_widths to get size of 1*,
265             # and finally, transfer to calc_widths.
266 0           my $width_used = 0; # used for fixed widths, non-*
267 0           my $total_float = 0; # sum up float_widths
268 0           for (my $col=0; $col
269 0 0         if ($float_widths->[$col] > 0) {
270             # we have a float (*) to handle
271 0           $total_float += $float_widths->[$col];
272             } else {
273             # presumably a fixed value
274 0           $width_used += $calc_widths->[$col];
275             }
276             }
277              
278             # check if width_used exceeds available width!
279 0 0         if ($width_used > $avail_width) {
280 0           carp "!! Warning !!\nSum of fixed widths ($width_used) exceeds available width ($avail_width), increase width.\n";
281 0           $avail_width = $width_used;
282             }
283              
284             # if == 0, should already be valid number (width in pts) in all calc_widths
285 0 0         if ($total_float > 0) {
286             # at least one * entry to allocate among at least 1 pt of space
287             # first, how much space to allocate, or does width need to be increased?
288 0 0         if ($avail_width - $width_used < 1) {
289             # too little space available, must increase total width
290 0           carp "!! Warning !!\nToo little space (".($avail_width-$width_used)."pts) to allocate among floats.\nIncrease table width by 5em per float unit.\n";
291 0           $avail_width += 5*$em_size*$total_float;
292             }
293              
294             # have SOME room to allocate, so how many points per *?
295 0           my $star_size = ($avail_width - $width_used)/$total_float;
296             # should be a positive value
297 0           for (my $col=0; $col
298 0 0         if ($float_widths->[$col] > 0) {
299 0           $calc_widths->[$col] = $star_size * $float_widths->[$col];
300             }
301             }
302             }
303              
304             # no floating column widths, and total of fixed < available width
305 0 0 0       if ($total_float == 0 && $width_used < $avail_width) {
306 0           carp "!! Warning !!\nAllocated width is narrower than specified table width. Reduce table width.\n";
307 0           $avail_width = $width_used;
308             }
309             # other choice would be to increase all columns by same percentage
310            
311 0           return ($calc_widths, $avail_width);
312             } # End of SetColumnWidths()
313              
314             1;