NAME

LaTeX::Table - Perl extension for the automatic generation of LaTeX tables.

VERSION

This document describes LaTeX::Table version 0.9.1

SYNOPSIS

use LaTeX::Table;
use Number::Format qw(:subs);  # use mighty CPAN to format values

my $header = [
    [ 'Item:2c', '' ],
    [ '\cmidrule(r){1-2}' ],
    [ 'Animal', 'Description', 'Price' ]
];

my $data = [
    [ 'Gnat',      'per gram', '13.65'   ],
    [ '',          'each',      '0.0173' ],
    [ 'Gnu',       'stuffed',  '92.59'   ],
    [ 'Emu',       'stuffed',  '33.33'   ],
    [ 'Armadillo', 'frozen',    '8.99'   ],
];


my $table = LaTeX::Table->new(
	{   
      filename    => 'prices.tex',
      maincaption => 'Price List',
      caption     => 'Try our special offer today!',
      label       => 'table:prices',
      position    => 'htb',
      header      => $header,
      data        => $data,
	}
);

# write LaTeX code in prices.tex
$table->generate();

# callback functions help you to format values easily (as
# a great alternative to LaTeX packages like rccol)
#
# Here, the first colum and the header is printed in upper
# case and the third colum is formatted with format_price()
$table->set_callback(sub { 
     my ($row, $col, $value, $is_header ) = @_;
     if ($col == 0 || $is_header) {
         $value = uc $value;
     }
     elsif ($col == 2 && !$is_header) {
         $value = format_price($value, 2, '');
     }
     return $value;
});     

print $table->generate_string();

Now in your LaTeX document:

\documentclass{article}

% for multipage tables
\usepackage{xtab}
% for publication quality tables
\usepackage{booktabs}

\begin{document}
\input{prices}
\end{document}

DESCRIPTION

LaTeX::Table provides functionality for an intuitive and easy generation of LaTeX tables. It ships with some predefined good looking table styles. This module supports multipage tables via the xtab package and publication quality tables with the booktabs package. It also supports the tabularx package for nicer fixed-width tables. Furthermore, it supports the colortbl package for colored tables optimized for presentations.

LaTeX makes professional typesetting easy. Unfortunately, this is not entirely true for tables. Many additional, highly specialized packages are therefore available on CTAN. This module supports the best packages and visualizes your in Perl generated or summarized results with high quality.

INTERFACE

my $table = LaTeX::Table->new($arg_ref)

Constructs a LaTeX::Table object. The parameter is an hash reference with options (see below).

$table->generate()

Generates the LaTeX table code. The generated LaTeX table can be included in a LaTeX document with the \input command:

% include prices.tex, generated by LaTeX::Table 
\input{prices}
$table->generate_string()

Same as generate() but instead of creating a LaTeX file, this returns the LaTeX code as string.

my $latexcode = $table->generate_string();
$table->get_available_themes()

Returns an hash reference to all available (predefined and customs) themes. See "THEMES" for details.

for my $theme ( keys %{ $table->get_available_themes } ) {
  ...
}

OPTIONS

Options can be defined in the constructor hash reference or with the setter set_<optionname>. Additionally, getters of the form get_<optionname> are created.

BASIC OPTIONS

filename

The name of the LaTeX output file. Default is 'latextable.tex'.

type

Can be either std for the standard LaTeX table or xtab for a xtabular table for multipage tables (in appendices for example). The latter requires the xtab LaTeX package (\usepackage{xtab} in your LaTeX document). Default is std.

The header. It is a reference to an array (the rows) of array references (the columns).

$table->set_header([ [ 'Animal', 'Price' ] ]);

will produce following header:

+--------+-------+
| Animal | Price |
+--------+-------+

Here an example for a multirow header:

$table->set_header([ [ 'Animal', 'Price' ], ['', '(roughly)' ] ]);

This code will produce this header:

+--------+-----------+
| Animal |   Price   |
|        | (roughly) |
+--------+-----------+

Single column rows that start with a backslash are treated as LaTeX commands and are not further formatted. So,

my $header = [
    [ 'Item:2c', '' ],
    ['\cline{1-2}'],
    [ 'Animal', 'Description', 'Price' ]
];

will produce following LaTeX code in the default Zurich theme:

\multicolumn{2}{c}{\textbf{Item}} & \multicolumn{1}{c}{\textbf{}}\\ 
\cline{1-2}
\multicolumn{1}{c}{\textbf{Animal}} & \multicolumn{1}{c}{\textbf{Description}} & \multicolumn{1}{c}{\textbf{Price}}\\ 

Note that there is no multicolum, textbf or \\ added to the second row.

data

The data. Once again a reference to an array (rows) of array references (columns).

$table->set_data([ [ 'Gnu', '92.59' ], [ 'Emu', '33.33' ] ]);

And you will get a table like this:

+-------+---------+
| Gnu   |   92.59 |
| Emu   |   33.33 |
+-------+---------+

An empty column array will produce a horizontal line:

$table->set_data([ [ 'Gnu', '92.59' ], [], [ 'Emu', '33.33' ] ]);

And you will get a table like this:

+-------+---------+
| Gnu   |   92.59 |
+-------+---------+
| Emu   |   33.33 |
+-------+---------+

Single column rows starting with a backslash are again printed without any formatting. So,

$table->set_data([ [ 'Gnu', '92.59' ], ['\hline'], [ 'Emu', '33.33' ] ]);

is equivalent to the example above (except that there always the correct line command is used, i.e. \midrule vs. \hline).

FLOATING TABLES

environment

If get_environment() returns a true value, then a floating environment will be generated. Default is 'table'. You can use 'sidewaystable' for rotated tables (requires the rotating package). This option only affects tables of type std.

\begin{table}[htb]
    \centering
    \begin{tabular}{lrr}
    ...
    \end{tabular}
    \caption{Price list}
    \label{table:prices}
\end{table} 
caption

The caption of the table. Only generated if get_caption() returns a true value. Default is 0. Requires environment.

caption_top

If get_caption_top() returns a true value, then the caption is placed above the table. To use the standard caption command (\caption in std, \topcaption in xtab) , use

...
caption_top => 1, 
...

You can specify an alternative command here:

...
caption_top => 'topcaption', # would require the topcapt package

Or even multiple commands:

caption_top =>
  '\setlength{\abovecaptionskip}{0pt}\setlength{\belowcaptionskip}{10pt}\caption',
...

Default 0 (caption below the table).

center

Defines whether the table is centered. Default 1 (centered). Requires environment.

label

The label of the table. Only generated if get_label() returns a true value. In LaTeX you can create a reference to the table with \ref{label}. Default is 0. Requires environment.

maincaption

If get_maincaption() returns a true value, then this value will be displayed in the Table Listing (\listoftables) and before the caption. Default 0. Requires environment.

size

Font size. Valid values are 'tiny', 'scriptsize', 'footnotesize', 'small', 'normal', 'large', 'Large', 'LARGE', 'huge', 'Huge' and 0. Default is 0 (does not define a font size). Requires environment.

position

The position of the environment, e.g. htb. Only generated if get_position() returns a true value. Requires environment.

TABULAR ENVIRONMENT

callback

If get_callback() returns a true value and the return value is a code reference, then this callback function will be called for every column in header and data. The return value of this function is then printed instead of the column value.

The passed arguments are $row, $col (both starting with 0), $value and $is_header.

use LaTeX::Encode;
use Number::Format qw(:subs);  
...

# use LaTeX::Encode to encode LaTeX special characters,
# format the third column with Format::Number (only the data)
my $table = LaTeX::Table->new(
    {   header   => $header,
        data     => $data,
        callback => sub {
            my ( $row, $col, $value, $is_header ) = @_;
            if ( $col == 2 && !$is_header ) {
                $value = format_price($value, 2, '');
            }
            else {
                $value = latex_encode($value);
            }
            return $value;
        },
    }
);
coldef

The table column definition, e.g. lrcr which would result in:

\begin{tabular}{lrcr}
..

If unset, LaTeX::Table tries to guess a good definition. Columns containing only numbers are right-justified, others left-justified. Columns with cells longer than 30 characters are paragraph columns of size 5 cm. These rules can be changed with set_coldef_strategy(). Default is 0 (guess good definition).

coldef_strategy

Controls the behaviour of the coldef calculation when get_coldef() does not return a true value. Is a reference to a hash with following keys:

IS_A_NUMBER => $regex

