Bug 14131 - Patroncard: Add possibility to print from patron lists
[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(GetPatronImage GetMember);
33 use C4::Creators;
34 use C4::Patroncards;
35 use Koha::List::Patron;
36
37 my $cgi = new CGI;
38
39 my ( $template, $loggedinuser, $cookie ) = get_template_and_user({
40                                                                      template_name   => "labels/label-home.tt",
41                                                                      query           => $cgi,
42                                                                      type            => "intranet",
43                                                                      authnotrequired => 0,
44                                                                      flagsrequired   => { tools => 'label_creator' },
45                                                                      debug           => 1,
46                                                                      });
47
48
49 my $batch_id    = $cgi->param('batch_id') if $cgi->param('batch_id');
50 my $template_id = $cgi->param('template_id') || undef;
51 my $layout_id   = $cgi->param('layout_id') || undef;
52 my $start_card = $cgi->param('start_card') || 1;
53 my @label_ids   = $cgi->param('label_id') if $cgi->param('label_id');
54 my @borrower_numbers  = $cgi->param('borrower_number') if $cgi->param('borrower_number');
55 my $patronlist_id = $cgi->param('patronlist_id');
56
57 my $items = undef; # items = cards
58 my $new_page = 0;
59
60 my $pdf_file = (@label_ids || @borrower_numbers ? "card_single_" . scalar(@label_ids || @borrower_numbers) : "card_batch_$batch_id");
61 print $cgi->header( -type       => 'application/pdf',
62                     -encoding   => 'utf-8',
63                     -attachment => "$pdf_file.pdf",
64                   );
65
66 my $pdf = C4::Creators::PDF->new(InitVars => 0);
67 my $batch = C4::Patroncards::Batch->retrieve(batch_id => $batch_id);
68 my $pc_template = C4::Patroncards::Template->retrieve(template_id => $template_id, profile_id => 1);
69 my $layout = C4::Patroncards::Layout->retrieve(layout_id => $layout_id);
70
71 $| = 1;
72
73 # set the paper size
74 my $lower_left_x  = 0;
75 my $lower_left_y  = 0;
76 my $upper_right_x = $pc_template->get_attr('page_width');
77 my $upper_right_y = $pc_template->get_attr('page_height');
78
79 $pdf->Compress(1); # comment this out to debug pdf files, but be sure to uncomment it in production or you may be very sorry...
80 $pdf->Mbox($lower_left_x, $lower_left_y, $upper_right_x, $upper_right_y);
81
82 my ($llx, $lly) = 0,0;
83 (undef, undef, $llx, $lly) = $pc_template->get_label_position($start_card);
84
85 if (@label_ids) {
86     my $batch_items = $batch->get_attr('items');
87     grep {
88         my $label_id = $_;
89         push(@{$items}, grep{$_->{'label_id'} == $label_id;} @{$batch_items});
90     } @label_ids;
91 }
92 elsif (@borrower_numbers) {
93     grep {
94         push(@{$items}, {borrower_number => $_});
95     } @borrower_numbers;
96 }
97 elsif ( $patronlist_id  ) {
98     my ($list) = GetPatronLists( { patron_list_id => $patronlist_id } );
99     my @borrowerlist = $list->patron_list_patrons()->search_related('borrowernumber')
100     ->get_column('borrowernumber')->all();
101     grep {
102         push(@{$items}, {borrower_number => $_});
103     } @borrowerlist;
104 }
105 else {
106     $items = $batch->get_attr('items');
107 }
108
109 my $layout_xml = XMLin($layout->get_attr('layout_xml'), ForceArray => 1);
110
111 if ($layout_xml->{'page_side'} eq 'B') { # rearrange items on backside of page to swap columns
112     my $even = 1;
113     my $odd = 0;
114     my @swap_array = ();
115     while ($even <= (scalar(@{$items})+1)) {
116         push (@swap_array, @{$items}[$even]);
117         push (@swap_array, @{$items}[$odd]);
118         $even += 2;
119         $odd += 2;
120     }
121     @{$items} = @swap_array;
122 }
123
124 CARD_ITEMS:
125 foreach my $item (@{$items}) {
126     if ($item) {
127         my $borrower_number = $item->{'borrower_number'};
128         my $card_number = GetMember(borrowernumber => $borrower_number)->{'cardnumber'};
129
130 #       Set barcode data
131         $layout_xml->{'barcode'}->[0]->{'data'} = $card_number if $layout_xml->{'barcode'};
132
133 #       Create a new patroncard object
134         my $patron_card = C4::Patroncards::Patroncard->new(
135                 batch_id                => 1,
136                 borrower_number         => $borrower_number,
137                 llx                     => $llx, # lower left corner of the card
138                 lly                     => $lly,
139                 height                  => $pc_template->get_attr('label_height'), # of the card
140                 width                   => $pc_template->get_attr('label_width'),
141                 layout                  => $layout_xml,
142                 text_wrap_cols          => 30, #FIXME: hardcoded,
143         );
144
145         $patron_card->draw_guide_box($pdf) if $layout_xml->{'guide_box'};
146         $patron_card->draw_barcode($pdf) if $layout_xml->{'barcode'};
147
148 #       Do image foo and place binary image data into layout hash
149         my $image_data = {};
150         my $error = undef;
151         my $images = $layout_xml->{'images'};
152         PROCESS_IMAGES:
153         foreach (keys %{$images}) {
154             if (grep{m/source/} keys(%{$images->{$_}->{'data_source'}->[0]})) {
155                 if ($images->{$_}->{'data_source'}->[0]->{'image_source'} eq 'none') {
156                     next PROCESS_IMAGES;
157                 }
158                 elsif ($images->{$_}->{'data_source'}->[0]->{'image_source'} eq 'patronimages') {
159                     ($image_data, $error) = GetPatronImage($borrower_number);
160                     warn sprintf('No image exists for borrower number %s.', $borrower_number) if !$image_data;
161                     next PROCESS_IMAGES if !$image_data;
162                 }
163                 elsif ($images->{$_}->{'data_source'}->[0]->{'image_source'} eq 'creator_images') {
164                     my $dbh = C4::Context->dbh();
165                     $dbh->{LongReadLen} = 1000000;      # allows us to read approx 1MB
166                     $image_data = $dbh->selectrow_hashref("SELECT imagefile FROM creator_images WHERE image_name = \'$images->{$_}->{'data_source'}->[0]->{'image_name'}\'");
167                     warn sprintf('Database returned the following error: %s.', $error) if $error;
168                     warn sprintf('Image does not exists in db table %s.', $images->{$_}->{'data_source'}->[0]->{'image_name'}) if !$image_data;
169                     next PROCESS_IMAGES if !$image_data;
170                 }
171                 else {
172                     warn sprintf('No retrieval method for image source %s.', $images->{$_}->{'data_source'}->[0]->{'image_source'});
173                     next PROCESS_IMAGES;
174                 }
175             }
176             else {
177                 warn sprintf("Unrecognized image data source: %s", $images->{$_}->{'data_source'});
178                 next PROCESS_IMAGES;
179             }
180
181         my $binary_data = $image_data->{'imagefile'};
182
183 #       invoke the display image object...
184         my $image = Graphics::Magick->new;
185         $image->BlobToImage($binary_data);
186
187 #       invoke the alt (aka print) image object...
188         my $alt_image = Graphics::Magick->new;
189         $alt_image->BlobToImage($binary_data);
190         $alt_image->Set(magick => 'jpg', quality => 100);
191
192         #To avoid pixelation have the image 5 times bigger and
193         #scale it down in PDF itself
194         my $oversize_factor = 8;
195         my $pdf_scale_factor = 1 / $oversize_factor;
196
197         my $alt_width = ceil($image->Get('width')); # the rounding up is important: Adobe reader does not handle long decimal numbers well
198         my $alt_height = ceil($image->Get('height'));
199         my $ratio = $alt_width / $alt_height;
200         my $display_height = ceil($images->{$_}->{'Dx'});
201         my $display_width = ceil($ratio * $display_height);
202
203
204         $image->Resize(width => $oversize_factor * $display_width, height => $oversize_factor * $display_height);
205         $image->Set(magick => 'jpg', quality => 100);
206
207 #       Write param for downsizing in pdf
208             $images->{$_}->{'scale'} = $pdf_scale_factor;
209
210 #       Write params for alt image...
211             $images->{$_}->{'alt'}->{'Sx'} = $oversize_factor * $alt_width;
212             $images->{$_}->{'alt'}->{'Sy'} = $oversize_factor * $alt_height;
213             $images->{$_}->{'alt'}->{'data'} = $alt_image->ImageToBlob();
214
215 #       Write params for display image...
216             $images->{$_}->{'Sx'} = $oversize_factor * $display_width;
217             $images->{$_}->{'Sy'} = $oversize_factor * $display_height;
218             $images->{$_}->{'data'} = $image->ImageToBlob();
219
220             my $err = $patron_card->draw_image($pdf);
221             warn sprintf ("Error encountered while attempting to draw image %s, %s", $_, $err) if $err;
222         }
223         $patron_card->draw_text($pdf);
224     }
225     ($llx, $lly, $new_page) = $pc_template->get_next_label_pos();
226     $pdf->Page() if $new_page;
227 }
228
229 $pdf->End();
230
231 # FIXME: Possibly do a redirect here if there were error encountered during PDF creation.
232
233 1;