Projekt

Allgemein

Profil

« Zurück | Weiter » 

Revision 42b702a6

Von Moritz Bunkus vor etwa 17 Jahren hinzugefügt

  • ID 42b702a6bbfdef8a094b1fafbdf205c986efd7be
  • Vorgänger de41ce6f
  • Nachfolger 93262a51

Umstellung der PDF-Erzeugungsroutine des ReportGenerator auf die Verwendung des Perl-Moduls PDF::API2, sofern es installiert ist, mit Fallback zur alten Routine mit html2ps.

Unterschiede anzeigen:

SL/InstallationCheck.pm
use English '-no_match_vars';
use IO::File;
use vars qw(@required_modules);
use vars qw(@required_modules @optional_modules);
@required_modules = (
{ "name" => "Class::Accessor", "url" => "http://search.cpan.org/~kasei/" },
......
{ "name" => "Digest::MD5", "url" => "http://search.cpan.org/~gaas/" },
);
@optional_modules = (
{ "name" => "PDF::API2", "url" => "http://search.cpan.org/~areibens/" },
);
sub module_available {
my ($module) = @_;
SL/ReportGenerator.pm
'html_template' => 'report_generator/html_report',
'pdf_template' => 'report_generator/pdf_report',
'pdf_export' => {
'paper_size' => 'A4',
'paper_size' => 'a4',
'orientation' => 'landscape',
'font_size' => '10',
'font_name' => 'Verdana',
'font_size' => '7',
'margin_top' => 1.5,
'margin_left' => 1.5,
'margin_bottom' => 1.5,
......
my $self = shift;
my %options = @_;
map { $self->{options}->{$_} = $options{$_} } keys %options;
while (my ($key, $value) = each %options) {
if ($key eq 'pdf_export') {
map { $self->{options}->{pdf_export}->{$_} = $value->{$_} } keys %{ $value };
} else {
$self->{options}->{$key} = $value;
}
}
}
sub set_options_from_form {
......
my $allow_pdf_export = $opts->{allow_pdf_export} && (-x $main::html2ps_bin) && (-x $main::ghostscript_bin);
eval { require PDF::API2; require PDF::Table; };
$allow_pdf_export |= 1 if (! $@);
my $variables = {
'TITLE' => $opts->{title},
'TOP_INFO_TEXT' => $self->html_format($opts->{top_info_text}),
......
return $self->{form}->parse_html_template($self->{options}->{html_template}, $variables);
}
sub _cm2bp {
# 1 bp = 1/72 in
# 1 in = 2.54 cm
return $_[0] * 72 / 2.54;
}
sub render_pdf_with_pdf_api2 {
my $self = shift;
my $variables = $self->prepare_html_content();
my $form = $self->{form};
my $myconfig = $self->{myconfig};
my $opts = $self->{options};
my $params = $opts->{pdf_export};
my (@data, @column_props, @cell_props);
my $data_row = [];
my $cell_props_row = [];
my @visible_columns = $self->get_visible_columns('HTML');
foreach $name (@visible_columns) {
$column = $self->{columns}->{$name};
push @{ $data_row }, $column->{text};
push @{ $cell_props_row }, {};
push @column_props, { 'justify' => $column->{align} eq 'right' ? 'right' : 'left' };
}
push @data, $data_row;
push @cell_props, $cell_props_row;
my $num_columns = scalar @column_props;
foreach my $row_set (@{ $self->{data} }) {
if ('HASH' eq ref $row_set) {
if ($row_set->{type} eq 'colspan_data') {
push @data, [ $row_set->{data} ];
$cell_props_row = [];
push @cell_props, $cell_props_row;
foreach (0 .. $num_columns - 1) {
push @{ $cell_props_row }, { 'background_color' => '#000000',
'font_color' => '#ffffff', };
}
}
next;
}
foreach my $row (@{ $row_set }) {
$data_row = [];
push @data, $data_row;
my $col_idx = 0;
foreach my $col_name (@visible_columns) {
my $col = $row->{$col_name};
push @{ $data_row }, join("\n", @{ $col->{data} });
$column_props[$col_idx]->{justify} = 'right' if ($col->{align} eq 'right');
$col_idx++;
}
$cell_props_row = [];
push @cell_props, $cell_props_row;
foreach (0 .. $num_columns - 1) {
push @{ $cell_props_row }, { };
}
}
}
foreach my $i (0 .. scalar(@data) - 1) {
my $aref = $data[$i];
my $num_columns_here = scalar @{ $aref };
if ($num_columns_here < $num_columns) {
push @{ $aref }, ('') x ($num_columns - $num_columns_here);
} elsif ($num_columns_here > $num_columns) {
splice @{ $aref }, $num_columns;
}
}
my $papersizes = {
'a3' => [ 842, 1190 ],
'a4' => [ 595, 842 ],
'a5' => [ 420, 595 ],
'letter' => [ 612, 792 ],
'legal' => [ 612, 1008 ],
};
my %supported_fonts = map { $_ => 1 } qw(courier georgia helvetica times verdana);
my $paper_size = defined $params->{paper_size} && defined $papersizes->{lc $params->{paper_size}} ? lc $params->{paper_size} : 'a4';
my ($paper_width, $paper_height);
if (lc $params->{orientation} eq 'landscape') {
($paper_width, $paper_height) = @{$papersizes->{$paper_size}}[1, 0];
} else {
($paper_width, $paper_height) = @{$papersizes->{$paper_size}}[0, 1];
}
my $margin_top = _cm2bp($params->{margin_top} || 1.5);
my $margin_bottom = _cm2bp($params->{margin_bottom} || 1.5);
my $margin_left = _cm2bp($params->{margin_left} || 1.5);
my $margin_right = _cm2bp($params->{margin_right} || 1.5);
my $table = PDF::Table->new();
my $pdf = PDF::API2->new();
my $page = $pdf->page();
$pdf->mediabox($paper_width, $paper_height);
my $font = $pdf->corefont(defined $params->{font_name} && $supported_fonts{lc $params->{font_name}} ? ucfirst $params->{font_name} : 'Verdana',
'-encoding' => $main::dbcharset || 'ISO-8859-15');
my $font_size = $params->{font_size} || 7;
my $title_font_size = $font_size + 1;
my $padding = 1;
my $font_height = $font_size + 2 * $padding;
my $title_font_height = $font_size + 2 * $padding;
my $header_height = 2 * $title_font_height if ($opts->{title});
my $footer_height = 2 * $font_height if ($params->{number});
my $top_text_height = 0;
if ($self->{options}->{top_info_text}) {
my $top_text = $self->{options}->{top_info_text};
$top_text =~ s/\r//g;
$top_text =~ s/\n+$//;
my @lines = split m/\n/, $top_text;
$top_text_height = $font_height * scalar @lines;
foreach my $line_no (0 .. scalar(@lines) - 1) {
my $y_pos = $paper_height - $margin_top - $header_height - $line_no * $font_height;
my $text_obj = $page->text();
$text_obj->font($font, $font_size);
$text_obj->translate($margin_left, $y_pos);
$text_obj->text($lines[$line_no]);
}
}
$table->table($pdf,
$page,
\@data,
'x' => $margin_left,
'w' => $paper_width - $margin_left - $margin_right,
'start_y' => $paper_height - $margin_top - $header_height - $top_text_height,
'next_y' => $paper_height - $margin_top - $header_height,
'start_h' => $paper_height - $margin_top - $margin_bottom - $header_height - $footer_height - $top_text_height,
'next_h' => $paper_height - $margin_top - $margin_bottom - $header_height - $footer_height,
'padding' => 1,
'background_color_odd' => '#ffffff',
'background_color_even' => '#eeeeee',
'font' => $font,
'font_size' => $font_size,
'font_color' => '#000000',
'header_props' => {
'bg_color' => '#ffffff',
'repeat' => 1,
'font_color' => '#000000',
},
'column_props' => \@column_props,
'cell_props' => \@cell_props,
);
foreach my $page_num (1..$pdf->pages()) {
my $curpage = $pdf->openpage($page_num);
if ($params->{number}) {
my $label = $main::locale->text("Page #1/#2", $page_num, $pdf->pages());
my $text_obj = $curpage->text();
$text_obj->font($font, $font_size);
$text_obj->translate(($paper_width - $margin_left - $margin_right) / 2 + $margin_left - $text_obj->advancewidth($label) / 2, $margin_bottom);
$text_obj->text($label);
}
if ($opts->{title}) {
my $text_obj = $curpage->text();
$text_obj->font($font, $title_font_size);
$text_obj->translate(($paper_width - $margin_left - $margin_right) / 2 + $margin_left - $text_obj->advancewidth($opts->{title}) / 2,
$paper_height - $margin_top);
$text_obj->text($opts->{title}, '-underline' => 1);
}
}
my $filename = $self->get_attachment_basename();
print qq|content-type: application/pdf\n|;
print qq|content-disposition: attachment; filename=${filename}.pdf\n\n|;
print $pdf->stringify();
}
sub verify_paper_size {
my $self = shift;
my $requested_paper_size = lc shift;
......
return $allowed_paper_sizes{$requested_paper_size} ? $requested_paper_size : $default_paper_size;
}
sub generate_pdf_content {
sub render_pdf_with_html2ps {
my $self = shift;
my $variables = $self->prepare_html_content();
my $form = $self->{form};
......
}
}
sub generate_pdf_content {
my $self = shift;
eval { require PDF::API2; require PDF::Table; };
if ($@) {
return $self->render_pdf_with_html2ps(@_);
} else {
return $self->render_pdf_with_pdf_api2(@_);
}
}
sub unescape_string {
my $self = shift;
my $text = shift;
bin/mozilla/reportgenerator.pl
$form->{copies} = max $myconfig{copies} * 1, 1;
my $allow_font_selection = 1;
eval { require PDF::API2; };
$allow_font_selection = 0 if ($@);
$form->{title} = $locale->text('PDF export -- options');
$form->header();
print $form->parse_html_template('report_generator/pdf_export_options', { 'HIDDEN' => \@form_values });
print $form->parse_html_template('report_generator/pdf_export_options', { 'HIDDEN' => \@form_values,
'ALLOW_FONT_SELECTION' => $allow_font_selection, });
$lxdebug->leave_sub();
}
doc/modules/LICENSE.PDF-Table
The "Artistic License"
Preamble
The intent of this document is to state the conditions under which a
Package may be copied, such that the Copyright Holder maintains some
semblance of artistic control over the development of the package,
while giving the users of the package the right to use and distribute
the Package in a more-or-less customary fashion, plus the right to make
reasonable modifications.
Definitions:
"Package" refers to the collection of files distributed by the
Copyright Holder, and derivatives of that collection of files
created through textual modification.
"Standard Version" refers to such a Package if it has not been
modified, or has been modified in accordance with the wishes
of the Copyright Holder as specified below.
"Copyright Holder" is whoever is named in the copyright or
copyrights for the package.
"You" is you, if you're thinking about copying or distributing
this Package.
"Reasonable copying fee" is whatever you can justify on the
basis of media cost, duplication charges, time of people involved,
and so on. (You will not be required to justify it to the
Copyright Holder, but only to the computing community at large
as a market that must bear the fee.)
"Freely Available" means that no fee is charged for the item
itself, though there may be fees involved in handling the item.
It also means that recipients of the item may redistribute it
under the same conditions they received it.
1. You may make and give away verbatim copies of the source form of the
Standard Version of this Package without restriction, provided that you
duplicate all of the original copyright notices and associated disclaimers.
2. You may apply bug fixes, portability fixes and other modifications
derived from the Public Domain or from the Copyright Holder. A Package
modified in such a way shall still be considered the Standard Version.
3. You may otherwise modify your copy of this Package in any way, provided
that you insert a prominent notice in each changed file stating how and
when you changed that file, and provided that you do at least ONE of the
following:
a) place your modifications in the Public Domain or otherwise make them
Freely Available, such as by posting said modifications to Usenet or
an equivalent medium, or placing the modifications on a major archive
site such as uunet.uu.net, or by allowing the Copyright Holder to include
your modifications in the Standard Version of the Package.
b) use the modified Package only within your corporation or organization.
c) rename any non-standard executables so the names do not conflict
with standard executables, which must also be provided, and provide
a separate manual page for each non-standard executable that clearly
documents how it differs from the Standard Version.
d) make other distribution arrangements with the Copyright Holder.
4. You may distribute the programs of this Package in object code or
executable form, provided that you do at least ONE of the following:
a) distribute a Standard Version of the executables and library files,
together with instructions (in the manual page or equivalent) on where
to get the Standard Version.
b) accompany the distribution with the machine-readable source of
the Package with your modifications.
c) give non-standard executables non-standard names, and clearly
document the differences in manual pages (or equivalent), together
with instructions on where to get the Standard Version.
d) make other distribution arrangements with the Copyright Holder.
5. You may charge a reasonable copying fee for any distribution of this
Package. You may charge any fee you choose for support of this
Package. You may not charge a fee for this Package itself. However,
you may distribute this Package in aggregate with other (possibly
commercial) programs as part of a larger (possibly commercial) software
distribution provided that you do not advertise this Package as a
product of your own. You may embed this Package's interpreter within
an executable of yours (by linking); this shall be construed as a mere
form of aggregation, provided that the complete Standard Version of the
interpreter is so embedded.
6. The scripts and library files supplied as input to or produced as
output from the programs of this Package do not automatically fall
under the copyright of this Package, but belong to whoever generated
them, and may be sold commercially, and may be aggregated with this
Package. If such scripts or library files are aggregated with this
Package via the so-called "undump" or "unexec" methods of producing a
binary executable image, then distribution of such an image shall
neither be construed as a distribution of this Package nor shall it
fall under the restrictions of Paragraphs 3 and 4, provided that you do
not represent such an executable image as a Standard Version of this
Package.
7. C subroutines (or comparably compiled subroutines in other
languages) supplied by you and linked into this Package in order to
emulate subroutines and variables of the language defined by this
Package shall not be considered part of this Package, but are the
equivalent of input as in Paragraph 6, provided these subroutines do
not change the language in any way that would cause it to fail the
regression tests for the language.
8. Aggregation of this Package with a commercial distribution is always
permitted provided that the use of this Package is embedded; that is,
when no overt attempt is made to make this Package's interfaces visible
to the end user of the commercial distribution. Such use shall not be
construed as a distribution of this Package.
9. The name of the Copyright Holder may not be used to endorse or promote
products derived from this software without specific prior written permission.
10. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
The End
doc/modules/README.PDF-Table
PDF-Table version 0.9.3
=====================
SOME NOTES
This module is intended for table generation using PDF::API2
The current version is RC1 and I will apreciate any feedback.
Developed and tested on i586 Linux SuSE 10.0 and perl, v5.8.7 built for i586-linux-thread-multi
CHANGES
Since version 0.02 there are many changes.
See the ChangeLog file or make a diff from the tools menu in CPAN
CONTACTS
See http://search.cpan.org/~omega/
INSTALLATION
To install this module type the following:
perl Makefile.PL
make
make test
make install
DEPENDENCIES
This module requires these other modules and libraries:
PDF::API2
COPYRIGHT AND LICENCE
Put the correct copyright and licence information here.
Copyright (C) 2006 by Daemmon Hughes
Extended by Desislav Kamenov since version 0.02
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.
locale/de/all
'Follow-Up saved.' => 'Wiedervorlage gespeichert.',
'Follow-Ups' => 'Wiedervorlagen',
'Follow-up for' => 'Wiedervorlage f?r',
'Font' => 'Schriftart',
'Font size' => 'Schriftgr&ouml;&szlig;e',
'For each unit there\'s either no or exactly one base unit. If you chose a base unit then you also have to chose a factor. That way the new unit will be defined as a multiple of the base unit. The base unit must be the &quot;smaller&quot; one. A factor may not be less than 1. Therefore you may define &quot;kg&quot; with the base unit &quot;g&quot; and a factor of &quot;1&quot;, but not the other way round.' => 'Einheiten haben entweder keine oder genau eine Basiseinheit, von der sie ein Vielfaches sind. Wenn Sie eine Basiseinheit ausw&auml;hlen, dann m&uuml;ssen Sie auch einen Faktor eingeben. Sie m&uuml;ssen Einheiten als ein Vielfaches einer kleineren Einheit eingeben. So ist die Definition von &quot;kg&quot; mit der Basiseinheit &quot;g&quot; und dem Faktor 1000 zul&auml;ssig, die Definition von &quot;g&quot; mit der Basiseinheit &quot;kg&quot; und dem Faktor &quot;0,001&quot; hingegen nicht.',
'Foreign Exchange Gain' => 'Wechselkursertr?ge',
......
'Packing List Date missing!' => 'Datum f?r Verpackungsliste fehlt!',
'Packing List Number missing!' => 'Verpackungslistennummer fehlt!',
'Packing Lists' => 'Lieferschein',
'Page #1/#2' => 'Seite #1/#2',
'Paid' => 'bezahlt',
'Part' => 'Ware',
'Part Description' => 'Artikelbeschreibung',
locale/de/ap
'POSTED AS NEW' => 'Als neu gebucht',
'PRINTED' => 'Gedruckt',
'Packing List' => 'Lieferschein',
'Page #1/#2' => 'Seite #1/#2',
'Paid' => 'bezahlt',
'Part Number' => 'Artikelnummer',
'Part description' => 'Artikelbeschreibung',
locale/de/ar
'POSTED AS NEW' => 'Als neu gebucht',
'PRINTED' => 'Gedruckt',
'Packing List' => 'Lieferschein',
'Page #1/#2' => 'Seite #1/#2',
'Paid' => 'bezahlt',
'Part Number' => 'Artikelnummer',
'Part description' => 'Artikelbeschreibung',
locale/de/ca
'POSTED AS NEW' => 'Als neu gebucht',
'PRINTED' => 'Gedruckt',
'Packing List' => 'Lieferschein',
'Page #1/#2' => 'Seite #1/#2',
'Pick List' => 'Sammelliste',
'Proforma Invoice' => 'Proformarechnung',
'Project Number' => 'Projektnummer',
locale/de/ct
'POSTED AS NEW' => 'Als neu gebucht',
'PRINTED' => 'Gedruckt',
'Packing List' => 'Lieferschein',
'Page #1/#2' => 'Seite #1/#2',
'Part Number' => 'Artikelnummer',
'Part description' => 'Artikelbeschreibung',
'Phone' => 'Telefon',
locale/de/dn
'Packing List' => 'Lieferschein',
'Packing List Date missing!' => 'Datum f?r Verpackungsliste fehlt!',
'Packing List Number missing!' => 'Verpackungslistennummer fehlt!',
'Page #1/#2' => 'Seite #1/#2',
'Part Description' => 'Artikelbeschreibung',
'Part Number' => 'Artikelnummer',
'Part description' => 'Artikelbeschreibung',
locale/de/do
'Packing List' => 'Lieferschein',
'Packing List Date missing!' => 'Datum f?r Verpackungsliste fehlt!',
'Packing List Number missing!' => 'Verpackungslistennummer fehlt!',
'Page #1/#2' => 'Seite #1/#2',
'Part Description' => 'Artikelbeschreibung',
'Part Number' => 'Artikelnummer',
'Part description' => 'Artikelbeschreibung',
locale/de/fu
'POSTED AS NEW' => 'Als neu gebucht',
'PRINTED' => 'Gedruckt',
'Packing List' => 'Lieferschein',
'Page #1/#2' => 'Seite #1/#2',
'Pick List' => 'Sammelliste',
'Proforma Invoice' => 'Proformarechnung',
'Purchase Order' => 'Lieferantenauftrag',
locale/de/gl
'POSTED AS NEW' => 'Als neu gebucht',
'PRINTED' => 'Gedruckt',
'Packing List' => 'Lieferschein',
'Page #1/#2' => 'Seite #1/#2',
'Part Number' => 'Artikelnummer',
'Part description' => 'Artikelbeschreibung',
'Pick List' => 'Sammelliste',
locale/de/ic
'Packing List' => 'Lieferschein',
'Packing List Date missing!' => 'Datum f?r Verpackungsliste fehlt!',
'Packing List Number missing!' => 'Verpackungslistennummer fehlt!',
'Page #1/#2' => 'Seite #1/#2',
'Part Description' => 'Artikelbeschreibung',
'Part Description missing!' => 'Artikelbezeichnung fehlt!',
'Part Number' => 'Artikelnummer',
locale/de/login
'Packing List' => 'Lieferschein',
'Packing List Date missing!' => 'Datum f?r Verpackungsliste fehlt!',
'Packing List Number missing!' => 'Verpackungslistennummer fehlt!',
'Page #1/#2' => 'Seite #1/#2',
'Part Description' => 'Artikelbeschreibung',
'Part Number' => 'Artikelnummer',
'Part description' => 'Artikelbeschreibung',
locale/de/oe
'Packing List' => 'Lieferschein',
'Packing List Date missing!' => 'Datum f?r Verpackungsliste fehlt!',
'Packing List Number missing!' => 'Verpackungslistennummer fehlt!',
'Page #1/#2' => 'Seite #1/#2',
'Part Description' => 'Artikelbeschreibung',
'Part Number' => 'Artikelnummer',
'Part description' => 'Artikelbeschreibung',
locale/de/projects
'POSTED AS NEW' => 'Als neu gebucht',
'PRINTED' => 'Gedruckt',
'Packing List' => 'Lieferschein',
'Page #1/#2' => 'Seite #1/#2',
'Part Number' => 'Artikelnummer',
'Part description' => 'Artikelbeschreibung',
'Pick List' => 'Sammelliste',
locale/de/reportgenerator
'POSTED AS NEW' => 'Als neu gebucht',
'PRINTED' => 'Gedruckt',
'Packing List' => 'Lieferschein',
'Page #1/#2' => 'Seite #1/#2',
'Pick List' => 'Sammelliste',
'Proforma Invoice' => 'Proformarechnung',
'Purchase Order' => 'Lieferantenauftrag',
locale/de/rp
'POSTED AS NEW' => 'Als neu gebucht',
'PRINTED' => 'Gedruckt',
'Packing List' => 'Lieferschein',
'Page #1/#2' => 'Seite #1/#2',
'Part Number' => 'Artikelnummer',
'Part description' => 'Artikelbeschreibung',
'Payments' => 'Zahlungsausg?nge',
locale/de/todo
'Packing List' => 'Lieferschein',
'Packing List Date missing!' => 'Datum f?r Verpackungsliste fehlt!',
'Packing List Number missing!' => 'Verpackungslistennummer fehlt!',
'Page #1/#2' => 'Seite #1/#2',
'Part Description' => 'Artikelbeschreibung',
'Part Number' => 'Artikelnummer',
'Part description' => 'Artikelbeschreibung',
locale/de/wh
'POSTED AS NEW' => 'Als neu gebucht',
'PRINTED' => 'Gedruckt',
'Packing List' => 'Lieferschein',
'Page #1/#2' => 'Seite #1/#2',
'Part Number' => 'Artikelnummer',
'Part description' => 'Artikelbeschreibung',
'Pick List' => 'Sammelliste',
modules/override/PDF/Table.pm
package PDF::Table;
use 5.006;
use strict;
use warnings;
our $VERSION = '0.9.3';
############################################################
#
# new - Constructor
#
# Parameters are meta information about the PDF
#
# $pdf = PDF::Table->new();
#
############################################################
sub new
{
my ($type) = @_;
my $class = ref($type) || $type;
my $self = {};
bless ($self, $class);
return $self;
}
############################################################
#
# text_block - utility method to build multi-paragraph blocks of text
#
############################################################
sub text_block
{
my $self = shift;
my $text_object = shift;
my $text = shift; # The text to be displayed
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 givven text
# Try to provide backward compatibility
foreach my $key (keys %arg)
{
my $newkey = $key;
if($newkey =~ s#^-##)
{
$arg{$newkey} = $arg{$key};
delete $arg{$key};
}
}
#####
#---
# Lets 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 ){ print "Error: Left Edge of Block is NOT defined!\n"; return; }
unless( $ybase > 0 ){ print "Error: Base Line of Block is NOT defined!\n"; return; }
unless( $width > 0 ){ print "Error: Width of Block is NOT defined!\n"; return; }
unless( $height > 0 ){ print "Error: Height of Block is NOT defined!\n"; return; }
# Check if any text to display
unless( defined( $text) and length($text) > 0 )
{
print "Warning: No input text found. Trying to add dummy '-' and not to break everything.\n";
$text = '-';
}
# Strip any <CR> and Split the text into paragraphs
$text =~ s/\r//g;
my @paragraphs = split(/\n/, $text);
# Width between lines in pixels
my $line_space = defined $arg{'lead'} && $arg{'lead'} > 0 ? $arg{'lead'} : 12;
# Calculate width of all words
my $space_width = $text_object->advancewidth("\x20");
my @words = split(/\s+/, $text);
foreach (@words)
{
next if exists $width{$_};
$width{$_} = $text_object->advancewidth($_);
}
my @paragraph = split(' ', shift(@paragraphs));
my $first_line = 1;
my $first_paragraph = 1;
# Little Init
$xpos = $xbase;
$ypos = $ybase;
$ypos = $ybase + $line_space;
my $bottom_border = $ybase - $height;
# While we can add another line
while ( $ypos >= $bottom_border + $line_space )
{
# Is there any text to render ?
unless (@paragraph)
{
# Finish if nothing left
last unless scalar @paragraphs;
# Else take one line from the text
@paragraph = split(' ', shift( @paragraphs ) );
$ypos -= $arg{'parspace'} if $arg{'parspace'};
last unless $ypos >= $bottom_border;
}
$ypos -= $line_space;
$xpos = $xbase;
# While there's room on the line, add another word
@line = ();
$line_width = 0;
if( $first_line && exists $arg{'hang'} )
{
my $hang_width = $text_object->advancewidth($arg{'hang'});
$text_object->translate( $xpos, $ypos );
$text_object->text( $arg{'hang'} );
$xpos += $hang_width;
$line_width += $hang_width;
$arg{'indent'} += $hang_width if $first_paragraph;
}
elsif( $first_line && exists $arg{'flindent'} && $arg{'flindent'} > 0 )
{
$xpos += $arg{'flindent'};
$line_width += $arg{'flindent'};
}
elsif( $first_paragraph && exists $arg{'fpindent'} && $arg{'fpindent'} > 0 )
{
$xpos += $arg{'fpindent'};
$line_width += $arg{'fpindent'};
}
elsif (exists $arg{'indent'} && $arg{'indent'} > 0 )
{
$xpos += $arg{'indent'};
$line_width += $arg{'indent'};
}
# Lets take from paragraph as many words as we can put into $width - $indent;
while ( @paragraph and $text_object->advancewidth( join("\x20", @line)."\x20" . $paragraph[0]) +
$line_width < $width )
{
push(@line, shift(@paragraph));
}
$line_width += $text_object->advancewidth(join('', @line));
# calculate the space width
if( $arg{'align'} eq 'fulljustify' or ($arg{'align'} eq 'justify' and @paragraph))
{
@line = split(//,$line[0]) if (scalar(@line) == 1) ;
$wordspace = ($width - $line_width) / (scalar(@line) - 1);
$align='justify';
}
else
{
$align=($arg{'align'} eq 'justify') ? 'left' : $arg{'align'};
$wordspace = $space_width;
}
$line_width += $wordspace * (scalar(@line) - 1);
if( $align eq 'justify')
{
foreach my $word (@line)
{
$text_object->translate( $xpos, $ypos );
$text_object->text( $word );
$xpos += ($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 / 2 ) - ( $line_width / 2 );
}
# render the line
$text_object->translate( $xpos, $ypos );
$endw = $text_object->text( join("\x20", @line));
}
$first_line = 0;
}#End of while(
unshift(@paragraphs, join(' ',@paragraph)) if scalar(@paragraph);
return ($endw, $ypos, join("\n", @paragraphs))
}
############################################################
# table - utility method to build multi-row, multicolumn tables
############################################################
sub table
{
my $self = shift;
my $pdf = shift;
my $page = shift;
my $data = shift;
my %arg = @_;
#=====================================
# Mandatory Arguments Section
#=====================================
unless($pdf and $page and $data)
{
print "Error: Mandatory parameter is missing pdf/page/data object!\n";
return;
}
# Try to provide backward compatibility
foreach my $key (keys %arg)
{
my $newkey = $key;
if($newkey =~ s#^-##)
{
$arg{$newkey} = $arg{$key};
delete $arg{$key};
}
}
#TODO: Add code for header props compatibility and col_props comp....
#####
my ( $xbase, $ybase, $width, $height ) = ( undef, undef, undef, undef );
# Could be 'int' or 'real' values
$xbase = $arg{'x' } || -1;
$ybase = $arg{'start_y'} || -1;
$width = $arg{'w' } || -1;
$height = $arg{'start_h'} || -1;
# Global geometry parameters are also mandatory.
unless( $xbase > 0 ){ print "Error: Left Edge of Table is NOT defined!\n"; return; }
unless( $ybase > 0 ){ print "Error: Base Line of Table is NOT defined!\n"; return; }
unless( $width > 0 ){ print "Error: Width of Table is NOT defined!\n"; return; }
unless( $height > 0 ){ print "Error: Height of Table is NOT defined!\n"; return; }
# Ensure default values for -next_y and -next_h
my $next_y = $arg{'next_y'} || $arg{'start_y'} || 0;
my $next_h = $arg{'next_h'} || $arg{'start_h'} || 0;
# Create Text Object
my $txt = $page->text;
# Set Default Properties
my $fnt_name = $arg{'font' } || $pdf->corefont('Times',-encode => 'utf8');
my $fnt_size = $arg{'font_size' } || 12;
my $max_word_len= $arg{'max_word_length' } || 20;
#=====================================
# Table Header Section
#=====================================
# Disable header row into the table
my $header_props = 0;
# 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 params and put defaults if needed
$header_props->{'repeat' } = $header_props->{'repeat' } || 0;
$header_props->{'font' } = $header_props->{'font' } || $fnt_name;
$header_props->{'font_color' } = $header_props->{'font_color' } || '#000066';
$header_props->{'font_size' } = $header_props->{'font_size' } || $fnt_size + 2;
$header_props->{'bg_color' } = $header_props->{'bg_color' } || '#FFFFAA';
}
my $header_row = undef;
#=====================================
# Other Parameters check
#=====================================
my $lead = $arg{'lead' } || $fnt_size;
my $pad_left = $arg{'padding_left' } || $arg{'padding'} || 0;
my $pad_right = $arg{'padding_right' } || $arg{'padding'} || 0;
my $pad_top = $arg{'padding_top' } || $arg{'padding'} || 0;
my $pad_bot = $arg{'padding_bottom' } || $arg{'padding'} || 0;
my $pad_w = $pad_left + $pad_right;
my $pad_h = $pad_top + $pad_bot ;
my $line_w = defined $arg{'border'} ? $arg{'border'} : 1 ;
my $background_color_even = $arg{'background_color_even' } || $arg{'background_color'} || undef;
my $background_color_odd = $arg{'background_color_odd' } || $arg{'background_color'} || undef;
my $font_color_even = $arg{'font_color_even' } || $arg{'font_color' } || 'black';
my $font_color_odd = $arg{'font_color_odd' } || $arg{'font_color' } || 'black';
my $border_color = $arg{'border_color' } || 'black';
my $min_row_h = $fnt_size + $pad_top + $pad_bot;
my $row_h = defined ($arg{'row_height'})
&&
($arg{'row_height'} > $min_row_h)
?
$arg{'row_height'} : $min_row_h;
my $pg_cnt = 1;
my $cur_y = $ybase;
my $cell_props = $arg{cell_props} || []; # per cell properties
my $row_cnt = ( ref $header_props and $header_props->{'repeat'} ) ? 1 : 0; # current row in user data
#If there is valid data array reference use it!
if(ref $data eq 'ARRAY')
{
# Copy the header row if header is enabled
@$header_row = $$data[0] if defined $header_props;
# 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 array ref of arrayrefs whose values are
# the actual widths of the column/row intersection
my $row_props = [];
# An array ref with the widths of the header row
my $header_row_props = [];
# Scalars that hold sum of the maximum and minimum widths of all columns
my ( $max_col_w , $min_col_w ) = ( 0,0 );
my ( $row, $col_name, $col_fnt_size, $space_w );
# Hash that will hold the width of every word from input text
my $word_w = {};
my $rows_counter = 0;
my $first_row = 1;
foreach $row ( @{$data} )
{
my $column_widths = []; #holds the width of each column
for( my $j = 0; $j < scalar(@$row) ; $j++ )
{
# look for font information for this column
$col_fnt_size = $col_props->[$j]->{'font_size'} || $fnt_size;
if( !$rows_counter and ref $header_props)
{
$txt->font( $header_props->{'font'}, $header_props->{'font_size'} );
}
elsif( $col_props->[$j]->{'font'} )
{
$txt->font( $col_props->[$j]->{'font'}, $col_fnt_size );
}
else
{
$txt->font( $fnt_name, $col_fnt_size );
}
# This should fix a bug with very long word like serial numbers etc.
# $myone is used because $1 gets out of scope in while condition
my $myone;
do{
$myone = 0;
# This RegEx will split any word that is longer than {25} symbols
$row->[$j] =~ s#(\b\S{$max_word_len}?)(\S.*?\b)# $1 $2#;
$myone = 1 if( defined $2 );
}while( $myone );
$space_w = $txt->advancewidth( "\x20" );
$column_widths->[$j] = 0;
$max_col_w = 0;
$min_col_w = 0;
my @words = split( /\s+/, $row->[$j] );
foreach( @words )
{
unless( exists $word_w->{$_} )
{ # Calculate the width of every word and add the space width to it
$word_w->{$_} = $txt->advancewidth( $_ ) + $space_w;
}
$column_widths->[$j] += $word_w->{$_};
$min_col_w = $word_w->{$_} if $word_w->{$_} > $min_col_w;
$max_col_w += $word_w->{$_};
}
$min_col_w += $pad_w;
$max_col_w += $pad_w;
$column_widths->[$j] += $pad_w;
# Keep a running total of the overall min and max widths
$col_props->[$j]->{min_w} = $col_props->[$j]->{min_w} || 0;
$col_props->[$j]->{max_w} = $col_props->[$j]->{max_w} || 0;
if( $min_col_w > $col_props->[$j]->{min_w} )
{ # Calculated Minimum Column Width is more than user-defined
$col_props->[$j]->{min_w} = $min_col_w ;
}
if( $max_col_w > $col_props->[$j]->{max_w} )
{ # Calculated Maximum Column Width is more than user-defined
$col_props->[$j]->{max_w} = $max_col_w ;
}
}#End of for(my $j....
$row_props->[$rows_counter] = $column_widths;
# Copy the calculated row properties of header row.
@$header_row_props = @$column_widths if(!$rows_counter and ref $header_props);
$rows_counter++;
}
# Calc real column widths and expand table width if needed.
my $calc_column_widths;
($calc_column_widths, $width) = $self->CalcColumnWidths( $col_props, $width );
my $comp_cnt = 1;
$rows_counter = 0;
my ( $gfx , $gfx_bg , $background_color , $font_color, );
my ( $bot_marg, $table_top_y, $text_start , $record, $record_widths );
# Each iteration adds a new page as neccessary
while(scalar(@{$data}))
{
my $page_header;
if($pg_cnt == 1)
{
$table_top_y = $ybase;
$bot_marg = $table_top_y - $height;
}
else
{
if(ref $arg{'new_page_func'})
{
$page = &{$arg{'new_page_func'}};
}
else
{
$page = $pdf->page;
}
$table_top_y = $next_y;
$bot_marg = $table_top_y - $next_h;
if( ref $header_props and $header_props->{'repeat'})
{
# Copy Header Data
@$page_header = @$header_row;
my $hrp ;
@$hrp = @$header_row_props ;
# Then prepend it to master data array
unshift @$data ,@$page_header ;
unshift @$row_props ,$hrp ;
$first_row = 1; # Means YES
}
}
# Check for safety reasons
if( $bot_marg < 0 )
{ # This warning should remain i think
print "!!! Warning: !!! Incorrect Table Geometry! Setting bottom margin to end of sheet!\n";
$bot_marg = 0;
}
$gfx_bg = $page->gfx;
$txt = $page->text;
$txt->font($fnt_name, $fnt_size);
$gfx = $page->gfx;
$gfx->strokecolor($border_color);
$gfx->linewidth($line_w);
# Draw the top line
$cur_y = $table_top_y;
$gfx->move( $xbase , $cur_y );
$gfx->hline($xbase + $width );
# Each iteration adds a row to the current page until the page is full
# or there are no more rows to add
while(scalar(@{$data}) and $cur_y-$row_h > $bot_marg)
{
# Remove the next item from $data
$record = shift @{$data};
# Added to resolve infite loop bug with returned undef values
for(my $d = 0; $d < scalar(@{$record}) ; $d++)
{
$record->[$d] = '-' unless( defined $record->[$d]);
}
$record_widths = shift @$row_props;
next unless $record;
# Choose colors for this row
$background_color = $rows_counter % 2 ? $background_color_even : $background_color_odd;
$font_color = $rows_counter % 2 ? $font_color_even : $font_color_odd;
if($first_row and ref $header_props)
{
$background_color = $header_props->{'bg_color'}
}
$text_start = $cur_y - $fnt_size - $pad_top;
my $cur_x = $xbase;
my $leftovers = undef; # Reference to text that is returned from textblock()
my $do_leftovers = 0;
# Process every column from current row
for( my $j = 0; $j < scalar( @$record); $j++ )
{
next unless $col_props->[$j]->{max_w};
next unless $col_props->[$j]->{min_w};
$leftovers->[$j] = undef;
# Choose font color
if( $first_row and ref $header_props )
{
$txt->fillcolor( $header_props->{'font_color'} );
}
elsif( $cell_props->[$row_cnt][$j]{font_color} )
{
$txt->fillcolor( $cell_props->[$row_cnt][$j]{font_color} );
}
elsif( $col_props->[$j]->{'font_color'} )
{
$txt->fillcolor( $col_props->[$j]->{'font_color'} );
}
else
{
$txt->fillcolor($font_color);
}
# Choose font size
if( $first_row and ref $header_props )
{
$col_fnt_size = $header_props->{'font_size'};
}
elsif( $col_props->[$j]->{'font_size'} )
{
$col_fnt_size = $col_props->[$j]->{'font_size'};
}
else
{
$col_fnt_size = $fnt_size;
}
# Choose font family
if( $first_row and ref $header_props )
{
$txt->font( $header_props->{'font'}, $header_props->{'font_size'});
}
elsif( $col_props->[$j]->{'font'} )
{
$txt->font( $col_props->[$j]->{'font'}, $col_fnt_size);
}
else
{
$txt->font( $fnt_name, $col_fnt_size);
}
#TODO: Implement Center text align
$col_props->[$j]->{justify} = $col_props->[$j]->{justify} || 'left';
# If the content is wider than the specified width, we need to add the text as a text block
if($record->[$j] !~ m#(.\n.)# and $record_widths->[$j] and ($record_widths->[$j] < $calc_column_widths->[$j]))
{
my $space = $pad_left;
if($col_props->[$j]->{justify} eq 'right')
{
$space = $calc_column_widths->[$j] -($txt->advancewidth($record->[$j]) + $pad_right);
}
$txt->translate( $cur_x + $space, $text_start );
$txt->text( $record->[$j] );
}
# Otherwise just use the $page->text() method
else
{
my($width_of_last_line, $ypos_of_last_line, $left_over_text) = $self->text_block(
$txt,
$record->[$j],
x => $cur_x + $pad_left,
y => $text_start,
w => $calc_column_widths->[$j] - $pad_w,
h => $cur_y - $bot_marg - $pad_top - $pad_bot,
align => $col_props->[$j]->{justify},
lead => $lead
);
# Desi - Removed $lead because of fixed incorrect ypos bug in text_block
my $this_row_h = $cur_y - ( $ypos_of_last_line - $pad_bot );
$row_h = $this_row_h if $this_row_h > $row_h;
if( $left_over_text )
{
$leftovers->[$j] = $left_over_text;
$do_leftovers = 1;
}
}
$cur_x += $calc_column_widths->[$j];
}
if( $do_leftovers )
{
unshift @$data, $leftovers;
unshift @$row_props, $record_widths;
$rows_counter--;
}
# Draw cell bgcolor
# This has to be separately from the text loop
# because we do not know the final height of the cell until all text has been drawn
$cur_x = $xbase;
for(my $j =0;$j < scalar(@$record);$j++)
{
if ( $cell_props->[$row_cnt][$j]->{'background_color'} ||
$col_props->[$j]->{'background_color'} ||
$background_color )
{
$gfx_bg->rect( $cur_x, $cur_y-$row_h, $calc_column_widths->[$j], $row_h);
if ( $cell_props->[$row_cnt][$j]->{'background_color'} && !$first_row )
{
$gfx_bg->fillcolor($cell_props->[$row_cnt][$j]->{'background_color'});
}
elsif( $col_props->[$j]->{'background_color'} && !$first_row )
{
$gfx_bg->fillcolor($col_props->[$j]->{'background_color'});
}
else
{
$gfx_bg->fillcolor($background_color);
}
$gfx_bg->fill();
}
$cur_x += $calc_column_widths->[$j];
}#End of for(my $j....
$cur_y -= $row_h;
$row_h = $min_row_h;
$gfx->move( $xbase , $cur_y );
$gfx->hline( $xbase + $width );
$rows_counter++;
$row_cnt++ unless ( $first_row );
$first_row = 0;
}# End of while(scalar(@{$data}) and $cur_y-$row_h > $bot_marg)
# Draw vertical lines
$gfx->move( $xbase, $table_top_y);
$gfx->vline( $cur_y );
my $cur_x = $xbase;
for( my $j = 0; $j < scalar(@$record); $j++ )
{
$cur_x += $calc_column_widths->[$j];
$gfx->move( $cur_x, $table_top_y );
$gfx->vline( $cur_y );
}
# ACTUALLY draw all the lines
$gfx->fillcolor( $border_color);
$gfx->stroke if $line_w;
$pg_cnt++;
}# End of while(scalar(@{$data}))
}# End of if(ref $data eq 'ARRAY')
return ($page,--$pg_cnt,$cur_y);
}
# calculate the column widths
sub CalcColumnWidths
{
my $self = shift;
my $col_props = shift;
my $avail_width = shift;
my $min_width = 0;
my $calc_widths ;
for(my $j = 0; $j < scalar( @$col_props); $j++)
{
$min_width += $col_props->[$j]->{min_w};
}
# I think this is the optimal variant when good view can be guaranateed
if($avail_width < $min_width)
{
# print "!!! Warning !!!\n Calculated Mininal width($min_width) > Table width($avail_width).\n",
# ' Expanding table width to:',int($min_width)+1,' but this could lead to unexpected results.',"\n",
# ' Possible solutions:',"\n",
# ' 0)Increase table width.',"\n",
# ' 1)Decrease font size.',"\n",
# ' 2)Choose a more narrow font.',"\n",
# ' 3)Decrease "max_word_length" parameter.',"\n",
# ' 4)Rotate page to landscape(if it is portrait).',"\n",
# ' 5)Use larger paper size.',"\n",
# '!!! --------- !!!',"\n";
$avail_width = int( $min_width) + 1;
}
my $span = 0;
# Calculate how much can be added to every column to fit the available width
$span = ($avail_width - $min_width) / scalar( @$col_props);
for(my $j = 0; $j < scalar(@$col_props); $j++ )
{
$calc_widths->[$j] = $col_props->[$j]->{min_w} + $span;
}
return ($calc_widths,$avail_width);
}
1;
__END__
=pod
=head1 NAME
PDF::Table - A utility class for building table layouts in a PDF::API2 object.
=head1 SYNOPSIS
use PDF::API2;
use PDF::Table;
my $pdftable = new PDF::Table;
my $pdf = new PDF::API2(-file => "table_of_lorem.pdf");
my $page = $pdf->page;
# some data to layout
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
$pdftable->table(
# required params
$pdf,
$page,
$some_data,
x => $left_edge_of_table,
w => 495,
start_y => 750,
next_y => 700,
start_h => 300,
next_h => 500,
# some optional params
padding => 5,
padding_right => 10,
background_color_odd => "gray",
background_color_even => "lightblue", #cell background color for even rows
);
# do other stuff with $pdf
$pdf->saveas();
...
=head1 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::API2 module from CPAN.
It can be used to display text data in a table layout within the PDF.
The text data must be in a 2d array (such as returned by a DBI statement handle fetchall_arrayref() call).
The 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, and 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.
=head1 METHODS
=head2 new
=over
Returns an instance of the class. There are no parameters.
... Dieser Diff wurde abgeschnitten, weil er die maximale Anzahl anzuzeigender Zeilen überschreitet.

Auch abrufbar als: Unified diff