2 # vim: softtabstop=4 tabstop=4 shiftwidth=4 ft=perl expandtab smarttab
11 use List::Util qw(sum);
13 our $VERSION = '0.10.1';
15 print __PACKAGE__.' is version: '.$VERSION.$/ if($ENV{'PDF_TABLE_DEBUG'});
17 ############################################################
21 # Parameters are meta information about the PDF
23 # $pdf = PDF::Table->new();
25 ############################################################
30 my $class = ref($type) || $type;
32 bless ($self, $class);
34 # Pass all the rest to init for validation and initialisation
42 my ($self, $pdf, $page, $data, %options ) = @_;
44 # Check and set default values
45 $self->set_defaults();
47 # Check and set mandatory params
49 $self->set_page($page);
50 $self->set_data($data);
51 $self->set_options(\%options);
59 $self->{'font_size'} = 12;
63 my ($self, $pdf) = @_;
64 $self->{'pdf'} = $pdf;
68 my ($self, $page) = @_;
69 if ( defined($page) && ref($page) ne 'PDF::API2::Page' ){
71 if( ref($self->{'pdf'}) eq 'PDF::API2' ){
72 $self->{'page'} = $self->{'pdf'}->page();
74 carp 'Warning: Page must be a PDF::API2::Page object but it seems to be: '.ref($page).$/;
75 carp 'Error: Cannot set page from passed PDF object either as it is invalid!'.$/;
79 $self->{'page'} = $page;
84 my ($self, $data) = @_;
89 my ($self, $options) = @_;
93 ############################################################
95 # text_block - utility method to build multi-paragraph blocks of text
97 ############################################################
102 my $text_object = shift;
103 my $text = shift; # The text to be displayed
104 my %arg = @_; # Additional Arguments
106 my ( $align, $xpos, $ypos, $xbase, $ybase, $line_width, $wordspace, $endw , $width, $height) =
107 ( undef , undef, undef, undef , undef , undef , undef , undef , undef , undef );
108 my @line = (); # Temp data array with words on one line
109 my %width = (); # The width of every unique word in the givven text
111 # Try to provide backward compatibility
112 foreach my $key (keys %arg)
115 if($newkey =~ s#^-##)
117 $arg{$newkey} = $arg{$key};
124 # Lets check mandatory parameters with no default values
126 $xbase = $arg{'x'} || -1;
127 $ybase = $arg{'y'} || -1;
128 $width = $arg{'w'} || -1;
129 $height = $arg{'h'} || -1;
130 unless( $xbase > 0 ){ carp "Error: Left Edge of Block is NOT defined!\n"; return; }
131 unless( $ybase > 0 ){ carp "Error: Base Line of Block is NOT defined!\n"; return; }
132 unless( $width > 0 ){ carp "Error: Width of Block is NOT defined!\n"; return; }
133 unless( $height > 0 ){ carp "Error: Height of Block is NOT defined!\n"; return; }
134 # Check if any text to display
135 unless( defined( $text) and length($text) > 0 )
137 carp "Warning: No input text found. Trying to add dummy '-' and not to break everything.\n";
141 # Strip any <CR> and Split the text into paragraphs
143 my @paragraphs = split(/\n/, $text);
145 # Width between lines in pixels
146 my $line_space = defined $arg{'lead'} && $arg{'lead'} > 0 ? $arg{'lead'} : 12;
148 # Calculate width of all words
149 my $space_width = $text_object->advancewidth("\x20");
150 my @words = split(/\s+/, $text);
153 next if exists $width{$_};
154 $width{$_} = $text_object->advancewidth($_);
157 my @paragraph = split(' ', shift(@paragraphs));
159 my $first_paragraph = 1;
164 $ypos = $ybase + $line_space;
165 my $bottom_border = $ypos - $height;
166 # While we can add another line
167 while ( $ypos >= $bottom_border + $line_space )
169 # Is there any text to render ?
172 # Finish if nothing left
173 last unless scalar @paragraphs;
174 # Else take one line from the text
175 @paragraph = split(' ', shift( @paragraphs ) );
177 $ypos -= $arg{'parspace'} if $arg{'parspace'};
178 last unless $ypos >= $bottom_border;
180 $ypos -= $line_space;
183 # While there's room on the line, add another word
186 if( $first_line && exists $arg{'hang'} )
188 my $hang_width = $text_object->advancewidth($arg{'hang'});
190 $text_object->translate( $xpos, $ypos );
191 $text_object->text( $arg{'hang'} );
193 $xpos += $hang_width;
194 $line_width += $hang_width;
195 $arg{'indent'} += $hang_width if $first_paragraph;
197 elsif( $first_line && exists $arg{'flindent'} && $arg{'flindent'} > 0 )
199 $xpos += $arg{'flindent'};
200 $line_width += $arg{'flindent'};
202 elsif( $first_paragraph && exists $arg{'fpindent'} && $arg{'fpindent'} > 0 )
204 $xpos += $arg{'fpindent'};
205 $line_width += $arg{'fpindent'};
207 elsif (exists $arg{'indent'} && $arg{'indent'} > 0 )
209 $xpos += $arg{'indent'};
210 $line_width += $arg{'indent'};
213 # Lets take from paragraph as many words as we can put into $width - $indent;
214 while ( @paragraph and $text_object->advancewidth( join("\x20", @line)."\x20" . $paragraph[0]) +
215 $line_width < $width )
217 push(@line, shift(@paragraph));
219 $line_width += $text_object->advancewidth(join('', @line));
221 # calculate the space width
222 if( $arg{'align'} eq 'fulljustify' or ($arg{'align'} eq 'justify' and @paragraph))
224 @line = split(//,$line[0]) if (scalar(@line) == 1) ;
225 $wordspace = ($width - $line_width) / (scalar(@line) - 1);
230 $align=($arg{'align'} eq 'justify') ? 'left' : $arg{'align'};
231 $wordspace = $space_width;
233 $line_width += $wordspace * (scalar(@line) - 1);
235 if( $align eq 'justify')
237 foreach my $word (@line)
239 $text_object->translate( $xpos, $ypos );
240 $text_object->text( $word );
241 $xpos += ($width{$word} + $wordspace) if (@line);
247 # calculate the left hand position of the line
248 if( $align eq 'right' )
250 $xpos += $width - $line_width;
252 elsif( $align eq 'center' )
254 $xpos += ( $width / 2 ) - ( $line_width / 2 );
258 $text_object->translate( $xpos, $ypos );
259 $endw = $text_object->text( join("\x20", @line));
263 unshift(@paragraphs, join(' ',@paragraph)) if scalar(@paragraph);
264 return ($endw, $ypos, join("\n", @paragraphs))
268 ################################################################
269 # table - utility method to build multi-row, multicolumn tables
270 ################################################################
279 #=====================================
280 # Mandatory Arguments Section
281 #=====================================
282 unless($pdf and $page and $data)
284 carp "Error: Mandatory parameter is missing pdf/page/data object!\n";
288 # Validate mandatory argument data type
289 croak "Error: Invalid pdf object received." unless (ref($pdf) eq 'PDF::API2');
290 croak "Error: Invalid page object received." unless (ref($page) eq 'PDF::API2::Page');
291 croak "Error: Invalid data received." unless ((ref($data) eq 'ARRAY') && scalar(@$data));
292 croak "Error: Missing required settings." unless (scalar(keys %arg));
294 # Validate settings key
295 my %valid_settings_key = (
308 background_color => 1,
309 background_color_odd => 1,
310 background_color_even => 1,
313 horizontal_borders => 1,
314 vertical_borders => 1,
319 font_color_even => 1,
321 background_color_odd => 1,
322 background_color_even => 1,
328 max_word_length => 1,
329 cell_render_hook => 1,
331 num_header_rows => 1,
333 foreach my $key (keys %arg)
335 # Provide backward compatibility
336 $arg{$key} = delete $arg{"-$key"} if $key =~ s/^-//;
338 croak "Error: Invalid setting key '$key' received."
339 unless exists $valid_settings_key{$key};
344 #TODO: Add code for header props compatibility and col_props comp....
346 my ( $xbase, $ybase, $width, $height ) = ( undef, undef, undef, undef );
347 # Could be 'int' or 'real' values
348 $xbase = $arg{'x' } || -1;
349 $ybase = $arg{'start_y'} || -1;
350 $width = $arg{'w' } || -1;
351 $height = $arg{'start_h'} || -1;
353 # Global geometry parameters are also mandatory.
354 unless( $xbase > 0 ){ carp "Error: Left Edge of Table is NOT defined!\n"; return; }
355 unless( $ybase > 0 ){ carp "Error: Base Line of Table is NOT defined!\n"; return; }
356 unless( $width > 0 ){ carp "Error: Width of Table is NOT defined!\n"; return; }
357 unless( $height > 0 ){ carp "Error: Height of Table is NOT defined!\n"; return; }
359 # Ensure default values for -next_y and -next_h
360 my $next_y = $arg{'next_y'} || $arg{'start_y'} || 0;
361 my $next_h = $arg{'next_h'} || $arg{'start_h'} || 0;
364 my $txt = $page->text;
366 # Set Default Properties
367 my $fnt_name = $arg{'font' } || $pdf->corefont('Times',-encode => 'utf8');
368 my $fnt_size = $arg{'font_size' } || 12;
369 my $fnt_underline = $arg{'font_underline' } || undef; # merely stating undef is the intended default
370 my $max_word_len = $arg{'max_word_length' } || 20;
372 #=====================================
373 # Table Header Section
374 #=====================================
375 # Disable header row into the table
376 my $header_props = undef;
378 # Check if the user enabled it ?
379 if(defined $arg{'header_props'} and ref( $arg{'header_props'}) eq 'HASH')
381 # Transfer the reference to local variable
382 $header_props = $arg{'header_props'};
384 # Check other params and put defaults if needed
385 $header_props->{'repeat' } = $header_props->{'repeat' } || 0;
386 $header_props->{'font' } = $header_props->{'font' } || $fnt_name;
387 $header_props->{'font_color' } = $header_props->{'font_color' } || '#000066';
388 $header_props->{'font_size' } = $header_props->{'font_size' } || $fnt_size + 2;
389 $header_props->{'font_underline'} = $header_props->{'font_underline'} || $fnt_underline;
390 $header_props->{'bg_color' } = $header_props->{'bg_color' } || '#FFFFAA';
391 $header_props->{'justify' } = $header_props->{'justify' };
392 $header_props->{num_header_rows } = $arg{num_header_rows } || 1;
394 #=====================================
395 # Other Parameters check
396 #=====================================
397 my $lead = $arg{'lead' } || $fnt_size;
398 my $pad_left = $arg{'padding_left' } || $arg{'padding'} || 0;
399 my $pad_right = $arg{'padding_right' } || $arg{'padding'} || 0;
400 my $pad_top = $arg{'padding_top' } || $arg{'padding'} || 0;
401 my $pad_bot = $arg{'padding_bottom'} || $arg{'padding'} || 0;
402 my $default_text = $arg{'default_text' } // '-';
403 my $line_w = defined $arg{'border'} ? $arg{'border'} : 1 ;
404 my $horiz_borders = defined $arg{'horizontal_borders'}
405 ? $arg{'horizontal_borders'}
407 my $vert_borders = defined $arg{'vertical_borders'}
408 ? $arg{'vertical_borders'}
411 my $background_color_even = $arg{'background_color_even' } || $arg{'background_color'} || undef;
412 my $background_color_odd = $arg{'background_color_odd' } || $arg{'background_color'} || undef;
413 my $font_color_even = $arg{'font_color_even' } || $arg{'font_color' } || 'black';
414 my $font_color_odd = $arg{'font_color_odd' } || $arg{'font_color' } || 'black';
415 my $border_color = $arg{'border_color' } || 'black';
417 my $min_row_h = $fnt_size + $pad_top + $pad_bot;
418 my $row_h = defined ($arg{'row_height'})
420 ($arg{'row_height'} > $min_row_h)
422 $arg{'row_height'} : $min_row_h;
426 my $cell_props = $arg{cell_props} || []; # per cell properties
428 #If there is no valid data array reference warn and return!
429 if(ref $data ne 'ARRAY')
431 carp "Passed table data is not an ARRAY reference. It's actually a ref to ".ref($data);
432 return ($page,0,$cur_y);
435 # Copy the header row if header is enabled
436 if (defined $header_props) {
437 map { push @header_rows, $$data[$_] } (0..$header_props->{num_header_rows} - 1);
439 # Determine column widths based on content
441 # an arrayref whose values are a hashref holding
442 # the minimum and maximum width of that column
443 my $col_props = $arg{'column_props'} || [];
445 # An array ref of arrayrefs whose values are
446 # the actual widths of the column/row intersection
447 my $row_col_widths = [];
448 # An array ref with the widths of the header row
449 my @header_row_props;
451 # Scalars that hold sum of the maximum and minimum widths of all columns
452 my ( $max_col_w , $min_col_w ) = ( 0,0 );
453 my ( $row, $col_name, $col_fnt_size, $col_fnt_underline, $space_w );
455 my $word_widths = {};
456 my $rows_height = [];
459 for( my $row_idx = 0; $row_idx < scalar(@$data) ; $row_idx++ )
461 push @header_row_props, [] if $row_idx < $header_props->{num_header_rows};
463 my $column_widths = []; #holds the width of each column
464 # Init the height for this row
465 $rows_height->[$row_idx] = 0;
467 for( my $column_idx = 0; $column_idx < scalar(@{$data->[$row_idx]}) ; $column_idx++ )
469 # look for font information for this column
470 my ($cell_font, $cell_font_size, $cell_font_underline);
472 if( !$row_idx and ref $header_props )
474 $cell_font = $header_props->{'font'};
475 $cell_font_size = $header_props->{'font_size'};
476 $cell_font_underline = $header_props->{'font_underline'};
479 # Get the most specific value if none was already set from header_props
480 $cell_font ||= $cell_props->[$row_idx][$column_idx]->{'font'}
481 || $col_props->[$column_idx]->{'font'}
484 $cell_font_size ||= $cell_props->[$row_idx][$column_idx]->{'font_size'}
485 || $col_props->[$column_idx]->{'font_size'}
488 $cell_font_underline ||= $cell_props->[$row_idx][$column_idx]->{'font_underline'}
489 || $col_props->[$column_idx]->{'font_underline'}
495 $txt->font( $cell_font, $cell_font_size );
497 # Set row height to biggest font size from row's cells
498 if( $cell_font_size > $rows_height->[$row_idx] )
500 $rows_height->[$row_idx] = $cell_font_size;
503 # This should fix a bug with very long words like serial numbers etc.
504 if( $max_word_len > 0 )
506 $data->[$row_idx][$column_idx] =~ s#(\S{$max_word_len})(?=\S)#$1 #g;
509 # Init cell size limits
510 $space_w = $txt->advancewidth( "\x20" );
511 $column_widths->[$column_idx] = 0;
515 my @words = split( /\s+/, $data->[$row_idx][$column_idx] );
519 unless( exists $word_widths->{$_} )
520 { # Calculate the width of every word and add the space width to it
521 $word_widths->{$_} = $txt->advancewidth( $_ ) + $space_w;
524 $column_widths->[$column_idx] += $word_widths->{$_};
525 $min_col_w = $word_widths->{$_} if( $word_widths->{$_} > $min_col_w );
526 $max_col_w += $word_widths->{$_};
529 $min_col_w += $pad_left + $pad_right;
530 $max_col_w += $pad_left + $pad_right;
531 $column_widths->[$column_idx] += $pad_left + $pad_right;
533 # Keep a running total of the overall min and max widths
534 $col_props->[$column_idx]->{'min_w'} ||= 0;
535 $col_props->[$column_idx]->{'max_w'} ||= 0;
537 if( $min_col_w > $col_props->[$column_idx]->{'min_w'} )
538 { # Calculated Minimum Column Width is more than user-defined
539 $col_props->[$column_idx]->{'min_w'} = $min_col_w ;
542 if( $max_col_w > $col_props->[$column_idx]->{'max_w'} )
543 { # Calculated Maximum Column Width is more than user-defined
544 $col_props->[$column_idx]->{'max_w'} = $max_col_w ;
546 }#End of for(my $column_idx....
548 $row_col_widths->[$row_idx] = $column_widths;
550 # Copy the calculated row properties of header row.
551 if (ref $header_props && $row_idx < $header_props->{num_header_rows}) {
552 push @header_row_props, [ @{ $column_widths } ];
556 # Calc real column widths and expand table width if needed.
557 my $calc_column_widths;
558 ($calc_column_widths, $width) = CalcColumnWidths( $col_props, $width );
559 my $num_cols = scalar @{ $calc_column_widths };
561 # Lets draw what we have!
563 # Store header row height for later use if headers have to be repeated
564 my @header_row_heights = @$rows_height[0 .. $header_props->{num_header_rows}-1];
566 my ( $gfx, $gfx_bg, $background_color, $font_color, $bot_marg, $table_top_y, $text_start);
568 my $remaining_header_rows = $header_props ? $header_props->{num_header_rows} : 0;
570 # Each iteration adds a new page as neccessary
571 while(scalar(@{$data}))
574 my $columns_number = 0;
578 $table_top_y = $ybase;
579 $bot_marg = $table_top_y - $height;
581 # Check for safety reasons
583 { # This warning should remain i think
584 #carp "!!! Warning: !!! Incorrect Table Geometry! start_h (${height}) is above start_y (${table_top_y}). Setting bottom margin to end of sheet!\n";
591 if(ref $arg{'new_page_func'})
593 $page = &{$arg{'new_page_func'}};
600 $table_top_y = $next_y;
601 $bot_marg = $table_top_y - $next_h;
603 # Check for safety reasons
605 { # This warning should remain i think
606 #carp "!!! Warning: !!! Incorrect Table Geometry! next_y or start_y (${next_y}) is above next_h or start_h (${next_h}). Setting bottom margin to end of sheet!\n";
610 if( ref $header_props and $header_props->{'repeat'})
612 for my $idx (0 .. $header_props->{num_header_rows} - 1) {
613 unshift @$data, [ @{ $header_rows[$idx] } ];
614 unshift @$row_col_widths, [ @{ $header_row_props[$idx] } ];
615 unshift @$rows_height, $header_row_heights[$idx];
617 $remaining_header_rows = $header_props->{num_header_rows};
622 $gfx_bg = $page->gfx;
624 $txt->font($fnt_name, $fnt_size);
626 $cur_y = $table_top_y;
631 $gfx->strokecolor($border_color);
632 $gfx->linewidth($line_w);
637 $gfx->move( $xbase , $cur_y );
638 $gfx->hline($xbase + $width );
646 # Each iteration adds a row to the current page until the page is full
647 # or there are no more rows to add
649 while(scalar(@{$data}) and $cur_y-$row_h > $bot_marg)
651 # Remove the next item from $data
652 my $record = shift @{$data};
654 # Get max columns number to know later how many vertical lines to draw
655 $columns_number = scalar(@$record)
656 if scalar(@$record) > $columns_number;
658 # Get the next set of row related settings
660 my $pre_calculated_row_height = shift @$rows_height;
663 my $record_widths = shift @$row_col_widths;
665 # Row coloumn props - TODO in another commit
667 # Row cell props - TODO in another commit
670 # Choose colors for this row
671 $background_color = $row_index % 2 ? $background_color_even : $background_color_odd;
672 $font_color = $row_index % 2 ? $font_color_even : $font_color_odd;
674 #Determine current row height
675 my $current_row_height = $pad_top + $pre_calculated_row_height + $pad_bot;
677 # $row_h is the calculated global user requested row height.
678 # It will be honored, only if it has bigger value than the calculated one.
679 # TODO: It's questionable if padding should be inclided in this calculation or not
680 if($current_row_height < $row_h){
681 $current_row_height = $row_h;
684 # Define the font y base position for this line.
685 $text_start = $cur_y - ($current_row_height - $pad_bot);
688 my $leftovers = undef; # Reference to text that is returned from textblock()
689 my $do_leftovers = 0;
690 my ($colspan, @vertical_lines);
692 # Process every cell(column) from current row
693 for( my $column_idx = 0; $column_idx < scalar( @$record); $column_idx++ )
695 next unless $col_props->[$column_idx]->{'max_w'};
696 next unless $col_props->[$column_idx]->{'min_w'};
697 $leftovers->[$column_idx] = undef;
699 # look for font information for this cell
700 my ($cell_font, $cell_font_size, $cell_font_color, $cell_font_underline, $justify);
702 if( $remaining_header_rows and ref $header_props)
704 $cell_font = $header_props->{'font'};
705 $cell_font_size = $header_props->{'font_size'};
706 $cell_font_color = $header_props->{'font_color'};
707 $cell_font_underline = $header_props->{'font_underline'};
708 $justify = $header_props->{'justify'};
711 # Get the most specific value if none was already set from header_props
712 $cell_font ||= $cell_props->[$row_index][$column_idx]->{'font'}
713 || $col_props->[$column_idx]->{'font'}
716 $cell_font_size ||= $cell_props->[$row_index][$column_idx]->{'font_size'}
717 || $col_props->[$column_idx]->{'font_size'}
720 $cell_font_color ||= $cell_props->[$row_index][$column_idx]->{'font_color'}
721 || $col_props->[$column_idx]->{'font_color'}
724 $cell_font_underline ||= $cell_props->[$row_index][$column_idx]->{'font_underline'}
725 || $col_props->[$column_idx]->{'font_underline'}
729 $justify ||= $cell_props->[$row_index][$column_idx]->{'justify'}
730 || $col_props->[$column_idx]->{'justify'}
734 # Init cell font object
735 $txt->font( $cell_font, $cell_font_size );
736 $txt->fillcolor($cell_font_color);
738 # Added to resolve infite loop bug with returned undef values
739 $record->[$column_idx] //= $cell_props->[$row_index][$column_idx]->{'default_text'}
740 // $col_props->[$column_idx]->{'default_text'}
744 if (!$remaining_header_rows && $cell_props->[$row_index][$column_idx]->{colspan}) {
745 $colspan = -1 == $cell_props->[$row_index][$column_idx]->{colspan}
746 ? $num_cols - $column_idx
747 : $cell_props->[$row_index][$column_idx]->{colspan};
748 my $last_idx = $column_idx + $colspan - 1;
749 $this_width = sum @{ $calc_column_widths }[$column_idx..$last_idx];
752 $this_width = $calc_column_widths->[$column_idx];
755 # If the content is wider than the specified width, we need to add the text as a text block
756 if( $record->[$column_idx] !~ m/(.\n.)/ and
757 $record_widths->[$column_idx] and
758 $record_widths->[$column_idx] <= $this_width
760 my $space = $pad_left;
761 if ($justify eq 'right')
763 $space = $this_width -($txt->advancewidth($record->[$column_idx]) + $pad_right);
765 elsif ($justify eq 'center')
767 $space = ($this_width - $txt->advancewidth($record->[$column_idx])) / 2;
769 $txt->translate( $cur_x + $space, $text_start );
771 $text_options{'-underline'} = $cell_font_underline if $cell_font_underline;
772 $txt->text( $record->[$column_idx], %text_options );
774 # Otherwise just use the $page->text() method
777 my ($width_of_last_line, $ypos_of_last_line, $left_over_text) = $self->text_block(
779 $record->[$column_idx],
780 x => $cur_x + $pad_left,
782 w => $this_width - $pad_left - $pad_right,
783 h => $cur_y - $bot_marg - $pad_top - $pad_bot,
787 # Desi - Removed $lead because of fixed incorrect ypos bug in text_block
788 my $current_cell_height = $cur_y - $ypos_of_last_line + $pad_bot;
789 if( $current_cell_height > $current_row_height )
791 $current_row_height = $current_cell_height;
794 if( $left_over_text )
796 $leftovers->[$column_idx] = $left_over_text;
801 # Hook to pass coordinates back - http://www.perlmonks.org/?node_id=754777
802 if (ref $arg{cell_render_hook} eq 'CODE') {
803 $arg{cell_render_hook}->(
810 $calc_column_widths->[$column_idx],
815 $cur_x += $calc_column_widths->[$column_idx];
817 push @vertical_lines, (!$colspan || (1 >= $colspan)) ? 1 : 0;
818 $colspan-- if $colspan;
822 unshift @$data, $leftovers;
823 unshift @$row_col_widths, $record_widths;
824 unshift @$rows_height, $pre_calculated_row_height;
828 # This has to be separately from the text loop
829 # because we do not know the final height of the cell until all text has been drawn
831 for(my $column_idx = 0 ; $column_idx < scalar(@$record) ; $column_idx++)
835 if( $remaining_header_rows and ref $header_props)
836 { #Compatibility Consistency with other props
837 $cell_bg_color = $header_props->{'bg_color'} || $header_props->{'background_color'};
840 # Get the most specific value if none was already set from header_props
841 $cell_bg_color ||= $cell_props->[$row_index][$column_idx]->{'background_color'}
842 || $col_props->[$column_idx]->{'background_color'}
843 || $background_color;
847 $gfx_bg->rect( $cur_x, $cur_y-$current_row_height, $calc_column_widths->[$column_idx], $current_row_height);
848 $gfx_bg->fillcolor($cell_bg_color);
851 $cur_x += $calc_column_widths->[$column_idx];
853 if ($line_w && $vertical_lines[$column_idx] && ($column_idx != (scalar(@{ $record }) - 1))) {
854 $gfx->move($cur_x, $cur_y);
855 $gfx->vline($cur_y - $row_h);
856 $gfx->fillcolor($border_color);
858 }#End of for(my $column_idx....
860 $cur_y -= $current_row_height;
861 if ($gfx && $horiz_borders)
863 $gfx->move( $xbase , $cur_y );
864 $gfx->hline( $xbase + $width );
868 if ($remaining_header_rows) {
869 $remaining_header_rows--;
871 $row_index++ unless $do_leftovers;
877 # Draw vertical lines
880 $gfx->move( $xbase, $table_top_y);
881 $gfx->vline( $cur_y );
882 $gfx->move($xbase + sum(@{ $calc_column_widths }[0..$num_cols - 1]), $table_top_y);
883 $gfx->vline( $cur_y );
886 # ACTUALLY draw all the lines
887 $gfx->fillcolor( $border_color);
891 }# End of while(scalar(@{$data}))
893 return ($page,--$pg_cnt,$cur_y);
897 # calculate the column widths
900 my $col_props = shift;
901 my $avail_width = shift;
906 for(my $j = 0; $j < scalar( @$col_props); $j++)
908 $min_width += $col_props->[$j]->{min_w} || 0;
911 # I think this is the optimal variant when good view can be guaranateed
912 if($avail_width < $min_width)
914 carp "!!! Warning !!!\n Calculated Mininal width($min_width) > Table width($avail_width).\n",
915 ' Expanding table width to:',int($min_width)+1,' but this could lead to unexpected results.',"\n",
916 ' Possible solutions:',"\n",
917 ' 0)Increase table width.',"\n",
918 ' 1)Decrease font size.',"\n",
919 ' 2)Choose a more narrow font.',"\n",
920 ' 3)Decrease "max_word_length" parameter.',"\n",
921 ' 4)Rotate page to landscape(if it is portrait).',"\n",
922 ' 5)Use larger paper size.',"\n",
923 '!!! --------- !!!',"\n";
924 $avail_width = int( $min_width) + 1;
928 # Calculate how much can be added to every column to fit the available width.
929 for(my $j = 0; $j < scalar(@$col_props); $j++ )
931 $calc_widths->[$j] = $col_props->[$j]->{min_w} || 0;;
934 # Allow columns to expand to max_w before applying extra space equally.
938 my $span = ($avail_width - $min_width) / scalar( @$col_props);
942 my $next_will_be_last_iter = 1;
943 for(my $j = 0; $j < scalar(@$col_props); $j++ )
945 my $new_w = $calc_widths->[$j] + $span;
947 if (!$is_last_iter && $new_w > $col_props->[$j]->{max_w})
949 $new_w = $col_props->[$j]->{max_w}
951 if ($calc_widths->[$j] != $new_w )
953 $calc_widths->[$j] = $new_w;
954 $next_will_be_last_iter = 0;
956 $min_width += $new_w;
958 last if $is_last_iter;
959 $is_last_iter = $next_will_be_last_iter;
962 return ($calc_widths,$avail_width);
972 PDF::Table - A utility class for building table layouts in a PDF::API2 object.
979 my $pdftable = new PDF::Table;
980 my $pdf = new PDF::API2(-file => "table_of_lorem.pdf");
981 my $page = $pdf->page;
983 # some data to layout
985 ["1 Lorem ipsum dolor",
986 "Donec odio neque, faucibus vel",
987 "consequat quis, tincidunt vel, felis."],
988 ["Nulla euismod sem eget neque.",
994 $left_edge_of_table = 50;
995 # build the table layout
1001 x => $left_edge_of_table,
1005 # some optional params
1009 padding_right => 10,
1010 background_color_odd => "gray",
1011 background_color_even => "lightblue", #cell background color for even rows
1014 # do other stuff with $pdf
1020 For a complete working example or initial script look into distribution`s 'examples' folder.
1025 This class is a utility for use with the PDF::API2 module from CPAN.
1026 It can be used to display text data in a table layout within a PDF.
1027 The text data must be in a 2D array (such as returned by a DBI statement handle fetchall_arrayref() call).
1028 The PDF::Table will automatically add as many new pages as necessary to display all of the data.
1029 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.
1030 Also a (non)repeated header row with different layout properties can be specified.
1032 See the L</METHODS> section for complete documentation of every parameter.
1038 my $pdf_table = new PDF::Table;
1044 Creates a new instance of the class. (to be improved)
1048 There are no parameters.
1052 Reference to the new instance
1058 my ($final_page, $number_of_pages, $final_y) = table($pdf, $page, $data, %settings)
1064 Generates a multi-row, multi-column table into an existing PDF document based on provided data set and settings.
1068 $pdf - a PDF::API2 instance representing the document being created
1069 $page - a PDF::API2::Page instance representing the current page of the document
1070 $data - an ARRAY reference to a 2D data structure that will be used to build the table
1071 %settings - HASH with geometry and formatting parameters.
1073 For full %settings description see section L</Table settings> below.
1075 This method will add more pages to the pdf instance as required based on the formatting options and the amount of data.
1079 The return value is a 3 items list where
1081 $final_page - The first item is a PDF::API2::Page instance that the table ends on
1082 $number_of_pages - The second item is the count of pages that the table spans on
1083 $final_y - The third item is the Y coordinate of the table bottom so that additional content can be added in the same document.
1087 my $pdf = new PDF::API2;
1088 my $page = $pdf->page();
1090 ['foo1','bar1','baz1'],
1091 ['foo2','bar2','baz2']
1100 my ($final_page, $number_of_pages, $final_y) = $pdftable->table( $pdf, $page, $data, %options );
1104 =head3 Table settings
1108 There are some mandatory parameteres for setting table geometry and position across page(s)
1112 =item B<x> - X coordinate of upper left corner of the table. Left edge of the sheet is 0.
1114 B<Value:> can be any whole number satisfying 0 =< X < PageWidth
1115 B<Default:> No default value
1119 =item B<start_y> - Y coordinate of upper left corner of the table at the initial page.
1121 B<Value:> can be any whole number satisfying 0 < start_y < PageHeight (depending on space availability when embedding a table)
1122 B<Default:> No default value
1126 =item B<w> - width of the table starting from X.
1128 B<Value:> can be any whole number satisfying 0 < w < PageWidth - x
1129 B<Default:> No default value
1133 =item B<start_h> - Height of the table on the initial page
1135 B<Value:> can be any whole number satisfying 0 < start_h < PageHeight - Current Y position
1136 B<Default:> No default value
1146 =item B<next_h> - Height of the table on any additional page
1148 B<Value:> can be any whole number satisfying 0 < next_h < PageHeight
1149 B<Default:> Value of param B<'start_h'>
1153 =item B<next_y> - Y coordinate of upper left corner of the table at any additional page.
1155 B<Value:> can be any whole number satisfying 0 < next_y < PageHeight
1156 B<Default:> Value of param B<'start_y'>
1160 =item B<max_word_length> - Breaks long words (like serial numbers hashes etc.) by adding a space after every Nth symbol
1162 B<Value:> can be any whole positive number
1165 max_word_length => 20 # Will add a space after every 20 symbols
1167 =item B<padding> - Padding applied to every cell
1169 =item B<padding_top> - top cell padding, overrides 'padding'
1171 =item B<padding_right> - right cell padding, overrides 'padding'
1173 =item B<padding_left> - left cell padding, overrides 'padding'
1175 =item B<padding_bottom> - bottom padding, overrides 'padding'
1177 B<Value:> can be any whole positive number
1179 B<Default padding:> 0
1181 B<Default padding_*> $padding
1183 padding => 5 # all sides cell padding
1184 padding_top => 8, # top cell padding, overrides 'padding'
1185 padding_right => 6, # right cell padding, overrides 'padding'
1186 padding_left => 2, # left cell padding, overrides 'padding'
1187 padding_bottom => undef # bottom padding will be 5 as it will fallback to 'padding'
1189 =item B<border> - Width of table border lines.
1191 =item B<horizontal_borders> - Width of horizontal border lines. Overrides 'border' value.
1193 =item B<vertical_borders> - Width of vertical border lines. Overrides 'border' value.
1195 B<Value:> can be any whole positive number. When set to 0 will disable border lines.
1198 border => 3 # border width is 3
1199 horizontal_borders => 1 # horizontal borders will be 1 overriding 3
1200 vertical_borders => undef # vertical borders will be 3 as it will fallback to 'border'
1202 =item B<vertical_borders> - Width of vertical border lines. Overrides 'border' value.
1204 B<Value:> Color specifier as 'name' or 'HEX'
1207 border_color => 'red'
1209 =item B<font> - instance of PDF::API2::Resource::Font defining the fontf to be used in the table
1211 B<Value:> can be any PDF::API2::Resource::* type of font
1212 B<Default:> 'Times' with UTF8 encoding
1214 font => $pdf->corefont("Helvetica", -encoding => "utf8")
1216 =item B<font_size> - Default size of the font that will be used across the table
1218 B<Value:> can be any positive number
1223 =item B<font_color> - Font color for all rows
1225 =item B<font_color_odd> - Font color for odd rows
1227 =item B<font_color_even> - Font color for even rows
1229 =item B<font_underline> - Font underline of the header row
1231 B<Value:> 'auto', integer of distance, or arrayref of distance & thickness (more than one pair will provide mlultiple underlines. Negative distance gives strike-through.
1234 =item B<background_color_odd> - Background color for odd rows
1236 =item B<background_color_even> - Background color for even rows
1238 B<Value:> Color specifier as 'name' or 'HEX'
1239 B<Default:> 'black' font on 'white' background
1241 font_color => '#333333'
1242 font_color_odd => 'purple'
1243 font_color_even => '#00FF00'
1244 background_color_odd => 'gray'
1245 background_color_even => 'lightblue'
1247 =item B<row_height> - Desired row height but it will be honored only if row_height > font_size + padding_top + padding_bottom
1249 B<Value:> can be any whole positive number
1250 B<Default:> font_size + padding_top + padding_bottom
1254 =item B<new_page_func> - CODE reference to a function that returns a PDF::API2::Page instance.
1256 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.
1257 For example you can use it to put Page Title, Page Frame, Page Numbers and other staff that you need.
1258 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.
1259 Don't forget that your function must return a page object created with PDF::API2 page() method.
1261 new_page_func => $code_ref
1263 =item B<header_props> - HASH reference to specific settings for the Header row of the table. See section L</Header Row Properties> below
1265 header_props => $hdr_props
1267 =item B<column_props> - HASH reference to specific settings for each column of the table. See section L</Column Properties> below
1269 column_props => $col_props
1271 =item B<cell_props> - HASH reference to specific settings for each column of the table. See section L</Cell Properties> below
1273 cell_props => $cel_props
1275 =item B<cell_render_hook> - CODE reference to a function called with the current cell coordinates. If used the parameter 'cell_render_hook' must be a function reference. It is most useful for creating a url link inside of a cell. The following example adds a link in the first column of each non-header row:
1277 cell_render_hook => sub {
1278 my ($page, $first_row, $row, $col, $x, $y, $w, $h) = @_;
1280 # Do nothing except for first column (and not a header row)
1281 return unless ($col == 0);
1282 return if ($first_row);
1285 my $value = $list_of_vals[$row-1];
1286 my $url = "https://${hostname}/app/${value}";
1288 my $annot = $page->annotation();
1289 $annot->url( $url, -rect => [$x, $y, $x+$w, $y+$h] );
1294 =head4 Header Row Properties
1296 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.
1297 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.
1301 =item B<font> - instance of PDF::API2::Resource::Font defining the fontf to be used in the header row
1303 B<Value:> can be any PDF::API2::Resource::* type of font
1304 B<Default:> 'font' of the table. See table parameter 'font' for more details.
1306 =item B<font_size> - Font size of the header row
1308 B<Value:> can be any positive number
1309 B<Default:> 'font_size' of the table + 2
1311 =item B<font_color> - Font color of the header row
1313 B<Value:> Color specifier as 'name' or 'HEX'
1314 B<Default:> '#000066'
1316 =item B<font_underline> - Font underline of the header row
1318 B<Value:> 'auto', integer of distance, or arrayref of distance & thickness (more than one pair will provide mlultiple underlines. Negative distance gives strike-through.
1321 =item B<bg_color> - Background color of the header row
1323 B<Value:> Color specifier as 'name' or 'HEX'
1326 =item B<repeat> - Flag showing if header row should be repeated on every new page
1328 B<Value:> 0,1 1-Yes/True, 0-No/False
1331 =item B<justify> - Alignment of text in the header row.
1333 B<Value:> One of 'left', 'right', 'center'
1334 B<Default:> Same as column alignment (or 'left' if undefined)
1338 font => $pdf->corefont("Helvetica", -encoding => "utf8"),
1340 font_color => '#004444',
1341 bg_color => 'yellow',
1348 =head4 Column Properties
1350 If the 'column_props' parameter is used, it should be an arrayref of hashrefs,
1351 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.
1352 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.
1354 Each hashref can contain any of the keys shown below:
1358 =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.
1360 B<Value:> can be any whole number satisfying 0 < min_w < w
1361 B<Default:> Auto calculated
1363 =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.
1365 B<Value:> can be any whole number satisfying 0 < max_w < w
1366 B<Default:> Auto calculated
1368 =item B<font> - instance of PDF::API2::Resource::Font defining the fontf to be used in this column
1370 B<Value:> can be any PDF::API2::Resource::* type of font
1371 B<Default:> 'font' of the table. See table parameter 'font' for more details.
1373 =item B<font_size> - Font size of this column
1375 B<Value:> can be any positive number
1376 B<Default:> 'font_size' of the table.
1378 =item B<font_color> - Font color of this column
1380 B<Value:> Color specifier as 'name' or 'HEX'
1381 B<Default:> 'font_color' of the table.
1383 =item B<font_underline> - Font underline of this cell
1385 B<Value:> 'auto', integer of distance, or arrayref of distance & thickness (more than one pair will provide mlultiple underlines. Negative distance gives strike-through.
1388 =item B<background_color> - Background color of this column
1390 B<Value:> Color specifier as 'name' or 'HEX'
1393 =item B<justify> - Alignment of text in this column
1395 B<Value:> One of 'left', 'right', 'center'
1401 {},# This is an empty hash so the next one will hold the properties for the second column from left to right.
1403 min_w => 100, # Minimum column width of 100.
1404 max_w => 150, # Maximum column width of 150 .
1405 justify => 'right', # Right text alignment
1406 font => $pdf->corefont("Helvetica", -encoding => "latin1"),
1408 font_color=> 'blue',
1409 background_color => '#FFFF00',
1416 NOTE: If 'min_w' and/or 'max_w' parameter is used in 'col_props', have in mind that it may be overridden by the calculated minimum/maximum cell witdh so that table can be created.
1417 When this happens a warning will be issued with some advises what can be done.
1418 In cases of a conflict between column formatting and odd/even row formatting, 'col_props' will override odd/even.
1420 =head4 Cell Properties
1422 If the 'cell_props' parameter is used, it should be an arrayref with arrays of hashrefs
1423 (of the same dimension as the data array) with one hashref for each cell of the table.
1425 Each hashref can contain any of the keys shown below:
1429 =item B<font> - instance of PDF::API2::Resource::Font defining the fontf to be used in this cell
1431 B<Value:> can be any PDF::API2::Resource::* type of font
1432 B<Default:> 'font' of the table. See table parameter 'font' for more details.
1434 =item B<font_size> - Font size of this cell
1436 B<Value:> can be any positive number
1437 B<Default:> 'font_size' of the table.
1439 =item B<font_color> - Font color of this cell
1441 B<Value:> Color specifier as 'name' or 'HEX'
1442 B<Default:> 'font_color' of the table.
1444 =item B<font_underline> - Font underline of this cell
1446 B<Value:> 'auto', integer of distance, or arrayref of distance & thickness (more than one pair will provide mlultiple underlines. Negative distance gives strike-through.
1449 =item B<background_color> - Background color of this cell
1451 B<Value:> Color specifier as 'name' or 'HEX'
1454 =item B<justify> - Alignment of text in this cell
1456 B<Value:> One of 'left', 'right', 'center'
1462 [ #This array is for the first row. If header_props is defined it will overwrite these settings.
1464 background_color => '#AAAA00',
1465 font_color => 'yellow',
1466 font_underline => [ 2, 2 ],
1473 background_color => '#CCCC00',
1474 font_color => 'blue',
1477 background_color => '#BBBB00',
1478 font_color => 'red',
1487 my $cell_props = [];
1488 $cell_props->[1][0] = {
1490 background_color => '#CCCC00',
1491 font_color => 'blue',
1496 NOTE: In case of a conflict between column, odd/even and cell formatting, cell formatting will overwrite the other two.
1497 In case of a conflict between header row and cell formatting, header formatting will override cell.
1501 my ($width_of_last_line, $ypos_of_last_line, $left_over_text) = text_block( $txt, $data, %settings)
1507 Utility method to create a block of text. The block may contain multiple paragraphs.
1508 It is mainly used internaly but you can use it from outside for placing formatted text anywhere on the sheet.
1510 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.
1511 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.
1515 $txt - a PDF::API2::Page::Text instance representing the text tool
1516 $data - a string that will be placed inside the block
1517 %settings - HASH with geometry and formatting parameters.
1521 The return value is a 3 items list where
1523 $width_of_last_line - Width of last line in the block
1524 $final_y - The Y coordinate of the block bottom so that additional content can be added after it
1525 $left_over_text - Text that was did not fit in the provided box geometry.
1530 my $page = $pdf->page;
1531 my $txt = $page->text;
1540 lead => $font_size | $distance_between_lines,
1541 align => "left|right|center|justify|fulljustify",
1542 hang => $optional_hanging_indent,
1543 Only one of the subsequent 3params can be given.
1544 They override each other.-parspace is the weightest
1545 parspace => $optional_vertical_space_before_first_paragraph,
1546 flindent => $optional_indent_of_first_line,
1547 fpindent => $optional_indent_of_first_paragraph,
1548 indent => $optional_indent_of_text_to_every_non_first_line,
1551 my ( $width_of_last_line, $final_y, $left_over_text ) = $pdftable->text_block( $txt, $data, %settings );
1565 Further development since Ver: 0.02 - Desislav Kamenov
1567 =head1 COPYRIGHT AND LICENSE
1569 Copyright (C) 2006 by Daemmon Hughes, portions Copyright 2004 Stone
1570 Environmental Inc. (www.stone-env.com) All Rights Reserved.
1572 This library is free software; you can redistribute it and/or modify
1573 it under the same terms as Perl itself, either Perl version 5.8.4 or,
1574 at your option, any later version of Perl 5 you may have available.
1580 =item by Daemmon Hughes
1582 Much of the work on this module was sponsered by
1583 Stone Environmental Inc. (www.stone-env.com).
1585 The text_block() method is a slightly modified copy of the one from
1586 Rick Measham's PDF::API2 tutorial at
1587 http://pdfapi2.sourceforge.net/cgi-bin/view/Main/YourFirstDocument
1589 =item by Desislav Kamenov (@deskata on Twitter)
1591 The development of this module was supported by SEEBURGER AG (www.seeburger.com) till year 2007
1593 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
1595 Thanks to all GitHub contributors!
1601 Hey PDF::Table is on GitHub. You are more than welcome to contribute!
1603 https://github.com/kamenov/PDF-Table