Module: Calculus::Latex

Included in:
Expression
Defined in:
lib/calculus/latex.rb

Overview

Renders expression to PNG image using latex<tt> and <tt>dvipng

Constant Summary collapse

TEMPLATE =

Basic latex template which use packages amsmath and amssymb from standard distributive and set off expression with $$.

<<-EOT.gsub(/^\s+/, '')
  \\documentclass{article}
  \\usepackage{amsmath,amssymb}
  \\begin{document}
  \\thispagestyle{empty}
  $$ # $$
  \\end{document}
EOT

Instance Method Summary collapse

Instance Method Details

#missing_commandsObject

Check LaTeX toolchain availability and returns array of missing tools



49
50
51
52
53
54
# File 'lib/calculus/latex.rb', line 49

def missing_commands
  commands = []
  commands << "latex" unless can_run?("latex -v")
  commands << "dvipng" unless can_run?("dvipng -v")
  commands
end

#to_png(background = 'White', density = 700) ⇒ Object

Render image from source expression string. It is possible to pass background color (default: 'White') and density (default: 700). See dvipng(1) page for details.

Raises CommandNotFound exception when some tools not available.

Returns path to images. Note that caller should take care about this file.



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/calculus/latex.rb', line 31

def to_png(background = 'White', density = 700)
  raise CommandNotFoundError, "Required commands missing: #{missing_commands.join(', ')} in PATH. (#{ENV['PATH']})" unless missing_commands.empty?

  temp_path = Dir.mktmpdir
  Dir.chdir(temp_path) do
    File.open("#{sha1}.tex", 'w') do |f|
      f.write(TEMPLATE.sub('#', self.to_s))
    end
    `latex -interaction=nonstopmode #{sha1}.tex && dvipng -q -T tight -bg #{background} -D #{density.to_i} -o #{sha1}.png #{sha1}.dvi`
  end
  return File.join(temp_path, "#{sha1}.png") if $?.exitstatus.zero?
ensure
  File.unlink("#{sha1}.tex") if File.exists?("#{sha1}.tex")
  File.unlink("#{sha1}.dvi") if File.exists?("#{sha1}.dvi")
end