libpdf...:Table(3pm)
β¨ okay bestie, welcome to the libpdf...:Table(3pm) page β¨ β User Contributed Perl Documentation, and we're about to make table layouts in PDFs look absolutely iconic. π
πΈ NAME πΈ
PDF::Table β A utility class for building table layouts in a PDF::Builder (or PDF::API2) object.
β¨ SYNOPSIS β¨
π Note on product usage
Rather than cluttering up the following documentation with (or PDF::API2) additions, wherever it refers to "PDF::Builder", understand that you can substitute "PDF::API2" to use that product instead EXCEPT where noted.
use PDF::Builder;
use PDF::Table;
my $pdftable = new PDF::Table;
my $pdf = new PDF::Builder(-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
# note: ignoring return values array
$pdftable->table(
# required parameters
$pdf,
$page,
$some_data,
'x' => $left_edge_of_table,
'w' => 495,
'y' => 500,
'h' => 300,
# some optional parameters
'next_y' => 750,
'next_h' => 500,
'padding' => 5,
'padding_right' => 10,
'bg_color_odd' => "gray",
'bg_color_even' => "lightblue", # cell bg color for even rows
'max_word_length' => 50, # 50 between forced splits
);
# do other stuff with $pdf
$pdf->save();
... and so on
π¦ 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::Builder (or PDF::API2, see note above) 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). 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.
π COMPATIBILITY π
Starting with version 1.000, several behaviors have changed (for the better, I believe). Nevertheless, there may be some users who prefer the old behaviors. To keep everybody happy, it is possible to easily revert to the old behaviors. Near the top of Table.pm, look for a section labeled "COMPATIBILITY WITH OLDER VERSIONS". You can change settings here to match old behaviors:
repeating headers
The old default for the "repeat" setting for a header was '0' (do not repeat after a table has been split across a page). I believe that most users will want to automatically repeat a header row at the start of each table fragment, but you can change this behavior if you wish. Change $repeat_default from 1 to 0 to get the old behavior (or, explicitly give "repeat => 0" in the header properties settings).
which rows are 'odd' (and which are 'even')
PDF::Table decided which rows were odd/even (background and foreground colors, etc) in an inconsistent manner, especially if a header was used (whether repeated or not). Now, the first data row (excluding headers) is "odd", and all rows after that alternate "even", "odd", etc., even across page breaks. If you want the old behavior, it can be requested. Change $oddeven_default from 1 to 0 to get the old behavior.
default cell padding
The old default for padding around the contents of a cell was 0. It is now 2pt. Change $padding_default from 2 to 0 to get the old behavior.
behavior of borders
The old behavior was calling both the frame around the table and the cell-divider rules as "border", and using the same settings for both. This has been changed to separate the two classes, with "border" referring to the outside framework, and "rules" referring to the dividers. Note that "rules" still inherit from "border", so an explicit definition of "rules => 0" (to hide interior rules) or another width (line weight) may still be needed to override the "border" setting for interior dividers.
Maintaining compatibility
Near the top of file Table.pm, look for "my $compat_mode = 0;". PDF::Table is shipped with a flag of 0 to use the new features of the library. If you have a pressing need to maintain compatibility with older versions of the library, you may change the value to 1. Note that a flag of 1 will break some of the t-tests, because of different padding defaults resulting in different text locations on the page.
Run-time changes
If you do not wish to change the PDF::Table code section to permanently change old-versus-new behavior, you can use the compatibility flag in the settings to temporarily change the variables listed above.
compatibility => [ 0, 0, 0 ]
will restore all behaviors to the old style, while
compatibility => [ 1, 0, 2 ]
will change only the designation of "odd/even" rows (element 1) to the old behavior, while leaving header repeat (element 0) and default padding (element 2) in the new behavior.
π METHODS π
β¨ new()
my $pdf_table = new PDF::Table;
or
my $pdf_table = PDF::Table->new();
Description
Creates a new instance of the class.
Parameters
There are no required parameters. You may pass $pdf, $page, $data, and %options; or can defer this until the table() method invocation (the usual technique).
Returns
Reference to the new instance
π table()
Generate output:
my ($final_page, $number_of_pages, $final_y) = table($pdf, $page, $data, %settings)
or, just report row sizes:
my @v_sizes = table($pdf, $page, $data, %settings, 'ink' => 0)
Description
Generates a multi-row, multi-column table into an existing PDF document, based on provided data set and settings.
Parameters
$pdf - a PDF::Builder instance representing the document being created
$page - a PDF::Builder::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
$data is normally an m x n matrix of strings, each string containing the content text of that cell, and arranged with each row being an anonymous array of strings. For example, a table of 3 rows of 4 columns would be
$data = [
[ 'c1', 'c2', 'c3', 'c4' ], # row 1
[ 'c1', 'c2', 'c3', 'c4' ], # row 2
[ 'c1', 'c2', 'c3', 'c4' ], # row 3
];
For PDF::Builder ONLY:
If you wish to enable markup (Markdown or HTML) for a cell, $data has the same structure, except that a cell with markup is itself an anonymous array of three items: a string describing the markup ('none', 'md1', 'html', or 'pre'), a string or anonymous array of strings representing the text and markup for the cell, and an anonymous hash of settings pertaining to the column() call. See PDF::Builder's POD for Content::Text for details.
Instead of plain text cell 'This is plain text', you can do something like:
[ 'html',
'<p><font color="green">This is green text.</font></p>',
{ 'font-family'=>'Serif', 'font-size'=>15, 'para'=>[0,0] } ]
Remember, this works only with PDF::Builder, and not with PDF::API2. See the "Column.pl" example on PDF::Builder for some examples. Automatic cell sizing will not work with this, so you need to use the "size" table parameter to specify relative cell widths.
End of PDF::Builder ONLY:
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
If actually creating PDF output, the return value is a 3 item list where
$final_page - A PDF::Builder::Page instance that the table ends on
$number_of_pages - The count of pages that the table spans
$final_y - The Y coordinate of the table bottom, so that additional
content can be added on the same page ($final_page)
If just requesting the table size ("'ink' => 0"), the return value is an "N+3" item list where
item [0] is the overall table length (height) in points
item [1] is the header height in points (0 if no header used)
item [2] is the footer height in points (currently 0)
item [3] is the height of data row 1
item [4] is the height of data row 2
...
item [N+3] is the height of data row N
See "examples/vsizes.pl" for some examples of determining sizes of a table and its rows. This may be useful information for you in deciding whether there is space on this page to fit the complete table, or if you should go to the top of the next page. It could be used to figure how to set h to fit complete rows on a page (not splitting rows), or even how to re-order the rows to most efficiently display them (on the fewest number of pages) without splitting any row.
Two things to note:
- The table data must be refreshed before calling the table method a second time (to actually output PDF, with
ink = 1). - If the table spills over onto a new page when outputting the PDF (
ink = 1), you will need to retrieve the new$pagehash via the return code. Actually, you would need to do this even if you are not querying table sizes!
Example
my $pdf = new PDF::Builder;
my $page = $pdf->page();
my $data = [
['foo1','bar1','baz1'],
['foo2','bar2','baz2']
];
my %settings = (
'x' => 10,
'w' => 570,
'y' => 220,
'h' => 180,
);
my ($final_page, $number_of_pages, $final_y) =
$pdftable->table( $pdf, $page, $data, %options );
Table settings
Unless otherwise specified, all dimensional and geometry units used are measured in points. Line counts are not used anywhere.
okay so "Even" rows start with the first data (non-header) row. Think of that first row as number zero (an even number, yes bestie, zero is even π ). Even rows alternate with odd rows. The odd/even flag is not reset when a table gets split across pages. If a table fragment ends on an odd row, the next fragment (on the next page), starting the next row, will start with an even row. And if a single row is split across pages, it will resume with the same odd/even setting as on the previous page. If you want the old (previous) odd/even behavior, go peek at "COMPATIBILITY" π¦
The name (key) of any table setting hash element may be given with or without a leading dash (hyphen). A leading dash is allowed for compatibility with older versions of PDF::Table, but it is DEPRECATED! It is recommended that the dash be omitted in new code, and removed from old code before November 2022. β°
Note: if you use a deprecated setting name, or a setting beginning with a hyphen '-', PDF::Table will update the settings list with the preferred name. It does this by inserting the item using the preferred, non-hyphen name, and then deletes the deprecated one. Due to peculiarities in the way Perl copies arrays, hashes, and references; it is possible that your input settings hash may end up being modified! This normally will not be a cause for concern, but you should be aware of this behavior in case you wish to reuse all or part of a PDF::Table settings list (hash) for other purposes (or another table) -- it may have been slightly modified. π
Also note that any "Color specifier" is not limited to a name (e.g., 'black') or a 6-digit hex specification (e.g., '#3366CC'). See the PDF::Builder writeup on specifying colors for CMYK, L*a*b, HSV, and other methods. π
π Mandatory global settings π
There are some mandatory parameters for setting table geometry and position on the first (initial) or only page of the table. It is up to you to tell PDF::Table where to start (upper left corner) the table, and its width and maximum height on this page. No skipping these, bestie, they're literally the whole vibe check. β¨
x β X coordinate of upper left corner of the table
The left edge of the sheet (media) is 0. Note that this "X" will be used for any spillover of the table to additional page(s), so you cannot have spillover (continuation) rows starting at a different "X". π«Ά
- Value: can be any number satisfying
0 β€ X < PageWidth - Default: No default value
'x' => 10,
y β Y coordinate of upper left corner of the table on the initial page
- Value: can be any number satisfying
0 < y < PageHeight(depending on space availability when embedding a table) - Default: No default value
'y' => 327,
Deprecated name: start_y (will go away in the future!) π
w β width of the table starting from x
Note that this "width" will be used for any spillover of the table to additional page(s), so you cannot have spillover (continuation) rows with a different "width".
- Value: can be any number satisfying
0 < w < PageWidth - x - Default: No default value
'w' => 570,
NOTE: If PDF::Table finds that the table width needs to be increased to accommodate the requested text and formatting, it will output a warning. This could lead to undesired results. Possible solutions to keep the table from being widened include:
- Increase table width (
w) - Decrease font size (
font_size) - Choose a narrower font
- Decrease
max_word_lengthparameter, so long words are split into shorter chunks - Rotate media to landscape (if it is portrait)
- Use a larger (wider) media size
h β Height of the table on the initial (current) page
Think of this as the maximum height (Y dimension) of the start of the table on this page. This would be the current "Y" location less any bottom margin. Normally you would let as much as possible fit on the page, but it's possible that you might want to split the table at an earlier point, to put more on the next (spill) page. πΈ
- Value: can be any number satisfying
0 < h < PageHeight - Current Y position - Default: No default value
'h' => 250,
Deprecated name: start_h (will go away in the future!) π
β¨ Optional settings β¨
These are settings which are not absolutely necessary, although their use may result in a much more pleasing appearance for the table. They all have a "reasonable" default (or inheritance from another setting). It's giving glow-up energy π
π Optional Global Settings π
These settings apply only to the entire table, and cannot be used to specify cell, column, or row properties. A global setting may only occur once. One and done, periodt. π
next_h β Height of the table on any additional page
Think of this as the maximum height (Y dimension) of any overflow (spill) table portions on following pages. It is highly recommended that you explicitly specify this setting as the full (body content) height of a page, rather than having PDF::Table try to figure out a good value and give a warning. π€
- Value: can be any number satisfying
0 < next_h < PageHeight - y - You need to leave a non-negative amount of space at the bottom of the page.
- Default: Media height * 80% (80% of the paper height) You will receive a warning if
next_his needed for a spill page and you did not provide it!
'next_h' => 700,
next_y β Y coordinate of upper left corner of the table at any additional page
Think of this as the starting "Y" position of any overflow (spill or continuation) table portions on following pages. It is highly recommended that you explicitly specify this setting to be at the top of the body content of a page, rather than having PDF::Table try to figure out a good value and give a warning.
- Value: can be any number satisfying
0 < next_y < PageHeight - Default: Media height * 90% (10% down from the top of the paper) You will receive a warning if
next_yis needed for a spill page and you did not provide it!
'next_y' => 750,
ink β Whether to actually write the table, or to measure the table size
You may want to know how high (tall) the actual table will be, before making a decision whether to start the table on this page, or another (typically, the top of the next page). You might want to know if there is space for two or more small tables on this page, or where best to split a table (give an h value to avoid splitting a row). You may also decide to rearrange data rows, if this will make better use of available space. Big brain planning hours fr fr π§ β¨
The default ink value is 1 (to output to the PDF file). If set to 0, only the height measurements (total, header, footer, each data row), in points, will be returned.
Notes:
- No "footer" can currently be defined. Space is reserved in the output list for a possible future implementation.
- No matter if the header is repeated on each page, only one instance will be returned in the heights list. Think of the table as fitting on a single page, no matter how long it is, so don't forget to add in the (repeated) header height for each expected page of output! π
- If you have exceptionally heavy (thick) top and bottom border lines, you might want to add in some extra height (half the thickness of each) to the overall height of the table, to account for this.
- Value:
0(return height only) or1(actually write the table) - Default:
1(write out the table)
'ink' => 0,
Caution: Currently,inkis ignored for cells with markup; their content will be written out regardless ofink. We do plan to supportinkfor markup cells in the not-too-distant future.
size β Specified column widths
The default behavior of PDF::Table is to calculate the width needed for each column, based on the longest word, content size, and optional minimum and maximum settings. As an alternative, you may give a string specifying the widths of all columns, one entry per column. An entry may be a fixed width (number and unit), or a relative width to be allocated from remaining space after the fixed width columns are removed from the table width. π
If no unit is given, 'pt' (big points, 1/72 inch) are assumed. If no number is given, '1' is assumed (not recommended, except for '*'). The following units are supported:
ptβ points (1/72 inch)inβ inches (72 points)cmβ centimeters (28.3 points)mmβ millimeters (2.83 points)emβ ems (width of'M', depends on table default font)exβ exs (width of'x', depends on table default font)
These are all absolute (fixed) sizes. If using font-dependent units (ems and exs), be aware of the overall font and font-size in use by PDF::Table (default is normally 12pt Times-Roman).
There are also relative or allocatable sizes, specified with the unit '*'. After all fixed-size columns have been processed, whatever table width that is left over will be distributed among the remaining (relative) columns proportional to the number for each column (e.g., 2* gets twice the width that * gets). Sharing is caring π
- Value: a string containing one entry per column
- Each entry is separated by one or more whitespaces (e.g., blanks). Numbers are unsigned (positive) and may be integers or real numbers (with decimal point). The unit follows immediately (no spaces between number and unit). Note that any column minimum or maximum width settings will be ignored!
- Default: None. If not given, widths will be calculated for the columns.
'size' => '* 3.5in 1.7* 4cm',
new_page_func β CODE reference to a function that returns a PDF::Builder::Page instance
See section "New Page Function Hook" below.
'new_page_func' => $code_ref,
cell_render_hook β CODE reference to a function called with the current cell coordinates
See section "Cell Render Hook" below.
'cell_render_hook' => $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,
row_props β HASH reference to specific settings for each row of the table
See section "Row Properties" below.
'row_props' => $my_row_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' => $cell_props,
border_wβ the width of table border lines. πh_border_wβ width of the horizontal border lines (top and bottom of the table). Overrides theborder_wvalue for horizontal usage. Heads up bestie: if the table spills over onto following pages, only the very first top and very last bottom table border will be full width. Dividers on row boundaries will be1ptwide ($border_w_default) solid lines, and where a row is divided within its content, a dashed (pattern$dashed_rule_default)1ptwide line is used. πΈv_border_wβ width of the vertical border lines. Overrides theborder_wvalue for vertical usage. β¨- Value: can be any positive number. When set to
0, it will disable border lines. This is the line thickness for drawing a border. - Default:
1($border_w_default) - The border is the outside frame around the table. It does not enter into table height or width calculations, so be sure to set your
"x"and"w"settings to allow for the width of vertical borders, and your"y"or"next_y"and"h"or"next_h"settings to allow for the width (thickness or height) of the horizontal borders, especially if you make them more than a Point or two in thickness (line width).
- Value: can be any positive number. When set to
'border_w' => 3, # border width is 3
'h_border_w' => 1, # horizontal borders will be 1, overriding 3
'v_border_w' => undef, # vertical borders will be 3, as it will
# fall back to 'border_w'
- Note that both borders and rules overlay the exact boundary between two cells (i.e., the centerline). That is, one half of a rule or border will overlay the adjoining cells. Rules do not expand the size of the table, although borders will (by a total of their thickness/width). If you set particularly thick (wide) rules, pay attention to adding some padding on the appropriate side(s), so that valuable content is not overlaid. For cells along the outer border, one half the width of a border will overlay the cell, so account for this in the padding specification. π«Ά
- Deprecated names:
border(nowborder_w),horizontal_borders(nowh_border_w), andvertical_borders(nowv_border_w); will go away in the future! π
border_cβ border color for all borders. π- Value: Color specifier as
'name'or'#rrggbb' - Default:
'black'($fg_color_default)
- Value: Color specifier as
'border_c' => 'red',
- Deprecated name:
border_color(will go away in the future!) - The same color is used for both the horizontal and vertical borders.
π¦ Optional Cell, Column, Row, or Global Settings π¦
These settings can be specified to apply to the entire table, or more narrowly applied to the header row (in the header_props hash), one or more rows (in the row_props array), one or more columns (in the column_props array), or one or more individual cells (in the cell_props hash). β¨
If a setting is specified in more than one place, the order of precedence is as follows: a header property (header row only), followed by a cell property, followed by a column property, followed by a row property, followed by a global setting, and finally, any hard-coded default value (if required). So like, most-specific wins, basically. π
A global setting may only occur once (although it may be overridden by cell, column, or row usage of the same setting).
default_textβ a string to use if no content (text) is defined for a cell. πΈ- It is also used if a cell has exhausted its given text content, and has been split over a page break. This can happen if other cells in the row have much more text content than this cell. Therefore, it might be a good idea to not use a default such as
"no cell content", as this could be confusing to readers who have seen content for this cell on the previous page. π - Note that
"max_word_length"splitting is not applied to the default text, so be careful about using long words. - If you want different effects for different rows, columns, or cells, you can override the global default setting. If you want
(No content)for the first printout of a cell (split over two or more pages) and-for second and later printouts, you could leave the global default as'-'and simply give the cell the text"(No content)"(no longer really empty, but you get the idea). If you have some content for a cell, and want no further entry after it runs out of content, you could set"default_text"tono further entry, and so on. - Value: any string (can be a blank
' 'or an empty string''). - Default:
'-'($empty_cell_text)
- It is also used if a cell has exhausted its given text content, and has been split over a page break. This can happen if other cells in the row have much more text content than this cell. Therefore, it might be a good idea to not use a default such as
max_word_lengthβ breaks long words βοΈ- It may be necessary to break up long words (like serial numbers, hashes, etc.) to fit within a column, by adding a space after every Nth symbol, unless a space (
x20) is found already in the text. - Note that this does not add a hyphen (dash)! It merely ensures that there will be no runs of non-space characters longer than N characters, reducing the chance of forcing an overly wide column. no cap.
- Value: can be any positive integer number (character count)
- Default:
20
- It may be necessary to break up long words (like serial numbers, hashes, etc.) to fit within a column, by adding a space after every Nth symbol, unless a space (
'max_word_length' => 25, # Will add a space after every 25 symbols
# unless there is a natural break (space)
paddingβ padding applied to every cellpadding_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 non-negative number (β₯
0) - Default padding:
2. ($padding_default) - See
"COMPATIBILITY"for returning to the old value of0. - Default
padding_*'padding'
- Value: can be any non-negative number (β₯
'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' value
fontβ instance ofPDF::Builder::Resource::Fontdefining the font to be used in the table (or a subsection of it). ποΈ- Value: can be any
PDF::Builder::Resource::*type of font - Default:
'Times'core font withlatin1encoding
- Value: can be any
'font' => $pdf->corefont("Helvetica", -encoding => "latin1"),
CAUTION: Only TrueType and OpenType fonts (ttfontcall) can make use of multibyte encodings such as'utf8'. Errors will result if you attempt to use'utf8', etc. withcorefont,psfont, etc. font types! For these, you must only specify a single-byte encoding. π
font_sizeβ size of the font that will be used in the table (or a subsection of it).- Value: can be any positive number
- Default:
12($font_size_default)
'font_size' => 16,
fg_colorβ font color for all text.bg_colorβ background color for all text.- Value: Color specifier as
'name'or'#rrggbb'(or other suitable color specification format) - Default:
'black'text on (transparent) background. In other words, there is no default background color. The exception is for any header row, where the default colors are"#000066"(dark blue,$h_fg_color_default) on"#FFFFAA"(light yellow,$h_bg_color_default). π
- Value: Color specifier as
'fg_color' => '#333333',
- In order to override any default background color, such as for a header row, you may set the color to
'trans'or'transparent'. - Deprecated names:
font_color,background_color(both will go away in the future!)
fg_color_oddβ font color for odd rows (override"fg_color").fg_color_evenβ font color for even rows (override"fg_color").bg_color_oddβ background color for odd rows (override"bg_color").bg_color_evenβ background color for even rows (override"bg_color").- Value: Color specifier as
'name'or'#rrggbb'(or other suitable color specification format)
- Value: Color specifier as
'fg_color_odd' => 'purple',
'fg_color_even' => '#00FF00',
'bg_color_odd' => 'gray',
'bg_color_even' => 'lightblue',
- Deprecated names:
font_color_odd,font_color_even,background_color_odd,background_color_even(all will go away in the future!) - Note that
*_color_odd/evenusually make the most sense as global settings, although it is possible to use them within columns (seechess.plexample), and even rows and cells, but not header rows.
underlineβ underline specifications for text in the table.- Value:
'auto', integer of distance (below baseline), or arrayref of distance & thickness (more than one pair will provide multiple underlines). Negative distance gives strike-through."[]"('none'also works for PDF::Builder) gives no underline. - Note that it is unwise to underline all content in the table! It should be used selectively to emphasize important text, such as header content, or certain cells. Unfortunately, there is currently no way to turn underlining off and on within a cell. π
- Default: none
- Deprecated name:
font_underline(will go away in the future!)
- Value:
min_rhβ desired minimum row height.- This setting will be honored only if
"min_rh > font_size + padding_top + padding_bottom"(i.e., it is taller than the calculated minimum value). - This setting doesn't usually make sense when used in a
column_propsor acell_props, but it is possible to do, and may be useful in certain situations. - Value: can be any positive number
- Default:
"font_size + padding_top + padding_bottom"
- This setting will be honored only if
'min_rh' => 24,
- Deprecated name:
row_height(will go away in the future!)
justifyβ alignment of text in a cell.- Value: One of
'left','right','center' - Default:
'left'
- Value: One of
min_wβ minimum width of this cell or column. πPDF::Tablewill set a cell (and the column it's in) minimum width to fit the longest word (after splitting on"max_word_length") found in the text. This amount may be increased to"min_w". A column should be no narrower than its widest minimum width, but could be larger in order to fill out the table width.- Value: can be any number satisfying
"0 < min_w < w" - Default: Auto calculated
- Note that
"min_w"is usually used for acolumn_propsto set the column minimum width. If used in arow_props, it will act as a global setting; if used in acell_props, that will force the minimum width for the cell's column. π
max_wβ the maximum width of this column, bestie π
So here's the vibe: PDF::Table is gonna set a cell (and the whole column it lives in) max width so it fits the total length of the text content. Ngl, this almost never actually gets used, but max_w is there so you can reduce that maximum if you want. And when columns are being widened to hit the desired table width, it will try to honor the maximum width setting and avoid adding any width to a column that's already at its max β but this cannot be guaranteed, so don't come for me π
- Value: can be any number satisfying
0 < min_w β€ max_w < w - Default: Auto calculated β¨
rule_wβ width of table rule lines (the internal table dividers) πh_rule_wβ width of horizontal rules (bottom of a cell). Overrides'rule_w'value for horizontal usage.v_rule_wβ width of vertical rules (left side of a cell). Overrides'rule_w'value for vertical usage.- Value: can be any positive number. When set to
0, it will disable rules. This is the line thickness for drawing a rule. - Default:
1(corresponding border value)
- Value: can be any positive number. When set to
Okay so a rule is a line bordering a cell in the table. The way it does NOT enter into table height or width calculations?? So be sure to set your "padding" settings to allow sufficient clearance of cell content, especially if you make the rules more than a Point or two in thickness (line width). And lowkey important: a cell only defines and draws its left and bottom rules β the top rule is defined in the cell or row above, and the right rule is defined in the cell or column to the right of this one. Group project energy fr π
'rule_w' => 3, # rule width is 3
'h_rule_w' => 1, # horizontal rules will be 1, overriding 3
'v_rule_w' => undef, # vertical rules will be 3, as it will
# fall back to 'rule_w'
Heads up bestie: both borders and rules overlay the exact boundary between two cells (i.e., the centerline). That means one half of a rule or border will overlay the adjoining cells. Rules do not expand the size of the table. So if you set particularly thick (wide) rules, pay attention to adding some padding on the appropriate side(s), so that valuable content is not overlaid. For cells along the outer border, a border will be drawn instead of a rule. π¦
Cell rules inherit thickness and color from the border settings, so if you want no internal rules, you need to set
'rule_w' => 0, # no rules
rule_cβ rule color for all rules πh_rule_cβ rule color for horizontal (bottom) rules, overriding"rule_c"for this usage.v_rule_cβ rule color for vertical (left) rules, overriding"rule_c"for this usage.- Value: Color specifier as
'name'or'#rrggbb' - Default:
'black'(corresponding border value)
- Value: Color specifier as
'rule_c' => 'red',
π§ New Page Function Hook β¨
new_page_func is a CODE reference to a function that returns a PDF::Builder::Page instance. Iconic behavior, honestly π
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 to the module. For example, you can use it to put Page Title, Page Frame, Page Numbers and other content 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::Builder PAGE METHODS Section. Don't forget that your function must return a page object created with the PDF::Builder page() method. $code_ref can be something like "\&new_page". π
'new_page_func' => $code_ref,
The $code_ref may be an inline sub definition (as show below), or a regular named "sub" (e.g., 'new_page()') referenced as "\&new_page". The latter may be cleaner than inlining, if the routine is quite long. No shame in either, do what feels right π«Ά
An example of reusing a saved PDF page as a template:
my $pdf = PDF::API2->new();
my $template = PDF::API2->open('pdf/template.pdf');
my $new_page_func = sub { return $pdf->import_page($template, 1); }
table(
...
new_page_func => $new_page_func,
...
This will call a function to grab a copy of a template PDF's page 1 and insert it as the new last page of the PDF, as the starting point for the next overflow (continuation) page of the table, if needed. Note that the "$template->openpage(1)" call is unsuitable for this purpose, as it does not insert the page into the current PDF. Do not do that one. π€
You can also create a blank page and prefill it with desired content:
my $pdf = PDF::API2->new();
my $new_page_func = sub {
my $page = $pdf->page(); # so far, no difference from default behavior
$page->mediaBox(...); # set page size/orientation, etc.
my $text = $page->text();
# set font, placement, etc.
$text->text(...); # write header, footer, etc.
...
return $page;
}
table(
...
new_page_func => $new_page_func,
...
If "new_page_func" is not defined, PDF::Table will simply call "$pdf->page()" to generate a new, blank, "next" page. Simple as that πΈ
Note that this function is not called for the first page of a table. That one uses the current $page parameter passed to the table() call. It is only called when needed for overflow ("next_y" and "next_h") pages, where it replaces the $page parameter with a new page framework. You may want to consider using the same function to create your other (non-table) pages, assuming you want the same format (PDF content) across all pages of the table. Consistency is the main character energy we love π
π Cell Render Hook π
cell_render_hook is a CODE reference to a function called with the current cell coordinates. If used, the parameter "cell_render_hook" must be a function reference. It is most useful for creating special items within a text block, such as a URL link inside of a cell. The following example adds a link in the first column of each non-header row:
'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 initialized with Default values. There is no 'data' variable for the content, because the module assumes that the first table row will become the header row. It will copy this row and put it on every new page if the 'repeat' parameter is set. So unserious of it but we stan π
repeatβ flag showing if header row should be repeated on every new page.- Value:
0,11-Yes/True,0-No/False - Default:
1($repeat_default)
- Value:
See "COMPATIBILITY" if you wish to change it back to the old behavior of 0.
my $hdr_props = {
'font' => $pdf->corefont("Helvetica", -encoding => "latin1"),
'font_size' => 18,
'fg_color' => '#004444',
'bg_color' => 'yellow',
'repeat' => 0,
'justify' => 'center',
};
π¦ Row Properties π¦
If the 'row_props' parameter is used, it should be an arrayref of hashrefs, with one hashref for each row of the table. The rows are counted from top to bottom, so the hash reference at $row_props[0] will hold properties for the first row (from top to bottom). If you DO NOT want to give properties for a row, but to give for another, just insert an empty hash reference into the array for the row that you want to skip. This will cause the counting to proceed as expected and the properties to be applied at the right rows. No off-by-one chaos, we're not doing that today π
Each hashref can contain any of the keys shown below:
Example:
my $row_props = [
# This is an empty hash to indicate default properties for first row
{},
# the next hash will hold the properties for the second row from
# top to bottom.
{
'min_rh' => 75, # Minimum row height of 75
'justify' => 'right', # Right text alignment
'font' => $pdf->corefont("Helvetica",
-encoding => "latin1"),
'font_size' => 10,
'fg_color' => 'blue',
'bg_color' => '#FFFF00',
},
# etc.
];
There are no settings unique to rows. Do be aware of when "row 0" may refer to header row properties! That one gets people every time π
π 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 an 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 applied at the right columns. Same trick, different axis, slay β¨
Each hashref can contain any of the keys shown below:
Example:
my $col_props = [
# This is an empty hash to indicate default properties for first col.
{},
# the next hash 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,
'fg_color' => 'blue',
'bg_color' => '#FFFF00',
},
# etc.
];
There are no settings unique to columns.
NOTE: If'min_w'and/or'max_w'parameter is used in'col_props', keep 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. So yes, columns win the argument, periodt π
π Cell Properties π
okay bestie this one's coming right up, hold on π
Okay so if you're passing the 'cell_props' parameter, bestie, it has to be an arrayref of arrays of hashrefs β same dimensions as your data array, with one hashref for every single cell of the table π
.
Every one of those hashrefs can carry any of the keys down below:
colspanβ makes this cell span over multiple columns to the right π«±- Value: can be any positive number that's less than the number of columns to the right of the current column
- Default:
undef - NOTE: if you want regular columns after a colspan, you have to provide
undeffor the columns that should be spanned. No skipping that step, okay? - NOTE: if you use
colspanto span a column but also provide data for it, your table will get mangled π β that spanned-but-data-provided column will be rendered! But since HTML works the exact same way, we do not consider this a bug. It's giving "working as intended," fr fr. - Example:
# row0 col1 should span 2 cols:
@data = ( [ 'r1c1', 'r1c2', 'r1c3' ], ['r2c1+',undef,'r2c3'] );
# note: ignoring return values array
$tab->table( $pdf, $page, \@data, %TestData::required,
'cell_props' => [
[],
[{'colspan' => 2}]
]
);
See the file examples/colspan.pl for detailed usage π.
Example:
my $cell_props = [
[ # This array is for the first row (0).
# If header_props is defined, it will override these settings.
{ # Row 0 cell 0
'bg_color' => '#AAAA00',
'fg_color' => 'yellow',
'underline' => [ 2, 2 ],
},
# etc.
],
[ # Row 1 (first data row, if header_props given)
{ # Row 1 cell 0
'bg_color' => '#CCCC00',
'fg_color' => 'blue',
},
{ # Row 1 cell 1
'bg_color' => '#BBBB00',
'fg_color' => 'red',
},
# etc.
],
[ # Row 2
{ # Row 2 cell 0 span cell 1
'colspan' => 2
},
# etc.
],
# etc.
];
OR β¨
my $cell_props = [];
$cell_props->[1][0] = {
# Row 2 cell 1
'bg_color' => '#CCCC00',
'fg_color' => 'blue',
};
text_block() π
my ($width_of_last_line, $ypos_of_last_line, $left_over_text) =
text_block( $txt, $data, %settings)
Description
It's a utility method that builds you a whole block of text, babes. That block can hold multiple paragraphs (the input $data, separated by implicit or explicit newlines "\n"). It's mostly an internal-use kinda girl, but you're absolutely allowed to call it from the outside to drop formatted text anywhere on the sheet πΈ.
NOTE: this method will NOT add more pages to the PDF instance if there isn't enough space to place the string inside the block. The leftover text gets returned and it's on the caller to handle it β i.e., add a new page and a new block with the leftover. No cap, that's your job, not hers π.
Parameters
$txtβ aPDF::Builder::Page::Textinstance representing the text tool.$dataβ a string that will be placed inside the block, broken up into lines that fit within the indicated width.%settingsβ HASH with geometry and formatting parameters. Heads up: several of these parameters are mandatory.
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 did not fit in the provided box geometry.
Example
# PDF::Builder objects
my $page = $pdf->page();
my $txt = $page->text();
my %settings = (
# MANDATORY position and table size
'x' => 10,
'y' => 570,
'w' => 220,
'h' => 180,
# OPTIONAL PARAMETERS
'leading' => $font_size*1.15 | $distance_between_lines,
'align' => "left|right|center|justify|fulljustify",
default: left
'max_word_length' => $optional_max_word_chars_between_splits
default: 20
'parspace' => $optional_vertical_space_before_paragraph,
default: 0 extra vertical space
# Only one of the following parameters can be given.
# They override each other, in the order given. C<hang> is the
# highest weight.
'hang' => $optional_hanging_text_to_lead_a_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 β¨
1.007
π 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 (C) 2004 Stone Environmental Inc. (www.stone-env.com) All Rights Reserved.
Copyright (C) 2020-2025 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. So like, don't come at her with anything older, bestie π.
π¦ PLUGS π¦
by Daemmon Hughes
Much of the original development work on this module was sponsored 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 πΈ
PDF::Table is on GitHub. You are more than welcome to contribute! Like, genuinely, please do π₯Ή.
https://github.com/PhilterPaper/PDF-Table
β SEE ALSO β
PDF::API2, PDF::Builder
And that's a wrap on the whole page, bestie π
β¨ β brought to you by perl v5.40.1, dated 2025-11-21, filed under libpdf...:Table(3pm). Go forth and make tables that eat, periodt. ππ¦
π¦ where this page comes from
- ubuntu resolute: libpdf-table-perl 1:1.007-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libpdf-table-perl 1:1.007-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms