7 our $VERSION = '0.9.10';
9 print __PACKAGE__.' is version: '.$VERSION.$/ if($ENV{'PDF_TABLE_DEBUG'});
11 ############################################################
15 # Parameters are meta information about the PDF
17 # $pdf = PDF::Table->new();
19 ############################################################
24 my $class = ref($type) || $type;
26 bless ($self, $class);
28 # Pass all the rest to init for validation and initialisation
36 my ($self, $pdf, $page, $data, %options ) = @_;
38 # Check and set default values
39 $self->set_defaults();
41 # Check and set mandatory params
43 $self->set_page($page);
44 $self->set_data($data);
45 $self->set_options(\%options);
53 $self->{'font_size'} = 12;
57 my ($self, $pdf) = @_;
58 $self->{'pdf'} = $pdf;
62 my ($self, $page) = @_;
63 if ( defined($page) && ref($page) ne 'PDF::API2::Page' ){
65 if( ref($self->{'pdf'}) eq 'PDF::API2' ){
66 $self->{'page'} = $self->{'pdf'}->page();
68 carp 'Warning: Page must be a PDF::API2::Page object but it seems to be: '.ref($page).$/;
69 carp 'Error: Cannot set page from passed PDF object either as it is invalid!'.$/;
73 $self->{'page'} = $page;
78 my ($self, $data) = @_;
83 my ($self, $options) = @_;
87 ############################################################
89 # text_block - utility method to build multi-paragraph blocks of text
91 ############################################################
96 my $text_object = shift;
97 my $text = shift; # The text to be displayed
98 my %arg = @_; # Additional Arguments
100 my ( $align, $xpos, $ypos, $xbase, $ybase, $line_width, $wordspace, $endw , $width, $height) =
101 ( undef , undef, undef, undef , undef , undef , undef , undef , undef , undef );
102 my @line = (); # Temp data array with words on one line
103 my %width = (); # The width of every unique word in the givven text
105 # Try to provide backward compatibility
106 foreach my $key (keys %arg)
109 if($newkey =~ s#^-##)
111 $arg{$newkey} = $arg{$key};
118 # Lets check mandatory parameters with no default values
120 $xbase = $arg{'x'} || -1;
121 $ybase = $arg{'y'} || -1;
122 $width = $arg{'w'} || -1;
123 $height = $arg{'h'} || -1;
124 unless( $xbase > 0 ){ carp "Error: Left Edge of Block is NOT defined!\n"; return; }
125 unless( $ybase > 0 ){ carp "Error: Base Line of Block is NOT defined!\n"; return; }
126 unless( $width > 0 ){ carp "Error: Width of Block is NOT defined!\n"; return; }
127 unless( $height > 0 ){ carp "Error: Height of Block is NOT defined!\n"; return; }
128 # Check if any text to display
129 unless( defined( $text) and length($text) > 0 )
131 carp "Warning: No input text found. Trying to add dummy '-' and not to break everything.\n";
135 # Strip any <CR> and Split the text into paragraphs
137 my @paragraphs = split(/\n/, $text);
139 # Width between lines in pixels
140 my $line_space = defined $arg{'lead'} && $arg{'lead'} > 0 ? $arg{'lead'} : 12;
142 # Calculate width of all words
143 my $space_width = $text_object->advancewidth("\x20");
144 my @words = split(/\s+/, $text);
147 next if exists $width{$_};
148 $width{$_} = $text_object->advancewidth($_);
151 my @paragraph = split(' ', shift(@paragraphs));
153 my $first_paragraph = 1;
158 $ypos = $ybase + $line_space;
159 my $bottom_border = $ypos - $height;
160 # While we can add another line
161 while ( $ypos >= $bottom_border + $line_space )
163 # Is there any text to render ?
166 # Finish if nothing left
167 last unless scalar @paragraphs;
168 # Else take one line from the text
169 @paragraph = split(' ', shift( @paragraphs ) );
171 $ypos -= $arg{'parspace'} if $arg{'parspace'};
172 last unless $ypos >= $bottom_border;
174 $ypos -= $line_space;
177 # While there's room on the line, add another word
180 if( $first_line && exists $arg{'hang'} )
182 my $hang_width = $text_object->advancewidth($arg{'hang'});
184 $text_object->translate( $xpos, $ypos );
185 $text_object->text( $arg{'hang'} );
187 $xpos += $hang_width;
188 $line_width += $hang_width;
189 $arg{'indent'} += $hang_width if $first_paragraph;
191 elsif( $first_line && exists $arg{'flindent'} && $arg{'flindent'} > 0 )
193 $xpos += $arg{'flindent'};
194 $line_width += $arg{'flindent'};
196 elsif( $first_paragraph && exists $arg{'fpindent'} && $arg{'fpindent'} > 0 )
198 $xpos += $arg{'fpindent'};
199 $line_width += $arg{'fpindent'};
201 elsif (exists $arg{'indent'} && $arg{'indent'} > 0 )
203 $xpos += $arg{'indent'};
204 $line_width += $arg{'indent'};
207 # Lets take from paragraph as many words as we can put into $width - $indent;
208 while ( @paragraph and $text_object->advancewidth( join("\x20", @line)."\x20" . $paragraph[0]) +
209 $line_width < $width )
211 push(@line, shift(@paragraph));
213 $line_width += $text_object->advancewidth(join('', @line));
215 # calculate the space width
216 if( $arg{'align'} eq 'fulljustify' or ($arg{'align'} eq 'justify' and @paragraph))
218 @line = split(//,$line[0]) if (scalar(@line) == 1) ;
219 $wordspace = ($width - $line_width) / (scalar(@line) - 1);
224 $align=($arg{'align'} eq 'justify') ? 'left' : $arg{'align'};
225 $wordspace = $space_width;
227 $line_width += $wordspace * (scalar(@line) - 1);
229 if( $align eq 'justify')
231 foreach my $word (@line)
233 $text_object->translate( $xpos, $ypos );
234 $text_object->text( $word );
235 $xpos += ($width{$word} + $wordspace) if (@line);
241 # calculate the left hand position of the line
242 if( $align eq 'right' )
244 $xpos += $width - $line_width;
246 elsif( $align eq 'center' )
248 $xpos += ( $width / 2 ) - ( $line_width / 2 );
252 $text_object->translate( $xpos, $ypos );
253 $endw = $text_object->text( join("\x20", @line));
257 unshift(@paragraphs, join(' ',@paragraph)) if scalar(@paragraph);
258 return ($endw, $ypos, join("\n", @paragraphs))
262 ################################################################
263 # table - utility method to build multi-row, multicolumn tables
264 ################################################################
273 #=====================================
274 # Mandatory Arguments Section
275 #=====================================
276 unless($pdf and $page and $data)
278 carp "Error: Mandatory parameter is missing pdf/page/data object!\n";
282 # Validate mandatory argument data type
283 croak "Error: Invalid pdf object received." unless (ref($pdf) eq 'PDF::API2');
284 croak "Error: Invalid page object received." unless (ref($page) eq 'PDF::API2::Page');
285 croak "Error: Invalid data received." unless ((ref($data) eq 'ARRAY') && scalar(@$data));
286 croak "Error: Missing required settings." unless (scalar(keys %arg));
288 # Validate settings key
289 my %valid_settings_key = (
302 background_color => 1,
303 background_color_odd => 1,
304 background_color_even => 1,
307 horizontal_borders => 1,
308 vertical_borders => 1,
312 font_color_even => 1,
313 background_color_odd => 1,
314 background_color_even => 1,
320 max_word_length => 1,
322 foreach my $key (keys %arg) {
323 croak "Error: Invalid setting key '$key' received."
324 unless (exists $valid_settings_key{$key});
327 # Try to provide backward compatibility
328 foreach my $key (keys %arg)
331 if($newkey =~ s#^-##)
333 $arg{$newkey} = $arg{$key};
339 #TODO: Add code for header props compatibility and col_props comp....
341 my ( $xbase, $ybase, $width, $height ) = ( undef, undef, undef, undef );
342 # Could be 'int' or 'real' values
343 $xbase = $arg{'x' } || -1;
344 $ybase = $arg{'start_y'} || -1;
345 $width = $arg{'w' } || -1;
346 $height = $arg{'start_h'} || -1;
348 # Global geometry parameters are also mandatory.
349 unless( $xbase > 0 ){ carp "Error: Left Edge of Table is NOT defined!\n"; return; }
350 unless( $ybase > 0 ){ carp "Error: Base Line of Table is NOT defined!\n"; return; }
351 unless( $width > 0 ){ carp "Error: Width of Table is NOT defined!\n"; return; }
352 unless( $height > 0 ){ carp "Error: Height of Table is NOT defined!\n"; return; }
354 # Ensure default values for -next_y and -next_h
355 my $next_y = $arg{'next_y'} || $arg{'start_y'} || 0;
356 my $next_h = $arg{'next_h'} || $arg{'start_h'} || 0;
359 my $txt = $page->text;
361 # Set Default Properties
362 my $fnt_name = $arg{'font' } || $pdf->corefont('Times',-encode => 'utf8');
363 my $fnt_size = $arg{'font_size' } || 12;
364 my $max_word_len= $arg{'max_word_length' } || 20;
366 #=====================================
367 # Table Header Section
368 #=====================================
369 # Disable header row into the table
370 my $header_props = undef;
372 # Check if the user enabled it ?
373 if(defined $arg{'header_props'} and ref( $arg{'header_props'}) eq 'HASH')
375 # Transfer the reference to local variable
376 $header_props = $arg{'header_props'};
378 # Check other params and put defaults if needed
379 $header_props->{'repeat' } = $header_props->{'repeat' } || 0;
380 $header_props->{'font' } = $header_props->{'font' } || $fnt_name;
381 $header_props->{'font_color' } = $header_props->{'font_color' } || '#000066';
382 $header_props->{'font_size' } = $header_props->{'font_size' } || $fnt_size + 2;
383 $header_props->{'bg_color' } = $header_props->{'bg_color' } || '#FFFFAA';
384 $header_props->{'justify' } = $header_props->{'justify' };
387 my $header_row = undef;
388 #=====================================
389 # Other Parameters check
390 #=====================================
391 my $lead = $arg{'lead' } || $fnt_size;
392 my $pad_left = $arg{'padding_left' } || $arg{'padding'} || 0;
393 my $pad_right = $arg{'padding_right' } || $arg{'padding'} || 0;
394 my $pad_top = $arg{'padding_top' } || $arg{'padding'} || 0;
395 my $pad_bot = $arg{'padding_bottom'} || $arg{'padding'} || 0;
396 my $line_w = defined $arg{'border'} ? $arg{'border'} : 1 ;
397 my $horiz_borders = defined $arg{'horizontal_borders'}
398 ? $arg{'horizontal_borders'}
400 my $vert_borders = defined $arg{'vertical_borders'}
401 ? $arg{'vertical_borders'}
404 my $background_color_even = $arg{'background_color_even' } || $arg{'background_color'} || undef;
405 my $background_color_odd = $arg{'background_color_odd' } || $arg{'background_color'} || undef;
406 my $font_color_even = $arg{'font_color_even' } || $arg{'font_color' } || 'black';
407 my $font_color_odd = $arg{'font_color_odd' } || $arg{'font_color' } || 'black';
408 my $border_color = $arg{'border_color' } || 'black';
410 my $min_row_h = $fnt_size + $pad_top + $pad_bot;
411 my $row_h = defined ($arg{'row_height'})
413 ($arg{'row_height'} > $min_row_h)
415 $arg{'row_height'} : $min_row_h;
419 my $cell_props = $arg{cell_props} || []; # per cell properties
421 #If there is no valid data array reference warn and return!
422 if(ref $data ne 'ARRAY')
424 carp "Passed table data is not an ARRAY reference. It's actually a ref to ".ref($data);
425 return ($page,0,$cur_y);
428 # Copy the header row if header is enabled
429 @$header_row = $$data[0] if defined $header_props;
430 # Determine column widths based on content
432 # an arrayref whose values are a hashref holding
433 # the minimum and maximum width of that column
434 my $col_props = $arg{'column_props'} || [];
436 # An array ref of arrayrefs whose values are
437 # the actual widths of the column/row intersection
438 my $row_col_widths = [];
439 # An array ref with the widths of the header row
440 my $header_row_props = [];
442 # Scalars that hold sum of the maximum and minimum widths of all columns
443 my ( $max_col_w , $min_col_w ) = ( 0,0 );
444 my ( $row, $col_name, $col_fnt_size, $space_w );
446 my $word_widths = {};
447 my $rows_height = [];
450 for( my $row_idx = 0; $row_idx < scalar(@$data) ; $row_idx++ )
452 my $column_widths = []; #holds the width of each column
453 # Init the height for this row
454 $rows_height->[$row_idx] = 0;
456 for( my $column_idx = 0; $column_idx < scalar(@{$data->[$row_idx]}) ; $column_idx++ )
458 # look for font information for this column
459 my ($cell_font, $cell_font_size);
461 if( !$row_idx and ref $header_props )
463 $cell_font = $header_props->{'font'};
464 $cell_font_size = $header_props->{'font_size'};
467 # Get the most specific value if none was already set from header_props
468 $cell_font ||= $cell_props->[$row_idx][$column_idx]->{'font'}
469 || $col_props->[$column_idx]->{'font'}
472 $cell_font_size ||= $cell_props->[$row_idx][$column_idx]->{'font_size'}
473 || $col_props->[$column_idx]->{'font_size'}
477 $txt->font( $cell_font, $cell_font_size );
479 # Set row height to biggest font size from row's cells
480 if( $cell_font_size > $rows_height->[$row_idx] )
482 $rows_height->[$row_idx] = $cell_font_size;
485 # This should fix a bug with very long words like serial numbers etc.
486 if( $max_word_len > 0 )
488 $data->[$row_idx][$column_idx] =~ s#(\S{$max_word_len})(?=\S)#$1 #g;
491 # Init cell size limits
492 $space_w = $txt->advancewidth( "\x20" );
493 $column_widths->[$column_idx] = 0;
497 my @words = split( /\s+/, $data->[$row_idx][$column_idx] );
501 unless( exists $word_widths->{$_} )
502 { # Calculate the width of every word and add the space width to it
503 $word_widths->{$_} = $txt->advancewidth( $_ ) + $space_w;
506 $column_widths->[$column_idx] += $word_widths->{$_};
507 $min_col_w = $word_widths->{$_} if( $word_widths->{$_} > $min_col_w );
508 $max_col_w += $word_widths->{$_};
511 $min_col_w += $pad_left + $pad_right;
512 $max_col_w += $pad_left + $pad_right;
513 $column_widths->[$column_idx] += $pad_left + $pad_right;
515 # Keep a running total of the overall min and max widths
516 $col_props->[$column_idx]->{'min_w'} ||= 0;
517 $col_props->[$column_idx]->{'max_w'} ||= 0;
519 if( $min_col_w > $col_props->[$column_idx]->{'min_w'} )
520 { # Calculated Minimum Column Width is more than user-defined
521 $col_props->[$column_idx]->{'min_w'} = $min_col_w ;
524 if( $max_col_w > $col_props->[$column_idx]->{'max_w'} )
525 { # Calculated Maximum Column Width is more than user-defined
526 $col_props->[$column_idx]->{'max_w'} = $max_col_w ;
528 }#End of for(my $column_idx....
530 $row_col_widths->[$row_idx] = $column_widths;
532 # Copy the calculated row properties of header row.
533 @$header_row_props = @$column_widths if(!$row_idx and ref $header_props);
536 # Calc real column widths and expand table width if needed.
537 my $calc_column_widths;
538 ($calc_column_widths, $width) = CalcColumnWidths( $col_props, $width );
540 # Lets draw what we have!
542 # Store header row height for later use if headers have to be repeated
543 my $header_row_height = $rows_height->[0];
545 my ( $gfx, $gfx_bg, $background_color, $font_color, $bot_marg, $table_top_y, $text_start);
547 # Each iteration adds a new page as neccessary
548 while(scalar(@{$data}))
550 my ($page_header, $columns_number);
554 $table_top_y = $ybase;
555 $bot_marg = $table_top_y - $height;
559 if(ref $arg{'new_page_func'})
561 $page = &{$arg{'new_page_func'}};
568 $table_top_y = $next_y;
569 $bot_marg = $table_top_y - $next_h;
571 if( ref $header_props and $header_props->{'repeat'})
574 @$page_header = @$header_row;
576 @$hrp = @$header_row_props ;
577 # Then prepend it to master data array
578 unshift @$data, @$page_header;
579 unshift @$row_col_widths, $hrp;
580 unshift @$rows_height, $header_row_height;
582 $first_row = 1; # Means YES
583 $row_index--; # Rollback the row_index because a new header row has been added
587 # Check for safety reasons
589 { # This warning should remain i think
590 carp "!!! Warning: !!! Incorrect Table Geometry! Setting bottom margin to end of sheet!\n";
594 $gfx_bg = $page->gfx;
596 $txt->font($fnt_name, $fnt_size);
598 $cur_y = $table_top_y;
603 $gfx->strokecolor($border_color);
604 $gfx->linewidth($line_w);
609 $gfx->move( $xbase , $cur_y );
610 $gfx->hline($xbase + $width );
618 # Each iteration adds a row to the current page until the page is full
619 # or there are no more rows to add
621 while(scalar(@{$data}) and $cur_y-$row_h > $bot_marg)
623 # Remove the next item from $data
624 my $record = shift @{$data};
626 # Get columns number to know later how many vertical lines to draw
627 # TODO: get the max number of columns per page as currently last row's columns overrides
628 $columns_number = scalar(@$record);
630 # Get the next set of row related settings
632 my $pre_calculated_row_height = shift @$rows_height;
635 my $record_widths = shift @$row_col_widths;
637 # Row coloumn props - TODO in another commit
639 # Row cell props - TODO in another commit
641 # Added to resolve infite loop bug with returned undef values
642 for(my $d = 0; $d < scalar(@{$record}) ; $d++)
644 $record->[$d] = '-' unless( defined $record->[$d]);
647 # Choose colors for this row
648 $background_color = $row_index % 2 ? $background_color_even : $background_color_odd;
649 $font_color = $row_index % 2 ? $font_color_even : $font_color_odd;
651 #Determine current row height
652 my $current_row_height = $pad_top + $pre_calculated_row_height + $pad_bot;
654 # $row_h is the calculated global user requested row height.
655 # It will be honored, only if it has bigger value than the calculated one.
656 # TODO: It's questionable if padding should be inclided in this calculation or not
657 if($current_row_height < $row_h){
658 $current_row_height = $row_h;
661 # Define the font y base position for this line.
662 $text_start = $cur_y - ($current_row_height - $pad_bot);
665 my $leftovers = undef; # Reference to text that is returned from textblock()
666 my $do_leftovers = 0;
668 # Process every cell(column) from current row
669 for( my $column_idx = 0; $column_idx < scalar( @$record); $column_idx++ )
671 next unless $col_props->[$column_idx]->{'max_w'};
672 next unless $col_props->[$column_idx]->{'min_w'};
673 $leftovers->[$column_idx] = undef;
675 # look for font information for this cell
676 my ($cell_font, $cell_font_size, $cell_font_color, $justify);
678 if( $first_row and ref $header_props)
680 $cell_font = $header_props->{'font'};
681 $cell_font_size = $header_props->{'font_size'};
682 $cell_font_color = $header_props->{'font_color'};
683 $justify = $header_props->{'justify'};
686 # Get the most specific value if none was already set from header_props
687 $cell_font ||= $cell_props->[$row_index][$column_idx]->{'font'}
688 || $col_props->[$column_idx]->{'font'}
691 $cell_font_size ||= $cell_props->[$row_index][$column_idx]->{'font_size'}
692 || $col_props->[$column_idx]->{'font_size'}
695 $cell_font_color ||= $cell_props->[$row_index][$column_idx]->{'font_color'}
696 || $col_props->[$column_idx]->{'font_color'}
699 $justify ||= $cell_props->[$row_index][$column_idx]->{'justify'}
700 || $col_props->[$column_idx]->{'justify'}
704 # Init cell font object
705 $txt->font( $cell_font, $cell_font_size );
706 $txt->fillcolor($cell_font_color);
708 # If the content is wider than the specified width, we need to add the text as a text block
709 if( $record->[$column_idx] !~ m/(.\n.)/ and
710 $record_widths->[$column_idx] and
711 $record_widths->[$column_idx] <= $calc_column_widths->[$column_idx]
713 my $space = $pad_left;
714 if ($justify eq 'right')
716 $space = $calc_column_widths->[$column_idx] -($txt->advancewidth($record->[$column_idx]) + $pad_right);
718 elsif ($justify eq 'center')
720 $space = ($calc_column_widths->[$column_idx] - $txt->advancewidth($record->[$column_idx])) / 2;
722 $txt->translate( $cur_x + $space, $text_start );
723 $txt->text( $record->[$column_idx] );
725 # Otherwise just use the $page->text() method
728 my ($width_of_last_line, $ypos_of_last_line, $left_over_text) = $self->text_block(
730 $record->[$column_idx],
731 x => $cur_x + $pad_left,
733 w => $calc_column_widths->[$column_idx] - $pad_left - $pad_right,
734 h => $cur_y - $bot_marg - $pad_top - $pad_bot,
738 # Desi - Removed $lead because of fixed incorrect ypos bug in text_block
739 my $current_cell_height = $cur_y - $ypos_of_last_line + $pad_bot;
740 if( $current_cell_height > $current_row_height )
742 $current_row_height = $current_cell_height;
745 if( $left_over_text )
747 $leftovers->[$column_idx] = $left_over_text;
751 $cur_x += $calc_column_widths->[$column_idx];
755 unshift @$data, $leftovers;
756 unshift @$row_col_widths, $record_widths;
757 unshift @$rows_height, $pre_calculated_row_height;
761 # This has to be separately from the text loop
762 # because we do not know the final height of the cell until all text has been drawn
764 for(my $column_idx = 0 ; $column_idx < scalar(@$record) ; $column_idx++)
768 if( $first_row and ref $header_props)
769 { #Compatibility Consistency with other props
770 $cell_bg_color = $header_props->{'bg_color'} || $header_props->{'background_color'};
773 # Get the most specific value if none was already set from header_props
774 $cell_bg_color ||= $cell_props->[$row_index][$column_idx]->{'background_color'}
775 || $col_props->[$column_idx]->{'background_color'}
776 || $background_color;
780 $gfx_bg->rect( $cur_x, $cur_y-$current_row_height, $calc_column_widths->[$column_idx], $current_row_height);
781 $gfx_bg->fillcolor($cell_bg_color);
784 $cur_x += $calc_column_widths->[$column_idx];
785 }#End of for(my $column_idx....
787 $cur_y -= $current_row_height;
788 if ($gfx && $horiz_borders)
790 $gfx->move( $xbase , $cur_y );
791 $gfx->hline( $xbase + $width );
794 $row_index++ unless ( $do_leftovers );
800 # Draw vertical lines
803 $gfx->move( $xbase, $table_top_y);
804 $gfx->vline( $cur_y );
806 for( my $j = 0; $j < $columns_number; $j++ )
808 $cur_x += $calc_column_widths->[$j];
809 $gfx->move( $cur_x, $table_top_y );
810 $gfx->vline( $cur_y );
814 # ACTUALLY draw all the lines
815 $gfx->fillcolor( $border_color);
819 }# End of while(scalar(@{$data}))
821 return ($page,--$pg_cnt,$cur_y);
825 # calculate the column widths
828 my $col_props = shift;
829 my $avail_width = shift;
834 for(my $j = 0; $j < scalar( @$col_props); $j++)
836 $min_width += $col_props->[$j]->{min_w} || 0;
839 # I think this is the optimal variant when good view can be guaranateed
840 if($avail_width < $min_width)
842 carp "!!! Warning !!!\n Calculated Mininal width($min_width) > Table width($avail_width).\n",
843 ' Expanding table width to:',int($min_width)+1,' but this could lead to unexpected results.',"\n",
844 ' Possible solutions:',"\n",
845 ' 0)Increase table width.',"\n",
846 ' 1)Decrease font size.',"\n",
847 ' 2)Choose a more narrow font.',"\n",
848 ' 3)Decrease "max_word_length" parameter.',"\n",
849 ' 4)Rotate page to landscape(if it is portrait).',"\n",
850 ' 5)Use larger paper size.',"\n",
851 '!!! --------- !!!',"\n";
852 $avail_width = int( $min_width) + 1;
856 # Calculate how much can be added to every column to fit the available width.
857 for(my $j = 0; $j < scalar(@$col_props); $j++ )
859 $calc_widths->[$j] = $col_props->[$j]->{min_w} || 0;;
862 # Allow columns to expand to max_w before applying extra space equally.
866 my $span = ($avail_width - $min_width) / scalar( @$col_props);
870 my $next_will_be_last_iter = 1;
871 for(my $j = 0; $j < scalar(@$col_props); $j++ )
873 my $new_w = $calc_widths->[$j] + $span;
875 if (!$is_last_iter && $new_w > $col_props->[$j]->{max_w})
877 $new_w = $col_props->[$j]->{max_w}
879 if ($calc_widths->[$j] != $new_w )
881 $calc_widths->[$j] = $new_w;
882 $next_will_be_last_iter = 0;
884 $min_width += $new_w;
886 last if $is_last_iter;
887 $is_last_iter = $next_will_be_last_iter;
890 return ($calc_widths,$avail_width);
900 PDF::Table - A utility class for building table layouts in a PDF::API2 object.
907 my $pdftable = new PDF::Table;
908 my $pdf = new PDF::API2(-file => "table_of_lorem.pdf");
909 my $page = $pdf->page;
911 # some data to layout
913 ["1 Lorem ipsum dolor",
914 "Donec odio neque, faucibus vel",
915 "consequat quis, tincidunt vel, felis."],
916 ["Nulla euismod sem eget neque.",
922 $left_edge_of_table = 50;
923 # build the table layout
929 x => $left_edge_of_table,
933 # some optional params
938 background_color_odd => "gray",
939 background_color_even => "lightblue", #cell background color for even rows
942 # do other stuff with $pdf
948 For a complete working example or initial script look into distribution`s 'examples' folder.
953 This class is a utility for use with the PDF::API2 module from CPAN.
954 It can be used to display text data in a table layout within a PDF.
955 The text data must be in a 2D array (such as returned by a DBI statement handle fetchall_arrayref() call).
956 The PDF::Table will automatically add as many new pages as necessary to display all of the data.
957 Various layout properties, such as font, font size, and cell padding and background color can be specified for each column and/or for even/odd rows.
958 Also a (non)repeated header row with different layout properties can be specified.
960 See the L</METHODS> section for complete documentation of every parameter.
966 my $pdf_table = new PDF::Table;
972 Creates a new instance of the class. (to be improved)
976 There are no parameters.
980 Reference to the new instance
986 my ($final_page, $number_of_pages, $final_y) = table($pdf, $page, $data, %settings)
992 Generates a multi-row, multi-column table into an existing PDF document based on provided data set and settings.
996 $pdf - a PDF::API2 instance representing the document being created
997 $page - a PDF::API2::Page instance representing the current page of the document
998 $data - an ARRAY reference to a 2D data structure that will be used to build the table
999 %settings - HASH with geometry and formatting parameters.
1001 For full %settings description see section L</Table settings> below.
1003 This method will add more pages to the pdf instance as required based on the formatting options and the amount of data.
1007 The return value is a 3 items list where
1009 $final_page - The first item is a PDF::API2::Page instance that the table ends on
1010 $number_of_pages - The second item is the count of pages that the table spans on
1011 $final_y - The third item is the Y coordinate of the table bottom so that additional content can be added in the same document.
1015 my $pdf = new PDF::API2;
1016 my $page = $pdf->page();
1018 ['foo1','bar1','baz1'],
1019 ['foo2','bar2','baz2']
1028 my ($final_page, $number_of_pages, $final_y) = $pdftable->table( $pdf, $page, $data, %options );
1032 =head3 Table settings
1036 There are some mandatory parameteres for setting table geometry and position across page(s)
1040 =item B<x> - X coordinate of upper left corner of the table. Left edge of the sheet is 0.
1042 B<Value:> can be any whole number satisfying 0 =< X < PageWidth
1043 B<Default:> No default value
1047 =item B<start_y> - Y coordinate of upper left corner of the table at the initial page.
1049 B<Value:> can be any whole number satisfying 0 < start_y < PageHeight (depending on space availability when embedding a table)
1050 B<Default:> No default value
1054 =item B<w> - width of the table starting from X.
1056 B<Value:> can be any whole number satisfying 0 < w < PageWidth - x
1057 B<Default:> No default value
1061 =item B<start_h> - Height of the table on the initial page
1063 B<Value:> can be any whole number satisfying 0 < start_h < PageHeight - Current Y position
1064 B<Default:> No default value
1074 =item B<next_h> - Height of the table on any additional page
1076 B<Value:> can be any whole number satisfying 0 < next_h < PageHeight
1077 B<Default:> Value of param B<'start_h'>
1081 =item B<next_y> - Y coordinate of upper left corner of the table at any additional page.
1083 B<Value:> can be any whole number satisfying 0 < next_y < PageHeight
1084 B<Default:> Value of param B<'start_y'>
1088 =item B<max_word_length> - Breaks long words (like serial numbers hashes etc.) by adding a space after every Nth symbol
1090 B<Value:> can be any whole positive number
1093 max_word_length => 20 # Will add a space after every 20 symbols
1095 =item B<padding> - Padding applied to every cell
1097 =item B<padding_top> - top cell padding, overrides 'padding'
1099 =item B<padding_right> - right cell padding, overrides 'padding'
1101 =item B<padding_left> - left cell padding, overrides 'padding'
1103 =item B<padding_bottom> - bottom padding, overrides 'padding'
1105 B<Value:> can be any whole positive number
1107 B<Default padding:> 0
1109 B<Default padding_*> $padding
1111 padding => 5 # all sides cell padding
1112 padding_top => 8, # top cell padding, overrides 'padding'
1113 padding_right => 6, # right cell padding, overrides 'padding'
1114 padding_left => 2, # left cell padding, overrides 'padding'
1115 padding_bottom => undef # bottom padding will be 5 as it will fallback to 'padding'
1117 =item B<border> - Width of table border lines.
1119 =item B<horizontal_borders> - Width of horizontal border lines. Overrides 'border' value.
1121 =item B<vertical_borders> - Width of vertical border lines. Overrides 'border' value.
1123 B<Value:> can be any whole positive number. When set to 0 will disable border lines.
1126 border => 3 # border width is 3
1127 horizontal_borders => 1 # horizontal borders will be 1 overriding 3
1128 vertical_borders => undef # vertical borders will be 3 as it will fallback to 'border'
1130 =item B<vertical_borders> - Width of vertical border lines. Overrides 'border' value.
1132 B<Value:> Color specifier as 'name' or 'HEX'
1135 border_color => 'red'
1137 =item B<font> - instance of PDF::API2::Resource::Font defining the fontf to be used in the table
1139 B<Value:> can be any PDF::API2::Resource::* type of font
1140 B<Default:> 'Times' with UTF8 encoding
1142 font => $pdf->corefont("Helvetica", -encoding => "utf8")
1144 =item B<font_size> - Default size of the font that will be used across the table
1146 B<Value:> can be any positive number
1151 =item B<font_color> - Font color for all rows
1153 =item B<font_color_odd> - Font color for odd rows
1155 =item B<font_color_even> - Font color for even rows
1157 =item B<background_color_odd> - Background color for odd rows
1159 =item B<background_color_even> - Background color for even rows
1161 B<Value:> Color specifier as 'name' or 'HEX'
1162 B<Default:> 'black' font on 'white' background
1164 font_color => '#333333'
1165 font_color_odd => 'purple'
1166 font_color_even => '#00FF00'
1167 background_color_odd => 'gray'
1168 background_color_even => 'lightblue'
1170 =item B<row_height> - Desired row height but it will be honored only if row_height > font_size + padding_top + padding_bottom
1172 B<Value:> can be any whole positive number
1173 B<Default:> font_size + padding_top + padding_bottom
1177 =item B<new_page_func> - CODE reference to a function that returns a PDF::API2::Page instance.
1179 If used the parameter 'new_page_func' must be a function reference which when executed will create a new page and will return the object back to the module.
1180 For example you can use it to put Page Title, Page Frame, Page Numbers and other staff that you need.
1181 Also if you need some different type of paper size and orientation than the default A4-Portrait for example B2-Landscape you can use this function ref to set it up for you. For more info about creating pages refer to PDF::API2 PAGE METHODS Section.
1182 Don't forget that your function must return a page object created with PDF::API2 page() method.
1184 new_page_func => $code_ref
1186 =item B<header_props> - HASH reference to specific settings for the Header row of the table. See section L</Header Row Properties> below
1188 header_props => $hdr_props
1190 =item B<column_props> - HASH reference to specific settings for each column of the table. See section L</Column Properties> below
1192 column_props => $col_props
1194 =item B<cell_props> - HASH reference to specific settings for each column of the table. See section L</Cell Properties> below
1196 cell_props => $cel_props
1200 =head4 Header Row Properties
1202 If the 'header_props' parameter is used, it should be a hashref. Passing an empty HASH will trigger a header row initialised with Default values.
1203 There is no 'data' variable for the content, because the module asumes that first table row will become the header row. It will copy this row and put it on every new page if 'repeat' param is set.
1207 =item B<font> - instance of PDF::API2::Resource::Font defining the fontf to be used in the header row
1209 B<Value:> can be any PDF::API2::Resource::* type of font
1210 B<Default:> 'font' of the table. See table parameter 'font' for more details.
1212 =item B<font_size> - Font size of the header row
1214 B<Value:> can be any positive number
1215 B<Default:> 'font_size' of the table + 2
1217 =item B<font_color> - Font color of the header row
1219 B<Value:> Color specifier as 'name' or 'HEX'
1220 B<Default:> '#000066'
1222 =item B<bg_color> - Background color of the header row
1224 B<Value:> Color specifier as 'name' or 'HEX'
1227 =item B<repeat> - Flag showing if header row should be repeated on every new page
1229 B<Value:> 0,1 1-Yes/True, 0-No/False
1232 =item B<justify> - Alignment of text in the header row.
1234 B<Value:> One of 'left', 'right', 'center'
1235 B<Default:> Same as column alignment (or 'left' if undefined)
1239 font => $pdf->corefont("Helvetica", -encoding => "utf8"),
1241 font_color => '#004444',
1242 bg_color => 'yellow',
1249 =head4 Column Properties
1251 If the 'column_props' parameter is used, it should be an arrayref of hashrefs,
1252 with one hashref for each column of the table. The columns are counted from left to right so the hash reference at $col_props[0] will hold properties for the first column from left to right.
1253 If you DO NOT want to give properties for a column but to give for another just insert and empty hash reference into the array for the column that you want to skip. This will cause the counting to proceed as expected and the properties to be applyed at the right columns.
1255 Each hashref can contain any of the keys shown below:
1259 =item B<min_w> - Minimum width of this column. Auto calculation will try its best to honour this param but aplying it is NOT guaranteed.
1261 B<Value:> can be any whole number satisfying 0 < min_w < w
1262 B<Default:> Auto calculated
1264 =item B<max_w> - Maximum width of this column. Auto calculation will try its best to honour this param but aplying it is NOT guaranteed.
1266 B<Value:> can be any whole number satisfying 0 < max_w < w
1267 B<Default:> Auto calculated
1269 =item B<font> - instance of PDF::API2::Resource::Font defining the fontf to be used in this column
1271 B<Value:> can be any PDF::API2::Resource::* type of font
1272 B<Default:> 'font' of the table. See table parameter 'font' for more details.
1274 =item B<font_size> - Font size of this column
1276 B<Value:> can be any positive number
1277 B<Default:> 'font_size' of the table.
1279 =item B<font_color> - Font color of this column
1281 B<Value:> Color specifier as 'name' or 'HEX'
1282 B<Default:> 'font_color' of the table.
1284 =item B<background_color> - Background color of this column
1286 B<Value:> Color specifier as 'name' or 'HEX'
1289 =item B<justify> - Alignment of text in this column
1291 B<Value:> One of 'left', 'right', 'center'
1297 {},# This is an empty hash so the next one will hold the properties for the second column from left to right.
1299 min_w => 100, # Minimum column width of 100.
1300 max_w => 150, # Maximum column width of 150 .
1301 justify => 'right', # Right text alignment
1302 font => $pdf->corefont("Helvetica", -encoding => "latin1"),
1304 font_color=> 'blue',
1305 background_color => '#FFFF00',
1312 NOTE: If 'min_w' and/or 'max_w' parameter is used in 'col_props', have in mind that it may be overriden by the calculated minimum/maximum cell witdh so that table can be created.
1313 When this happens a warning will be issued with some advises what can be done.
1314 In cases of a conflict between column formatting and odd/even row formatting, 'col_props' will override odd/even.
1316 =head4 Cell Properties
1318 If the 'cell_props' parameter is used, it should be an arrayref with arrays of hashrefs
1319 (of the same dimension as the data array) with one hashref for each cell of the table.
1321 Each hashref can contain any of the keys shown below:
1325 =item B<font> - instance of PDF::API2::Resource::Font defining the fontf to be used in this cell
1327 B<Value:> can be any PDF::API2::Resource::* type of font
1328 B<Default:> 'font' of the table. See table parameter 'font' for more details.
1330 =item B<font_size> - Font size of this cell
1332 B<Value:> can be any positive number
1333 B<Default:> 'font_size' of the table.
1335 =item B<font_color> - Font color of this cell
1337 B<Value:> Color specifier as 'name' or 'HEX'
1338 B<Default:> 'font_color' of the table.
1340 =item B<background_color> - Background color of this cell
1342 B<Value:> Color specifier as 'name' or 'HEX'
1345 =item B<justify> - Alignment of text in this cell
1347 B<Value:> One of 'left', 'right', 'center'
1353 [ #This array is for the first row. If header_props is defined it will overwrite these settings.
1355 background_color => '#AAAA00',
1356 font_color => 'yellow',
1363 background_color => '#CCCC00',
1364 font_color => 'blue',
1367 background_color => '#BBBB00',
1368 font_color => 'red',
1377 my $cell_props = [];
1378 $cell_props->[1][0] = {
1380 background_color => '#CCCC00',
1381 font_color => 'blue',
1386 NOTE: In case of a conflict between column, odd/even and cell formating, cell formating will overwrite the other two.
1387 In case of a conflict between header row and cell formating, header formating will override cell.
1391 my ($width_of_last_line, $ypos_of_last_line, $left_over_text) = text_block( $txt, $data, %settings)
1397 Utility method to create a block of text. The block may contain multiple paragraphs.
1398 It is mainly used internaly but you can use it from outside for placing formated text anywhere on the sheet.
1400 NOTE: This method will NOT add more pages to the pdf instance if the space is not enough to place the string inside the block.
1401 Leftover text will be returned and has to be handled by the caller - i.e. add a new page and a new block with the leftover.
1405 $txt - a PDF::API2::Page::Text instance representing the text tool
1406 $data - a string that will be placed inside the block
1407 %settings - HASH with geometry and formatting parameters.
1411 The return value is a 3 items list where
1413 $width_of_last_line - Width of last line in the block
1414 $final_y - The Y coordinate of the block bottom so that additional content can be added after it
1415 $left_over_text - Text that was did not fit in the provided box geometry.
1420 my $page = $pdf->page;
1421 my $txt = $page->text;
1430 lead => $font_size | $distance_between_lines,
1431 align => "left|right|center|justify|fulljustify",
1432 hang => $optional_hanging_indent,
1433 Only one of the subsequent 3params can be given.
1434 They override each other.-parspace is the weightest
1435 parspace => $optional_vertical_space_before_first_paragraph,
1436 flindent => $optional_indent_of_first_line,
1437 fpindent => $optional_indent_of_first_paragraph,
1438 indent => $optional_indent_of_text_to_every_non_first_line,
1441 my ( $width_of_last_line, $final_y, $left_over_text ) = $pdftable->text_block( $txt, $data, %settings );
1455 Further development since Ver: 0.02 - Desislav Kamenov
1457 =head1 COPYRIGHT AND LICENSE
1459 Copyright (C) 2006 by Daemmon Hughes, portions Copyright 2004 Stone
1460 Environmental Inc. (www.stone-env.com) All Rights Reserved.
1462 This library is free software; you can redistribute it and/or modify
1463 it under the same terms as Perl itself, either Perl version 5.8.4 or,
1464 at your option, any later version of Perl 5 you may have available.
1470 =item by Daemmon Hughes
1472 Much of the work on this module was sponsered by
1473 Stone Environmental Inc. (www.stone-env.com).
1475 The text_block() method is a slightly modified copy of the one from
1476 Rick Measham's PDF::API2 L<tutorial|http://rick.measham.id.au/pdf-api2>.
1478 =item by Desislav Kamenov (@deskata on Twitter)
1480 The development of this module was supported by SEEBURGER AG (www.seeburger.com) till year 2007
1482 Thanks to my friends Krasimir Berov and Alex Kantchev for helpful tips and QA during development of versions 0.9.0 to 0.9.5
1484 Thanks to all GitHub contributors!
1490 Hey PDF::Table is on GitHub. You are more than welcome to contribute!
1492 https://github.com/kamenov/PDF-Table