PDF-Table-1.005/0000755000000000000000000000000014365336123011661 5ustar rootrootPDF-Table-1.005/INFO/0000755000000000000000000000000014365336755012427 5ustar rootrootPDF-Table-1.005/INFO/Deprecated0000644000000000000000000001017414365336064014406 0ustar rootrootA list of DEPRECATED names and interfaces in PDF::Table. In most cases, these are names that have been changed for simplification and consistency. The old names will not be kept around forever, and will be removed AT LEAST two (2) years after notice is given here. Where possible, when using the old names, a warning notice will be given in a release at least six (6) months before the old name is removed from the code. It would behoove you to make a quick check of "INFO/Deprecated" at each release, so that you don't end up getting caught flat-footed by the removal of a name, and have to scurry to update your code! Anything added to the deprecated list should also show up in "Changes", giving you a "heads up". The POD, examples, and t-tests have been updated to use the new forms. There should not be any use of deprecated setting names anywhere. In order of scheduled removal date: font_color entry in global args, *_prop properties This has been renamed to 'fg_color', as it is the text (foreground) color. 'font_color' is scheduled to be removed after November 2022. font_color_odd entry in global args, *_prop properties This has been renamed to 'fg_color_odd', as it is the text (foreground) color (for odd-numbered rows). 'font_color_odd' is scheduled to be removed after November 2022. font_color_even entry in global args, *_prop properties This has been renamed to 'fg_color_even', as it is the text (foreground) color (for even-numbered rows). 'font_color_even' is scheduled to be removed after November 2022. background_color entry in global args, *_prop properties This has been renamed to 'bg_color', as it is the cell (background) color (for all rows). Note that 'bg_color' was already permitted in header_props. 'background_color' is scheduled to be removed after November 2022. background_color_odd entry in global args, *_prop properties This has been renamed to 'bg_color_odd', as it is the cell (background) color (for odd-numbered rows). 'background_color_odd' is scheduled to be removed after November 2022. background_color_even entry in global args, *_prop properties This has been renamed to 'bg_color_even', as it is the cell (background) color (for even-numbered rows). 'background_color_even' is scheduled to be removed after November 2022. font_underline entry in global args, *_prop properties This has been renamed to just 'underline', as it really isn't related to the font in use. 'font_underline' is scheduled to be removed after November 2022. start_y entry in global args, *_prop properties This has been renamed to just 'y'. 'start_y' is scheduled to be removed after November 2022. start_h entry in global args, *_prop properties This has been renamed to just 'h'. 'start_h' is scheduled to be removed after November 2022. lead entry in global args, *_prop properties This has been renamed to 'leading' (the printer's term), pronounced 'ledding'. 'lead' is scheduled to be removed after November 2022. row_height entry in global args, *_prop properties This has been renamed to 'min_rh'. 'row_height' is scheduled to be removed after November 2022. border entry in global args This has been renamed to 'border_w'. 'border' is scheduled to be removed after November 2022. horizontal_borders entry in global args This has been renamed to 'h_border_w'. 'horizontal_borders' is scheduled to be removed after November 2022. vertical_borders entry in global args This has been renamed to 'v_border_w'. 'vertical_borders' is scheduled to be removed after November 2022. border_color entry in global args This has been renamed to 'border_c'. 'border_color' is scheduled to be removed after November 2022. leading '-' on setting names (hash key, e.g., '-next_h') will no longer be allowed after November 2022. Please update your programs to no longer use setting names with a leading dash or hyphen. *** If I have missed any deprecated interfaces, please let me know! *** ======= Deprecated items that have already been removed ===================== (first entry expected December, 2022 or later) PDF-Table-1.005/INFO/SPONSORS0000644000000000000000000000241014365336064013626 0ustar rootrootS P O N S O R S H I P S We would like to thank the following individuals and organizations for sponsoring new features in PDF::Table: Amtivo Group, Kings Hill, Kent, England -- FontManager and Column with MD and HTML markup. Also support added to PDF::Table to use these new features with PDF::Builder. If you would like to see new features for PDF::Table on an accelerated schedule, please feel free to contact us (via catskilltech.com Contact page) to discuss scope, schedule, and cost. Please keep in mind that such a sponsorship does NOT create any exclusive intellectual property belonging to the sponsor! Rather, all results go into the public code repository for all to use immediately. You simply get the features sooner, and your name engraved on a plaque in this file (OK, just listed above). If you wish to purchase new features for PDF::Table (and/or PDF::Builder or any other open source product we provide) that are NOT released to the public, that is, are your exclusive intellectual property, feel free to contact us for a discussion of scope, schedule, and cost. Note that the cost will be higher, as the world doesn't get to share in the benefits of this work! Please consider a sponsorship for work that will be released to the public, and benefit it. PDF-Table-1.005/INFO/Changes_20190000644000000000000000000002216614365336064014375 0ustar rootroot(see Changes for later changes) Version 0.11.0 Colspan feature by domm Version 0.10.0 Introduces underlined text in cells Version 0.9.13 Fixed issue #33 - Desislav Kamenov Version 0.9.12 - hotfix for failing tests - Desislav Kamenov Version 0.9.11 Changes by contributors on GitHub - Keith Carangelo, Mohammad S Anwar 3264342 Added cell_render_hook subroutine to create hyperlinks 0fb2e57 Fixed broken link to Rick Measham's tutorial. 8361ec3 Fixed new_page_func valid setting 38610ec Header alignment default should be column alignment e3ec184 Added parameter checking in the method table(). - Added unit test t/table.t script. a73e67f Proposed fix to the CPANTS error as below: - Added standard unit test for MANIFEST file (t/manifest.t). - Removed MYMETA.json, MYMETA.yml and Makefile (auto generated files) - Added entry "t/manifest.t" to the MANIFEST file. - Updated MANIFEST.SKIP file. Version 0.9.10 Changes by contributors on GitHub - azawawi, joenio 6fab323 Modernize hashbang #! to be more perlbrew friendly 58c36df Add relative link to Changes file efaf173 Simple installation/development commands cfbcf48 More README.md simplification a7889bc Fix README.md 43c2182 Fix warning: Useless use of greediness modifier '?' in regex db4bc44 Fix #17, page parameter should be optional f93ed16 "utf8" pragma solves issue with characters rendered wrong e69524e fix script that test issue #15 5d5628f avoid warning about use of greediness modifier Version 0.9.8/9 Added MANIFEST.SKIP and fixed a broken build with 0.9.8 Added some utility methods to new() Version 0.9.7 - for a detailed log and changed files visit GitHub Added a few initialisation methods to the help new() and later on accommodate static initialisation within table() textblock() Repackaged to fix Issue #16 Version 0.9.7 - for a detailed log and changed files visit GitHub Reviewed and updated README Huge POD rewrite Adding a small script that generates HTML from POD and applies CSS from CPAN. Useful for reviewing the POD before release. Added a test for POD validation Added an example file that can test GitHub Issues #8, #9, #10 GitHub [Issue #9] [Issue #10] Fixed cell_props applied to a different row when 'Repeat Headers' is enabled Introduced column_numbers variable to avoid using $record in a broader scope. Further improvement needed. Header row height is copied to each new page when 'Repeat Headers' is enabled Fixed messing up row height when repeat headers is enabled due to access by array index vs shift/unshift Fixed row height for rows with text blocks Headers_props variable has been wrongly initialised with 0 causing a copy of the first data row even when header props are not passed as parameter Added initialisation of header props justify param so that column and cell properties are not affecting the default value. Fixed an issue with messing up row properties when repeating the header row on each page. Examples have been formatted. One new example added (header.pl) for demonstrating how header row can be added to multiple pages. No need to export variables. Added one more test. Removed pad_w and pad_h local variable as useless Fixed typo causing a bug with row_height param. Added example file for row_height. To be used for writing a test. Added POD for row_height param Row counting should not be skipped if it is first row. Added one more test(duplicates existing) but only to have base. Extracted PDF::API2 Mock as a separate package. Created New test with the very basics. Create a new package that will hold predefined data for tests so it can be reused. Fixed a variable that masks earlier declaration. Fixed Issue #4 - Row height is calculated correctly depending on font size. Some variables are renamed to more meaningful. Row counting is done in a new way with single counter that is used for column and cell props retrieval. Row height is now calculated for each row based on maximum font size from all cells. Refactored some variable names and unified row counting during column size calculation phase. Fixed doc details in POD Cosmetic changes Decreased indent and reduced if body. For easier review, diff with whitespace changes disabled. Added github url in readme Version 0.9.6 ---------------------------- Fixed typo in POD. Closes #71816 Thanks to Gregor Herrmann Small code refactoring. Added patch for infinite loop fix. Closes #77376 Thanks to John Bazik Added patch for header justification. Closes #77566 Thanks to James Lance Added horizontal_borders, vertical_borders params to table(). Closes #79883 Thanks to Eric Johnson Version 0.9.5 - 18.Oct.2011 ---------------------------- MANIFEST was missing sample pdf file. Accidentally left alternative code for infinite loop fix commented out. Fixed. Added a test for that. Version 0.9.4 - 17.Oct.2011 ---------------------------- Don't bump row count when row spans a page. Closes #67401. Fixed bug: don't call text_block if record width is exactly cell width. Fixed bug in text_block: bottom is (top - height), not (baseline - height). Example script typo fixed. Closes #55133. Don't set up strokes when border is 0. Apparently breaks Acrobat. Closes #40705 and #55137. Changed print warnings to carp. Closes #38007. Added center justification for columns and cells. Tests, too. Closes #37924. Fixed infinite loop caused by uninitialized $2. Thanks to Petri Kaurinkoski. Closes #34017. Fixed perl warning if $col_prop->{min_w} is undef. Thanks to Matthias Pitzl (NEPOS). Closes #30720. Fixed default header background color bug, closes #28542. Added mock PDF::API2 packages to test script and added tests. Improve column width calculations so wider content gets wider columns. Added column width test. Thanks to Barrie Slaymaker (RBS). Closes #26158. Version 0.9.3 - 27.12.2006 ---------------------------- Added backward compatibility and now again params with '-' front are supported. Both params with '-'and without are valid and can be even mixed together. I excuse for changing the interface before. Added cell_props parameter which can define properties for a single cell as specified by user. Thanks for cell_props patch to Bodo Bauer. Removed Version requirement of Perl 5.8.7 and only version to 5.6.0 is required. Thanks to Jonas Pasche for reporting it. Updated examples/sample1.pl file to try the capabilities of the module immediately after download. Documentation Update. Fixed bug with interpreting \n as special char but not as newline. Thanks to Jonas Pasche for reporting it. (reminder: text with \n must be enclosed in double quotes i.e. "text\nnewline" ) Fixed documentation inacuracy for text_block(). It is called as $pdftable->text_block() of course. Thanks to Jonas Pasche for reporting it. Fixed bug with first_line overlapping with former paragraph last line. Thanks to Jonas Pasche for reporting it and contributing a patch. Version 0.9.2 - 02.Oct.2006 ---------------------------- Fixed bug with 'col_props->bg_color' overriding 'header_props->bg_color' Thanks to Giulio Di Giuliomaria Fixed some documentation inacuracys. Added some new documentation. 'column_props->width' parameter changed to 'min_w' Added example script to instantly test the module when downloaded. See 'examples' into the tar.gz archive. Version 0.9.1 - 18.Sep.2006 ---------------------------- Removed Debug Message "Created New Page" Fixed bug with not working header row bg_color parameter Thanks to Bodo Bauer for submiting the patch. Version 0.9 - 14.Sep.2006 ---------------------------- Fixed 'fontsize' bug at line 234 to font_size and parameter is working correctly Changed all parameters not to start with '-' So now '-start_h' becomes only 'start_h' Changed default font encoding form latin1 to UTF8 Added Default Values for next_h next_y parameters Added Minimum value check for x y start_h start_y Optimization for min row height calculations Added 'new_page_func parameter'. This is should be a reference to function which is called every time when a new page needs to be created so the table can span.See online manual for more info how to use it. Added Check if any text in sub text_block before splitting the parameter. Fixed bug with infinite loop when spanning to a new page. Splitting long words to parts because of breaking table cels Parameter in text_block() 'parspace' space before block start (paragraph). So the first line will start and height $ybase $parspace. So is every next paragraph into the block. Undocumented Parameter in text_block() 'indent' indent of every line Undocumented Parameter in text_block() 'flindent' indent of first line Undocumented Parameter in text_block() 'fpindent' indent of first paragraph The Above parameters are excluding each other in the following order: parspace,flindent,fpindent,indent The one that is found first and has valid value is being used Added Header Row support with repeat on every new page and different layout than the other rows Parameter 'w' for table is not optional any more (could change) Changed table width calculation and now module tries to use as much space as it is given but not more than it. Default values for many options Better source formatting Fixed incorrect y position returned from text_block() Others that i dont remember. PDF-Table-1.005/INFO/Table.html0000644000000000000000000020103714365336064014340 0ustar rootrootPDF::Table

NAME

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

SYNOPSIS

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.

 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();
...

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:

1. The table data must be refreshed before calling the table method a second time (to actually output PDF, with ink = 1).

2. If the table spills over onto a new page when outputting the PDF (ink = 1), you will need to retrieve the new $page hash 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.

"Even" rows start with the first data (non-header) row. Think of this first row as number zero (an even number). Even rows alternate with odd rows. The odd/even flag is not reset when a table is 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. If a row is split across pages, it will resume with the same odd/even setting as on the previous page. If you desire to have the old (previous) odd/even behavior, see "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 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.

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.

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:

    1) Increase table width (w)
    2) Decrease font size (font_size)
    3) Choose a narrower font
    4) Decrease "max_word_length" parameter, so long words are split into
        shorter chunks
    5) Rotate media to landscape (if it is portrait)
    6) 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).

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.

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_h is 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_y is 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.

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:

1. No "footer" can currently be defined. Space is reserved in the output list for a possible future implementation.

2. 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!

3. 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) or 1 (actually write the table)

Default: 1 (write out the table)

    'ink'  => 0,

Caution: Currently, ink is ignored for cells with markup; their content will be written out regardless of ink. We do plan to support ink for 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).

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 - Width of table border lines.
h_border_w - Width of horizontal border lines (top and bottom of the table). Overrides 'border_w' value for horizontal usage. Note that 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 be 1pt wide ($border_w_default) solid lines, and where a row is divided within its content, a dashed (pattern $dashed_rule_default) 1pt wide line is used.
v_border_w - Width of vertical border lines. Overrides 'border_w' value 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).

    '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 (now 'border_w'), horizontal_borders (now 'h_border_w'), and vertical_borders (now 'v_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)

    '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 header_props hash), one or more rows (in row_props array), one or more columns (in column_props array), or one or more individual cells (in 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).

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 to no further entry, and so on.

Value: any string (can be a blank ' ' or an empty string '').

Default: '-' ($empty_cell_text)

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.

Value: can be any positive integer number (character count)

Default: 20

    'max_word_length' => 25,    # Will add a space after every 25 symbols
                                # unless there is a natural break (space)
padding - Padding applied to every cell
padding_top - top cell padding, overrides 'padding'
padding_right - right cell padding, overrides 'padding'
padding_left - left cell padding, overrides 'padding'
padding_bottom - bottom padding, overrides 'padding'

Value: can be any non-negative number (≥ 0)

Default padding: 2. ($padding_default)

See "COMPATIBILITY" for returning to the old value of 0.

Default padding_* 'padding'

    'padding'        => 5,     # all sides cell padding
    'padding_top'    => 8,     # top cell padding, overrides 'padding'
    'padding_right'  => 6,     # right cell padding, overrides 'padding'
    'padding_left'   => 2,     # left cell padding, overrides 'padding'
    'padding_bottom' => undef, # bottom padding will be 5, as it will fall
                               # back to 'padding' value
font - instance of PDF::Builder::Resource::Font defining 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 with latin1 encoding

    'font' => $pdf->corefont("Helvetica", -encoding => "latin1"),

CAUTION: Only TrueType and OpenType fonts (ttfont call) can make use of multibyte encodings such as 'utf8'. Errors will result if you attempt to use 'utf8', etc. with corefont, 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).

    'fg_color'      => '#333333',

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)

    '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/even usually make the most sense as global settings, although it is possible to use them within columns (see chess.pl example), 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!)

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_props or a cell_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

    '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'

min_w - Minimum width of this cell or column.

PDF::Table will 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 a column_props to set the column minimum width. If used in a row_props, it will act as a global setting; if used in a cell_props, that will force the minimum width for the cell's column.

max_w - Maximum width of this column.

PDF::Table will set a cell (and the column it's in) maximum width to fit the total length of the text content. This will seldom be actually used, but max_w may be used to reduce this maximum. When columns are being widened in order to meet the desired table width, it will try to honor the maximum width setting and avoid adding any width to a column already at its maximum width (but this cannot be guaranteed).

Value: can be any number satisfying 0 < min_w ≤ max_w < w

Default: Auto calculated

rule_w - Width of table rule lines (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)

A rule is a line bordering a cell in the table. While it does not enter into table height or width calculations, 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). Note that 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.

    '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'

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. 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)

    'rule_c' => 'red',

New Page Function Hook

new_page_func is a CODE reference to a function that returns a PDF::Builder::Page instance.

If used, the parameter 'new_page_func' must be a function reference which, when executed, will create a new page and will return the object 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.

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.

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.

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.

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.

repeat - Flag showing if header row should be repeated on every new page.

Value: 0,1 1-Yes/True, 0-No/False

Default: 1 ($repeat_default)

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.

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!

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.

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.

Cell Properties

If the 'cell_props' parameter is used, it should be an arrayref with arrays of hashrefs (of the same dimension as the data array) with one hashref for each cell of the table.

Each hashref can contain any of the keys shown below:

colspan - Span this cell over multiple columns to the right.

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

Default: undef

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

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

Example:

    # 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

Utility method to create a block of text. The block may contain multiple paragraphs (input $data separated by implicit or explicit newlines \n). It is mainly used internally, but you can use it from outside for placing formatted text anywhere on the sheet.

NOTE: This method will NOT add more pages to the PDF instance if the space is not enough to place the string inside the block. Leftover text will be returned and has to be handled by the caller - i.e., add a new page and a new block with the leftover.

Parameters
    $txt  - a PDF::Builder::Page::Text instance 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. Note that
                several 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.005

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-2023 by Phil M Perry.

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.7 or, at your option, any later version of Perl 5 you may have available. Note that Perl 5.10 is the minimum supported level.

PLUGS

by Daemmon Hughes

Much of the 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!

https://github.com/PhilterPaper/PDF-Table

SEE ALSO

PDF::API2, PDF::Builder

