| 1 | # /=====================================================================\ # | ||
| 2 | # | LaTeXML::Post::LaTeXImages | # | ||
| 3 | # | Abstract Postprocessor to create images from LaTeX code | # | ||
| 4 | # |=====================================================================| # | ||
| 5 | # | Part of LaTeXML: | # | ||
| 6 | # | Public domain software, produced as part of work done by the | # | ||
| 7 | # | United States Government & not subject to copyright in the US. | # | ||
| 8 | # |---------------------------------------------------------------------| # | ||
| 9 | # | Bruce Miller <bruce.miller@nist.gov> #_# | # | ||
| 10 | # | http://dlmf.nist.gov/LaTeXML/ (o o) | # | ||
| 11 | # \=========================================================ooo==U==ooo=/ # | ||
| 12 | |||
| 13 | package LaTeXML::Post::LaTeXImages; | ||
| 14 | use strict; | ||
| 15 | use warnings; | ||
| 16 | use DB_File; | ||
| 17 | use Config; | ||
| 18 | use LaTeXML::Util::Image; | ||
| 19 | use POSIX qw(ceil); | ||
| 20 | use LaTeXML::Util::Pathname; | ||
| 21 | use File::Temp; | ||
| 22 | use File::Which; | ||
| 23 | use LaTeXML::Post; | ||
| 24 | use base qw(LaTeXML::Post::Processor); | ||
| 25 | |||
| 26 | #====================================================================== | ||
| 27 | |||
| 28 | # Other silly constants that might want changing? | ||
| 29 | ##our $TMP = '/tmp'; | ||
| 30 | our $LATEXCMD = 'latex'; #(or elatex) [ CONFIGURABLE? Encoded in PI?] | ||
| 31 | |||
| 32 | # The purpose of this module is to convert TeX fragments into png (or similar), | ||
| 33 | # typically via dvi and other intermediate formats. | ||
| 34 | # LaTeX converts the TeX stuff to dvi; | ||
| 35 | # dvips converts the dvi to eps, and ImageMagick can convert the eps to png; | ||
| 36 | # OR dvipng can convert the dvi to png MUCH quicker... if it's available. | ||
| 37 | |||
| 38 | # Options: | ||
| 39 | # source : (dir) | ||
| 40 | # magnification : typically something like 1.33333, but you may want bigger | ||
| 41 | # maxwidth : maximum page width, in pixels (whenever line breaking is possible) | ||
| 42 | # dpi : assumed DPI for the target medium (default 96) | ||
| 43 | # background : color of background (for anti-aliasing, since it is made transparent) | ||
| 44 | # imagetype : typically 'png' or 'gif'. | ||
| 45 | sub new { | ||
| 46 | my ($class, %options) = @_; | ||
| 47 | my $self = $class->SUPER::new(%options); | ||
| 48 | $$self{magnification} = $options{magnification} || 1.33333; | ||
| 49 | $$self{maxwidth} = $options{maxwidth} || 800; | ||
| 50 | $$self{dpi} = $options{dpi} || 96; | ||
| 51 | $$self{background} = $options{background} || "#FFFFFF"; | ||
| 52 | $$self{imagetype} = $options{imagetype} || 'png'; | ||
| 53 | |||
| 54 | # Parameters for separating the clipping box from the | ||
| 55 | # desired padding between image edge and "ink" | ||
| 56 | $$self{padding} = $options{padding} || 2; # pixels | ||
| 57 | # amount of extra space (+padding) to put between object & rules for clipping | ||
| 58 | $$self{clippingfudge} = 3; # px | ||
| 59 | $$self{clippingrule} = 0.90; # pixels (< 1 to avoid antialiasing..?) | ||
| 60 | |||
| 61 | # Sanity check of dvi processing... | ||
| 62 | # If trying to create svg... | ||
| 63 | if (($$self{imagetype} eq 'svg') && (!defined $options{use_dvisvgm}) && which('dvisvgm')) { | ||
| 64 | $$self{use_dvisvgm} = 1; } | ||
| 65 | elsif ($$self{use_dvisvgm} && (($$self{imagetype} ne 'svg') || !which('dvisvgm'))) { | ||
| 66 | $$self{use_dvisvgm} = 0; } # but disable if inappropriate or unavailable | ||
| 67 | # We'll use dvipng (MUCH faster) if requested or not forbidden & available. | ||
| 68 | # But be careful: it can't handle much postscript, so better NOT for graphics! | ||
| 69 | if (($$self{imagetype} eq 'png') && (!defined $options{use_dvipng}) && which('dvipng')) { | ||
| 70 | $$self{use_dvipng} = 1; } | ||
| 71 | elsif ($$self{use_dvipng} && (($$self{imagetype} ne 'png') || !which('dvipng'))) { | ||
| 72 | $$self{use_dvipng} = 0; } # but disable if inappropriate or unavailable. | ||
| 73 | |||
| 74 | # Parameterize according to the selected dvi-to-whatever processor. | ||
| 75 | my $mag = int($$self{magnification} * 1000); | ||
| 76 | my $dpi = int($$self{dpi} * $$self{magnification}); | ||
| 77 | # Unfortunately, each command has incompatible -o option to name the output file. | ||
| 78 | # Note that the formatting char used, '%', has to be doubled on Windows!! | ||
| 79 | # Maybe that's only true when it looks like an environment variable? | ||
| 80 | # Ie. %variable% ? | ||
| 81 | # my $fmt = ($^O eq 'MSWin32' ? '%%' : '%'); | ||
| 82 | my $fmt = '%'; | ||
| 83 | if ($$self{use_dvisvgm}) { | ||
| 84 | # img name uses 2 digits for page; what happens at 100? | ||
| 85 | ## $$self{dvicmd} = "dvisvgm --page=1- --bbox=min --mag=$mag -o imgx-${fmt}p"; | ||
| 86 | # dvisvgm currently creates glyph descriptions w/ unicode attribute having the wrong codepoint | ||
| 87 | # firefox, chromium use this codepoint instead of the glyph "drawing" | ||
| 88 | # a later version of dvisvgm should do better at synthesizing the unicode? | ||
| 89 | # but for now, we'll use --no-fonts, which creates glyph drawings rather than "glyphs" | ||
| 90 | # Also, increase the bounding box from min by 1pt | ||
| 91 | # Also, note incompatible change in the -o option after version 1.6; | ||
| 92 | # it now can take a number of digits (%3p) for pages, BUT old version produces imgx-%3p.svg!! | ||
| 93 | # So, simply use %p, let new version do 1,..,9,10,... | ||
| 94 | # Recovery code below! | ||
| 95 | $$self{dvicmd} = "dvisvgm --page=1- --bbox=1pt --scale=$$self{magnification} --no-fonts -o imgx-${fmt}p"; | ||
| 96 | $$self{dvicmd_output_name} = 'imgx-%02d.svg'; | ||
| 97 | $$self{dvicmd_output_type} = 'svg'; | ||
| 98 | $$self{frame_output} = 0; } | ||
| 99 | elsif ($$self{use_dvipng}) { | ||
| 100 | $$self{dvicmd} = "dvipng -bg Transparent -T tight -q -D$dpi -o imgx-${fmt}03d.png"; | ||
| 101 | $$self{dvicmd_output_name} = 'imgx-%03d.png'; | ||
| 102 | $$self{dvicmd_output_type} = 'png32'; | ||
| 103 | $$self{frame_output} = 1; } | ||
| 104 | else { | ||
| 105 | # Useful DVIPS options: | ||
| 106 | # -q : run quietly | ||
| 107 | # -x# : magnification * 1000 | ||
| 108 | # -S1 -i : make a separate file for each `section' consisting of a single page. | ||
| 109 | # QUESTION: dvips' naming scheme allows for 999 pages... what happens at 1000? | ||
| 110 | # -E : crop each page close to the `ink'. | ||
| 111 | # -j0 : don't subset fonts; silly really, but some font tests are making problems! | ||
| 112 | $$self{dvicmd} = "dvips -q -S1 -i -E -j0 -x$mag -o imgx"; | ||
| 113 | $$self{dvicmd_output_name} = 'imgx%03d'; | ||
| 114 | $$self{dvicmd_output_type} = 'eps'; | ||
| 115 | $$self{frame_output} = 1; } | ||
| 116 | return $self; } | ||
| 117 | |||
| 118 | #********************************************************************** | ||
| 119 | # Check whether this processor actually has the resources it needs to process. | ||
| 120 | # I don't know if there's a general API implied here; | ||
| 121 | # It could, conceivably be use in planning post processing? | ||
| 122 | # But generally, before signalling an error, you'd want to know that the processor | ||
| 123 | # is even needed. | ||
| 124 | # This test is called once we know that, from within | ||
| 125 | # | ||
| 126 | # At any rate: To process LaTeX snippets into images, we will need | ||
| 127 | # * latex (or related) from a TeX installation | ||
| 128 | # * Image::Magick (or similar) [see LaTeXML::Util::Image] | ||
| 129 | sub canProcess { | ||
| 130 | my ($self) = @_; | ||
| 131 | # Check if we have Image::Magick (or similar) | ||
| 132 | if (!image_can_image()) { | ||
| 133 | Error('expected', 'Image::Magick', undef, | ||
| 134 | "No available image processing module found; Skipping.", | ||
| 135 | "Please install one of: " . join(',', image_classes())); | ||
| 136 | return; } | ||
| 137 | # AND check if we have an approriprate latex!!! | ||
| 138 | if (($LATEXCMD =~ /^(\S+)/) && !which($1)) { # does the command seem to be available? | ||
| 139 | Error('expected', $LATEXCMD, undef, | ||
| 140 | "No latex command ($LATEXCMD) found; Skipping.", | ||
| 141 | "Please install TeX to generate images from LaTeX"); | ||
| 142 | return; } | ||
| 143 | return 1; } | ||
| 144 | |||
| 145 | #********************************************************************** | ||
| 146 | # Methods that must be defined; | ||
| 147 | |||
| 148 | # This is an abstract class; concrete classes must select the nodes to process. | ||
| 149 | # We'll still need to use $proc->extractTeX($doc,$node) | ||
| 150 | # to extract the actual TeX string! | ||
| 151 | sub toProcess { | ||
| 152 | return (); } | ||
| 153 | |||
| 154 | # $self->extractTeX($doc,$node)=>$texstring; | ||
| 155 | sub extractTeX { | ||
| 156 | return ""; } | ||
| 157 | |||
| 158 | # $self->format_tex($texstring) | ||
| 159 | sub format_tex { | ||
| 160 | return ""; } | ||
| 161 | |||
| 162 | # $self->setTeXImage($doc,$node,$imagepath,$width,$height); | ||
| 163 | # This is the default | ||
| 164 | sub setTeXImage { | ||
| 165 | my ($self, $doc, $node, $path, $width, $height, $depth) = @_; | ||
| 166 | $node->setAttribute('imagesrc', $path); | ||
| 167 | $node->setAttribute('imagewidth', $width); | ||
| 168 | $node->setAttribute('imageheight', $height); | ||
| 169 | $node->setAttribute('imagedepth', $depth) if defined $depth; | ||
| 170 | return; } | ||
| 171 | |||
| 172 | #====================================================================== | ||
| 173 | # Methods that could be wrapped, overridden. | ||
| 174 | |||
| 175 | # Should be called by extractTeX | ||
| 176 | sub cleanTeX { | ||
| 177 | my ($self, $tex) = @_; | ||
| 178 | return unless defined $tex; | ||
| 179 | my $style = ''; | ||
| 180 | # Save any leading style | ||
| 181 | if ($tex =~ s/^\s*(\\displaystyle|\\textstyle|\\scriptstyle|\\scriptscriptstyle)\s*//) { | ||
| 182 | $style = $1; } | ||
| 183 | $tex =~ s/^(?:\\\s*,|\\!\s*|\\>\s*|\\;\s*|\\:\s*|\\ \s*|\\\/\s*)*//; # Trim leading spacing (especially negative!) | ||
| 184 | $tex =~ s/(?:\\\s*,|\\!\s*|\\>\s*|\\;\s*|\\:\s*|\\ \s*|\\\/\s*)*$//; # and trailing spacing | ||
| 185 | # Strip comments, but watchout for \% (or more exactly, an ODD number of \) | ||
| 186 | $tex =~ s/(?<!\\)((?:\\\\)*)\%[^\n]*\n/$1/gs; | ||
| 187 | $tex = $style . ' ' . $tex if $style; # Put back the style, if any | ||
| 188 | return $tex; } | ||
| 189 | |||
| 190 | #********************************************************************** | ||
| 191 | |||
| 192 | #********************************************************************** | ||
| 193 | # Generating & Processing the LaTeX source. | ||
| 194 | #********************************************************************** | ||
| 195 | # Need the destination directory AND (optionally?) a subdir for the images. | ||
| 196 | # both are only used here. | ||
| 197 | # Alternatively, a dest for doc & dest for images ? | ||
| 198 | # What we really need to know is: | ||
| 199 | # (1) where to write the images. | ||
| 200 | # (2) relative path from doc to images. | ||
| 201 | |||
| 202 | # sub process { | ||
| 203 | # my ($self, $doc, @nodes) = @_; | ||
| 204 | # return $self->generateImages($doc, @nodes); } | ||
| 205 | |||
| 206 | sub generateImages { | ||
| 207 | my ($self, $doc, @nodes) = @_; | ||
| 208 | |||
| 209 | my $jobname = "ltxmlimg"; | ||
| 210 | my $orig_cwd = pathname_cwd(); | ||
| 211 | my $sep = $Config::Config{path_sep}; | ||
| 212 | local $ENV{TEXINPUTS} = join($sep, '.', $doc->getSearchPaths, | ||
| 213 | pathname_concat(pathname_installation(), 'texmf'), | ||
| 214 | ($ENV{TEXINPUTS} || $sep)); | ||
| 215 | |||
| 216 | my %table = (); | ||
| 217 | |||
| 218 | # === Get the desired nodes, extract the set of unique tex strings, | ||
| 219 | # noting which need processing. | ||
| 220 | # Note that if desiredResourcePathname is implemented, we might get | ||
| 221 | # several desired names for the same chunk of tex!!! | ||
| 222 | my ($ntotal, $nuniq) = (0, 0); | ||
| 223 | foreach my $node (@nodes) { | ||
| 224 | my $tex = $self->extractTeX($doc, $node); | ||
| 225 | next if !(defined $tex) || ($tex =~ /^\s*$/); | ||
| 226 | $ntotal++; | ||
| 227 | |||
| 228 | # Ideally, $dest is relative to document.. | ||
| 229 | my $dest = $self->desiredResourcePathname($doc, $node, undef, $$self{imagetype}); | ||
| 230 | # my $key = (ref $self) . ":" . $tex . ($dest ? ":$dest" : ''); | ||
| 231 | my $key = (ref $self) . ':' . $$self{imagetype} . ':' . $tex; | ||
| 232 | my $entry = $table{$key}; | ||
| 233 | if (!$entry) { | ||
| 234 | $nuniq++; | ||
| 235 | $entry = $table{$key} = { tex => $tex, key => $key, nodes => [], dest => [] }; } | ||
| 236 | # Why do I need to make things so complicated?!?! | ||
| 237 | # It may be desired that a particular image gets a specific name. | ||
| 238 | # AND, the same TeX may get different names, or some with & without names!! | ||
| 239 | if ($dest && (!grep { $dest eq $_ } @{ $$entry{dest} })) { | ||
| 240 | push(@{ $$entry{dest} }, $dest); } | ||
| 241 | push(@{ $$entry{nodes} }, $node); } | ||
| 242 | |||
| 243 | return $doc unless $nuniq; # No strings to process! | ||
| 244 | |||
| 245 | return unless $self->canProcess; | ||
| 246 | |||
| 247 | # === Check which objects still need processing. | ||
| 248 | my $destdir = $doc->getDestinationDirectory; | ||
| 249 | my @pending = (); | ||
| 250 | foreach my $key (sort keys %table) { | ||
| 251 | my $store = $doc->cacheLookup($key); | ||
| 252 | if ($store && ($store =~ /^(.*);(\d+);(\d+);(\d+)$/)) { | ||
| 253 | next if -f pathname_absolute($1, $destdir); } | ||
| 254 | push(@pending, $table{$key}); } | ||
| 255 | |||
| 256 | NoteProgress(" [$nuniq unique; " . scalar(@pending) . " new]"); | ||
| 257 | if (@pending) { # if any images need processing | ||
| 258 | # Create working directory; note TMPDIR attempts to put it in standard place (like /tmp/) | ||
| 259 | File::Temp->safe_level(File::Temp::HIGH); | ||
| 260 | my $workdir = File::Temp->newdir("LaTeXMLXXXXXX", TMPDIR => 1); | ||
| 261 | # === Generate the LaTeX file. | ||
| 262 | my $texfile = pathname_make(dir => $workdir, name => $jobname, type => 'tex'); | ||
| 263 | my $TEX; | ||
| 264 | if (!open($TEX, '>', $texfile)) { | ||
| 265 | Error('I/O', $texfile, undef, "Cant write to '$texfile'", "Response was: $!"); | ||
| 266 | return $doc; } | ||
| 267 | binmode $TEX, ':encoding(UTF-8)'; | ||
| 268 | print $TEX $self->pre_preamble($doc); | ||
| 269 | print $TEX "\\makeatletter\n"; | ||
| 270 | print $TEX $self->preamble($doc) . "\n"; | ||
| 271 | print $TEX "\\makeatother\n"; | ||
| 272 | print $TEX "\\begin{document}\n"; | ||
| 273 | foreach my $entry (@pending) { | ||
| 274 | ## print TEX "\\fbox{$$entry{tex}}\\clearpage\n"; } | ||
| 275 | print $TEX "$$entry{tex}\\clearpage\n"; } | ||
| 276 | print $TEX "\\end{document}\n"; | ||
| 277 | close($TEX); | ||
| 278 | |||
| 279 | # === Run LaTeX on the file. | ||
| 280 | # (keep the command simple so it works in Windows) | ||
| 281 | pathname_chdir($workdir); | ||
| 282 | my $ltxcommand = "$LATEXCMD $jobname > $jobname.ltxoutput"; | ||
| 283 | my $ltxerr = system($ltxcommand); | ||
| 284 | pathname_chdir($orig_cwd); | ||
| 285 | |||
| 286 | # Sometimes latex returns non-zero code, even though it apparently succeeded. | ||
| 287 | # And sometimes it doesn't produce a dvi, even with 0 return code? | ||
| 288 | if (($ltxerr != 0) || (!-f "$workdir/$jobname.dvi")) { | ||
| 289 | my $preserve = $$LaTeXML::POST{verbosity} > 0; # preserve junk when verbosity high. | ||
| 290 | $workdir->unlink_on_destroy(0) if $preserve; | ||
| 291 | Error('shell', $LATEXCMD, undef, | ||
| 292 | "LaTeX command '$ltxcommand' failed", | ||
| 293 | ($ltxerr == 0 ? "No dvi file generated" : "returned code $ltxerr (!= 0): $@"), | ||
| 294 | ($preserve ? "See $workdir/$jobname.log" : "Re-run with --verbose to see TeX log")); | ||
| 295 | return $doc; } | ||
| 296 | $workdir->unlink_on_destroy(0) if $$LaTeXML::POST{verbosity} > 2; | ||
| 297 | |||
| 298 | # Extract dimensions (width x height+depth) from each image from log file. | ||
| 299 | my @dimensions = (); | ||
| 300 | my $LOG; | ||
| 301 | if (open($LOG, '<', "$workdir/$jobname.log")) { | ||
| 302 | while (<$LOG>) { | ||
| 303 | if (/^\s*LXIMAGE\s*(\d+)\s*=\s*([\+\-\d\.]+)pt\s*x\s*([\+\-\d\.]+)pt\s*\+\s*([\+\-\d\.]+)pt\s*$/) { | ||
| 304 | $dimensions[$1] = [$2, $3, $4]; } } | ||
| 305 | close($LOG); } | ||
| 306 | else { | ||
| 307 | Warn('expected', 'dimensions', undef, | ||
| 308 | "Couldn't read log file $workdir/$jobname.log to extract image dimensions", | ||
| 309 | "Response was: $!"); } | ||
| 310 | |||
| 311 | # === Run dvicmd to extract individual png|postscript files. | ||
| 312 | pathname_chdir($workdir); | ||
| 313 | my $dvicommand = "$$self{dvicmd} $jobname.dvi > $jobname.dvioutput"; | ||
| 314 | my $dvierr = system($dvicommand); | ||
| 315 | pathname_chdir($orig_cwd); | ||
| 316 | |||
| 317 | if ($dvierr != 0) { | ||
| 318 | Error('shell', $$self{dvicmd}, undef, | ||
| 319 | "Shell command '$dvicommand' (for dvi conversion) failed (see $workdir for clues)", | ||
| 320 | "Response was: $!"); | ||
| 321 | return $doc; } | ||
| 322 | # === Convert each image to appropriate type and put in place. | ||
| 323 | my $pixels_per_pt = $$self{magnification} * $$self{dpi} / 72.27; | ||
| 324 | my ($index, $ndigits) = (0, 1 + int(log($doc->cacheLookup((ref $self) . ':_max_image_') || 1) / log(10))); | ||
| 325 | foreach my $entry (@pending) { | ||
| 326 | my $src = "$workdir/" . sprintf($$self{dvicmd_output_name}, ++$index); | ||
| 327 | # Recovery patchup for incompatible change to dvisvgm! | ||
| 328 | if (($index == 1) && (!-f $src) && (-f "$workdir/imgx-1.svg")) { | ||
| 329 | $$self{dvicmd_output_name} = 'imgx-%d.svg'; | ||
| 330 | $src = "$workdir/imgx-1.svg"; } | ||
| 331 | if (-f $src) { | ||
| 332 | my @dests = @{ $$entry{dest} }; | ||
| 333 | push(@dests, $self->generateResourcePathname($doc, $$entry{nodes}[0], undef, $$self{imagetype})) | ||
| 334 | unless @dests; | ||
| 335 | foreach my $dest (@dests) { | ||
| 336 | my $absdest = $doc->checkDestination($dest); | ||
| 337 | my ($ww, $hh, $dd) = map { $_ * $pixels_per_pt } @{ $dimensions[$index] }; | ||
| 338 | my ($w, $h); | ||
| 339 | if ($$self{frame_output}) { # If framed, trim the frame | ||
| 340 | ($w, $h) = $self->convert_image($doc, $src, $absdest); | ||
| 341 | next unless defined $w && defined $h; } | ||
| 342 | else { | ||
| 343 | pathname_copy($src, $absdest); | ||
| 344 | $w = int($ww + 0.5); $h = int($hh + $dd + 0.5); } | ||
| 345 | my $d = int(0.5 + ($dd || 0) + $$self{padding}); | ||
| 346 | if ((($w == 1) && ($ww > 1)) || (($h == 1) && ($hh > 1))) { | ||
| 347 | Warn('expected', 'image', undef, "Image for '$$entry{tex}' was cropped to nothing!"); } | ||
| 348 | # print STDERR "\nFor key='$$entry{key}': Image[$index] '$dest' $$entry{tex} $ww x $hh + $dd ==> $w x $h \\ $d\n"; | ||
| 349 | $doc->cacheStore($$entry{key}, "$dest;$w;$h;$d"); } | ||
| 350 | } | ||
| 351 | else { | ||
| 352 | Warn('expected', 'image', undef, "Missing image '$src'; See $workdir/$jobname.log"); } } } | ||
| 353 | |||
| 354 | # Finally, modify the original document to record the associated images. | ||
| 355 | foreach my $entry (values %table) { | ||
| 356 | next unless ($doc->cacheLookup($$entry{key}) || '') =~ /^(.*);(\d+);(\d+);(\d+)$/; | ||
| 357 | my ($image, $width, $height, $depth) = ($1, $2, $3, $4); | ||
| 358 | # Ideally, $image is already relative, but if not, make relative to document | ||
| 359 | my $reldest = pathname_relative($image, $doc->getDestinationDirectory); | ||
| 360 | foreach my $node (@{ $$entry{nodes} }) { | ||
| 361 | $self->setTeXImage($doc, $node, $reldest, $width, $height, $depth); } } | ||
| 362 | |||
| 363 | $doc->closeCache; # If opened. | ||
| 364 | return $doc; } | ||
| 365 | |||
| 366 | #====================================================================== | ||
| 367 | # Generating & Processing the LaTeX source. | ||
| 368 | #====================================================================== | ||
| 369 | |||
| 370 | sub pre_preamble { | ||
| 371 | my ($self, $doc) = @_; | ||
| 372 | my @classdata = $self->find_documentclass_and_packages($doc); | ||
| 373 | my ($class, $class_options, $oldstyle) = @{ shift(@classdata) }; | ||
| 374 | $class_options = "[$class_options]" if $class_options && ($class_options !~ /^\[.*\]$/); | ||
| 375 | $class_options = '' unless defined $class_options; | ||
| 376 | my $documentcommand = ($oldstyle ? "\\documentstyle" : "\\documentclass"); | ||
| 377 | my $packages = ''; | ||
| 378 | my $dest = $doc->getDestination; | ||
| 379 | my $description = ($dest ? "% Destination $dest" : ""); | ||
| 380 | my $pts_per_pixel = 72.27 / $$self{dpi} / $$self{magnification}; | ||
| 381 | foreach my $pkgdata (@classdata) { | ||
| 382 | my ($package, $package_options) = @$pkgdata; | ||
| 383 | $package_options = "[$package_options]" if $package_options && ($package_options !~ /^\[.*\]$/); | ||
| 384 | $packages .= "\\usepackage$package_options\{$package\}\n"; } | ||
| 385 | |||
| 386 | my $w = ceil($$self{maxwidth} * $pts_per_pixel); # Page Width in points. | ||
| 387 | my $gap = ($$self{padding} + $$self{clippingfudge}) * $pts_per_pixel; | ||
| 388 | my $th = ($$self{frame_output} | ||
| 389 | ? $$self{clippingrule} * $pts_per_pixel # clipping box thickness in points. | ||
| 390 | : 0); # NO clipping box! | ||
| 391 | # print STDERR "w=$w, gap=$gap, thickness=$th\n"; | ||
| 392 | return <<"EOPreamble"; | ||
| 393 | \\batchmode | ||
| 394 | \\def\\inlatexml{true} | ||
| 395 | $documentcommand$class_options\{$class\} | ||
| 396 | $description | ||
| 397 | $packages | ||
| 398 | \\makeatletter | ||
| 399 | \\setlength{\\hoffset}{0pt}\\setlength{\\voffset}{0pt} | ||
| 400 | \\setlength{\\textwidth}{${w}pt} | ||
| 401 | \\thispagestyle{empty}\\pagestyle{empty}\\title{}\\author{}\\date{} | ||
| 402 | % Extra definitions for LaTeXML generated TeX | ||
| 403 | \\def\\FCN#1{#1} | ||
| 404 | \\def\\DUAL{\\\@ifnextchar[{\\\@DUAL}{\\\@DUAL[]}} | ||
| 405 | \\def\\\@DUAL[#1]#2#3{#3}% Use presentation form!!! | ||
| 406 | \\newcount\\lxImageNumber\\lxImageNumber=0\\relax | ||
| 407 | \\newbox\\lxImageBox | ||
| 408 | \\newdimen\\lxImageBoxSep | ||
| 409 | \\setlength\\lxImageBoxSep{${gap}\\p\@} | ||
| 410 | \\newdimen\\lxImageBoxRule | ||
| 411 | \\setlength\\lxImageBoxRule{${th}\\p\@} | ||
| 412 | \\def\\lxShowImage{% | ||
| 413 | \\global\\advance\\lxImageNumber1\\relax | ||
| 414 | \\\@tempdima\\wd\\lxImageBox | ||
| 415 | \\advance\\\@tempdima-\\lxImageBoxSep | ||
| 416 | \\advance\\\@tempdima-\\lxImageBoxSep | ||
| 417 | \\typeout{LXIMAGE \\the\\lxImageNumber\\space= \\the\\\@tempdima\\space x \\the\\ht\\lxImageBox\\space + \\the\\dp\\lxImageBox}% | ||
| 418 | \\\@tempdima\\lxImageBoxRule | ||
| 419 | \\advance\\\@tempdima\\lxImageBoxSep | ||
| 420 | \\advance\\\@tempdima\\dp\\lxImageBox | ||
| 421 | \\hbox{% | ||
| 422 | \\lower\\\@tempdima\\hbox{% | ||
| 423 | \\vbox{% | ||
| 424 | \\hrule\\\@height\\lxImageBoxRule% | ||
| 425 | \\hbox{% | ||
| 426 | \\vrule\\\@width\\lxImageBoxRule% | ||
| 427 | \\vbox{% | ||
| 428 | \\vskip\\lxImageBoxSep | ||
| 429 | \\box\\lxImageBox | ||
| 430 | \\vskip\\lxImageBoxSep | ||
| 431 | }% | ||
| 432 | \\vrule\\\@width\\lxImageBoxRule% | ||
| 433 | }% | ||
| 434 | \\hrule\\\@height\\lxImageBoxRule% | ||
| 435 | }% | ||
| 436 | }% | ||
| 437 | }% | ||
| 438 | }% | ||
| 439 | \\def\\lxBeginImage{\\setbox\\lxImageBox\\hbox\\bgroup\\color\@begingroup\\kern\\lxImageBoxSep} | ||
| 440 | \\def\\lxEndImage{\\kern\\lxImageBoxSep\\color\@endgroup\\egroup} | ||
| 441 | \\makeatother | ||
| 442 | EOPreamble | ||
| 443 | } | ||
| 444 | |||
| 445 | #====================================================================== | ||
| 446 | # Converting the postscript images to gif/png/whatever | ||
| 447 | # Note that properly trimming the clipping box (and keeping the right | ||
| 448 | # padding and dimensions) is harder than it seems! | ||
| 449 | # | ||
| 450 | # Note that this conversion is, indeed, quite slow. | ||
| 451 | # Profiling indicates that virtually ALL the time is taken in ->Read !! | ||
| 452 | # (not the various trimming/shaving). | ||
| 453 | #====================================================================== | ||
| 454 | |||
| 455 | sub convert_image { | ||
| 456 | my ($self, $doc, $src, $dest) = @_; | ||
| 457 | my ($bg, $fg) = ($$self{background}, 'black'); | ||
| 458 | |||
| 459 | my $image = image_object(antialias => 'True', background => $bg, density => $$self{dpi}); | ||
| 460 | my $err = $image->Read($$self{dvicmd_output_type} . ':' . $src); | ||
| 461 | if ($err) { | ||
| 462 | Warn('imageprocessing', 'read', undef, | ||
| 463 | "Image conversion failed to read '$src'", | ||
| 464 | "Response was: $err"); return; } | ||
| 465 | |||
| 466 | my ($ww, $hh) = $image->Get('width', 'height'); # Get final image size | ||
| 467 | |||
| 468 | # We can't quite rely on the -E option to dvips; there may or may not be white outside the clipbox; | ||
| 469 | # Moreover, rounding can leave (possibly gray) 'tabs' on the clipbox corners. | ||
| 470 | # To be sure, add known white border, and trim away all white AND gray | ||
| 471 | $image->Border(width => 1, height => 1, fill => $bg); | ||
| 472 | $image->Trim(fuzz => '75%'); # Fuzzy, to trim the gray tabs, as well!! | ||
| 473 | $image->Set(fuzz => '0%'); # But, be SURE to RESET fuzz!! (It is NOT an "argument"!!!) | ||
| 474 | # [Also, be CAREFULL of ImageMagick's Floodfill variants, they sometimes go wild] | ||
| 475 | |||
| 476 | # Finally, shave off the rule & fudge padding. | ||
| 477 | my $fudge = int(0.5 + $$self{clippingfudge} + $$self{clippingrule}); | ||
| 478 | $image->Shave(width => $fudge, height => $fudge); | ||
| 479 | |||
| 480 | my ($w, $h) = $image->Get('width', 'height'); # Get final image size | ||
| 481 | # ImageMagick tries to manage a "virtual" image within the image data, | ||
| 482 | # (whatever that means) | ||
| 483 | # This resets it back to the origin which avoids confusion, all 'round! | ||
| 484 | $image->Set(page => "${w}x${h}+0+0"); | ||
| 485 | |||
| 486 | # Ideally, we'd make the alpha exactly opposite the ink, rather than merely 1 bit | ||
| 487 | # It would seem that this should do it, but currently just seems to turn off alpha completely!!! | ||
| 488 | # $image = $image->Fx(expression=>'(3.0-r+g+b)/3.0', channel=>'alpha'); | ||
| 489 | $image->Transparent(color => $bg); | ||
| 490 | |||
| 491 | NoteProgressDetailed(" [Converting $src => $dest ($w x $h)]"); | ||
| 492 | |||
| 493 | # Workaround bad png detection(?) in ImageMagick 6.6.5 (???) | ||
| 494 | if ($$self{imagetype} eq 'png') { | ||
| 495 | $dest = "png32:$dest"; } | ||
| 496 | |||
| 497 | $image->Write(filename => $dest); | ||
| 498 | return ($w, $h); } | ||
| 499 | |||
| 500 | sub DESTROY { | ||
| 501 | if (my $tmpdir = File::Spec->tmpdir()) { | ||
| 502 | if (-d $tmpdir && opendir(my $tmpdir_fh, $tmpdir)) { | ||
| 503 | my @empty_magick = grep { -z $_ } map { "$tmpdir/$_" } readdir($tmpdir_fh); | ||
| 504 | closedir($tmpdir_fh); | ||
| 505 | unlink $_ foreach @empty_magick; | ||
| 506 | } } | ||
| 507 | return; } | ||
| 508 | |||
| 509 | #====================================================================== | ||
| 510 | 1; |