Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RuntimeError (Failed to execute: Error: "\xFE" from ASCII-8BIT to UTF-8):

Trying to use Wicked PDF.

I have this code in the controller

  def pdf
  pdf = WickedPdf.new.pdf_from_string(
  render_to_string(
  pdf: 'filename.pdf',
  template: '/pages/poa.html.slim',
  layout: '/layouts/pdf'),
  header: {
      content: render_to_string({
          template: '/pdfs/poa_header.html.slim',
          layout: '/layouts/pdf'
      })
  })

   save_path = [Rails.root, '/public/pdf/', 'filename.pdf'].join
   File.open(save_path, 'wb') do |file | file << pdf
   end
   end

I am getting this error message when trying to execute the action above

RuntimeError (Failed to execute:

Error: "\xFE" from ASCII-8BIT to UTF-8):

I already tried to empty the content of templates and layout I am rendering but still got the error.

like image 483
RodM Avatar asked Jun 11 '13 14:06

RodM


2 Answers

This can happen if you try to write to a file that is not in binary mode.

Either open the file with the 'b' flag File.open(file_path, 'wb'), or if you already have a file handle, you can switch it to binary mode before writing:

f = Tempfile.open(%w(my .pdf))
f.binmode
f << pdf
f.close
like image 180
powers Avatar answered Sep 18 '22 08:09

powers


I just ran into this issue myself. Strangely, it was only happening when I was running under Rails 4.rc2 (worked fine under Rails 3.2.13). I got around it by forcing the resulting pdf string encoding to UTF-8.

So in your example, try something like this:

File.open(save_path, 'wb') do |file | file << pdf.force_encoding("UTF-8")

While the above line fixed things for me, I found out the underlying issue was actually some gems that were downgraded during the process of upgrading to Rails 4.rc2. After forcing some dependencies to get later gem versions, I can now run without the #force_encoding as I did before with rails 3.

like image 37
Eric Hutzelman Avatar answered Sep 21 '22 08:09

Eric Hutzelman