Created
November 3, 2010 10:37
-
-
Save thokra/660949 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SvgController < ApplicationController | |
require 'active_support/secure_random' | |
def create | |
# create an SVG image | |
# based on Highcharts index.php | |
batik_path = Rails.root.to_s() + '/vendor/batik/batik-rasterizer.jar' | |
svg = params[:svg] | |
filename = params[:filename].blank? ? "chart" : params[:filename] | |
if params[:type] == 'image/png' | |
type = '-m image/png'; | |
ext = 'png' | |
elsif params[:type] == 'image/jpeg' | |
type = '-m image/jpeg' | |
ext = 'jpg' | |
elsif params[:type] == 'application/pdf' | |
type = '-m application/pdf' | |
ext = 'pdf' | |
else | |
show_error "unknown image type: #{params[:type]}" | |
end | |
# two random file names - one for Batik to read (with SVG XML) and one for it to write to | |
tempname = ActiveSupport::SecureRandom.hex(16) | |
outfile = "tmp/#{tempname}.#{ext}" | |
infile = "tmp/#{tempname}.svg" | |
width = "-w #{params[:width]}" if params[:width] | |
# do the conversion | |
File.open(infile, 'w') {|f| f.write(svg) } # SVG definition for Batik to read | |
cmd = "java -jar #{batik_path} #{type} -d #{outfile} #{width} #{infile}" | |
logger.info(cmd) | |
rsp = system(cmd) | |
# For now, rely on existence and size of output file as an idicator of success | |
fs = File.size?( outfile) | |
if fs.nil? || fs < 10 | |
show_error( "Output file empty; #{rsp}") | |
else | |
# Send output back to user; note use of :stream => false so that we can delete the file (otherwise we don't know when stream is complete...) | |
send_file outfile, :type => params[:type], :filename=> "#{filename}.#{ext}", :disposition => 'attachment', :stream => false | |
end | |
File.delete( infile, outfile) | |
end | |
def show_error(rsp) | |
render :text => "Unable to export image; #{rsp}", :status => 500 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment