11

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.

Kauê Gimenes
  • 1,278
  • 1
  • 13
  • 30
RodM
  • 426
  • 1
  • 5
  • 19

4 Answers4

15

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
powers
  • 658
  • 6
  • 21
6

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.

Eric Hutzelman
  • 206
  • 1
  • 5
  • This fixed it for me. Could you tell me which gems you updated to get rid of this?? – iwiznia Nov 11 '13 at 18:17
  • I wish I could, but there were so many gems involved I didn't track it down to a single one. I would recommend looking for very outdated gems (bundle outdated) and start with those. – Eric Hutzelman Nov 13 '13 at 17:05
  • ok, thanks! Its strange since it's a new project and using rails 4.0.... I'll take a look and post them here if I find out which one is it. – iwiznia Nov 14 '13 at 12:08
0

I was getting the exact same error using WickedPdf.new.pdf_from_string.

try removing:

WickedPdf.new.pdf_from_string

so it reads:

pdf = render_from_string( pdf: ....

0

This is from special characters that are appearing somewhere in your template code, (e.g. curly quotes that come from pasting from MS-Word). I use this bit of code to find exactly where its happening:

body = File.read('raw.txt')
puts body.encode('ASCII-8BIT', :invalid => :replace, :undef => :replace)
Michael Lang
  • 1,028
  • 12
  • 21