Bug 12461 [QA Followup]
[koha.git] / patroncards / create-pdf.pl
blobe660af6179cba1e703e636017f7796bcd89b4835
1 #!/usr/bin/perl
3 # Copyright 2009 Foundations Bible College.
5 # This file is part of Koha.
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.
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.
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>.
20 use strict;
21 use warnings;
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);
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;
38 my $cgi = new CGI;
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 my $batch_id = $cgi->param('batch_id') if $cgi->param('batch_id');
49 my $template_id = $cgi->param('template_id') || undef;
50 my $layout_id = $cgi->param('layout_id') || undef;
51 my $start_card = $cgi->param('start_card') || 1;
52 my @label_ids = $cgi->multi_param('label_id') if $cgi->param('label_id');
53 my @borrower_numbers = $cgi->multi_param('borrower_number') if $cgi->param('borrower_number');
54 my $patronlist_id = $cgi->param('patronlist_id');
56 my $items = undef; # items = cards
57 my $new_page = 0;
59 # Wrap pdf creation part into an eval, some vars need scope outside eval
60 my $pdf_ok;
61 my $pdf;
62 my $pdf_file;
63 my $cardscount = 0;
65 #Note fo bug 14138: Indenting follows in separate patch to ease review
66 eval {
67 $pdf_file = (@label_ids || @borrower_numbers ? "card_single_" . scalar(@label_ids || @borrower_numbers) : "card_batch_$batch_id");
69 $pdf = C4::Creators::PDF->new(InitVars => 0);
70 my $batch = C4::Patroncards::Batch->retrieve(batch_id => $batch_id);
71 my $pc_template = C4::Patroncards::Template->retrieve(template_id => $template_id, profile_id => 1);
72 my $layout = C4::Patroncards::Layout->retrieve(layout_id => $layout_id);
74 $| = 1;
76 # set the paper size
77 my $lower_left_x = 0;
78 my $lower_left_y = 0;
79 my $upper_right_x = $pc_template->get_attr('page_width');
80 my $upper_right_y = $pc_template->get_attr('page_height');
82 $pdf->Compress(1); # comment this out to debug pdf files, but be sure to uncomment it in production or you may be very sorry...
83 $pdf->Mbox($lower_left_x, $lower_left_y, $upper_right_x, $upper_right_y);
85 my ($llx, $lly) = 0,0;
86 (undef, undef, $llx, $lly) = $pc_template->get_label_position($start_card);
88 if (@label_ids) {
89 my $batch_items = $batch->get_attr('items');
90 grep {
91 my $label_id = $_;
92 push(@{$items}, grep{$_->{'label_id'} == $label_id;} @{$batch_items});
93 } @label_ids;
95 elsif (@borrower_numbers) {
96 grep {
97 push(@{$items}, {borrower_number => $_});
98 } @borrower_numbers;
100 elsif ( $patronlist_id ) {
101 my ($list) = GetPatronLists( { patron_list_id => $patronlist_id } );
102 my @borrowerlist = $list->patron_list_patrons()->search_related('borrowernumber')
103 ->get_column('borrowernumber')->all();
104 grep {
105 push(@{$items}, {borrower_number => $_});
106 } @borrowerlist;
108 else {
109 $items = $batch->get_attr('items');
112 my $layout_xml = XMLin($layout->get_attr('layout_xml'), ForceArray => 1);
114 if ($layout_xml->{'page_side'} eq 'B') { # rearrange items on backside of page to swap columns
115 my $even = 1;
116 my $odd = 0;
117 my @swap_array = ();
118 while ($even <= (scalar(@{$items})+1)) {
119 push (@swap_array, @{$items}[$even]);
120 push (@swap_array, @{$items}[$odd]);
121 $even += 2;
122 $odd += 2;
124 @{$items} = @swap_array;
127 CARD_ITEMS:
128 foreach my $item (@{$items}) {
129 if ($item) {
130 $cardscount ++;
131 my $borrower_number = $item->{'borrower_number'};
132 my $card_number = GetMember(borrowernumber => $borrower_number)->{'cardnumber'};
134 # Set barcode data
135 $layout_xml->{'barcode'}->[0]->{'data'} = $card_number if $layout_xml->{'barcode'};
137 # Create a new patroncard object
138 my $patron_card = C4::Patroncards::Patroncard->new(
139 batch_id => 1,
140 borrower_number => $borrower_number,
141 llx => $llx, # lower left corner of the card
142 lly => $lly,
143 height => $pc_template->get_attr('label_height'), # of the card
144 width => $pc_template->get_attr('label_width'),
145 layout => $layout_xml,
146 text_wrap_cols => 30, #FIXME: hardcoded,
149 $patron_card->draw_guide_box($pdf) if $layout_xml->{'guide_box'};
150 $patron_card->draw_barcode($pdf) if $layout_xml->{'barcode'};
152 # Do image foo and place binary image data into layout hash
153 my $image_data = {};
154 my $error = undef;
155 my $images = $layout_xml->{'images'};
156 PROCESS_IMAGES:
157 foreach (keys %{$images}) {
158 if (grep{m/source/} keys(%{$images->{$_}->{'data_source'}->[0]})) {
159 if ($images->{$_}->{'data_source'}->[0]->{'image_source'} eq 'none') {
160 next PROCESS_IMAGES;
162 elsif ($images->{$_}->{'data_source'}->[0]->{'image_source'} eq 'patronimages') {
163 my $patron_image = Koha::Patron::Images->find($borrower_number);
164 if ($patron_image) {
165 $image_data->{'imagefile'} = $patron_image->imagefile;
167 else {
168 warn sprintf('No image exists for borrower number %s.', $borrower_number);
170 next PROCESS_IMAGES unless $patron_image;
172 elsif ($images->{$_}->{'data_source'}->[0]->{'image_source'} eq 'creator_images') {
173 my $dbh = C4::Context->dbh();
174 $dbh->{LongReadLen} = 1000000; # allows us to read approx 1MB
175 $image_data = $dbh->selectrow_hashref("SELECT imagefile FROM creator_images WHERE image_name = \'$images->{$_}->{'data_source'}->[0]->{'image_name'}\'");
176 warn sprintf('Database returned the following error: %s.', $error) if $error;
177 warn sprintf('Image does not exists in db table %s.', $images->{$_}->{'data_source'}->[0]->{'image_name'}) if !$image_data;
178 next PROCESS_IMAGES if !$image_data;
180 else {
181 warn sprintf('No retrieval method for image source %s.', $images->{$_}->{'data_source'}->[0]->{'image_source'});
182 next PROCESS_IMAGES;
185 else {
186 warn sprintf("Unrecognized image data source: %s", $images->{$_}->{'data_source'});
187 next PROCESS_IMAGES;
190 my $binary_data = $image_data->{'imagefile'};
192 # invoke the display image object...
193 my $image = Graphics::Magick->new;
194 $image->BlobToImage($binary_data);
196 # invoke the alt (aka print) image object...
197 my $alt_image = Graphics::Magick->new;
198 $alt_image->BlobToImage($binary_data);
199 $alt_image->Set(magick => 'jpg', quality => 100);
201 #To avoid pixelation have the image 5 times bigger and
202 #scale it down in PDF itself
203 my $oversize_factor = 8;
204 my $pdf_scale_factor = 1 / $oversize_factor;
206 my $alt_width = ceil($image->Get('width')); # the rounding up is important: Adobe reader does not handle long decimal numbers well
207 my $alt_height = ceil($image->Get('height'));
208 my $ratio = $alt_width / $alt_height;
209 my $display_height = ceil($images->{$_}->{'Dx'});
210 my $display_width = ceil($ratio * $display_height);
213 $image->Resize(width => $oversize_factor * $display_width, height => $oversize_factor * $display_height);
214 $image->Set(magick => 'jpg', quality => 100);
216 # Write param for downsizing in pdf
217 $images->{$_}->{'scale'} = $pdf_scale_factor;
219 # Write params for alt image...
220 $images->{$_}->{'alt'}->{'Sx'} = $oversize_factor * $alt_width;
221 $images->{$_}->{'alt'}->{'Sy'} = $oversize_factor * $alt_height;
222 $images->{$_}->{'alt'}->{'data'} = $alt_image->ImageToBlob();
224 # Write params for display image...
225 $images->{$_}->{'Sx'} = $oversize_factor * $display_width;
226 $images->{$_}->{'Sy'} = $oversize_factor * $display_height;
227 $images->{$_}->{'data'} = $image->ImageToBlob();
229 my $err = $patron_card->draw_image($pdf);
230 warn sprintf ("Error encountered while attempting to draw image %s, %s", $_, $err) if $err;
232 $patron_card->draw_text($pdf);
234 ($llx, $lly, $new_page) = $pc_template->get_next_label_pos();
235 $pdf->Page() if $new_page;
237 # No errors occurred within eval, we can issue the pdf
238 $pdf_ok = 1 if ($cardscount > 0);
239 }; # end of eval block
241 if ($pdf_ok) {
242 #issue the pdf
243 print $cgi->header( -type => 'application/pdf',
244 -encoding => 'utf-8',
245 -attachment => "$pdf_file.pdf",
247 $pdf->End();
249 else {
250 # warn user that pdf is not created
251 my $errparams = '&pdferr=1';
252 $errparams .= "&errba=$batch_id" if $batch_id;
253 $errparams .= "&errpl=$patronlist_id" if $patronlist_id;
254 $errparams = $errparams.'&errpt='.$cgi->param('borrower_number') if $cgi->param('borrower_number');
255 $errparams .= "&errlo=$layout_id" if $layout_id;
256 $errparams .= "&errtpl=$template_id" if $template_id;
257 $errparams .= "&errnocards=1" if !$cardscount;
259 print $cgi->redirect("/cgi-bin/koha/patroncards/manage.pl?card_element=batch$errparams");