9f76c0095fef4c51e7f1dfd3c8292b0435136655
[kivitendo-erp.git] / SL / DB / Printer.pm
1 package SL::DB::Printer;
2
3 use strict;
4
5 use Carp;
6
7 use SL::DB::MetaSetup::Printer;
8 use SL::DB::Manager::Printer;
9 use SL::DB::Helper::Util;
10
11 __PACKAGE__->meta->initialize;
12
13 sub description {
14   goto &printer_description;
15 }
16
17 sub validate {
18   my ($self) = @_;
19
20   my @errors;
21   push @errors, $::locale->text('The description is missing.')    if !$self->printer_description;
22   push @errors, $::locale->text('The command is missing.')        if !$self->printer_command;
23   push @errors, $::locale->text('The description is not unique.') if !SL::DB::Helper::Util::is_unique($self, 'printer_description');
24
25   return @errors;
26 }
27
28 sub print_document {
29   my ($self, %params) = @_;
30
31   croak "Need either a 'content' or a 'file_name' parameter" if !defined($params{content}) && !$params{file_name};
32
33   my $copies  = $params{copies} || 1;
34   my $command = SL::Template::create(type => 'ShellCommand', form => Form->new(''))->parse($self->printer_command);
35   my $content = $params{content} // scalar(File::Slurp::read_file($params{file_name}));
36
37   for (1..$copies) {
38     open my $out, '|-', $command or die $!;
39     binmode $out;
40     print $out $content;
41     close $out;
42   }
43 }
44
45 1;
46 __END__
47
48 =pod
49
50 =encoding utf8
51
52 =head1 NAME
53
54 SL::DB::Printer - Rose model for database table printers
55
56 =head1 SYNOPSIS
57
58   my $printer = SL::DB::Printer->new(id => 4711)->load;
59   $printer->print_document(
60     copies    => 2,
61     file_name => '/path/to/file.pdf',
62   );
63
64 =head1 FUNCTIONS
65
66 =over 4
67
68 =item C<print_document %params>
69
70 Prints a document by spawning the external command stored in
71 C<$self-E<gt>printer_command> and sending content to it.
72
73 The caller must provide either the content to send to the printer
74 (parameter C<content>) or a name to a file whose content is sent
75 verbatim (parameter C<file_name>).
76
77 An optional parameter C<copies> can be given to specify the number of
78 copies to print. This is done by invoking the print command multiple
79 times. The number of copies defaults to 1.
80
81 =back
82
83 =head1 BUGS
84
85 Nothing here yet.
86
87 =head1 AUTHOR
88
89 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
90
91 =cut