开发者

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

开发者 https://www.devze.com 2023-01-06 14:45 出处:网络
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.

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


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

pdfdata.force_encoding('BINARY')


Did you inspect the variable pdfdata and check whether it is proper or not?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号