【发布时间】:2013-07-28 07:37:19
【问题描述】:
我可以通过以下方式下载 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 '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 帮助我弄清楚我必须为资产指定绝对路径而不是相对路径。当我删除以下行时,我能够生成 PDF 文件:
<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
现在,我不知道如何用绝对路径替换它。看来 post 是我需要的,但我仍然无法弄清楚这对于我的情况来说会是什么样子。
【问题讨论】:
-
挂了多久?在 Rails 的控制台中,您是否收到来自
wkhtmltopdf的任何错误?有时它似乎挂起,但实际上处理 PDF 需要很长时间。在切断请求之前,它运行了多长时间? -
我在 Mac OS x 上遇到的上述问题。现在我在 Linux Mint 上也有同样的情况。它仍然“等待本地主机...” 20 分钟,似乎这将是无止境的。我只需要按 Ctrl + c 取消服务器。
-
当我在 40 分钟后关闭服务器时,它为我生成了 pdf 文件。我在 1 分钟后再次尝试关闭服务器,在这种情况下它显示:命令失败:/usr/bin/wkhtmltopdf --page-size Letter --margin-top 0.75in --margin-right 0.75in --margin-bottom 0.75in --margin-left 0.75in --encoding UTF-8 --quiet - -
-
尝试从终端运行
wkhtmltopdf,在 Rails 之外,使用相同的参数,看看它是否会给你任何错误。也就是说,运行/usr/bin/wkhtmltopdf --page-size Letter --margin-top 0.75in --margin-right 0.75in --margin-bottom... -
我运行时它也挂了: /usr/bin/wkhtmltopdf --page-size Letter --margin-top 0.75in --margin-right 0.75in --margin-bottom 0.75in -- margin-left 0.75in --encoding UTF-8 --quiet - -
标签: ruby-on-rails pdf pdf-generation ruby-on-rails-4 wkhtmltopdf