The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

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

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 => 500,
     start_h => 300,
     # some optional params
     next_y  => 750,
     next_h  => 500,
     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();
...

EXAMPLE

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

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 a 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.

METHODS

new()

    my $pdf_table = new PDF::Table;
Description

Creates a new instance of the class. (to be improved)

Parameters

There are no parameters.

Returns

Reference to the new instance

table()

    my ($final_page, $number_of_pages, $final_y) = table($pdf, $page, $data, %settings)
    
Description

Generates a multi-row, multi-column table into an existing PDF document based on provided data set and settings.

Parameters
    $pdf      - a PDF::API2 instance representing the document being created
    $page     - a PDF::API2::Page instance representing the current page of the document
    $data     - an ARRAY reference to a 2D data structure that will be used to build the table
    %settings - HASH with geometry and formatting parameters. 

For full %settings description see section "Table settings" below.

This method will add more pages to the pdf instance as required based on the formatting options and the amount of data.

Returns

The return value is a 3 items list where

    $final_page - The first item is a PDF::API2::Page instance that the table ends on
    $number_of_pages - The second item is the count of pages that the table spans on
    $final_y - The third item is the Y coordinate of the table bottom so that additional content can be added in the same document.
Example
    my $pdf  = new PDF::API2;
    my $page = $pdf->page();
    my $data = [
        ['foo1','bar1','baz1'],
        ['foo2','bar2','baz2']
    ];
    my %settings = (
        x       => 10,
        w       => 570,
        start_y => 220,
        start_h => 180,
    );
    
    my ($final_page, $number_of_pages, $final_y) = $pdftable->table( $pdf, $page, $data, %options );

Table settings

Mandatory

There are some mandatory parameteres for setting table geometry and position across page(s)

x - X coordinate of upper left corner of the table. Left edge of the sheet is 0.

Value: can be any whole number satisfying 0 =< X < PageWidth Default: No default value

    x => 10
start_y - Y coordinate of upper left corner of the table at the initial page.

Value: can be any whole number satisfying 0 < start_y < PageHeight (depending on space availability when embedding a table) Default: No default value

    start_y => 327
w - width of the table starting from X.

Value: can be any whole number satisfying 0 < w < PageWidth - x Default: No default value

    w  => 570
start_h - Height of the table on the initial page

Value: can be any whole number satisfying 0 < start_h < PageHeight - Current Y position Default: No default value

    start_h => 250
    

Optional

next_h - Height of the table on any additional page

Value: can be any whole number satisfying 0 < next_h < PageHeight Default: Value of param 'start_h'

    next_h  => 700
next_y - Y coordinate of upper left corner of the table at any additional page.

Value: can be any whole number satisfying 0 < next_y < PageHeight Default: Value of param 'start_y'

    next_y  => 750
max_word_length - Breaks long words (like serial numbers hashes etc.) by adding a space after every Nth symbol

Value: can be any whole positive number Default: 20

    max_word_length => 20    # Will add a space after every 20 symbols
padding - Padding applied to every cell
padding_top - top cell padding, overrides 'padding'
padding_right - right cell padding, overrides 'padding'
padding_left - left cell padding, overrides 'padding'
padding_bottom - bottom padding, overrides 'padding'

Value: can be any whole positive number

Default padding: 0

Default padding_* $padding

    padding        => 5      # all sides cell padding
    padding_top    => 8,     # top cell padding, overrides 'padding'
    padding_right  => 6,     # right cell padding, overrides 'padding'
    padding_left   => 2,     # left cell padding, overrides 'padding'
    padding_bottom => undef  # bottom padding will be 5 as it will fallback to 'padding'
border - Width of table border lines.
horizontal_borders - Width of horizontal border lines. Overrides 'border' value.
vertical_borders - Width of vertical border lines. Overrides 'border' value.

Value: can be any whole positive number. When set to 0 will disable border lines. Default: 1

    border             => 3     # border width is 3
    horizontal_borders => 1     # horizontal borders will be 1 overriding 3
    vertical_borders   => undef # vertical borders will be 3 as it will fallback to 'border'
vertical_borders - Width of vertical border lines. Overrides 'border' value.

Value: Color specifier as 'name' or 'HEX' Default: 'black'

    border_color => 'red'
font - instance of PDF::API2::Resource::Font defining the fontf to be used in the table

Value: can be any PDF::API2::Resource::* type of font Default: 'Times' with UTF8 encoding

    font => $pdf->corefont("Helvetica", -encoding => "utf8")
font_size - Default size of the font that will be used across the table

Value: can be any positive number Default: 12

    font_size => 16
font_color - Font color for all rows
font_color_odd - Font color for odd rows
font_color_even - Font color for even rows
background_color_odd - Background color for odd rows
background_color_even - Background color for even rows

Value: Color specifier as 'name' or 'HEX' Default: 'black' font on 'white' background

    font_color            => '#333333'
    font_color_odd        => 'purple'
    font_color_even       => '#00FF00'
    background_color_odd  => 'gray'     
    background_color_even => 'lightblue'
row_height - Desired row height but it will be honored only if row_height > font_size + padding_top + padding_bottom

Value: can be any whole positive number Default: font_size + padding_top + padding_bottom

    row_height => 24
 
new_page_func - CODE reference to a function that returns a PDF::API2::Page instance.

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.

    new_page_func  => $code_ref
    
header_props - HASH reference to specific settings for the Header row of the table. See section "Header Row Properties" below
    header_props => $hdr_props
column_props - HASH reference to specific settings for each column of the table. See section "Column Properties" below
    column_props => $col_props
