我可以下载 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'
应用程序.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 帮助我弄清楚我必须为 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
从与 wkhtmltopdf
相同的服务器加载 Assets 时挂起正在运行。
使用 绝对 URL 为 Assets 解决了问题。
套装asset_host
在 Rails 的配置中,这也会影响 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/