Bug 18541 - Patron card creator: Add a grid to support layout design
[koha.git] / C4 / Patroncards / Patroncard.pm
1 package C4::Patroncards::Patroncard;
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 autouse 'Data::Dumper' => qw(Dumper);
24 use Text::Wrap qw(wrap);
25 #use Font::TTFMetrics;
26
27 use C4::Creators::Lib qw(get_font_types get_unit_values);
28 use C4::Creators::PDF qw(StrWidth);
29 use C4::Patroncards::Lib qw(unpack_UTF8 text_alignment leading box get_borrower_attributes);
30
31
32 sub new {
33     my ($invocant, %params) = @_;
34     my $type = ref($invocant) || $invocant;
35
36     my $units = get_unit_values();
37     my $unitvalue = 1;
38     my $unitdesc = '';
39     foreach my $un (@$units){
40         if ($un->{'type'} eq $params{'layout'}->{'units'}) {
41             $unitvalue = $un->{'value'};
42             $unitdesc = $un->{'desc'};
43         }
44     }
45
46     my $self = {
47         batch_id                => $params{'batch_id'},
48         #card_number             => $params{'card_number'},
49         borrower_number         => $params{'borrower_number'},
50         llx                     => $params{'llx'},
51         lly                     => $params{'lly'},
52         height                  => $params{'height'},
53         width                   => $params{'width'},
54         layout                  => $params{'layout'},
55         unitvalue               => $unitvalue,
56         unitdesc                => $unitdesc,
57         text_wrap_cols          => $params{'text_wrap_cols'},
58         barcode_height_scale    => $params{'layout'}->{'barcode'}[0]->{'height_scale'} || 0.01,
59         barcode_width_scale     => $params{'layout'}->{'barcode'}[0]->{'width_scale'} || 0.8,
60     };
61     bless ($self, $type);
62     return $self;
63 }
64
65 sub draw_barcode {
66     my ($self, $pdf) = @_;
67     # Default values for barcode scaling are set in constructor to work with pre-existing installations
68     my $barcode_height_scale = $self->{'barcode_height_scale'};
69     my $barcode_width_scale = $self->{'barcode_width_scale'};
70
71     _draw_barcode(      $self,
72                         llx     => $self->{'llx'} + $self->{'layout'}->{'barcode'}->[0]->{'llx'},
73                         lly     => $self->{'lly'} + $self->{'layout'}->{'barcode'}->[0]->{'lly'},
74                         width   => $self->{'width'} * $barcode_width_scale,
75                         y_scale_factor  => $self->{'height'} * $barcode_height_scale,
76                         barcode_type    => $self->{'layout'}->{'barcode'}->[0]->{'type'},
77                         barcode_data    => $self->{'layout'}->{'barcode'}->[0]->{'data'},
78                         text    => $self->{'layout'}->{'barcode'}->[0]->{'text_print'},
79     );
80 }
81
82 sub draw_guide_box {
83     my ($self, $pdf) = @_;
84     warn sprintf('No pdf object passed in.') and return -1 if !$pdf;
85
86     my $obj_stream = "q\n";                            # save the graphic state
87     $obj_stream .= "0.5 w\n";                          # border line width
88     $obj_stream .= "1.0 0.0 0.0  RG\n";                # border color red
89     $obj_stream .= "1.0 1.0 1.0  rg\n";                # fill color white
90     $obj_stream .= "$self->{'llx'} $self->{'lly'} $self->{'width'} $self->{'height'} re\n";    # a rectangle
91     $obj_stream .= "B\n";                              # fill (and a little more)
92     $obj_stream .= "Q\n";                              # restore the graphic state
93     $pdf->Add($obj_stream);
94 }
95
96 sub draw_guide_grid {
97     my ($self, $pdf) = @_;
98     warn sprintf('No pdf object passed in.') and return -1 if !$pdf;
99
100     # Set up the grid in user defined units.
101     # Each 5th and 10th line get separate values
102
103     my $obj_stream = "q\n";   # save the graphic state
104     my $x = $self->{'llx'};
105     my $y = $self->{'lly'};
106
107     my $cnt = 0;
108     for ( $x = $self->{'llx'}/$self->{'unitvalue'}; $x <= ($self->{'llx'} + $self->{'width'})/$self->{'unitvalue'}; $x++) {
109         my $xx = $x*$self->{'unitvalue'};
110         my $yy = $y + $self->{'height'};
111         if ( ($cnt % 10) && ! ($cnt % 5) ) {
112             $obj_stream .= "0.0 1.0 0.0  RG\n";
113             $obj_stream .= "0 w\n";
114         } elsif ( $cnt % 5 ) {
115             $obj_stream .= "0.0 1.0 1.0  RG\n";
116             $obj_stream .= "0 w\n";
117         } else {
118             $obj_stream .= "0.0 0.0 1.0  RG\n";
119             $obj_stream .= "0 w\n";
120         }
121         $cnt ++;
122
123         $obj_stream .= "$xx $y m\n";
124         $obj_stream .= "$xx $yy l\n";
125
126         $obj_stream .= "s\n";
127     }
128
129     $x = $self->{'llx'};
130     $y = $self->{'lly'};
131     $cnt = 0;
132     for ( $y = $self->{'lly'}/$self->{'unitvalue'}; $y <= ($self->{'lly'} + $self->{'height'})/$self->{'unitvalue'}; $y++) {
133
134         my $xx = $x + $self->{'width'};
135         my $yy = $y*$self->{'unitvalue'};
136
137         if ( ($cnt % 10) && ! ($cnt % 5) ) {
138             $obj_stream .= "0.0 1.0 0.0  RG\n";
139             $obj_stream .= "0 w\n";
140         } elsif ( $cnt % 5 ) {
141             $obj_stream .= "0.0 1.0 1.0  RG\n";
142             $obj_stream .= "0 w\n";
143         } else {
144             $obj_stream .= "0.0 0.0 1.0  RG\n";
145             $obj_stream .= "0 w\n";
146         }
147         $cnt ++;
148
149         $obj_stream .= "$x $yy m\n";
150         $obj_stream .= "$xx $yy l\n";
151         $obj_stream .= "s\n";
152     }
153
154     $obj_stream .= "Q\n"; # restore the graphic state
155     $pdf->Add($obj_stream);
156
157     # Add info about units
158     my $strbottom = "0/0 $self->{'unitdesc'}";
159     my $strtop = sprintf('%.2f', $self->{'width'}/$self->{'unitvalue'}) .'/'. sprintf('%.2f', $self->{'height'}/$self->{'unitvalue'});
160     my $font_size = 6;
161     $pdf->Font( 'Courier' );
162     $pdf->FontSize( $font_size );
163     my $strtop_len = $pdf->StrWidth($strtop) * 1.5;
164     $pdf->Text( $self->{'llx'} + 2, $self->{'lly'} + 2, $strbottom );
165     $pdf->Text( $self->{'llx'} + $self->{'width'} - $strtop_len , $self->{'lly'} + $self->{'height'} - $font_size , $strtop );
166 }
167
168
169 sub draw_text {
170     my ($self, $pdf, %params) = @_;
171     warn sprintf('No pdf object passed in.') and return -1 if !$pdf;
172     my @card_text = ();
173     return unless (ref($self->{'layout'}->{'text'}) eq 'ARRAY'); # just in case there is not text
174     my $text = [@{$self->{'layout'}->{'text'}}]; # make a copy of the arrayref *not* simply a pointer
175     while (scalar @$text) {
176         my $line = shift @$text;
177         my $parse_line = $line;
178         my @orig_line = split(/ /,$line);
179         if ($parse_line =~ m/<[A-Za-z0-9_]+>/) {     # test to see if the line has db fields embedded...
180             my @fields = ();
181             while ($parse_line =~ m/<([A-Za-z0-9_]+)>(.*$)/) {
182                 push (@fields, $1);
183                 $parse_line = $2;
184             }
185             my $borrower_attributes = get_borrower_attributes($self->{'borrower_number'},@fields);
186             grep{ # substitute data for db fields
187                 if ($_ =~ m/<([A-Za-z0-9_]+)>/) {
188                     my $field = $1;
189                     $_ =~ s/$_/$borrower_attributes->{$field}/;
190                 }
191             } @orig_line;
192             $line = join(' ',@orig_line);
193         }
194         my $text_attribs = shift @$text;
195         my $origin_llx = $self->{'llx'} + $text_attribs->{'llx'};
196         my $origin_lly = $self->{'lly'} + $text_attribs->{'lly'};
197         my $Tx = 0;     # final text llx
198         my $Ty = $origin_lly;   # final text lly
199         my $Tw = 0;     # final text word spacing. See http://www.adobe.com/devnet/pdf/pdf_reference.html ISO 32000-1
200 #FIXME: Move line wrapping code to its own sub if possible
201         my $trim = '';
202         my @lines = ();
203 #FIXME: Using embedded True Type fonts is a far superior way of handing things as well as being much more unicode friendly.
204 #       However this will take significant work using better than PDF::Reuse to do it. For the time being, I'm leaving
205 #       the basic code here commented out to preserve the basic method of accomplishing this. -chris_n
206 #
207 #        my $m = Font::TTFMetrics->new("/usr/share/fonts/truetype/msttcorefonts/Times_New_Roman_Bold.ttf");
208 #        my $units_per_em =  $m->get_units_per_em();
209 #        my $font_units_width = $m->string_width($line);
210 #        my $string_width = ($font_units_width * $text_attribs->{'font_size'}) / $units_per_em;
211         my $string_width = C4::Creators::PDF->StrWidth($line, $text_attribs->{'font'}, $text_attribs->{'font_size'});
212         if (($string_width + $text_attribs->{'llx'}) > $self->{'width'}) {
213             WRAP_LINES:
214             while (1) {
215 #                $line =~ m/^.*(\s\b.*\b\s*|\s&|\<\b.*\b\>)$/; # original regexp... can be removed after dev stage is over
216                 $line =~ m/^.*(\s.*\s*|\s&|\<.*\>)$/;
217                 warn sprintf('Line wrap failed. DEBUG INFO: Data: \'%s\'\n Method: C4::Patroncards->draw_text Additional Information: Line wrap regexp failed. (Please file in this information in a bug report at http://bugs.koha-community.org', $line) and last WRAP_LINES if !$1;
218                 $trim = $1 . $trim;
219                 $line =~ s/$1//;
220                 $string_width = C4::Creators::PDF->StrWidth($line, $text_attribs->{'font'}, $text_attribs->{'font_size'});
221 #                $font_units_width = $m->string_width($line);
222 #                $string_width = ($font_units_width * $text_attribs->{'font_size'}) / $units_per_em;
223                 if (($string_width + $text_attribs->{'llx'}) < $self->{'width'}) {
224                     ($Tx, $Tw) = text_alignment($origin_llx, $self->{'width'}, $text_attribs->{'llx'}, $string_width, $line, $text_attribs->{'text_alignment'});
225                     push @lines, {line=> $line, Tx => $Tx, Ty => $Ty, Tw => $Tw};
226                     $line = undef;
227                     last WRAP_LINES if $trim eq '';
228                     $Ty -= leading($text_attribs->{'font_size'});
229                     $line = $trim;
230                     $trim = '';
231                     $string_width = C4::Creators::PDF->StrWidth($line, $text_attribs->{'font'}, $text_attribs->{'font_size'});
232                     #$font_units_width = $m->string_width($line);
233                     #$string_width = ($font_units_width * $text_attribs->{'font_size'}) / $units_per_em;
234                     if (($string_width + $text_attribs->{'llx'}) < $self->{'width'}) {
235                         ($Tx, $Tw) = text_alignment($origin_llx, $self->{'width'}, $text_attribs->{'llx'}, $string_width, $line, $text_attribs->{'text_alignment'});
236                         $line =~ s/^\s+//g;     # strip naughty leading spaces
237                         push @lines, {line=> $line, Tx => $Tx, Ty => $Ty, Tw => $Tw};
238                         last WRAP_LINES;
239                     }
240                 }
241             }
242         }
243         else {
244             ($Tx, $Tw) = text_alignment($origin_llx, $self->{'width'}, $text_attribs->{'llx'}, $string_width, $line, $text_attribs->{'text_alignment'});
245             $line =~ s/^\s+//g;     # strip naughty leading spaces
246             push @lines, {line=> $line, Tx => $Tx, Ty => $Ty, Tw => $Tw};
247         }
248 # Draw boxes around text box areas
249 # FIXME: This needs to compensate for the point height of decenders. In its current form it is helpful but not really usable. The boxes are also not transparent atm.
250 #        If these things were fixed, it may be desirable to give the user control over whether or not to display these boxes for layout design.
251         if (0) {
252             my $box_height = 0;
253             my $box_lly = $origin_lly;
254             if (scalar(@lines) > 1) {
255                 $box_height += scalar(@lines) * ($text_attribs->{'font_size'} * 1.2);
256                 $box_lly -= ($text_attribs->{'font_size'} * 0.2);
257             }
258             else {
259                 $box_height += $text_attribs->{'font_size'};
260             }
261             box ($origin_llx, $box_lly, $self->{'width'} - $text_attribs->{'llx'}, $box_height, $pdf);
262         }
263         $pdf->Font($text_attribs->{'font'});
264         $pdf->FontSize($text_attribs->{'font_size'});
265         foreach my $line (@lines) {
266             $pdf->Text($line->{'Tx'}, $line->{'Ty'}, $line->{'line'});
267         }
268     }
269 }
270
271 sub draw_image {
272     my ($self, $pdf) = @_;
273     warn sprintf('No pdf object passed in.') and return -1 if !$pdf;
274     my $images = $self->{'layout'}->{'images'};
275     PROCESS_IMAGES:
276     foreach my $image (keys %$images) {
277         next PROCESS_IMAGES if $images->{$image}->{'data_source'}->[0]->{'image_source'} eq 'none';
278         my $Tx = $self->{'llx'} + $images->{$image}->{'Tx'};
279         my $Ty = $self->{'lly'} + $images->{$image}->{'Ty'};
280         warn sprintf('No image passed in.') and next if !$images->{$image}->{'data'};
281         my $intName = $pdf->AltJpeg($images->{$image}->{'data'},$images->{$image}->{'Sx'}, $images->{$image}->{'Sy'}, 1, $images->{$image}->{'alt'}->{'data'},$images->{$image}->{'alt'}->{'Sx'}, $images->{$image}->{'alt'}->{'Sy'}, 1);
282         my $obj_stream = "q\n";
283         $obj_stream .= "$images->{$image}->{'Sx'} $images->{$image}->{'Ox'} $images->{$image}->{'Oy'} $images->{$image}->{'Sy'} $Tx $Ty cm\n";       # see http://www.adobe.com/devnet/pdf/pdf_reference.html sec 8.3.3 of ISO 32000-1
284         $obj_stream .= "$images->{$image}->{'scale'} 0 0 $images->{$image}->{'scale'} 0 0 cm\n"; #scale to 20%
285         $obj_stream .= "/$intName Do\n";
286         $obj_stream .= "Q\n";
287         $pdf->Add($obj_stream);
288     }
289 }
290
291 sub _draw_barcode {   # this is cut-and-paste from Label.pm because there is no common place for it atm...
292     my $self = shift;
293     my %params = @_;
294     my $x_scale_factor = 1;
295     my $num_of_chars = length($params{'barcode_data'});
296     my $tot_bar_length = 0;
297     my $bar_length = 0;
298     my $guard_length = 10;
299     if ($params{'barcode_type'} =~ m/CODE39/) {
300         $bar_length = '17.5';
301         $tot_bar_length = ($bar_length * $num_of_chars) + ($guard_length * 2);  # not sure what all is going on here and on the next line; this is old (very) code
302         $x_scale_factor = ($params{'width'} / $tot_bar_length);
303         if ($params{'barcode_type'} eq 'CODE39MOD') {
304             my $c39 = CheckDigits('code_39');   # get modulo 43 checksum
305             $params{'barcode_data'} = $c39->complete($params{'barcode_data'});
306         }
307         elsif ($params{'barcode_type'} eq 'CODE39MOD10') {
308             my $c39_10 = CheckDigits('siret');   # get modulo 10 checksum
309             $params{'barcode_data'} = $c39_10->complete($params{'barcode_data'});
310         }
311         eval {
312             PDF::Reuse::Barcode::Code39(
313                 x                   => $params{'llx'},
314                 y                   => $params{'lly'},
315                 value               => "*$params{barcode_data}*",
316                 xSize               => $x_scale_factor,
317                 ySize               => $params{'y_scale_factor'},
318                 hide_asterisk       => 1,
319                 text                => $params{'text'},
320                 mode                => 'graphic',
321             );
322         };
323         if ($@) {
324             warn sprintf('Barcode generation failed for item %s with this error: %s', $self->{'item_number'}, $@);
325         }
326     }
327     elsif ($params{'barcode_type'} eq 'COOP2OF5') {
328         $bar_length = '9.43333333333333';
329         $tot_bar_length = ($bar_length * $num_of_chars) + ($guard_length * 2);
330         $x_scale_factor = ($params{'width'} / $tot_bar_length) * 0.9;
331         eval {
332             PDF::Reuse::Barcode::COOP2of5(
333                 x                   => $params{'llx'},
334                 y                   => $params{'lly'},
335                 value               => "*$params{barcode_data}*",
336                 xSize               => $x_scale_factor,
337                 ySize               => $params{'y_scale_factor'},
338                 mode                    => 'graphic',
339             );
340         };
341         if ($@) {
342             warn sprintf('Barcode generation failed for item %s with this error: %s', $self->{'item_number'}, $@);
343         }
344     }
345     elsif ( $params{'barcode_type'} eq 'INDUSTRIAL2OF5' ) {
346         $bar_length = '13.1333333333333';
347         $tot_bar_length = ($bar_length * $num_of_chars) + ($guard_length * 2);
348         $x_scale_factor = ($params{'width'} / $tot_bar_length) * 0.9;
349         eval {
350             PDF::Reuse::Barcode::Industrial2of5(
351                 x                   => $params{'llx'},
352                 y                   => $params{'lly'},
353                 value               => "*$params{barcode_data}*",
354                 xSize               => $x_scale_factor,
355                 ySize               => $params{'y_scale_factor'},
356                 mode                    => 'graphic',
357             );
358         };
359         if ($@) {
360             warn sprintf('Barcode generation failed for item %s with this error: %s', $self->{'item_number'}, $@);
361         }
362     }
363 }
364
365 1;
366 __END__
367
368 =head1 AUTHOR
369
370 Chris Nighswonger <cnighswonger AT foundations DOT edu>
371
372 =cut
373
374
375