1

My Rails 3.1 app makes a web service call to get a pdf file that I then need to send to the browser for download.

The XML response is something like this:

<RenderResponse>
  <Result>blahblah this is the file info<Result>
  <Extension>PDF</Extension>
  <MimeType>application/pdf</MimeType>
</RenderResponse>

I am then trying to convert the "Result" tag to a file as so:

@report = @results[:render_response][:result]
@report_name = MyReport.pdf
File.open(@report_name, "w+") do |f|
  f.puts @report
end

finally I try to send to the browser:

send_file File.read(@report_name), :filename => @report_name, :type => "application/pdf; charset=utf-8", :disposition => "attachment"

This yields an error the says "Cannot Read File" and it spits out all the text from the results tag.

If I use send_data as so:

send_data File.read(@report_name).force_encoding('BINARY'), :filename => @report_name, :type => "application/pdf; charset=utf-8", :disposition => "attachment"

The download works but I get a file with 0KB and an Adobe Error that says the file "MyReport.pdf" can't be opened because "its either not a supported file type or it has been damaged".

How can I take the XML response file info, create the file, and stream to the browser?

user2967603
  • 139
  • 12
  • can you try with this ` File.open(file, 'r') do |f| send_data f.read.force_encoding('BINARY'), :filename => filename, :type => "application/pdf", :disposition => "attachment" end` – Deepti Kakade Aug 25 '16 at 07:33
  • Thanks for the comment. I have tried this and it did not solve that problem. I did find a solution and will post it. – user2967603 Aug 25 '16 at 15:32

1 Answers1

0

I found the solution. send_file is the correct stream mechanism to use but I needed to decode the string while writing to the file. I also need to add the 'b' parameter to the File.open call.

This works:

File.open(@report_name, "wb+") do |f|
  f.puts Base64.decode64(@report)
end



@file = File.open(@report_name, 'r')

   send_file @file, :filename => @report_name, :type => "application/pdf; charset=utf-8", :disposition => "attachment"
user2967603
  • 139
  • 12