# This is a sample controller which takes user input from an HTML form and generates a PDF 
# containing what the user submitted. 

class RmlSampleController < ActionController::Base

  def index
     
    # if request method is post -> generate pdf
    if request.request_method == :post
      
      python = "python"                            # You can use a custom python build/version
      pythonpath = '$PYTHONPATH'                   # Override PYTHONPATH if you installed somewhere unusual
      rml2pdfpyc = '/path/to/rml2pdf.pyc'          # Path to RML2PDF compiled python file
      tmp_path = '/tmp/' 
      tmp_rml_file = "#{tmp_path}rml_sample.rml"   # Path to rml generated rml file
      pdf_filename = 'hello.pdf'                   # PDF filename - used in rml
      tmp_pdf_file = "#{tmp_path}#{pdf_filename}"  # Path to rml generated pdf file

      # process rml template to string 
      rml = render_to_string :template => "rml_sample/rml/sample.rml", :locals => {
        :name => params[:name],
        :pdf_filename => pdf_filename
      }

      # create rml file
      file = File.open(tmp_rml_file, 'w')
      file.puts(rml)
      file.close()

      # create pdf file
      system("PYTHONPATH=#{pythonpath} python #{rml2pdfpyc} #{tmp_rml_file}")
      
      # open pdf file
      pdf_file = open(tmp_pdf_file, 'r')
      
      # send pdf to browser
      send_data(pdf_file.read, :filename => pdf_filename, :type => "application/pdf")
    end
  end
  
end
