1 package SL::Template::LaTeX;
3 use parent qw(SL::Template::Simple);
9 use English qw(-no_match_vars);
12 use HTML::Entities ();
13 use List::MoreUtils qw(any);
14 use Scalar::Util qw(blessed);
15 use Unicode::Normalize qw();
18 use SL::System::Process;
20 my %text_markup_replace = (
27 my ($self, $content, %params) = @_;
29 $content = $::locale->quote_special_chars('Template/LaTeX', $content);
31 # Allow some HTML markup to be converted into the output format's
32 # corresponding markup code, e.g. bold or italic.
33 foreach my $key (keys(%text_markup_replace)) {
34 my $new = $text_markup_replace{$key};
35 $content =~ s/\$\<\$${key}\$\>\$(.*?)\$<\$\/${key}\$>\$/\\${new}\{$1\}/gi;
38 $content =~ s/[\x00-\x1f]//g;
45 '<ul>' => "\\begin{itemize} ",
46 '</ul>' => "\\end{itemize} ",
47 '<ol>' => "\\begin{enumerate} ",
48 '</ol>' => "\\end{enumerate} ",
53 '<strong>' => "\\textbf{",
57 '<em>' => "\\textit{",
59 '<u>' => "\\underline{",
63 '<sub>' => "\\textsubscript{",
65 '<sup>' => "\\textsuperscript{",
67 '<br/>' => "\\newline ",
68 '<br>' => "\\newline ",
72 my ($to_replace) = @_;
74 my $vspace = '\vspace*{0.5cm}';
75 return $vspace x (length($to_replace) / length($html_replace{'<br>'}));
79 my ($self, $content, %params) = @_;
81 $content =~ s{ \r+ }{}gx;
82 $content =~ s{ \n+ }{ }gx;
83 $content =~ s{ (?:\ |\s)+ }{ }gx;
84 $content =~ s{ (?:\ |\s)+$ }{}gx;
85 $content =~ s{ (?: <br/?> )+$ }{}gx;
87 my @parts = grep { $_ } map {
88 if (substr($_, 0, 1) eq '<') {
90 $html_replace{$_} || '';
93 $::locale->quote_special_chars('Template/LaTeX', HTML::Entities::decode_entities($_));
95 } split(m{(<.*?>)}x, $content);
97 $content = join '', @parts;
98 $content =~ s{ (?: [\n\s] | \\newline )+ $ }{}gx; # remove line breaks at the end of the text
99 $content =~ s{ ^ \s+ }{}gx; # remove white space at the start of the text
100 $content =~ s{ ^ ( \\newline \ )+ }{ _lb_to_space($1) }gxe; # convert line breaks at the start of the text to vertical space
101 $content =~ s{ ( \n\n+ ) ( \\newline \ )+ }{ $1 . _lb_to_space($2) }gxe; # convert line breaks at the start of a paragraph to vertical space
102 $content =~ s{ ( \\end\{ [^\}]+ \} \h* ) ( \\newline \ )+ }{ $1 . _lb_to_space($2) }gxe; # convert line breaks after LaTeX environments like lists to vertical space
103 $content =~ s{ ^ \h+ \\newline }{\\newline}gmx;
104 $content =~ s{ \n\n \h* \\newline \h* }{\n\n}gmx;
110 html => \&_format_html,
111 text => \&_format_text,
117 my $self = $type->SUPER::new(@_);
123 my ($self, $content, $variable) = @_;
126 $formatters{ $self->{variable_content_types}->{$variable} }
127 // $formatters{ $self->{default_content_type} }
128 // $formatters{ text };
130 $content =~ s{[^\p{Print}\n]|\p{Cf}}{}g;
131 $variable =~ s{[^\p{Print}\n]|\p{Cf}}{}g;
133 return $formatter->($self, $content, variable => $variable);
137 my ($self, $var, $text, $start_tag, $end_tag, @indices) = @_;
139 my ($form, $new_contents) = ($self->{"form"}, "");
141 my $ary = $self->_get_loop_variable($var, 1, @indices);
144 my $current_page = 1;
145 my ($current_line, $corrent_row) = (0, 1);
146 my $description_array = $self->_get_loop_variable("description", 1);
147 my $longdescription_array = $self->_get_loop_variable("longdescription", 1);
148 my $linetotal_array = $self->_get_loop_variable("linetotal", 1);
150 $form->{TEMPLATE_ARRAYS}->{cumulatelinetotal} = [];
152 # forech block hasn't given us an array. ignore
153 return $new_contents unless ref $ary eq 'ARRAY';
155 for (my $i = 0; $i < scalar(@{$ary}); $i++) {
157 $form->{"__first__"} = $i == 0;
158 $form->{"__last__"} = ($i + 1) == scalar(@{$ary});
159 $form->{"__odd__"} = (($i + 1) % 2) == 1;
160 $form->{"__counter__"} = $i + 1;
162 #everything from here to the next marker should be removed after the release of 2.7.0
163 if ( ref $description_array eq 'ARRAY'
164 && scalar @{$description_array} == scalar @{$ary}
165 && $self->{"chars_per_line"} != 0)
167 my $lines = int(length($description_array->[$i]) / $self->{"chars_per_line"});
170 $description_array->[$i] =~ s/(\\newline\s?)*$//;
171 $lines++ while ($description_array->[$i] =~ m/\\newline/g);
174 if ($current_page == 1) {
175 $lpp = $self->{"lines_on_first_page"};
177 $lpp = $self->{"lines_on_second_page"};
180 # Yes we need a manual page break -- or the user has forced one
181 if ( (($current_line + $lines) > $lpp)
182 || ($description_array->[$i] =~ /<pagebreak>/)
183 || ( ref $longdescription_array eq 'ARRAY'
184 && $longdescription_array->[$i] =~ /<pagebreak>/)) {
185 my $pb = $self->{"pagebreak_block"};
187 # replace the special variables <%sumcarriedforward%>
190 my $psum = $form->format_amount($self->{"myconfig"}, $sum, 2);
191 $pb =~ s/$self->{tag_start_qm}sumcarriedforward$self->{tag_end_qm}/$psum/g;
192 $pb =~ s/$self->{tag_start_qm}lastpage$self->{tag_end_qm}/$current_page/g;
194 my $new_text = $self->parse_block($pb, (@indices, $i));
195 return undef unless (defined($new_text));
196 $new_contents .= $new_text;
201 $current_line += $lines;
203 #stop removing code here.
205 if ( ref $linetotal_array eq 'ARRAY'
206 && $i < scalar(@{$linetotal_array})) {
207 $sum += $form->parse_amount($self->{"myconfig"}, $linetotal_array->[$i]);
210 $form->{TEMPLATE_ARRAYS}->{cumulatelinetotal}->[$i] = $form->format_amount($self->{"myconfig"}, $sum, 2);
212 my $new_text = $self->parse_block($text, (@indices, $i));
213 return undef unless (defined($new_text));
214 $new_contents .= $start_tag . $new_text . $end_tag;
216 map({ delete($form->{"__${_}__"}); } qw(first last odd counter));
218 return $new_contents;
222 my ($self, $text, $pos, $var, $not) = @_;
224 my $tag_start_len = length $self->{tag_start};
227 $pos = 0 unless ($pos);
229 while ($pos < length($text)) {
232 next if (substr($text, $pos - 1, length($self->{tag_start})) ne $self->{tag_start});
234 my $keyword_pos = $pos - 1 + $tag_start_len;
236 if ((substr($text, $keyword_pos, 2) eq 'if') || (substr($text, $keyword_pos, 7) eq 'foreach')) {
239 } elsif ((substr($text, $keyword_pos, 4) eq 'else') && (1 == $depth)) {
242 "$self->{tag_start}else$self->{tag_end} outside of "
243 . "$self->{tag_start}if$self->{tag_end} / "
244 . "$self->{tag_start}ifnot$self->{tag_end}.";
248 my $block = substr($text, 0, $pos - 1);
249 substr($text, 0, $pos - 1) = "";
250 $text =~ s!^$self->{tag_start_qm}.+?$self->{tag_end_qm}!!;
251 $text = $self->{tag_start} . 'if' . ($not ? " " : "not ") . $var . $self->{tag_end} . $text;
253 return ($block, $text);
255 } elsif (substr($text, $keyword_pos, 3) eq 'end') {
258 my $block = substr($text, 0, $pos - 1);
259 substr($text, 0, $pos - 1) = "";
260 $text =~ s!^$self->{tag_start_qm}.+?$self->{tag_end_qm}!!;
262 return ($block, $text);
271 $main::lxdebug->enter_sub();
273 my ($self, $contents, @indices) = @_;
275 my $new_contents = "";
277 while ($contents ne "") {
278 my $pos_if = index($contents, $self->{tag_start} . 'if');
279 my $pos_foreach = index($contents, $self->{tag_start} . 'foreach');
281 if ((-1 == $pos_if) && (-1 == $pos_foreach)) {
282 $new_contents .= $self->substitute_vars($contents, @indices);
286 if ((-1 == $pos_if) || ((-1 != $pos_foreach) && ($pos_if > $pos_foreach))) {
287 $new_contents .= $self->substitute_vars(substr($contents, 0, $pos_foreach), @indices);
288 substr($contents, 0, $pos_foreach) = "";
290 if ($contents !~ m|^($self->{tag_start_qm}foreach (.+?)$self->{tag_end_qm})|) {
291 $self->{"error"} = "Malformed $self->{tag_start}foreach$self->{tag_end}.";
292 $main::lxdebug->leave_sub();
298 substr($contents, 0, length($1)) = "";
301 ($block, $contents) = $self->find_end($contents);
303 $self->{"error"} = "Unclosed $self->{tag_start}foreach$self->{tag_end}." unless ($self->{"error"});
304 $main::lxdebug->leave_sub();
308 my $new_text = $self->parse_foreach($var, $block, "", "", @indices);
309 if (!defined($new_text)) {
310 $main::lxdebug->leave_sub();
313 $new_contents .= $new_text;
316 if (!$self->_parse_block_if(\$contents, \$new_contents, $pos_if, @indices)) {
317 $main::lxdebug->leave_sub();
323 $main::lxdebug->leave_sub();
325 return $new_contents;
328 sub parse_first_line {
330 my $line = shift || "";
332 if ($line =~ m/([^\s]+)set-tag-style([^\s]+)/) {
334 $self->{error} = "The tag start and end markers must not be equal.";
338 $self->set_tag_style($1, $2);
344 sub _parse_config_option {
351 my ($key, $value) = split m/\s*=\s*/, $line, 2;
353 if ($key eq 'tag-style') {
354 $self->set_tag_style(split(m/\s+/, $value, 2));
356 if ($key eq 'use-template-toolkit') {
357 $self->set_use_template_toolkit($value);
361 sub _parse_config_lines {
365 my ($comment_start, $comment_end) = ("", "");
367 if (ref $self eq 'SL::Template::LaTeX') {
368 $comment_start = '\s*%';
369 } elsif (ref $self eq 'SL::Template::HTML') {
370 $comment_start = '\s*<!--';
371 $comment_end = '(?:--)?>\s*';
373 $comment_start = '\s*\#';
376 my $num_lines = scalar @{ $lines };
379 while ($i < $num_lines) {
380 my $line = $lines->[$i];
382 if ($line !~ m/^${comment_start}\s*config\s*:(.*?)${comment_end}$/i) {
387 $self->_parse_config_option($1);
388 splice @{ $lines }, $i, 1;
393 sub _embed_file_directive {
394 my ($self, $file) = @_;
396 # { source => $xmlfile,
397 # name => 'ZUGFeRD-invoice.xml',
398 # description => $::locale->text('ZUGFeRD invoice'), }
400 my $file_name = blessed($file->{source}) && $file->{source}->can('filename') ? $file->{source}->filename : "" . $file->{source}->filename;
401 my $embed_name = $file->{name} // $file_name;
402 $embed_name =~ s{.*/}{};
404 my $embed_name_ascii = $::locale->quote_special_chars('filenames', $embed_name);
405 $embed_name_ascii =~ s{[^a-z0-9!@#$%^&*(){}[\],.+'"=_-]+}{}gi;
410 my ($name, $value) = @_;
411 return if ($value // '') eq '';
412 push @options, sprintf('%s={%s}', $name, $value); # TODO: escaping
415 $add_opt->('filespec', $embed_name_ascii);
416 $add_opt->('ucfilespec', $embed_name);
417 $add_opt->('desc', $file->{description});
418 $add_opt->('afrelationship', $file->{relationship});
419 $add_opt->('mimetype', $file->{mime_type});
421 return sprintf('\embedfile[%s]{%s}', join(',', @options), $file_name);
424 sub _force_mandatory_packages {
425 my ($self, @lines) = @_;
429 my @required_packages = qw(textcomp ulem);
430 push @required_packages, 'embedfile' if $self->{pdf_a};
432 foreach my $line (@lines) {
433 if ($line =~ m/\\usepackage[^\{]*{(.*?)}/) {
434 $used_packages{$1} = 1;
436 } elsif ($line =~ m/\\begin\{document\}/) {
437 if ($self->{pdf_a} && $self->{pdf_a}->{xmp}) {
438 my $version = $self->{pdf_a}->{version} // '3a';
439 my $xmp_file_name = $self->{userspath} . "/pdfa.xmp";
440 my $out = IO::File->new($xmp_file_name, ">:encoding(utf-8)") || croak "Error creating ${xmp_file_name}: $!";
441 $out->print(Encode::encode('utf-8', $self->{pdf_a}->{xmp}));
445 "\\usepackage[a-${version},mathxmp]{pdfx}[2018/12/22]\n",
446 "\\usepackage[genericmode]{tagpdf}\n",
447 "\\tagpdfsetup{activate-all}\n",
448 "\\hypersetup{pdfstartview=}\n",
452 push @new_lines, map { "\\usepackage{$_}\n" } grep { !$used_packages{$_} } @required_packages;
453 push @new_lines, $line;
454 push @new_lines, map { $self->_embed_file_directive($_) } @{ $self->{pdf_attachments} // [] };
459 push @new_lines, $line;
468 my $form = $self->{"form"};
470 if (!open(IN, "$form->{templates}/$form->{IN}")) {
471 $self->{"error"} = "$form->{templates}/$form->{IN}: $!";
478 $self->_parse_config_lines(\@lines);
479 @lines = $self->_force_mandatory_packages(@lines) if (ref $self eq 'SL::Template::LaTeX');
481 my $contents = join("", @lines);
483 # detect pagebreak block and its parameters
484 if ($contents =~ /^(.*)($self->{tag_start_qm}pagebreak\s+(\d+)\s+(\d+)\s+(\d+)\s*$self->{tag_end_qm}(.*?)$self->{tag_start_qm}end(\s*pagebreak)?$self->{tag_end_qm})/s) {
485 $self->{"chars_per_line"} = $3;
486 $self->{"lines_on_first_page"} = $4;
487 $self->{"lines_on_second_page"} = $5;
488 $self->{"pagebreak_block"} = $6;
490 substr($contents, length($1), length($2)) = "";
493 $self->{"forced_pagebreaks"} = [];
496 if ($self->{use_template_toolkit}) {
497 if ($self->{custom_tag_style}) {
498 $contents = "[% TAGS $self->{tag_start} $self->{tag_end} %]\n" . $contents;
501 my $globals = global_vars();
503 $::form->template->process(\$contents, { %$form, %$globals }, \$new_contents) || die $::form->template->error;
505 $new_contents = $self->parse_block($contents);
507 if (!defined($new_contents)) {
508 $main::lxdebug->leave_sub();
512 binmode OUT, ":utf8";
513 print OUT Unicode::Normalize::normalize('C', $new_contents);
515 if ($form->{"format"} =~ /postscript/i) {
516 return $self->convert_to_postscript();
517 } elsif ($form->{"format"} =~ /pdf/i) {
518 return $self->convert_to_pdf();
524 sub _texinputs_path {
525 my ($self, $templates_path) = @_;
527 my $exe_dir = SL::System::Process::exe_dir();
528 $templates_path = $exe_dir . '/' . $templates_path unless $templates_path =~ m{^/};
530 return join(':', grep({ $_ } ('.', $exe_dir . '/texmf', $exe_dir . '/users', $templates_path, $ENV{TEXINPUTS})), '');
533 sub convert_to_postscript {
535 my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
537 # Convert the tex file to postscript
538 local $ENV{TEXINPUTS} = $self->_texinputs_path($form->{templates});
540 if (!chdir("$userspath")) {
541 $self->{"error"} = "chdir : $!";
546 $form->{tmpfile} =~ s/\Q$userspath\E\///g;
548 my $latex = $self->_get_latex_path();
549 my $old_home = $ENV{HOME};
550 my $old_openin_any = $ENV{openin_any};
551 $ENV{HOME} = $userspath =~ m|^/| ? $userspath : getcwd();
552 $ENV{openin_any} = "r";
554 for (my $run = 1; $run <= 2; $run++) {
555 if (system("${latex} --interaction=nonstopmode $form->{tmpfile} " .
556 "> $form->{tmpfile}.err") == -1) {
557 die "system call to $latex failed: $!";
560 $ENV{HOME} = $old_home;
561 $ENV{openin_any} = $old_openin_any;
562 $self->{"error"} = $form->cleanup($latex);
567 $form->{tmpfile} =~ s/tex$/dvi/;
569 if (system("dvips $form->{tmpfile} -o -q > /dev/null") == -1) {
570 die "system call to dvips failed: $!";
572 $ENV{HOME} = $old_home;
573 $ENV{openin_any} = $old_openin_any;
576 $self->{"error"} = "dvips : $?";
577 $self->cleanup('dvips');
580 $form->{tmpfile} =~ s/dvi$/ps/;
589 my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
591 # Convert the tex file to PDF
592 local $ENV{TEXINPUTS} = $self->_texinputs_path($form->{templates});
594 if (!chdir("$userspath")) {
595 $self->{"error"} = "chdir : $!";
600 $form->{tmpfile} =~ s/\Q$userspath\E\///g;
602 my $latex = $self->_get_latex_path();
603 my $old_home = $ENV{HOME};
604 my $old_openin_any = $ENV{openin_any};
605 $ENV{HOME} = $userspath =~ m|^/| ? $userspath : getcwd();
606 $ENV{openin_any} = "r";
608 for (my $run = 1; $run <= 2; $run++) {
609 if (system("${latex} --interaction=nonstopmode $form->{tmpfile} " .
610 "> $form->{tmpfile}.err") == -1) {
611 die "system call to $latex failed: $!";
615 $ENV{HOME} = $old_home;
616 $ENV{openin_any} = $old_openin_any;
617 $self->{error} = $form->cleanup($latex);
622 $ENV{HOME} = $old_home;
623 $ENV{openin_any} = $old_openin_any;
624 $form->{tmpfile} =~ s/tex$/pdf/;
631 sub _get_latex_path {
632 return $::lx_office_conf{applications}->{latex} || 'pdflatex';
635 sub get_mime_type() {
638 if ($self->{"form"}->{"format"} =~ /postscript/i) {
639 return "application/postscript";
641 return "application/pdf";
649 sub parse_and_create_pdf {
650 my ($class, $template_file_name, %params) = @_;
652 my $userspath = delete($params{userspath}) || $::lx_office_conf{paths}->{userspath};
653 my $keep_temp = $::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files};
654 my ($tex_fh, $tex_file_name) = File::Temp::tempfile(
655 'kivitendo-printXXXXXX',
658 UNLINK => $keep_temp ? 0 : 1,,
661 my $old_wd = getcwd();
663 my $local_form = Form->new('');
664 $local_form->{cwd} = $old_wd;
665 $local_form->{IN} = $template_file_name;
666 $local_form->{tmpdir} = $userspath;
667 $local_form->{tmpfile} = $tex_file_name;
668 $local_form->{templates} = SL::DB::Default->get->templates;
670 foreach (keys %params) {
671 croak "The parameter '$_' must not be used." if exists $local_form->{$_};
672 $local_form->{$_} = $params{$_};
677 my $template = SL::Template::LaTeX->new(file_name => $template_file_name, form => $local_form, userspath => $userspath);
678 my $result = $template->parse($tex_fh) && $template->convert_to_pdf;
680 die $template->{error} unless $result;
683 } or do { $error = $EVAL_ERROR; };
689 chmod(((stat $tex_file_name)[2] & 07777) | 0660, $tex_file_name);
691 my $tmpfile = $tex_file_name;
692 $tmpfile =~ s/\.\w+$//;
693 unlink(grep { !m/\.pdf$/ } <$tmpfile.*>);
696 return (error => $error) if $error;
697 return (file_name => do { $tex_file_name =~ s/tex$/pdf/; $tex_file_name });
703 INSTANCE_CONF => $::instance_conf,
705 LXCONFIG => $::lx_office_conf,
706 LXDEBUG => $::lxdebug,
707 MYCONFIG => \%::myconfig,