class Svg2pdf::Processor

Public Class Methods

new(input, mode, format, options) click to toggle source
# File lib/svg2pdf.rb, line 53
def initialize(input, mode, format, options)
  @svg = input
  @mode = format
  @mode = :jpeg if @mode == :jpg
  setup_options options
  if mode == :from_data
    @handle = RSVG::Handle.new_from_data(@svg)
  else
    @handle = RSVG::Handle.new_from_file(@svg)
  end
end

Public Instance Methods

process() click to toggle source
# File lib/svg2pdf.rb, line 65
def process
  case @mode
    when :jpeg, :jpg, :png  then render_image
    when :pdf, :ps          then render
    else raise Svg2pdf::UnsupportedFormatError, "Invalid output format: %s" % @mode.to_s
  end
end

Private Instance Methods

check_cairo() click to toggle source
# File lib/svg2pdf.rb, line 134
def check_cairo
  raise CairoError.new("Cairo library not found") if ! RSVG.cairo_available?
end
check_svg_file() click to toggle source
# File lib/svg2pdf.rb, line 129
def check_svg_file
  raise FileNotFoundError unless File.exists? File.expand_path @svg
  raise InvalidSvgFileError unless File.extname(@svg)[1..-1].downcase =~ /^svg$/
end
create_context(arg) click to toggle source
# File lib/svg2pdf.rb, line 109
def create_context(arg)
  surface = @surface_class.new(arg, @width, @height)
  context = Cairo::Context.new(surface)
  context.scale(@ratio, @ratio)
  context.render_rsvg_handle(@handle)
  context
end
perform_checks() click to toggle source
# File lib/svg2pdf.rb, line 124
def perform_checks
  check_cairo
  check_svg_file
end
render() click to toggle source
# File lib/svg2pdf.rb, line 75
def render
  setup
  @context = create_context @options[:output_file]
  @context.target.finish
  File.new @options[:output_file]
end
render_image() click to toggle source
# File lib/svg2pdf.rb, line 82
def render_image
  setup
  @context = create_context Cairo::FORMAT_ARGB32

  temp = Tempfile.new("svg2")
  @context.target.write_to_png(temp.path)
  @context.target.finish
  @pixbuf = Gdk::Pixbuf.new(temp.path)
  @pixbuf.save(@options[:output_file], @mode.to_s)

  File.new @options[:output_file]
end
setup() click to toggle source
# File lib/svg2pdf.rb, line 95
def setup
  @ratio = @options[:ratio]
  @dim = @handle.dimensions
  @width = @dim.width * @ratio
  @height = @dim.height * @ratio

  surface_class_name = case @mode
    when :jpg, :jpeg, :png  then "ImageSurface"
    when :ps                then "PSSurface"
    when :pdf               then "PDFSurface"
  end
  @surface_class = Cairo.const_get(surface_class_name)
end
setup_options(options) click to toggle source
# File lib/svg2pdf.rb, line 117
def setup_options(options)
  # TODO: check working_dir, output_name, etc
  @options = options
  @options[:output_name] += '-' + SecureRandom.hex(16)
  @options[:output_file] = File.join(@options[:working_dir], @options[:output_name] + '.' + @mode.to_s)
end