【发布时间】:2014-05-15 21:50:05
【问题描述】:
我正在尝试创建一个列出我所有项目的 .pdf (#index)。
我找到了一个很棒的链接-How do generate PDFs in Rails with Prawn,但它是 2008 年的,希望我使用 prawnto 插件。
我使用的是 Rails 3.2.13,所以我决定使用gem prawn 和RailsCast #153 PDFs with Prawn (revised),以供参考。我能够成功地让Prawn 在我的工作:
projects_controller
def show
我无法让 .pdf 在我的 def index 中工作。
我试图模仿我所做的,使用def show 的教程,def index 的教程,但遇到路由错误。
到目前为止,这是我的代码:
宝石文件
gem 'prawn', '0.12.0'
projects_controller.rb
class ProjectsController < ApplicationController
def index
redirect_to action: :active, search =>params[:search]
end
def active
@action = "active"
....
.... // search code
.... // kaminari code
@projects = Project.order(sort_column + "" + sort_direction)
respond_to do |format|
format.json { render "index" }
format.html { render "index" }
format.pdf do
pdf = ProjectAllPdf.new(@projects)
send_data pdf.render, filename: "project_#{@project.product}.pdf",
type: "application/pdf",
disposition: "inline"
end
end
end
def show
@project = Project.find(params[:id])
respond_to do |format|
format.json { render json:@project }
format.html # show.html.erb
format.pdf do
pdf = ProjectPdf.new(@project)
send_data pdf.render, filename: "project_#{@project.product}.pdf",
type: "application/pdf",
disposition: "inline"
end
end
end
end
show.html.erb
<p><%= link_to "Printable Receipt (PDF)", project_path(@project, format: "pdf") %></p>
index.html.erb
<p><%= link_to "Printable Receipt (PDF)", projects_path(@projects, format: "pdf") %></p>
然后我格式化了我的文件 project_pdf.rb
class ProjectPdf < Prawn::Document
def initialize(project)
super(top_margin: 70)
@project = project
overview_print
end
def overview_print
text "Project #{@project.product}", size: 24, style: :bold, align: :center
move_down 30
text "<b>Product:</b> #{@project.product}", :inline_format => true
move_down 8
text "<b>Version Number:</b> #{@project.version_number}", :inline_format => true
move_down 8
....
....
end
end
然后我尝试模仿最后一个文件以使#index 正常工作
projectall_pdf.rb
class ProjectAllPdf < Prawn::Document
def initialize(project)
super(top_margin: 70)
@project = project
overview_print
end
def overview_print
@projects.each do |project|
text "<b>Product:</b> #{@project.product}", :inline_format => true
move_down 8
text "<b>Version Number:</b> #{@project.version_number}", :inline_format => true
move_down 8
....
....
end
end
end
#show 的一切都很好。我只是显然对如何处理#index 部分感到困惑(def active,在 index.html.erb 和 projectall_pdf.rb 中链接 .pdf)
【问题讨论】:
标签: ruby-on-rails-3 prawn