ruby-on-rails - 执行失败: Error: "\xFE" from ASCII-8BIT to UTF-8

标签 ruby-on-rails encoding utf-8 wicked-pdf

Rails 4 *Mac OSX 10.8.4*

<小时/>

我使用以下 Gem 来生成 wicked_pdf pdf:

gem 'wkhtmltopdf-binary'
gem 'wicked_pdf'

将 View 渲染为 pdf 效果很好,并且 Google 可以正确显示其 PDF 查看器。我的 PDF 看起来正是我想要的样子。

当我尝试将 pdf 保存到光盘上,以便通过电子邮件发送给用户时,问题就出现了。

例如,这工作正常:

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

这将在 Google Chrome PDF 查看器中呈现 pdf。

但这里是我想要生成 PDF 并保存到文件的地方。

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

但我收到错误:

Failed to execute:

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

最佳答案

试试这个:

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

在内存中呈现为字符串的 PDF 似乎是 ASCII 格式,因此将其保存为这样:)

关于ruby-on-rails - 执行失败: Error: "\xFE" from ASCII-8BIT to UTF-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18566713/

相关文章:

javascript - 单个 Javascript 函数无法在 Heroku 上运行

node.js - 如何在请求 promise 中制作 UTF-8?

c++ - 将 utf8 实体从 json 解码为 utf8 C++

php - Laravel 返回 Patchwork\\utf8\\Bootup 错误

ruby-on-rails - 是否可以使用 Paperclip 将 Amazon Cloudfront 签名 URL 用于附件

ruby-on-rails - 传递给 Capybara::Queries::SelectorQuery 的未使用参数

ruby-on-rails - 如何通过删除 Time.Now 对出生日期格式进行 Rspec 测试?

python - 如何确定 Python 中 datetime.strftime(...) 的编码?

java - 欧洲编码

java - Java 中的 UTF-8 和 UTF-16