Bug 14362: PEGI15 Circulation/AgeRestrictionMarkers test fails
[koha.git] / patroncards / create-pdf.pl
1 #!/usr/bin/perl
2 #
3 # Copyright 2009 Foundations Bible College.
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use strict;
21 use warnings;
22
23 use CGI qw ( -utf8 );
24 use C4::Auth;
25 use Graphics::Magick;
26 use XML::Simple;
27 use POSIX qw(ceil);
28 use autouse 'Data::Dumper' => qw(Dumper);
29
30 use C4::Debug;
31 use C4::Context;
32 use autouse 'C4::Members' => qw(GetMember);
33 use C4::Creators;
34 use C4::Patroncards;
35 use Koha::List::Patron;
36 use Koha::Patron::Images;
37
38 my $cgi = new CGI;
39
40 my ( $template, $loggedinuser, $cookie ) = get_template_and_user({
41                                                                      template_name   => "labels/label-home.tt",
42                                                                      query           => $cgi,
43                                                                      type            => "intranet",
44                                                                      authnotrequired => 0,
45                                                                      flagsrequired   => { tools => 'label_creator' },
46                                                                      debug           => 1,
47                                                                      });
48
49
50 my $batch_id    = $cgi->param('batch_id') if $cgi->param('batch_id');
51 my $template_id = $cgi->param('template_id') || undef;
52 my $layout_id   = $cgi->param('layout_id') || undef;
53 my $start_card = $cgi->param('start_card') || 1;
54 my @label_ids   = $cgi->multi_param('label_id') if $cgi->param('label_id');
55 my @borrower_numbers  = $cgi->multi_param('borrower_number') if $cgi->param('borrower_number');
56 my $patronlist_id = $cgi->param('patronlist_id');
57
58 my $items = undef; # items = cards
59 my $new_page = 0;
60
61 my $pdf_file = (@label_ids || @borrower_numbers ? "card_single_" . scalar(@label_ids || @borrower_numbers) : "card_batch_$batch_id");
62 print $cgi->header( -type       => 'application/pdf',
63                     -encoding   => 'utf-8',
64                     -attachment => "$pdf_file.pdf",
65                   );
66
67 my $pdf = C4::Creators::PDF->new(InitVars => 0);
68 my $batch = C4::Patroncards::Batch->retrieve(batch_id => $batch_id);
69 my $pc_template = C4::Patroncards::Template->retrieve(template_id => $template_id, profile_id => 1);
70 my $layout = C4::Patroncards::Layout->retrieve(layout_id => $layout_id);
71
72 $| = 1;
73
74 # set the paper size
75 my $lower_left_x  = 0;
76 my $lower_left_y  = 0;
77 my $upper_right_x = $pc_template->get_attr('page_width');
78 my $upper_right_y = $pc_template->get_attr('page_height');
79
80 $pdf->Compress(1); # comment this out to debug pdf files, but be sure to uncomment it in production or you may be very sorry...
81 $pdf->Mbox($lower_left_x, $lower_left_y, $upper_right_x, $upper_right_y);
82
83 my ($llx, $lly) = 0,0;
84 (undef, undef, $llx, $lly) = $pc_template->get_label_position($start_card);
85
86 if (@label_ids) {
87     my $batch_items = $batch->get_attr('items');
88     grep {
89         my $label_id = $_;
90         push(@{$items}, grep{$_->{'label_id'} == $label_id;} @{$batch_items});
91     } @label_ids;
92 }
93 elsif (@borrower_numbers) {
94     grep {
95         push(@{$items}, {borrower_number => $_});
96     } @borrower_numbers;
97 }
98 elsif ( $patronlist_id  ) {
99     my ($list) = GetPatronLists( { patron_list_id => $patronlist_id } );
100     my @borrowerlist = $list->patron_list_patrons()->search_related('borrowernumber')
101     ->get_column('borrowernumber')->all();
102     grep {
103         push(@{$items}, {borrower_number => $_});
104     } @borrowerlist;
105 }
106 else {
107     $items = $batch->get_attr('items');
108 }
109
110 my $layout_xml = XMLin($layout->get_attr('layout_xml'), ForceArray => 1);
111
112 if ($layout_xml->{'page_side'} eq 'B') { # rearrange items on backside of page to swap columns
113     my $even = 1;
114     my $odd = 0;
115     my @swap_array = ();
116     while ($even <= (scalar(@{$items})+1)) {
117         push (@swap_array, @{$items}[$even]);
118         push (@swap_array, @{$items}[$odd]);
119         $even += 2;
120         $odd += 2;
121     }
122     @{$items} = @swap_array;
123 }
124
125 CARD_ITEMS:
126 foreach my $item (@{$items}) {
127     if ($item) {
128         my $borrower_number = $item->{'borrower_number'};
129         my $card_number = GetMember(borrowernumber => $borrower_number)->{'cardnumber'};
130
131 #       Set barcode data
132         $layout_xml->{'barcode'}->[0]->{'data'} = $card_number if $layout_xml->{'barcode'};
133
134 #       Create a new patroncard object
135         my $patron_card = C4::Patroncards::Patroncard->new(
136                 batch_id                => 1,
137                 borrower_number         => $borrower_number,
138                 llx                     => $llx, # lower left corner of the card
139                 lly                     => $lly,
140                 height                  => $pc_template->get_attr('label_height'), # of the card
141                 width                   => $pc_template->get_attr('label_width'),
142                 layout                  => $layout_xml,
143                 text_wrap_cols          => 30, #FIXME: hardcoded,
144         );
145
146         $patron_card->draw_guide_box($pdf) if $layout_xml->{'guide_box'};
147         $patron_card->draw_barcode($pdf) if $layout_xml->{'barcode'};
148
149 #       Do image foo and place binary image data into layout hash
150         my $image_data = {};
151         my $error = undef;
152         my $images = $layout_xml->{'images'};
153         PROCESS_IMAGES:
154         foreach (keys %{$images}) {
155             if (grep{m/source/} keys(%{$images->{$_}->{'data_source'}->[0]})) {
156                 if ($images->{$_}->{'data_source'}->[0]->{'image_source'} eq 'none') {
157                     next PROCESS_IMAGES;
158                 }
159                 elsif ($images->{$_}->{'data_source'}->[0]->{'image_source'} eq 'patronimages') {
160                     my $patron_image = Koha::Patron::Images->find($borrower_number);
161                     warn sprintf('No image exists for borrower number %s.', $borrower_number) unless $patron_image;
162                     next PROCESS_IMAGES unless $patron_image;
163                 }
164                 elsif ($images->{$_}->{'data_source'}->[0]->{'image_source'} eq 'creator_images') {
165                     my $dbh = C4::Context->dbh();
166                     $dbh->{LongReadLen} = 1000000;      # allows us to read approx 1MB
167                     $image_data = $dbh->selectrow_hashref("SELECT imagefile FROM creator_images WHERE image_name = \'$images->{$_}->{'data_source'}->[0]->{'image_name'}\'");
168                     warn sprintf('Database returned the following error: %s.', $error) if $error;
169                     warn sprintf('Image does not exists in db table %s.', $images->{$_}->{'data_source'}->[0]->{'image_name'}) if !$image_data;
170                     next PROCESS_IMAGES if !$image_data;
171                 }
172                 else {
173                     warn sprintf('No retrieval method for image source %s.', $images->{$_}->{'data_source'}->[0]->{'image_source'});
174                     next PROCESS_IMAGES;
175                 }
176             }
177             else {
178                 warn sprintf("Unrecognized image data source: %s", $images->{$_}->{'data_source'});
179                 next PROCESS_IMAGES;
180             }
181
182         my $binary_data = $image_data->{'imagefile'};
183
184 #       invoke the display image object...
185         my $image = Graphics::Magick->new;
186         $image->BlobToImage($binary_data);
187
188 #       invoke the alt (aka print) image object...
189         my $alt_image = Graphics::Magick->new;
190         $alt_image->BlobToImage($binary_data);
191         $alt_image->Set(magick => 'jpg', quality => 100);
192
193         #To avoid pixelation have the image 5 times bigger and
194         #scale it down in PDF itself
195         my $oversize_factor = 8;
196         my $pdf_scale_factor = 1 / $oversize_factor;
197
198         my $alt_width = ceil($image->Get('width')); # the rounding up is important: Adobe reader does not handle long decimal numbers well
199         my $alt_height = ceil($image->Get('height'));
200         my $ratio = $alt_width / $alt_height;
201         my $display_height = ceil($images->{$_}->{'Dx'});
202         my $display_width = ceil($ratio * $display_height);
203
204
205         $image->Resize(width => $oversize_factor * $display_width, height => $oversize_factor * $display_height);
206         $image->Set(magick => 'jpg', quality => 100);
207
208 #       Write param for downsizing in pdf
209             $images->{$_}->{'scale'} = $pdf_scale_factor;
210
211 #       Write params for alt image...
212             $images->{$_}->{'alt'}->{'Sx'} = $oversize_factor * $alt_width;
213             $images->{$_}->{'alt'}->{'Sy'} = $oversize_factor * $alt_height;
214             $images->{$_}->{'alt'}->{'data'} = $alt_image->ImageToBlob();
215
216 #       Write params for display image...
217             $images->{$_}->{'Sx'} = $oversize_factor * $display_width;
218             $images->{$_}->{'Sy'} = $oversize_factor * $display_height;
219             $images->{$_}->{'data'} = $image->ImageToBlob();
220
221             my $err = $patron_card->draw_image($pdf);
222             warn sprintf ("Error encountered while attempting to draw image %s, %s", $_, $err) if $err;
223         }
224         $patron_card->draw_text($pdf);
225     }
226     ($llx, $lly, $new_page) = $pc_template->get_next_label_pos();
227     $pdf->Page() if $new_page;
228 }
229
230 $pdf->End();
231
232 # FIXME: Possibly do a redirect here if there were error encountered during PDF creation.
233
234 1;