PDF-Table-1.005/.perlcriticrc0000644000000000000000000000013712777770572014367 0ustar rootrootseverity = 5 [Perl::Critic::Policy::BuiltinFunctions::ProhibitStringyEval] allow_includes = 1 PDF-Table-1.005/examples/0000755000000000000000000000000014365336755013512 5ustar rootrootPDF-Table-1.005/examples/PDFpref0000644000000000000000000000012014365336065014706 0ustar rootrootPDF::Builder # choice for testing. must be in same directory as running program PDF-Table-1.005/examples/size.pl0000644000000000000000000002242114365336065015014 0ustar rootroot#!/usr/bin/env perl use warnings; use strict; use diagnostics; use PDF::Table; =pod This example file gives an overview of the functionality of the 'size' parameter for PDF::Table. =cut # Please use TABSTOP=4 for best view # ------------- # -A or -B on command line to select preferred library (if available) # then look for PDFpref file and read A or B forms my ($PDFpref, $rcA, $rcB); # which is available? my $prefFile = "./PDFpref"; my $prefix = 0; # by default, do not add a prefix to the output name my $prefDefault = "B"; # PDF::Builder default if no prefFile, or both installed if (@ARGV) { # A or -A argument: set PDFpref to A else B if ($ARGV[0] =~ m/^-?([AB])/i) { $PDFpref = uc($1); $prefix = 1; } else { print STDERR "Unknown command line flag $ARGV[0] ignored.\n"; } } if (!defined $PDFpref) { if (-f $prefFile && -r $prefFile) { open my $FH, '<', $prefFile or die "error opening $prefFile: $!\n"; $PDFpref = <$FH>; if ($PDFpref =~ m/^A/i) { # something starting with A, assume want PDF::API2 $PDFpref = 'A'; } elsif ($PDFpref =~ m/^B/i) { # something starting with B, assume want PDF::Builder $PDFpref = 'B'; } elsif ($PDFpref =~ m/^PDF:{1,2}A/i) { # something starting with PDF:A or PDF::A, assume want PDF::API2 $PDFpref = 'A'; } elsif ($PDFpref =~ m/^PDF:{1,2}B/i) { # something starting with PDF:B or PDF::B, assume want PDF::Builder $PDFpref = 'B'; } else { print STDERR "Don't see A... or B..., default to $prefDefault\n"; $PDFpref = $prefDefault; } close $FH; } else { # no preference expressed, default to PDF::Builder print STDERR "No preference file found, so default to $prefDefault\n"; $PDFpref = $prefDefault; } } foreach (1 .. 2) { if ($PDFpref eq 'A') { # A(PI2) preferred $rcA = eval { require PDF::API2; 1; }; if (!defined $rcA) { $rcA = 0; } # else is 1; if ($rcA) { $rcB = 0; last; } $PDFpref = 'B'; } if ($PDFpref eq 'B') { # B(uilder) preferred $rcB = eval { require PDF::Builder; 1; }; if (!defined $rcB) { $rcB = 0; } # else is 1; if ($rcB) { $rcA = 0; last; } $PDFpref = 'A'; } } if (!$rcA && !$rcB) { die "Neither PDF::API2 nor PDF::Builder is installed!\n"; } # ------------- our $VERSION = '1.005'; # VERSION our $LAST_UPDATE = '1.004'; # manually update whenever code is changed my $outfile = $0; if ($outfile =~ m#[\\/]([^\\/]+)$#) { $outfile = $1; } $outfile =~ s/\.pl$/.pdf/; # command line -A or -B adds A_ or B_ to outfile if ($prefix) { $outfile = $PDFpref . "_" . $outfile; } my $pdftable = PDF::Table->new(); # ------------- my $pdf; if ($rcA) { print STDERR "Using PDF::API2 library\n"; $pdf = PDF::API2->new( -file => $outfile ); } else { print STDERR "Using PDF::Builder library\n"; $pdf = PDF::Builder->new( -file => $outfile, -compress => 'none' ); } # ------------- my $page = $pdf->page(); $pdf->mediabox('A4'); my $txt = $page->text(); my $font = $pdf->corefont("Times-Roman"); $txt->font($font, 12); # A4 as defined by PDF::API2 is h=842 w=545 for portrait # some data to lay out. emphasis is on size string. my $some_dataX = [ # header shows size entries [ '*', '2.1cm', '27mm', '5em', '.99in', '7.5ex', '1.9*' ], [ '1 Lorem ipsum dolor', 'Donec odio neque, fauci bus vel', '1 conse quat quis, tinci dunt vel, felis.', '1 Lorem ipsum dolor', 'Donec odio neque, fauci bus vel', '1 conse quat quis, tinci dunt vel, felis.', '1 Lorem ipsum dolor', ], [ 'Nulla euis mod sem eget neque.', 'Donec odio neque', 'Sed eu velit.', 'Nulla euis mod sem eget neque.', 'Donec odio neque', 'Sed eu velit.', 'Nulla euis mod sem eget neque.', ], ]; my $some_data; my $yCur = 800; my $size = '* 2.1cm 27mm 5em .99in 7.5ex 1.9*'; my $title = "Normal operation"; for (my $row = 0; $row < 3; $row++) { $some_data->[$row] = $some_dataX->[$row]; } makeTable($pdftable, $pdf, $page, $txt, $some_data, $yCur, $size, $title); # do some others where 'size' has to be adjusted, etc. $yCur -= 250; $size = '50pt 50 50 50 50pt 50 *'; $title = "implicit and explicit pt widths"; for (my $row = 0; $row < 3; $row++) { $some_data->[$row] = $some_dataX->[$row]; } makeTable($pdftable, $pdf, $page, $txt, $some_data, $yCur, $size, $title); $yCur -= 250; $size = '60pt 60 60 60 60pt 60 60pt'; $title = "all explicit widths, falls short of overall width (reduce overall)"; for (my $row = 0; $row < 3; $row++) { $some_data->[$row] = $some_dataX->[$row]; } makeTable($pdftable, $pdf, $page, $txt, $some_data, $yCur, $size, $title); # new page $page = $pdf->page(); $pdf->mediabox('A4'); $txt = $page->text(); $font = $pdf->corefont("Times-Roman"); $txt->font($font, 12); $yCur = 800; #$yCur -= 250; $size = '75pt 75 75 75 75pt 75 75pt'; $title = "all explicit widths, too wide (increase width)"; for (my $row = 0; $row < 3; $row++) { $some_data->[$row] = $some_dataX->[$row]; } makeTable($pdftable, $pdf, $page, $txt, $some_data, $yCur, $size, $title); #$yCur = 800; $yCur -= 250; $size = '* * * * * * *'; $title = "evenly allocated widths"; for (my $row = 0; $row < 3; $row++) { $some_data->[$row] = $some_dataX->[$row]; } makeTable($pdftable, $pdf, $page, $txt, $some_data, $yCur, $size, $title); #$yCur = 800; $yCur -= 250; $size = '* 2* 3* 1.5* .95* * 2*'; $title = "unevenly allocated widths"; for (my $row = 0; $row < 3; $row++) { $some_data->[$row] = $some_dataX->[$row]; } makeTable($pdftable, $pdf, $page, $txt, $some_data, $yCur, $size, $title); # new page $page = $pdf->page(); $pdf->mediabox('A4'); $txt = $page->text(); $font = $pdf->corefont("Times-Roman"); $txt->font($font, 12); # recoverable errors (warnings) $yCur = 800; #$yCur -= 250; $size = '82.42 82.42 82.42 82.42 82.42 82.42 *'; $title = "insufficient space left for allocated column (widen table)"; for (my $row = 0; $row < 3; $row++) { $some_data->[$row] = $some_dataX->[$row]; } makeTable($pdftable, $pdf, $page, $txt, $some_data, $yCur, $size, $title); #$yCur = 800; $yCur -= 250; $size = '-75pt 37zg 3.4.2in 100 in 2CM *'; # -75 number whole entry not recognized (use *) # zg unit not recognized, use mm instead # 3.4.2 number not recognized, use 1 instead # 100 and in recognized as two columns (100pt and 1in) # CM OK (treat as cm) $title = "various number and unit errors to ignore"; for (my $row = 0; $row < 3; $row++) { $some_data->[$row] = $some_dataX->[$row]; } makeTable($pdftable, $pdf, $page, $txt, $some_data, $yCur, $size, $title); if (0) { # fatal errors #$yCur = 800; $yCur -= 250; # one of possibly several cases if (1) { $size = ' '; $title = "no column width elements in size string"; } for (my $row = 0; $row < 3; $row++) { $some_data->[$row] = $some_dataX->[$row]; } makeTable($pdftable, $pdf, $page, $txt, $some_data, $yCur, $size, $title); } $pdf->save(); # ------------------------------------- # build the table layout. like the data (text), the various properties and # settings could be pulled out of line. sub makeTable { my ($pdftable, $pdf, $page, $txt, $some_data, $yCur, $size, $title) = @_; print "--------- $title -------------\n"; $txt->translate(10, $yCur+20); $txt->text($title); my @size_vec = split /\s+/, $size; $some_data->[0] = \@size_vec; $pdftable->table( # required params $pdf, $page, $some_data, # Geometry of the document x => 50, w => 495, # width: most of an A4 page y => $yCur, next_y => 800, h => 250, # reduce to force overflow to new page next_h => 250, # some optional params for fancy results size => $size, bg_color_odd => 'lightblue', bg_color_even => "#EEEEAA", # using default font (Times-Roman 12pt) header_props => { bg_color => "#F0AAAA", font => $pdf->corefont( "Helvetica", -encoding => "latin1" ), font_size => 10, fg_color => "#006600", repeat => 1 # default # note that col 2 inherits RJ from column_props setting }, column_props => [ {}, # no properties for the first column { # column 2 overrides: force wider, # larger font, right-justified, own bg. min_w => 250, # ignored justify => "right", font => $pdf->corefont( "Times-Roman", -encoding => "latin1" ), font_size => 10, fg_color => 'white', bg_color => '#8CA6C5', }, # column 3 no overrides ], cell_props => [ [ # This is the first(header) row of the table and here # %header_prop has priority, so no effect with these settings { bg_color => '#000000', fg_color => 'blue', }, # etc. ], [ # Row 2 (first data row) { # Row 2 col 1 bg_color => '#000000', fg_color => 'white', }, { # Row 2 col 2 bg_color => '#AAAA00', fg_color => 'red', }, { # Row 2 col 3 bg_color => '#FFFFFF', fg_color => 'green', }, # etc. ], [ # Row 3 (second data row) { # Row 3 cell 1 bg_color => '#AAAAAA', fg_color => 'blue', }, # etc. rest of columns are normal ], # etc. rest of rows are normal ], ); # end of table() call return; } # end of makeTable() PDF-Table-1.005/examples/chess.pl0000644000000000000000000001745514365336065015162 0ustar rootroot#!/usr/bin/env perl use warnings; use strict; use diagnostics; use PDF::Table; ######################################################## # NOTE: latest version of PDF::API2 (2.043) seems to # have some incompatible font changes, resulting in # $min_width being twice what it is in PDF::Builder, and # resulting in the chessboard being far too big. This # is being investigated. ######################################################## #my $mode = 'text'; # use letters from Helvetica my $mode = 'graphics'; # use Unicode chess glyphs from DejaVu-Sans #my $mode = 'images'; # TBD use of images # Demonstrate a chessboard using even and odd row bg and fg color definitions # on a per-column ($column_props) basis. # Gray bg shows move of White Knight to capture Black King's Bishop (both red), # with $cell_props. # Once images are supported, will change to pictures of pieces (or maybe both). # Please use TABSTOP=4 for best view # ------------- # -A or -B on command line to select preferred library (if available) # then look for PDFpref file and read A or B forms my ($PDFpref, $rcA, $rcB); # which is available? my $prefFile = "./PDFpref"; my $prefix = 0; # by default, do not add a prefix to the output name my $prefDefault = "B"; # PDF::Builder default if no prefFile, or both installed if (@ARGV) { # A or -A argument: set PDFpref to A else B if ($ARGV[0] =~ m/^-?([AB])/i) { $PDFpref = uc($1); $prefix = 1; } else { print STDERR "Unknown command line flag $ARGV[0] ignored.\n"; } } if (!defined $PDFpref) { if (-f $prefFile && -r $prefFile) { open my $FH, '<', $prefFile or die "error opening $prefFile: $!\n"; $PDFpref = <$FH>; if ($PDFpref =~ m/^A/i) { # something starting with A, assume want PDF::API2 $PDFpref = 'A'; } elsif ($PDFpref =~ m/^B/i) { # something starting with B, assume want PDF::Builder $PDFpref = 'B'; } elsif ($PDFpref =~ m/^PDF:{1,2}A/i) { # something starting with PDF:A or PDF::A, assume want PDF::API2 $PDFpref = 'A'; } elsif ($PDFpref =~ m/^PDF:{1,2}B/i) { # something starting with PDF:B or PDF::B, assume want PDF::Builder $PDFpref = 'B'; } else { print STDERR "Don't see A... or B..., default to $prefDefault\n"; $PDFpref = $prefDefault; } close $FH; } else { # no preference expressed, default to PDF::Builder print STDERR "No preference file found, so default to $prefDefault\n"; $PDFpref = $prefDefault; } } foreach (1 .. 2) { if ($PDFpref eq 'A') { # A(PI2) preferred $rcA = eval { require PDF::API2; 1; }; if (!defined $rcA) { $rcA = 0; } # else is 1; if ($rcA) { $rcB = 0; last; } $PDFpref = 'B'; } if ($PDFpref eq 'B') { # B(uilder) preferred $rcB = eval { require PDF::Builder; 1; }; if (!defined $rcB) { $rcB = 0; } # else is 1; if ($rcB) { $rcA = 0; last; } $PDFpref = 'A'; } } if (!$rcA && !$rcB) { die "Neither PDF::API2 nor PDF::Builder is installed!\n"; } # appears to work as of 2.044 #if ($PDFpref eq 'A') { # print STDERR "chess example fails due to PDF::API2 bug, and is not run.\n"; # exit(0); #} # ------------- our $VERSION = '1.005'; # VERSION our $LAST_UPDATE = '1.004'; # manually update whenever code is changed my $outfile = $0; if ($outfile =~ m#[\\/]([^\\/]+)$#) { $outfile = $1; } $outfile =~ s/\.pl$/.pdf/; # command line -A or -B adds A_ or B_ to outfile if ($prefix) { $outfile = $PDFpref . "_" . $outfile; } my $pdftable = PDF::Table->new(); # ------------- my $pdf; if ($rcA) { print STDERR "Using PDF::API2 library\n"; $pdf = PDF::API2->new( -file => $outfile ); } else { print STDERR "Using PDF::Builder library\n"; $pdf = PDF::Builder->new( -file => $outfile ); } # ------------- my $page = $pdf->page(); $pdf->mediabox('A4'); # A4 as defined by PDF::API2 is h=842 w=545 for portrait # some data to lay out. notice that there are 8 rows of 8 columns my $chessboard; if ($mode eq 'text') { $chessboard = [ # rows TTB, LTR value=piece name, or blank for empty # unfortunately, none of the corefonts include chess pieces [ 'WKB', ' ', ' ', ' ', ' ', ' ', 'WK', 'WKR' ], [ ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'BR' ], [ ' ', ' ', 'WR', ' ', ' ', ' ', ' ', ' ' ], [ ' ', ' ', 'BKB', ' ', 'Bp', ' ', 'Bp', ' ' ], [ 'WN', ' ', 'Wp', ' ', 'BK', ' ', 'Wp', ' ' ], [ ' ', 'Bp', ' ', ' ', 'Wp', ' ', ' ', 'Bp' ], [ ' ', 'Wp', ' ', ' ', 'Wp', ' ', ' ', 'Wp' ], [ ' ', ' ', ' ', ' ', ' ', 'WN', ' ', ' ' ], ]; } else { $chessboard = [ # rows TTB, LTR value=piece name, or blank for empty [ "\x{2657}", ' ', ' ', ' ', ' ', ' ', "\x{2654}", "\x{2656}" ], [ ' ', ' ', ' ', ' ', ' ', ' ', ' ', "\x{265C}" ], [ ' ', ' ', "\x{2656}", ' ', ' ', ' ', ' ', ' ' ], [ ' ', ' ', "\x{265D}", ' ', "\x{265F}", ' ', "\x{265F}", ' ' ], [ "\x{2658}", ' ', "\x{2659}", ' ', "\x{265A}", ' ', "\x{2659}", ' ' ], [ ' ', "\x{265F}", ' ', ' ', "\x{2659}", ' ', ' ', "\x{265F}" ], [ ' ', "\x{2659}", ' ', ' ', "\x{2659}", ' ', ' ', "\x{2659}" ], [ ' ', ' ', ' ', ' ', ' ', "\x{2658}", ' ', ' ' ], ]; } # what's the longest string (widest text) we'll use? my ($font, $font_size, $min_width); if ($mode eq 'text') { $font = $pdf->corefont('Helvetica'); $font_size = 15; } else { $font = $pdf->ttfont('/Windows/Fonts/dejavusans.ttf'); $font_size = 30; # $font_size /= 2.11 if $PDFpref eq 'A'; # work around one of the bugs } my $text = $page->text(); $text->font($font, $font_size); if ($mode eq 'text') { $min_width = $text->advancewidth('WKR'); } else { $min_width = 1.7*$text->advancewidth($chessboard->[0][0]); } $min_width += 2 * 2; # L + R padding # build the table layout $pdftable->table( # required params $pdf, $page, $chessboard, x => 20, w => 8 * $min_width, y => 700, h => 8 * $min_width + 1, # if +0, last row to next page! # some optional params padding => 2, padding_top => # center vertically in cell, trial & error ($mode eq 'text')? 10.4: 6.4, justify => "center", font => $font, font_size => $font_size, min_w => $min_width, max_w => $min_width, min_rh => $min_width, # unfortunately, the chess pieces (graphics) are designed for # black on white, and black fg disappears against black bg. # however BonW and WonB make it hard to tell B and W pieces! column_props => [ {bg_color_odd => 'black', fg_color_odd => 'white', # col 0 bg_color_even => 'white', fg_color_even => 'black' }, {bg_color_odd => 'white', fg_color_odd => 'black', # col 1 bg_color_even => 'black', fg_color_even => 'white' }, {bg_color_odd => 'black', fg_color_odd => 'white', # col 2 bg_color_even => 'white', fg_color_even => 'black' }, {bg_color_odd => 'white', fg_color_odd => 'black', # col 3 bg_color_even => 'black', fg_color_even => 'white' }, {bg_color_odd => 'black', fg_color_odd => 'white', # col 4 bg_color_even => 'white', fg_color_even => 'black' }, {bg_color_odd => 'white', fg_color_odd => 'black', # col 5 bg_color_even => 'black', fg_color_even => 'white' }, {bg_color_odd => 'black', fg_color_odd => 'white', # col 6 bg_color_even => 'white', fg_color_even => 'black' }, {bg_color_odd => 'white', fg_color_odd => 'black', # col 7 bg_color_even => 'black', fg_color_even => 'white' }, ], cell_props => [ [],[],[], # rows 0-2, no cell overrides # red fg looks good for text, but bad for symbols # anyone who knows chess will figure out it's NxB [ # row 3 col 2 gray bg, red fg {}, {}, { bg_color => '#888888' } ], [ # row 4 cols 0-2 gray bg, red fg for col 0 { bg_color => '#888888' }, { bg_color => '#888888' }, { bg_color => '#888888' }, ], ], ); $pdf->save(); PDF-Table-1.005/examples/sample1.pl0000644000000000000000000001456014365336065015411 0ustar rootroot#!/usr/bin/env perl use warnings; use strict; use diagnostics; use PDF::Table; =pod This example file gives an overview of the functionalities provided by PDF::Table. Also it can be used to bootstrap your code. =cut # Please use TABSTOP=4 for best view # ------------- # -A or -B on command line to select preferred library (if available) # then look for PDFpref file and read A or B forms my ($PDFpref, $rcA, $rcB); # which is available? my $prefFile = "./PDFpref"; my $prefix = 0; # by default, do not add a prefix to the output name my $prefDefault = "B"; # PDF::Builder default if no prefFile, or both installed if (@ARGV) { # A or -A argument: set PDFpref to A else B if ($ARGV[0] =~ m/^-?([AB])/i) { $PDFpref = uc($1); $prefix = 1; } else { print STDERR "Unknown command line flag $ARGV[0] ignored.\n"; } } if (!defined $PDFpref) { if (-f $prefFile && -r $prefFile) { open my $FH, '<', $prefFile or die "error opening $prefFile: $!\n"; $PDFpref = <$FH>; if ($PDFpref =~ m/^A/i) { # something starting with A, assume want PDF::API2 $PDFpref = 'A'; } elsif ($PDFpref =~ m/^B/i) { # something starting with B, assume want PDF::Builder $PDFpref = 'B'; } elsif ($PDFpref =~ m/^PDF:{1,2}A/i) { # something starting with PDF:A or PDF::A, assume want PDF::API2 $PDFpref = 'A'; } elsif ($PDFpref =~ m/^PDF:{1,2}B/i) { # something starting with PDF:B or PDF::B, assume want PDF::Builder $PDFpref = 'B'; } else { print STDERR "Don't see A... or B..., default to $prefDefault\n"; $PDFpref = $prefDefault; } close $FH; } else { # no preference expressed, default to PDF::Builder print STDERR "No preference file found, so default to $prefDefault\n"; $PDFpref = $prefDefault; } } foreach (1 .. 2) { if ($PDFpref eq 'A') { # A(PI2) preferred $rcA = eval { require PDF::API2; 1; }; if (!defined $rcA) { $rcA = 0; } # else is 1; if ($rcA) { $rcB = 0; last; } $PDFpref = 'B'; } if ($PDFpref eq 'B') { # B(uilder) preferred $rcB = eval { require PDF::Builder; 1; }; if (!defined $rcB) { $rcB = 0; } # else is 1; if ($rcB) { $rcA = 0; last; } $PDFpref = 'A'; } } if (!$rcA && !$rcB) { die "Neither PDF::API2 nor PDF::Builder is installed!\n"; } # ------------- our $VERSION = '1.005'; # VERSION our $LAST_UPDATE = '1.004'; # manually update whenever code is changed my $outfile = $0; if ($outfile =~ m#[\\/]([^\\/]+)$#) { $outfile = $1; } $outfile =~ s/\.pl$/.pdf/; # command line -A or -B adds A_ or B_ to outfile if ($prefix) { $outfile = $PDFpref . "_" . $outfile; } my $pdftable = PDF::Table->new(); # ------------- my $pdf; if ($rcA) { print STDERR "Using PDF::API2 library\n"; $pdf = PDF::API2->new( -file => $outfile ); } else { print STDERR "Using PDF::Builder library\n"; $pdf = PDF::Builder->new( -file => $outfile, -compress => 'none' ); } # ------------- my $page = $pdf->page(); $pdf->mediabox('A4'); # A4 as defined by PDF::API2 is h=842 w=545 for portrait # some data to lay out. I believe that it is partly Bulgarian, created by the # previous owner of this package. my $some_data = [ [ 'Header', 'Row', 'Test' ], [ '1 Lorem ipsum dolor', 'Donec odio neque, faucibus vel', '1 consequat quis, tincidunt vel, felis.' ], [ 'Nulla euismod sem eget neque.', 'Donec odio neque', 'Sed eu velit.' ], [ 'Az sym bulgarin', # column 2 has explicit \n's for 3 physical lines "i ne razbiram DESI\ngorniq \nezik", # column 3 has implied \n's for 4 physical lines # note that lines 2-4 have huge leading spaces stripped away "zatova reshih da dobavq edin ili dva novi reda" ], [ # extra row height requested with row_height (min_rh) 'da dobavq edin dva reda', 'v tozi primer AND extra height', 'na bulgarski ezik s latinica' ], [ '5 Lorem ipsum dolor', 'Donec odio neque, faucibus vel', '5 consequat quis, tincidunt vel, felis.' ], [ 'Nulla euismod sem eget neque.', 'Donec odio neque', 'Sed eu velit.' ], [ 'Az sym bulgarin', 'i ne razbiram gorniq ezik', 'zatova reshih' ], [ 'da dobavq edin dva reda', 'v tozi primer', 'na bulgarski ezik s latinica' ], ]; # build the table layout. like the data (text), the various properties and # settings could be pulled out of line. $pdftable->table( # required params $pdf, $page, $some_data, # Geometry of the document x => 50, w => 495, # width: most of an A4 page y => 792, next_y => 700, h => 400, # reduce to force overflow to new page next_h => 500, # some optional params for fancy results padding => 3, padding_right => 10, bg_color_odd => 'lightblue', bg_color_even => "#EEEEAA", # using default font (Times-Roman 12pt) header_props => { bg_color => "#F0AAAA", font => $pdf->corefont( "Helvetica", -encoding => "latin1" ), font_size => 14, fg_color => "#006600", repeat => 1 # default # note that col 2 inherits RJ from column_props setting }, column_props => [ {}, # no properties for the first column { # column 2 overrides: force wider, # larger font, right-justified, own bg. min_w => 250, justify => "right", font => $pdf->corefont( "Times-Roman", -encoding => "latin1" ), font_size => 14, fg_color => 'white', bg_color => '#8CA6C5', }, # column 3 no overrides ], cell_props => [ [ # This is the first(header) row of the table and here # %header_prop has priority, so no effect with these settings { bg_color => '#000000', fg_color => 'blue', }, # etc. ], [ # Row 2 (first data row) { # Row 2 col 1 bg_color => '#000000', fg_color => 'white', }, { # Row 2 col 2 bg_color => '#AAAA00', fg_color => 'red', }, { # Row 2 col 3 bg_color => '#FFFFFF', fg_color => 'green', }, # etc. ], [ # Row 3 (second data row) { # Row 3 cell 1 bg_color => '#AAAAAA', fg_color => 'blue', }, # etc. rest of columns are normal ], # etc. rest of rows are normal ], row_props => [ {}, {}, {}, {}, { # Row 5 (4th data row) 'min_rh' => 75, # extra height on this row }, ], ); # end of table() call $pdf->save(); PDF-Table-1.005/examples/header_repeat_with_cell_props.pl0000644000000000000000000001163114365336065022110 0ustar rootroot#!/usr/bin/env perl use warnings; use strict; use diagnostics; use PDF::Table; # Please use TABSTOP=4 for best view # ------------- # -A or -B on command line to select preferred library (if available) # then look for PDFpref file and read A or B forms my ($PDFpref, $rcA, $rcB); # which is available? my $prefFile = "./PDFpref"; my $prefix = 0; # by default, do not add a prefix to the output name my $prefDefault = "B"; # PDF::Builder default if no prefFile, or both installed if (@ARGV) { # A or -A argument: set PDFpref to A else B if ($ARGV[0] =~ m/^-?([AB])/i) { $PDFpref = uc($1); $prefix = 1; } else { print STDERR "Unknown command line flag $ARGV[0] ignored.\n"; } } if (!defined $PDFpref) { if (-f $prefFile && -r $prefFile) { open my $FH, '<', $prefFile or die "error opening $prefFile: $!\n"; $PDFpref = <$FH>; if ($PDFpref =~ m/^A/i) { # something starting with A, assume want PDF::API2 $PDFpref = 'A'; } elsif ($PDFpref =~ m/^B/i) { # something starting with B, assume want PDF::Builder $PDFpref = 'B'; } elsif ($PDFpref =~ m/^PDF:{1,2}A/i) { # something starting with PDF:A or PDF::A, assume want PDF::API2 $PDFpref = 'A'; } elsif ($PDFpref =~ m/^PDF:{1,2}B/i) { # something starting with PDF:B or PDF::B, assume want PDF::Builder $PDFpref = 'B'; } else { print STDERR "Don't see A... or B..., default to $prefDefault\n"; $PDFpref = $prefDefault; } close $FH; } else { # no preference expressed, default to PDF::Builder print STDERR "No preference file found, so default to $prefDefault\n"; $PDFpref = $prefDefault; } } foreach (1 .. 2) { if ($PDFpref eq 'A') { # A(PI2) preferred $rcA = eval { require PDF::API2; 1; }; if (!defined $rcA) { $rcA = 0; } # else is 1; if ($rcA) { $rcB = 0; last; } $PDFpref = 'B'; } if ($PDFpref eq 'B') { # B(uilder) preferred $rcB = eval { require PDF::Builder; 1; }; if (!defined $rcB) { $rcB = 0; } # else is 1; if ($rcB) { $rcA = 0; last; } $PDFpref = 'A'; } } if (!$rcA && !$rcB) { die "Neither PDF::API2 nor PDF::Builder is installed!\n"; } # ------------- our $VERSION = '1.005'; # VERSION our $LAST_UPDATE = '1.004'; # manually update whenever code is changed my $outfile = $0; if ($outfile =~ m#[\\/]([^\\/]+)$#) { $outfile = $1; } $outfile =~ s/\.pl$/.pdf/; # command line -A or -B adds A_ or B_ to outfile if ($prefix) { $outfile = $PDFpref . "_" . $outfile; } my $pdftable = PDF::Table->new(); # ------------- my $pdf; if ($rcA) { print STDERR "Using PDF::API2 library\n"; $pdf = PDF::API2->new( -file => $outfile ); } else { print STDERR "Using PDF::Builder library\n"; $pdf = PDF::Builder->new( -file => $outfile ); } # ------------- my $page = $pdf->page(); $pdf->mediabox('A4'); # A4 as defined by PDF::API2 is h=842 w=545 for portrait # some data to layout my $some_data = [ [ 'Header', 'Row', 'Test' ], [ '1 Lorem ipsum dolor', 'Donec', 'consequat quis, tincidunt vel, felis.' ], [ '2 Lorem ipsum dolor', 'Donec super long text goes here to provoke a text block', 'consequat quis, tincidunt vel, felis.' ], [ '3 Lorem ipsum dolor', 'Donec', 'consequat quis, tincidunt vel, felis.' ], [ '4 Lorem ipsum dolor', 'Donec super long text goes here to provoke a text block', 'consequat quis, tincidunt vel, felis.' ], [ '5 Lorem ipsum dolor', 'Donec', 'consequat quis, tincidunt vel, felis.' ], [ '6 Lorem ipsum dolor', 'Donec', 'consequat quis, tincidunt vel, felis.' ], [ '7 Lorem ipsum dolor', 'Donec', 'consequat quis, tincidunt vel, felis.' ], [ '8 Lorem ipsum dolor', 'Donec', 'consequat quis, tincidunt vel, felis.' ], [ '9 Lorem ipsum dolor', 'Donec', 'consequat quis, tincidunt vel, felis.' ], ]; # build the table layout my $cell_props = []; $cell_props->[2][1] = { background_color => '#000000', # or bg_color font_color => 'blue', # or fg_color justify => 'left' }; $cell_props->[4][1] = { background_color => '#000000', font_color => 'red', justify => 'center' }; $cell_props->[6][1] = { background_color => '#000000', font_color => 'yellow', justify => 'right' }; # note that cell properties taken out-of-line $pdftable->table( # required params $pdf, $page, $some_data, x => 10, w => 350, start_y => 780, # or y next_y => 780, start_h => 210, # or h next_h => 210, # some optional params font_size => 10, padding => 10, #padding_right => 10, horizontal_borders => 1, header_props => { bg_color => "silver", font => $pdf->corefont( "Helvetica", -encoding => "utf8" ), font_size => 20, font_color => "#006600", # or fg_color #justify => 'left', repeat => 1, # default }, cell_props => $cell_props ); $pdf->save(); PDF-Table-1.005/examples/border_rules.pl0000644000000000000000000002425214365336065016535 0ustar rootroot#!/usr/bin/env perl use warnings; use strict; use diagnostics; use PDF::Table; # Demonstrate a number of border and rule settings. # Please use TABSTOP=4 for best view # ------------- # -A or -B on command line to select preferred library (if available) # then look for PDFpref file and read A or B forms my ($PDFpref, $rcA, $rcB); # which is available? my $prefFile = "./PDFpref"; my $prefix = 0; # by default, do not add a prefix to the output name my $prefDefault = "B"; # PDF::Builder default if no prefFile, or both installed if (@ARGV) { # A or -A argument: set PDFpref to A else B if ($ARGV[0] =~ m/^-?([AB])/i) { $PDFpref = uc($1); $prefix = 1; } else { print STDERR "Unknown command line flag $ARGV[0] ignored.\n"; } } if (!defined $PDFpref) { if (-f $prefFile && -r $prefFile) { open my $FH, '<', $prefFile or die "error opening $prefFile: $!\n"; $PDFpref = <$FH>; if ($PDFpref =~ m/^A/i) { # something starting with A, assume want PDF::API2 $PDFpref = 'A'; } elsif ($PDFpref =~ m/^B/i) { # something starting with B, assume want PDF::Builder $PDFpref = 'B'; } elsif ($PDFpref =~ m/^PDF:{1,2}A/i) { # something starting with PDF:A or PDF::A, assume want PDF::API2 $PDFpref = 'A'; } elsif ($PDFpref =~ m/^PDF:{1,2}B/i) { # something starting with PDF:B or PDF::B, assume want PDF::Builder $PDFpref = 'B'; } else { print STDERR "Don't see A... or B..., default to $prefDefault\n"; $PDFpref = $prefDefault; } close $FH; } else { # no preference expressed, default to PDF::Builder print STDERR "No preference file found, so default to $prefDefault\n"; $PDFpref = $prefDefault; } } foreach (1 .. 2) { if ($PDFpref eq 'A') { # A(PI2) preferred $rcA = eval { require PDF::API2; 1; }; if (!defined $rcA) { $rcA = 0; } # else is 1; if ($rcA) { $rcB = 0; last; } $PDFpref = 'B'; } if ($PDFpref eq 'B') { # B(uilder) preferred $rcB = eval { require PDF::Builder; 1; }; if (!defined $rcB) { $rcB = 0; } # else is 1; if ($rcB) { $rcA = 0; last; } $PDFpref = 'A'; } } if (!$rcA && !$rcB) { die "Neither PDF::API2 nor PDF::Builder is installed!\n"; } # ------------- our $VERSION = '1.005'; # VERSION our $LAST_UPDATE = '1.004'; # manually update whenever code is changed my $outfile = $0; if ($outfile =~ m#[\\/]([^\\/]+)$#) { $outfile = $1; } $outfile =~ s/\.pl$/.pdf/; # command line -A or -B adds A_ or B_ to outfile if ($prefix) { $outfile = $PDFpref . "_" . $outfile; } my $pdftable = PDF::Table->new(); # ------------- my $pdf; if ($rcA) { print STDERR "Using PDF::API2 library\n"; $pdf = PDF::API2->new( -file => $outfile ); } else { print STDERR "Using PDF::Builder library\n"; # $pdf = PDF::Builder->new( -file => $outfile ); $pdf = PDF::Builder->new( -file => $outfile, -compress=>'none' ); } # ------------- my $page = $pdf->page(); ############################################################################ # illustrate thick border with inherited rules, thin rules, no rules # -------------------- table 1a my $table = [ # rows TTB, LTR [ 'Thick', 'border', ], [ 'Inherit', 'rules', ], ]; my $font_size = 15; my $font = $pdf->corefont('Helvetica'); my $fontb = $pdf->corefont('Helvetica-Bold'); # build the table layout $pdftable->table( # required params $pdf, $page, $table, x => 10, w => 100, y => 700, h => 100, # some optional params justify => "center", font => $font, font_size => $font_size, border_w => 8, # default padding 2 isn't quite enough, but show effect cell_props => [ [], [ { font => $fontb, }, ], ], ); # -------------------- table 1b $table = [ # rows TTB, LTR [ 'Thick', 'border', ], [ 'Thin', 'rules', ], ]; # build the table layout $pdftable->table( # required params $pdf, $page, $table, x => 160, w => 100, y => 700, h => 100, # some optional params justify => "center", font => $font, font_size => $font_size, # borders both black, 8 wide border_w => 8, # rules blue, 1 wide rule_w => 1, rule_c => 'blue', cell_props => [ [], [ { font => $fontb, }, ], ], ); # -------------------- table 1c $table = [ # rows TTB, LTR [ 'Thick', 'border', ], [ 'No', 'rules', ], ]; # build the table layout $pdftable->table( # required params $pdf, $page, $table, x => 310, w => 100, y => 700, h => 100, # some optional params justify => "center", font => $font, font_size => $font_size, # vertical borders thick, horizontal borders (override) thinner border_w => 8, h_border_w => 3, # no visible rules rule_w => 0, cell_props => [ [], [ { font => $fontb, }, ], ], ); ############################################################################ # -------------------- table 2 # illustrate lots of row, col, cell color and rules variations $table = [ # rows TTB, LTR [ '0,0', '0,1', '0,2', '0,3', '0,4', '0,5', '0,6', '0,7' ], [ '1,0', '1,1', '1,2', '1,3', '1,4', '1,5', '1,6', '1,7' ], [ '2,0', '2,1', '2,2', '2,3', '2,4', '2,5', '2,6', '2,7' ], [ '3,0', '3,1', '3,2', '3,3', '3,4', '3,5', '3,6', '3,7' ], [ '4,0', '4,1', '4,2', '4,3', '4,4', '4,5', '4,6', '4,7' ], [ '5,0', '5,1', '5,2', '5,3', '5,4', '5,5', '5,6', '5,7' ], [ '6,0', '6,1', '6,2', '6,3', '6,4', '6,5', '6,6', '6,7' ], [ '7,0', '7,1', '7,2', '7,3', '7,4', '7,5', '7,6', '7,7' ], ]; # build the table layout $pdftable->table( # required params $pdf, $page, $table, x => 10, w => 500, y => 590, h => 500, # some optional params justify => "center", font => $font, font_size => $font_size, padding => 10, # thick borders border_w => 3, border_c => 'green', # thin rules rule_w => 1, # rule_c inherits from border_c (green) # play some games with colors and rules. note that varying rule widths # and changes of rule color may not align perfectly nicely in wild # examples like this! # 1. no rules around 1,1 (also affects 0,1 and 1,2) and bold font # 2. 4,5 and 4,6 (overlap pink column) light blue bg # 3. 6,3 and 7,3 (overlap yellow row) light green bg # 4. 4,1 left and bottom rules thick black cell_props => [ [ # row 0 {}, { h_rule_w => 0, }, # 0,1 no bottom rule (top of 1,1) ], [ # row 1 {}, # 1,0 { font => $fontb, rule_w => 0, }, # 1,1 { v_rule_w => 0, }, # 1,2 no left rule (right of 1,1) ], [],[], [ # row 4 {}, { rule_c => 'black', rule_w => 4, }, # 4,1 {},{},{}, { bg_color => '#EEEEFF', }, # 4,5 { bg_color => '#EEEEFF', }, # 4,6 ], [], [ # row 6 {},{},{}, { bg_color => '#AAFFAA', } # 6,3 ], [ # row 7 {},{},{}, { bg_color => '#AAFFAA', } # 7,3 ], ], # 5. col 4 thick left vertical rule (form full line) # 6. col 5 thick bottom rule # 7. col 6 pink background column_props => [ {},{},{},{}, { v_rule_w => 4, v_rule_c => 'black', }, { h_rule_w => 4, h_rule_c => '#666666', }, { bg_color => 'pink', }, ], # 8. row 3 thick left rule # 9. row 5 bottom horizontal rule (form full line), thick red # 10. row 7 yellow background row_props => [ {},{},{}, { v_rule_w => 5, v_rule_c => '#888888', }, {}, { h_rule_w => 3, h_rule_c => 'red', }, {}, { bg_color => 'yellow', }, ], ); ############################################################################ # -------------------- table 3 # illustrate different kinds of bottom/top borders on row/table splits # Lorem Ipsum text, borrowed from PDF::Builder::examples/022_truefonts $table = [ [ # 0,0 "Sed ut perspiciatis, unde omnis iste natus error sit ". "voluptatem accusantium doloremque laudantium, totam rem aperiam eaque ipsa, ". "quae ab illo inventore veritatis et quasi architecto beatae vitae dicta ". "sunt, explicabo.", # 0,1 "Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur ". "aut odit aut fugit, sed quia consequuntur magni dolores eos, qui ratione ". "dolor sit, voluptatem sequi nesciunt, neque porro quisquam est, qui dolorem ". "ipsum, quia amet, consectetur, adipisci velit, sed quia non numquam eius ". "modi tempora incidunt, ut labore et dolore magnam aliquam quaerat ". "voluptatem." ], [ # 1,0 "Ut enim ad minima veniam, quis nostrum exercitationem ullam ". "corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur?", # 1,1 "Quis autem vel eum iure reprehenderit, qui in ea voluptate velit esse, quam ". "nihil molestiae consequatur, vel illum, qui dolorem eum fugiat, quo voluptas ". "nulla pariatur?" ], [ # 2,0 "At vero eos et accusamus et iusto odio dignissimos ducimus, ". "qui blanditiis praesentium voluptatum deleniti atque corrupti, quos dolores ". "et quas molestias excepturi sint, obcaecati cupiditate non provident, ". "similique sunt in culpa, qui officia deserunt mollitia animi, id est laborum ". "et dolorum fuga.", # 2,1 "Et harum quidem rerum facilis est et expedita distinctio." ], [ # 3,0 "Nam libero tempore, cum soluta nobis est eligendi optio, cumque nihil ". "impedit, quo minus id, quod maxime placeat, facere possimus, omnis voluptas ". "assumenda est, omnis dolor repellendus.", # 3,1 "Temporibus autem quibusdam et aut ". "officiis debitis aut rerum necessitatibus saepe eveniet, ut et voluptates ". "repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur ". "a sapiente delectus, ut aut reiciendis voluptatibus maiores alias ". "consequatur aut perferendis doloribus asperiores repellat." ] ]; # build the table layout $pdftable->table( # required params $pdf, $page, $table, x => 10, w => 240, y => 200, # start near bottom h => 150, # adjust to split in middle of row next_y => 700, next_h => 500, # adjust to split at least once at row boundary # 530 is also a good split # some optional params default_text => ' ', justify => "left", font => $font, font_size => $font_size, padding => 10, # thick borders border_w => 6, border_c => '#222222', # thin rules rule_w => 2, # to distinguish from split-row solid/dashed # rule_c inherits from border_c (dark gray) ); $pdf->save(); PDF-Table-1.005/examples/colspan.pl0000644000000000000000000001241114365336065015477 0ustar rootroot#!/usr/bin/env perl use strict; use warnings; use PDF::Table; # ------------- # -A or -B on command line to select preferred library (if available) # then look for PDFpref file and read A or B forms my ($PDFpref, $rcA, $rcB); # which is available? my $prefFile = "./PDFpref"; my $prefix = 0; # by default, do not add a prefix to the output name my $prefDefault = "B"; # PDF::Builder default if no prefFile, or both installed if (@ARGV) { # A or -A argument: set PDFpref to A else B if ($ARGV[0] =~ m/^-?([AB])/i) { $PDFpref = uc($1); $prefix = 1; } else { print STDERR "Unknown command line flag $ARGV[0] ignored.\n"; } } if (!defined $PDFpref) { if (-f $prefFile && -r $prefFile) { open my $FH, '<', $prefFile or die "error opening $prefFile: $!\n"; $PDFpref = <$FH>; if ($PDFpref =~ m/^A/i) { # something starting with A, assume want PDF::API2 $PDFpref = 'A'; } elsif ($PDFpref =~ m/^B/i) { # something starting with B, assume want PDF::Builder $PDFpref = 'B'; } elsif ($PDFpref =~ m/^PDF:{1,2}A/i) { # something starting with PDF:A or PDF::A, assume want PDF::API2 $PDFpref = 'A'; } elsif ($PDFpref =~ m/^PDF:{1,2}B/i) { # something starting with PDF:B or PDF::B, assume want PDF::Builder $PDFpref = 'B'; } else { print STDERR "Don't see A... or B..., default to $prefDefault\n"; $PDFpref = $prefDefault; } close $FH; } else { # no preference expressed, default to PDF::Builder print STDERR "No preference file found, so default to $prefDefault\n"; $PDFpref = $prefDefault; } } foreach (1 .. 2) { if ($PDFpref eq 'A') { # A(PI2) preferred $rcA = eval { require PDF::API2; 1; }; if (!defined $rcA) { $rcA = 0; } # else is 1; if ($rcA) { $rcB = 0; last; } $PDFpref = 'B'; } if ($PDFpref eq 'B') { # B(uilder) preferred $rcB = eval { require PDF::Builder; 1; }; if (!defined $rcB) { $rcB = 0; } # else is 1; if ($rcB) { $rcA = 0; last; } $PDFpref = 'A'; } } if (!$rcA && !$rcB) { die "Neither PDF::API2 nor PDF::Builder is installed!\n"; } # ------------- our $VERSION = '1.005'; # VERSION our $LAST_UPDATE = '1.004'; # manually update whenever code is changed my $outfile = $0; if ($outfile =~ m#[\\/]([^\\/]+)$#) { $outfile = $1; } $outfile =~ s/\.pl$/.pdf/; # command line -A or -B adds A_ or B_ to outfile if ($prefix) { $outfile = $PDFpref . "_" . $outfile; } my $pdftable = PDF::Table->new(); # ------------- my $pdf; if ($rcA) { print STDERR "Using PDF::API2 library\n"; $pdf = PDF::API2->new( -file => $outfile ); } else { print STDERR "Using PDF::Builder library\n"; $pdf = PDF::Builder->new( -file => $outfile ); } # ------------- my $page = $pdf->page(); $pdf->mediabox('A4'); my $data = [ # Row 1, with 3 cols [ "(r1c1) Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", "(r1c2) Ut", "(r1c3) enim ad minim veniam, [3 cols in row 1]" ], # Row 2, one col with colspan=3 [ "(r2c1++) quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. [spans 3 columns]" ], # Row 3, one regular col, one with colspan=2 [ "(r3c1) Excepteur sint occaecat cupidatat", "(r3c2+) non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. [spans cols 2 and 3]" ], # Row 4, just three regular cols, second empty [ "(r4c1) Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", " ", # if "", get warning about inserting default text "(r4c3) Ut enim. [3 columns, second empty]" ], # Row 5, colspan in first col, then a regular col [ "(r5c1+) Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", undef, "(r5c3) Ut enim. [span first two cols]" ], ]; $pdftable->table( $pdf, $page, $data, w => 265, # width of table x => 10, # position from left start_y => 750, # or y. position from bottom start_h => 700, # or h. max height of table padding => 5, # padding on all 4 sides of a cell column_props => [ { min_w => 150, background_color => 'grey' }, # col 1 { background_color => 'red' }, # col 2, including # colspanned col 3 on row 3 {} # col 3 (nothing) ], cell_props => [ # no header, so data row 0 is actually row 1 [ {}, # row 1 cell 2 & 3 overrides { background_color => 'pink' }, # or bg_color { background_color => 'blue', colspan => 1 } ], [ { colspan => 3 } ], # row 2 cell 1 override [ {}, { colspan => 2 } ], # row 3 cell 2 override [ ], # row 4 [ { colspan => 2 } ], # row 5 cell 1 override ], ); $pdf->save(); PDF-Table-1.005/examples/header.pl0000644000000000000000000001243514365336065015276 0ustar rootroot#!/usr/bin/env perl use warnings; use strict; use diagnostics; use PDF::Table; # Please use TABSTOP=4 for best view # ------------- # -A or -B on command line to select preferred library (if available) # then look for PDFpref file and read A or B forms my ($PDFpref, $rcA, $rcB); # which is available? my $prefFile = "./PDFpref"; my $prefix = 0; # by default, do not add a prefix to the output name my $prefDefault = "B"; # PDF::Builder default if no prefFile, or both installed if (@ARGV) { # A or -A argument: set PDFpref to A else B if ($ARGV[0] =~ m/^-?([AB])/i) { $PDFpref = uc($1); $prefix = 1; } else { print STDERR "Unknown command line flag $ARGV[0] ignored.\n"; } } if (!defined $PDFpref) { if (-f $prefFile && -r $prefFile) { open my $FH, '<', $prefFile or die "error opening $prefFile: $!\n"; $PDFpref = <$FH>; if ($PDFpref =~ m/^A/i) { # something starting with A, assume want PDF::API2 $PDFpref = 'A'; } elsif ($PDFpref =~ m/^B/i) { # something starting with B, assume want PDF::Builder $PDFpref = 'B'; } elsif ($PDFpref =~ m/^PDF:{1,2}A/i) { # something starting with PDF:A or PDF::A, assume want PDF::API2 $PDFpref = 'A'; } elsif ($PDFpref =~ m/^PDF:{1,2}B/i) { # something starting with PDF:B or PDF::B, assume want PDF::Builder $PDFpref = 'B'; } else { print STDERR "Don't see A... or B..., default to $prefDefault\n"; $PDFpref = $prefDefault; } close $FH; } else { # no preference expressed, default to PDF::Builder print STDERR "No preference file found, so default to $prefDefault\n"; $PDFpref = $prefDefault; } } foreach (1 .. 2) { if ($PDFpref eq 'A') { # A(PI2) preferred $rcA = eval { require PDF::API2; 1; }; if (!defined $rcA) { $rcA = 0; } # else is 1; if ($rcA) { $rcB = 0; last; } $PDFpref = 'B'; } if ($PDFpref eq 'B') { # B(uilder) preferred $rcB = eval { require PDF::Builder; 1; }; if (!defined $rcB) { $rcB = 0; } # else is 1; if ($rcB) { $rcA = 0; last; } $PDFpref = 'A'; } } if (!$rcA && !$rcB) { die "Neither PDF::API2 nor PDF::Builder is installed!\n"; } # ------------- our $VERSION = '1.005'; # VERSION our $LAST_UPDATE = '1.004'; # manually update whenever code is changed my $outfile = $0; if ($outfile =~ m#[\\/]([^\\/]+)$#) { $outfile = $1; } $outfile =~ s/\.pl$/.pdf/; # command line -A or -B adds A_ or B_ to outfile if ($prefix) { $outfile = $PDFpref . "_" . $outfile; } my $pdftable = PDF::Table->new(); # ------------- my $pdf; if ($rcA) { print STDERR "Using PDF::API2 library\n"; $pdf = PDF::API2->new( -file => $outfile ); } else { print STDERR "Using PDF::Builder library\n"; $pdf = PDF::Builder->new( -file => $outfile ); } # ------------- my $page = $pdf->page(); $pdf->mediabox('A4'); # A4 as defined by PDF::API2 is h=842 w=545 for portrait # some data to lay out. notice that there are 9 rows with the raw data for # 'two' and 'four' being split up into multiple lines = multiple single rows, # as well as 'four' being split on max_word_length my $some_data = [ # H. dk blue on yellow, underlined (each page) [ 'HeaderA', 'HeaderB' ], # 1. white on red,blue underlined (page 1) [ 'foo', 'bar Aye' ], # 2. dk gray on light gray, underlined (page 2) [ 'one', 'twosie' ], # 3. light gray on dk gray, col 2 underlined, split multiple pages 3-6 [ 'two', 'four score and seven years ago our forefathers brought forth' ], # 4. dk gray on light gray, underlined (page 7) [ 'three', 'six pack' ], # 5. light gray on dk gray, underlined, split multiple pages 8-9 [ 'four', 'abcdefghijklmnopqrstuvwxyz' ], ]; # build the table layout # this will show the header and one line (row), meaning two rows will be # split up into multiple pages $pdftable->table( # required params $pdf, $page, $some_data, x => 10, w => 255, start_y => 700, # or y next_y => 700, start_h => 69, # or h. just enough height for two rows per page next_h => 69, # (repeated header + next data row single line) # some optional params bg_color_odd => "#666666", bg_color_even => "#EEEEEE", fg_color_odd => "#EEEEEE", fg_color_even => "#666666", padding_left => 10, # new padding_right => 10, border => 0, # no frame or rules (default thin line) font_size => 20, # default leading about 25 #font_underline => 'auto', # underline everything with thin line font_underline => [3, 2], # or underline. thick underline for all # text (including header) unless override max_word_length => 13, # force alphabet row to split in half header_props => { # font size defaults to 22, leading to 27.5 background_color => 'yellow', # or bg_color repeat => 1 # is now default }, cell_props => [ [], # header row no cell overrides [ # first data row (foo bar Aye) { background_color => 'red', fg_color => 'white' }, { background_color => 'blue', fg_color => 'white' } ], [], # second data row, no cell overrides [ # third data row, no underline first column 'two four...' { underline => [] } # 'none' OK for PDF::Builder ], ], ); $pdf->save(); PDF-Table-1.005/examples/row_height.pl0000644000000000000000000000724514365336065016210 0ustar rootroot#!/usr/bin/env perl use warnings; use strict; use diagnostics; # 25 rows of one text line, each with a height taller than before use PDF::Table; # ------------- # -A or -B on command line to select preferred library (if available) # then look for PDFpref file and read A or B forms my ($PDFpref, $rcA, $rcB); # which is available? my $prefFile = "./PDFpref"; my $prefix = 0; # by default, do not add a prefix to the output name my $prefDefault = "B"; # PDF::Builder default if no prefFile, or both installed if (@ARGV) { # A or -A argument: set PDFpref to A else B if ($ARGV[0] =~ m/^-?([AB])/i) { $PDFpref = uc($1); $prefix = 1; } else { print STDERR "Unknown command line flag $ARGV[0] ignored.\n"; } } if (!defined $PDFpref) { if (-f $prefFile && -r $prefFile) { open my $FH, '<', $prefFile or die "error opening $prefFile: $!\n"; $PDFpref = <$FH>; if ($PDFpref =~ m/^A/i) { # something starting with A, assume want PDF::API2 $PDFpref = 'A'; } elsif ($PDFpref =~ m/^B/i) { # something starting with B, assume want PDF::Builder $PDFpref = 'B'; } elsif ($PDFpref =~ m/^PDF:{1,2}A/i) { # something starting with PDF:A or PDF::A, assume want PDF::API2 $PDFpref = 'A'; } elsif ($PDFpref =~ m/^PDF:{1,2}B/i) { # something starting with PDF:B or PDF::B, assume want PDF::Builder $PDFpref = 'B'; } else { print STDERR "Don't see A... or B..., default to $prefDefault\n"; $PDFpref = $prefDefault; } close $FH; } else { # no preference expressed, default to PDF::Builder print STDERR "No preference file found, so default to $prefDefault\n"; $PDFpref = $prefDefault; } } foreach (1 .. 2) { if ($PDFpref eq 'A') { # A(PI2) preferred $rcA = eval { require PDF::API2; 1; }; if (!defined $rcA) { $rcA = 0; } # else is 1; if ($rcA) { $rcB = 0; last; } $PDFpref = 'B'; } if ($PDFpref eq 'B') { # B(uilder) preferred $rcB = eval { require PDF::Builder; 1; }; if (!defined $rcB) { $rcB = 0; } # else is 1; if ($rcB) { $rcA = 0; last; } $PDFpref = 'A'; } } if (!$rcA && !$rcB) { die "Neither PDF::API2 nor PDF::Builder is installed!\n"; } # ------------- our $VERSION = '1.005'; # VERSION our $LAST_UPDATE = '1.004'; # manually update whenever code is changed my $outfile = $0; if ($outfile =~ m#[\\/]([^\\/]+)$#) { $outfile = $1; } $outfile =~ s/\.pl$/.pdf/; # command line -A or -B adds A_ or B_ to outfile if ($prefix) { $outfile = $PDFpref . "_" . $outfile; } my $pdftable = PDF::Table->new(); # ------------- my $pdf; if ($rcA) { print STDERR "Using PDF::API2 library\n"; $pdf = PDF::API2->new( -file => $outfile ); } else { print STDERR "Using PDF::Builder library\n"; $pdf = PDF::Builder->new( -file => $outfile ); } # ------------- my $page = $pdf->page(); $pdf->mediabox('A4'); # A4 as defined by PDF::API2 is h=842 w=545 for portrait my $data = []; # some data to layout foreach my $num ( 1 .. 25 ) { push( @$data, [ 'foo' . $num, 'bar' . $num ] ); } # ever-increasing row height my @rows; foreach my $num ( 0 .. 24 ) { push @rows, { row_height => 25 + 3*$num }; } # build the table layout $pdftable->table( # required params $pdf, $page, $data, x => 10, w => 150, start_y => 750, # or y. start near top of page next_y => 700, start_h => 200, # or h. first page short, subsequent much longer next_h => 500, # some optional params border => 1, font_size => 10, max_word_length => 15, padding => 5, row_props => \@rows, ); $pdf->save(); PDF-Table-1.005/examples/010_fonts.pl0000644000000000000000000002007714365336065015560 0ustar rootroot#!/usr/bin/perl -w use strict; use warnings; use Carp 'verbose'; local $SIG{__DIE__} = sub { Carp::confess(@_) }; use Data::Dumper; use PDF::Table; # ------------- # -A or -B on command line to select preferred library (if available) # then look for PDFpref file and read A or B forms my ($PDFpref, $rcA, $rcB); # which is available? my $prefFile = "./PDFpref"; my $prefDefault = "B"; # PDF::Builder default if no prefFile, or both installed if (@ARGV) { # A or -A argument: set PDFpref to A else B if ($ARGV[0] =~ m/^-?([AB])/i) { $PDFpref = uc($1); } else { print STDERR "Unknown command line flag $ARGV[0] ignored.\n"; } } if (!defined $PDFpref) { if (-f $prefFile && -r $prefFile) { open my $FH, '<', $prefFile or die "error opening $prefFile: $!\n"; $PDFpref = <$FH>; if ($PDFpref =~ m/^A/i) { # something starting with A, assume want PDF::API2 $PDFpref = 'A'; } elsif ($PDFpref =~ m/^B/i) { # something starting with B, assume want PDF::Builder $PDFpref = 'B'; } elsif ($PDFpref =~ m/^PDF:{1,2}A/i) { # something starting with PDF:A or PDF::A, assume want PDF::API2 $PDFpref = 'A'; } elsif ($PDFpref =~ m/^PDF:{1,2}B/i) { # something starting with PDF:B or PDF::B, assume want PDF::Builder $PDFpref = 'B'; } else { print STDERR "Don't see A... or B..., default to $prefDefault\n"; $PDFpref = $prefDefault; } close $FH; } else { # no preference expressed, default to PDF::Builder print STDERR "No preference file found, so default to $prefDefault\n"; $PDFpref = $prefDefault; } } foreach (1 .. 2) { if ($PDFpref eq 'A') { # A(PI2) preferred $rcA = eval { require PDF::API2; 1; }; if (!defined $rcA) { $rcA = 0; } # else is 1; if ($rcA) { $rcB = 0; last; } $PDFpref = 'B'; } if ($PDFpref eq 'B') { # B(uilder) preferred $rcB = eval { require PDF::Builder; 1; }; if (!defined $rcB) { $rcB = 0; } # else is 1; if ($rcB) { $rcA = 0; last; } $PDFpref = 'A'; } } if (!$rcA && !$rcB) { die "Neither PDF::API2 nor PDF::Builder is installed!\n"; } # ------------- our $VERSION = '1.005'; # VERSION our $LAST_UPDATE = '1.002'; # manually update whenever code is changed my $outfile = $0; $outfile =~ s/\.pl$/.pdf/; # TTF font to use. customize path per your local system. # DejaVuSans.ttf also needs to exist in this directory my $dir = # '/usr/share/fonts/truetype/dejavu/'; '/Windows/Fonts/'; my ( $pdf, $page, $font, $ttfont, $text, $pdftable, $left_edge_of_table, $try ); use utf8; $try = " accents: á é í ó ú Á É Í Ó Ú Spanish (tilde): ñ Ñ ¿ ¡ German (umlaut): ä ö ü ß Ö Ä Ü Cyrillic: ѐ Ѐ Ѡ ѡ Ѣ Greek: α β γ δ Γ Δ Armenian: Ա Բ Գ Դ Ե Hebrew: א ב ג ד Arabic: ر ش س ذ Mono: iI lL zero=0 one=1 Latin-1 Supplement: ° À Ð à ð Latin-Extended A: Ā Đ Ġ Latin-Extended B: ƀ Ɛ Ơ Cyrillic Supplement: Ԃ Ԡ Ԓ http://dejavu.sourceforge.net/samples/DejaVuSans.pdf "; no utf8; # https://github.com/dejavu-fonts/dejavu-fonts # /usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf # You can save custom fonts in the folder ~/.fonts # $ sudo apt update && sudo apt -y install font-manager # https://dejavu-fonts.github.io/Samples.html make_another('010_fonts-default.pdf', '', $try , 'logo.png' ); use utf8; my $try_utf8 = $try; make_another('010_fonts-use_utf.pdf', 'DejaVuSans', $try_utf8 , 'logo.png' ); no utf8; my $no_utf8 = $try; make_another('010_fonts-no_utf8.pdf', 'DejaVuSans', $no_utf8 , 'logo.png' ); # make_another('010_fonts-default.pdf', 'DejaVuSans', $try , 'logo.png' ); sub make_another { my ($file, $passed_font_name, $passed_text, $passed_image_name ) = @_ ; print "Passed \$file = '$file', \$font_name = '$passed_font_name', \$image_name = '$passed_image_name' \n"; print "\n INLINE! accents: á é í ó ú Á É Í Ó Ú Spanish (tilde): ñ Ñ ¿ ¡ German (umlaut): ä ö ü ß Ö Ä Ü Cyrillic: ѐ Ѐ Ѡ ѡ Ѣ Greek: α β γ δ Γ Δ Armenian: Ա Բ Գ Դ Ե Hebrew: א ב ג ד Arabic: ر ش س ذ Mono: iI lL zero=0 one=1 Latin-1 Supplement: ° À Ð à ð Latin-Extended A: Ā Đ Ġ Latin-Extended B: ƀ Ɛ Ơ Cyrillic Supplement: Ԃ Ԡ Ԓ http://dejavu.sourceforge.net/samples/DejaVuSans.pdf "; # Create a blank PDF file # ------------- my $pdf; if ($rcA) { print STDERR "Using PDF::API2 library\n"; $pdf = PDF::API2->new(); } else { print STDERR "Using PDF::Builder library\n"; $pdf = PDF::Builder->new(); } # ------------- $pdftable = PDF::Table->new(); # Add a blank page $page = $pdf->page(); # Set the page size # my $page->mediabox('Letter'); # Add a built-in font to the PDF # Add some text to the page $text = $page->text(); $font = $pdf->corefont('Helvetica-Bold' ); # default to Latin-1 encoding $text->font( $font, 14 ); $text->translate( 50, 700 ); $text->text("In core font: $passed_text\n"); print "$dir$passed_font_name.ttf\n"; my $ttfont; if ($passed_font_name eq '') { $ttfont = $pdf->ttfont($dir.'DejaVuSans'.'.ttf'); } else { $ttfont = $pdf->ttfont($dir.$passed_font_name.'.ttf'); } $text->font( $ttfont, 14 ); $text->translate( 50, 650 ); $text->text("In true type font: $passed_text\n"); $text->translate( 50, 600 ); $text->text("In true type font: INLINE! accents: á é í ó ú Á É Í Ó Ú Spanish (tilde): ñ Ñ ¿ ¡ German (umlaut): ä ö ü ß Ö Ä Ü Cyrillic: ѐ Ѐ Ѡ ѡ Ѣ Greek: α β γ δ Γ Δ Armenian: Ա Բ Գ Դ Ե Hebrew: א ב ג ד Arabic: ر ش س ذ Mono: iI lL zero=0 one=1 Latin-1 Supplement: ° À Ð à ð Latin-Extended A: Ā Đ Ġ Latin-Extended B: ƀ Ɛ Ơ Cyrillic Supplement: Ԃ Ԡ Ԓ http://dejavu.sourceforge.net/samples/DejaVuSans.pdf \n"); my $some_data = [ ['core font: '. $passed_text], ]; $left_edge_of_table = 50; # x # w # start_y # start_h # next_y # next_h # lead # padding # padding_right # padding_left # padding_top # padding_bottom # background_color # background_color_odd # background_color_even # border # border_color # horizontal_borders # vertical_borders # font # font_size # font_underline # font_color # font_color_even # font_color_odd # background_color_odd # background_color_even # row_height # new_page_func # header_props # column_props # cell_props # max_word_length # cell_render_hook # default_text # # build the table layout $pdftable->table( # required params $pdf, $page, $some_data, x => $left_edge_of_table, w => 500, start_y => 500, start_h => 300, # some optional params font => $font , # next_y => 750, # next_h => 500, # padding => 5, # padding_right => 10, # background_color_odd => "gray", # background_color_even => "lightblue", # cell background color for even rows ); $some_data = [ ['true type font: '. $passed_text], ]; $left_edge_of_table = 50; if ($passed_font_name) { $pdftable->table( $pdf, $page, $some_data, x => $left_edge_of_table, w => 500, start_y => 500, start_h => 300, font => $ttfont , ); } else { # go to default font $pdftable->table( $pdf, $page, $some_data, x => $left_edge_of_table, w => 500, start_y => 500, start_h => 300, ); } # Save the PDF $pdf->saveas($file); return; } PDF-Table-1.005/t/0000755000000000000000000000000014365336755012137 5ustar rootrootPDF-Table-1.005/t/Basics.t0000644000000000000000000000642314365336065013527 0ustar rootroot#!/usr/bin/perl use strict; use warnings; use Test::More tests => 7; use lib 't/lib'; # Needed for 'make test' from project dir use TestData; use PDFAPI2Mock; # provide dummy PDF::API2. obviously a real PDF::API2 or # PDF::Builder installation will be needed in order to run BEGIN { use_ok('PDF::Table'); } require_ok('PDF::Table'); my ( $pdf, $page, $tab, @data, %opts ); $pdf = PDF::API2->new(); $page = $pdf->page(); $tab = PDF::Table->new($pdf,$page); @data = ( [ 'foo', 'bar', 'baz' ], ); $tab->table( $pdf, $page, \@data, %TestData::required, ); #Check default font size ok( $pdf->match( [ [qw(font 1 12)], [qw(font 1 12)], [qw(font 1 12)] ] ), 'default font_size' ) || note explain $pdf; #Check default text placement ok( $pdf->match( [ [qw(translate 12 686)], [qw(text foo)] ], [ [qw(translate 112 686)], [qw(text bar)] ], [ [qw(translate 212 686)], [qw(text baz)] ], ), 'default text placement in one row' ) or note explain $pdf; #Check default splitting of long words @data = ( ['123456789012345678901234567890123456789012345678901234567890'], ); %opts = ( %TestData::required, w => 400, #override w so table() will not use text_block() ); $tab->table( $pdf, $page, \@data, %opts ); ok( $pdf->match( [ [ 'text', '12345678901234567890 12345678901234567890 12345678901234567890' ] ], ), 'default break long words on every 20th character' ) or note explain $pdf; # # Test header alignment if unspecified (should default to column alignment # if unspecified) # $pdf = PDF::API2->new(); $page = $pdf->page(); $tab = PDF::Table->new($pdf,$page); @data = ( [ 'head1', 'head2', 'head3'], [ 'foo', 'bar', 'baz' ], ); # Match column properties to default header properties my $col_props = [ { font_color => '#000066', font_size => 14, background_color => '#FFFFAA', justify => 'left' }, { font_color => '#000066', font_size => 14, background_color => '#FFFFAA', justify => 'center' }, { font_color => '#000066', font_size => 14, background_color => '#FFFFAA', justify => 'right' }, ]; %opts = ( %TestData::required, column_props => $col_props, ); $tab->table( $pdf, $page, \@data, %opts ); my @pdf_no_header_props = $pdf->getall; my $pdf2 = PDF::API2->new(); my $page2 = $pdf2->page(); my $tab2 = PDF::Table->new($pdf2,$page2); @data = ( [ 'head1', 'head2', 'head3'], [ 'foo', 'bar', 'baz' ], ); %opts = ( %TestData::required, header_props => { repeat => 1, }, column_props => $col_props, ); $tab2->table( $pdf2, $page2, \@data, %opts ); ok( $pdf2->match( \@pdf_no_header_props ), 'Header alignment matches column alignment if unspecified' ) or note explain $pdf2; $pdf = PDF::API2->new(); $page = $pdf->page(); @data = ( [0..2], [3..5], [6..8] ); my $cell_data; %opts = ( %TestData::required, cell_render_hook => sub { my ($page, $first_row, $row, $col, $x, $y, $w, $h) = @_; $cell_data .= "($row, $col), "; } ); $tab = PDF::Table->new( $pdf, $page ); $tab->table( $pdf2, $page2, \@data, %opts ); ok( $cell_data eq '(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2), ', 'The cell_render_hook() subroutine output is valid' ) or diag explain \$pdf; 1; PDF-Table-1.005/t/Colspan.t0000644000000000000000000000305714365336065013722 0ustar rootroot#!/usr/bin/perl use strict; use warnings; use Test::More tests => 7; use lib 't/lib'; # Needed for 'make test' from project dir use TestData; use PDFAPI2Mock; # provide dummy PDF::API2. obviously a real PDF::API2 or # PDF::Builder installation will be needed in order to run BEGIN { use_ok('PDF::Table'); } require_ok('PDF::Table'); my ( $pdf, $page, $tab, @data ); $pdf = PDF::API2->new(); $page = $pdf->page(); $tab = PDF::Table->new($pdf,$page); @data = ( [ 'r1c1', 'r1c2', 'r1c3' ], ['r2c1', undef, 'r2c3'] ); $tab->table( $pdf, $page, \@data, %TestData::required, column_props => [ { background_color => 'red' }, ], cell_props => [ [], [{colspan=>2}] ] ); #Check first row text placement ok( $pdf->match( [ [qw(translate 12 686)], [qw(text r1c1)] ], [ [qw(translate 112 686)], [qw(text r1c2)] ], [ [qw(translate 212 686)], [qw(text r1c3)] ], ), 'text placement in first row' ) or note explain $pdf; ok( $pdf->match( [ [qw(translate 12 667)], [qw(text r2c1)] ], ), 'text placement r2c1' ) or note explain $pdf; ok( $pdf->match( [ [qw(translate 212 667)], [qw(text r2c3)] ], ), 'text placement r2c3' ) or note explain $pdf; ok( $pdf->match( [ [qw(rect 10 681 100 19)], [qw(fillcolor red)] ], ), 'r1c1 background box' ) or note explain $pdf; ok( $pdf->match( [ [qw(rect 10 662 200 19)], [qw(fillcolor red)] ], ), 'r2c1 colspan background box' ) or note explain $pdf; 1; PDF-Table-1.005/t/PDF-Table.t0000644000000000000000000001044414365336065013757 0ustar rootroot#!/usr/bin/perl use strict; use warnings; use Test::More tests => 11; #use Config; no longer needed use lib 't/lib'; # Needed for 'make test' from project dirs use TestData qw(); use PDFAPI2Mock; # provide dummy PDF::API2. obviously a real PDF::API2 or # PDF::Builder installation will be needed in order to run BEGIN { use_ok('PDF::Table') } my ($col_widths); ($col_widths, undef) = PDF::Table::ColumnWidth::CalcColumnWidths( 400, [ 50, 50, 50, 50 ], [ 200, 200, 200, 200 ], [ -1, -1, -1, -1 ] ); is_deeply( $col_widths, [ 100, 100, 100, 100 ], 'CalcColumnWidths - even'); ($col_widths, undef) = PDF::Table::ColumnWidth::CalcColumnWidths( 400, [ 41, 58, 48 ], [ 51, 600, 48 ], [ -1, -1, -1 ] ); # some float values round to small number of decimal places, so no difference # between regular, long double, and quad math Perls $col_widths->[0] = int(1000*$col_widths->[0] + 0.5)/1000; $col_widths->[1] = int(1000*$col_widths->[1] + 0.5)/1000; $col_widths->[2] = int(1000*$col_widths->[2] + 0.5)/1000; # was 125.333, 142.333, 132.333 is_deeply( $col_widths, [ 41, 311, 48 ], 'CalcColumnWidths - uneven'); ($col_widths, undef) = PDF::Table::ColumnWidth::CalcColumnWidths( 400, [ 50, 0 ], # undef min_w value [ 50, 50 ], [ -1, -1 ] ); # was 225, 175 is_deeply( $col_widths, [ 200, 200 ], 'CalcColumnWidths - undef'); my ($pdf, $page, $tab, @data, @required); @data = ( [ 'foo', 'bar', 'baz' ], ); @required = ( x => 10, w => 300, start_y => 750, next_y => 700, start_h => 40, next_h => 500, ); $pdf = PDF::API2->new; $page = $pdf->page; $tab = PDF::Table->new($pdf, $page); # # this tickles a bug (#34017) which causes an infinite loop # 'foo' =~ /(o)(o)/; $tab->table($pdf, $page, [@data], @required, border => 1, border_color => 'black', font_size => 12, background_color => 'gray', column_props => [ {}, { background_color => 'red' }, {}, ], cell_props => [ [ {}, {}, { background_color => 'blue' } ], ], ); ok($pdf->match( [[qw(translate 12 736)],[qw(text foo)]], [[qw(translate 112 736)],[qw(text bar)]], [[qw(translate 212 736)],[qw(text baz)]], ), 'text position') or note explain $pdf; ok($pdf->match( [[qw(rect 10 731 100 19)],[qw(fillcolor gray)]], [[qw(rect 110 731 100 19)],[qw(fillcolor red)]], [[qw(rect 210 731 100 19)],[qw(fillcolor blue)]], ), 'default header fillcolor') or note explain $pdf; ok($pdf->match( [[qw(gfx)],[qw(strokecolor black)],[qw(linewidth 1)]], [[qw(stroke)]], ), "draw borders"); $pdf = PDF::API2->new; $page = $pdf->page; $tab->table($pdf, $page, [@data], @required, border => 0, border_color => 'black', font_size => 12, column_props => [ {}, { justify => 'center' }, { justify => 'center' }, ], cell_props => [ [ { justify => 'center' }, {}, { justify => 'right' } ], ], ); ok($pdf->match( [[qw(translate 60 736)],[qw(text_center foo)]], [[qw(translate 160 736)],[qw(text_center bar)]], [[qw(translate 308 736)],[qw(text_right baz)]], ), 'justify right and center') or note explain $pdf; ok(!$pdf->match( [[qw(gfx)],[qw(strokecolor black)],[qw(linewidth 0)]], ), "don't set up zero-width borders"); # table is only 3 lines high (4*12 > 40). @data = ( [ 'foo', 'bar' ], [ 'one', 'two' ], [ 'thr', 'four score and seven years ago our fathers brought forth' ], [ 'fiv', 'six' ], [ 'sev', 'abcdefghijklmnopqrstuvwxyz' ], ); $pdf = PDF::API2->new; $page = $pdf->page; $tab->table($pdf, $page, [@data], @required, border => 0, font_size => 12, max_word_length => 13, cell_props => [ [], [ { background_color => 'blue' }, {} ], ], ); ok(1,'Skip test because the one below is not working and must be fixed'); #ok($pdf->match( # [[qw(page)]], # [[qw(rect 10 714 20 12)],[qw(fillcolor blue)]], # [[qw(translate 10 714)],[qw(text thr)]], # [[qw(page)]], # [[qw(rect 10 688 20 12)],[qw(fillcolor blue)]], # [[qw(translate 10 688)],[qw(text -)]], #), 'keep cell_props values when row spans a page'); ok($pdf->match( [['text', 'abcdefghijklm nopqrstuvwxyz']], ), 'break long words on max_word_length'); 1; PDF-Table-1.005/t/table.t0000644000000000000000000000254414365336065013412 0ustar rootroot#!/usr/bin/perl use strict; use warnings; use Test::More tests => 6; use lib 't/lib'; # Needed for 'make test' from project dirs use PDFAPI2Mock; # provide dummy PDF::API2. obviously a real PDF::API2 or # PDF::Builder installation will be needed in order to run BEGIN { use_ok('PDF::Table'); } local $SIG{__WARN__} = sub { my $message = shift; die $message; }; my $pdf = PDF::API2->new; my $page = $pdf->page; my $object = PDF::Table->new($pdf, $page); my $data = [ 'foo', 'bar', 'baz' ]; my $required = [ x => 10, w => 300, start_y => 750, next_y => 700, start_h => 40, next_h => 500 ]; ok($object->table($pdf, $page, [$data], @$required), "basic test"); eval { $object->table('pdf', $page, [$data], @$required) }; like($@, qr/Error: Invalid PDF object received/, "Invalid PDF object received"); eval { $object->table($pdf, 'page', [$data], @$required) }; like($@, qr/Error: Invalid page object received/, "Invalid page object received"); eval { $object->table($pdf, $page, 'data', @$required) }; like($@, qr/Error: Invalid data received/, "Invalid data received"); eval { $object->table($pdf, $page, 'data', 'required') }; like($@, qr/Odd number of elements in hash assignment/, "Odd number of elements in hash assignment"); done_testing(); 1; PDF-Table-1.005/t/lib/0000755000000000000000000000000014365336755012705 5ustar rootrootPDF-Table-1.005/t/lib/TestData.pm0000644000000000000000000000032614365336065014747 0ustar rootrootpackage TestData; use strict; use warnings; our %test = ( a => 1 ); our %required = ( x => 10, w => 300, y => 700, next_y => 600, h => 100, next_h => 500, ); 1; PDF-Table-1.005/t/lib/PDFAPI2Mock.pm0000644000000000000000000000435314365336065015101 0ustar rootroot#!/usr/bin/perl use warnings; use strict; package PDFAPI2Mock; BEGIN { # Mock PDF::API2 # this is a mini MockObject with factory methods package Mock; ## no critic sub new { return bless [] => shift; } sub get { my $self = shift; my $method = shift; # optional method name return $method ? grep( { $_->[0] eq $method } @$self ) : @$self; } sub getall { my $self = shift; my @all; for (@$self) { push @all, ref( $_->[1] ) ? ( [ $_->[0] ], $_->[1]->getall ) : $_; } return @all; } sub match { my $self = shift; my $all = join( "\n", map { join( "\0", @$_ ) } $self->getall ); for (@_) { my $patt = join( "\n", map { join( "\0", @$_ ) } @$_ ); return 0 unless $all =~ /^$patt$/mcg; } return 1; } # class methods for creating object methods sub set_true { my $class = shift; for my $method (@_) { no strict 'refs'; ## no critic *{ $class . '::' . $method } = sub { push @{ +shift }, [ $method, @_ ]; return 1 }; } return; } sub factory { my $class = shift; my $target = shift; my $method = shift; no strict 'refs'; ## no critic *{ $class . '::' . $method } = sub { my $thing = $target->new; push @{ +shift }, [ $method, $thing ]; return $thing; }; return; } package PDF::API2; ## no critic our @ISA = 'Mock'; __PACKAGE__->set_true(qw(corefont)); __PACKAGE__->factory( 'PDF::API2::Page', 'page' ); package PDF::API2::Page; ## no critic our @ISA = 'Mock'; __PACKAGE__->factory( 'PDF::API2::Content', 'gfx' ); __PACKAGE__->factory( 'PDF::API2::Content::Text', 'text' ); package PDF::API2::Content; ## no critic our @ISA = 'Mock'; __PACKAGE__->set_true( qw(strokecolor linewidth linedash move hline vline fillcolor stroke rect fill)); package PDF::API2::Content::Text; ## no critic our @ISA = 'Mock'; __PACKAGE__->set_true(qw(font fillcolor translate text text_center text_right)); sub advancewidth { shift; return 5 * length shift } } return 1; PDF-Table-1.005/xt/0000755000000000000000000000000014365336110012310 5ustar rootrootPDF-Table-1.005/xt/manifest.t0000644000000000000000000000063414261160700014301 0ustar rootroot#!perl -T use 5.010; use strict; use warnings FATAL => 'all'; use Test::More; my $min_tcm = 0.9; # Windows: SET AUTHOR_TESTING=1 BEGIN { unless ($ENV{'AUTHOR_TESTING'}) { print qq{1..0 # SKIP Test::CheckManifest, for testing by the author\n}; exit } } eval "use Test::CheckManifest $min_tcm"; plan skip_all => "Test::CheckManifest $min_tcm required" if $@; ok_manifest(); 1; PDF-Table-1.005/xt/pod.t0000644000000000000000000000063114261160700013252 0ustar rootroot#!/usr/bin/perl use strict; use warnings; use Test::More; my $min_ver = 1.52; # was 1.00, for Test::Pod # Windows: SET AUTHOR_TESTING=1 BEGIN { unless ($ENV{'AUTHOR_TESTING'}) { print qq{1..0 # SKIP Test::Pod, for testing by the author\n}; exit } } eval "use Test::Pod $min_ver"; plan skip_all => "Test::Pod $min_ver required for testing POD" if $@; all_pod_files_ok(); 1; PDF-Table-1.005/Changes0000644000000000000000000002746214365336064013173 0ustar rootrootChange history for Perl extension PDF::Table. === Version 1.005 (2023-01-28) lib/PDF/Table.pm Update cell checking when using markup, so that anything which CAN be by default stringified, will be. Some customers are using default or implicit stringification of objects, which was being caught as an unsupported data type, and rendered as "(invalid)" in a cell. The downside is that if you send something nonsensical (e.g., reference to a SCALAR), you will see the stringified reference (address), as done in the 1.003 and earlier versions. Makefile.PL remove PROVIDES clause, as was getting build warnings about it. === Version 1.004 (2023-01-21) lib/PDF/Table.pm, lib/PDF/Table.pod, INFO/SPONSORS (new), INFO/Table.html, MANIFEST For PDF::Builder ONLY, allow specification of cell 'markup' (Markdown or HTML), to permit great flexibility in cell content. See PDF::Builder's examples/Column.pl for an example of usage. This work (as well as markup changes for PDF::Builder) has been kindly sponsored by Amtivo Group (see INFO/SPONSORS). lib/PDF/Table.pm, examples/sample1-size-vsizes.pl The 'Times' font should be named 'Times-Roman', to conform with the correct core font naming. PDF::Builder no longer silently accepts 'Times' as an alias for 'Times-Roman', and now gives a warning. xt/manifest.t, xt/pod.t, MANIFEST, util/2_t-tests.pl Move author tests from t/ to xt/ examples/chess.pl PDF::API2 (PREVIOUS to release 2.044) has a bug in its TTF handling, where it fails to translate some Unicode points ("U+nnnn" number) to the appropriate font glyph entry, and instead puts the Unicode point in the glyph list. This is incorrect, and usually results in a mismapping. As of PDF::API2 v 2.044, chess.pl seems to be working again. examples/*.pl If command line -A or -B, add prefix A_ or B_ to the output file name. This can be useful when using -A or -B with util/3_examples.pl to generate different output PDFs for PDF::API2 and PDF::Builder. Keep in mind that an example given without -A or -B will not add the prefix. lib/PDF/Table.pm, lib/PDF/Table.pod, INFO/Table.html, examples/vsizes.pl (new), util/3_examples.pl Dry run to return vertical size (overall, header, [footer], each row), no output to PDF, with "ink" set to 0. lib/PDF/Table.pod (moved), MANIFEST, util/pod2cpanhtml.pl, Makefile.PL Move .pod up a level (thanks to "perlpunk") lib/PDF/Table/Table.pod, INFO/Table.html, examples/chess.pl, INFO/Changes_2019, lib/PDF/Table.pm Typos caught by lintian (via emollier) and codespell (via mdeweerd). CONTRIBUTING, MANIFEST add Contribution guide === Version 1.003 (2022-07-05) lib/PDF/Table/ColumnWidth.pm, lib/PDF/Table/Table.pod, examples/size.pl, MANIFEST, util/3_examples.pl Add the ability to specify fixed and relative sizes for column widths, rather than having to accept system-calculated widths. You give a string to the 'size' optional global setting specifying the absolute width of a column (in, pt, cm, mm, em, or ex units), and/or a unit of '*' to indicate remaining space is to be split up among these columns. lib/PDF/Table.pm, lib/PDF/Table/Settings.pm, MANIFEST Split out deprecated_settings and check_settings functions into new file. lib/PDF/Table.pm, lib/PDF/Table/ColumnWidth.pm, MANIFEST, t/PDF-Table.t Split out CalcColumnWidths function into new file. examples/chess.pl PDF::API2 work-around added for font-handling change in 2.043. The problem is being investigated, but the chess example almost works for now. lib/PDF/Table.pm, lib/PDF/Table/Table.pod, MANIFEST Split out documentation into separate POD file. lib/PDF/Table.pm Fix handling of degenerate case of header-only, without data rows (#71). lib/PDF/Table.pm, t/PDF-Table.t Finish cleanup of column width calculations (#68, #72). Makefile.PL, LICENSE, MANIFEST.SKIP Build (at install) META.* with "provides" member. Add separate license file. Add some items to MANIFEST SKIP file to clean up. lib/PDF/Table.pm $LAST_UPDATE changed from 'my' storage class to 'our', so can be accessed programmatically. lib/PDF/Table.pm Absolute minimum with of a column reset to at least $min_col_width (a new global default) to prevent text_block() width errors. Update build process to ensure consistent "unix" formatting of most human-readable files. Some non-CPAN builds were complaining about MS-DOS format (CRLF line ends) on some files. lib/PDF/Table.pm, examples/chess.pl, t/PDF-Table.t Fix handling of max_w [GitHub #68], rewrite column width calculations. This may result in some noticable changes in column widths from before. lib/PDF/Table.pm Remove requirement that "empty cell" text not be an empty string (allow $empty_cell_text to be ''), permitting completely empty cells. lib/PDF/Table.pm minor comment updates README.md, lib/PDF/Table.pm, INFO/Table.html 2022 copyright. NOT archiving Changes yet. === Version 1.002 (2020-12-27) README.md, lib/PDF/Table.pm, Makefile.PL Miscellaneous updates to clean up support URLs, emails, etc. util/pod2cpanhtml.pl Remove use of search.cpan.org CSS reference, as that site no longer exists. Looking for a good replacement, possibly Bootstrap, that doesn't require that a phone be turned to landscape orientation in order to read text at a decent size. lib/PDF/Table.pm Cells spanning columns only had the first part (cell) of the bottom horizontal rule drawn. Reported by "stefanalt". Fixed to draw full spanned width. t/PDF-Table.t One calculated value was considerably different between standard Perl (uses doubles for floats), long-double Perl, and quad-math Perl. Round the calculated value to 6 decimal digits so that it works on any system. === Version 1.001 (2020-11-05) lib/PDF/Table.pm fix edge case where no borders led to no rules [GH 55]. t/manifest.t, t/pod.t Make author-only (AUTHOR_TESTING=1). ref [GH 61] lib/PDF/Table.pm, t/pod.t POD change =head5 to =head4, to look better and stop older POD checkers from complaining (in t/pod.t). Also minimum Test::Pod version 1.52 (was 1.00). ref [GH 61]. examples/sample1.pl, t/lib/TestData.pm, INFO/Deprecated, lib/PDF/Table.pm Replace deprecated setting names by current names in the POD, examples, and t-tests. After November 2022, settings names (args) with a leading dash (hyphen) will no longer be permitted. === Version 1.000 (2020-11-03) INFO/Deprecated, INFO/Table.html, lib/PDF/Table.pm Final cleanup of POD and generation of HTML documentation, and listing of all deprecated setting names. t/lib/PDFAPI2Mock.pm add linedash dummy call so t tests can run. lib/PDF/Table.pm, MANIFEST, examples/border_rules.pl, util/3_examples.pl Old "borders" was vertical and horizontal rules PLUS outside rules (frame). Separate into "borders" (outside) and "rules" (inside). Add border_rules.pl example to illustrate. examples/chess.pl with DejaVu-Sans, can use chess piece images .github/worksflows/test.yml, README.md minor fixes in README to make lint run happily, stop checking Table.html. examples/*.pl Allow -A or -B on the command line (case insensitive) to override PDFpref file (if any) setting. This speeds up testing for PDF::API2 vs PDF::Builder (default). lib/PDF/Table.pm, INFO/Deprecated, INFO/Table.html, MANIFEST, examples/chess.pl, t/PDF-Table.t, t/lib/PDFAPI2Mock.pm, util/3_examples.pl Clean up handling of minimum and maximum cell widths (min_w and max_w). Clean up handling of background and foreground colors. Add chess.pl example to show off color handling. Update t-tests for slight coordinate changes. Add row_props (row properties) similar to column_props, to set things on a per-row basis. If the table spills over to a new page, and next_y and/or next_h was NOT given, issue a warning and for a default use 90% of the media height for next_y and 80% for next_h (ref ticket #11). This should be better than using the (start_)y and (start_)h values for the table. Add new, more consistent aliases for a number of settings (ref ticket #13). The old setting names are still available for at least TWO YEARS, after which, they will be REMOVED. Over the next two years you should update your code to use the new setting names. The settings involved are: 'start_y' is now 'y' 'start_h' is now 'h' 'row_height' is now 'min_rh' 'background_color' is now 'bg_color' 'background_color_odd' is now 'bg_color_odd' 'background_color_even' is now 'bg_color_even' 'font_color' is now 'fg_color' 'font_color_odd' is now 'fg_color_odd' 'font_color_even' is now 'fg_color_even' 'font_underline' is now 'underline' 'lead' is now 'leading' These are listed in INFO/Deprecated. In the near future, the examples and t-tests will be updated to use the new setting names. Ship with Table.html (documentation) in INFO/. Update MANIFEST. Remove 010_fonts.pl from the util/3_examples.pl list. I'm still not sure why it should be in the examples -- basically, it shows that UTF-8 doesn't work with core fonts, but that's already a documented limitation (in PDF::Builder). 010_fonts.pl is still in the examples/ directory, if anyone wants to play with it. Add INFO/Deprecated to list names and interfaces scheduled to be removed in the future (at least 2 years). MANIFEST updated. Split out older Changes list into INFO/Changes_2019. MANIFEST updated. Increase default cell padding to 2pt. See documentation "COMPATIBILITY" for how to get the old behavior (0pt padding). t/Basics.t, t/Colspan.t, t/PDF-Table.t expected write locations updated. examples/colspan.pl and examples/header.pl were widened slightly to accommodate the padding. Make "odd/even" row consistent with or without a header (repeated or not), particularly when a table is split across pages, and when a row itself is split in such a case. See documentation "COMPATIBILITY" for how to get the old behavior. Header 'repeat' default changed from 0 (no) to 1 (yes), as most of the time a user will want to repeat any header on each new page. Suppress repeating a header with a value of 0. See documentation "COMPATIBILITY" for how to get the old behavior. Currently, PDF::Table is shipped to use the new behaviors, with as much compatibility as possible with existing code (see $compat_mode in Table.pm). Unless you have need to use the old behaviors for existing code, we suggest that you leave $compat_mode as 0, use the 'compatibility' setting, or individually set the flags, to make use of the new behaviors. Also use the new settings names, unless there is a need for compatibility in existing code. Eventually, use of the old names will produce warnings, and later, error messages, but the old behaviors should be available for a long time. You should examine your existing code and plan to update it over time. Initialize %arg entries (defaults) so no uninitialized errors. #57 reported by Larry Leszczynski (larryl) for text_block() along with PR. Minor build process cleanup Minor spelling and typo fixes in POD and examples === Version 0.12.0 (2020-04-09) Permit either PDF::API2 or PDF::Builder (#51) Don't use UTF-8 with corefonts General cleanup of typos and misspellings in Table.pm Minimum Perl 5.10 in Makefile.PL (#53) More cleanup of text in Table.pm Add tools (util) for running PerlCritic, t-tests, examples Clean up code to pass PerlCritic Clean up examples to run with either API2 or Builder. PDFpref file to declare which to use if both available Comments in t tests about use of Mock PDFAPI2 Document needed and optional prerequisite modules (see INFO/Changes_2019 for earlier changes) PDF-Table-1.005/PDFpref0000644000000000000000000000012014365336064013067 0ustar rootrootPDF::Builder # choice for testing. must be in same directory as running program PDF-Table-1.005/CONTRIBUTING.md0000644000000000000000000000533614353113123014107 0ustar rootroot# Contributing to the development of PDF::Table **Working on your first Pull Request?** You can learn how from this *free* series [How to Contribute to an Open Source Project on GitHub](https://kcd.im/pull-request) We would appreciate the community around us chipping in with code, tests, documentation, and even just bug reports and feature requests. It's better knowing what users of PDF::Table want and need, than for us to guess. It's not good to spend a lot of time working on something that no one is interested in! You can contribute to the discussion by posting bug reports, feature requests, observations, etc. to the [GitHub issues area](https://github.com/ PhilterPaper/PDF-Table/issues?q=is%3Aissue+sort%3Aupdated-desc "issues") (please tag new threads accordingly, using ["Labels"], if possible). For code changes, a GitHub pull request, a formal patch file (e.g., "diff"), or even a replacement file or manual patch will do, so long as it's clear where it goes and what it does. If the volume of such work becomes excessive (i.e., a burden to us), we reserve the right to limit the ways that code changes can be submitted. At this point, the volume is low enough that almost anything can be handled. Please DO NOT send us code changes "out of the blue" (without prior discussion), unless they are very small, so that you're not out a lot of effort if we decline the offer. ## Do NOT... Do NOT under ANY circumstances open a PR (Pull Request) to **report a _bug_.** It is a waste of both _your_ and _our_ time and effort. Open a regular ticket (issue), and attach a Perl (.pl) program illustrating the problem, if possible. If you believe that you have a program patch (i.e., a permanent change to the code), and offer to share it as a PR, we may give the go-ahead. Unsolicited PRs may be closed without further action. Please do not start on a massive project (especially, new function), without discussing it with us first (via email or one of the discussion areas). This will save you the disappointment of seeing your hard work rejected because it doesn't fit in with what's going on with the rest of the PDF::Table project. You are free to try contributing anything you want, or even to fork the project if you don't like the direction it's taking. Keeping in touch and coordinating with us ensures that your work won't be wasted. If you have something dependent on PDF::Table functionality, but it doesn't fit our roadmap for core functionality, we may suggest that you release it as a separate package on CPAN (dependent on PDF::Table), or as a new sub-package to be under PDF::Table (e.g., like PDF::API2::Ladder), under either our ownership or yours. Good luck, and best wishes using and helping with PDF::Table! December, 2022 PDF-Table-1.005/LICENSE0000644000000000000000000000071714365336064012677 0ustar rootrootCopyright (C) 2006 by Daemmon Hughes Extended by Desislav Kamenov (Twitter @deskata) versions 0.02 - 0.11 Extended by Phil Perry since version 0.12. Copyright (C) 2020 - 2023 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 now the minimum for installation. PDF-Table-1.005/util/0000755000000000000000000000000014365336755012651 5ustar rootrootPDF-Table-1.005/util/pod2cpanhtml.pl0000644000000000000000000000203614365336065015574 0ustar rootroot#!/usr/bin/env perl -w #This script has been taken from a forum somewhere in the vast Internet space :) #Its purpose is to generate the HTML from POD and apply some CSS as it will look like on CPAN #Typical use: perl pod2cpanhtml.pl lib/PDF/Table.pod pdftable.html use strict; use warnings; use Pod::Simple::HTML; our $VERSION = '1.005'; # VERSION our $LAST_UPDATE = '1.000'; # manually update whenever code is changed my $parser = Pod::Simple::HTML->new(); my ($IN, $OUT); if (defined $ARGV[0]) { open $IN, '<', $ARGV[0] or die "Couldn't open $ARGV[0]: $!\n"; } else { $IN = \*STDIN; } if (defined $ARGV[1]) { open $OUT, '>', "$ARGV[1]" or die "Couldn't open $ARGV[1]: $!\n"; } else { $OUT = \*STDOUT; } $parser->index(1); # site no longer exists. TBD see if there is some good replacement out there, # preferably one that doesn't require turning a phone to landscape mode in # order to see text at a decent size. #$parser->html_css('http://search.cpan.org/s/style.css'); $parser->output_fh(*$OUT); $parser->parse_file(*$IN); PDF-Table-1.005/util/3_examples.pl0000644000000000000000000000711414365336065015243 0ustar rootroot#!/usr/bin/perl # run examples test suite # roughly equivalent to examples.bat # you will need to update the %args list before running # author: Phil M Perry # adapted from PDF::Builder tool suite use strict; use warnings; our $VERSION = '1.005'; # VERSION our $LAST_UPDATE = '1.004'; # manually update whenever code is changed # dependent on optional packages: # command line: # -step = stop after each test to let the tester look at the PDF file # -cont = (default) run continuously to the end, to not tie up tester # -A (/^-?A(pi2)?/i) force use of PDF::API2 if installed # -B (/^-?B(uilder)?/i) force use of PDF::Builder if installed (default) my $pause; my (@example_list, @example_results); # push @example_list, "010_fonts.pl"; # push @example_results, "show examples of accented and other non-ASCII characters.\n"; push @example_list, "colspan.pl"; push @example_results, "demonstrate colspan=n table organization.\n"; push @example_list, "header.pl"; push @example_results, "demonstrate column headings.\n"; push @example_list, "header_repeat_with_cell_props.pl"; push @example_results, "demonstrate column headings with many properties.\n"; push @example_list, "row_height.pl"; push @example_results, "show table with various row heights specified.\n"; push @example_list, "sample1.pl"; push @example_results, "show a number of PDF::Table capabilities.\n"; push @example_list, "chess.pl"; push @example_results, "show a chessboard with some effects.\n"; push @example_list, "border_rules.pl"; push @example_results, "illustrate borders and rules effects.\n"; push @example_list, "size.pl"; push @example_results, "illustrate using size setting for column widths.\n"; push @example_list, "vsizes.pl"; push @example_results, "illustrate getting table size in advance.\n"; # run with perl examples/ [args] my %args; # if you do not define a file for a test (leave it EMPTY ''), it will be skipped # if any spaces in a path, make sure double quoted or use escapes # # colspan needs ______ and _________ # $args{'colspan'} = "blah blah"; my $lib = ''; # -A or -B, optional my $type; # -cont OR -step allowed (default -cont) # zero or one or two command line flags allowed (zero or one of -A|-B, # zero or one of -cont|-step, -cont is default). then any other args # passed on to program. while (@ARGV) { if ($ARGV[0] =~ m/^-?A(PI2)?/i) { $lib = '-A'; } elsif ($ARGV[0] =~ m/^-?B(uilder)?/i) { $lib = '-B'; } elsif ($ARGV[0] eq '-cont') { $type = '-cont'; } elsif ($ARGV[0] eq '-step') { $type = '-step'; } else { last; } splice @ARGV, 0, 1; # remove command line arg so <> will work } $type ||= '-cont'; # default $pause = ''; # some warnings: foreach my $test (@example_list) { if ($test eq '______') { print "$test: to display the resulting PDFs, you may need to install\n"; print " East Asian fonts for your PDF reader.\n"; $pause = ' '; } } if ($pause eq ' ') { print "Press Enter to continue: "; $pause = <>; } print STDERR "\nStarting example runs..."; my ($i, $arg); for ($i=0; $i; } PDF-Table-1.005/util/2_t-tests.pl0000644000000000000000000000320614365336065015025 0ustar rootroot#!/usr/bin/perl # run all "t" tests # must be run from parent of t/ # author: Phil M Perry # adapted from PDF::Builder tool suite use strict; use warnings; our $VERSION = '1.005'; # VERSION our $LAST_UPDATE = '0.12'; # manually update whenever code is changed my $perl = 'perl'; # run Perl command. add path, etc. if needed # command line flags, mutually exclusive: # -raw show full output of each t-test run # -noOK exclude "ok" lines so can easily spot error lines DEFAULT my @test_list = qw( Basics Colspan PDF-Table table ); # override full list above, and run just one or two tests #@test_list = qw( Colspan ); # moved to xt/ # manifest # pod my @need_T = qw( Colspan manifest ); # perl t/.t will run it my $type; # one command line arg allowed (-noOK is default) if (scalar @ARGV == 0) { $type = '-noOK'; } elsif (scalar @ARGV == 1) { if ($ARGV[0] eq '-raw') { $type = '-raw'; } elsif ($ARGV[0] eq '-noOK') { # default $type = '-noOK'; } else { die "Unknown command line argument '$ARGV[0]'\n"; } } else { die "0 or 1 argument permitted. -noOK is default.\n"; } my $TT = ''; foreach my $file (@test_list) { $TT = ''; foreach (@need_T) { if ($_ eq $file) { $TT = '-T'; last; } } my @results = `$perl $TT t/$file.t`; # TBD: detect if a FAILED test, and remark at end if any failures print "\nt/$file.t\n"; if ($type eq '-raw') { print "@results"; } else { # -noOK remove any lines which start with "ok" foreach my $line (@results) { if ($line !~ m/^ok/) { print $line; } } } } PDF-Table-1.005/util/1_pc.pl0000644000000000000000000001134614365336065014027 0ustar rootroot#!/usr/bin/perl # run perlcritic test suite # needless to say, 'perlcritic' command must be installed # author: Phil M Perry # adapted from PDF::Builder tool suite use strict; use warnings; our $VERSION = '1.005'; # VERSION our $LAST_UPDATE = '1.002'; # manually update whenever code is changed # command line: # -5 run perlcritic -5 . (should be clean) # -5x exclude certain common errors (none at this time) # -4 run perlcritic -4 . should get a number of common errors # -4x exclude certain common errors DEFAULT # -3 run perlcritic -3 . should get a number of errors # -3x exclude certain common errors # -2 run perlcritic -2 . should get more errors # -2x exclude certain common errors # -1 run perlcritic -1 . should get even more errors # -1x exclude certain common errors # # levels 1,2,3 are only for the morbidly curious! # (although some warnings look like they should be addressed) # output OK is always ignored my @ignore_list = ( # should not ignore any level 5 warnings "Use IO::Interactive::is_interactive", # not a core module! # common level 4 warnings to ignore # removed 'no warnings' in 3.021. remove next line 3.022 or later # "Code before warnings", # due to use of "no warnings" pragma # removed 'no warnings' in 3.021. remove next line 3.022 or later # "Warnings disabled at", # due to use of "no warnings" pragma "Close filehandles as soon as possible", # it thinks there is no "close" on an open # filehandle, due to either too many lines for # it to buffer, or use of other code to close "Always unpack ", # Always unpack @_ first at line # not using @_ or $_[n] directly is good practice, # but it doesn't seem to recognize legitimate uses "Subroutine name is a homonym for builtin function", # e.g., we define "open" when there is already a # system (CORE::) open (ambiguous unless CORE:: # added) "Symbols are exported by default", # it doesn't like something about our use of # @EXPORT and @EXPORT_OK "Pragma \"constant\" used at", # will have to investigate why "use constant" # is flagged. TBD # common level 3 warnings to ignore for now '"die" used instead of "croak"', # '"warn" used instead of "carp"', # 'Regular expression without "/x" flag', # "Backtick operator used", # "high complexity score", # "Cascading if-elsif chain", # "Hard tabs used at", # '"local" variable not initialized', # ); # Note that level 4 includes any level 5 errors, etc. # my $level; my @exclude; # leave empty unless "x" suffix # one command line arg allowed (-4x is default) if (scalar @ARGV == 0) { $level = '-4'; @exclude = @ignore_list; } elsif (scalar @ARGV == 1) { if ($ARGV[0] eq '-5') { $level = '-5'; } elsif ($ARGV[0] eq '-5x') { $level = '-5'; @exclude = @ignore_list; } elsif ($ARGV[0] eq '-4') { $level = '-4'; } elsif ($ARGV[0] eq '-4x') { # default $level = '-4'; @exclude = @ignore_list; } elsif ($ARGV[0] eq '-3') { $level = '-3'; } elsif ($ARGV[0] eq '-3x') { $level = '-3'; @exclude = @ignore_list; } elsif ($ARGV[0] eq '-2') { $level = '-2'; } elsif ($ARGV[0] eq '-2x') { $level = '-3'; @exclude = @ignore_list; } elsif ($ARGV[0] eq '-1') { $level = '-1'; } elsif ($ARGV[0] eq '-1x') { $level = '-1'; @exclude = @ignore_list; } else { die "Unknown command line argument '$ARGV[0]'\n"; } } else { die "0 or 1 argument permitted. -4 is default.\n"; } print STDERR "Calling perlcritic $level"; if (scalar @exclude > 0) { print STDERR ", with excluded warning list"; } print STDERR ". This can take several minutes to run!\n"; my @results = `perlcritic $level .`; # always remove " source OK" my @results2 = (); foreach my $line (@results) { if ($line !~ m/ source OK/) { push @results2, $line; } } if (scalar @exclude > 0 && scalar @results2 > 0) { @results = @results2; @results2 = (); # remove common errors foreach my $line (@results) { my $keep = 1; foreach (@exclude) { if ($line =~ m/$_/) { $keep = 0; last; } } if ($keep) { push @results2, $line; } } } if (scalar(@results2) == 0) { print STDERR "No errors reported.\n"; } else { print STDERR scalar(@results2)." errors reported:\n"; print "@results2"; } PDF-Table-1.005/META.json0000644000000000000000000000223114365336123013300 0ustar rootroot{ "abstract" : "A utility class for building table layouts in a PDF::Builder (or PDF::API2) object.", "author" : [ "Phil Perry" ], "dynamic_config" : 1, "generated_by" : "ExtUtils::MakeMaker version 7.66, CPAN::Meta::Converter version 2.150010", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "PDF-Table", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "perl" : "5.010" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/PhilterPaper/PDF-Table/issues" }, "repository" : { "url" : "https://github.com/PhilterPaper/PDF-Table" } }, "version" : "1.005", "x_serialization_backend" : "JSON::PP version 4.16" } PDF-Table-1.005/MANIFEST0000644000000000000000000000150614365336123013014 0ustar rootroot.perlcriticrc .perl-version Changes CONTRIBUTING.md examples/010_fonts.pl examples/colspan.pl examples/chess.pl examples/border_rules.pl examples/header.pl examples/header_repeat_with_cell_props.pl examples/PDFpref examples/row_height.pl examples/sample1.pl examples/size.pl INFO/Changes_2019 INFO/Deprecated INFO/SPONSORS INFO/Table.html lib/PDF/Table.pm lib/PDF/Table.pod lib/PDF/Table/ColumnWidth.pm lib/PDF/Table/Settings.pm LICENSE Makefile.PL MANIFEST MANIFEST.SKIP PDFpref README.md t/Basics.t t/Colspan.t t/lib/PDFAPI2Mock.pm t/lib/TestData.pm t/PDF-Table.t t/table.t xt/pod.t xt/manifest.t util/1_pc.pl util/2_t-tests.pl util/3_examples.pl util/pod2cpanhtml.pl META.yml Module YAML meta-data (added by MakeMaker) META.json Module JSON meta-data (added by MakeMaker) PDF-Table-1.005/MANIFEST.SKIP0000644000000000000000000000045614365336064013570 0ustar rootroot#Experimental/development/testing scripts and files ^experiment.*$ ^issue_scripts/.* #Backups .*\.old$ .*\.bak$ .*~ #Editor stuff .*\.swp$ #Blib folder ^blib/* #Git folder \.git #Hidden files ^\..* #Auto-generated files ^MYMETA.json$ ^MYMETA.yml$ ^Makefile$ #Build-related ^version$ ^RoadMap$ PDF-Table-1.005/README.md0000644000000000000000000000444514365336064013153 0ustar rootroot# PDF::Table This module creates text blocks and tables into PDF documents using the PDF::API2 or PDF::Builder Perl module. [![Open Issues](https://img.shields.io/github/issues/PhilterPaper/PDF-Table)](https://github.com/PhilterPaper/PDF-Table/issues) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](https://makeapullrequest.com) [![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://GitHub.com/PhilterPaper/PDF-Table/graphs/commit-activity) The official repository for PDF::Table module collaboration: "https://github.com/PhilterPaper/PDF-Table.git" Any patches, pull requests, issues and feedback are more than welcome. Do NOT under ANY circumstances open a PR (Pull Request) to report a bug. It is a waste of both your and our time and effort. Open a regular ticket (issue), and attach a Perl (.pl) program illustrating the problem, if possible. If you believe that you have a program patch, and offer to share it as a PR, we may give the go-ahead. Unsolicited PRs may be closed without further action. ## Prerequisites Required for installation: Test::More Optional for installation: Test::Pod, Test::CheckManifest Required for running: Carp, PDF::API2 and/or PDF::Builder Optional for running: Pod::Simple::HTML ## Installation To install the module from CPAN, please type the following command: ```cpanm PDF::Table``` To test or add features to this module, please type the following command: ```cpanm .``` ## Changes To see a list of changes, please do one or more of the following: - Read the [Changes](Changes) file - Review commits history on GitHub - Make a diff from the tools menu at CPAN ## Contacts - Use the issue tracker on GitHub, "https://github.com/PhilterPaper/PDF-Table/issues" - See "https://metacpan.org/pod/PDF::Table" for distribution and more information ## License Copyright (C) 2006 by Daemmon Hughes Extended by Desislav Kamenov (Twitter @deskata) versions 0.02 - 0.11 Extended by Phil Perry since version 0.12 Copyright (C) 2020 - 2023 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 now the minimum for installation. PDF-Table-1.005/Makefile.PL0000644000000000000000000000232614365336064013642 0ustar rootroot#! perl use strict; use warnings; use 5.010; use ExtUtils::MakeMaker; # See lib/ExtUtils/MakeMaker.pm for details of how to influence # the contents of the Makefile that is written. WriteMakefile( NAME => 'PDF::Table', VERSION_FROM => 'lib/PDF/Table.pm', # finds $VERSION MIN_PERL_VERSION => 5.010000, # Perl 5.10 minimum LICENSE => 'perl_5', PREREQ_PM => {}, # e.g., Module::Name => 1.1 # modules you MAY have to (or want to) install: # Build and install: # Test::Pod (can test without, tests if present) # Test::CheckManifest (can test without, tests if present) # Test::More (required) (is core) # Run time: # Pod::Simple::HTML (for POD->HTML generation, optional) (is core) # Carp (required) (is core) # And of course, PDF::API2 *OR* PDF::Builder (both can be installed) ABSTRACT_FROM => 'lib/PDF/Table.pod', # retrieve abstract from module AUTHOR => 'Phil Perry', META_MERGE => { resources => { bugtracker => 'https://github.com/PhilterPaper/PDF-Table/issues', repository => 'https://github.com/PhilterPaper/PDF-Table', }, }, ); PDF-Table-1.005/lib/0000755000000000000000000000000014365336755012442 5ustar rootrootPDF-Table-1.005/lib/PDF/0000755000000000000000000000000014365336110013034 5ustar rootrootPDF-Table-1.005/lib/PDF/Table/0000755000000000000000000000000014365336755014102 5ustar rootrootPDF-Table-1.005/lib/PDF/Table/ColumnWidth.pm0000644000000000000000000003103614365336063016670 0ustar rootrootpackage PDF::Table::ColumnWidth; use strict; use warnings; use Carp; use List::Util qw[min max]; # core our $VERSION = '1.005'; # VERSION our $LAST_UPDATE = '1.003'; # manually update whenever code is changed ################################################################### # calculate the column widths # minimum: any specified min_w, increased to longest word in column # maximum: largest total length of content, reduced to any spec. max_w # maximum must be at least as large as minimum # TBD: rules and borders? currently overlay cells. consider # expanding h and w by width of rules and borders. would involve # mucking with cell background fill dimensions? remember that # rule widths could vary by cell. perhaps could just increase cell # dimensions (and padding) by rule widths, and continue to overlay? # expand min widths to fill to desired total width, try not to # exceed maximum widths # NOTE: this routine is called directly from t/PDF-Table.t ################################################################### sub CalcColumnWidths { my $avail_width = shift; # specified table width my $col_min_width = shift; # content-driven min widths (longest word) and # optional min_w my $col_max_content = shift; # content-driven max widths my $max_w = shift; # -1 unless optional max_w for column my $min_width = 0; # calculate minimum overall table width needed my $calc_widths ; # each column's calculated width my $num_cols = scalar(@$max_w); # total requested minimum width (min_w property) plus min for content # also initialize result calc_widths to min_width for (my $j = 0; $j < scalar $num_cols; $j++) { # min_w requested minimum AND longest word $calc_widths->[$j] = $col_min_width->[$j]; # overall table minimum width $min_width += $calc_widths->[$j]; } # minimum possible width for each column results in wider table? if ($avail_width < $min_width) { carp "!!! Warning !!!\n Table width expanded from $avail_width to $min_width\n"; $avail_width = $min_width; } # Calculate how much can be added to every column to fit the available width # Allow columns to expand to max_w before applying extra space equally. # @max is SMALLER of max_w (if given) and content length, but at least as # large as $col_min_width my (@max, @natural, @indices); # @max = absolute widest this column can be # initially max_w if given (>0), else table width for (my $col=0; $col<$num_cols; $col++) { $max[$col] = $avail_width; if ($max_w->[$col] > 0) { $max[$col] = min($max[$col], $max_w->[$col]); } $max[$col] = max($max[$col], $col_min_width->[$col]); } # @natural = width fraction of avail_width, based only on content size # ($col_max_content), before any limits applied my $sum_content_size = 0; for (my $col=0; $col<$num_cols; $col++) { $sum_content_size += $col_max_content->[$col]; } $sum_content_size /= $avail_width; for (my $col=0; $col<$num_cols; $col++) { $natural[$col] = $col_max_content->[$col]/$sum_content_size; } # loop to adjust sizes, after setting size to natural #my $old_total_delta = -1; my $total_delta = 0; my $again = 1; for (my $col=0; $col<$num_cols; $col++) { $calc_widths->[$col] = $natural[$col]; } while ($again) { $again = 0; # let expand to satisfy min be offset by contract to satisfy max # note that $total_delta adjusted from previous loop, not restarted for (my $col = 0; $col < $num_cols; $col++) { if ($calc_widths->[$col] < $col_min_width->[$col]) { $total_delta += $col_min_width->[$col] - $calc_widths->[$col]; $calc_widths->[$col] = $col_min_width->[$col]; } elsif ($calc_widths->[$col] > $max[$col]) { $total_delta -= $calc_widths->[$col] - $max[$col]; $calc_widths->[$col] = $max[$col]; } } # total_delta within +/-.1% of avail_width? we're done! if (abs($total_delta) <= 0.001*$avail_width) { last; } my $change_amt; if ($total_delta > 0) { # net was we expanded more to satisfy min, so reduce any column # not at min, proportional to content (natural) @indices = (); # @indices lists all columns NOT already at min $sum_content_size = 0; for (my $col=0; $col<$num_cols; $col++) { if ($calc_widths->[$col] == $col_min_width->[$col]) { next; } push @indices, $col; $sum_content_size += $col_max_content->[$col]; } if (!scalar @indices || $sum_content_size <= 0) { # everyone at min but need to reduce... should NOT see this carp "Problem... need to reduce column widths, but all already at minimum!"; last; } my $max_reduce_size; $sum_content_size /= $total_delta; foreach my $col (@indices) { $max_reduce_size = $calc_widths->[$col] - $col_min_width->[$col]; # change amount is positive $change_amt = $col_max_content->[$col]/$sum_content_size; $change_amt = min($change_amt, $max_reduce_size); $calc_widths->[$col] -= $change_amt; $total_delta -= $change_amt; $again = 1; } } else { # total_delta < 0 # net was we contracted more to satisfy max, so expand any column # not at max, proportional to content (natural) @indices = (); # @indices lists all columns NOT already at max $sum_content_size = 0; for (my $col=0; $col<$num_cols; $col++) { if ($calc_widths->[$col] == $max[$col]) { next; } push @indices, $col; $sum_content_size += $col_max_content->[$col]; } if (!scalar @indices || $sum_content_size <= 0) { # everyone at max but need to increase... should NOT see this carp "Problem... need to increase column widths, but all already at maximum!"; last; } my $max_increase_size; $sum_content_size /= $total_delta; foreach my $col (@indices) { $max_increase_size = $max[$col] - $calc_widths->[$col]; # change amount is positive $change_amt = -$col_max_content->[$col]/$sum_content_size; $change_amt = min($change_amt, $max_increase_size); $calc_widths->[$col] += $change_amt; $total_delta += $change_amt; $again = 1; } } # if-elsif to handle decrease or increase by total_delta } # while($again) loop return ($calc_widths, $avail_width); } # End of CalcColumnWidths() ################################################################### # set the column widths per 'size' string # width = available width of table (points) # size = string describing each column's width # NvalUnit for each, where Nval is a positive number # (default 1) and Unit is an optional unit or float # specifier. Nval, or Unit, or both must be given for # each column. # If Unit not given, the number is assumed to be Points # (1/72 inch). Permitted units are cm, mm, in, em, ex, pt # (any case). # returned values are array of column widths (points) and # total width (points), increased if necessary ################################################################### sub SetColumnWidths { my $avail_width = shift; # specified table width my $size = shift; # width specifications my $em_size = shift; # size of em in points my $ex_size = shift; # size of ex in points my @colspecs = split /\s+/, $size; if (!scalar @colspecs) { die "!! Error !!\nNo column width specifications found in size '$size'!\n"; } my ($calc_widths, $float_widths, $number, $unit); for (my $col=0; $col 1 inch } else { # unable to disassemble this entry, including negative numbers carp "!! Warning !!\nUnable to decode column $col entry '$colspecs[$col]', using '*' instead\n"; $number = 1; $unit = '*'; } # see if legal number \d+, \d+., \d+.\d+, .\d+ if ($number =~ m#^\d+$# || $number =~ m#^\d+\.$# || $number =~ m#^\d+\.\d+$# || $number =~ m#^\.\d+$#) { # valid number, use $number } else { # invalid number format, replace by 1 # can detect multiple decimal points, but no check for range carp "!! Warning !!\nInvalid number '$number' in column $col, using '1' instead.\n"; $number = 1; } # see if legal unit *, pt, in, cm, mm, em, ex # if so, convert to points, add to calc_widths array if ($unit =~ m#^\*$#) { $calc_widths->[$col] = -1; # mark as floating for now $float_widths->[$col] = $number; } elsif ($unit =~ m#^pt$#i) { $calc_widths->[$col] = $number; $float_widths->[$col] = -1; } elsif ($unit =~ m#^in$#i) { $calc_widths->[$col] = $number * 72; $float_widths->[$col] = -1; } elsif ($unit =~ m#^cm$#i) { $calc_widths->[$col] = $number * 72 / 2.54; $float_widths->[$col] = -1; } elsif ($unit =~ m#^mm$#i) { $calc_widths->[$col] = $number * 72 / 25.4; $float_widths->[$col] = -1; } elsif ($unit =~ m#^em$#i) { $calc_widths->[$col] = $number * $em_size; $float_widths->[$col] = -1; } elsif ($unit =~ m#^ex$#i) { $calc_widths->[$col] = $number * $ex_size; $float_widths->[$col] = -1; } else { # invalid unit, replace by mm carp "!! Warning !!\nInvalid unit '$unit' in column $col, using 'mm' instead.\n"; $unit = 'mm'; $calc_widths->[$col] = $number * 72 / 25.4; $float_widths->[$col] = -1; } } # loop through columns $col # calc_widths -1 need updating from float_widths # first need to calculate available space to allocate (if < 1 pt, increase # width with warning). divide by sum of float_widths to get size of 1*, # and finally, transfer to calc_widths. my $width_used = 0; # used for fixed widths, non-* my $total_float = 0; # sum up float_widths for (my $col=0; $col[$col] > 0) { # we have a float (*) to handle $total_float += $float_widths->[$col]; } else { # presumably a fixed value $width_used += $calc_widths->[$col]; } } # check if width_used exceeds available width! if ($width_used > $avail_width) { carp "!! Warning !!\nSum of fixed widths ($width_used) exceeds available width ($avail_width), increase width.\n"; $avail_width = $width_used; } # if == 0, should already be valid number (width in pts) in all calc_widths if ($total_float > 0) { # at least one * entry to allocate among at least 1 pt of space # first, how much space to allocate, or does width need to be increased? if ($avail_width - $width_used < 1) { # too little space available, must increase total width carp "!! Warning !!\nToo little space (".($avail_width-$width_used)."pts) to allocate among floats.\nIncrease table width by 5em per float unit.\n"; $avail_width += 5*$em_size*$total_float; } # have SOME room to allocate, so how many points per *? my $star_size = ($avail_width - $width_used)/$total_float; # should be a positive value for (my $col=0; $col[$col] > 0) { $calc_widths->[$col] = $star_size * $float_widths->[$col]; } } } # no floating column widths, and total of fixed < available width if ($total_float == 0 && $width_used < $avail_width) { carp "!! Warning !!\nAllocated width is narrower than specified table width. Reduce table width.\n"; $avail_width = $width_used; } # other choice would be to increase all columns by same percentage return ($calc_widths, $avail_width); } # End of SetColumnWidths() 1; PDF-Table-1.005/lib/PDF/Table/Settings.pm0000644000000000000000000001550314365336063016234 0ustar rootrootpackage PDF::Table::Settings; use strict; use warnings; use Carp; our $VERSION = '1.005'; # VERSION our $LAST_UPDATE = '1.003'; # manually update whenever code is changed ########################################################### # move deprecated settings names to current names, and delete old # assume any leading '-' already removed # warning if both deprecated and new name given (use new) # release at T-6 months, consider issuing warning to remind update needed # release at T-0 months, give warning on use of deprecated items # release at T+12 months, remove deprecated names ############################################################ sub deprecated_settings { my ($data, $row_props, $col_props, $cell_props, $header_props, $argref) = @_; # 1 $row_props, 2 $col_props, 3 $cell_props, 4 $header_props # need to use $_[n] form so that its call be reference, not value #my $data = $_[0]; #my $argref = $_[5]; #my %arg = %{$argref}; my %cur_names = ( # old deprecated name new current name # (old_key) 'start_y' => 'y', 'start_h' => 'h', 'row_height' => 'min_rh', 'background_color' => 'bg_color', 'background_color_odd' => 'bg_color_odd', 'background_color_even' => 'bg_color_even', 'font_color' => 'fg_color', 'font_color_odd' => 'fg_color_odd', 'font_color_even' => 'fg_color_even', 'font_underline' => 'underline', #'justify' => 'align', # different set of values allowed 'lead' => 'leading', 'border' => 'border_w', 'horizontal_borders' => 'h_border_w', 'vertical_borders' => 'v_border_w', 'border_color' => 'border_c', # currently same color for H and V borders ); # global arg foreach my $old_key (keys %cur_names) { if (defined $argref->{$old_key}) { # set deprecated name setting (need to transfer to new name). # did we also set new name setting? if (defined $argref->{$cur_names{$old_key}}) { carp "!! Warning !! both deprecated global name '$old_key' and current name '$cur_names{$old_key}' given, current name's value used."; } else { $argref->{$cur_names{$old_key}} = $argref->{$old_key}; delete $argref->{$old_key}; # eventually given warning to stop using $old_key } } } # row properties foreach my $old_key (keys %cur_names) { for (my $row = 0; $row < scalar(@$data); $row++) { if (defined $row_props->[$row]->{$old_key}) { # set deprecated name setting (need to transfer to new name). if (defined $row_props->[$row]->{$cur_names{$old_key}}) { # did we also set new name setting? carp "!! Warning !! both deprecated name '$old_key' and current name '$cur_names{$old_key}' given in row_props[$row], current name's value used."; } else { # transfer deprecated setting to new $row_props->[$row]->{$cur_names{$old_key}} = $row_props->[$row]->{$old_key}; delete $row_props->[$row]->{$old_key}; # eventually given warning to stop using $old_key } } } } # column properties foreach my $old_key (keys %cur_names) { for (my $col = 0; $col < scalar(@{$col_props}); $col++) { if (defined $col_props->[$col]->{$old_key}) { # set deprecated name setting (need to transfer to new name). if (defined $col_props->[$col]->{$cur_names{$old_key}}) { # did we also set new name setting? carp "!! Warning !! both deprecated name '$old_key' and current name '$cur_names{$old_key}' given in column_props[$col], current name's value used."; } else { # transfer deprecated setting to new $col_props->[$col]->{$cur_names{$old_key}} = $col_props->[$col]->{$old_key}; delete $col_props->[$col]->{$old_key}; # eventually given warning to stop using $old_key } } } } # cell properties foreach my $old_key (keys %cur_names) { for (my $row = 0; $row < scalar(@$data); $row++) { for ( my $col = 0; $col < scalar(@{$data->[$row]}); $col++ ) { if (defined $cell_props->[$row][$col]->{$old_key}) { # set deprecated name setting (need to transfer to new name). if (defined $cell_props->[$row][$col]->{$cur_names{$old_key}}) { # did we also set new name setting? carp "!! Warning !! both deprecated name '$old_key' and current name '$cur_names{$old_key}' given in cell_props[$row][$col], current name's value used."; } else { # transfer deprecated setting to new $cell_props->[$row][$col]->{$cur_names{$old_key}} = $cell_props->[$row][$col]->{$old_key}; delete $cell_props->[$row][$col]->{$old_key}; # eventually given warning to stop using $old_key } } } } } # header properties if ($header_props) { foreach my $old_key (keys %cur_names) { if (defined $header_props->{$old_key}) { # set deprecated name setting (need to transfer to new name). # did we also set new name setting? if (defined $header_props->{$cur_names{$old_key}}) { carp "!! Warning !! both deprecated header name '$old_key' and current name '$cur_names{$old_key}' given, current name's value used."; } else { $header_props->{$cur_names{$old_key}} = $header_props->{$old_key}; delete $header_props->{$old_key}; # eventually given warning to stop using $old_key } } } } return; } # end of deprecated_settings() ############################################################ # validate/fix up settings and parameters as much as possible TBD per #12 ############################################################ sub check_settings { my (%arg) = @_; # TBD $arg{} values, some col, row, cell, header? # x, y >= 0; w, h >= 0; x+w < page width; y+h < page height # next_h (if def) > 0, next_y (if def) >= 0; next_y+next_h < page height # line widths >= 0, min_rh > 0 # TBD in general, validate integer values and possibly some # other values, per #12 return; } # end of check_settings() 1; PDF-Table-1.005/lib/PDF/Table.pod0000644000000000000000000013757014365335316014613 0ustar rootroot=pod =head1 NAME PDF::Table - A utility class for building table layouts in a PDF::Builder (or PDF::API2) object. =head1 SYNOPSIS Rather than cluttering up the following documentation with B<(or PDF::API2)> additions, wherever it refers to C, understand that you can substitute C to use that product instead. 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(); ... =head2 EXAMPLE For a complete working example or initial script look into distribution's 'examples' folder. =head1 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 C 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 L section for complete documentation of every parameter. =head1 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 C. You can change settings here to match old behaviors: =over =item repeating headers The old default for the C 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 C<$repeat_default> from 1 to 0 to get the old behavior (or, explicitly give C 0> in the header properties settings). =item 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 C<$oddeven_default> from 1 to 0 to get the old behavior. =item default cell padding The old default for padding around the contents of a cell was 0. It is now 2pt. Change C<$padding_default> from 2 to 0 to get the old behavior. =item behavior of borders The old behavior was calling both the frame around the table I 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 C 0> (to hide interior rules) or another width (line weight) may still be needed to override the "border" setting for interior dividers. =back =head2 Maintaining compatibility Near the top of file Table.pm, look for C. PDF::Table is shipped with a flag of C<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 C<1>. Note that a flag of C<1> will break some of the t-tests, because of different padding defaults resulting in different text locations on the page. =head2 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 I 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. =head1 METHODS =head2 new() my $pdf_table = new PDF::Table; or my $pdf_table = PDF::Table->new(); =over =item Description Creates a new instance of the class. =item 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). =item Returns Reference to the new instance =back =head2 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) =over =item Description Generates a multi-row, multi-column table into an existing PDF document, based on provided data set and settings. =item 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 B<$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 ]; B If you wish to enable I (Markdown or HTML) for a cell, C<$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 C 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', '

