class Text2png::Converter

Attributes

base[R]
density[R]
dir[R]
formula[R]
hash[R]
name[R]

Public Class Methods

new(formula, density: 155) click to toggle source
# File lib/text2png/converter.rb, line 9
def initialize(formula, density: 155)
  @formula = formula
  @density = density
  @hash    = SecureRandom.hex(16)
  @base    = File.join TEMP_DIR, hash
end

Public Instance Methods

content() click to toggle source
# File lib/text2png/converter.rb, line 16
    def content
      @content ||= <<-END.gsub(/^ {6}/, "")
        \\documentclass[12pt]{article}
        \\usepackage[utf8]{inputenc}
        \\usepackage{#{LATEX_PACKAGES.join(", ")}}
        \\begin{document}
        \\pagestyle{empty}
        \\begin{displaymath}
        #{formula}
        \\end{displaymath}
        \\end{document}
      END
    end
data() click to toggle source
# File lib/text2png/converter.rb, line 30
def data
  @data ||= png do |io|
    "data:image/png;base64, #{Base64.encode64(io.read)}"
  end
end
png(&block) click to toggle source
# File lib/text2png/converter.rb, line 36
def png(&block)
  @png ||= proc do
    args = [
     "-q -T tight -D #{density}", "-o #{base}.png", "#{base}.dvi"
    ]

    tex
    dvi
    Text2png::dvipng.run(*args).raise!
    clean!

    path(:png)
  end.call

  file(:png, &block)
end

Private Instance Methods

clean!() click to toggle source
# File lib/text2png/converter.rb, line 74
def clean!
  FileUtils.rm %W{tex aux log dvi}.map {|ext| path(ext)}
end
dvi() click to toggle source
# File lib/text2png/converter.rb, line 62
def dvi
  @dvi ||= proc do
    args = [
      "-output-directory=#{TEMP_DIR}", "-interaction=nonstopmode", tex
    ]

    Text2png::latex.run(*args).raise!

    path(:dvi)
  end.call
end
file(ext, mode = "r", &block) click to toggle source
# File lib/text2png/converter.rb, line 78
def file(ext, mode = "r", &block)
  FileUtils.mkdir TEMP_DIR if !File.exists? TEMP_DIR
  File.open(path(ext), mode, &block)
end
path(ext) click to toggle source
# File lib/text2png/converter.rb, line 83
def path(ext)
  "#{base}.#{ext}"
end
tex() click to toggle source
# File lib/text2png/converter.rb, line 55
def tex
  @tex ||= file(:tex, "w") do |file|
    file.write content
    file.path
  end
end