Defines a column as NUMBER when all cells in this column match the specified regular expression. Default is qr{\A([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?\z}xms.

IS_LONG => $n

Defines a column as LONG when one cell is equal or larger than $n characters (default 30).

NUMBER_COL => $attribute, NUMBER_COL_X => $attribute

The coldef attribute for NUMBER columns. Default 'r' (right-justified).

LONG_COL => $attribute, LONG_COL_X => $attribute

The coldef attribute for LONG columns. Default 'p{5cm}' (paragraph column with text vertically aligned at the top, width 5cm) and 'X' when the tabularx package is used.

DEFAULT => $attribute, DEFAULT_X => $attribute

The coldef attribute for columns that are neither NUMBER nor LONG. Default 'l' (left-justified).

Example:

$table->set_coldef_strategy({
  IS_A_NUMBER => qr{\A \d+ \z}xms, # integers only
  IS_LONG     => 60, # min. 60 characters
  LONG_COL    => 'm{7cm}', # vertically aligned at the middle, 7cm
});
resizebox

If get_resizebox() returns a true value, then the resizebox command is used to resize the table. Takes as argument a reference to an array. The first element is the desired witdth. If a second element is not given, then the hight is set to a value so that the aspect ratio is still the same. Requires the graphicx LaTeX package. Default 0.

$table->set_resizebox([ '0.6\textwidth' ]);

$table->set_resizebox([ '300pt', '200pt' ]);
width

If get_width() returns a true value, then {tabular*}{width}{@{\extracolsep{\fill}} ... } (or {xtabular*}{width}{ ... }, respectively) is used. For tables of type 'std', you can also use the tabularx LaTeX package (see below).

# use 75% of textwidth 
$table->set_width('0.75\textwidth');

# or 300 points (1/72 inch)
$table->set_width('300pt');
width_environment

If get_width() (see above) returns a true value and table is of type std, then this option specifies whether tabular* or the tabularx package should be used. The latter is great when you have long columns because tabularx tries to optimize the column widths. Default is 'tabular*'.

MULTIPAGE TABLES

tabletailmsg

Message at the end of a multipage table. Default is Continued on next page.

tabletail

Custom table tail. Default is multicolumn with the tabletailmsg (see above) right-justified.

xentrystretch

Option for xtab. Play with this option if the number of rows per page is not optimal. Requires a number as parameter. Default is 0 (does not use this option).

$table->set_xentrystretch(-0.1);

THEMES

theme

The name of the theme. Default is Zurich.

predef_themes

All predefined themes. Getter only.

custom_themes

All custom themes. See "CUSTOM THEMES".

columns_like_header

Takes as argument a reference to an array with column ids (again, starting with 0). These columns are formatted like header columns.

# a "transposed" table ...
my $table = LaTeX::Table->new(
    {   data     => $data,
        columns_like_header => [ 0 ],
    };

MULTICOLUMNS

Multicolumns are defined in LaTeX with \multicolumn{$cols}{$alignment}{$text}. This module supports a simple shortcut of the format $text:$cols$alignment. For example, Item:2c is equivalent to \multicolumn{2}{c}{Item}. Note that vertical lines (|) are automatically added here according the LINES settings in the theme. See "CUSTOM THEMES". LaTeX::Table also uses this shortcut to determine the column ids. So in this example,

my $data = [ [' \multicolumn{2}{c}{A}', 'B' ], [ 'C:2c', 'D' ] ];

'B' would have an column id of 1 and 'D' 2 ('A' and 'C' both 0). This is important for callback functions and for the coldef calculation. See "TABULAR ENVIRONMENT".

THEMES

The theme can be selected with $table->set_theme($themename). Currently, following predefined themes are available: Zurich, plain (no formatting), NYC (for presentations), Dresden, Berlin, Miami and Houston. The script generate_examples.pl in the examples directory of this distributions generates some examples for all available themes.

The default theme, Zurich, is highly recommended. It requires \usepackage{booktabs} in your LaTeX document. The top and bottom lines are slightly heavier (ie thicker, or darker) than the other lines. No vertical lines. You want this. Believe it.

CUSTOM THEMES

Custom themes can be defined with an array reference containing all options (explained later):

# a very ugly theme...
my $themes = { 
            'Leipzig' => {
                'HEADER_FONT_STYLE'  => 'sc',
                'HEADER_FONT_COLOR'  => 'white',
                'HEADER_BG_COLOR'    => 'blue',
                'HEADER_CENTERED'    => 1,
                'DATA_BG_COLOR_ODD'  => 'blue!30',
                'DATA_BG_COLOR_EVEN' => 'blue!10',
                'CAPTION_FONT_STYLE' => 'sc',
                'VERTICAL_LINES'     => [ 1, 2, 1 ],
                'HORIZONTAL_LINES'   => [ 1, 2, 0 ],
                'BOOKTABS'           => 0,
            },
        };

$table->set_custom_themes($themes);
Fonts

HEADER_FONT_STYLE, CAPTION_FONT_STYLE. Valid values are bf (bold), it (italics), sc (caps) and tt (typewriter). When this option is undef, then header (or caption, respectively) is written in normal font.

Colors

HEADER_FONT_COLOR can be used to specify a different font color for the header. Requires the color LaTeX package.

Set HEADER_BG_COLOR to use a background color in the header, DATA_BG_COLOR_EVEN and DATA_BG_COLOR_ODD for even and odd data rows. Requires the colortbl and the xcolor LaTeX package.

You can define colors with DEFINE_COLORS, for example:

'DEFINE_COLORS'      => '\definecolor{latextbl}{RGB}{78,130,190}',
Lines

VERTICAL_LINES, HORIZONTAL_LINES. A reference to an array with three integers, e.g. [ 1, 2, 0 ]. The first integer defines the number of outer lines. The second the number of lines after the header and after the first column. The third is the number of inner lines. For example "DRESDEN" is defined as:

'Dresden' => {
    ...  
    'VERTICAL_LINES'     => [ 1, 2, 1 ],
    'HORIZONTAL_LINES'   => [ 1, 2, 0 ],
}

The first integers define one outer line - vertical and horizontal. So a box is drawn around the table. The second integers define two lines between header and table and two vertical lines between first and second column. And finally the third integers define that columns are separated by a single vertical line whereas rows are not separated by horizontal lines.

Misc
HEADER_CENTERED

Valid values are 0 (not centered) or 1 (centered).

BOOKTABS

Use the Booktabs package for "Publication quality tables". Instead of \hline, LaTeX::Table then uses \toprule, \midrule and \bottomrule. 0 (don't use this package) or 1 (use it).

EXAMPLES

See examples/examples.pdf in this distribution for examples for most of the features of this module. This document was generated with examples/generate_examples.pl.

DIAGNOSTICS

If you get a LaTeX error message, please check whether you have included all required packages. The packages we use are booktabs, color, colortbl, graphicx, rotating, tabularx, xcolor and xtab.

LaTeX::Table may throw one of these errors:

callback is not a code reference

The return value of get_callback() is not a code reference. See "TABULAR ENVIRONMENT".

columns_like_header is not an array reference

The return value of get_columns_like_header() is not an array reference. See "THEMES".

data/header is not an array reference

get_data() (or get_header(), respectively) does not return a reference to an array. See "BASIC OPTIONS".

data[$i]/header[$i] is not an array reference

The ith element of get_data() (or get_header()) is not an array reference. See "BASIC OPTIONS".

data[$i][$j]/header[$i][$j] is not a scalar

The jth column in the ith row is not a scalar. See "BASIC OPTIONS".

DEPRECATED. ...

There were some minor API changes in LaTeX::Table 0.1.0 and 0.8.0. Just apply the changes to the script and/or contact its author.

Family not known: ... . Valid families are: ...

You have set a font family to an invalid value. See "CUSTOM THEMES".

Size not known: ... . Valid sizes are: ...

You have set a font size to an invalid value. See "CUSTOM THEMES".

coldef_strategy not a hash reference.

The return value of get_coldef_strategy() is not a hash reference. See "TABULAR ENVIRONMENT".

resizebox is not an array reference

The return value of get_resizebox() is not a reference to an array. See "TABULAR ENVIRONMENT".

Theme not known: ...

You have set the option theme to an invalid value. See "THEMES".

Undefined value in data[$i][$j]/header[$i][$j]

The value in this cell is undef. See "BASIC OPTIONS".

Width not known: ...

You have set option width_environment to an invalid value. See "TABULAR ENVIRONMENT".

width_environment is tabularx and width is unset.

You have to specify a width when using the tabularx package. See "TABULAR ENVIRONMENT".

xentrystretch not a number

You have set the option xentrystretch to an invalid value. This option requires a number. See "MULTIPAGE TABLES".

CONFIGURATION AND ENVIRONMENT

LaTeX::Table requires no configuration files or environment variables.

DEPENDENCIES

Carp, Class::Std, English, Fatal, Readonly, Scalar::Util, Text::Wrap

INCOMPATIBILITIES

None reported.

BUGS AND LIMITATIONS

No bugs have been reported.

Please report any bugs or feature requests to bug-latex-table@rt.cpan.org, or through the web interface at http://rt.cpan.org.

SEE ALSO

Data::Table, LaTeX::Encode

CREDITS

Andrew Ford (ANDREWF): many great suggestions.

AUTHOR

Markus Riester <mriester@gmx.de>

LICENSE AND COPYRIGHT

Copyright (c) 2006-2008, Markus Riester <mriester@gmx.de>. All rights reserved.

This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See perlartistic.

DISCLAIMER OF WARRANTY

BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.