Skip to content

Instantly share code, notes, and snippets.

@vaiorabbit
Created April 7, 2012 11:42
Show Gist options
  • Save vaiorabbit/2327978 to your computer and use it in GitHub Desktop.
Save vaiorabbit/2327978 to your computer and use it in GitHub Desktop.
Converts math formula (written in TeX language) into PNG file via Google Chart API.
# -*- coding: utf-8 -*-
require 'date'
require 'uri'
require 'net/http'
USAGE = <<EOL
Converts math formula (written in TeX language) into PNG file via Google Chart API.
USAGE: $ ruby #{__FILE__} "Formula_in_TeX_language"
ex.) ruby chartapi.rb "x = \\frac{-b\\pm\\sqrt{b^2-4ac}}{2a}"
EOL
class FormulaImage
# Ref.: Mathematical Formulas - Infographics — Google Developers
# https://developers.google.com/chart/infographics/docs/formulas
ROOT_URL = "https://chart.googleapis.com/chart?cht=tx&chl="
def initialize( formula )
@query_url = ROOT_URL + URI.escape(formula, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
@image = nil
end
def fetch
uri = URI.parse(@query_url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(uri.request_uri)
resp = http.request(request)
@image = resp.body
end
def save( filename = nil )
filename = "Formula-#{Time.now.to_datetime}.png" if filename == nil
File.open( filename, "wb", :encoding => "BINARY" ) do |file|
file.write( @image )
end
end
def as_img_tag
"<img src=\"#{@query_url}\" />"
end
end
if __FILE__ == $0
if ARGV.length == 0
puts USAGE
exit
end
formula_image = FormulaImage.new( ARGV[0] )
formula_image.fetch
formula_image.save
puts formula_image.as_img_tag
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment