7

Rails 4 *Mac OSX 10.8.4*


I'm using the following Gem for wicked_pdf pdf generation:

gem 'wkhtmltopdf-binary'
gem 'wicked_pdf'

Rendering Views as pdfs works fine and Google displays it's PDF viewer correctly. My PDFs look exactly how I want them to.

The problem arises when I try to save a pdf to disc, for the purpose of emailing them to a user.

For example, this works fine:

def command
  @event = Event.find(params[:id])
  @client = Contact.find(@event.client_id)
  @organizer = Contact.find(@event.organizer_id)
  render layout: 'command',
       pdf: 'Event Command',
       show_as_html: params[:debug].present?,
       dpi: 300,
       print_media_type: true,
       margin: {
           top: 0,
           bottom: 0,
           left: 0,
           right: 0
       }
  end

That will render the pdf in the Google Chrome PDF viewer.

But here, is where I want to generate a PDF and save to file.

def send_email
  @event = Event.find(params[:id])
  @client = Contact.find(@event.client_id)
  @organizer = Contact.find(@event.organizer_id)

  proforma = render_to_string(
      pdf: 'proforma.pdf',
      template: 'events/proforma',
      layout: 'proforma'
  )

  pdf = WickedPdf.new.pdf_from_string(
    proforma
  )

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

But I'm getting the error:

Failed to execute:

Error: "\xFE" from ASCII-8BIT to UTF-8
sergserg
  • 21,716
  • 41
  • 129
  • 182
  • `pdf = WickedPdf.new.pdf_from_string( proforma.encode!('UTF-8') )` .....or `proforma.encode!('UTF-8')` Please encode it – Rajarshi Das Sep 02 '13 at 06:18
  • https://www.ruby-forum.com/topic/208730 more about encoding like "\xfe" – Rajarshi Das Sep 02 '13 at 06:19
  • @RajarshiDas: undefined method `force_encoding!' for # - Any ideas? Edit: I'm using Ruby 2.0.0 – sergserg Sep 02 '13 at 06:21
  • please see my comment it is updated – Rajarshi Das Sep 02 '13 at 06:23
  • @RajarshiDas: That is one of the thing I have tried, getting the same error. It's as if a character was invalid but that doesn't make sense since it generates the PDF fine when just displaying it. Why is it giving me problems when saving to disk. – sergserg Sep 02 '13 at 06:28
  • it is not able to generate the pdf how can it save it on your disk your `proforma` has some hex string and it not able to convert it into string...Please use magic_encoding https://rubygems.org/gems/magic_encoding gem or used `# -*- encoding : utf-8 -*-` in top of the file if it is not resolved – Rajarshi Das Sep 02 '13 at 06:50

1 Answers1

7

Try this:

   File.open(save_path, 'w:ASCII-8BIT') do |file|
     file << pdf
   end

The PDF rendered as a string in memory seems to be in ASCII, so save it as such :)

Martin T.
  • 3,132
  • 1
  • 30
  • 31