我可以下载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)
的Gemfile:
gem 'pdfkit'
application.rb中:
config.middleware.use "PDFKit::Middleware"
根据PDFKit railscast这应该足以生成pdf文件只需添加 .pdf
...
UPDATE:
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>
UPDATE 2:
感谢@Arman H帮助我弄清楚我必须指定资产的绝对路径而不是相对路径 . 当我删除以下行时,我能够生成PDF文件:
<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
现在,我无法得到如何用 absolute paths 替换它 . 这似乎是我需要的,但我仍然无法弄清楚这对我的情况会是怎样的 .
3 回答
问题是由于
stylesheet_link_tag
和javascript_include_tag
使用了相对URL,这通常会导致wkhtmltopdf
从运行wkhtmltopdf
的同一服务器加载资产时挂起 .使用 absolute URLs 资产解决了问题 .
在Rails的配置中设置
asset_host
,这也会影响stylesheet_link_tag
和javascript_include_tag
:在development.rb中设置
config.action_controller.asset_host = "http://localhost"
实际上在呈现HTML时没有实现 .我按照这里的方法:http://jguimont.com/post/2627758108/pdfkit-and-its-middleware-on-heroku
它对我来说就像一个魅力 . 希望这有助于某人 . 只需在config / intializers中抛出assets.rb就可以了 .
我有同样的问题,我的日志显示页面已呈现但是没有生成pdf并且浏览器将挂起 . 它最终与操作系统兼容性,缺少图书馆员,宝石和依赖关系无关,而是我需要将我的Puma服务器(已设置为1)的最大允许线程数提高到2或更多 . 然后生成pdf正常 .