Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails send_data throws "invalid byte sequence in UTF-8"... but why?

I'm using Rails to generate a PDF with the executable wkhtmltopdf and then using send_data to send the result back to the user as a PDF file.

 view = ActionView::Base.new(ActionController::Base.view_paths,  {})
 html = "<h1>A heading</h1>"
 pdfdata = `echo '#{html}' | #{RAILS_ROOT}/lib/pdf/wkhtmltopdf-i386 - -`
 send_data pdfdata, :filename => 'readthis.pdf', :disposition => 'attachment', :type => "application/pdf"

The PDF is generated properly, but Rails complains ArgumentError (invalid byte sequence in UTF-8) from the send_data method. Changing it to send "foobar" as :type => text/html makes it work, so it's definitely got a problem with pdfdata.

I don't understand. Isn't send_data supposed to send binary data? Of course it's not valid UTF-8. Or am I missing something?

Thanks

like image 734
doctororange Avatar asked Jul 06 '10 07:07

doctororange


1 Answers

Rails assumes UTF-8. Telling it explicitly that it is binary data solves the problem. Thanks for your help.

pdfdata.force_encoding('BINARY')
like image 115
doctororange Avatar answered Oct 23 '22 16:10

doctororange