cell_props - HASH reference to specific settings for each column of the table. See section "Cell Properties" below
    cell_props => $cel_props
    cell_render_hook  => sub {
        my ($page, $first_row, $row, $col, $x, $y, $w, $h) = @_;

        # Do nothing except for first column (and not a header row)
        return unless ($col == 0);
        return if ($first_row);

        # Create link
        my $value = $list_of_vals[$row-1];
        my $url = "https://${hostname}/app/${value}";

        my $annot = $page->annotation();
        $annot->url( $url, -rect => [$x, $y, $x+$w, $y+$h] );
    },
    

Header Row Properties

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. 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.

font - instance of PDF::API2::Resource::Font defining the fontf to be used in the header row

Value: can be any PDF::API2::Resource::* type of font Default: 'font' of the table. See table parameter 'font' for more details.

font_size - Font size of the header row

Value: can be any positive number Default: 'font_size' of the table + 2

font_color - Font color of the header row

Value: Color specifier as 'name' or 'HEX' Default: '#000066'

bg_color - Background color of the header row

Value: Color specifier as 'name' or 'HEX' Default: #FFFFAA

repeat - Flag showing if header row should be repeated on every new page

Value: 0,1 1-Yes/True, 0-No/False Default: 0

justify - Alignment of text in the header row.

Value: One of 'left', 'right', 'center' Default: Same as column alignment (or 'left' if undefined)

    my $hdr_props = 
    {
        font       => $pdf->corefont("Helvetica", -encoding => "utf8"),
        font_size  => 18,
        font_color => '#004444',
        bg_color   => 'yellow', 
        repeat     => 1,    
        justify    => 'center'
    };

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:

min_w - Minimum width of this column. Auto calculation will try its best to honour this param but aplying it is NOT guaranteed.

Value: can be any whole number satisfying 0 < min_w < w Default: Auto calculated

max_w - Maximum width of this column. Auto calculation will try its best to honour this param but aplying it is NOT guaranteed.

Value: can be any whole number satisfying 0 < max_w < w Default: Auto calculated

font - instance of PDF::API2::Resource::Font defining the fontf to be used in this column

Value: can be any PDF::API2::Resource::* type of font Default: 'font' of the table. See table parameter 'font' for more details.

font_size - Font size of this column

Value: can be any positive number Default: 'font_size' of the table.

font_color - Font color of this column

Value: Color specifier as 'name' or 'HEX' Default: 'font_color' of the table.

background_color - Background color of this column

Value: Color specifier as 'name' or 'HEX' Default: undef

justify - Alignment of text in this column

Value: One of 'left', 'right', 'center' Default: 'left'

Example:

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

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. When this happens a warning will be issued with some advises what can be done. In cases of a conflict between column formatting and odd/even row formatting, 'col_props' will override odd/even.

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 the keys shown below:

font - instance of PDF::API2::Resource::Font defining the fontf to be used in this cell

Value: can be any PDF::API2::Resource::* type of font Default: 'font' of the table. See table parameter 'font' for more details.

font_size - Font size of this cell

Value: can be any positive number Default: 'font_size' of the table.

font_color - Font color of this cell

Value: Color specifier as 'name' or 'HEX' Default: 'font_color' of the table.

background_color - Background color of this cell

Value: Color specifier as 'name' or 'HEX' Default: undef

justify - Alignment of text in this cell

Value: One of 'left', 'right', 'center' Default: 'left'

Example:

    my $cell_props = [
        [ #This array is for the first row. If header_props is defined it will overwrite these settings.
            {    #Row 1 cell 1
                background_color => '#AAAA00',
                font_color       => 'yellow',
            },

            # etc.
        ],
        [#Row 2
            {    #Row 2 cell 1
                background_color => '#CCCC00',
                font_color       => 'blue',
            },
            {    #Row 2 cell 2
                background_color => '#BBBB00',
                font_color       => 'red',
            },
            # etc.
        ],
        # etc.
    ];

    OR
    
    my $cell_props = [];
    $cell_props->[1][0] = {
        #Row 2 cell 1
        background_color => '#CCCC00',
        font_color       => 'blue',
    };

NOTE: 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 and cell formating, header formating will override cell.

text_block()

    my ($width_of_last_line, $ypos_of_last_line, $left_over_text) = text_block( $txt, $data, %settings)
Description

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.

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. 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.

Parameters
    $txt  - a PDF::API2::Page::Text instance representing the text tool
    $data - a string that will be placed inside the block
    %settings - HASH with geometry and formatting parameters.
     
Reuturns

The return value is a 3 items list where

    $width_of_last_line - Width of last line in the block
    $final_y - The Y coordinate of the block bottom so that additional content can be added after it
    $left_over_text - Text that was did not fit in the provided box geometry.
    
Example
    # PDF::API2 objects
    my $page = $pdf->page;
    my $txt  = $page->text;

    my %settings = (
        x => 10,
        y => 570,
        w => 220,
        h => 180
        
        #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,
    );
    
    my ( $width_of_last_line, $final_y, $left_over_text ) = $pdftable->text_block( $txt, $data, %settings );
 

VERSION

0.9.7

AUTHOR

Daemmon Hughes

DEVELOPMENT

Further development since Ver: 0.02 - Desislav Kamenov

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.

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 (@deskata on Twitter)

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

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

Thanks to all GitHub contributors!

CONTRIBUTION

Hey PDF::Table is on GitHub. You are more than welcome to contribute!

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

SEE ALSO

PDF::API2