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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With