NAME
LaTeX::Table - Perl extension for the automatic generation of LaTeX tables.
VERSION
This document describes LaTeX::Table version 0.9.4
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 (Zurich theme, the default)
\usepackage{booktabs}
% for the NYC theme
\usepackage{array}
\usepackage{colortbl}
\usepackage{color}
\usepackage{xcolor}
\begin{document}
\input{prices}
\end{document}
DESCRIPTION
LaTeX makes professional typesetting easy. Unfortunately, this is not entirely true for tables and the standard LaTeX table macros have a rather limited functionality. This module supports many packages that are available on CTAN and hides the complexity of using them behind an easy and intuitive API.
FEATURES
This module supports multipage tables via the xtab
package. For publication quality tables it utilizes 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. It ships with some predefined, good looking "THEMES".
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 standard LaTeX tables or 'xtab' for multipage tables (in appendices for example). The latter requires the
xtab
LaTeX package (\usepackage{xtab}
in the preamble of your LaTeX document). Default is 'std'. header
-
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
\multicolumn
,\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' ] ]);
Now you will get such a table:
+-------+---------+ | 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). In two-column documents, 'table*' will place the table across the columns. This option only affects tables oftype
std because xtab tables have their own, non-floating environment. This non-floating environment, however, supports all options in this section except forposition
.\begin{table}[htb] \centering \begin{tabular}{lrr} ... \end{tabular} \caption{Price list} \label{table:prices} \end{table}
-
The caption of the table. Only generated if get_caption() returns a true value. Default is 0. Requires
environment
. -
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) because standard LaTeX macros are optimized for bottom captions. For multi-page tables, however, top captions are highly recommended.
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. Default is 0. Requires
environment
. -
If get_maincaption() returns a true value, then this value will be displayed in the Table Listing (
\listoftables
) and before thecaption
. Default 0. Requiresenvironment
. 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
anddata
. 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 p (paragraph) columns of size '5cm' or X columns when thetabularx
package is selected. 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. It is a reference to a hash that contains regular expressions that define the types of the columns. For example, the standard types NUMBER and LONG are defined as:{ NUMBER => qr{\A\s*([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?\s*\z}xms, NUMBER_MUST_MATCH_ALL => 1, NUMBER_COL => 'r', NUMBER_COL_X => 'r', LONG => qr{\A\s*.{30,}?\s*\z}xms, LONG_MUST_MATCH_ALL => 0, LONG_COL => 'p{5cm}', LONG_COL_X => 'X', };
TYPE => $regex
-
New types are defined with the regular expression $regex. All cells that match this regular expression have type TYPE. A cell can have multiple types. The name of a type is not allowed to contain underscores (
_
). TYPE_MUST_MATCH_ALL
-
This defines if whether a column has type TYPE when all cells are of type
TYPE
or at least one. Default is1
(must match all).Note that columns can have only one type. Types are applied alphabetically, so for example a LONG NUMBER column has as final type NUMBER.
TYPE_COL
-
The
coldef
attribute for TYPE columns. Required (no default value). TYPE_COL_X
-
Same as
TYPE_COL
but fortabularx
tables. If undefined, the attribute defined inTYPE_COL
is used fortabularx
tables. DEFAULT_COL
,DEFAULT_COL_X
-
The
coldef
attribute for columns that do not match any specified type. Default 'l' (left-justified).
Examples:
# change standard types $table->set_coldef_strategy({ NUMBER => qr{\A \s* \d+ \s* \z}xms, # integers only LONG => qr{\A \s* .{60,} \s* \z}xms, # min. 60 characters LONG_COL => '>{\raggedright\arraybackslash}p{7cm}', # non-justified }); # add new types (here: center columns that contain only URLs) $table->set_coldef_strategy({ URL => qr{\A \s* http }xms, URL_COL => 'c', });
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
LaTeX::Table
will use thetabular*
(orxtabular*
for xtab tables) environment instead oftabular
(orxtabular
, respectively). For tables oftype
std, it supports also thetabularx
LaTeX package (see below).# use 75% of textwidth $table->set_width('0.75\textwidth');
width_environment
-
If get_width() (see above) returns a true value and table is of
type
std, then this option specifies whethertabular*
or thetabularx
package should be used. The latter is great when you have long columns becausetabularx
tries to optimize the column widths. Default is 'tabular*'.# use the tabularx package (for a std table) $table->set_width('300pt'); $table->set_width_environment('tabularx');
MULTIPAGE TABLES
tableheadmsg
-
When get_caption_top() and get_tableheadmsg() both return true values, then additional captions are printed on the continued pages. Default caption text is
Continued from previous page
. 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 ], } );
header_sideways
-
If get_header_sideways() returns a true value, then the header columns will be rotated by 90 degrees. Requires the
rotating
LaTeX package. Does not affect data columns specified in columns_like_header(). If you do not want to rotate all headers, use a callback function instead:... header_sideways => 0, callback => sub { my ( $row, $col, $value, $is_header ) = @_; if ( $col != 0 && $is_header ) { $value = '\begin{sideways}' . $value . '\end{sideways}'; } return $value; } ...
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), Berlin, Dresden, Houston, Miami and Paris. 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.
CUSTOM THEMES
Custom themes can be defined with an array reference containing all options (explained later):
# a very ugly theme...
my $themes = {
'Duisburg' => {
'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 ],
'EXTRA_ROW_HEIGHT' => '2pt',
'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 thecolor
LaTeX package.Set
HEADER_BG_COLOR
to use a background color in the header,DATA_BG_COLOR_EVEN
andDATA_BG_COLOR_ODD
for even and odd data rows. Requires thecolortbl
and thexcolor
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
-
EXTRA_ROW_HEIGHT
-
Will set
\extrarowheight
in the floating environment. Requires thearray
LaTeX package. HEADER_CENTERED
-
Valid values are 0 (not centered) or 1 (centered).
BOOKTABS
-
Use the
booktabs
LaTeX 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 a short tutorial that covers the main features of this module.
DIAGNOSTICS
If you get a LaTeX error message, please check whether you have included all required packages. The packages we use are array
, 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 the "SYNOPSIS" and "TABULAR ENVIRONMENT" for examples how to use this option.
coldef_strategy
not a hash reference.-
The return value of get_coldef_strategy() is not a hash reference. See "TABULAR ENVIRONMENT".
- Missing column attribute for ...
-
You have specified a new type in
coldef_strategy
but forgot to add the column attribute. 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
,data[$i]
,header[$i]
is not an array referencedata[$i][$j]/header[$i][$j]
is not a scalar- Undefined value in
data[$i][$j]/header[$i][$j]
-
See "BASIC OPTIONS" for the correct usage of the options
data
andheader
. - DEPRECATED. ...
-
There were some minor API changes in
LaTeX::Table
0.1.0, 0.8.0, 0.9.0 and 0.9.3. Just apply the changes to the script or contact its author. - Family not known: ... . Valid families are: ...
- Size not known: ... . Valid sizes are: ...
-
You have set a font family or size to an invalid value. See "CUSTOM THEMES".
- Theme not known: ...
-
You have set the option
theme
to an invalid value. See "THEMES" and the examples/examples.pdf document in this distribution. - Width environment not known: ...
width_environment
istabularx
andwidth
is unset.-
You have set option
width_environment
to an invalid value. 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" and the documentation of thebooktabs
LaTeX package.
CONFIGURATION AND ENVIRONMENT
LaTeX::Table
requires no configuration files or environment variables.
DEPENDENCIES
Carp, Class::Std, English, Fatal, Readonly, Scalar::Util, Text::Wrap
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
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>
.
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.