92349d4d6c2ad4d075e070c81484dbb8943297ec
[kivitendo-erp.git] / SL / Helper / CreatePDF.pm
1 package SL::Helper::CreatePDF;
2
3 use strict;
4
5 use Cwd;
6 use English qw(-no_match_vars);
7 use File::Slurp ();
8 use File::Temp ();
9 use String::ShellQuote ();
10
11 use SL::Form;
12 use SL::Common;
13 use SL::MoreCommon;
14 use SL::Template;
15 use SL::Template::LaTeX;
16
17 use Exporter 'import';
18 our @EXPORT_OK = qw(create_pdf merge_pdfs);
19 our %EXPORT_TAGS = (
20   all => \@EXPORT_OK,
21 );
22
23 sub create_pdf {
24   my ($class, %params) = @_;
25
26   my $userspath       = $::lx_office_conf{paths}->{userspath};
27   my $form            = Form->new('');
28   $form->{format}     = 'pdf';
29   $form->{cwd}        = getcwd();
30   $form->{templates}  = $::instance_conf->get_templates;
31   $form->{IN}         = $params{template} . '.tex';
32   $form->{tmpdir}     = $form->{cwd} . '/' . $userspath;
33
34   my $vars            = $params{variables} || {};
35   $form->{$_}         = $vars->{$_} for keys %{ $vars };
36
37   my $temp_fh;
38   ($temp_fh, $form->{tmpfile}) = File::Temp::tempfile(
39     'kivitendo-printXXXXXX',
40     SUFFIX => '.tex',
41     DIR    => $userspath,
42     UNLINK => ($::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files})? 0 : 1,
43   );
44
45   my $parser = SL::Template::LaTeX->new(
46     $form->{IN},
47     $form,
48     \%::myconfig,
49     $userspath,
50   );
51
52   my $result = $parser->parse($temp_fh);
53
54   close $temp_fh;
55   chdir $form->{cwd};
56
57   if (!$result) {
58     $form->cleanup;
59     die $parser->get_error;
60   }
61
62   if (($params{return} || 'content') eq 'file_name') {
63     my $new_name = $userspath . '/keep-' . $form->{tmpfile};
64     rename $userspath . '/' . $form->{tmpfile}, $new_name;
65
66     $form->cleanup;
67
68     return $new_name;
69   }
70
71   my $pdf = File::Slurp::read_file($userspath . '/' . $form->{tmpfile});
72
73   $form->cleanup;
74
75   return $pdf;
76 }
77
78 sub merge_pdfs {
79   my ($class, %params) = @_;
80
81   return scalar(File::Slurp::read_file($params{file_names}->[0])) if scalar(@{ $params{file_names} }) < 2;
82
83   my ($temp_fh, $temp_name) = File::Temp::tempfile(
84     'kivitendo-printXXXXXX',
85     SUFFIX => '.pdf',
86     DIR    => $::lx_office_conf{paths}->{userspath},
87     UNLINK => ($::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files})? 0 : 1,
88   );
89   close $temp_fh;
90
91   my $input_names = join ' ', String::ShellQuote::shell_quote(@{ $params{file_names} });
92   my $exe         = $::lx_office_conf{applications}->{ghostscript} || 'gs';
93   my $output      = `$exe -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=${temp_name} ${input_names} 2>&1`;
94
95   die "Executing gs failed: $ERRNO" if !defined $output;
96   die $output                       if $? != 0;
97
98   return scalar File::Slurp::read_file($temp_name);
99 }
100
101 1;