我可以通过以下方式下载pdf文件:
curl google.com | wkhtmltopdf - test.pdf
因此,这意味着wkhtmlpdf安装成功。
但是,当我尝试通过访问
http://localhost:3000/contacts/1.pdf
生成pdf文件时挂起。在状态栏中,它显示:Waiting for 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)
gem 文件:
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 %>
layouts/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帮助我弄清楚我必须为 Assets 指定绝对路径,而不是相对 Assets 。删除以下几行后,我便能够生成PDF文件:
<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
现在,我不知道如何用绝对路径代替它。看来这个post是我所需要的,但是我仍然无法弄清楚我的情况是什么样。
最佳答案
该问题是由于stylesheet_link_tag
和javascript_include_tag
使用相对URL引起的,当从运行wkhtmltopdf
的同一台服务器加载 Assets 时,这通常会导致wkhtmltopdf
挂起。
对 Assets 使用绝对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-on-rails - 使用PDFkit gem生成pdf卡在rails 4上,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17908359/