PDF-Table-1.005/ 0000755 0000000 0000000 00000000000 14365336123 011661 5 ustar root root PDF-Table-1.005/INFO/ 0000755 0000000 0000000 00000000000 14365336755 012427 5 ustar root root PDF-Table-1.005/INFO/Deprecated 0000644 0000000 0000000 00000010174 14365336064 014406 0 ustar root root A 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/SPONSORS 0000644 0000000 0000000 00000002410 14365336064 013626 0 ustar root root S 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_2019 0000644 0000000 0000000 00000022166 14365336064 014375 0 ustar root root (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.html 0000644 0000000 0000000 00000201037 14365336064 014340 0 ustar root root
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();
...
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.
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:
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).
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.
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.
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.
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.
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).
$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
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.
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!
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.
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.
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
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
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!)
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).
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!
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!
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.
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:
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.
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!
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).
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 '').
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' => 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
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.
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!)
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.
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!)
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!)
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.
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
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
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 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] );
},
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.
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!
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.
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:
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.
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.
$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.
$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.
# 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 );
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.
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
PDF-Table-1.005/.perlcriticrc 0000644 0000000 0000000 00000000137 12777770572 014367 0 ustar root root severity = 5
[Perl::Critic::Policy::BuiltinFunctions::ProhibitStringyEval]
allow_includes = 1
PDF-Table-1.005/examples/ 0000755 0000000 0000000 00000000000 14365336755 013512 5 ustar root root PDF-Table-1.005/examples/PDFpref 0000644 0000000 0000000 00000000120 14365336065 014706 0 ustar root root PDF::Builder # choice for testing. must be in same directory as running program
PDF-Table-1.005/examples/size.pl 0000644 0000000 0000000 00000022421 14365336065 015014 0 ustar root root #!/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.pl 0000644 0000000 0000000 00000017455 14365336065 015162 0 ustar root root #!/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.pl 0000644 0000000 0000000 00000014560 14365336065 015411 0 ustar root root #!/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.pl 0000644 0000000 0000000 00000011631 14365336065 022110 0 ustar root root #!/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.pl 0000644 0000000 0000000 00000024252 14365336065 016535 0 ustar root root #!/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.pl 0000644 0000000 0000000 00000012411 14365336065 015477 0 ustar root root #!/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.pl 0000644 0000000 0000000 00000012435 14365336065 015276 0 ustar root root #!/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.pl 0000644 0000000 0000000 00000007245 14365336065 016210 0 ustar root root #!/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.pl 0000644 0000000 0000000 00000020077 14365336065 015560 0 ustar root root #!/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/ 0000755 0000000 0000000 00000000000 14365336755 012137 5 ustar root root PDF-Table-1.005/t/Basics.t 0000644 0000000 0000000 00000006423 14365336065 013527 0 ustar root root #!/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.t 0000644 0000000 0000000 00000003057 14365336065 013722 0 ustar root root #!/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.t 0000644 0000000 0000000 00000010444 14365336065 013757 0 ustar root root #!/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.t 0000644 0000000 0000000 00000002544 14365336065 013412 0 ustar root root #!/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/ 0000755 0000000 0000000 00000000000 14365336755 012705 5 ustar root root PDF-Table-1.005/t/lib/TestData.pm 0000644 0000000 0000000 00000000326 14365336065 014747 0 ustar root root package 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.pm 0000644 0000000 0000000 00000004353 14365336065 015101 0 ustar root root #!/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/ 0000755 0000000 0000000 00000000000 14365336110 012310 5 ustar root root PDF-Table-1.005/xt/manifest.t 0000644 0000000 0000000 00000000634 14261160700 014301 0 ustar root root #!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.t 0000644 0000000 0000000 00000000631 14261160700 013252 0 ustar root root #!/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/Changes 0000644 0000000 0000000 00000027462 14365336064 013173 0 ustar root root Change 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/PDFpref 0000644 0000000 0000000 00000000120 14365336064 013067 0 ustar root root PDF::Builder # choice for testing. must be in same directory as running program
PDF-Table-1.005/CONTRIBUTING.md 0000644 0000000 0000000 00000005336 14353113123 014107 0 ustar root root # 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/LICENSE 0000644 0000000 0000000 00000000717 14365336064 012677 0 ustar root root 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/util/ 0000755 0000000 0000000 00000000000 14365336755 012651 5 ustar root root PDF-Table-1.005/util/pod2cpanhtml.pl 0000644 0000000 0000000 00000002036 14365336065 015574 0 ustar root root #!/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.pl 0000644 0000000 0000000 00000007114 14365336065 015243 0 ustar root root #!/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.pl 0000644 0000000 0000000 00000003206 14365336065 015025 0 ustar root root #!/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.pl 0000644 0000000 0000000 00000011346 14365336065 014027 0 ustar root root #!/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.json 0000644 0000000 0000000 00000002231 14365336123 013300 0 ustar root root {
"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/MANIFEST 0000644 0000000 0000000 00000001506 14365336123 013014 0 ustar root root .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.SKIP 0000644 0000000 0000000 00000000456 14365336064 013570 0 ustar root root #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.md 0000644 0000000 0000000 00000004445 14365336064 013153 0 ustar root root # PDF::Table
This module creates text blocks and tables into PDF documents using the
PDF::API2 or PDF::Builder Perl module.
[](https://github.com/PhilterPaper/PDF-Table/issues)
[](https://makeapullrequest.com)
[](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.PL 0000644 0000000 0000000 00000002326 14365336064 013642 0 ustar root root #! 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/ 0000755 0000000 0000000 00000000000 14365336755 012442 5 ustar root root PDF-Table-1.005/lib/PDF/ 0000755 0000000 0000000 00000000000 14365336110 013034 5 ustar root root PDF-Table-1.005/lib/PDF/Table/ 0000755 0000000 0000000 00000000000 14365336755 014102 5 ustar root root PDF-Table-1.005/lib/PDF/Table/ColumnWidth.pm 0000644 0000000 0000000 00000031036 14365336063 016670 0 ustar root root package 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.pm 0000644 0000000 0000000 00000015503 14365336063 016234 0 ustar root root package 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.pod 0000644 0000000 0000000 00000137570 14365335316 014613 0 ustar root root =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:
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
I (continuation) page of the table, if needed. Note that the
C<$template-Eopenpage(1)> call is B 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 C is not defined, PDF::Table will simply call
C<$pdf-Epage()> to generate a new, blank, "next" page.
Note that this function is B called for the first page of a table. That
one uses the current C<$page> parameter passed to the C
call. It is
only called when needed for overflow (C and C) pages, where
it replaces the C<$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.
=head4 Cell Render Hook
B is a CODE reference to a function called with the
current cell coordinates. If used, the parameter C 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] );
},
=head4 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.
=over
=item B - Flag showing if header row should be repeated on every new
page.
B 0,1 1-Yes/True, 0-No/False
B C<1> ($repeat_default)
See L if you wish to change it back to the old behavior
of C<0>.
my $hdr_props = {
'font' => $pdf->corefont("Helvetica", -encoding => "latin1"),
'font_size' => 18,
'fg_color' => '#004444',
'bg_color' => 'yellow',
'repeat' => 0,
'justify' => 'center',
};
=back
=head4 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 C<$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:
=over
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 I row properties!
=back
=head4 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 C<$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:
=over
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.
=back
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.
=head4 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:
=over
=item B - Span this cell over multiple columns to the right.
B can be any positive number less than the number of columns to the
right of the current column
B undef
NOTE: If you want to have regular columns B a colspan, you have to
provide C for the columns that should be spanned
NOTE: If you use C 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}]
]
);
=back
See the file C 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',
};
=head2 text_block()
my ($width_of_last_line, $ypos_of_last_line, $left_over_text) =
text_block( $txt, $data, %settings)
=over
=item Description
Utility method to create a block of text. The block may contain multiple
paragraphs (input C<$data> separated by implicit or explicit newlines C<\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.
=item 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.
=item 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.
=item 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 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 );
=back
=head1 VERSION
1.005
=head1 AUTHOR
Daemmon Hughes
=head1 DEVELOPMENT
Further development Versions 0.02 -- 0.11 - Desislav Kamenov
Further development since Ver: 0.12 - Phil Perry
=head1 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.
=head1 PLUGS
=over
=item 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
=item 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!
=back
=head1 CONTRIBUTION
PDF::Table is on GitHub. You are more than welcome to contribute!
https://github.com/PhilterPaper/PDF-Table
=head1 SEE ALSO
L, L
=cut
PDF-Table-1.005/lib/PDF/Table.pm 0000644 0000000 0000000 00000244004 14365336062 014433 0 ustar root root #!/usr/bin/env perl
# vim: softtabstop=4 tabstop=4 shiftwidth=4 ft=perl expandtab smarttab
use 5.010;
use strict;
use warnings;
package PDF::Table;
# portions (c) copyright 2004 Stone Environmental Inc.
# (c) copyright 2006 Daemmon Hughes
# (c) copyright 2020 - 2023 by Phil M. Perry
use Carp;
use List::Util qw[min max]; # core
use PDF::Table::ColumnWidth;
use PDF::Table::Settings;
# can't move text_block() b/c many globals referenced
our $VERSION = '1.005'; # fixed, read by Makefile.PL
our $LAST_UPDATE = '1.005'; # manually update whenever code is changed
# don't forget to update VERSION down in POD area
my $compat_mode = 0; # 0 = new behaviors, 1 = compatible with old
# NOTE that a number of t-tests will FAIL in mode 1 (compatible with old)
# due to slightly different text placements
# ================ COMPATIBILITY WITH OLDER VERSIONS ===============
my $repeat_default = 1; # header repeat: old = change to 0
my $oddeven_default = 1; # odd/even lines, use old method = change to 0
my $padding_default = 2; # 2 points of padding. old = 0 (no padding)
# ==================================================================
if ($compat_mode) { # 1: be compatible with older PDF::Table behavior
($repeat_default, $oddeven_default, $padding_default) = (0, 0, 0);
} else { # 0: do not force compatibility with older PDF::Table behavior
($repeat_default, $oddeven_default, $padding_default) = (1, 1, 2);
}
# ================ OTHER GLOBAL DEFAULTS =========================== per #7
my $fg_color_default = 'black'; # foreground text color
# no bg_color_default (defaults to transparent background)
my $h_fg_color_default = '#000066'; # fg text color for header
my $h_bg_color_default = '#FFFFAA'; # bg color for header
my $font_size_default = 12; # base font size
my $leading_ratio = 1.25; # leading/font_size ratio (if 'lead' not given)
my $border_w_default = 1; # line width for borders
my $max_wordlen_default = 20; # split any run of 20 non-space chars
my $empty_cell_text = '-'; # something to put in an empty cell
my $dashed_rule_default = 2; # dash/space pattern length for broken rows
my $min_col_width = 2; # absolute minimum width of a column, > 0
# ==================================================================
my $ink = 1; # by default, actually make PDF output
print __PACKAGE__.' is version: '.$VERSION.$/ if ($ENV{'PDF_TABLE_DEBUG'});
############################################################
#
# new - Constructor
#
# Parameters are meta information about the PDF. They may be
# omitted, so long as the information is passed instead to
# the table() method.
#
# $pdf = PDF::Table->new();
# $page = $pdf->page();
# $data
# %options
#
############################################################
sub new {
my $type = shift(@_);
my $class = ref($type) || $type;
my $self = {};
bless ($self, $class);
# Pass all the rest to init for validation and initialization
$self->_init(@_);
return $self;
}
sub _init {
my ($self, $pdf, $page, $data, %options ) = @_;
# Check and set default values
$self->set_defaults();
# Check and set mandatory parameters
$self->set_pdf($pdf);
$self->set_page($page);
$self->set_data($data);
$self->set_options(\%options);
return;
}
sub set_defaults {
my $self = shift;
$self->{'font_size'} = $font_size_default;
$min_col_width = max($min_col_width, 1); # minimum width
return;
}
sub set_pdf {
my ($self, $pdf) = @_;
$self->{'pdf'} = $pdf;
return;
}
sub set_page {
my ($self, $page) = @_;
if ( defined($page) && ref($page) ne 'PDF::API2::Page'
&& ref($page) ne 'PDF::Builder::Page' ) {
if (ref($self->{'pdf'}) eq 'PDF::API2' ||
ref($self->{'pdf'}) eq 'PDF::Builder') {
$self->{'page'} = $self->{'pdf'}->page();
} else {
carp 'Warning: Page must be a PDF::API2::Page or PDF::Builder::Page object but it seems to be: '.ref($page).$/;
carp 'Error: Cannot set page from passed PDF object either, as it is invalid!'.$/;
}
return;
}
$self->{'page'} = $page;
return;
}
sub set_data {
my ($self, $data) = @_;
# TODO: implement
return;
}
sub set_options {
my ($self, $options) = @_;
# TODO: implement
return;
}
################################################################
# table - utility method to build multi-row, multicolumn tables
################################################################
sub table {
#use Storable qw( dclone );
# can't use Storable::dclone because can't handle CODE. would like to deep
# clone %arg so that modifications (remove leading '-' and/or substitute for
# deprecated names) won't modify original %arg hash on the outside.
my $self = shift;
my $pdf = shift;
my $page = shift;
my $data = shift;
my %arg = @_;
#=====================================
# Mandatory Arguments Section
#=====================================
unless ($pdf and $page and $data) {
carp "Error: Mandatory parameter is missing PDF/page/data object!\n";
return ($page, 0, 0);
}
# Validate mandatory argument data type
croak "Error: Invalid PDF object received."
unless (ref($pdf) eq 'PDF::API2' ||
ref($pdf) eq 'PDF::Builder');
croak "Error: Invalid page object received."
unless (ref($page) eq 'PDF::API2::Page' ||
ref($page) eq 'PDF::Builder::Page');
croak "Error: Invalid data received."
unless ((ref($data) eq 'ARRAY') && scalar(@$data));
croak "Error: Missing required settings."
unless (scalar(keys %arg));
# ==================================================================
# did client code ask to redefine?
($repeat_default, $oddeven_default, $padding_default) =
@{$arg{'compatibility'}} if defined $arg{'compatibility'};
# set some defaults !!!!
$arg{'cell_render_hook' } ||= undef;
# $ink is whether or not to output PDF, as opposed to sizing
$ink = $arg{'ink'} if defined $arg{'ink'}; # 1 yes, 0 no (size)
my @vsizes;
# Validate settings key
my %valid_settings_key = (
'x' => 1, # global, mandatory
'w' => 1, # global, mandatory
'y' => 1, # global, mandatory
'start_y' => 1, # deprecated
'h' => 1, # global, mandatory
'start_h' => 1, # deprecated
'ink' => 1, # global
'next_y' => 1, # global
'next_h' => 1, # global
'leading' => 1, # text_block
'lead' => 1, # deprecated
'padding' => 1, # global
'padding_right' => 1, # global
'padding_left' => 1, # global
'padding_top' => 1, # global
'padding_bottom' => 1, # global
'bg_color' => 1, # global, header, row, column, cell
'background_color' => 1, # deprecated
'bg_color_odd' => 1, # global, column, cell
'background_color_odd'=> 1, # deprecated
'bg_color_even' => 1, # global, column, cell
'background_color_even'=> 1, # deprecated
'fg_color' => 1, # global, header, row, column, cell
'font_color' => 1, # deprecated
'fg_color_odd' => 1, # global, column, cell
'font_color_odd' => 1, # deprecated
'fg_color_even' => 1, # global, column, cell
'font_color_even' => 1, # deprecated
'border_w' => 1, # global
'border' => 1, # deprecated
'h_border_w' => 1, # global
'horizontal_borders' => 1, # deprecated
'v_border_w' => 1, # global
'vertical_borders' => 1, # deprecated
'border_c' => 1, # global
'border_color' => 1, # deprecated
# possibly in future, separate h_border_c and v_border_c
'rule_w' => 1, # global, row, column, cell
'h_rule_w' => 1, # global, row, column, cell
'v_rule_w' => 1, # global, row, column, cell
'rule_c' => 1, # global, row, column, cell
'h_rule_c' => 1, # global, row, column, cell
'v_rule_c' => 1, # global, row, column, cell
'font' => 1, # global, header, row, column, cell
'font_size' => 1, # global, header, row, column, cell
'underline' => 1, # global, header, row, column, cell
'font_underline' => 1, # deprecated
'min_w' => 1, # global, header, row, column, cell
'max_w' => 1, # global, header, row, column, cell
'min_rh' => 1, # global, header, row, column, cell
'row_height' => 1, # deprecated
'new_page_func' => 1, # global
'header_props' => 1, # includes sub-settings like repeat
'row_props' => 1, # includes sub-settings like fg_color
'column_props' => 1, # includes sub-settings like fg_color
'cell_props' => 1, # includes sub-settings like fg_color
'max_word_length' => 1, # global, text_block
'cell_render_hook' => 1, # global
'default_text' => 1, # global
'justify' => 1, # global
# 'repeat' # header
# 'align' # text_block
# 'parspace' # text_block
# 'hang' # text_block
# 'flindent' # text_block
# 'fpindent' # text_block
# 'indent' # text_block
'size' => 1, # global
);
foreach my $key (keys %arg) {
# Provide backward compatibility
$arg{$key} = delete $arg{"-$key"} if $key =~ s/^-//;
croak "Error: Invalid setting key '$key' received."
unless exists $valid_settings_key{$key};
}
my ( $xbase, $ybase, $width, $height ) = ( undef, undef, undef, undef );
# TBD eventually deprecated start_y and start_h go away
# special treatment here because haven't yet copied deprecated names
$xbase = $arg{'x'} || -1;
$ybase = $arg{'y'} || $arg{'start_y'} || -1;
$width = $arg{'w'} || -1;
$height = $arg{'h'} || $arg{'start_h'} || -1;
# Global geometry parameters are also mandatory.
unless ( $xbase > 0 ) {
carp "Error: Left Edge of Table is NOT defined!\n";
return ($page, 0, $ybase);
}
unless ( $ybase > 0 ) {
carp "Error: Base Line of Table is NOT defined!\n";
return ($page, 0, $ybase);
}
unless ( $width > 0 ) {
carp "Error: Width of Table is NOT defined!\n";
return ($page, 0, $ybase);
}
unless ( $height > 0 ) {
carp "Error: Height of Table is NOT defined!\n";
return ($page, 0, $ybase);
}
my $bottom_margin = $ybase - $height;
my $pg_cnt = 1;
my $cur_y = $ybase;
my $cell_props = $arg{'cell_props'} || []; # per cell properties
# If there is no valid data array reference, warn and return!
if (ref $data ne 'ARRAY') {
carp "Passed table data is not an ARRAY reference. It's actually a ref to ".ref($data);
return ($page, 0, $cur_y);
}
# Ensure default values for next_y and next_h
my $next_y = $arg{'next_y'} || undef;
my $next_h = $arg{'next_h'} || undef;
my $size = $arg{'size'} || undef;
# Create Text Object
my $txt = $page->text(); # $ink==0 still needs for font size, etc.
# doing sizing or actual output?
if (!$ink) {
@vsizes = (0, 0, 0); # overall, header, footer (future)
# push each row onto @vsizes as defined
# override y,h to nearly infinitely large (will never paginate)
$ybase = $height = 2147000000;
}
#=====================================
# Table Header Section
#
# order of precedence: header_props, column_props, globals, defaults
# here, header settings are initialized to globals/defaults
#=====================================
# Disable header row into the table
my $header_props = undef;
my $do_headers = 0; # not doing headers
# Check if the user enabled it ?
if (defined $arg{'header_props'} and ref( $arg{'header_props'}) eq 'HASH') {
# Transfer the reference to local variable
$header_props = $arg{'header_props'};
# Check other parameters and put defaults if needed
$header_props->{'repeat' } ||= $repeat_default;
$do_headers = 1; # do headers, no repeat
$do_headers = 2 if $header_props->{'repeat'}; # do headers w/ repeat
}
my $header_row = undef;
# Copy the header row (text) if header is enabled
@$header_row = $$data[0] if $do_headers;
# Determine column widths based on content
# an arrayref whose values are a hashref holding
# the minimum and maximum width of that column
my $col_props = $arg{'column_props'} || [];
# an arrayref whose values are a hashref holding
# various row settings for a specific row
my $row_props = $arg{'row_props'} || [];
# deprecated setting (globals) names, copy to new names
PDF::Table::Settings::deprecated_settings(
$data, $row_props, $col_props, $cell_props, $header_props, \%arg);
# check settings values as much as possible
PDF::Table::Settings::check_settings(%arg);
#=====================================
# Set Global Default Properties
#=====================================
# geometry-related global settings checked, last value for find_value()
my $fnt_obj = $arg{'font' } ||
$pdf->corefont('Times-Roman',-encode => 'latin1');
my $fnt_size = $arg{'font_size' } || $font_size_default;
my $min_leading = $fnt_size * $leading_ratio;
my $leading = $arg{'leading'} || $min_leading;
if ($leading < $fnt_size) {
carp "Warning: Global leading value $leading is less than font size $fnt_size, increased to $min_leading\n";
$arg{'leading'} = $leading = $min_leading;
}
# can't condense $border_w to || because border_w=>0 gets default of 1!
my $border_w = defined $arg{'border_w'}? $arg{'border_w'}: 1;
my $h_border_w = $arg{'h_border_w'} || $border_w;
my $v_border_w = $arg{'v_border_w'} || $border_w;
# non-geometry global settings
my $border_c = $arg{'border_c'} || $fg_color_default;
# global fallback values for find_value() call
my $underline = $arg{'underline' } ||
undef; # merely stating undef is the intended default
my $max_word_len = $arg{'max_word_length' } || $max_wordlen_default;
my $default_text = $arg{'default_text' } || $empty_cell_text;
# An array ref of arrayrefs whose values are
# the actual widths of the column/row intersection
my $row_col_widths = [];
# An array ref with the widths of the header row
my $h_row_widths = [];
# Scalars that hold sum of the maximum and minimum widths of all columns
my ( $max_col_w, $min_col_w ) = ( 0,0 );
my ( $row, $space_w );
my $word_widths = {};
my $rows_height = [];
my $first_row = 1;
my $is_header_row = 0;
# per-cell values
my ($cell_font, $cell_font_size, $cell_underline, $cell_justify,
$cell_height, $cell_pad_top, $cell_pad_right, $cell_pad_bot,
$cell_pad_left, $cell_leading, $cell_max_word_len, $cell_bg_color,
$cell_fg_color, $cell_bg_color_even, $cell_bg_color_odd,
$cell_fg_color_even, $cell_fg_color_odd, $cell_min_w, $cell_max_w,
$cell_h_rule_w, $cell_v_rule_w, $cell_h_rule_c, $cell_v_rule_c,
$cell_def_text, $cell_markup);
# for use by find_value()
my $GLOBALS = [$cell_props, $col_props, $row_props, -1, -1, \%arg];
# ----------------------------------------------------------------------
# GEOMETRY
# figure row heights and column widths,
# update overall table width if necessary
# here we're only interested in things that affect the table geometry
#
# $rows_height->[$row_idx] array overall height of each row
# $calc_column_widths overall width of each column
my $col_min_width = []; # holds the running width of each column
my $col_max_content = []; # min and max (min_w & longest word,
# length of content)
my $max_w = []; # each column's max_w, if defined
for ( my $row_idx = 0; $row_idx < scalar(@$data) ; $row_idx++ ) {
$GLOBALS->[3] = $row_idx;
my $column_widths = []; # holds the width of each column
# initialize the height for this row
$rows_height->[$row_idx] = 0;
for ( my $col_idx = 0;
$col_idx < scalar(@{$data->[$row_idx]});
$col_idx++ ) {
$GLOBALS->[4] = $col_idx;
# initialize min and max column content widths to 0
$col_min_width->[$col_idx]=0 if !defined $col_min_width->[$col_idx];
$col_max_content->[$col_idx]=0 if !defined $col_max_content->[$col_idx];
# determine if this content is a simple string for normal usage,
# or it is markup
my $bad_markup = '';
if (ref($data->[$row_idx][$col_idx]) eq '') {
# it is a scalar string for normal usage
# (or some data easily stringified)
$cell_markup = '';
} elsif (ref($data->[$row_idx][$col_idx]) eq 'ARRAY') {
# it is an array for markup usage. exact type is the first
# element.
if (!defined $data->[$row_idx][$col_idx]->[0]) {
$bad_markup = 'array has no data';
} else {
$cell_markup = $data->[$row_idx][$col_idx]->[0];
# [0] should be none, md1, html, or pre
if ($cell_markup ne 'none' && $cell_markup ne 'md1' &&
$cell_markup ne 'html' && $cell_markup ne 'pre') {
$bad_markup = "markup type '$cell_markup' unsupported";
# [1] should be string or array of strings
} elsif (defined $data->[$row_idx][$col_idx]->[1] &&
ref($data->[$row_idx][$col_idx]->[1]) ne '' &&
ref($data->[$row_idx][$col_idx]->[1]) ne 'ARRAY') {
$bad_markup = 'data not string or array of strings';
# [2] should be hash reference (possibly empty)
} elsif (defined $data->[$row_idx][$col_idx]->[2] &&
ref($data->[$row_idx][$col_idx]->[2]) ne 'HASH') {
$bad_markup = 'options not hash ref';
}
# [3+] additional elements ignored
}
} else {
# um, is not a legal data type for this purpose, even if it
# IS able to stringify to something reasonable.
# See if we can stringify it... better than a total failure?
my $string = ''; # in case stringification fails
$bad_markup = ''; # in case stringification succeeds
eval { $string = ''.$data->[$row_idx][$col_idx]; };
$bad_markup = 'is not a string or array reference' if $@;
$data->[$row_idx][$col_idx] = $string;
# if fatal error in eval, $string will be empty, and $bad_markup
# will cause it to be ignored anyway
}
if ($bad_markup ne '') {
# replace bad markup with a simple string
carp "Cell $row_idx,$col_idx $bad_markup.\n";
$data->[$row_idx][$col_idx] = '(invalid)';
$cell_markup = '';
}
if ( !$row_idx && $do_headers ) {
# header row
$is_header_row = 1;
$GLOBALS->[3] = 0;
$cell_font = $header_props->{'font'};
$cell_font_size = $header_props->{'font_size'};
$cell_leading = $header_props->{'leading'};
$cell_height = $header_props->{'min_rh'};
$cell_pad_top = $header_props->{'padding_top'} ||
$header_props->{'padding'};
$cell_pad_right = $header_props->{'padding_right'} ||
$header_props->{'padding'};
$cell_pad_bot = $header_props->{'padding_bottom'} ||
$header_props->{'padding'};
$cell_pad_left = $header_props->{'padding_left'} ||
$header_props->{'padding'};
$cell_max_word_len = $header_props->{'max_word_length'};
$cell_min_w = $header_props->{'min_w'};
$cell_max_w = $header_props->{'max_w'};
$cell_def_text = $header_props->{'default_text'};
# items not of interest for determining geometry
#$cell_underline = $header_props->{'underline'};
#$cell_justify = $header_props->{'justify'};
#$cell_bg_color = $header_props->{'bg_color'};
#$cell_fg_color = $header_props->{'fg_color'};
#$cell_bg_color_even= undef;
#$cell_bg_color_odd = undef;
#$cell_fg_color_even= undef;
#$cell_fg_color_odd = undef;
#$cell_h_rule_w = header_props->{'h_rule_w'};
#$cell_v_rule_w = header_props->{'v_rule_w'};
#$cell_h_rule_c = header_props->{'h_rule_c'};
#$cell_v_rule_c = header_props->{'v_rule_c'};
} else {
# not a header row, so uninitialized
$is_header_row = 0;
$cell_font = undef;
$cell_font_size = undef;
$cell_leading = undef;
$cell_height = undef;
$cell_pad_top = undef;
$cell_pad_right = undef;
$cell_pad_bot = undef;
$cell_pad_left = undef;
$cell_max_word_len = undef;
$cell_min_w = undef;
$cell_max_w = undef;
$cell_def_text = undef;
# items not of interest for determining geometry
#$cell_underline = undef;
#$cell_justify = undef;
#$cell_bg_color = undef;
#$cell_fg_color = undef;
#$cell_bg_color_even= undef;
#$cell_bg_color_odd = undef;
#$cell_fg_color_even= undef;
#$cell_fg_color_odd = undef;
#$cell_h_rule_w = undef;
#$cell_v_rule_w = undef;
#$cell_h_rule_c = undef;
#$cell_v_rule_c = undef;
}
# Get the most specific value if none was already set from header_props
# TBD should header_props be treated like a row_props (taking
# precedence over row_props), but otherwise like a row_props? or
# should anything in header_props take absolute precedence as now?
$cell_font = find_value($cell_font,
'font', '', $fnt_obj, $GLOBALS);
$cell_font_size = find_value($cell_font_size,
'font_size', '', 0, $GLOBALS);
if ($cell_font_size == 0) {
if ($is_header_row) {
$cell_font_size = $fnt_size + 2;
} else {
$cell_font_size = $fnt_size;
}
}
$cell_leading = find_value($cell_leading, 'leading',
'', -1, $GLOBALS);
$cell_height = find_value($cell_height,
'min_rh', '', 0, $GLOBALS);
$cell_pad_top = find_value($cell_pad_top, 'padding_top',
'padding', $padding_default,
$GLOBALS);
$cell_pad_right = find_value($cell_pad_right, 'padding_right',
'padding', $padding_default,
$GLOBALS);
$cell_pad_bot = find_value($cell_pad_bot, 'padding_bottom',
'padding', $padding_default,
$GLOBALS);
$cell_pad_left = find_value($cell_pad_left, 'padding_left',
'padding', $padding_default,
$GLOBALS);
$cell_max_word_len = find_value($cell_max_word_len, 'max_word_len',
'', $max_word_len, $GLOBALS);
$cell_min_w = find_value($cell_min_w, 'min_w',
'', undef, $GLOBALS);
$cell_max_w = find_value($cell_max_w, 'max_w',
'', undef, $GLOBALS);
if (defined $cell_max_w && defined $cell_min_w) {
$cell_max_w = max($cell_max_w, $cell_min_w);
}
$cell_def_text = find_value($cell_def_text, 'default_text', '',
$default_text, $GLOBALS);
# items not of interest for determining geometry
#$cell_underline = find_value($cell_underline,
# 'underline', '', $underline, $GLOBALS);
#$cell_justify = find_value($cell_justify,
# 'justify', '', 'left', $GLOBALS);
#$cell_bg_color = find_value($cell_bg_color, 'bg_color',
# '', undef, $GLOBALS);
#$cell_fg_color = find_value($cell_fg_color, 'fg_color',
# '', $fg_color_default, $GLOBALS);
#$cell_bg_color_even = find_value($cell_bg_color_even,
# 'bg_color_even', '', undef, $GLOBALS);
#$cell_bg_color_odd = find_value($cell_bg_color_odd,
# 'bg_color_odd', '', undef, $GLOBALS);
#$cell_fg_color_even = find_value($cell_fg_color_even,
# 'fg_color_even', '', undef, $GLOBALS);
#$cell_fg_color_odd = find_value($cell_fg_color_odd,
# 'fg_color_odd', '', undef, $GLOBALS);
#$cell_h_rule_w = find_value($cell_h_rule_w, 'h_rule_w',
# 'rule_w', $h_border_w, $GLOBALS);
#$cell_v_rule_w = find_value($cell_v_rule_w, 'v_rule_w',
# 'rule_w', $v_border_w, $GLOBALS);
#$cell_h_rule_c = find_value($cell_h_rule_c, 'h_rule_c',
# 'rule_c', $border_c, $GLOBALS);
#$cell_v_rule_c = find_value($cell_v_rule_c, 'v_rule_c',
# 'rule_c', $border_c, $GLOBALS);
my $min_leading = $cell_font_size * $leading_ratio;
if ($cell_leading <= 0) {
# leading left at default, silently set to minimum
$cell_leading = $min_leading;
} else {
# leading specified, but is too small?
if ($cell_leading < $cell_font_size) {
carp "Warning: Cell[$row_idx][$col_idx] leading value $cell_leading is less than font size $cell_font_size, increased to $min_leading\n";
$cell_leading = $min_leading;
}
}
# Set Font
$txt->font( $cell_font, $cell_font_size );
# Set row height to biggest font size from row's cells
# Note that this assumes just one line of text per cell
$rows_height->[$row_idx] = max($rows_height->[$row_idx],
$cell_leading + $cell_pad_top + $cell_pad_bot, $cell_height);
# This should fix a bug with very long words like serial numbers,
# etc. TBD: consider splitting ONLY on end of line, and adding a
# hyphen (dash) at split. would have to track split words (by
# index numbers?) and glue them back together when there's space
# to do so (including hyphen).
# update: split words only if simple strings (not calling column())
if ( $cell_max_word_len > 0 && $data->[$row_idx][$col_idx] &&
ref($data->[$row_idx][$col_idx]) eq '') {
$data->[$row_idx][$col_idx] =~ s#(\S{$cell_max_word_len})(?=\S)#$1 #g;
}
# Init cell size limits (per row)
$space_w = $txt->advancewidth( "\x20" );
# font/size can change for each cell, so space width can vary
$column_widths->[$col_idx] = 0; # per-row basis
$max_col_w = 0;
$min_col_w = 0;
my @words;
@words = split( /\s+/, $data->[$row_idx][$col_idx] )
if $data->[$row_idx][$col_idx];
# TBD count up spaces instead of assuming one between each word,
# don't know what to do about \t (not defined!). NBSP would
# be treated as non-space for these calculations, not sure
# how it would render. \r, \n, etc. no space? then there is
# check how text is split into lines in text_block if
# multiple spaces between words.
# for cell, minimum width is longest word, maximum is entire text
# treat header row like any data row for this
# increase minimum width to (optional) specified column min width
# keep (optional) specified column max width separate
# NOTE that cells with only blanks will be treated as empty (no
# words) and have only L+R padding for a width!
foreach ( @words ) {
unless ( exists $word_widths->{$_} ) {
# Calculate the width of every word and add the space width to it
# caching each word so only figure width once
$word_widths->{$_} = $txt->advancewidth($_);
}
# minimum width is longest word or fragment
$min_col_w = max($min_col_w, $word_widths->{$_});
# maximum width is total text in cell
if ($max_col_w) {
# already have text, so add a space first
# note that multiple spaces between words become one!
$max_col_w += $space_w;
} else {
# first word, so no space [before]
}
$max_col_w += $word_widths->{$_};
}
# don't forget any default text! it's not split on max_word_len
# TBD should default_text be split like other text?
$min_col_w = max($min_col_w, $txt->advancewidth($cell_def_text));
# at this point we have longest word (min_col_w), overall length
# (max_col_w) of this cell. add L+R padding
# cell_min/max_w are optional settings
# TBD what if $cell_def_text is longer?
$min_col_w += $cell_pad_left + $cell_pad_right;
$min_col_w = max($min_col_w, $cell_min_w) if defined $cell_min_w;
$max_col_w += $cell_pad_left + $cell_pad_right;
$max_col_w = max($min_col_w, $max_col_w);
$col_min_width->[$col_idx] = max($col_min_width->[$col_idx],
$min_col_w);
$col_max_content->[$col_idx] = max($col_max_content->[$col_idx],
$max_col_w);
if (!defined $max_w->[$col_idx]) { $max_w->[$col_idx] = -1; }
$max_w->[$col_idx] = max($max_w->[$col_idx], $cell_max_w) if
defined $cell_max_w; # otherwise -1
$column_widths->[$col_idx] = $col_max_content->[$col_idx];
} # (End of cols) for (my $col_idx....
$row_col_widths->[$row_idx] = $column_widths;
# Copy the calculated row properties of header row.
@$h_row_widths = @$column_widths if !$row_idx && $do_headers;
} # (End of rows) for ( my $row_idx row heights and column widths
# Calc real column widths and expand table width if needed.
my $calc_column_widths;
my $em_size = $txt->advancewidth('M');
my $ex_size = $txt->advancewidth('x');
if (defined $size) {
($calc_column_widths, $width) =
PDF::Table::ColumnWidth::SetColumnWidths(
$width, $size, $em_size, $ex_size );
} else {
($calc_column_widths, $width) =
PDF::Table::ColumnWidth::CalcColumnWidths(
$width, $col_min_width, $col_max_content, $max_w );
}
# ----------------------------------------------------------------------
# Let's draw what we have!
my $row_idx = 0; # first row (might be header)
my $row_is_odd = 0; # first data row output (row 0) is "even"
# Store header row height for later use if headers have to be repeated
my $header_min_rh = $rows_height->[0]; # harmless if no header
# kind of top border to draw, depending on start or continuation
my $next_top_border = 0;
my ( $gfx, $gfx_bg, $bg_color, $fg_color,
$bot_margin, $table_top_y, $text_start_y);
# Each iteration adds a new page as necessary
while (scalar(@{$data})) { # still row(s) remaining to output
my ($page_header, $columns_number);
if ($pg_cnt == 1) {
# on first page output
$table_top_y = $ybase;
$bot_margin = $table_top_y - $height;
# Check for safety reasons
if ( $bot_margin < 0 ) {
carp "!!! Warning: !!! Incorrect Table Geometry! h ($height) greater than remaining page space y ($table_top_y). Reducing height to fit on page.\n";
$bot_margin = 0;
$height = $table_top_y;
}
} else {
# on subsequent (overflow) pages output
if (ref $arg{'new_page_func'}) {
$page = &{ $arg{'new_page_func'} };
} else {
$page = $pdf->page();
}
# we NEED next_y and next_h! if undef, complain and use
# 90% and 80% respectively of page height
if (!defined $next_y) {
my @page_dim = $page->mediabox();
$next_y = ($page_dim[3] - $page_dim[1]) * 0.9;
carp "!!! Error: !!! Table spills to next page, but no next_y was given! Using $next_y.\n";
}
if (!defined $next_h) {
my @page_dim = $page->mediabox();
$next_h = ($page_dim[3] - $page_dim[1]) * 0.8;
carp "!!! Error: !!! Table spills to next page, but no next_h was given! Using $next_h.\n";
}
$table_top_y = $next_y;
$bot_margin = $table_top_y - $next_h;
# Check for safety reasons
if ( $bot_margin < 0 ) {
carp "!!! Warning: !!! Incorrect Table Geometry! next_h ($next_h) greater than remaining page space next_y ($next_y), must be reduced to fit on page.\n";
$bot_margin = 0;
$next_h = $table_top_y;
}
# push copy of header onto remaining table data, if repeated hdr
if ( $do_headers == 2 ) {
# Copy Header Data
@$page_header = @$header_row;
my $hrw ;
@$hrw = @$h_row_widths ;
# Then prepend it to master data array
unshift @$data, @$page_header;
unshift @$row_col_widths, $hrw;
unshift @$rows_height, $header_min_rh;
$first_row = 1; # Means YES
# Roll back the row_idx because a new header row added
$row_idx--;
}
}
# ----------------------------------------------------------------
# should be at top of table for current page
# either start of table, or continuation
# pg_cnt >= 1
# do_headers = 0 not doing headers
# 1 non-repeating header
# 2 repeating header
# check if enough vertical space for first data row (row 0 or 1), AND
# for header (0) if doing a header row! increase height, decrease
# bot_margin. possible that bot_margin goes < 0 (warning message).
# TBD if first page (pg_cnt==1), and sufficient space on next page,
# just skip first page and go on to second
# For degenerate cases where there is only a header row and no data
# row(s), don't try to make use of missing rows height [1]
my $min_height = $rows_height->[0];
$min_height += $rows_height->[1] if
($do_headers && $pg_cnt==1 || $do_headers==2 && $pg_cnt>1) &&
defined $rows_height->[1];
if ($min_height >= $table_top_y - $bot_margin) {
# Houston, we have a problem. height isn't enough
my $delta = $min_height - ($table_top_y - $bot_margin) + 1;
if ($delta > $bot_margin) {
carp "!! Error !! Insufficient space (by $delta) to get minimum number of row(s) on page. Some content may be lost off page bottom";
} else {
carp "!! Warning !! Need to expand allotted vertical height by $delta to fit minimum number of row(s) on page";
}
$bot_margin -= $delta;
if ($pg_cnt == 1) {
$height += $delta;
} else {
$next_h += $delta;
}
}
# order is important -- cell background layer must be rendered
# before text layer and then other graphics (rules, borders)
$gfx_bg = $page->gfx() if $ink;
$txt = $page->text();
$cur_y = $table_top_y;
# let's just always go ahead and create $gfx (for drawing borders
# and rules), as it will almost always be needed
$gfx = $page->gfx() if $ink; # for borders, rules, etc.
$gfx->strokecolor($border_c) if $ink;
# Draw the top line (border), only if h_border_w > 0, as we
# don't know what rules are doing
if ($ink && $h_border_w) {
if ($next_top_border == 0) {
# first top border (page 1), use specified border
$gfx->linewidth($h_border_w);
} elsif ($next_top_border == 1) {
# solid thin line at start of a row
$gfx->linewidth($border_w_default);
} else { # == 2
# dashed thin line at continuation in middle of row
$gfx->linewidth($border_w_default);
$gfx->linedash($dashed_rule_default);
}
$gfx->move( $xbase-$v_border_w/2 , $cur_y );
$gfx->hline($xbase + $width + $v_border_w/2);
$gfx->stroke();
$gfx->linedash();
}
my @actual_column_widths;
my %colspanned;
# Each iteration adds a row to the current page until the page is full
# or there are no more rows to add
# Row_Loop
while (scalar(@{$data}) and $cur_y-$rows_height->[0] > $bot_margin) {
# Remove the next item from $data
my $data_row = shift @{$data};
# Get max columns number to know later how many vertical lines to draw
$columns_number = scalar(@$data_row);
# Get the next set of row related settings
# Row Height (starting point for $current_min_rh)
my $current_min_rh = shift @$rows_height;
my $actual_row_height = $current_min_rh;
# Row cell widths
my $data_row_widths = shift @$row_col_widths;
# remember, don't have cell_ stuff yet, just row items ($row_idx)!
my $cur_x = $xbase;
my $leftovers = undef; # Reference to text that is returned from text_block()
my $do_leftovers = 0; # part of a row spilled to next page
# Process every cell(column) from current row
# due to colspan, some rows have fewer columns than others
my @save_bg_color; # clear out for each row
my @save_fg_color;
my (@save_v_rule_w, @save_v_rule_c, @save_h_rule_w, @save_h_rule_c);
for ( my $col_idx = 0; $col_idx < $columns_number; $col_idx++ ) {
$GLOBALS->[3] = $row_idx;
$GLOBALS->[4] = $col_idx;
# now have each cell[$row_idx][$col_idx]
next if $colspanned{$row_idx.'_'.$col_idx};
$leftovers->[$col_idx] = undef;
# look for font information for this cell
my ($cell_font, $cell_font_size, $cell_leading, $cell_underline,
$cell_pad_top, $cell_pad_right, $cell_pad_bot,
$cell_pad_left, $cell_justify, $cell_fg_color,
$cell_bg_color, $cell_def_text, $cell_min_w, $cell_max_w);
if ($first_row and $do_headers) {
$is_header_row = 1;
$GLOBALS->[3] = 0;
$cell_font = $header_props->{'font'};
$cell_font_size = $header_props->{'font_size'};
$cell_leading = $header_props->{'leading'};
$cell_height = $header_props->{'min_rh'};
$cell_pad_top = $header_props->{'padding_top'} ||
$header_props->{'padding'};
$cell_pad_right = $header_props->{'padding_right'} ||
$header_props->{'padding'};
$cell_pad_bot = $header_props->{'padding_bottom'} ||
$header_props->{'padding'};
$cell_pad_left = $header_props->{'padding_left'} ||
$header_props->{'padding'};
$cell_max_word_len = $header_props->{'max_word_length'};
$cell_min_w = $header_props->{'min_w'};
$cell_max_w = $header_props->{'max_w'};
$cell_underline = $header_props->{'underline'};
$cell_def_text = $header_props->{'default_text'};
$cell_justify = $header_props->{'justify'};
$cell_bg_color = $header_props->{'bg_color'};
$cell_fg_color = $header_props->{'fg_color'};
$cell_bg_color_even= undef;
$cell_bg_color_odd = undef;
$cell_fg_color_even= undef;
$cell_fg_color_odd = undef;
$cell_h_rule_w = $header_props->{'h_rule_w'};
$cell_v_rule_w = $header_props->{'v_rule_w'};
$cell_h_rule_c = $header_props->{'h_rule_c'};
$cell_v_rule_c = $header_props->{'v_rule_c'};
} else {
# not header row, so initialize to undefined
$is_header_row = 0;
$cell_font = undef;
$cell_font_size = undef;
$cell_leading = undef;
$cell_height = undef;
$cell_pad_top = undef;
$cell_pad_right = undef;
$cell_pad_bot = undef;
$cell_pad_left = undef;
$cell_max_word_len = undef;
$cell_min_w = undef;
$cell_max_w = undef;
$cell_underline = undef;
$cell_def_text = undef;
$cell_justify = undef;
$cell_bg_color = undef;
$cell_fg_color = undef;
$cell_bg_color_even= undef;
$cell_bg_color_odd = undef;
$cell_fg_color_even= undef;
$cell_fg_color_odd = undef;
$cell_h_rule_w = undef;
$cell_v_rule_w = undef;
$cell_h_rule_c = undef;
$cell_v_rule_c = undef;
}
# Get the most specific value if none was already set from header_props
$cell_font = find_value($cell_font,
'font', '', $fnt_obj, $GLOBALS);
$cell_font_size = find_value($cell_font_size,
'font_size', '', 0, $GLOBALS);
if ($cell_font_size == 0) {
if ($is_header_row) {
$cell_font_size = $fnt_size + 2;
} else {
$cell_font_size = $fnt_size;
}
}
$cell_leading = find_value($cell_leading, 'leading',
'leading', -1, $GLOBALS);
if ($cell_leading <= 0) {
$cell_leading = $cell_font_size * $leading_ratio;
}
$cell_height = find_value($cell_height,
'min_rh', '', 0, $GLOBALS);
$cell_pad_top = find_value($cell_pad_top, 'padding_top',
'padding', $padding_default,
$GLOBALS);
$cell_pad_right = find_value($cell_pad_right, 'padding_right',
'padding', $padding_default,
$GLOBALS);
$cell_pad_bot = find_value($cell_pad_bot, 'padding_bottom',
'padding', $padding_default,
$GLOBALS);
$cell_pad_left = find_value($cell_pad_left, 'padding_left',
'padding', $padding_default,
$GLOBALS);
$cell_max_word_len = find_value($cell_max_word_len,
'max_word_len', '',
$max_word_len, $GLOBALS);
$cell_min_w = find_value($cell_min_w, 'min_w',
'', undef, $GLOBALS);
$cell_max_w = find_value($cell_max_w, 'max_w',
'', undef, $GLOBALS);
if (defined $cell_max_w && defined $cell_min_w) {
$cell_max_w = max($cell_max_w, $cell_min_w);
}
$cell_underline = find_value($cell_underline,
'underline', '', $underline,
$GLOBALS);
$cell_def_text = find_value($cell_def_text, 'default_text',
'', $default_text, $GLOBALS);
$cell_justify = find_value($cell_justify, 'justify',
'justify', 'left', $GLOBALS);
# cell bg may still be undef after this, fg must be defined
if ($is_header_row) {
$cell_bg_color = find_value($cell_bg_color, 'bg_color',
'', $h_bg_color_default,
$GLOBALS);
$cell_fg_color = find_value($cell_fg_color, 'fg_color',
'', $h_fg_color_default,
$GLOBALS);
# don't use even/odd colors in header
} else {
$cell_bg_color = find_value($cell_bg_color, 'bg_color',
'', undef, $GLOBALS);
$cell_fg_color = find_value($cell_fg_color, 'fg_color',
'', undef, $GLOBALS);
$cell_bg_color_even = find_value($cell_bg_color_even,
'bg_color_even', '', undef, $GLOBALS);
$cell_bg_color_odd = find_value($cell_bg_color_odd,
'bg_color_odd', '', undef, $GLOBALS);
$cell_fg_color_even = find_value($cell_fg_color_even,
'fg_color_even', '', undef, $GLOBALS);
$cell_fg_color_odd = find_value($cell_fg_color_odd,
'fg_color_odd', '', undef, $GLOBALS);
}
$cell_h_rule_w = find_value($cell_h_rule_w, 'h_rule_w',
'rule_w', $h_border_w, $GLOBALS);
$cell_v_rule_w = find_value($cell_v_rule_w, 'v_rule_w',
'rule_w', $v_border_w, $GLOBALS);
$cell_h_rule_c = find_value($cell_h_rule_c, 'h_rule_c',
'rule_c', $border_c, $GLOBALS);
$cell_v_rule_c = find_value($cell_v_rule_c, 'v_rule_c',
'rule_c', $border_c, $GLOBALS);
# Choose colors for this row. may still be 'undef' after this!
# cell, column, row, global color settings always override
# whatever _even/odd sets
$bg_color = $cell_bg_color;
$fg_color = $cell_fg_color;
if ($oddeven_default) { # new method with consistent odd/even
if (!defined $bg_color) {
$bg_color = $row_is_odd ? $cell_bg_color_odd : $cell_bg_color_even;
}
if (!defined $fg_color) {
$fg_color = $row_is_odd ? $cell_fg_color_odd : $cell_fg_color_even;
}
# don't toggle odd/even yet, wait til end of row
} else { # old method with inconsistent odd/even
if (!defined $bg_color) {
$bg_color = $row_idx % 2 ? $cell_bg_color_even : $cell_bg_color_odd;
}
if (!defined $fg_color) {
$fg_color = $row_idx % 2 ? $cell_fg_color_even : $cell_fg_color_odd;
}
}
# force fg_color to have a value, but bg_color may remain undef
$fg_color ||= $fg_color_default;
## check if so much padding that baseline forced below cell
## bottom, possibly resulting in infinite loop!
#if ($cell_pad_top + $cell_pad_bot + $cell_leading > $cell_height) {
# my $reduce = $cell_pad_top + $cell_pad_bot -
# ($cell_height - $cell_leading);
# carp "Warning! Vertical padding reduced by $reduce to fit cell[$row_idx][$col_idx]";
# $cell_pad_top -= $reduce/2;
# $cell_pad_bot -= $reduce/2;
#}
# Define the font y base position for this line.
$text_start_y = $cur_y - $cell_pad_top - $cell_font_size;
# VARIOUS WIDTHS:
# $col_min_w->[$col_idx] the minimum needed for a column,
# based on requested min_w and maximum word size (longest
# word just fits). this is the running minimum, not the
# per-row value.
# $col_max_w->[$col_idx] the maximum needed for a column,
# based on requested max_w and total length of text, as if
# the longest entire cell is to be written out as one line.
# this is the running maximum, not the per-row value.
#
# $calc_column_widths->[$col_idx] = calculated column widths
# (at least the minimum requested and maximum word size)
# apportioned across the full requested width. these are the
# column widths you'll actually see drawn (before colspan).
# $actual_column_widths[$row_idx][$col_idx] = calculated width
# for this cell, increased by colspan (cols to right).
#
# $data_row_widths->[$col_idx] = cell content width list for
# a row, first element of row_col_widths. could vary down a
# column due to differing length of content.
# $row_col_widths->[$row_idx] = list of max widths per row,
# which can vary down a column due to differing length of
# content.
# $column_widths->[$col_idx] = list of maximum cell widths
# across this row, used to load up $row_col_widths and
# $h_row_widths (header).
# Initialize cell font object
$txt->font( $cell_font, $cell_font_size );
$txt->fillcolor($fg_color) if $ink;
# make sure cell's text is never undef
$data_row->[$col_idx] //= $cell_def_text;
# Handle colspan
my $c_cell_props = $cell_props->[$row_idx][$col_idx];
my $this_cell_width = $calc_column_widths->[$col_idx];
if ($c_cell_props && $c_cell_props->{'colspan'} && $c_cell_props->{'colspan'} > 1) {
my $colspan = $c_cell_props->{'colspan'};
for my $offset (1 .. $colspan - 1) {
$this_cell_width += $calc_column_widths->[$col_idx + $offset]
if $calc_column_widths->[$col_idx + $offset];
$colspanned{$row_idx.'_'.($col_idx + $offset)} = 1;
}
}
$this_cell_width = max($this_cell_width, $min_col_width);
$actual_column_widths[$row_idx][$col_idx] = $this_cell_width;
my %text_options;
if ($cell_underline) {
$text_options{'-underline'} = $cell_underline;
$text_options{'-strokecolor'} = $fg_color;
}
# If the content is wider than the specified width,
# we need to add the text as a text block
# Otherwise just use the $page->text() method
my $content = $data_row->[$col_idx];
$content = $cell_def_text if (ref($content) eq '' &&
$content eq '');
# empty content? doesn't seem to do any harm
if ( ref($content) eq 'ARRAY') {
# it's a markup cell
$cell_markup = $content->[0];
# if it's "leftover" content, markup is 'pre'
my ($rc, $next_y, $remainder);
# upper left corner, width, and max height of this column?
my $ULx = $cur_x + $cell_pad_left;
my $ULy = $cur_y - $cell_pad_top;
my $width = $actual_column_widths[$row_idx][$col_idx] -
$cell_pad_right - $cell_pad_left;
my $max_h = $cur_y - $bottom_margin -
$cell_pad_top - $cell_pad_bot;
($rc, $next_y, $remainder) =
$txt->column($page, $txt, $gfx, $cell_markup,
$content->[1],
'rect'=>[$ULx, $ULy, $width, $max_h],
'font_size'=>$cell_font_size,
%{$content->[2]});
if ($rc) {
# splitting cell
$actual_row_height = max($actual_row_height,
$cur_y - $bottom_margin);
} else {
# got entire content onto this page
$actual_row_height = max($actual_row_height,
$cur_y - $next_y + $cell_pad_bot +
($cell_leading - $cell_font_size)*1.0);
}
# 1.0 multiplier is a good-looking fudge factor to add a
# little space between bottom of text and bottom of cell
# at this point, actual_row_height is the used
# height of this row, for purposes of background cell
# color and left rule drawing. current_min_rh is left as
# the height of one line + padding.
if ( $rc ) {
$leftovers->[$col_idx] = [ 'pre', $remainder,
$content->[2] ];
$do_leftovers = 1;
}
} elsif ( $content !~ m/(.\n.)/ and
$data_row_widths->[$col_idx] and
$data_row_widths->[$col_idx] <=
$actual_column_widths[$row_idx][$col_idx] ) {
# no embedded newlines (no multiple lines)
# and the content width is <= calculated column width?
# content will fit on one line, use text_* calls
if ($ink) {
if ($cell_justify eq 'right') {
# right justified before right padding
$txt->translate($cur_x + $actual_column_widths[$row_idx][$col_idx] - $cell_pad_right, $text_start_y);
$txt->text_right($content, %text_options);
} elsif ($cell_justify eq 'center') {
# center text within the margins (padding)
$txt->translate($cur_x + $cell_pad_left + ($actual_column_widths[$row_idx][$col_idx] - $cell_pad_left - $cell_pad_right)/2, $text_start_y);
$txt->text_center($content, %text_options);
} else {
# left justified after left padding
# (text_left alias for text, in PDF::Builder only)
$txt->translate($cur_x + $cell_pad_left, $text_start_y);
$txt->text($content, %text_options);
}
}
} else {
my ($width_of_last_line, $ypos_of_last_line,
$left_over_text)
= $self->text_block(
$txt,
$content,
$row_idx, $col_idx,
# mandatory args
'x' => $cur_x + $cell_pad_left,
'y' => $text_start_y,
'w' => $actual_column_widths[$row_idx][$col_idx] -
$cell_pad_left - $cell_pad_right,
'h' => $cur_y - $bot_margin -
$cell_pad_top - $cell_pad_bot,
# non-mandatory args
'font_size' => $cell_font_size,
'leading' => $cell_leading,
'align' => $cell_justify,
'text_opt' => \%text_options,
);
# Desi - Removed $leading because of
# fixed incorrect ypos bug in text_block
$actual_row_height = max($actual_row_height,
$cur_y - $ypos_of_last_line + $cell_pad_bot +
($cell_leading - $cell_font_size)*2.5);
# 2.5 multiplier is a good-looking fudge factor to add a
# little space between bottom of text and bottom of cell
# at this point, actual_row_height is the used
# height of this row, for purposes of background cell
# color and left rule drawing. current_min_rh is left as
# the height of one line + padding.
if ( $left_over_text ) {
$leftovers->[$col_idx] = $left_over_text;
$do_leftovers = 1;
}
}
# Hook to pass coordinates back - http://www.perlmonks.org/?node_id=754777
if (ref $arg{'cell_render_hook'} eq 'CODE') {
$arg{'cell_render_hook'}->(
$page,
$first_row,
$row_idx,
$col_idx,
$cur_x,
$cur_y-$actual_row_height,
$actual_column_widths[$row_idx][$col_idx],
$actual_row_height
);
}
$cur_x += $actual_column_widths[$row_idx][$col_idx];
# otherwise lose track of column-related settings
$save_bg_color[$col_idx] = $bg_color;
$save_fg_color[$col_idx] = $fg_color;
$save_v_rule_w[$col_idx] = $cell_v_rule_w;
$save_h_rule_w[$col_idx] = $cell_h_rule_w;
$save_v_rule_c[$col_idx] = $cell_v_rule_c;
$save_h_rule_c[$col_idx] = $cell_h_rule_c;
} # done looping through columns for this row
if ( $do_leftovers ) {
# leftover text in row to output later as new-ish row?
unshift @$data, $leftovers;
unshift @$row_col_widths, $data_row_widths;
unshift @$rows_height, $current_min_rh;
# if push actual_row_height back onto rows_height, it will be
# far too much in some cases, resulting in excess blank space at bottom.
}
if ($oddeven_default) { # new method with consistent odd/even
if ( !($first_row and $do_headers) ) {
# only toggle if not a header
$row_is_odd = ! $row_is_odd;
}
}
# Draw cell bgcolor
# This has to be done separately from the text loop
# because we do not know the final height of the cell until
# all text has been drawn. Nevertheless, it ($gfx_bg) will
# still be rendered before text ($txt).
$cur_x = $xbase;
for (my $col_idx = 0;
$col_idx < scalar(@$data_row);
$col_idx++) {
# restore cell_bg_color, etc.
$bg_color = $save_bg_color[$col_idx];
$fg_color = $save_fg_color[$col_idx];
$cell_v_rule_w = $save_v_rule_w[$col_idx];
$cell_h_rule_w = $save_h_rule_w[$col_idx];
$cell_v_rule_c = $save_v_rule_c[$col_idx];
$cell_h_rule_c = $save_h_rule_c[$col_idx];
# TBD rowspan!
if ($ink) {
if (defined $bg_color &&
!$colspanned{$row_idx.'_'.$col_idx}) {
$gfx_bg->rect( $cur_x, $cur_y-$actual_row_height,
$actual_column_widths[$row_idx][$col_idx], $actual_row_height);
$gfx_bg->fillcolor($bg_color);
$gfx_bg->fill();
}
# draw left vertical border of this cell unless leftmost
if ($gfx && $cell_v_rule_w && $col_idx &&
!$colspanned{$row_idx.'_'.$col_idx}) {
$gfx->linewidth($cell_v_rule_w);
$gfx->strokecolor($cell_v_rule_c);
$gfx->move($cur_x, $cur_y-$actual_row_height);
$gfx->vline( $cur_y - ($row_idx? 0: $h_border_w/2));
$gfx->stroke(); # don't confuse different widths and colors
}
# draw bottom horizontal rule of this cell unless bottom
# of page (no more data or not room for at least one line).
# TBD fix up when implement rowspan
if ($gfx && $cell_h_rule_w && scalar(@{$data}) &&
$cur_y-$actual_row_height-$current_min_rh > $bot_margin ) {
$gfx->linewidth($cell_h_rule_w);
$gfx->strokecolor($cell_h_rule_c);
$gfx->move($cur_x, $cur_y-$actual_row_height);
$gfx->hline( $cur_x + $actual_column_widths[$row_idx][$col_idx] );
$gfx->stroke(); # don't confuse different widths and colors
}
}
$cur_x += $calc_column_widths->[$col_idx];
} # End of for (my $col_idx....
$cur_y -= $actual_row_height;
if (!$ink) {
if ($first_row && $do_headers) {
# this was a header row
$vsizes[1] = $actual_row_height;
} else {
# this was a non-header row
push @vsizes, $actual_row_height;
}
# if implement footer, it will go in [2]
}
if ($do_leftovers) {
# a row has been split across pages. undo bg toggle
$row_is_odd = !$row_is_odd;
$next_top_border = 2; # dashed line
} else {
$row_idx++;
$next_top_border = 1; # solid line
}
$first_row = 0;
} # End of Row_Loop for this page, and possibly whole table
# draw bottom border on this page. first, is this very last row?
# The line overlays and hides any odd business with vertical rules
# in the last row
if (!scalar(@{$data})) { $next_top_border = 0; }
if ($ink) {
if ($gfx && $h_border_w) {
if ($next_top_border == 0) {
# last bottom border, use specified border
$gfx->linewidth($h_border_w);
} elsif ($next_top_border == 1) {
# solid thin line at start of a row
$gfx->linewidth($border_w_default);
} else { # == 2
# dashed thin line at continuation in middle of row
$gfx->linewidth($border_w_default);
$gfx->linedash($dashed_rule_default);
}
# leave next_top_border for next page top of continued table
$gfx->strokecolor($border_c);
$gfx->move( $xbase-$v_border_w/2 , $cur_y );
$gfx->hline($xbase + $width + $v_border_w/2);
$gfx->stroke();
$gfx->linedash();
}
if ($gfx) {
if ($v_border_w) {
# Draw left and right table borders
# These overlay and hide any odd business with horizontal
# rules at the left or right edge
$gfx->linewidth($v_border_w);
$gfx->move( $xbase, $table_top_y);
$gfx->vline( $cur_y );
$gfx->move( $xbase + $width, $table_top_y);
$gfx->vline( $cur_y );
}
# draw all the unrendered lines
$gfx->stroke();
}
}
$pg_cnt++; # on a spillover page
} # End of while (scalar(@{$data})) next row, adding new page if necessary
if ($ink) {
return ($page, --$pg_cnt, $cur_y);
} else {
# calculate overall table height as sum of 1..$#vsizes
for (my $i = 1; $i < @vsizes; $i++) {
$vsizes[0] += $vsizes[$i];
}
# might need to account for really thick horizontal border rules
return @vsizes;
}
} # end of table()
############################################################
# find a value that might be set in a default or in a global
# or column/row/cell specific parameter. fixed order of search
# is cell/header properties, column properties, row properties,
# fallback sequences (e.g., padding_left inherits from padding),
# global default
############################################################
sub find_value {
my ($cell_val, $name, $fallback, $default, $GLOBALS) = @_;
# $fallback can be '' (will be skipped)
my ($cell_props, $col_props, $row_props, $row_idx, $col_idx, $argref) =
@$GLOBALS;
# $row_idx should be 0 for a header entry
my %arg = %$argref;
# $default should never be undefined, except for specific cases!
if (!defined $default &&
($name ne 'underline' &&
$name ne 'bg_color' && $name ne 'fg_color' &&
$name ne 'bg_color_even' && $name ne 'bg_color_odd' &&
$name ne 'fg_color_even' && $name ne 'fg_color_odd' &&
$name ne 'min_w' && $name ne 'max_w') ) {
carp "Error! find_value() default value undefined for '$name'\n";
}
# upon entry, $cell_val is usually either undefined (data row) or
# header property setting (in which case, already set and we're done here)
$cell_val = $cell_props->[$row_idx][$col_idx]->{$name} if
!defined $cell_val;
$cell_val = $cell_props->[$row_idx][$col_idx]->{$fallback} if
!defined $cell_val && $fallback ne '';
$cell_val = $col_props->[$col_idx]->{$name} if
!defined $cell_val;
$cell_val = $col_props->[$col_idx]->{$fallback} if
!defined $cell_val && $fallback ne '';
$cell_val = $row_props->[$row_idx]->{$name} if
!defined $cell_val;
$cell_val = $row_props->[$row_idx]->{$fallback} if
!defined $cell_val && $fallback ne '';
$cell_val = $arg{$name} if
!defined $cell_val;
$cell_val = $arg{$fallback} if
!defined $cell_val && $fallback ne '';
# final court of appeal is the global default (usually defined)
if (!defined $cell_val) {
$cell_val = $default;
}
return $cell_val;
} # end of find_value()
############################################################
# text_block - utility method to build multi-paragraph blocks of text
#
# Parameters:
# $text_object the TEXT object used to output to the PDF
# $text the text to be formatted
# %arg settings to control the formatting and
# output.
# mandatory: x, y, w, h (block position and dimensions)
# defaults are provided for:
# font_size (global $font_size_default)
# leading (font_size * global $leading_ratio)
# no defaults for:
# text_opt (such as underline flag and color)
# parspace (extra vertical space before a paragraph)
# hang (text for ?)
# indent (indentation amount)
# fpindent (first paragraph indent amount)
# flindent (first line indent amount)
# align (justification left|center|right|fulljustify|justify)
#
# $text comes in as one string, possibly with \n embedded.
# split at \n to form 2 or more @paragraphs. each @paragraph
# is a @paragraphs element split on ' ' (list of words to
# fill the available width). one word at a time is moved
# from @paragraph to @line, until the width of the joined
# @line (with ' ' between words) can't be any larger.
# TBD: deal with multiple spaces between words
############################################################
sub text_block {
my $self = shift;
my $text_object = shift;
my $text = shift; # The text to be displayed
my $row_idx = shift; # cell row,col for debug
my $col_idx = shift;
my %arg = @_; # Additional Arguments
my ( $align, $xpos, $ypos, $xbase, $ybase, $line_width, $wordspace, $endw , $width, $height) =
( undef , undef, undef, undef , undef , undef , undef , undef , undef , undef );
my @line = (); # Temp data array with words on one line
my %width = (); # The width of every unique word in the given text
my %text_options = %{ $arg{'text_opt'} };
# Try to provide backward compatibility. "-" starting key name is optional
foreach my $key (keys %arg) {
my $newkey = $key;
if ($newkey =~ s#^-##) {
$arg{$newkey} = $arg{$key};
delete $arg{$key};
}
}
#####
#---
# Let's check mandatory parameters with no default values
#---
$xbase = $arg{'x'} || -1;
$ybase = $arg{'y'} || -1;
$width = $arg{'w'} || -1;
$height = $arg{'h'} || -1;
unless ( $xbase > 0 ) {
carp "Error: Left Edge of Block is NOT defined!\n";
return (0, $ybase, '');
}
unless ( $ybase > 0 ) {
carp "Error: Base Line of Block is NOT defined!\n";
return (0, $ybase, '');
}
unless ( $width > 0 ) {
carp "Error: Width of Block is NOT defined!\n";
return (0, $ybase, '');
}
unless ( $height > 0 ) {
carp "Error: Height of Block is NOT defined!\n";
return (0, $ybase, '');
}
# Check if any text to display. If called from table(), should have
# default text by the time of the call, so this is really as a failsafe
# for standalone text_block() calls. Note that '' won't work!
unless ( defined( $text) and length($text) > 0 ) {
# carp "Warning: No input text found. Use dummy '-'.\n";
# $text = $empty_cell_text;
$text = ' ';
}
# Strip any and Split the text into paragraphs
# if you're on a platform that uses \r to end a line (old Macs?)...
# we're in text_block() only if long line or \n's seen
# @paragraphs is list of paragraphs (long lines)
# @paragraph is list of words within present paragraph (long line)
$text =~ s/\r//g;
my @paragraphs = split(/\n/, $text);
# Width between lines (leading) in points
my $font_size = $arg{'font_size'} || $font_size_default;
my $line_space = defined $arg{'leading'} && $arg{'leading'} > 0 ? $arg{'leading'} : undef;
$line_space ||= $font_size * $leading_ratio;
# leading must be at least font size
$line_space = $font_size * $leading_ratio if $font_size > $line_space;
# Calculate width of all words
my $space_width = $text_object->advancewidth("\x20");
my %word_width;
my @text_words = split(/\s+/, $text);
foreach (@text_words) {
next if exists $word_width{$_};
$word_width{$_} = $text_object->advancewidth($_);
}
# get word list for first paragraph
my @paragraph = split(' ', shift(@paragraphs));
my $first_line = 1; # first line of THIS paragraph
my $paragraph_number = 1;
# Little Init
$xpos = $xbase;
$ypos = $ybase;
$ypos = $ybase + $line_space;
# bottom_border doesn't need to consider pad_bot, as we're only considering
# the space actually available within the cell, already reduced by padding.
my $bottom_border = $ypos - $height;
# While we can add another line. No handling of widows and orphans.
while ( $ypos >= $bottom_border + $line_space ) {
# Is there any text to render ?
unless (@paragraph) {
# Finish if nothing left of all the paragraphs in text
last unless scalar @paragraphs; # another paragraph to process?
# Else take one paragraph (long line) from the text
@paragraph = split(' ', shift( @paragraphs ) );
$paragraph_number++;
# extra space between paragraphs? only if a previous paragraph
$ypos -= $arg{'parspace'} if $arg{'parspace'} and
$paragraph_number > 1;
last unless $ypos >= $bottom_border;
}
$ypos -= $line_space;
$xpos = $xbase;
# While there's room on the line, add another word
@line = ();
$line_width = 0;
# TBD what exactly is hang supposed to do, interaction with
# indent, flindent, fpindent AND effect on min cell width
if ( $first_line && exists $arg{'hang'} ) {
# fixed text to output first, for first line of a paragraph
# TBD Note that hang text is not yet checked for min_col_width or
# max_word_len, and other indents could make line too wide for col!
my $hang_width = $text_object->advancewidth($arg{'hang'});
$text_object->translate( $xpos, $ypos ) if $ink;
$text_object->text( $arg{'hang'} ) if $ink;
$xpos += $hang_width;
$line_width += $hang_width;
$arg{'indent'} += $hang_width if $paragraph_number == 1;
} elsif ( $first_line && exists $arg{'flindent'} &&
$arg{'flindent'} > 0 ) {
# amount to indent on first line of a paragraph
$xpos += $arg{'flindent'};
$line_width += $arg{'flindent'};
} elsif ( $paragraph_number == 1 && exists $arg{'fpindent'} &&
$arg{'fpindent'} > 0 ) {
# amount to indent first paragraph's first line TBD ??
$xpos += $arg{'fpindent'};
$line_width += $arg{'fpindent'};
} elsif ( exists $arg{'indent'} &&
$arg{'indent'} > 0 ) {
# amount to indent first line of following paragraphs
$xpos += $arg{'indent'};
$line_width += $arg{'indent'};
}
# Let's take from paragraph as many words as we can put
# into $width - $indent. repeatedly test with "just one more" word
# from paragraph list, until overflow.
# TBD might be more efficient (as originally intended?) to build
# library of word widths and add them together until "too big",
# back off.
# TBD don't forget to properly handle runs of more than one space.
while ( @paragraph ) {
if ( !@line ) {
# first time through, @line is empty
# first word in paragraph SHOULD fit!!
# TBD: what if $line_width > 0??? due to indent, etc.?
# add 0.01 as safety
if ( $text_object->advancewidth( $paragraph[0] ) +
$line_width <= $width+0.01 ) {
push(@line, shift(@paragraph));
next if @paragraph;
} else {
# this should never happen, but just in case, to
# prevent an infinite loop...
die("!!! Error !!! first word in paragraph for row $row_idx, col $col_idx '$paragraph[0]' doesn't fit into empty line!");
}
} else {
# @line has text in it already
if ( $text_object->advancewidth( join(" ", @line)." " . $paragraph[0] ) +
$line_width <= $width ) {
push(@line, shift(@paragraph));
next if @paragraph;
}
}
last;
}
$line_width += $text_object->advancewidth(join(' ', @line));
# calculate the space width (width to use for a space)
$align = $arg{'align'} || 'left';
if ( $align eq 'fulljustify' or
($align eq 'justify' and @paragraph)) {
@line = split(//,$line[0]) if scalar(@line) == 1;
if (scalar(@line) > 1) {
$wordspace = ($width - $line_width) / (scalar(@line) - 1);
} else {
$wordspace = 0; # effectively left-aligned for single word
}
$align = 'justify';
} else {
# not adding extra spacing between words, just real space
$align = 'left' if $align eq 'justify';
$wordspace = $space_width;
}
$line_width += $wordspace * (scalar(@line) - 1);
if ( $align eq 'justify') {
foreach my $word (@line) {
$text_object->translate( $xpos, $ypos ) if $ink;
$text_object->text( $word ) if $ink;
$xpos += ($word_width{$word} + $wordspace) if (@line);
}
$endw = $width;
} else {
# calculate the left hand position of the line
# if ( $align eq 'right' ) {
# $xpos += $width - $line_width;
# } elsif ( $align eq 'center' ) {
# $xpos += ( $width - $line_width ) / 2;
# }
if ($ink) {
# render the line. TBD This may not work right with indents!
if ($align eq 'right') {
$text_object->translate( $xpos+$width, $ypos );
$endw = $text_object->text_right(join(' ', @line), %text_options);
} elsif ($align eq 'center') {
$text_object->translate( $xpos + $width/2, $ypos );
$endw = $text_object->text_center(join(' ', @line), %text_options);
} else {
$text_object->translate( $xpos, $ypos );
$endw = $text_object->text(join(' ', @line), %text_options);
}
}
}
$first_line = 0;
} # End of while (fitting within vertical space)
# any leftovers of current paragraph? will return as first new paragraph
unshift(@paragraphs, join(' ',@paragraph)) if scalar(@paragraph);
return ($endw, $ypos, join("\n", @paragraphs))
} # End of text_block()
1;
__END__
=pod
For documentation, see Table/Table.pod. A copy of table.html is included in
the library for your convenience, or you can use a tool such as pod2html to
create the HTML.
PDF-Table-1.005/.perl-version 0000644 0000000 0000000 00000000007 14365336064 014310 0 ustar root root 5.10.0
PDF-Table-1.005/META.yml 0000644 0000000 0000000 00000001314 14365336114 013131 0 ustar root root ---
abstract: 'A utility class for building table layouts in a PDF::Builder (or PDF::API2) object.'
author:
- 'Phil Perry'
build_requires:
ExtUtils::MakeMaker: '0'
configure_requires:
ExtUtils::MakeMaker: '0'
dynamic_config: 1
generated_by: 'ExtUtils::MakeMaker version 7.66, CPAN::Meta::Converter version 2.150010'
license: perl
meta-spec:
url: http://module-build.sourceforge.net/META-spec-v1.4.html
version: '1.4'
name: PDF-Table
no_index:
directory:
- t
- inc
requires:
perl: '5.010'
resources:
bugtracker: https://github.com/PhilterPaper/PDF-Table/issues
repository: https://github.com/PhilterPaper/PDF-Table
version: '1.005'
x_serialization_backend: 'CPAN::Meta::YAML version 0.018'