This file is indexed.

/usr/share/perl5/PDF/Table.pm is in libpdf-table-perl 0.9.6003-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
package PDF::Table;

use 5.006;
use strict;
use warnings;
use Carp;
our $VERSION = '0.9.6';


############################################################
#
# new - Constructor
#
# Parameters are meta information about the PDF
#
# $pdf = PDF::Table->new();
#
############################################################

sub new
{
    my ($type) = @_;

    my $class = ref($type) || $type;
    my $self  = {};
    bless ($self, $class);
    return $self;
}

############################################################
#
# text_block - utility method to build multi-paragraph blocks of text
#
############################################################

sub text_block
{
    my $self        = shift;
    my $text_object = shift;
    my $text        = shift;    # The text to be displayed
    my %arg         = @_;       # Additional Arguments

    my  ( $align, $xpos, $ypos, $xbase, $ybase, $line_width, $wordspace, $endw , $width, $height) = 
        ( undef , undef, undef, undef , undef , undef      , undef     , undef , undef , undef  );
    my @line        = ();       # Temp data array with words on one line 
    my %width       = ();       # The width of every unique word in the givven text

    # Try to provide backward compatibility
    foreach my $key (keys %arg)
    {
        my $newkey = $key;
        if($newkey =~ s#^-##)
        {
            $arg{$newkey} = $arg{$key};
            delete $arg{$key};
        }
    }
    #####

    #---
    # Lets check mandatory parameters with no default values
    #---
    $xbase  = $arg{'x'} || -1;
    $ybase  = $arg{'y'} || -1;
    $width  = $arg{'w'} || -1;
    $height = $arg{'h'} || -1;
    unless( $xbase  > 0 ){ carp "Error: Left Edge of Block is NOT defined!\n";  return; }
    unless( $ybase  > 0 ){ carp "Error: Base Line of Block is NOT defined!\n"; return; }
    unless( $width  > 0 ){ carp "Error: Width of Block is NOT defined!\n";  return; }
    unless( $height > 0 ){ carp "Error: Height of Block is NOT defined!\n"; return; }
    # Check if any text to display
    unless( defined( $text) and length($text) > 0 )
    {
        carp "Warning: No input text found. Trying to add dummy '-' and not to break everything.\n";
        $text = '-';
    }

    # Strip any <CR> and Split the text into paragraphs
    $text =~ s/\r//g;
    my @paragraphs  = split(/\n/, $text);

    # Width between lines in pixels
    my $line_space = defined $arg{'lead'} && $arg{'lead'} > 0 ? $arg{'lead'} : 12;

    # Calculate width of all words
    my $space_width = $text_object->advancewidth("\x20");
    my @words = split(/\s+/, $text);
    foreach (@words) 
    {
        next if exists $width{$_};
        $width{$_} = $text_object->advancewidth($_);
    }

    my @paragraph = split(' ', shift(@paragraphs));
    my $first_line = 1;
    my $first_paragraph = 1;

    # Little Init
    $xpos = $xbase;
    $ypos = $ybase;
    $ypos = $ybase + $line_space;
    my $bottom_border = $ypos - $height; 
    # While we can add another line
    while ( $ypos >= $bottom_border + $line_space ) 
    {
        # Is there any text to render ?
        unless (@paragraph) 
        {
            # Finish if nothing left
            last unless scalar @paragraphs;
            # Else take one line from the text
            @paragraph = split(' ', shift( @paragraphs ) );

            $ypos -= $arg{'parspace'} if $arg{'parspace'};
            last unless $ypos >= $bottom_border;
        }
        $ypos -= $line_space;
        $xpos = $xbase;

        # While there's room on the line, add another word
        @line = ();
        $line_width = 0;
        if( $first_line && exists $arg{'hang'} ) 
        {
            my $hang_width = $text_object->advancewidth($arg{'hang'});
    
            $text_object->translate( $xpos, $ypos );
            $text_object->text( $arg{'hang'} );
    
            $xpos         += $hang_width;
            $line_width   += $hang_width;
            $arg{'indent'} += $hang_width if $first_paragraph;
        }
        elsif( $first_line && exists $arg{'flindent'} && $arg{'flindent'} > 0 ) 
        {
            $xpos += $arg{'flindent'};
            $line_width += $arg{'flindent'};
        }
        elsif( $first_paragraph && exists $arg{'fpindent'} && $arg{'fpindent'} > 0 ) 
        {
            $xpos += $arg{'fpindent'};
            $line_width += $arg{'fpindent'};
        }
        elsif (exists $arg{'indent'} && $arg{'indent'} > 0 ) 
        {
            $xpos += $arg{'indent'};
            $line_width += $arg{'indent'};
        }
    
        # Lets take from paragraph as many words as we can put into $width - $indent; 
        while ( @paragraph and $text_object->advancewidth( join("\x20", @line)."\x20" . $paragraph[0]) + 
                                $line_width < $width ) 
        {
            push(@line, shift(@paragraph));
        }
        $line_width += $text_object->advancewidth(join('', @line));
            
        # calculate the space width
        if( $arg{'align'} eq 'fulljustify' or ($arg{'align'} eq 'justify' and @paragraph)) 
        {
            @line = split(//,$line[0]) if (scalar(@line) == 1) ;
            $wordspace = ($width - $line_width) / (scalar(@line) - 1);
            $align='justify';
        } 
        else 
        {
            $align=($arg{'align'} eq 'justify') ? 'left' : $arg{'align'};
            $wordspace = $space_width;
        }
        $line_width += $wordspace * (scalar(@line) - 1);
    
        if( $align eq 'justify') 
        {
            foreach my $word (@line) 
            {
                $text_object->translate( $xpos, $ypos );
                $text_object->text( $word );
                $xpos += ($width{$word} + $wordspace) if (@line);
            }
            $endw = $width;
        } 
        else 
        {
            # calculate the left hand position of the line
            if( $align eq 'right' ) 
            {
                $xpos += $width - $line_width;
            } 
            elsif( $align eq 'center' ) 
            {
                $xpos += ( $width / 2 ) - ( $line_width / 2 );
            }
    
            # render the line
            $text_object->translate( $xpos, $ypos );
            $endw = $text_object->text( join("\x20", @line));
        }
        $first_line = 0;
    }#End of while(
    unshift(@paragraphs, join(' ',@paragraph)) if scalar(@paragraph);
    return ($endw, $ypos, join("\n", @paragraphs))
}


############################################################
# table - utility method to build multi-row, multicolumn tables
############################################################
sub table
    {
    my $self    = shift;
    my $pdf     = shift;
    my $page    = shift;
    my $data    = shift;
    my %arg     = @_;

    #=====================================
    # Mandatory Arguments Section
    #=====================================
    unless($pdf and $page and $data)
    {
        carp "Error: Mandatory parameter is missing pdf/page/data object!\n";
        return;
    }
    # Try to provide backward compatibility
    foreach my $key (keys %arg)
    {
        my $newkey = $key;
        if($newkey =~ s#^-##)
        {
            $arg{$newkey} = $arg{$key};
            delete $arg{$key};
        }
    }
    #TODO: Add code for header props compatibility and col_props comp....
    #####
    my ( $xbase, $ybase, $width, $height ) = ( undef, undef, undef, undef );
    # Could be 'int' or 'real' values
    $xbase  = $arg{'x'      } || -1;    
    $ybase  = $arg{'start_y'} || -1;
    $width  = $arg{'w'      } || -1;
    $height = $arg{'start_h'} || -1;

    # Global geometry parameters are also mandatory. 
    unless( $xbase  > 0 ){ carp "Error: Left Edge of Table is NOT defined!\n";  return; }
    unless( $ybase  > 0 ){ carp "Error: Base Line of Table is NOT defined!\n"; return; }
    unless( $width  > 0 ){ carp "Error: Width of Table is NOT defined!\n";  return; }
    unless( $height > 0 ){ carp "Error: Height of Table is NOT defined!\n"; return; }

    # Ensure default values for -next_y and -next_h
    my $next_y  = $arg{'next_y'} || $arg{'start_y'} || 0;
    my $next_h  = $arg{'next_h'} || $arg{'start_h'} || 0;

    # Create Text Object
    my $txt     = $page->text;
    # Set Default Properties
    my $fnt_name    = $arg{'font'            } || $pdf->corefont('Times',-encode => 'utf8');
    my $fnt_size    = $arg{'font_size'       } || 12;
    my $max_word_len= $arg{'max_word_length' } || 20;

    #=====================================
    # Table Header Section
    #=====================================
    # Disable header row into the table
    my $header_props = 0;
    # Check if the user enabled it ?
    if(defined $arg{'header_props'} and ref( $arg{'header_props'}) eq 'HASH')
    {
        # Transfer the reference to local variable
        $header_props = $arg{'header_props'};
        # Check other params and put defaults if needed
        $header_props->{'repeat'        } = $header_props->{'repeat'        } || 0;
        $header_props->{'font'          } = $header_props->{'font'          } || $fnt_name;
        $header_props->{'font_color'    } = $header_props->{'font_color'    } || '#000066';
        $header_props->{'font_size'     } = $header_props->{'font_size'     } || $fnt_size + 2;
        $header_props->{'bg_color'      } = $header_props->{'bg_color'      } || '#FFFFAA';
    }
    my $header_row  = undef;
    #=====================================
    # Other Parameters check
    #=====================================
    
    my $lead          = $arg{'lead'         } || $fnt_size;
    my $pad_left      = $arg{'padding_left' } || $arg{'padding'} || 0;
    my $pad_right     = $arg{'padding_right'    } || $arg{'padding'} || 0;
    my $pad_top       = $arg{'padding_top'  } || $arg{'padding'} || 0;
    my $pad_bot       = $arg{'padding_bottom'   } || $arg{'padding'} || 0;
    my $pad_w         = $pad_left + $pad_right;
    my $pad_h         = $pad_top  + $pad_bot    ;
    my $line_w        = defined $arg{'border'} ? $arg{'border'} : 1 ;
    my $horiz_borders = defined $arg{'horizontal_borders'}
        ? $arg{'horizontal_borders'}
        : $line_w;
    my $vert_borders  = defined $arg{'vertical_borders'}
        ? $arg{'vertical_borders'}
        : $line_w;
    
    my $background_color_even   = $arg{'background_color_even'  } || $arg{'background_color'} || undef;
    my $background_color_odd    = $arg{'background_color_odd'   } || $arg{'background_color'} || undef;
    my $font_color_even         = $arg{'font_color_even'        } || $arg{'font_color'      } || 'black';
    my $font_color_odd          = $arg{'font_color_odd'         } || $arg{'font_color'      } || 'black';
    my $border_color            = $arg{'border_color'           } || 'black';

    my $min_row_h   = $fnt_size + $pad_top + $pad_bot;
    my $row_h       = defined ($arg{'row_height'}) 
                                && 
                    ($arg{'row_height'} > $min_row_h) 
                                ? 
                     $arg{'row_height'} : $min_row_h;

    my $pg_cnt      = 1;
    my $cur_y       = $ybase;
    my $cell_props  = $arg{cell_props} || [];   # per cell properties
    my $row_cnt     = ( ref $header_props and $header_props->{'repeat'} ) ?  1 : 0; # current row in user data

    #If there is valid data array reference use it!
    if(ref $data eq 'ARRAY')
    {
        # Copy the header row if header is enabled
        @$header_row = $$data[0] if defined $header_props;
        # Determine column widths based on content

        #  an arrayref whose values are a hashref holding 
        #  the minimum and maximum width of that column
        my $col_props =  $arg{'column_props'} || [];

        # An array ref of arrayrefs whose values are 
        #  the actual widths of the column/row intersection
        my $row_props = [];
        # An array ref with the widths of the header row 
        my $header_row_props = [];
 
        # Scalars that hold sum of the maximum and minimum widths of all columns 
        my ( $max_col_w  , $min_col_w   ) = ( 0,0 );
        my ( $row, $col_name, $col_fnt_size, $space_w );

        # Hash that will hold the width of every word from input text
        my $word_widths  = {};
        my $rows_counter = 0;
        my $first_row    = 1;

        foreach $row ( @{$data} )
        {
            my $column_widths = []; #holds the width of each column
            for( my $column_idx = 0; $column_idx < scalar(@$row) ; $column_idx++ )
            {
                # look for font information for this column
                my ($cell_font, $cell_font_size);
                
                if( !$rows_counter and ref $header_props )
                {   
                    $cell_font      = $header_props->{'font'};
                    $cell_font_size = $header_props->{'font_size'};
                }
                
                # Get the most specific value if none was already set from header_props
                $cell_font      ||= $cell_props->[$rows_counter][$column_idx]->{'font'} 
                                ||  $col_props->[$column_idx]->{'font'}
                                ||  $fnt_name;
                                  
                $cell_font_size ||= $cell_props->[$rows_counter][$column_idx]->{'font_size'}
                                ||  $col_props->[$column_idx]->{'font_size'}
                                ||  $fnt_size;
                                  
                # Set Font
                $txt->font( $cell_font, $cell_font_size ); 

                # This should fix a bug with very long words like serial numbers etc.
                if( $max_word_len > 0 )
                {
                    $row->[$column_idx] =~ s#(\S{$max_word_len}?)(?=\S)#$1 #g;  
                }
                
                # Init cell size limits  
                $space_w                      = $txt->advancewidth( "\x20" );
                $column_widths->[$column_idx] = 0;
                $max_col_w                    = 0;
                $min_col_w                    = 0;

                my @words = split( /\s+/, $row->[$column_idx] );

                foreach( @words ) 
                {
                    unless( exists $word_widths->{$_} )
                    {   # Calculate the width of every word and add the space width to it
                        $word_widths->{$_} = $txt->advancewidth( $_ ) + $space_w;
                    }
                    
                    $column_widths->[$column_idx] += $word_widths->{$_};
                    $min_col_w                     = $word_widths->{$_} if( $word_widths->{$_} > $min_col_w );
                    $max_col_w                    += $word_widths->{$_};
                }
                
                $min_col_w                    += $pad_w;
                $max_col_w                    += $pad_w;
                $column_widths->[$column_idx] += $pad_w;

                # Keep a running total of the overall min and max widths
                $col_props->[$column_idx]->{'min_w'} ||= 0;
                $col_props->[$column_idx]->{'max_w'} ||= 0;

                if( $min_col_w > $col_props->[$column_idx]->{'min_w'} )
                {   # Calculated Minimum Column Width is more than user-defined
                    $col_props->[$column_idx]->{'min_w'} = $min_col_w ;
                }
                
                if( $max_col_w > $col_props->[$column_idx]->{'max_w'} )
                {   # Calculated Maximum Column Width is more than user-defined
                    $col_props->[$column_idx]->{'max_w'} = $max_col_w ;
                }
            }#End of for(my $column_idx....
            
            $row_props->[$rows_counter] = $column_widths;
            
            # Copy the calculated row properties of header row. 
            @$header_row_props = @$column_widths if(!$rows_counter and ref $header_props);
            
            $rows_counter++;
        }
        # Calc real column widths and expand table width if needed.
        my $calc_column_widths; 
        ($calc_column_widths, $width) = CalcColumnWidths( $col_props, $width );

        my $comp_cnt     = 1;
        $rows_counter    = 0;

        my ( $gfx     , $gfx_bg     , $background_color , $font_color,              );
        my ( $bot_marg, $table_top_y, $text_start       , $record,  $record_widths  );

        # Each iteration adds a new page as neccessary
        while(scalar(@{$data}))
        {
            my $page_header;
            if($pg_cnt == 1)
            {
                $table_top_y = $ybase;
                $bot_marg = $table_top_y - $height;
            }
            else
            {
                if(ref $arg{'new_page_func'})
                {   
                    $page = &{$arg{'new_page_func'}};   
                }
                else
                {   
                    $page = $pdf->page; 
                }

                $table_top_y = $next_y;
                $bot_marg = $table_top_y - $next_h;

                if( ref $header_props and $header_props->{'repeat'})
                {
                    # Copy Header Data
                    @$page_header = @$header_row;
                    my $hrp ;
                    @$hrp = @$header_row_props ;
                    # Then prepend it to master data array
                    unshift @$data      ,@$page_header  ;
                    unshift @$row_props ,$hrp           ;
                    $first_row = 1; # Means YES
                }
            }

            # Check for safety reasons
            if( $bot_marg < 0 )
            {   # This warning should remain i think
                carp "!!! Warning: !!! Incorrect Table Geometry! Setting bottom margin to end of sheet!\n";
                $bot_marg = 0;
            }

            $gfx_bg = $page->gfx;
            $txt = $page->text;
            $txt->font($fnt_name, $fnt_size); 

            $cur_y = $table_top_y;

            if ($line_w)
            {
                $gfx = $page->gfx;
                $gfx->strokecolor($border_color);
                $gfx->linewidth($line_w);

                # Draw the top line
                if ($horiz_borders) 
                {
                    $gfx->move( $xbase , $cur_y );
                    $gfx->hline($xbase + $width );
                }
            }
            else
            {
                $gfx = undef;
            }

            # Each iteration adds a row to the current page until the page is full 
            #  or there are no more rows to add
            while(scalar(@{$data}) and $cur_y-$row_h > $bot_marg)
            {
                # Remove the next item from $data
                $record = shift @{$data};
                # Added to resolve infite loop bug with returned undef values
                for(my $d = 0; $d < scalar(@{$record}) ; $d++)
                { 
                    $record->[$d] = '-' unless( defined $record->[$d]); 
                }

                $record_widths = shift @$row_props;
                next unless $record;

                # Choose colors for this row
                $background_color = $rows_counter % 2 ? $background_color_even  : $background_color_odd;
                $font_color       = $rows_counter % 2 ? $font_color_even        : $font_color_odd;

                $text_start      = $cur_y - $fnt_size - $pad_top;
                my $cur_x        = $xbase;
                my $leftovers    = undef;   # Reference to text that is returned from textblock()
                my $do_leftovers = 0;

                # Process every cell(column) from current row
                for( my $column_idx = 0; $column_idx < scalar( @$record); $column_idx++ ) 
                {
                    next unless $col_props->[$column_idx]->{'max_w'};
                    next unless $col_props->[$column_idx]->{'min_w'};  
                    $leftovers->[$column_idx] = undef;

                    # look for font information for this cell
                    my ($cell_font, $cell_font_size, $cell_font_color, $justify);
                                        
                    if( $first_row and ref $header_props)
                    {   
                        $cell_font       = $header_props->{'font'};
                        $cell_font_size  = $header_props->{'font_size'};
                        $cell_font_color = $header_props->{'font_color'};
                        $justify         = $header_props->{'justify'};
                    }
                    
                    # Get the most specific value if none was already set from header_props
                    $cell_font       ||= $cell_props->[$rows_counter][$column_idx]->{'font'} 
                                     ||  $col_props->[$column_idx]->{'font'}
                                     ||  $fnt_name;
                                      
                    $cell_font_size  ||= $cell_props->[$rows_counter][$column_idx]->{'font_size'}
                                     ||  $col_props->[$column_idx]->{'font_size'}
                                     ||  $fnt_size;
                                      
                    $cell_font_color ||= $cell_props->[$rows_counter][$column_idx]->{'font_color'}
                                     ||  $col_props->[$column_idx]->{'font_color'}
                                     ||  $font_color;
                                    
                    $justify         ||= $cell_props->[$row_cnt][$column_idx]->{'justify'}
                                     ||  $col_props->[$column_idx]->{'justify'}
                                     ||  $arg{'justify'}
                                     ||  'left';                                    
                    
                    # Init cell font object
                    $txt->font( $cell_font, $cell_font_size );
                    $txt->fillcolor($cell_font_color);
 
                    # If the content is wider than the specified width, we need to add the text as a text block
                    if( $record->[$column_idx] !~ m/(.\n.)/ and
                        $record_widths->[$column_idx] and 
                        $record_widths->[$column_idx] <= $calc_column_widths->[$column_idx]
                    ){
                        my $space = $pad_left;
                        if ($justify eq 'right')
                        {
                            $space = $calc_column_widths->[$column_idx] -($txt->advancewidth($record->[$column_idx]) + $pad_right);
                        }
                        elsif ($justify eq 'center')
                        {
                            $space = ($calc_column_widths->[$column_idx] - $txt->advancewidth($record->[$column_idx])) / 2;
                        }
                        $txt->translate( $cur_x + $space, $text_start );
                        $txt->text( $record->[$column_idx] );
                    }
                    # Otherwise just use the $page->text() method
                    else
                    {
                        my ($width_of_last_line, $ypos_of_last_line, $left_over_text) = $self->text_block(
                            $txt,
                            $record->[$column_idx],
                            x        => $cur_x + $pad_left,
                            y        => $text_start,
                            w        => $calc_column_widths->[$column_idx] - $pad_w,
                            h        => $cur_y - $bot_marg - $pad_top - $pad_bot,
                            align    => $justify,
                            lead     => $lead
                        );
                        # Desi - Removed $lead because of fixed incorrect ypos bug in text_block
                        my $this_row_h = $cur_y - ( $ypos_of_last_line - $pad_bot );
                        $row_h = $this_row_h if $this_row_h > $row_h;
                        if( $left_over_text )
                        {
                            $leftovers->[$column_idx] = $left_over_text;
                            $do_leftovers = 1;
                        }
                    }
                    $cur_x += $calc_column_widths->[$column_idx];
                }
                if( $do_leftovers )
                {
                    unshift @$data, $leftovers;
                    unshift @$row_props, $record_widths;
                    $rows_counter--;
                }
                # Draw cell bgcolor
                # This has to be separately from the text loop 
                #  because we do not know the final height of the cell until all text has been drawn
                $cur_x = $xbase;
                for(my $j =0;$j < scalar(@$record);$j++)
                {
                    my $bg_color;
                    if ( $first_row && ref $header_props ){
                        $bg_color = $header_props->{'bg_color'};
                    }
                    elsif ( $cell_props->[$row_cnt][$j]->{'background_color'})
                    {
                        $bg_color = $cell_props->[$row_cnt][$j]->{'background_color'};
                    }
                    elsif( $col_props->[$j]->{'background_color'})
                    {
                        $bg_color = $col_props->[$j]->{'background_color'};
                    }
                    else
                    {
                        $bg_color = $background_color;
                    }
                    if ($bg_color)
                    {
                        $gfx_bg->rect( $cur_x, $cur_y-$row_h, $calc_column_widths->[$j], $row_h);
                        $gfx_bg->fillcolor($bg_color);
                        $gfx_bg->fill();
                    }
                    $cur_x += $calc_column_widths->[$j];
                }#End of for(my $j....

                $cur_y -= $row_h;
                $row_h  = $min_row_h;
                if ($gfx && $horiz_borders)
                {
                    $gfx->move(  $xbase , $cur_y );
                    $gfx->hline( $xbase + $width );
                }
                $rows_counter++;
                $row_cnt++ unless ( $first_row || $do_leftovers );
                $first_row = 0;
            }# End of while(scalar(@{$data}) and $cur_y-$row_h > $bot_marg)

            if ($gfx)
            {
                # Draw vertical lines
                if ($vert_borders) 
                {
                    $gfx->move(  $xbase, $table_top_y);
                    $gfx->vline( $cur_y );
                    my $cur_x = $xbase;
                    for( my $j = 0; $j < scalar(@$record); $j++ )
                    {
                        $cur_x += $calc_column_widths->[$j];
                        $gfx->move(  $cur_x, $table_top_y );
                        $gfx->vline( $cur_y );
                    }
                }

                # ACTUALLY draw all the lines
                $gfx->fillcolor( $border_color);
                $gfx->stroke;
            }
            $pg_cnt++;
        }# End of while(scalar(@{$data}))
    }# End of if(ref $data eq 'ARRAY')

    return ($page,--$pg_cnt,$cur_y);
}


# calculate the column widths
sub CalcColumnWidths
{
    my $col_props   = shift;
    my $avail_width = shift;
    my $min_width   = 0;

    my $calc_widths ;

    for(my $j = 0; $j < scalar( @$col_props); $j++)
    {
        $min_width += $col_props->[$j]->{min_w} || 0;
    }

    # I think this is the optimal variant when good view can be guaranateed
    if($avail_width < $min_width)
    {
        carp "!!! Warning !!!\n Calculated Mininal width($min_width) > Table width($avail_width).\n",
            ' Expanding table width to:',int($min_width)+1,' but this could lead to unexpected results.',"\n",
            ' Possible solutions:',"\n",
            '  0)Increase table width.',"\n",
            '  1)Decrease font size.',"\n",
            '  2)Choose a more narrow font.',"\n",
            '  3)Decrease "max_word_length" parameter.',"\n",
            '  4)Rotate page to landscape(if it is portrait).',"\n",
            '  5)Use larger paper size.',"\n",
            '!!! --------- !!!',"\n";
        $avail_width = int( $min_width) + 1;

    }

    # Calculate how much can be added to every column to fit the available width.
    for(my $j = 0; $j < scalar(@$col_props); $j++ )
    {
        $calc_widths->[$j] = $col_props->[$j]->{min_w} || 0;;
    }

    # Allow columns to expand to max_w before applying extra space equally.
    my $is_last_iter;
    for (;;)
    {
        my $span = ($avail_width - $min_width) / scalar( @$col_props);
        last if $span <= 0;

        $min_width = 0;
        my $next_will_be_last_iter = 1;
        for(my $j = 0; $j < scalar(@$col_props); $j++ )
        {
            my $new_w = $calc_widths->[$j] + $span;

            if (!$is_last_iter && $new_w > $col_props->[$j]->{max_w})
            {
                $new_w = $col_props->[$j]->{max_w}
            }
            if ($calc_widths->[$j] != $new_w )
            {
                $calc_widths->[$j] = $new_w;
                $next_will_be_last_iter = 0;
            }
            $min_width += $new_w;
        }
        last if $is_last_iter;
        $is_last_iter = $next_will_be_last_iter;
    }

    return ($calc_widths,$avail_width);
}
1;

__END__

=pod

=head1 NAME

PDF::Table - A utility class for building table layouts in a PDF::API2 object.

=head1 SYNOPSIS

 use PDF::API2;
 use PDF::Table;

 my $pdftable = new PDF::Table;
 my $pdf = new PDF::API2(-file => "table_of_lorem.pdf");
 my $page = $pdf->page;

 # some data to layout
 my $some_data =[
    ["1 Lorem ipsum dolor",
    "Donec odio neque, faucibus vel",
    "consequat quis, tincidunt vel, felis."],
    ["Nulla euismod sem eget neque.",
    "Donec odio neque",
    "Sed eu velit."],
    #... and so on
 ];

 $left_edge_of_table = 50;
 # build the table layout
 $pdftable->table(
     # required params
     $pdf,
     $page,
     $some_data,
     x => $left_edge_of_table,
     w => 495,
     start_y => 750,
     next_y  => 700,
     start_h => 300,
     next_h  => 500,
     # some optional params
     padding => 5,
     padding_right => 10,
     background_color_odd  => "gray",
     background_color_even => "lightblue", #cell background color for even rows
  );

 # do other stuff with $pdf
 $pdf->saveas();
...

=head1 EXAMPLE

For a complete working example or initial script look into distribution`s 'examples' folder.


=head1 DESCRIPTION

This class is a utility for use with the PDF::API2 module from CPAN. 
It can be used to display text data in a table layout within the PDF. 
The text data must be in a 2d array (such as returned by a DBI statement handle fetchall_arrayref() call). 
The PDF::Table will automatically add as many new pages as necessary to display all of the data. 
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. 
Also a (non)repeated header row with different layout properties can be specified. 

See the METHODS section for complete documentation of every parameter.

=head1  METHODS

=head2 new

=over

Returns an instance of the class. There are no parameters.

=back

=head2 table($pdf, $page_obj, $data, %opts)

=over

The main method of this class. 
Takes a PDF::API2 instance, a page instance, some data to build the table and formatting options. 
The formatting options should be passed as named parameters. 
This method will add more pages to the pdf instance as required based on the formatting options and the amount of data.

=back

=over

The return value is a 3 item list where 
The first item is the PDF::API2::Page instance that the table ends on,
The second item is the count of pages that the table spans, and 
The third item is the y position of the table bottom.

=back

=over

=item Example:

 ($end_page, $pages_spanned, $table_bot_y) = $pdftable->table(
     $pdf,               # A PDF::API2 instance
     $page_to_start_on,  # A PDF::API2::Page instance created with $page_to_start_on = $pdf->page(); 
     $data,              # 2D arrayref of text strings
     x  => $left_edge_of_table,    #X - coordinate of upper left corner
     w  => 570, # width of table.
     start_y => $initial_y_position_on_first_page,
     next_y  => $initial_y_position_on_every_new_page,
     start_h => $table_height_on_first_page,
     next_h  => $table_height_on_every_new_page,
     #OPTIONAL PARAMS BELOW
     max_word_length=> 20,   # add a space after every 20th symbol in long words like serial numbers
     padding        => 5,    # cell padding
     padding_top    => 10,   # top cell padding, overides padding
     padding_right  => 10,   # right cell padding, overides padding
     padding_left   => 10,   # left cell padding, overides padding
     padding_bottom => 10,   # bottom padding, overides -padding
     border         => 1,    # border width, default 1, use 0 for no border
     border_color   => 'red',# default black
     horizontal_borders => 1, # defaults to 1, use 0 for no horizontal borders
     vertical_borders   => 1, # defaults to 1, use 0 for no vertical borders
     font           => $pdf->corefont("Helvetica", -encoding => "utf8"), # default font
     font_size      => 12,
     font_color_odd => 'purple',
     font_color_even=> 'black',
     background_color_odd  => 'gray',         #cell background color for odd rows
     background_color_even => 'lightblue',     #cell background color for even rows
     new_page_func  => $code_ref,  # see section TABLE SPANNING
     header_props   => $hdr_props, # see section HEADER ROW PROPERTIES
     column_props   => $col_props, # see section COLUMN PROPERTIES
     cell_props     => $row_props, # see section CELL PROPERTIES
 )

=back

=over

=item HEADER ROW PROPERTIES

If the 'header_props' parameter is used, it should be a hashref. 
It is your choice if it will be anonymous inline hash or predefined one.
Also as you can see there is no data variable for the content because the module asumes that the 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.

=back

    $hdr_props = 
    {
        # This param could be a pdf core font or user specified TTF.
        #  See PDF::API2 FONT METHODS for more information
        font       => $pdf->corefont("Times", -encoding => "utf8"),
        font_size  => 10,
        font_color => '#006666',
        bg_color   => 'yellow',
        repeat     => 1,    # 1/0 eq On/Off  if the header row should be repeated to every new page
    };

=over

=item COLUMN PROPERTIES

If the 'column_props' parameter is used, it should be an arrayref of hashrefs, 
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. 
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.

Each hashref can contain any of the keys shown below:

=back

  $col_props = [
    {},# This is an empty hash so the next one will hold the properties for the second row from left to right.
    {
        min_w => 100,       # Minimum column width.
        max_w => 150,       # Maximum column width.
        justify => 'right', # One of left|center|right ,
        font => $pdf->corefont("Times", -encoding => "latin1"),
        font_size => 10,
        font_color=> 'blue',
        background_color => '#FFFF00',
    },
    # etc.
  ];

=over

If the 'min_w' parameter is used for 'col_props', have in mind that it can be overwritten 
by the calculated minimum cell witdh if the userdefined value is less that calculated.
This is done for safety reasons. 
In cases of a conflict between column formatting and odd/even row formatting, 
the former will override the latter.

=back

=over

=item CELL PROPERTIES

If the 'cell_props' parameter is used, it should be an arrayref with arrays of hashrefs
(of the same dimension as the data array) with one hashref for each cell of the table.
Each hashref can contain any of keys shown here:

=back

  $cell_props = [
    [ #This array is for the first row. If header_props is defined it will overwrite this settings.
      {#Row 1 cell 1
        background_color => '#AAAA00',
        font_color       => 'blue',
      },
      # etc.
    ],
    [ #Row 2
      {#Row 2 cell 1
        background_color => '#CCCC00',
        font_color       => 'blue',
      },
      {#Row 2 cell 2
        background_color => '#CCCC00',
        font_color       => 'blue',
      },
      # etc.
    ],
    # etc.
  ];

=over

In case of a conflict between column, odd/even and cell formating, cell formating will overwrite the other two.
In case of a conflict between header row cell formating, header formating will win.

=back

=over



=item TABLE SPANNING    

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.
For example you can use it to put Page Title, Page Frame, Page Numbers and other staff that you need.
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.
Don't forget that your function must return a page object created with PDF::API2 page() method.

=back

=head2 text_block( $txtobj, $string, x => $x, y => $y, w => $width, h => $height)

=over

Utility method to create a block of text. The block may contain multiple paragraphs.
It is mainly used internaly but you can use it from outside for placing formated text anywhere on the sheet.

=back

=over

=item Example:

=back

=over

 # PDF::API2 objects
 my $page = $pdf->page;
 my $txt = $page->text;

=back

=over

 ($width_of_last_line, $ypos_of_last_line, $left_over_text) = $pdftable->text_block(
    $txt,
    $text_to_place,
    #X,Y - coordinates of upper left corner
    x        => $left_edge_of_block,
    y        => $y_position_of_first_line,
    w        => $width_of_block,
    h        => $height_of_block,
    #OPTIONAL PARAMS
    lead     => $font_size | $distance_between_lines,
    align    => "left|right|center|justify|fulljustify",
    hang     => $optional_hanging_indent,
    Only one of the subsequent 3params can be given. 
    They override each other.-parspace is the weightest
    parspace => $optional_vertical_space_before_first_paragraph,
    flindent => $optional_indent_of_first_line,
    fpindent => $optional_indent_of_first_paragraph,

    indent   => $optional_indent_of_text_to_every_non_first_line,
 );


=back

=head1 AUTHOR

Daemmon Hughes

=head1 DEVELOPMENT

ALL IMPROVEMENTS and BUGS Since Ver: 0.02

Desislav Kamenov

=head1 VERSION

0.9.6

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2006 by Daemmon Hughes, portions Copyright 2004 Stone
Environmental Inc. (www.stone-env.com) All Rights Reserved.

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.4 or,
at your option, any later version of Perl 5 you may have available.

=head1 PLUGS

by Daemmon Hughes

Much of the work on this module was sponsered by
Stone Environmental Inc. (www.stone-env.com).

The text_block() method is a slightly modified copy of the one from
Rick Measham's PDF::API2 tutorial at
http://pdfapi2.sourceforge.net/cgi-bin/view/Main/YourFirstDocument

by Desislav Kamenov

The development of this module was sponsored by SEEBURGER AG (www.seeburger.com) till 2007 year

Thanks to my friends Krasimir Berov and Alex Kantchev for helpful tips and QA during development.

=head1 CONTRIBUTION

Hey PDF::Table is on GitHub. We'd be happy to join us there.

https://github.com/kamenov/PDF-Table

=head1 SEE ALSO

L<PDF::API2>

=cut