PDF::Table update auf aktuelle Version aus git
[kivitendo-erp.git] / modules / override / PDF / Table.pm
1 package PDF::Table;
2
3 use 5.006;
4 use strict;
5 use warnings;
6 use Carp;
7 our $VERSION = '0.9.10';
8
9 print __PACKAGE__.' is version: '.$VERSION.$/ if($ENV{'PDF_TABLE_DEBUG'});
10
11 ############################################################
12 #
13 # new - Constructor
14 #
15 # Parameters are meta information about the PDF
16 #
17 # $pdf = PDF::Table->new();
18 #
19 ############################################################
20
21 sub new
22 {
23     my $type = shift(@_);
24     my $class = ref($type) || $type;
25     my $self  = {};
26     bless ($self, $class);
27
28     # Pass all the rest to init for validation and initialisation
29     $self->_init(@_);
30
31     return $self;
32 }
33
34 sub _init
35 {
36     my ($self, $pdf, $page, $data, %options ) = @_;
37
38     # Check and set default values 
39     $self->set_defaults();
40
41     # Check and set mandatory params
42     $self->set_pdf($pdf);
43     $self->set_page($page);
44     $self->set_data($data);
45     $self->set_options(\%options);
46
47     return;
48 }
49
50 sub set_defaults{
51         my $self = shift;
52         
53         $self->{'font_size'} = 12;
54 }
55
56 sub set_pdf{
57     my ($self, $pdf) = @_;
58     $self->{'pdf'} = $pdf;
59 }
60
61 sub set_page{
62     my ($self, $page) = @_;
63     if ( defined($page) && ref($page) ne 'PDF::API2::Page' ){
64
65         if( ref($self->{'pdf'}) eq 'PDF::API2' ){
66             $self->{'page'} = $self->{'pdf'}->page();
67         } else {
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!'.$/;
70         }
71         return;
72     }
73     $self->{'page'} = $page;
74
75 }
76
77 sub set_data{
78     my ($self, $data) = @_;
79     #TODO: implement
80 }
81
82 sub set_options{
83     my ($self, $options) = @_;
84     #TODO: implement
85 }
86
87 ############################################################
88 #
89 # text_block - utility method to build multi-paragraph blocks of text
90 #
91 ############################################################
92
93 sub text_block
94 {
95     my $self        = shift;
96     my $text_object = shift;
97     my $text        = shift;    # The text to be displayed
98     my %arg         = @_;       # Additional Arguments
99
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
104
105     # Try to provide backward compatibility
106     foreach my $key (keys %arg)
107     {
108         my $newkey = $key;
109         if($newkey =~ s#^-##)
110         {
111             $arg{$newkey} = $arg{$key};
112             delete $arg{$key};
113         }
114     }
115     #####
116
117     #---
118     # Lets check mandatory parameters with no default values
119     #---
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 )
130     {
131         carp "Warning: No input text found. Trying to add dummy '-' and not to break everything.\n";
132         $text = '-';
133     }
134
135     # Strip any <CR> and Split the text into paragraphs
136     $text =~ s/\r//g;
137     my @paragraphs  = split(/\n/, $text);
138
139     # Width between lines in pixels
140     my $line_space = defined $arg{'lead'} && $arg{'lead'} > 0 ? $arg{'lead'} : 12;
141
142     # Calculate width of all words
143     my $space_width = $text_object->advancewidth("\x20");
144     my @words = split(/\s+/, $text);
145     foreach (@words) 
146     {
147         next if exists $width{$_};
148         $width{$_} = $text_object->advancewidth($_);
149     }
150
151     my @paragraph = split(' ', shift(@paragraphs));
152     my $first_line = 1;
153     my $first_paragraph = 1;
154
155     # Little Init
156     $xpos = $xbase;
157     $ypos = $ybase;
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 ) 
162     {
163         # Is there any text to render ?
164         unless (@paragraph) 
165         {
166             # Finish if nothing left
167             last unless scalar @paragraphs;
168             # Else take one line from the text
169             @paragraph = split(' ', shift( @paragraphs ) );
170
171             $ypos -= $arg{'parspace'} if $arg{'parspace'};
172             last unless $ypos >= $bottom_border;
173         }
174         $ypos -= $line_space;
175         $xpos = $xbase;
176
177         # While there's room on the line, add another word
178         @line = ();
179         $line_width = 0;
180         if( $first_line && exists $arg{'hang'} ) 
181         {
182             my $hang_width = $text_object->advancewidth($arg{'hang'});
183     
184             $text_object->translate( $xpos, $ypos );
185             $text_object->text( $arg{'hang'} );
186     
187             $xpos         += $hang_width;
188             $line_width   += $hang_width;
189             $arg{'indent'} += $hang_width if $first_paragraph;
190         }
191         elsif( $first_line && exists $arg{'flindent'} && $arg{'flindent'} > 0 ) 
192         {
193             $xpos += $arg{'flindent'};
194             $line_width += $arg{'flindent'};
195         }
196         elsif( $first_paragraph && exists $arg{'fpindent'} && $arg{'fpindent'} > 0 ) 
197         {
198             $xpos += $arg{'fpindent'};
199             $line_width += $arg{'fpindent'};
200         }
201         elsif (exists $arg{'indent'} && $arg{'indent'} > 0 ) 
202         {
203             $xpos += $arg{'indent'};
204             $line_width += $arg{'indent'};
205         }
206     
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 ) 
210         {
211             push(@line, shift(@paragraph));
212         }
213         $line_width += $text_object->advancewidth(join('', @line));
214             
215         # calculate the space width
216         if( $arg{'align'} eq 'fulljustify' or ($arg{'align'} eq 'justify' and @paragraph)) 
217         {
218             @line = split(//,$line[0]) if (scalar(@line) == 1) ;
219             $wordspace = ($width - $line_width) / (scalar(@line) - 1);
220             $align='justify';
221         } 
222         else 
223         {
224             $align=($arg{'align'} eq 'justify') ? 'left' : $arg{'align'};
225             $wordspace = $space_width;
226         }
227         $line_width += $wordspace * (scalar(@line) - 1);
228     
229         if( $align eq 'justify') 
230         {
231             foreach my $word (@line) 
232             {
233                 $text_object->translate( $xpos, $ypos );
234                 $text_object->text( $word );
235                 $xpos += ($width{$word} + $wordspace) if (@line);
236             }
237             $endw = $width;
238         } 
239         else 
240         {
241             # calculate the left hand position of the line
242             if( $align eq 'right' ) 
243             {
244                 $xpos += $width - $line_width;
245             } 
246             elsif( $align eq 'center' ) 
247             {
248                 $xpos += ( $width / 2 ) - ( $line_width / 2 );
249             }
250     
251             # render the line
252             $text_object->translate( $xpos, $ypos );
253             $endw = $text_object->text( join("\x20", @line));
254         }
255         $first_line = 0;
256     }#End of while(
257     unshift(@paragraphs, join(' ',@paragraph)) if scalar(@paragraph);
258     return ($endw, $ypos, join("\n", @paragraphs))
259 }
260
261
262 ################################################################
263 # table - utility method to build multi-row, multicolumn tables
264 ################################################################
265 sub table
266 {
267     my $self    = shift;
268     my $pdf     = shift;
269     my $page    = shift;
270     my $data    = shift;
271     my %arg     = @_;
272
273     #=====================================
274     # Mandatory Arguments Section
275     #=====================================
276     unless($pdf and $page and $data)
277     {
278         carp "Error: Mandatory parameter is missing pdf/page/data object!\n";
279         return;
280     }
281
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));
287
288     # Validate settings key
289     my %valid_settings_key = (
290         x                     => 1,
291         w                     => 1,
292         start_y               => 1,
293         start_h               => 1,
294         next_y                => 1,
295         next_h                => 1,
296         lead                  => 1,
297         padding               => 1,
298         padding_right         => 1,
299         padding_left          => 1,
300         padding_top           => 1,
301         padding_bottom        => 1,
302         background_color      => 1,
303         background_color_odd  => 1,
304         background_color_even => 1,
305         border                => 1,
306         border_color          => 1,
307         horizontal_borders    => 1,
308         vertical_borders      => 1,
309         font                  => 1,
310         font_size             => 1,
311         font_color            => 1,
312         font_color_even       => 1,
313         background_color_odd  => 1,
314         background_color_even => 1,
315         row_height            => 1,
316         new_page_func         => 1,
317         header_props          => 1,
318         column_props          => 1,
319         cell_props            => 1,
320         max_word_length       => 1,
321     );
322     foreach my $key (keys %arg) {
323         croak "Error: Invalid setting key '$key' received." 
324             unless (exists $valid_settings_key{$key});
325     }
326
327     # Try to provide backward compatibility
328     foreach my $key (keys %arg)
329     {
330         my $newkey = $key;
331         if($newkey =~ s#^-##)
332         {
333             $arg{$newkey} = $arg{$key};
334             delete $arg{$key};
335         }
336     }
337     
338     ######
339     #TODO: Add code for header props compatibility and col_props comp....
340     ######
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;
347
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; }
353
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;
357
358     # Create Text Object
359     my $txt     = $page->text;
360
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;
365
366     #=====================================
367     # Table Header Section
368     #=====================================
369     # Disable header row into the table
370     my $header_props = undef;
371
372     # Check if the user enabled it ?
373     if(defined $arg{'header_props'} and ref( $arg{'header_props'}) eq 'HASH')
374     {
375         # Transfer the reference to local variable
376         $header_props = $arg{'header_props'};
377
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'       };
385     }
386
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'}
399         : $line_w;
400     my $vert_borders  = defined $arg{'vertical_borders'}
401         ? $arg{'vertical_borders'}
402         : $line_w;
403     
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';
409
410     my $min_row_h   = $fnt_size + $pad_top + $pad_bot;
411     my $row_h       = defined ($arg{'row_height'}) 
412                                 && 
413                     ($arg{'row_height'} > $min_row_h) 
414                                 ? 
415                      $arg{'row_height'} : $min_row_h;
416
417     my $pg_cnt      = 1;
418     my $cur_y       = $ybase;
419     my $cell_props  = $arg{cell_props} || [];   # per cell properties
420
421     #If there is no valid data array reference warn and return!
422     if(ref $data ne 'ARRAY')
423     {
424         carp "Passed table data is not an ARRAY reference. It's actually a ref to ".ref($data);
425         return ($page,0,$cur_y);
426     }
427
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
431
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'} || [];
435
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 = [];
441  
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 );
445
446     my $word_widths  = {};
447     my $rows_height  = [];
448     my $first_row    = 1;
449
450     for( my $row_idx = 0; $row_idx < scalar(@$data) ; $row_idx++ )
451     {
452         my $column_widths = []; #holds the width of each column
453         # Init the height for this row
454         $rows_height->[$row_idx] = 0;
455         
456         for( my $column_idx = 0; $column_idx < scalar(@{$data->[$row_idx]}) ; $column_idx++ )
457         {
458             # look for font information for this column
459             my ($cell_font, $cell_font_size);
460             
461             if( !$row_idx and ref $header_props )
462             {   
463                 $cell_font      = $header_props->{'font'};
464                 $cell_font_size = $header_props->{'font_size'};
465             }
466             
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'}
470                             ||  $fnt_name;
471                               
472             $cell_font_size ||= $cell_props->[$row_idx][$column_idx]->{'font_size'}
473                             ||  $col_props->[$column_idx]->{'font_size'}
474                             ||  $fnt_size;
475                               
476             # Set Font
477             $txt->font( $cell_font, $cell_font_size ); 
478             
479             # Set row height to biggest font size from row's cells
480             if( $cell_font_size  > $rows_height->[$row_idx] )
481             {   
482                 $rows_height->[$row_idx] = $cell_font_size;
483             }
484
485             # This should fix a bug with very long words like serial numbers etc.
486             if( $max_word_len > 0 )
487             {
488                 $data->[$row_idx][$column_idx] =~ s#(\S{$max_word_len})(?=\S)#$1 #g;
489             }
490
491             # Init cell size limits
492             $space_w                      = $txt->advancewidth( "\x20" );
493             $column_widths->[$column_idx] = 0;
494             $max_col_w                    = 0;
495             $min_col_w                    = 0;
496
497             my @words = split( /\s+/, $data->[$row_idx][$column_idx] );
498
499             foreach( @words ) 
500             {
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;
504                 }
505                 
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->{$_};
509             }
510             
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;
514
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;
518
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 ;
522             }
523             
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 ;
527             }
528         }#End of for(my $column_idx....
529         
530         $row_col_widths->[$row_idx] = $column_widths;
531         
532         # Copy the calculated row properties of header row. 
533         @$header_row_props = @$column_widths if(!$row_idx and ref $header_props);
534     }
535
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 );
539
540     # Lets draw what we have!
541     my $row_index    = 0;
542     # Store header row height for later use if headers have to be repeated
543     my $header_row_height = $rows_height->[0];
544
545     my ( $gfx, $gfx_bg, $background_color, $font_color, $bot_marg, $table_top_y, $text_start);
546
547     # Each iteration adds a new page as neccessary
548     while(scalar(@{$data}))
549     {
550         my ($page_header, $columns_number);
551
552         if($pg_cnt == 1)
553         {
554             $table_top_y = $ybase;
555             $bot_marg = $table_top_y - $height;
556         }
557         else
558         {
559             if(ref $arg{'new_page_func'})
560             {   
561                 $page = &{$arg{'new_page_func'}};   
562             }
563             else
564             {   
565                 $page = $pdf->page; 
566             }
567     
568             $table_top_y = $next_y;
569             $bot_marg = $table_top_y - $next_h;
570
571             if( ref $header_props and $header_props->{'repeat'})
572             {
573                 # Copy Header Data
574                 @$page_header = @$header_row;
575                 my $hrp ;
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;
581
582                 $first_row = 1; # Means YES
583                 $row_index--; # Rollback the row_index because a new header row has been added
584             }
585         }
586
587         # Check for safety reasons
588         if( $bot_marg < 0 )
589         {   # This warning should remain i think
590             carp "!!! Warning: !!! Incorrect Table Geometry! Setting bottom margin to end of sheet!\n";
591             $bot_marg = 0;
592         }
593
594         $gfx_bg = $page->gfx;
595         $txt = $page->text;
596         $txt->font($fnt_name, $fnt_size); 
597
598         $cur_y = $table_top_y;
599
600         if ($line_w)
601         {
602             $gfx = $page->gfx;
603             $gfx->strokecolor($border_color);
604             $gfx->linewidth($line_w);
605
606             # Draw the top line
607             if ($horiz_borders) 
608             {
609                 $gfx->move( $xbase , $cur_y );
610                 $gfx->hline($xbase + $width );
611             }
612         }
613         else
614         {
615             $gfx = undef;
616         }
617
618         # Each iteration adds a row to the current page until the page is full 
619         #  or there are no more rows to add
620         # Row_Loop
621         while(scalar(@{$data}) and $cur_y-$row_h > $bot_marg)
622         {
623             # Remove the next item from $data
624             my $record = shift @{$data};
625             
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);
629
630             # Get the next set of row related settings
631             # Row Height
632             my $pre_calculated_row_height = shift @$rows_height;
633
634             # Row cell widths
635             my $record_widths = shift @$row_col_widths;
636
637             # Row coloumn props - TODO in another commit
638
639             # Row cell props - TODO in another commit
640
641             # Added to resolve infite loop bug with returned undef values
642             for(my $d = 0; $d < scalar(@{$record}) ; $d++)
643             { 
644                 $record->[$d] = '-' unless( defined $record->[$d]); 
645             }
646
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;
650
651             #Determine current row height
652             my $current_row_height = $pad_top + $pre_calculated_row_height + $pad_bot;
653
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;
659             }
660
661             # Define the font y base position for this line.
662             $text_start      = $cur_y - ($current_row_height - $pad_bot);
663
664             my $cur_x        = $xbase;
665             my $leftovers    = undef;   # Reference to text that is returned from textblock()
666             my $do_leftovers = 0;
667
668             # Process every cell(column) from current row
669             for( my $column_idx = 0; $column_idx < scalar( @$record); $column_idx++ ) 
670             {
671                 next unless $col_props->[$column_idx]->{'max_w'};
672                 next unless $col_props->[$column_idx]->{'min_w'};  
673                 $leftovers->[$column_idx] = undef;
674
675                 # look for font information for this cell
676                 my ($cell_font, $cell_font_size, $cell_font_color, $justify);
677                                     
678                 if( $first_row and ref $header_props)
679                 {   
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'};
684                 }
685                 
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'}
689                                  ||  $fnt_name;
690                                   
691                 $cell_font_size  ||= $cell_props->[$row_index][$column_idx]->{'font_size'}
692                                  ||  $col_props->[$column_idx]->{'font_size'}
693                                  ||  $fnt_size;
694                                   
695                 $cell_font_color ||= $cell_props->[$row_index][$column_idx]->{'font_color'}
696                                  ||  $col_props->[$column_idx]->{'font_color'}
697                                  ||  $font_color;
698                                 
699                 $justify         ||= $cell_props->[$row_index][$column_idx]->{'justify'}
700                                  ||  $col_props->[$column_idx]->{'justify'}
701                                  ||  $arg{'justify'}
702                                  ||  'left';                                    
703                 
704                 # Init cell font object
705                 $txt->font( $cell_font, $cell_font_size );
706                 $txt->fillcolor($cell_font_color);
707  
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]
712                 ){
713                     my $space = $pad_left;
714                     if ($justify eq 'right')
715                     {
716                         $space = $calc_column_widths->[$column_idx] -($txt->advancewidth($record->[$column_idx]) + $pad_right);
717                     }
718                     elsif ($justify eq 'center')
719                     {
720                         $space = ($calc_column_widths->[$column_idx] - $txt->advancewidth($record->[$column_idx])) / 2;
721                     }
722                     $txt->translate( $cur_x + $space, $text_start );
723                     $txt->text( $record->[$column_idx] );
724                 }
725                 # Otherwise just use the $page->text() method
726                 else
727                 {
728                     my ($width_of_last_line, $ypos_of_last_line, $left_over_text) = $self->text_block(
729                         $txt,
730                         $record->[$column_idx],
731                         x        => $cur_x + $pad_left,
732                         y        => $text_start,
733                         w        => $calc_column_widths->[$column_idx] - $pad_left - $pad_right,
734                         h        => $cur_y - $bot_marg - $pad_top - $pad_bot,
735                         align    => $justify,
736                         lead     => $lead
737                     );
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 )
741                     {
742                         $current_row_height = $current_cell_height;
743                     }
744                     
745                     if( $left_over_text )
746                     {
747                         $leftovers->[$column_idx] = $left_over_text;
748                         $do_leftovers = 1;
749                     }
750                 }
751                 $cur_x += $calc_column_widths->[$column_idx];
752             }
753             if( $do_leftovers )
754             {
755                 unshift @$data, $leftovers;
756                 unshift @$row_col_widths, $record_widths;
757                 unshift @$rows_height, $pre_calculated_row_height;
758             }
759             
760             # Draw cell bgcolor
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
763             $cur_x = $xbase;
764             for(my $column_idx = 0 ; $column_idx < scalar(@$record) ; $column_idx++)
765             {
766                 my $cell_bg_color;
767                                     
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'};
771                 }
772                 
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;
777
778                 if ($cell_bg_color)
779                 {
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);
782                     $gfx_bg->fill();
783                 }
784                 $cur_x += $calc_column_widths->[$column_idx];
785             }#End of for(my $column_idx....
786
787             $cur_y -= $current_row_height;
788             if ($gfx && $horiz_borders)
789             {
790                 $gfx->move(  $xbase , $cur_y );
791                 $gfx->hline( $xbase + $width );
792             }
793
794             $row_index++ unless ( $do_leftovers );
795             $first_row = 0;
796         }# End of Row_Loop
797
798         if ($gfx)
799         {
800             # Draw vertical lines
801             if ($vert_borders) 
802             {
803                 $gfx->move(  $xbase, $table_top_y);
804                 $gfx->vline( $cur_y );
805                 my $cur_x = $xbase;
806                 for( my $j = 0; $j < $columns_number; $j++ )
807                 {
808                     $cur_x += $calc_column_widths->[$j];
809                     $gfx->move(  $cur_x, $table_top_y );
810                     $gfx->vline( $cur_y );
811                 }
812             }
813
814             # ACTUALLY draw all the lines
815             $gfx->fillcolor( $border_color);
816             $gfx->stroke;
817         }
818         $pg_cnt++;
819     }# End of while(scalar(@{$data}))
820
821     return ($page,--$pg_cnt,$cur_y);
822 }
823
824
825 # calculate the column widths
826 sub CalcColumnWidths
827 {
828     my $col_props   = shift;
829     my $avail_width = shift;
830     my $min_width   = 0;
831
832     my $calc_widths ;
833
834     for(my $j = 0; $j < scalar( @$col_props); $j++)
835     {
836         $min_width += $col_props->[$j]->{min_w} || 0;
837     }
838
839     # I think this is the optimal variant when good view can be guaranateed
840     if($avail_width < $min_width)
841     {
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;
853
854     }
855
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++ )
858     {
859         $calc_widths->[$j] = $col_props->[$j]->{min_w} || 0;;
860     }
861
862     # Allow columns to expand to max_w before applying extra space equally.
863     my $is_last_iter;
864     for (;;)
865     {
866         my $span = ($avail_width - $min_width) / scalar( @$col_props);
867         last if $span <= 0;
868
869         $min_width = 0;
870         my $next_will_be_last_iter = 1;
871         for(my $j = 0; $j < scalar(@$col_props); $j++ )
872         {
873             my $new_w = $calc_widths->[$j] + $span;
874
875             if (!$is_last_iter && $new_w > $col_props->[$j]->{max_w})
876             {
877                 $new_w = $col_props->[$j]->{max_w}
878             }
879             if ($calc_widths->[$j] != $new_w )
880             {
881                 $calc_widths->[$j] = $new_w;
882                 $next_will_be_last_iter = 0;
883             }
884             $min_width += $new_w;
885         }
886         last if $is_last_iter;
887         $is_last_iter = $next_will_be_last_iter;
888     }
889
890     return ($calc_widths,$avail_width);
891 }
892 1;
893
894 __END__
895
896 =pod
897
898 =head1 NAME
899
900 PDF::Table - A utility class for building table layouts in a PDF::API2 object.
901
902 =head1 SYNOPSIS
903
904  use PDF::API2;
905  use PDF::Table;
906
907  my $pdftable = new PDF::Table;
908  my $pdf = new PDF::API2(-file => "table_of_lorem.pdf");
909  my $page = $pdf->page;
910
911  # some data to layout
912  my $some_data =[
913     ["1 Lorem ipsum dolor",
914     "Donec odio neque, faucibus vel",
915     "consequat quis, tincidunt vel, felis."],
916     ["Nulla euismod sem eget neque.",
917     "Donec odio neque",
918     "Sed eu velit."],
919     #... and so on
920  ];
921
922  $left_edge_of_table = 50;
923  # build the table layout
924  $pdftable->table(
925      # required params
926      $pdf,
927      $page,
928      $some_data,
929      x => $left_edge_of_table,
930      w => 495,
931      start_y => 500,
932      start_h => 300,
933      # some optional params
934      next_y  => 750,
935      next_h  => 500,
936      padding => 5,
937      padding_right => 10,
938      background_color_odd  => "gray",
939      background_color_even => "lightblue", #cell background color for even rows
940   );
941
942  # do other stuff with $pdf
943  $pdf->saveas();
944 ...
945
946 =head1 EXAMPLE
947
948 For a complete working example or initial script look into distribution`s 'examples' folder.
949
950
951 =head1 DESCRIPTION
952
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. 
959
960 See the L</METHODS> section for complete documentation of every parameter.
961
962 =head1 METHODS
963
964 =head2 new()
965
966     my $pdf_table = new PDF::Table;
967
968 =over
969
970 =item Description
971
972 Creates a new instance of the class. (to be improved)
973
974 =item Parameters
975
976 There are no parameters. 
977
978 =item Returns
979
980 Reference to the new instance
981
982 =back
983
984 =head2 table()
985
986     my ($final_page, $number_of_pages, $final_y) = table($pdf, $page, $data, %settings)
987     
988 =over
989
990 =item Description
991
992 Generates a multi-row, multi-column table into an existing PDF document based on provided data set and settings.
993
994 =item Parameters
995
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. 
1000
1001 For full %settings description see section L</Table settings> below.
1002
1003 This method will add more pages to the pdf instance as required based on the formatting options and the amount of data.
1004
1005 =item Reuturns
1006
1007 The return value is a 3 items list where 
1008
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.
1012
1013 =item Example
1014
1015     my $pdf  = new PDF::API2;
1016     my $page = $pdf->page();
1017     my $data = [
1018         ['foo1','bar1','baz1'],
1019         ['foo2','bar2','baz2']
1020     ];
1021     my %settings = (
1022         x       => 10,
1023         w       => 570,
1024         start_y => 220,
1025         start_h => 180,
1026     );
1027     
1028     my ($final_page, $number_of_pages, $final_y) = $pdftable->table( $pdf, $page, $data, %options );
1029
1030 =back
1031
1032 =head3 Table settings
1033
1034 =head4 Mandatory
1035
1036 There are some mandatory parameteres for setting table geometry and position across page(s)
1037
1038 =over 
1039
1040 =item B<x> - X coordinate of upper left corner of the table. Left edge of the sheet is 0.
1041
1042 B<Value:> can be any whole number satisfying 0 =< X < PageWidth
1043 B<Default:> No default value 
1044
1045     x => 10
1046
1047 =item B<start_y> - Y coordinate of upper left corner of the table at the initial page.
1048
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
1051
1052     start_y => 327
1053
1054 =item B<w> - width of the table starting from X.
1055
1056 B<Value:> can be any whole number satisfying 0 < w < PageWidth - x
1057 B<Default:> No default value
1058
1059     w  => 570
1060
1061 =item B<start_h> - Height of the table on the initial page
1062
1063 B<Value:> can be any whole number satisfying 0 < start_h < PageHeight - Current Y position
1064 B<Default:> No default value
1065
1066     start_h => 250
1067     
1068 =back
1069
1070 =head4 Optional
1071
1072 =over
1073
1074 =item B<next_h> - Height of the table on any additional page
1075
1076 B<Value:> can be any whole number satisfying 0 < next_h < PageHeight
1077 B<Default:> Value of param B<'start_h'>
1078
1079     next_h  => 700
1080
1081 =item B<next_y> - Y coordinate of upper left corner of the table at any additional page.
1082
1083 B<Value:> can be any whole number satisfying 0 < next_y < PageHeight
1084 B<Default:> Value of param B<'start_y'>
1085
1086     next_y  => 750
1087
1088 =item B<max_word_length> - Breaks long words (like serial numbers hashes etc.) by adding a space after every Nth symbol 
1089
1090 B<Value:> can be any whole positive number
1091 B<Default:> 20
1092
1093     max_word_length => 20    # Will add a space after every 20 symbols
1094
1095 =item B<padding> - Padding applied to every cell 
1096
1097 =item B<padding_top>    - top cell padding, overrides 'padding'
1098
1099 =item B<padding_right>  - right cell padding, overrides 'padding'
1100
1101 =item B<padding_left>   - left cell padding, overrides 'padding'
1102
1103 =item B<padding_bottom> - bottom padding, overrides 'padding'
1104
1105 B<Value:> can be any whole positive number
1106
1107 B<Default padding:> 0
1108
1109 B<Default padding_*> $padding
1110     
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'
1116
1117 =item B<border> - Width of table border lines. 
1118
1119 =item B<horizontal_borders> - Width of horizontal border lines. Overrides 'border' value.
1120
1121 =item B<vertical_borders> -  Width of vertical border lines. Overrides 'border' value.
1122
1123 B<Value:> can be any whole positive number. When set to 0 will disable border lines.
1124 B<Default:> 1
1125       
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'
1129
1130 =item B<vertical_borders> -  Width of vertical border lines. Overrides 'border' value.
1131
1132 B<Value:> Color specifier as 'name' or 'HEX'
1133 B<Default:> 'black'
1134
1135     border_color => 'red'
1136
1137 =item B<font> - instance of PDF::API2::Resource::Font defining the fontf to be used in the table
1138
1139 B<Value:> can be any PDF::API2::Resource::* type of font
1140 B<Default:> 'Times' with UTF8 encoding
1141
1142     font => $pdf->corefont("Helvetica", -encoding => "utf8")
1143
1144 =item B<font_size> - Default size of the font that will be used across the table
1145
1146 B<Value:> can be any positive number
1147 B<Default:> 12
1148     
1149     font_size => 16
1150
1151 =item B<font_color> - Font color for all rows
1152
1153 =item B<font_color_odd> - Font color for odd rows
1154
1155 =item B<font_color_even> - Font color for even rows 
1156
1157 =item B<background_color_odd> - Background color for odd rows
1158
1159 =item B<background_color_even> - Background color for even rows
1160
1161 B<Value:> Color specifier as 'name' or 'HEX'
1162 B<Default:> 'black' font on 'white' background
1163
1164     font_color            => '#333333'
1165     font_color_odd        => 'purple'
1166     font_color_even       => '#00FF00'
1167     background_color_odd  => 'gray'     
1168     background_color_even => 'lightblue'
1169
1170 =item B<row_height> - Desired row height but it will be honored only if row_height > font_size + padding_top + padding_bottom
1171
1172 B<Value:> can be any whole positive number
1173 B<Default:> font_size + padding_top + padding_bottom
1174     
1175     row_height => 24
1176  
1177 =item B<new_page_func> - CODE reference to a function that returns a PDF::API2::Page instance.
1178
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.
1183
1184     new_page_func  => $code_ref
1185     
1186 =item B<header_props> - HASH reference to specific settings for the Header row of the table. See section L</Header Row Properties> below
1187     
1188     header_props => $hdr_props
1189
1190 =item B<column_props> - HASH reference to specific settings for each column of the table. See section L</Column Properties> below
1191
1192     column_props => $col_props
1193
1194 =item B<cell_props> - HASH reference to specific settings for each column of the table. See section L</Cell Properties> below
1195     
1196     cell_props => $cel_props
1197
1198 =back
1199
1200 =head4 Header Row Properties
1201
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.
1204
1205 =over
1206
1207 =item B<font> - instance of PDF::API2::Resource::Font defining the fontf to be used in the header row
1208
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.
1211
1212 =item B<font_size> - Font size of the header row
1213
1214 B<Value:> can be any positive number
1215 B<Default:> 'font_size' of the table + 2  
1216
1217 =item B<font_color> - Font color of the header row
1218
1219 B<Value:> Color specifier as 'name' or 'HEX'
1220 B<Default:> '#000066'
1221
1222 =item B<bg_color> - Background color of the header row
1223
1224 B<Value:> Color specifier as 'name' or 'HEX'
1225 B<Default:> #FFFFAA
1226
1227 =item B<repeat> - Flag showing if header row should be repeated on every new page
1228
1229 B<Value:> 0,1   1-Yes/True, 0-No/False 
1230 B<Default:> 0
1231
1232 =item B<justify> - Alignment of text in the header row.
1233
1234 B<Value:> One of 'left', 'right', 'center'
1235 B<Default:> Same as column alignment (or 'left' if undefined)
1236
1237     my $hdr_props = 
1238     {
1239         font       => $pdf->corefont("Helvetica", -encoding => "utf8"),
1240         font_size  => 18,
1241         font_color => '#004444',
1242         bg_color   => 'yellow', 
1243         repeat     => 1,    
1244         justify    => 'center'
1245     };
1246
1247 =back
1248
1249 =head4 Column Properties
1250
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.
1254
1255 Each hashref can contain any of the keys shown below:
1256
1257 =over
1258
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.
1260
1261 B<Value:> can be any whole number satisfying 0 < min_w < w
1262 B<Default:> Auto calculated
1263
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.
1265
1266 B<Value:> can be any whole number satisfying 0 < max_w < w
1267 B<Default:> Auto calculated
1268
1269 =item B<font> - instance of PDF::API2::Resource::Font defining the fontf to be used in this column
1270
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.
1273
1274 =item B<font_size> - Font size of this column
1275
1276 B<Value:> can be any positive number
1277 B<Default:> 'font_size' of the table.
1278
1279 =item B<font_color> - Font color of this column
1280
1281 B<Value:> Color specifier as 'name' or 'HEX'
1282 B<Default:> 'font_color' of the table.
1283
1284 =item B<background_color> - Background color of this column
1285
1286 B<Value:> Color specifier as 'name' or 'HEX'
1287 B<Default:> undef
1288
1289 =item B<justify> - Alignment of text in this column
1290
1291 B<Value:> One of 'left', 'right', 'center'
1292 B<Default:> 'left'
1293
1294 Example:
1295
1296     my $col_props = [
1297         {},# This is an empty hash so the next one will hold the properties for the second column from left to right.
1298         {
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"),
1303             font_size => 10,
1304             font_color=> 'blue',
1305             background_color => '#FFFF00',
1306         },
1307         # etc.
1308     ];
1309
1310 =back
1311
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.
1315
1316 =head4 Cell Properties
1317
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.
1320
1321 Each hashref can contain any of the keys shown below:
1322
1323 =over
1324
1325 =item B<font> - instance of PDF::API2::Resource::Font defining the fontf to be used in this cell
1326
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.
1329
1330 =item B<font_size> - Font size of this cell
1331
1332 B<Value:> can be any positive number
1333 B<Default:> 'font_size' of the table.
1334
1335 =item B<font_color> - Font color of this cell
1336
1337 B<Value:> Color specifier as 'name' or 'HEX'
1338 B<Default:> 'font_color' of the table.
1339
1340 =item B<background_color> - Background color of this cell
1341
1342 B<Value:> Color specifier as 'name' or 'HEX'
1343 B<Default:> undef
1344
1345 =item B<justify> - Alignment of text in this cell
1346
1347 B<Value:> One of 'left', 'right', 'center'
1348 B<Default:> 'left'
1349
1350 Example:
1351
1352     my $cell_props = [
1353         [ #This array is for the first row. If header_props is defined it will overwrite these settings.
1354             {    #Row 1 cell 1
1355                 background_color => '#AAAA00',
1356                 font_color       => 'yellow',
1357             },
1358
1359             # etc.
1360         ],
1361         [#Row 2
1362             {    #Row 2 cell 1
1363                 background_color => '#CCCC00',
1364                 font_color       => 'blue',
1365             },
1366             {    #Row 2 cell 2
1367                 background_color => '#BBBB00',
1368                 font_color       => 'red',
1369             },
1370             # etc.
1371         ],
1372         # etc.
1373     ];
1374
1375     OR
1376     
1377     my $cell_props = [];
1378     $cell_props->[1][0] = {
1379         #Row 2 cell 1
1380         background_color => '#CCCC00',
1381         font_color       => 'blue',
1382     };
1383
1384 =back
1385     
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.
1388
1389 =head2 text_block()
1390
1391     my ($width_of_last_line, $ypos_of_last_line, $left_over_text) = text_block( $txt, $data, %settings)
1392
1393 =over
1394
1395 =item Description
1396
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.
1399
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.
1402
1403 =item Parameters
1404
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.
1408      
1409 =item Reuturns
1410
1411 The return value is a 3 items list where 
1412
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.
1416     
1417 =item Example
1418
1419     # PDF::API2 objects
1420     my $page = $pdf->page;
1421     my $txt  = $page->text;
1422
1423     my %settings = (
1424         x => 10,
1425         y => 570,
1426         w => 220,
1427         h => 180
1428         
1429         #OPTIONAL PARAMS
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,
1439     );
1440     
1441     my ( $width_of_last_line, $final_y, $left_over_text ) = $pdftable->text_block( $txt, $data, %settings );
1442  
1443 =back
1444
1445 =head1 VERSION
1446
1447 0.9.7
1448
1449 =head1 AUTHOR
1450
1451 Daemmon Hughes
1452
1453 =head1 DEVELOPMENT
1454
1455 Further development since Ver: 0.02 - Desislav Kamenov
1456
1457 =head1 COPYRIGHT AND LICENSE
1458
1459 Copyright (C) 2006 by Daemmon Hughes, portions Copyright 2004 Stone
1460 Environmental Inc. (www.stone-env.com) All Rights Reserved.
1461
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.
1465
1466 =head1 PLUGS
1467
1468 =over 
1469
1470 =item by Daemmon Hughes
1471
1472 Much of the work on this module was sponsered by
1473 Stone Environmental Inc. (www.stone-env.com).
1474
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>.
1477
1478 =item by Desislav Kamenov (@deskata on Twitter)
1479
1480 The development of this module was supported by SEEBURGER AG (www.seeburger.com) till year 2007
1481
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
1483
1484 Thanks to all GitHub contributors!
1485
1486 =back
1487
1488 =head1 CONTRIBUTION
1489
1490 Hey PDF::Table is on GitHub. You are more than welcome to contribute!
1491
1492 https://github.com/kamenov/PDF-Table
1493
1494 =head1 SEE ALSO
1495
1496 L<PDF::API2>
1497
1498 =cut
1499