The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

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

VERSION

This document describes LaTeX::Table version 0.9.10

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{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. The powerful new ctable package is supported and especially recommended when footnotes are needed. LaTeX::Table 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 } ) {
    ...
  }
$table->search_path( add => "MyThemes" );

LaTeX::Table will search under the LaTeX::Table::Themes:: namespace for themes. You can add here an additional search path. Inherited from Module::Pluggable.

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 'std' for standard LaTeX tables, 'ctable' for tables using the ctable package or 'xtab' for multipage tables (in appendices for example, requires the xtab LaTeX package).

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', '' ],
      ['\cmidrule{1-2}'],
      [ 'Animal', 'Description', 'Price' ]
  ];

will produce following LaTeX code in the default Zurich theme:

  \multicolumn{2}{c}{\textbf{Item}} & \multicolumn{1}{c}{\textbf{}}\\ 
  \cmidrule{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 |
  +-------+---------+

This works also in header.

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. For std tables, the default environment is 'table'. A true value different from '1' will be used as environment name. Default is 1 (use a 'table' environment).

The non-floating xtab environment is mandatory (get_environment() must return a true value here) and supports all options in this section except for position.

The ctable type automatically adds an environment when any of the following options are set.

  \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) because the spacing in the standard LaTeX macros is optimized for bottom captions. At least for multipage tables, however, top captions are highly recommended. You can use the caption LaTeX package to fix the spacing:

  \usepackage[tableposition=top]{caption} 
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.

shortcaption

Same as maincaption, but does not appear in the caption, only in the table listing. Default 0. Requires environment.

center, right, left

Defines how the table is aligned in the available textwidth. Default is centered. Requires environment. Only one of these options may return a true value.

  # don't generate any centering code
  $self->set_center(0);
label

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

position

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

sideways

Rotates the environment by 90 degrees. Requires the rotating LaTeX package.

This does not work with xtab tables - please tell me if you know how to implement this.

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.

star

Use the starred versions of the environments, which place the float over two columns when the twocolumn option or the \twocolumn command is active.

TABULAR ENVIRONMENT

custom_tabular_environment

If get_custom_tabular_environment() returns a true value, then this specified environment is used instead of the standard environments 'tabular' (std) or 'xtabular' (xtab). For xtab tables, you can also use the 'mpxtabular' environment here if you need footnotes. See the documentation of the xtab package.

See also the documentation of width below for cases when a width is specified.

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 the tabularx 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*(?=\w+\s+\w+).{29,}?\S}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 is 1 ($regex 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 for tabularx tables. If undefined, the attribute defined in TYPE_COL is used for tabularx tables as well.

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_COL => '>{\raggedright\arraybackslash}p{7cm}', # non-justified
  });

  # add new types (here: columns that contain only URLs)
  $table->set_coldef_strategy({
    URL     => qr{\A \s* http }xms, 
    URL_COL => '>{\ttfamily}l',
  });

  
width

If get_width() returns a true value, then LaTeX::Table will append a * to the tabular environment name (e.g. tabular* or xtabular*) and will add the specified width. It will also add @{\extracolsep{\fill}} to the table column definition:

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

This will produce following LaTeX code:

  \begin{tabular*}{0.75\textwidth}{l@{\extracolsep{\fill} ... }

For tables of type std, it is also possible to use the tabularx LaTeX package (see width_environment below). The tables of type ctable automatically use the tabularx package.

width_environment

If get_width() (see above) returns a true value and table is of type std, then this option provides the possibility to add a custom tabular environment that supports a table width:

  \begin{environment}{width}{def}

To use for example the one provided by the tabularx LaTeX package, write:

  # use the tabularx package (for a std table)
  $table->set_width('300pt');
  $table->set_width_environment('tabularx');

Note this will not add @{\extracolsep{\fill}} and that this overwrites a custom_tabular_environment. Default is 0 (see width).

maxwidth

Only supported by tables of type ctable.

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;
          },
      }
  );
foottable

Only supported by tables of type ctable. The footnote \tnote commands. See the documentation of the ctable LaTeX package.

  $table->set_foottable('\tnote{footnotes are placed under the table}');
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 width. 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' ]);

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. See "THEMES".

predef_themes

All predefined themes. Getter only.

custom_themes

All custom themes. See LaTeX::Table::Themes::ThemeI.

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 LaTeX::Table::Themes::ThemeI. 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 main themes are available: Zurich, plain (no formatting), NYC (for presentations), Berlin and Paris. Variants of these themes are also available, see the theme modules below. 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.

See LaTeX::Table::Themes::ThemeI how to define custom themes.

LaTeX::Table::Themes::Beamer, LaTeX::Table::Themes::Booktabs, LaTeX::Table::Themes::Classic, LaTeX::Table::Themes::Modern.

EXAMPLES

See examples/examples.pdf in this distribution for a short tutorial that covers the main features of this module. See also the example application csv2pdf for an example of the common task of converting a CSV (or Excel) file to LaTeX or even PDF.

DIAGNOSTICS

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

LaTeX::Table may throw one of these errors and warnings:

IO error: Can't ...

In method generate(), it was not possible to write the LaTeX code to filename.

Invalid usage of option ...

See the examples in this document and in examples/examples.pdf for the correct usage of this option.

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.

CONFIGURATION AND ENVIRONMENT

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

DEPENDENCIES

Carp, Module::Pluggable, Moose, English, Scalar::Util, Template, 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

Data::Table, LaTeX::Encode

CREDITS

David Carlisle for the colortbl and the tabularx LaTeX packages.
Wybo Dekker for the ctable LaTeX package.
Simon Fear for the booktabs LaTeX package. The "SYNOPSIS" table is the example in his documentation.
Andrew Ford (ANDREWF) for many great suggestions. He also wrote LaTeX::Driver and LaTeX::Encode which are used by csv2pdf.
Lapo Filippo Mori for the excellent tutorial Tables in LaTeX2e: Packages and Methods.
Peter Wilson for the xtab LaTeX package.

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.