This is green text.

', { 'font-family'=>'Serif', 'font-size'=>15, 'para'=>[0,0] } ] Remember, this works only with PDF::Builder, and I 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 C table parameter to specify relative cell widths. B For full C<%settings> description see section L below. This method will add more pages to the PDF instance as required, based on the formatting options and the amount of data. =item 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 (C<'ink' =E 0>), the return value is an C 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 C 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 I 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 I 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: 1. The table data must be refreshed before calling the table method a second time (to actually output PDF, with ink = 1). 2. If the table spills over onto a new page when outputting the PDF (ink = 1), you will need to retrieve the new C<$page> hash via the return code. Actually, you would need to do this even if you are not querying table sizes! =item 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 ); =back =head3 Table settings Unless otherwise specified, all dimensional and geometry units used are measured in I. Line counts are not used anywhere. "Even" rows start with the first data (non-header) row. Think of this first row as number zero (an I number). Even rows alternate with odd rows. The odd/even flag is B reset when a table is 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. If a I is split across pages, it will resume with the same odd/even setting as on the previous page. If you desire to have the old (previous) odd/even behavior, see L
. 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 is B It is recommended that the dash be omitted in new code, and removed from old code before November 2022. B 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. 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. =head4 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. =over =item B - X coordinate of upper left corner of the table. The left edge of the sheet (media) is 0. B that this C will be used for any spillover of the table to additional page(s), so you cannot have spillover (continuation) rows starting at a different C. B can be any number satisfying C<0 E X < PageWidth> B No default value 'x' => 10, =item B - Y coordinate of upper left corner of the table on the initial page. B can be any number satisfying C<0 < y < PageHeight> (depending on space availability when embedding a table) B No default value 'y' => 327, B I (will go away in the future!) =item B - width of the table starting from C. B that this C will be used for any spillover of the table to additional page(s), so you cannot have spillover (continuation) rows with a different C. B can be any number satisfying C<0 < w < PageWidth - x> B No default value 'w' => 570, B 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: 1) Increase table width (w) 2) Decrease font size (font_size) 3) Choose a narrower font 4) Decrease "max_word_length" parameter, so long words are split into shorter chunks 5) Rotate media to landscape (if it is portrait) 6) Use a larger (wider) media size =item B - Height of the table on the initial (current) page. Think of this as the I (Y dimension) of the start of the table on this page. This would be the current C 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. B can be any number satisfying C<0 < h < PageHeight - Current Y position> B No default value 'h' => 250, B I (will go away in the future!) =back =head4 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). =head4 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. =over =item B - Height of the table on any additional page. Think of this as the I (Y dimension) of any overflow (spill) table portions on following pages. I.> B can be any number satisfying C<0 < next_h < PageHeight - y> You need to leave a non-negative amount of space at the bottom of the page. B Media height * 80% (80% of the paper height) You will receive a warning if C is needed for a spill page and you did not provide it! 'next_h' => 700, =item B - Y coordinate of upper left corner of the table at any additional page. Think of this as the starting C position of any overflow (spill or continuation) table portions on following pages. I.> B can be any number satisfying C<0 < next_y < PageHeight> B Media height * 90% (10% down from the top of the paper) You will receive a warning if C is needed for a spill page and you did not provide it! 'next_y' => 750, =item B - 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 I page, or another (typically, the top of the I 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 C value to avoid splitting a row). You may also decide to rearrange data rows, if this will make better use of available space. The default I value is I<1> (to output to the PDF file). If set to I<0>, only the height measurements (total, header, footer, each data row), in points, will be returned. B 1. No "footer" can currently be defined. Space is reserved in the output list for a possible future implementation. 2. 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! 3. 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. B 0 (return height only) or 1 (actually write the table) B 1 (write out the table) 'ink' => 0, B Currently, C is ignored for cells with I; their content will be written out regardless of C. We I plan to support C for markup cells in the not-too-distant future. =item B - 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: =over =item B - points (1/72 inch) =item B - inches (72 points) =item B - centimeters (28.3 points) =item B - millimeters (2.83 points) =item B - ems (width of 'M', depends on table default font) =item B - exs (width of 'x', depends on table default font) =back 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., B<2*> gets twice the width that B<*> gets). B 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 I or I width settings will be ignored! B None. If not given, widths will be calculated for the columns. 'size' => '* 3.5in 1.7* 4cm', =item B - CODE reference to a function that returns a PDF::Builder::Page instance. See section L below. 'new_page_func' => $code_ref, =item B - CODE reference to a function called with the current cell coordinates. See section L below. 'cell_render_hook' => $code_ref, =item B - HASH reference to specific settings for the Header row of the table. See section L below. 'header_props' => $hdr_props, =item B - HASH reference to specific settings for each row of the table. See section L below. 'row_props' => $my_row_props, =item B - HASH reference to specific settings for each column of the table. See section L below. 'column_props' => $col_props, =item B - HASH reference to specific settings for each column of the table. See section L below. 'cell_props' => $cell_props, =item B - Width of table border lines. =item B - Width of horizontal border lines (top and bottom of the table). Overrides 'border_w' value for horizontal usage. Note that 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 be 1pt wide ($border_w_default) solid lines, and where a row is divided within its content, a dashed (pattern $dashed_rule_default) 1pt wide line is used. =item B - Width of vertical border lines. Overrides 'border_w' value for vertical usage. B can be any positive number. When set to 0, it will disable border lines. This is the line thickness for drawing a border. B C<1> ($border_w_default) The I is the B frame around the table. It does not enter into table height or width calculations, so be sure to set your C and C settings to allow for the width of vertical borders, and your C or C and C or C 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). '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. B I (now 'border_w'), I (now 'h_border_w'), and I (now 'v_border_w'); will go away in the future! =item B - Border color for all borders. B Color specifier as 'name' or '#rrggbb' B C<'black'> ($fg_color_default) 'border_c' => 'red', B I (will go away in the future!) The same color is used for both the horizontal and vertical borders. =back =head4 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 header_props hash), one or more rows (in row_props array), one or more columns (in column_props array), or one or more individual cells (in 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). A global setting may only occur once (although it may be overridden by cell, column, or row usage of the same setting). =over =item B - 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 I 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 C splitting is I 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 B<(No content)> for the first printout of a cell (split over two or more pages) and B<-> for second and later printouts, you could leave the global default as '-' and simply give the cell the text "(No content)" (no longer really I, but you get the idea). If you have some content for a cell, and want B after it runs out of content, you could set C to B, and so on. B any string (can be a blank ' ' or an empty string ''). B '-' ($empty_cell_text) =item B - 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. B that this does I add a hyphen (dash)! It merely ensures that there will be no runs of non-space characters longer than I characters, reducing the chance of forcing an overly wide column. B can be any positive integer number (character count) B C<20> 'max_word_length' => 25, # Will add a space after every 25 symbols # unless there is a natural break (space) =item B - Padding applied to every cell =item B - top cell padding, overrides 'padding' =item B - right cell padding, overrides 'padding' =item B - left cell padding, overrides 'padding' =item B - bottom padding, overrides 'padding' B can be any non-negative number (E 0) B C<2>. ($padding_default) See L
for returning to the old value of C<0>. B C<'padding'> 'padding' => 5, # all sides cell padding 'padding_top' => 8, # top cell padding, overrides 'padding' 'padding_right' => 6, # right cell padding, overrides 'padding' 'padding_left' => 2, # left cell padding, overrides 'padding' 'padding_bottom' => undef, # bottom padding will be 5, as it will fall # back to 'padding' value =item B - instance of PDF::Builder::Resource::Font defining the font to be used in the table (or a subsection of it). B can be any PDF::Builder::Resource::* type of font B C<'Times'> core font with I encoding 'font' => $pdf->corefont("Helvetica", -encoding => "latin1"), B Only TrueType and OpenType fonts (ttfont call) can make use of multibyte encodings such as 'utf8'. Errors will result if you attempt to use 'utf8', etc. with corefont, psfont, etc. font types! For these, you I only specify a single-byte encoding. =item B - Size of the font that will be used in the table (or a subsection of it). B can be any positive number B C<12> ($font_size_default) 'font_size' => 16, =item B - Font color for all text. =item B - Background color for all text. B Color specifier as 'name' or '#rrggbb' (or other suitable color specification format) B C<'black'> text on (transparent) background. In other words, there is no default background color. The exception is for any B
row, where the default colors are C<#000066> (dark blue, $h_fg_color_default) on C<#FFFFAA> (light yellow, $h_bg_color_default). 'fg_color' => '#333333', B I (both will go away in the future!) =item B - Font color for odd rows (override C). =item B - Font color for even rows (override C). =item B - Background color for odd rows (override C). =item B - Background color for even rows (override C). B Color specifier as 'name' or '#rrggbb' (or other suitable color specification format) 'fg_color_odd' => 'purple', 'fg_color_even' => '#00FF00', 'bg_color_odd' => 'gray', 'bg_color_even' => 'lightblue', B I (all will go away in the future!) Note that *_color_odd/even usually make the most sense as global settings, although it I possible to use them within columns (see chess.pl example), and even rows and cells, but not header rows. =item B - Underline specifications for text in the table. B 'auto', integer of distance (below baseline), or arrayref of distance & thickness (more than one pair will provide multiple underlines). Negative distance gives strike-through. C<[]> ('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 I important text, such as header content, or certain cells. Unfortunately, there is currently no way to turn underlining off and on I a cell. B none B I (will go away in the future!) =item B - Desired minimum row height. This setting will be honored only if C 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_props or a cell_props, but it I possible to do, and may be useful in certain situations. B can be any positive number B C 'min_rh' => 24, B I (will go away in the future!) =item B - Alignment of text in a cell. B One of 'left', 'right', 'center' B C<'left'> =item B - Minimum width of this cell or column. PDF::Table will set a cell (and the column it's in) minimum width to fit the longest word (after splitting on C) found in the text. This amount may be increased to C. A column should be no narrower than its widest minimum width, but could be larger in order to fill out the table width. B can be any number satisfying C<0 < min_w < w> B Auto calculated Note that C is usually used for a column_props to set the column minimum width. If used in a row_props, it will act as a I setting; if used in a cell_props, that will force the minimum width for the cell's column. =item B - Maximum width of this column. PDF::Table will set a cell (and the column it's in) maximum width to fit the total length of the text content. This will seldom be actually used, but C may be used to I this maximum. When columns are being widened in order to meet the desired table width, it will try to honor the maximum width setting and avoid adding any width to a column already at its maximum width (but this cannot be guaranteed). B can be any number satisfying C<0 < min_w E max_w < w> B Auto calculated =item B - Width of table rule lines (internal table dividers). =item B - Width of horizontal rules (bottom of a cell). Overrides 'rule_w' value for horizontal usage. =item B - Width of vertical rules (left side of a cell). Overrides 'rule_w' value for vertical usage. B can be any positive number. When set to 0, it will disable rules. This is the line thickness for drawing a rule. B C<1> (corresponding border value) A I is a line bordering a I in the table. While it does not enter into table height or width calculations, be sure to set your C settings to allow sufficient clearance of cell content, especially if you make the rules more than a Point or two in thickness (line width). Note that 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. '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' 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. 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 I will be drawn instead of a I. 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 =item B - Rule color for all rules. =item B - Rule color for horizontal (bottom) rules, overriding C for this usage. =item B - Rule color for vertical (left) rules, overriding C for this usage. B Color specifier as 'name' or '#rrggbb' B C<'black'> (corresponding border value) 'rule_c' => 'red', =back =head4 New Page Function Hook B is a CODE reference to a function that returns a PDF::Builder::Page instance. If used, the parameter 'C' 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. C<$code_ref> can be something like C<\&new_page>. 'new_page_func' => $code_ref, The C<$code_ref> may be an inline sub definition (as show below), or a regular named C (e.g., 'new_page()') referenced as C<\&new_page>. The latter may be cleaner than inlining, if the routine is quite long. An example of reusing a saved PDF page as a I