我可以通过以下方式下载 pdf 文件:
curl google.com | wkhtmltopdf - test.pdf
所以这意味着wkhtmlpdf安装成功。
但是,当我尝试通过访问生成 pdf 文件时http://localhost:3000/contacts/1.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'
应用程序.rb:
config.middleware.use "PDFKit::Middleware"
根据PDFKit 轨道广播这应该足以生成 pdf 文件,只需添加.pdf
...
UPDATE:
显示.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是我所需要的,但我仍然无法弄清楚这对于我的情况来说会是什么样子。