views:

39

answers:

2

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

A: 

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

Suman Mukherjee
Well, it certainly contains characters which cannot be properly represented by terminal output or vim, but that's to be expected, right? It's a PDF file.
doctororange
A: 

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

pdfdata.force_encoding('BINARY')
doctororange