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{.*/}{};
406 my ($name, $value) = @_;
407 return if ($value // '') eq '';
408 push @options, sprintf('%s={%s}', $name, $value); # TODO: escaping
411 $add_opt->('ucfilespec', $embed_name);
412 $add_opt->('desc', $file->{description});
413 $add_opt->('afrelationship', $file->{relationship});
414 $add_opt->('mimetype', $file->{mime_type});
416 return sprintf('\embedfile[%s]{%s}', join(',', @options), $file_name);
419 sub _force_mandatory_packages {
420 my ($self, @lines) = @_;
423 my (%used_packages, $at_beginning_of_document);
424 my @required_packages = qw(textcomp ulem);
425 push @required_packages, 'embedfile' if $self->{pdf_a};
427 foreach my $line (@lines) {
428 if ($line =~ m/\\usepackage[^\{]*{(.*?)}/) {
429 $used_packages{$1} = 1;
431 } elsif (($line =~ m/\\documentclass/) && $self->{pdf_a}) {
432 my $version = $self->{pdf_a}->{version} // '3a';
433 my $meta = $self->{pdf_a}->{meta_data} // {};
436 "\\RequirePackage{filecontents}\n",
437 "\\begin{filecontents*}{\\jobname.xmpdata}\n",
438 ($meta->{title} ? sprintf("\\Title{%s}\n", $meta->{title}) : ""),
439 ($meta->{author} ? sprintf("\\Author{%s}\n", $meta->{author}) : ""),
440 ($meta->{language} ? sprintf("\\Language{%s}\n", $meta->{language}) : ""),
441 "\\end{filecontents*}\n",
443 "\\usepackage[a-${version},mathxmp]{pdfx}[2018/12/22]\n",
444 "\\usepackage[genericmode]{tagpdf}\n",
445 "\\tagpdfsetup{activate-all}\n",
446 "\\hypersetup{pdfstartview=}\n",
451 } elsif ($line =~ m/\\begin\{document\}/) {
452 $at_beginning_of_document = 1;
453 push @new_lines, map { "\\usepackage{$_}\n" } grep { !$used_packages{$_} } @required_packages;
456 push @new_lines, $line;
458 if ($at_beginning_of_document) {
459 $at_beginning_of_document = 0;
461 push @new_lines, map { $self->_embed_file_directive($_) } @{ $self->{pdf_attachments} // [] };
471 my $form = $self->{"form"};
473 if (!open(IN, "$form->{templates}/$form->{IN}")) {
474 $self->{"error"} = "$form->{templates}/$form->{IN}: $!";
481 $self->_parse_config_lines(\@lines);
482 @lines = $self->_force_mandatory_packages(@lines) if (ref $self eq 'SL::Template::LaTeX');
484 my $contents = join("", @lines);
486 # detect pagebreak block and its parameters
487 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) {
488 $self->{"chars_per_line"} = $3;
489 $self->{"lines_on_first_page"} = $4;
490 $self->{"lines_on_second_page"} = $5;
491 $self->{"pagebreak_block"} = $6;
493 substr($contents, length($1), length($2)) = "";
496 $self->{"forced_pagebreaks"} = [];
499 if ($self->{use_template_toolkit}) {
500 if ($self->{custom_tag_style}) {
501 $contents = "[% TAGS $self->{tag_start} $self->{tag_end} %]\n" . $contents;
504 my $globals = global_vars();
506 $::form->template->process(\$contents, { %$form, %$globals }, \$new_contents) || die $::form->template->error;
508 $new_contents = $self->parse_block($contents);
510 if (!defined($new_contents)) {
511 $main::lxdebug->leave_sub();
515 binmode OUT, ":utf8";
516 print OUT Unicode::Normalize::normalize('C', $new_contents);
518 if ($form->{"format"} =~ /postscript/i) {
519 return $self->convert_to_postscript();
520 } elsif ($form->{"format"} =~ /pdf/i) {
521 return $self->convert_to_pdf();
527 sub _texinputs_path {
528 my ($self, $templates_path) = @_;
530 my $exe_dir = SL::System::Process::exe_dir();
531 $templates_path = $exe_dir . '/' . $templates_path unless $templates_path =~ m{^/};
533 return join(':', grep({ $_ } ('.', $exe_dir . '/texmf', $templates_path, $ENV{TEXINPUTS})), '');
536 sub convert_to_postscript {
538 my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
540 # Convert the tex file to postscript
541 local $ENV{TEXINPUTS} = $self->_texinputs_path($form->{templates});
543 if (!chdir("$userspath")) {
544 $self->{"error"} = "chdir : $!";
549 $form->{tmpfile} =~ s/\Q$userspath\E\///g;
551 my $latex = $self->_get_latex_path();
552 my $old_home = $ENV{HOME};
553 my $old_openin_any = $ENV{openin_any};
554 $ENV{HOME} = $userspath =~ m|^/| ? $userspath : getcwd();
555 $ENV{openin_any} = "r";
557 for (my $run = 1; $run <= 2; $run++) {
558 if (system("${latex} --interaction=nonstopmode $form->{tmpfile} " .
559 "> $form->{tmpfile}.err") == -1) {
560 die "system call to $latex failed: $!";
563 $ENV{HOME} = $old_home;
564 $ENV{openin_any} = $old_openin_any;
565 $self->{"error"} = $form->cleanup($latex);
570 $form->{tmpfile} =~ s/tex$/dvi/;
572 if (system("dvips $form->{tmpfile} -o -q > /dev/null") == -1) {
573 die "system call to dvips failed: $!";
575 $ENV{HOME} = $old_home;
576 $ENV{openin_any} = $old_openin_any;
579 $self->{"error"} = "dvips : $?";
580 $self->cleanup('dvips');
583 $form->{tmpfile} =~ s/dvi$/ps/;
592 my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
594 # Convert the tex file to PDF
595 local $ENV{TEXINPUTS} = $self->_texinputs_path($form->{templates});
597 if (!chdir("$userspath")) {
598 $self->{"error"} = "chdir : $!";
603 $form->{tmpfile} =~ s/\Q$userspath\E\///g;
605 my $latex = $self->_get_latex_path();
606 my $old_home = $ENV{HOME};
607 my $old_openin_any = $ENV{openin_any};
608 $ENV{HOME} = $userspath =~ m|^/| ? $userspath : getcwd();
609 $ENV{openin_any} = "r";
611 for (my $run = 1; $run <= 2; $run++) {
612 if (system("${latex} --interaction=nonstopmode $form->{tmpfile} " .
613 "> $form->{tmpfile}.err") == -1) {
614 die "system call to $latex failed: $!";
618 $ENV{HOME} = $old_home;
619 $ENV{openin_any} = $old_openin_any;
620 $self->{error} = $form->cleanup($latex);
625 $ENV{HOME} = $old_home;
626 $ENV{openin_any} = $old_openin_any;
627 $form->{tmpfile} =~ s/tex$/pdf/;
634 sub _get_latex_path {
635 return $::lx_office_conf{applications}->{latex} || 'pdflatex';
638 sub get_mime_type() {
641 if ($self->{"form"}->{"format"} =~ /postscript/i) {
642 return "application/postscript";
644 return "application/pdf";
652 sub parse_and_create_pdf {
653 my ($class, $template_file_name, %params) = @_;
655 my $keep_temp = $::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files};
656 my ($tex_fh, $tex_file_name) = File::Temp::tempfile(
657 'kivitendo-printXXXXXX',
659 DIR => $::lx_office_conf{paths}->{userspath},
660 UNLINK => $keep_temp ? 0 : 1,,
663 my $old_wd = getcwd();
665 my $local_form = Form->new('');
666 $local_form->{cwd} = $old_wd;
667 $local_form->{IN} = $template_file_name;
668 $local_form->{tmpdir} = $::lx_office_conf{paths}->{userspath};
669 $local_form->{tmpfile} = $tex_file_name;
670 $local_form->{templates} = SL::DB::Default->get->templates;
672 foreach (keys %params) {
673 croak "The parameter '$_' must not be used." if exists $local_form->{$_};
674 $local_form->{$_} = $params{$_};
679 my $template = SL::Template::LaTeX->new(file_name => $template_file_name, form => $local_form);
680 my $result = $template->parse($tex_fh) && $template->convert_to_pdf;
682 die $template->{error} unless $result;
685 } or do { $error = $EVAL_ERROR; };
691 chmod(((stat $tex_file_name)[2] & 07777) | 0660, $tex_file_name);
693 my $tmpfile = $tex_file_name;
694 $tmpfile =~ s/\.\w+$//;
695 unlink(grep { !m/\.pdf$/ } <$tmpfile.*>);
698 return (error => $error) if $error;
699 return (file_name => do { $tex_file_name =~ s/tex$/pdf/; $tex_file_name });
705 INSTANCE_CONF => $::instance_conf,
707 LXCONFIG => $::lx_office_conf,
708 LXDEBUG => $::lxdebug,
709 MYCONFIG => \%::myconfig,