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) = @_;
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/\\begin\{document\}/) {
432 if ($self->{pdf_a} && $self->{pdf_a}->{xmp}) {
433 my $version = $self->{pdf_a}->{version} // '3a';
434 my $xmp_file_name = $self->{userspath} . "/pdfa.xmp";
435 my $out = IO::File->new($xmp_file_name, ">:encoding(utf-8)") || croak "Error creating ${xmp_file_name}: $!";
436 $out->print(Encode::encode('utf-8', $self->{pdf_a}->{xmp}));
440 "\\usepackage[a-${version},mathxmp]{pdfx}[2018/12/22]\n",
441 "\\usepackage[genericmode]{tagpdf}\n",
442 "\\tagpdfsetup{activate-all}\n",
443 "\\hypersetup{pdfstartview=}\n",
447 push @new_lines, map { "\\usepackage{$_}\n" } grep { !$used_packages{$_} } @required_packages;
448 push @new_lines, $line;
449 push @new_lines, map { $self->_embed_file_directive($_) } @{ $self->{pdf_attachments} // [] };
454 push @new_lines, $line;
463 my $form = $self->{"form"};
465 if (!open(IN, "$form->{templates}/$form->{IN}")) {
466 $self->{"error"} = "$form->{templates}/$form->{IN}: $!";
473 $self->_parse_config_lines(\@lines);
474 @lines = $self->_force_mandatory_packages(@lines) if (ref $self eq 'SL::Template::LaTeX');
476 my $contents = join("", @lines);
478 # detect pagebreak block and its parameters
479 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) {
480 $self->{"chars_per_line"} = $3;
481 $self->{"lines_on_first_page"} = $4;
482 $self->{"lines_on_second_page"} = $5;
483 $self->{"pagebreak_block"} = $6;
485 substr($contents, length($1), length($2)) = "";
488 $self->{"forced_pagebreaks"} = [];
491 if ($self->{use_template_toolkit}) {
492 if ($self->{custom_tag_style}) {
493 $contents = "[% TAGS $self->{tag_start} $self->{tag_end} %]\n" . $contents;
496 my $globals = global_vars();
498 $::form->template->process(\$contents, { %$form, %$globals }, \$new_contents) || die $::form->template->error;
500 $new_contents = $self->parse_block($contents);
502 if (!defined($new_contents)) {
503 $main::lxdebug->leave_sub();
507 binmode OUT, ":utf8";
508 print OUT Unicode::Normalize::normalize('C', $new_contents);
510 if ($form->{"format"} =~ /postscript/i) {
511 return $self->convert_to_postscript();
512 } elsif ($form->{"format"} =~ /pdf/i) {
513 return $self->convert_to_pdf();
519 sub _texinputs_path {
520 my ($self, $templates_path) = @_;
522 my $exe_dir = SL::System::Process::exe_dir();
523 $templates_path = $exe_dir . '/' . $templates_path unless $templates_path =~ m{^/};
525 return join(':', grep({ $_ } ('.', $exe_dir . '/texmf', $exe_dir . '/users', $templates_path, $ENV{TEXINPUTS})), '');
528 sub convert_to_postscript {
530 my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
532 # Convert the tex file to postscript
533 local $ENV{TEXINPUTS} = $self->_texinputs_path($form->{templates});
535 if (!chdir("$userspath")) {
536 $self->{"error"} = "chdir : $!";
541 $form->{tmpfile} =~ s/\Q$userspath\E\///g;
543 my $latex = $self->_get_latex_path();
544 my $old_home = $ENV{HOME};
545 my $old_openin_any = $ENV{openin_any};
546 $ENV{HOME} = $userspath =~ m|^/| ? $userspath : getcwd();
547 $ENV{openin_any} = "r";
549 for (my $run = 1; $run <= 2; $run++) {
550 if (system("${latex} --interaction=nonstopmode $form->{tmpfile} " .
551 "> $form->{tmpfile}.err") == -1) {
552 die "system call to $latex failed: $!";
555 $ENV{HOME} = $old_home;
556 $ENV{openin_any} = $old_openin_any;
557 $self->{"error"} = $form->cleanup($latex);
562 $form->{tmpfile} =~ s/tex$/dvi/;
564 if (system("dvips $form->{tmpfile} -o -q > /dev/null") == -1) {
565 die "system call to dvips failed: $!";
567 $ENV{HOME} = $old_home;
568 $ENV{openin_any} = $old_openin_any;
571 $self->{"error"} = "dvips : $?";
572 $self->cleanup('dvips');
575 $form->{tmpfile} =~ s/dvi$/ps/;
584 my ($form, $userspath) = ($self->{"form"}, $self->{"userspath"});
586 # Convert the tex file to PDF
587 local $ENV{TEXINPUTS} = $self->_texinputs_path($form->{templates});
589 if (!chdir("$userspath")) {
590 $self->{"error"} = "chdir : $!";
595 $form->{tmpfile} =~ s/\Q$userspath\E\///g;
597 my $latex = $self->_get_latex_path();
598 my $old_home = $ENV{HOME};
599 my $old_openin_any = $ENV{openin_any};
600 $ENV{HOME} = $userspath =~ m|^/| ? $userspath : getcwd();
601 $ENV{openin_any} = "r";
603 for (my $run = 1; $run <= 2; $run++) {
604 if (system("${latex} --interaction=nonstopmode $form->{tmpfile} " .
605 "> $form->{tmpfile}.err") == -1) {
606 die "system call to $latex failed: $!";
610 $ENV{HOME} = $old_home;
611 $ENV{openin_any} = $old_openin_any;
612 $self->{error} = $form->cleanup($latex);
617 $ENV{HOME} = $old_home;
618 $ENV{openin_any} = $old_openin_any;
619 $form->{tmpfile} =~ s/tex$/pdf/;
626 sub _get_latex_path {
627 return $::lx_office_conf{applications}->{latex} || 'pdflatex';
630 sub get_mime_type() {
633 if ($self->{"form"}->{"format"} =~ /postscript/i) {
634 return "application/postscript";
636 return "application/pdf";
644 sub parse_and_create_pdf {
645 my ($class, $template_file_name, %params) = @_;
647 my $userspath = delete($params{userspath}) || $::lx_office_conf{paths}->{userspath};
648 my $keep_temp = $::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files};
649 my ($tex_fh, $tex_file_name) = File::Temp::tempfile(
650 'kivitendo-printXXXXXX',
653 UNLINK => $keep_temp ? 0 : 1,,
656 my $old_wd = getcwd();
658 my $local_form = Form->new('');
659 $local_form->{cwd} = $old_wd;
660 $local_form->{IN} = $template_file_name;
661 $local_form->{tmpdir} = $userspath;
662 $local_form->{tmpfile} = $tex_file_name;
663 $local_form->{templates} = SL::DB::Default->get->templates;
665 foreach (keys %params) {
666 croak "The parameter '$_' must not be used." if exists $local_form->{$_};
667 $local_form->{$_} = $params{$_};
672 my $template = SL::Template::LaTeX->new(file_name => $template_file_name, form => $local_form, userspath => $userspath);
673 my $result = $template->parse($tex_fh) && $template->convert_to_pdf;
675 die $template->{error} unless $result;
678 } or do { $error = $EVAL_ERROR; };
684 chmod(((stat $tex_file_name)[2] & 07777) | 0660, $tex_file_name);
686 my $tmpfile = $tex_file_name;
687 $tmpfile =~ s/\.\w+$//;
688 unlink(grep { !m/\.pdf$/ } <$tmpfile.*>);
691 return (error => $error) if $error;
692 return (file_name => do { $tex_file_name =~ s/tex$/pdf/; $tex_file_name });
698 INSTANCE_CONF => $::instance_conf,
700 LXCONFIG => $::lx_office_conf,
701 LXDEBUG => $::lxdebug,
702 MYCONFIG => \%::myconfig,