ruby-on-rails – 使用PDFkit gem生成pdf在rails 4上挂起

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 使用PDFkit gem生成pdf在rails 4上挂起前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我可以下载pdf文件
curl google.com | wkhtmltopdf - test.pdf

所以这意味着,wkhtmlpdf安装成功了.

但是,当我尝试通过访问http:// localhost:3000 / contacts / 1.pdf生成pdf文件时,它会挂起.在状态栏中显示:等待localhost …

Rails服务器输出

Started GET "/contacts/1.pdf" for 127.0.0.1 at 2013-07-28 21:45:06 +0900
  ActiveRecord::SchemaMigration Load (0.1ms)  SELECT "schema_migrations".* FROM "schema_migrations"
Processing by ContactsController#show as HTML
  Parameters: {"id"=>"1"}
  Contact Load (0.3ms)  SELECT "contacts".* FROM "contacts" WHERE "contacts"."id" = ? LIMIT 1  [["id","1"]]
  Rendered contacts/show.html.erb within layouts/application (1.4ms)
Completed 200 OK in 99ms (Views: 57.0ms | ActiveRecord: 0.7ms)

的Gemfile:

gem 'pdfkit'

application.rb中:

config.middleware.use "PDFKit::Middleware"

根据PDFKit railscast,这应该足以生成pdf文件只需添加.pdf …

更新:

show.html.erb:

<p id="notice"><%= notice %></p>

<p>
  <strong>Name:</strong>
  <%= @contact.name %>
</p>

<p>
  <strong>Age:</strong>
  <%= @contact.age %>
</p>

<%= link_to 'Edit',edit_contact_path(@contact) %> |
<%= link_to 'Back',contacts_path %>

布局/ application.html.erb:

<!DOCTYPE html>
<html>
<head>
  <title>Pdftest</title>
  <%= stylesheet_link_tag    "application",media: "all","data-turbolinks-track" => true %>
  <%= javascript_include_tag "application","data-turbolinks-track" => true %>
  <%= csrf_Meta_tags %>
</head>
<body>

<%= yield %>

</body>
</html>

更新2:

感谢@Arman H帮助我弄清楚我必须为资产指定绝对路径而不是相对路径.当我删除以下行时,我能够生成PDF文件

<%= stylesheet_link_tag    "application","data-turbolinks-track" => true %>
<%= javascript_include_tag "application","data-turbolinks-track" => true %>

现在,我无法用绝对路径来替代它.看来这post是我需要的,但我仍然无法弄清楚这对我的情况会是怎样的.

解决方法

问题是由stylesheet_link_tag和javascript_include_tag使用相对URL,这通常会导致wkhtmltopdf在运行wkhtmltopdf的同一服务器上加载资源时挂起.

使用资产的绝对URL解决了这个问题.

在Rails的配置中设置asset_host,这也会影响stylesheet_link_tag和javascript_include_tag:

# Modify asset host config setting in `config/application.rb`
# Or create a new initializer: `config/initializers/wkhtmltopdf.rb`
config.action_controller.asset_host = "http://mysite.com"

# Or you can have different hosts for development (local) and production (CDN):
# In `config/environments/development.rb`
config.action_controller.asset_host = "http://localhost"
# In `config/environments/production.rb`
config.action_controller.asset_host = "http://d111111abcdef8.cloudfront.net"

猜你在找的Ruby相关文章