NAME

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

SYNOPSIS

Rather than cluttering up the following documentation with (or PDF::Builder) additions, wherever it refers to PDF::API2, understand that you can substitute PDF::Builder to use that product instead.

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 lay out
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
    max_word_length => 50, # 50 between forced splits
 );

# 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 (or PDF::Builder) 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, 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 item 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
$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 parameters 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 fall back 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 fall back to 'border'
border_color - Border color for all borders.

Value: Color specifier as 'name' or '#rrggbb'

Default: 'black'

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

Value: can be any PDF::API2::Resource::* type of font

Default: 'Times' with latin1 encoding

font => $pdf->corefont("Helvetica", -encoding => "latin1")
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
font_underline - Font underline of the header row

Value: 'auto', integer of distance, or arrayref of distance & thickness (more than one pair will provide multiple underlines. Negative distance gives strike-through.

Default: none

background_color_odd - Background color for odd rows
background_color_even - Background color for even rows

Value: Color specifier as 'name' or '#rrggbb'

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 stuff that you need. Also if you need a different paper size and orientation than the default US-Letter, e.g., 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 font 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 '#rrggbb'

Default: #000066

font_underline - Font underline of the header row

Value: 'auto', integer of distance, or arrayref of distance & thickness (more than one pair will provide multiple underlines. Negative distance gives strike-through.

Default: none

bg_color - Background color of the header row

Value: Color specifier as 'name' or '#rrggbb'

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 => "latin1"),
    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 applying 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 applying 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 font 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 '#rrggbb'

Default: font_color of the table.

font_underline - Font underline of this cell

Value: 'auto', integer of distance, or arrayref of distance & thickness (more than one pair will provide multiple underlines. Negative distance gives strike-through.

Default: none

background_color - Background color of this column

Value: Color specifier as 'name' or '#rrggbb'

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 overridden by the calculated minimum/maximum cell width so that the table can be created. When this happens, a warning will be issued with some suggestions on 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 font 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 '#rrggbb'

Default: font_color of the table.

font_underline - Font underline of this cell

Value: 'auto', integer of distance, or arrayref of distance & thickness (more than one pair will provide multiple underlines. Negative distance gives strike-through.

Default: none

background_color - Background color of this cell

Value: Color specifier as 'name' or '#rrggbb'

Default: undef

justify - Alignment of text in this cell

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

Default: 'left'

colspan - Span this cell over multiple columns to the right

Value: can be any positive number less than the number of columns to the right of the current column

Default: undef

NOTE: If you want to have regular columns after a colspan, you have to provide undef for the columns that should be spanned

NOTE: If you use colspan to span a column, but provide data for it, your table will be mangled: the spanned-but-data-provided-column will be rendered! But as HTML works the same way, we do not consider this a bug.

Example:

# row2 col1 should span 2 cols:
@data = ( [ 'r1c1', 'r1c2', 'r1c3' ], ['r2c1+',undef,'r2c3'] );
$tab->table( $pdf, $page, \@data, %TestData::required,
  cell_props => [
      [],
      [{colspan=>2}]
  ]
);

See "colspan.pl" in examples for detailed usage.

Example:

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

        # etc.
    ],
    [#Row 2
        {    #Row 2 cell 1
            background_color => '#CCCC00',
            font_color       => 'blue',
        },
        {    #Row 2 cell 2
            background_color => '#BBBB00',
            font_color       => 'red',
        },
        # etc.
    ],
    [#Row 3
        {    #Row 3 cell 1 span cell 2
            colspan          => 2
        },
        # 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 formatting; cell formatting will override the other two. In case of a conflict between header row and cell formatting, header formatting 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 internally but you can use it from outside for placing formatted 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.
Returns

The return value is a 3 item 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",
    max_word_length => $optional_max_word_chars_between_splits
    hang     => $optional_hanging_indent,
    Only one of the subsequent params can be given.
    They override each other. parspace is the highest weight
    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.12

AUTHOR

Daemmon Hughes

DEVELOPMENT

Further development Versions 0.02 -- 0.11 - Desislav Kamenov

Further development since Ver: 0.12 - Phil Perry

COPYRIGHT AND LICENSE

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

Copyright (C) 2020 by Phil M Perry.

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.7 or, at your option, any later version of Perl 5 you may have available. Note that Perl 5.10 is the minimum supported level.

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/PhilterPaper/PDF-Table

SEE ALSO

PDF::API2, PDF::Builder