我正在尝试使用Rails 3生成一个PDF文件。我有一个带有一些值的表,我想以PDF格式显示这些数据。我已经编写了一些代码,解释如下。
index.html.erb:
<h1>Choose the option</h1>
<p>
<%= link_to "new input",products_new_path %>
</p>
<table>
<tr>
<th>Product name</th>
<th>Product Catagory</th>
</tr>
<% @product.each do |p| %>
<tr>
<td><%= p.p_name %></td>
<td><%= p.p_catagory %></td>
</tr>
<% end %>
</table>products_controller.rb:
class ProductsController < ApplicationController
def index
@product=Product.all
respond_to do |format|
format.html
format.pdf do
pdf = Prawn::Document.new
send_data pdf.render, filename: 'report.pdf', type: 'application/pdf'
end
end
end
def new
@product=Product.new
end
def create
@product=Product.new(params[:product])
if @product.save
flash[:notice]="Data submitted"
flash[:color]="valid"
redirect_to :action => "index"
else
flash[:alert]="Data could not finish"
flash[:color]="invalid"
render 'new'
end
end
endGemfile:
source 'https://rubygems.org'
gem 'rails', '3.2.19'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
gem 'sqlite3'
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', :platforms => :ruby
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'
# To use Jbuilder templates for JSON
# gem 'jbuilder'
# Use unicorn as the app server
# gem 'unicorn'
# Deploy with Capistrano
# gem 'capistrano'
# To use debugger
# gem 'debugger'
gem 'prawn'配置/初始化/mime_type.rb.
Mime::Type.register "application/pdf", :pdf请帮助我解决这个问题,并让我知道如何运行应用程序(例如-localhost:3000/products.pdf)来获取这个pdf文件。
发布于 2015-05-07 10:43:35
我要做的是将这一行添加到Gemfile中,以生成一个有对虾的表:
gem 'prawn-table'确保您使用的是以下版本:
bundle show
# * prawn (2.0.1)
# * prawn-table (0.2.1)在控制器中,如果要在调用索引操作时生成PDF文件,可以将以下内容添加到其中:
def index
@products = Product.all
require "prawn/table"
require "prawn"
Prawn::Document.generate("test.pdf") do |pdf|
table_data = Array.new
table_data << ["Product name", "Product category"]
@products.each do |p|
table_data << [p.name, p.category]
end
pdf.table(table_data, :width => 500, :cell_style => { :inline_format => true })
end
end如果需要,可以添加一些html语法:
["<b>#{p.name}</b>", "<i>#{p.category}</i>"]结果如下:

发布于 2015-05-07 11:35:35
@satya,我建议你用“虾”和“虾桌”的宝石。
创建pdf的步骤是-
1:#创建pdf对象
pdf = Prawn::Document.new()2:#在pdf对象中指定值
pdf.text "To Date - #{extra_data[:to_date]}"想了解更多信息,你可以看这段视频-
http://railscasts.com/episodes/153-pdfs-with-prawn
发布于 2015-05-12 07:37:00
@satya,使用这个->返回Product.get_product_report_runtime_pdf(input_data),类型::send_data,文件名:"Units_report_#{Time.now.strftime("%Y%m%d%H%M%S")}.pdf“将返回运行时创建的pdf,如果您也想要html页面,那么在发送数据之前不要使用send_data。
在产品模型->下,我在这里返回空白的pdf,所以使用所需的代码,无论你想在你的pdf。
def get_product_report_runtime_pdf
pdf = Prawn::Document.new
return pdf.render 结束
https://stackoverflow.com/questions/30097822
复制相似问题